hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a0053149a3070cad1f01717cc980f436d7abb8e0
1,043
cpp
C++
SWUST OJ/0983.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
SWUST OJ/0983.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
SWUST OJ/0983.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <string> using namespace std; struct TreeNode { struct TreeNode* left; struct TreeNode* right; char elem; }; TreeNode* BinaryTreeFromOrderings(string inorder, string aftorder, int length) { if(length == 0) { return NULL; } TreeNode* node = new TreeNode;//Noice that [new] should be written out. node->elem = *(aftorder.begin()+length-1); cout<<node->elem<<endl; int rootIndex = 0; for(rootIndex = 0;rootIndex < length; rootIndex++)//a variation of the loop { if(inorder[rootIndex] == *(aftorder.begin()+length-1)) break; } node->left = BinaryTreeFromOrderings(inorder aftorder , rootIndex); node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, aftorder + rootIndex , length - (rootIndex + 1)); return node; } int main(const int argc,const char** argv) { string af; string in; cin>>af>>in; BinaryTreeFromOrderings(in, af, af.length()); return 0; }
25.439024
116
0.642378
windcry1
a00568d228b315f5b91afcaa5af5c285916d3ff1
4,306
hpp
C++
Common/include/common/expected.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Common/include/common/expected.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Common/include/common/expected.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
#ifndef FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP #define FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP #include <cassert> #include "either.hpp" #include "error.hpp" template<typename T> class Expected { public: using Value = T; template<typename U> using Next = Expected<U>; Expected(const Value& value) : either_(value) {} Expected(Value&& value) : either_(std::move(value)) {} Expected(const Error& error) : either_(error) {} Expected(Error&& error) : either_(std::move(error)) {} bool has_value() const { return !either_.is_left(); } Error& get_error() & { return either_.get_left(); } Error&& get_error() && { return std::move(either_.get_left()); } const Error& get_error() const& { return either_.get_left(); } Value& get_value() & { return either_.get_right(); } Value&& get_value() && { return std::move(either_.get_right()); } const Value& get_value() const& { return either_.get_right(); } auto& get_either() & { return either_; } auto&& get_either() && { return std::move(either_); } const auto& get_either() const& { return either_; } template<typename Function> auto map_error(Function&& fn) const { static_assert(!std::is_void<decltype(fn(get_error()))>::value, ""); if (has_value()) { return *this; } else { return Expected{fn(get_error())}; } } template<typename Function> Expected&& map_error(Function&& fn) && { static_assert(!std::is_void<decltype(fn(get_error()))>::value, ""); if (has_value()) { return std::move(*this); } else { return std::move(Expected{fn(get_error())}); } } // Map functor. // If the expected has value then unwrap it, pass it to the given function, // wrap the function's return value in another expected, and return that. // If the expected has no value then return an empty optional with a type // matching the function. // A return value of void is handled by mapping to Monostate. Likewise, // no parameters are passed to `fn' in the case where Value=Monostate. // This method can be chained with other calls to map(), &c. template<typename Function> auto map(Function&& fn) & { return map_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto map(Function&& fn) && { return map_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto map(Function&& fn) const& { return map_impl(*this, std::forward<Function>(fn)); } // If the expected has value then unwrap it, pass it to the given function, // and then return whatever value that function returned. // If the expected has no value then return an empty optional with a type // matching the function. // A return value of void is handled by mapping to Monostate. Likewise, // no parameters are passed to `fn' in the case where Value=Monostate. // This method can be chained with other calls to map(), &c. template<typename Function> auto and_then(Function&& fn) & { return and_then_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto and_then(Function&& fn) && { return and_then_impl(std::move(*this), std::forward<Function>(fn)); } template<typename Function> auto and_then(Function&& fn) const& { return and_then_impl(*this, std::forward<Function>(fn)); } // If the expected has no value then execute the function. // The function accepts no parameters and returns no value. // Since or_else() returns *this, it can be chained with map(), &c. template<typename Function> auto or_else(Function&& fn) & { return or_else_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto or_else(Function&& fn) && { return or_else_impl(std::move(*this), std::forward<Function>(fn)); } template<typename Function> auto or_else(Function&& fn) const& { return or_else_impl(*this, std::forward<Function>(fn)); } private: Either<Error, Value> either_; }; #endif // FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP
32.621212
79
0.640269
foxostro
a0074f0850ba3a6c2c79ce2eb5f072110cd06f99
1,231
cpp
C++
Playground/Noise/src/Noise.cpp
fountainment/cherry-soda
3dd0eb7d0b5503ba572ff2104990856ef7a87495
[ "MIT" ]
27
2020-01-16T08:20:54.000Z
2022-03-29T20:40:15.000Z
Playground/Noise/src/Noise.cpp
fountainment/cherry-soda
3dd0eb7d0b5503ba572ff2104990856ef7a87495
[ "MIT" ]
10
2022-01-07T14:07:27.000Z
2022-03-19T18:13:44.000Z
Playground/Noise/src/Noise.cpp
fountainment/cherry-soda
3dd0eb7d0b5503ba572ff2104990856ef7a87495
[ "MIT" ]
6
2019-12-27T10:04:07.000Z
2021-12-15T17:29:24.000Z
#include "Noise.h" #include <CherrySoda/CherrySoda.h> using noise::Noise; using namespace cherrysoda; static STL::Action<> s_updateAction; Noise::Noise() : base() { SetTitle("Noise"); SetClearColor(Color::Black); } void Noise::Update() { base::Update(); if (s_updateAction) { s_updateAction(); } } void Noise::Initialize() { base::Initialize(); unsigned char* data = new unsigned char[200 * 200 * 4]; std::memset(data, 0xFF, 200 * 200 * 4); for (int i = 0; i < 200 * 200; ++i) { data[i * 4 ] = Calc::GetRandom()->Next(256); data[i * 4 + 1] = Calc::GetRandom()->Next(256); data[i * 4 + 2] = Calc::GetRandom()->Next(256); } auto texture = Texture2D::FromRGBA(data, 200, 200); delete [] data; auto image = new Image(texture); auto entity = new Entity(); auto scene = new Scene(); auto renderer = new EverythingRenderer(); s_updateAction = [image](){ image->RotateOnZ(Engine::Instance()->DeltaTime()); }; renderer->GetCamera()->Position(Math::Vec3(0.f, 0.f, 200.f)); renderer->SetEffect(Graphics::GetEmbeddedEffect("sprite")); image->CenterOrigin(); entity->Add(image); scene->Add(entity); scene->Add(renderer); SetScene(scene); } void Noise::LoadContent() { base::LoadContent(); }
19.234375
82
0.649878
fountainment
a007ce907249b0cfa3b9d4e362fb7247fe6fc8b8
709
cpp
C++
src/serialize19.lib/serialize19/serialize.std_vector.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
src/serialize19.lib/serialize19/serialize.std_vector.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
src/serialize19.lib/serialize19/serialize.std_vector.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
#include "ReadArchive.h" #include "dynamicWrite.h" #include "serialize.std_vector.h" #include <gtest/gtest.h> using namespace serialize19; TEST(serialize, std_vector) { using T = std::vector<int>; auto input = T{7, 13, 23}; auto buffer = dynamicWrite(input); auto reader = ReadArchive{buffer.slice()}; auto output = T{}; serialize(reader, output); EXPECT_EQ(output, input); } TEST(serialize, std_vector_empty) { using T = std::vector<int>; auto input = T{}; auto buffer = dynamicWrite(input); auto reader = ReadArchive{buffer.slice()}; auto output = T{}; serialize(reader, output); EXPECT_EQ(output, input); }
20.852941
47
0.626234
Fettpet
a0085db3a07d7eeb0d58e2eca0d26e5d07723e42
2,173
hpp
C++
multiview/multiview_cpp/src/perceive/calibration/find-homography.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/perceive/calibration/find-homography.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/perceive/calibration/find-homography.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#pragma once #include "perceive/foundation.hpp" #include "perceive/geometry.hpp" namespace perceive::calibration { /// /// Class for efficiently evaluating a 'find-homography' cost function /// // What not use a closure, like good c++11?? Because this object // is meant to work with python bindings! class FindHomographyCostFunctor { public: // Lp norm is appled to the homography errors as a vector Lp_norm_t method{Lp_norm_t::L1}; // The set of world points, and corner (i.e., image) points std::vector<Vector2r> W, C; // Evaluate the cost function for the passed set of parameters // X is a 3x3 homography (H) in row major order // the result is the mean-sq-err for (C[i] - H W[i]) in R2 real evaluate(const real X[9]) const; static real homography_err(const Matrix3r& H, const std::vector<Vector2r>& W, const std::vector<Vector2r>& C, Lp_norm_t method); // Unpacks X[9] (ie, the paramaters) as a normalized homography Matrix3r unpack(const real X[9]) const; // Human readable print-out shows W and C std::string to_string() const; }; // Such that C[i] = H * W[i] real estimate_homography_LLS(const std::vector<Vector3r>& W, const std::vector<Vector3r>& C, Matrix3r& H); real estimate_homography_LLS(const std::vector<Vector2r>& W, const std::vector<Vector2r>& C, Matrix3r& H); inline void translate_homographies(vector<Matrix3r>& Hs, const Vector2 C) { Matrix3r HC = Matrix3r::Identity(); Matrix3r t; HC(0, 2) = C(0); HC(1, 2) = C(1); for(auto& H : Hs) { t = HC * H; H = t; } } void H_to_r1r2t(const Matrix3r& H, Vector3& ssa, Vector3r& t, bool feedback = false); void r1r2t_to_H(const Vector3& ssa, const Vector3r& t, Matrix3r& H); void H_to_r1r2t(const Matrix3r& H, Vector6r& X); void r1r2t_to_H(const Vector6r& X, Matrix3r& H); // Given 8 values, calculates the last value of the homography // (h33), such that the homography has determinant 1.0. // The value of H(2, 2) is ignored and over-written. void complete_homography(Matrix3r& H); } // namespace perceive::calibration
31.042857
80
0.664059
prcvlabs
a00e03ef5e335ba68f5a721360f741c90cbf7c77
4,055
hpp
C++
include/lbann/objective_functions/weight_regularization/l2.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
include/lbann/objective_functions/weight_regularization/l2.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
include/lbann/objective_functions/weight_regularization/l2.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED #define LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED #include "lbann/objective_functions/objective_function_term.hpp" namespace lbann { template <typename> class data_type_optimizer; template <typename> class data_type_weights; /** @class l2_weight_regularization * @brief Apply L2 regularization to a set of weights. * * Given a weights tensor @f$ w @f$, * @f[ L2(w) = \frac{1}{2} \sum\limits_{i} w(i)^2 @f] * Note the @f$ 1/2 @f$ scaling factor. */ class l2_weight_regularization : public objective_function_term { public: using AccumulateDataType = DataType; using OptimizerType = data_type_optimizer<DataType>; using WeightsType = data_type_weights<DataType>; template <El::Device D> using DMatType = El::Matrix<AccumulateDataType, D>; using CPUMatType = DMatType<El::Device::CPU>; public: /** @param scale_factor The objective function term is * @f$ \text{scale\_factor} \times \sum L2(w_i) @f$ */ l2_weight_regularization(EvalType scale_factor = 1); l2_weight_regularization* copy() const override { return new l2_weight_regularization(*this); } /** Archive for checkpoint and restart */ template <class Archive> void serialize( Archive & ar ) { ar(cereal::base_class<objective_function_term>(this)); } std::string name() const override { return "L2 weight regularization"; } void setup(model& m) override; void start_evaluation() override; EvalType finish_evaluation() override; /** Compute the gradient w.r.t. the activations. * * L2 regularization is independent of forward prop output, so * nothing needs to be done here. * * @todo Come up with a better function name in the base class. */ void differentiate() override {}; /** Compute the gradient w.r.t. the weights. * * @f[ \nabla_w L2(w) = w @f] */ void compute_weight_regularization() override; private: /** Contributions to evaluated value. */ std::map<El::Device, CPUMatType> m_contributions; /** For non-blocking allreduces. */ Al::request m_allreduce_req; #ifdef LBANN_HAS_GPU /** For non-blocking GPU-CPU memory copies. */ gpu_lib::event_wrapper m_copy_event; #endif // LBANN_HAS_GPU /** Add the sum of squares of @c vals to @c contribution. * * @param vals The values to accumulate * @param contribution @f$ 1 \times 1 @f$ matrix. Used as an * accumulation variable. */ template <El::Device Device> static void accumulate_contribution(const DMatType<Device>& vals, DMatType<Device>& contribution); }; } // namespace lbann #endif // LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED
34.956897
97
0.687546
oyamay
a00e4b3f6bc46d7db803a7a07903956875a56519
1,985
cc
C++
proto_builder/oss/unified_diff_test.cc
google/cpp-proto-builder
b23afd1b55e2c6c20a3d82e3285f794b1acb3faa
[ "Apache-2.0" ]
1
2021-08-18T23:41:31.000Z
2021-08-18T23:41:31.000Z
proto_builder/oss/unified_diff_test.cc
google/cpp-proto-builder
b23afd1b55e2c6c20a3d82e3285f794b1acb3faa
[ "Apache-2.0" ]
null
null
null
proto_builder/oss/unified_diff_test.cc
google/cpp-proto-builder
b23afd1b55e2c6c20a3d82e3285f794b1acb3faa
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The CPP Proto Builder Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "proto_builder/oss/unified_diff.h" #include <string> #include "gmock/gmock.h" #include "proto_builder/oss/testing/cpp_pb_gunit.h" namespace proto_builder::oss { namespace { using ::testing::HasSubstr; using ::testing::IsEmpty; TEST(UnifiedDiffTest, Empty) { EXPECT_THAT(UnifiedDiff(/*left=*/"", /*right=*/"", "left", "right", 0), IsEmpty()); } TEST(UnifiedDiffTest, DiffLineNum) { EXPECT_THAT(UnifiedDiff(/*left=*/"extra_left_content\n", /*right=*/"", "left", "right", 0), HasSubstr("Line Number: 2-2")); } TEST(UnifiedDiffTest, SingleDiff) { EXPECT_THAT(UnifiedDiff("left_content", "right_content", "left", "right", 0), HasSubstr("Line Number: 1\n" "--- left_content\n" "+++ right_content")); } TEST(UnifiedDiffTest, DiffOnDiffLines) { std::string diff = UnifiedDiff( "same_content\n" "left_content", "same_content\n" "right_content\n" "extra_right_content", "left", "right", 0); EXPECT_THAT(diff, HasSubstr("Line Number: 2\n" "--- left_content\n" "+++ right_content\n")); EXPECT_THAT(diff, HasSubstr("Line Number: 3-3\n" "+++ extra_right_content")); } } // namespace } // namespace proto_builder::oss
31.507937
80
0.627708
google
a00f9f1f620bea25cab77ae6a5c084de702031d3
443
cpp
C++
codechef/FEB20/SNUG_FIT.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codechef/FEB20/SNUG_FIT.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codechef/FEB20/SNUG_FIT.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--){ int n; cin >> n; unsigned a[n]; unsigned b[n]; for(int i=0 ; i<n ; i++) cin >> a[i]; for(int i=0 ; i<n ; i++) cin >> b[i]; sort(a,a+n); sort(b,b+n); unsigned long long int out = 0; for(int i=0 ; i<n ; i++) out += min(a[i],b[i]); cout << out << "\n"; } }
15.821429
34
0.525959
udayan14
a00fbe00148d2fc12ea641bd37d2192d403d6f1a
3,483
cpp
C++
src/peanoclaw/native/scenarios/CalmOcean.cpp
unterweg/peanoclaw
2d8b45727e3b26d824f8afc6a8772736176083af
[ "BSD-3-Clause" ]
1
2015-07-14T10:05:52.000Z
2015-07-14T10:05:52.000Z
src/peanoclaw/native/scenarios/CalmOcean.cpp
unterweg/peanoclaw
2d8b45727e3b26d824f8afc6a8772736176083af
[ "BSD-3-Clause" ]
null
null
null
src/peanoclaw/native/scenarios/CalmOcean.cpp
unterweg/peanoclaw
2d8b45727e3b26d824f8afc6a8772736176083af
[ "BSD-3-Clause" ]
1
2019-12-03T15:58:53.000Z
2019-12-03T15:58:53.000Z
/* * CalmOcean.cpp * * Created on: Jun 10, 2014 * Author: kristof */ #include "peanoclaw/native/scenarios/CalmOcean.h" #include "peanoclaw/Patch.h" peanoclaw::native::scenarios::CalmOcean::CalmOcean( std::vector<std::string> arguments ) : _domainSize(1.0) { if(arguments.size() != 4) { std::cerr << "Expected arguments for Scenario 'CalmOcean': subgridTopology subdivisionFactor endTime globalTimestepSize" << std::endl << "\tGot " << arguments.size() << " arguments." << std::endl; throw ""; } double subgridTopologyPerDimension = atof(arguments[0].c_str()); _demandedMeshWidth = _domainSize/ subgridTopologyPerDimension; _subdivisionFactor = tarch::la::Vector<DIMENSIONS,int>(atoi(arguments[1].c_str())); _endTime = atof(arguments[2].c_str()); _globalTimestepSize = atof(arguments[3].c_str()); } void peanoclaw::native::scenarios::CalmOcean::initializePatch(peanoclaw::Patch& patch) { const tarch::la::Vector<DIMENSIONS, double> patchPosition = patch.getPosition(); const tarch::la::Vector<DIMENSIONS, double> meshWidth = patch.getSubcellSize(); peanoclaw::grid::SubgridAccessor& accessor = patch.getAccessor(); tarch::la::Vector<DIMENSIONS, int> subcellIndex; for (int yi = 0; yi < patch.getSubdivisionFactor()(1); yi++) { for (int xi = 0; xi < patch.getSubdivisionFactor()(0); xi++) { subcellIndex(0) = xi; subcellIndex(1) = yi; double X = patchPosition(0) + xi*meshWidth(0); double Y = patchPosition(1) + yi*meshWidth(1); double q0 = getWaterHeight(X, Y); double q1 = 0.0; double q2 = 0.0; accessor.setValueUNew(subcellIndex, 0, q0); accessor.setValueUNew(subcellIndex, 1, q1); accessor.setValueUNew(subcellIndex, 2, q2); accessor.setParameterWithGhostlayer(subcellIndex, 0, 0.0); assertion2(tarch::la::equals(accessor.getValueUNew(subcellIndex, 0), q0, 1e-5), accessor.getValueUNew(subcellIndex, 0), q0); assertion2(tarch::la::equals(accessor.getValueUNew(subcellIndex, 1), q1, 1e-5), accessor.getValueUNew(subcellIndex, 1), q1); assertion2(tarch::la::equals(accessor.getValueUNew(subcellIndex, 2), q2, 1e-5), accessor.getValueUNew(subcellIndex, 2), q2); } } } tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::computeDemandedMeshWidth(peanoclaw::Patch& patch, bool isInitializing) { return _demandedMeshWidth; } //PeanoClaw-Scenario tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::getDomainOffset() const { return 0; } tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::getDomainSize() const { return _domainSize; } tarch::la::Vector<DIMENSIONS,double> peanoclaw::native::scenarios::CalmOcean::getInitialMinimalMeshWidth() const { return _demandedMeshWidth; } tarch::la::Vector<DIMENSIONS,int> peanoclaw::native::scenarios::CalmOcean::getSubdivisionFactor() const { return _subdivisionFactor; } double peanoclaw::native::scenarios::CalmOcean::getGlobalTimestepSize() const { return _globalTimestepSize; } double peanoclaw::native::scenarios::CalmOcean::getEndTime() const { return _endTime; } //pure SWE-Scenario float peanoclaw::native::scenarios::CalmOcean::getWaterHeight(float x, float y) { return 1.0f; } float peanoclaw::native::scenarios::CalmOcean::waterHeightAtRest() { return getWaterHeight(0, 0); } float peanoclaw::native::scenarios::CalmOcean::endSimulation() { return (float)getEndTime(); }
35.540816
150
0.718346
unterweg
a01030feb34187f4615a90a325940c27664d6e15
7,569
cc
C++
contrib/endpoints/src/grpc/transcoding/request_weaver.cc
mandarjog/proxy
33d357e35a95c92f46012bb16396f949c240fd47
[ "Apache-2.0" ]
1
2020-10-27T12:17:07.000Z
2020-10-27T12:17:07.000Z
contrib/endpoints/src/grpc/transcoding/request_weaver.cc
mandarjog/proxy
33d357e35a95c92f46012bb16396f949c240fd47
[ "Apache-2.0" ]
null
null
null
contrib/endpoints/src/grpc/transcoding/request_weaver.cc
mandarjog/proxy
33d357e35a95c92f46012bb16396f949c240fd47
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 Google Inc. 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 "contrib/endpoints/src/grpc/transcoding/request_weaver.h" #include <string> #include <vector> #include "google/protobuf/stubs/stringpiece.h" #include "google/protobuf/type.pb.h" #include "google/protobuf/util/internal/datapiece.h" #include "google/protobuf/util/internal/object_writer.h" namespace google { namespace api_manager { namespace transcoding { namespace pb = google::protobuf; namespace pbconv = google::protobuf::util::converter; RequestWeaver::RequestWeaver(std::vector<BindingInfo> bindings, pbconv::ObjectWriter* ow) : root_(), current_(), ow_(ow), non_actionable_depth_(0) { for (const auto& b : bindings) { Bind(std::move(b.field_path), std::move(b.value)); } } RequestWeaver* RequestWeaver::StartObject(pb::StringPiece name) { ow_->StartObject(name); if (current_.empty()) { // The outermost StartObject(""); current_.push(&root_); return this; } if (non_actionable_depth_ == 0) { WeaveInfo* info = current_.top()->FindWeaveMsg(name); if (info != nullptr) { current_.push(info); return this; } } // At this point, we don't match any messages we need to weave into, so // we won't need to do any matching until we leave this object. ++non_actionable_depth_; return this; } RequestWeaver* RequestWeaver::EndObject() { if (non_actionable_depth_ > 0) { --non_actionable_depth_; } else { WeaveTree(current_.top()); current_.pop(); } ow_->EndObject(); return this; } RequestWeaver* RequestWeaver::StartList(google::protobuf::StringPiece name) { ow_->StartList(name); // We don't support weaving inside lists, so we won't need to do any matching // until we leave this list. ++non_actionable_depth_; return this; } RequestWeaver* RequestWeaver::EndList() { ow_->EndList(); --non_actionable_depth_; return this; } RequestWeaver* RequestWeaver::RenderBool(google::protobuf::StringPiece name, bool value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderBool(name, value); return this; } RequestWeaver* RequestWeaver::RenderInt32(google::protobuf::StringPiece name, google::protobuf::int32 value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderInt32(name, value); return this; } RequestWeaver* RequestWeaver::RenderUint32(google::protobuf::StringPiece name, google::protobuf::uint32 value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderUint32(name, value); return this; } RequestWeaver* RequestWeaver::RenderInt64(google::protobuf::StringPiece name, google::protobuf::int64 value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderInt64(name, value); return this; } RequestWeaver* RequestWeaver::RenderUint64(google::protobuf::StringPiece name, google::protobuf::uint64 value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderUint64(name, value); return this; } RequestWeaver* RequestWeaver::RenderDouble(google::protobuf::StringPiece name, double value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderDouble(name, value); return this; } RequestWeaver* RequestWeaver::RenderFloat(google::protobuf::StringPiece name, float value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderFloat(name, value); return this; } RequestWeaver* RequestWeaver::RenderString( google::protobuf::StringPiece name, google::protobuf::StringPiece value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderString(name, value); return this; } RequestWeaver* RequestWeaver::RenderNull(google::protobuf::StringPiece name) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderNull(name); return this; } RequestWeaver* RequestWeaver::RenderBytes(google::protobuf::StringPiece name, google::protobuf::StringPiece value) { if (non_actionable_depth_ == 0) { CollisionCheck(name); } ow_->RenderBytes(name, value); return this; } void RequestWeaver::Bind(std::vector<const pb::Field*> field_path, std::string value) { WeaveInfo* current = &root_; // Find or create the path from the root to the leaf message, where the value // should be injected. for (size_t i = 0; i < field_path.size() - 1; ++i) { current = current->FindOrCreateWeaveMsg(field_path[i]); } if (!field_path.empty()) { current->bindings.emplace_back(field_path.back(), std::move(value)); } } void RequestWeaver::WeaveTree(RequestWeaver::WeaveInfo* info) { for (const auto& data : info->bindings) { pbconv::ObjectWriter::RenderDataPieceTo( pbconv::DataPiece(pb::StringPiece(data.second), true), pb::StringPiece(data.first->name()), ow_); } info->bindings.clear(); for (auto& msg : info->messages) { // Enter into the message only if there are bindings or submessages left if (!msg.second.bindings.empty() || !msg.second.messages.empty()) { ow_->StartObject(msg.first->name()); WeaveTree(&msg.second); ow_->EndObject(); } } info->messages.clear(); } void RequestWeaver::CollisionCheck(pb::StringPiece name) { if (current_.empty()) return; for (auto it = current_.top()->bindings.begin(); it != current_.top()->bindings.end();) { if (name == it->first->name()) { if (it->first->cardinality() == pb::Field::CARDINALITY_REPEATED) { pbconv::ObjectWriter::RenderDataPieceTo( pbconv::DataPiece(pb::StringPiece(it->second), true), name, ow_); } else { // TODO: Report collision error. For now we just ignore // the conflicting binding. } it = current_.top()->bindings.erase(it); continue; } ++it; } } RequestWeaver::WeaveInfo* RequestWeaver::WeaveInfo::FindWeaveMsg( const pb::StringPiece field_name) { for (auto& msg : messages) { if (field_name == msg.first->name()) { return &msg.second; } } return nullptr; } RequestWeaver::WeaveInfo* RequestWeaver::WeaveInfo::CreateWeaveMsg( const pb::Field* field) { messages.emplace_back(field, WeaveInfo()); return &messages.back().second; } RequestWeaver::WeaveInfo* RequestWeaver::WeaveInfo::FindOrCreateWeaveMsg( const pb::Field* field) { WeaveInfo* found = FindWeaveMsg(field->name()); return found == nullptr ? CreateWeaveMsg(field) : found; } } // namespace transcoding } // namespace api_manager } // namespace google
29.566406
80
0.652134
mandarjog
a0115c88d2d2f11ac8d1c76a32b7b5421b478576
493
cpp
C++
OpenGL3D Game/Floor.cpp
TheSandstorm/Tank-Busters
06aec0b25a92e8c9c8959c5173cbef605bb6543d
[ "MIT" ]
null
null
null
OpenGL3D Game/Floor.cpp
TheSandstorm/Tank-Busters
06aec0b25a92e8c9c8959c5173cbef605bb6543d
[ "MIT" ]
null
null
null
OpenGL3D Game/Floor.cpp
TheSandstorm/Tank-Busters
06aec0b25a92e8c9c8959c5173cbef605bb6543d
[ "MIT" ]
null
null
null
#include "Floor.h" CFloor::CFloor(glm::vec3 _Pos) { Scale = glm::vec3(8.0f, 8.0f, 0.2f); Rotation = glm::vec3(0.0f, 0.0f, 0.0f); Pos = _Pos; VAO = CObjectManager::GetMesh(FLOOR_ENTITY)->VAO; IndicesCount = CObjectManager::GetMesh(FLOOR_ENTITY)->IndicesCount; Texture = CObjectManager::GetMesh(FLOOR_ENTITY)->Texture; Shader = CObjectManager::GetMesh(FLOOR_ENTITY)->Shader; Type = FLOOR_ENTITY; } void CFloor::Update(float _DeltaTime) { VPMatrix = CCamera::GetMatrix(); Render(); }
24.65
68
0.716024
TheSandstorm
a01550a82f0c5a1c5cf1d4b3faa388c32cf1f027
2,223
cpp
C++
Source/Editor/src/Panels/PanelResources.cpp
bar0net/BlueFir-Engine
24526a07b60c09c04fdab6b12a5e3312b68ab400
[ "MIT" ]
null
null
null
Source/Editor/src/Panels/PanelResources.cpp
bar0net/BlueFir-Engine
24526a07b60c09c04fdab6b12a5e3312b68ab400
[ "MIT" ]
null
null
null
Source/Editor/src/Panels/PanelResources.cpp
bar0net/BlueFir-Engine
24526a07b60c09c04fdab6b12a5e3312b68ab400
[ "MIT" ]
null
null
null
#include "PanelResources.h" #include "../../Vendor/imgui-docking/imgui.h" #include "AssetsObserver.h" #include "ModuleResources.h" #include "Resource.h" #include "../ModuleEditor.h" #include "PanelResourcePreview.h" #include <string> #include <vector> #include <stack> void bluefir::editor::PanelResources::Init() { } void bluefir::editor::PanelResources::Draw() { if (!enabled_) return; ImGui::Begin(name_.c_str(), &enabled_); std::vector<std::string> asset_list = bluefir_resources.observer->GetAssetList(); if (ImGui::TreeNode("Assets")) { std::stack<std::string> asset_container; std::stack<bool> node_open; asset_container.push(BF_FILESYSTEM_ASSETSDIR); node_open.push(true); for (std::string it : asset_list) { while (!asset_container.empty() && it.find(asset_container.top()) == it.npos) { if (asset_container.empty()) break; asset_container.pop(); if (node_open.top()) ImGui::TreePop(); node_open.pop(); } size_t length = asset_container.top().length(); std::string name = it.substr(length+1, it.npos); if (base::FileSystem::IsDir(it.c_str())) { asset_container.push(it); node_open.push(ImGui::TreeNode(name.c_str())); } else { if (node_open.top()) { bool selected = (it == selected_asset); if (ImGui::Selectable(name.c_str(), &selected)) { if (selected_uid != 0) ((PanelResourcePreview*)bluefir_editor.resource_preview_)->Release(); selected_asset = it; selected_uid = bluefir_resources.Find(selected_asset.c_str()); ((PanelResourcePreview*)bluefir_editor.resource_preview_)->Set(selected_uid); } } //if (ImGui::TreeNode(name.c_str())) ImGui::TreePop(); } } while (!node_open.empty()) { if (node_open.top()) ImGui::TreePop(); node_open.pop(); } } ImGui::Separator(); ImGui::Text("Selected Resource:"); UID uid = bluefir_resources.Find(selected_asset.c_str()); if (uid != 0) { const resources::Resource* resource = bluefir_resources.Get(uid); ImGui::Text("UID: %s\nFile: %s\nType: %d\nInstances: %d", std::to_string(resource->GetUID()).c_str(), resource->GetFile(), (unsigned)resource->GetType(), resource->Count()); } ImGui::End(); }
24.7
175
0.664867
bar0net
a0155cc74392ea229d7545d5f346aa85df0eaf36
569
hpp
C++
mys/lib/mys/errors/not_implemented.hpp
eerimoq/sython
90937bf44b798b9c1ae0d18e31e11e95967b46c6
[ "MIT" ]
83
2020-08-18T18:48:46.000Z
2021-01-01T17:00:45.000Z
mys/lib/mys/errors/not_implemented.hpp
eerimoq/sython
90937bf44b798b9c1ae0d18e31e11e95967b46c6
[ "MIT" ]
31
2021-01-05T00:32:36.000Z
2022-02-23T13:34:33.000Z
mys/lib/mys/errors/not_implemented.hpp
eerimoq/sython
90937bf44b798b9c1ae0d18e31e11e95967b46c6
[ "MIT" ]
7
2021-01-03T11:53:03.000Z
2022-02-22T17:49:42.000Z
#pragma once #include "base.hpp" namespace mys { class NotImplementedError : public Error { public: String m_message; NotImplementedError() { } NotImplementedError(const String& message) : m_message(message) { } virtual ~NotImplementedError() { } [[ noreturn ]] void __throw(); String __str__(); }; class __NotImplementedError final : public __Error { public: __NotImplementedError(const mys::shared_ptr<NotImplementedError>& error) : __Error(static_cast<mys::shared_ptr<Error>>(error)) { } }; }
17.78125
76
0.660808
eerimoq
a0159e63ea13c1863ef3f2bda895cc10b32aea32
3,340
cpp
C++
dataAQ.cpp
kevinyxlu/cs32lab03
582c42181d8e7891a6f34a3ef5f524c915e963a1
[ "MIT" ]
null
null
null
dataAQ.cpp
kevinyxlu/cs32lab03
582c42181d8e7891a6f34a3ef5f524c915e963a1
[ "MIT" ]
null
null
null
dataAQ.cpp
kevinyxlu/cs32lab03
582c42181d8e7891a6f34a3ef5f524c915e963a1
[ "MIT" ]
null
null
null
/* aggregate data */ #include "dataAQ.h" #include "demogData.h" #include <iostream> #include <algorithm> dataAQ::dataAQ() {} /* necessary function to aggregate the data - this CAN and SHOULD vary per student - depends on how they map, etc. */ void dataAQ::createStateData(std::vector<shared_ptr<demogData>> theData) { //FILL in std::string currentState = theData[0]->getState(); std::vector<shared_ptr<demogData>> stateCounties; for (auto entry : theData) { if (entry->getState() != currentState) { theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties))); // std::cout << "New map entry for state: " << currentState << "\n"; //deboog stateCounties.clear(); currentState = entry->getState(); } stateCounties.push_back(entry); } if (stateCounties.size()) { theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties))); //std::cout << "New map entry for (final) state: " << currentState << "\n"; //deboog stateCounties.clear(); } //std::cout << theStates.size() << "\n"; //deboog } //return the name of the state with the largest population under age 5 string dataAQ::youngestPop() { //FILL in double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getpopUnder5() > record) { usurper = state.first; record = state.second->getpopUnder5(); } } return usurper; } //return the name of the state with the largest population under age 18 string dataAQ::teenPop() { double record = 0; string usurper = ""; for (auto state : theStates) { //std::cout << state.first << ": " << state.second->getpopUnder18() << " vs " << record << "\n"; if (state.second->getpopUnder18() > record) { usurper = state.first; record = state.second->getpopUnder18(); } } return usurper; } //return the name of the state with the largest population over age 65 string dataAQ::wisePop() { double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getpopOver65() > record) { usurper = state.first; record = state.second->getpopOver65(); } } return usurper; } //return the name of the state with the largest population who did not receive high school diploma string dataAQ::underServeHS() { //FILL in double record = 0; string usurper = ""; for (auto state : theStates) { if ((100.0 - state.second->getHSup()) > record) { usurper = state.first; record = 100.0 - state.second->getHSup(); } } return usurper; } //return the name of the state with the largest population who did receive bachelors degree and up string dataAQ::collegeGrads() { double record = 0; string usurper = ""; for (auto state : theStates) { if ((state.second->getBAup()) > record) { usurper = state.first; record = state.second->getBAup(); } } return usurper; } //return the name of the state with the largest population below the poverty line string dataAQ::belowPoverty() { double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getPoverty() > record) { usurper = state.first; record = state.second->getPoverty(); } } return usurper; }
29.557522
112
0.648802
kevinyxlu
a018bdf1a7bf6325df518c8134d16e5575c93d20
3,329
cpp
C++
automated-tests/src/dali/utc-Dali-Semaphore.cpp
dalihub/dali-core
f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195
[ "Apache-2.0", "BSD-3-Clause" ]
21
2016-11-18T10:26:40.000Z
2021-11-02T09:46:15.000Z
automated-tests/src/dali/utc-Dali-Semaphore.cpp
dalihub/dali-core
f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-10-18T17:39:12.000Z
2020-12-01T11:45:36.000Z
automated-tests/src/dali/utc-Dali-Semaphore.cpp
dalihub/dali-core
f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195
[ "Apache-2.0", "BSD-3-Clause" ]
16
2017-03-08T15:50:32.000Z
2021-05-24T06:58:10.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <dali-test-suite-utils.h> #include <dali/devel-api/threading/semaphore.h> #include <dali/public-api/dali-core.h> #include <algorithm> #include <chrono> #include <future> #include <stdexcept> #include <thread> int UtcDaliSemaphoreTryAcquire(void) { using namespace std::chrono_literals; constexpr auto waitTime{100ms}; tet_infoline("Testing Dali::Semaphore try acquire methods"); Dali::Semaphore<3> sem(0); DALI_TEST_EQUALS(false, sem.TryAcquire(), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireFor(waitTime), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION); sem.Release(3); DALI_TEST_EQUALS(true, sem.TryAcquire(), TEST_LOCATION); DALI_TEST_EQUALS(true, sem.TryAcquireFor(waitTime), TEST_LOCATION); DALI_TEST_EQUALS(true, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquire(), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireFor(waitTime), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION); END_TEST; } int UtcDaliSemaphoreInvalidArguments(void) { tet_infoline("Testing Dali::Semaphore invalid arguments"); Dali::Semaphore<2> sem(0); DALI_TEST_THROWS(sem.Release(3), std::invalid_argument); DALI_TEST_THROWS(sem.Release(-1), std::invalid_argument); sem.Release(1); DALI_TEST_THROWS(sem.Release(2), std::invalid_argument); sem.Release(1); DALI_TEST_THROWS(sem.Release(1), std::invalid_argument); DALI_TEST_THROWS(Dali::Semaphore<1>(2), std::invalid_argument); DALI_TEST_THROWS(Dali::Semaphore<>(-1), std::invalid_argument); END_TEST; } int UtcDaliSemaphoreAcquire(void) { tet_infoline("Testing Dali::Semaphore multithread acquire"); using namespace std::chrono_literals; constexpr std::ptrdiff_t numTasks{2}; auto f = [](Dali::Semaphore<numTasks>& sem, bool& flag) { sem.Acquire(); flag = true; }; auto flag1{false}, flag2{false}; Dali::Semaphore<numTasks> sem(0); auto fut1 = std::async(std::launch::async, f, std::ref(sem), std::ref(flag1)); auto fut2 = std::async(std::launch::async, f, std::ref(sem), std::ref(flag2)); DALI_TEST_EQUALS(std::future_status::timeout, fut1.wait_for(100ms), TEST_LOCATION); DALI_TEST_EQUALS(std::future_status::timeout, fut2.wait_for(100ms), TEST_LOCATION); DALI_TEST_EQUALS(false, flag1, TEST_LOCATION); DALI_TEST_EQUALS(false, flag2, TEST_LOCATION); sem.Release(numTasks); fut1.wait(); DALI_TEST_EQUALS(true, flag1, TEST_LOCATION); fut2.wait(); DALI_TEST_EQUALS(true, flag2, TEST_LOCATION); END_TEST; }
32.637255
107
0.73836
dalihub
a01cc72ac877cdd9a5bc51643b519b3a5edb6914
278
cpp
C++
osal/linux/InternalErrorCodes.cpp
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
osal/linux/InternalErrorCodes.cpp
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
osal/linux/InternalErrorCodes.cpp
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
#include "../../osal/InternalErrorCodes.h" ReturnValue_t InternalErrorCodes::translate(uint8_t code) { //TODO This class can be removed return HasReturnvaluesIF::RETURN_FAILED; } InternalErrorCodes::InternalErrorCodes() { } InternalErrorCodes::~InternalErrorCodes() { }
18.533333
59
0.769784
bl4ckic3
a022d0a4a0cfeef4a021d4159ed2cdccfc0136df
3,508
cpp
C++
libs/GFX/Events.cpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
1
2019-08-14T12:31:50.000Z
2019-08-14T12:31:50.000Z
libs/GFX/Events.cpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
libs/GFX/Events.cpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
// // Created by killian on 13/11/18. // Epitech 3 years remaining // See http://github.com/KillianG // #include <SFML/Window/Event.hpp> #include "Events.hpp" #include <iostream> /** * simple constructor * @param mgr eventmanager */ gfx::Event::Event(EventManager &mgr) : _mgr(mgr){ } /** * get all events using sfml poll event * @param window the window where the events come from */ void gfx::Event::getEvents(std::shared_ptr<sf::RenderWindow> window) { sf::Event event; while (window->pollEvent(event)) { if (event.type == sf::Event::KeyReleased) { if (event.key.code == sf::Keyboard::Space) this->_mgr.emit<gfx::KeyReleasedEvent>(std::forward<std::string>("Space")); } if (event.type == sf::Event::MouseButtonPressed) this->_mgr.emit<gfx::ClickEvent>(std::forward<gfx::Vector2I>({event.mouseButton.x, event.mouseButton.y})); if (event.type == sf::Event::MouseButtonReleased) this->_mgr.emit<gfx::MouseReleaseEvent>( std::forward<gfx::Vector2I>({event.mouseButton.x, event.mouseButton.y})); if (event.type == sf::Event::MouseMoved) this->_mgr.emit<gfx::MouseMoveEvent>(std::forward<gfx::Vector2I>({event.mouseMove.x, event.mouseMove.y})); if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Space) this->_mgr.emit<gfx::KeyPressedEvent>(std::forward<std::string>("Space")); if (event.key.code == sf::Keyboard::Escape) this->_mgr.emit<gfx::KeyPressedEvent>(std::forward<std::string>("Escape")); } if (event.type == sf::Event::TextEntered) { std::string str = ""; if (event.text.unicode == 8) this->_mgr.emit<gfx::InputEvent>(); else { sf::Utf32::encodeAnsi(event.text.unicode, std::back_inserter(str), 'e'); for (auto a : str) { if (!std::isalnum(a) && a != '.') return; } this->_mgr.emit<gfx::InputEvent>(std::forward<std::string>(str)); } } } } /** * simple constructor for clickevent * @param pos the position */ gfx::ClickEvent::ClickEvent(gfx::Vector2I pos) : pos(pos) {} /** * getter for position of clickevent * @return */ const gfx::Vector2I gfx::ClickEvent::getPosition() const { return this->pos; } const gfx::Vector2I gfx::MouseMoveEvent::getPosition() const { return this->pos; } gfx::MouseMoveEvent::MouseMoveEvent(gfx::Vector2I pos) : pos(pos) {} gfx::MouseReleaseEvent::MouseReleaseEvent(gfx::Vector2I pos) : pos(pos) { } const gfx::Vector2I gfx::MouseReleaseEvent::getPosition() const { return this->pos; } gfx::KeyPressedEvent::KeyPressedEvent(std::string key) { this->key = key; } const std::string &gfx::KeyPressedEvent::getKey() const { return this->key; } gfx::KeyReleasedEvent::KeyReleasedEvent(std::string key) { this->key = key; } const std::string &gfx::KeyReleasedEvent::getKey() const { return this->key; } std::string gfx::InputEvent::input = ""; gfx::InputEvent::InputEvent() { if (gfx::InputEvent::input.size() > 0) gfx::InputEvent::input.pop_back(); } gfx::InputEvent::InputEvent(std::string input) { gfx::InputEvent::input += input; } std::string gfx::InputEvent::clear() { std::string copy = gfx::InputEvent::input; gfx::InputEvent::input.clear(); return copy; }
29.233333
118
0.608609
KillianG
a025b6636c624c0382da02eca001cd939cf62860
1,526
cpp
C++
src/RE/NiSystem.cpp
powerof3/CommonLibVR
c84cd2c63ccba0cc88a212fe9cf86b5470b10a4f
[ "MIT" ]
6
2020-04-05T04:37:42.000Z
2022-03-19T17:42:24.000Z
src/RE/NiSystem.cpp
kassent/CommonLibSSE
394231b44ba01925fef9d01ea2b0b29c2fff601c
[ "MIT" ]
3
2021-11-08T09:31:20.000Z
2022-03-02T19:22:42.000Z
src/RE/NiSystem.cpp
kassent/CommonLibSSE
394231b44ba01925fef9d01ea2b0b29c2fff601c
[ "MIT" ]
6
2020-04-10T18:11:46.000Z
2022-01-18T22:31:25.000Z
#include "RE/NiSystem.h" #include <cassert> #include <cstdarg> namespace RE { int NiMemcpy(void* a_dest, std::size_t a_destSize, const void* a_src, std::size_t a_count) { auto result = memcpy_s(a_dest, a_destSize, a_src, a_count); assert(result == 0); return result; } int NiSprintf(char* a_dest, std::size_t a_destSize, const char* a_format, ...) { assert(a_format); std::va_list kArgs; va_start(kArgs, a_format); auto ret = NiVsprintf(a_dest, a_destSize, a_format, kArgs); va_end(kArgs); return ret; } char* NiStrcat(char* a_dest, std::size_t a_destSize, const char* a_src) { strcat_s(a_dest, a_destSize, a_src); return a_dest; } char* NiStrncpy(char* a_dest, std::size_t a_destSize, const char* a_src, std::size_t a_count) { strncpy_s(a_dest, a_destSize, a_src, a_count); return a_dest; } int NiVsnprintf(char* a_dest, std::size_t a_destSize, std::size_t a_count, const char* a_format, std::va_list a_args) { if (a_destSize == 0) { return 0; } assert(a_dest); assert(a_count < a_destSize || a_count == NI_TRUNCATE); assert(a_format); a_dest[0] = '\0'; bool truncate = (a_count == NI_TRUNCATE); auto result = vsnprintf_s(a_dest, a_destSize, a_count, a_format, a_args); if (result < -1 && !truncate) { result = static_cast<int>(a_count); } return result; } int NiVsprintf(char* a_dest, std::size_t a_destSize, const char* a_format, std::va_list a_args) { return NiVsnprintf(a_dest, a_destSize, NI_TRUNCATE, a_format, a_args); } }
20.90411
118
0.690039
powerof3
a0260a48557c2be356124c61a0598f764425b6e0
1,899
cpp
C++
docs/trainings/random-trainings/18th-SHU-CPC/solutions/i.cpp
Dup4/TI1050
4534909ef9a3b925d556d341ea5e2629357f68e6
[ "MIT" ]
null
null
null
docs/trainings/random-trainings/18th-SHU-CPC/solutions/i.cpp
Dup4/TI1050
4534909ef9a3b925d556d341ea5e2629357f68e6
[ "MIT" ]
null
null
null
docs/trainings/random-trainings/18th-SHU-CPC/solutions/i.cpp
Dup4/TI1050
4534909ef9a3b925d556d341ea5e2629357f68e6
[ "MIT" ]
1
2022-03-03T13:33:48.000Z
2022-03-03T13:33:48.000Z
#include <bits/stdc++.h> using namespace std; using ll = long long; #define SZ(x) (int(x.size())) const int N = 1e3 + 10, mod = 1e9 + 7; int n, m, v[N], fac[N], inv[N], bit[N], fbit[N]; ll f[N][N]; char s[N]; ll qpow(ll base, ll n) { ll res = 1; while (n) { if (n & 1) res = res * base % mod; base = base * base % mod; n >>= 1; } return res; } ll C(int n, int m) { return 1ll * fac[n] * inv[m] % mod * inv[n - m] % mod; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); fac[0] = 1; for (int i = 1; i < N; ++i) fac[i] = 1ll * fac[i - 1] * i % mod; inv[N - 1] = qpow(fac[N - 1], mod - 2); for (int i = N - 1; i >= 1; --i) inv[i - 1] = 1ll * inv[i] * i % mod; bit[0] = 1; for (int i = 1; i < N; ++i) bit[i] = 1ll * bit[i - 1] * 26 % mod; fbit[0] = 1; fbit[1] = qpow(26, mod - 2); for (int i = 2; i < N; ++i) fbit[i] = 1ll * fbit[i - 1] * fbit[1] % mod; f[0][0] = 1; for (int i = 1; i < N; ++i) { for (int j = 0; j <= i; ++j) { if (!j) { f[i][j] += f[i - 1][0] + f[i - 1][1]; f[i][j] %= mod; } else if (j < i) { f[i][j] += f[i - 1][j - 1] * 26 + f[i - 1][j + 1]; f[i][j] %= mod; } else if (j == i) { f[i][j] += f[i - 1][j - 1] * 26 % mod; f[i][j] %= mod; } } } cin >> n >> m; vector<string> vec(n + 1); for (int i = 1; i <= n; ++i) cin >> vec[i] >> v[i]; ll res = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { int len = SZ(vec[j]); if (i >= len) { res += f[m][i] * (i - len + 1) % mod * v[j] % mod * fbit[len] % mod; res %= mod; } } } printf("%lld\n", res); return 0; }
27.521739
84
0.360716
Dup4
a02670913b490831814bb5582910b07f68be6442
525
cc
C++
part-1/week-2/strassen_algorithm/benchmark.cc
mohitsakhuja/algorithms-course
bb9ca82279ee9d1ff9881d00d693a33084db214b
[ "MIT" ]
13
2019-07-07T17:25:57.000Z
2020-11-25T10:26:59.000Z
part-1/week-2/strassen_algorithm/benchmark.cc
mohitsakhuja/algorithms-course
bb9ca82279ee9d1ff9881d00d693a33084db214b
[ "MIT" ]
null
null
null
part-1/week-2/strassen_algorithm/benchmark.cc
mohitsakhuja/algorithms-course
bb9ca82279ee9d1ff9881d00d693a33084db214b
[ "MIT" ]
9
2019-08-30T19:11:45.000Z
2020-12-23T18:47:30.000Z
#include "benchmark.hh" #include <iostream> // Returns number of seconds between b and a double calculate(const struct rusage *b, const struct rusage *a) { if (b == NULL || a == NULL) return 0.0; return ((((a->ru_utime.tv_sec * 1000000 + a->ru_utime.tv_usec) - (b->ru_utime.tv_sec * 1000000 + b->ru_utime.tv_usec)) + ((a->ru_stime.tv_sec * 1000000 + a->ru_stime.tv_usec) - (b->ru_stime.tv_sec * 1000000 + b->ru_stime.tv_usec))) / 1000000.0); }
32.8125
78
0.579048
mohitsakhuja
a0273da26637dd4a31357d5be0471e5dcc855a2b
10,981
cc
C++
aimsalgo/src/aimsalgo/optimization/levmrq.cc
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
4
2019-07-09T05:34:10.000Z
2020-10-16T00:03:15.000Z
aimsalgo/src/aimsalgo/optimization/levmrq.cc
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
72
2018-10-31T14:52:50.000Z
2022-03-04T11:22:51.000Z
aimsalgo/src/aimsalgo/optimization/levmrq.cc
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
null
null
null
/* This software and supporting documentation are distributed by * Institut Federatif de Recherche 49 * CEA/NeuroSpin, Batiment 145, * 91191 Gif-sur-Yvette cedex * France * * This software is governed by the CeCILL-B license under * French law and abiding by the rules of distribution of free software. * You can use, modify and/or redistribute the software under the * terms of the CeCILL-B license as circulated by CEA, CNRS * and INRIA at the following URL "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. */ // activate deprecation warning #ifdef AIMSDATA_CLASS_NO_DEPREC_WARNING #undef AIMSDATA_CLASS_NO_DEPREC_WARNING #endif #include <cstdlib> #include <cartodata/volume/volume.h> #include <aims/optimization/levmrq.h> #include <aims/io/writer.h> using namespace std; using namespace carto; template < class T > LMFunction< T > *LevenbergMarquardt< T >::doit( rc_ptr<Volume< T > >& x, rc_ptr<Volume< T > >& y, rc_ptr<Volume< T > > *sig, rc_ptr<Volume< int > > *ia, rc_ptr<Volume< T > > *covar ) { ASSERT( x->getSizeY() == 1 && x->getSizeZ() == 1 && x->getSizeT() == 1 ); ASSERT( y->getSizeY() == 1 && y->getSizeZ() == 1 && y->getSizeT() == 1 ); ASSERT( x->getSizeX() == y->getSizeX() ); int i, itst; T alambda, chisq, ochisq; bool ok = true, status = true; int n = x->getSizeX(); int ma = lmFonc->param().size(); VolumeRef< T > tsig( n ); VolumeRef< int > tia( ma ); VolumeRef< T > tcov( ma, ma ); VolumeRef< T > alpha( ma, ma ); if ( sig ) { ASSERT( (*sig)->getSizeY() == 1 && (*sig)->getSizeZ() == 1 && (*sig)->getSizeT() == 1); ASSERT( (*sig)->getSizeX() == x->getSizeX() ); tsig = *sig; } else for ( i=0; i<n; i++ ) tsig( i ) = (T)1; if ( ia ) { ASSERT( (*ia)->getSizeY() == 1 && (*ia)->getSizeZ() == 1 && (*ia)->getSizeT() == 1 ); ASSERT( (*ia)->getSizeX() == ma ); tia = *ia; } else for ( i=0; i<ma; i++ ) tia( i ) = 1; itst = 0; alambda = (T)(-1); chisq = ochisq = (T)0; status = mrqmin( x, y, tsig, tia, &chisq, &alambda, tcov, alpha ); if ( !status ) return (LMFunction< T > *)0; while ( ok ) { ochisq = chisq; status = mrqmin( x, y, tsig, tia, &chisq, &alambda, tcov, alpha ); if ( !status ) return (LMFunction< T > *)0; std::cout << "chisq = " << chisq << " vs " << ochisq << std::endl ; if ( chisq > ochisq ) itst = 0; else if ( (T)fabs( ochisq - chisq ) < (T)0.1 ) itst++; if ( itst >= 4 ) { alambda = (T)0; status = mrqmin( x, y, tsig, tia, &chisq, &alambda, tcov, alpha ); if ( !status ) return (LMFunction< T > *)0; ok = false; } } if ( covar ) *covar = tcov; return lmFonc; } template LMFunction< float > * LevenbergMarquardt< float >::doit( rc_ptr<Volume< float > >& x, rc_ptr<Volume< float > >& y, rc_ptr<Volume< float > > *sig, rc_ptr<Volume< int > > *ia, rc_ptr<Volume< float > > *covar ); template LMFunction< double > * LevenbergMarquardt< double >::doit( rc_ptr<Volume< double > >& x, rc_ptr<Volume< double > >& y, rc_ptr<Volume< double > > *sig, rc_ptr<Volume< int > > *ia, rc_ptr<Volume< double > > *covar ); template< class T > bool LevenbergMarquardt< T >::mrqmin( rc_ptr<Volume< T > >& x, rc_ptr<Volume< T > >& y, rc_ptr<Volume< T > >& sig, rc_ptr<Volume< int > >& ia, T *chisq, T *alambda, rc_ptr<Volume< T > >& covar, rc_ptr<Volume< T > >& alpha ) { int j, k, l, m; int mfit; int ma = ia->getSizeX(); /*static*/ T ochisq; /*static*/ vector< T > atry; /*static*/ VolumeRef< T > beta; /*static*/ VolumeRef< T > da; /*static*/ VolumeRef< T > oneda; atry = vector< T >( ma ); beta = VolumeRef< T >( ma ); da = VolumeRef< T >( ma ); for ( mfit=0, j=0; j<ma; j++ ) if ( ia->at( j ) ) mfit++; oneda = VolumeRef< T >( mfit ); atry = lmFonc->param(); mrqcof( x, y, sig, ia, chisq, alpha, beta ); ochisq = (*chisq); if ( *alambda < (T)0 ) { std::cerr << "init " << std::endl ; *alambda = (T)0.001; // std::cerr << "init " << std::endl ; // atry = vector< T >( ma ); // beta = VolumeRef< T >( ma ); // da = VolumeRef< T >( ma ); // // for ( mfit=0, j=0; j<ma; j++ ) // if ( ia->at( j ) ) mfit++; // // oneda = VolumeRef< T >( mfit ); // // *alambda = (T)0.001; // // mrqcof( x, y, sig, ia, chisq, alpha, beta ); // // ochisq = (*chisq); // // atry = lmFonc->param(); } for ( j=-1, l=0; l<ma; l++ ) { if ( ia->at( l ) ) { for ( j++, k=-1, m=0; m<ma; m++ ) { if ( ia->at( m ) ) { k++; covar->at( j, k ) = alpha->at( j, k ); } } covar->at( j, j ) = alpha->at( j, j ) * ( (T)1 + (*alambda) ); oneda( j ) = beta( j ); } } // aims::Writer< VolumeRef<T> > wriCov( "covar.ima") ; // wriCov.write( covar ) ; // // aims::Writer< VolumeRef<T> > wriOD( "oneda.ima") ; // wriOD.write( oneda ) ; bool status = gaussj.doit( covar, oneda, mfit ); if ( !status ) return false; for ( j=0; j<mfit; j++ ) da( j ) = oneda( j ); if ( *alambda == (T)0 ) { covsrt.doit( covar, &ia, mfit ); } else { for ( j=-1, l=0; l<ma; l++ ) if ( ia->at( l ) ) lmFonc->param()[ l ] += da( ++j ); mrqcof( x, y, sig, ia, chisq, covar, da ); if ( *chisq < ochisq ) { *alambda *= (T)0.1; std::cout << "alamda decreased from " << *alambda << " to " << *alambda / 10 << endl ; ochisq = (*chisq); for ( j=-1, l=0; l<ma; l++ ) { if ( ia->at( l ) ) { for ( j++, k=-1, m=0; m<ma; m++ ) { if ( ia->at( m ) ) { k++; alpha->at( j, k ) = covar->at( j, k ); } } beta( j ) = da( j ); atry = lmFonc->param(); } } } else { //std::cout << "alamda increased from " << *alamda << " to " << *alamda * 10 << endl ; *alambda *= (T)10.0; *chisq = ochisq; lmFonc->param() = atry; } } cout << "mrqmin end" << endl ; return true; } template bool LevenbergMarquardt< float >::mrqmin( rc_ptr<Volume< float > >& x, rc_ptr<Volume< float > >& sig, rc_ptr<Volume< float > >& y, rc_ptr<Volume< int > >& ia, float *chisq, float *alambda, rc_ptr<Volume< float > >& covar, rc_ptr<Volume< float > >& alpha ); template bool LevenbergMarquardt< double >::mrqmin( rc_ptr<Volume< double > >& x, rc_ptr<Volume< double > >& y, rc_ptr<Volume< double > >& sig, rc_ptr<Volume< int > >& ia, double *chisq, double *alambda, rc_ptr<Volume< double > >& covar, rc_ptr<Volume< double > >& beta ); template< class T > void LevenbergMarquardt< T >::mrqcof( rc_ptr<Volume< T > >& x, rc_ptr<Volume< T > >& y, rc_ptr<Volume< T > >& sig, rc_ptr<Volume< int > >& ia, T *chisq, rc_ptr<Volume< T > >& alpha, rc_ptr<Volume< T > >& beta ) { int i, j, k, l, m, mfit=0; T ymod, wt, sig2i, dy; int n = x->getSizeX(); int ma = ia->getSizeX(); for ( j=0; j<ma; j++ ) if ( ia->at( j ) ) mfit++; for ( j=0; j<mfit; j++ ) { for ( k=0; k<=j; k++ ) alpha->at( j, k ) = (T)0; beta->at( j ) = (T)0; } *chisq = (T)0; for ( i=0; i<n; i++ ) { //std::cerr << "" << << std::endl ; ymod = lmFonc->eval( x->at( i ) ); sig2i = (T)1 / ( sig->at( i ) * sig->at( i ) ); dy = y->at( i ) - ymod; for ( j=-1, l=0; l<ma; l++ ) { if ( ia->at( l ) ) { wt = lmFonc->derivative()[ l ] * sig2i; for ( j++, k=-1, m=0; m<=l; m++ ) if ( ia->at( m ) ) alpha->at( j, ++k ) += wt * lmFonc->derivative()[ m ]; beta->at( j ) += dy * wt; } } *chisq += dy * dy * sig2i; } for ( j=1; j<mfit; j++ ) for ( k=0; k<j; k++ ) alpha->at( k, j ) = alpha->at( j, k ); } template void LevenbergMarquardt< float >::mrqcof( rc_ptr<Volume< float > >& x, rc_ptr<Volume< float > >& y, rc_ptr<Volume< float > >& sig, rc_ptr<Volume< int > >& ia, float *chisq, rc_ptr<Volume< float > >& alpha, rc_ptr<Volume< float > >& beta ); template void LevenbergMarquardt< double >::mrqcof( rc_ptr<Volume< double > >& x, rc_ptr<Volume< double > >& y, rc_ptr<Volume< double > >& sig, rc_ptr<Volume< int > >& ia, double *chisq, rc_ptr<Volume< double > >& alpha, rc_ptr<Volume< double > >& beta );
29.127321
89
0.471451
brainvisa
a027e3d0dc7341bdef7386e61bfbf614e158c25f
553
cpp
C++
src/task_simple.cpp
dvetutnev/Ecwid-Console-downloader
35994baae9d4ab518d465aeafbdc0020c5482532
[ "MIT" ]
1
2017-07-04T07:20:24.000Z
2017-07-04T07:20:24.000Z
src/task_simple.cpp
dvetutnev/Ecwid-Console-downloader
35994baae9d4ab518d465aeafbdc0020c5482532
[ "MIT" ]
null
null
null
src/task_simple.cpp
dvetutnev/Ecwid-Console-downloader
35994baae9d4ab518d465aeafbdc0020c5482532
[ "MIT" ]
null
null
null
#include "task_simple.h" #include <sstream> std::unique_ptr<Task> TaskListSimple::get() { using namespace std; unique_ptr<Task> ret; while( !stream.eof() ) { string buf; getline(stream, buf); if ( buf.empty() ) continue; istringstream sbuf{ move(buf) }; string uri, fname; sbuf >> uri; sbuf >> fname; if ( uri.empty() || fname.empty() ) continue; ret = make_unique<Task>( move(uri), path + fname ); break; } return ret; }
19.068966
59
0.520796
dvetutnev
a0299759b45b07ad5685d744d2c8a237742b8213
9,030
cpp
C++
cli/tests/DistributedCommandExecutorTestRunner.cpp
yuanchenl/quickstep
cc20fed6e56b0e583ae15a0219c070c8bacf14ba
[ "Apache-2.0" ]
1
2021-08-22T19:16:59.000Z
2021-08-22T19:16:59.000Z
cli/tests/DistributedCommandExecutorTestRunner.cpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
null
null
null
cli/tests/DistributedCommandExecutorTestRunner.cpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
1
2021-11-30T13:50:59.000Z
2021-11-30T13:50:59.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include "cli/tests/DistributedCommandExecutorTestRunner.hpp" #include <cstdio> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "cli/CommandExecutorUtil.hpp" #include "cli/Constants.hpp" #include "cli/DropRelation.hpp" #include "cli/PrintToScreen.hpp" #include "parser/ParseStatement.hpp" #include "query_execution/BlockLocator.hpp" #include "query_execution/BlockLocatorUtil.hpp" #include "query_execution/ForemanDistributed.hpp" #include "query_execution/QueryExecutionTypedefs.hpp" #include "query_execution/QueryExecutionUtil.hpp" #include "query_optimizer/Optimizer.hpp" #include "query_optimizer/OptimizerContext.hpp" #include "query_optimizer/QueryHandle.hpp" #include "query_optimizer/tests/TestDatabaseLoader.hpp" #include "storage/DataExchangerAsync.hpp" #include "storage/StorageManager.hpp" #include "utility/MemStream.hpp" #include "utility/SqlError.hpp" #include "glog/logging.h" #include "tmb/id_typedefs.h" #include "tmb/message_bus.h" #include "tmb/tagged_message.h" using std::make_unique; using std::string; using std::vector; using tmb::TaggedMessage; namespace quickstep { class CatalogRelation; namespace C = cli; const char *DistributedCommandExecutorTestRunner::kResetOption = "reset_before_execution"; DistributedCommandExecutorTestRunner::DistributedCommandExecutorTestRunner(const string &storage_path) : query_id_(0) { bus_.Initialize(); cli_id_ = bus_.Connect(); bus_.RegisterClientAsSender(cli_id_, kAdmitRequestMessage); bus_.RegisterClientAsSender(cli_id_, kPoisonMessage); bus_.RegisterClientAsReceiver(cli_id_, kQueryExecutionSuccessMessage); bus_.RegisterClientAsSender(cli_id_, kBlockDomainRegistrationMessage); bus_.RegisterClientAsReceiver(cli_id_, kBlockDomainRegistrationResponseMessage); block_locator_ = make_unique<BlockLocator>(&bus_); block_locator_->start(); test_database_loader_ = make_unique<optimizer::TestDatabaseLoader>( storage_path, block_locator::getBlockDomain( test_database_loader_data_exchanger_.network_address(), cli_id_, &locator_client_id_, &bus_), locator_client_id_, &bus_); DCHECK_EQ(block_locator_->getBusClientID(), locator_client_id_); test_database_loader_data_exchanger_.set_storage_manager(test_database_loader_->storage_manager()); test_database_loader_data_exchanger_.start(); test_database_loader_->createTestRelation(false /* allow_vchar */); test_database_loader_->loadTestRelation(); // NOTE(zuyu): Foreman should initialize before Shiftboss so that the former // could receive a registration message from the latter. foreman_ = make_unique<ForemanDistributed>(*block_locator_, &bus_, test_database_loader_->catalog_database(), nullptr /* query_processor */); foreman_->start(); // We don't use the NUMA aware version of worker code. const vector<numa_node_id> numa_nodes(1 /* Number of worker threads per instance */, kAnyNUMANodeID); bus_local_.Initialize(); worker_ = make_unique<Worker>(0 /* worker_thread_index */, &bus_local_); const vector<tmb::client_id> worker_client_ids(1, worker_->getBusClientID()); worker_directory_ = make_unique<WorkerDirectory>(worker_client_ids.size(), worker_client_ids, numa_nodes); storage_manager_ = make_unique<StorageManager>( storage_path, block_locator::getBlockDomain( data_exchanger_.network_address(), cli_id_, &locator_client_id_, &bus_), locator_client_id_, &bus_); DCHECK_EQ(block_locator_->getBusClientID(), locator_client_id_); data_exchanger_.set_storage_manager(storage_manager_.get()); shiftboss_ = make_unique<Shiftboss>(&bus_, &bus_local_, storage_manager_.get(), worker_directory_.get(), storage_manager_->hdfs()); data_exchanger_.start(); shiftboss_->start(); worker_->start(); } DistributedCommandExecutorTestRunner::~DistributedCommandExecutorTestRunner() { const tmb::MessageBus::SendStatus send_status = QueryExecutionUtil::SendTMBMessage(&bus_, cli_id_, foreman_->getBusClientID(), TaggedMessage(kPoisonMessage)); CHECK(send_status == tmb::MessageBus::SendStatus::kOK); worker_->join(); shiftboss_->join(); foreman_->join(); test_database_loader_data_exchanger_.shutdown(); test_database_loader_.reset(); data_exchanger_.shutdown(); storage_manager_.reset(); CHECK(MessageBus::SendStatus::kOK == QueryExecutionUtil::SendTMBMessage(&bus_, cli_id_, locator_client_id_, TaggedMessage(kPoisonMessage))); test_database_loader_data_exchanger_.join(); data_exchanger_.join(); block_locator_->join(); } void DistributedCommandExecutorTestRunner::runTestCase( const string &input, const std::set<string> &options, string *output) { // TODO(qzeng): Test multi-threaded query execution when we have a Sort operator. VLOG(4) << "Test SQL(s): " << input; if (options.find(kResetOption) != options.end()) { test_database_loader_->clear(); test_database_loader_->createTestRelation(false /* allow_vchar */); test_database_loader_->loadTestRelation(); } MemStream output_stream; sql_parser_.feedNextBuffer(new string(input)); while (true) { ParseResult result = sql_parser_.getNextStatement(); if (result.condition != ParseResult::kSuccess) { if (result.condition == ParseResult::kError) { *output = result.error_message; } break; } const ParseStatement &parse_statement = *result.parsed_statement; std::printf("%s\n", parse_statement.toString().c_str()); try { if (parse_statement.getStatementType() == ParseStatement::kCommand) { const ParseCommand &command = static_cast<const ParseCommand &>(parse_statement); const PtrVector<ParseString> &arguments = *(command.arguments()); const string &command_str = command.command()->value(); string command_response; if (command_str == C::kDescribeDatabaseCommand) { command_response = C::ExecuteDescribeDatabase(arguments, *test_database_loader_->catalog_database()); } else if (command_str == C::kDescribeTableCommand) { if (arguments.empty()) { command_response = C::ExecuteDescribeDatabase(arguments, *test_database_loader_->catalog_database()); } else { command_response = C::ExecuteDescribeTable(arguments, *test_database_loader_->catalog_database()); } } else { THROW_SQL_ERROR_AT(command.command()) << "Unsupported command"; } std::fprintf(output_stream.file(), "%s", command_response.c_str()); } else { optimizer::OptimizerContext optimizer_context; auto query_handle = std::make_unique<QueryHandle>(query_id_++, cli_id_); optimizer_.generateQueryHandle(parse_statement, test_database_loader_->catalog_database(), &optimizer_context, query_handle.get()); const CatalogRelation *query_result_relation = query_handle->getQueryResultRelation(); QueryExecutionUtil::ConstructAndSendAdmitRequestMessage( cli_id_, foreman_->getBusClientID(), query_handle.release(), &bus_); const tmb::AnnotatedMessage annotated_message = bus_.Receive(cli_id_, 0, true); DCHECK_EQ(kQueryExecutionSuccessMessage, annotated_message.tagged_message.message_type()); if (query_result_relation) { PrintToScreen::PrintRelation(*query_result_relation, test_database_loader_->storage_manager(), output_stream.file()); DropRelation::Drop(*query_result_relation, test_database_loader_->catalog_database(), test_database_loader_->storage_manager()); } } } catch (const SqlError &error) { *output = error.formatMessage(input); break; } } if (output->empty()) { *output = output_stream.str(); } } } // namespace quickstep
37.782427
116
0.716058
yuanchenl
a03043f317c61138818e4ae9d2c0ee66ca4487e6
28,037
cpp
C++
source/slang/slang-check-constraint.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
895
2017-06-10T13:38:39.000Z
2022-03-31T02:29:15.000Z
source/slang/slang-check-constraint.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
708
2017-06-15T16:03:12.000Z
2022-03-28T19:01:37.000Z
source/slang/slang-check-constraint.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
80
2017-06-12T15:36:58.000Z
2022-03-23T12:04:24.000Z
// slang-check-constraint.cpp #include "slang-check-impl.h" // This file provides the core services for creating // and solving constraint systems during semantic checking. // // We currently use constraint systems primarily to solve // for the implied values to use for generic parameters when a // generic declaration is being applied without explicit // generic arguments. // // Conceptually, our constraint-solving strategy starts by // trying to "unify" the actual argument types to a call // with the parameter types of the callee (which may mention // generic parameters). E.g., if we have a situation like: // // void doIt<T>(T a, vector<T,3> b); // // int x, y; // ... // doIt(x, y); // // then an we would try to unify the type of the argument // `x` (which is `int`) with the type of the parameter `a` // (which is `T`). Attempting to unify a concrete type // and a generic type parameter would (in the simplest case) // give rise to a constraint that, e.g., `T` must be `int`. // // In our example, unifying `y` and `b` creates a more complex // scenario, because we cannot ever unify `int` with `vector<T,3>`; // there is no possible value of `T` for which those two types // are equivalent. // // So instead of the simpler approach to unification (which // works well for languages without implicit type conversion), // our approach to unification recognizes that scalar types // can be promoted to vectors, and thus tries to unify the // type of `y` with the element type of `b`. // // When it comes time to actually solve the constraints, we // might have seemingly conflicting constraints: // // void another<U>(U a, U b); // // float x; int y; // another(x, y); // // In this case we'd have constraints that `U` must be `int`, // *and* that `U` must be `float`, which is clearly impossible // to satisfy. Instead, our constraints are treated as a kind // of "lower bound" on the type variable, and we combine // those lower bounds using the "join" operation (in the // sense of "meet" and "join" on lattices), which ideally // gives us a type for `U` that all the argument types can // convert to. namespace Slang { Type* SemanticsVisitor::TryJoinVectorAndScalarType( VectorExpressionType* vectorType, BasicExpressionType* scalarType) { // Join( vector<T,N>, S ) -> vetor<Join(T,S), N> // // That is, the join of a vector and a scalar type is // a vector type with a joined element type. auto joinElementType = TryJoinTypes( vectorType->elementType, scalarType); if(!joinElementType) return nullptr; return createVectorType( joinElementType, vectorType->elementCount); } Type* SemanticsVisitor::TryJoinTypeWithInterface( Type* type, DeclRef<InterfaceDecl> interfaceDeclRef) { // The most basic test here should be: does the type declare conformance to the trait. if(isDeclaredSubtype(type, interfaceDeclRef)) return type; // Just because `type` doesn't conform to the given `interfaceDeclRef`, that // doesn't necessarily indicate a failure. It is possible that we have a call // like `sqrt(2)` so that `type` is `int` and `interfaceDeclRef` is // `__BuiltinFloatingPointType`. The "obvious" answer is that we should infer // the type `float`, but it seems like the compiler would have to synthesize // that answer from thin air. // // A robsut/correct solution here might be to enumerate set of types types `S` // such that for each type `X` in `S`: // // * `type` is implicitly convertible to `X` // * `X` conforms to the interface named by `interfaceDeclRef` // // If the set `S` is non-empty then we would try to pick the "best" type from `S`. // The "best" type would be a type `Y` such that `Y` is implicitly convertible to // every other type in `S`. // // We are going to implement a much simpler strategy for now, where we only apply // the search process if `type` is a builtin scalar type, and then we only search // through types `X` that are also builtin scalar types. // Type* bestType = nullptr; if(auto basicType = dynamicCast<BasicExpressionType>(type)) { for(Int baseTypeFlavorIndex = 0; baseTypeFlavorIndex < Int(BaseType::CountOf); baseTypeFlavorIndex++) { // Don't consider `type`, since we already know it doesn't work. if(baseTypeFlavorIndex == Int(basicType->baseType)) continue; // Look up the type in our session. auto candidateType = type->getASTBuilder()->getBuiltinType(BaseType(baseTypeFlavorIndex)); if(!candidateType) continue; // We only want to consider types that implement the target interface. if(!isDeclaredSubtype(candidateType, interfaceDeclRef)) continue; // We only want to consider types where we can implicitly convert from `type` if(!canConvertImplicitly(candidateType, type)) continue; // At this point, we have a candidate type that is usable. // // If this is our first viable candidate, then it is our best one: // if(!bestType) { bestType = candidateType; } else { // Otherwise, we want to pick the "better" type between `candidateType` // and `bestType`. // // We are going to be a bit loose here, and not worry about the // case where conversion is allowed in both directions. // // TODO: make this completely robust. // if(canConvertImplicitly(bestType, candidateType)) { // Our candidate can convert to the current "best" type, so // it is logically a more specific type that satisfies our // constraints, therefore we should keep it. // bestType = candidateType; } } } if(bestType) return bestType; } // For all other cases, we will just bail out for now. // // TODO: In the future we should build some kind of side data structure // to accelerate either one or both of these queries: // // * Given a type `T`, what types `U` can it convert to implicitly? // // * Given an interface `I`, what types `U` conform to it? // // The intersection of the sets returned by these two queries is // the set of candidates we would like to consider here. return nullptr; } Type* SemanticsVisitor::TryJoinTypes( Type* left, Type* right) { // Easy case: they are the same type! if (left->equals(right)) return left; // We can join two basic types by picking the "better" of the two if (auto leftBasic = as<BasicExpressionType>(left)) { if (auto rightBasic = as<BasicExpressionType>(right)) { auto leftFlavor = leftBasic->baseType; auto rightFlavor = rightBasic->baseType; // TODO(tfoley): Need a special-case rule here that if // either operand is of type `half`, then we promote // to at least `float` // Return the one that had higher rank... if (leftFlavor > rightFlavor) return left; else { SLANG_ASSERT(rightFlavor > leftFlavor); // equality was handles at the top of this function return right; } } // We can also join a vector and a scalar if(auto rightVector = as<VectorExpressionType>(right)) { return TryJoinVectorAndScalarType(rightVector, leftBasic); } } // We can join two vector types by joining their element types // (and also their sizes...) if( auto leftVector = as<VectorExpressionType>(left)) { if(auto rightVector = as<VectorExpressionType>(right)) { // Check if the vector sizes match if(!leftVector->elementCount->equalsVal(rightVector->elementCount)) return nullptr; // Try to join the element types auto joinElementType = TryJoinTypes( leftVector->elementType, rightVector->elementType); if(!joinElementType) return nullptr; return createVectorType( joinElementType, leftVector->elementCount); } // We can also join a vector and a scalar if(auto rightBasic = as<BasicExpressionType>(right)) { return TryJoinVectorAndScalarType(leftVector, rightBasic); } } // HACK: trying to work trait types in here... if(auto leftDeclRefType = as<DeclRefType>(left)) { if( auto leftInterfaceRef = leftDeclRefType->declRef.as<InterfaceDecl>() ) { // return TryJoinTypeWithInterface(right, leftInterfaceRef); } } if(auto rightDeclRefType = as<DeclRefType>(right)) { if( auto rightInterfaceRef = rightDeclRefType->declRef.as<InterfaceDecl>() ) { // return TryJoinTypeWithInterface(left, rightInterfaceRef); } } // TODO: all the cases for vectors apply to matrices too! // Default case is that we just fail. return nullptr; } SubstitutionSet SemanticsVisitor::TrySolveConstraintSystem( ConstraintSystem* system, DeclRef<GenericDecl> genericDeclRef) { // For now the "solver" is going to be ridiculously simplistic. // The generic itself will have some constraints, and for now we add these // to the system of constrains we will use for solving for the type variables. // // TODO: we need to decide whether constraints are used like this to influence // how we solve for type/value variables, or whether constraints in the parameter // list just work as a validation step *after* we've solved for the types. // // That is, should we allow `<T : Int>` to be written, and cause us to "infer" // that `T` should be the type `Int`? That seems a little silly. // // Eventually, though, we may want to support type identity constraints, especially // on associated types, like `<C where C : IContainer && C.IndexType == Int>` // These seem more reasonable to have influence constraint solving, since it could // conceivably let us specialize a `X<T> : IContainer` to `X<Int>` if we find // that `X<T>.IndexType == T`. for( auto constraintDeclRef : getMembersOfType<GenericTypeConstraintDecl>(genericDeclRef) ) { if(!TryUnifyTypes(*system, getSub(m_astBuilder, constraintDeclRef), getSup(m_astBuilder, constraintDeclRef))) return SubstitutionSet(); } SubstitutionSet resultSubst = genericDeclRef.substitutions; // We will loop over the generic parameters, and for // each we will try to find a way to satisfy all // the constraints for that parameter List<Val*> args; for (auto m : getMembers(genericDeclRef)) { if (auto typeParam = m.as<GenericTypeParamDecl>()) { Type* type = nullptr; for (auto& c : system->constraints) { if (c.decl != typeParam.getDecl()) continue; auto cType = as<Type>(c.val); SLANG_RELEASE_ASSERT(cType); if (!type) { type = cType; } else { auto joinType = TryJoinTypes(type, cType); if (!joinType) { // failure! return SubstitutionSet(); } type = joinType; } c.satisfied = true; } if (!type) { // failure! return SubstitutionSet(); } args.add(type); } else if (auto valParam = m.as<GenericValueParamDecl>()) { // TODO(tfoley): maybe support more than integers some day? // TODO(tfoley): figure out how this needs to interact with // compile-time integers that aren't just constants... IntVal* val = nullptr; for (auto& c : system->constraints) { if (c.decl != valParam.getDecl()) continue; auto cVal = as<IntVal>(c.val); SLANG_RELEASE_ASSERT(cVal); if (!val) { val = cVal; } else { if(!val->equalsVal(cVal)) { // failure! return SubstitutionSet(); } } c.satisfied = true; } if (!val) { // failure! return SubstitutionSet(); } args.add(val); } else { // ignore anything that isn't a generic parameter } } // After we've solved for the explicit arguments, we need to // make a second pass and consider the implicit arguments, // based on what we've already determined to be the values // for the explicit arguments. // Before we begin, we are going to go ahead and create the // "solved" substitution that we will return if everything works. // This is because we are going to use this substitution, // partially filled in with the results we know so far, // in order to specialize any constraints on the generic. // // E.g., if the generic parameters were `<T : ISidekick>`, and // we've already decided that `T` is `Robin`, then we want to // search for a conformance `Robin : ISidekick`, which involved // apply the substitutions we already know... GenericSubstitution* solvedSubst = m_astBuilder->create<GenericSubstitution>(); solvedSubst->genericDecl = genericDeclRef.getDecl(); solvedSubst->outer = genericDeclRef.substitutions.substitutions; solvedSubst->args = args; resultSubst.substitutions = solvedSubst; for( auto constraintDecl : genericDeclRef.getDecl()->getMembersOfType<GenericTypeConstraintDecl>() ) { DeclRef<GenericTypeConstraintDecl> constraintDeclRef( constraintDecl, solvedSubst); // Extract the (substituted) sub- and super-type from the constraint. auto sub = getSub(m_astBuilder, constraintDeclRef); auto sup = getSup(m_astBuilder, constraintDeclRef); // Search for a witness that shows the constraint is satisfied. auto subTypeWitness = tryGetSubtypeWitness(sub, sup); if(subTypeWitness) { // We found a witness, so it will become an (implicit) argument. solvedSubst->args.add(subTypeWitness); } else { // No witness was found, so the inference will now fail. // // TODO: Ideally we should print an error message in // this case, to let the user know why things failed. return SubstitutionSet(); } // TODO: We may need to mark some constrains in our constraint // system as being solved now, as a result of the witness we found. } // Make sure we haven't constructed any spurious constraints // that we aren't able to satisfy: for (auto c : system->constraints) { if (!c.satisfied) { return SubstitutionSet(); } } return resultSubst; } bool SemanticsVisitor::TryUnifyVals( ConstraintSystem& constraints, Val* fst, Val* snd) { // if both values are types, then unify types if (auto fstType = as<Type>(fst)) { if (auto sndType = as<Type>(snd)) { return TryUnifyTypes(constraints, fstType, sndType); } } // if both values are constant integers, then compare them if (auto fstIntVal = as<ConstantIntVal>(fst)) { if (auto sndIntVal = as<ConstantIntVal>(snd)) { return fstIntVal->value == sndIntVal->value; } } // Check if both are integer values in general if (auto fstInt = as<IntVal>(fst)) { if (auto sndInt = as<IntVal>(snd)) { auto fstParam = as<GenericParamIntVal>(fstInt); auto sndParam = as<GenericParamIntVal>(sndInt); bool okay = false; if (fstParam) { if(TryUnifyIntParam(constraints, fstParam->declRef, sndInt)) okay = true; } if (sndParam) { if(TryUnifyIntParam(constraints, sndParam->declRef, fstInt)) okay = true; } return okay; } } if (auto fstWit = as<DeclaredSubtypeWitness>(fst)) { if (auto sndWit = as<DeclaredSubtypeWitness>(snd)) { auto constraintDecl1 = fstWit->declRef.as<TypeConstraintDecl>(); auto constraintDecl2 = sndWit->declRef.as<TypeConstraintDecl>(); SLANG_ASSERT(constraintDecl1); SLANG_ASSERT(constraintDecl2); return TryUnifyTypes(constraints, constraintDecl1.getDecl()->getSup().type, constraintDecl2.getDecl()->getSup().type); } } SLANG_UNIMPLEMENTED_X("value unification case"); // default: fail //return false; } bool SemanticsVisitor::tryUnifySubstitutions( ConstraintSystem& constraints, Substitutions* fst, Substitutions* snd) { // They must both be NULL or non-NULL if (!fst || !snd) return !fst && !snd; if(auto fstGeneric = as<GenericSubstitution>(fst)) { if(auto sndGeneric = as<GenericSubstitution>(snd)) { return tryUnifyGenericSubstitutions( constraints, fstGeneric, sndGeneric); } } // TODO: need to handle other cases here return false; } bool SemanticsVisitor::tryUnifyGenericSubstitutions( ConstraintSystem& constraints, GenericSubstitution* fst, GenericSubstitution* snd) { SLANG_ASSERT(fst); SLANG_ASSERT(snd); auto fstGen = fst; auto sndGen = snd; // They must be specializing the same generic if (fstGen->genericDecl != sndGen->genericDecl) return false; // Their arguments must unify SLANG_RELEASE_ASSERT(fstGen->args.getCount() == sndGen->args.getCount()); Index argCount = fstGen->args.getCount(); bool okay = true; for (Index aa = 0; aa < argCount; ++aa) { if (!TryUnifyVals(constraints, fstGen->args[aa], sndGen->args[aa])) { okay = false; } } // Their "base" specializations must unify if (!tryUnifySubstitutions(constraints, fstGen->outer, sndGen->outer)) { okay = false; } return okay; } bool SemanticsVisitor::TryUnifyTypeParam( ConstraintSystem& constraints, GenericTypeParamDecl* typeParamDecl, Type* type) { // We want to constrain the given type parameter // to equal the given type. Constraint constraint; constraint.decl = typeParamDecl; constraint.val = type; constraints.constraints.add(constraint); return true; } bool SemanticsVisitor::TryUnifyIntParam( ConstraintSystem& constraints, GenericValueParamDecl* paramDecl, IntVal* val) { // We only want to accumulate constraints on // the parameters of the declarations being // specialized (don't accidentially constrain // parameters of a generic function based on // calls in its body). if(paramDecl->parentDecl != constraints.genericDecl) return false; // We want to constrain the given parameter to equal the given value. Constraint constraint; constraint.decl = paramDecl; constraint.val = val; constraints.constraints.add(constraint); return true; } bool SemanticsVisitor::TryUnifyIntParam( ConstraintSystem& constraints, DeclRef<VarDeclBase> const& varRef, IntVal* val) { if(auto genericValueParamRef = varRef.as<GenericValueParamDecl>()) { return TryUnifyIntParam(constraints, genericValueParamRef.getDecl(), val); } else { return false; } } bool SemanticsVisitor::TryUnifyTypesByStructuralMatch( ConstraintSystem& constraints, Type* fst, Type* snd) { if (auto fstDeclRefType = as<DeclRefType>(fst)) { auto fstDeclRef = fstDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(fstDeclRef.getDecl())) return TryUnifyTypeParam(constraints, typeParamDecl, snd); if (auto sndDeclRefType = as<DeclRefType>(snd)) { auto sndDeclRef = sndDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(sndDeclRef.getDecl())) return TryUnifyTypeParam(constraints, typeParamDecl, fst); // can't be unified if they refer to different declarations. if (fstDeclRef.getDecl() != sndDeclRef.getDecl()) return false; // next we need to unify the substitutions applied // to each declaration reference. if (!tryUnifySubstitutions( constraints, fstDeclRef.substitutions.substitutions, sndDeclRef.substitutions.substitutions)) { return false; } return true; } } return false; } bool SemanticsVisitor::TryUnifyConjunctionType( ConstraintSystem& constraints, AndType* fst, Type* snd) { // Unifying a type `T` with `A & B` amounts to unifying // `T` with `A` and also `T` with `B`. // // If either unification is impossible, then the full // case is also impossible. // return TryUnifyTypes(constraints, fst->left, snd) && TryUnifyTypes(constraints, fst->right, snd); } bool SemanticsVisitor::TryUnifyTypes( ConstraintSystem& constraints, Type* fst, Type* snd) { if (fst->equals(snd)) return true; // An error type can unify with anything, just so we avoid cascading errors. if (auto fstErrorType = as<ErrorType>(fst)) return true; if (auto sndErrorType = as<ErrorType>(snd)) return true; // If one or the other of the types is a conjunction `X & Y`, // then we want to recurse on both `X` and `Y`. // // Note that we check this case *before* we check if one of // the types is a generic parameter below, so that we should // never end up trying to match up a type parameter with // a conjunction directly, and will instead find all of the // "leaf" types we need to constrain it to. // if( auto fstAndType = as<AndType>(fst) ) { return TryUnifyConjunctionType(constraints, fstAndType, snd); } if( auto sndAndType = as<AndType>(snd) ) { return TryUnifyConjunctionType(constraints, sndAndType, fst); } // A generic parameter type can unify with anything. // TODO: there actually needs to be some kind of "occurs check" sort // of thing here... if (auto fstDeclRefType = as<DeclRefType>(fst)) { auto fstDeclRef = fstDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(fstDeclRef.getDecl())) { if(typeParamDecl->parentDecl == constraints.genericDecl ) return TryUnifyTypeParam(constraints, typeParamDecl, snd); } } if (auto sndDeclRefType = as<DeclRefType>(snd)) { auto sndDeclRef = sndDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(sndDeclRef.getDecl())) { if(typeParamDecl->parentDecl == constraints.genericDecl ) return TryUnifyTypeParam(constraints, typeParamDecl, fst); } } // If we can unify the types structurally, then we are golden if(TryUnifyTypesByStructuralMatch(constraints, fst, snd)) return true; // Now we need to consider cases where coercion might // need to be applied. For now we can try to do this // in a completely ad hoc fashion, but eventually we'd // want to do it more formally. if(auto fstVectorType = as<VectorExpressionType>(fst)) { if(auto sndScalarType = as<BasicExpressionType>(snd)) { return TryUnifyTypes( constraints, fstVectorType->elementType, sndScalarType); } } if(auto fstScalarType = as<BasicExpressionType>(fst)) { if(auto sndVectorType = as<VectorExpressionType>(snd)) { return TryUnifyTypes( constraints, fstScalarType, sndVectorType->elementType); } } // TODO: the same thing for vectors... return false; } }
36.223514
121
0.545458
JKot-Coder
a0314f02d8d423dc32c2861e5a3ad1225429589b
4,366
cc
C++
src/decoderbin/nbest-to-ctm.cc
zh794390558/eesen
890c1394abc4beba06baf79eb8203a5c65d30eb8
[ "Apache-2.0" ]
798
2015-08-19T21:15:28.000Z
2022-03-31T06:11:02.000Z
src/decoderbin/nbest-to-ctm.cc
xiachen1993/eesen
4d4920ca6a2f7166cf603d81c0fd40c5c26e65a0
[ "Apache-2.0" ]
173
2015-10-19T16:24:48.000Z
2021-08-23T11:39:54.000Z
src/decoderbin/nbest-to-ctm.cc
xiachen1993/eesen
4d4920ca6a2f7166cf603d81c0fd40c5c26e65a0
[ "Apache-2.0" ]
293
2015-09-09T19:31:42.000Z
2022-03-31T06:11:04.000Z
// decoderbin/nbest-to-ctm.cc // Copyright 2012 Johns Hopkins University (Author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "lat/lattice-functions.h" int main(int argc, char *argv[]) { try { using namespace eesen; typedef eesen::int32 int32; const char *usage = "Takes as input lattices which must be linear (single path),\n" "and must be in CompactLattice form where the transition-ids on the arcs\n" "have been aligned with the word boundaries... typically the input will\n" "be a lattice that has been piped through lattice-1best and then\n" "lattice-word-align. It outputs ctm format (with integers in place of words),\n" "assuming the frame length is 0.01 seconds by default (change this with the\n" "--frame-length option). Note: the output is in the form\n" "utterance-id 1 <begin-time> <end-time> <word-id>\n" "and you can post-process this to account for segmentation issues and to \n" "convert ints to words; note, the times are relative to start of the utterance.\n" "\n" "Usage: nbest-to-ctm [options] <aligned-linear-lattice-rspecifier> <ctm-wxfilename>\n" "e.g.: lattice-1best --acoustic-weight=0.08333 ark:1.lats | \\\n" " lattice-align-words data/lang/phones/word_boundary.int exp/dir/final.mdl ark:- ark:- | \\\n" " nbest-to-ctm ark:- 1.ctm\n"; ParseOptions po(usage); BaseFloat frame_shift = 0.01; int32 precision = 2; po.Register("frame-shift", &frame_shift, "Time in seconds between frames.\n"); po.Register("precision", &precision, "Number of decimal places for start duration times\n"); po.Read(argc, argv); if (po.NumArgs() != 2) { po.PrintUsage(); exit(1); } std::string lats_rspecifier = po.GetArg(1), ctm_wxfilename = po.GetArg(2); SequentialCompactLatticeReader clat_reader(lats_rspecifier); int32 n_done = 0, n_err = 0; Output ko(ctm_wxfilename, false); // false == non-binary write mode. ko.Stream() << std::fixed; // Set to "fixed" floating point model, where precision() specifies // the #digits after the decimal point. ko.Stream().precision(precision); for (; !clat_reader.Done(); clat_reader.Next()) { std::string key = clat_reader.Key(); CompactLattice clat = clat_reader.Value(); std::vector<int32> words, times, lengths; if (!CompactLatticeToWordAlignment(clat, &words, &times, &lengths)) { n_err++; KALDI_WARN << "Format conversion failed for key " << key; } else { KALDI_ASSERT(words.size() == times.size() && words.size() == lengths.size()); for (size_t i = 0; i < words.size(); i++) { if (words[i] == 0) // Don't output anything for <eps> links, which continue; // correspond to silence.... ko.Stream() << key << " 1 " << (frame_shift * times[i]) << ' ' << (frame_shift * lengths[i]) << ' ' << words[i] <<std::endl; } n_done++; } } ko.Close(); // Note: we don't normally call Close() on these things, // we just let them go out of scope and it happens automatically. // We do it this time in order to avoid wrongly printing out a success message // if the stream was going to fail to close KALDI_LOG << "Converted " << n_done << " linear lattices to ctm format; " << n_err << " had errors."; return (n_done != 0 ? 0 : 1); } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
40.425926
107
0.631241
zh794390558
a0325cfe4eb57f4de08e777c7de20c764a033b86
6,676
cpp
C++
src/generated/lsd_savepicture.cpp
akien-mga/liblcf
37c16d8dc0a1656f9a17d0374d6dfe14e2ded262
[ "MIT" ]
null
null
null
src/generated/lsd_savepicture.cpp
akien-mga/liblcf
37c16d8dc0a1656f9a17d0374d6dfe14e2ded262
[ "MIT" ]
null
null
null
src/generated/lsd_savepicture.cpp
akien-mga/liblcf
37c16d8dc0a1656f9a17d0374d6dfe14e2ded262
[ "MIT" ]
null
null
null
/* !!!! GENERATED FILE - DO NOT EDIT !!!! * -------------------------------------- * * This file is part of liblcf. Copyright (c) 2019 liblcf authors. * https://github.com/EasyRPG/liblcf - https://easyrpg.org * * liblcf is Free/Libre Open Source Software, released under the MIT License. * For the full copyright and license information, please view the COPYING * file that was distributed with this source code. */ // Headers #include "lsd_reader.h" #include "lsd_chunks.h" #include "reader_struct_impl.h" // Read SavePicture. template <> char const* const Struct<RPG::SavePicture>::name = "SavePicture"; template <> Field<RPG::SavePicture> const* Struct<RPG::SavePicture>::fields[] = { new TypedField<RPG::SavePicture, std::string>( &RPG::SavePicture::name, LSD_Reader::ChunkSavePicture::name, "name", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::start_x, LSD_Reader::ChunkSavePicture::start_x, "start_x", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::start_y, LSD_Reader::ChunkSavePicture::start_y, "start_y", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_x, LSD_Reader::ChunkSavePicture::current_x, "current_x", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_y, LSD_Reader::ChunkSavePicture::current_y, "current_y", 0, 0 ), new TypedField<RPG::SavePicture, bool>( &RPG::SavePicture::fixed_to_map, LSD_Reader::ChunkSavePicture::fixed_to_map, "fixed_to_map", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_magnify, LSD_Reader::ChunkSavePicture::current_magnify, "current_magnify", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_top_trans, LSD_Reader::ChunkSavePicture::current_top_trans, "current_top_trans", 0, 0 ), new TypedField<RPG::SavePicture, bool>( &RPG::SavePicture::transparency, LSD_Reader::ChunkSavePicture::transparency, "transparency", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_red, LSD_Reader::ChunkSavePicture::current_red, "current_red", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_green, LSD_Reader::ChunkSavePicture::current_green, "current_green", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_blue, LSD_Reader::ChunkSavePicture::current_blue, "current_blue", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_sat, LSD_Reader::ChunkSavePicture::current_sat, "current_sat", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::effect_mode, LSD_Reader::ChunkSavePicture::effect_mode, "effect_mode", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_effect, LSD_Reader::ChunkSavePicture::current_effect, "current_effect", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_bot_trans, LSD_Reader::ChunkSavePicture::current_bot_trans, "current_bot_trans", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::spritesheet_cols, LSD_Reader::ChunkSavePicture::spritesheet_cols, "spritesheet_cols", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::spritesheet_rows, LSD_Reader::ChunkSavePicture::spritesheet_rows, "spritesheet_rows", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::spritesheet_frame, LSD_Reader::ChunkSavePicture::spritesheet_frame, "spritesheet_frame", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::spritesheet_speed, LSD_Reader::ChunkSavePicture::spritesheet_speed, "spritesheet_speed", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::frames, LSD_Reader::ChunkSavePicture::frames, "frames", 0, 0 ), new TypedField<RPG::SavePicture, bool>( &RPG::SavePicture::spritesheet_play_once, LSD_Reader::ChunkSavePicture::spritesheet_play_once, "spritesheet_play_once", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::map_layer, LSD_Reader::ChunkSavePicture::map_layer, "map_layer", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::battle_layer, LSD_Reader::ChunkSavePicture::battle_layer, "battle_layer", 0, 0 ), new TypedField<RPG::SavePicture, RPG::SavePicture::Flags>( &RPG::SavePicture::flags, LSD_Reader::ChunkSavePicture::flags, "flags", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::finish_x, LSD_Reader::ChunkSavePicture::finish_x, "finish_x", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::finish_y, LSD_Reader::ChunkSavePicture::finish_y, "finish_y", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_magnify, LSD_Reader::ChunkSavePicture::finish_magnify, "finish_magnify", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_top_trans, LSD_Reader::ChunkSavePicture::finish_top_trans, "finish_top_trans", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_bot_trans, LSD_Reader::ChunkSavePicture::finish_bot_trans, "finish_bot_trans", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_red, LSD_Reader::ChunkSavePicture::finish_red, "finish_red", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_green, LSD_Reader::ChunkSavePicture::finish_green, "finish_green", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_blue, LSD_Reader::ChunkSavePicture::finish_blue, "finish_blue", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_sat, LSD_Reader::ChunkSavePicture::finish_sat, "finish_sat", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::finish_effect, LSD_Reader::ChunkSavePicture::finish_effect, "finish_effect", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::time_left, LSD_Reader::ChunkSavePicture::time_left, "time_left", 0, 0 ), new TypedField<RPG::SavePicture, double>( &RPG::SavePicture::current_rotation, LSD_Reader::ChunkSavePicture::current_rotation, "current_rotation", 0, 0 ), new TypedField<RPG::SavePicture, int32_t>( &RPG::SavePicture::current_waver, LSD_Reader::ChunkSavePicture::current_waver, "current_waver", 0, 0 ), NULL }; template class Struct<RPG::SavePicture>;
22.707483
77
0.712403
akien-mga
a0357e9cd0f19dcca39eb366a2724bd340c371bb
1,611
cpp
C++
src/Object2D.cpp
Ryozuki/GForce
a36ab77587773057e1b6fc84cb6efe9987dc4473
[ "MIT" ]
null
null
null
src/Object2D.cpp
Ryozuki/GForce
a36ab77587773057e1b6fc84cb6efe9987dc4473
[ "MIT" ]
null
null
null
src/Object2D.cpp
Ryozuki/GForce
a36ab77587773057e1b6fc84cb6efe9987dc4473
[ "MIT" ]
null
null
null
/* * (c) Ryozuki See LICENSE.txt in the root of the distribution for more information. * If you are missing that file, acquire a complete release at https://github.com/Ryozuki/GForce */ #include <GForce/Object2D.hpp> #include <GForce/Constants.hpp> namespace gf { Object2D::Object2D(double mass) { setMass(mass); } void Object2D::setMass(double mass) { m_Mass = mass; } void Object2D::addForce(Vector2D force) { m_Force += force; } void Object2D::setForce(Vector2D force) { m_Force = force; } void Object2D::tick(double deltaTime) { if(deltaTime == 0) return; m_Velocity += getAcceleration() * deltaTime; m_Position += m_Velocity * deltaTime; } void Object2D::setPosition(Vector2D new_pos) { m_Position = new_pos; } void Object2D::setVelocity(Vector2D new_vel) { m_Velocity = new_vel; } void Object2D::addVelocity(Vector2D vel) { m_Velocity += vel; } Vector2D Object2D::getAcceleration() const { return getForce() / getMass(); } void Object2D::resetForce() { m_Force = Vector2D(); } void Object2D::resetVelocity() { m_Velocity = Vector2D(); } void Object2D::stopMovement() { resetForce(); resetVelocity(); } void Object2D::applyGravity(Object2D &a, bool update_a) { double force = GRAVITATIONAL_CONSTANT * (getMass() * a.getMass()) / distanceTo(a); Vector2D forceV = (a.getPosition() - getPosition()).direction(); forceV *= force; addForce(forceV); if(update_a) a.addForce(-forceV); } double Object2D::distanceTo(const Object2D &other) const { return getPosition().distanceTo(other.getPosition()); } }
17.703297
96
0.688392
Ryozuki
a03b320fe75a6e87efa21af0902a15eebcda16f5
598
cpp
C++
C++/01_Backtracking/MEDIUM_PERMUTATIONS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/01_Backtracking/MEDIUM_PERMUTATIONS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/01_Backtracking/MEDIUM_PERMUTATIONS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > result; permuteRecursive(result, 0, num); return result; } // permute num[begin..end] // invariant: num[0..begin-1] have been fixed/permuted void permuteRecursive(vector<vector<int> > &result, int begin, vector<int> &num) { if (begin >= num.size()) { // one permutation instance result.push_back(num); return; } for (int i = begin; i < num.size(); i++) { swap(num[begin], num[i]); permuteRecursive(num, begin + 1, result); // reset swap(num[begin], num[i]); } }
22.148148
81
0.603679
animeshramesh
a041ed9f8cac4a98baa2a5af904a417a3bbca844
3,729
hpp
C++
zug/state_traits.hpp
CJBussey/zug
4c9aff02c5f870f2ba518ba7f93ceb6a00e5fda8
[ "BSL-1.0" ]
null
null
null
zug/state_traits.hpp
CJBussey/zug
4c9aff02c5f870f2ba518ba7f93ceb6a00e5fda8
[ "BSL-1.0" ]
null
null
null
zug/state_traits.hpp
CJBussey/zug
4c9aff02c5f870f2ba518ba7f93ceb6a00e5fda8
[ "BSL-1.0" ]
null
null
null
// // zug: transducers for C++ // Copyright (C) 2019 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #pragma once #include <type_traits> #include <utility> namespace zug { /*! * Interface for a type specializing the `State` concept. * * A `State` is the first parameter of a reducing function, also known as the * accumulator. Every type is a model of `State`, with the following * default implementation. However, one might want to specialize the * state it for a particular accumulator type, such that transducers * can operate with it. A transducer should not make assumptions * about the state it receives, instead, it can only wrap it using * `wrap_state` to attach additional data. * * For an example of a stateful reducing function, see `take`. * * @see wrap_state * @see take */ template <typename StateT> struct state_traits { /*! * Returns whether the value is idempotent, and thus, the reduction * can finish. */ template <typename T> static bool is_reduced(T&&) { return false; } /*! * Returns the associated from the current state. If the state * contains no associated data, the `default_data` will be returned. */ template <typename T, typename D> static decltype(auto) data(T&&, D&& d) { return std::forward<D>(d)(); } /*! * Unwraps all the layers of state wrappers returning the deepmost */ template <typename T> static T&& complete(T&& state) { return std::forward<T>(state); } /*! * Unwraps this layers of state wrappers, returning the nested * state for the next reducing function. */ template <typename T> static T&& unwrap(T&& state) { return std::forward<T>(state); } /*! * Unwraps all layers of state wrappers, returning the most nested * state for the innermost reducing function. */ template <typename T> static T&& unwrap_all(T&& state) { return std::forward<T>(state); } /*! * Copies all layers of state wrappers but replaces the innermost * state with `substate`. */ template <typename T, typename U> static U&& rewrap(T&&, U&& x) { return std::forward<U>(x); } }; template <typename T> using state_traits_t = state_traits<std::decay_t<T>>; /*! * Convenience function for calling `state_traits::complete` */ template <typename T> decltype(auto) state_complete(T&& s) { return state_traits_t<T>::complete(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::is_reduced` */ template <typename T> bool state_is_reduced(T&& s) { return state_traits_t<T>::is_reduced(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::data` */ template <typename T, typename D> decltype(auto) state_data(T&& s, D&& d) { return state_traits_t<T>::data(std::forward<T>(s), std::forward<D>(d)); } /*! * Convenience function for calling `state_traits::unwrap` */ template <typename T> decltype(auto) state_unwrap(T&& s) { return state_traits_t<T>::unwrap(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::unwrap_all` */ template <typename T> decltype(auto) state_unwrap_all(T&& s) { return state_traits_t<T>::unwrap_all(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::unwrap_all` */ template <typename T, typename U> decltype(auto) state_rewrap(T&& s, U&& x) { return state_traits_t<T>::rewrap(std::forward<T>(s), std::forward<U>(x)); } } // namespace zug
24.372549
78
0.659426
CJBussey
a044127b3ec32060224277df4d8acda13c9b1c1a
58,225
cpp
C++
engine/audio/private/snd_op_sys/sos_op_math.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
cstrike15_src/engine/audio/private/snd_op_sys/sos_op_math.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
cstrike15_src/engine/audio/private/snd_op_sys/sos_op_math.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//============ Copyright (c) Valve Corporation, All rights reserved. ============ // // //=============================================================================== #include "audio_pch.h" #include "tier2/interval.h" #include "math.h" #include "sos_op.h" #include "sos_op_math.h" #include "snd_dma.h" #include "../../cl_splitscreen.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // ------------------------------------------------------------------------ // GOOD OLD MACROS #define SOS_DtoR 0.01745329251994329500 #define RtoD 57.29577951308232300000 #define SOS_DEG2RAD(d) ((float)(d) * DtoR) #define SOS_RAD2DEG(r) ((float)(r) * RtoD) #define SOS_RADIANS(deg) ((deg)*DtoR) #define SOS_DEGREES(rad) ((rad)*RtoD) //----------------------------------------------------------------------------- #define SOS_MIN(a,b) (((a) < (b)) ? (a) : (b)) #define SOS_MAX(a,b) (((a) > (b)) ? (a) : (b)) #define SOS_ABS(a) (((a) < 0) ? -(a) : (a)) #define SOS_FLOOR(a) ((a) > 0 ? (int)(a) : -(int)(-a)) #define SOS_CEILING(a) ((a)==(int)(a) ? (a) : (a)>0 ? 1+(int)(a) : -(1+(int)(-a))) #define SOS_ROUND(a) ((a)>0 ? (int)(a+0.5) : -(int)(0.5-a)) #define SOS_SGN(a) (((a)<0) ? -1 : 1) #define SOS_SQR(a) ((a)*(a)) #define SOS_MOD(a,b) (a)%(b) // ---------------------------------------------------------------------------- #define SOS_RAMP(value,a,b) (((a) - (float)(value)) / ((a) - (b))) #define SOS_LERP(factor,a,b) ((a) + (((b) - (a)) * (factor))) #define SOS_RESCALE(X,Xa,Xb,Ya,Yb) SOS_LERP(SOS_RAMP(X,Xa,Xb),Ya,Yb) #define SOS_INRANGE(x,a,b) (((x) >= SOS_MIN(a,b)) && ((x) <= SOS_MAX(a,b))) #define SOS_CLAMP(x,a,b) ((x)<SOS_MIN(a,b)?SOS_MIN(a,b):(x)>MAX(a,b)?SOS_MAX(a,b):(x)) #define SOS_CRAMP(value,a,b) SOS_CLAMP(SOS_RAMP(value,a,b),0,1) #define SOS_CLERP(factor,a,b) SOS_CLAMP(SOS_LERP(factor,a,b),a,b) #define SOS_CRESCALE(X,Xa,Xb,Ya,Yb) SOS_CLAMP(SOS_RESCALE(X,Xa,Xb,Ya,Yb),Ya,Yb) #define SOS_SIND(deg) sin(SOS_RADIANS(deg)) #define SOS_COSD(deg) cos(SOS_RADIANS(deg)) #define SOS_TAND(deg) tan(SOS_RADIANS(deg)) #define SOS_ATAN2(a,b) atan2(a,b) #define SOS_UNITSINUSOID(x) SOS_LERP(SOS_SIND(SOS_CLERP(x,-90,90)),0.5,1.0) #define SOS_ELERP(factor,a,b) SOS_LERP(SOS_UNITSINUSOID(factor),a,b) //----------------------------------------------------------- extern Color OpColor; extern Color ConnectColor; extern Color ResultColor; SOFunc1Type_t S_GetFunc1Type( const char *pValueString ) { if ( !V_strcasecmp( pValueString, "none" ) ) { return SO_FUNC1_NONE; } else if ( !V_strcasecmp( pValueString, "sin" ) ) { return SO_FUNC1_SIN; } else if ( !V_strcasecmp( pValueString, "asin" ) ) { return SO_FUNC1_ASIN; } else if ( !V_strcasecmp( pValueString, "cos" ) ) { return SO_FUNC1_COS; } else if ( !V_strcasecmp( pValueString, "acos" ) ) { return SO_FUNC1_ACOS; } else if ( !V_strcasecmp( pValueString, "tan" ) ) { return SO_FUNC1_TAN; } else if ( !V_strcasecmp( pValueString, "atan" ) ) { return SO_FUNC1_ATAN; } else if ( !V_strcasecmp( pValueString, "sinh" ) ) { return SO_FUNC1_SINH; } else if ( !V_strcasecmp( pValueString, "asinh" ) ) { return SO_FUNC1_ASINH; } else if ( !V_strcasecmp( pValueString, "cosh" ) ) { return SO_FUNC1_COSH; } else if ( !V_strcasecmp( pValueString, "acosh" ) ) { return SO_FUNC1_ACOSH; } else if ( !V_strcasecmp( pValueString, "tanh" ) ) { return SO_FUNC1_TANH; } else if ( !V_strcasecmp( pValueString, "atanh" ) ) { return SO_FUNC1_ATANH; } else if ( !V_strcasecmp( pValueString, "exp" ) ) { return SO_FUNC1_EXP; } else if ( !V_strcasecmp( pValueString, "expm1" ) ) { return SO_FUNC1_EXPM1; } else if ( !V_strcasecmp( pValueString, "exp2" ) ) { return SO_FUNC1_EXP2; } else if ( !V_strcasecmp( pValueString, "log" ) ) { return SO_FUNC1_LOG; } else if ( !V_strcasecmp( pValueString, "log2" ) ) { return SO_FUNC1_LOG2; } else if ( !V_strcasecmp( pValueString, "log1p" ) ) { return SO_FUNC1_LOG1P; } else if ( !V_strcasecmp( pValueString, "log10" ) ) { return SO_FUNC1_LOG10; } else if ( !V_strcasecmp( pValueString, "logb" ) ) { return SO_FUNC1_LOGB; } else if ( !V_strcasecmp( pValueString, "fabs" ) ) { return SO_FUNC1_FABS; } else if ( !V_strcasecmp( pValueString, "sqrt" ) ) { return SO_FUNC1_SQRT; } else if ( !V_strcasecmp( pValueString, "erf" ) ) { return SO_FUNC1_ERF; } else if ( !V_strcasecmp( pValueString, "erfc" ) ) { return SO_FUNC1_ERFC; } else if ( !V_strcasecmp( pValueString, "gamma" ) ) { return SO_FUNC1_GAMMA; } else if ( !V_strcasecmp( pValueString, "lgamma" ) ) { return SO_FUNC1_LGAMMA; } else if ( !V_strcasecmp( pValueString, "ceil" ) ) { return SO_FUNC1_CEIL; } else if ( !V_strcasecmp( pValueString, "floor" ) ) { return SO_FUNC1_FLOOR; } else if ( !V_strcasecmp( pValueString, "rint" ) ) { return SO_FUNC1_RINT; } else if ( !V_strcasecmp( pValueString, "nearbyint" ) ) { return SO_FUNC1_NEARBYINT; } else if ( !V_strcasecmp( pValueString, "rintol" ) ) { return SO_FUNC1_RINTOL; } else if ( !V_strcasecmp( pValueString, "round" ) ) { return SO_FUNC1_ROUND; } else if ( !V_strcasecmp( pValueString, "roundtol" ) ) { return SO_FUNC1_ROUNDTOL; } else if ( !V_strcasecmp( pValueString, "trunc" ) ) { return SO_FUNC1_TRUNC; } else { return SO_FUNC1_NONE; } } void S_PrintFunc1Type( SOFunc1Type_t nType, int nLevel ) { const char *pType; switch ( nType ) { case SO_FUNC1_NONE: pType = "none"; break; case SO_FUNC1_SIN: pType = "sin"; break; case SO_FUNC1_ASIN: pType = "asin"; break; case SO_FUNC1_COS: pType = "cos"; break; case SO_FUNC1_ACOS: pType = "acos"; break; case SO_FUNC1_TAN: pType = "tan"; break; case SO_FUNC1_ATAN: pType = "atan"; break; case SO_FUNC1_SINH: pType = "sinh"; break; case SO_FUNC1_ASINH: pType = "asinh"; break; case SO_FUNC1_COSH: pType = "cosh"; break; case SO_FUNC1_ACOSH: pType = "acosh"; break; case SO_FUNC1_TANH: pType = "tanh"; break; case SO_FUNC1_ATANH: pType = "atanh"; break; case SO_FUNC1_EXP: pType = "exp"; break; case SO_FUNC1_EXPM1: pType = "expm1"; break; case SO_FUNC1_EXP2: pType = "exp2"; break; case SO_FUNC1_LOG: pType = "log"; break; case SO_FUNC1_LOG2: pType = "log2"; break; case SO_FUNC1_LOG1P: pType = "log1p"; break; case SO_FUNC1_LOG10: pType = "log10"; break; case SO_FUNC1_LOGB: pType = "logb"; break; case SO_FUNC1_FABS: pType = "fabs"; break; case SO_FUNC1_SQRT: pType = "sqrt"; break; case SO_FUNC1_ERF: pType = "erf"; break; case SO_FUNC1_ERFC: pType = "erfc"; break; case SO_FUNC1_GAMMA: pType = "gamma"; break; case SO_FUNC1_LGAMMA: pType = "lgamma"; break; case SO_FUNC1_CEIL: pType = "ceil"; break; case SO_FUNC1_FLOOR: pType = "floor"; break; case SO_FUNC1_RINT: pType = "rint"; break; case SO_FUNC1_NEARBYINT: pType = "nearbyint"; break; case SO_FUNC1_RINTOL: pType = "rintol"; break; case SO_FUNC1_ROUND: pType = "round"; break; case SO_FUNC1_ROUNDTOL: pType = "roundtol"; break; case SO_FUNC1_TRUNC: pType = "trunc"; break; default: pType = "none"; break; } Log_Msg( LOG_SOUND_OPERATOR_SYSTEM, OpColor, "%*sFunction: %s\n", nLevel, " ", pType ); } SOOpType_t S_GetExpressionType( const char *pValueString ) { if ( !V_strcasecmp( pValueString, "none" ) ) { return SO_OP_NONE; } else if ( !V_strcasecmp( pValueString, "set" ) ) { return SO_OP_SET; } else if ( !V_strcasecmp( pValueString, "add" ) ) { return SO_OP_ADD; } else if ( !V_strcasecmp( pValueString, "sub" ) ) { return SO_OP_SUB; } else if ( !V_strcasecmp( pValueString, "mult" ) ) { return SO_OP_MULT; } else if ( !V_strcasecmp( pValueString, "div" ) ) { return SO_OP_DIV; } else if ( !V_strcasecmp( pValueString, "mod" ) ) { return SO_OP_MOD; } else if ( !V_strcasecmp( pValueString, "max" ) ) { return SO_OP_MAX; } else if ( !V_strcasecmp( pValueString, "min" ) ) { return SO_OP_MIN; } else if ( !V_strcasecmp( pValueString, "invert" ) ) { return SO_OP_INV; } else if ( !V_strcasecmp( pValueString, "greater_than" ) ) { return SO_OP_GT; } else if ( !V_strcasecmp( pValueString, "less_than" ) ) { return SO_OP_LT; } else if ( !V_strcasecmp( pValueString, "greater_than_or_equal" ) ) { return SO_OP_GTOE; } else if ( !V_strcasecmp( pValueString, "less_than_or_equal" ) ) { return SO_OP_LTOE; } else if ( !V_strcasecmp( pValueString, "equals" ) ) { return SO_OP_EQ; } else if ( !V_strcasecmp( pValueString, "not_equal" ) ) { return SO_OP_NOT_EQ; } else if ( !V_strcasecmp( pValueString, "invert_scale" ) ) { return SO_OP_INV_SCALE; } else if ( !V_strcasecmp( pValueString, "pow" ) ) { return SO_OP_POW; } else { return SO_OP_NONE; } } void S_PrintOpType( SOOpType_t nType, int nLevel ) { const char *pType; switch ( nType ) { case SO_OP_NONE: pType = "none"; break; case SO_OP_SET: pType = "set"; break; case SO_OP_ADD: pType = "add"; break; case SO_OP_SUB: pType = "sub"; break; case SO_OP_MULT: pType = "mult"; break; case SO_OP_DIV: pType = "div"; break; case SO_OP_MOD: pType = "mod"; break; case SO_OP_MAX: pType = "max"; break; case SO_OP_MIN: pType = "min"; break; case SO_OP_INV: pType = "invert"; break; case SO_OP_GT: pType = "greater_than"; break; case SO_OP_LT: pType = "less_than"; break; case SO_OP_GTOE: pType = "greater_than_or_equal"; break; case SO_OP_LTOE: pType = "less_than_or_equal"; break; case SO_OP_EQ: pType = "equals"; break; case SO_OP_NOT_EQ: pType = "not_equal"; break; case SO_OP_INV_SCALE: pType = "invert_scale"; break; case SO_OP_POW: pType = "pow"; break; default: pType = "none"; break; } Log_Msg( LOG_SOUND_OPERATOR_SYSTEM, OpColor, "%*sOperation: %s\n", nLevel, " ", pType ); } //----------------------------------------------------------------------------- // CSosOperatorFunc1 // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFunc1, "math_func1" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFunc1, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorFunc1, m_flInput1, SO_SINGLE, "input1" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFunc1, "math_func1" ) void CSosOperatorFunc1::SetDefaults( void *pVoidMem ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 0.0 ) // do nothing by default pStructMem->m_funcType = SO_FUNC1_NONE; pStructMem->m_bNormTrig = false; } void CSosOperatorFunc1::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; float flResult = 0.0; switch ( pStructMem->m_funcType ) { case SO_OP_NONE: break; case SO_FUNC1_SIN: flResult = sin( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_ASIN: flResult = asin( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_COS: flResult = cos( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_ACOS: flResult = acos( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_TAN: flResult = tan( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_ATAN: flResult = atan( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_SINH: flResult = sinh( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ASINH: // flResult = asinh( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_COSH: flResult = cosh( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ACOSH: // flResult = acosh( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_TANH: flResult = tanh( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ATANH: // flResult = atanh( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_EXP: flResult = exp( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_EXPM1: // flResult = expm1( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_EXP2: // flResult = exp2( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_LOG: flResult = log( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_LOG2: // flResult = log2( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_LOG1P: // flResult = log1p( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_LOG10: flResult = log10( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_LOGB: // flResult = logb( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_FABS: flResult = fabs( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_SQRT: flResult = sqrt( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ERF: // flResult = erf( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_ERFC: // flResult = erfc( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_GAMMA: // flResult = gamma( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_LGAMMA: // flResult = lgamma( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_CEIL: flResult = ceil( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_FLOOR: flResult = floor( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_RINT: // flResult = rint( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_NEARBYINT: // flResult = nearbyint( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_RINTOL: // flResult = rintol( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_ROUND: flResult = SOS_ROUND( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ROUNDTOL: // flResult = roundtol( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_TRUNC: // flResult = trunc( pStructMem->m_flInput1[0] ); // break; default: break; } if( pStructMem->m_bNormTrig ) { flResult = ( flResult + 1.0 ) * 0.5; } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorFunc1::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintFunc1Type( pStructMem->m_funcType, nLevel ); Log_Msg( LOG_SND_OPERATORS, OpColor, "%*snormalize_trig: %s\n", nLevel, " ", pStructMem->m_bNormTrig ? "true": "false" ); } void CSosOperatorFunc1::OpHelp( ) const { } void CSosOperatorFunc1::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "function" ) ) { pStructMem->m_funcType = S_GetFunc1Type( pValueString ); } else if ( !V_strcasecmp( pParamString, "normalize_trig" ) ) { if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_bNormTrig = true; } else { pStructMem->m_bNormTrig = false; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorFloat // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFloat, "math_float" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFloat, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloat, m_flInput1, SO_SINGLE, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloat, m_flInput2, SO_SINGLE, "input2") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFloat, "math_float" ) void CSosOperatorFloat::SetDefaults( void *pVoidMem ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SINGLE, 0.0 ) // do nothing by default pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorFloat::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; float flResult = 0.0; switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: flResult = pStructMem->m_flInput1[0]; break; case SO_OP_ADD: flResult = pStructMem->m_flInput1[0] + pStructMem->m_flInput2[0]; break; case SO_OP_SUB: flResult = pStructMem->m_flInput1[0] - pStructMem->m_flInput2[0]; break; case SO_OP_MULT: flResult = pStructMem->m_flInput1[0] * pStructMem->m_flInput2[0]; break; case SO_OP_DIV: if ( pStructMem->m_flInput2[0] > 0.0 ) { flResult = pStructMem->m_flInput1[0] / pStructMem->m_flInput2[0]; } break; case SO_OP_MOD: if ( pStructMem->m_flInput2[0] > 0.0 ) { flResult = fmodf( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); } break; case SO_OP_MAX: flResult = MAX( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); break; case SO_OP_MIN: flResult = MIN( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); break; case SO_OP_INV: flResult = 1.0 - pStructMem->m_flInput1[0]; break; case SO_OP_GT: flResult = pStructMem->m_flInput1[0] > pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_LT: flResult = pStructMem->m_flInput1[0] < pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_GTOE: flResult = pStructMem->m_flInput1[0] >= pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_LTOE: flResult = pStructMem->m_flInput1[0] <= pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_EQ: flResult = pStructMem->m_flInput1[0] == pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_NOT_EQ: flResult = pStructMem->m_flInput1[0] != pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_INV_SCALE: flResult = 1.0 - ( ( 1.0 - pStructMem->m_flInput1[0] ) * pStructMem->m_flInput2[0] ); break; case SO_OP_POW: flResult = FastPow( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); break; default: break; } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorFloat::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorFloat::OpHelp( ) const { } void CSosOperatorFloat::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorVec3 // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorVec3, "math_vec3" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorVec3, m_flOutput, SO_VEC3, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorVec3, m_flInput1, SO_VEC3, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorVec3, m_flInput2, SO_VEC3, "input2") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorVec3, "math_vec3" ) void CSosOperatorVec3::SetDefaults( void *pVoidMem ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_VEC3, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_VEC3, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_VEC3, 0.0 ) pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorVec3::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; for( int i = 0; i < SO_POSITION_ARRAY_SIZE; i++ ) { switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i]; break; case SO_OP_ADD: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] + pStructMem->m_flInput2[i]; break; case SO_OP_SUB: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] - pStructMem->m_flInput2[i]; break; case SO_OP_MULT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] * pStructMem->m_flInput2[i]; break; case SO_OP_DIV: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] / pStructMem->m_flInput2[i]; } break; case SO_OP_MOD: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = fmodf( pStructMem->m_flInput1[i], pStructMem->m_flInput2[i] ); } break; case SO_OP_MAX: pStructMem->m_flOutput[i] = MAX(pStructMem->m_flInput1[i], pStructMem->m_flInput2[i]); break; case SO_OP_MIN: pStructMem->m_flOutput[i] = MIN(pStructMem->m_flInput1[i], pStructMem->m_flInput2[i]); break; case SO_OP_INV: pStructMem->m_flOutput[i] = 1.0 - pStructMem->m_flInput1[i]; break; case SO_OP_GT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] > pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] < pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_GTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] >= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] <= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_EQ: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] == pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; default: break; } } } void CSosOperatorVec3::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorVec3::OpHelp( ) const { } void CSosOperatorVec3::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorSpeakers //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorSpeakers, "math_speakers" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorSpeakers, m_flOutput, SO_SPEAKERS, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorSpeakers, m_flInput1, SO_SPEAKERS, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorSpeakers, m_flInput2, SO_SPEAKERS, "input2") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorSpeakers, "math_speakers" ) void CSosOperatorSpeakers::SetDefaults( void *pVoidMem ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SPEAKERS, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SPEAKERS, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SPEAKERS, 0.0 ) pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorSpeakers::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; for( int i = 0; i < SO_MAX_SPEAKERS; i++ ) { switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i]; break; case SO_OP_ADD: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] + pStructMem->m_flInput2[i]; break; case SO_OP_SUB: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] - pStructMem->m_flInput2[i]; break; case SO_OP_MULT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] * pStructMem->m_flInput2[i]; break; case SO_OP_DIV: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] / pStructMem->m_flInput2[i]; } break; case SO_OP_MOD: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = fmodf( pStructMem->m_flInput1[i], pStructMem->m_flInput2[i] ); } break; case SO_OP_MAX: pStructMem->m_flOutput[i] = MAX( pStructMem->m_flInput1[i], pStructMem->m_flInput2[i] ); break; case SO_OP_MIN: pStructMem->m_flOutput[i] = MIN( pStructMem->m_flInput1[1], pStructMem->m_flInput2[i] ); break; case SO_OP_INV: pStructMem->m_flOutput[i] = 1.0 - pStructMem->m_flInput1[i]; break; case SO_OP_GT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] > pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] < pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_GTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] >= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] <= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_EQ: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] == pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; default: break; } } } void CSosOperatorSpeakers::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorSpeakers::OpHelp( ) const { } void CSosOperatorSpeakers::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else if ( !V_strcasecmp( pParamString, "left_front" ) ) { pStructMem->m_flInput1[IFRONT_LEFT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "right_front" ) ) { pStructMem->m_flInput1[IFRONT_RIGHT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "left_rear" ) ) { pStructMem->m_flInput1[IREAR_LEFT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "right_rear" ) ) { pStructMem->m_flInput1[IREAR_RIGHT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "center" ) ) { pStructMem->m_flInput1[IFRONT_CENTER] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "lfe" ) ) { pStructMem->m_flInput1[IFRONT_CENTER0] = RandomInterval( ReadInterval( pValueString ) ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorFloatAccumulate12 // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFloatAccumulate12, "math_float_accumulate12" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput1, SO_SINGLE, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput2, SO_SINGLE, "input2") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput3, SO_SINGLE, "input3") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput4, SO_SINGLE, "input4") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput5, SO_SINGLE, "input5") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput6, SO_SINGLE, "input6") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput7, SO_SINGLE, "input7") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput8, SO_SINGLE, "input8") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput9, SO_SINGLE, "input9") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput10, SO_SINGLE, "input10") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput11, SO_SINGLE, "input11") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput12, SO_SINGLE, "input12") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFloatAccumulate12, "math_float_accumulate12" ) void CSosOperatorFloatAccumulate12::SetDefaults( void *pVoidMem ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput3, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput4, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput5, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput6, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput7, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput8, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput9, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput10, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput11, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput12, SO_SINGLE, 1.0 ) // do nothing by default pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorFloatAccumulate12::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; float flResult = 0.0; switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_ADD: flResult = pStructMem->m_flInput1[0] + pStructMem->m_flInput2[0] + pStructMem->m_flInput3[0] + pStructMem->m_flInput4[0] + pStructMem->m_flInput5[0] + pStructMem->m_flInput6[0] + pStructMem->m_flInput7[0] + pStructMem->m_flInput8[0] + pStructMem->m_flInput9[0] + pStructMem->m_flInput10[0] + pStructMem->m_flInput11[0] + pStructMem->m_flInput12[0]; break; case SO_OP_SUB: flResult = pStructMem->m_flInput1[0] - pStructMem->m_flInput2[0] - pStructMem->m_flInput3[0] - pStructMem->m_flInput4[0] - pStructMem->m_flInput5[0] - pStructMem->m_flInput6[0] - pStructMem->m_flInput7[0] - pStructMem->m_flInput8[0] - pStructMem->m_flInput9[0] - pStructMem->m_flInput10[0] - pStructMem->m_flInput11[0] - pStructMem->m_flInput12[0]; break; case SO_OP_MULT: flResult = pStructMem->m_flInput1[0] * pStructMem->m_flInput2[0] * pStructMem->m_flInput3[0] * pStructMem->m_flInput4[0] * pStructMem->m_flInput5[0] * pStructMem->m_flInput6[0] * pStructMem->m_flInput7[0] * pStructMem->m_flInput8[0] * pStructMem->m_flInput9[0] * pStructMem->m_flInput10[0] * pStructMem->m_flInput11[0] * pStructMem->m_flInput12[0]; break; case SO_OP_DIV: flResult = pStructMem->m_flInput1[0] / pStructMem->m_flInput2[0] / pStructMem->m_flInput3[0] / pStructMem->m_flInput4[0] / pStructMem->m_flInput5[0] / pStructMem->m_flInput6[0] / pStructMem->m_flInput7[0] / pStructMem->m_flInput8[0] / pStructMem->m_flInput9[0] / pStructMem->m_flInput10[0] / pStructMem->m_flInput11[0] / pStructMem->m_flInput12[0]; break; case SO_OP_MAX: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_MIN: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_EQ: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_INV_SCALE: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; default: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorFloatAccumulate12::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorFloatAccumulate12::OpHelp( ) const { } void CSosOperatorFloatAccumulate12::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorSourceDistance // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorSourceDistance, "calc_source_distance" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorSourceDistance, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorSourceDistance, m_flInputPos, SO_VEC3, "input_position" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorSourceDistance, "calc_source_distance" ) void CSosOperatorSourceDistance::SetDefaults( void *pVoidMem ) const { CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputPos, SO_VEC3, 0.0 ) pStructMem->m_b2D = false; pStructMem->m_bForceNotPlayerSound = false; } void CSosOperatorSourceDistance::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; pStructMem->m_flOutput[0] = FLT_MAX; // calculate the distance to the nearest ss player FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh ) { Vector vSource; if ( pScratchPad->m_bIsPlayerSound && !pStructMem->m_bForceNotPlayerSound ) { // Hack for now // get 2d forward direction vector, ignoring pitch angle Vector listener_forward2d; ConvertListenerVectorTo2D( &listener_forward2d, &pScratchPad->m_vPlayerRight[ hh ] ); // player sounds originate from 1' in front of player, 2d VectorMultiply(listener_forward2d, 12.0, vSource ); } else { Vector vPosition; vPosition[0] = pStructMem->m_flInputPos[0]; vPosition[1] = pStructMem->m_flInputPos[1]; vPosition[2] = pStructMem->m_flInputPos[2]; VectorSubtract( vPosition, pScratchPad->m_vPlayerOrigin[ hh ], vSource ); } // normalize source_vec and get distance from listener to source float checkDist = 0.0; if ( pStructMem->m_b2D ) { checkDist = vSource.Length2D(); } else { checkDist = VectorNormalize( vSource ); } if ( checkDist < pStructMem->m_flOutput[0] ) { pStructMem->m_flOutput[0] = checkDist; } } } void CSosOperatorSourceDistance::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorSourceDistance::OpHelp( ) const { } void CSosOperatorSourceDistance::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "in2D" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_b2D = false; } else if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_b2D = true; } } else if ( !V_strcasecmp( pParamString, "force_not_player_sound" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bForceNotPlayerSound = false; } else if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_bForceNotPlayerSound = true; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorFacing // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFacing, "calc_angles_facing" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorFacing, m_flInputAngles, SO_VEC3, "input_angles" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFacing, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFacing, "calc_angles_facing" ) void CSosOperatorFacing::SetDefaults( void *pVoidMem ) const { CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInputAngles, SO_VEC3, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) } void CSosOperatorFacing::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; if( !pChannel ) { Log_Warning( LOG_SND_OPERATORS, "Error: Sound operator %s requires valid channel pointer, being called without one\n", pStack->GetOperatorName( nOpIndex )); return; } QAngle vAngles; vAngles[0] = pStructMem->m_flInputAngles[0]; vAngles[1] = pStructMem->m_flInputAngles[1]; vAngles[2] = pStructMem->m_flInputAngles[2]; float flFacing = SND_GetFacingDirection( pChannel, pScratchPad->m_vBlendedListenerOrigin, vAngles ); pStructMem->m_flOutput[0] = (flFacing + 1.0) * 0.5; } void CSosOperatorFacing::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorFacing::OpHelp( ) const { } void CSosOperatorFacing::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorRemapValue // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorRemapValue, "math_remap_float" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInput, SO_SINGLE, "input" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMin, SO_SINGLE, "input_min" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMax, SO_SINGLE, "input_max" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMapMin, SO_SINGLE, "input_map_min" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMapMax, SO_SINGLE, "input_map_max" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorRemapValue, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorRemapValue, "math_remap_float" ) void CSosOperatorRemapValue::SetDefaults( void *pVoidMem ) const { CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInputMin, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputMax, SO_SINGLE, 0.1 ) SOS_INIT_INPUT_VAR( m_flInputMapMin, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputMapMax, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput, SO_SINGLE, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) pStructMem->m_bClampRange = true; pStructMem->m_bDefaultMax = true; } void CSosOperatorRemapValue::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; float flResult; float flValue = pStructMem->m_flInput[0]; float flMin = pStructMem->m_flInputMin[0]; float flMax = pStructMem->m_flInputMax[0]; float flMapMin = pStructMem->m_flInputMapMin[0]; float flMapMax = pStructMem->m_flInputMapMax[0]; // if ( flMin > flMax ) // { // Log_Warning( LOG_SND_OPERATORS, "Warning: remap_value operator min arg is greater than max arg\n"); // // } if ( flMapMin > flMapMax && flMin != flMax ) { // swap everything around float flTmpMin = flMapMin; flMapMin = flMapMax; flMapMax = flTmpMin; flTmpMin = flMin; flMin = flMax; flMax = flTmpMin; // Log_Warning( LOG_SND_OPERATORS, "Warning: remap_value operator map min arg is greater than map max arg\n"); } if( flMin == flMax ) { if( flValue < flMin) { flResult = flMapMin; } else if( flValue > flMax ) { flResult = flMapMax; } else { flResult = pStructMem->m_bDefaultMax ? flMapMax : flMapMin; } } else if ( flMapMin == flMapMax ) { flResult = flMapMin; } else if( flValue <= flMin && flMin < flMax ) { flResult = flMapMin; } else if( flValue >= flMax && flMax > flMin) { flResult = flMapMax; } else if( flValue >= flMin && flMin > flMax ) { flResult = flMapMin; } else if( flValue <= flMax && flMax < flMin) { flResult = flMapMax; } else { flResult = RemapVal( flValue, flMin, flMax, flMapMin, flMapMax ); // flResult = SOS_RESCALE( flValue, flMin, flMax, flMapMin, flMapMax ); } if( pStructMem->m_bClampRange ) { if( flMapMin < flMapMax ) { flResult = clamp( flResult, flMapMin, flMapMax ); } else { flResult = clamp( flResult, flMapMax, flMapMin ); } } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorRemapValue::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorRemapValue::OpHelp( ) const { } void CSosOperatorRemapValue::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "clamp_range" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bClampRange = false; } } else if ( !V_strcasecmp( pParamString, "default_to_max" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bDefaultMax = false; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorCurve4 //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorCurve4, "math_curve_2d_4knot" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInput, SO_SINGLE, "input" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorCurve4, m_flOutput, SO_SINGLE, "output" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX1, SO_SINGLE, "input_X1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY1, SO_SINGLE, "input_Y1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX2, SO_SINGLE, "input_X2" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY2, SO_SINGLE, "input_Y2" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX3, SO_SINGLE, "input_X3" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY3, SO_SINGLE, "input_Y3" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX4, SO_SINGLE, "input_X4" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY4, SO_SINGLE, "input_Y4" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorCurve4, "math_curve_2d_4knot" ) void CSosOperatorCurve4::SetDefaults( void *pVoidMem ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInput, SO_SINGLE, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputX1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputY1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputX2, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputY2, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputX3, SO_SINGLE, 2.0 ) SOS_INIT_INPUT_VAR( m_flInputY3, SO_SINGLE, 2.0 ) SOS_INIT_INPUT_VAR( m_flInputX4, SO_SINGLE, 3.0 ) SOS_INIT_INPUT_VAR( m_flInputY4, SO_SINGLE, 3.0 ) pStructMem->m_nCurveType = SO_OP_CURVETYPE_STEP; } void CSosOperatorCurve4::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; float flResult = 0.0; float flInput = pStructMem->m_flInput[0]; if ( flInput >= pStructMem->m_flInputX4[0] ) { flResult = pStructMem->m_flInputY4[0]; } else if ( flInput <= pStructMem->m_flInputX1[0] ) { flResult = pStructMem->m_flInputY1[0]; } else { float flX[4]; float flY[4]; flX[0] = pStructMem->m_flInputX1[0]; flX[1] = pStructMem->m_flInputX2[0]; flX[2] = pStructMem->m_flInputX3[0]; flX[3] = pStructMem->m_flInputX4[0]; flY[0] = pStructMem->m_flInputY1[0]; flY[1] = pStructMem->m_flInputY2[0]; flY[2] = pStructMem->m_flInputY3[0]; flY[3] = pStructMem->m_flInputY4[0]; int i; for( i = 0; i < (4 - 1); i++ ) { if( flInput > flX[i] && flInput < flX[i+1] ) { break; } } if( pStructMem->m_nCurveType == SO_OP_CURVETYPE_STEP ) { flResult = flY[i]; } else if( pStructMem->m_nCurveType == SO_OP_CURVETYPE_LINEAR ) { flResult = SOS_RESCALE( flInput, flX[i], flX[i+1], flY[i], flY[i+1] ); } } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorCurve4::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); Log_Msg( LOG_SND_OPERATORS, OpColor, "%*scurve_type: %s\n", nLevel, " ", pStructMem->m_nCurveType == SO_OP_CURVETYPE_STEP ? "step": "linear" ); } void CSosOperatorCurve4::OpHelp( ) const { } void CSosOperatorCurve4::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "curve_type" ) ) { if ( !V_strcasecmp( pValueString, "step" ) ) { pStructMem->m_nCurveType = SO_OP_CURVETYPE_STEP; } else if ( !V_strcasecmp( pValueString, "linear" ) ) { pStructMem->m_nCurveType = SO_OP_CURVETYPE_LINEAR; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorRandom //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorRandom, "math_random" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRandom, m_flInputMin, SO_SINGLE, "input_min" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRandom, m_flInputMax, SO_SINGLE, "input_max" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRandom, m_flInputSeed, SO_SINGLE, "input_seed" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorRandom, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorRandom, "math_random" ) void CSosOperatorRandom::SetDefaults( void *pVoidMem ) const { CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInputMin, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputMax, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputSeed, SO_SINGLE, -1.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) pStructMem->m_bRoundToInt = false; } void CSosOperatorRandom::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; if( pStructMem->m_flInputSeed[0] < 0.0 ) { int iSeed = (int)( Plat_FloatTime() * 100 ); g_pSoundOperatorSystem->m_operatorRandomStream.SetSeed( iSeed ); } else { g_pSoundOperatorSystem->m_operatorRandomStream.SetSeed( (int) pStructMem->m_flInputSeed[0] ); } float fResult = g_pSoundOperatorSystem->m_operatorRandomStream.RandomFloat( pStructMem->m_flInputMin[0], pStructMem->m_flInputMax[0] ); if( pStructMem->m_bRoundToInt ) { int nRound = (int) (fResult + 0.5); if( nRound < (int) pStructMem->m_flInputMin[0] ) { nRound++; } else if( nRound > (int) pStructMem->m_flInputMax[0] ) { nRound--; } fResult = (float) nRound; } pStructMem->m_flOutput[0] = fResult; } void CSosOperatorRandom::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorRandom::OpHelp( ) const { } void CSosOperatorRandom::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "round_to_int" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bRoundToInt = false; } else if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_bRoundToInt = true; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorLogicOperator //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorLogicSwitch, "math_logic_switch" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorLogicSwitch, m_flInput1, SO_SINGLE, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorLogicSwitch, m_flInput2, SO_SINGLE, "input2" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorLogicSwitch, m_flInputSwitch, SO_SINGLE, "input_switch" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorLogicSwitch, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorLogicSwitch, "math_logic_switch" ) void CSosOperatorLogicSwitch::SetDefaults( void *pVoidMem ) const { CSosOperatorLogicSwitch_t *pStructMem = (CSosOperatorLogicSwitch_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputSwitch, SO_SINGLE, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) } void CSosOperatorLogicSwitch::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorLogicSwitch_t *pStructMem = (CSosOperatorLogicSwitch_t *)pVoidMem; pStructMem->m_flOutput[0] = ( (pStructMem->m_flInputSwitch[0] > 0) ? ( pStructMem->m_flInput2[0] ) : ( pStructMem->m_flInput1[0] ) ); } void CSosOperatorLogicSwitch::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorLogicSwitch::OpHelp( ) const { } void CSosOperatorLogicSwitch::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorLogicSwitch_t *pStructMem = (CSosOperatorLogicSwitch_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } }
30.357143
176
0.688055
DannyParker0001
a0458cebda3e2326dbc153532319f242f3b2e592
7,340
cpp
C++
core/Transaction/Transfer.cpp
mm-s/symbol-sdk-cpp
2151503ff69d582de47acde1dffae02ed21e78ab
[ "MIT" ]
null
null
null
core/Transaction/Transfer.cpp
mm-s/symbol-sdk-cpp
2151503ff69d582de47acde1dffae02ed21e78ab
[ "MIT" ]
null
null
null
core/Transaction/Transfer.cpp
mm-s/symbol-sdk-cpp
2151503ff69d582de47acde1dffae02ed21e78ab
[ "MIT" ]
null
null
null
/** *** Copyright (c) 2016-2019, Jaguar0625, gimre, BloodyRookie, Tech Bureau, Corp. *** Copyright (c) 2020-present, Jaguar0625, gimre, BloodyRookie. *** All rights reserved. *** *** This file is part of Catapult. *** *** Catapult is free software: you can redistribute it and/or modify *** it under the terms of the GNU Lesser General Public License as published by *** the Free Software Foundation, either version 3 of the License, or *** (at your option) any later version. *** *** Catapult is distributed in the hope that it will be useful, *** but WITHOUT ANY WARRANTY; without even the implied warranty of *** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *** GNU Lesser General Public License for more details. *** *** You should have received a copy of the GNU Lesser General Public License *** along with Catapult. If not, see <http://www.gnu.org/licenses/>. **/ #include "Transfer.h" #include "../catapult/BufferInputStreamAdapter.h" #include "../catapult/EntityIoUtils.h" #include "../Network.h" #include "../catapult/TransferBuilder.h" #include "../catapult/SharedKey.h" #include "../catapult/CryptoUtils.h" #include "../catapult/AesDecrypt.h" #include "../catapult/SecureRandomGenerator.h" #include "../catapult/OpensslContexts.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <openssl/evp.h> #ifdef __clang__ #pragma clang diagnostic pop #endif namespace symbol { namespace core { /// Implementation for the class c using c = core::Transfer; using std::move; using std::ostringstream; using std::make_pair; c::Transfer(const Network& n, ptr<catapult::model::TransferTransaction> t): m_catapultTransferTx(t), b(n, t) { } c::Transfer(Transfer&& other): b(move(other)), m_catapultTransferTx(other.m_catapultTransferTx) { other.m_catapultTransferTx = nullptr; } pair<ko, ptr<Transfer>> c::create(const Network& n, const Blob& mem) { auto is = catapult::io::BufferInputStreamAdapter(mem); // catapult::model::IsSizeValidT<catapult::model::Transaction> // EntityType type= // BasicEntityType bet=catapult::model::ToBasicEntityType(entity.Type); std::unique_ptr<catapult::model::TransferTransaction> ptx; try { ptx = catapult::io::ReadEntity<catapult::model::TransferTransaction>(is); assert(ptx->Type == catapult::model::Entity_Type_Transfer); } catch (...) { ///CATAPULT_THROW_INVALID_ARGUMENT("size is insufficient"); return make_pair("KO 84039", nullptr); } if (n.identifier() != ptx->Network) { return make_pair("KO 82291", nullptr); } return make_pair(ok, new Transfer(n, ptx.release())); } /* uint64_t Random() { return utils::LowEntropyRandomGenerator()(); } uint8_t RandomByte() { return static_cast<uint8_t>(Random()); } std::generate_n(container.begin(), container.size(), []() { return static_cast<typename T::value_type>(RandomByte()); }); */ namespace { using namespace catapult; void Prepend(std::vector<uint8_t>& buffer, RawBuffer prefix) { buffer.resize(buffer.size() + prefix.Size); std::memmove(buffer.data() + prefix.Size, buffer.data(), buffer.size() - prefix.Size); std::memcpy(buffer.data(), prefix.pData, prefix.Size); } void AesGcmEncrypt( const crypto::SharedKey& encryptionKey, const crypto::AesGcm256::IV& iv, const RawBuffer& input, std::vector<uint8_t>& output) { // encrypt input into output output.resize(input.Size); auto outputSize = static_cast<int>(output.size()); utils::memcpy_cond(output.data(), input.pData, input.Size); crypto::OpensslCipherContext cipherContext; cipherContext.dispatch(EVP_EncryptInit_ex, EVP_aes_256_gcm(), nullptr, encryptionKey.data(), iv.data()); if (0 != outputSize) cipherContext.dispatch(EVP_EncryptUpdate, output.data(), &outputSize, output.data(), outputSize); cipherContext.dispatch(EVP_EncryptFinal_ex, output.data() + outputSize, &outputSize); // get tag crypto::AesGcm256::Tag tag; cipherContext.dispatch(EVP_CIPHER_CTX_ctrl, EVP_CTRL_GCM_GET_TAG, 16, tag.data()); // tag || iv || data Prepend(output, iv); Prepend(output, tag); } } pair<ko, c::Msg> c::encrypt(const c::Msg& clearText, const PrivateKey& src, const PublicKey& rcpt) { using namespace catapult::crypto; Keys srcKeys(src); auto sharedKey = DeriveSharedKey(srcKeys, rcpt); Msg encrypted; SecureRandomGenerator g; AesGcm256::IV iv; try { g.fill(iv.data(), iv.size()); } catch(...) { return make_pair("KO 88119 Could not generate secure random bits.", move(encrypted)); } AesGcmEncrypt(sharedKey, iv, clearText, encrypted); return make_pair(ok, move(encrypted)); } pair<ko, ptr<Transfer>> c::create(const Network& n, const UnresolvedAddress& rcpt, const MosaicValues& m, const Amount& maxfee, const TimeSpan& deadline, const Msg& msg, const ptr<PrivateKey>& encryptPrivateKey, const ptr<PublicKey>& encryptPublicKey) { PublicKey unused; catapult::builders::TransferBuilder builder(n.identifier(), unused); Msg finalMsg; if (encryptPrivateKey != nullptr) { if (encryptPublicKey == nullptr) { return make_pair("KO 33092 Recipient Public Key is required.", nullptr); } if (msg.empty()) { return make_pair("KO 33092 Message is empty.", nullptr); } auto addr = n.newAddress(*encryptPublicKey); if (*addr != rcpt) { delete addr; return make_pair("KO 33092 Encryption Public Key must correspond to the recipient address.", nullptr); } delete addr; auto r = encrypt(msg, *encryptPrivateKey, *encryptPublicKey); if (is_ko(r.first)) { return make_pair(r.first, nullptr); } Keys myKeys(*encryptPrivateKey); finalMsg.resize(1+myKeys.publicKey().Size+r.second.size()); finalMsg[0]='\1'; auto dest=finalMsg.data()+1; memcpy(dest, myKeys.publicKey().data(), myKeys.publicKey().Size); dest+=myKeys.publicKey().Size; memcpy(dest, r.second.data(), r.second.size()); } else { finalMsg=msg; finalMsg.insert(finalMsg.begin(), '\0'); } if (!finalMsg.empty()) { builder.setMessage(catapult::utils::RawBuffer(finalMsg.data(), finalMsg.size())); } builder.setRecipientAddress(rcpt); // for (const auto& seed : seeds) { // auto mosaicId = mosaicNameToMosaicIdMap.at(seed.Name); // builder.addMosaic({ mosaicId, seed.Amount }); // } //cout << "xXXXXXXXXXXXXXX " << m.unwrap() << endl; //UnresolvedMosaicId um(m.unwrap()); for (auto& i: m) { builder.addMosaic({ UnresolvedMosaicId{i.first.unwrap()}, i.second }); } builder.setDeadline(Timestamp(deadline.millis())); auto x = builder.build().release(); //cout << "XXXXXXXXXXXXXXXXXXXX" << endl; //cout << x->Network << " " << x->Size << " bytes" << endl; return make_pair(ok, new Transfer(n, x)); } bool c::toStream(ostream& os) const { if (m_catapultTx==nullptr) { return false; } Blob buf; buf.resize(m_catapultTx->Size); memcpy(buf.data(), m_catapultTx, m_catapultTx->Size); os << catapult::utils::HexFormat(buf); return true; } }} // namespaces std::ostream& operator << (std::ostream& os, const symbol::core::Transfer& o) { o.toStream(os); return os; }
33.063063
254
0.68624
mm-s
a0464fb8daa61b27648ec975dad2c94ef549f21e
2,153
cpp
C++
Week 3/id_425/LeetCode_127_425.cpp
larryRishi/algorithm004-05
e60d0b1176acd32a9184b215e36d4122ba0b6263
[ "Apache-2.0" ]
1
2019-10-12T06:48:45.000Z
2019-10-12T06:48:45.000Z
Week 3/id_425/LeetCode_127_425.cpp
larryRishi/algorithm004-05
e60d0b1176acd32a9184b215e36d4122ba0b6263
[ "Apache-2.0" ]
1
2019-12-01T10:02:03.000Z
2019-12-01T10:02:03.000Z
Week 3/id_425/LeetCode_127_425.cpp
larryRishi/algorithm004-05
e60d0b1176acd32a9184b215e36d4122ba0b6263
[ "Apache-2.0" ]
null
null
null
/* * @lc app=leetcode.cn id=127 lang=cpp * * [127] 单词接龙 * * https://leetcode-cn.com/problems/word-ladder/description/ * * algorithms * Medium (37.12%) * Likes: 151 * Dislikes: 0 * Total Accepted: 13.1K * Total Submissions: 34.9K * Testcase Example: '"hit"\n"cog"\n["hot","dot","dog","lot","log","cog"]' * * 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord * 的最短转换序列的长度。转换需遵循如下规则: * * * 每次转换只能改变一个字母。 * 转换过程中的中间单词必须是字典中的单词。 * * * 说明: * * * 如果不存在这样的转换序列,返回 0。 * 所有单词具有相同的长度。 * 所有单词只由小写字母组成。 * 字典中不存在重复的单词。 * 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 * * * 示例 1: * * 输入: * beginWord = "hit", * endWord = "cog", * wordList = ["hot","dot","dog","lot","log","cog"] * * 输出: 5 * * 解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", * ⁠ 返回它的长度 5。 * * * 示例 2: * * 输入: * beginWord = "hit" * endWord = "cog" * wordList = ["hot","dot","dog","lot","log"] * * 输出: 0 * * 解释: endWord "cog" 不在字典中,所以无法进行转换。 * */ // @lc code=start class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> dict(wordList.begin(),wordList.end()); //将vector转换为unordered_set queue<string> todo; todo.push(beginWord); int ladder = 1; while(!todo.empty()){ int n = todo.size(); for (int i=0;i<n; i++){ string word = todo.front(); todo.pop(); if(word == endWord){ return ladder; } dict.erase(word); for (int j = 0; j < word.size(); j++){ char c = word[j]; for (int k = 0; k < 26; k++){ word[j]='a'+k; if(dict.find(word)!=dict.end()){ todo.push(word); } } word[j] = c; } } ladder++; } return 0; } }; // @lc code=end
22.904255
95
0.444961
larryRishi
a047ebe9dbb9beb28e8de88ae894ce1316a25205
4,310
cpp
C++
src/InputHandler.cpp
kaprikawn/target
36a38e789b7be5faad03ff1b48a45200eab7fa93
[ "MIT" ]
null
null
null
src/InputHandler.cpp
kaprikawn/target
36a38e789b7be5faad03ff1b48a45200eab7fa93
[ "MIT" ]
2
2017-05-31T11:48:08.000Z
2017-05-31T11:49:26.000Z
src/InputHandler.cpp
kaprikawn/target
36a38e789b7be5faad03ff1b48a45200eab7fa93
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include "InputHandler.hpp" #include "Game.hpp" InputHandler* InputHandler::s_pInstance = 0; void InputHandler::initialiseJoysticks() { if( SDL_WasInit( SDL_INIT_JOYSTICK ) == 0 ) { SDL_InitSubSystem( SDL_INIT_JOYSTICK ); } if( SDL_NumJoysticks() > 0 ) { for( int i = 0; i < SDL_NumJoysticks(); i++ ) { SDL_Joystick* joy = SDL_JoystickOpen( i ); if( joy == NULL ) { std::cout << SDL_GetError() << std::endl; } else { m_joysticks.push_back( joy ); //m_joystickValues.push_back( std::make_pair( new Vector2D( 0, 0 ), new Vector2D( 0, 0 ) ) ); for( int b = 0; b < SDL_JoystickNumButtons( joy ); b++ ) { m_buttonStates.push_back( false ); } } } SDL_JoystickEventState( SDL_ENABLE ); m_bJoysticksInitialised = true; } else { m_bJoysticksInitialised = false; } std::cout << "Initialised " << m_joysticks.size() << " joystick(s)" << std::endl; } void InputHandler::onKeyDown() { m_keystates = SDL_GetKeyboardState( NULL ); if( m_keystates[ SDL_SCANCODE_ESCAPE ] == 1 ) { TheGame::Instance() -> quit(); } } void InputHandler::onKeyUp() { m_keystates = SDL_GetKeyboardState( NULL ); } bool InputHandler::isKeyDown( SDL_Scancode key ) { if( m_keystates != 0 ) { if( m_keystates[key] == 1 ) { return true; } else { return false; } } return false; } bool InputHandler::isPressed( int button ) { if( button == 0 ) { if( m_keystates[ SDL_SCANCODE_RIGHT ] == 1 || currentHat == SDL_HAT_RIGHT || currentHat == SDL_HAT_RIGHTUP || currentHat == SDL_HAT_RIGHTDOWN ) { return true; } } else if( button == 1 ) { if( m_keystates[ SDL_SCANCODE_LEFT ] == 1 || currentHat == SDL_HAT_LEFT || currentHat == SDL_HAT_LEFTUP || currentHat == SDL_HAT_LEFTDOWN ) { return true; } } else if( button == 2 ) { if( m_keystates[ SDL_SCANCODE_UP ] == 1 || currentHat == SDL_HAT_UP || currentHat == SDL_HAT_LEFTUP || currentHat == SDL_HAT_RIGHTUP ) { return true; } } else if( button == 3 ) { if( m_keystates[ SDL_SCANCODE_DOWN ] == 1 || currentHat == SDL_HAT_DOWN || currentHat == SDL_HAT_LEFTDOWN || currentHat == SDL_HAT_RIGHTDOWN ) { return true; } } else if( button == 4 ) { // fire if( m_keystates[ SDL_SCANCODE_Z ] == 1 ) { return true; } if( m_gamepadsInitialised ) { if( m_buttonStates[ 2 ] ) { return true; } } } else if( button == 5 ) { // roll if( m_keystates[ SDL_SCANCODE_X ] == 1 ) { return true; } } else if( button == 6 ) { // bomb if( m_keystates[ SDL_SCANCODE_C ] == 1 ) { return true; } } else if( button == 7 ) { // start if( m_keystates[ SDL_SCANCODE_S ] == 1 ) { return true; } } else if( button == 8 ) { // quit if( m_keystates[ SDL_SCANCODE_Q ] == 1 ) { return true; } } else if( button == 9 ) { // ok if( m_keystates[ SDL_SCANCODE_O ] == 1 ) { return true; } } else if( button == 10 ) { // back if( m_keystates[ SDL_SCANCODE_BACKSPACE ] == 1 ) { return true; } } return false; } void InputHandler::onHatMotion( SDL_Event &event ) { if( !m_bJoysticksInitialised ) { return; } for( int i = 0; i < m_joysticks.size(); i++ ) { currentHat = SDL_JoystickGetHat( m_joysticks[i], 0 ); } } void InputHandler::update() { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_QUIT: TheGame::Instance() -> quit(); break; case SDL_KEYDOWN: onKeyDown(); break; case SDL_KEYUP: onKeyUp(); break; case SDL_JOYHATMOTION: onHatMotion( event ); break; case SDL_JOYBUTTONDOWN: whichOne = event.jaxis.which; m_buttonStates[ event.jbutton.button ] = true; //printf( "%d pressed\n", event.jbutton.button ); break; case SDL_JOYBUTTONUP: whichOne = event.jaxis.which; m_buttonStates[ event.jbutton.button ] = false; break; default: break; } } } void InputHandler::clean() { if( m_gamepadsInitialised ) { for( unsigned int i = 0; i < SDL_NumJoysticks(); i++ ) { SDL_JoystickClose( m_joysticks[i] ); } } }
27.278481
149
0.588399
kaprikawn
a04bd9a30c84737eb29e298b575e5e6269570e87
336
cpp
C++
Source/remote_main.cpp
farkmarnum/imogen
f5a726e060315ea71de98f6b9eb06ba58bf2527d
[ "MIT" ]
null
null
null
Source/remote_main.cpp
farkmarnum/imogen
f5a726e060315ea71de98f6b9eb06ba58bf2527d
[ "MIT" ]
null
null
null
Source/remote_main.cpp
farkmarnum/imogen
f5a726e060315ea71de98f6b9eb06ba58bf2527d
[ "MIT" ]
null
null
null
#include <imogen_gui/imogen_gui.h> #include <lemons_app_utils/lemons_app_utils.h> namespace Imogen { struct RemoteApp : lemons::GuiApp<Remote> { RemoteApp() : lemons::GuiApp<Imogen::Remote> (String ("Imogen ") + TRANS ("Remote"), "0.0.1", { 1060, 640 }) { } }; } // namespace Imogen START_JUCE_APPLICATION (Imogen::RemoteApp)
18.666667
98
0.696429
farkmarnum
a04cdd61bd41801c12aacb89c7090ceabebe79d9
1,517
cpp
C++
Linked_List/InsertDLL.cpp
krcpr007/DSA-Abdul_Bari_codesAndPdfs-
06d19a936009502d39fb5e401e9d90bf6d7911c9
[ "MIT" ]
1
2021-12-06T13:49:47.000Z
2021-12-06T13:49:47.000Z
Linked_List/InsertDLL.cpp
krcpr007/DSA-Abdul_Bari_codesAndPdfs-
06d19a936009502d39fb5e401e9d90bf6d7911c9
[ "MIT" ]
null
null
null
Linked_List/InsertDLL.cpp
krcpr007/DSA-Abdul_Bari_codesAndPdfs-
06d19a936009502d39fb5e401e9d90bf6d7911c9
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; struct Node { struct Node *next; struct Node *prev; int data; } *first = NULL; void Create(int A[], int n) { struct Node *t, *last; first = new Node; first->data = A[0]; first->prev = first->next = NULL; last = first; for (int i = 1; i < n; i++) { t = new Node; t->data = A[i]; t->next = last->next; t->prev = last; last->next = t; last = t; } } void Display(struct Node *p) { while (p) { printf("%d ", p->data); p = p->next; } cout << endl; } int Length(struct Node *p) { int len = 0; while (p) { len++; p = p->next; } return len; } void InsertDLL(struct Node *p, int index, int x) { struct Node *t; if (index < 0 || index > Length(p)) { return; } if (index == 0) { t = new Node; t->data = x; t->prev = NULL; t->next = first; first->prev = t; first = t; } else { t = new Node; t->data = x; for (int i = 0; i < index - 1; i++) { p = p->next; } t->next = p->next; t->prev = p; if (p->next) { p->next->prev = t; } p->next = t; } } int main() { int Arr[] = {2, 3, 5, 7, 6, 0}; Create(Arr, 6); Display(first); InsertDLL(first, 2, 150); cout << endl; Display(first); return 0; }
16.138298
48
0.418589
krcpr007
a04d63c6ca2609b6ceb7488948b20ebbe116d4e4
730
hpp
C++
include/DataSeries/ByteField.hpp
sbu-fsl/DataSeries
8436462519eb22fc653387885b5f0339fb419061
[ "BSD-2-Clause" ]
6
2015-02-27T19:15:11.000Z
2018-10-25T14:22:31.000Z
include/DataSeries/ByteField.hpp
yoursunny/DataSeries
b5b9db8e40a79a3e546a59cd72a80be89412d7b2
[ "BSD-2-Clause" ]
7
2015-08-17T15:18:50.000Z
2017-08-16T00:16:19.000Z
include/DataSeries/ByteField.hpp
sbu-fsl/DataSeries
8436462519eb22fc653387885b5f0339fb419061
[ "BSD-2-Clause" ]
8
2015-07-13T23:02:28.000Z
2020-09-28T19:06:26.000Z
// -*-C++-*- /* (c) Copyright 2003-2009, Hewlett-Packard Development Company, LP See the file named COPYING for license details */ /** @file byte field class */ #ifndef DATASERIES_BYTEFIELD_HPP #define DATASERIES_BYTEFIELD_HPP /** \brief Accessor for byte fields */ class ByteField : public dataseries::detail::SimpleFixedField<uint8_t> { public: ByteField(ExtentSeries &dataseries, const std::string &field, int flags = 0, byte default_value = 0, bool auto_add = true) : dataseries::detail::SimpleFixedField<uint8_t>(dataseries, field, flags, default_value) { if (auto_add) { dataseries.addField(*this); } } friend class GF_Byte; }; #endif
22.8125
100
0.658904
sbu-fsl
a050b35eeea30520be28878ed3a557363b030e82
502
cpp
C++
src/PeerNotificationOfMintService.cpp
izzy-developer/core
32b83537a255aeef50a64252ea001c99c7e69a01
[ "MIT" ]
null
null
null
src/PeerNotificationOfMintService.cpp
izzy-developer/core
32b83537a255aeef50a64252ea001c99c7e69a01
[ "MIT" ]
null
null
null
src/PeerNotificationOfMintService.cpp
izzy-developer/core
32b83537a255aeef50a64252ea001c99c7e69a01
[ "MIT" ]
1
2022-03-15T23:32:26.000Z
2022-03-15T23:32:26.000Z
#include <PeerNotificationOfMintService.h> #include <uint256.h> #include <net.h> #include <protocol.h> PeerNotificationOfMintService::PeerNotificationOfMintService( std::vector<CNode*>& peers ): peers_(peers) { } bool PeerNotificationOfMintService::havePeersToNotify() const { return !peers_.empty(); } void PeerNotificationOfMintService::notifyPeers(const uint256& blockHash) const { for (CNode* peer : peers_) { peer->PushInventory(CInv(MSG_BLOCK, blockHash)); } }
21.826087
79
0.729084
izzy-developer
a052e433a1e4d331bd91972d8582fe3336ab0752
5,927
cc
C++
kernel/source/System.cc
brunexgeek/machina
e65c275cf57031b2e859802eff19eb40284299db
[ "Apache-2.0" ]
8
2016-09-24T14:17:57.000Z
2021-09-21T17:15:49.000Z
kernel/source/System.cc
brunexgeek/machina
e65c275cf57031b2e859802eff19eb40284299db
[ "Apache-2.0" ]
null
null
null
kernel/source/System.cc
brunexgeek/machina
e65c275cf57031b2e859802eff19eb40284299db
[ "Apache-2.0" ]
null
null
null
#include <sys/system.h> #include <sys/sysio.h> #include <sys/errors.h> #include <sys/bcm2837.h> #include <sys/types.h> #include <sys/sync.h> #include <sys/timer.hh> #include <sys/heap.h> #include <sys/pmm.hh> #include <machina/VMM.hh> #include <sys/Display.hh> #include <sys/Screen.hh> #include <sys/mailbox.h> #include <sys/uart.h> #include <mc/string.h> #include <sys/vfs.h> #include <sys/ramfs.h> #include <sys/procfs.h> #include <mc/string.h> /* * BSS area begin marker. */ extern uint8_t __begin_bss; /* * BSS area end marker. */ extern uint8_t __end_bss; /* * Pointer to the first C/C++ static construtor. */ extern void (*__begin_init_array) (void); /* * Pointer to the end of C/C++ static construtor list. * The last valid constructor is the one before this. */ extern void (*__end_init_array) (void); namespace machina { static volatile bool DISABLED_CORES[SYS_CPU_CORES]; int kernel_main(); /* * Raspberry Pi 1 uses ARMv6 that do not provides WFI instruction, * so we need to use the ARMv5 alternative. See the link * http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka13332.html * for more information. */ static void system_disableCore() { while (true) { uart_puts("Disabling CPU core"); #if (RPIGEN == 1) size_t value = 0; asm volatile ("mcr p15, 0, %0, c7, c0, 4" : "=r" (value)); #else //asm volatile ("dsb"); asm volatile ("wfi"); #endif } } static void system_shutdown(void) { #ifdef ENABLE_MULTI_CORE // read the CPU ID register to find out what core is shutting down size_t value = 0; asm volatile ("mrc p15, 0, %0, c0, c0, 5" : "=r" (value)); uint32_t current = value & (SYS_CPU_CORES - 1); // we don't shutdown the main core before to shutdown the others while (current == 0) { sync_dataMemBarrier(); // check whether the other cores are disabled bool result = true; for (size_t i = 1; i < SYS_CPU_CORES; ++i) result &= DISABLED_CORES[i]; if (!result) { // wait some time until next verification sync_dataSyncBarrier(); asm volatile ("wfi"); } } DISABLED_CORES[current] = true; sync_dataMemBarrier(); #endif //sync_disableInterrupts(); #if (RPIGEN > 1) sync_dataSyncBarrier(); #endif system_disableCore(); } /** * @brief Reboots the Raspberry Pi. * * This code was originally implemented by PlutoniumBob and published * at https://www.raspberrypi.org/forums/viewtopic.php?f=72&t=53862#p413949 */ static void system_reboot(void) { sync_dataSyncBarrier(); PUT32(SOC_PM_WDOG, SOC_PM_PASSWORD | 1); PUT32(SOC_PM_RSTC, SOC_PM_PASSWORD | SOC_PM_RSTC_WRCFG_FULL_RESET); system_disableCore(); } /* static void system_initializeVFP() { size_t cacr; asm volatile ( "mrc p15, 0, %0, c1, c0, 2" : "=r" (cacr) ); cacr |= 3 << 20; // cp10 (single precision) cacr |= 3 << 22; // cp11 (double precision) asm volatile ( "mcr p15, 0, %0, c1, c0, 2" :: "r" (cacr) ); sync_instSyncBarrier(); asm volatile ( "fmxr fpexc, %0" :: "r" (1 << 30) ); asm volatile ( "fmxr fpscr, %0" :: "r" (0) ); } */ int proc_sysname( uint8_t *buffer, int size, void *data ) { (void) data; const char *sysname = "Machina"; size_t len = strlen(sysname); if (size >= (int)(len + 1) * 2) { strncpy((char*) buffer, sysname, len + 1); return (int)(len + 1) * 2; } return 0; } extern "C" void system_initialize() { timer_initialize(); uart_init(); uart_puts("Initializing kernel...\nKernel arguments: "); for (size_t i = 0; i < SYS_CPU_CORES; ++i) DISABLED_CORES[i] = false; uart_putc('\n'); #if (RPIGEN != 1) && defined(ENABLE_MULTI_CORE) // put all other CPU cores to sleep for (unsigned i = 1; i < SYS_CPU_CORES; i++) { // https://www.raspberrypi.org/forums/viewtopic.php?f=72&t=98904&start=25#p700528 PUT32(0x4000008C + 0x10 * i, (uint32_t) &system_disableCore); } #endif // initializes the VFP //system_initializeVFP(); // clear the BBS area for (uint8_t *p = &__begin_bss; p < &__end_bss; ++p) *p = 0; // we also need to call the C/C++ static construtors manually void (**p) (void) = 0; for (p = &__begin_init_array; p < &__end_init_array; ++p) (**p) (); // Note: The next calls will initialize our memory managers. It's // crucial that no dynamic memory allocation is attempted before // that point. This includes using 'new' and 'delete' C++ operators. procfs_initialize(); procfs_register("/sysname", proc_sysname, NULL); pmm_register(); if (vfs_mount("procfs", "procfs", "/proc", "", 0, NULL) == EOK) uart_puts("Mounted '/proc'\n"); uart_puts("Starting kernel main...\n"); switch ( kernel_main () ) { case EREBOOT: system_reboot(); break; default: system_shutdown(); } } #ifdef ENABLE_MULTI_CORE extern "C" void system_enableCoreEx (void) { // L1 data cache may contain random entries after reset, delete them InvalidateDataCacheL1Only (); system_initializeVFP(); main_secondary(); system_shutdown(); } #endif #include "tamzen-10x20.c" #include <sys/timer.hh> int kernel_main() { Display &display = Display::getInstance(); const Font *font = Font::load(___fonts_Tamzen10x20_psf, ___fonts_Tamzen10x20_psf_len); TextScreen *ts = TextScreen::create( display.getWidth(), display.getHeight(), display.getDepth(), *font); heap_dump(); ts->print("\nCompiled on %S\nVideo memory at 0x%08p with %d bytes\n\n", __TIME__, display.getBuffer(), display.getBufferSize() ); sync_enableInterrupts(); ts->colorTest(); //ts->print(u"Now is %d\n", (uint32_t) timer_tick()); // print physical memory information struct file *fp = NULL; if (vfs_open("/proc/frames", 0, &fp) == EOK) { char buf[1024]; int c = vfs_read(fp, (uint8_t*)buf, sizeof(buf)); if (c >= 0) { c /= sizeof(char); buf[c] = 0; ts->write(buf, c); uart_puts(buf); } vfs_close(fp); } ts->refresh(); display.draw(*ts); system_disableCore(); return 0; } } // machina
19.69103
87
0.66138
brunexgeek
a057288f6491ef93600ed75057f53cbabdb3215c
2,356
hpp
C++
source/xyo/xyo-networking-socket.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-networking-socket.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-networking-socket.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
// // XYO // // Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com> // Created by Grigore Stefan <g_stefan@yahoo.com> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #ifndef XYO_NETWORKING_SOCKET_HPP #define XYO_NETWORKING_SOCKET_HPP #ifndef XYO_NETWORKING_NETWORK_HPP #include "xyo-networking-network.hpp" #endif #ifndef XYO_STREAM_IREAD_HPP #include "xyo-stream-iread.hpp" #endif #ifndef XYO_STREAM_IWRITE_HPP #include "xyo-stream-iwrite.hpp" #endif #ifndef XYO_NETWORKING_IPADRESS4_HPP #include "xyo-networking-ipaddress4.hpp" #endif #ifndef XYO_NETWORKING_IPADRESS6_HPP #include "xyo-networking-ipaddress6.hpp" #endif #ifndef XYO_ENCODING_STRING_HPP #include "xyo-encoding-string.hpp" #endif namespace XYO { namespace Networking { using namespace XYO::DataStructures; using namespace XYO::Stream; using namespace XYO::Encoding; class IPAddress_; class Socket_; class Socket: public virtual IRead, public virtual IWrite { XYO_DISALLOW_COPY_ASSIGN_MOVE(Socket); protected: Socket_ *this_; Socket *linkOwner_; IPAddress_ *ipAddress; bool ipAddressIs6; public: XYO_EXPORT Socket(); XYO_EXPORT ~Socket(); XYO_EXPORT operator bool() const; XYO_EXPORT bool openClient(IPAddress4 &adr_); XYO_EXPORT bool openServer(IPAddress4 &adr_); XYO_EXPORT bool openClient(IPAddress6 &adr_); XYO_EXPORT bool openServer(IPAddress6 &adr_); XYO_EXPORT bool listen(uint16_t queue_); XYO_EXPORT bool accept(Socket &socket_); XYO_EXPORT void close(); XYO_EXPORT size_t read(void *output, size_t ln); XYO_EXPORT size_t write(const void *input, size_t ln); XYO_EXPORT int waitToWrite(uint32_t microSeconds); XYO_EXPORT int waitToRead(uint32_t microSeconds); XYO_EXPORT bool openClientX(const String &adr_); XYO_EXPORT bool openServerX(const String &adr_); XYO_EXPORT bool isIPAddress4(); XYO_EXPORT bool isIPAddress6(); XYO_EXPORT bool getIPAddress4(IPAddress4 &); XYO_EXPORT bool getIPAddress6(IPAddress6 &); XYO_EXPORT void becomeOwner(Socket &socket_); XYO_EXPORT void linkOwner(Socket &socket_); XYO_EXPORT void unLinkOwner(); XYO_EXPORT void transferOwner(Socket &socket_); }; }; }; #endif
24.541667
63
0.716469
g-stefan
a05a50765d3b069636de3e0c7a272c57d16bf3b4
7,247
hpp
C++
test/functional/forall/reduce-multiple-segment/tests/test-forall-segment-multiple-ReduceSum.hpp
ggeorgakoudis/RAJA
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
[ "BSD-3-Clause" ]
1
2020-11-19T04:55:20.000Z
2020-11-19T04:55:20.000Z
test/functional/forall/reduce-multiple-segment/tests/test-forall-segment-multiple-ReduceSum.hpp
ggeorgakoudis/RAJA
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
[ "BSD-3-Clause" ]
null
null
null
test/functional/forall/reduce-multiple-segment/tests/test-forall-segment-multiple-ReduceSum.hpp
ggeorgakoudis/RAJA
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
[ "BSD-3-Clause" ]
null
null
null
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-20, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #ifndef __TEST_FORALL_MULTIPLE_REDUCESUM_HPP__ #define __TEST_FORALL_MULTIPLE_REDUCESUM_HPP__ #include <cstdlib> #include <numeric> template <typename IDX_TYPE, typename DATA_TYPE, typename WORKING_RES, typename EXEC_POLICY, typename REDUCE_POLICY> void ForallReduceSumMultipleStaggeredTestImpl(IDX_TYPE first, IDX_TYPE last) { RAJA::TypedRangeSegment<IDX_TYPE> r1(first, last); camp::resources::Resource working_res{WORKING_RES::get_default()}; DATA_TYPE* working_array; DATA_TYPE* check_array; DATA_TYPE* test_array; allocateForallTestData<DATA_TYPE>(last, working_res, &working_array, &check_array, &test_array); const DATA_TYPE initval = 2; for (IDX_TYPE i = 0; i < last; ++i) { test_array[i] = initval; } working_res.memcpy(working_array, test_array, sizeof(DATA_TYPE) * last); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum0(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum1(initval * 1); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum2(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum3(initval * 3); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum4(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum5(initval * 5); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum6(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum7(initval * 7); const DATA_TYPE index_len = static_cast<DATA_TYPE>(last - first); const int nloops = 2; for (int j = 0; j < nloops; ++j) { RAJA::forall<EXEC_POLICY>(r1, [=] RAJA_HOST_DEVICE(IDX_TYPE idx) { sum0 += working_array[idx]; sum1 += working_array[idx] * 2; sum2 += working_array[idx] * 3; sum3 += working_array[idx] * 4; sum4 += working_array[idx] * 5; sum5 += working_array[idx] * 6; sum6 += working_array[idx] * 7; sum7 += working_array[idx] * 8; }); DATA_TYPE check_val = initval * index_len * (j + 1); ASSERT_EQ(1 * check_val, static_cast<DATA_TYPE>(sum0.get())); ASSERT_EQ(2 * check_val + (initval*1), static_cast<DATA_TYPE>(sum1.get())); ASSERT_EQ(3 * check_val, static_cast<DATA_TYPE>(sum2.get())); ASSERT_EQ(4 * check_val + (initval*3), static_cast<DATA_TYPE>(sum3.get())); ASSERT_EQ(5 * check_val, static_cast<DATA_TYPE>(sum4.get())); ASSERT_EQ(6 * check_val + (initval*5), static_cast<DATA_TYPE>(sum5.get())); ASSERT_EQ(7 * check_val, static_cast<DATA_TYPE>(sum6.get())); ASSERT_EQ(8 * check_val + (initval*7), static_cast<DATA_TYPE>(sum7.get())); } deallocateForallTestData<DATA_TYPE>(working_res, working_array, check_array, test_array); } template <typename IDX_TYPE, typename DATA_TYPE, typename WORKING_RES, typename EXEC_POLICY, typename REDUCE_POLICY> void ForallReduceSumMultipleStaggered2TestImpl(IDX_TYPE first, IDX_TYPE last) { RAJA::TypedRangeSegment<IDX_TYPE> r1(first, last); camp::resources::Resource working_res{WORKING_RES::get_default()}; DATA_TYPE* working_array; DATA_TYPE* check_array; DATA_TYPE* test_array; allocateForallTestData<DATA_TYPE>(last, working_res, &working_array, &check_array, &test_array); const DATA_TYPE initval = 2; for (IDX_TYPE i = 0; i < last; ++i) { test_array[i] = initval; } working_res.memcpy(working_array, test_array, sizeof(DATA_TYPE) * last); const DATA_TYPE index_len = static_cast<DATA_TYPE>(last - first); // Workaround for broken omp-target reduction interface. // This should be `sumX;` not `sumX(0);` RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum0(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum1(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum2(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum3(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum4(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum5(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum6(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum7(0); sum0.reset(0); sum1.reset(initval * 1); sum2.reset(0); sum3.reset(initval * 3); sum4.reset(0.0); sum5.reset(initval * 5); sum6.reset(0.0); sum7.reset(initval * 7); const int nloops = 3; for (int j = 0; j < nloops; ++j) { RAJA::forall<EXEC_POLICY>(r1, [=] RAJA_HOST_DEVICE(IDX_TYPE idx) { sum0 += working_array[idx]; sum1 += working_array[idx] * 2; sum2 += working_array[idx] * 3; sum3 += working_array[idx] * 4; sum4 += working_array[idx] * 5; sum5 += working_array[idx] * 6; sum6 += working_array[idx] * 7; sum7 += working_array[idx] * 8; }); DATA_TYPE check_val = initval * index_len * (j + 1); ASSERT_EQ(1 * check_val, static_cast<DATA_TYPE>(sum0.get())); ASSERT_EQ(2 * check_val + (initval*1), static_cast<DATA_TYPE>(sum1.get())); ASSERT_EQ(3 * check_val, static_cast<DATA_TYPE>(sum2.get())); ASSERT_EQ(4 * check_val + (initval*3), static_cast<DATA_TYPE>(sum3.get())); ASSERT_EQ(5 * check_val, static_cast<DATA_TYPE>(sum4.get())); ASSERT_EQ(6 * check_val + (initval*5), static_cast<DATA_TYPE>(sum5.get())); ASSERT_EQ(7 * check_val, static_cast<DATA_TYPE>(sum6.get())); ASSERT_EQ(8 * check_val + (initval*7), static_cast<DATA_TYPE>(sum7.get())); } deallocateForallTestData<DATA_TYPE>(working_res, working_array, check_array, test_array); } TYPED_TEST_SUITE_P(ForallReduceSumMultipleTest); template <typename T> class ForallReduceSumMultipleTest : public ::testing::Test { }; TYPED_TEST_P(ForallReduceSumMultipleTest, ReduceSumMultipleForall) { using IDX_TYPE = typename camp::at<TypeParam, camp::num<0>>::type; using DATA_TYPE = typename camp::at<TypeParam, camp::num<1>>::type; using WORKING_RES = typename camp::at<TypeParam, camp::num<2>>::type; using EXEC_POLICY = typename camp::at<TypeParam, camp::num<3>>::type; using REDUCE_POLICY = typename camp::at<TypeParam, camp::num<4>>::type; ForallReduceSumMultipleStaggeredTestImpl<IDX_TYPE, DATA_TYPE, WORKING_RES, EXEC_POLICY, REDUCE_POLICY>(0, 2115); ForallReduceSumMultipleStaggered2TestImpl<IDX_TYPE, DATA_TYPE, WORKING_RES, EXEC_POLICY, REDUCE_POLICY>(0, 2115); } REGISTER_TYPED_TEST_SUITE_P(ForallReduceSumMultipleTest, ReduceSumMultipleForall); #endif // __TEST_FORALL_MULTIPLE_REDUCESUM_HPP__
37.35567
81
0.62688
ggeorgakoudis
a05b14db1fcc5898b89124aebc5ac61e1f8f80a1
4,520
cpp
C++
include/hydro/engine/core.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/engine/core.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/engine/core.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #include "core.hpp" namespace hydro::engine { /** * */ Boolean::Boolean() { mValue = false; } /** * */ Boolean::Boolean(bool value) { mValue = value; } /** * */ Boolean::Boolean(const Boolean &_bool) { mValue = _bool.mValue; } /** * */ Boolean::Boolean(Boolean &&_bool) { mValue = _bool.mValue; } /** * */ Boolean::~Boolean() { } /** * */ Boolean & Boolean::operator=(const Boolean &rhs) { mValue = rhs.mValue; return (*this); } /** * */ Boolean & Boolean::operator=(Boolean &&rhs) { mValue = rhs.mValue; return (*this); } /** * */ Number::Number() { mValue = 0.0; } Number::Number(double value) { mValue = value; } Number::Number(const Number &number) { mValue = number.mValue; } Number::Number(Number &&number) { mValue = number.mValue; } Number::~Number() { } Number & Number::operator=(const Number &rhs) { mValue = rhs.mValue; return (*this); } Number & Number::operator=(Number &&rhs) { mValue = rhs.mValue; return (*this); } /** * */ Color::Color() { mValue = 0; } /** * */ Color::Color(Number value) { mValue = value; } /** * */ Color::Color(Number r, Number g, Number b, Number a) { uint8_t red = r; uint8_t green = g; uint8_t blue = b; uint8_t alpha = a; mValue = (double)((red << 24) + (green << 16) + (blue << 8) + (alpha)); } /** * */ Color::Color(const Color &color) { mValue = color.mValue; } /** * */ Color::Color(Color &&color) { mValue = color.mValue; } /** * */ Color::~Color() { } Number Color::getRed() const { uint64_t value = (uint64_t)mValue.valueOf() >> 24 & 0xFF; return (double)value; } Number Color::getGreen() const { uint64_t value = (uint64_t)mValue.valueOf() >> 16 & 0xFF; return (double)value; } Number Color::getBlue() const { uint64_t value = (uint64_t)mValue.valueOf() >> 8 & 0xFF; return (double)value; } Number Color::getAlpha() const { uint64_t value = (uint64_t)mValue.valueOf() & 0xFF; return (double)value; } Number Color::valueOf() const { return mValue; } Color & Color::operator=(const Color &color) { mValue = color.mValue; return (*this); } Color & Color::operator=(Color &&color) { mValue = color.mValue; return (*this); } /** * */ String::String() { } /** * */ String::String(const char *) { } /** * */ String::String(const String &string) { } /** * */ String::String(String &&string) { } /** * */ String::~String() { } /** * */ Any::Any() //: mContent{ new holder<undefined_t>{ undefined } } { } /** * */ Any::Any(undefined_t) { } /** * */ Any::Any(std::nullptr_t) { } /** * */ Any::Any(Boolean _bool) { } /** * */ Any::Any(Color color) { } /** * */ Any::Any(String string) { } /** * */ Any::Any(Number number) { } /** * */ Any::Any(object_ptr<HElement> object) { } /** * */ Any::Any(const Any &any) : mContent{any.mContent->clone()} { } /** * */ Any::Any(Any &&any) { } /** * */ Any::~Any() { } /** * */ bool Any::isNull() const { return type() == typeid(std::nullptr_t); } /** * */ bool Any::isUndefined() const { return type() == typeid(undefined_t); } /** * */ bool Any::isBoolean() const { return type() == typeid(Boolean); } /** * */ bool Any::isColor() const { return type() == typeid(Color); } /** * */ bool Any::isNumber() const { return type() == typeid(Number); } /** * */ bool Any::isString() const { return type() == typeid(Number); } /** * */ Any::operator bool() const { if (isBoolean()) return (Boolean)(*this); else if (isString()) return (String)(*this); else if (isNumber()) return (double)(Number)(*this) != 0; else if (isNull() || isUndefined()) return false; else if (isColor()) return true; return false; } /** * */ Any &Any::operator=(const Any &rhs) { mContent = std::unique_ptr<placeholder>{rhs.mContent->clone()}; return (*this); } /** * */ Any &Any::operator=(Any &&rhs) { mContent = std::unique_ptr<placeholder>{rhs.mContent->clone()}; return (*this); } } // namespace hydro::engine
10.917874
75
0.520796
hydraate
a05c4dbe94e5b34750c26ec518ccecec4a60bd21
3,977
cpp
C++
raspberry/particle_slam.cpp
stheophil/MappingRover2
25d968a4f27016a3eb61b70e48d3f137887d440c
[ "MIT" ]
11
2015-11-12T11:12:50.000Z
2021-07-27T02:15:23.000Z
raspberry/particle_slam.cpp
stheophil/MappingRover2
25d968a4f27016a3eb61b70e48d3f137887d440c
[ "MIT" ]
null
null
null
raspberry/particle_slam.cpp
stheophil/MappingRover2
25d968a4f27016a3eb61b70e48d3f137887d440c
[ "MIT" ]
5
2015-11-12T03:10:28.000Z
2018-12-02T21:38:21.000Z
#include "particle_slam.h" #include "robot_configuration.h" #include "error_handling.h" #include "occupancy_grid.inl" #include <boost/range/algorithm/max_element.hpp> #include <boost/range/adaptor/transformed.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <random> #include <future> ///////////////////// // SParticle SParticle::SParticle() : m_pose(rbt::pose<double>::zero()), m_matLikelihood(c_nMapExtent, c_nMapExtent, CV_32FC1, cv::Scalar(0)) {} SParticle::SParticle(SParticle const& p) : m_pose(p.m_pose), m_matLikelihood(p.m_matLikelihood.clone()), m_occgrid(p.m_occgrid) {} SParticle& SParticle::operator=(SParticle const& p) { m_pose = p.m_pose; m_matLikelihood = p.m_matLikelihood.clone(); m_occgrid = p.m_occgrid; return *this; } void SParticle::update(SScanLine const& scanline) { m_pose = sample_motion_model(m_pose, scanline.translation(), scanline.rotation()); // OPTIMIZE: Match fewer points m_fWeight = measurement_model_map(m_pose, scanline, [this](rbt::point<double> const& pt) { auto const ptn = ToGridCoordinate(pt); return static_cast<double>(m_matLikelihood.at<float>(ptn.y, ptn.x)); }); // OPTIMIZE: Recalculate occupancy grid after resampling? // OPTIMIZE: m_occgrid.update also sets occupancy of robot itself each time boost::for_each(scanline.m_vecscan, [&](auto const& scan) { m_occgrid.update(m_pose, scan.m_fRadAngle, scan.m_nDistance); }); cv::distanceTransform(m_occgrid.ObstacleMap(), m_matLikelihood, CV_DIST_L2, 3); } /////////////////////// // SParticleSLAM CParticleSlamBase::CParticleSlamBase(int cParticles) : m_vecparticle(cParticles), m_itparticleBest(m_vecparticle.end()), m_vecparticleTemp(cParticles) {} static std::random_device s_rd; void CParticleSlamBase::receivedSensorData(SScanLine const& scanline) { // TODO: Ignore data when robot is not moving for a long time // if scanline full, update all particles, LOG("Update particles"); LOG("t = (" << scanline.translation().x << ";" << scanline.translation().y << ") " "r = " << scanline.rotation()); std::vector<std::future<double>> vecfuture; boost::for_each(m_vecparticle, [&](SParticle& p) { vecfuture.emplace_back( std::async(std::launch::async | std::launch::deferred, [&] { p.update(scanline); return p.m_fWeight; } )); }); double fWeightTotal = 0.0; for(int i=0; i<vecfuture.size(); ++i) { fWeightTotal += vecfuture[i].get(); #ifdef ENABLE_LOG auto const& p = m_vecparticle[i]; LOG("Particle " << i << " -> " << " pt = (" << p.m_pose.m_pt.x << "; " << p.m_pose.m_pt.y << ") " << " yaw = " << p.m_pose.m_fYaw << " w = " << p.m_fWeight); #endif } // Resampling // Thrun, Probabilistic robotics, p. 110 auto const fStepSize = fWeightTotal/m_vecparticle.size(); auto const r = std::uniform_real_distribution<double>(0.0, fStepSize)(s_rd); auto c = m_vecparticle.front().m_fWeight; auto itparticleOut = m_vecparticleTemp.begin(); for(int i = 0, m = 0; m<m_vecparticle.size(); ++m) { auto const u = r + m * fStepSize; while(c<u) { ++i; c += m_vecparticle[i].m_fWeight; } LOG("Sample particle " << i); *itparticleOut = m_vecparticle[i]; ++itparticleOut; } std::swap(m_vecparticle, m_vecparticleTemp); m_itparticleBest = boost::max_element( boost::adaptors::transform(m_vecparticle, std::mem_fn(&SParticle::m_fWeight)) ).base(); m_vecpose.emplace_back(m_itparticleBest->m_pose); } cv::Mat CParticleSlamBase::getMap() const { ASSERT(m_itparticleBest!=m_vecparticle.end()); return m_itparticleBest->m_occgrid.ObstacleMapWithPoses(m_vecpose); }
33.141667
102
0.629117
stheophil
a05daf912350cae6cd5ca8e8354d387667c75fe6
678
cpp
C++
src/cpp_language_linkage.cpp
Silveryard/cppast
6bb3f330cb0aec63e5631e175c24428581a34b0b
[ "MIT" ]
null
null
null
src/cpp_language_linkage.cpp
Silveryard/cppast
6bb3f330cb0aec63e5631e175c24428581a34b0b
[ "MIT" ]
null
null
null
src/cpp_language_linkage.cpp
Silveryard/cppast
6bb3f330cb0aec63e5631e175c24428581a34b0b
[ "MIT" ]
null
null
null
// Copyright (C) 2017-2022 Jonathan Müller and cppast contributors // SPDX-License-Identifier: MIT #include <cppast/cpp_language_linkage.hpp> #include <cppast/cpp_entity_kind.hpp> using namespace cppast; cpp_entity_kind cpp_language_linkage::kind() noexcept { return cpp_entity_kind::language_linkage_t; } bool cpp_language_linkage::is_block() const noexcept { if (begin() == end()) { // An empty container must be a "block" of the form: extern "C" {} return true; } return std::next(begin()) != end(); // more than one entity, so block } cpp_entity_kind cpp_language_linkage::do_get_entity_kind() const noexcept { return kind(); }
23.37931
74
0.707965
Silveryard
a05ec922b76dbf54bfacf45ade3eabbe8eb470d5
8,304
cpp
C++
src/main.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
5
2019-06-26T07:50:43.000Z
2021-12-17T08:52:39.000Z
src/main.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
1
2019-11-28T06:57:49.000Z
2019-11-28T06:57:49.000Z
src/main.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
1
2020-05-27T06:11:17.000Z
2020-05-27T06:11:17.000Z
#include "defines.hpp" #include "main.hpp" int main(int argc, char *argv[]) { double score; IplImage *img; CvMat temp; Mat image_draw; Mat image_temp; float *ptr; float *ptr_temp; float *ptr_thresholded; float *ptr_scored; float *ptr_removed_duplicate; int flag_box_exist=0; //getFiles("./test_image/",files); //char str[30]; //int size = files.size(); //for (int i = 0; i < size; i++) //{ // cout << "file size: "<< size <<files[i]<< endl; //} std::cout << "OpenCV Version: " << CV_VERSION << endl; img = cvLoadImage("./test_image/person-bike.jpg"); CvMat *mat = cvGetMat(img, &temp); cvNamedWindow("Input_Image", CV_WINDOW_AUTOSIZE); cvShowImage("Input_Image", img); cvWaitKey(0); double overlap = NMS_OVERLAP; //********************************************* Selective Search Boxes ********************************** bool fast_mode = FAST_MODE; double im_width = IM_WIDTH; CvMat *crop_boxes = selective_search_boxes(img, fast_mode, im_width); CvMat *boxes = cvCloneMat(crop_boxes); double minBoxSize = MIN_BOX_SIZE; printf("boxes number: %d \n", boxes->rows); CvMat *boxes_filtered = FilterBoxesWidth(boxes, minBoxSize); printf("remained boxes number after filtered: %d \n", boxes_filtered->rows); CvMat *boxes_remove_duplicates = BoxRemoveDuplicates(boxes_filtered); printf("remained boxes number removed duplicates: %d \n", boxes_remove_duplicates->rows); float *ptr_tmp; int Box_num = boxes_remove_duplicates->rows; double scale = img->width / im_width; //scale all boxes for (int i = 0; i < boxes_remove_duplicates->rows; i++) { ptr_tmp = (float*)(boxes_remove_duplicates->data.ptr + i * boxes_remove_duplicates->step); for (int j = 0; j < boxes_remove_duplicates->cols; j++) { *(ptr_tmp + j) = (*(ptr_tmp + j) - 1) * scale + 1; } } //********************************************** RCNN Extract Regions ********************************** //Image Crop Initialization int batch_size = 256; int result; Crop crop_param((char *)"warp", 227, 16); char cmdbuf0[80]; char cmdbuf1[80]; char cmdbuf2[80]; char cmdbuf3[80]; char crop_image_dir[80]; printf("Box_num = %d\n", Box_num); //convert cropped mat from RGB to BGR Mat mat_bgr; Mat mat_rgb = iplImageToMat(img, true); cvtColor(mat_rgb,mat_bgr,CV_RGB2BGR); IplImage img_bgr(mat_bgr); //cvNamedWindow("BGR-IPL", CV_WINDOW_AUTOSIZE); //cvShowImage("BGR-IPL", &img_bgr); //cvWaitKey(0); for (int j = 0; j < Box_num; j++) //for (int j = 0; j < 1000; j++) { CvMat *input_box = cvCreateMat(1, 4, CV_32FC1); ptr = (float*)(input_box->data.ptr + 0 * input_box->step); ptr_temp = (float*)(boxes_remove_duplicates->data.ptr + j * boxes_remove_duplicates->step); for (int k = 0; k < boxes_remove_duplicates->cols; k++) { *(ptr + k) = *(ptr_temp + k); } CvMat image_batches = Rcnn_extract_regions(&img_bgr, input_box, batch_size, crop_param); Mat cropped_Mat = cvMatToMat(&image_batches, true); sprintf(crop_image_dir, "./images/cropped_image_%03d.jpg",j); //printf("%s \n", crop_image_dir); imwrite(crop_image_dir, cropped_Mat); } //************************************************ DLA Processing *********************************************** sprintf(cmdbuf0, "rm ./*.dat"); printf("%s \n", cmdbuf0); system(cmdbuf0); //********************************************** Put Input into DLA ********************************************* sprintf(cmdbuf1, "./run.py --image_dir ./images --dst_dir ./output --mean_file ./mean/image_mean.mat"); printf("%s \n", cmdbuf1); system(cmdbuf1); //***************************************** Converting .dat into .txt ************************************************* sprintf(cmdbuf2, "./convert_dat_into_txt.py"); printf("%s \n", cmdbuf2); system(cmdbuf2); //****************************************** Get output data from .txt ************************************************* int box_col_num = TOTAL_CLASS + 4; CvMat *boxes_scored = cvCreateMat(boxes_remove_duplicates->rows,box_col_num,CV_32FC1); printf("get txt data \n"); char buf[2000]; char spliter[] = " ,!"; char *pch; int j; float f_num = 0; #ifdef TEST_WITH_TXT for (int ind = 0 ; ind < 1500; ind ++) #else for (int ind = 0 ; ind < Box_num; ind ++) #endif { string message; ifstream infile; if(ind < 100) sprintf(cmdbuf3, "./txt/data%03d.txt",ind); else sprintf(cmdbuf3, "./txt/data%d.txt",ind); infile.open(cmdbuf3); ptr = (float*)(boxes_scored->data.ptr + ind * boxes_scored->step); ptr_removed_duplicate = (float*)(boxes_remove_duplicates->data.ptr + ind * boxes_remove_duplicates->step); *(ptr) = *(ptr_removed_duplicate); *(ptr + 1) = *(ptr_removed_duplicate + 1); *(ptr + 2) = *(ptr_removed_duplicate + 2); *(ptr + 3) = *(ptr_removed_duplicate + 3); if(infile.is_open()) { while(infile.good() && !infile.eof()) { memset(buf,0,2000); infile.getline(buf,2000); } pch = strtok(buf,spliter); j = 4; while(pch != NULL) { f_num=atof(pch); *(ptr + j) = f_num; pch = strtok(NULL,spliter); j++; } infile.close(); } else { for(int cnt = 4; cnt < (TOTAL_CLASS + 4); cnt ++) { *(ptr + cnt) = 0; } } } //************************************************ Post Processing ********************************** //***************************************** NMS & DRAW Boxes Processing ********************************** printf("Final Stage \n"); double threshold = THRESHOLD; int length_index_reserved = 0; int *index_reserved = new int[boxes_scored->rows]; printf("boxes_scored size is [%d %d] \n",boxes_scored->rows,boxes_scored->cols); for (int num_class = 0; num_class < TOTAL_CLASS; num_class++) { length_index_reserved = 0; for (int i = 0; i < boxes_scored->rows; i++) { ptr = (float*)(boxes_scored->data.ptr + i * boxes_scored->step); if ((*(ptr + 4 + num_class)) > THRESHOLD) { index_reserved[length_index_reserved] = i; length_index_reserved = length_index_reserved + 1; } } //printf("index_reserved done \n"); if(length_index_reserved > 0) { CvMat * boxes_thresholded = cvCreateMat(length_index_reserved, 5, CV_32FC1); for (int i = 0; i < length_index_reserved; i++) { ptr = (float*)(boxes_scored->data.ptr + (index_reserved[i]) * boxes_scored->step); ptr_thresholded = (float*)(boxes_thresholded->data.ptr + i * boxes_thresholded->step); for (int j = 0; j < (boxes_thresholded->cols - 1); j++) { *(ptr_thresholded + j) = *(ptr + j); } *(ptr_thresholded + 4) = *(ptr + 4 + num_class); } //printf("Class %d boxes_scored after thresholded is %d \n",num_class,length_index_reserved); const char* class_type_c2 = classification[num_class].c_str(); printf("Class %s boxes_scored after thresholded is %d \n",class_type_c2,length_index_reserved); CvMat * print_box = cvCreateMat(boxes_thresholded->rows, 5, CV_32FC1); printf("Thresholded boxes: \n"); PrintCvMatValue(boxes_thresholded); print_box = nms(boxes_thresholded, overlap); printf("Print boxes after nms: \n"); PrintCvMatValue(print_box); image_draw = drawboxes(mat, print_box, num_class); CvMat temp2 = image_draw; cvCopy(&temp2, mat); flag_box_exist = 1; } else { string class_type = classification[num_class]; const char* class_type_c = class_type.c_str(); printf("Class %s number is 0 \n",class_type_c); } } Mat image_origin = cvMatToMat(mat, true); if(flag_box_exist) { imwrite("./output/output_image.jpg",image_draw); cvNamedWindow("Output Image", CV_WINDOW_AUTOSIZE); imshow("Output Image", image_draw); cvWaitKey(); } else { imwrite("./output/output_image.jpg",image_origin); cvNamedWindow("Output Image", CV_WINDOW_AUTOSIZE); imshow("Output Image", image_origin); cvWaitKey(); } return 0; }
29.136842
130
0.572977
Sensenzhl
a0633cc1c051b9b53e05f788bd694fdac2b37e70
2,328
cpp
C++
experimental/brunsc/python_console/convert_simtk_vec3.cpp
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
39
2015-05-10T23:23:03.000Z
2022-01-26T01:31:30.000Z
experimental/brunsc/python_console/convert_simtk_vec3.cpp
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
13
2016-03-04T05:29:23.000Z
2021-02-07T01:11:10.000Z
experimental/brunsc/python_console/convert_simtk_vec3.cpp
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
44
2015-11-11T07:30:59.000Z
2021-12-26T16:41:21.000Z
#include "convert_simtk_vec3.hpp" #include "SimTKcommon/SmallMatrix.h" #include <boost/python.hpp> namespace bp = boost::python; namespace stk = SimTK; struct vec3_to_python_tuple { static PyObject* convert(SimTK::Vec3 const& v) { std::vector<SimTK::Real> values(&v[0], &v[0] + 3); return bp::incref(bp::tuple(values).ptr()); } }; struct vec3_from_python_tuple { vec3_from_python_tuple() { bp::converter::registry::push_back( &convertible, &construct, bp::type_id<SimTK::Vec3>()); } static void* convertible(PyObject* obj_ptr) { if( !PySequence_Check( obj_ptr ) ) { return 0; } if( !PyObject_HasAttrString( obj_ptr, "__len__" ) ) { return 0; } bp::object py_sequence( bp::handle<>( bp::borrowed( obj_ptr ) ) ); if( 3 != bp::len( py_sequence ) ) { return 0; } // Ensure that the element type is correct for (Py_ssize_t i = 0; i < 3; ++i) { if (! boost::python::extract<double>(py_sequence[i]).check() ) return 0; } return obj_ptr; } static void construct( PyObject* obj_ptr, bp::converter::rvalue_from_python_stage1_data* data) { // Fill in values double x, y, z; if (!PyArg_ParseTuple(obj_ptr, "ddd", &x, &y, &z)) { // Raise exception, error will have been set by PyArg_ParseTuple bp::throw_error_already_set(); } // Grab pointer to memory into which to construct the new Vec3 typedef bp::converter::rvalue_from_python_storage<SimTK::Vec3> vec3_storage; void* const storage = reinterpret_cast<vec3_storage*>(data)->storage.bytes; // in-place construct the new QString using the character data // extraced from the python object new (storage) SimTK::Vec3(x, y, z); // Stash the memory chunk pointer for later use by boost.python data->convertible = storage; } }; void register_simtk_vec3_conversion() { // std::cout << "registering vec3 conversion" << std::endl; // bp::to_python_converter<SimTK::Vec3, vec3_to_python_tuple>(); vec3_from_python_tuple(); }
28.048193
84
0.579897
lens-biophotonics
a06647cc4ed4e5721156752b70feed5e2e399295
565
cpp
C++
LeetCode/Problems/Algorithms/#645_SetMismatch_sol4_visited_vector_O(N)_time_O(N)_extra_space_24ms_21.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#645_SetMismatch_sol4_visited_vector_O(N)_time_O(N)_extra_space_24ms_21.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#645_SetMismatch_sol4_visited_vector_O(N)_time_O(N)_extra_space_24ms_21.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findErrorNums(vector<int>& nums) { const int N = nums.size(); int duplicate = -1; int missing = -1; vector<bool> vis(N + 1, false); for(int num: nums){ if(vis[num]){ duplicate = num; } vis[num] = true; } for(int num = 1; num <= N; ++num){ if(!vis[num]){ missing = num; } } return {duplicate, missing}; } };
23.541667
51
0.380531
Tudor67
a067312eeebb22ba175f1c44fa0cd58ecb1122b1
4,220
cc
C++
exegesis/x86/operand_translator_test.cc
mrexodia/EXEgesis
91af85cfdd5d5b2e8d5d2a04aaa5d5175685acc7
[ "Apache-2.0" ]
null
null
null
exegesis/x86/operand_translator_test.cc
mrexodia/EXEgesis
91af85cfdd5d5b2e8d5d2a04aaa5d5175685acc7
[ "Apache-2.0" ]
null
null
null
exegesis/x86/operand_translator_test.cc
mrexodia/EXEgesis
91af85cfdd5d5b2e8d5d2a04aaa5d5175685acc7
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "exegesis/x86/operand_translator.h" #include "exegesis/testing/test_util.h" #include "exegesis/util/proto_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace exegesis { namespace x86 { namespace { using ::exegesis::testing::EqualsProto; TEST(OperandTranslatorTest, Works) { const auto instruction = ParseProtoFromStringOrDie<InstructionProto>(R"pb( legacy_instruction: true vendor_syntax { mnemonic: 'ADD' operands { addressing_mode: DIRECT_ADDRESSING encoding: MODRM_REG_ENCODING value_size_bits: 32 name: 'r32' } operands { addressing_mode: NO_ADDRESSING encoding: IMMEDIATE_VALUE_ENCODING value_size_bits: 8 name: 'imm8' } })pb"); constexpr const char kExpected[] = R"pb( mnemonic: 'ADD' operands { name: 'ecx' } operands { name: '0x11' })pb"; EXPECT_THAT(InstantiateOperands(instruction), EqualsProto(kExpected)); } TEST(OperandTranslatorTest, Avx512) { const auto instruction = ParseProtoFromStringOrDie<InstructionProto>(R"pb( vendor_syntax { mnemonic: "VPADDB" operands { addressing_mode: DIRECT_ADDRESSING encoding: MODRM_REG_ENCODING value_size_bits: 128 name: "xmm1" tags { name: "k1" } tags { name: "z" } usage: USAGE_WRITE } operands { addressing_mode: DIRECT_ADDRESSING encoding: VEX_V_ENCODING value_size_bits: 128 name: "xmm2" usage: USAGE_READ } operands { addressing_mode: INDIRECT_ADDRESSING encoding: MODRM_RM_ENCODING value_size_bits: 128 name: "m128" usage: USAGE_READ } } available_in_64_bit: true legacy_instruction: true raw_encoding_specification: "EVEX.NDS.128.66.0F.WIG FC /r")pb"); constexpr char kExpectedFormat[] = R"pb( mnemonic: "VPADDB" operands { name: "xmm1" tags { name: "k1" } tags { name: "z" } } operands { name: "xmm2" } operands { name: "xmmword ptr[RSI]" } )pb"; EXPECT_THAT(InstantiateOperands(instruction), EqualsProto(kExpectedFormat)); } TEST(OperandTranslatorTest, Avx512StaticRounding) { const auto instruction = ParseProtoFromStringOrDie<InstructionProto>(R"pb( vendor_syntax { mnemonic: "VADDPD" operands { addressing_mode: DIRECT_ADDRESSING encoding: MODRM_REG_ENCODING value_size_bits: 512 name: "zmm1" tags { name: "k1" } tags { name: "z" } usage: USAGE_WRITE } operands { addressing_mode: DIRECT_ADDRESSING encoding: VEX_V_ENCODING value_size_bits: 512 name: "zmm2" usage: USAGE_READ } operands { addressing_mode: DIRECT_ADDRESSING encoding: MODRM_RM_ENCODING value_size_bits: 512 name: "zmm3" usage: USAGE_READ } operands { addressing_mode: NO_ADDRESSING encoding: X86_STATIC_PROPERTY_ENCODING usage: USAGE_READ tags { name: "er" } } } available_in_64_bit: true raw_encoding_specification: "EVEX.NDS.512.66.0F.W1 58 /r")pb"); constexpr char kExpectedFormat[] = R"pb( mnemonic: "VADDPD" operands { name: "zmm1" tags { name: "k1" } tags { name: "z" } } operands { name: "zmm2" } operands { name: "zmm3" } operands { tags { name: "rn-sae" } })pb"; EXPECT_THAT(InstantiateOperands(instruction), EqualsProto(kExpectedFormat)); } } // namespace } // namespace x86 } // namespace exegesis
28.133333
78
0.645261
mrexodia
a0681f9df9d7c68c7c3c98257c34a33e4a055fb3
569
cpp
C++
level_zero/tools/source/sysman/linux/pmt/pmt_helper.cpp
lukaszgotszaldintel/compute-runtime
9b12dc43904806db07616ffb8b1c4495aa7d610f
[ "MIT" ]
null
null
null
level_zero/tools/source/sysman/linux/pmt/pmt_helper.cpp
lukaszgotszaldintel/compute-runtime
9b12dc43904806db07616ffb8b1c4495aa7d610f
[ "MIT" ]
null
null
null
level_zero/tools/source/sysman/linux/pmt/pmt_helper.cpp
lukaszgotszaldintel/compute-runtime
9b12dc43904806db07616ffb8b1c4495aa7d610f
[ "MIT" ]
null
null
null
/* * Copyright (C) 2020-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/tools/source/sysman/linux/pmt/pmt.h" namespace L0 { const std::map<std::string, uint64_t> deviceKeyOffsetMap = { {"PACKAGE_ENERGY", 0x400}, {"COMPUTE_TEMPERATURES", 0x68}, {"SOC_TEMPERATURES", 0x60}, {"CORE_TEMPERATURES", 0x6c}}; ze_result_t PlatformMonitoringTech::getKeyOffsetMap(std::string guid, std::map<std::string, uint64_t> &keyOffsetMap) { keyOffsetMap = deviceKeyOffsetMap; return ZE_RESULT_SUCCESS; } } // namespace L0
24.73913
118
0.711775
lukaszgotszaldintel
a06975d84bbf1316389188c2b68832431f32791a
3,072
cc
C++
src/core/vulkan/debug_msg.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/vulkan/debug_msg.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/vulkan/debug_msg.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
#include "debug_msg.h" using namespace std; DebugMessenger::DebugMessenger( const VkInstance& instance, const VkDebugUtilsMessengerCreateInfoEXT* createInfoExt ) : instance(instance) { #ifndef NDEBUG if(CreateDebugUtilsMessengerEXT(instance, createInfoExt, nullptr, &callback) != VK_SUCCESS) throw runtime_error("Failed to create debug messenger !"); #endif } DebugMessenger::~DebugMessenger() { DestroyDebugUtilsMessengerEXT(instance, callback, nullptr); } VKAPI_ATTR VkBool32 VKAPI_CALL DebugMessenger::DebugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT msgSeverity, VkDebugUtilsMessageTypeFlagsEXT msgType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { std::string str; if (msgSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { str.append("\033[1;31m"); } else if (msgSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) { str.append("\033[1;93m"); } else if (msgSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) { str.append("\033[1;94m"); } else { str.append("\033[3m"); } if (msgType >= VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) { str.append("PERFORMANCE: "); } else if (msgType >= VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) { str.append("VALIDATION: "); } else { str.append("GENERAL: "); } cerr << str << pCallbackData->pMessage << "\033[0m" << endl; return VK_FALSE; } VkResult DebugMessenger::CreateDebugUtilsMessengerEXT( const VkInstance& instance, const VkDebugUtilsMessengerCreateInfoEXT* createInfoExt, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT*pCallback ) { auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); if(func != nullptr) { return func(instance, createInfoExt, pAllocator, pCallback); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void DebugMessenger::DestroyDebugUtilsMessengerEXT(const VkInstance& instance, VkDebugUtilsMessengerEXT callback, const VkAllocationCallbacks* pAllocator) { auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); if(func != nullptr) { func(instance, callback, pAllocator); } } void DebugMessenger::PopulateDebugUtilsMessengerCreateInfoEXT(VkDebugUtilsMessengerCreateInfoEXT* createInfo) { *createInfo = { .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT , .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT , .pfnUserCallback = DebugCallback, .pUserData = nullptr, }; }
33.758242
156
0.73763
5aitama
a06e3d6cf6537e682482b2355ea46c0e81da58a1
5,411
cpp
C++
snippets/cpp/VS_Snippets_Winforms/Windows.Forms.Control Properties/CPP/controlproperties.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/Windows.Forms.Control Properties/CPP/controlproperties.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/Windows.Forms.Control Properties/CPP/controlproperties.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
#using <System.Data.dll> #using <System.Windows.Forms.dll> #using <System.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Data; namespace ControlProperties { public ref class Form1: public System::Windows::Forms::Form { private: System::Windows::Forms::ImageList^ imageList1; System::Windows::Forms::Button^ button2; System::ComponentModel::IContainer^ components; public: Form1() { InitializeComponent(); //this->AddMyGroupBox(); } protected: ~Form1() { if ( components != nullptr ) { delete components; } } private: void InitializeComponent() { this->components = gcnew System::ComponentModel::Container; System::Resources::ResourceManager^ resources = gcnew System::Resources::ResourceManager( Form1::typeid ); this->imageList1 = gcnew System::Windows::Forms::ImageList( this->components ); this->button2 = gcnew System::Windows::Forms::Button; this->SuspendLayout(); // // imageList1 // this->imageList1->ColorDepth = System::Windows::Forms::ColorDepth::Depth8Bit; this->imageList1->ImageSize = System::Drawing::Size( 16, 16 ); this->imageList1->ImageStream = (dynamic_cast<System::Windows::Forms::ImageListStreamer^>(resources->GetObject( "imageList1.ImageStream" ))); this->imageList1->TransparentColor = System::Drawing::Color::Transparent; // // button2 // this->button2->Location = System::Drawing::Point( 40, 232 ); this->button2->Name = "button2"; this->button2->TabIndex = 0; this->button2->Text = "button1"; this->button2->Click += gcnew System::EventHandler( this, &Form1::button2_Click ); // // Form1 // this->BackColor = System::Drawing::Color::FromArgb( ((System::Byte)(0)) ),((System::Byte)(64)),((System::Byte)(0)); this->ClientSize = System::Drawing::Size( 408, 405 ); array<System::Windows::Forms::Control^>^temp0 = {this->button2}; this->Controls->AddRange( temp0 ); this->Name = "Form1"; this->Text = "Form1"; this->ResumeLayout( false ); } //<snippet3> // Add a button to a form and set some of its common properties. private: void AddMyButton() { // Create a button and add it to the form. Button^ button1 = gcnew Button; // Anchor the button to the bottom right corner of the form button1->Anchor = static_cast<AnchorStyles>(AnchorStyles::Bottom | AnchorStyles::Right); // Assign a background image. button1->BackgroundImage = imageList1->Images[ 0 ]; // Specify the layout style of the background image. Tile is the default. button1->BackgroundImageLayout = ImageLayout::Center; // Make the button the same size as the image. button1->Size = button1->BackgroundImage->Size; // Set the button's TabIndex and TabStop properties. button1->TabIndex = 1; button1->TabStop = true; // Add a delegate to handle the Click event. button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click ); // Add the button to the form. this->Controls->Add( button1 ); } // </snippet3> //<snippet2> // Add a GroupBox to a form and set some of its common properties. private: void AddMyGroupBox() { // Create a GroupBox and add a TextBox to it. GroupBox^ groupBox1 = gcnew GroupBox; TextBox^ textBox1 = gcnew TextBox; textBox1->Location = Point(15,15); groupBox1->Controls->Add( textBox1 ); // Set the Text and Dock properties of the GroupBox. groupBox1->Text = "MyGroupBox"; groupBox1->Dock = DockStyle::Top; // Disable the GroupBox (which disables all its child controls) groupBox1->Enabled = false; // Add the Groupbox to the form. this->Controls->Add( groupBox1 ); } // </snippet2> // <snippet1> // Reset all the controls to the user's default Control color. private: void ResetAllControlsBackColor( Control^ control ) { control->BackColor = SystemColors::Control; control->ForeColor = SystemColors::ControlText; if ( control->HasChildren ) { // Recursively call this method for each child control. IEnumerator^ myEnum = control->Controls->GetEnumerator(); while ( myEnum->MoveNext() ) { Control^ childControl = safe_cast<Control^>(myEnum->Current); ResetAllControlsBackColor( childControl ); } } } // </snippet1> void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { this->ResetAllControlsBackColor( this ); } void button2_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { this->AddMyButton(); } }; } [STAThread] int main() { Application::Run( gcnew ControlProperties::Form1 ); }
31.643275
150
0.598226
BohdanMosiyuk
a06e51350b082ceec2d9139791eca4120c74d8e5
1,623
hh
C++
CommManipulatorObjects/smartsoft/src-gen/CommManipulatorObjects/CommVacuumGripperEventStateACE.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
null
null
null
CommManipulatorObjects/smartsoft/src-gen/CommManipulatorObjects/CommVacuumGripperEventStateACE.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
CommManipulatorObjects/smartsoft/src-gen/CommManipulatorObjects/CommVacuumGripperEventStateACE.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef COMMMANIPULATOROBJECTS_COMMVACUUMGRIPPEREVENTSTATE_ACE_H_ #define COMMMANIPULATOROBJECTS_COMMVACUUMGRIPPEREVENTSTATE_ACE_H_ #include "CommManipulatorObjects/CommVacuumGripperEventState.hh" #include <ace/CDR_Stream.h> // serialization operator for DataStructure CommVacuumGripperEventState ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const CommManipulatorObjectsIDL::CommVacuumGripperEventState &data); // de-serialization operator for DataStructure CommVacuumGripperEventState ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, CommManipulatorObjectsIDL::CommVacuumGripperEventState &data); // serialization operator for CommunicationObject CommVacuumGripperEventState ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const CommManipulatorObjects::CommVacuumGripperEventState &obj); // de-serialization operator for CommunicationObject CommVacuumGripperEventState ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, CommManipulatorObjects::CommVacuumGripperEventState &obj); #endif /* COMMMANIPULATOROBJECTS_COMMVACUUMGRIPPEREVENTSTATE_ACE_H_ */
45.083333
116
0.754775
canonical-robots
a06f522b40afbef674cf7b485b0815554f5f343a
1,712
hh
C++
GeneralUtilities/inc/RSNTIO.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
GeneralUtilities/inc/RSNTIO.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
GeneralUtilities/inc/RSNTIO.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
// Data structures used to dump info and then re-sample particles from // a ROOT tree in some multi-stage job configurations. // // Andrei Gaponenko, 2015 #ifndef GeneralUtilities_inc_RSNTIO_hh #define GeneralUtilities_inc_RSNTIO_hh namespace mu2e { namespace IO { //================================================================ struct StoppedParticleF { float x; float y; float z; float t; StoppedParticleF() : x(), y(), z(), t() {} static const char *branchDescription() { return "x/F:y/F:z/F:time/F"; } static unsigned numBranchLeaves() { return 4; } }; //================================================================ struct StoppedParticleTauNormF { float x; float y; float z; float t; float tauNormalized; StoppedParticleTauNormF() : x(), y(), z(), t(), tauNormalized() {} static const char *branchDescription() { return "x/F:y/F:z/F:time/F:tauNormalized/F"; } static unsigned numBranchLeaves() { return 5; } }; //================================================================ struct InFlightParticleD { double x; double y; double z; double time; double px; double py; double pz; int pdgId; InFlightParticleD() : x(), y(), z(), time(), px(), py(), pz(), pdgId() {} static const char *branchDescription() { return "x/D:y/D:z/D:time/D:px/D:py/D:pz/D:pdgId/I"; } static unsigned numBranchLeaves() { return 8; } }; //================================================================ } // IO } // mu2e #endif/*GeneralUtilities_inc_RSNTIO_hh*/
24.112676
79
0.488318
bonventre
a0703053140cfab9dea50462c88f3a2ee5740f6e
5,497
cpp
C++
src/rivercrossing/rivercrossing.cpp
WatchJolley/rivercrossing
694c4245a8a5ae000e8d6338695a24dcedbb13a8
[ "MIT" ]
null
null
null
src/rivercrossing/rivercrossing.cpp
WatchJolley/rivercrossing
694c4245a8a5ae000e8d6338695a24dcedbb13a8
[ "MIT" ]
null
null
null
src/rivercrossing/rivercrossing.cpp
WatchJolley/rivercrossing
694c4245a8a5ae000e8d6338695a24dcedbb13a8
[ "MIT" ]
null
null
null
#include "rivercrossing/rivercrossing.h" #include "rivercrossing/movement_network.h" bool RiverCrossing::optimisationCheck(int x, int y) { double startA = SM.getActivity(x, y); double bestA = startA; int newX = x; int newY = y; for (int x2 = f(x, -2, RIVER::x); x2 <= f(x, 2, RIVER::x); x2++) { for (int y2 = f(y, -2, RIVER::y); y2 <= f(y, 2, RIVER::y); y2++) { if ( !((x2 == x) && (y2 == y)) ) { if ( SM.getActivity(x2, y2) > bestA) { bestA = SM.getActivity(x2, y2); newX = x2; newY = y2; } } } } x = newX; y = newY; // if no activity value is larger then exit if (startA == bestA) { return true; } return false; } void RiverCrossing::action(bool pickUpAction) { agent.carrying = pickUpAction; worlds.cell[ agent.x ][ agent.y ] = EMPTYCELL; updateNetworks(); } bool RiverCrossing::move() { if (USE_MOVEMENT) { vector<double> input; vector<double> outputs; int active = 0; double normActivity = SM.returnLargestActivity(); movement.loadInputs(agent.x, agent.y, SM, input, normActivity); movement.update(input); movement.getOutputs(outputs); for (int i = 0; i < 8; i++) { if ( outputs.at(active) < outputs.at(i) ) active = i; } return updatePostions( postions[active][0], postions[active][1] ); } else { int x = agent.x; int y = agent.y; int newX = x; int newY = y; double startA = SM.getActivity(x, y); double bestA = startA; for (int x2 = f(x, -1, RIVER::x); x2 <= f(x, 1, RIVER::x); x2++) { for (int y2 = f(y, -1, RIVER::y); y2 <= f(y, 1, RIVER::y); y2++) { if ( !((x2 == x) && (y2 == y)) ) { if ( SM.getActivity(x2, y2) > bestA) { bestA = SM.getActivity(x2, y2); newX = x2; newY = y2; } } } } agent.x = newX; agent.y = newY; // if no activity value is larger then exit if (startA == bestA) if(optimisationCheck(agent.x, agent.y)) return true; return false; } } int RiverCrossing::step() { bool failed = move(); worlds.updateHeatmap(agent.x,agent.y); if (failed) return TRAP; updateNetworks(true); // the action of an animat is based on the postion if (!DN_network.compare("RGB")) { vector<double> inputs; int o = worlds.getCell( agent.x, agent.y ); DN.loadInputs(worlds, inputs, o, agent.carrying); DN.update(inputs); } double pickUp = DN.getAction(); // pick up Stone if ((!agent.carrying) && ( pickUp >= 0.1f) && (worlds.cell[agent.x][agent.y] == STONE)) action(true); // put down Stone if ((agent.carrying) && ( pickUp <= -0.1f) && (worlds.cell[agent.x][agent.y] == WATER)) action(false); agent.age += 1; if (agent.debug == true) { worlds.printAnimat(agent.x, agent.y); SM.print(agent.x, agent.y); } return worlds.getCell( agent.x, agent.y ); } int RiverCrossing::run(int river, bool analyse, int seed, bool debug) { if (seed) randomise(seed); complete = false; worlds = dsWorld(river); agent = animat(getStarting()); worlds.updateHeatmap(agent.x,agent.y); if (debug) agent.debug = true; updateNetworks(); while (true) { int c = 0; c = step(); if (c == RESOURCE) { if (agent.debug == true) worlds.printHeatmap(); if (analyse) ages[river].push_back(agent.age); complete = true; return 1; } if (c == TRAP || c == WATER) { agent.death = c; if (agent.debug == true) worlds.printHeatmap(); return 0; } if (agent.age >= 200) { agent.death = AGE; if (agent.debug == true) worlds.printHeatmap(); return 0; } } } double RiverCrossing::evaluate() { int fitness = 0; for (int world = 0; world < 4; world++) { if (world != fitness ) break; fitness += run(world); } return fitness; } RiverCrossing::RiverCrossing(vector<double> genome) { // create seperate genomes for each network vector<int> genomeSplit = {config::DN_size, config::SM_size, config::MV_size}; vector<double> genomes[genomeSplit.size()]; for (int i = 0; i < genomeSplit.size(); i++) { if (genomeSplit.at(i) != 0) { auto it = std::next( genome.begin(), genomeSplit.at(i)); std::move(genome.begin(), it, std::back_inserter(genomes[i])); // ## genome.erase(genome.begin(), it); } } // configure network types this->DN_network = config::DN_network; this->SM_network = config::SM_network; DN.configureType(DN_network); SM.configureType(SM_network); // configure movement network this->USE_MOVEMENT = config::USE_MOVEMENT; // build DN if (genomes[0].size() > 0) { DN.buildNetwork(genomes[0]); } else { DN.buildNetwork(); } // build SM if (genomes[1].size() > 0) { SM.buildNetwork(genomes[1]); } else { SM.buildNetwork(); } // build Movement if (USE_MOVEMENT) movement.buildNetwork(genomes[2]); for(int i = 0; i < 5; i++) iotas.push_back( 0.0 ); needToUpdateShunting = false; complete = false; }
25.215596
91
0.538294
WatchJolley
a0704c167849356e9549e02fa6180431189c41a8
805
cpp
C++
cpp/cpp/14. Longest Common Prefix.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
3
2021-08-07T07:01:34.000Z
2021-08-07T07:03:02.000Z
cpp/cpp/14. Longest Common Prefix.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
cpp/cpp/14. Longest Common Prefix.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/longest-common-prefix/ // Write a function to find the longest common prefix string amongst an array of // strings. // If there is no common prefix, return an empty string "". //////////////////////////////////////////////////////////////////////////////// class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.size() == 1) return strs[0]; string ans; for (int i = 0; i < strs[0].size(); ++i) { char ch = strs[0][i]; // compare with other strs for (int j = 1; j < strs.size(); ++j) { if (i >= strs[j].size() || ch != strs[j][i]) { return ans; } } ans += ch; } return ans; } };
28.75
80
0.445963
longwangjhu
a0718acb0d7fca7e6d429a78a6e93d1b26d22975
5,228
cxx
C++
main/sal/osl/all/debugbase.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sal/osl/all/debugbase.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sal/osl/all/debugbase.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sal.hxx" #include "rtl/strbuf.hxx" #include "rtl/string.hxx" #include "rtl/ustring.hxx" #include "osl/process.h" #include "osl/diagnose.hxx" #include "boost/bind.hpp" #include <vector> #include <algorithm> // define own ones, independent of OSL_DEBUG_LEVEL: #define DEBUGBASE_ENSURE_(c, f, l, m) \ do \ { \ if (!(c) && _OSL_GLOBAL osl_assertFailedLine(f, l, m)) \ _OSL_GLOBAL osl_breakDebug(); \ } while (0) #define DEBUGBASE_ENSURE(c, m) DEBUGBASE_ENSURE_(c, OSL_THIS_FILE, __LINE__, m) namespace { typedef std::vector<rtl::OString> OStringVec; struct StaticDebugBaseAddressFilter : rtl::StaticWithInit<OStringVec const, StaticDebugBaseAddressFilter> { OStringVec const operator()() const { OStringVec vec; rtl_uString * pStr = 0; rtl::OUString const name( RTL_CONSTASCII_USTRINGPARAM("OSL_DEBUGBASE_STORE_ADDRESSES") ); if (osl_getEnvironment( name.pData, &pStr ) == osl_Process_E_None) { rtl::OUString const str(pStr); rtl_uString_release(pStr); sal_Int32 nIndex = 0; do { vec.push_back( rtl::OUStringToOString( str.getToken( 0, ';', nIndex ), RTL_TEXTENCODING_ASCII_US ) ); } while (nIndex >= 0); } return vec; } }; inline bool isSubStr( char const* pStr, rtl::OString const& subStr ) { return rtl_str_indexOfStr( pStr, subStr.getStr() ) >= 0; } struct DebugBaseMutex : ::rtl::Static<osl::Mutex, DebugBaseMutex> {}; } // anon namespace extern "C" { osl::Mutex & SAL_CALL osl_detail_ObjectRegistry_getMutex() SAL_THROW_EXTERN_C() { return DebugBaseMutex::get(); } bool SAL_CALL osl_detail_ObjectRegistry_storeAddresses( char const* pName ) SAL_THROW_EXTERN_C() { OStringVec const& rVec = StaticDebugBaseAddressFilter::get(); if (rVec.empty()) return false; // check for "all": rtl::OString const& rFirst = rVec[0]; if (rtl_str_compare_WithLength( rFirst.getStr(), rFirst.getLength(), RTL_CONSTASCII_STRINGPARAM("all") ) == 0) return true; OStringVec::const_iterator const iEnd( rVec.end() ); return std::find_if( rVec.begin(), iEnd, boost::bind( &isSubStr, pName, _1 ) ) != iEnd; } bool SAL_CALL osl_detail_ObjectRegistry_checkObjectCount( osl::detail::ObjectRegistryData const& rData, std::size_t nExpected ) SAL_THROW_EXTERN_C() { std::size_t nSize; if (rData.m_bStoreAddresses) nSize = rData.m_addresses.size(); else nSize = static_cast<std::size_t>(rData.m_nCount); bool const bRet = (nSize == nExpected); if (! bRet) { rtl::OStringBuffer buf; buf.append( RTL_CONSTASCII_STRINGPARAM("unexpected number of ") ); buf.append( rData.m_pName ); buf.append( RTL_CONSTASCII_STRINGPARAM(": ") ); buf.append( static_cast<sal_Int64>(nSize) ); DEBUGBASE_ENSURE( false, buf.makeStringAndClear().getStr() ); } return bRet; } void SAL_CALL osl_detail_ObjectRegistry_registerObject( osl::detail::ObjectRegistryData & rData, void const* pObj ) SAL_THROW_EXTERN_C() { if (rData.m_bStoreAddresses) { osl::MutexGuard const guard( osl_detail_ObjectRegistry_getMutex() ); std::pair<osl::detail::VoidPointerSet::iterator, bool> const insertion( rData.m_addresses.insert(pObj) ); DEBUGBASE_ENSURE( insertion.second, "### insertion failed!?" ); static_cast<void>(insertion); } else { osl_incrementInterlockedCount(&rData.m_nCount); } } void SAL_CALL osl_detail_ObjectRegistry_revokeObject( osl::detail::ObjectRegistryData & rData, void const* pObj ) SAL_THROW_EXTERN_C() { if (rData.m_bStoreAddresses) { osl::MutexGuard const guard( osl_detail_ObjectRegistry_getMutex() ); std::size_t const n = rData.m_addresses.erase(pObj); DEBUGBASE_ENSURE( n == 1, "erased more than 1 entry!?" ); static_cast<void>(n); } else { osl_decrementInterlockedCount(&rData.m_nCount); } } } // extern "C"
32.880503
79
0.646136
Grosskopf
a071db0dee153f6c9c571993f502d3c81640ccfc
7,876
cpp
C++
src/tests/add-ons/kernel/file_systems/udf/r5/UdfString.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
4
2017-06-17T22:03:56.000Z
2019-01-25T10:51:55.000Z
src/tests/add-ons/kernel/file_systems/udf/r5/UdfString.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
null
null
null
src/tests/add-ons/kernel/file_systems/udf/r5/UdfString.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
3
2018-12-17T13:07:38.000Z
2021-09-08T13:07:31.000Z
#include "UdfString.h" #include "ByteOrder.h" /*! \brief Converts the given unicode character to utf8. \param c The unicode character. \param out Pointer to a C-string of at least 4 characters long into which the output utf8 characters will be written. The string that is pointed to will be incremented to reflect the number of characters written, i.e. if \a out initially points to a pointer to the first character in string named \c str, and the function writes 4 characters to \c str, then upon returning, out will point to a pointer to the fifth character in \c str. */ static void unicode_to_utf8(uint32 c, char **out) { char *s = *out; if (c < 0x80) *(s++) = c; else if (c < 0x800) { *(s++) = 0xc0 | (c>>6); *(s++) = 0x80 | (c & 0x3f); } else if (c < 0x10000) { *(s++) = 0xe0 | (c>>12); *(s++) = 0x80 | ((c>>6) & 0x3f); *(s++) = 0x80 | (c & 0x3f); } else if (c <= 0x10ffff) { *(s++) = 0xf0 | (c>>18); *(s++) = 0x80 | ((c>>12) & 0x3f); *(s++) = 0x80 | ((c>>6) & 0x3f); *(s++) = 0x80 | (c & 0x3f); } *out = s; } /*! \brief Converts the given utf8 character to 4-byte unicode. \param in Pointer to a C-String from which utf8 characters will be read. *in will be incremented to reflect the number of characters read, similarly to the \c out parameter for Udf::unicode_to_utf8(). \return The 4-byte unicode character, or **in if passed an invalid character, or 0 if passed any NULL pointers. */ static uint32 utf8_to_unicode(const char **in) { if (!in) return 0; uint8 *bytes = (uint8 *)*in; if (!bytes) return 0; int32 length; uint8 mask = 0x1f; switch (bytes[0] & 0xf0) { case 0xc0: case 0xd0: length = 2; break; case 0xe0: length = 3; break; case 0xf0: mask = 0x0f; length = 4; break; default: // valid 1-byte character // and invalid characters (*in)++; return bytes[0]; } uint32 c = bytes[0] & mask; int32 i = 1; for (;i < length && (bytes[i] & 0x80) > 0;i++) c = (c << 6) | (bytes[i] & 0x3f); if (i < length) { // invalid character (*in)++; return (uint32)bytes[0]; } *in += length; return c; } using namespace Udf; /*! \brief Creates an empty string object. */ String::String() : fCs0String(NULL) , fUtf8String(NULL) { } /*! \brief Creates a new String object from the given Utf8 string. */ String::String(const char *utf8) : fCs0String(NULL) , fUtf8String(NULL) { SetTo(utf8); } /*! \brief Creates a new String object from the given Cs0 string. */ String::String(const char *cs0, uint32 length) : fCs0String(NULL) , fUtf8String(NULL) { SetTo(cs0, length); } String::~String() { DEBUG_INIT("String"); _Clear(); } /*! \brief Assignment from a Utf8 string. */ void String::SetTo(const char *utf8) { DEBUG_INIT_ETC("String", ("utf8: `%s', strlen(utf8): %ld", utf8, utf8 ? strlen(utf8) : 0)); _Clear(); if (!utf8) { PRINT(("passed NULL utf8 string\n")); return; } uint32 length = strlen(utf8); // First copy the utf8 string fUtf8String = new(nothrow) char[length+1]; if (!fUtf8String){ PRINT(("new fUtf8String[%ld] allocation failed\n", length+1)); return; } memcpy(fUtf8String, utf8, length+1); // Next convert to raw 4-byte unicode. Then we'll do some // analysis to figure out if we have any invalid characters, // and whether we can get away with compressed 8-bit unicode, // or have to use burly 16-bit unicode. uint32 *raw = new(nothrow) uint32[length]; if (!raw) { PRINT(("new uint32 raw[%ld] temporary string allocation failed\n", length)); _Clear(); return; } const char *in = utf8; uint32 rawLength = 0; for (uint32 i = 0; i < length && uint32(in-utf8) < length; i++, rawLength++) raw[i] = utf8_to_unicode(&in); // Check for invalids. uint32 mask = 0xffff0000; for (uint32 i = 0; i < rawLength; i++) { if (raw[i] & mask) { PRINT(("WARNING: utf8 string contained a multi-byte sequence which " "was converted into a unicode character larger than 16-bits; " "character will be converted to an underscore character for " "safety.\n")); raw[i] = '_'; } } // See if we can get away with 8-bit compressed unicode mask = 0xffffff00; bool canUse8bit = true; for (uint32 i = 0; i < rawLength; i++) { if (raw[i] & mask) { canUse8bit = false; break; } } // Build our cs0 string if (canUse8bit) { fCs0Length = rawLength+1; fCs0String = new(nothrow) char[fCs0Length]; if (fCs0String) { fCs0String[0] = '\x08'; // 8-bit compressed unicode for (uint32 i = 0; i < rawLength; i++) fCs0String[i+1] = raw[i] % 256; } else { PRINT(("new fCs0String[%ld] allocation failed\n", fCs0Length)); _Clear(); return; } } else { fCs0Length = rawLength*2+1; fCs0String = new(nothrow) char[fCs0Length]; if (fCs0String) { uint32 pos = 0; fCs0String[pos++] = '\x10'; // 16-bit unicode for (uint32 i = 0; i < rawLength; i++) { // 16-bit unicode chars must be written big endian uint16 value = uint16(raw[i]); uint8 high = uint8(value >> 8 & 0xff); uint8 low = uint8(value & 0xff); fCs0String[pos++] = high; fCs0String[pos++] = low; } } else { PRINT(("new fCs0String[%ld] allocation failed\n", fCs0Length)); _Clear(); return; } } // Clean up delete [] raw; raw = NULL; } /*! \brief Assignment from a Cs0 string. */ void String::SetTo(const char *cs0, uint32 length) { DEBUG_INIT_ETC("String", ("cs0: %p, length: %ld", cs0, length)); _Clear(); if (length == 0) return; if (!cs0) { PRINT(("passed NULL cs0 string\n")); return; } // First copy the Cs0 string and length fCs0String = new(nothrow) char[length]; if (fCs0String) { memcpy(fCs0String, cs0, length); fCs0Length = length; } else { PRINT(("new fCs0String[%ld] allocation failed\n", length)); return; } // Now convert to utf8 // The first byte of the CS0 string is the compression ID. // - 8: 1 byte characters // - 16: 2 byte, big endian characters // - 254: "CS0 expansion is empty and unique", 1 byte characters // - 255: "CS0 expansion is empty and unique", 2 byte, big endian characters PRINT(("compression ID: %d\n", cs0[0])); switch (reinterpret_cast<const uint8*>(cs0)[0]) { case 8: case 254: { const uint8 *inputString = reinterpret_cast<const uint8*>(&(cs0[1])); int32 maxLength = length-1; // Max length of input string in uint8 characters int32 allocationLength = maxLength*2+1; // Need at most 2 utf8 chars per uint8 char fUtf8String = new(nothrow) char[allocationLength]; if (fUtf8String) { char *outputString = fUtf8String; for (int32 i = 0; i < maxLength && inputString[i]; i++) { unicode_to_utf8(inputString[i], &outputString); } outputString[0] = 0; } else { PRINT(("new fUtf8String[%ld] allocation failed\n", allocationLength)); } break; } case 16: case 255: { const uint16 *inputString = reinterpret_cast<const uint16*>(&(cs0[1])); int32 maxLength = (length-1) / 2; // Max length of input string in uint16 characters int32 allocationLength = maxLength*3+1; // Need at most 3 utf8 chars per uint16 char fUtf8String = new(nothrow) char[allocationLength]; if (fUtf8String) { char *outputString = fUtf8String; for (int32 i = 0; i < maxLength && inputString[i]; i++) { unicode_to_utf8(B_BENDIAN_TO_HOST_INT16(inputString[i]), &outputString); } outputString[0] = 0; } else { PRINT(("new fUtf8String[%ld] allocation failed\n", allocationLength)); } break; } default: PRINT(("invalid compression id!\n")); break; } } void String::_Clear() { DEBUG_INIT("String"); delete [] fCs0String; fCs0String = NULL; delete [] fUtf8String; fUtf8String = NULL; }
25.162939
88
0.621508
axeld
a07229e840ea6f28a1c50a25def309b496814818
3,448
cpp
C++
src/sdk/utils/base32.cpp
proximax-storage/cpp-xpx-chain-sdk
ff562e8a089849eb0b7f8edc83ad61c7a2728f34
[ "Apache-2.0" ]
1
2019-12-06T06:55:37.000Z
2019-12-06T06:55:37.000Z
src/sdk/utils/base32.cpp
proximax-storage/cpp-xpx-chain-sdk
ff562e8a089849eb0b7f8edc83ad61c7a2728f34
[ "Apache-2.0" ]
null
null
null
src/sdk/utils/base32.cpp
proximax-storage/cpp-xpx-chain-sdk
ff562e8a089849eb0b7f8edc83ad61c7a2728f34
[ "Apache-2.0" ]
null
null
null
/** *** Copyright 2019 ProximaX Limited. All rights reserved. *** Use of this source code is governed by the Apache 2.0 *** license that can be found in the LICENSE file. **/ #include <xpxchaincpp/utils/base32.h> #include <cctype> namespace xpx_chain_sdk { namespace { const char* Base32_Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; const char Base32_Padding = '='; constexpr uint8_t Base32_Block_Size = 5; // in bits std::string_view TrimPadding(std::string_view encoded) { size_t resultSize = encoded.size(); for (; resultSize > 0 && encoded[resultSize - 1] == Base32_Padding; --resultSize); return encoded.substr(0, resultSize); } size_t GetBase32DecodedSize(size_t sizeWithoutPadding) { return (sizeWithoutPadding * Base32_Block_Size) / 8; } std::string Base32Encode(RawBuffer buffer, bool usePadding) { if (buffer.empty()) { return std::string{}; } // Calculating size of encoded data. size_t encodedSize = (buffer.size() * 8) / Base32_Block_Size; if ((buffer.size() * 8) % Base32_Block_Size) { encodedSize += 1; if (usePadding) { encodedSize += 8 - encodedSize % 8; // padding should complement to 8-byte boundary } } // Encoding data. std::string encoded(encodedSize, '='); // unnecessary padding will be overwritten during encoding uint32_t blocksBuffer = buffer[0]; uint32_t bitsLeft = 8; uint32_t encodedIndex = 0; uint32_t nextIndex = 1; while (nextIndex < buffer.size() || bitsLeft > 0) { if (bitsLeft < Base32_Block_Size) { if (nextIndex < buffer.size()) { blocksBuffer <<= 8; blocksBuffer |= 0xFF & buffer[nextIndex++]; bitsLeft += 8; } else { blocksBuffer <<= Base32_Block_Size - bitsLeft; bitsLeft = Base32_Block_Size; } } encoded[encodedIndex++] = Base32_Alphabet[0x1F & (blocksBuffer >> (bitsLeft - Base32_Block_Size))]; bitsLeft -= Base32_Block_Size; } return encoded; } bool Base32Decode(std::string_view encoded, MutableRawBuffer decoded) { uint32_t blocksBuffer = 0; uint32_t bitsLeft = 0; uint32_t decodedIndex = 0; for (size_t i = 0; i < encoded.size(); ++i) { char ch = encoded[i]; blocksBuffer <<= Base32_Block_Size; if (ch >= 'A' && ch <= 'Z') { ch = (ch & 0x1F) - 1; } else if (ch >= '2' && ch <= '7') { ch -= static_cast<int>('2') - 26; } else { return false; } blocksBuffer |= ch; bitsLeft += Base32_Block_Size; if (bitsLeft >= 8) { decoded[decodedIndex++] = blocksBuffer >> (bitsLeft - 8); bitsLeft -= 8; } } return true; } } std::string Base32::Encode(RawBuffer buffer) { return Base32Encode(buffer, false); } std::string Base32::EncodeWithPadding(RawBuffer buffer) { return Base32Encode(buffer, true); } bool Base32::Decode(std::string_view encoded, std::vector<uint8_t>& decoded) { auto encodedWithoutPadding = TrimPadding(encoded); decoded.resize(GetBase32DecodedSize(encodedWithoutPadding.size())); return Base32Decode(encodedWithoutPadding, decoded); } bool Base32::DecodeToBuffer(std::string_view encoded, MutableRawBuffer decoded) { auto encodedWithoutPadding = TrimPadding(encoded); if (decoded.size() != GetBase32DecodedSize(encodedWithoutPadding.size())) { return false; } return Base32Decode(encodedWithoutPadding, decoded); } }
26.121212
103
0.652552
proximax-storage
a07330bb7caaefec44d44cac204c32877e003639
11,614
cpp
C++
deps/libgeos/geos/src/geomgraph/EdgeEndStar.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
42
2021-03-26T17:34:52.000Z
2022-03-18T14:15:31.000Z
deps/libgeos/geos/src/geomgraph/EdgeEndStar.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
29
2021-06-03T14:24:01.000Z
2022-03-23T15:43:58.000Z
deps/libgeos/geos/src/geomgraph/EdgeEndStar.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
8
2021-05-14T19:26:37.000Z
2022-03-21T13:44:42.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2011 Sandro Santilli <strk@kbt.io> * Copyright (C) 2005-2006 Refractions Research Inc. * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geomgraph/EdgeEndStar.java r428 (JTS-1.12+) * **********************************************************************/ #include <geos/util/TopologyException.h> #include <geos/geomgraph/EdgeEndStar.h> #include <geos/algorithm/locate/SimplePointInAreaLocator.h> #include <geos/geom/Location.h> #include <geos/geomgraph/Label.h> #include <geos/geom/Position.h> #include <geos/geomgraph/GeometryGraph.h> #include <cassert> #include <string> #include <vector> #include <sstream> #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif using namespace geos::geom; namespace geos { namespace geomgraph { // geos.geomgraph /*public*/ EdgeEndStar::EdgeEndStar() : edgeMap() { ptInAreaLocation[0] = Location::NONE; ptInAreaLocation[1] = Location::NONE; } /*public*/ Coordinate& EdgeEndStar::getCoordinate() { static Coordinate nullCoord(DoubleNotANumber, DoubleNotANumber, DoubleNotANumber); if(edgeMap.empty()) { return nullCoord; } EdgeEndStar::iterator it = begin(); EdgeEnd* e = *it; assert(e); return e->getCoordinate(); } /*public*/ const Coordinate& EdgeEndStar::getCoordinate() const { return const_cast<EdgeEndStar*>(this)->getCoordinate(); } /*public*/ EdgeEnd* EdgeEndStar::getNextCW(EdgeEnd* ee) { EdgeEndStar::iterator it = find(ee); if(it == end()) { return nullptr; } if(it == begin()) { it = end(); --it; } else { --it; } return *it; } /*public*/ void EdgeEndStar::computeLabelling(std::vector<GeometryGraph*>* geomGraph) //throw(TopologyException *) { computeEdgeEndLabels((*geomGraph)[0]->getBoundaryNodeRule()); // Propagate side labels around the edges in the star // for each parent Geometry // // these calls can throw a TopologyException propagateSideLabels(0); propagateSideLabels(1); /* * If there are edges that still have null labels for a geometry * this must be because there are no area edges for that geometry * incident on this node. * In this case, to label the edge for that geometry we must test * whether the edge is in the interior of the geometry. * To do this it suffices to determine whether the node for the * edge is in the interior of an area. * If so, the edge has location INTERIOR for the geometry. * In all other cases (e.g. the node is on a line, on a point, or * not on the geometry at all) the edge * has the location EXTERIOR for the geometry. * * Note that the edge cannot be on the BOUNDARY of the geometry, * since then there would have been a parallel edge from the * Geometry at this node also labelled BOUNDARY * and this edge would have been labelled in the previous step. * * This code causes a problem when dimensional collapses are present, * since it may try and determine the location of a node where a * dimensional collapse has occurred. * The point should be considered to be on the EXTERIOR * of the polygon, but locate() will return INTERIOR, since it is * passed the original Geometry, not the collapsed version. * * If there are incident edges which are Line edges labelled BOUNDARY, * then they must be edges resulting from dimensional collapses. * In this case the other edges can be labelled EXTERIOR for this * Geometry. * * MD 8/11/01 - NOT TRUE! The collapsed edges may in fact be in the * interior of the Geometry, which means the other edges should be * labelled INTERIOR for this Geometry. * Not sure how solve this... Possibly labelling needs to be split * into several phases: * area label propagation, symLabel merging, then finally null label * resolution. */ bool hasDimensionalCollapseEdge[2] = {false, false}; for(EdgeEnd* e : *this) { assert(e); const Label& label = e->getLabel(); for(uint8_t geomi = 0; geomi < 2; geomi++) { if(label.isLine(geomi) && label.getLocation(geomi) == Location::BOUNDARY) { hasDimensionalCollapseEdge[geomi] = true; } } } for(EdgeEnd* e : *this) { assert(e); Label& label = e->getLabel(); for(uint32_t geomi = 0; geomi < 2; ++geomi) { if(label.isAnyNull(geomi)) { Location loc = Location::NONE; if(hasDimensionalCollapseEdge[geomi]) { loc = Location::EXTERIOR; } else { Coordinate& p = e->getCoordinate(); loc = getLocation(geomi, p, geomGraph); } label.setAllLocationsIfNull(geomi, loc); } } } } /*private*/ void EdgeEndStar::computeEdgeEndLabels( const algorithm::BoundaryNodeRule& boundaryNodeRule) { // Compute edge label for each EdgeEnd for(EdgeEndStar::iterator it = begin(); it != end(); ++it) { EdgeEnd* ee = *it; assert(ee); ee->computeLabel(boundaryNodeRule); } } /*public*/ Location EdgeEndStar::getLocation(uint32_t geomIndex, const Coordinate& p, std::vector<GeometryGraph*>* geom) { // compute location only on demand if(ptInAreaLocation[geomIndex] == Location::NONE) { ptInAreaLocation[geomIndex] = algorithm::locate::SimplePointInAreaLocator::locate(p, (*geom)[geomIndex]->getGeometry()); } return ptInAreaLocation[geomIndex]; } /*public*/ bool EdgeEndStar::isAreaLabelsConsistent(const GeometryGraph& geomGraph) { computeEdgeEndLabels(geomGraph.getBoundaryNodeRule()); return checkAreaLabelsConsistent(0); } /*private*/ bool EdgeEndStar::checkAreaLabelsConsistent(uint32_t geomIndex) { // Since edges are stored in CCW order around the node, // As we move around the ring we move from the right to // the left side of the edge // if no edges, trivially consistent if(edgeMap.empty()) { return true; } // initialize startLoc to location of last L side (if any) assert(*rbegin()); const Label& startLabel = (*rbegin())->getLabel(); Location startLoc = startLabel.getLocation(geomIndex, Position::LEFT); // Found unlabelled area edge assert(startLoc != Location::NONE); Location currLoc = startLoc; for(EdgeEndStar::iterator it = begin(), itEnd = end(); it != itEnd; ++it) { EdgeEnd* e = *it; assert(e); const Label& eLabel = e->getLabel(); // we assume that we are only checking a area // Found non-area edge assert(eLabel.isArea(geomIndex)); Location leftLoc = eLabel.getLocation(geomIndex, Position::LEFT); Location rightLoc = eLabel.getLocation(geomIndex, Position::RIGHT); // check that edge is really a boundary between inside and outside! if(leftLoc == rightLoc) { return false; } // check side location conflict //assert(rightLoc == currLoc); // "side location conflict " + locStr); if(rightLoc != currLoc) { return false; } currLoc = leftLoc; } return true; } /*public*/ void EdgeEndStar::propagateSideLabels(uint32_t geomIndex) //throw(TopologyException *) { // Since edges are stored in CCW order around the node, // As we move around the ring we move from the right to the // left side of the edge Location startLoc = Location::NONE; EdgeEndStar::iterator beginIt = begin(); EdgeEndStar::iterator endIt = end(); EdgeEndStar::iterator it; // initialize loc to location of last L side (if any) for(it = beginIt; it != endIt; ++it) { EdgeEnd* e = *it; assert(e); const Label& label = e->getLabel(); if(label.isArea(geomIndex) && label.getLocation(geomIndex, Position::LEFT) != Location::NONE) { startLoc = label.getLocation(geomIndex, Position::LEFT); } } // no labelled sides found, so no labels to propagate if(startLoc == Location::NONE) { return; } Location currLoc = startLoc; for(it = beginIt; it != endIt; ++it) { EdgeEnd* e = *it; assert(e); Label& label = e->getLabel(); // set null ON values to be in current location if(label.getLocation(geomIndex, Position::ON) == Location::NONE) { label.setLocation(geomIndex, Position::ON, currLoc); } // set side labels (if any) // if (label.isArea()) //ORIGINAL if(label.isArea(geomIndex)) { Location leftLoc = label.getLocation(geomIndex, Position::LEFT); Location rightLoc = label.getLocation(geomIndex, Position::RIGHT); // if there is a right location, that is the next // location to propagate if(rightLoc != Location::NONE) { if(rightLoc != currLoc) { std::stringstream ss; ss << "side location conflict at "; ss << e->getCoordinate().toString(); ss << ". This can occur if the input geometry is invalid."; throw util::TopologyException(ss.str()); } if(leftLoc == Location::NONE) { // found single null side at e->getCoordinate() assert(0); } currLoc = leftLoc; } else { /* * RHS is null - LHS must be null too. * This must be an edge from the other * geometry, which has no location * labelling for this geometry. * This edge must lie wholly inside or * outside the other geometry (which is * determined by the current location). * Assign both sides to be the current * location. */ // found single null side assert(label.getLocation(geomIndex, Position::LEFT) == Location::NONE); label.setLocation(geomIndex, Position::RIGHT, currLoc); label.setLocation(geomIndex, Position::LEFT, currLoc); } } } } /*public*/ std::string EdgeEndStar::print() const { std::ostringstream s; s << *this; return s.str(); } std::ostream& operator<< (std::ostream& os, const EdgeEndStar& es) { os << "EdgeEndStar: " << es.getCoordinate() << "\n"; for(EdgeEndStar::const_iterator it = es.begin(), itEnd = es.end(); it != itEnd; ++it) { const EdgeEnd* e = *it; assert(e); os << *e; } return os; } } // namespace geos.geomgraph } // namespace geos
31.304582
92
0.5855
khrushjing
a0760b5ff624b06be1f243f7da1f7df0e1b2bbdd
3,464
cpp
C++
dstore/network/socket.cpp
Charles0429/dstore
a825e6c4cc30d853f10b7a56f5a9286c2e57cc75
[ "MIT" ]
78
2016-09-24T16:56:00.000Z
2022-03-05T01:05:40.000Z
dstore/network/socket.cpp
Charles0429/dstore
a825e6c4cc30d853f10b7a56f5a9286c2e57cc75
[ "MIT" ]
null
null
null
dstore/network/socket.cpp
Charles0429/dstore
a825e6c4cc30d853f10b7a56f5a9286c2e57cc75
[ "MIT" ]
9
2016-09-30T07:45:35.000Z
2022-03-18T02:43:53.000Z
#include "socket.h" #include <errno.h> #include "errno_define.h" #include "socket_operator.h" #include "log.h" using namespace dstore::network; ListenSocket::ListenSocket(void) : listen_fd_(-1) { } ListenSocket::ListenSocket(int listen_fd) : listen_fd_(listen_fd) { } ListenSocket::~ListenSocket(void) { } void ListenSocket::set_listen_fd(int listen_fd) { listen_fd_ = listen_fd; } int ListenSocket::get_listen_fd(void) { return listen_fd_; } int ListenSocket::socket(const InetAddr &addr) { int ret = DSTORE_SUCCESS; int listen_fd = dstore::network::socket(addr.get_family(), addr.get_socket_type(), addr.get_protocol()); if (-1 == listen_fd) { LOG_WARN("create listen socket failed"); ret = DSTORE_LISTEN_ERROR; return ret; } listen_fd_ = listen_fd; return ret; } int ListenSocket::bind(const InetAddr &addr) { int ret = DSTORE_SUCCESS; ret = dstore::network::bind(listen_fd_, addr.get_addr(), *addr.get_addr_len()); if (-1 == ret) { LOG_WARN("bind listen socket failed, fd=%d", listen_fd_); ret = DSTORE_BIND_ERROR; return ret; } return ret; } int ListenSocket::listen(int backlog) { int ret = DSTORE_SUCCESS; ret = dstore::network::listen(listen_fd_, backlog); if (-1 == ret) { LOG_WARN("listen socket failed, fd=%d", listen_fd_); ret = DSTORE_LISTEN_ERROR; return ret; } return ret; } int ListenSocket::accept(int *fd, InetAddr *addr) { int ret = DSTORE_SUCCESS; *fd = dstore::network::accept(listen_fd_, addr->get_addr(), addr->get_addr_len()); if (-1 == *fd) { LOG_WARN("accept failed, listen_fd=%d", listen_fd_); ret = DSTORE_ACCEPT_ERROR; return ret; } return ret; } int ListenSocket::set_reuseaddr(void) { int ret = DSTORE_SUCCESS; ret = dstore::network::set_reuseaddr(listen_fd_); if (-1 == ret) { LOG_WARN("set reuseaddr failed, listen_fd=%d", listen_fd_); ret = DSTORE_SET_SOCKET_ERROR; return ret; } return ret; } int ListenSocket::set_nonblocking(void) { int ret = DSTORE_SUCCESS; ret = dstore::network::set_nonblocking(listen_fd_); if (-1 == ret) { LOG_WARN("set nonblocking failed, listen_fd=%d", listen_fd_); ret = DSTORE_SET_SOCKET_ERROR; return ret; } return ret; } Socket::Socket(void) : fd_(-1) { } Socket::Socket(int fd) : fd_(fd) { } Socket::~Socket(void) { } void Socket::set_fd(int fd) { fd_ = fd; } int Socket::get_fd(void) { return fd_; } int Socket::socket(const InetAddr &addr) { int ret = DSTORE_SUCCESS; int fd = dstore::network::socket(addr.get_family(), addr.get_socket_type(), addr.get_protocol()); if (-1 == fd) { LOG_WARN("create listen socket failed"); ret = DSTORE_LISTEN_ERROR; return ret; } fd_ = fd; return ret; } int Socket::connect(const InetAddr &addr) { int ret = DSTORE_SUCCESS; ret = dstore::network::connect(fd_, addr.get_addr(), *addr.get_addr_len()); if (-1 == ret) { if (errno == EINPROGRESS) { ret = DSTORE_CONNECT_IN_PROGRESS; } else { ret = DSTORE_CONNECT_ERROR; } } return ret; } int Socket::set_nonblocking(void) { int ret = DSTORE_SUCCESS; ret = dstore::network::set_nonblocking(fd_); if (-1 == ret) { LOG_WARN("set non blocking failed, fd_=%d", fd_); ret = DSTORE_SET_SOCKET_ERROR; return ret; } return ret; } void Socket::close(void) { dstore::network::close(fd_); } bool Socket::is_connect_ok(void) { return dstore::network::is_connect_ok(fd_); }
19.460674
106
0.670035
Charles0429
a079f25c5f518f88abc920c6bdce081a1096dec5
8,001
cpp
C++
gen/windows/kin/eigen/src/p_VectorNav_to_LeftToeBottom.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
26
2018-07-20T15:20:19.000Z
2022-03-14T07:12:12.000Z
gen/windows/kin/eigen/src/p_VectorNav_to_LeftToeBottom.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
2
2019-04-19T22:57:00.000Z
2022-01-11T12:46:20.000Z
gen/windows/kin/eigen/src/p_VectorNav_to_LeftToeBottom.cpp
UMich-BipedLab/Cassie_StateEstimation
d410ddce0ab342651f5ec0540c2867faf959a3a9
[ "BSD-3-Clause" ]
10
2018-07-29T08:05:14.000Z
2022-02-03T08:48:11.000Z
/* * Automatically Generated from Mathematica. * Thu 23 May 2019 13:11:48 GMT-04:00 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "p_VectorNav_to_LeftToeBottom.h" #ifdef _MSC_VER #define INLINE __forceinline /* use __forceinline (VC++ specific) */ #else #define INLINE static inline /* use standard inline */ #endif /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ INLINE double Power(double x, double y) { return pow(x, y); } INLINE double Sqrt(double x) { return sqrt(x); } INLINE double Abs(double x) { return fabs(x); } INLINE double Exp(double x) { return exp(x); } INLINE double Log(double x) { return log(x); } INLINE double Sin(double x) { return sin(x); } INLINE double Cos(double x) { return cos(x); } INLINE double Tan(double x) { return tan(x); } INLINE double Csc(double x) { return 1.0/sin(x); } INLINE double Sec(double x) { return 1.0/cos(x); } INLINE double ArcSin(double x) { return asin(x); } INLINE double ArcCos(double x) { return acos(x); } /* update ArcTan function to use atan2 instead. */ INLINE double ArcTan(double x, double y) { return atan2(y,x); } INLINE double Sinh(double x) { return sinh(x); } INLINE double Cosh(double x) { return cosh(x); } INLINE double Tanh(double x) { return tanh(x); } #define E 2.71828182845904523536029 #define Pi 3.14159265358979323846264 #define Degree 0.01745329251994329576924 /* * Sub functions */ static void output1(Eigen::Matrix<double,3,1> &p_output1, const Eigen::Matrix<double,14,1> &var1) { double t719; double t1986; double t2046; double t2253; double t2328; double t2368; double t3031; double t3325; double t3328; double t3332; double t3506; double t3669; double t3730; double t3762; double t3876; double t3920; double t3931; double t3950; double t3986; double t4033; double t4065; double t4164; double t4165; double t4167; double t4207; double t4217; double t4218; double t4234; double t4247; double t4249; double t4267; double t4304; double t4307; double t4308; double t4357; double t4363; double t4397; double t4538; double t1278; double t1383; double t2930; double t2937; double t2957; double t3017; double t3042; double t3050; double t2365; double t2650; double t2792; double t4708; double t3121; double t3234; double t3238; double t3504; double t3583; double t3642; double t4742; double t4759; double t4770; double t4794; double t4806; double t4815; double t3835; double t3855; double t3866; double t4047; double t4067; double t4111; double t4829; double t4832; double t4840; double t4860; double t4863; double t4883; double t4182; double t4187; double t4206; double t4263; double t4297; double t4301; double t4906; double t4917; double t4928; double t4958; double t4963; double t4966; double t4326; double t4328; double t4334; double t4990; double t4994; double t5002; double t5015; double t5020; double t5035; double t4627; double t4657; double t4678; double t4713; double t4715; double t4734; double t5166; double t5170; double t5171; double t5177; double t5189; double t5192; double t5202; double t5222; double t5223; double t5229; double t5232; double t5237; double t5247; double t5248; double t5251; double t5256; double t5257; double t5270; double t5276; double t5280; double t5282; double t5284; double t5286; double t5294; t719 = Cos(var1[1]); t1986 = Cos(var1[2]); t2046 = Cos(var1[3]); t2253 = -1.*t2046; t2328 = 1. + t2253; t2368 = Sin(var1[3]); t3031 = Sin(var1[2]); t3325 = Cos(var1[4]); t3328 = -1.*t3325; t3332 = 1. + t3328; t3506 = Sin(var1[4]); t3669 = -1.*t719*t1986*t2368; t3730 = -1.*t2046*t719*t3031; t3762 = t3669 + t3730; t3876 = t2046*t719*t1986; t3920 = -1.*t719*t2368*t3031; t3931 = t3876 + t3920; t3950 = Cos(var1[5]); t3986 = -1.*t3950; t4033 = 1. + t3986; t4065 = Sin(var1[5]); t4164 = t3506*t3762; t4165 = t3325*t3931; t4167 = t4164 + t4165; t4207 = t3325*t3762; t4217 = -1.*t3506*t3931; t4218 = t4207 + t4217; t4234 = Cos(var1[6]); t4247 = -1.*t4234; t4249 = 1. + t4247; t4267 = Sin(var1[6]); t4304 = -1.*t4065*t4167; t4307 = t3950*t4218; t4308 = t4304 + t4307; t4357 = t3950*t4167; t4363 = t4065*t4218; t4397 = t4357 + t4363; t4538 = Cos(var1[0]); t1278 = -1.*t719; t1383 = 1. + t1278; t2930 = Sin(var1[1]); t2937 = -1.*t1986; t2957 = 1. + t2937; t3017 = -0.049*t2957; t3042 = -0.09*t3031; t3050 = 0. + t3017 + t3042; t2365 = -0.049*t2328; t2650 = -0.21*t2368; t2792 = 0. + t2365 + t2650; t4708 = Sin(var1[0]); t3121 = -0.21*t2328; t3234 = 0.049*t2368; t3238 = 0. + t3121 + t3234; t3504 = -0.2707*t3332; t3583 = 0.0016*t3506; t3642 = 0. + t3504 + t3583; t4742 = t4538*t1986*t2930; t4759 = -1.*t4708*t3031; t4770 = t4742 + t4759; t4794 = -1.*t1986*t4708; t4806 = -1.*t4538*t2930*t3031; t4815 = t4794 + t4806; t3835 = -0.0016*t3332; t3855 = -0.2707*t3506; t3866 = 0. + t3835 + t3855; t4047 = 0.0184*t4033; t4067 = -0.7055*t4065; t4111 = 0. + t4047 + t4067; t4829 = -1.*t2368*t4770; t4832 = t2046*t4815; t4840 = t4829 + t4832; t4860 = t2046*t4770; t4863 = t2368*t4815; t4883 = t4860 + t4863; t4182 = -0.7055*t4033; t4187 = -0.0184*t4065; t4206 = 0. + t4182 + t4187; t4263 = -1.1135*t4249; t4297 = 0.0216*t4267; t4301 = 0. + t4263 + t4297; t4906 = t3506*t4840; t4917 = t3325*t4883; t4928 = t4906 + t4917; t4958 = t3325*t4840; t4963 = -1.*t3506*t4883; t4966 = t4958 + t4963; t4326 = -0.0216*t4249; t4328 = -1.1135*t4267; t4334 = 0. + t4326 + t4328; t4990 = -1.*t4065*t4928; t4994 = t3950*t4966; t5002 = t4990 + t4994; t5015 = t3950*t4928; t5020 = t4065*t4966; t5035 = t5015 + t5020; t4627 = 0.135*t1383; t4657 = 0.049*t2930; t4678 = 0. + t4627 + t4657; t4713 = -0.09*t2957; t4715 = 0.049*t3031; t4734 = 0. + t4713 + t4715; t5166 = t1986*t4708*t2930; t5170 = t4538*t3031; t5171 = t5166 + t5170; t5177 = t4538*t1986; t5189 = -1.*t4708*t2930*t3031; t5192 = t5177 + t5189; t5202 = -1.*t2368*t5171; t5222 = t2046*t5192; t5223 = t5202 + t5222; t5229 = t2046*t5171; t5232 = t2368*t5192; t5237 = t5229 + t5232; t5247 = t3506*t5223; t5248 = t3325*t5237; t5251 = t5247 + t5248; t5256 = t3325*t5223; t5257 = -1.*t3506*t5237; t5270 = t5256 + t5257; t5276 = -1.*t4065*t5251; t5280 = t3950*t5270; t5282 = t5276 + t5280; t5284 = t3950*t5251; t5286 = t4065*t5270; t5294 = t5284 + t5286; p_output1(0)=-0.03155 - 0.049*t1383 + 0.004500000000000004*t2930 + t3642*t3762 + t3866*t3931 + t4111*t4167 + t4206*t4218 + t4301*t4308 + t4334*t4397 + 0.0306*(t4267*t4308 + t4234*t4397) - 1.1312*(t4234*t4308 - 1.*t4267*t4397) + t1986*t2792*t719 + t3050*t719 - 1.*t3031*t3238*t719; p_output1(1)=0. + 0.135*(1. - 1.*t4538) + t2930*t3050*t4538 + t4538*t4678 - 1.*t4708*t4734 + t2792*t4770 + t3238*t4815 + t3642*t4840 + t3866*t4883 + t4111*t4928 + t4206*t4966 + t4301*t5002 + t4334*t5035 + 0.0306*(t4267*t5002 + t4234*t5035) - 1.1312*(t4234*t5002 - 1.*t4267*t5035) + 0.1305*t4538*t719; p_output1(2)=0.07996 - 0.135*t4708 + t2930*t3050*t4708 + t4678*t4708 + t4538*t4734 + t2792*t5171 + t3238*t5192 + t3642*t5223 + t3866*t5237 + t4111*t5251 + t4206*t5270 + t4301*t5282 + t4334*t5294 + 0.0306*(t4267*t5282 + t4234*t5294) - 1.1312*(t4234*t5282 - 1.*t4267*t5294) + 0.1305*t4708*t719; } Eigen::Matrix<double,3,1> p_VectorNav_to_LeftToeBottom(const Eigen::Matrix<double,14,1> &var1) //void p_VectorNav_to_LeftToeBottom(Eigen::Matrix<double,3,1> &p_output1, const Eigen::Matrix<double,14,1> &var1) { /* Call Subroutines */ Eigen::Matrix<double,3,1> p_output1; output1(p_output1, var1); return p_output1; }
24.46789
302
0.648919
UMich-BipedLab
a07a80b46816c1985521c15c05f81b3e980c341c
48,255
cc
C++
CryoMEM/cacti/old_src/uca.cc
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
2
2021-05-26T12:32:46.000Z
2021-12-15T13:10:37.000Z
CryoMEM/cacti/old_src/uca.cc
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
1
2022-03-02T01:49:20.000Z
2022-03-18T10:37:59.000Z
CryoMEM/cacti/old_src/uca.cc
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
null
null
null
/***************************************************************************** * CACTI 7.0 * SOFTWARE LICENSE AGREEMENT * Copyright 2015 Hewlett-Packard Development Company, L.P. * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.” * ***************************************************************************/ #include <iostream> #include <math.h> #include "uca.h" #include "TSV.h" #include "memorybus.h" UCA::UCA(const DynamicParameter& dyn_p) : dp(dyn_p), bank(dp), nbanks(g_ip->nbanks), refresh_power(0) { int num_banks_ver_dir = 1 << ((bank.area.h > bank.area.w) ? _log2(nbanks) / 2 : (_log2(nbanks) - _log2(nbanks) / 2)); int num_banks_hor_dir = nbanks / num_banks_ver_dir; if (dp.use_inp_params) { RWP = dp.num_rw_ports; ERP = dp.num_rd_ports; EWP = dp.num_wr_ports; SCHP = dp.num_search_ports; } else { RWP = g_ip->num_rw_ports; ERP = g_ip->num_rd_ports; EWP = g_ip->num_wr_ports; SCHP = g_ip->num_search_ports; } num_addr_b_bank = (dp.number_addr_bits_mat + dp.number_subbanks_decode) * (RWP + ERP + EWP); num_di_b_bank = dp.num_di_b_bank_per_port * (RWP + EWP); num_do_b_bank = dp.num_do_b_bank_per_port * (RWP + ERP); num_si_b_bank = dp.num_si_b_bank_per_port * SCHP; num_so_b_bank = dp.num_so_b_bank_per_port * SCHP; if (!dp.fully_assoc && !dp.pure_cam) { if (g_ip->fast_access && dp.is_tag == false) { num_do_b_bank *= g_ip->data_assoc; } htree_in_add = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, 0, num_do_b_bank, 0, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Add_htree, true); htree_in_data = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, 0, num_do_b_bank, 0, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Data_in_htree, true); htree_out_data = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, 0, num_do_b_bank, 0, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Data_out_htree, true); } else { htree_in_add = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, num_si_b_bank, num_do_b_bank, num_so_b_bank, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Add_htree, true); htree_in_data = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, num_si_b_bank, num_do_b_bank, num_so_b_bank, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Data_in_htree, true); htree_out_data = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, num_si_b_bank, num_do_b_bank, num_so_b_bank, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Data_out_htree, true); htree_in_search = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, num_si_b_bank, num_do_b_bank, num_so_b_bank, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Data_in_htree, true); htree_out_search = new Htree2( g_ip->wt, bank.area.w, bank.area.h, num_addr_b_bank, num_di_b_bank, num_si_b_bank, num_do_b_bank, num_so_b_bank, num_banks_ver_dir * 2, num_banks_hor_dir * 2, Data_out_htree, true); } area.w = htree_in_data->area.w; area.h = htree_in_data->area.h; area_all_dataramcells = bank.mat.subarray.get_total_cell_area() * dp.num_subarrays * g_ip->nbanks; // cout<<"area cell"<<area_all_dataramcells<<endl; // cout<<area.get_area()<<endl; if (g_ip->print_detail_debug) cout << "uca.cc: g_ip->is_3d_mem = " << g_ip->is_3d_mem << endl; if (g_ip->is_3d_mem) { membus_RAS = new Memorybus( g_ip->wt, bank.mat.area.w, bank.mat.area.h, bank.mat.subarray.area.w, bank.mat.subarray.area.h, _log2(dp.num_r_subarray * dp.Ndbl), _log2(dp.num_c_subarray * dp.Ndwl), g_ip->burst_depth * g_ip->io_width, dp.Ndbl, dp.Ndwl, Row_add_path, dp); membus_CAS = new Memorybus( g_ip->wt, bank.mat.area.w, bank.mat.area.h, bank.mat.subarray.area.w, bank.mat.subarray.area.h, _log2(dp.num_r_subarray * dp.Ndbl), _log2(dp.num_c_subarray * dp.Ndwl), g_ip->burst_depth * g_ip->io_width, dp.Ndbl, dp.Ndwl, Col_add_path, dp); membus_data = new Memorybus( g_ip->wt, bank.mat.area.w, bank.mat.area.h, bank.mat.subarray.area.w, bank.mat.subarray.area.h, _log2(dp.num_r_subarray * dp.Ndbl), _log2(dp.num_c_subarray * dp.Ndwl), g_ip->burst_depth * g_ip->io_width, dp.Ndbl, dp.Ndwl, Data_path, dp); area.h = membus_RAS->area.h; area.w = membus_RAS->area.w; if (g_ip->print_detail_debug) { cout << "uca.cc: area.h = " << area.h / 1e3 << " mm" << endl; cout << "uca.cc: area.w = " << area.w / 1e3 << " mm" << endl; cout << "uca.cc: bank.area.h = " << bank.area.h / 1e3 << " mm" << endl; cout << "uca.cc: bank.area.w = " << bank.area.w / 1e3 << " mm" << endl; cout << "uca.cc: bank.mat.area.h = " << bank.mat.area.h / 1e3 << " mm" << endl; cout << "uca.cc: bank.mat.area.w = " << bank.mat.area.w / 1e3 << " mm" << endl; cout << "uca.cc: bank.mat.subarray.area.h = " << bank.mat.subarray.area.h / 1e3 << " mm" << endl; cout << "uca.cc: bank.mat.subarray.area.w = " << bank.mat.subarray.area.w / 1e3 << " mm" << endl; cout << "uca.cc: dp.num_subarrays = " << dp.num_subarrays << endl; // cout<<"uca.cc: area_all_dataramcells: "<<area_all_dataramcells/1e6<<" mm2"<<endl; //****************** Final results for output **************** cout << "uca.cc: area efficiency = " << area_all_dataramcells / (area.w * area.h) * 100 << " %" << endl; // cout<<area.get_area()<<endl; cout << "uca.cc: area = " << area.get_area() / 1e6 << " mm2" << endl; } } // delay calculation double inrisetime = 0.0; compute_delays(inrisetime); compute_power_energy(); if (g_ip->is_3d_mem) { // Add TSV delay to the terms // --- Although there are coarse and fine, because is_array and os_bank TSV are the same, so they are the same TSV tsv_os_bank(Coarse); TSV tsv_is_subarray(Fine); if (g_ip->print_detail_debug) { tsv_os_bank.print_TSV(); tsv_is_subarray.print_TSV(); } comm_bits = 6; row_add_bits = _log2(dp.num_r_subarray * dp.Ndbl); col_add_bits = _log2(dp.num_c_subarray * dp.Ndwl); data_bits = g_ip->burst_depth * g_ip->io_width; // enum Part_grain part_gran = Fine_rank_level; double redundancy_perc_TSV = 0.5; switch (g_ip->partition_gran) { case 0: // Coarse_rank_level: delay_TSV_tot = (g_ip->num_die_3d - 1) * tsv_os_bank.delay; num_TSV_tot = (comm_bits + row_add_bits + col_add_bits + data_bits * 2) * (1 + redundancy_perc_TSV); //* (g_ip->nbanks/4) area_TSV_tot = num_TSV_tot * tsv_os_bank.area.get_area(); dyn_pow_TSV_tot = num_TSV_tot * (g_ip->num_die_3d - 1) * tsv_os_bank.power.readOp.dynamic; dyn_pow_TSV_per_access = (comm_bits + row_add_bits + col_add_bits + data_bits) * (g_ip->num_die_3d - 1) * tsv_os_bank.power.readOp.dynamic; area_address_bus = membus_RAS->area_address_bus * (1.0 + (double)comm_bits / (double)(row_add_bits + col_add_bits)); area_data_bus = membus_RAS->area_data_bus; break; case 1: // Fine_rank_level: delay_TSV_tot = (g_ip->num_die_3d) * tsv_os_bank.delay; num_TSV_tot = (comm_bits + row_add_bits + col_add_bits + data_bits / 2) * g_ip->nbanks * (1 + redundancy_perc_TSV); area_TSV_tot = num_TSV_tot * tsv_os_bank.area.get_area(); dyn_pow_TSV_tot = num_TSV_tot * (g_ip->num_die_3d) * tsv_os_bank.power.readOp.dynamic; dyn_pow_TSV_per_access = (comm_bits + row_add_bits + col_add_bits + data_bits) * (g_ip->num_die_3d) * tsv_os_bank.power.readOp.dynamic; // area_address_bus = (comm_bits + row_add_bits + col_add_bits) * 25.0; // area_data_bus = membus_RAS->area_data_bus + (double)data_bits/2 * 25.0; break; case 2: // Coarse_bank_level: delay_TSV_tot = (g_ip->num_die_3d) * tsv_os_bank.delay; num_TSV_tot = (comm_bits + row_add_bits + col_add_bits + data_bits / 2) * g_ip->nbanks * g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd * (1 + redundancy_perc_TSV); area_TSV_tot = num_TSV_tot * tsv_os_bank.area.get_area(); dyn_pow_TSV_tot = num_TSV_tot * (g_ip->num_die_3d) * tsv_os_bank.power.readOp.dynamic; dyn_pow_TSV_per_access = (comm_bits + row_add_bits + col_add_bits + data_bits) * (g_ip->num_die_3d) * tsv_os_bank.power.readOp.dynamic; // area_address_bus = (comm_bits + row_add_bits + col_add_bits) * 25.0; // area_data_bus = (double)data_bits/2 * 25.0; // activate_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; // read_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; // write_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; // precharge_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; break; case 3: // Fine_bank_level: delay_TSV_tot = (g_ip->num_die_3d) * tsv_os_bank.delay; num_TSV_tot = (comm_bits + row_add_bits + col_add_bits + data_bits) * g_ip->nbanks * g_ip->ndwl * g_ip->ndbl / g_ip->num_tier_col_sprd / g_ip->num_tier_row_sprd * (1 + redundancy_perc_TSV); area_TSV_tot = num_TSV_tot * tsv_os_bank.area.get_area(); dyn_pow_TSV_tot = num_TSV_tot * (g_ip->num_die_3d) * tsv_os_bank.power.readOp.dynamic; dyn_pow_TSV_per_access = (comm_bits + row_add_bits + col_add_bits + data_bits) * (g_ip->num_die_3d) * tsv_os_bank.power.readOp.dynamic; // area_address_bus = pow(2, (comm_bits + row_add_bits + col_add_bits)) * 25.0; // area_data_bus = pow(2, data_bits/2) * 25.0; // activate_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; // read_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; // write_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; // precharge_energy *= g_ip->num_tier_row_sprd * g_ip->num_tier_col_sprd; break; default: assert(0); break; } if (g_ip->print_detail_debug) { cout << "uca.cc: num_TSV_tot = " << num_TSV_tot << endl; } area_lwl_drv = membus_RAS->area_lwl_drv * g_ip->nbanks; area_row_predec_dec = membus_RAS->area_row_predec_dec * g_ip->nbanks; area_col_predec_dec = membus_CAS->area_col_predec_dec * g_ip->nbanks; area_subarray = membus_RAS->area_subarray * g_ip->nbanks; area_bus = membus_RAS->area_bus * g_ip->nbanks; area_data_drv = membus_data->area_data_drv * g_ip->nbanks; area_IOSA = membus_data->area_IOSA * g_ip->nbanks; area_sense_amp = membus_data->area_sense_amp * g_ip->nbanks; area_address_bus = membus_RAS->area_address_bus * (1.0 + (double)comm_bits / (double)(row_add_bits + col_add_bits)) * g_ip->nbanks; ; area_data_bus = membus_RAS->area_data_bus + membus_data->area_local_dataline * g_ip->nbanks; area_per_bank = (area_lwl_drv + area_row_predec_dec + area_col_predec_dec + area_subarray + area_bus + area_data_drv + area_IOSA + area_address_bus + area_data_bus) / g_ip->nbanks + area_sense_amp; t_RCD += delay_TSV_tot; t_RAS += delay_TSV_tot; t_RC += delay_TSV_tot; t_RP += delay_TSV_tot; t_CAS += 2 * delay_TSV_tot; t_RRD += delay_TSV_tot; activate_energy += dyn_pow_TSV_per_access; read_energy += dyn_pow_TSV_per_access; write_energy += dyn_pow_TSV_per_access; precharge_energy += dyn_pow_TSV_per_access; // double area_per_die = area.get_area(); // double area_stack_tot = g_ip->num_die_3d * (area.get_area() + area_TSV_tot); // int num_die = g_ip->num_die_3d; // area.set_area(area_stack_tot); if (g_ip->num_die_3d > 1 || g_ip->partition_gran > 0) total_area_per_die = area_all_dataramcells + area_TSV_tot; else total_area_per_die = area_all_dataramcells; if (g_ip->is_3d_mem && g_ip->print_detail_debug) { cout << "------- CACTI 3D DRAM Main Memory -------" << endl; cout << "\nMemory Parameters:\n"; cout << " Total memory size (Gb): " << (int)(g_ip->cache_sz) << endl; cout << " Number of banks: " << (int)g_ip->nbanks << endl; cout << " Technology size (nm): " << g_ip->F_sz_nm << endl; cout << " Page size (bits): " << g_ip->page_sz_bits << endl; cout << " Burst depth: " << g_ip->burst_depth << endl; cout << " Chip IO width: " << g_ip->io_width << endl; cout << " Ndwl: " << dp.Ndwl << endl; cout << " Ndbl: " << dp.Ndbl << endl; cout << " # rows in subarray: " << dp.num_r_subarray << endl; cout << " # columns in subarray: " << dp.num_c_subarray << endl; cout << "\nResults:\n"; cout << " ******************Timing terms******************" << endl; cout << " t_RCD (Row to Column command Delay): " << t_RCD * 1e9 << " ns" << endl; cout << " t_RAS (Row Access Strobe latency): " << t_RAS * 1e9 << " ns" << endl; cout << " t_RC (Row Cycle): " << t_RC * 1e9 << " ns" << endl; cout << " t_CAS (Column Access Strobe latency): " << t_CAS * 1e9 << " ns" << endl; cout << " t_RP (Row Precharge latency): " << t_RP * 1e9 << " ns" << endl; // cout<<" t_RRD (Row activation to Row activation Delay): "<<t_RRD * 1e9 << " ns"<<endl; cout << " *******************Power terms******************" << endl; cout << " Activation energy: " << activate_energy * 1e9 << " nJ" << endl; cout << " Read energy: " << read_energy * 1e9 << " nJ" << endl; cout << " Write energy: " << write_energy * 1e9 << " nJ" << endl; // cout<<" Precharge energy: "<<precharge_energy * 1e9 << " nJ" <<endl; cout << " Activation power: " << activate_power * 1e3 << " mW" << endl; cout << " Read power: " << read_power * 1e3 << " mW" << endl; cout << " Write power: " << write_power * 1e3 << " mW" << endl; // cout<<" Peak read power: "<< read_energy/((g_ip->burst_depth)/(g_ip->sys_freq_MHz*1e6)/2) * 1e3 << " mW" <<endl; cout << " ********************Area terms******************" << endl; // cout<<" Height: "<<area.h/1e3<<" mm"<<endl; // cout<<" Length: "<<area.w/1e3<<" mm"<<endl; cout << " DRAM+peri Area: " << area.get_area() / 1e6 << " mm2" << endl; // cout<<" Area efficiency: "<<area_all_dataramcells/area.get_area()*100 <<" %"<<endl; cout << " Total Area: " << total_area_per_die / 1e6 / 0.5 << " mm2" << endl; if (g_ip->print_detail_debug) { cout << " ********************Other terms******************" << endl; double act_bus_energy = membus_RAS->center_stripe->power.readOp.dynamic + membus_RAS->bank_bus->power.readOp.dynamic + membus_RAS->add_predec->power.readOp.dynamic + membus_RAS->add_dec->power.readOp.dynamic; cout << " Act Bus Energy: " << act_bus_energy * 1e9 << " nJ" << endl; cout << " Act Bank Energy: " << (activate_energy - act_bus_energy) * 1e9 << " nJ" << endl; double act_bus_latency = membus_RAS->center_stripe->delay + membus_RAS->bank_bus->delay + membus_RAS->add_predec->delay + membus_RAS->add_dec->delay; cout << " Act Bus Latency: " << act_bus_latency * 1e9 << " ns" << endl; cout << " Act Bank Latency: " << (t_RCD - act_bus_latency) * 1e9 << " ns" << endl; cout << " activate_energy: " << activate_energy * 1e9 << " nJ" << endl; } if (g_ip->num_die_3d > 1) { cout << " ********************TSV terms******************" << endl; cout << " TSV area overhead: " << area_TSV_tot / 1e6 << " mm2" << endl; cout << " TSV latency overhead: " << delay_TSV_tot * 1e9 << " ns" << endl; cout << " TSV energy overhead per access: " << dyn_pow_TSV_per_access * 1e9 << " nJ" << endl; } cout << endl << endl << endl; } } } UCA::~UCA() { delete htree_in_add; delete htree_in_data; delete htree_out_data; if (g_ip->is_3d_mem) { delete membus_RAS; delete membus_CAS; delete membus_data; } } double UCA::compute_delays(double inrisetime) { double outrisetime = bank.compute_delays(inrisetime); // CACTI3DD if (g_ip->is_3d_mem) { outrisetime = bank.compute_delays(membus_RAS->out_rise_time); // ram_delay_inside_mat = bank.mat.delay_bitline;// + bank.mat.delay_matchchline; // access_time = membus_RAS->delay + bank.mat.delay_bitline + bank.mat.delay_sa + membus_CAS->delay + membus_data->delay; // double t_rcd = membus_RAS->delay + bank.mat.delay_bitline + bank.mat.delay_sa; // t_RCD= membus_RAS->add_dec->delay + membus_RAS->lwl_drv->delay + bank.mat.delay_bitline + bank.mat.delay_sa; t_RCD = membus_RAS->add_dec->delay + membus_RAS->lwl_drv->delay + bank.mat.delay_bitline + bank.mat.delay_sa; t_RAS = membus_RAS->delay + bank.mat.delay_bitline + bank.mat.delay_sa + bank.mat.delay_bl_restore; precharge_delay = bank.mat.delay_writeback + bank.mat.delay_wl_reset + bank.mat.delay_bl_restore; t_RP = precharge_delay; t_RC = t_RAS + t_RP; t_CAS = membus_CAS->delay + bank.mat.delay_subarray_out_drv + membus_data->delay; t_RRD = membus_RAS->center_stripe->delay + membus_RAS->bank_bus->delay; // t_RRD = membus_RAS->delay; access_time = t_RCD + t_CAS; multisubbank_interleave_cycle_time = membus_RAS->center_stripe->delay + membus_RAS->bank_bus->delay; // cout<<"uca.cc: multisubbank_interleave_cycle_time = "<<multisubbank_interleave_cycle_time<<endl; cycle_time = t_RC + precharge_delay; // cout<<"uca.cc: cycle_time = "<<cycle_time<<endl; outrisetime = t_RCD / (1.0 - 0.5); // correct? if (g_ip->print_detail_debug) { cout << endl << "Network delays: " << endl; cout << "uca.cc: membus_RAS->delay = " << membus_RAS->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_CAS->delay = " << membus_CAS->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_data->delay = " << membus_data->delay * 1e9 << " ns" << endl; cout << "Row Address Delay components: " << endl; cout << "uca.cc: membus_RAS->center_stripe->delay = " << membus_RAS->center_stripe->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_RAS->bank_bus->delay = " << membus_RAS->bank_bus->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_RAS->add_predec->delay = " << membus_RAS->add_predec->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_RAS->add_dec->delay = " << membus_RAS->add_dec->delay * 1e9 << " ns" << endl; // cout<<"uca.cc: membus_RAS->global_WL->delay = "<<membus_RAS->global_WL->delay * 1e9 << " ns" <<endl; cout << "uca.cc: membus_RAS->lwl_drv->delay = " << membus_RAS->lwl_drv->delay * 1e9 << " ns" << endl; cout << "Bank Delay components: " << endl; cout << "uca.cc: bank.mat.delay_bitline = " << bank.mat.delay_bitline * 1e9 << " ns" << endl; cout << "uca.cc: bank.mat.delay_sa = " << bank.mat.delay_sa * 1e9 << " ns" << endl; cout << "Column Address Delay components: " << endl; // cout<<"uca.cc: membus_CAS->center_stripe->delay = "<<membus_CAS->center_stripe->delay * 1e9 << " ns" <<endl; cout << "uca.cc: membus_CAS->bank_bus->delay = " << membus_CAS->bank_bus->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_CAS->add_predec->delay = " << membus_CAS->add_predec->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_CAS->add_dec->delay = " << membus_CAS->add_dec->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_CAS->column_sel->delay = " << membus_CAS->column_sel->delay * 1e9 << " ns" << endl; cout << "Data IO Path Delay components: " << endl; cout << "uca.cc: bank.mat.delay_subarray_out_drv = " << bank.mat.delay_subarray_out_drv * 1e9 << " ns" << endl; // cout<<"uca.cc: membus_data->center_stripe->delay = "<<membus_data->center_stripe->delay * 1e9 << " ns" <<endl; cout << "uca.cc: membus_data->bank_bus->delay = " << membus_data->bank_bus->delay * 1e9 << " ns" << endl; cout << "uca.cc: membus_data->global_data->delay = " << membus_data->global_data->delay * 1e9 << " ns" << endl; // cout<<"uca.cc: membus_data->data_drv->delay = "<<membus_data->data_drv->delay * 1e9 << " ns" <<endl; cout << "uca.cc: membus_data->local_data->delay = " << membus_data->local_data->delay * 1e9 << " ns" << endl; cout << "Bank precharge/restore delay components: " << endl; cout << "uca.cc: bank.mat.delay_bl_restore = " << bank.mat.delay_bl_restore * 1e9 << " ns" << endl; cout << "General delay components: " << endl; cout << "uca.cc: t_RCD = " << t_RCD * 1e9 << " ns" << endl; cout << "uca.cc: t_RAS = " << t_RAS * 1e9 << " ns" << endl; cout << "uca.cc: t_RC = " << t_RC * 1e9 << " ns" << endl; cout << "uca.cc: t_CAS = " << t_CAS * 1e9 << " ns" << endl; cout << "uca.cc: t_RRD = " << t_RRD * 1e9 << " ns" << endl; cout << "uca.cc: access_time = " << access_time * 1e9 << " ns" << endl; } } // CACTI3DD else { double delay_array_to_mat = htree_in_add->delay + bank.htree_in_add->delay; double max_delay_before_row_decoder = delay_array_to_mat + bank.mat.r_predec->delay; delay_array_to_sa_mux_lev_1_decoder = delay_array_to_mat + bank.mat.sa_mux_lev_1_predec->delay + bank.mat.sa_mux_lev_1_dec->delay; delay_array_to_sa_mux_lev_2_decoder = delay_array_to_mat + bank.mat.sa_mux_lev_2_predec->delay + bank.mat.sa_mux_lev_2_dec->delay; double delay_inside_mat = bank.mat.row_dec->delay + bank.mat.delay_bitline + bank.mat.delay_sa; delay_before_subarray_output_driver = MAX( MAX(max_delay_before_row_decoder + delay_inside_mat, // row_path delay_array_to_mat + bank.mat.b_mux_predec->delay + bank.mat.bit_mux_dec->delay + bank.mat.delay_sa), // col_path MAX(delay_array_to_sa_mux_lev_1_decoder, // sa_mux_lev_1_path delay_array_to_sa_mux_lev_2_decoder)); // sa_mux_lev_2_path delay_from_subarray_out_drv_to_out = bank.mat.delay_subarray_out_drv_htree + bank.htree_out_data->delay + htree_out_data->delay; access_time = bank.mat.delay_comparator; double ram_delay_inside_mat; if (dp.fully_assoc) { // delay of FA contains both CAM tag and RAM data { // delay of CAM ram_delay_inside_mat = bank.mat.delay_bitline + bank.mat.delay_matchchline; access_time = htree_in_add->delay + bank.htree_in_add->delay; // delay of fully-associative data array access_time += ram_delay_inside_mat + delay_from_subarray_out_drv_to_out; } } else { access_time = delay_before_subarray_output_driver + delay_from_subarray_out_drv_to_out; // data_acc_path } if (dp.is_main_mem) { double t_rcd = max_delay_before_row_decoder + delay_inside_mat; double cas_latency = MAX(delay_array_to_sa_mux_lev_1_decoder, delay_array_to_sa_mux_lev_2_decoder) + delay_from_subarray_out_drv_to_out; access_time = t_rcd + cas_latency; } double temp; if (!dp.fully_assoc) { temp = delay_inside_mat + bank.mat.delay_wl_reset + bank.mat.delay_bl_restore; // TODO: : revisit if (dp.is_dram) { temp += bank.mat.delay_writeback; // temp stores random cycle time } temp = MAX(temp, bank.mat.r_predec->delay); temp = MAX(temp, bank.mat.b_mux_predec->delay); temp = MAX(temp, bank.mat.sa_mux_lev_1_predec->delay); temp = MAX(temp, bank.mat.sa_mux_lev_2_predec->delay); } else { ram_delay_inside_mat = bank.mat.delay_bitline + bank.mat.delay_matchchline; temp = ram_delay_inside_mat + bank.mat.delay_cam_sl_restore + bank.mat.delay_cam_ml_reset + bank.mat.delay_bl_restore + bank.mat.delay_hit_miss_reset + bank.mat.delay_wl_reset; temp = MAX(temp, bank.mat.b_mux_predec->delay); // TODO: revisit whether distinguish cam and ram bitline etc. temp = MAX(temp, bank.mat.sa_mux_lev_1_predec->delay); temp = MAX(temp, bank.mat.sa_mux_lev_2_predec->delay); } // The following is true only if the input parameter "repeaters_in_htree" is set to false --Nav if (g_ip->rpters_in_htree == false) { temp = MAX(temp, bank.htree_in_add->max_unpipelined_link_delay); } cycle_time = temp; double delay_req_network = max_delay_before_row_decoder; double delay_rep_network = delay_from_subarray_out_drv_to_out; multisubbank_interleave_cycle_time = MAX(delay_req_network, delay_rep_network); if (dp.is_main_mem) { multisubbank_interleave_cycle_time = htree_in_add->delay; precharge_delay = htree_in_add->delay + bank.htree_in_add->delay + bank.mat.delay_writeback + bank.mat.delay_wl_reset + bank.mat.delay_bl_restore; cycle_time = access_time + precharge_delay; } else { precharge_delay = 0; } /** double dram_array_availability = 0; if (dp.is_dram) { dram_array_availability = (1 - dp.num_r_subarray * cycle_time / dp.dram_refresh_period) * 100; } **/ } // CACTI3DD, else return outrisetime; } // note: currently, power numbers are for a bank of an array void UCA::compute_power_energy() { bank.compute_power_energy(); power = bank.power; // CACTI3DD if (g_ip->is_3d_mem) { double datapath_energy = 0.505e-9 * g_ip->F_sz_nm / 55; // double chip_IO_width = 4; // g_ip->burst_len = 4; activate_energy = membus_RAS->power.readOp.dynamic + (bank.mat.power_bitline.readOp.dynamic + bank.mat.power_sa.readOp.dynamic) * dp.Ndwl; // /4 read_energy = (membus_CAS->power.readOp.dynamic + bank.mat.power_subarray_out_drv.readOp.dynamic + membus_data->power.readOp.dynamic) + datapath_energy; //* g_ip->burst_len; write_energy = (membus_CAS->power.readOp.dynamic + bank.mat.power_subarray_out_drv.readOp.dynamic + membus_data->power.readOp.dynamic + bank.mat.power_sa.readOp.dynamic * g_ip->burst_depth * g_ip->io_width / g_ip->page_sz_bits) + datapath_energy; //* g_ip->burst_len; precharge_energy = (bank.mat.power_bitline.readOp.dynamic + bank.mat.power_bl_precharge_eq_drv.readOp.dynamic) * dp.Ndwl; // /4 activate_power = activate_energy / t_RC; double col_cycle_act_row; // col_cycle_act_row = MAX(MAX(MAX(membus_CAS->center_stripe->delay + membus_CAS->bank_bus->delay, bank.mat.delay_subarray_out_drv), // membus_data->delay), membus_data->out_seg->delay *g_ip->burst_depth); // col_cycle_act_row = membus_data->out_seg->delay * g_ip->burst_depth; col_cycle_act_row = (1e-6 / (double)g_ip->sys_freq_MHz) / 2 * g_ip->burst_depth; //--- Activity factor assumption comes from Micron data spreadsheet. read_power = 0.25 * read_energy / col_cycle_act_row; write_power = 0.15 * write_energy / col_cycle_act_row; if (g_ip->print_detail_debug) { cout << "Row Address Delay components: " << endl; cout << "Row Address Delay components: " << endl; cout << "Network power terms: " << endl; cout << "uca.cc: membus_RAS->power.readOp.dynamic = " << membus_RAS->power.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_CAS->power.readOp.dynamic = " << membus_CAS->power.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_data->power.readOp.dynamic = " << membus_data->power.readOp.dynamic * 1e9 << " nJ" << endl; cout << "Row Address Power components: " << endl; cout << "uca.cc: membus_RAS->power_bus.readOp.dynamic = " << membus_RAS->power_bus.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_RAS->power_add_predecoder.readOp.dynamic = " << membus_RAS->power_add_predecoder.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_RAS->power_add_decoders.readOp.dynamic = " << membus_RAS->power_add_decoders.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_RAS->power_lwl_drv.readOp.dynamic = " << membus_RAS->power_lwl_drv.readOp.dynamic * 1e9 << " nJ" << endl; cout << "Bank Power components: " << endl; cout << "uca.cc: bank.mat.power_bitline = " << bank.mat.power_bitline.readOp.dynamic * dp.Ndwl * 1e9 << " nJ" << endl; cout << "uca.cc: bank.mat.power_sa = " << bank.mat.power_sa.readOp.dynamic * dp.Ndwl * 1e9 << " nJ" << endl; cout << "Column Address Power components: " << endl; cout << "uca.cc: membus_CAS->power_bus.readOp.dynamic = " << membus_CAS->power_bus.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_CAS->power_add_predecoder.readOp.dynamic = " << membus_CAS->power_add_predecoder.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_CAS->power_add_decoders.readOp.dynamic = " << membus_CAS->power_add_decoders.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_CAS->power.readOp.dynamic = " << membus_CAS->power.readOp.dynamic * 1e9 << " nJ" << endl; cout << "Data Path Power components: " << endl; cout << "uca.cc: bank.mat.power_subarray_out_drv.readOp.dynamic = " << bank.mat.power_subarray_out_drv.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: membus_data->power.readOp.dynamic = " << membus_data->power.readOp.dynamic * 1e9 << " nJ" << endl; cout << "uca.cc: bank.mat.power_sa = " << bank.mat.power_sa.readOp.dynamic * g_ip->burst_depth * g_ip->io_width / g_ip->page_sz_bits * 1e9 << " nJ" << endl; //****************** Final results for output **************** cout << "General Power components: " << endl; cout << "uca.cc: activate_energy = " << activate_energy * 1e9 << " nJ" << endl; cout << "uca.cc: read_energy = " << read_energy * 1e9 << " nJ" << endl; cout << "uca.cc: write_energy = " << write_energy * 1e9 << " nJ" << endl; cout << "uca.cc: precharge_energy = " << precharge_energy * 1e9 << " nJ" << endl; cout << "uca.cc: activate_power = " << activate_power * 1e3 << " mW" << endl; cout << "uca.cc: read_power = " << read_power * 1e3 << " mW" << endl; cout << "uca.cc: write_power = " << write_power * 1e3 << " mW" << endl; } } // CACTI3DD else { power_routing_to_bank.readOp.dynamic = htree_in_add->power.readOp.dynamic + htree_out_data->power.readOp.dynamic; power_routing_to_bank.writeOp.dynamic = htree_in_add->power.readOp.dynamic + htree_in_data->power.readOp.dynamic; if (dp.fully_assoc || dp.pure_cam) power_routing_to_bank.searchOp.dynamic = htree_in_search->power.searchOp.dynamic + htree_out_search->power.searchOp.dynamic; power_routing_to_bank.readOp.leakage += htree_in_add->power.readOp.leakage + htree_in_data->power.readOp.leakage + htree_out_data->power.readOp.leakage; power_routing_to_bank.readOp.gate_leakage += htree_in_add->power.readOp.gate_leakage + htree_in_data->power.readOp.gate_leakage + htree_out_data->power.readOp.gate_leakage; if (dp.fully_assoc || dp.pure_cam) { power_routing_to_bank.readOp.leakage += htree_in_search->power.readOp.leakage + htree_out_search->power.readOp.leakage; power_routing_to_bank.readOp.gate_leakage += htree_in_search->power.readOp.gate_leakage + htree_out_search->power.readOp.gate_leakage; } power.searchOp.dynamic += power_routing_to_bank.searchOp.dynamic; power.readOp.dynamic += power_routing_to_bank.readOp.dynamic; power.readOp.leakage += power_routing_to_bank.readOp.leakage; power.readOp.gate_leakage += power_routing_to_bank.readOp.gate_leakage; // calculate total write energy per access power.writeOp.dynamic = power.readOp.dynamic - bank.mat.power_bitline.readOp.dynamic * dp.num_act_mats_hor_dir + bank.mat.power_bitline.writeOp.dynamic * dp.num_act_mats_hor_dir - power_routing_to_bank.readOp.dynamic + power_routing_to_bank.writeOp.dynamic + bank.htree_in_data->power.readOp.dynamic - bank.htree_out_data->power.readOp.dynamic; if (dp.is_dram == false) { power.writeOp.dynamic -= bank.mat.power_sa.readOp.dynamic * dp.num_act_mats_hor_dir; } dyn_read_energy_from_closed_page = power.readOp.dynamic; dyn_read_energy_from_open_page = power.readOp.dynamic - (bank.mat.r_predec->power.readOp.dynamic + bank.mat.power_row_decoders.readOp.dynamic + bank.mat.power_bl_precharge_eq_drv.readOp.dynamic + bank.mat.power_sa.readOp.dynamic + bank.mat.power_bitline.readOp.dynamic) * dp.num_act_mats_hor_dir; dyn_read_energy_remaining_words_in_burst = (MAX((g_ip->burst_len / g_ip->int_prefetch_w), 1) - 1) * ((bank.mat.sa_mux_lev_1_predec->power.readOp.dynamic + bank.mat.sa_mux_lev_2_predec->power.readOp.dynamic + bank.mat.power_sa_mux_lev_1_decoders.readOp.dynamic + bank.mat.power_sa_mux_lev_2_decoders.readOp.dynamic + bank.mat.power_subarray_out_drv.readOp.dynamic) * dp.num_act_mats_hor_dir + bank.htree_out_data->power.readOp.dynamic + power_routing_to_bank.readOp.dynamic); dyn_read_energy_from_closed_page += dyn_read_energy_remaining_words_in_burst; dyn_read_energy_from_open_page += dyn_read_energy_remaining_words_in_burst; activate_energy = htree_in_add->power.readOp.dynamic + bank.htree_in_add->power_bit.readOp.dynamic * bank.num_addr_b_routed_to_mat_for_act + (bank.mat.r_predec->power.readOp.dynamic + bank.mat.power_row_decoders.readOp.dynamic + bank.mat.power_sa.readOp.dynamic) * dp.num_act_mats_hor_dir; read_energy = (htree_in_add->power.readOp.dynamic + bank.htree_in_add->power_bit.readOp.dynamic * bank.num_addr_b_routed_to_mat_for_rd_or_wr + (bank.mat.sa_mux_lev_1_predec->power.readOp.dynamic + bank.mat.sa_mux_lev_2_predec->power.readOp.dynamic + bank.mat.power_sa_mux_lev_1_decoders.readOp.dynamic + bank.mat.power_sa_mux_lev_2_decoders.readOp.dynamic + bank.mat.power_subarray_out_drv.readOp.dynamic) * dp.num_act_mats_hor_dir + bank.htree_out_data->power.readOp.dynamic + htree_in_data->power.readOp.dynamic) * g_ip->burst_len; write_energy = (htree_in_add->power.readOp.dynamic + bank.htree_in_add->power_bit.readOp.dynamic * bank.num_addr_b_routed_to_mat_for_rd_or_wr + htree_in_data->power.readOp.dynamic + bank.htree_in_data->power.readOp.dynamic + (bank.mat.sa_mux_lev_1_predec->power.readOp.dynamic + bank.mat.sa_mux_lev_2_predec->power.readOp.dynamic + bank.mat.power_sa_mux_lev_1_decoders.readOp.dynamic + bank.mat.power_sa_mux_lev_2_decoders.readOp.dynamic) * dp.num_act_mats_hor_dir) * g_ip->burst_len; precharge_energy = (bank.mat.power_bitline.readOp.dynamic + bank.mat.power_bl_precharge_eq_drv.readOp.dynamic) * dp.num_act_mats_hor_dir; } // CACTI3DD leak_power_subbank_closed_page = (bank.mat.r_predec->power.readOp.leakage + bank.mat.b_mux_predec->power.readOp.leakage + bank.mat.sa_mux_lev_1_predec->power.readOp.leakage + bank.mat.sa_mux_lev_2_predec->power.readOp.leakage + bank.mat.power_row_decoders.readOp.leakage + bank.mat.power_bit_mux_decoders.readOp.leakage + bank.mat.power_sa_mux_lev_1_decoders.readOp.leakage + bank.mat.power_sa_mux_lev_2_decoders.readOp.leakage + bank.mat.leak_power_sense_amps_closed_page_state) * dp.num_act_mats_hor_dir; leak_power_subbank_closed_page += (bank.mat.r_predec->power.readOp.gate_leakage + bank.mat.b_mux_predec->power.readOp.gate_leakage + bank.mat.sa_mux_lev_1_predec->power.readOp.gate_leakage + bank.mat.sa_mux_lev_2_predec->power.readOp.gate_leakage + bank.mat.power_row_decoders.readOp.gate_leakage + bank.mat.power_bit_mux_decoders.readOp.gate_leakage + bank.mat.power_sa_mux_lev_1_decoders.readOp.gate_leakage + bank.mat.power_sa_mux_lev_2_decoders.readOp.gate_leakage) * dp.num_act_mats_hor_dir; //+ // bank.mat.leak_power_sense_amps_closed_page_state) * dp.num_act_mats_hor_dir; leak_power_subbank_open_page = (bank.mat.r_predec->power.readOp.leakage + bank.mat.b_mux_predec->power.readOp.leakage + bank.mat.sa_mux_lev_1_predec->power.readOp.leakage + bank.mat.sa_mux_lev_2_predec->power.readOp.leakage + bank.mat.power_row_decoders.readOp.leakage + bank.mat.power_bit_mux_decoders.readOp.leakage + bank.mat.power_sa_mux_lev_1_decoders.readOp.leakage + bank.mat.power_sa_mux_lev_2_decoders.readOp.leakage + bank.mat.leak_power_sense_amps_open_page_state) * dp.num_act_mats_hor_dir; leak_power_subbank_open_page += (bank.mat.r_predec->power.readOp.gate_leakage + bank.mat.b_mux_predec->power.readOp.gate_leakage + bank.mat.sa_mux_lev_1_predec->power.readOp.gate_leakage + bank.mat.sa_mux_lev_2_predec->power.readOp.gate_leakage + bank.mat.power_row_decoders.readOp.gate_leakage + bank.mat.power_bit_mux_decoders.readOp.gate_leakage + bank.mat.power_sa_mux_lev_1_decoders.readOp.gate_leakage + bank.mat.power_sa_mux_lev_2_decoders.readOp.gate_leakage) * dp.num_act_mats_hor_dir; // bank.mat.leak_power_sense_amps_open_page_state) * dp.num_act_mats_hor_dir; leak_power_request_and_reply_networks = power_routing_to_bank.readOp.leakage + bank.htree_in_add->power.readOp.leakage + bank.htree_in_data->power.readOp.leakage + bank.htree_out_data->power.readOp.leakage; leak_power_request_and_reply_networks += power_routing_to_bank.readOp.gate_leakage + bank.htree_in_add->power.readOp.gate_leakage + bank.htree_in_data->power.readOp.gate_leakage + bank.htree_out_data->power.readOp.gate_leakage; if (dp.fully_assoc || dp.pure_cam) { leak_power_request_and_reply_networks += htree_in_search->power.readOp.leakage + htree_out_search->power.readOp.leakage; leak_power_request_and_reply_networks += htree_in_search->power.readOp.gate_leakage + htree_out_search->power.readOp.gate_leakage; } if (dp.is_dram) { // if DRAM, add contribution of power spent in row predecoder drivers, blocks and decoders to refresh power refresh_power = (bank.mat.r_predec->power.readOp.dynamic * dp.num_act_mats_hor_dir + bank.mat.row_dec->power.readOp.dynamic) * dp.num_r_subarray * dp.num_subarrays; refresh_power += bank.mat.per_bitline_read_energy * dp.num_c_subarray * dp.num_r_subarray * dp.num_subarrays; refresh_power += bank.mat.power_bl_precharge_eq_drv.readOp.dynamic * dp.num_act_mats_hor_dir; refresh_power += bank.mat.power_sa.readOp.dynamic * dp.num_act_mats_hor_dir; refresh_power /= dp.dram_refresh_period; } if (dp.is_tag == false) { power.readOp.dynamic = dyn_read_energy_from_closed_page; power.writeOp.dynamic = dyn_read_energy_from_closed_page - dyn_read_energy_remaining_words_in_burst - bank.mat.power_bitline.readOp.dynamic * dp.num_act_mats_hor_dir + bank.mat.power_bitline.writeOp.dynamic * dp.num_act_mats_hor_dir + (power_routing_to_bank.writeOp.dynamic - power_routing_to_bank.readOp.dynamic - bank.htree_out_data->power.readOp.dynamic + bank.htree_in_data->power.readOp.dynamic) * (MAX((g_ip->burst_len / g_ip->int_prefetch_w), 1) - 1); // FIXME if (dp.is_dram == false) { power.writeOp.dynamic -= bank.mat.power_sa.readOp.dynamic * dp.num_act_mats_hor_dir; } } // if DRAM, add refresh power to total leakage if (dp.is_dram) { power.readOp.leakage += refresh_power; } // TODO: below should be avoided. /*if (dp.is_main_mem) { power.readOp.leakage += MAIN_MEM_PER_CHIP_STANDBY_CURRENT_mA * 1e-3 * g_tp.peri_global.Vdd / g_ip->nbanks; }*/ if (g_ip->is_3d_mem) { // ---This is only to make sure the following assert() functions don't generate errors. The values are not used in 3D DRAM models // power = power + membus_RAS->power + membus_CAS->power + membus_data->power; //for leakage power add up, not used yet for optimization power.readOp.dynamic = read_energy; power.writeOp.dynamic = write_energy; // ---Before the brackets, power = power.bank, and all the specific leakage terms have and only have accounted for bank to mat levels. // power.readOp.leakage = power.readOp.leakage + membus_RAS->power.readOp.leakage + membus_CAS->power.readOp.leakage + // membus_data->power.readOp.leakage; power.readOp.leakage = membus_RAS->power.readOp.leakage + membus_CAS->power.readOp.leakage + membus_data->power.readOp.leakage; // cout << "test: " << power.readOp.dynamic << endl; // cout << "test: " << membus_RAS->power.readOp.leakage << endl; // cout << "test: " << membus_CAS->power.readOp.leakage << endl; // cout << "test: " << membus_data->power.readOp.leakage << endl; // cout << "test: power.readOp.leakage" << power.readOp.leakage << endl; } assert(power.readOp.dynamic > 0); assert(power.writeOp.dynamic > 0); assert(power.readOp.leakage > 0); }
56.904481
160
0.589763
SNU-HPCS
a07b0749198d5d3300b136c0be01d0c2f1d362e4
11,583
hpp
C++
applications/ExternalSolversApplication/external_includes/for_parallel_superlu/superlu.hpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/ExternalSolversApplication/external_includes/for_parallel_superlu/superlu.hpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
applications/ExternalSolversApplication/external_includes/for_parallel_superlu/superlu.hpp
jiaqiwang969/Kratos-test
ed082abc163e7b627f110a1ae1da465f52f48348
[ "BSD-4-Clause" ]
null
null
null
/* * * Copyright (c) Kresimir Fresl 2003 * Copyright (c) Georg Baum 2004 * * Permission to copy, modify, use and distribute this software * for any non-commercial or commercial purpose is granted provided * that this license appear on all copies of the software source code. * * Author assumes no responsibility whatsoever for its use and makes * no guarantees about its quality, correctness or reliability. * * Author acknowledges the support of the Faculty of Civil Engineering, * University of Zagreb, Croatia. * */ /** * Adapted to SuperLU_MT by Janosch Stascheit * Institute for Structural Mechanics * Ruhr-University Bochum */ #ifndef BOOST_NUMERIC_BINDINGS_SUPERLU_MT_H #define BOOST_NUMERIC_BINDINGS_SUPERLU_MT_H // #define BOOST_NUMERIC_BINDINGS_SUPERLU_PRINT #include <boost/numeric/bindings/traits/sparse_traits.hpp> #include "external_includes/superlu/superlu_mt_overloads.hpp" #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK # include <boost/static_assert.hpp> # include <boost/type_traits/same_traits.hpp> #endif #ifdef BOOST_NUMERIC_BINDINGS_SUPERLU_PRINT # include <iostream> # include <algorithm> # include <iterator> #endif // #include "external_includes/superlu/slu_mt_util.h" // #include "external_includes/superlu/pdsp_defs.h" // #include "external_includes/superlu/slu_mt_Cnames.h" namespace boost { namespace numeric { namespace bindings { namespace superlu { enum permc_spec_t { natural = 0, // Pc = I // .. is there a bug in SuperLU ? // .. get_perm_c.c & mmd.c ? // attma_min_degree = 1, // min. degree on the structure of A^T * A atpla_min_degree = 2, // min. degree on the structure of A^T + A colamd = 3 // approx. min. degree for unsymmetric matrices }; template <typename MatrA, typename MatrB> inline int pgssv (int nproc, MatrA const& a, MatrB& b, permc_spec_t perm_spec = colamd) { typedef traits::sparse_matrix_traits<MatrA> matraits; typedef traits::matrix_traits<MatrB> mbtraits; std::cout << "I am in parallel pgssv, running with " << nproc << " threads" << std::endl; BOOST_STATIC_ASSERT((boost::is_same< typename matraits::matrix_structure, traits::general_t >::value)); BOOST_STATIC_ASSERT((boost::is_same< typename matraits::storage_format, traits::compressed_t >::value)); BOOST_STATIC_ASSERT((boost::is_same< typename matraits::ordering_type, traits::column_major_t >::value)); BOOST_STATIC_ASSERT(matraits::index_base == 0); BOOST_STATIC_ASSERT((boost::is_same< typename mbtraits::matrix_structure, traits::general_t >::value)); BOOST_STATIC_ASSERT((boost::is_same< typename mbtraits::ordering_type, traits::column_major_t >::value)); typedef typename matraits::value_type val_t; MatrA& aa = const_cast<MatrA&> (a); int m = matraits::size1 (aa); assert (m == matraits::size2 (aa)); assert (m == mbtraits::size1 (b)); SuperMatrix A, B, L, U; /** manual index vector generation */ int *index1_vector = new (std::nothrow) int[a.index1_data().size()]; int *index2_vector = new (std::nothrow) int[a.index2_data().size()]; for( int i = 0; i < a.index1_data().size(); i++ ) { index1_vector[i] = (int)a.index1_data()[i]; // std::cout << index1_vector[i] << " "; } // std::cout << std::endl; // std::cout << std::endl; for( int i = 0; i < a.index2_data().size(); i++ ) { index2_vector[i] = (int)a.index2_data()[i]; // std::cout << index2_vector[i] << " "; } // std::cout << std::endl; detail::Create_CompCol_Matrix (&A, m, m, matraits::num_nonzeros (aa), matraits::value_storage (aa), index2_vector, index1_vector // (int*)matraits::index1_storage (aa), // (int*)matraits::index2_storage (aa) ); std::cout << "Matrix storage type: " << A.Mtype << std::endl; detail::Create_Dense_Matrix (&B, mbtraits::size1(b), mbtraits::size2(b), mbtraits::storage (b), // mbtraits::leading_dimension (b)); mbtraits::size1(b)); #ifdef BOOST_NUMERIC_BINDINGS_SUPERLU_PRINT detail::Print_CompCol_Matrix (val_t(), "A", &A); detail::Print_Dense_Matrix (val_t(), "B", &B); std::cout << std::endl; #endif int *perm_r = new (std::nothrow) int[m]; if (!perm_r) return -100; int *perm_c = new (std::nothrow) int[m]; if (!perm_c) { // std::cout << "####### deleting perm_r" << std::endl; delete[] perm_r; return -101; } /* * Get column permutation vector perm_c[], according to permc_spec: * permc_spec = 0: natural ordering * permc_spec = 1: minimum degree on structure of A’*A * permc_spec = 2: minimum degree on structure of A’+A * permc_spec = 3: approximate minimum degree for unsymmetric matrices */ int permc_spec = 3; get_perm_c(permc_spec, &A, perm_c); #ifdef BOOST_NUMERIC_BINDINGS_SUPERLU_PRINT std::cout << "perm_c: "; std::copy (perm_c, perm_c + m, std::ostream_iterator<int> (std::cout, " ")); std::cout << std::endl << std::endl; #endif // superlu_mt_options_t options; // set_default_options(&options); // options.RowPerm = static_cast<rowperm_t>(perm_spec); /** * testing options */ // options.ColPerm = static_cast<colperm_t>(colamd); int info = 0; // std::cout << "A.ncol: " << A.ncol << std::endl; // for( int i=0; i<4; i++ ) // { // std::cout<< "####superlu.hpp#### running solver in iteration no. " << i << std::endl; boost::numeric::bindings::superlu::detail::pgssv( nproc, &A, perm_c, perm_r, &L, &U, &B, &info ); // } // std::cout << "########## free memory..." << std::endl; //StatFree(&stat); Destroy_CompCol_Matrix (&U); Destroy_SuperNode_Matrix (&L); delete[] perm_c; delete[] perm_r; Destroy_SuperMatrix_Store (&B); Destroy_SuperMatrix_Store (&A); delete[] index1_vector; delete[] index2_vector; return info; } /** * specialisation for single equation systems Ax=b * note: template parameter DataType is only for distinguation * with AX=B specialisation * by Janosch Stascheit */ // template <typename MatrA, typename VecB> // inline // int gssv (MatrA const& a, VecB& b, int single, permc_spec_t perm_spec = colamd) // { // // adapted to row_major // typedef traits::sparse_matrix_traits<MatrA> matraits; // typedef traits::vector_traits<VecB> vtraits; // // #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK // BOOST_STATIC_ASSERT((boost::is_same< // typename matraits::matrix_structure, traits::general_t // >::value)); // BOOST_STATIC_ASSERT((boost::is_same< // typename matraits::storage_format, traits::compressed_t // >::value)); // BOOST_STATIC_ASSERT((boost::is_same< // typename matraits::ordering_type, traits::row_major_t // >::value)); // // BOOST_STATIC_ASSERT(matraits::index_base == 0); // // // BOOST_STATIC_ASSERT((boost::is_same< // // typename mbtraits::matrix_structure, traits::general_t // // >::value)); // // BOOST_STATIC_ASSERT((boost::is_same< // // typename mbtraits::ordering_type, traits::row_major_t // // >::value)); // #endif // // typedef typename matraits::value_type val_t; // // MatrA& aa = const_cast<MatrA&> (a); // // int m = matraits::size1 (aa); // assert (m == matraits::size2 (aa)); // assert (m == vtraits::size (b)); // // SuperMatrix A, B, L, U; // // detail::Create_CompRow_Matrix (&A, m, m, matraits::num_nonzeros (aa), // matraits::value_storage (aa), // (int*)matraits::index2_storage (aa), // (int*)matraits::index1_storage (aa) ); // // detail::Create_Dense_Matrix (&B, m, 1, // vtraits::storage(b), // b.size() // // vtraits::vector_storage(b), // // vtraits::leading_dimension (b) // ); // // #ifdef BOOST_NUMERIC_BINDINGS_SUPERLU_PRINT // detail::Print_CompCol_Matrix (val_t(), "A", &A); // detail::Print_Dense_Matrix (val_t(), "B", &B); // std::cout << std::endl; // #endif // // int *perm_r = new (std::nothrow) int[m]; // if (!perm_r) // return -100; // int *perm_c = new (std::nothrow) int[m]; // if (!perm_c) { // delete[] perm_r; // return -101; // } // #ifdef BOOST_NUMERIC_BINDINGS_SUPERLU_PRINT // std::cout << "perm_c: "; // std::copy (perm_c, perm_c + m, // std::ostream_iterator<int> (std::cout, " ")); // std::cout << std::endl << std::endl; // #endif // // superlu_options_t options; // set_default_options(&options); // options.RowPerm = static_cast<rowperm_t>(perm_spec); // SuperLUStat_t stat; // StatInit(&stat); // // int info = 0; // detail::gssv (val_t(), &options, &A, perm_c, perm_r, &L, &U, &B, &stat, &info); // // #ifdef BOOST_NUMERIC_BINDINGS_SUPERLU_PRINT // // detail::Print_SuperNode_Matrix (val_t(), "L + U - I", &L); // // detail::Print_CompCol_Matrix (val_t(), "U", &U); // // // std::cout << std::endl; // // SCformat* Lstore = (SCformat*) L.Store; // // NCformat* Ustore = (NCformat*) U.Store; // // std::cout << "No of nonzeros in L = " << Lstore->nnz << std::endl; // // std::cout << "No of nonzeros in U = " << Ustore->nnz << std::endl; // // std::cout << std::endl; // // SCformat* Lstore = (SCformat*) L.Store; // // for (int i = 0; i < Lstore->nnz; ++i) // // std::cout << ((val_t*) (Lstore->nzval))[i] << " "; // // std::cout << std::endl << std::endl; // // // detail::Print_Dense_Matrix (val_t(), "X", &B); // std::cout << std::endl; // #endif // // if (options.PrintStat) { // StatPrint(&stat); // } // StatFree(&stat); // Destroy_CompCol_Matrix (&U); // Destroy_SuperNode_Matrix (&L); // delete[] perm_c; // delete[] perm_r; // Destroy_SuperMatrix_Store (&B); // Destroy_SuperMatrix_Store (&A); // // return info; // } // } }}} #endif
36.084112
109
0.538203
jiaqiwang969
a07d4c9a55b588b6021614471fddb06506f576a0
2,702
cpp
C++
tests/generators.deactivated/lesson_21_auto_generate_0.cpp
fish2000/halogen
6962e9babc49bcb845deb72b0e5ed5033a2444a6
[ "MIT" ]
6
2016-08-24T14:28:29.000Z
2019-07-26T22:23:06.000Z
tests/generators.deactivated/lesson_21_auto_generate_0.cpp
fish2000/halogen
6962e9babc49bcb845deb72b0e5ed5033a2444a6
[ "MIT" ]
2
2018-08-11T22:47:00.000Z
2020-11-19T13:49:26.000Z
tests/generators.deactivated/lesson_21_auto_generate_0.cpp
fish2000/halogen
6962e9babc49bcb845deb72b0e5ed5033a2444a6
[ "MIT" ]
null
null
null
#include "Halide.h" using namespace Halide; class AutoScheduled : public Halide::Generator<AutoScheduled> { public: Input<Buffer<float>> input{ "input", 3 }; Input<float> factor{ "factor" }; Output<Buffer<float>> output1{ "output1", 2 }; Output<Buffer<float>> output2{ "output2", 2 }; public: Expr sum3x3(Func f, Var x, Var y) { return f(x-1, y-1) + f(x-1, y) + f(x-1, y+1) + f(x, y-1) + f(x, y) + f(x, y+1) + f(x+1, y-1) + f(x+1, y) + f(x+1, y+1); } public: void generate() { Func in_b = BoundaryConditions::repeat_edge(input); gray(x, y) = 0.299f * in_b(x, y, 0) + 0.587f * in_b(x, y, 1) + 0.114f * in_b(x, y, 2); Iy(x, y) = gray(x-1, y-1)*(-1.0f/12) + gray(x-1, y+1)*(1.0f/12) + gray(x, y-1)*(-2.0f/12) + gray(x, y+1)*(2.0f/12) + gray(x+1, y-1)*(-1.0f/12) + gray(x+1, y+1)*(1.0f/12); Ix(x, y) = gray(x-1, y-1)*(-1.0f/12) + gray(x+1, y-1)*(1.0f/12) + gray(x-1, y)*(-2.0f/12) + gray(x+1, y)*(2.0f/12) + gray(x-1, y+1)*(-1.0f/12) + gray(x+1, y+1)*(1.0f/12); Ixx(x, y) = Ix(x, y) * Ix(x, y); Iyy(x, y) = Iy(x, y) * Iy(x, y); Ixy(x, y) = Ix(x, y) * Iy(x, y); Sxx(x, y) = sum3x3(Ixx, x, y); Syy(x, y) = sum3x3(Iyy, x, y); Sxy(x, y) = sum3x3(Ixy, x, y); det(x, y) = Sxx(x, y) * Syy(x, y) - Sxy(x, y) * Sxy(x, y); trace(x, y) = Sxx(x, y) + Syy(x, y); harris(x, y) = det(x, y) - 0.04f * trace(x, y) * trace(x, y); output1(x, y) = harris(x + 2, y + 2); output2(x, y) = factor * harris(x + 2, y + 2); } public: void schedule() { if (auto_schedule) { input.dim(0).set_bounds_estimate(0, 1024); input.dim(1).set_bounds_estimate(0, 1024); input.dim(2).set_bounds_estimate(0, 3); factor.set_estimate(2.0f); output1.estimate(x, 0, 1024) .estimate(y, 0, 1024); output2.estimate(x, 0, 1024) .estimate(y, 0, 1024); } else { gray.compute_root(); Iy.compute_root(); Ix.compute_root(); } } private: Var x{"x"}, y{"y"}, c{"c"}; Func gray, Iy, Ix, Ixx, Iyy, Ixy, Sxx, Syy, Sxy, det, trace, harris; }; HALIDE_REGISTER_GENERATOR(AutoScheduled, auto_schedule_gen)
39.735294
98
0.417469
fish2000
a07e8c8d24dfd8d68f888109c8de0731638a7a6c
4,619
cxx
C++
Common/DataModel/vtkLagrangeHexahedron.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
1,755
2015-01-03T06:55:00.000Z
2022-03-29T05:23:26.000Z
Common/DataModel/vtkLagrangeHexahedron.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
29
2015-04-23T20:58:30.000Z
2022-03-02T16:16:42.000Z
Common/DataModel/vtkLagrangeHexahedron.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
1,044
2015-01-05T22:48:27.000Z
2022-03-31T02:38:26.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkLagrangeHexahedron.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkLagrangeHexahedron.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkHexahedron.h" #include "vtkIdList.h" #include "vtkLagrangeCurve.h" #include "vtkLagrangeInterpolation.h" #include "vtkLagrangeQuadrilateral.h" #include "vtkLine.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkTriangle.h" #include "vtkVector.h" #include "vtkVectorOperators.h" vtkStandardNewMacro(vtkLagrangeHexahedron); vtkLagrangeHexahedron::vtkLagrangeHexahedron() = default; vtkLagrangeHexahedron::~vtkLagrangeHexahedron() = default; void vtkLagrangeHexahedron::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } vtkCell* vtkLagrangeHexahedron::GetEdge(int edgeId) { vtkLagrangeCurve* result = EdgeCell; const auto set_number_of_ids_and_points = [&](const vtkIdType& npts) -> void { result->Points->SetNumberOfPoints(npts); result->PointIds->SetNumberOfIds(npts); }; const auto set_ids_and_points = [&](const vtkIdType& face_id, const vtkIdType& vol_id) -> void { result->Points->SetPoint(face_id, this->Points->GetPoint(vol_id)); result->PointIds->SetId(face_id, this->PointIds->GetId(vol_id)); }; this->SetEdgeIdsAndPoints(edgeId, set_number_of_ids_and_points, set_ids_and_points); return result; } vtkCell* vtkLagrangeHexahedron::GetFace(int faceId) { vtkLagrangeQuadrilateral* result = FaceCell; const auto set_number_of_ids_and_points = [&](const vtkIdType& npts) -> void { result->Points->SetNumberOfPoints(npts); result->PointIds->SetNumberOfIds(npts); }; const auto set_ids_and_points = [&](const vtkIdType& face_id, const vtkIdType& vol_id) -> void { result->Points->SetPoint(face_id, this->Points->GetPoint(vol_id)); result->PointIds->SetId(face_id, this->PointIds->GetId(vol_id)); }; this->SetFaceIdsAndPoints(result, faceId, set_number_of_ids_and_points, set_ids_and_points); return result; } /**\brief Populate the linear hex returned by GetApprox() with point-data from one voxel-like * intervals of this cell. * * Ensure that you have called GetOrder() before calling this method * so that this->Order is up to date. This method does no checking * before using it to map connectivity-array offsets. */ vtkHexahedron* vtkLagrangeHexahedron::GetApproximateHex( int subId, vtkDataArray* scalarsIn, vtkDataArray* scalarsOut) { vtkHexahedron* approx = this->GetApprox(); bool doScalars = (scalarsIn && scalarsOut); if (doScalars) { scalarsOut->SetNumberOfTuples(8); } int i, j, k; if (!this->SubCellCoordinatesFromId(i, j, k, subId)) { vtkErrorMacro("Invalid subId " << subId); return nullptr; } // Get the point coordinates (and optionally scalars) for each of the 8 corners // in the approximating hexahedron spanned by (i, i+1) x (j, j+1) x (k, k+1): for (vtkIdType ic = 0; ic < 8; ++ic) { const vtkIdType corner = this->PointIndexFromIJK( i + ((((ic + 1) / 2) % 2) ? 1 : 0), j + (((ic / 2) % 2) ? 1 : 0), k + ((ic / 4) ? 1 : 0)); vtkVector3d cp; this->Points->GetPoint(corner, cp.GetData()); approx->Points->SetPoint(ic, cp.GetData()); approx->PointIds->SetId(ic, doScalars ? corner : this->PointIds->GetId(corner)); if (doScalars) { scalarsOut->SetTuple(ic, scalarsIn->GetTuple(corner)); } } return approx; } void vtkLagrangeHexahedron::InterpolateFunctions(const double pcoords[3], double* weights) { vtkLagrangeInterpolation::Tensor3ShapeFunctions(this->GetOrder(), pcoords, weights); } void vtkLagrangeHexahedron::InterpolateDerivs(const double pcoords[3], double* derivs) { vtkLagrangeInterpolation::Tensor3ShapeDerivatives(this->GetOrder(), pcoords, derivs); } vtkHigherOrderCurve* vtkLagrangeHexahedron::GetEdgeCell() { return EdgeCell; } vtkHigherOrderQuadrilateral* vtkLagrangeHexahedron::GetFaceCell() { return FaceCell; } vtkHigherOrderInterpolation* vtkLagrangeHexahedron::GetInterpolation() { return Interp; };
33.230216
98
0.708162
LongerVisionUSA
a080683290668721aeabc1263f06df97365f2c05
23,109
cpp
C++
src/threed_beam_fea.cpp
latture/threed-beam-fea
a3443cfe66c852d09f3f7349fbb7a32dfd3582ac
[ "BSD-2-Clause" ]
8
2018-06-11T09:00:34.000Z
2021-01-08T16:21:56.000Z
src/threed_beam_fea.cpp
latture/threed-beam-fea
a3443cfe66c852d09f3f7349fbb7a32dfd3582ac
[ "BSD-2-Clause" ]
null
null
null
src/threed_beam_fea.cpp
latture/threed-beam-fea
a3443cfe66c852d09f3f7349fbb7a32dfd3582ac
[ "BSD-2-Clause" ]
4
2019-11-17T13:26:57.000Z
2020-03-05T15:05:42.000Z
// Copyright 2015. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: ryan.latture@gmail.com (Ryan Latture) #include <boost/format.hpp> #include <chrono> #include <cmath> #include <exception> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include "threed_beam_fea.h" namespace fea { namespace { void writeStringToTxt(std::string filename, std::string data) { std::ofstream output_file; output_file.open(filename); if (!output_file.is_open()) { throw std::runtime_error( (boost::format("Error opening file %s.") % filename).str() ); } output_file << data; output_file.close(); } } inline double norm(const Node &n1, const Node &n2) { const Node dn = n2 - n1; return dn.norm(); } void GlobalStiffAssembler::calcKelem(unsigned int i, const Job &job) { // extract element properties const double EA = job.props[i].EA; const double EIz = job.props[i].EIz; const double EIy = job.props[i].EIy; const double GJ = job.props[i].GJ; // store node indices of current element const int nn1 = job.elems[i][0]; const int nn2 = job.elems[i][1]; // calculate the length of the element const double length = norm(job.nodes[nn1], job.nodes[nn2]); // store the entries in the (local) elemental stiffness matrix as temporary values to avoid recalculation const double tmpEA = EA / length; const double tmpGJ = GJ / length; const double tmp12z = 12.0 * EIz / (length * length * length); const double tmp6z = 6.0 * EIz / (length * length); const double tmp1z = EIz / length; const double tmp12y = 12.0 * EIy / (length * length * length); const double tmp6y = 6.0 * EIy / (length * length); const double tmp1y = EIy / length; // update local elemental stiffness matrix Klocal(0, 0) = tmpEA; Klocal(0, 6) = -tmpEA; Klocal(1, 1) = tmp12z; Klocal(1, 5) = tmp6z; Klocal(1, 7) = -tmp12z; Klocal(1, 11) = tmp6z; Klocal(2, 2) = tmp12y; Klocal(2, 4) = -tmp6y; Klocal(2, 8) = -tmp12y; Klocal(2, 10) = -tmp6y; Klocal(3, 3) = tmpGJ; Klocal(3, 9) = -tmpGJ; Klocal(4, 2) = -tmp6y; Klocal(4, 4) = 4.0 * tmp1y; Klocal(4, 8) = tmp6y; Klocal(4, 10) = 2.0 * tmp1y; Klocal(5, 1) = tmp6z; Klocal(5, 5) = 4.0 * tmp1z; Klocal(5, 7) = -tmp6z; Klocal(5, 11) = 2.0 * tmp1z; Klocal(6, 0) = -tmpEA; Klocal(6, 6) = tmpEA; Klocal(7, 1) = -tmp12z; Klocal(7, 5) = -tmp6z; Klocal(7, 7) = tmp12z; Klocal(7, 11) = -tmp6z; Klocal(8, 2) = -tmp12y; Klocal(8, 4) = tmp6y; Klocal(8, 8) = tmp12y; Klocal(8, 10) = tmp6y; Klocal(9, 3) = -tmpGJ; Klocal(9, 9) = tmpGJ; Klocal(10, 2) = -tmp6y; Klocal(10, 4) = 2.0 * tmp1y; Klocal(10, 8) = tmp6y; Klocal(10, 10) = 4.0 * tmp1y; Klocal(11, 1) = tmp6z; Klocal(11, 5) = 2.0 * tmp1z; Klocal(11, 7) = -tmp6z; Klocal(11, 11) = 4.0 * tmp1z; // calculate unit normal vector along local x-direction Eigen::Vector3d nx = job.nodes[nn2] - job.nodes[nn1]; nx.normalize(); // calculate unit normal vector along y-direction const Eigen::Vector3d ny = job.props[i].normal_vec.normalized(); // update rotation matrices calcAelem(nx, ny); // update Kelem Kelem = AelemT * Klocal * Aelem; }; void GlobalStiffAssembler::calcAelem(const Eigen::Vector3d &nx, const Eigen::Vector3d &ny) { // calculate the unit normal vector in local z direction Eigen::Vector3d nz; nz = nx.cross(ny); const double dlz = nz.squaredNorm(); nz /= dlz; // update rotation matrix Aelem(0, 0) = nx(0); Aelem(0, 1) = nx(1); Aelem(0, 2) = nx(2); Aelem(1, 0) = ny(0); Aelem(1, 1) = ny(1); Aelem(1, 2) = ny(2); Aelem(2, 0) = nz(0); Aelem(2, 1) = nz(1); Aelem(2, 2) = nz(2); Aelem(3, 3) = nx(0); Aelem(3, 4) = nx(1); Aelem(3, 5) = nx(2); Aelem(4, 3) = ny(0); Aelem(4, 4) = ny(1); Aelem(4, 5) = ny(2); Aelem(5, 3) = nz(0); Aelem(5, 4) = nz(1); Aelem(5, 5) = nz(2); Aelem(6, 6) = nx(0); Aelem(6, 7) = nx(1); Aelem(6, 8) = nx(2); Aelem(7, 6) = ny(0); Aelem(7, 7) = ny(1); Aelem(7, 8) = ny(2); Aelem(8, 6) = nz(0); Aelem(8, 7) = nz(1); Aelem(8, 8) = nz(2); Aelem(9, 9) = nx(0); Aelem(9, 10) = nx(1); Aelem(9, 11) = nx(2); Aelem(10, 9) = ny(0); Aelem(10, 10) = ny(1); Aelem(10, 11) = ny(2); Aelem(11, 9) = nz(0); Aelem(11, 10) = nz(1); Aelem(11, 11) = nz(2); // update transposed rotation matrix AelemT(0, 0) = nx(0); AelemT(0, 1) = ny(0); AelemT(0, 2) = nz(0); AelemT(1, 0) = nx(1); AelemT(1, 1) = ny(1); AelemT(1, 2) = nz(1); AelemT(2, 0) = nx(2); AelemT(2, 1) = ny(2); AelemT(2, 2) = nz(2); AelemT(3, 3) = nx(0); AelemT(3, 4) = ny(0); AelemT(3, 5) = nz(0); AelemT(4, 3) = nx(1); AelemT(4, 4) = ny(1); AelemT(4, 5) = nz(1); AelemT(5, 3) = nx(2); AelemT(5, 4) = ny(2); AelemT(5, 5) = nz(2); AelemT(6, 6) = nx(0); AelemT(6, 7) = ny(0); AelemT(6, 8) = nz(0); AelemT(7, 6) = nx(1); AelemT(7, 7) = ny(1); AelemT(7, 8) = nz(1); AelemT(8, 6) = nx(2); AelemT(8, 7) = ny(2); AelemT(8, 8) = nz(2); AelemT(9, 9) = nx(0); AelemT(9, 10) = ny(0); AelemT(9, 11) = nz(0); AelemT(10, 9) = nx(1); AelemT(10, 10) = ny(1); AelemT(10, 11) = nz(1); AelemT(11, 9) = nx(2); AelemT(11, 10) = ny(2); AelemT(11, 11) = nz(2); }; void GlobalStiffAssembler::operator()(SparseMat &Kg, const Job &job, const std::vector<Tie> &ties) { int nn1, nn2; unsigned int row, col; const unsigned int dofs_per_elem = DOF::NUM_DOFS; // form vector to hold triplets that will be used to assemble global stiffness matrix std::vector<Eigen::Triplet<double> > triplets; triplets.reserve(40 * job.elems.size() + 4 * dofs_per_elem * ties.size()); for (unsigned int i = 0; i < job.elems.size(); ++i) { // update Kelem with current elemental stiffness matrix calcKelem(i, job); // get sparse representation of the current elemental stiffness matrix SparseKelem = Kelem.sparseView(); // pull out current node indices nn1 = job.elems[i][0]; nn2 = job.elems[i][1]; for (unsigned int j = 0; j < SparseKelem.outerSize(); ++j) { for (SparseMat::InnerIterator it(SparseKelem, j); it; ++it) { row = it.row(); col = it.col(); // check position in local matrix and update corresponding global position if (row < 6) { // top left if (col < 6) { triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn1 + row, dofs_per_elem * nn1 + col, it.value())); } // top right else { triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn1 + row, dofs_per_elem * (nn2 - 1) + col, it.value())); } } else { // bottom left if (col < 6) { triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * (nn2 - 1) + row, dofs_per_elem * nn1 + col, it.value())); } // bottom right else { triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * (nn2 - 1) + row, dofs_per_elem * (nn2 - 1) + col, it.value())); } } } } } loadTies(triplets, ties); Kg.setFromTriplets(triplets.begin(), triplets.end()); }; void loadBCs(SparseMat &Kg, SparseMat &force_vec, const std::vector<BC> &BCs, unsigned int num_nodes) { unsigned int bc_idx; const unsigned int dofs_per_elem = DOF::NUM_DOFS; // calculate the index that marks beginning of Lagrange multiplier coefficients const unsigned int global_add_idx = dofs_per_elem * num_nodes; for (size_t i = 0; i < BCs.size(); ++i) { bc_idx = dofs_per_elem * BCs[i].node + BCs[i].dof; // update global stiffness matrix Kg.insert(bc_idx, global_add_idx + i) = 1; Kg.insert(global_add_idx + i, bc_idx) = 1; // update force vector. All values are already zero. Only update if BC if non-zero. if (std::abs(BCs[i].value) > std::numeric_limits<double>::epsilon()) { force_vec.insert(global_add_idx + i, 0) = BCs[i].value; } } }; void loadEquations(SparseMat &Kg, const std::vector<Equation> &equations, unsigned int num_nodes, unsigned int num_bcs) { size_t row_idx, col_idx; const unsigned int dofs_per_elem = DOF::NUM_DOFS; const unsigned int global_add_idx = dofs_per_elem * num_nodes + num_bcs; for (size_t i = 0; i < equations.size(); ++i) { row_idx = global_add_idx + i; for (size_t j = 0; j < equations[i].terms.size(); ++j) { col_idx = dofs_per_elem * equations[i].terms[j].node_number + equations[i].terms[j].dof; Kg.insert(row_idx, col_idx) = equations[i].terms[j].coefficient; Kg.insert(col_idx, row_idx) = equations[i].terms[j].coefficient; } } }; void loadTies(std::vector<Eigen::Triplet<double> > &triplets, const std::vector<Tie> &ties) { const unsigned int dofs_per_elem = DOF::NUM_DOFS; unsigned int nn1, nn2; double lmult, rmult, spring_constant; for (size_t i = 0; i < ties.size(); ++i) { nn1 = ties[i].node_number_1; nn2 = ties[i].node_number_2; lmult = ties[i].lmult; rmult = ties[i].rmult; for (unsigned int j = 0; j < dofs_per_elem; ++j) { // first 3 DOFs are linear DOFs, second 2 are rotational, last is torsional spring_constant = j < 3 ? lmult : rmult; triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn1 + j, dofs_per_elem * nn1 + j, spring_constant)); triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn2 + j, dofs_per_elem * nn2 + j, spring_constant)); triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn1 + j, dofs_per_elem * nn2 + j, -spring_constant)); triplets.push_back(Eigen::Triplet<double>(dofs_per_elem * nn2 + j, dofs_per_elem * nn1 + j, -spring_constant)); } } }; std::vector<std::vector<double> > computeTieForces(const std::vector<Tie> &ties, const std::vector<std::vector<double> > &nodal_displacements) { const unsigned int dofs_per_elem = DOF::NUM_DOFS; unsigned int nn1, nn2; double lmult, rmult, spring_constant, delta1, delta2; std::vector<std::vector<double> > tie_forces(ties.size(), std::vector<double>(dofs_per_elem)); for (size_t i = 0; i < ties.size(); ++i) { nn1 = ties[i].node_number_1; nn2 = ties[i].node_number_2; lmult = ties[i].lmult; rmult = ties[i].rmult; for (unsigned int j = 0; j < dofs_per_elem; ++j) { // first 3 DOFs are linear DOFs, second 2 are rotational, last is torsional spring_constant = j < 3 ? lmult : rmult; delta1 = nodal_displacements[nn1][j]; delta2 = nodal_displacements[nn2][j]; tie_forces[i][j] = spring_constant * (delta2 - delta1); } } return tie_forces; } void loadForces(SparseMat &force_vec, const std::vector<Force> &forces) { const unsigned int dofs_per_elem = DOF::NUM_DOFS; unsigned int idx; for (size_t i = 0; i < forces.size(); ++i) { idx = dofs_per_elem * forces[i].node + forces[i].dof; force_vec.insert(idx, 0) = forces[i].value; } }; Summary solve(const Job &job, const std::vector<BC> &BCs, const std::vector<Force> &forces, const std::vector<Tie> &ties, const std::vector<Equation> &equations, const Options &options) { auto initial_start_time = std::chrono::high_resolution_clock::now(); Summary summary; summary.num_nodes = job.nodes.size(); summary.num_elems = job.elems.size(); summary.num_bcs = BCs.size(); summary.num_ties = ties.size(); const unsigned int dofs_per_elem = DOF::NUM_DOFS; // calculate size of global stiffness matrix and force vector const unsigned long size = dofs_per_elem * job.nodes.size() + BCs.size() + equations.size(); // construct global stiffness matrix and force vector SparseMat Kg(size, size); SparseMat force_vec(size, 1); force_vec.reserve(forces.size() + BCs.size()); // construct global assembler object and assemble global stiffness matrix auto start_time = std::chrono::high_resolution_clock::now(); GlobalStiffAssembler assembleK3D = GlobalStiffAssembler(); assembleK3D(Kg, job, ties); auto end_time = std::chrono::high_resolution_clock::now(); auto delta_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); summary.assembly_time_in_ms = delta_time; if (options.verbose) std::cout << "Global stiffness matrix assembled in " << delta_time << " ms.\nNow preprocessing factorization..." << std::endl; // load prescribed boundary conditions into stiffness matrix and force vector loadBCs(Kg, force_vec, BCs, job.nodes.size()); if (equations.size() > 0) { loadEquations(Kg, equations, job.nodes.size(), BCs.size()); } // load prescribed forces into force vector if (forces.size() > 0) { loadForces(force_vec, forces); } // compress global stiffness matrix since all non-zero values have been added. Kg.prune(1.e-14); Kg.makeCompressed(); // initialize solver based on whether MKL should be used #ifdef EIGEN_USE_MKL_ALL Eigen::PardisoLU<SparseMat> solver; #else Eigen::SparseLU<SparseMat> solver; #endif //Compute the ordering permutation vector from the structural pattern of Kg start_time = std::chrono::high_resolution_clock::now(); solver.analyzePattern(Kg); end_time = std::chrono::high_resolution_clock::now(); delta_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); summary.preprocessing_time_in_ms = delta_time; if (options.verbose) std::cout << "Preprocessing step of factorization completed in " << delta_time << " ms.\nNow factorizing global stiffness matrix..." << std::endl; // Compute the numerical factorization start_time = std::chrono::high_resolution_clock::now(); solver.factorize(Kg); end_time = std::chrono::high_resolution_clock::now(); delta_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); summary.factorization_time_in_ms = delta_time; if (options.verbose) std::cout << "Factorization completed in " << delta_time << " ms. Now solving system..." << std::endl; //Use the factors to solve the linear system start_time = std::chrono::high_resolution_clock::now(); SparseMat dispSparse = solver.solve(force_vec); end_time = std::chrono::high_resolution_clock::now(); delta_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); summary.solve_time_in_ms = delta_time; if (options.verbose) std::cout << "System was solved in " << delta_time << " ms.\n" << std::endl; // convert to dense matrix Eigen::VectorXd disp(dispSparse); // convert from Eigen vector to std vector std::vector<std::vector<double> > disp_vec(job.nodes.size(), std::vector<double>(dofs_per_elem)); for (size_t i = 0; i < disp_vec.size(); ++i) { for (unsigned int j = 0; j < dofs_per_elem; ++j) // round all values close to 0.0 disp_vec[i][j] = std::abs(disp(dofs_per_elem * i + j)) < options.epsilon ? 0.0 : disp(dofs_per_elem * i + j); } summary.nodal_displacements = disp_vec; // [calculate nodal forces start_time = std::chrono::high_resolution_clock::now(); Kg = Kg.topLeftCorner(dofs_per_elem * job.nodes.size(), dofs_per_elem * job.nodes.size()); dispSparse = dispSparse.topRows(dofs_per_elem * job.nodes.size()); SparseMat nodal_forces_sparse = Kg * dispSparse; Eigen::VectorXd nodal_forces_dense(nodal_forces_sparse); std::vector<std::vector<double> > nodal_forces_vec(job.nodes.size(), std::vector<double>(dofs_per_elem)); for (size_t i = 0; i < nodal_forces_vec.size(); ++i) { for (unsigned int j = 0; j < dofs_per_elem; ++j) // round all values close to 0.0 nodal_forces_vec[i][j] = std::abs(nodal_forces_dense(dofs_per_elem * i + j)) < options.epsilon ? 0.0 : nodal_forces_dense( dofs_per_elem * i + j); } summary.nodal_forces = nodal_forces_vec; end_time = std::chrono::high_resolution_clock::now(); summary.nodal_forces_solve_time_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>( end_time - start_time).count(); //] // [ calculate forces associated with ties if (ties.size() > 0) { start_time = std::chrono::high_resolution_clock::now(); summary.tie_forces = computeTieForces(ties, disp_vec); end_time = std::chrono::high_resolution_clock::now(); summary.tie_forces_solve_time_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>( end_time - start_time).count(); } // ] // [save files specified in options CSVParser csv; start_time = std::chrono::high_resolution_clock::now(); if (options.save_nodal_displacements) { csv.write(options.nodal_displacements_filename, disp_vec, options.csv_precision, options.csv_delimiter); } if (options.save_nodal_forces) { csv.write(options.nodal_forces_filename, nodal_forces_vec, options.csv_precision, options.csv_delimiter); } if (options.save_tie_forces) { csv.write(options.tie_forces_filename, summary.tie_forces, options.csv_precision, options.csv_delimiter); } end_time = std::chrono::high_resolution_clock::now(); summary.file_save_time_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>( end_time - start_time).count(); // ] auto final_end_time = std::chrono::high_resolution_clock::now(); delta_time = std::chrono::duration_cast<std::chrono::milliseconds>(final_end_time - initial_start_time).count(); summary.total_time_in_ms = delta_time; if (options.save_report) { writeStringToTxt(options.report_filename, summary.FullReport()); } if (options.verbose) std::cout << summary.FullReport(); return summary; }; } // namespace fea
39.706186
132
0.537583
latture
a0823f182da9173595efdef70b3b69e83659b7a6
3,780
cpp
C++
libnhttp/nhttp/server/internals/contents/http_raw_request_content.cpp
jay94ks/libnhttp
a244eb2d04c339454ef4831b43d1ab270ee7d13d
[ "MIT" ]
4
2021-04-11T22:46:13.000Z
2021-05-27T06:01:37.000Z
libnhttp/nhttp/server/internals/contents/http_raw_request_content.cpp
jay94ks/libnhttp
a244eb2d04c339454ef4831b43d1ab270ee7d13d
[ "MIT" ]
3
2021-05-26T04:16:56.000Z
2021-05-27T04:34:14.000Z
libnhttp/nhttp/server/internals/contents/http_raw_request_content.cpp
jay94ks/libnhttp
a244eb2d04c339454ef4831b43d1ab270ee7d13d
[ "MIT" ]
1
2021-04-11T22:46:15.000Z
2021-04-11T22:46:15.000Z
#include "http_raw_request_content.hpp" #include "../http_chunked_buffer.hpp" namespace nhttp { namespace server { http_raw_request_content::http_raw_request_content(std::shared_ptr<http_chunked_buffer> buffer, ssize_t total_bytes) : waiter(false, true), buffer(buffer), total_bytes(total_bytes), read_requested(false), avail_bytes(0), is_end(false), non_block(false) { } /* determines validity of this stream. */ bool http_raw_request_content::is_valid() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer != nullptr; } /* determines currently at end of stream. */ bool http_raw_request_content::is_end_of() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer == nullptr || (avail_bytes <= 0 && is_end) || !total_bytes; } /* determines this stream is based on non-blocking or not. */ bool http_raw_request_content::is_nonblock() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer == nullptr || non_block; } bool http_raw_request_content::set_nonblock(bool value) { std::lock_guard<decltype(spinlock)> guard(spinlock); non_block = value; return true; } /* determines this stream can be read immediately or not. */ bool http_raw_request_content::can_read() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer == nullptr || avail_bytes > 0; } bool http_raw_request_content::wanna_read(size_t spins) const { while (spins--) { if (!spinlock.try_lock()) return false; if (buffer != nullptr && read_requested) { spinlock.unlock(); return true; } spinlock.unlock(); } return false; } /* notify given bytes ready to provide. */ void http_raw_request_content::notify(size_t bytes, bool is_end) { std::lock_guard<decltype(spinlock)> guard(spinlock); avail_bytes += bytes; this->is_end = is_end; waiter.signal(); } /* link will call this before terminating the request. */ void http_raw_request_content::disconnect() { std::lock_guard<decltype(spinlock)> guard(spinlock); buffer = nullptr; read_requested = false; avail_bytes = 0; waiter.signal(); } /** * get total length of this stream. * @warn default-impl uses `tell()` and `seek()` to provide length! * @returns: * >= 0: length. * < 0: not supported. */ ssize_t http_raw_request_content::get_length() const { std::lock_guard<decltype(spinlock)> guard(spinlock); if (buffer != nullptr) { set_errno_c(0); if (total_bytes < 0) set_errno_c(ENOTSUP); return total_bytes; } set_errno_c(ENOENT); return 0; } /** * read bytes from stream. * @returns: * > 0: read size. * = 0: end of stream. * < 0: not supported or not available if non-block. * @note: * errno == EWOULDBLOCK: for non-block mode. */ int32_t http_raw_request_content::read(void* buf, size_t len) { std::lock_guard<decltype(spinlock)> guard(spinlock); return read_locked(buf, len); } int32_t http_raw_request_content::read_locked(void* buf, size_t len) { size_t read_bytes; set_errno(0); while (buffer != nullptr) { if ((read_bytes = len > avail_bytes ? avail_bytes : len) > 0) { size_t ret = buffer->read(buf, read_bytes); /* keep flag if length is less than read. */ read_requested = ret < len; avail_bytes -= ret; if (avail_bytes > 0) waiter.signal(); else waiter.unsignal(); std::this_thread::yield(); return int32_t(ret); } read_requested = true; if (non_block) { set_errno(EWOULDBLOCK); spinlock.unlock(); return -1; } if (is_end) { break; } spinlock.unlock(); std::this_thread::yield(); if (!waiter.try_wait()) waiter.wait(); spinlock.lock(); } set_errno(ENOENT); return 0; } } }
22.235294
117
0.678836
jay94ks
a08265b23ba33f1469b0f44856788185cc86b9ab
1,144
cpp
C++
EjerciciosJuez/EjerciciosJuez/dyv4.cpp
Kadaiser/UCM.FDI.EDA
97ab05c06054b90015c27fd4177ed0c3a02b6fbe
[ "Unlicense" ]
null
null
null
EjerciciosJuez/EjerciciosJuez/dyv4.cpp
Kadaiser/UCM.FDI.EDA
97ab05c06054b90015c27fd4177ed0c3a02b6fbe
[ "Unlicense" ]
null
null
null
EjerciciosJuez/EjerciciosJuez/dyv4.cpp
Kadaiser/UCM.FDI.EDA
97ab05c06054b90015c27fd4177ed0c3a02b6fbe
[ "Unlicense" ]
null
null
null
#include<iostream> using namespace std; const int N = 100000; typedef struct { int menor; int mayor; }par; par divide(int *v, int ini, int fin) { par p; if ((ini + 1) == fin) //vector de dos elementos { if (v[ini] <= v[fin])//decidir mayor/menor { p.menor = v[ini]; p.mayor = v[fin]; } else { p.menor = v[fin]; p.mayor = v[ini]; } } else //dividir y resolver { par izq, der; int mitad = ((fin - ini) / 2) + ini; izq = divide(v, ini, mitad); der = divide(v, mitad + 1, fin); (izq.menor <= der.menor) ? p.menor = izq.menor : p.menor = der.menor; (izq.mayor <= der.mayor) ? p.mayor = der.mayor : p.mayor = izq.mayor; } return p; } int main() { int primero, longitud, valor; int v[N] = { 0 }; par izq, der; while (cin >> primero, primero != 0) { longitud = 0; v[longitud] = primero; while (cin >> valor, valor != 0) { longitud++; v[longitud] = valor; } izq = divide(v, 0, longitud / 2); der = divide(v, (longitud / 2) + 1, longitud); if (izq.menor <= der.menor && izq.mayor<=der.mayor) cout << "SI" << '\n'; else cout << "NO" << '\n'; } return 0; }
16.112676
71
0.548951
Kadaiser
a084e4bea63910d8e7bec1b30b26238694bbb5a2
16,607
cpp
C++
Wexport/release/windows/obj/src/openfl/display3D/_internal/_AGALConverter/SourceRegister.cpp
BushsHaxs/FNF-coding-tutorial
596c6a938eb687440cbcddda9a4005db67bc68bb
[ "Apache-2.0" ]
1
2021-07-19T05:10:43.000Z
2021-07-19T05:10:43.000Z
Wexport/release/windows/obj/src/openfl/display3D/_internal/_AGALConverter/SourceRegister.cpp
BushsHaxs/FNF-coding-tutorial
596c6a938eb687440cbcddda9a4005db67bc68bb
[ "Apache-2.0" ]
null
null
null
Wexport/release/windows/obj/src/openfl/display3D/_internal/_AGALConverter/SourceRegister.cpp
BushsHaxs/FNF-coding-tutorial
596c6a938eb687440cbcddda9a4005db67bc68bb
[ "Apache-2.0" ]
1
2021-12-11T09:19:29.000Z
2021-12-11T09:19:29.000Z
#include <hxcpp.h> #ifndef INCLUDED_38344beec7696400 #define INCLUDED_38344beec7696400 #include "cpp/Int64.h" #endif #ifndef INCLUDED_openfl_display3D__internal_AGALConverter #include <openfl/display3D/_internal/AGALConverter.h> #endif #ifndef INCLUDED_openfl_display3D__internal__AGALConverter_ProgramType #include <openfl/display3D/_internal/_AGALConverter/ProgramType.h> #endif #ifndef INCLUDED_openfl_display3D__internal__AGALConverter_SourceRegister #include <openfl/display3D/_internal/_AGALConverter/SourceRegister.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_6326831c4b7b616c_961_new,"openfl.display3D._internal._AGALConverter.SourceRegister","new",0xa0d15d23,"openfl.display3D._internal._AGALConverter.SourceRegister.new","openfl/display3D/_internal/AGALConverter.hx",961,0x4de1651d) HX_LOCAL_STACK_FRAME(_hx_pos_6326831c4b7b616c_979_toGLSL,"openfl.display3D._internal._AGALConverter.SourceRegister","toGLSL",0x906ee816,"openfl.display3D._internal._AGALConverter.SourceRegister.toGLSL","openfl/display3D/_internal/AGALConverter.hx",979,0x4de1651d) HX_LOCAL_STACK_FRAME(_hx_pos_6326831c4b7b616c_964_parse,"openfl.display3D._internal._AGALConverter.SourceRegister","parse",0xa1e213b6,"openfl.display3D._internal._AGALConverter.SourceRegister.parse","openfl/display3D/_internal/AGALConverter.hx",964,0x4de1651d) HX_LOCAL_STACK_FRAME(_hx_pos_6326831c4b7b616c_949_boot,"openfl.display3D._internal._AGALConverter.SourceRegister","boot",0x0e79220f,"openfl.display3D._internal._AGALConverter.SourceRegister.boot","openfl/display3D/_internal/AGALConverter.hx",949,0x4de1651d) namespace openfl{ namespace display3D{ namespace _internal{ namespace _AGALConverter{ void SourceRegister_obj::__construct(){ HX_STACKFRAME(&_hx_pos_6326831c4b7b616c_961_new) } Dynamic SourceRegister_obj::__CreateEmpty() { return new SourceRegister_obj; } void *SourceRegister_obj::_hx_vtable = 0; Dynamic SourceRegister_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< SourceRegister_obj > _hx_result = new SourceRegister_obj(); _hx_result->__construct(); return _hx_result; } bool SourceRegister_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x5dd77f8b; } ::String SourceRegister_obj::toGLSL(::hx::Null< bool > __o_emitSwizzle,::hx::Null< int > __o_offset){ bool emitSwizzle = __o_emitSwizzle.Default(true); int offset = __o_offset.Default(0); HX_STACKFRAME(&_hx_pos_6326831c4b7b616c_979_toGLSL) HXLINE( 980) if ((this->type == 3)) { HXLINE( 982) if (::hx::IsPointerEq( this->programType,::openfl::display3D::_internal::_AGALConverter::ProgramType_obj::VERTEX_dyn() )) { HXLINE( 982) return HX_("gl_Position",63,0d,2a,e5); } else { HXLINE( 982) return HX_("gl_FragColor",d7,68,e4,21); } } HXLINE( 985) bool fullxyzw; HXDLIN( 985) if ((this->s == 228)) { HXLINE( 985) fullxyzw = (this->sourceMask == 15); } else { HXLINE( 985) fullxyzw = false; } HXLINE( 986) ::String swizzle = HX_("",00,00,00,00); HXLINE( 988) bool _hx_tmp; HXDLIN( 988) if ((this->type != 5)) { HXLINE( 988) _hx_tmp = !(fullxyzw); } else { HXLINE( 988) _hx_tmp = false; } HXDLIN( 988) if (_hx_tmp) { HXLINE( 993) if (((this->sourceMask & 1) != 0)) { HXLINE( 995) switch((int)((this->s & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } HXLINE( 993) if (((this->sourceMask & 2) != 0)) { HXLINE( 995) switch((int)(((this->s >> 2) & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } HXLINE( 993) if (((this->sourceMask & 4) != 0)) { HXLINE( 995) switch((int)(((this->s >> 4) & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } HXLINE( 993) if (((this->sourceMask & 8) != 0)) { HXLINE( 995) switch((int)(((this->s >> 6) & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } } HXLINE(1010) ::String str = ::openfl::display3D::_internal::AGALConverter_obj::prefixFromType(this->type,this->programType); HXLINE(1012) if ((this->d == 0)) { HXLINE(1015) str = (str + (this->n + offset)); } else { HXLINE(1020) str = (str + this->o); HXLINE(1021) ::String indexComponent = HX_("",00,00,00,00); HXLINE(1022) switch((int)(this->q)){ case (int)0: { HXLINE(1025) indexComponent = HX_("x",78,00,00,00); } break; case (int)1: { HXLINE(1027) indexComponent = HX_("y",79,00,00,00); } break; case (int)2: { HXLINE(1029) indexComponent = HX_("z",7a,00,00,00); } break; case (int)3: { HXLINE(1031) indexComponent = HX_("w",77,00,00,00); } break; } HXLINE(1033) ::String indexRegister = ::openfl::display3D::_internal::AGALConverter_obj::prefixFromType(this->itype,this->programType); HXDLIN(1033) ::String indexRegister1 = (((indexRegister + this->n) + HX_(".",2e,00,00,00)) + indexComponent); HXLINE(1034) str = (str + ((((HX_("[ int(",3e,aa,07,15) + indexRegister1) + HX_(") +",74,38,1f,00)) + offset) + HX_("]",5d,00,00,00))); } HXLINE(1037) bool _hx_tmp1; HXDLIN(1037) if (emitSwizzle) { HXLINE(1037) _hx_tmp1 = (swizzle != HX_("",00,00,00,00)); } else { HXLINE(1037) _hx_tmp1 = false; } HXDLIN(1037) if (_hx_tmp1) { HXLINE(1039) str = (str + (HX_(".",2e,00,00,00) + swizzle)); } HXLINE(1042) return str; } HX_DEFINE_DYNAMIC_FUNC2(SourceRegister_obj,toGLSL,return ) ::openfl::display3D::_internal::_AGALConverter::SourceRegister SourceRegister_obj::parse( cpp::Int64Struct v, ::openfl::display3D::_internal::_AGALConverter::ProgramType programType,int sourceMask){ HX_GC_STACKFRAME(&_hx_pos_6326831c4b7b616c_964_parse) HXLINE( 965) ::openfl::display3D::_internal::_AGALConverter::SourceRegister sr = ::openfl::display3D::_internal::_AGALConverter::SourceRegister_obj::__alloc( HX_CTX ); HXLINE( 966) sr->programType = programType; HXLINE( 967) cpp::Int64Struct a = _hx_int64_shr(v,63); HXDLIN( 967) sr->d = _hx_int64_low(_hx_int64_and(a,( ::cpp::Int64Struct(1)))); HXLINE( 968) cpp::Int64Struct a1 = _hx_int64_shr(v,48); HXDLIN( 968) sr->q = _hx_int64_low(_hx_int64_and(a1,( ::cpp::Int64Struct(3)))); HXLINE( 969) cpp::Int64Struct a2 = _hx_int64_shr(v,40); HXDLIN( 969) sr->itype = _hx_int64_low(_hx_int64_and(a2,( ::cpp::Int64Struct(15)))); HXLINE( 970) cpp::Int64Struct a3 = _hx_int64_shr(v,32); HXDLIN( 970) sr->type = _hx_int64_low(_hx_int64_and(a3,( ::cpp::Int64Struct(15)))); HXLINE( 971) cpp::Int64Struct a4 = _hx_int64_shr(v,24); HXDLIN( 971) sr->s = _hx_int64_low(_hx_int64_and(a4,( ::cpp::Int64Struct(255)))); HXLINE( 972) cpp::Int64Struct a5 = _hx_int64_shr(v,16); HXDLIN( 972) sr->o = _hx_int64_low(_hx_int64_and(a5,( ::cpp::Int64Struct(255)))); HXLINE( 973) sr->n = _hx_int64_low(_hx_int64_and(v,( ::cpp::Int64Struct(65535)))); HXLINE( 974) sr->sourceMask = sourceMask; HXLINE( 975) return sr; } STATIC_HX_DEFINE_DYNAMIC_FUNC3(SourceRegister_obj,parse,return ) ::hx::ObjectPtr< SourceRegister_obj > SourceRegister_obj::__new() { ::hx::ObjectPtr< SourceRegister_obj > __this = new SourceRegister_obj(); __this->__construct(); return __this; } ::hx::ObjectPtr< SourceRegister_obj > SourceRegister_obj::__alloc(::hx::Ctx *_hx_ctx) { SourceRegister_obj *__this = (SourceRegister_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(SourceRegister_obj), true, "openfl.display3D._internal._AGALConverter.SourceRegister")); *(void **)__this = SourceRegister_obj::_hx_vtable; __this->__construct(); return __this; } SourceRegister_obj::SourceRegister_obj() { } void SourceRegister_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(SourceRegister); HX_MARK_MEMBER_NAME(d,"d"); HX_MARK_MEMBER_NAME(itype,"itype"); HX_MARK_MEMBER_NAME(n,"n"); HX_MARK_MEMBER_NAME(o,"o"); HX_MARK_MEMBER_NAME(programType,"programType"); HX_MARK_MEMBER_NAME(q,"q"); HX_MARK_MEMBER_NAME(s,"s"); HX_MARK_MEMBER_NAME(sourceMask,"sourceMask"); HX_MARK_MEMBER_NAME(type,"type"); HX_MARK_END_CLASS(); } void SourceRegister_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(d,"d"); HX_VISIT_MEMBER_NAME(itype,"itype"); HX_VISIT_MEMBER_NAME(n,"n"); HX_VISIT_MEMBER_NAME(o,"o"); HX_VISIT_MEMBER_NAME(programType,"programType"); HX_VISIT_MEMBER_NAME(q,"q"); HX_VISIT_MEMBER_NAME(s,"s"); HX_VISIT_MEMBER_NAME(sourceMask,"sourceMask"); HX_VISIT_MEMBER_NAME(type,"type"); } ::hx::Val SourceRegister_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"d") ) { return ::hx::Val( d ); } if (HX_FIELD_EQ(inName,"n") ) { return ::hx::Val( n ); } if (HX_FIELD_EQ(inName,"o") ) { return ::hx::Val( o ); } if (HX_FIELD_EQ(inName,"q") ) { return ::hx::Val( q ); } if (HX_FIELD_EQ(inName,"s") ) { return ::hx::Val( s ); } break; case 4: if (HX_FIELD_EQ(inName,"type") ) { return ::hx::Val( type ); } break; case 5: if (HX_FIELD_EQ(inName,"itype") ) { return ::hx::Val( itype ); } break; case 6: if (HX_FIELD_EQ(inName,"toGLSL") ) { return ::hx::Val( toGLSL_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"sourceMask") ) { return ::hx::Val( sourceMask ); } break; case 11: if (HX_FIELD_EQ(inName,"programType") ) { return ::hx::Val( programType ); } } return super::__Field(inName,inCallProp); } bool SourceRegister_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"parse") ) { outValue = parse_dyn(); return true; } } return false; } ::hx::Val SourceRegister_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"d") ) { d=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"n") ) { n=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"o") ) { o=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"q") ) { q=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"s") ) { s=inValue.Cast< int >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< int >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"itype") ) { itype=inValue.Cast< int >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"sourceMask") ) { sourceMask=inValue.Cast< int >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"programType") ) { programType=inValue.Cast< ::openfl::display3D::_internal::_AGALConverter::ProgramType >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void SourceRegister_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("d",64,00,00,00)); outFields->push(HX_("itype",a3,db,1b,c2)); outFields->push(HX_("n",6e,00,00,00)); outFields->push(HX_("o",6f,00,00,00)); outFields->push(HX_("programType",5e,fb,2c,c4)); outFields->push(HX_("q",71,00,00,00)); outFields->push(HX_("s",73,00,00,00)); outFields->push(HX_("sourceMask",67,27,ba,70)); outFields->push(HX_("type",ba,f2,08,4d)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo SourceRegister_obj_sMemberStorageInfo[] = { {::hx::fsInt,(int)offsetof(SourceRegister_obj,d),HX_("d",64,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,itype),HX_("itype",a3,db,1b,c2)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,n),HX_("n",6e,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,o),HX_("o",6f,00,00,00)}, {::hx::fsObject /* ::openfl::display3D::_internal::_AGALConverter::ProgramType */ ,(int)offsetof(SourceRegister_obj,programType),HX_("programType",5e,fb,2c,c4)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,q),HX_("q",71,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,s),HX_("s",73,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,sourceMask),HX_("sourceMask",67,27,ba,70)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,type),HX_("type",ba,f2,08,4d)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *SourceRegister_obj_sStaticStorageInfo = 0; #endif static ::String SourceRegister_obj_sMemberFields[] = { HX_("d",64,00,00,00), HX_("itype",a3,db,1b,c2), HX_("n",6e,00,00,00), HX_("o",6f,00,00,00), HX_("programType",5e,fb,2c,c4), HX_("q",71,00,00,00), HX_("s",73,00,00,00), HX_("sourceMask",67,27,ba,70), HX_("type",ba,f2,08,4d), HX_("toGLSL",f9,58,08,7a), ::String(null()) }; ::hx::Class SourceRegister_obj::__mClass; static ::String SourceRegister_obj_sStaticFields[] = { HX_("parse",33,90,55,bd), ::String(null()) }; void SourceRegister_obj::__register() { SourceRegister_obj _hx_dummy; SourceRegister_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("openfl.display3D._internal._AGALConverter.SourceRegister",b1,8f,b5,4c); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &SourceRegister_obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(SourceRegister_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(SourceRegister_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< SourceRegister_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = SourceRegister_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = SourceRegister_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void SourceRegister_obj::__boot() { { HX_STACKFRAME(&_hx_pos_6326831c4b7b616c_949_boot) HXDLIN( 949) __mClass->__meta__ = ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("obj",f7,8f,54,00), ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:FieldDocComment",70,56,1b,20)))))); } } } // end namespace openfl } // end namespace display3D } // end namespace _internal } // end namespace _AGALConverter
39.729665
263
0.637924
BushsHaxs
a0854cdc46be26319f323a521cc75876e4b9e912
377
cpp
C++
codelib/dynamic_programming/knapsack2.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/dynamic_programming/knapsack2.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/dynamic_programming/knapsack2.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> int main() { int N, C; std::cin >> N >> C; int W[N], V[N]; for (int i = 0; i < N; ++i) std::cin >> W[i] >> V[i]; int dp[C + 1]; memset(dp, 0, sizeof dp); for (int w = 0; w <= C; ++w) for (int i = 0; i < N; ++i) dp[w] = (w < W[i]) ? dp[w] : dp[w - W[i]] + V[i]; std::cout << dp[C] << "\n"; return 0; }
17.952381
55
0.416446
TissueRoll
a0875bc7620f11832ee4b123d023c6d15c691c98
591
cc
C++
algo/dp/palindrome.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/dp/palindrome.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/dp/palindrome.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> #include <string> using namespace std; int minCut(const string &s) { int N = s.length(); bool p[N][N]; int f[N+1]; for (int j=0; j<=N; ++j) { f[j] = j-1; p[j][j] = true; for (int i=0; i<j; ++i) { if (s.at(i) == s.at(j-1) && (j - i < 2 || p[i+1][j-1])) { p[i][j] = true; f[j] = min(f[j], f[i]+1); } else { p[i][j] = false; } } } return f[N]; } int main() { printf("%d\n", minCut("abcbc")); return 0; }
19.7
69
0.382403
liuheng
a087ce3c898567dc12a5de7b6fa9cb3c1796b19e
420
cpp
C++
_learning/cpp/karan.cpp
kerbless/uncoding
4da2d3c497a1ab57ac28e2668d09ba4edf7a42e3
[ "MIT" ]
null
null
null
_learning/cpp/karan.cpp
kerbless/uncoding
4da2d3c497a1ab57ac28e2668d09ba4edf7a42e3
[ "MIT" ]
null
null
null
_learning/cpp/karan.cpp
kerbless/uncoding
4da2d3c497a1ab57ac28e2668d09ba4edf7a42e3
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> unsing namespace std; struct karan_list { char* name; int price; karan_list* pointer_to_itself; } banana; class karan_class { karan_list*; public: } //karan_list banana; //same thing as line 9 "banana" int main(int argc, char *argv[]) { //karan_list banana; //same thing as line 9 "banana" BUT scoped on main cout << "Hello, World!"; return 0; }
19.090909
75
0.661905
kerbless
a0881f28bc370a9ebdef061cf2c9d6948b6822e0
39,119
cpp
C++
tests/get_kv_table_nodeos_tests.cpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
13,162
2017-05-29T22:08:27.000Z
2022-03-29T19:25:05.000Z
tests/get_kv_table_nodeos_tests.cpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
6,450
2017-05-30T14:41:50.000Z
2022-03-30T11:30:04.000Z
tests/get_kv_table_nodeos_tests.cpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
4,491
2017-05-29T22:08:32.000Z
2022-03-29T07:09:52.000Z
#include <boost/test/unit_test.hpp> #include <boost/algorithm/string/predicate.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/abi_serializer.hpp> #include <eosio/chain/wasm_eosio_constraints.hpp> #include <eosio/chain/resource_limits.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/wast_to_wasm.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/chain/backing_store/kv_context.hpp> #include <contracts.hpp> #include <fc/io/fstream.hpp> #include <Runtime/Runtime.h> #include <fc/variant_object.hpp> #include <fc/io/json.hpp> #include <array> #include <utility> #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif BOOST_AUTO_TEST_SUITE(get_kv_table_nodeos_tests) using namespace eosio::chain; using namespace eosio::testing; using namespace fc; BOOST_FIXTURE_TEST_CASE( get_kv_table_nodeos_test, TESTER ) try { eosio::chain_apis::read_only::get_table_rows_result result; auto chk_result = [&](int row, int data, bool show_payer = false) { char bar[5] = {'b', 'o', 'b', 'a', 0}; bar[3] += data - 1; // 'a' + data - 1 auto& row_value = result.rows[row]; auto check_row_value_data = [&data, &bar](const auto& v) { BOOST_CHECK_EQUAL(bar, v["primary_key"].as_string()); BOOST_CHECK_EQUAL(bar, v["bar"]); BOOST_CHECK_EQUAL(std::to_string(data), v["foo"].as_string()); }; if (show_payer) { BOOST_CHECK_EQUAL(row_value["payer"].as_string(), "kvtable"); check_row_value_data(row_value["data"]); } else { check_row_value_data(row_value); } }; produce_blocks(2); create_accounts({"kvtable"_n}); produce_block(); set_code(config::system_account_name, contracts::kv_bios_wasm()); set_abi(config::system_account_name, contracts::kv_bios_abi().data()); push_action("eosio"_n, "ramkvlimits"_n, "eosio"_n, mutable_variant_object()("k", 1024)("v", 1024)("i", 1024)); produce_blocks(1); set_code("kvtable"_n, contracts::kv_table_test_wasm()); set_abi("kvtable"_n, contracts::kv_table_test_abi().data()); produce_blocks(1); auto arg = mutable_variant_object(); push_action("kvtable"_n, "setup"_n, "kvtable"_n, arg); ////////////////////////////// // primarykey ////////////////////////////// eosio::chain_apis::read_only plugin(*(this->control), {}, fc::microseconds::maximum()); eosio::chain_apis::read_only::get_kv_table_rows_params p; p.code = "kvtable"_n; p.table = "kvtable"_n; p.index_name = "primarykey"_n; p.index_value = "boba"; p.encode_type = "name"; p.lower_bound = {}; p.upper_bound = {}; p.json = true; p.reverse = false; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.show_payer = true; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1, p.show_payer); p.show_payer = false; p.reverse = true; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.reverse = false; p.index_name = "primarykey"_n; p.index_value = "bobj"; p.encode_type = ""; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.encode_type = "name"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.encode_type = "name"; p.index_value = "bob"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.index_value = "bobx"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.show_payer = true; p.index_value = {}; p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 2, p.show_payer); chk_result(1, 3, p.show_payer); chk_result(2, 4, p.show_payer); chk_result(3, 5, p.show_payer); p.index_value = "boba"; p.lower_bound = "bobb"; p.upper_bound = "bobe"; BOOST_CHECK_THROW(plugin.read_only::get_kv_table_rows(p), contract_table_query_exception); p.index_value = {}; p.lower_bound = "bobe"; p.upper_bound = "bobb"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.show_payer = false; p.lower_bound = "aaaa"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); chk_result(9, 10); p.lower_bound = "boba"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(9, 10); p.lower_bound = "bobj"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.lower_bound = "bobz"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.lower_bound = "bob"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.reverse = true; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); chk_result(9, 1); p.reverse = true; p.lower_bound = "bobc"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(8u, result.rows.size()); p.reverse = false; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "bobc"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(8u, result.rows.size()); p.reverse = false; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.reverse = true; p.lower_bound = "bobj"; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); p.lower_bound = ""; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); chk_result(4, 1); p.reverse = false; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); chk_result(0, 3); chk_result(1, 4); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 1; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 5); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); // test next_key p.index_name = "primarykey"_n; p.index_value = {}; p.reverse = false; p.encode_type = "name"; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobc"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0E800000000000"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.next_key, "bobe"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0EA00000000000"); chk_result(0, 3); chk_result(1, 4); p.lower_bound = result.next_key; p.limit = 1; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobf"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0EB00000000000"); chk_result(0, 5); p.lower_bound = result.next_key; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); p.reverse = true; p.upper_bound = "bobj"; p.lower_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobh"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0ED00000000000"); chk_result(0, 10); chk_result(1, 9); p.upper_bound = result.next_key; p.limit = 7; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(7u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "boba"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0E600000000000"); chk_result(0, 8); chk_result(1, 7); chk_result(2, 6); chk_result(3, 5); chk_result(4, 4); chk_result(5, 3); chk_result(6, 2); p.upper_bound = result.next_key; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 1); ////////////////////////////// // foo ////////////////////////////// p.reverse = false; p.index_name = "foo"_n; p.index_value = "A"; // 10 p.encode_type = "hex"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = "10"; p.encode_type = ""; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = "10"; p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = {}; p.encode_type = "hex"; p.lower_bound = "1"; p.upper_bound = "10"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0"; p.upper_bound = "10"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.lower_bound = "2"; p.upper_bound = "9"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(8u, result.rows.size()); chk_result(0, 2); chk_result(1, 3); chk_result(2, 4); chk_result(3, 5); chk_result(4, 6); chk_result(5, 7); chk_result(6, 8); chk_result(7, 9); p.lower_bound = "0"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.lower_bound = "1"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.lower_bound = "10"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.lower_bound = "11"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.reverse = false; p.lower_bound = "0"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); // test next_key p.index_name = "foo"_n; p.reverse = false; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(3)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000003"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(6)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000006"); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key; p.limit = 4; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(10)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "000000000000000A"); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); p.encode_type = "hex"; p.lower_bound = "0"; p.upper_bound = {}; p.limit = 4; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(5)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000005"); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); p.lower_bound = result.next_key; p.limit = 5; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "A"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "000000000000000A"); chk_result(0, 5); chk_result(1, 6); chk_result(2, 7); chk_result(3, 8); chk_result(4, 9); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); p.lower_bound = "10"; p.limit = 20; //maximize limit for the following test cases result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); ////////////////////////////// // bar ////////////////////////////// p.index_name = "bar"_n; p.index_value = "boba"; p.encode_type = ""; p.lower_bound = {}; p.upper_bound = {}; p.reverse = false; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.encode_type = "string"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.index_value = "bobj"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = "bobx"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.index_value = {}; p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 2); chk_result(1, 3); chk_result(2, 4); chk_result(3, 5); p.index_value = {}; p.lower_bound = "boba1"; p.upper_bound = "bobj"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.index_value = {}; p.lower_bound = "boba"; p.upper_bound = "bobj1"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.lower_bound = "boba"; p.upper_bound = "c"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.lower_bound = "a"; p.upper_bound = "c"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "aaaa"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); p.lower_bound = "boba"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); p.lower_bound = "bobj"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.lower_bound = "bobz"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.lower_bound = "b"; p.upper_bound = "bobj1"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "bobj"; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.reverse = true; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 10); p.lower_bound = "b"; p.upper_bound = "bobj1"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "bobj"; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); p.lower_bound = {}; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); chk_result(4, 1); p.reverse = false; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key_bytes; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); // test next_key p.index_name = "bar"_n; p.encode_type = "string"; p.reverse = false; p.index_value = {}; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobc"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "626F62630000"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobf"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "626F62660000"); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); ////////////////////////////// // uint32_t : 0, 10, 20,..., 80, 90 ////////////////////////////// p.reverse = false; p.index_name = "u"_n; p.index_value = "A"; // 10 p.encode_type = "hex"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.index_value = {}; p.encode_type = ""; p.lower_bound = "10"; p.upper_bound = "100"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0"; p.upper_bound = "110"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); ////////////////////////////// // int32_t : -40, -30,..., 40, 50 ////////////////////////////// p.reverse = false; p.index_name = "i"_n; p.index_value = "A"; p.encode_type = "hex"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 6); p.index_value = {}; p.encode_type = ""; p.lower_bound = "-10"; p.upper_bound = "100"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(7u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(7u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-100"; p.upper_bound = "100"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-100"; p.upper_bound = "100"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.upper_bound = {}; p.encode_type = "bytes"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 3); chk_result(1, 4); // test next_key p.reverse = false; p.index_name = "i"_n; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-100"; p.upper_bound = "100"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(-20)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "7FFFFFEC"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(0)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "80000000"); chk_result(0, 3); chk_result(1, 4); ////////////////////////////// // int64_t : -400, -300,...,400, 500 ////////////////////////////// p.reverse = false; p.index_name = "ii"_n; p.index_value = "100"; p.encode_type = "dec"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 6); p.index_value = {}; p.encode_type = ""; p.lower_bound = "-100"; p.upper_bound = "100"; p.limit = 10; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-1000"; p.upper_bound = "1000"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-1000"; p.upper_bound = "1000"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 1); chk_result(1, 2); p.encode_type = "bytes"; p.lower_bound = result.next_key_bytes; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 3); chk_result(1, 4); // test next_key p.reverse = false; p.index_name = "ii"_n; p.encode_type = "dec"; p.index_value = {}; p.lower_bound = "-1000"; p.upper_bound = "1000"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(-200)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "7FFFFFFFFFFFFF38"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(0)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "8000000000000000"); chk_result(0, 3); chk_result(1, 4); ////////////////////////////// // double: 0, 1.01, 2.02,..., 9.09 ////////////////////////////// p.reverse = false; p.index_name = "ff"_n; p.index_value = {}; p.encode_type = ""; p.lower_bound = "0.0"; p.upper_bound = "100"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.001"; p.upper_bound = "1000.0"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); chk_result(0, 2); chk_result(1, 3); chk_result(2, 4); chk_result(3, 5); chk_result(4, 6); chk_result(5, 7); chk_result(6, 8); chk_result(7, 9); chk_result(8, 10); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.001"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); chk_result(0, 2); chk_result(8, 10); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-0.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-10.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.00001"; p.upper_bound = "10.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.reverse = true; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.0"; p.upper_bound = "100"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.001"; p.upper_bound = "1000.0"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = {}; p.upper_bound = "4.039999999"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-0.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-10.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.00001"; p.upper_bound = "10.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.reverse = false; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.02"; p.upper_bound = "3.03000001"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 2); chk_result(1, 3); p.encode_type = "bytes"; p.lower_bound = result.next_key_bytes; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 4); chk_result(1, 5); // test next_key p.reverse = false; p.index_name = "ff"_n; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-0.02"; p.upper_bound = "-0.01"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("2.02") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C00028F5C28F5C29"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("4.04") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C01028F5C28F5C29"); chk_result(0, 3); chk_result(1, 4); p.lower_bound = "0.02"; p.upper_bound = "3.03000001"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("3.03") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C0083D70A3D70A3D"); chk_result(0, 2); chk_result(1, 3); p.lower_bound = result.next_key; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("5.05") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C014333333333333"); chk_result(0, 4); chk_result(1, 5); // test no --lower, --upper, and --index with different --limit p.reverse = false; p.index_name = "foo"_n; p.encode_type = "dec"; p.index_value = {}; p.lower_bound = {}; p.upper_bound = {}; p.limit = 9; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(10)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "000000000000000A"); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); chk_result(9, 10); p.reverse = true; p.limit = 9; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(1)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000001"); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); chk_result(9, 1); // test default lower bound p.reverse = false; p.lower_bound = {}; p.upper_bound = "9"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); // test default upper bound p.reverse = true; p.lower_bound = "2"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); } FC_LOG_AND_RETHROW() BOOST_AUTO_TEST_SUITE_END()
29.568405
113
0.657839
forfreeday
a0885664a8581abe9dee5a5222aa1b2ec1f917fa
853
cpp
C++
CodeForces/Complete/300-399/367A-SerejaAndAlgorithm.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/300-399/367A-SerejaAndAlgorithm.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/300-399/367A-SerejaAndAlgorithm.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <iostream> #include <string> #include <vector> #include <algorithm> int main(){ std::string input; getline(std::cin, input); std::vector<std::vector<long> > counts(1 + input.size(), std::vector<long>(3,0)); for(long p = 1; p <= input.size(); p++){ for(long q = 0; q < 3; q++){counts[p][q] = counts[p - 1][q] + (input[p - 1] == 'x' + q);} } long m(0); scanf("%ld", &m); while(m--){ long start(0), end(0); scanf("%ld %ld", &start, &end); std::vector<long> dist(3); for(int q = 0; q < 3; q++){dist[q] = counts[end][q] - counts[start - 1][q];} sort(dist.begin(), dist.end()); //std::cout << input.substr(start - 1, end - start + 1) << "\t"; if(end - start + 1 < 3 || dist[2] - dist[0] <= 1){puts("YES");} else{puts("NO");} } return 0; }
30.464286
97
0.502931
Ashwanigupta9125
a08a2380c9836f91a03bd0327e1d35993eb3e767
3,370
cpp
C++
kernel/arch/x86_64/device/acpi.cpp
fengjixuchui/WingOS
5ab44c9748888bba677c08e8332b6c84bc2374f6
[ "BSD-2-Clause" ]
null
null
null
kernel/arch/x86_64/device/acpi.cpp
fengjixuchui/WingOS
5ab44c9748888bba677c08e8332b6c84bc2374f6
[ "BSD-2-Clause" ]
null
null
null
kernel/arch/x86_64/device/acpi.cpp
fengjixuchui/WingOS
5ab44c9748888bba677c08e8332b6c84bc2374f6
[ "BSD-2-Clause" ]
null
null
null
#include <com.h> #include <device/acpi.h> #include <device/apic.h> #include <logging.h> #include <utility.h> #include <virtual.h> acpi main_acpi; void *get_rsdp(void) { for (uintptr_t i = get_mem_addr(0x80000); i < get_mem_addr(0x100000); i += 16) { if (i == get_mem_addr(0xa0000)) { i = get_mem_addr(0xe0000 - 16); continue; } if (!strncmp((char *)i, "RSD PTR ", 8)) { return (void *)i; } } return nullptr; } acpi::acpi() { } void *acpi::find_entry(const char *entry_name) { RSDT *rsdt = get_mem_addr<RSDT *>((descriptor->firstPart.RSDT_address)); int entries = (rsdt->h.Length - sizeof(rsdt->h)) / 4; for (int i = 0; i < entries; i++) { if (rsdt->PointerToOtherSDT[i] == 0) { continue; } RSDTHeader *h = get_mem_addr<RSDTHeader *>((rsdt->PointerToOtherSDT[i])); if (!strncmp(h->Signature, entry_name, 4)) { return (void *)h; } } // Not found return nullptr; } void *findFACP(void *RootSDT) { RSDT *rsdt = reinterpret_cast<RSDT *>(RootSDT); int entries = (rsdt->h.Length - sizeof(rsdt->h)) / 4; for (int i = 0; i < entries; i++) { if (rsdt->PointerToOtherSDT[i] == 0) { continue; } RSDTHeader *h = reinterpret_cast<RSDTHeader *>(rsdt->PointerToOtherSDT[i]); if (!strncmp(h->Signature, "FACP", 4)) { return (void *)h; } } // No FACP found return nullptr; } void acpi::init(uint64_t rsdp) { log("acpi", LOG_DEBUG, "loading acpi"); descriptor = (RSDPDescriptor20 *)get_rsdp(); rsdt_table = get_mem_addr<RSDT *>(descriptor->firstPart.RSDT_address); log("rsdt", LOG_DEBUG, "logging rsdt"); RSDT *rsdt = get_mem_addr<RSDT *>((descriptor->firstPart.RSDT_address)); int entries = (rsdt->h.Length - sizeof(rsdt->h)) / 4; for (int i = 0; i < entries; i++) { if (rsdt->PointerToOtherSDT[i] == 0) { continue; } RSDTHeader *h = get_mem_addr<RSDTHeader *>((rsdt->PointerToOtherSDT[i])); log("rsdt", LOG_INFO, "entry: {}, signature: {}, EOM: {} ", i, range_str(h->Signature, 4), range_str(h->OEMID, 6)); } } void acpi::init_in_paging() { RSDT *rsdt = rsdt_table; int entries = (rsdt->h.Length - sizeof(rsdt->h)) / 4; uintptr_t ddat = ALIGN_DOWN((uintptr_t)rsdt, PAGE_SIZE); map_page(ddat, get_mem_addr(ddat), true, false); map_page(ddat + PAGE_SIZE, get_mem_addr(ddat + PAGE_SIZE), true, false); rsdt = (RSDT *)get_mem_addr((uint64_t)rsdt); for (int i = 0; i < entries; i++) { uint64_t addr = rsdt->PointerToOtherSDT[i]; addr = ALIGN_DOWN(addr, PAGE_SIZE); map_page(addr, get_mem_addr(addr), true, false); map_page(addr + PAGE_SIZE, get_mem_addr(addr + PAGE_SIZE), true, false); map_page(addr + (PAGE_SIZE * 2), get_mem_addr(addr + (PAGE_SIZE * 2)), true, false); } } void acpi::getFACP() { RSDT *rsdt = (RSDT *)rsdt_table; int entries = (rsdt->h.Length - sizeof(rsdt->h)) / 4; for (int i = 0; i < entries; i++) { if (rsdt->PointerToOtherSDT[i] == 0) { continue; } } } acpi *acpi::the() { return &main_acpi; }
22.466667
123
0.557567
fengjixuchui
a08dcd49634673392fcca1df1e110bcc82239866
12,147
cpp
C++
psx/_dump_/_dump_merge_c_src_/diabpsx/psxsrc/glue.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
null
null
null
psx/_dump_/_dump_merge_c_src_/diabpsx/psxsrc/glue.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
null
null
null
psx/_dump_/_dump_merge_c_src_/diabpsx/psxsrc/glue.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
null
null
null
// C:\diabpsx\PSXSRC\GLUE.CPP #include "types.h" // address: 0x8009250C // line start: 417 // line end: 569 void BgTask__FP4TASK(struct TASK *T) { // register: 2 // size: 0x10 register struct DEF_ARGS *Args; // register: 19 register bool IsTown; // register: 16 register int TextId; // register: 17 register int Level; // register: 18 register int ObjId; // register: 20 register int List; // address: 0xFFFFFDE0 // size: 0xDC auto struct CBlocks_dup_1 MyBlocks; // address: 0xFFFFFEC0 // size: 0x80 auto struct CPlayer_dup_1 MyPlayer; // address: 0xFFFFFF40 // size: 0x80 auto struct CPlayer_dup_1 MyPlayer2; // address: 0xFFFFFFC0 // size: 0x10 auto struct GPanel_dup_1 P1Panel; // address: 0xFFFFFFD0 // size: 0x10 auto struct GPanel_dup_1 P2Panel; } // address: 0x8008EFEC // line start: 417 // line end: 572 void BgTask__FP4TASK_addr_8008EFEC(struct TASK *T) { // register: 2 // size: 0x10 register struct DEF_ARGS *Args; // register: 19 register bool IsTown; // register: 16 register int TextId; // register: 17 register int Level; // register: 18 register int ObjId; // register: 20 register int List; // address: 0xFFFFFDD0 // size: 0xE0 auto struct CBlocks MyBlocks; // address: 0xFFFFFEB0 // size: 0x84 auto struct CPlayer MyPlayer; // address: 0xFFFFFF38 // size: 0x84 auto struct CPlayer MyPlayer2; // address: 0xFFFFFFC0 // size: 0x10 auto struct GPanel P1Panel; // address: 0xFFFFFFD0 // size: 0x10 auto struct GPanel P2Panel; } // address: 0x80091A00 // line start: 430 // line end: 612 void BgTask__FP4TASK_addr_80091A00(struct TASK *T) { // register: 2 // size: 0x10 register struct DEF_ARGS *Args; // register: 18 register bool IsTown; // register: 16 register int TextId; // register: 17 register int Level; // register: 19 register int ObjId; // register: 20 register int List; // address: 0xFFFFFDD0 // size: 0xE0 auto struct CBlocks MyBlocks; // address: 0xFFFFFEB0 // size: 0x84 auto struct CPlayer MyPlayer; // address: 0xFFFFFF38 // size: 0x84 auto struct CPlayer MyPlayer2; // address: 0xFFFFFFC0 // size: 0x10 auto struct GPanel P1Panel; // address: 0xFFFFFFD0 // size: 0x10 auto struct GPanel P2Panel; } // address: 0x8008E928 // line start: 427 // line end: 585 void BgTask__FP4TASK_addr_8008E928(struct TASK *T) { // register: 2 // size: 0x10 register struct DEF_ARGS *Args; // register: 19 register bool IsTown; // register: 16 register int TextId; // register: 17 register int Level; // register: 18 register int ObjId; // register: 20 register int List; // address: 0xFFFFFDD0 // size: 0xE0 auto struct CBlocks_dup_4 MyBlocks; // address: 0xFFFFFEB0 // size: 0x84 auto struct CPlayer MyPlayer; // address: 0xFFFFFF38 // size: 0x84 auto struct CPlayer MyPlayer2; // address: 0xFFFFFFC0 // size: 0x10 auto struct GPanel P1Panel; // address: 0xFFFFFFD0 // size: 0x10 auto struct GPanel P2Panel; } // address: 0x80091E60 // line start: 438 // line end: 625 void BgTask__FP4TASK_addr_80091E60(struct TASK *T) { // register: 2 // size: 0x10 register struct DEF_ARGS *Args; // register: 18 register bool IsTown; // register: 16 register int TextId; // register: 17 register int Level; // register: 19 register int ObjId; // register: 20 register int List; // address: 0xFFFFFDD0 // size: 0xE0 auto struct CBlocks_dup_14 MyBlocks; // address: 0xFFFFFEB0 // size: 0x84 auto struct CPlayer_dup_14 MyPlayer; // address: 0xFFFFFF38 // size: 0x84 auto struct CPlayer_dup_14 MyPlayer2; // address: 0xFFFFFFC0 // size: 0x10 auto struct GPanel_dup_14 P1Panel; // address: 0xFFFFFFD0 // size: 0x10 auto struct GPanel_dup_14 P2Panel; } // address: 0x80092434 // line start: 386 // line end: 406 void DoShowPanelGFX__FP6GPanelT0(struct GPanel_dup_1 *P1, struct GPanel_dup_1 *P2) { } // address: 0x8008EF14 // line start: 386 // line end: 406 void DoShowPanelGFX__FP6GPanelT0_addr_8008EF14(struct GPanel *P1, struct GPanel *P2) { } // address: 0x80091D88 // line start: 407 // line end: 427 void DoShowPanelGFX__FP6GPanelT0_addr_80091D88(struct GPanel_dup_14 *P1, struct GPanel_dup_14 *P2) { } // address: 0x80091BB8 // size: 0x8 // line start: 624 // line end: 629 struct PInf *FindPlayerChar__FP12PlayerStruct(struct PlayerStruct_dup_11 *P) { } // address: 0x80090D9C // size: 0x8 // line start: 620 // line end: 625 struct PInf *FindPlayerChar__FP12PlayerStruct_addr_80090D9C(struct PlayerStruct_dup_6 *P) { } // address: 0x8008F598 // size: 0x8 // line start: 607 // line end: 612 struct PInf *FindPlayerChar__FP12PlayerStruct_addr_8008F598(struct PlayerStruct *P) { } // address: 0x800925B4 // size: 0xC // line start: 652 // line end: 657 struct PInf *FindPlayerChar__FP12PlayerStruct_addr_800925B4(struct PlayerStruct_dup_13 *P) { } // address: 0x800924B4 // size: 0xC // line start: 660 // line end: 665 struct PInf *FindPlayerChar__FP12PlayerStruct_addr_800924B4(struct PlayerStruct *P) { } // address: 0x800914C4 // size: 0x8 // line start: 624 // line end: 629 struct PInf *FindPlayerChar__FP12PlayerStruct_addr_800914C4(struct PlayerStruct_dup_7 *P) { } // address: 0x8008EEF8 // size: 0x8 // line start: 620 // line end: 625 struct PInf *FindPlayerChar__FP12PlayerStruct_addr_8008EEF8(struct PlayerStruct_dup_4 *P) { } // address: 0x80092010 // size: 0xC // line start: 647 // line end: 652 struct PInf_dup_12 *FindPlayerChar__FP12PlayerStruct_addr_80092010(struct PlayerStruct *P) { } // address: 0x80092040 // line start: 656 // line end: 668 int FindPlayerChar__FP12PlayerStructb(struct PlayerStruct *P, bool InTown) { // register: 3 // size: 0xC register struct PInf_dup_12 *Inf; } // address: 0x8008EF28 // line start: 629 // line end: 635 int FindPlayerChar__FP12PlayerStructb_addr_8008EF28(struct PlayerStruct_dup_4 *P, bool InTown) { // register: 2 // size: 0x8 register struct PInf *Inf; } // address: 0x8008F5C8 // line start: 616 // line end: 622 int FindPlayerChar__FP12PlayerStructb_addr_8008F5C8(struct PlayerStruct *P, bool InTown) { // register: 2 // size: 0x8 register struct PInf *Inf; } // address: 0x80091BE8 // line start: 633 // line end: 639 int FindPlayerChar__FP12PlayerStructb_addr_80091BE8(struct PlayerStruct_dup_11 *P, bool InTown) { // register: 2 // size: 0x8 register struct PInf *Inf; } // address: 0x800914F4 // line start: 633 // line end: 639 int FindPlayerChar__FP12PlayerStructb_addr_800914F4(struct PlayerStruct_dup_7 *P, bool InTown) { // register: 2 // size: 0x8 register struct PInf *Inf; } // address: 0x800925E4 // line start: 661 // line end: 673 int FindPlayerChar__FP12PlayerStructb_addr_800925E4(struct PlayerStruct_dup_13 *P, bool InTown) { // register: 3 // size: 0xC register struct PInf *Inf; } // address: 0x800924E4 // line start: 669 // line end: 681 int FindPlayerChar__FP12PlayerStructb_addr_800924E4(struct PlayerStruct *P, bool InTown) { // register: 3 // size: 0xC register struct PInf *Inf; } // address: 0x80090DCC // line start: 629 // line end: 635 int FindPlayerChar__FP12PlayerStructb_addr_80090DCC(struct PlayerStruct_dup_6 *P, bool InTown) { // register: 2 // size: 0x8 register struct PInf *Inf; } // address: 0x800924C0 // size: 0xC // line start: 627 // line end: 637 struct PInf *FindPlayerChar__FPc(char *Id) { { // register: 17 register int f; } } // address: 0x80091F1C // size: 0xC // line start: 622 // line end: 632 struct PInf_dup_12 *FindPlayerChar__FPc_addr_80091F1C(char *Id) { { // register: 17 register int f; } } // address: 0x8008F4B4 // size: 0x8 // line start: 582 // line end: 592 struct PInf *FindPlayerChar__FPc_addr_8008F4B4(char *Id) { { } } // address: 0x80092558 // size: 0xC // line start: 642 // line end: 648 struct PInf *FindPlayerChar__Fiii(int Char, int Wep, int Arm) { // address: 0xFFFFFFE0 // size: 0x14 auto char TxBuff[20]; } // address: 0x8008F53C // size: 0x8 // line start: 597 // line end: 603 struct PInf *FindPlayerChar__Fiii_addr_8008F53C(int Char, int Wep, int Arm) { // address: 0xFFFFFFE0 // size: 0x14 auto char TxBuff[20]; } // address: 0x80091FB4 // size: 0xC // line start: 637 // line end: 643 struct PInf_dup_12 *FindPlayerChar__Fiii_addr_80091FB4(int Char, int Wep, int Arm) { // address: 0xFFFFFFE0 // size: 0x14 auto char TxBuff[20]; } // address: 0x8008EE48 // line start: 305 // line end: 306 bool GLUE_Finished__Fv() { } // address: 0x8008F65C // size: 0x10 // line start: 649 // line end: 656 struct MonstList *GLUE_GetCurrentList__Fi(int Level) { // register: 17 // size: 0x8 register struct MonstLevel *MLev; // register: 16 register int List; } // address: 0x8008ED30 // line start: 231 // line end: 232 int GLUE_GetMonsterList__Fv() { } // address: 0x8008E738 // line start: 289 // line end: 295 void GLUE_PreDun__Fv() { } // address: 0x8008EDE4 // line start: 272 // line end: 279 void GLUE_PreTown__Fv() { } // address: 0x8008ED90 // line start: 257 // line end: 262 void GLUE_ResumeGame__Fv() { // register: 16 // size: 0x5C register struct TASK *T; } // address: 0x8008EE54 // line start: 316 // line end: 317 void GLUE_SetFinished__Fb(bool NewFinished) { } // address: 0x8008EEF4 // line start: 360 // line end: 364 bool GLUE_SetHomingScrollFlag__Fb(bool NewFlag) { // register: 2 register bool OldFlag; } // address: 0x8008ED24 // line start: 220 // line end: 221 void GLUE_SetMonsterList__Fi(int List) { } // address: 0x8008EEE4 // line start: 348 // line end: 352 bool GLUE_SetShowGameScreenFlag__Fb(bool NewFlag) { // register: 2 register bool OldFlag; } // address: 0x8008EF04 // line start: 372 // line end: 376 bool GLUE_SetShowPanelFlag__Fb(bool NewFlag) { // register: 2 register bool OldFlag; } // address: 0x8008EE60 // line start: 327 // line end: 339 void GLUE_StartBg__Fibi(int TextId, bool IsTown, int Level) { // register: 2 // size: 0x10 register struct DEF_ARGS *Args; } // address: 0x8008ED3C // line start: 242 // line end: 247 void GLUE_SuspendGame__Fv() { // register: 16 // size: 0x5C register struct TASK *T; } // address: 0x8008EF68 // line start: 645 // line end: 651 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb(struct CPlayer *Player, struct PlayerStruct_dup_4 *Plr, bool InTown) { // register: 16 register int Id; } // address: 0x80091C28 // line start: 649 // line end: 655 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb_addr_80091C28(struct CPlayer *Player, struct PlayerStruct_dup_11 *Plr, bool InTown) { // register: 16 register int Id; } // address: 0x80092B18 // line start: 629 // line end: 635 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb_addr_80092B18(struct CPlayer_dup_1 *Player, struct PlayerStruct *Plr, bool InTown) { // register: 16 register int Id; } // address: 0x8008F608 // line start: 632 // line end: 638 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb_addr_8008F608(struct CPlayer *Player, struct PlayerStruct *Plr, bool InTown) { // register: 16 register int Id; } // address: 0x80091534 // line start: 649 // line end: 655 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb_addr_80091534(struct CPlayer *Player, struct PlayerStruct_dup_7 *Plr, bool InTown) { // register: 16 register int Id; } // address: 0x80092644 // line start: 685 // line end: 700 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb_addr_80092644(struct CPlayer *Player, struct PlayerStruct_dup_13 *Plr, bool InTown) { // register: 16 register int Id; } // address: 0x80090E0C // line start: 645 // line end: 651 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb_addr_80090E0C(struct CPlayer *Player, struct PlayerStruct_dup_6 *Plr, bool InTown) { // register: 16 register int Id; } // address: 0x80092544 // line start: 693 // line end: 708 void MakeSurePlayerDressedProperly__FR7CPlayerR12PlayerStructb_addr_80092544(struct CPlayer_dup_14 *Player, struct PlayerStruct *Plr, bool InTown) { // register: 16 register int Id; }
20.380872
148
0.718614
maoa3
a08dfa504231b7ecc0ddbf1965dd6b74532c4bab
968
cpp
C++
src/mbgl/style/layers/raster_layer_properties.cpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
4,234
2015-01-09T08:10:16.000Z
2022-03-30T14:13:55.000Z
src/mbgl/style/layers/raster_layer_properties.cpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
12,771
2015-01-01T20:27:42.000Z
2022-03-24T18:14:44.000Z
src/mbgl/style/layers/raster_layer_properties.cpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
1,571
2015-01-08T08:24:53.000Z
2022-03-28T06:30:53.000Z
// clang-format off // This file is generated. Edit scripts/generate-style-code.js, then run `make style-code`. #include <mbgl/style/layers/raster_layer_properties.hpp> #include <mbgl/style/layers/raster_layer_impl.hpp> namespace mbgl { namespace style { RasterLayerProperties::RasterLayerProperties( Immutable<RasterLayer::Impl> impl_) : LayerProperties(std::move(impl_)) {} RasterLayerProperties::RasterLayerProperties( Immutable<RasterLayer::Impl> impl_, RasterPaintProperties::PossiblyEvaluated evaluated_) : LayerProperties(std::move(impl_)), evaluated(std::move(evaluated_)) {} RasterLayerProperties::~RasterLayerProperties() = default; unsigned long RasterLayerProperties::constantsMask() const { return evaluated.constantsMask(); } const RasterLayer::Impl& RasterLayerProperties::layerImpl() const { return static_cast<const RasterLayer::Impl&>(*baseImpl); } } // namespace style } // namespace mbgl // clang-format on
26.888889
91
0.762397
roblabs
a08ed3ac88c6ac54150aab794124e7716ce128f7
811
cpp
C++
answers/ArghyaDas21112001/Day 6/Question 1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
22
2021-03-16T14:07:47.000Z
2021-08-13T08:52:50.000Z
answers/ArghyaDas21112001/Day 6/Question 1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
174
2021-03-16T21:16:40.000Z
2021-06-12T05:19:51.000Z
answers/ArghyaDas21112001/Day 6/Question 1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
135
2021-03-16T16:47:12.000Z
2021-06-27T14:22:38.000Z
#include <iostream> using namespace std; int main() { int size; cout<<"enter the size: "; cin>>size; int max=0; int candies[size]; cout<<"Enter the candies: "; for(int i=0;i<size;i++) { cin>>candies[i]; } int extraCandies; cout<<"Enter the extraCandies: "; cin>>extraCandies; bool ans[size]; for(int i=0;i<size;i++) { if(candies[i]>max) { max=candies[i]; } } for(int i=0;i<size;i++) { if((candies[i]+extraCandies)>=max) { ans[i]=true; } else { ans[i]=false; } if(ans[i]==0) { cout<<"False "; } else { cout<<"True "; } } return 0; }
16.22
42
0.409371
arc03
a090aa811b06cf2c0bb33ae37df066622432cd64
4,016
cpp
C++
tests/src/deviceLib/hip_threadfence_system.cpp
JosephGeoBenjamin/HIP-forOpenCV
c48a8df33d59d84ef2180fb17a539b404f04429f
[ "MIT" ]
2
2019-09-10T15:50:53.000Z
2019-09-11T01:14:49.000Z
tests/src/deviceLib/hip_threadfence_system.cpp
JosephGeoBenjamin/HIP-forOpenCV
c48a8df33d59d84ef2180fb17a539b404f04429f
[ "MIT" ]
null
null
null
tests/src/deviceLib/hip_threadfence_system.cpp
JosephGeoBenjamin/HIP-forOpenCV
c48a8df33d59d84ef2180fb17a539b404f04429f
[ "MIT" ]
1
2019-07-04T00:48:48.000Z
2019-07-04T00:48:48.000Z
/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, 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. */ /* HIT_START * BUILD: %t %s ../test_common.cpp NVCC_OPTIONS -std=c++11 * RUN: %t * HIT_END */ #include <vector> #include <atomic> #include <thread> #include <cassert> #include <cstdio> #include "hip/hip_runtime.h" #include "hip/device_functions.h" #include "test_common.h" #define HIP_ASSERT(x) (assert((x) == hipSuccess)) __host__ __device__ void fence_system() { #ifdef __HIP_DEVICE_COMPILE__ __threadfence_system(); #else std::atomic_thread_fence(std::memory_order_seq_cst); #endif } __host__ __device__ void round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) { for (int i = 0; i < num_iter; i++) { while (*flag % num_dev != id) fence_system(); // invalid the cache for read (*data)++; fence_system(); // make sure the store to data is sequenced before the store to flag (*flag)++; fence_system(); // invalid the cache to flush out flag } } __global__ void gpu_round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) { round_robin(id, num_dev, num_iter, data, flag); } int main() { int num_gpus = 0; HIP_ASSERT(hipGetDeviceCount(&num_gpus)); if (num_gpus == 0) { passed(); return 0; } volatile int* data; HIP_ASSERT(hipHostMalloc(&data, sizeof(int), hipHostMallocCoherent)); constexpr int init_data = 1000; *data = init_data; volatile int* flag; HIP_ASSERT(hipHostMalloc(&flag, sizeof(int), hipHostMallocCoherent)); *flag = 0; // number of rounds per device constexpr int num_iter = 1000; // one CPU thread + 1 kernel/GPU const int num_dev = num_gpus + 1; int next_id = 0; std::vector<std::thread> threads; // create a CPU thread for the round_robin threads.push_back(std::thread(round_robin, next_id++, num_dev, num_iter, data, flag)); // run one thread per GPU dim3 dim_block(1, 1, 1); dim3 dim_grid(1, 1, 1); // launch one kernel per device for the round robin for (; next_id < num_dev; ++next_id) { threads.push_back(std::thread([=]() { HIP_ASSERT(hipSetDevice(next_id - 1)); hipLaunchKernelGGL(gpu_round_robin, dim_grid, dim_block, 0, 0x0, next_id, num_dev, num_iter, data, flag); HIP_ASSERT(hipDeviceSynchronize()); })); } for (auto& t : threads) { t.join(); } int expected_data = init_data + num_dev * num_iter; int expected_flag = num_dev * num_iter; bool passed = *data == expected_data && *flag == expected_flag; HIP_ASSERT(hipHostFree((void*)data)); HIP_ASSERT(hipHostFree((void*)flag)); if (passed) { passed(); } else { failed("Failed Verification!\n"); } return 0; }
31.375
94
0.669323
JosephGeoBenjamin
a0910c0f585c1ea6bf139e7e0484462e4f2e68e2
534
hpp
C++
graphics_app/include/Graphics/InputEvents/MouseMoveEvent.hpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
graphics_app/include/Graphics/InputEvents/MouseMoveEvent.hpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
graphics_app/include/Graphics/InputEvents/MouseMoveEvent.hpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
#ifndef GRAPHICS_MOUSEMOVEEVENT_HPP #define GRAPHICS_MOUSEMOVEEVENT_HPP #include <cmath> namespace Graphics { struct MouseMoveEvent { std::uint32_t timestamp; // in milliseconds std::uint32_t windowId; std::uint32_t x; std::uint32_t y; double_t deltaT; MouseMoveEvent(uint32_t timestamp, uint32_t windowId, uint32_t x, uint32_t y, double_t deltaT) : timestamp(timestamp), windowId(windowId), x(x), y(y), deltaT(deltaT) { } }; } // namespace Graphics #endif // GRAPHICS_MOUSEMOVEEVENT_HPP
20.538462
98
0.719101
timow-gh
a09204d5388a32269578b741fb9a8e0b67122ac6
798
cc
C++
chrome/browser/chromeos/power/screen_dimming_observer.cc
leiferikb/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
7
2015-05-20T22:41:35.000Z
2021-11-18T19:07:59.000Z
chrome/browser/chromeos/power/screen_dimming_observer.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome/browser/chromeos/power/screen_dimming_observer.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/power/screen_dimming_observer.h" #include "ash/shell.h" #include "chromeos/dbus/dbus_thread_manager.h" namespace chromeos { ScreenDimmingObserver::ScreenDimmingObserver() { DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(this); } ScreenDimmingObserver::~ScreenDimmingObserver() { DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver(this); } void ScreenDimmingObserver::ScreenDimmingRequested(ScreenDimmingState state) { ash::Shell::GetInstance()->SetDimming( state == PowerManagerClient::Observer::SCREEN_DIMMING_IDLE); } } // namespace chromeos
30.692308
78
0.776942
leiferikb
90b4272536e9ccf3c123c3ea8462926c22f31e82
797
cpp
C++
53.cpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
53.cpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
53.cpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
#include <iostream> #include <set> #include <vector> #include "headers/euler.hpp" const int MIN_N = 1; const int MAX_N = 100; const int MAX_VALUE = 1000000; int main(int argc, char** argv) { int numAboveMax = 0; for (int n = MIN_N; n <= MAX_N; n++) { for (int r = 1; r <= n / 2; r++) { if (euler::choose(n, r) > MAX_VALUE) { std::cout << n << " choose " << r << " is above " << MAX_VALUE << std::endl; numAboveMax += n - r - r + 1; break; } } } std::cout << "23 choose 10: " << euler::choose(23, 10) << std::endl; std::cout << "Total terms in n {" << MIN_N << ".." << MAX_N << "} above " << MAX_VALUE << ", " << "r <= n, " << "for n choose r: " << numAboveMax << std::endl; return 0; }
23.441176
96
0.483061
DouglasSherk
90b6ba974333ae36e701d87d96da5dc7dc3eba27
5,100
cpp
C++
src/Kernel/Champs/instancie_src_Kernel_Champs.cpp
cea-trust-platform/trust-code
c4f42d8f8602a8cc5e0ead0e29dbf0be8ac52f72
[ "BSD-3-Clause" ]
12
2021-06-30T18:50:38.000Z
2022-03-23T09:03:16.000Z
src/Kernel/Champs/instancie_src_Kernel_Champs.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
null
null
null
src/Kernel/Champs/instancie_src_Kernel_Champs.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
2
2021-10-04T09:19:39.000Z
2021-12-15T14:21:04.000Z
// // Warning : DO NOT EDIT ! // To update this file, run: make depend // #include <verifie_pere.h> #include <Boundary_field_inward.h> #include <Ch_front_Vortex.h> #include <Ch_front_input.h> #include <Ch_front_input_uniforme.h> #include <Ch_input_uniforme.h> #include <Champ_Don_Fonc_txyz.h> #include <Champ_Don_Fonc_xyz.h> #include <Champ_Don_lu.h> #include <Champ_Fonc_Fonction.h> #include <Champ_Fonc_Fonction_txyz.h> #include <Champ_Fonc_Fonction_txyz_Morceaux.h> #include <Champ_Fonc_Morceaux.h> #include <Champ_Fonc_Tabule.h> #include <Champ_Fonc_t.h> #include <Champ_Front_Fonction.h> #include <Champ_Generique_Champ.h> #include <Champ_Generique_Correlation.h> #include <Champ_Generique_Divergence.h> #include <Champ_Generique_Ecart_Type.h> #include <Champ_Generique_Extraction.h> #include <Champ_Generique_Gradient.h> #include <Champ_Generique_Interpolation.h> #include <Champ_Generique_Morceau_Equation.h> #include <Champ_Generique_Moyenne.h> #include <Champ_Generique_Predefini.h> #include <Champ_Generique_Reduction_0D.h> #include <Champ_Generique_Statistiques.h> #include <Champ_Generique_Transformation.h> #include <Champ_Generique_refChamp.h> #include <Champ_Generique_refChamp_special.h> #include <Champ_Tabule_Morceaux.h> #include <Champ_Tabule_Temps.h> #include <Champ_Uniforme.h> #include <Champ_Uniforme_Morceaux.h> #include <Champ_Uniforme_Morceaux_Tabule_Temps.h> #include <Champ_front_Tabule.h> #include <Champ_front_bruite.h> #include <Champ_front_calc.h> #include <Champ_front_calc_interne.h> #include <Champ_front_debit.h> #include <Champ_front_debit_massique.h> #include <Champ_front_fonc.h> #include <Champ_front_fonc_gradient.h> #include <Champ_front_fonc_pois_ipsn.h> #include <Champ_front_fonc_pois_tube.h> #include <Champ_front_lu.h> #include <Champ_front_normal.h> #include <Champ_front_t.h> #include <Champ_front_tangentiel.h> #include <Champ_front_txyz.h> #include <Champ_front_uniforme.h> #include <Champ_front_xyz_debit.h> #include <Champ_input_P0.h> #include <Init_par_partie.h> #include <Tayl_Green.h> #include <champ_init_canal_sinal.h> void instancie_src_Kernel_Champs() { Cerr << "src_Kernel_Champs" << finl; Boundary_field_inward inst1;verifie_pere(inst1); Champ_front_normal_VEF inst2;verifie_pere(inst2); Ch_front_Vortex inst3;verifie_pere(inst3); Ch_front_input inst4;verifie_pere(inst4); Ch_front_input_uniforme inst5;verifie_pere(inst5); Ch_input_uniforme inst6;verifie_pere(inst6); Champ_Don_Fonc_txyz inst7;verifie_pere(inst7); Champ_Don_Fonc_xyz inst8;verifie_pere(inst8); Champ_Don_lu inst9;verifie_pere(inst9); Champ_Fonc_Fonction inst10;verifie_pere(inst10); Sutherland inst11;verifie_pere(inst11); Champ_Fonc_Fonction_txyz inst12;verifie_pere(inst12); Champ_Fonc_Fonction_txyz_Morceaux inst13;verifie_pere(inst13); Champ_Fonc_Morceaux inst14;verifie_pere(inst14); Champ_Fonc_Tabule inst15;verifie_pere(inst15); Champ_Fonc_t inst16;verifie_pere(inst16); Champ_Front_Fonction inst17;verifie_pere(inst17); Champ_Generique_Champ inst18;verifie_pere(inst18); Champ_Generique_Correlation inst19;verifie_pere(inst19); Champ_Generique_Divergence inst20;verifie_pere(inst20); Champ_Generique_Ecart_Type inst21;verifie_pere(inst21); Champ_Generique_Extraction inst22;verifie_pere(inst22); Champ_Generique_Gradient inst23;verifie_pere(inst23); Champ_Generique_Interpolation inst24;verifie_pere(inst24); Champ_Generique_Morceau_Equation inst25;verifie_pere(inst25); Champ_Generique_Moyenne inst26;verifie_pere(inst26); Champ_Generique_Predefini inst27;verifie_pere(inst27); Champ_Generique_Reduction_0D inst28;verifie_pere(inst28); Champ_Generique_Statistiques inst29;verifie_pere(inst29); Champ_Generique_Transformation inst30;verifie_pere(inst30); Champ_Generique_refChamp inst31;verifie_pere(inst31); Champ_Generique_refChamp_special inst32;verifie_pere(inst32); Champ_Tabule_Morceaux inst33;verifie_pere(inst33); Champ_Tabule_Temps inst34;verifie_pere(inst34); Champ_Uniforme inst35;verifie_pere(inst35); Champ_Uniforme_Morceaux inst36;verifie_pere(inst36); Champ_Uniforme_Morceaux_Tabule_Temps inst37;verifie_pere(inst37); Champ_front_Tabule inst38;verifie_pere(inst38); Champ_front_bruite inst39;verifie_pere(inst39); Champ_front_calc inst40;verifie_pere(inst40); Champ_front_calc_interne inst41;verifie_pere(inst41); Champ_front_debit inst42;verifie_pere(inst42); Champ_front_debit_massique inst43;verifie_pere(inst43); Champ_front_fonc inst44;verifie_pere(inst44); Champ_front_fonc_gradient inst45;verifie_pere(inst45); Champ_front_fonc_pois_ipsn inst46;verifie_pere(inst46); Champ_front_fonc_pois_tube inst47;verifie_pere(inst47); Champ_front_lu inst48;verifie_pere(inst48); Champ_front_normal inst49;verifie_pere(inst49); Champ_front_t inst50;verifie_pere(inst50); Champ_front_tangentiel inst51;verifie_pere(inst51); Champ_front_txyz inst52;verifie_pere(inst52); Champ_front_uniforme inst53;verifie_pere(inst53); Champ_front_xyz_debit inst54;verifie_pere(inst54); Champ_input_P0 inst55;verifie_pere(inst55); Init_par_partie inst56;verifie_pere(inst56); Tayl_Green inst57;verifie_pere(inst57); champ_init_canal_sinal inst58;verifie_pere(inst58); }
41.463415
65
0.855098
cea-trust-platform
90bb1845c1eaa509f2436edbc110851d5a14a788
2,458
cpp
C++
generated-sources/cpp-qt5-qhttpengine-server/mojang-authentication/server/src/models/com.github.asyncmc.mojang.authentication.cpp.qt5.qhttpengine.server.model/OAIUsernamePassword.cpp
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/cpp-qt5-qhttpengine-server/mojang-authentication/server/src/models/com.github.asyncmc.mojang.authentication.cpp.qt5.qhttpengine.server.model/OAIUsernamePassword.cpp
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/cpp-qt5-qhttpengine-server/mojang-authentication/server/src/models/com.github.asyncmc.mojang.authentication.cpp.qt5.qhttpengine.server.model/OAIUsernamePassword.cpp
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
/** * Mojang Authentication API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2020-06-05 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIUsernamePassword.h" #include "OAIHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace OpenAPI { OAIUsernamePassword::OAIUsernamePassword(QString json) { this->fromJson(json); } OAIUsernamePassword::OAIUsernamePassword() { this->init(); } OAIUsernamePassword::~OAIUsernamePassword() { } void OAIUsernamePassword::init() { m_username_isSet = false; m_password_isSet = false; } void OAIUsernamePassword::fromJson(QString jsonString) { QByteArray array (jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIUsernamePassword::fromJsonObject(QJsonObject json) { ::OpenAPI::fromJsonValue(username, json[QString("username")]); ::OpenAPI::fromJsonValue(password, json[QString("password")]); } QString OAIUsernamePassword::asJson () const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIUsernamePassword::asJsonObject() const { QJsonObject obj; if(m_username_isSet){ obj.insert(QString("username"), ::OpenAPI::toJsonValue(username)); } if(m_password_isSet){ obj.insert(QString("password"), ::OpenAPI::toJsonValue(password)); } return obj; } QString OAIUsernamePassword::getUsername() const { return username; } void OAIUsernamePassword::setUsername(const QString &username) { this->username = username; this->m_username_isSet = true; } QString OAIUsernamePassword::getPassword() const { return password; } void OAIUsernamePassword::setPassword(const QString &password) { this->password = password; this->m_password_isSet = true; } bool OAIUsernamePassword::isSet() const { bool isObjectUpdated = false; do{ if(m_username_isSet){ isObjectUpdated = true; break;} if(m_password_isSet){ isObjectUpdated = true; break;} }while(false); return isObjectUpdated; } }
21.752212
109
0.713588
AsyncMC
90be2cbd32d08ba9edfe3eedfb6e94729a67beb8
1,075
cpp
C++
src/luogu/P1118/26915047_ac_100_100ms_932k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P1118/26915047_ac_100_100ms_932k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P1118/26915047_ac_100_100ms_932k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <cctype> int n, sum; bool vis[36]; int ans[36]; int f[36]; int read() { int ret, f = 1; char ch; while(!isdigit(ch = getchar())) (ch == '-') && (f = -1); for(ret = ch - '0'; isdigit(ch = getchar()); ret *= 10, ret += ch - '0'); return ret * f; } void print(int x) { if(x < 0) putchar('-'), x = -x; if(x > 9) print(x / 10); putchar(x % 10 + '0'); } bool dfs(int step, int num, int k) { if(k > sum) return 0; if(step == n) { if(k == sum) { ans[step] = num; return 1; } else return 0; } vis[num] = 1; for(int i = 1; i <= n; ++i) if(!vis[i] && dfs(step + 1, i, k + f[step] * i)) { ans[step] = num; return 1; } vis[num] = 0; return 0; } int main() { n = read(), sum = read(); f[0] = f[n - 1] = 1; for(int i = 1; i * 2 < n; ++i) f[i] = f[n - 1 - i] = (n - i) * f[i - 1] / i; if(dfs(0, 0, 0)) for(int i = 1; i <= n; ++i) print(ans[i]), putchar(' '); return 0; }
20.673077
74
0.417674
lnkkerst
90be2ed575fc2d6ebccfc9a0aac7c9c4ad77f4e7
27,408
cpp
C++
ethsw_hal_stub/src/ethsw_stub_hal.cpp
rdkcmf/rdkb-tools-tdkb
9f9c3600cd701d5fc90ac86a6394ebd28d49267e
[ "Apache-2.0" ]
null
null
null
ethsw_hal_stub/src/ethsw_stub_hal.cpp
rdkcmf/rdkb-tools-tdkb
9f9c3600cd701d5fc90ac86a6394ebd28d49267e
[ "Apache-2.0" ]
null
null
null
ethsw_hal_stub/src/ethsw_stub_hal.cpp
rdkcmf/rdkb-tools-tdkb
9f9c3600cd701d5fc90ac86a6394ebd28d49267e
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016-2017 Intel 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 "ethsw_stub_hal.h" #define WAIT_TIME 5 #define MAX_BUFFER_SIZE 128 #define MAX_STRING_SIZE 64 #define MAX_BUFFER_SIZE_TO_SEND 512 #define MAXBITRATE_10 10 #define MAXBITRATE_100 100 #define MAXBITRATE_1000 1000 #define MAXBITRATE_10000 10000 #define RETURN_SUCCESS 0 #define RETURN_FAILURE 1 #define TEST_SUCCESS true #define TEST_FAILURE false #define CHECK_PARAM_AND_RET(x) if ((x) == NULL) \ { \ DEBUG_PRINT(DEBUG_ERROR,"!!!NULL Pointer!!! :: %s:%d\n", __func__, __LINE__); \ return TEST_FAILURE; \ } /******************************************************************************************** *Function name : testmodulepre_requisites *Description : testmodulepre_requisites will be used for registering TDK with the CR *@param [in] : None *@param [out] : Return string "SUCCESS" in case of success else return string "FAILURE" **********************************************************************************************/ std::string ethsw_stub_hal::testmodulepre_requisites() { /*Dummy function required as it is pure virtual. No need to register with CCSP bus for HAL*/ return "SUCCESS"; } /********************************************************************************************** *Function name : testmodulepost_requisites *Description : testmodulepost_requisites will be used for unregistering TDK with the CR *@param [in] : None *@param [out] : Return TEST_SUCCESS or TEST_FAILURE based on the return value **********************************************************************************************/ bool ethsw_stub_hal::testmodulepost_requisites() { /*Dummy function required as it is pure virtual. No need to register with CCSP bus for HAL*/ return TEST_SUCCESS; } /*************************************************************************************** *Function name : ethsw_stub_hal_Init *Description : This function is used to register all the ethsw_stub_hal methods. *param [in] : szVersion - version, ptrAgentObj - Agent obhect *@param [out] : Return TEST_SUCCESS or TEST_FAILURE ***************************************************************************************/ bool ethsw_stub_hal::initialize(IN const char* szVersion) { DEBUG_PRINT(DEBUG_TRACE, "ethsw_stub_hal Initialize----->Entry\n"); return TEST_SUCCESS; } /***************************************************************************************************** *Function name : ethsw_stub_hal_Get_Port_Admin_Status *Description : This function will invoke the SSP HAL wrapper to get the ethsw port admin status *@param [in] : req - It will give port id (port number) and flag(for negative scenario) *@param [out] : response - filled with SUCCESS or FAILURE based on the return value *******************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_Port_Admin_Status(IN const Json::Value& req, OUT Json::Value& response) { int portID = 0; char getAdminStatus[MAX_STRING_SIZE] = {0}; int isNegativeScenario = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_Port_Admin_Status stub\n"); if(&req["PortID"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } portID = req["PortID"].asInt(); if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_GetAdminPortStatus(portID, getAdminStatus, isNegativeScenario) == RETURN_SUCCESS) { DEBUG_PRINT(DEBUG_TRACE, "Successfully retrieved the admin status\n"); response["result"] = "SUCCESS"; response["details"] = getAdminStatus; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_Port_Admin_Status function has failed.Please check logs"; return; } } /********************************************************************************************* *Function name : ethsw_stub_hal_Get_Port_Cfg *Description : This function will invoke the SSP HAL wrapper to get the ethsw port cfg *@param [in] : req - It will give port id (port number) and flag(for negative scenario) *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_Port_Cfg(IN const Json::Value& req, OUT Json::Value& response) { int portID = 0; char duplexMode[MAX_STRING_SIZE] = {0}; int maxBitRate = 0; char resultDetails[MAX_BUFFER_SIZE_TO_SEND] = {0}; int isNegativeScenario = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_Port_Cfg stub \n"); if(&req["PortID"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } portID = req["PortID"].asInt(); if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_GetPortCfg(portID, duplexMode, &maxBitRate, isNegativeScenario) == RETURN_SUCCESS) { snprintf(resultDetails, MAX_BUFFER_SIZE_TO_SEND, "/%d/%s/", maxBitRate, duplexMode); response["result"] = "SUCCESS"; response["details"] = resultDetails; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_Port_Cfg function has failed.Please check logs"; return; } } /********************************************************************************************* *Function name : ethsw_stub_hal_Get_Port_Status *Description : This function will invoke the SSP HAL wrapper to get the ethsw port status *@param [in] : req - It will give port id (port number) and flag(for negative scenario) *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_Port_Status(IN const Json::Value& req, OUT Json::Value& response) { int portID = 0; char linkStatus[MAX_STRING_SIZE] = {0}; int bitRate = 0; char resultDetails[MAX_BUFFER_SIZE_TO_SEND] = {0}; int isNegativeScenario = 0; char duplexMode[MAX_STRING_SIZE] = {0}; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_Port_Status stub \n"); if(&req["PortID"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } portID = req["PortID"].asInt(); if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_GetPort_Status(portID, linkStatus, &bitRate, duplexMode, isNegativeScenario) == RETURN_SUCCESS) { snprintf(resultDetails, MAX_BUFFER_SIZE_TO_SEND, "/%d/%s/%s/", bitRate, linkStatus, duplexMode); response["result"] = "SUCCESS"; response["details"] = resultDetails; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_Port_Status function has failed.Please check logs"; return; } } /******************************************************************************************************** *Function name : ethsw_stub_hal_Init *Description : This function will invoke the SSP HAL wrapper to intialize the ethsw_stub_hal HAL *@param [in] : req - request sent by Test Manager *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ************************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Init(IN const Json::Value& req, OUT Json::Value& response) { DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Init stub\n"); if(ssp_ethsw_stub_hal_Init() == RETURN_SUCCESS) { response["result"] = "SUCCESS"; response["details"] = "ethsw_stub_hal_Init function has been intailized successfully"; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Init function has failed.Please check logs"; return; } } /**************************************************************************************************************** *Function name : ethsw_stub_hal_LocatePort_By_MacAddress *Description : This function will invoke the SSP HAL wrapper to Locate Port By MacAddress *@param [in] : req - It will give MAC Address(MAC of associated device) and flag(for negative scenario) *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ****************************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_LocatePort_By_MacAddress(IN const Json::Value& req, OUT Json::Value& response) { char macID[MAX_STRING_SIZE] = {0}; int portId = 0; char resultDetails[MAX_BUFFER_SIZE_TO_SEND] = {0}; int isNegativeScenario = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_LocatePort_By_MacAddress stub\n"); if(macID == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } strncpy(macID,req["macID"].asCString(), MAX_STRING_SIZE); if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_LocatePort_By_MacAddress(macID, &portId, isNegativeScenario) == RETURN_SUCCESS) { snprintf(resultDetails, MAX_BUFFER_SIZE_TO_SEND, "%d", portId); response["result"] = "SUCCESS"; response["details"] = resultDetails; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_LocatePort_By_MacAddress function has failed.Please check logs"; return; } } /*************************************************************************************** *Function name : ethsw_stub_hal_SetAgingSpeed *Description : This function will invoke the SSP HAL wrapper to Set Aging Speed *@param [in] : req - It will give port id and aging speed to be set *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ******************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_SetAgingSpeed(IN const Json::Value& req, OUT Json::Value& response) { int portID = 0; int agingSpeed = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_SetAgingSpeed stub\n"); if(&req["PortID"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } if(&req["AgingSpeed"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } portID = req["PortID"].asInt(); agingSpeed = req["AgingSpeed"].asInt(); DEBUG_PRINT(DEBUG_TRACE, "PortID = %d, AgingSpeed = %d\n", portID, agingSpeed); if(ssp_ethsw_stub_hal_SetAgingSpeed(portID, agingSpeed) == RETURN_SUCCESS) { response["result"] = "SUCCESS"; response["details"] = "ethsw_stub_hal_SetAgingSpeed function has passed"; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_SetAgingSpeed function has failed.Please check logs"; return; } } /****************************************************************************************** *Function name : ethsw_stub_hal_SetPortAdminStatus *Description : This function will invoke the SSP HAL wrapper to Set Port Admin Status *@param [in] : req - It will give port id and admin status to be set *@param [out] : response - filled with SUCCESS or FAILURE based on the return value *******************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_SetPortAdminStatus(IN const Json::Value& req, OUT Json::Value& response) { int portID = 0; char adminStatus[MAX_STRING_SIZE] = {0}; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_SetPortAdminStatus stub\n"); if(&req["PortID"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } if(&req["adminstatus"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } portID = req["PortID"].asInt(); strncpy(adminStatus, req["adminstatus"].asCString(), MAX_STRING_SIZE); if(ssp_ethsw_stub_hal_SetPortAdminStatus(portID, adminStatus) == RETURN_SUCCESS) { response["result"] = "SUCCESS"; response["details"] = "ethsw_stub_hal_SetPortAdminStatus function has been executed successfully"; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_SetPortAdminStatus function has been failed"; return; } } /****************************************************************************************** *Function name : ethsw_stub_hal_SetPortCfg *Description : This function will invoke the SSP HAL wrapper to Set Port Cfg *@param [in] : req - It will give port id, linkrate and duplex mode to be set *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ********************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_SetPortCfg(IN const Json::Value& req, OUT Json::Value& response) { int portID = 0; int linkRate = 0; char duplexMode[MAX_STRING_SIZE] = {0}; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_SetPortCfg stub\n"); if(&req["PortID"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } if(&req["linkrate"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } if(&req["mode"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } portID = req["PortID"].asInt(); linkRate = req["linkrate"].asInt(); strncpy(duplexMode, req["mode"].asCString(), MAX_STRING_SIZE); if(ssp_ethsw_stub_hal_SetPortCfg(portID, linkRate, duplexMode) == RETURN_SUCCESS) { response["result"] = "SUCCESS"; response["details"] = "ethsw_stub_hal_SetPortCfg function has been executed successfully"; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_SetPortCfg function has been failed"; return; } } /******************************************************************************************* * * Function Name : ethsw_stub_hal_Get_AssociatedDevice * Description :This function will invoke the SSP HAL wrapper to get the ethsw assocoated device * * @param [in] req- : * @param [out] response - filled with SUCCESS or FAILURE based on the output staus of operation * ********************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_AssociatedDevice(IN const Json::Value& req, OUT Json::Value& response) { DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_AssociatedDevice stub\n"); int isNegativeScenario = 0; char details[120] = {'\0'}; eth_device_t *eth_device_conf_ptr = NULL; unsigned long int array_size = 0; if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_Get_AssociatedDevice(&array_size,&eth_device_conf_ptr,isNegativeScenario) == RETURN_SUCCESS) { if(eth_device_conf_ptr != NULL && array_size > 0) { sprintf(details, "array_size: %lu, port: %d, mac address: %02x:%02x:%02x:%02x:%02x:%02x, status: %d, lanid: %d, devTxRate: %d, devRxRate: %d",array_size, eth_device_conf_ptr->eth_port,eth_device_conf_ptr->eth_devMacAddress[0],eth_device_conf_ptr->eth_devMacAddress[1],eth_device_conf_ptr->eth_devMacAddress[2],eth_device_conf_ptr->eth_devMacAddress[3],eth_device_conf_ptr->eth_devMacAddress[4],eth_device_conf_ptr->eth_devMacAddress[5],eth_device_conf_ptr->eth_Active,eth_device_conf_ptr->eth_vlanid,eth_device_conf_ptr->eth_devTxRate,eth_device_conf_ptr->eth_devRxRate); DEBUG_PRINT(DEBUG_TRACE, "Successfully retrieved the associated device status status\n"); response["result"] = "SUCCESS"; response["details"] = details; free(eth_device_conf_ptr); eth_device_conf_ptr = NULL; return; } else { response["result"] = "SUCCESS"; response["details"] = "No Associated device found. CcspHalExtSw_getAssociatedDeviceice() returned empty buffer"; return; } } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_AssociatedDevice function has failed.Please check logs"; return; } } /********************************************************************************************* *Function name : ethsw_stub_hal_Get_EthWanInterfaceName *Description : This function will invoke the SSP HAL wrapper to get the ethwan interface name *@param [in] : req - flag(for negative scenario) *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_EthWanInterfaceName(IN const Json::Value& req, OUT Json::Value& response) { char interface[MAX_STRING_SIZE] = {0}; char resultDetails[MAX_BUFFER_SIZE_TO_SEND] = {0}; int isNegativeScenario = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_EthWanInterfaceName stub \n"); if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_Get_EthWanInterfaceName(interface, isNegativeScenario) == RETURN_SUCCESS) { sprintf(resultDetails, "%s", interface); response["result"] = "SUCCESS"; response["details"] = resultDetails; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_EthWanInterfaceName function has failed.Please check logs"; return; } } /********************************************************************************************* *Function name : ethsw_stub_hal_Get_EthWanEnable *Description : This function will invoke the SSP HAL wrapper to get the ethwan enable status *@param [in] : req - flag(for negative scenario) *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_EthWanEnable(IN const Json::Value& req, OUT Json::Value& response) { unsigned char enableState = 0; char resultDetails[MAX_BUFFER_SIZE_TO_SEND] = {0}; int isNegativeScenario = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_EthWanEnable stub \n"); if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_Get_EthWanEnable(&enableState, isNegativeScenario) == RETURN_SUCCESS) { sprintf(resultDetails, "%d", enableState); response["result"] = "SUCCESS"; response["details"] = resultDetails; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_EthWanEnable function has failed.Please check logs"; return; } } /*************************************************************************************** *Function name : ethsw_stub_hal_Set_EthWanEnable *Description : This function will invoke the SSP HAL wrapper to Set EthWanEnable state *@param [in] : req - It will give the eth wan enable state to be set *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ******************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Set_EthWanEnable(IN const Json::Value& req, OUT Json::Value& response) { unsigned char enableState = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Set_EthWanEnable stub\n"); if(&req["enable"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } enableState = req["enable"].asInt(); DEBUG_PRINT(DEBUG_TRACE, "enableState = %d\n", enableState); if(ssp_ethsw_stub_hal_Set_EthWanEnable(enableState) == RETURN_SUCCESS) { response["result"] = "SUCCESS"; response["details"] = "ethsw_stub_hal_Set_EthWanEnable function has passed"; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Set_EthWanEnable function has failed.Please check logs"; return; } } /********************************************************************************************* *Function name : ethsw_stub_hal_Get_EthWanPort *Description : This function will invoke the SSP HAL wrapper to get the ethwan port number *@param [in] : req - flag(for negative scenario) *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_EthWanPort(IN const Json::Value& req, OUT Json::Value& response) { unsigned int portNum = 0; char resultDetails[MAX_BUFFER_SIZE_TO_SEND] = {0}; int isNegativeScenario = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_EthWanPort stub \n"); if(&req["flag"]) { isNegativeScenario = req["flag"].asInt(); } if(ssp_ethsw_stub_hal_Get_EthWanPort(&portNum, isNegativeScenario) == RETURN_SUCCESS) { sprintf(resultDetails, "%u", portNum); response["result"] = "SUCCESS"; response["details"] = resultDetails; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_EthWanPort function has failed.Please check logs"; return; } } /*************************************************************************************** *Function name : ethsw_stub_hal_Set_EthWanPort *Description : This function will invoke the SSP HAL wrapper to Set EthWanPort number *@param [in] : req - It will give the eth wan port number to be set *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ******************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Set_EthWanPort(IN const Json::Value& req, OUT Json::Value& response) { unsigned int portNum = 0; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Set_EthWanPort stub\n"); if(&req["port"] == NULL) { response["result"] = "FAILURE"; response["details"] = "NULL parameter as input argument"; return; } portNum = req["port"].asInt(); DEBUG_PRINT(DEBUG_TRACE, "portNum = %d\n", portNum); if(ssp_ethsw_stub_hal_Set_EthWanPort(portNum) == RETURN_SUCCESS) { response["result"] = "SUCCESS"; response["details"] = "ethsw_stub_hal_Set_EthWanPort function has passed"; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Set_EthWanPort function has failed.Please check logs"; return; } } /********************************************************************************************* *Function name : ethsw_stub_hal_Get_EthWanLinkStatus *Description : This function will invoke the SSP HAL wrapper to get the ethwan link status *@param [in] : *@param [out] : response - filled with SUCCESS or FAILURE based on the return value ************************************************************************************************/ void ethsw_stub_hal::ethsw_stub_hal_Get_EthWanLinkStatus(IN const Json::Value& req, OUT Json::Value& response) { int linkStatus = 0; char resultDetails[MAX_BUFFER_SIZE_TO_SEND] = {0}; DEBUG_PRINT(DEBUG_TRACE,"Inside Function ethsw_stub_hal_Get_EthLinkStatus stub \n"); if(ssp_ethsw_stub_hal_Get_EthWanLinkStatus(&linkStatus) == RETURN_SUCCESS) { sprintf(resultDetails, "%d", linkStatus); response["result"] = "SUCCESS"; response["details"] = resultDetails; return; } else { response["result"] = "FAILURE"; response["details"] = "ethsw_stub_hal_Get_EthWanLinkStatus function has failed.Please check logs"; return; } } /*************************************************************************************************** *Function Name : CreateObject *Description : This function is used to create a new object of the class "ethsw_stub_hal". *@param [in] : None ***************************************************************************************************/ extern "C" ethsw_stub_hal* CreateObject(TcpSocketServer &ptrtcpServer) { return new ethsw_stub_hal(ptrtcpServer); } /************************************************************************************* *Function Name : cleanup *Description : This function will be used to the close things cleanly. *@param [in] : szVersion - version, ptrAgentObj - Agent object *@param [out] : response - filled with SUCCESS or FAILURE based on the return value **************************************************************************************/ bool ethsw_stub_hal::cleanup(IN const char* szVersion) { DEBUG_PRINT(DEBUG_TRACE, "cleaning up\n"); return TEST_SUCCESS; } /********************************************************************************** *Function Name : DestroyObject *Description : This function will be used to destroy the ethsw_stub_hal object. *@param [in] : Input argument is ethsw_stub_hal Object **********************************************************************************/ extern "C" void DestroyObject(ethsw_stub_hal *stubobj) { DEBUG_PRINT(DEBUG_TRACE, "Destroying ethsw_stub_hal object\n"); delete stubobj; }
39.042735
587
0.587237
rdkcmf
90c107c048ee2e7cdfce59ea890da3f0030241ec
733
hpp
C++
include/anisthesia/media.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
33
2017-02-07T00:03:31.000Z
2022-02-09T12:06:52.000Z
include/anisthesia/media.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
7
2017-07-26T22:40:22.000Z
2022-01-30T08:05:51.000Z
include/anisthesia/media.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
9
2017-08-05T10:33:05.000Z
2021-10-03T00:23:21.000Z
#pragma once #include <chrono> #include <functional> #include <string> #include <vector> namespace anisthesia { using media_time_t = std::chrono::milliseconds; enum class MediaInfoType { Unknown, File, Tab, Title, Url, }; enum class MediaState { Unknown, Playing, Paused, Stopped, }; struct MediaInfo { MediaInfoType type = MediaInfoType::Unknown; std::string value; }; struct Media { MediaState state = MediaState::Unknown; // currently unused media_time_t duration; // currently unused media_time_t position; // currently unused std::vector<MediaInfo> information; }; using media_proc_t = std::function<bool(const MediaInfo&)>; } // namespace anisthesia
17.452381
62
0.683492
swiftcitrus
90c2f126eefd11fac5ab2a9b0f9e0bb149c698b3
41,450
cc
C++
Geometry/HcalCommonData/src/HcalDDDSimConstants.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Geometry/HcalCommonData/src/HcalDDDSimConstants.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Geometry/HcalCommonData/src/HcalDDDSimConstants.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "Geometry/HcalCommonData/interface/HcalDDDSimConstants.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/Exception.h" #include "CLHEP/Units/GlobalPhysicalConstants.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" #include <cmath> //#define EDM_ML_DEBUG HcalDDDSimConstants::HcalDDDSimConstants(const HcalParameters* hp) : hpar(hp) { #ifdef EDM_ML_DEBUG edm::LogInfo("HCalGeom") << "HcalDDDSimConstants::HcalDDDSimConstants (const HcalParameter* hp) constructor\n"; #endif initialize(); #ifdef EDM_ML_DEBUG std::vector<HcalCellType> cellTypes = HcalCellTypes(); edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants: " << cellTypes.size() << " cells of type HCal (All)\n"; #endif } HcalDDDSimConstants::~HcalDDDSimConstants() { #ifdef EDM_ML_DEBUG edm::LogInfo ("HCalGeom") << "HcalDDDSimConstants::destructed!!!\n"; #endif } HcalCellType::HcalCell HcalDDDSimConstants::cell(const int& idet, const int& zside, const int& depth, const int& etaR, const int& iphi) const { double etaMn = hpar->etaMin[0]; double etaMx = hpar->etaMax[0]; if (idet==static_cast<int>(HcalEndcap)) { etaMn = hpar->etaMin[1]; etaMx = hpar->etaMax[1]; } else if (idet==static_cast<int>(HcalForward)) { etaMn = hpar->etaMin[2]; etaMx = hpar->etaMax[2]; } double eta = 0, deta = 0, phi = 0, dphi = 0, rz = 0, drz = 0; bool ok = false, flagrz = true; if ((idet==static_cast<int>(HcalBarrel)||idet==static_cast<int>(HcalEndcap)|| idet==static_cast<int>(HcalOuter)||idet==static_cast<int>(HcalForward)) && etaR >=etaMn && etaR <= etaMx && depth > 0) ok = true; if (idet == static_cast<int>(HcalEndcap) && depth>(int)(hpar->zHE.size()))ok=false; else if (idet == static_cast<int>(HcalBarrel) && depth > maxLayerHB_+1) ok=false; else if (idet == static_cast<int>(HcalOuter) && depth != 4) ok=false; else if (idet == static_cast<int>(HcalForward) && depth > maxDepth[2]) ok=false; if (ok) { eta = getEta(idet, etaR, zside, depth); deta = deltaEta(idet, etaR, depth); double fibin, fioff; if (idet == static_cast<int>(HcalBarrel)|| idet == static_cast<int>(HcalOuter)) { fioff = hpar->phioff[0]; fibin = hpar->phibin[etaR-1]; } else if (idet == static_cast<int>(HcalEndcap)) { fioff = hpar->phioff[1]; fibin = hpar->phibin[etaR-1]; } else { fioff = hpar->phioff[2]; fibin = hpar->phitable[etaR-hpar->etaMin[2]]; if (unitPhi(fibin) > 2) fioff = hpar->phioff[4]; } phi =-fioff + (iphi - 0.5)*fibin; dphi = 0.5*fibin; if (idet == static_cast<int>(HcalForward)) { int ir = nR + hpar->etaMin[2] - etaR - 1; if (ir > 0 && ir < nR) { rz = 0.5*(hpar->rTable[ir]+hpar->rTable[ir-1]); drz = 0.5*(hpar->rTable[ir]-hpar->rTable[ir-1]); } else { ok = false; #ifdef EDM_ML_DEBUG edm::LogInfo("HCalGeom") << "HcalDDDSimConstants: wrong eta " << etaR << " (" << ir << "/" << nR << ") Detector " << idet << std::endl; #endif } } else if (etaR <= nEta) { int laymin(depth), laymax(depth); if (idet == static_cast<int>(HcalOuter)) { laymin = (etaR > hpar->noff[2]) ? ((int)(hpar->zHE.size())) : ((int)(hpar->zHE.size()))-1; laymax = ((int)(hpar->zHE.size())); } double d1=0, d2=0; if (idet == static_cast<int>(HcalEndcap)) { flagrz = false; d1 = hpar->zHE[laymin-1] - hpar->dzHE[laymin-1]; d2 = hpar->zHE[laymax-1] + hpar->dzHE[laymax-1]; } else { d1 = hpar->rHB[laymin-1] - hpar->drHB[laymin-1]; d2 = hpar->rHB[laymax-1] + hpar->drHB[laymax-1]; } rz = 0.5*(d2+d1); drz = 0.5*(d2-d1); } else { ok = false; edm::LogWarning("HCalGeom") << "HcalDDDSimConstants: wrong depth " << depth << " or etaR " << etaR << " for detector " << idet; } } else { ok = false; edm::LogWarning("HCalGeom") << "HcalDDDSimConstants: wrong depth " << depth << " det " << idet; } HcalCellType::HcalCell tmp(ok,eta,deta,phi,dphi,rz,drz,flagrz); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants: det/side/depth/etaR/" << "phi " << idet << "/" << zside << "/" << depth << "/" << etaR << "/" << iphi << " Cell Flag " << tmp.ok << " " << tmp.eta << " " << tmp.deta << " phi " << tmp.phi << " " << tmp.dphi << " r(z) " << tmp.rz << " " << tmp.drz << " " << tmp.flagrz; #endif return tmp; } int HcalDDDSimConstants::findDepth(const int& det, const int& eta, const int& phi, const int& zside, const int& lay) const { int depth = (ldmap_.isValid(det,phi,zside)) ? ldmap_.getDepth(det,eta,phi,zside,lay) : -1; return depth; } unsigned int HcalDDDSimConstants::findLayer(const int& layer, const std::vector<HcalParameters::LayerItem>& layerGroup) const { unsigned int id = layerGroup.size(); for (unsigned int i = 0; i < layerGroup.size(); i++) { if (layer == (int)(layerGroup[i].layer)) { id = i; break; } } return id; } std::vector<std::pair<double,double> > HcalDDDSimConstants::getConstHBHE(const int& type) const { std::vector<std::pair<double,double> > gcons; if (type == 0) { for (unsigned int i=0; i<hpar->rHB.size(); ++i) { gcons.emplace_back(std::pair<double,double>(hpar->rHB[i],hpar->drHB[i])); } } else { for (unsigned int i=0; i<hpar->zHE.size(); ++i) { gcons.emplace_back(std::pair<double,double>(hpar->zHE[i],hpar->dzHE[i])); } } return gcons; } int HcalDDDSimConstants::getDepthEta16(const int& det, const int& phi, const int& zside) const { int depth = ldmap_.getDepth16(det,phi,zside); if (depth < 0) depth = (det == 2) ? depthEta16[1] : depthEta16[0]; #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "getDepthEta16: " << det << ":" << depth; #endif return depth; } int HcalDDDSimConstants::getDepthEta16M(const int& det) const { int depth = (det == 2) ? depthEta16[1] : depthEta16[0]; std::vector<int> phis; int detsp = ldmap_.validDet(phis); if (detsp == det) { int zside = (phis[0] > 0) ? 1 : -1; int iphi = (phis[0] > 0) ? phis[0] : -phis[0]; int depthsp = ldmap_.getDepth16(det,iphi,zside); if (det == 1 && depthsp > depth) depth = depthsp; if (det == 2 && depthsp < depth) depth = depthsp; } return depth; } int HcalDDDSimConstants::getDepthEta29(const int& phi, const int& zside, const int& i) const { int depth = (i == 0) ? ldmap_.getMaxDepthLastHE(2,phi,zside) : -1; if (depth < 0) depth = (i == 1) ? depthEta29[1] : depthEta29[0]; return depth; } int HcalDDDSimConstants::getDepthEta29M(const int& i, const bool& planOne) const { int depth = (i == 1) ? depthEta29[1] : depthEta29[0]; if (i == 0 && planOne) { std::vector<int> phis; int detsp = ldmap_.validDet(phis); if (detsp == 2) { int zside = (phis[0] > 0) ? 1 : -1; int iphi = (phis[0] > 0) ? phis[0] : -phis[0]; int depthsp = ldmap_.getMaxDepthLastHE(2,iphi,zside); if (depthsp > depth) depth = depthsp; } } return depth; } std::pair<int,double> HcalDDDSimConstants::getDetEta(const double& eta, const int& depth) const { int hsubdet(0), ieta(0); double etaR(0); double heta = fabs(eta); for (int i = 0; i < nEta; i++) if (heta > hpar->etaTable[i]) ieta = i + 1; if (heta <= hpar->etaRange[1]) { if ((ieta == hpar->etaMin[1] && depth==depthEta16[1]) || (ieta > hpar->etaMax[0])) { hsubdet = static_cast<int>(HcalEndcap); } else { hsubdet = static_cast<int>(HcalBarrel); } etaR = eta; } else { hsubdet = static_cast<int>(HcalForward); double theta = 2.*atan(exp(-heta)); double hR = zVcal*tan(theta); etaR = (eta >= 0. ? hR : -hR); } return std::pair<int,double>(hsubdet,etaR); } int HcalDDDSimConstants::getEta(const int& det, const int& lay, const double& hetaR) const { int ieta(0); if (det == static_cast<int>(HcalForward)) { // Forward HCal ieta = hpar->etaMax[2]; for (int i = nR-1; i > 0; i--) if (hetaR < hpar->rTable[i]) ieta = hpar->etaMin[2] + nR - i - 1; } else { // Barrel or Endcap ieta = 1; for (int i = 0; i < nEta-1; i++) if (hetaR > hpar->etaTable[i]) ieta = i + 1; if (det == static_cast<int>(HcalBarrel)) { if (ieta > hpar->etaMax[0]) ieta = hpar->etaMax[0]; if (lay == maxLayer_) { if (hetaR > etaHO[1] && ieta == hpar->noff[2]) ieta++; } } else if (det == static_cast<int>(HcalEndcap)) { if (ieta <= hpar->etaMin[1]) ieta = hpar->etaMin[1]; } } return ieta; } std::pair<int,int> HcalDDDSimConstants::getEtaDepth(const int& det, int etaR, const int& phi, const int& zside, int depth, const int& lay) const { #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDEsimConstants:getEtaDepth: I/P " << det << ":" << etaR << ":" << phi << ":" << zside << ":" << depth << ":" << lay; #endif //Modify the depth index if ((det == static_cast<int>(HcalEndcap)) && (etaR == 17) && (lay == 1)) etaR = 18; if (det == static_cast<int>(HcalForward)) { // Forward HCal } else if (det == static_cast<int>(HcalOuter)) { depth = 4; } else { if (lay >= 0) { depth = layerGroup(det, etaR, phi, zside, lay-1); if (etaR == hpar->noff[0] && lay > 1) { int kphi = phi + int((hpar->phioff[3]+0.1)/hpar->phibin[etaR-1]); kphi = (kphi-1)%4 + 1; if (kphi == 2 || kphi == 3) depth = layerGroup(det, etaR, phi, zside, lay-2); } } else if (det == static_cast<int>(HcalBarrel)) { if (depth>getMaxDepth(det,etaR,phi,zside,false)) depth = getMaxDepth(det,etaR,phi,zside,false); } if (etaR >= hpar->noff[1] && depth > getDepthEta29(phi,zside,0)) { etaR -= getDepthEta29(phi,zside,1); } else if (etaR == hpar->etaMin[1]) { if (det == static_cast<int>(HcalBarrel)) { if (depth > getDepthEta16(det, phi, zside)) depth = getDepthEta16(det, phi, zside); } else { if (depth < getDepthEta16(det, phi, zside)) depth = getDepthEta16(det, phi, zside); } } } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDEsimConstants:getEtaDepth: O/P " << etaR << ":" << depth; #endif return std::pair<int,int>(etaR,depth); } double HcalDDDSimConstants::getEtaHO(const double& etaR, const double& x, const double& y, const double& z) const { if (hpar->zHO.size() > 4) { double eta = fabs(etaR); double r = std::sqrt(x*x+y*y); if (r > rminHO) { double zz = fabs(z); if (zz > hpar->zHO[3]) { if (eta <= hpar->etaTable[10]) eta = hpar->etaTable[10]+0.001; } else if (zz > hpar->zHO[1]) { if (eta <= hpar->etaTable[4]) eta = hpar->etaTable[4]+0.001; } } eta = (z >= 0. ? eta : -eta); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "R " << r << " Z " << z << " eta " << etaR << ":" << eta; if (eta != etaR) edm::LogInfo ("HCalGeom") << "**** Check *****"; #endif return eta; } else { return etaR; } } int HcalDDDSimConstants::getFrontLayer(const int& det, const int& eta) const { int lay=0; if (det == 1) { if (std::abs(eta) == 16) lay = layFHB[1]; else lay = layFHB[0]; } else { if (std::abs(eta) == 16) lay = layFHE[1]; else if (std::abs(eta) == 18) lay = layFHE[2]; else lay = layFHE[0]; } return lay; } int HcalDDDSimConstants::getLastLayer(const int& det, const int& eta) const { int lay=0; if (det == 1) { if (std::abs(eta) == 15) lay = layBHB[1]; else if (std::abs(eta) == 16) lay = layBHB[2]; else lay = layBHB[0]; } else { if (std::abs(eta) == 16) lay = layBHE[1]; else if (std::abs(eta) == 17) lay = layBHE[2]; else if (std::abs(eta) == 18) lay = layBHE[3]; else lay = layBHE[0]; } return lay; } double HcalDDDSimConstants::getLayer0Wt(const int& det, const int& phi, const int& zside) const { double wt = ldmap_.getLayer0Wt(det, phi, zside); if (wt < 0) wt = (det == 2) ? hpar->Layer0Wt[1] : hpar->Layer0Wt[0]; return wt; } int HcalDDDSimConstants::getLayerFront(const int& det, const int& eta, const int& phi, const int& zside, const int& depth) const { int layer = ldmap_.getLayerFront(det, eta, phi, zside, depth); if (layer < 0) { if (det == 1 || det == 2) { layer = 1; for (int l=0; l<getLayerMax(eta,depth); ++l) { if ((int)(layerGroup(eta-1,l)) == depth+1) { layer = l+1; break; } } } else { layer = (eta > hpar->noff[2]) ? maxLayerHB_+1 : maxLayer_; } } return layer; } int HcalDDDSimConstants::getLayerBack(const int& det, const int& eta, const int& phi, const int& zside, const int& depth) const { int layer = ldmap_.getLayerBack(det, eta, phi, zside, depth); if (layer < 0) { if (det == 1 || det ==2) { layer = depths[depth-1][eta-1]; } else { layer = maxLayer_; } } return layer; } int HcalDDDSimConstants::getLayerMax(const int& eta, const int& depth) const { int layermx = ((eta < hpar->etaMin[1]) && depth-1 < maxDepth[0]) ? maxLayerHB_+1 : (int)layerGroupSize(eta-1); return layermx; } int HcalDDDSimConstants::getMaxDepth(const int& det, const int& eta, const int& phi, const int& zside, const bool& partialDetOnly) const { int dmax(-1); if (partialDetOnly) { if (ldmap_.isValid(det,phi,zside)) { dmax = ldmap_.getDepths(eta).second; } } else if (det == 1 || det == 2) { if (ldmap_.isValid(det,phi,zside)) dmax = ldmap_.getDepths(eta).second; else if (det == 2) dmax = layerGroup(eta-1,maxLayer_); else if (eta == hpar->etaMax[0]) dmax = getDepthEta16(det,phi,zside); else dmax = layerGroup(eta-1,maxLayerHB_); } else if (det == 3) { // HF dmax = maxHFDepth(zside*eta,phi); } else if (det == 4) { // HO dmax = maxDepth[3]; } else { dmax = -1; } return dmax; } int HcalDDDSimConstants::getMinDepth(const int& det, const int& eta, const int& phi, const int& zside, const bool& partialDetOnly) const { int lmin(-1); if (partialDetOnly) { if (ldmap_.isValid(det,phi,zside)) { lmin = ldmap_.getDepths(eta).first; } } else if (det == 3) { // HF lmin = 1; } else if (det == 4) { // HO lmin = maxDepth[3]; } else { if (ldmap_.isValid(det,phi,zside)) { lmin = ldmap_.getDepths(eta).first; } else if (layerGroupSize(eta-1) > 0) { lmin = (int)(layerGroup(eta-1, 0)); unsigned int type = (det == 1) ? 0 : 1; if (type == 1 && eta == hpar->etaMin[1]) lmin = getDepthEta16(det, phi, zside); } else { lmin = 1; } } return lmin; } std::pair<int,int> HcalDDDSimConstants::getModHalfHBHE(const int& type) const { if (type == 0) { return std::pair<int,int>(nmodHB,nzHB); } else { return std::pair<int,int>(nmodHE,nzHE); } } std::pair<double,double> HcalDDDSimConstants::getPhiCons(const int& det, const int& ieta) const { double fioff(0), fibin(0); if (det == static_cast<int>(HcalForward)) { // Forward HCal fioff = hpar->phioff[2]; fibin = hpar->phitable[ieta-hpar->etaMin[2]]; if (unitPhi(fibin) > 2) { // HF double-phi fioff = hpar->phioff[4]; } } else { // Barrel or Endcap if (det == static_cast<int>(HcalEndcap)) { fioff = hpar->phioff[1]; } else { fioff = hpar->phioff[0]; } fibin = hpar->phibin[ieta-1]; } return std::pair<double,double>(fioff,fibin); } std::vector<std::pair<int,double> > HcalDDDSimConstants::getPhis(const int& subdet, const int& ieta) const { std::vector<std::pair<int,double> > phis; int ietaAbs = (ieta > 0) ? ieta : -ieta; std::pair<double,double> ficons = getPhiCons(subdet, ietaAbs); int nphi = int((CLHEP::twopi+0.1*ficons.second)/ficons.second); int units = unitPhi(subdet, ietaAbs); for (int ifi = 0; ifi < nphi; ++ifi) { double phi =-ficons.first + (ifi+0.5)*ficons.second; int iphi = phiNumber(ifi+1,units); phis.emplace_back(std::pair<int,double>(iphi,phi)); } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "getPhis: subdet|ieta|iphi " << subdet << "|" << ieta << " with " << phis.size() << " phi bins"; for (unsigned int k=0; k<phis.size(); ++k) edm::LogVerbatim("HcalGeom") << "[" << k << "] iphi " << phis[k].first << " phi " << phis[k].second/CLHEP::deg; #endif return phis; } std::vector<HcalCellType> HcalDDDSimConstants::HcalCellTypes() const{ std::vector<HcalCellType> cellTypes = HcalCellTypes(HcalBarrel); #ifdef EDM_ML_DEBUG edm::LogInfo ("HCalGeom") << "HcalDDDSimConstants: " << cellTypes.size() << " cells of type HCal Barrel\n"; for (unsigned int i=0; i<cellTypes.size(); i++) edm::LogInfo ("HCalGeom") << "Cell " << i << " " << cellTypes[i] << "\n"; #endif std::vector<HcalCellType> hoCells = HcalCellTypes(HcalOuter); #ifdef EDM_ML_DEBUG edm::LogInfo ("HCalGeom") << "HcalDDDSimConstants: " << hoCells.size() << " cells of type HCal Outer\n"; for (unsigned int i=0; i<hoCells.size(); i++) edm::LogInfo ("HCalGeom") << "Cell " << i << " " << hoCells[i] << "\n"; #endif cellTypes.insert(cellTypes.end(), hoCells.begin(), hoCells.end()); std::vector<HcalCellType> heCells = HcalCellTypes(HcalEndcap); #ifdef EDM_ML_DEBUG edm::LogInfo ("HCalGeom") << "HcalDDDSimConstants: " << heCells.size() << " cells of type HCal Endcap\n"; for (unsigned int i=0; i<heCells.size(); i++) edm::LogInfo ("HCalGeom") << "Cell " << i << " " << heCells[i] << "\n"; #endif cellTypes.insert(cellTypes.end(), heCells.begin(), heCells.end()); std::vector<HcalCellType> hfCells = HcalCellTypes(HcalForward); #ifdef EDM_ML_DEBUG edm::LogInfo ("HCalGeom") << "HcalDDDSimConstants: " << hfCells.size() << " cells of type HCal Forward\n"; for (unsigned int i=0; i<hfCells.size(); i++) edm::LogInfo ("HCalGeom") << "Cell " << i << " " << hfCells[i] << "\n"; #endif cellTypes.insert(cellTypes.end(), hfCells.begin(), hfCells.end()); return cellTypes; } std::vector<HcalCellType> HcalDDDSimConstants::HcalCellTypes(const HcalSubdetector& subdet, int ieta, int depthl) const { std::vector<HcalCellType> cellTypes; if (subdet == HcalForward) { if (dzVcal < 0) return cellTypes; } int dmin, dmax, indx, nz; double hsize = 0; switch(subdet) { case HcalEndcap: dmin = 1; dmax = maxLayer_+1; indx = 1; nz = nzHE; break; case HcalForward: dmin = 1; dmax = (!idHF2QIE.empty()) ? 2 : maxDepth[2]; indx = 2; nz = 2; break; case HcalOuter: dmin = 4; dmax = 4; indx = 0; nz = nzHB; break; default: dmin = 1; dmax = maxLayerHB_+1; indx = 0; nz = nzHB; break; } if (depthl > 0) dmin = dmax = depthl; int ietamin = (ieta>0) ? ieta : hpar->etaMin[indx]; int ietamax = (ieta>0) ? ieta : hpar->etaMax[indx]; int phi = (indx == 2) ? 3 : 1; // Get the Cells int subdet0 = static_cast<int>(subdet); for (int depth=dmin; depth<=dmax; depth++) { int shift = getShift(subdet, depth); double gain = getGain (subdet, depth); if (subdet == HcalForward) { if (depth%2 == 1) hsize = dzVcal; else hsize = dzVcal-0.5*dlShort; } for (int eta=ietamin; eta<=ietamax; eta++) { for (int iz=0; iz<nz; ++iz) { int zside = -2*iz + 1; HcalCellType::HcalCell temp1 = cell(subdet0,zside,depth,eta,phi); if (temp1.ok) { std::vector<std::pair<int,double> > phis = getPhis(subdet0,eta); HcalCellType temp2(subdet, eta, zside, depth, temp1, shift, gain, hsize); double dphi, fioff; std::vector<int> phiMiss2; if ((subdet == HcalBarrel) || (subdet == HcalOuter)) { fioff = hpar->phioff[0]; dphi = hpar->phibin[eta-1]; if (subdet == HcalOuter) { if (eta == hpar->noff[4]) { int kk = (iz == 0) ? 7 : (7+hpar->noff[5]); for (int miss=0; miss<hpar->noff[5+iz]; miss++) { phiMiss2.emplace_back(hpar->noff[kk]); kk++; } } } } else if (subdet == HcalEndcap) { fioff = hpar->phioff[1]; dphi = hpar->phibin[eta-1]; } else { fioff = hpar->phioff[2]; dphi = hpar->phitable[eta-hpar->etaMin[2]]; if (unitPhi(dphi) > 2) fioff = hpar->phioff[4]; } int unit = unitPhi(dphi); temp2.setPhi(phis,phiMiss2,fioff,dphi,unit); cellTypes.emplace_back(temp2); // For HF look at extra cells if ((subdet == HcalForward) && (!idHF2QIE.empty())) { HcalCellType temp3(subdet, eta, zside+2, depth, temp1, shift, gain, hsize); std::vector<int> phiMiss3; for (auto & phi : phis) { bool ok(false); for (auto l : idHF2QIE) { if ((eta*zside == l.ieta()) && (phi.first == l.iphi())) { ok = true; break; } } if (!ok) phiMiss3.emplace_back(phi.first); } dphi = hpar->phitable[eta-hpar->etaMin[2]]; unit = unitPhi(dphi); fioff = (unit > 2) ? hpar->phioff[4] : hpar->phioff[2]; temp3.setPhi(phis,phiMiss2,fioff,dphi,unit); cellTypes.emplace_back(temp3); } } } } } return cellTypes; } int HcalDDDSimConstants::maxHFDepth(const int& eta, const int& iphi) const { int mxdepth = maxDepth[2]; if (!idHF2QIE.empty()) { bool ok(false); for (auto k : idHF2QIE) { if ((eta == k.ieta()) && (iphi == k.iphi())) { ok = true; break; } } if (!ok) mxdepth = 2; } return mxdepth; } unsigned int HcalDDDSimConstants::numberOfCells(const HcalSubdetector& subdet) const{ unsigned int num = 0; std::vector<HcalCellType> cellTypes = HcalCellTypes(subdet); for (auto & cellType : cellTypes) { num += (unsigned int)(cellType.nPhiBins()); } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants:numberOfCells " << cellTypes.size() << " " << num << " for subdetector " << subdet; #endif return num; } int HcalDDDSimConstants::phiNumber(const int& phi, const int& units) const { int iphi_skip = phi; if (units==2) iphi_skip = (phi-1)*2+1; else if (units==4) iphi_skip = (phi-1)*4-1; if (iphi_skip < 0) iphi_skip += 72; return iphi_skip; } void HcalDDDSimConstants::printTiles() const { std::vector<int> phis; int detsp = ldmap_.validDet(phis); int kphi = (detsp > 0) ? phis[0] : 1; int zside = (kphi > 0) ? 1 : -1; int iphi = (kphi > 0) ? kphi : -kphi; edm::LogVerbatim("HcalGeom") << "Tile Information for HB from " << hpar->etaMin[0] << " to " << hpar->etaMax[0] << "\n"; for (int eta=hpar->etaMin[0]; eta<= hpar->etaMax[0]; eta++) { int dmax = getMaxDepth(1,eta,iphi,-zside,false); for (int depth=1; depth<=dmax; depth++) printTileHB(eta, iphi, -zside, depth); if (detsp == 1) { int dmax = getMaxDepth(1,eta,iphi,zside,false); for (int depth=1; depth<=dmax; depth++) printTileHB(eta, iphi, zside, depth); } } edm::LogVerbatim("HcalGeom") << "\nTile Information for HE from " << hpar->etaMin[1] << " to " << hpar->etaMax[1] << "\n"; for (int eta=hpar->etaMin[1]; eta<= hpar->etaMax[1]; eta++) { int dmin = (eta == hpar->etaMin[1]) ? getDepthEta16(2,iphi,-zside) : 1; int dmax = getMaxDepth(2,eta,iphi,-zside,false); for (int depth=dmin; depth<=dmax; depth++) printTileHE(eta, iphi, -zside, depth); if (detsp == 2) { int dmax = getMaxDepth(2,eta,iphi,zside,false); for (int depth=1; depth<=dmax; depth++) printTileHE(eta, iphi, zside, depth); } } } int HcalDDDSimConstants::unitPhi(const int& det, const int& etaR) const { double dphi = (det == static_cast<int>(HcalForward)) ? hpar->phitable[etaR-hpar->etaMin[2]] : hpar->phibin[etaR-1]; return unitPhi(dphi); } int HcalDDDSimConstants::unitPhi(const double& dphi) const { const double fiveDegInRad = 2*M_PI/72; int units = int(dphi/fiveDegInRad+0.5); if (units < 1) units = 1; return units; } void HcalDDDSimConstants::initialize( void ) { nEta = hpar->etaTable.size(); nR = hpar->rTable.size(); nPhiF = nR - 1; isBH_ = false; #ifdef EDM_ML_DEBUG for (int i=0; i<nEta-1; ++i) { edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants:Read LayerGroup" << i << ":"; for (unsigned int k=0; k<layerGroupSize( i ); k++) edm::LogVerbatim("HcalGeom") << " [" << k << "] = " << layerGroup(i, k); } #endif // Geometry parameters for HF dlShort = hpar->gparHF[0]; zVcal = hpar->gparHF[4]; dzVcal = hpar->dzVcal; #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants: dlShort " << dlShort << " zVcal " << zVcal << " and dzVcal " << dzVcal; #endif //Transform some of the parameters maxDepth = hpar->maxDepth; maxDepth[0] = maxDepth[1] = 0; for (int i=0; i<nEta-1; ++i) { unsigned int imx = layerGroupSize( i ); int laymax = (imx > 0) ? layerGroup( i, imx-1 ) : 0; if (i < hpar->etaMax[0]) { int laymax0 = (imx > 16) ? layerGroup(i, 16) : laymax; if (i+1 == hpar->etaMax[0] && laymax0 > 2) laymax0 = 2; if (maxDepth[0] < laymax0) maxDepth[0] = laymax0; } if (i >= hpar->etaMin[1]-1 && i < hpar->etaMax[1]) { if (maxDepth[1] < laymax) maxDepth[1] = laymax; } } #ifdef EDM_ML_DEBUG for (int i=0; i<4; ++i) edm::LogVerbatim("HcalGeom") << "Detector Type [" << i << "] iEta " << hpar->etaMin[i] << ":" << hpar->etaMax[i] << " MaxDepth " << maxDepth[i]; #endif int maxdepth = (maxDepth[1]>maxDepth[0]) ? maxDepth[1] : maxDepth[0]; for (int i=0; i<maxdepth; ++i) { for (int k=0; k<nEta-1; ++k) { int layermx = getLayerMax(k+1,i+1); int ll = layermx; for (int l=layermx-1; l >= 0; --l) { if ((int)layerGroup( k, l ) == i+1) { ll = l+1; break; } } depths[i].emplace_back(ll); } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "Depth " << i << " with " << depths[i].size() << " etas:"; for (int k=0; k<nEta-1; ++k) edm::LogVerbatim("HcalGeom") << " [" << k << "] " << depths[i][k]; #endif } nzHB = hpar->modHB[1]; nmodHB = hpar->modHB[0]; nzHE = hpar->modHE[1]; nmodHE = hpar->modHE[0]; #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants:: " << nzHB << ":" << nmodHB << " barrel and " << nzHE << ":" << nmodHE << " endcap half-sectors"; #endif if (hpar->rHB.size() > maxLayerHB_+1 && hpar->zHO.size() > 4) { rminHO = hpar->rHO[0]; for (int k=0; k<4; ++k) etaHO[k] = hpar->rHO[k+1]; } else { rminHO =-1.0; etaHO[0] = hpar->etaTable[4]; etaHO[1] = hpar->etaTable[4]; etaHO[2] = hpar->etaTable[10]; etaHO[3] = hpar->etaTable[10]; } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HO Eta boundaries " << etaHO[0] << " " << etaHO[1] << " " << etaHO[2] << " " << etaHO[3]; edm::LogVerbatim("HcalGeom") << "HO Parameters " << rminHO << " " << hpar->zHO.size(); for (int i=0; i<4; ++i) edm::LogVerbatim("HcalGeom") << " eta[" << i << "] = " << etaHO[i]; for (unsigned int i=0; i<hpar->zHO.size(); ++i) edm::LogVerbatim("HcalGeom") << " zHO[" << i << "] = " << hpar->zHO[i]; #endif int noffsize = 7 + hpar->noff[5] + hpar->noff[6]; int noffl(noffsize+5); if ((int)(hpar->noff.size()) > (noffsize+3)) { depthEta16[0] = hpar->noff[noffsize]; depthEta16[1] = hpar->noff[noffsize+1]; depthEta29[0] = hpar->noff[noffsize+2]; depthEta29[1] = hpar->noff[noffsize+3]; if ((int)(hpar->noff.size()) > (noffsize+4)) { noffl += (2*hpar->noff[noffsize+4]); if ((int)(hpar->noff.size()) > noffl) isBH_ = (hpar->noff[noffl] > 0); } } else { depthEta16[0] = 2; depthEta16[1] = 3; depthEta29[0] = 2; depthEta29[1] = 1; } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "isBH_ " << hpar->noff.size() << ":" << noffsize << ":" << noffl << ":" << isBH_; edm::LogVerbatim("HcalGeom") << "Depth index at ieta = 16 for HB (max) " << depthEta16[0] << " HE (min) " <<depthEta16[1] << "; max depth for itea = 29 : (" << depthEta29[0] << ":" << depthEta29[1] << ")"; #endif if ((int)(hpar->noff.size()) > (noffsize+4)) { int npair = hpar->noff[noffsize+4]; int kk = noffsize+4; for (int k=0; k<npair; ++k) { idHF2QIE.emplace_back(HcalDetId(HcalForward,hpar->noff[kk+1],hpar->noff[kk+2],1)); kk += 2; } } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << idHF2QIE.size() << " detector channels having 2 QIE cards:"; for (unsigned int k=0; k<idHF2QIE.size(); ++k) edm::LogVerbatim("HcalGeom") << " [" << k << "] " << idHF2QIE[k]; #endif layFHB[0] = 0; layFHB[1] = 1; layBHB[0] = 16; layBHB[1] = 15; layBHB[2] = 8; layFHE[0] = 1; layFHE[1] = 4; layFHE[2] = 0; layBHE[0] = 18; layBHE[1] = 9; layBHE[2] = 14; layBHE[3] = 16; depthMaxSp_ = std::pair<int,int>(0,0); int noffk(noffsize+5); if ((int)(hpar->noff.size()) > (noffsize+5)) { noffk += (2*hpar->noff[noffsize+4]); if ((int)(hpar->noff.size()) >= noffk+7) { int dtype = hpar->noff[noffk+1]; int nphi = hpar->noff[noffk+2]; int ndeps = hpar->noff[noffk+3]; int ndp16 = hpar->noff[noffk+4]; int ndp29 = hpar->noff[noffk+5]; double wt = 0.1*(hpar->noff[noffk+6]); if ((int)(hpar->noff.size()) >= (noffk+7+nphi+3*ndeps)) { if (dtype == 1 || dtype == 2) { std::vector<int> ifi, iet, ily, idp; for (int i=0; i<nphi; ++i) ifi.emplace_back(hpar->noff[noffk+7+i]); for (int i=0; i<ndeps;++i) { iet.emplace_back(hpar->noff[noffk+7+nphi+3*i]); ily.emplace_back(hpar->noff[noffk+7+nphi+3*i+1]); idp.emplace_back(hpar->noff[noffk+7+nphi+3*i+2]); } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "Initialize HcalLayerDepthMap for " << "Detector " << dtype << " etaMax " << hpar->etaMax[dtype] << " with " << nphi << " sectors"; for (int i=0; i<nphi; ++i) edm::LogVerbatim("HcalGeom") << " [" << i << "] " << ifi[i]; edm::LogVerbatim("HcalGeom") << "And " << ndeps << " depth sections"; for (int i=0; i<ndeps;++i) edm::LogVerbatim("HcalGeom") << " [" << i << "] " << iet[i] << " " << ily[i] << " " << idp[i]; edm::LogVerbatim("HcalGeom") <<"Maximum depth for last HE Eta tower " << depthEta29[0] << ":" << ndp16 << ":" << ndp29 << " L0 Wt " << hpar->Layer0Wt[dtype-1] << ":" << wt; #endif ldmap_.initialize(dtype,hpar->etaMax[dtype-1],ndp16,ndp29,wt,ifi,iet, ily,idp); int zside = (ifi[0]>0) ? 1 : -1; int iphi = (ifi[0]>0) ? ifi[0] : -ifi[0]; depthMaxSp_ = std::pair<int,int>(dtype,ldmap_.getDepthMax(dtype,iphi,zside)); } } int noffm = (noffk+7+nphi+3*ndeps); if ((int)(hpar->noff.size()) > noffm) { int ndnext = hpar->noff[noffm]; if (ndnext > 4 && (int)(hpar->noff.size()) >= noffm+ndnext) { for (int i=0; i<2; ++i) layFHB[i] = hpar->noff[noffm+i+1]; for (int i=0; i<3; ++i) layFHE[i] = hpar->noff[noffm+i+3]; } if (ndnext > 11 && (int)(hpar->noff.size()) >= noffm+ndnext) { for (int i=0; i<3; ++i) layBHB[i] = hpar->noff[noffm+i+6]; for (int i=0; i<4; ++i) layBHE[i] = hpar->noff[noffm+i+9]; } } } } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "Front Layer Definition for HB: " << layFHB[0] << ":" << layFHB[1] << " and for HE: " << layFHE[0] << ":" << layFHE[1] << ":" << layFHE[2]; edm::LogVerbatim("HcalGeom") << "Last Layer Definition for HB: " << layBHB[0] << ":" << layBHB[1] << ":" << layBHB[2] << " and for HE: " << layBHE[0] << ":" << layBHE[1] << ":" << layBHE[2] << ":" << layBHE[3]; #endif if (depthMaxSp_.first == 0) { depthMaxSp_ = depthMaxDf_ = std::pair<int,int>(2,maxDepth[1]); } else if (depthMaxSp_.first == 1) { depthMaxDf_ = std::pair<int,int>(1,maxDepth[0]); if (depthMaxSp_.second > maxDepth[0]) maxDepth[0] = depthMaxSp_.second; } else { depthMaxDf_ = std::pair<int,int>(2,maxDepth[1]); if (depthMaxSp_.second > maxDepth[1]) maxDepth[1] = depthMaxSp_.second; } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") <<"Detector type and maximum depth for all RBX " << depthMaxDf_.first << ":" <<depthMaxDf_.second << " and for special RBX " << depthMaxSp_.first << ":" << depthMaxSp_.second; #endif } double HcalDDDSimConstants::deltaEta(const int& det, const int& etaR, const int& depth) const { double tmp = 0; if (det == static_cast<int>(HcalForward)) { int ir = nR + hpar->etaMin[2] - etaR - 1; if (ir > 0 && ir < nR) { double z = zVcal; if (depth%2 != 1) z += dlShort; tmp = 0.5*(getEta(hpar->rTable[ir-1],z)-getEta(hpar->rTable[ir],z)); } } else { if (etaR > 0 && etaR < nEta) { if (etaR == hpar->noff[1]-1 && depth > depthEta29[0]) { tmp = 0.5*(hpar->etaTable[etaR+1]-hpar->etaTable[etaR-1]); } else if (det == static_cast<int>(HcalOuter)) { if (etaR == hpar->noff[2]) { tmp = 0.5*(etaHO[0]-hpar->etaTable[etaR-1]); } else if (etaR == hpar->noff[2]+1) { tmp = 0.5*(hpar->etaTable[etaR]-etaHO[1]); } else if (etaR == hpar->noff[3]) { tmp = 0.5*(etaHO[2]-hpar->etaTable[etaR-1]); } else if (etaR == hpar->noff[3]+1) { tmp = 0.5*(hpar->etaTable[etaR]-etaHO[3]); } else { tmp = 0.5*(hpar->etaTable[etaR]-hpar->etaTable[etaR-1]); } } else { tmp = 0.5*(hpar->etaTable[etaR]-hpar->etaTable[etaR-1]); } } } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants::deltaEta " << etaR << " " << depth << " ==> " << tmp; #endif return tmp; } double HcalDDDSimConstants::getEta(const int& det, const int& etaR, const int& zside, int depth) const { double tmp = 0; if (det == static_cast<int>(HcalForward)) { int ir = nR + hpar->etaMin[2] - etaR - 1; if (ir > 0 && ir < nR) { double z = zVcal; if (depth%2 != 1) z += dlShort; tmp = 0.5*(getEta(hpar->rTable[ir-1],z)+getEta(hpar->rTable[ir],z)); } } else { if (etaR > 0 && etaR < nEta) { if (etaR == hpar->noff[1]-1 && depth > depthEta29[0]) { tmp = 0.5*(hpar->etaTable[etaR+1]+hpar->etaTable[etaR-1]); } else if (det == static_cast<int>(HcalOuter)) { if (etaR == hpar->noff[2]) { tmp = 0.5*(etaHO[0]+hpar->etaTable[etaR-1]); } else if (etaR == hpar->noff[2]+1) { tmp = 0.5*(hpar->etaTable[etaR]+etaHO[1]); } else if (etaR == hpar->noff[3]) { tmp = 0.5*(etaHO[2]+hpar->etaTable[etaR-1]); } else if (etaR == hpar->noff[3]+1) { tmp = 0.5*(hpar->etaTable[etaR]+etaHO[3]); } else { tmp = 0.5*(hpar->etaTable[etaR]+hpar->etaTable[etaR-1]); } } else { tmp = 0.5*(hpar->etaTable[etaR]+hpar->etaTable[etaR-1]); } } } if (zside == 0) tmp = -tmp; #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants::getEta " << etaR << " " << zside << " " << depth << " ==> " << tmp; #endif return tmp; } double HcalDDDSimConstants::getEta(const double& r, const double& z) const { double tmp = 0; if (z != 0) tmp = -log(tan(0.5*atan(r/z))); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants::getEta " << r << " " << z << " ==> " << tmp; #endif return tmp; } int HcalDDDSimConstants::getShift(const HcalSubdetector& subdet, const int& depth) const { int shift; switch(subdet) { case HcalEndcap: shift = hpar->HEShift[0]; break; case HcalForward: shift = hpar->HFShift[(depth-1)%2]; break; case HcalOuter: shift = hpar->HBShift[3]; break; default: shift = hpar->HBShift[0]; break; } return shift; } double HcalDDDSimConstants::getGain(const HcalSubdetector& subdet, const int& depth) const { double gain; switch(subdet) { case HcalEndcap: gain = hpar->HEGains[0]; break; case HcalForward: gain = hpar->HFGains[(depth-1)%2]; break; case HcalOuter: gain = hpar->HBGains[3]; break; default: gain = hpar->HBGains[0]; break; } return gain; } void HcalDDDSimConstants::printTileHB(const int& eta, const int& phi, const int& zside, const int& depth) const { edm::LogVerbatim("HcalGeom") << "HcalDDDSimConstants::printTileHB for eta " << eta << " and depth " << depth; double etaL = hpar->etaTable.at(eta-1); double thetaL = 2.*atan(exp(-etaL)); double etaH = hpar->etaTable.at(eta); double thetaH = 2.*atan(exp(-etaH)); int layL = getLayerFront(1,eta,phi,zside,depth); int layH = getLayerBack(1,eta,phi,zside,depth); edm::LogVerbatim("HcalGeom") << "\ntileHB:: eta|depth " << zside*eta << "|" << depth << " theta " << thetaH/CLHEP::deg << ":" << thetaL/CLHEP::deg << " Layer " << layL << ":" << layH-1; for (int lay=layL; lay<layH; ++lay) { std::vector<double> area(2,0); int kk(0); double mean(0); for (unsigned int k=0; k<hpar->layHB.size(); ++k) { if (lay == hpar->layHB[k]) { double zmin = hpar->rhoxHB[k]*std::cos(thetaL)/std::sin(thetaL); double zmax = hpar->rhoxHB[k]*std::cos(thetaH)/std::sin(thetaH); double dz = (std::min(zmax,hpar->dxHB[k]) - zmin); if (dz > 0) { area[kk] = dz*hpar->dyHB[k]; mean += area[kk]; kk++; } } } if (area[0] > 0) { mean /= (kk*100); edm::LogVerbatim("HcalGeom") << std::setw(2) << lay << " Area " << std::setw(8) << area[0] << " " << std::setw(8) << area[1] << " Mean " << mean; } } } void HcalDDDSimConstants::printTileHE(const int& eta, const int& phi, const int& zside, const int& depth) const { double etaL = hpar->etaTable[eta-1]; double thetaL = 2.*atan(exp(-etaL)); double etaH = hpar->etaTable[eta]; double thetaH = 2.*atan(exp(-etaH)); int layL = getLayerFront(2,eta,phi,zside,depth); int layH = getLayerBack(2,eta,phi,zside,depth); double phib = hpar->phibin[eta-1]; int nphi = 2; if (phib > 6*CLHEP::deg) nphi = 1; edm::LogVerbatim("HcalGeom") << "\ntileHE:: Eta/depth " << zside*eta << "|" << depth << " theta " << thetaH/CLHEP::deg << ":" << thetaL/CLHEP::deg << " Layer " << layL << ":" << layH-1 << " phi " << nphi; for (int lay=layL; lay<layH; ++lay) { std::vector<double> area(4,0); int kk(0); double mean(0); for (unsigned int k=0; k<hpar->layHE.size(); ++k) { if (lay == hpar->layHE[k]) { double rmin = hpar->zxHE[k]*std::tan(thetaH); double rmax = hpar->zxHE[k]*std::tan(thetaL); if ((lay != 0 || eta == 18) && (lay != 1 || (eta == 18 && hpar->rhoxHE[k]-hpar->dyHE[k] > 1000) || (eta != 18 && hpar->rhoxHE[k]-hpar->dyHE[k] < 1000)) && rmin+30 < hpar->rhoxHE[k]+hpar->dyHE[k] && rmax > hpar->rhoxHE[k]-hpar->dyHE[k]) { rmin = std::max(rmin,hpar->rhoxHE[k]-hpar->dyHE[k]); rmax = std::min(rmax,hpar->rhoxHE[k]+hpar->dyHE[k]); double dx1 = rmin*std::tan(phib); double dx2 = rmax*std::tan(phib); double ar1=0, ar2=0; if (nphi == 1) { ar1 = 0.5*(rmax-rmin)*(dx1+dx2-4.*hpar->dx1HE[k]); mean += ar1; } else { ar1 = 0.5*(rmax-rmin)*(dx1+dx2-2.*hpar->dx1HE[k]); ar2 = 0.5*(rmax-rmin)*((rmax+rmin)*tan(10.*CLHEP::deg)-4*hpar->dx1HE[k])-ar1; mean += (ar1+ar2); } area[kk] = ar1; area[kk+2] = ar2; kk++; } } } if (area[0] > 0 && area[1] > 0) { int lay0 = lay-1; if (eta == 18) lay0++; if (nphi == 1) { mean /= (kk*100); edm::LogVerbatim("HcalGeom") << std::setw(2) << lay0 << " Area " << std::setw(8) << area[0] << " " << std::setw(8) << area[1] << " Mean " << mean; } else { mean /= (kk*200); edm::LogVerbatim("HcalGeom") << std::setw(2) << lay0 << " Area " << std::setw(8) << area[0] << " " << std::setw(8) << area[1] << ":" << std::setw(8) << area[2] << " " << std::setw(8) << area[3] << " Mean " << mean; } } } } unsigned int HcalDDDSimConstants::layerGroupSize(int eta) const { unsigned int k = 0; for (auto const & it : hpar->layerGroupEtaSim) { if (it.layer == (unsigned int)(eta + 1)) { return it.layerGroup.size(); } if (it.layer > (unsigned int)(eta + 1)) break; k = it.layerGroup.size(); } return k; } unsigned int HcalDDDSimConstants::layerGroup(int eta, int i) const { unsigned int k = 0; for (auto const & it : hpar->layerGroupEtaSim) { if (it.layer == (unsigned int)(eta + 1)) { return it.layerGroup.at(i); } if (it.layer > (unsigned int)(eta + 1)) break; k = it.layerGroup.at(i); } return k; } unsigned int HcalDDDSimConstants::layerGroup(int det, int eta, int phi, int zside, int lay) const { int depth0 = findDepth(det,eta,phi,zside,lay); unsigned int depth = (depth0 > 0) ? (unsigned int)(depth0) : layerGroup(eta-1,lay); return depth; }
32.975338
127
0.565018
bisnupriyasahu
90c3c946ac93b3010bb64efc5456a848f4525c6e
3,826
cpp
C++
src/gazebo_tvc_controller_plugin.cpp
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-05-23T02:52:14.000Z
2021-05-23T02:52:14.000Z
src/gazebo_tvc_controller_plugin.cpp
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-06-15T18:52:15.000Z
2021-06-15T18:52:15.000Z
src/gazebo_tvc_controller_plugin.cpp
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-06-15T03:25:12.000Z
2021-06-15T03:25:12.000Z
/* * Copyright (C) 2012-2015 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 <gazebo_tvc_controller_plugin.h> using namespace gazebo; using namespace std; GZ_REGISTER_MODEL_PLUGIN(TVCControllerPlugin) TVCControllerPlugin::TVCControllerPlugin() {} void TVCControllerPlugin::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { model_ = _model; sdf_ = _sdf; world_ = model_->GetWorld(); // default params namespace_.clear(); if (_sdf->HasElement("robotNamespace")) { namespace_ = _sdf->GetElement("robotNamespace")->Get<std::string>(); } else { gzerr << "[gazebo_tvc_controller] Please specify a robotNamespace.\n"; } node_handle_ = transport::NodePtr(new transport::Node()); node_handle_->Init(namespace_); // TVC pub/sub topics tvc_status_pub_topic_ = "~/" + model_->GetName() + "/tvc_status"; tvc_target_sub_topic_ = "~/" + model_->GetName() + "/tvc_target"; // TVC pub/sub tvc_status_pub_ = node_handle_->Advertise<sensor_msgs::msgs::TVCStatus>( tvc_status_pub_topic_, 10); tvc_target_sub_ = node_handle_->Subscribe<sensor_msgs::msgs::TVCTarget>( tvc_target_sub_topic_, &TVCControllerPlugin::TVCTargetCallback, this); // Get linear actuator joints (from lander.sdf) actuator_1_joint_name = "actuator_1_outer__actuator_1_inner__prismatic"; actuator_2_joint_name = "actuator_2_outer__actuator_2_inner__prismatic"; actuator_1_joint = model_->GetJoint(actuator_1_joint_name); actuator_2_joint = model_->GetJoint(actuator_2_joint_name); } void TVCControllerPlugin::Init() { // plugin update connections.push_back(event::Events::ConnectWorldUpdateBegin( boost::bind(&TVCControllerPlugin::OnUpdate, this))); std::cout << "TVCControllerPlugin::Init" << std::endl; } void TVCControllerPlugin::OnUpdate() { handle_control(); sendTVCStatus(); } void TVCControllerPlugin::handle_control() { // Get current linear actuator joint positions _actuator_current_1 = actuator_1_joint->Position(0); _actuator_current_2 = actuator_2_joint->Position(0); // Get actual forces for linear actuators _actuator_status_1 = -1; _actuator_status_2 = -1; // Save velocity of linear actuators _actuator_velocity_1 = actuator_1_joint->GetVelocity(0); _actuator_velocity_2 = actuator_2_joint->GetVelocity(0); // Apply forces to linear actuators actuator_1_joint->SetForce(0, _actuator_status_1); actuator_2_joint->SetForce(0, _actuator_status_2); } void TVCControllerPlugin::sendTVCStatus() { sensor_msgs::msgs::TVCStatus tvc_status_msg; tvc_status_msg.set_actuator_status_1(_actuator_status_1); tvc_status_msg.set_actuator_target_1(_actuator_target_1); tvc_status_msg.set_actuator_current_1(_actuator_current_1); tvc_status_msg.set_actuator_velocity_1(_actuator_velocity_1); tvc_status_msg.set_actuator_status_2(_actuator_status_2); tvc_status_msg.set_actuator_target_2(_actuator_target_2); tvc_status_msg.set_actuator_current_2(_actuator_current_2); tvc_status_msg.set_actuator_velocity_2(_actuator_velocity_2); tvc_status_pub_->Publish(tvc_status_msg); } void TVCControllerPlugin::TVCTargetCallback(TVCTargetPtr &msg) { _actuator_target_1 = msg->actuator_1_target(); _actuator_target_2 = msg->actuator_2_target(); }
34.160714
75
0.763722
helkebir
90c3fdde22b9dd8b82dbf387daee4d2d0605c073
1,063
cpp
C++
test/doc_snippets/generator_impl.cpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-22T11:29:02.000Z
2020-09-22T11:29:02.000Z
test/doc_snippets/generator_impl.cpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
test/doc_snippets/generator_impl.cpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-29T08:57:13.000Z
2020-09-29T08:57:13.000Z
/** * * This file contains code snippets from the documentation as a reference. * * Please do not change this file unless you change the corresponding snippets * in the documentation as well! * **/ #include <glog/logging.h> #include <gtest/gtest.h> #include <tudocomp/Generator.hpp> using namespace tdc; class MyGenerator : public Generator { public: inline static Meta meta() { Meta m(Generator::type_desc(), "my_generator", "An example generator"); m.param("length").primitive(); m.param("char").primitive('a'); return m; } inline static std::string generate(size_t length, char c) { return std::string(length, c); } using Generator::Generator; inline virtual std::string generate() override { return generate( config().param("length").as_uint(), config().param("char").as_int()); } }; TEST(doc_generator_impl, test) { auto generator = Algorithm::instance<MyGenerator>("length=7, char=64"); ASSERT_EQ("@@@@@@@", generator->generate()); }
24.159091
79
0.64064
421408
90c51dcb4556c69ee42cec1e1aed73b797c57d05
6,394
cc
C++
foomatic_shell/verifier.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
foomatic_shell/verifier.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
foomatic_shell/verifier.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium OS 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 "foomatic_shell/verifier.h" #include <set> #include <base/check.h> #include <base/logging.h> #include <base/no_destructor.h> namespace foomatic_shell { namespace { // A set of allowed environment variables that may be set for executed commands. const std::set<std::string> AllowedVariables() { static const base::NoDestructor<std::set<std::string>> variables({"NOPDF"}); return *variables; } bool HasPrefix(const std::string& str, const std::string& prefix) { if (prefix.size() > str.size()) return false; return (str.compare(0, prefix.size(), prefix) == 0); } } // namespace bool Verifier::VerifyScript(Script* script, int recursion_level) { DCHECK(script != nullptr); if (recursion_level > 5) { message_ = "too many recursive subshell invocations"; return false; } for (auto& pipeline : script->pipelines) { for (auto& segment : pipeline.segments) { // Save the position of the current segment (in case of an error). position_ = Position(segment); // Verify the segment. bool result = false; if (segment.command) { // It is a Command. result = VerifyCommand(segment.command.get()); } else { // It is a Script. DCHECK(segment.script); result = VerifyScript(segment.script.get(), recursion_level + 1); } if (!result) return false; } } return true; } bool Verifier::VerifyCommand(Command* command) { DCHECK(command != nullptr); // Verify variables set for this command. for (auto& var : command->variables_with_values) { if (AllowedVariables().count(var.variable.value) == 0) { message_ = "variable " + var.variable.value + " is not allowed"; return false; } } const std::string& cmd = command->application.value; // The "cat" command is allowed <=> it has no parameters or it has only a // single parameter "-". if (cmd == "cat") { if (command->parameters.empty()) return true; if (command->parameters.size() == 1 && Value(command->parameters.front()) == "-") return true; message_ = "cat: disallowed parameter"; return false; } // The "cut" command is always allowed. if (cmd == "cut") return true; // The "date" command is allowed <=> it has no parameters with prefixes "-s" // or "--set". if (cmd == "date") { for (auto& parameter : command->parameters) { const std::string param = Value(parameter); if (HasPrefix(param, "-s") || HasPrefix(param, "--set")) { message_ = "date: disallowed parameter"; return false; } } return true; } // The "echo" command is always allowed. if (cmd == "echo") return true; // The "gs" command is verified in separate method. if (cmd == "gs") return VerifyGs(command->parameters); // The "pdftops" command used by foomatic-rip is located at // /usr/libexec/cups/filter/pdftops, not /usr/bin/pdftops (a default one). // It takes 5 or 6 parameters. if (cmd == "pdftops") return true; // The "printf" command is always allowed. if (cmd == "printf") return true; // The "sed" command is allowed <=> it has no parameters with prefixes "-i" // or "--in-place". Moreover, the "--sandbox" parameter is added. if (cmd == "sed") { bool value_expected = false; for (auto& parameter : command->parameters) { if (value_expected) { // This string is a value required by the previous parameter. value_expected = false; continue; } const std::string param = Value(parameter); // We do not care about command line parameters shorter than two // characters or not started with '-'. if (param.size() < 2 || param[0] != '-') { continue; } // If the parameter begins with '--' there is only one case to check. if (param[1] == '-') { if (HasPrefix(param, "--in-place")) { message_ = "sed: disallowed parameter"; return false; } continue; } // The parameter begins with single '-'. It may contain several options // glued together. for (size_t i = 1; i < param.size(); ++i) { if (param[i] == 'i') { message_ = "sed: disallowed parameter"; return false; } if (param[i] == 'e' || param[i] == 'f') { // These options require a value. If it is the last character of // the parameter the value is provided in the next parameter. // Otherwise, the remaining part of the parameter is the value. value_expected = (i == param.size() - 1); break; } } } if (value_expected) { message_ = "sed: the last parameter has missing value"; return false; } Token token; token.type = Token::Type::kNativeString; token.value = "--sandbox"; token.begin = token.end = command->application.end; const StringAtom string_atom = {{token}}; command->parameters.push_back(string_atom); return true; } // All other commands are disallowed. message_ = "disallowed command: " + command->application.value; return false; } // Parameters “-dSAFER” and “-sOutputFile=-” must be present. // No other “-sOutputFile=” parameters are allowed. // Parameters “-dNOSAFER” and “-dALLOWPSTRANSPARENCY” are disallowed. bool Verifier::VerifyGs(const std::vector<StringAtom>& parameters) { bool safer = false; bool output_file = false; for (auto& parameter : parameters) { const std::string param = Value(parameter); if (param == "-dPARANOIDSAFER" || param == "-dSAFER") { safer = true; continue; } if (param == "-sOutputFile=-" || param == "-sOutputFile=%stdout") { output_file = true; continue; } if (HasPrefix(param, "-sOutputFile=") || param == "-dNOSAFER" || param == "-dALLOWPSTRANSPARENCY") { message_ = "gs: disallowed parameter"; return false; } } if (!safer) { message_ = "gs: the parameter -dSAFER is missing"; return false; } if (!output_file) { message_ = "gs: the parameter -sOutputFile=- is missing"; return false; } return true; } } // namespace foomatic_shell
30.303318
80
0.614326
Toromino
90c95d4e903ce6c6c8f7cf6a77ddc622197b6464
2,891
cc
C++
src/gui.cc
daeyun/Scry
f4952ce39c6960266b022600445583f0a12858c3
[ "BSD-2-Clause" ]
2
2015-02-02T20:35:13.000Z
2017-10-12T08:04:09.000Z
src/gui.cc
daeyun/Scry
f4952ce39c6960266b022600445583f0a12858c3
[ "BSD-2-Clause" ]
null
null
null
src/gui.cc
daeyun/Scry
f4952ce39c6960266b022600445583f0a12858c3
[ "BSD-2-Clause" ]
null
null
null
/** * @file gui.cc * @author Daeyun Shin <daeyun@dshin.org> * @version 0.1 * @date 2015-01-02 * @copyright librender is free software released under the BSD 2-Clause * license. */ #include "gui.h" #define GLM_FORCE_RADIANS #include <thread> #include <condition_variable> #include <glm/gtx/string_cast.hpp> #include "config.h" namespace librender { namespace gui { RenderParams* render_params; /** * @brief Create a GLFW window. Invisible if width or height is 0. * @param width Window width in pixels. * @param height Window height in pixels. * @param title Title of the window. * @return Pointer to the created GLFW window. */ GLFWwindow* CreateWindow(int width, int height, const std::string& title, const RenderParams& render_params) { if (!glfwInit()) throw std::runtime_error("Failed to initialize GLFW"); bool is_visible = true; if (width == 0 || height == 0) { is_visible = false; height = width = 1; } // Antialiasing glfwWindowHint(GLFW_SAMPLES, render_params.num_msaa_samples); // OpenGL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); if (!is_visible) glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // For OS X glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Open a window and create its OpenGL context. GLFWwindow* window = glfwCreateWindow(width, height, title.c_str(), NULL, NULL); if (window == NULL) { glfwTerminate(); throw std::runtime_error("Failed to open GLFW window."); } if (is_visible) InitWindowControls(window); glfwMakeContextCurrent(window); return window; } void InitWindowControls(GLFWwindow* window) { glfwSetKeyCallback(window, KeyEventHandler); } void KeyEventHandler(GLFWwindow* window, int key, int scancode, int action, int mods) { float delta = librender::config::window_control_speed * std::sqrt(render_params->r) * 0.07; if (action & (GLFW_PRESS | GLFW_REPEAT)) switch (key) { case GLFW_KEY_UP: if (mods & GLFW_MOD_SHIFT) render_params->r += delta; else render_params->el += delta; break; case GLFW_KEY_DOWN: if (mods & GLFW_MOD_SHIFT) render_params->r -= delta; else render_params->el -= delta; break; case GLFW_KEY_LEFT: if (mods & GLFW_MOD_SHIFT) render_params->up_angle -= delta * 20; else render_params->az -= delta; break; case GLFW_KEY_RIGHT: if (mods & GLFW_MOD_SHIFT) render_params->up_angle += delta * 20; else render_params->az += delta; break; case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, GL_TRUE); default: return; } } } }
26.281818
75
0.655828
daeyun
90c960f5cbd3f304875008e54a910ee3694808a3
4,061
cpp
C++
src/entities/Alien.cpp
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
src/entities/Alien.cpp
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
src/entities/Alien.cpp
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
#include "entities.h" #include <SFML/Graphics.hpp> #include <memory> #include <vector> #include <iostream> using namespace std; Alien::Alien(int max_LP, int xPos, int yPos, int speed, int group_number, int targetCheckArea, int threatfulTargetCheckArea) : Fighter(max_LP, xPos, yPos, speed, targetCheckArea, threatfulTargetCheckArea), group_number(group_number), hasAggressiveBehavior(threatfulTargetCheckArea!=-1) { } //inherited functions void Alien::on_Notify(Component* subject, Event event) { } void Alien::_init() { Entity::state = SEARCH; if(!texture.loadFromFile("data/entities/alien.png")) { if(!texture.loadFromFile("../data/entities/alien.png")) { std::cout << "erreur" << '\n'; } } sprite.setTexture(texture); sprite.setTextureRect(sf::IntRect(0,0,32,32)); } int Alien::stateValue() { int value; switch (Entity::state) { case SEARCH: value = 0; break; case OFFENSIVE: value = 1; break; default: value = -1; } return value; } std::string Alien::getStateS() { std::string the_string; switch (state) { case SEARCH: the_string = "SEARCH"; break; case OFFENSIVE: the_string = "OFFENSIVE"; break; default: the_string = "ERROR"; } the_string += " : " + std::to_string(targets.size()); return the_string; } void Alien::check() { checkTargets(); if(targets.empty()) state = SEARCH; else state = OFFENSIVE; } void Alien::action() { switch(state) { case SEARCH: { if(path.empty()) notify(this, E_GET_RANDOM_PATH); move(); break; } case OFFENSIVE: { shared_ptr<Alien> t = dynamic_pointer_cast<Alien>(getTopTarget()); if(t != nullptr) std::cout << "coucou je cible un alien" << '\n'; else std::cout << "coucou je cible PAS un alien" << '\n'; std::cout << "ma cible est déclarée" << '\n'; offensive_action(); break; } default: { Entity::state = SEARCH; } } } void Alien::die() { std::cout << "An alien just died at (" << Entity::pos.x << "," << Entity::pos.y << ")" << '\n'; } void Alien::answer_radar(std::shared_ptr<Entity> e) { if(!isDead()) { shared_ptr<Entity> me = std::dynamic_pointer_cast<Entity>(Observer::shared_from_this()); e->add(false,me); } } void Alien::increaseThreat(shared_ptr<Entity> target, int threatIncrease) { if(isTargetable(target)) { super::increaseThreat(target, threatIncrease); if(targets.empty()) Entity::state = SEARCH; else Entity::state = OFFENSIVE; } } void Alien::attack(shared_ptr<Entity> target) { if(isTargetable(target)) { target->takeDamage(2); if (target->isDead()) path.clear(); } } void Alien::checkTargets() { Fighter::checkTargets(); if(hasAggressiveBehavior) { notify(this, E_LF_ROV); for(int i=0; i<rov.size(); i++) { if(getDistanceTo(rov[i])<=targetCheckArea) { increaseThreat(rov[i], 2); } } rov.clear(); notify(this, E_LF_AL); for(int i=0; i<al.size(); i++) { if(getDistanceTo(al[i])<=targetCheckArea) { if(isTargetable(al[i])) increaseThreat(al[i], 1); } } al.clear(); } } bool Alien::isTargetable(shared_ptr<Entity> target) { shared_ptr<Alien> t = dynamic_pointer_cast<Alien>(target); if(t!=nullptr && (id==t->getID() || t->getGroup()==group_number)) return false; return true; } int Alien::getGroup() { return group_number; } std::string Alien::tostring() { return "alien"; }
20.004926
285
0.539276
Nyarlana
90c9af5478fa0de2005b9fd8e3485d687465eebd
3,017
hpp
C++
include/MEL/Math/Filter.hpp
mahilab/MEL
b877b2ed9cd265b1ee3c1cc623a339ec1dc73185
[ "Zlib" ]
6
2018-09-14T05:07:03.000Z
2021-09-30T17:15:11.000Z
include/MEL/Math/Filter.hpp
mahilab/MEL
b877b2ed9cd265b1ee3c1cc623a339ec1dc73185
[ "Zlib" ]
null
null
null
include/MEL/Math/Filter.hpp
mahilab/MEL
b877b2ed9cd265b1ee3c1cc623a339ec1dc73185
[ "Zlib" ]
3
2018-09-20T00:58:31.000Z
2022-02-09T06:02:56.000Z
// MIT License // // MEL - Mechatronics Engine & Library // Copyright (c) 2019 Mechatronics and Haptic Interfaces Lab - Rice University // // 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. // // Author(s): Craig McDonald (craig.g.mcdonald@gmail.com) #pragma once #include <MEL/Math/Process.hpp> #include <vector> namespace mel { //============================================================================== // CLASS DECLARATION //============================================================================== class Filter : public Process { public: /// Construct Filter from transfer function coefficients Filter(const std::vector<double>& b, const std::vector<double>& a, uint32 seeding = 0); /// Applies the filter operation for one time step double update(const double x, const Time& current_time = Time::Zero) override; /// Returns the filtered value since the last update double get_value() const; /// Sets the internal states s_ to all be zero void reset() override; /// Returns the Filter numerator coefficients const std::vector<double>& get_b() const; /// Returns the Filter denominator coefficients const std::vector<double>& get_a() const; /// Set the Filter seeding void set_seeding(uint32 seeding); /// Sets the Filter coefficients void set_coefficients(const std::vector<double>& b, const std::vector<double>& a); protected: /// Construct empty Filter of order n Filter(std::size_t n, uint32 seeding); private: /// Direct form II transposed filter implementation double dir_form_ii_t(const double x); /// Calls the Filter multiple times on the initial value to avoid startup /// transients void seed(const double x, const uint32 iterations); private: double value_; ///< the filtered value std::size_t n_; ///< filter order std::vector<double> b_; ///< numerator coefficients std::vector<double> a_; ///< denominator coefficients std::vector<double> s_; ///< internal memory bool has_seeding_; ///< indicates whether or not to call seed on first update bool first_update_; ///< indicates first update upon reset bool will_filter_; ///< will the coefficients actually filter (i.e a and b are not both {1,0})? uint32 seed_count_; ///< number of iterations to call on update upon seeding }; } // namespace mel
35.916667
105
0.649321
mahilab
90cd0bfec0988fa652ac00f573ce55d68f758b16
1,396
cc
C++
src/gfx.cc
JesseMaurais/SDL2_lua
cb8dba41c4030267dd88f4d376123d2a71d5735f
[ "Zlib" ]
null
null
null
src/gfx.cc
JesseMaurais/SDL2_lua
cb8dba41c4030267dd88f4d376123d2a71d5735f
[ "Zlib" ]
null
null
null
src/gfx.cc
JesseMaurais/SDL2_lua
cb8dba41c4030267dd88f4d376123d2a71d5735f
[ "Zlib" ]
null
null
null
#include <lux/lux.hpp> #include <SDL2/SDL.h> #include <SDL2/SDL2_gfxPrimitives.h> #include "Common.h" extern "C" int luaopen_SDL2_gfx(lua_State *state) { if (!luaL_getmetatable(state, SDL_METATABLE)) { return luaL_error(state, SDL_REQUIRED); } luaL_Reg regs [] = { {"Pixel", lux_cast(pixelRGBA)}, {"HLine", lux_cast(hlineRGBA)}, {"VLine", lux_cast(vlineRGBA)}, {"Rectangle", lux_cast(rectangleRGBA)}, {"RoundedRectangle", lux_cast(roundedRectangleRGBA)}, {"Box", lux_cast(boxRGBA)}, {"RoundedBox", lux_cast(roundedBoxRGBA)}, {"Line", lux_cast(lineRGBA)}, {"AALine", lux_cast(aalineRGBA)}, {"ThickLine", lux_cast(thickLineRGBA)}, {"Circle", lux_cast(circleRGBA)}, {"Arc", lux_cast(arcRGBA)}, {"AACircle", lux_cast(aacircleRGBA)}, {"FilledCircle", lux_cast(filledCircleRGBA)}, {"Ellipse", lux_cast(ellipseRGBA)}, {"AAEllipse", lux_cast(aaellipseRGBA)}, {"FilledEllipse", lux_cast(filledEllipseRGBA)}, {"Pie", lux_cast(pieRGBA)}, {"FilledPie", lux_cast(filledPieRGBA)}, {"Trigon", lux_cast(trigonRGBA)}, {"AATrigon", lux_cast(aatrigonRGBA)}, {"FilledTrigon", lux_cast(filledTrigonRGBA)}, {"Polygon", lux_cast(polygonRGBA)}, {"AAPolygon", lux_cast(aapolygonRGBA)}, {"FilledPolygon", lux_cast(filledPolygonRGBA)}, {"TexturedPolygon", lux_cast(texturedPolygon)}, {"Bezier", lux_cast(bezierRGBA)}, {nullptr, nullptr} }; luaL_setfuncs(state, regs, 0); return 1; }
29.702128
54
0.714183
JesseMaurais
90cd969c3bccb788fb88f494b57862ba35d7b3e9
413
cpp
C++
src/forthy2/ops/stack.cpp
codr7/forthy2
36464f548cf092bc03f580df87f66f1e71cf4dee
[ "MIT" ]
53
2019-10-20T00:56:59.000Z
2021-02-18T20:30:16.000Z
src/forthy2/ops/stack.cpp
codr7/forthy2
36464f548cf092bc03f580df87f66f1e71cf4dee
[ "MIT" ]
2
2019-10-28T11:02:10.000Z
2020-06-28T20:10:22.000Z
src/forthy2/ops/stack.cpp
codr7/forthy2
36464f548cf092bc03f580df87f66f1e71cf4dee
[ "MIT" ]
6
2019-10-28T10:55:59.000Z
2021-02-18T20:30:18.000Z
#include "forthy2/cx.hpp" #include "forthy2/ops/stack.hpp" #include "forthy2/form.hpp" #include "forthy2/val.hpp" namespace forthy2 { StackOp::StackOp(Form &form, Node<Op> &prev): Op(form, prev), end_pc(nullptr) {} void StackOp::dealloc(Cx &cx) { Op::dealloc(cx); cx.stack_op.put(*this); } void StackOp::dump(ostream &out) { out << "stack " << dynamic_cast<StackForm &>(form).body; } }
22.944444
82
0.64891
codr7
90ce6c2d79ea7eaf5e85de11ba343ca76d493be0
974
cpp
C++
codeforces/B - Polycarp Training/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/B - Polycarp Training/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/B - Polycarp Training/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: * kzvd4729 created: May/14/2019 20:45 * solution_verdict: Accepted language: GNU C++14 * run_time: 155 ms memory_used: 10400 KB * problem: https://codeforces.com/contest/1165/problem/B ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n;multiset<int>st; for(int i=1;i<=n;i++) { int x;cin>>x;st.insert(x); } int ans=1; while(st.size()) { int x=*st.begin(); if(x>=ans) ans++; st.erase(st.find(x)); } cout<<ans-1<<endl; return 0; }
32.466667
111
0.38501
kzvd4729
90d2faa0bb2d7e3ff2ed3d9a521a04e8f571950d
2,793
hpp
C++
src/reir/exec/compiler.hpp
large-scale-oltp-team/reir
427db5f24e15f22cd2a4f4a716caf9392dae1d9b
[ "Apache-2.0" ]
1
2020-03-04T10:57:14.000Z
2020-03-04T10:57:14.000Z
src/reir/exec/compiler.hpp
large-scale-oltp-team/reir
427db5f24e15f22cd2a4f4a716caf9392dae1d9b
[ "Apache-2.0" ]
3
2018-11-02T07:47:26.000Z
2018-11-05T09:06:54.000Z
src/reir/exec/compiler.hpp
large-scale-oltp-team/reir
427db5f24e15f22cd2a4f4a716caf9392dae1d9b
[ "Apache-2.0" ]
null
null
null
#ifndef REIR_COMPILER_HPP_ #define REIR_COMPILER_HPP_ #include <cassert> #include <unordered_map> #include <iostream> #include <llvm/ADT/STLExtras.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/JITSymbol.h> #include <llvm/ExecutionEngine/RTDyldMemoryManager.h> #include <llvm/ExecutionEngine/RuntimeDyld.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h> #include <llvm/ExecutionEngine/Orc/CompileUtils.h> #include <llvm/ExecutionEngine/Orc/IRCompileLayer.h> #include <llvm/ExecutionEngine/Orc/IRTransformLayer.h> #include <llvm/ExecutionEngine/Orc/LambdaResolver.h> #include <llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h> #include <llvm/IR/DataLayout.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/IR/Mangler.h> #include <llvm/Support/DynamicLibrary.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Transforms/Scalar.h> #include <llvm/Transforms/Scalar/GVN.h> #include <llvm/IR/IRBuilder.h> #include "tuple.hpp" #include "ast_node.hpp" namespace llvm { class TargetMachine; class Function; class Module; } // namespace llvm namespace reir { namespace node { class Node; } class MetaData; class DBInterface; class CompilerContext; class Compiler { void init_functions(CompilerContext& ctx); using OptimizeFunction = std::function<std::shared_ptr<llvm::Module>(std::shared_ptr<llvm::Module>)>; std::unique_ptr<llvm::TargetMachine> target_machine_; llvm::DataLayout data_layout_; llvm::orc::RTDyldObjectLinkingLayer obj_layer_; std::unique_ptr<llvm::orc::JITCompileCallbackManager> CompileCallbackManager; llvm::orc::IRCompileLayer<decltype(obj_layer_), llvm::orc::SimpleCompiler> compile_layer_; llvm::orc::IRTransformLayer<decltype(compile_layer_), OptimizeFunction> optimize_layer_; llvm::orc::CompileOnDemandLayer<decltype(optimize_layer_)> CODLayer; public: using ModuleHandle = decltype(CODLayer)::ModuleHandleT; public: Compiler(); typedef bool(*exec_func)(node::Node*); void compile_and_exec(DBInterface& dbi, MetaData& md, node::Node* ast); void compile_and_exec(CompilerContext& ctx, DBInterface& dbi, MetaData& md, node::Node* ast); llvm::TargetMachine* get_target_machine() { return target_machine_.get(); } ModuleHandle add_module(std::unique_ptr<llvm::Module> m); llvm::JITSymbol find_symbol(const std::string& name); ~Compiler() = default; private: void compile(CompilerContext& ctx, DBInterface& dbi, MetaData& md, node::Node* ast); std::shared_ptr<llvm::Module> optimize_module(std::shared_ptr<llvm::Module> M); public: // it should be private and friend classess // llvm members }; } // namespace reir #endif // REIR_COMPILER_HPP_
30.358696
95
0.775152
large-scale-oltp-team
90d3e1f4e601605322446d84dd7cec2e743544d2
4,706
cpp
C++
src/ch8/frame_buffer.test.cpp
notskm/chip8
9e70088acd079fc6f2ed2545fb13ee6160dd12aa
[ "MIT" ]
null
null
null
src/ch8/frame_buffer.test.cpp
notskm/chip8
9e70088acd079fc6f2ed2545fb13ee6160dd12aa
[ "MIT" ]
null
null
null
src/ch8/frame_buffer.test.cpp
notskm/chip8
9e70088acd079fc6f2ed2545fb13ee6160dd12aa
[ "MIT" ]
null
null
null
#include "ch8/frame_buffer.hpp" #include <array> #include <catch2/catch.hpp> #include <type_traits> #include <utility> TEST_CASE("frame_buffer constructor initializes each pixel to 0, 0, 0, 0") { const auto buffer = ch8::frame_buffer<64, 32>{}; REQUIRE(buffer.data() == std::array<std::uint8_t, 64 * 32 * 4>{}); } TEST_CASE("frame_buffer<64, 32>::width returns 64") { const auto buffer = ch8::frame_buffer<64, 32>{}; REQUIRE(buffer.width() == 64); } TEST_CASE("frame_buffer<83, 21>::width returns 83") { const auto buffer = ch8::frame_buffer<83, 21>{}; REQUIRE(buffer.width() == 83); } TEST_CASE("frame_buffer<64, 32>::height returns 32") { const auto buffer = ch8::frame_buffer<64, 32>{}; REQUIRE(buffer.height() == 32); } TEST_CASE("frame_buffer<83, 21>::height returns 21") { const auto buffer = ch8::frame_buffer<83, 21>{}; REQUIRE(buffer.height() == 21); } TEST_CASE( "Modifying the array returned by frame_buffer::data modifies the framebuffer") { auto buffer = ch8::frame_buffer<2, 4>{}; buffer.data().front() = 58; REQUIRE(buffer.data().front() == 58); } TEST_CASE("frame_buffer::data returns a const ref when frame_buffer is const") { using buffer = ch8::frame_buffer<8, 4>; using result = decltype(std::declval<const buffer>().data()); using const_data_ref = const std::array<std::uint8_t, 8 * 4 * 4>&; STATIC_REQUIRE(std::is_same_v<result, const_data_ref>); } TEST_CASE("frame_buffer::pixel returns the color of the pixel at (10, 30)") { constexpr auto x = std::size_t{10}; constexpr auto y = std::size_t{29}; constexpr auto color = ch8::color{26, 105, 46, 234}; auto buffer = ch8::frame_buffer<28, 30>{}; auto& data = buffer.data(); data.at(y * buffer.width() * 4 + x * 4 + 0) = color.r; data.at(y * buffer.width() * 4 + x * 4 + 1) = color.g; data.at(y * buffer.width() * 4 + x * 4 + 2) = color.b; data.at(y * buffer.width() * 4 + x * 4 + 3) = color.a; REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE("frame_buffer::pixel returns the color of the pixel at (50, 20)") { constexpr auto x = std::size_t{50}; constexpr auto y = std::size_t{20}; constexpr auto color = ch8::color{12, 84, 27, 85}; auto buffer = ch8::frame_buffer<70, 35>{}; auto& data = buffer.data(); data.at(y * buffer.width() * 4 + x * 4 + 0) = color.r; data.at(y * buffer.width() * 4 + x * 4 + 1) = color.g; data.at(y * buffer.width() * 4 + x * 4 + 2) = color.b; data.at(y * buffer.width() * 4 + x * 4 + 3) = color.a; REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE("frame_buffer::pixel sets the color of the pixel at (39, 13)") { constexpr auto x = std::size_t{50}; constexpr auto y = std::size_t{20}; constexpr auto color = ch8::color{63, 26, 19, 157}; auto buffer = ch8::frame_buffer<83, 27>{}; buffer.pixel(x, y, color); REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE("frame_buffer::pixel sets the color of the pixel at (3, 67)") { constexpr auto x = std::size_t{3}; constexpr auto y = std::size_t{67}; constexpr auto color = ch8::color{83, 27, 55, 29}; auto buffer = ch8::frame_buffer<38, 74>{}; buffer.pixel(x, y, color); REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE( "frame_buffer::clear sets each pixel to transparent when no color is provided") { auto buffer = ch8::frame_buffer<83, 21>{}; buffer.data().fill(std::uint8_t{83}); buffer.clear(); for (auto x = std::size_t{0}; x < buffer.width(); ++x) { for (auto y = std::size_t{0}; y < buffer.height(); ++y) { REQUIRE(buffer.pixel(x, y) == ch8::color{0, 0, 0, 0}); } } } TEST_CASE("frame_buffer::clear sets each pixel to the color provided") { constexpr auto color = ch8::color{73, 28, 95, 23}; auto buffer = ch8::frame_buffer<83, 21>{}; buffer.data().fill(std::uint8_t{83}); buffer.clear(color); for (auto x = std::size_t{0}; x < buffer.width(); ++x) { for (auto y = std::size_t{0}; y < buffer.height(); ++y) { REQUIRE(buffer.pixel(x, y) == color); } } } TEST_CASE("color{103, 39, 38, 255} == color{103, 39, 38, 255}") { REQUIRE(ch8::color{103, 39, 38, 255} == ch8::color{103, 39, 38, 255}); } TEST_CASE("color{83, 67, 201, 143} == color{83, 67, 201, 143}") { REQUIRE(ch8::color{83, 67, 201, 143} == ch8::color{83, 67, 201, 143}); } TEST_CASE("color{103, 39, 38, 255} != color{38, 165, 44, 221}") { REQUIRE(ch8::color{103, 39, 38, 255} != ch8::color{38, 165, 44, 221}); } TEST_CASE("color{83, 67, 201, 143} != color{84, 32, 65, 93}") { REQUIRE(ch8::color{83, 67, 201, 143} != ch8::color{84, 32, 65, 93}); }
29.4125
83
0.60476
notskm
90d3eff83f7fdf30e395fa8d07742a090409c167
9,346
cpp
C++
Siv3D/src/Siv3D/Monitor/SivMonitor.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Monitor/SivMonitor.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Monitor/SivMonitor.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Monitor.hpp> # if defined(SIV3D_TARGET_WINDOWS) # include <Siv3D/Windows.hpp> # include "../Siv3DEngine.hpp" # include "../Window/IWindow.hpp" namespace s3d { namespace detail { // チェック用デバイス名とモニタハンドル using MonitorCheck = std::pair<const String, HMONITOR>; static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM userData) { MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(monitorInfo); ::GetMonitorInfoW(hMonitor, &monitorInfo); Monitor* monitor = (Monitor*)userData; if (monitor->displayDeviceName.toWstr() == monitorInfo.szDevice) { monitor->displayRect.x = monitorInfo.rcMonitor.left; monitor->displayRect.y = monitorInfo.rcMonitor.top; monitor->displayRect.w = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left; monitor->displayRect.h = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top; monitor->workArea.x = monitorInfo.rcWork.left; monitor->workArea.y = monitorInfo.rcWork.top; monitor->workArea.w = monitorInfo.rcWork.right - monitorInfo.rcWork.left; monitor->workArea.h = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; return false; } return true; } static BOOL CALLBACK MonitorCheckProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM userData) { MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(monitorInfo); ::GetMonitorInfoW(hMonitor, &monitorInfo); MonitorCheck* monitor = (MonitorCheck*)userData; if (monitor->first.toWstr() == monitorInfo.szDevice) { monitor->second = hMonitor; return false; } return true; } } namespace System { Array<Monitor> EnumerateActiveMonitors() { Array<Monitor> monitors; DISPLAY_DEVICE displayDevice; displayDevice.cb = sizeof(displayDevice); // デスクトップとして割り当てられている仮想ディスプレイを検索 for (int32 deviceIndex = 0; ::EnumDisplayDevicesW(0, deviceIndex, &displayDevice, 0); ++deviceIndex) { if (displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) { DISPLAY_DEVICE monitor; ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); // デスクトップとして使われているモニターの一覧を取得 for (int32 monitorIndex = 0; ::EnumDisplayDevicesW(displayDevice.DeviceName, monitorIndex, &monitor, 0); ++monitorIndex) { if ((monitor.StateFlags & DISPLAY_DEVICE_ACTIVE) && !(monitor.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER)) { Monitor monitorInfo; monitorInfo.displayDeviceName = Unicode::FromWString(displayDevice.DeviceName); // モニターの配置とサイズを取得 ::EnumDisplayMonitors(nullptr, nullptr, detail::MonitorEnumProc, (LPARAM)&monitorInfo); // その他の情報を取得 monitorInfo.id = Unicode::FromWString(monitor.DeviceID); monitorInfo.name = Unicode::FromWString(monitor.DeviceString); monitorInfo.isPrimary = !!(displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE); monitors.push_back(monitorInfo); } ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); } } ZeroMemory(&displayDevice, sizeof(displayDevice)); displayDevice.cb = sizeof(displayDevice); } return monitors; } size_t GetCurrentMonitorIndex() { const HMONITOR currentMonitor = ::MonitorFromWindow(Siv3DEngine::GetWindow()->getHandle(), MONITOR_DEFAULTTOPRIMARY); size_t index = 0; DISPLAY_DEVICE displayDevice; displayDevice.cb = sizeof(displayDevice); // デスクトップとして割り当てられている仮想デスクトップを検索 for (int32 deviceIndex = 0; ::EnumDisplayDevicesW(0, deviceIndex, &displayDevice, 0); ++deviceIndex) { if (displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) { DISPLAY_DEVICE monitor; ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); // デスクトップとして使われているモニターの一覧を取得 for (int32 monitorIndex = 0; ::EnumDisplayDevicesW(displayDevice.DeviceName, monitorIndex, &monitor, 0); ++monitorIndex) { if ((monitor.StateFlags & DISPLAY_DEVICE_ACTIVE) && !(monitor.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER)) { detail::MonitorCheck desc = { Unicode::FromWString(displayDevice.DeviceName), nullptr }; // モニターのハンドルを取得 ::EnumDisplayMonitors(nullptr, nullptr, detail::MonitorCheckProc, (LPARAM)&desc); if (desc.second == currentMonitor) { return index; } ++index; } ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); } } ZeroMemory(&displayDevice, sizeof(displayDevice)); displayDevice.cb = sizeof(displayDevice); } return 0; } } } # elif defined(SIV3D_TARGET_MACOS) # include "../../ThirdParty/GLFW/include/GLFW/glfw3.h" # include <Siv3D/Window.hpp> namespace s3d { namespace System { Array<Monitor> EnumerateActiveMonitors() { Array<Monitor> results; int32 numMonitors; GLFWmonitor** monitors = ::glfwGetMonitors(&numMonitors); for (int32 i = 0; i < numMonitors; ++i) { GLFWmonitor* monitor = monitors[i]; Monitor result; result.name = Unicode::Widen(::glfwGetMonitorName(monitor)); uint32 displayID, unitNumber; int32 xPos, yPos, width, height; int32 wx, wy, ww, wh; glfwGetMonitorInfo_Siv3D(monitor, &displayID, &unitNumber, &xPos, &yPos, &width, &height, &wx, &wy, &ww, &wh); result.id = Format(displayID); result.displayDeviceName = Format(unitNumber); result.displayRect.x = xPos; result.displayRect.y = yPos; result.displayRect.w = width; result.displayRect.h = height; result.workArea.x = wx; result.workArea.y = wy; result.workArea.w = ww; result.workArea.h = wh; result.isPrimary = (i == 0); results.push_back(result); } return results; } size_t GetCurrentMonitorIndex() { const auto& state = Window::GetState(); const Point pos = state.pos; const Size size = state.windowSize; const auto monitors = EnumerateActiveMonitors(); int32 bestoverlap = 0; size_t bestIndex = 0; for (size_t i = 0; i < monitors.size(); ++i) { const auto& monitor = monitors[i]; const Point mPos = monitor.displayRect.pos; const Size mSize = monitor.displayRect.size; const int32 overlap = std::max(0, std::min(pos.x + size.x, mPos.x + mSize.x) - std::max(pos.x, mPos.x)) * std::max(0, std::min(pos.y + size.y, mPos.y + mSize.y) - std::max(pos.y, mPos.y)); if (bestoverlap < overlap) { bestoverlap = overlap; bestIndex = i; } } return bestIndex; } } } # elif defined(SIV3D_TARGET_LINUX) # include "../../ThirdParty/GLFW/include/GLFW/glfw3.h" # include <Siv3D/Window.hpp> namespace s3d { namespace System { Array<Monitor> EnumerateActiveMonitors() { Array<Monitor> results; int32 numMonitors; GLFWmonitor** monitors = ::glfwGetMonitors(&numMonitors); for (int32 i = 0; i < numMonitors; ++i) { GLFWmonitor* monitor = monitors[i]; Monitor result; result.name = Unicode::Widen(::glfwGetMonitorName(monitor)); uint32 displayID; int32 xPos, yPos, width, height; int32 wx, wy, ww, wh; char* name = nullptr; glfwGetMonitorInfo_Siv3D(monitor, &displayID, &name, &xPos, &yPos, &width, &height, &wx, &wy, &ww, &wh); result.id = Format(displayID); result.displayDeviceName = Unicode::Widen(name); result.displayRect.x = xPos; result.displayRect.y = yPos; result.displayRect.w = width; result.displayRect.h = height; result.workArea.x = wx; result.workArea.y = wy; result.workArea.w = ww; result.workArea.h = wh; result.isPrimary = (i == 0); results.push_back(result); ::free(name); // free monitor name buffer. } return results; } size_t GetCurrentMonitorIndex() { const auto& state = Window::GetState(); const Point pos = state.pos; const Size size = state.windowSize; const auto monitors = EnumerateActiveMonitors(); int32 bestoverlap = 0; size_t bestIndex = 0; for (size_t i = 0; i < monitors.size(); ++i) { const auto& monitor = monitors[i]; const Point mPos = monitor.displayRect.pos; const Size mSize = monitor.displayRect.size; const int32 overlap = std::max(0, std::min(pos.x + size.x, mPos.x + mSize.x) - std::max(pos.x, mPos.x)) * std::max(0, std::min(pos.y + size.y, mPos.y + mSize.y) - std::max(pos.y, mPos.y)); if (bestoverlap < overlap) { bestoverlap = overlap; bestIndex = i; } } return bestIndex; } } } # endif namespace s3d { void Formatter(FormatData& formatData, const Monitor& value) { String output; output += U"Name: " + value.name + U"\n"; output += U"ID: " + value.id + U"\n"; output += U"DisplayDeviceName: " + value.displayDeviceName + U"\n"; output += U"DisplayRect: " + Format(value.displayRect) + U"\n"; output += U"WorkArea: " + Format(value.workArea) + U"\n"; output += U"Primary: " + Format(value.isPrimary); formatData.string.append(output); } }
27.168605
125
0.656645
Fuyutsubaki
90daddb9d6e0c63b59a9202895e5b6f94dd48e7c
2,101
hpp
C++
cpp/visualmesh/network_structure.hpp
wongjoel/VisualMesh
98b973c6cd371aab51f2b631f75c9ac820d3b744
[ "MIT" ]
14
2018-06-22T19:46:34.000Z
2022-02-02T15:22:39.000Z
cpp/visualmesh/network_structure.hpp
wongjoel/VisualMesh
98b973c6cd371aab51f2b631f75c9ac820d3b744
[ "MIT" ]
2
2020-12-12T04:51:51.000Z
2021-06-28T01:14:42.000Z
cpp/visualmesh/network_structure.hpp
wongjoel/VisualMesh
98b973c6cd371aab51f2b631f75c9ac820d3b744
[ "MIT" ]
8
2018-06-11T14:54:45.000Z
2022-02-02T15:22:50.000Z
/* * Copyright (C) 2017-2020 Trent Houliston <trent@houliston.me> * * 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. */ #ifndef VISUALMESH_NETWORKSTRUCTURE_HPP #define VISUALMESH_NETWORKSTRUCTURE_HPP #include <vector> namespace visualmesh { /// Weights are a matrix (vector of vectors) template <typename Scalar> using Weights = std::vector<std::vector<Scalar>>; /// Biases are a vector template <typename Scalar> using Biases = std::vector<Scalar>; enum ActivationFunction { SELU, RELU, SOFTMAX, TANH, }; /// A layer is made up of weights biases and activation function template <typename Scalar> struct Layer { Weights<Scalar> weights; Biases<Scalar> biases; ActivationFunction activation; }; /// A convolutional layer is made up of a list of network layers template <typename Scalar> using ConvolutionalGroup = std::vector<Layer<Scalar>>; /// A network is a list of convolutional layers template <typename Scalar> using NetworkStructure = std::vector<ConvolutionalGroup<Scalar>>; } // namespace visualmesh #endif // VISUALMESH_NETWORKSTRUCTURE_HPP
36.859649
120
0.763922
wongjoel