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
98ff08ad62b4630adc74e7145b7519a588623505
3,155
cpp
C++
src/common/snippets/tests/src/pass/insert_load_store.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/common/snippets/tests/src/pass/insert_load_store.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/common/snippets/tests/src/pass/insert_load_store.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include "pass/insert_load_store.hpp" #include "common_test_utils/common_utils.hpp" #include <subgraph_lowered.hpp> namespace ov { namespace test { namespace snippets { std::string InsertLoadStoreTests::getTestCaseName(testing::TestParamInfo<insertLoadStoreParams> obj) { std::vector<Shape> inputShapes(3); std::vector<Shape> broadcastShapes(3); std::tie(inputShapes[0], inputShapes[1], inputShapes[2], broadcastShapes[0], broadcastShapes[1], broadcastShapes[2]) = obj.param; std::ostringstream result; for (size_t i = 0; i < inputShapes.size(); i++) result << "IS[" << i << "]=" << CommonTestUtils::vec2str(inputShapes[i]) << "_"; for (size_t i = 0; i < broadcastShapes.size(); i++) result << "BS[" << i << "]=" << CommonTestUtils::vec2str(broadcastShapes[i]) << "_"; return result.str(); } void InsertLoadStoreTests::SetUp() { TransformationTestsF::SetUp(); std::vector<Shape> inputShapes(3); std::vector<Shape> broadcastShapes(3); std::tie(inputShapes[0], inputShapes[1], inputShapes[2], broadcastShapes[0], broadcastShapes[1], broadcastShapes[2]) = this->GetParam(); snippets_function = std::make_shared<EltwiseThreeInputsLoweredFunction>(inputShapes, broadcastShapes); } TEST_P(InsertLoadStoreTests, ThreeInputsEltwise) { auto subgraph = getLoweredSubgraph(snippets_function->getOriginal()); function = subgraph->get_body(); function_ref = snippets_function->getLowered(); } namespace InsertLoadStoreTestsInstantiation { using ov::Shape; std::vector<Shape> inputShapes1{{1, 1, 2, 5, 1}, {1, 4, 1, 5, 1}}; std::vector<Shape> inputShapes2{{1, 1, 2, 5, 1}, {1, 4, 1, 5, 1}, {1, 4, 1, 5, 16}}; Shape exec_domain{1, 4, 2, 5, 16}; Shape emptyShape{}; INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BroadcastLoad, InsertLoadStoreTests, ::testing::Combine( ::testing::Values(exec_domain), ::testing::ValuesIn(inputShapes1), ::testing::ValuesIn(inputShapes1), ::testing::Values(emptyShape), ::testing::Values(exec_domain), ::testing::Values(exec_domain)), InsertLoadStoreTests::getTestCaseName); INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BroadcastMove, InsertLoadStoreTests, ::testing::Combine( ::testing::Values(exec_domain), ::testing::Values(Shape {1, 4, 1, 5, 16}), ::testing::ValuesIn(inputShapes2), ::testing::Values(emptyShape), ::testing::Values(exec_domain), ::testing::Values(exec_domain)), InsertLoadStoreTests::getTestCaseName); } // namespace InsertLoadStoreTestsInstantiation } // namespace snippets } // namespace test } // namespace ov
43.819444
106
0.602536
kurylo
c70026920b9b42ade4db1c9d68a1fba2d951e98f
3,190
cpp
C++
cmdstan/stan/lib/stan_math/test/unit/math/fwd/mat/fun/array_builder_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/fwd/mat/fun/array_builder_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/fwd/mat/fun/array_builder_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/fwd/mat.hpp> #include <gtest/gtest.h> using stan::math::fvar; TEST(AgradFwdMatrixArrayBuilder,fvar_double) { using std::vector; using stan::math::array_builder; EXPECT_EQ(0U, array_builder<fvar<double> >().array().size()); vector<fvar<double> > x = array_builder<fvar<double> >() .add(fvar<double>(1,4)) .add(fvar<double>(3,4)) .add(fvar<double>(2,4)) .array(); EXPECT_EQ(3U,x.size()); EXPECT_FLOAT_EQ(1.0, x[0].val_); EXPECT_FLOAT_EQ(3.0, x[1].val_); EXPECT_FLOAT_EQ(2.0, x[2].val_); EXPECT_FLOAT_EQ(4.0, x[0].d_); EXPECT_FLOAT_EQ(4.0, x[1].d_); EXPECT_FLOAT_EQ(4.0, x[2].d_); vector<vector<fvar<double> > > xx = array_builder<vector<fvar<double> > >() .add(array_builder<fvar<double> >() .add(fvar<double>(1,4)) .add(fvar<double>(2,4)).array()) .add(array_builder<fvar<double> >() .add(fvar<double>(3,4)) .add(fvar<double>(4,4)).array()) .add(array_builder<fvar<double> >() .add(fvar<double>(5,4)) .add(fvar<double>(6,4)).array()) .array(); EXPECT_EQ(3U,xx.size()); for (size_t i = 0; i < 3; ++i) EXPECT_EQ(2U,xx[i].size()); EXPECT_EQ(1,xx[0][0].val_); EXPECT_EQ(2,xx[0][1].val_); EXPECT_EQ(3,xx[1][0].val_); EXPECT_EQ(4,xx[1][1].val_); EXPECT_EQ(5,xx[2][0].val_); EXPECT_EQ(6,xx[2][1].val_); EXPECT_EQ(4,xx[0][0].d_); EXPECT_EQ(4,xx[0][1].d_); EXPECT_EQ(4,xx[1][0].d_); EXPECT_EQ(4,xx[1][1].d_); EXPECT_EQ(4,xx[2][0].d_); EXPECT_EQ(4,xx[2][1].d_); } TEST(AgradFwdMatrixArrayBuilder,fvar_fvar_double) { using std::vector; using stan::math::array_builder; EXPECT_EQ(0U, array_builder<fvar<fvar<double> > >().array().size()); vector<fvar<fvar<double> > > x = array_builder<fvar<fvar<double> > >() .add(fvar<fvar<double> >(1,4)) .add(fvar<fvar<double> >(3,4)) .add(fvar<fvar<double> >(2,4)) .array(); EXPECT_EQ(3U,x.size()); EXPECT_FLOAT_EQ(1.0, x[0].val_.val_); EXPECT_FLOAT_EQ(3.0, x[1].val_.val_); EXPECT_FLOAT_EQ(2.0, x[2].val_.val_); EXPECT_FLOAT_EQ(4.0, x[0].d_.val_); EXPECT_FLOAT_EQ(4.0, x[1].d_.val_); EXPECT_FLOAT_EQ(4.0, x[2].d_.val_); vector<vector<fvar<fvar<double> > > > xx = array_builder<vector<fvar<fvar<double> > > >() .add(array_builder<fvar<fvar<double> > >() .add(fvar<fvar<double> >(1,4)) .add(fvar<fvar<double> >(2,4)).array()) .add(array_builder<fvar<fvar<double> > >() .add(fvar<fvar<double> >(3,4)) .add(fvar<fvar<double> >(4,4)).array()) .add(array_builder<fvar<fvar<double> > >() .add(fvar<fvar<double> >(5,4)) .add(fvar<fvar<double> >(6,4)).array()) .array(); EXPECT_EQ(3U,xx.size()); for (size_t i = 0; i < 3; ++i) EXPECT_EQ(2U,xx[i].size()); EXPECT_EQ(1,xx[0][0].val_.val_); EXPECT_EQ(2,xx[0][1].val_.val_); EXPECT_EQ(3,xx[1][0].val_.val_); EXPECT_EQ(4,xx[1][1].val_.val_); EXPECT_EQ(5,xx[2][0].val_.val_); EXPECT_EQ(6,xx[2][1].val_.val_); EXPECT_EQ(4,xx[0][0].d_.val_); EXPECT_EQ(4,xx[0][1].d_.val_); EXPECT_EQ(4,xx[1][0].d_.val_); EXPECT_EQ(4,xx[1][1].d_.val_); EXPECT_EQ(4,xx[2][0].d_.val_); EXPECT_EQ(4,xx[2][1].d_.val_); }
30.09434
70
0.600627
yizhang-cae
c7009a6717d265862759f97ad4eae6dd772e7109
1,954
hpp
C++
src/para/peak_tolerance.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
8
2018-05-23T14:37:31.000Z
2022-02-04T23:48:38.000Z
src/para/peak_tolerance.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
9
2019-08-31T08:17:45.000Z
2022-02-11T20:58:06.000Z
src/para/peak_tolerance.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
4
2018-04-25T01:39:38.000Z
2020-05-20T19:25:07.000Z
//Copyright (c) 2014 - 2020, The Trustees of Indiana University. // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #ifndef TOPPIC_PARA_PEAK_TOLERANCE_HPP_ #define TOPPIC_PARA_PEAK_TOLERANCE_HPP_ #include <string> #include <memory> #include <vector> #include "common/xml/xml_dom_element.hpp" namespace toppic { class XmlDOMDocument; class PeakTolerance { public: PeakTolerance(double ppo); explicit PeakTolerance(xercesc::DOMElement* element); double compStrictErrorTole(double mass); // consider zero ptm relaxed error double compRelaxErrorTole(double m1, double m2); double getPpo() {return ppo_;} int getIntPpm() {return static_cast<int>(ppo_ * 1000000);} bool isUseMinTolerance() {return use_min_tolerance_;} double getMinTolerance() {return min_tolerance_;} void setPpo(double ppo) {ppo_ = ppo;} void setUseMinTolerance(bool use_min_tolerance) { use_min_tolerance_ = use_min_tolerance;} void setMinTolerance(double min_tolerance) { min_tolerance_ = min_tolerance;} void appendXml(XmlDOMDocument* xml_doc, xercesc::DOMElement* parent); static std::string getXmlElementName() {return "peak_tolerance";} private: double ppo_; /* whether or not use minimum tolerance */ bool use_min_tolerance_ = true; double min_tolerance_ = 0.01; }; typedef std::shared_ptr<PeakTolerance> PeakTolerancePtr; typedef std::vector<PeakTolerancePtr> PeakTolerancePtrVec; } /* namespace toppic */ #endif
27.138889
74
0.759468
toppic-suite
c7078a5b9c0dc68041b4e5bba29763e76c8c7cfc
1,185
cpp
C++
31_Next_Permutation.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
31_Next_Permutation.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
31_Next_Permutation.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
/* 31. Next Permutation Medium Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). The replacement must be in place and use only constant extra memory. Example 1: Input: nums = [1,2,3] Output: [1,3,2] Example 2: Input: nums = [3,2,1] Output: [1,2,3] Example 3: Input: nums = [1,1,5] Output: [1,5,1] Example 4: Input: nums = [1] Output: [1] Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 100 */ class Solution { public: void nextPermutation(vector<int>& nums) { int r=nums.size()-2,l=nums.size()-1; while(r>=0){ if(nums[r]<nums[r+1]){ break; } r--; } if(r<0){ reverse(nums.begin(),nums.end()); }else{ while(l>r){ if(nums[l]>nums[r]){ break; } l--; } swap(nums[l],nums[r]); reverse(nums.begin()+r+1,nums.end()); } } };
17.954545
124
0.521519
AvadheshChamola
c708832b68888328a59ac5320f9a900134857c44
1,295
cpp
C++
Dev/Cpp/Viewer/Graphics/efk.PostEffects.cpp
NumAniCloud/Effekseer
f4547a57eea4c85b55cb8218bf6cac6af6d6dd37
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-11-21T01:34:30.000Z
2020-11-21T01:34:30.000Z
Dev/Cpp/Viewer/Graphics/efk.PostEffects.cpp
NumAniCloud/Effekseer
f4547a57eea4c85b55cb8218bf6cac6af6d6dd37
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Dev/Cpp/Viewer/Graphics/efk.PostEffects.cpp
NumAniCloud/Effekseer
f4547a57eea4c85b55cb8218bf6cac6af6d6dd37
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
#include "efk.PostEffects.h" #ifdef _WIN32 #include "Platform/DX11/efk.PostEffectsDX11.h" #endif #include "Platform/GL/efk.PostEffectsGL.h" namespace efk { BloomEffect* PostEffect::CreateBloom(Graphics* graphics, EffekseerRenderer::Renderer* renderer) { #ifdef _WIN32 if (graphics->GetDeviceType() == DeviceType::DirectX11) { return new BloomEffectDX11(graphics, renderer); } #endif if (graphics->GetDeviceType() == DeviceType::OpenGL) { return new BloomEffectGL(graphics, renderer); } return nullptr; } TonemapEffect* PostEffect::CreateTonemap(Graphics* graphics, EffekseerRenderer::Renderer* renderer) { #ifdef _WIN32 if (graphics->GetDeviceType() == DeviceType::DirectX11) { return new TonemapEffectDX11(graphics, renderer); } #endif if (graphics->GetDeviceType() == DeviceType::OpenGL) { return new TonemapEffectGL(graphics, renderer); } return nullptr; } LinearToSRGBEffect* PostEffect::CreateLinearToSRGB(Graphics* graphics, EffekseerRenderer::Renderer* renderer) { #ifdef _WIN32 if (graphics->GetDeviceType() == DeviceType::DirectX11) { return new LinearToSRGBEffectDX11(graphics, renderer); } #endif if (graphics->GetDeviceType() == DeviceType::OpenGL) { return new LinearToSRGBEffectGL(graphics, renderer); } return nullptr; } } // namespace efk
22.327586
109
0.75444
NumAniCloud
c70896ba3c9b2968b4d834f2e67373f3857eae07
5,917
cc
C++
src/fdb5/rules/Schema.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
5
2020-01-03T10:23:05.000Z
2021-10-21T12:52:47.000Z
src/fdb5/rules/Schema.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
null
null
null
src/fdb5/rules/Schema.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
1
2021-07-08T16:26:06.000Z
2021-07-08T16:26:06.000Z
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include <fstream> #include "fdb5/LibFdb5.h" #include "fdb5/rules/Schema.h" #include "fdb5/rules/Rule.h" #include "fdb5/database/Key.h" #include "fdb5/rules/SchemaParser.h" #include "fdb5/database/WriteVisitor.h" namespace fdb5 { //---------------------------------------------------------------------------------------------------------------------- Schema::Schema() { } Schema::Schema(const eckit::PathName &path) { load(path); } Schema::Schema(std::istream& s) { load(s); } Schema::~Schema() { clear(); } const Rule* Schema::ruleFor(const Key& dbKey, const Key& idxKey) const { std::vector<Key> keys; keys.push_back(dbKey); keys.push_back(idxKey); for (std::vector<Rule *>::const_iterator i = rules_.begin(); i != rules_.end(); ++i ) { const Rule* r = (*i)->ruleFor(keys , 0); if (r) { return r; } } return 0; } void Schema::expand(const metkit::mars::MarsRequest &request, ReadVisitor &visitor) const { Key full; std::vector<Key> keys(3); for (std::vector<Rule *>::const_iterator i = rules_.begin(); i != rules_.end(); ++i ) { // eckit::Log::info() << "Rule " << **i << std::endl; // (*i)->dump(eckit::Log::info()); (*i)->expand(request, visitor, 0, keys, full); } } void Schema::expand(const Key &field, WriteVisitor &visitor) const { Key full; std::vector<Key> keys(3); visitor.rule(0); // reset to no rule so we verify that we pick at least one for (std::vector<Rule *>::const_iterator i = rules_.begin(); i != rules_.end(); ++i ) { (*i)->expand(field, visitor, 0, keys, full); } } void Schema::expandSecond(const metkit::mars::MarsRequest& request, ReadVisitor& visitor, const Key& dbKey) const { const Rule* dbRule = nullptr; for (const Rule* r : rules_) { if (r->match(dbKey)) { dbRule = r; break; } } ASSERT(dbRule); Key full = dbKey; std::vector<Key> keys(3); keys[0] = dbKey; for (std::vector<Rule*>:: const_iterator i = dbRule->rules_.begin(); i != dbRule->rules_.end(); ++i) { (*i)->expand(request, visitor, 1, keys, full); } } void Schema::expandSecond(const Key& field, WriteVisitor& visitor, const Key& dbKey) const { const Rule* dbRule = nullptr; for (const Rule* r : rules_) { if (r->match(dbKey)) { dbRule = r; break; } } ASSERT(dbRule); Key full = dbKey; std::vector<Key> keys(3); keys[0] = dbKey; for (std::vector<Rule*>:: const_iterator i = dbRule->rules_.begin(); i != dbRule->rules_.end(); ++i) { (*i)->expand(field, visitor, 1, keys, full); } } bool Schema::expandFirstLevel(const Key &dbKey, Key &result) const { bool found = false; for (std::vector<Rule *>::const_iterator i = rules_.begin(); i != rules_.end() && !found; ++i ) { (*i)->expandFirstLevel(dbKey, result, found); } return found; } bool Schema::expandFirstLevel(const metkit::mars::MarsRequest& request, Key &result) const { bool found = false; for (const Rule* rule : rules_) { rule->expandFirstLevel(request, result, found); if (found) break; } return found; } void Schema::matchFirstLevel(const Key &dbKey, std::set<Key> &result, const char* missing) const { for (std::vector<Rule *>::const_iterator i = rules_.begin(); i != rules_.end(); ++i ) { (*i)->matchFirstLevel(dbKey, result, missing); } } void Schema::matchFirstLevel(const metkit::mars::MarsRequest& request, std::set<Key>& result, const char* missing) const { for (std::vector<Rule *>::const_iterator i = rules_.begin(); i != rules_.end(); ++i ) { (*i)->matchFirstLevel(request, result, missing); } } void Schema::load(const eckit::PathName &path, bool replace) { path_ = path; eckit::Log::debug<LibFdb5>() << "Loading FDB rules from " << path << std::endl; std::ifstream in(path.localPath()); if (!in) throw eckit::CantOpenFile(path); load(in, replace); } void Schema::load(std::istream& s, bool replace) { if (replace) { clear(); } SchemaParser parser(s); parser.parse(*this, rules_, registry_); check(); } void Schema::clear() { for (std::vector<Rule *>::iterator i = rules_.begin(); i != rules_.end(); ++i ) { delete *i; } } void Schema::dump(std::ostream &s) const { registry_.dump(s); for (std::vector<Rule *>::const_iterator i = rules_.begin(); i != rules_.end(); ++i ) { (*i)->dump(s); s << std::endl; } } void Schema::check() { for (std::vector<Rule *>::iterator i = rules_.begin(); i != rules_.end(); ++i ) { /// @todo print offending rule in meaningful message ASSERT((*i)->depth() == 3); (*i)->registry_.updateParent(&registry_); (*i)->updateParent(0); } } void Schema::print(std::ostream &out) const { out << "Schema[path=" << path_ << "]"; } const Type &Schema::lookupType(const std::string &keyword) const { return registry_.lookupType(keyword); } bool Schema::empty() const { return rules_.empty(); } const std::string &Schema::path() const { return path_; } const TypesRegistry& Schema::registry() const { return registry_; } std::ostream &operator<<(std::ostream &s, const Schema &x) { x.print(s); return s; } //---------------------------------------------------------------------------------------------------------------------- } // namespace fdb5
26.533632
123
0.577658
dvuckovic
c70ce1514ff7cfcd3c560f89406e3041d99c2bb5
5,576
cc
C++
PhysicsTools/HepMCCandAlgos/plugins/ParticleDecayDrawer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
PhysicsTools/HepMCCandAlgos/plugins/ParticleDecayDrawer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
PhysicsTools/HepMCCandAlgos/plugins/ParticleDecayDrawer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/* class ParticleDecayDrawer * * \author Luca Lista, INFN */ #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Utilities/interface/ESGetToken.h" #include "SimGeneral/HepPDTRecord/interface/ParticleDataTable.h" #include "DataFormats/Common/interface/View.h" #include "DataFormats/Candidate/interface/Candidate.h" class ParticleDecayDrawer : public edm::EDAnalyzer { public: ParticleDecayDrawer(const edm::ParameterSet &); private: void analyze(const edm::Event &, const edm::EventSetup &) override; edm::EDGetTokenT<edm::View<reco::Candidate> > srcToken_; std::string decay(const reco::Candidate &, std::list<const reco::Candidate *> &) const; edm::ESHandle<ParticleDataTable> pdt_; edm::ESGetToken<ParticleDataTable, edm::DefaultRecord> pdtToken_; /// print parameters bool printP4_, printPtEtaPhi_, printVertex_; /// print 4 momenta std::string printP4(const reco::Candidate &) const; /// accept candidate bool accept(const reco::Candidate &, const std::list<const reco::Candidate *> &) const; /// select candidate bool select(const reco::Candidate &) const; /// has valid daughters in the chain bool hasValidDaughters(const reco::Candidate &) const; }; #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/Event.h" #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Utilities/interface/EDMException.h" #include <iostream> #include <sstream> #include <algorithm> using namespace std; using namespace edm; using namespace reco; ParticleDecayDrawer::ParticleDecayDrawer(const ParameterSet &cfg) : srcToken_(consumes<edm::View<reco::Candidate> >(cfg.getParameter<InputTag>("src"))), pdtToken_(esConsumes<ParticleDataTable, edm::DefaultRecord>()), printP4_(cfg.getUntrackedParameter<bool>("printP4", false)), printPtEtaPhi_(cfg.getUntrackedParameter<bool>("printPtEtaPhi", false)), printVertex_(cfg.getUntrackedParameter<bool>("printVertex", false)) {} bool ParticleDecayDrawer::accept(const reco::Candidate &c, const list<const Candidate *> &skip) const { if (find(skip.begin(), skip.end(), &c) != skip.end()) return false; return select(c); } bool ParticleDecayDrawer::select(const reco::Candidate &c) const { return c.status() == 3; } bool ParticleDecayDrawer::hasValidDaughters(const reco::Candidate &c) const { size_t ndau = c.numberOfDaughters(); for (size_t i = 0; i < ndau; ++i) if (select(*c.daughter(i))) return true; return false; } void ParticleDecayDrawer::analyze(const Event &event, const EventSetup &es) { pdt_ = es.getHandle(pdtToken_); Handle<View<Candidate> > particles; event.getByToken(srcToken_, particles); list<const Candidate *> skip; vector<const Candidate *> nodes, moms; for (View<Candidate>::const_iterator p = particles->begin(); p != particles->end(); ++p) { if (p->numberOfMothers() > 1) { if (select(*p)) { skip.push_back(&*p); nodes.push_back(&*p); for (size_t j = 0; j < p->numberOfMothers(); ++j) { const Candidate *mom = p->mother(j); const Candidate *grandMom; while ((grandMom = mom->mother()) != nullptr) mom = grandMom; if (select(*mom)) { moms.push_back(mom); } } } } } cout << "-- decay: --" << endl; if (!moms.empty()) { if (moms.size() > 1) for (size_t m = 0; m < moms.size(); ++m) { string dec = decay(*moms[m], skip); if (!dec.empty()) cout << "{ " << dec << " } "; } else cout << decay(*moms[0], skip); } if (!nodes.empty()) { cout << "-> "; if (nodes.size() > 1) { for (size_t n = 0; n < nodes.size(); ++n) { skip.remove(nodes[n]); string dec = decay(*nodes[n], skip); if (!dec.empty()) { if (dec.find("->", 0) != string::npos) cout << " ( " << dec << " )"; else cout << " " << dec; } } } else { skip.remove(nodes[0]); cout << decay(*nodes[0], skip); } } cout << endl; } string ParticleDecayDrawer::printP4(const Candidate &c) const { ostringstream cout; if (printP4_) cout << " (" << c.px() << ", " << c.py() << ", " << c.pz() << "; " << c.energy() << ")"; if (printPtEtaPhi_) cout << " [" << c.pt() << ": " << c.eta() << ", " << c.phi() << "]"; if (printVertex_) cout << " {" << c.vx() << ", " << c.vy() << ", " << c.vz() << "}"; return cout.str(); } string ParticleDecayDrawer::decay(const Candidate &c, list<const Candidate *> &skip) const { string out; if (find(skip.begin(), skip.end(), &c) != skip.end()) return out; skip.push_back(&c); int id = c.pdgId(); const ParticleData *pd = pdt_->particle(id); assert(pd != nullptr); out += (pd->name() + printP4(c)); size_t validDau = 0, ndau = c.numberOfDaughters(); for (size_t i = 0; i < ndau; ++i) if (accept(*c.daughter(i), skip)) ++validDau; if (validDau == 0) return out; out += " ->"; for (size_t i = 0; i < ndau; ++i) { const Candidate *d = c.daughter(i); if (accept(*d, skip)) { string dec = decay(*d, skip); if (dec.find("->", 0) != string::npos) out += (" ( " + dec + " )"); else out += (" " + dec); } } return out; } #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(ParticleDecayDrawer);
32.418605
103
0.61406
ckamtsikis
c71319b609ad64a452c22be56d35aa26aea8f6cb
294
cc
C++
lib/src/Compiler/Runtime/RuntimePhase.cc
milliburn/llvmPy
d6fa3002e823fae00cf33d9b2ea480604681376c
[ "MIT" ]
1
2019-01-22T02:58:04.000Z
2019-01-22T02:58:04.000Z
lib/src/Compiler/Runtime/RuntimePhase.cc
roberth-k/llvmPy
d6fa3002e823fae00cf33d9b2ea480604681376c
[ "MIT" ]
null
null
null
lib/src/Compiler/Runtime/RuntimePhase.cc
roberth-k/llvmPy
d6fa3002e823fae00cf33d9b2ea480604681376c
[ "MIT" ]
null
null
null
#include <assert.h> #include <llvmPy/Compiler/Runtime/RuntimePhase.h> using namespace llvmPy; static std::string const phaseName = "rt"; RuntimePhase::RuntimePhase(RT &rt) : Phase(phaseName), _rt(rt) { } int RuntimePhase::run(RTModule &module) { _rt.import(module); return 0; }
15.473684
49
0.704082
milliburn
c71370c682704f2c244defe01bae201aacb14251
4,263
cpp
C++
test/impl/UniqueTokenStorage_test.cpp
mark-grimes/Communique
969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a
[ "Apache-2.0" ]
null
null
null
test/impl/UniqueTokenStorage_test.cpp
mark-grimes/Communique
969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a
[ "Apache-2.0" ]
1
2015-11-25T09:48:34.000Z
2015-11-25T09:48:34.000Z
test/impl/UniqueTokenStorage_test.cpp
mark-grimes/Communique
969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a
[ "Apache-2.0" ]
null
null
null
#include <communique/impl/UniqueTokenStorage.h> #include "../catch.hpp" #include <iostream> #include <map> SCENARIO( "Test that UniqueTokenStorage behaves as expected", "[UniqueTokenStorage][tools]" ) { GIVEN( "A UniqueTokenStorage<uint64_t,uint32_t> instance" ) { // Use a 32 bit unsigned int as the tokens, and a normal unsigned int for the values communique::impl::UniqueTokenStorage<uint64_t,uint8_t> myTokenStorage; WHEN( "I try to retrieve from an empty container" ) { CHECK_THROWS( myTokenStorage.pop(9) ); CHECK_THROWS( myTokenStorage.pop(0) ); uint64_t result; CHECK( myTokenStorage.pop(0,result)==false ); CHECK( myTokenStorage.pop(9,result)==false ); } WHEN( "I try to retrieve previously stored items I get the correct ones back" ) { std::vector< std::pair<uint64_t,uint8_t> > storedItems; // keep a record of what's stored so I can check // Fill with random values for( size_t index=0; index<200; ++index ) { // Get a random number to store uint64_t newValue=std::rand()*static_cast<float>(std::numeric_limits<uint64_t>::max())/RAND_MAX; uint8_t newKey; REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) ); storedItems.push_back( std::make_pair(newValue,newKey) ); } // Try and retrieve each of these values and make sure the result is correct for( const auto& valueKeyPair : storedItems ) { uint64_t retrievedValue; REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop( valueKeyPair.second ) ); CHECK( retrievedValue==valueKeyPair.first ); } } WHEN( "I try to completely fill a container" ) { uint64_t newValue; uint8_t newKey; // Fill with arbitrary values, take out some as I go for( uint64_t index=0; index<=std::numeric_limits<uint8_t>::max(); ++index ) { REQUIRE_NOTHROW( newKey=myTokenStorage.push( index ) ); } newValue=34; CHECK_THROWS( newKey=myTokenStorage.push( newValue ) ); // Try and retrieve an arbitrary entry uint8_t retrieveKey=64; uint64_t retrievedValue; REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(retrieveKey) ); // Then try and add another entry CHECK_NOTHROW( newKey=myTokenStorage.push( retrievedValue ) ); // Collection should be full again, so make sure I can't add anything else CHECK_THROWS( newKey=myTokenStorage.push( newValue ) ); } WHEN( "I fill then empty some items, I can still retrieve the correct ones back items" ) { std::map<uint8_t,uint64_t> storedItems; // keep a record of what's stored so I can check uint64_t newValue; uint8_t newKey; // Fill with random values for( size_t index=0; index<=std::numeric_limits<uint8_t>::max(); ++index ) { // Get a random number to store newValue=std::rand()*static_cast<float>(std::numeric_limits<uint64_t>::max())/RAND_MAX; REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) ); storedItems[newKey]=newValue; } // Check container is actually full newValue=34; CHECK_THROWS( newKey=myTokenStorage.push( newValue ) ); // Remove some arbitrary items uint64_t retrievedValue; REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(0) ); REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(1) ); REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(2) ); REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(65) ); REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(128) ); newValue=5; REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) ); storedItems[newKey]=newValue; newValue=6; REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) ); storedItems[newKey]=newValue; newValue=7; REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) ); storedItems[newKey]=newValue; newValue=8; REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) ); storedItems[newKey]=newValue; newValue=9; REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) ); storedItems[newKey]=newValue; // Try and retrieve each of these values and make sure the result is correct for( const auto& keyValuePair : storedItems ) { uint64_t retrievedValue; REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop( keyValuePair.first ) ); CHECK( retrievedValue==keyValuePair.second ); } } } }
34.658537
107
0.71757
mark-grimes
c716bfe967ba29b14591030c3502628b29a4fdbf
624
cpp
C++
Files/VK18/VK18-16521309.cpp
nishant-khanorkar/CodeChef-Submissions
4019e859d95bfa7fe763acf330c98f5f54b7b185
[ "MIT" ]
null
null
null
Files/VK18/VK18-16521309.cpp
nishant-khanorkar/CodeChef-Submissions
4019e859d95bfa7fe763acf330c98f5f54b7b185
[ "MIT" ]
null
null
null
Files/VK18/VK18-16521309.cpp
nishant-khanorkar/CodeChef-Submissions
4019e859d95bfa7fe763acf330c98f5f54b7b185
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ll long long int using namespace std; int main() { ll gg,hh,kk,i,j,k,m,a1,a2; ll ab[2000007],ans[1000007]; ab[0]=0; for(i=1;i<=2000005;i++) { j=i+1; a1=a2=0; while(j>0) { m=j%10; if(m%2) a1+=m; else a2+=m; j/=10; } ab[i]=abs(a1-a2)+ab[i-1]; } ans[1]=2; for(i=2;i<=1000001;i++) ans[i]=ans[i-1]+2*(ab[2*i-1]-ab[i-1])-(ab[2*i-1]-ab[2*i-2]); cin>>gg; while(gg--) { cin>>hh; cout<<ans[hh]<<endl; } return 0; }
16
68
0.399038
nishant-khanorkar
c7171eaca46d7e99f6636ad5a650731d17054c21
2,108
cpp
C++
game/main.cpp
geoffwhitehead/moonbase-commander-game
8eb3664e1275e9f0d22fe22d25d334654a57a949
[ "MIT" ]
1
2017-09-30T21:16:35.000Z
2017-09-30T21:16:35.000Z
game/main.cpp
geoffwhitehead/moonbase-commander-game
8eb3664e1275e9f0d22fe22d25d334654a57a949
[ "MIT" ]
null
null
null
game/main.cpp
geoffwhitehead/moonbase-commander-game
8eb3664e1275e9f0d22fe22d25d334654a57a949
[ "MIT" ]
null
null
null
#include "../nclgl/OGLRenderer.h" #include "../engine-base/Camera.h" #include "../engine-base/GameManager.h" #include "../engine-audio/AudioManager.h" #include "../engine-input/InputManager.h" #include "../engine-base/GameLogicManager.h" #include "../engine-physics/PhysicsManager.h" #include "ContactListener.h" #include "GameInput.h" #include "GameAudio.h" #include "GameLogic.h" #include "GameIO.h" #include <iostream> #include <map> // screen size #define W_X 1600.0f #define W_Y 900.0f #define p_factor 12.0f const float pixels_per_m = 20.0f; //const float gravity = -pixels_per_m / 0.7f; // adjust const float gravity = 0.0f; void main(void) { // GAME MANAGER GameManager *gm = new GameManager(W_X, W_Y); // PHYSICS PhysicsManager* pm = new PhysicsManager(gm, gravity, pixels_per_m); // FILE IO GameIO* gio = new GameIO("./levels/", pm->b2_world, pm->pixels_per_m); gm->addFileInput(gio); gm->loadLevel("level_1.json"); // CAMERA Camera* camera = new Camera(0.0f, 0.0f, Vector3(0, 0, 400), W_X, W_Y); Camera::projMatrix = Matrix4::Orthographic(1, 1000, W_X/ pixels_per_m, -W_X/ pixels_per_m, W_Y/ pixels_per_m,-W_Y/ pixels_per_m); //Camera::viewMatrix = Matrix4::BuildCamera(Vector3(0.0, 50.0, 20.0), Vector3(0.0, 0.0, 0.0)); //camera->BuildViewMatrix(); //ADD SYSTEM MANAGERS AudioManager* am = new AudioManager(gio); // init with file input to cause it to load audio from file InputManager* im = new InputManager(); GameLogicManager* glm = new GameLogicManager(); //CREATE SUB SYSTEMS GameLogic* gl = new GameLogic(gm, glm, pm->b2_world, am, camera); GameInput* gi = new GameInput(gl, camera); ContactListener* cl = new ContactListener(gl); GameAudio* ga = new GameAudio(gl, am); // created to seperate audio from game //register managers gm->addSystemManager(am); pm->addListener(cl); gm->addSystemManager(im); gm->addSystemManager(glm); gm->addSystemManager(pm); //register sub systems im->addSubSystem(camera); glm->addSubSystem(gl); im->addSubSystem(gi); am->addSubSystem(ga); // register with audio manager so updates are called gm->run(); }
28.106667
130
0.711575
geoffwhitehead
c718f6aad5362e53f34bd66af06eed9d09b42e06
16,667
cpp
C++
src/app/voltdb/voltdb_src/src/ee/common/executorcontext.cpp
OpenMPDK/SMDK
8f19d32d999731242cb1ab116a4cb445d9993b15
[ "BSD-3-Clause" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
src/app/voltdb/voltdb_src/src/ee/common/executorcontext.cpp
H2O0Lee/SMDK
eff49bc17a55a83ea968112feb2e2f2ea18c4ff5
[ "BSD-3-Clause" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
src/app/voltdb/voltdb_src/src/ee/common/executorcontext.cpp
H2O0Lee/SMDK
eff49bc17a55a83ea968112feb2e2f2ea18c4ff5
[ "BSD-3-Clause" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* This file is part of VoltDB. * Copyright (C) 2008-2020 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ #include "common/executorcontext.hpp" #include "common/SynchronizedThreadLock.h" #include "executors/abstractexecutor.h" #include "executors/insertexecutor.h" #include "storage/AbstractDRTupleStream.h" #include "storage/DRTupleStreamUndoAction.h" #include "storage/persistenttable.h" #include "plannodes/insertnode.h" #include "debuglog.h" #ifdef LINUX #include <malloc.h> #endif // LINUX using namespace std; namespace voltdb { namespace { /** * This is the pthread_specific key for the ExecutorContext * of the logically executing site. See ExecutorContext::getExecutorContext * and ExecutorContext::getThreadExecutorContext. */ pthread_key_t logical_executor_context_static_key; /** * This is the pthread_specific key for the Topend * of the site actually executing. See ExecutorContext::getExecutorContext * and ExecutorContext::getThreadExecutorContext. */ pthread_key_t physical_topend_static_key; pthread_once_t static_keyOnce = PTHREAD_ONCE_INIT; /** * This function will initiate global settings and create thread key once per process. * */ void globalInitOrCreateOncePerProcess() { #ifdef LINUX // We ran into an issue where memory wasn't being returned to the // operating system (and thus reducing RSS) when freeing. See // ENG-891 for some info. It seems that some code we use somewhere // (maybe JVM, but who knows) calls mallopt and changes some of // the tuning parameters. At the risk of making that software // angry, the following code resets the tunable parameters to // their default values. // Note: The parameters and default values come from looking at // the glibc 2.5 source, which is the version that ships // with redhat/centos 5. The code seems to also be effective on // newer versions of glibc (tested againsts 2.12.1). mallopt(M_MXFAST, 128); // DEFAULT_MXFAST // note that DEFAULT_MXFAST was increased to 128 for 64-bit systems // sometime between glibc 2.5 and glibc 2.12.1 mallopt(M_TRIM_THRESHOLD, 128 * 1024); // DEFAULT_TRIM_THRESHOLD mallopt(M_TOP_PAD, 0); // DEFAULT_TOP_PAD mallopt(M_MMAP_THRESHOLD, 128 * 1024); // DEFAULT_MMAP_THRESHOLD mallopt(M_MMAP_MAX, 65536); // DEFAULT_MMAP_MAX mallopt(M_CHECK_ACTION, 3); // DEFAULT_CHECK_ACTION #endif // LINUX // Be explicit about running in the standard C locale for now. std::locale::global(std::locale("C")); setenv("TZ", "UTC", 0); // set timezone as "UTC" in EE level (void) pthread_key_create(&logical_executor_context_static_key, NULL); (void) pthread_key_create(&physical_topend_static_key, NULL); SynchronizedThreadLock::create(); } } void globalDestroyOncePerProcess() { SynchronizedThreadLock::destroy(); pthread_key_delete(logical_executor_context_static_key); pthread_key_delete(physical_topend_static_key); static_keyOnce = PTHREAD_ONCE_INIT; } ExecutorContext::ExecutorContext(int64_t siteId, CatalogId partitionId, UndoQuantum *undoQuantum, Topend* topend, Pool* tempStringPool, VoltDBEngine* engine, std::string const& hostname, CatalogId hostId, AbstractDRTupleStream *drStream, AbstractDRTupleStream *drReplicatedStream, CatalogId drClusterId) : m_topend(topend), m_tempStringPool(tempStringPool), m_undoQuantum(undoQuantum), m_drStream(drStream), m_drReplicatedStream(drReplicatedStream), m_engine(engine), m_lttBlockCache(topend, engine ? engine->tempTableMemoryLimit() : 50*1024*1024, siteId), // engine may be null in unit tests m_siteId(siteId), m_partitionId(partitionId), m_hostname(hostname), m_hostId(hostId), m_drClusterId(drClusterId) { (void)pthread_once(&static_keyOnce, globalInitOrCreateOncePerProcess); bindToThread(); } ExecutorContext::~ExecutorContext() { m_lttBlockCache.releaseAllBlocks(); // currently does not own any of its pointers VOLT_DEBUG("De-installing EC(%ld) for partition %d", (long)this, m_partitionId); pthread_setspecific(logical_executor_context_static_key, NULL); pthread_setspecific(physical_topend_static_key, NULL); } void ExecutorContext::assignThreadLocals(const EngineLocals& mapping) { pthread_setspecific(logical_executor_context_static_key, const_cast<ExecutorContext*>(mapping.context)); ThreadLocalPool::assignThreadLocals(mapping); } void ExecutorContext::resetStateForTest() { pthread_setspecific(logical_executor_context_static_key, NULL); pthread_setspecific(physical_topend_static_key, NULL); ThreadLocalPool::resetStateForTest(); } void ExecutorContext::bindToThread() { pthread_setspecific(logical_executor_context_static_key, this); // At this point the logical and physical sites must be the // same. So the two top ends are identical. pthread_setspecific(physical_topend_static_key, m_topend); VOLT_DEBUG("Installing EC(%p) for partition %d", this, m_partitionId); } ExecutorContext* ExecutorContext::getExecutorContext() { (void)pthread_once(&static_keyOnce, globalInitOrCreateOncePerProcess); return static_cast<ExecutorContext*>(pthread_getspecific(logical_executor_context_static_key)); } Topend* ExecutorContext::getPhysicalTopend() { (void)pthread_once(&static_keyOnce, globalInitOrCreateOncePerProcess); return static_cast<Topend *>(pthread_getspecific(physical_topend_static_key)); } UniqueTempTableResult ExecutorContext::executeExecutors(int subqueryId) { const std::vector<AbstractExecutor*>& executorList = getExecutors(subqueryId); return executeExecutors(executorList, subqueryId); } UniqueTempTableResult ExecutorContext::executeExecutors( const std::vector<AbstractExecutor*>& executorList, int subqueryId) { // Walk through the list and execute each plannode. // The query planner guarantees that for a given plannode, // all of its children are positioned before it in this list, // therefore dependency tracking is not needed here. int ctr = 0; try { for (AbstractExecutor *executor: executorList) { vassert(executor); if (isTraceOn()) { char name[32]; snprintf(name, 32, "%s", planNodeToString(executor->getPlanNode()->getPlanNodeType()).c_str()); getPhysicalTopend()->traceLog(true, name, NULL); } // Call the execute method to actually perform whatever action // it is that the node is supposed to do... if (!executor->execute(m_staticParams)) { if (isTraceOn()) { getPhysicalTopend()->traceLog(false, NULL, NULL); } InsertExecutor* insertExecutor = dynamic_cast<InsertExecutor*>(executor); if (insertExecutor != nullptr && insertExecutor->exceptionMessage() != nullptr) { throw SerializableEEException(insertExecutor->exceptionMessage()); } else { throw SerializableEEException("Unspecified execution error detected"); } } if (isTraceOn()) { getPhysicalTopend()->traceLog(false, NULL, NULL); } ++ctr; } } catch (const SerializableEEException &e) { if (SynchronizedThreadLock::isInSingleThreadMode()) { // Assign the correct pool back to this thread SynchronizedThreadLock::signalLowestSiteFinished(); } // Clean up any tempTables when the plan finishes abnormally. // This needs to be the caller's responsibility for normal returns because // the caller may want to first examine the final output table. cleanupAllExecutors(); // Normally, each executor cleans its memory pool as it finishes execution, // but in the case of a throw, it may not have had the chance. // So, clean up all the memory pools now. //TODO: This code singles out inline nodes for cleanup. // Is that because the currently active (memory pooling) non-inline // executor always cleans itself up before throwing??? // But if an active executor can be that smart, an active executor with // (potential) inline children could also be smart enough to clean up // after its inline children, and this post-processing would not be needed. for (AbstractExecutor *executor: executorList) { vassert(executor); AbstractPlanNode * node = executor->getPlanNode(); std::map<PlanNodeType, AbstractPlanNode*>::iterator it; std::map<PlanNodeType, AbstractPlanNode*> inlineNodes = node->getInlinePlanNodes(); for (it = inlineNodes.begin(); it != inlineNodes.end(); it++ ) { AbstractPlanNode *inlineNode = it->second; inlineNode->getExecutor()->cleanupMemoryPool(); } } if (subqueryId == 0) { VOLT_TRACE("The Executor's execution at position '%d' failed", ctr); } else { VOLT_TRACE("The Executor's execution at position '%d' in subquery %d failed", ctr, subqueryId); } throw; } AbstractTempTable *result = executorList.back()->getPlanNode()->getTempOutputTable(); return UniqueTempTableResult(result); } Table* ExecutorContext::getSubqueryOutputTable(int subqueryId) const { const std::vector<AbstractExecutor*>& executorList = getExecutors(subqueryId); vassert(!executorList.empty()); return executorList.back()->getPlanNode()->getOutputTable(); } AbstractTempTable* ExecutorContext::getCommonTable(const std::string& tableName, int cteStmtId) { AbstractTempTable* table = NULL; auto it = m_commonTableMap.find(tableName); if (it == m_commonTableMap.end()) { UniqueTempTableResult result = executeExecutors(cteStmtId); table = result.release(); m_commonTableMap.insert(std::make_pair(tableName, table)); } else { table = it->second; } return table; } void ExecutorContext::cleanupAllExecutors() { // If something failed before we could even instantiate the plan, // there won't even be an executors map. if (m_executorsMap != NULL) { for(auto& entry : *m_executorsMap) { int subqueryId = entry.first; cleanupExecutorsForSubquery(subqueryId); } } // Clear any cached results from executed subqueries m_subqueryContextMap.clear(); m_commonTableMap.clear(); } void ExecutorContext::cleanupExecutorsForSubquery( const std::vector<AbstractExecutor*>& executorList) const { for (AbstractExecutor *executor: executorList) { vassert(executor); executor->cleanupTempOutputTable(); } } void ExecutorContext::cleanupExecutorsForSubquery(int subqueryId) const { const std::vector<AbstractExecutor*>& executorList = getExecutors(subqueryId); cleanupExecutorsForSubquery(executorList); } void ExecutorContext::resetExecutionMetadata(ExecutorVector* executorVector) { if (m_tuplesModifiedStack.size() != 0) { m_tuplesModifiedStack.pop(); } vassert(m_tuplesModifiedStack.size() == 0); executorVector->resetLimitStats(); } void ExecutorContext::reportProgressToTopend(const TempTableLimits *limits) { int64_t allocated = limits != NULL ? limits->getAllocated() : -1; int64_t peak = limits != NULL ? limits->getPeakMemoryInBytes() : -1; //Update stats in java and let java determine if we should cancel this query. m_progressStats.TuplesProcessedInFragment += m_progressStats.TuplesProcessedSinceReport; int64_t tupleReportThreshold = getPhysicalTopend()->fragmentProgressUpdate( m_engine->getCurrentIndexInBatch(), m_progressStats.LastAccessedPlanNodeType, m_progressStats.TuplesProcessedInBatch + m_progressStats.TuplesProcessedInFragment, allocated, peak); m_progressStats.TuplesProcessedSinceReport = 0; if (tupleReportThreshold < 0) { VOLT_DEBUG("Interrupt query."); char buff[100]; /** * NOTE: this is NOT a broken sentence. The complete * error message reported will be: * * VOLTDB ERROR: Transaction Interrupted A SQL query was terminated after 1.00# seconds because it exceeded the query-specific timeout period. The query-specific timeout is currently 1.0 seconds. The default query timeout is currently 10.0 seconds and can be changed in the systemsettings section of the deployment file. * * See also: tests/sqlcmd/scripts/querytimeout/timeout.err */ snprintf(buff, 100, "A SQL query was terminated after %.03f seconds because it exceeded the", static_cast<double>(tupleReportThreshold) / -1000.0); throw InterruptException(std::string(buff)); } m_progressStats.TupleReportThreshold = tupleReportThreshold; } bool ExecutorContext::allOutputTempTablesAreEmpty() const { if (m_executorsMap != nullptr) { for(auto& entry : *m_executorsMap) { for(auto const* executor : entry.second) { if (! executor->outputTempTableIsEmpty()) { return false; } } } } return true; } void ExecutorContext::setDrStream(AbstractDRTupleStream *drStream) { vassert(m_drStream != NULL); vassert(drStream != NULL); vassert(m_drStream->m_committedSequenceNumber >= drStream->m_committedSequenceNumber); int64_t lastCommittedSpHandle = std::max(m_lastCommittedSpHandle, drStream->m_openTxnId); m_drStream->periodicFlush(-1L, lastCommittedSpHandle); int64_t oldSeqNum = m_drStream->m_committedSequenceNumber; m_drStream = drStream; m_drStream->setLastCommittedSequenceNumber(oldSeqNum); } void ExecutorContext::setDrReplicatedStream(AbstractDRTupleStream *drReplicatedStream) { if (m_drReplicatedStream == NULL || drReplicatedStream == NULL) { m_drReplicatedStream = drReplicatedStream; return; } vassert(m_drReplicatedStream->m_committedSequenceNumber >= drReplicatedStream->m_committedSequenceNumber); int64_t lastCommittedSpHandle = std::max(m_lastCommittedSpHandle, drReplicatedStream->m_openTxnId); m_drReplicatedStream->periodicFlush(-1L, lastCommittedSpHandle); int64_t oldSeqNum = m_drReplicatedStream->m_committedSequenceNumber; m_drReplicatedStream = drReplicatedStream; m_drReplicatedStream->setLastCommittedSequenceNumber(oldSeqNum); } /** * To open DR stream to start binary logging for a transaction at this level, * 1. It needs to be a multipartition transaction. * 2. It is NOT a read-only transaction as it generates no data change on any partition. * * For single partition transactions, DR stream's binary logging is handled as is * at persistenttable level. */ bool ExecutorContext::checkTransactionForDR() { bool result = false; if (UniqueId::isMpUniqueId(m_uniqueId) && m_undoQuantum != NULL) { if (m_externalStreamsEnabled && m_drStream && m_drStream->drStreamStarted()) { if (m_drStream->transactionChecks(m_spHandle, m_uniqueId)) { m_undoQuantum->registerUndoAction( new (*m_undoQuantum) DRTupleStreamUndoAction(m_drStream, m_drStream->m_committedUso, 0)); } result = true; } if (m_drReplicatedStream && m_drReplicatedStream->drStreamStarted()) { if (m_drReplicatedStream->transactionChecks(m_spHandle, m_uniqueId)) { m_undoQuantum->registerUndoAction( new (*m_undoQuantum) DRTupleStreamUndoAction( m_drReplicatedStream, m_drReplicatedStream->m_committedUso, 0)); } } } return result; } } // end namespace voltdb
42.30203
328
0.699346
OpenMPDK
c71a59e885c1226bb0817675657235af87c80a5f
1,987
cpp
C++
ports/esp32/src/OTA.cpp
ygjukim/hFramework
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
[ "MIT" ]
33
2017-07-03T22:49:30.000Z
2022-03-31T19:32:55.000Z
ports/esp32/src/OTA.cpp
ygjukim/hFramework
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
[ "MIT" ]
6
2017-07-13T13:23:22.000Z
2019-10-25T17:51:28.000Z
ports/esp32/src/OTA.cpp
ygjukim/hFramework
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
[ "MIT" ]
17
2017-07-01T05:35:47.000Z
2022-03-22T23:33:00.000Z
#include <hFramework.h> #include <cstring> #include <utility> #include "esp_ota_ops.h" namespace hFramework { namespace OTA { const esp_partition_t* getOtaPartition() { const esp_partition_t* bootPartition = esp_ota_get_boot_partition(); const char* newname; if (bootPartition == nullptr || strcmp("ota_0", bootPartition->label) == 0) { fprintf(stderr, "OTA: currently running from partition 'ota_0'\n"); newname = "ota_1"; } else if (strcmp("ota_1", bootPartition->label) == 0) { fprintf(stderr, "OTA: currently running from partition 'ota_1'\n"); newname = "ota_0"; } else { fprintf(stderr, "OTA: invalid boot partition\n"); return nullptr; } return esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, newname); } bool run(uint32_t crc32, int length, hStreamDev& dev) { const esp_partition_t* otaPart = getOtaPartition(); esp_ota_handle_t handle; if (esp_ota_begin(otaPart, 0, &handle) != 0) { fprintf(stderr, "OTA: esp_ota_begin error\n"); return false; } const int maxChunkSize = 4096; char* chunkBuffer = (char*)malloc(maxChunkSize); while (length > 0) { int chunkSize = std::min(length, maxChunkSize); if (dev.readAll(chunkBuffer, chunkSize) != chunkSize) { fprintf(stderr, "OTA: steam read failed\n"); return false; } length -= chunkSize; if (esp_ota_write(handle, chunkBuffer, chunkSize) != 0) { fprintf(stderr, "OTA: esp_ota_write error\n"); return false; } } if (esp_ota_end(handle) != 0) { fprintf(stderr, "OTA: esp_ota_end failed\n"); return false; } // TODO: check crc32 if (esp_ota_set_boot_partition(otaPart) != 0) { fprintf(stderr, "OTA: esp_ota_set_boot_partition\n"); return false; } fprintf(stderr, "OTA: finished successfully\n"); return true; } } }
27.985915
96
0.630096
ygjukim
c71cc72be8c6d79d01e0da7690a5c2f3c4d257f7
279
cpp
C++
src/Test.PlcNext/Deployment/PortNameTooShort/src/PortNameTooShortProgram.cpp
PLCnext/PLCnext_CLI
cf8ad590f05196747b403da891bdd5da86f82469
[ "Apache-2.0" ]
7
2020-10-08T12:37:49.000Z
2021-03-29T07:49:52.000Z
src/Test.PlcNext/Deployment/PortNameTooShort/src/PortNameTooShortProgram.cpp
PLCnext/PLCnext_CLI
cf8ad590f05196747b403da891bdd5da86f82469
[ "Apache-2.0" ]
10
2020-10-09T14:04:01.000Z
2022-03-09T09:38:58.000Z
src/Test.PlcNext/Deployment/PortNameTooShort/src/PortNameTooShortProgram.cpp
PLCnext/PLCnext_CLI
cf8ad590f05196747b403da891bdd5da86f82469
[ "Apache-2.0" ]
2
2020-09-04T06:45:39.000Z
2020-10-30T10:07:33.000Z
#include "PortNameTooShortProgram.hpp" #include "Arp/System/Commons/Logging.h" #include "Arp/System/Core/ByteConverter.hpp" namespace PortNameTooShort { void PortNameTooShortProgram::Execute() { //implement program } } // end of namespace PortNameTooShort
19.928571
45
0.734767
PLCnext
c72191e3edc2be1cb12de94a53cd84a52c58176d
215
cpp
C++
8_bit_manipulation/5_even_odd.cpp
ShyamNandanKumar/coding-ninja2
a43a21575342261e573f71f7d8eff0572f075a17
[ "MIT" ]
11
2021-01-02T10:07:17.000Z
2022-03-16T00:18:06.000Z
8_bit_manipulation/5_even_odd.cpp
meyash/cp_master
316bf47db2a5b40891edd73cff834517993c3d2a
[ "MIT" ]
null
null
null
8_bit_manipulation/5_even_odd.cpp
meyash/cp_master
316bf47db2a5b40891edd73cff834517993c3d2a
[ "MIT" ]
5
2021-05-19T11:17:18.000Z
2021-09-16T06:23:31.000Z
// check if num is even or odd // just check last bit #include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; if((n&1)==1){ cout<<"Odd"; }else{ cout<<"Even"; } }
14.333333
30
0.506977
ShyamNandanKumar
c724e1bb075d6c4d90d921e9ba588d4e53c0e120
4,855
cpp
C++
src/plugins/simulator/entities/led_entity.cpp
hoelzl/argos3
05e2b8a0a2a94139a0753ebfac4d4c51cdea8e1c
[ "MIT" ]
null
null
null
src/plugins/simulator/entities/led_entity.cpp
hoelzl/argos3
05e2b8a0a2a94139a0753ebfac4d4c51cdea8e1c
[ "MIT" ]
null
null
null
src/plugins/simulator/entities/led_entity.cpp
hoelzl/argos3
05e2b8a0a2a94139a0753ebfac4d4c51cdea8e1c
[ "MIT" ]
null
null
null
/** * @file <argos3/core/simulator/entity/led_entity.cpp> * * @author Carlo Pinciroli - <ilpincy@gmail.com> */ #include "led_entity.h" #include <argos3/core/simulator/space/space.h> #include <argos3/plugins/simulator/media/led_medium.h> namespace argos { /****************************************/ /****************************************/ CLEDEntity::CLEDEntity(CComposableEntity* pc_parent) : CPositionalEntity(pc_parent), m_pcMedium(NULL) {} /****************************************/ /****************************************/ CLEDEntity::CLEDEntity(CComposableEntity* pc_parent, const std::string& str_id, const CVector3& c_position, const CColor& c_color) : CPositionalEntity(pc_parent, str_id, c_position, CQuaternion()), m_cColor(c_color), m_cInitColor(c_color), m_pcMedium(NULL) {} /****************************************/ /****************************************/ void CLEDEntity::Init(TConfigurationNode& t_tree) { try { /* Parse XML */ CPositionalEntity::Init(t_tree); GetNodeAttribute(t_tree, "color", m_cInitColor); m_cColor = m_cInitColor; } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error while initializing led entity", ex); } } /****************************************/ /****************************************/ void CLEDEntity::Reset() { CPositionalEntity::Reset(); m_cColor = m_cInitColor; } /****************************************/ /****************************************/ void CLEDEntity::Destroy() { if(HasMedium()) { RemoveFromMedium(); } } /****************************************/ /****************************************/ void CLEDEntity::SetEnabled(bool b_enabled) { CEntity::SetEnabled(b_enabled); if(IsEnabled()) { m_cColor = m_cInitColor; } } /****************************************/ /****************************************/ void CLEDEntity::AddToMedium(CLEDMedium& c_medium) { if(HasMedium()) { RemoveFromMedium(); } m_pcMedium = &c_medium; c_medium.AddEntity(*this); } /****************************************/ /****************************************/ void CLEDEntity::RemoveFromMedium() { try { GetMedium().RemoveEntity(*this); m_pcMedium = NULL; } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Can't remove LED entity \"" << GetId() << "\" from medium.", ex); } } /****************************************/ /****************************************/ CLEDMedium& CLEDEntity::GetMedium() const { if(m_pcMedium == NULL) { THROW_ARGOSEXCEPTION("LED entity \"" << GetId() << "\" has no medium associated."); } return *m_pcMedium; } /****************************************/ /****************************************/ void CLEDEntitySpaceHashUpdater::operator()(CAbstractSpaceHash<CLEDEntity>& c_space_hash, CLEDEntity& c_element) { /* Discard LEDs switched off */ if(c_element.GetColor() != CColor::BLACK) { /* Calculate the position of the LED in the space hash */ c_space_hash.SpaceToHashTable(m_nI, m_nJ, m_nK, c_element.GetPosition()); /* Update the corresponding cell */ c_space_hash.UpdateCell(m_nI, m_nJ, m_nK, c_element); } } /****************************************/ /****************************************/ CLEDEntityGridUpdater::CLEDEntityGridUpdater(CGrid<CLEDEntity>& c_grid) : m_cGrid(c_grid) {} /****************************************/ /****************************************/ bool CLEDEntityGridUpdater::operator()(CLEDEntity& c_entity) { /* Discard LEDs switched off */ if(c_entity.GetColor() != CColor::BLACK) { try { /* Calculate the position of the LED in the space hash */ m_cGrid.PositionToCell(m_nI, m_nJ, m_nK, c_entity.GetPosition()); /* Update the corresponding cell */ m_cGrid.UpdateCell(m_nI, m_nJ, m_nK, c_entity); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("While updating the LED grid for LED \"" << c_entity.GetContext() << c_entity.GetId() << "\"", ex); } } /* Continue with the other entities */ return true; } /****************************************/ /****************************************/ REGISTER_STANDARD_SPACE_OPERATIONS_ON_ENTITY(CLEDEntity); /****************************************/ /****************************************/ }
30.923567
139
0.444284
hoelzl
c7272fab357b540cdd71d596e135c3789072c14e
15,219
cpp
C++
iTunesBackup/core/Utils.cpp
BlueMatthew/iTunesBackup
d70615988d782a5b1b721797c6e38c6cbb1a4542
[ "Apache-2.0" ]
1
2022-01-11T06:01:26.000Z
2022-01-11T06:01:26.000Z
iTunesBackup/core/Utils.cpp
BlueMatthew/iTunesBackup
d70615988d782a5b1b721797c6e38c6cbb1a4542
[ "Apache-2.0" ]
null
null
null
iTunesBackup/core/Utils.cpp
BlueMatthew/iTunesBackup
d70615988d782a5b1b721797c6e38c6cbb1a4542
[ "Apache-2.0" ]
null
null
null
// // Utils.cpp // WechatExporter // // Created by Matthew on 2020/9/30. // Copyright © 2020 Matthew. All rights reserved. // #include "Utils.h" #include <ctime> #include <vector> #include <sstream> #include <iomanip> #include <fstream> #include <algorithm> #include <codecvt> #include <locale> #include <cstdio> #include <chrono> #ifdef _WIN32 #include <direct.h> #include <atlstr.h> #include <sys/utime.h> #include <Shlwapi.h> #ifndef NDEBUG #include <cassert> #endif #else #include <utime.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <sqlite3.h> #include "FileSystem.h" void replaceAll(std::string& input, const std::string& search, const std::string& replace) { size_t pos = 0; while((pos = input.find(search, pos)) != std::string::npos) { input.replace(pos, search.length(), replace); pos += replace.length(); } } void replaceAll(std::string& input, const std::vector<std::pair<std::string, std::string>>& pairs) { for (std::vector<std::pair<std::string, std::string>>::const_iterator it = pairs.cbegin(); it != pairs.cend(); ++it) { size_t pos = 0; while((pos = input.find(it->first, pos)) != std::string::npos) { input.replace(pos, it->first.length(), it->second); pos += it->second.length(); } } } std::string replaceAll(const std::string& input, const std::string& search, const std::string& replace) { std::string result = input; replaceAll(result, search, replace); return result; } std::string replaceAll(const std::string& input, const std::vector<std::pair<std::string, std::string>>& pairs) { std::string result = input; replaceAll(result, pairs); return result; } bool endsWith(const std::string& str, const std::string& suffix) { return str.size() >= suffix.size() && 0 == str.compare(str.size()-suffix.size(), suffix.size(), suffix); } bool endsWith(const std::string& str, std::string::value_type ch) { return !str.empty() && str[str.size() - 1] == ch; } bool startsWith(const std::string& str, const std::string& prefix, int pos/* = 0*/) { return str.size() >= prefix.size() && 0 == str.compare(pos, prefix.size(), prefix); } bool startsWith(const std::string& str, std::string::value_type ch) { return !str.empty() && str[0] == ch; } std::vector<std::string> split(const std::string& str, const std::string& delimiter) { std::vector<std::string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delimiter, prev); if (pos == std::string::npos) pos = str.length(); std::string token = str.substr(prev, pos-prev); if (!token.empty()) tokens.push_back(token); prev = pos + delimiter.length(); } while (pos < str.length() && prev < str.length()); return tokens; } std::string join(const std::vector<std::string>& elements, const char *const delimiter) { return join(std::cbegin(elements), std::cend(elements), delimiter); } std::string join(std::vector<std::string>::const_iterator b, std::vector<std::string>::const_iterator e, const char *const delimiter) { std::ostringstream os; if (b != e) { auto pe = prev(e); for (std::vector<std::string>::const_iterator it = b; it != pe; ++it) { os << *it; os << delimiter; } b = pe; } if (b != e) { os << *b; } return os.str(); } std::string safeHTML(const std::string& s) { static std::vector<std::pair<std::string, std::string>> replaces = { {"&", "&amp;"}, /*{" ", "&nbsp;"}, */{"<", "&lt;"}, {">", "&gt;"}, {"\r\n", "<br/>"}, {"\r", "<br/>"}, {"\n", "<br/>"} }; return replaceAll(s, replaces); } void removeHtmlTags(std::string& html) { std::string::size_type startpos = 0; while ((startpos = html.find("<", startpos)) != std::string::npos) { // auto startpos = html.find("<"); auto endpos = html.find(">", startpos + 1); if (endpos == std::string::npos) { break; } html.erase(startpos, endpos - startpos + 1); } } std::string removeCdata(const std::string& str) { if (startsWith(str, "<![CDATA[") && endsWith(str, "]]>")) return str.substr(9, str.size() - 12); return str; } std::string fromUnixTime(unsigned int unixtime, bool localTime/* = true*/) { std::time_t ts = unixtime; std::tm* t1 = std::localtime(&ts); if (!localTime) { std::time_t local_secs = std::mktime(t1); struct tm *t2 = gmtime(&ts); std::time_t gmt_secs = mktime(t2); ts -= gmt_secs - local_secs; t1 = std::localtime(&ts); } char buf[30] = { 0 }; std::strftime(buf, 30, "%Y-%m-%d %H:%M:%S", t1); // std::stringstream ss; // or if you're going to print, just input directly into the output stream // ss << std::put_time(t, "%Y-%m-%d %H:%M:%S"); return std::string(buf); } uint32_t getUnixTimeStamp() { time_t rawTime = 0; time(&rawTime); struct tm *localTm = localtime(&rawTime); return mktime(localTm); } /* bool existsFile(const std::string &path) { #ifdef _WIN32 struct stat buffer; CW2A pszA(CA2W(path.c_str(), CP_UTF8)); return (stat ((LPCSTR)pszA, &buffer) == 0); #else struct stat buffer; return (stat(path.c_str(), &buffer) == 0); #endif } */ /* int makePathImpl(const std::string::value_type *path, mode_t mode) { struct stat st; int status = 0; if (stat(path, &st) != 0) { // Directory does not exist. EEXIST for race condition if (mkdir(path, mode) != 0 && errno != EEXIST) status = -1; } else if (!S_ISDIR(st.st_mode)) { // errno = ENOTDIR; status = -1; } return status; } int makePath(const std::string& path, mode_t mode) { std::vector<std::string::value_type> copypath; copypath.reserve(path.size() + 1); std::copy(path.begin(), path.end(), std::back_inserter(copypath)); copypath.push_back('\0'); std::replace(copypath.begin(), copypath.end(), '\\', '/'); std::vector<std::string::value_type>::iterator itStart = copypath.begin(); std::vector<std::string::value_type>::iterator it; int status = 0; while (status == 0 && (it = std::find(itStart, copypath.end(), '/')) != copypath.end()) { if (it != copypath.begin()) { // Neither root nor double slash in path *it = '\0'; status = makePathImpl(&copypath[0], mode); *it = '/'; } itStart = it + 1; } if (status == 0) { status = makePathImpl(&copypath[0], mode); } return status; } */ /* bool moveFile(const std::string& src, const std::string& dest, bool overwrite) { #ifdef _WIN32 CW2T pszSrc(CA2W(src.c_str(), CP_UTF8)); CW2T pszDest(CA2W(dest.c_str(), CP_UTF8)); if (overwrite) { ::DeleteFile(pszDest); } BOOL bErrorFlag = ::MoveFile(pszSrc, pszDest); return (TRUE == bErrorFlag); #else if (overwrite) { remove(dest.c_str()); } return 0 == rename(src.c_str(), dest.c_str()); #endif } bool copyFile(const std::string& src, const std::string& dest) { #ifdef _WIN32 CW2T pszSrc(CA2W(src.c_str(), CP_UTF8)); CW2T pszDest(CA2W(dest.c_str(), CP_UTF8)); BOOL bErrorFlag = ::CopyFile(pszSrc, pszDest, FALSE); return (TRUE == bErrorFlag); #else std::ifstream ss(src, std::ios::binary); std::ofstream ds(dest, std::ios::binary); ds << ss.rdbuf(); return true; #endif } */ #ifdef _WIN32 std::string utf8ToLocalAnsi(const std::string& utf8Str) { CW2A pszA(CA2W(utf8Str.c_str(), CP_UTF8)); return std::string((LPCSTR)pszA); } #else #endif void updateFileTime(const std::string& path, time_t mtime) { #ifdef _WIN32 CW2T pszT(CA2W(path.c_str(), CP_UTF8)); struct _stat st; struct _utimbuf new_times; _tstat((LPCTSTR)pszT, &st); new_times.actime = st.st_atime; /* keep atime unchanged */ new_times.modtime = mtime; _tutime((LPCTSTR)pszT, &new_times); #else struct stat st; struct utimbuf new_times; stat(path.c_str(), &st); new_times.actime = st.st_atime; /* keep atime unchanged */ new_times.modtime = mtime; utime(path.c_str(), &new_times); #endif } /* bool deleteFile(const std::string& fileName) { return 0 == std::remove(fileName.c_str()); } */ int openSqlite3Database(const std::string& path, sqlite3 **ppDb, bool readOnly/* = true*/) { std::string sep(1, DIR_SEP); std::string encodedPath; #ifdef _WIN32 TCHAR szDriver[_MAX_DRIVE] = { 0 }; TCHAR szDir[_MAX_DIR] = { 0 }; CW2T pszT(CA2W(normalizePath(path).c_str(), CP_UTF8)); _tsplitpath(pszT, szDriver, szDir, NULL, NULL); size_t driveLen = _tcslen(szDriver); if (driveLen == 0) { // NO driver encodedPath = path; } else { CW2A pszU8(CT2W(&pszT[driveLen]), CP_UTF8); encodedPath = pszU8; } #else encodedPath = normalizePath(path); #endif std::vector<std::string> parts = split(encodedPath, sep); std::vector<std::string> encodedParts; encodedPath.reserve(parts.size() + 1); for (std::vector<std::string>::const_iterator it = parts.cbegin(); it != parts.cend(); ++it) { encodedParts.push_back(encodeUrl(*it)); } // curl_easy_cleanup(curl); encodedPath = join(encodedParts, sep.c_str()); #ifdef _WIN32 if (driveLen == 0) { if (_tcslen(szDir) > 0 && szDir[0] == DIR_SEP) { encodedPath = sep + encodedPath; } } else { CW2A pszU8(CT2W(szDriver), CP_UTF8); encodedPath = (LPCSTR)pszU8 + sep + encodedPath; } #else if (startsWith(path, sep)) { encodedPath = sep + encodedPath; } #endif #ifdef _WIN32 std::string pathWithQuery = "file:///" + encodedPath; #else std::string pathWithQuery = "file://" + encodedPath; #endif // std::string pathWithQuery = "file:" + path; pathWithQuery += readOnly ? "?immutable=1&mode=ro" : "?mode=rw"; // return sqlite3_open_v2(path.c_str(), ppDb, SQLITE_OPEN_READONLY, NULL); return sqlite3_open_v2(pathWithQuery.c_str(), ppDb, readOnly ? (SQLITE_OPEN_READONLY | SQLITE_OPEN_URI) : (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI), NULL); } bool isBigEndian() { short int number = 0x1; char *numPtr = (char*)&number; return (numPtr[0] != 1); } template<typename T> T swapEndian(T u) { union ET { T u; unsigned char u8[sizeof(T)]; } src, dest; src.u = u; for (size_t i = 0; i < sizeof(T); ++i) dest.u8[i] = src.u8[sizeof(T) - i - 1]; return dest.u; } int GetBigEndianInteger(const unsigned char* data, int startIndex/* = 0*/) { if (isBigEndian()) { return *((int *)(data + startIndex)); } #ifndef NDEBUG int aa = (data[startIndex] << 24) | (data[startIndex + 1] << 16) | (data[startIndex + 2] << 8) | data[startIndex + 3]; int bb = swapEndian(*((int *)(data + startIndex))); if (aa == bb) { aa = bb; } #endif return swapEndian(*((int *)&data[startIndex])); } int16_t bigEndianToNative(int16_t n) { return isBigEndian() ? n : swapEndian(n); } int32_t bigEndianToNative(int32_t n) { return isBigEndian() ? n : swapEndian(n); } int64_t bigEndianToNative(int64_t n) { return isBigEndian() ? n : swapEndian(n); } uint16_t bigEndianToNative(uint16_t n) { return isBigEndian() ? n : swapEndian(n); } uint32_t bigEndianToNative(uint32_t n) { return isBigEndian() ? n : swapEndian(n); } uint64_t bigEndianToNative(uint64_t n) { return isBigEndian() ? n : swapEndian(n); } int GetLittleEndianInteger(const unsigned char* data, int startIndex/* = 0*/) { return (data[startIndex + 3] << 24) | (data[startIndex + 2] << 16) | (data[startIndex + 1] << 8) | data[startIndex]; } std::string encodeUrl(const std::string& url) { std::string encodedUrl; #ifdef _WIN32 encodedUrl = url; CW2T szUrl(CA2W(url.c_str(), CP_UTF8)); LPTSTR lpOutputBuffer = new TCHAR[1]; DWORD dwSize = 1; HRESULT res = ::UrlEscape(szUrl, lpOutputBuffer, &dwSize, URL_ESCAPE_PERCENT | URL_ESCAPE_AS_UTF8); if (res == E_POINTER) { delete[] lpOutputBuffer; dwSize++; lpOutputBuffer = new TCHAR[dwSize]; lpOutputBuffer[dwSize - 1] = 0; res = ::UrlEscape(szUrl, lpOutputBuffer, &dwSize, URL_ESCAPE_PERCENT | URL_ESCAPE_AS_UTF8); if (SUCCEEDED(res)) { encodedUrl = CW2A(CT2W(lpOutputBuffer), CP_UTF8); } } if (lpOutputBuffer != NULL) { delete[] lpOutputBuffer; lpOutputBuffer = NULL; } #else #define IS_UNRESERVED(ch) (std::isalnum((char)ch) || ch == '-' || ch == '.' || ch == '_' || ch == '~') const std::string::value_type* const hex = "0123456789ABCDEF"; for (auto iter = url.begin(); iter != url.end(); ++iter) { // for utf8 encoded string, char ASCII can be greater than 127. int ch = static_cast<unsigned char>(*iter); // ch should be same under both utf8 and utf16. if (!IS_UNRESERVED(ch)) { encodedUrl.push_back('%'); encodedUrl.push_back(hex[(ch >> 4) & 0xF]); encodedUrl.push_back(hex[ch & 0xF]); } else { // ASCII don't need to be encoded, which should be same on both utf8 and utf16. encodedUrl.push_back(*iter); } } #ifndef NDEBUG /* std::string encodedUrl2; CURL *curl = curl_easy_init(); if(curl) { char *output = curl_easy_escape(curl, url.c_str(), static_cast<int>(url.size())); if(output) { encodedUrl2 = output; curl_free(output); } curl_easy_cleanup(curl); } assert(encodedUrl2 == encodedUrl); */ #endif #endif return encodedUrl; } std::string getTimestampString(bool includingYMD/* = false*/, bool includingMs/* = false*/) { using std::chrono::system_clock; auto currentTime = std::chrono::system_clock::now(); char buffer[80]; std::time_t tt; tt = system_clock::to_time_t ( currentTime ); auto timeinfo = localtime (&tt); strftime (buffer, 80, includingYMD ? "%F %H:%M:%S" : "%H:%M:%S", timeinfo); if (includingMs) { auto transformed = currentTime.time_since_epoch().count() / 1000000; auto millis = transformed % 1000; sprintf(buffer, "%s.%03d", buffer, (int)millis); } return std::string(buffer); } bool isNumber(const std::string &s) { return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit); }
25.365
181
0.576713
BlueMatthew
c72750f602073b391ea96f9d237851726eda7727
4,336
cpp
C++
radiation/cpp/src/explorer_lp.cpp
dfridovi/exploration
5e66115178988bd264a920041dfeab6d3539caec
[ "BSD-3-Clause" ]
5
2018-07-08T08:32:49.000Z
2022-03-13T10:17:09.000Z
radiation/cpp/src/explorer_lp.cpp
dfridovi/exploration
5e66115178988bd264a920041dfeab6d3539caec
[ "BSD-3-Clause" ]
5
2016-11-30T02:52:58.000Z
2018-05-24T04:46:49.000Z
radiation/cpp/src/explorer_lp.cpp
dfridovi/exploration
5e66115178988bd264a920041dfeab6d3539caec
[ "BSD-3-Clause" ]
2
2016-12-01T04:06:40.000Z
2019-06-19T16:32:28.000Z
/* * Copyright (c) 2015, The Regents of the University of California (Regents). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Please contact the author(s) of this library if you have any questions. * Author: David Fridovich-Keil ( dfk@eecs.berkeley.edu ) */ /////////////////////////////////////////////////////////////////////////////// // // Exploration on a 2D grid. Tries to find the specified number of radiation // sources (located at random lattice points) by choosing trajectories of // the specified number of steps that maximize mutual information between // simulated measurements and the true map. // /////////////////////////////////////////////////////////////////////////////// #include <explorer_lp.h> #include <glog/logging.h> #include <random> #include <string> #include <math.h> namespace radiation { // Constructor/destructor. ExplorerLP::~ExplorerLP() {} ExplorerLP::ExplorerLP(unsigned int num_rows, unsigned int num_cols, unsigned int num_sources, double regularizer, unsigned int num_steps, double fov, unsigned int num_samples, const std::vector<Source2D>& sources, const GridPose2D& initial_pose) : Explorer2D(num_rows, num_cols, num_sources, regularizer, fov, sources, initial_pose), num_steps_(num_steps), num_samples_(num_samples) {} ExplorerLP::ExplorerLP(unsigned int num_rows, unsigned int num_cols, unsigned int num_sources, double regularizer, unsigned int num_steps, double fov, unsigned int num_samples) : Explorer2D(num_rows, num_cols, num_sources, regularizer, fov), num_steps_(num_steps), num_samples_(num_samples) {} // Plan a new trajectory. bool ExplorerLP::PlanAhead(std::vector<GridPose2D>& trajectory) { // Generate conditional entropy vector. Eigen::VectorXd hzx; std::vector<unsigned int> trajectory_ids; map_.GenerateEntropyVector(num_samples_, num_steps_, pose_, fov_, hzx, trajectory_ids); CHECK(hzx.rows() == trajectory_ids.size()); // Compute the arg max of this conditional entropy vector. double max_value = -1.0; unsigned int trajectory_id = 0; for (unsigned int ii = 0; ii < hzx.rows(); ii++) { if (hzx(ii) > max_value) { max_value = hzx(ii); trajectory_id = trajectory_ids[ii]; } } // Check that we found a valid trajectory (with non-negative entropy). if (max_value < 0.0) { VLOG(1) << "Could not find a positive conditional entropy trajectory."; return false; } // Decode this trajectory id. trajectory.clear(); DecodeTrajectory(trajectory_id, num_steps_, pose_, trajectory); return true; } } // namespace radiation
40.148148
79
0.675969
dfridovi
d17703ec69b9fc6ccbe5af7df0e6d0b9c75a85fa
2,918
hpp
C++
Safety/Libraries/Drivers/Inc/PPM.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
15
2017-09-12T14:54:16.000Z
2021-09-21T23:28:57.000Z
Safety/Libraries/Drivers/Inc/PPM.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
67
2017-10-31T02:04:44.000Z
2022-03-28T01:02:25.000Z
Safety/Libraries/Drivers/Inc/PPM.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
48
2017-09-28T23:47:17.000Z
2022-01-08T18:30:40.000Z
/** * Implements PPM driver. Support variable PPM, where the input can be * from 8-12 channels. Note that the assumption is that we're going to be * reading signals that range from 1-2ms. If you're trying to read outside of this range, * modify the prescaler in the implementation, as we may get a timer overflow or get really bad precision! * Its fine if the signals we're reading are around the same ranges however, like 800us to 2200us. In that case * just modify the setLimits() so the percentages received are correct * @author Serj Babayan * @copyright Waterloo Aerial Robotics Group 2019 * https://raw.githubusercontent.com/UWARG/ZeroPilot-SW/devel/LICENSE.md * * Hardware Info: * * Timer14 - PPM * PPM PIN - B1 */ #include <stdint.h> #include "GPIO.hpp" #include "PWM.hpp" static const int32_t MAX_PPM_CHANNELS = 12; class PPMChannel { public: /** * How many channels are we expecting in the input port? * Usually this is only 8 * @param num_channels * @param disconnect_timeout Number of ms to wait before we consider channel disconnected */ explicit PPMChannel(uint8_t num_channels = 8, uint32_t disconnect_timeout = 1000); /** * Reconfigure number of channels * @param num_channels */ StatusCode setNumChannels(uint8_t num_channels); /** * Set expected input limits for a particular channel * @param channel * @param min Min time in us (for a 0% signal) * @param max Max time in us (for 100% signal) * @param deadzone time in us for deadzone. ie. if deadzone is set to 50, a signal that is received * with a 1050us length will still be considered 0% */ StatusCode setLimits(uint8_t channel, uint32_t min, uint32_t max, uint32_t deadzone); /** * Set the disconnect timeout * @param timeout * @return */ StatusCode setTimeout(uint32_t timeout); /** * Setup timer14 with interrupts, gpios, etc.. * @return */ StatusCode setup(); /** * Reset all pins to their default state. Stop the timer and interrupts * @return */ StatusCode reset(); /** * Returns a percent value that was most recently received from the PPM channel, as a percentage * from 0-100 * @param num * @return 0 if an invalid channel number was given */ uint8_t get(PWMChannelNum num); /** * Same as above function, but returns the captured value in microseconds instead * @param num * @return 0 if an invalid channel number was given */ uint32_t get_us(PWMChannelNum num); /** * Wether the channel has disconnected based on the timeout * @param sys_time Current system time in ms * @return */ bool is_disconnected(uint32_t sys_time); private: int32_t deadzones[MAX_PPM_CHANNELS]; int32_t min_values[MAX_PPM_CHANNELS]; //stores min tick values for each channel int32_t max_values[MAX_PPM_CHANNELS]; //stores max tick values for each channel uint32_t disconnect_timeout; bool is_setup = false; GPIOPin ppm_pin; };
29.77551
111
0.724469
YashrajN
d17790213d15384333e2034a51d74f3a7bb35eb6
16,201
cc
C++
third_party/mcpat/cacti/highradix.cc
s-kanev/XIOSim
9673bbd15ba72c9cce15243a462bffb5d9ded9ae
[ "BSD-3-Clause" ]
55
2015-05-29T19:59:33.000Z
2022-02-08T03:08:15.000Z
third_party/mcpat/cacti/highradix.cc
s-kanev/XIOSim
9673bbd15ba72c9cce15243a462bffb5d9ded9ae
[ "BSD-3-Clause" ]
1
2015-04-03T04:40:26.000Z
2015-04-03T04:40:26.000Z
third_party/mcpat/cacti/highradix.cc
s-kanev/XIOSim
9673bbd15ba72c9cce15243a462bffb5d9ded9ae
[ "BSD-3-Clause" ]
7
2015-04-03T00:28:32.000Z
2018-09-01T20:53:58.000Z
/*------------------------------------------------------------ * CACTI 6.5 * Copyright 2008 Hewlett-Packard Development Corporation * All Rights Reserved * * Permission to use, copy, and modify this software and its documentation is * hereby granted only under the following terms and conditions. Both the * above copyright notice and this permission notice must appear in all copies * of the software, derivative works or modified versions, and any portions * thereof, and both notices must appear in supporting documentation. * * Users of this software agree to the terms and conditions set forth herein, and * hereby grant back to Hewlett-Packard Company and its affiliated companies ("HP") * a non-exclusive, unrestricted, royalty-free right and license under any changes, * enhancements or extensions made to the core functions of the software, including * but not limited to those affording compatibility with other hardware or software * environments, but excluding applications which incorporate this software. * Users further agree to use their best efforts to return to HP any such changes, * enhancements or extensions that they make and inform HP of noteworthy uses of * this software. Correspondence should be provided to HP at: * * Director of Intellectual Property Licensing * Office of Strategy and Technology * Hewlett-Packard Company * 1501 Page Mill Road * Palo Alto, California 94304 * * This software may be distributed (but not offered for sale or transferred * for compensation) to third parties, provided such third parties agree to * abide by the terms and conditions of this notice. * * THE SOFTWARE IS PROVIDED "AS IS" AND HP DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL HP * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. *------------------------------------------------------------*/ #include "highradix.h" #include <iomanip> using namespace std; #define MAX_WIRE_SCALE 1 HighRadix::HighRadix( double SUB_SWITCH_SZ_, double ROWS_, double FREQUENCY_, // GHz double RADIX_, double VC_COUNT_, double FLIT_SZ_, double AF_,// activity factor double DIE_LEN_,//u double DIE_HT_,//u double INP_BUFF_ENT_, double ROW_BUFF_ENT_, double COL_BUFF_ENT_, TechnologyParameter::DeviceType *dt ):SUB_SWITCH_SZ(SUB_SWITCH_SZ_), ROWS(ROWS_), FREQUENCY(FREQUENCY_), RADIX(RADIX_), VC_COUNT(VC_COUNT_), FLIT_SZ(FLIT_SZ_), AF(AF_), DIE_LEN(DIE_LEN_), DIE_HT(DIE_HT_), INP_BUFF_ENT(INP_BUFF_ENT_), ROW_BUFF_ENT(ROW_BUFF_ENT_), COL_BUFF_ENT(COL_BUFF_ENT_), deviceType(dt) { double area_scale=1; double tech_init = 90; if (g_ip->F_sz_nm == 65) { area_scale*=1; } else if(g_ip->F_sz_nm == 45) { area_scale*=1; } else if(g_ip->F_sz_nm == 32) { area_scale*=2; } DIE_LEN = sqrt(DIE_LEN_*DIE_HT_/area_scale); DIE_HT = DIE_LEN; COLUMNS = pow(RADIX/SUB_SWITCH_SZ, 2)/ROWS; INP_BUFF_SZ = FLIT_SZ * INP_BUFF_ENT; ROW_BUFF_SZ = ROW_BUFF_ENT * FLIT_SZ; COL_BUFF_SZ = COL_BUFF_ENT * FLIT_SZ; area.set_area(0); } void HighRadix::compute_power() { num_sub = ROWS * COLUMNS; //FIXME change cb power to per input double scale = 1; while (true) { Wire winit(scale, scale); cb = new Crossbar(SUB_SWITCH_SZ, SUB_SWITCH_SZ, FLIT_SZ); cb->compute_power(); if (cb->delay*1e12 < (1/FREQUENCY)*(1e3)) break; else { scale+=0.2; if (scale > MAX_WIRE_SCALE) break; cout << "scale = " << scale << endl; } } cb->power.readOp.dynamic /= SUB_SWITCH_SZ; // crossbar power per message scale = 1; while (true) { Wire winit(scale, scale); out_cb = new Crossbar(1, SUB_SWITCH_SZ, FLIT_SZ); out_cb->compute_power(); if (out_cb->delay*1e12 < (1/FREQUENCY)*(1e3)) break; else { scale+=0.2; if (scale > MAX_WIRE_SCALE) break; cout << "scale = " << scale << endl; } } Wire winit; out_cb->power.readOp.dynamic /= SUB_SWITCH_SZ; // power per message //arbiter initialization vc_arb = new Arbiter(VC_COUNT, FLIT_SZ, cb->area.w); vc_arb->compute_power(); c_arb = new Arbiter(COLUMNS, FLIT_SZ, cb->area.w); c_arb->compute_power(); cb_arb = new Arbiter(RADIX/ROWS, FLIT_SZ, cb->area.w); cb_arb->compute_power(); // input buffer, row/column buffer initialization inp_buff = buffer_(FLIT_SZ, INP_BUFF_SZ); c_buff = buffer_(FLIT_SZ, COL_BUFF_SZ*2); r_buff = buffer_(FLIT_SZ, ROW_BUFF_SZ*2); // repeated wire initialization hor_bus = new Wire(g_ip->wt, DIE_LEN); // effective ht of vertical bus (connecting cb to column buffer) in each sub-switch double eff_ht = (ROWS * (ROWS +1)/2) * (DIE_HT/ROWS); ver_bus = new Wire(g_ip->wt, eff_ht); // sub switch includes row buffers, column buffers, vc/crossbar/column arbitration and a 2 stage crossbar traversal sub_switch_power(); power.readOp.dynamic += sub_sw.power.readOp.dynamic * num_sub; power.readOp.leakage += sub_sw.power.readOp.leakage * num_sub; // input buffer power power.readOp.dynamic += 2 /*r&w*/ * inp_buff->power.readOp.dynamic * RADIX; power.readOp.leakage += inp_buff->power.readOp.leakage * RADIX; // buses power.readOp.dynamic += hor_bus->power.readOp.dynamic * FLIT_SZ * SUB_SWITCH_SZ * ROWS; power.readOp.leakage += hor_bus->power.readOp.leakage * FLIT_SZ * SUB_SWITCH_SZ * ROWS; power.readOp.dynamic += ver_bus->power.readOp.dynamic * FLIT_SZ * COLUMNS * SUB_SWITCH_SZ; power.readOp.leakage += ver_bus->power.readOp.leakage * FLIT_SZ * ROWS * COLUMNS * SUB_SWITCH_SZ; // To calculate contribution of each component to the total power compute_crossbar_power(); compute_bus_power(); compute_arb_power(); compute_buff_power(); //area sub_sw.area.set_area(sub_sw.area.get_area() + cb->area.get_area()); sub_sw.area.set_area(sub_sw.area.get_area() + out_cb->area.get_area()); sub_sw.area.set_area(sub_sw.area.get_area() + r_buff->area.get_area() * VC_COUNT * SUB_SWITCH_SZ); sub_sw.area.set_area(sub_sw.area.get_area() + c_buff->area.get_area() * VC_COUNT * SUB_SWITCH_SZ); buff_tot.area.set_area(buff_tot.area.get_area() + inp_buff->area.get_area() * RADIX); buff_tot.area.set_area(buff_tot.area.get_area() + VC_COUNT * r_buff->area.get_area() * SUB_SWITCH_SZ * num_sub); buff_tot.area.set_area(buff_tot.area.get_area() + VC_COUNT * c_buff->area.get_area() * SUB_SWITCH_SZ * num_sub); crossbar_tot.area.set_area(crossbar_tot.area.get_area() + cb->area.get_area() * num_sub); crossbar_tot.area.set_area(crossbar_tot.area.get_area() + out_cb->area.get_area() * num_sub); wire_tot.area.set_area(hor_bus->area.get_area() * FLIT_SZ * SUB_SWITCH_SZ * ROWS); wire_tot.area.set_area(ver_bus->area.get_area() * FLIT_SZ * ROWS * COLUMNS); } void HighRadix::compute_crossbar_power() { crossbar_tot.power = cb->power; crossbar_tot.power = crossbar_tot.power + out_cb->power; crossbar_tot.power.readOp.dynamic *= num_sub; crossbar_tot.power.readOp.leakage *= num_sub; } void HighRadix::compute_bus_power() { wire_tot.power.readOp.dynamic = hor_bus->power.readOp.dynamic * FLIT_SZ * SUB_SWITCH_SZ * ROWS; wire_tot.power.readOp.leakage = hor_bus->power.readOp.leakage * FLIT_SZ * SUB_SWITCH_SZ * ROWS; wire_tot.power.readOp.dynamic += ver_bus->power.readOp.dynamic * FLIT_SZ * COLUMNS * SUB_SWITCH_SZ; wire_tot.power.readOp.leakage += ver_bus->power.readOp.leakage * FLIT_SZ * ROWS * COLUMNS * SUB_SWITCH_SZ; } void HighRadix::compute_arb_power() { arb_tot.power = cb_arb->power; arb_tot.power = arb_tot.power + vc_arb->power; // for CB traversal arb_tot.power = arb_tot.power + c_arb->power; arb_tot.power = arb_tot.power + vc_arb->power; // to the o/p port arb_tot.power.readOp.dynamic *= num_sub; arb_tot.power.readOp.leakage *= num_sub; } void HighRadix::compute_buff_power() { //input buffer read/write buff_tot.power.readOp.dynamic = 2 * inp_buff->power.readOp.dynamic * RADIX; buff_tot.power.readOp.leakage = inp_buff->power.readOp.leakage * RADIX; //row buffer read/write buff_tot.power.readOp.dynamic += r_buff->power.readOp.dynamic * 2 * num_sub; buff_tot.power.readOp.leakage += r_buff->power.readOp.leakage * num_sub; //column buffer read/write buff_tot.power.readOp.dynamic += c_buff->power.readOp.dynamic * 2 * num_sub; buff_tot.power.readOp.leakage += c_buff->power.readOp.leakage * num_sub; } void HighRadix::sub_switch_power() { // each sub-switch power sub_sw.power.readOp.dynamic = sub_sw.power.readOp.dynamic + r_buff->power.readOp.dynamic * 2 /* one read and one write */ * VC_COUNT; sub_sw.power.readOp.leakage = sub_sw.power.readOp.leakage + r_buff->power.readOp.leakage * VC_COUNT; sub_sw.power = sub_sw.power + cb->power; sub_sw.power.readOp.dynamic = sub_sw.power.readOp.dynamic + 2 * c_buff->power.readOp.dynamic /* one read and one write */ * VC_COUNT; sub_sw.power.readOp.leakage = sub_sw.power.readOp.leakage + c_buff->power.readOp.leakage * VC_COUNT; sub_sw.power = sub_sw.power + out_cb->power; // arbiter power sub_sw.power = sub_sw.power + cb_arb->power; sub_sw.power = sub_sw.power + vc_arb->power; // for CB traversal sub_sw.power = sub_sw.power + c_arb->power; sub_sw.power = sub_sw.power + vc_arb->power; // to the o/p port } HighRadix::~HighRadix() { delete inp_buff; delete r_buff; delete c_buff; delete c_arb; delete cb_arb; delete vc_arb; delete out_cb; } Mat * HighRadix::buffer_(double block_sz, double sz) { DynamicParameter dyn_p; dyn_p.is_tag = false; dyn_p.num_subarrays = 1; dyn_p.num_mats = 1; dyn_p.Ndbl = 1; dyn_p.Ndwl = 1; dyn_p.Nspd = 1; dyn_p.deg_bl_muxing = 1; dyn_p.deg_senseamp_muxing_non_associativity = 1; dyn_p.Ndsam_lev_1 = 1; dyn_p.Ndsam_lev_2 = 1; dyn_p.number_addr_bits_mat = 8; dyn_p.number_way_select_signals_mat = 1; dyn_p.num_act_mats_hor_dir = 1; dyn_p.is_dram = false; dyn_p.V_b_sense = deviceType->Vdd; // FIXME check power calc. dyn_p.ram_cell_tech_type = dyn_p.num_r_subarray = (int) (sz/block_sz); dyn_p.num_c_subarray = (int) block_sz; dyn_p.num_mats_h_dir = 1; dyn_p.num_mats_v_dir = 1; dyn_p.num_do_b_subbank = (int)block_sz; dyn_p.num_do_b_mat = (int) block_sz; dyn_p.num_di_b_mat = (int) block_sz; dyn_p.use_inp_params = 1; dyn_p.num_wr_ports = 1; dyn_p.num_rd_ports = 1; dyn_p.num_rw_ports = 0; dyn_p.num_se_rd_ports =0; dyn_p.out_w = (int) block_sz; dyn_p.cell.h = g_tp.sram.b_h + 2 * g_tp.wire_outside_mat.pitch * (dyn_p.num_wr_ports + dyn_p.num_rw_ports - 1 + dyn_p.num_rd_ports); dyn_p.cell.w = g_tp.sram.b_w + 2 * g_tp.wire_outside_mat.pitch * (dyn_p.num_rw_ports - 1 + (dyn_p.num_rd_ports - dyn_p.num_se_rd_ports) + dyn_p.num_wr_ports) + g_tp.wire_outside_mat.pitch * dyn_p.num_se_rd_ports; Mat *buff = new Mat(dyn_p); buff->compute_delays(0); buff->compute_power_energy(); return buff; } void HighRadix::print_buffer(Component *c) { // cout << "\tDelay - " << c->delay * 1e6 << " ns" << endl; cout << "\tDynamic Power - " << c->power.readOp.dynamic*1e9 << " nJ" << endl; cout << "\tLeakage Power - " << c->power.readOp.leakage*1e3 << " mW" << endl; cout << "\tWidth - " << c->area.w << " u" << endl; cout << "\tLength - " << c->area.h << " u" << endl; } void HighRadix::print_router() { cout << "\n\nRouter stats:\n"; cout << "\tNetwork frequency - " << FREQUENCY <<" GHz\n"; cout << "\tNo. of Virtual channels - " << VC_COUNT << "\n"; cout << "\tSub-switch size - " << (int)SUB_SWITCH_SZ << endl; cout << "\tNo. of rows - " << (int)ROWS << endl; cb->print_crossbar(); out_cb->print_crossbar(); vc_arb->print_arbiter(); c_arb->print_arbiter(); cb_arb->print_arbiter(); // hor_bus->print_wire(); cout << "\n\nBuffer stats:\n"; cout << "\nInput Buffer stats:\n"; print_buffer (inp_buff); cout << "\nRow Buffer stats:\n"; print_buffer (r_buff); cout << "\nColumn Buffer stats:\n"; print_buffer (c_buff); cout << "\n\n Router dynamic power (max) = " << power.readOp.dynamic * FREQUENCY * 1e9 << " W\n"; cout << " Router dynamic power (load - " << AF << ") = " << power.readOp.dynamic * FREQUENCY * 1e9 * AF << " W\n"; cout << "\n\nDetailed Stats\n"; cout << "--------------\n"; cout << "Power dissipated in buses/wires - " << setprecision(3) << wire_tot.power.readOp.dynamic * FREQUENCY * 1e9 << " W"; cout << "\t" <<setiosflags(ios::fixed) << setprecision(2) << (wire_tot.power.readOp.dynamic/power.readOp.dynamic)*100 << " %\n"; cout << "Buffer power - " << buff_tot.power.readOp.dynamic * FREQUENCY * 1e9 << " W"; cout << "\t" << (buff_tot.power.readOp.dynamic/power.readOp.dynamic)*100 << " %\n"; cout << "Crossbar power - " << crossbar_tot.power.readOp.dynamic * FREQUENCY * 1e9 << " W"; cout << "\t" << (crossbar_tot.power.readOp.dynamic/power.readOp.dynamic)*100 << " %\n"; cout << "Arbiter power - " << arb_tot.power.readOp.dynamic * FREQUENCY * 1e9 << " W"; cout << "\t" << (arb_tot.power.readOp.dynamic/power.readOp.dynamic)*100 << " %\n"; cout << "Sub-switch power (dynamic) - " << sub_sw.power.readOp.dynamic * num_sub * FREQUENCY * 1e9 << " W"; cout << "\t" << (sub_sw.power.readOp.dynamic * num_sub/power.readOp.dynamic)*100 << " %\n"; cout << "Input buffer power (dynamic) - " << 2 * inp_buff->power.readOp.dynamic * RADIX * FREQUENCY * 1e9 << " W"; cout << "\t" << (2 * inp_buff->power.readOp.dynamic * RADIX/power.readOp.dynamic)*100 << " %\n"; cout << "\nLeakage power\n"; cout << "Router power - " << power.readOp.leakage << " W\n"; cout << "Bus power - " <<setprecision(4) << wire_tot.power.readOp.leakage << " W\n"; cout << "Buffer power - " << buff_tot.power.readOp.leakage << " W\n"; cout << "Crossbar power - " << crossbar_tot.power.readOp.leakage << " W\n"; cout << "Arbiter power - " << arb_tot.power.readOp.leakage << " W\n"; cout << "Sub-switch power - " << sub_sw.power.readOp.leakage << " W" <<endl; cout << "\n\nArea Stats\n"; cout << "Input buffer dimension (mm x mm)- " << inp_buff->area.get_h()*1e-3 << " x " << inp_buff->area.get_w()*1e-3 << endl; cout << "Row buffer (mm x mm) - " << r_buff->area.w*1e-3 << " x " << r_buff->area.h*1e-3 << endl; cout << "Col buffer (mm x mm) - " << c_buff->area.w*1e-3 << " x " << c_buff->area.h*1e-3 << endl; cout << "Crossbar area (mm x mm) - " << cb->area.w*1e-3 << " x " << cb->area.h*1e-3 << endl; // cout << "Wire hor area (nm x nm) - " << hor_bus->area.w*1e3 << " x " << hor_bus->area.h*1e3 << endl; // cout << "Wire ver area (nm x nm) - " << ver_bus->area.w*1e3 << " x " << ver_bus->area.h*1e3 << endl; cout << "Wire total - " << wire_tot.area.get_area()*1e-6 << " mm2\n"; cout << "Crossbar total - " << crossbar_tot.area.get_area()*1e-6 << " mm2\n"; cout << "Buff total - " << buff_tot.area.get_area()*1e-6 << " mm2\n"; cout << "Subswitch - " << sub_sw.area.get_area()*1e-6 << " mm2\n"; cout << "Subswitch total - " << sub_sw.area.get_area()*num_sub*1e-6 << " mm2\n"; cout << "Total area - " << (wire_tot.area.get_area() + crossbar_tot.area.get_area() + buff_tot.area.get_area())*1e-6 << endl; }
41.223919
126
0.645639
s-kanev
d17ab0648db2690e2ef9a65a32161d0fb946cb54
8,024
cpp
C++
be/src/runtime/export_task_mgr.cpp
mengqinghuan/Doris
c0cccb27c966821f630400ad8d19f49a59bc582c
[ "Apache-2.0" ]
1
2017-08-10T13:14:50.000Z
2017-08-10T13:14:50.000Z
be/src/runtime/export_task_mgr.cpp
rinack/palo
fb64a1a8e8ed612cd95d1ea0c67bf70804a1d2da
[ "Apache-2.0" ]
null
null
null
be/src/runtime/export_task_mgr.cpp
rinack/palo
fb64a1a8e8ed612cd95d1ea0c67bf70804a1d2da
[ "Apache-2.0" ]
1
2021-07-21T03:05:40.000Z
2021-07-21T03:05:40.000Z
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved // 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 "runtime/export_task_mgr.h" #include "runtime/exec_env.h" #include "runtime/fragment_mgr.h" #include "runtime/plan_fragment_executor.h" #include "runtime/runtime_state.h" #include "gen_cpp/FrontendService.h" #include "gen_cpp/BackendService.h" #include "gen_cpp/HeartbeatService_types.h" #include "gen_cpp/MasterService_types.h" namespace palo { #define VLOG_EXPORT VLOG(2) static size_t LRU_MAX_CASH_TASK_NUM = 1000; ExportTaskMgr::ExportTaskMgr(ExecEnv* exec_env) : _exec_env(exec_env), _success_tasks(LRU_MAX_CASH_TASK_NUM), _failed_tasks(LRU_MAX_CASH_TASK_NUM) { } ExportTaskMgr::~ExportTaskMgr() { } Status ExportTaskMgr::init() { return Status::OK; } Status ExportTaskMgr::start_task(const TExportTaskRequest& request) { const TUniqueId& id = request.params.params.fragment_instance_id; std::lock_guard<std::mutex> l(_lock); auto it = _running_tasks.find(id); if (it != _running_tasks.end()) { // Already have this task, return what??? LOG(INFO) << "Duplicated export task(" << id << ")"; return Status::OK; } // If already success, we return Status::OK // and wait master ask me success information if (_success_tasks.exists(id)) { // Already success LOG(INFO) << "Already successful export task(" << id << ")"; return Status::OK; } RETURN_IF_ERROR(_exec_env->fragment_mgr()->exec_plan_fragment( request.params, std::bind<void>(&ExportTaskMgr::finalize_task, this, std::placeholders::_1))); // redo this task if failed before if (_failed_tasks.exists(id)) { _failed_tasks.erase(id); } VLOG_EXPORT << "accept one export Task. id=" << id; _running_tasks.insert(id); return Status::OK; } Status ExportTaskMgr::cancel_task(const TUniqueId& id) { std::lock_guard<std::mutex> l(_lock); auto it = _running_tasks.find(id); if (it == _running_tasks.end()) { // Nothing to do LOG(INFO) << "No such export task id, just print to info " << id; return Status::OK; } _running_tasks.erase(it); VLOG_EXPORT << "task id(" << id << ") have been removed from ExportTaskMgr."; ExportTaskCtx ctx; ctx.status = Status::CANCELLED; _failed_tasks.put(id, ctx); return Status::OK; } Status ExportTaskMgr::erase_task(const TUniqueId& id) { std::lock_guard<std::mutex> l(_lock); auto it = _running_tasks.find(id); if (it != _running_tasks.end()) { std::stringstream ss; ss << "Task(" << id << ") is running, can not be deleted."; return Status(ss.str()); } _success_tasks.erase(id); _failed_tasks.erase(id); return Status::OK; } void ExportTaskMgr::finalize_task(PlanFragmentExecutor* executor) { ExportTaskResult result; RuntimeState* state = executor->runtime_state(); if (executor->status().ok()) { result.files = state->export_output_files(); } finish_task(state->fragment_instance_id(), executor->status(), result); // Try to report this finished task to master report_to_master(executor); } Status ExportTaskMgr::finish_task(const TUniqueId& id, const Status& status, const ExportTaskResult& result) { std::lock_guard<std::mutex> l(_lock); auto it = _running_tasks.find(id); if (it == _running_tasks.end()) { std::stringstream ss; ss << "Unknown task id(" << id << ")."; return Status(ss.str()); } _running_tasks.erase(it); ExportTaskCtx ctx; ctx.status = status; ctx.result = result; if (status.ok()) { _success_tasks.put(id, ctx); } else { _failed_tasks.put(id, ctx); } VLOG_EXPORT << "Move task(" << id << ") from running to " << (status.ok() ? "success tasks" : "failed tasks"); return Status::OK; } Status ExportTaskMgr::get_task_state(const TUniqueId& id, TExportStatusResult* result) { std::lock_guard<std::mutex> l(_lock); auto it = _running_tasks.find(id); if (it != _running_tasks.end()) { result->status.__set_status_code(TStatusCode::OK); result->__set_state(TExportState::RUNNING); return Status::OK; } // Successful if (_success_tasks.exists(id)) { ExportTaskCtx ctx; _success_tasks.get(id, &ctx); result->status.__set_status_code(TStatusCode::OK); result->__set_state(TExportState::FINISHED); result->__set_files(ctx.result.files); return Status::OK; } // failed information if (_failed_tasks.exists(id)) { ExportTaskCtx ctx; _success_tasks.get(id, &ctx); result->status.__set_status_code(TStatusCode::OK); result->__set_state(TExportState::CANCELLED); return Status::OK; } // NO this task result->status.__set_status_code(TStatusCode::OK); result->__set_state(TExportState::CANCELLED); return Status::OK; } void ExportTaskMgr::report_to_master(PlanFragmentExecutor* executor) { TUpdateExportTaskStatusRequest request; RuntimeState* state = executor->runtime_state(); request.protocolVersion = FrontendServiceVersion::V1; request.taskId = state->fragment_instance_id(); Status status = get_task_state(state->fragment_instance_id(), &request.taskStatus); if (!status.ok()) { return; } const TNetworkAddress& master_address = _exec_env->master_info()->network_address; FrontendServiceConnection client( _exec_env->frontend_client_cache(), master_address, 500, &status); if (!status.ok()) { std::stringstream ss; ss << "Connect master failed, with address(" << master_address.hostname << ":" << master_address.port << ")"; LOG(WARNING) << ss.str(); return ; } VLOG_ROW << "export updateExportTaskStatus. request is " << apache::thrift::ThriftDebugString(request).c_str(); TFeResult res; try { try { client->updateExportTaskStatus(res, request); } catch (apache::thrift::transport::TTransportException& e) { LOG(WARNING) << "Retrying report export tasks status to master(" << master_address.hostname << ":" << master_address.port << ") because: " << e.what(); status = client.reopen(500); if (!status.ok()) { LOG(WARNING) << "Client repoen failed. with address(" << master_address.hostname << ":" << master_address.port << ")"; return ; } client->updateExportTaskStatus(res, request); } } catch (apache::thrift::TException& e) { // failed when retry. std::stringstream ss; ss << "Fail to report export task to master(" << master_address.hostname << ":" << master_address.port << "). reason: " << e.what(); LOG(WARNING) << ss.str(); } LOG(INFO) << "Successfully report elt task status to master." << " id=" << print_id(request.taskId); } } // end namespace palo
33.020576
90
0.637961
mengqinghuan
d17fd6d9180a3debe969e442111c13bb948ef421
9,853
cpp
C++
Src/Core/DeviceBridge.cpp
chowdaryd/C3
118a35f88d0cf3ca526af5052b1140f1b7d3ff4b
[ "BSD-3-Clause" ]
null
null
null
Src/Core/DeviceBridge.cpp
chowdaryd/C3
118a35f88d0cf3ca526af5052b1140f1b7d3ff4b
[ "BSD-3-Clause" ]
1
2020-05-05T21:25:16.000Z
2020-05-05T21:25:16.000Z
Src/Core/DeviceBridge.cpp
CX-4/C3
da84536f229999fb5cba43fe7d983dcc8f80b830
[ "BSD-3-Clause" ]
null
null
null
#include "StdAfx.h" #include "DeviceBridge.h" #include "Relay.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::C3::Core::DeviceBridge::DeviceBridge(std::shared_ptr<Relay>&& relay, DeviceId did, HashT typeNameHash, std::shared_ptr<Device>&& device, bool isNegotiationChannel, bool isSlave, ByteVector args /*= ByteVector()*/) : m_IsNegotiationChannel(isNegotiationChannel) , m_IsSlave(isSlave) , m_Did{ did } , m_TypeNameHash(typeNameHash) , m_Relay{ relay } , m_Device{ std::move(device) } { if (!isNegotiationChannel) return; auto readView = ByteView{ args }; std::tie(m_InputId, m_OutpuId) = readView.Read<ByteVector, ByteVector>(); m_NonNegotiatiedArguments = readView; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::OnAttach() { GetDevice()->OnAttach(shared_from_this()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::Detach() { m_IsAlive = false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::Close() { auto relay = GetRelay(); relay->DetachDevice(GetDid()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::OnReceive() { GetDevice()->OnReceive(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::PassNetworkPacket(ByteView packet) { if (m_IsNegotiationChannel && !m_IsSlave) // negotiation channel does not support chunking. Just pass packet and leave. return GetRelay()->OnPacketReceived(packet, shared_from_this()); m_QoS.PushReceivedChunk(packet); auto nextPacket = m_QoS.GetNextPacket(); if (!nextPacket.empty()) GetRelay()->OnPacketReceived(nextPacket, shared_from_this()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::OnPassNetworkPacket(ByteView packet) { auto lock = std::lock_guard<std::mutex>{ m_ProtectWriteInConcurrentThreads }; if (m_IsNegotiationChannel) // negotiation channel does not support chunking. Just pass packet and leave. { auto sent = GetDevice()->OnSendToChannelInternal(packet); if (sent != packet.size()) throw std::runtime_error{OBF("Negotiation channel does not support chunking. Packet size: ") + std::to_string(packet.size()) + OBF(" Channel sent: ") + std::to_string(sent)}; return; } auto oryginalSize = static_cast<uint32_t>(packet.size()); auto messageId = m_QoS.GetOutgouingPacketId(); uint32_t chunkId = 0u; while (!packet.empty()) { auto data = ByteVector{}.Write(messageId, chunkId, oryginalSize).Concat(packet); auto sent = GetDevice()->OnSendToChannelInternal(data); if (sent >= QualityOfService::s_MinFrameSize || sent == data.size()) // if this condition were not channel must resend data. { chunkId++; packet.remove_prefix(sent - QualityOfService::s_HeaderSize); } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::PostCommandToConnector(ByteView packet) { GetRelay()->PostCommandToConnector(packet, shared_from_this()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::OnCommandFromConnector(ByteView command) { auto lock = std::lock_guard<std::mutex>{ m_ProtectWriteInConcurrentThreads }; GetDevice()->OnCommandFromConnector(command); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::C3::Core::DeviceBridge::RunCommand(ByteView command) { return GetDevice()->OnRunCommand(command); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::ByteVector FSecure::C3::Core::DeviceBridge::WhoAreYou() { return GetDevice()->OnWhoAmI(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::Log(LogMessage const& message) { GetRelay()->Log(message, GetDid()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::C3::DeviceId FSecure::C3::Core::DeviceBridge::GetDid() const { return m_Did; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::StartUpdatingInSeparateThread() { std::thread{ [this, self = shared_from_this()]() { WinTools::StructuredExceptionHandling::SehWrapper([&]() { while (m_IsAlive) try { std::this_thread::sleep_for(GetDevice()->GetUpdateDelay()); OnReceive(); } catch (std::exception const& exception) { Log({ OBF_SEC("std::exception while updating: ") + exception.what(), LogMessage::Severity::Error }); } catch (...) { Log({ OBF_SEC("Unknown exception while updating."), LogMessage::Severity::Error }); } }, [this]() { # if defined _DEBUG Log({ "Signal captured, ending thread execution.", LogMessage::Severity::Error }); # endif }); }}.detach(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::SetUpdateDelay(std::chrono::milliseconds minUpdateDelayInMs, std::chrono::milliseconds maxUpdateDelayInMs) { GetDevice()->SetUpdateDelay(minUpdateDelayInMs, maxUpdateDelayInMs); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::SetUpdateDelay(std::chrono::milliseconds frequencyInMs) { GetDevice()->SetUpdateDelay(frequencyInMs); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::shared_ptr<FSecure::C3::Device> FSecure::C3::Core::DeviceBridge::GetDevice() const { return m_Device; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::shared_ptr<FSecure::C3::Core::Relay> FSecure::C3::Core::DeviceBridge::GetRelay() const { return m_Relay; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// FSecure::HashT FSecure::C3::Core::DeviceBridge::GetTypeNameHash() const { return m_TypeNameHash; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool FSecure::C3::Core::DeviceBridge::IsChannel() const { auto device = GetDevice(); return device ? device->IsChannel() : false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool FSecure::C3::Core::DeviceBridge::IsNegotiationChannel() const { return m_IsNegotiationChannel && IsChannel(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FSecure::C3::Core::DeviceBridge::SetErrorStatus(std::string_view errorMessage) { m_Error = errorMessage; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string FSecure::C3::Core::DeviceBridge::GetErrorStatus() { return m_Error; }
46.042056
222
0.383538
chowdaryd
d180b05df5259a9d8786957993c9f3fc7560fd90
1,423
cpp
C++
src/pal/tests/palsuite/c_runtime/_snprintf_s/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
159
2020-06-17T01:01:55.000Z
2022-03-28T10:33:37.000Z
src/pal/tests/palsuite/c_runtime/_snprintf_s/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-06-27T01:16:35.000Z
2022-02-06T20:33:24.000Z
src/pal/tests/palsuite/c_runtime/_snprintf_s/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-05-21T08:18:20.000Z
2021-06-29T01:13:13.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================ ** ** Source: test1.c ** ** Purpose: General test to see if sprintf_s works correctly ** ** **==========================================================================*/ #include <palsuite.h> #include "../_snprintf_s.h" /* * Notes: memcmp is used, as is strlen. */ int __cdecl main(int argc, char *argv[]) { char checkstr[] = "hello world"; char buf[256] = { 0 }; int ret; if (PAL_Initialize(argc, argv) != 0) { return FAIL; } _snprintf_s(buf, 256, _TRUNCATE, "hello world"); if (memcmp(checkstr, buf, strlen(checkstr)+1) != 0) { Fail("ERROR: expected \"%s\" (up to %d chars), got \"%s\"\n", checkstr, 256, buf); } _snprintf_s(buf, 256, _TRUNCATE, "xxxxxxxxxxxxxxxxx"); ret = _snprintf_s(buf, 8, _TRUNCATE, "hello world"); if (ret >= 0) { Fail("ERROR: expected negative return value, got %d", ret); } if (memcmp(checkstr, buf, 7) != 0 || buf[7] != 0 || buf[8] != 'x') { Fail("ERROR: expected %s (up to %d chars), got %s\n", checkstr, 8, buf); } PAL_Terminate(); return PASS; }
24.118644
78
0.510892
elinor-fung
d181ec15f6334b917385d3e91fbf4c41dd92ce0e
622
cpp
C++
cpp/rot13.cpp
angelopassaro/Hacktoberfest-1
21f90f5d49efba9b1a27f4d9b923f5017ab43f0e
[ "Apache-2.0" ]
1
2020-10-06T01:20:07.000Z
2020-10-06T01:20:07.000Z
cpp/rot13.cpp
angelopassaro/Hacktoberfest-1
21f90f5d49efba9b1a27f4d9b923f5017ab43f0e
[ "Apache-2.0" ]
null
null
null
cpp/rot13.cpp
angelopassaro/Hacktoberfest-1
21f90f5d49efba9b1a27f4d9b923f5017ab43f0e
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <cctype> std::string rot13(std::string source) { std::string transformed; for (size_t i = 0; i < source.size(); ++i) { if (isalpha(source[i])) { if ((tolower(source[i]) - 'a') < 13) transformed.append(1, source[i] + 13); else transformed.append(1, source[i] - 13); } else { transformed.append(1, source[i]); } } return transformed; } int main() { std::string teststring = "hello world {}"; std::string output = rot13(teststring); std::cout << "rot13 of \"" << teststring << " is " << output << std::endl; }
23.923077
78
0.573955
angelopassaro
d1830235551238a11afab51cc05d4121d8aa5921
3,168
cpp
C++
DigDuck/source/ipinfo.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
1
2016-01-05T07:24:32.000Z
2016-01-05T07:24:32.000Z
DigDuck/source/ipinfo.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
null
null
null
DigDuck/source/ipinfo.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
null
null
null
#include "ipinfo.h" #include <QDebug> ipInfo::ipInfo() { } //返回字符串数组 QStringList ipInfo::ipAddr (const QString &ip) { QStringList address = ip.split ("."); return address; } //判断是否为IP格式 bool ipInfo::isIP (const QString &ip ) { QStringList address = ip.split ("."); int num = 0; for(int i =0 ;i<address.length ();i++){ if(address[i].toInt ()>0 && address[i].toInt ()<256) num++; } if(num == 4) return true; return false; // qDebug ()<<num; } //获取端口号 QStringList ipInfo::ipPort (const QString &port) { QStringList ipport = port.split (","); return ipport; } //判断IP前两段是否一致 bool ipInfo::isSame_2 (const QString &begin, const QString &end) { QStringList one = begin.split ("."); QStringList two = end.split ("."); if(one[0] == two[0] && one[1] == two[1]) return true; return false; } //判断IP前三段是否一致 bool ipInfo::isSame_3 (const QString &begin, const QString &end) { QStringList one = begin.split ("."); QStringList two = end.split ("."); if(one[0] == two[0] && one[1] == two[1] && one[2] == two[2]) return true; return false; } //IP地址比较大小 bool ipInfo::isLarge (const QString &begin, const QString &end) { QStringList one = begin.split ("."); QStringList two = end.split ("."); int sum_1 = one[0].toInt ()*255*255*255 + one[1].toInt ()*255*255 +one[2].toInt ()*255 + one[3].toInt (); int sum_2 = two[0].toInt ()*255*255*255 + two[1].toInt ()*255*255 +two[2].toInt ()*255 + two[3].toInt (); if(sum_2 >= sum_1) return true; return false; } //从字典读取每一行文本内容 QStringList ipInfo::getFileContent (const QString &filePath) { QFile file (filePath); if(!file.open (QIODevice::ReadOnly | QIODevice::Text)) // QMessageBox::warning (this,"error","file open failed!"); qDebug ()<<"file open failed!"; file.seek (0); QString str; QStringList array ; str = file.readAll (); array = str.split ("\n"); return array; } //遍历字典中每一行的IP段中所有的IP QStringList ipInfo::getIP (const QString &begin,const QString &end) { QStringList begin_ip = begin.split ("."); QStringList end_ip = end.split ("."); QStringList ipAddress; // 42.121.4.41 42.121.5.50 for(int a = begin_ip[2].toInt ();a<=end_ip[2].toInt ();a++){ for(int b= ( a == begin_ip[2].toInt ()? begin_ip[3].toInt (): 0);b<=( a == end_ip[2].toInt ()? end_ip[3].toInt ():255);b++){ QString str_a = QString::number (a,10); QString str_b = QString::number (b,10); ipAddress << begin_ip[0]+"."+begin_ip[1]+"."+str_a+"."+str_b; } } return ipAddress; } //计算IP个数 int ipInfo::ipNum (QString begin_ip, QString end_ip) { QStringList begin = begin_ip.split ("."); QStringList end = end_ip.split ("."); int num = 0; for(int a = begin[2].toInt ();a<=end[2].toInt ();a++){ for(int b= ( a == begin[2].toInt ()? begin[3].toInt (): 0);b<=( a == end[2].toInt ()? end[3].toInt ():255);b++){ num++; } } return num; }
28.035398
133
0.554924
mickelfeng
d189ea96a8e55d39bec3de32b781d2950fda3df2
3,025
cc
C++
src/ray/core_worker/transport/normal_scheduling_queue.cc
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
1
2021-09-20T15:45:59.000Z
2021-09-20T15:45:59.000Z
src/ray/core_worker/transport/normal_scheduling_queue.cc
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
53
2021-10-06T20:08:04.000Z
2022-03-21T20:17:25.000Z
src/ray/core_worker/transport/normal_scheduling_queue.cc
dsctt/ray
29d94a22114b02adfd3745c4991a3ce70592dd16
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 The Ray 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 "ray/core_worker/transport/normal_scheduling_queue.h" namespace ray { namespace core { NormalSchedulingQueue::NormalSchedulingQueue(){}; void NormalSchedulingQueue::Stop() { // No-op } bool NormalSchedulingQueue::TaskQueueEmpty() const { absl::MutexLock lock(&mu_); return pending_normal_tasks_.empty(); } // Returns the current size of the task queue. size_t NormalSchedulingQueue::Size() const { absl::MutexLock lock(&mu_); return pending_normal_tasks_.size(); } /// Add a new task's callbacks to the worker queue. void NormalSchedulingQueue::Add( int64_t seq_no, int64_t client_processed_up_to, std::function<void(rpc::SendReplyCallback)> accept_request, std::function<void(rpc::SendReplyCallback)> reject_request, rpc::SendReplyCallback send_reply_callback, const std::string &concurrency_group_name, const FunctionDescriptor &function_descriptor, TaskID task_id, const std::vector<rpc::ObjectReference> &dependencies) { absl::MutexLock lock(&mu_); // Normal tasks should not have ordering constraints. RAY_CHECK(seq_no == -1); // Create a InboundRequest object for the new task, and add it to the queue. pending_normal_tasks_.push_back( InboundRequest(std::move(accept_request), std::move(reject_request), std::move(send_reply_callback), task_id, dependencies.size() > 0, /*concurrency_group_name=*/"", function_descriptor)); } // Search for an InboundRequest associated with the task that we are trying to cancel. // If found, remove the InboundRequest from the queue and return true. Otherwise, // return false. bool NormalSchedulingQueue::CancelTaskIfFound(TaskID task_id) { absl::MutexLock lock(&mu_); for (std::deque<InboundRequest>::reverse_iterator it = pending_normal_tasks_.rbegin(); it != pending_normal_tasks_.rend(); ++it) { if (it->TaskID() == task_id) { pending_normal_tasks_.erase(std::next(it).base()); return true; } } return false; } /// Schedules as many requests as possible in sequence. void NormalSchedulingQueue::ScheduleRequests() { while (true) { InboundRequest head; { absl::MutexLock lock(&mu_); if (!pending_normal_tasks_.empty()) { head = pending_normal_tasks_.front(); pending_normal_tasks_.pop_front(); } else { return; } } head.Accept(); } } } // namespace core } // namespace ray
33.611111
90
0.716033
dsctt
d189ed9d6b8ac829e994d250169c59de358605f6
12,159
cpp
C++
cnn/main.cpp
FCS-holding/acc_lib
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
[ "Apache-2.0" ]
null
null
null
cnn/main.cpp
FCS-holding/acc_lib
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
[ "Apache-2.0" ]
null
null
null
cnn/main.cpp
FCS-holding/acc_lib
1b6c0bc5467400e2ac678d18426cbbc7d44e8fec
[ "Apache-2.0" ]
null
null
null
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <assert.h> #include <stdbool.h> #include <sys/types.h> #include <sys/stat.h> //#include <CL/opencl.h> #include <sys/time.h> #include <iostream> #include <fstream> #include <string> //#include "cnn_cfg.hpp" #include "vgg16.hpp" //////////////////////////////////////////////////////////////////////////////// using namespace std; //////////////////////////////////////////////////////////////////////////////// data_t absub(data_t a, data_t b) { data_t tmp = (a>b)?(data_t)(a-b):(data_t)(b-a); return tmp; } data_t abadd(data_t a, data_t b) { data_t tmp1 = (a>(data_t)0)?(data_t)a:(data_t)((data_t)-1*a); data_t tmp2 = (b>(data_t)0)?(data_t)b:(data_t)((data_t)-1*b); data_t tmp3 = (data_t)(tmp1+tmp2)/(data_t)2; return tmp3; } float cmpratio(data_t a, data_t b) { float diff = (float)absub(a, b); float aver = (float)abadd(a, b); float ratio = diff/aver; return ratio; } template<typename data_t> void memset_int(data_t *m, data_t val, int addr, int length) { for(int i=0; i<length; i++) { m[i + addr] = val; } } void reorder_weight(data_t weight[512][512][3][3], data_t bias[512], data_t *m, int addr, layer conv) { for(int i=0; i<conv.fout; i++) { for(int j=0; j<conv.fin; j++) { for(int k=0; k<3; k++) { for(int h=0; h<3; h++) { weight[i][j][k][h] = m[ addr + i*conv.fin*9 + j*9 + k*3 + h ]; } } } if(conv.fin<UNROLL) { for(int j=conv.fin; j<UNROLL; j++) { for(int k=0; k<3; k++) { for(int h=0; h<3; h++) { weight[i][j][k][h] = (data_t)0; } } } } } //conv.fin * conv.fout matches with vgg16_sw; for(int i=0; i<conv.fout; i++) { bias[i] = m[addr + conv.fin*conv.fout*9 + i]; } int in_factor = (conv.fin>UNROLL)?conv.fin:UNROLL; for(int ii=0; ii<conv.fout; ii+=HWFOut) { for(int jj=0; jj<in_factor; jj+=HWFIn) { for(int k=0; k<3; k++) { for(int h=0; h<3; h++) { for(int i=0; i<HWFOut; i++) { for(int j=0; j<HWFIn; j++) { m[addr + ii*in_factor*9 + jj*9 + (k*3+h)*HWFOut*HWFIn + i*HWFIn+j] = weight[ii+i][jj+j][k][h]; } } } } } } for(int i=0; i<conv.fout; i++) { m[addr + conv.fout*in_factor*9 + i] = bias[i]; } } void prepare_weight( bw_t *DRAM_weight_reorder, data_t *DRAM_weight ) { static data_t weight[512][512][3][3]; static data_t bias[512]; reorder_weight(weight, bias, DRAM_weight, 0, conv1_1); reorder_weight(weight, bias, DRAM_weight, Layer11, conv1_2); reorder_weight(weight, bias, DRAM_weight, Layer12, conv2_1); reorder_weight(weight, bias, DRAM_weight, Layer21, conv2_2); reorder_weight(weight, bias, DRAM_weight, Layer22, conv3_1); reorder_weight(weight, bias, DRAM_weight, Layer31, conv3_2); reorder_weight(weight, bias, DRAM_weight, Layer32, conv3_3); reorder_weight(weight, bias, DRAM_weight, Layer33, conv4_1); reorder_weight(weight, bias, DRAM_weight, Layer41, conv4_2); reorder_weight(weight, bias, DRAM_weight, Layer42, conv4_3); reorder_weight(weight, bias, DRAM_weight, Layer43, conv5_1); reorder_weight(weight, bias, DRAM_weight, Layer51, conv5_2); reorder_weight(weight, bias, DRAM_weight, Layer52, conv5_3); bw_t tmp; for(int i=0; i<WEIGHTSIZE/UNROLL; i++) { for(int j=0; j<UNROLL; j++) { data_t data = DRAM_weight[i*UNROLL + j]; int *idata = (int*)&data; tmp.range((j+1)*32-1, j*32) = *idata; } DRAM_weight_reorder[i] = tmp; } } void prepare_image(bw_t *m_fm, int addr_fm, data_t *m, int addr_m, int length) { int factor = UNROLL; bw_t data; for(int i=0; i<length/factor; i++) { for(int j=0; j<factor; j++) { data_t fdata = m[addr_m + i*factor + j]; int* idata = (int*) &fdata; data.range((j+1)*32-1, j*32) = *idata; } m_fm[i + addr_fm] = data; } float adata[8][224][224]; factor = sizeof(bw_t)/sizeof(float); bw_t tmp; for(int i=0; i<3; i++) { for(int j=0; j<224; j++) { for(int k=0; k<224; k+=factor){ for(int kk=0; kk<factor; kk++) { int tdata = m_fm[(i*224*224+j*224+k)/factor].range((kk+1)*32-1, kk*32); float *fdata = (float*)&tdata; adata[i][j][k+kk] = *fdata; } } } } for(int i=3; i<8; i++) { for(int j=0; j<224; j++) { for(int k=0; k<224; k++){ adata[i][j][k] = (float)0; } } } for(int j=0; j<224; j++) { for(int k=0; k<224; k++){ for(int i=0; i<8; i++) { float fdata2 = adata[i][j][k]; int *idata = (int*)&fdata2; tmp.range((i+1)*32-1, i*32) = *idata; } m_fm[(j*224+k)] = tmp; } } } template<typename wb_t, typename data_t, int num, int row, int col, int tf_row, int tf_col> void reorder_output(data_t *m , wb_t *m_fm, int addr) { static data_t data[num][row][col]; for(int ii=0; ii<num; ii+=UNROLL) { for(int r=0; r<row; r++) { for(int c=0; c<col; c++) { for(int i=0; i<UNROLL; i++) { int idata = m_fm[addr/UNROLL +(r*col+c) + (ii/UNROLL)*row*col].range((i+1)*32-1, i*32); float *fdata = (float*)&idata ; data[ii+i][r][c] = *fdata; } } } } for(int i=0; i<num; i++) { for(int j=0; j<row; j++) { for(int k=0; k<col; k++) { m[i*row*col + j*col + k] = data[i][j][k]; } } } } void bwmemcpy(bw_t *dst, int addrdst, bw_t *src, int addrsrc, int length) { for(int i=0; i<length; i++) { dst[i + addrdst] = src[i + addrsrc]; } } int main(int argc, char** argv) { //----------------------------- //init DRAM data_t *DRAM_sw; int swDramSize = (WEIGHTSIZE+ INFM+ FM11); DRAM_sw = (data_t*) malloc(swDramSize*sizeof(data_t)); if (DRAM_sw==NULL) { printf("malloc failure\n"); exit (1); } memset_int<data_t>(DRAM_sw, (data_t)0.010, 0, swDramSize); memset_int<data_t>(DRAM_sw, (data_t)0.011, WEIGHTSIZE, 224*100); memset_int<data_t>(DRAM_sw, (data_t)0.002, (WEIGHTSIZE+224*100), (224*124+224*324)); memset_int<data_t>(DRAM_sw, (data_t)0.015, (WEIGHTSIZE+(224*224+224*324)), 124*224); memset_int<data_t>(DRAM_sw, (data_t)0.001, 0, Layer11); memset_int<data_t>(DRAM_sw, (data_t)0.002, 0, Layer11/2); memset_int<data_t>(DRAM_sw, (data_t)0.013, 0, Layer11/3); memset_int<data_t>(DRAM_sw, (data_t)0.002, Layer11, Layer12-Layer11); memset_int<data_t>(DRAM_sw, (data_t)0.0015, Layer31, (Layer32-Layer31)/2); memset_int<data_t>(DRAM_sw, (data_t)0.005, Layer42, Layer43-Layer42); memset_int<data_t>(DRAM_sw, (data_t)0.003, Layer52, Layer53-Layer52); /* for(int i=0; i<64; i++) { for(int j=0; j<3; j++) { for(int k=0; k<9; k++) { if(j<8) DRAM_sw[i*3*9 + j*9 + k] = (10*(j+1) + k) + (data_t)(i+1)/100; else DRAM_sw[i*3*9 + j*9 + k] = (data_t)0; } } } */ printf("0. init DRAM_sw finish\n"); int DramSize_weight = (WEIGHTSIZE); data_t *DRAM_weight = (data_t*) malloc(DramSize_weight*sizeof(data_t)); bw_t *DRAM_weight_reorder = (bw_t*) malloc(DramSize_weight*sizeof(data_t)); int DramSize_featmap = (INFM + FM11+FM12+PL12 + FM21+FM22+PL22+ FM31+FM32+FM33+PL33+ FM41+FM42+FM43+PL43+ FM51+FM52+FM53+PL53); bw_t *DRAM_featmap = (bw_t*) malloc(DramSize_featmap*sizeof(data_t)); int DramSize_hw = DramSize_weight + DramSize_featmap; bw_t *DRAM_hw = (bw_t*) malloc(DramSize_hw*sizeof(data_t)); printf("1. init DRAM_hw finish\n"); memcpy(DRAM_weight, DRAM_sw, sizeof(data_t)*WEIGHTSIZE); printf("2. memcpy DRAM_weight\n"); prepare_weight(DRAM_weight_reorder, DRAM_weight); //reorder weights and transform them into bw_t printf("3. prepare DRAM weight\n"); //-------------------------------------------- //prepare image - memcpy DRAM_sw->DRAM_featmap and reorder first image prepare_image(DRAM_featmap, 0, DRAM_sw, WEIGHTSIZE, 224*224*3); printf("4. prepare DRAM feature map\n"); bwmemcpy(DRAM_hw, WEIGHTSIZE/UNROLL, DRAM_featmap, 0, DramSize_featmap/UNROLL); printf("5. concat feat map\n"); bwmemcpy(DRAM_hw, 0, DRAM_weight_reorder, 0, WEIGHTSIZE/UNROLL); printf("6. concat weight\n"); //write reordered data into data bw_t bw_data; ofstream ofresult("input_reorder.txt", ios::app); for(int i=0; i<224*224*8; i++) { if(i%8==0) bw_data = DRAM_featmap[i/8]; int tt = bw_data.range((i%8+1)*32-1, (i%8)*32); float *data = (float*)&tt; //ofresult << *data <<"\t" << tt << "\t" << bw_data.range((i%8+1)*32-1, (i%8)*32) <<endl; ofresult << *data <<endl; } ofresult.close(); //----------------------------- //start compute vgg16_sw2(DRAM_sw); printf("software simulation finish!\n"); vgg16(DRAM_hw); printf("hardware simulation finish!\n"); //----------------------------- //compare input reorder //for layer1 only /* float data1, data2, dataaccu=0.0; FILE *fp1=fopen("reorder_weight.txt", "r"); FILE *fp2=fopen("load_weight.txt", "r"); ofstream ofcompare("compare.txt", ios::app); for(int i=0; i<64*8*9; i++) { fscanf(fp1, "%f\n", &data1); fscanf(fp2, "%f\n", &data2); float tmodata = (data1-data2>0)?(data1-data2):(data2-data1); if(tmodata ==0) ofcompare << data1 << "\t\t" << data2 << "\t\t" << tmodata << endl; else ofcompare << data1 << "\t\t" << data2 << "\t\t" << tmodata << "<<" << endl; dataaccu += tmodata; } printf("accumulate: %f\n", dataaccu); ofcompare.close(); fclose(fp1); fclose(fp2); */ int cnt=0; //----------------------------- //compare result #if 1 data_t tmp_sw=0; data_t tmp_hw=0; data_t sum=0; data_t *DRAM_result = (data_t*)malloc(PL53*sizeof(data_t)); int result_addr = WEIGHTSIZE + INFM+ FM11+FM12+PL12+ FM21+FM22+PL22+ FM31+FM32+FM33+PL33+ FM41+FM42+FM43+PL43+ FM51+FM52+FM53; reorder_output<ap_uint<32*8>, data_t, POOL53, POOL53_R, POOL53_R, HWFR, HWFC>(DRAM_result, DRAM_hw, result_addr); for(int i=0; i<PL53; i++) { tmp_sw = DRAM_sw[WEIGHTSIZE+ INFM+ i]; tmp_hw = DRAM_result[i]; //if (cmpratio(tmp_sw, tmp_hw)>1E-4) { printf("sw:%f,\t hw:%f,\t ratio:%f\n", (float)tmp_sw, (float)tmp_hw, (float)cmpratio(tmp_sw, tmp_hw)); // cnt+=1; //} } #else data_t tmp_sw=0; data_t tmp_hw=0; data_t sum=0; data_t *DRAM_result = (data_t*)malloc(FM11*sizeof(data_t)); int result_addr = WEIGHTSIZE + INFM; reorder_output<ap_uint<32*8>, data_t, CONV11, CONV11_R, CONV11_R, HWFR, HWFC>(DRAM_result, DRAM_hw, result_addr); for(int i=0; i<FM11; i++) { tmp_sw = DRAM_sw[WEIGHTSIZE+ INFM+ i]; sum += tmp_sw; tmp_hw = DRAM_result[i]; if (cmpratio(tmp_sw, tmp_hw)>1E-5) { printf("sw:%f,\t hw:%f,\t ratio:%f\n", (float)tmp_sw, (float)tmp_hw, (float)cmpratio(tmp_sw, tmp_hw)); cnt+=1; } } #endif free(DRAM_result); free(DRAM_weight); free(DRAM_featmap); free(DRAM_sw); free(DRAM_hw); if(cnt==0) { printf("SUCCESS\n"); } else { printf("FAIL\n"); printf("cnt:%d\n", cnt); } // Validate our results /* timeval startSw, endSw; gettimeofday(&startSw, NULL); gettimeofday(&endSw, NULL); printf("software time :%8.6f ms\n ", (endSw.tv_sec-startSw.tv_sec)*1e+3 + (endSw.tv_usec-startSw.tv_usec)*1e-03 ); printf("Compute Golden Result Finish\n"); */ }
35.040346
131
0.546344
FCS-holding
d18a59aa26a3d619a220eccaf3ca5db3b4c919e5
10,255
cpp
C++
tests/capture_ut.cpp
orivej/pire
1df29444fcdff712320f9b6af6f28188838b774c
[ "MIT" ]
212
2015-01-09T12:15:30.000Z
2022-01-25T17:20:22.000Z
tests/capture_ut.cpp
orivej/pire
1df29444fcdff712320f9b6af6f28188838b774c
[ "MIT" ]
35
2015-07-28T11:50:39.000Z
2020-09-17T20:48:43.000Z
tests/capture_ut.cpp
orivej/pire
1df29444fcdff712320f9b6af6f28188838b774c
[ "MIT" ]
34
2015-02-10T12:43:27.000Z
2022-01-25T17:20:27.000Z
/* * capture_ut.cpp -- * * Copyright (c) 2007-2010, Dmitry Prokoptsev <dprokoptsev@gmail.com>, * Alexander Gololobov <agololobov@gmail.com> * * This file is part of Pire, the Perl Incompatible * Regular Expressions library. * * Pire is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pire 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 Public License for more details. * You should have received a copy of the GNU Lesser Public License * along with Pire. If not, see <http://www.gnu.org/licenses>. */ #include <stub/hacks.h> #include <stub/saveload.h> #include <stub/utf8.h> #include <stub/memstreams.h> #include "stub/cppunit.h" #include <pire.h> #include <extra.h> #include <string.h> SIMPLE_UNIT_TEST_SUITE(TestPireCapture) { using Pire::CapturingScanner; using Pire::SlowCapturingScanner; typedef Pire::CapturingScanner::State State; CapturingScanner Compile(const char* regexp, int index) { Pire::Lexer lexer; lexer.Assign(regexp, regexp + strlen(regexp)); lexer.AddFeature(Pire::Features::CaseInsensitive()); lexer.AddFeature(Pire::Features::Capture(static_cast<size_t>(index))); Pire::Fsm fsm = lexer.Parse(); fsm.Surround(); fsm.Determine(); return fsm.Compile<Pire::CapturingScanner>(); } SlowCapturingScanner SlowCompile(const char* regexp, int index, const Pire::Encoding& encoding = Pire::Encodings::Utf8()) { Pire::Lexer lexer; lexer.AddFeature(Pire::Features::Capture((size_t) index)); lexer.SetEncoding(encoding); TVector<wchar32> ucs4; encoding.FromLocal(regexp, regexp + strlen(regexp), std::back_inserter(ucs4)); lexer.Assign(ucs4.begin(), ucs4.end()); Pire::Fsm fsm = lexer.Parse(); fsm.Surround(); return fsm.Compile<Pire::SlowCapturingScanner>(); } State RunRegexp(const CapturingScanner& scanner, const char* str) { State state; scanner.Initialize(state); Step(scanner, state, Pire::BeginMark); Run(scanner, state, str, str + strlen(str)); Step(scanner, state, Pire::EndMark); return state; } SlowCapturingScanner::State RunRegexp(const SlowCapturingScanner& scanner, const char* str) { SlowCapturingScanner::State state; scanner.Initialize(state); Run(scanner, state, str, str + strlen(str)); return state; } ystring Captured(const State& state, const char* str) { if (state.Captured()) return ystring(str + state.Begin() - 1, str + state.End() - 1); else return ystring(); } SIMPLE_UNIT_TEST(Trivial) { CapturingScanner scanner = Compile("google_id\\s*=\\s*[\'\"]([a-z0-9]+)[\'\"]\\s*;", 1); State state; const char* str; str = "google_id = 'abcde';"; state = RunRegexp(scanner, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("abcde")); str = "var google_id = 'abcde'; eval(google_id);"; state = RunRegexp(scanner, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("abcde")); str = "google_id != 'abcde';"; state = RunRegexp(scanner, str); UNIT_ASSERT(!state.Captured()); } SIMPLE_UNIT_TEST(Sequential) { CapturingScanner scanner = Compile("google_id\\s*=\\s*[\'\"]([a-z0-9]+)[\'\"]\\s*;", 1); State state; const char* str; str = "google_id = 'abcde'; google_id = 'xyz';"; state = RunRegexp(scanner, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("abcde")); str = "var google_id = 'abc de'; google_id = 'xyz';"; state = RunRegexp(scanner, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("xyz")); } SIMPLE_UNIT_TEST(NegatedTerminator) { CapturingScanner scanner = Compile("=(\\d+)[^\\d]", 1); State state; const char* str; str = "=12345;"; state = RunRegexp(scanner, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("12345")); } SIMPLE_UNIT_TEST(FakeEdges) { CapturingScanner scanner = Compile("(/to-match-with)", 1); State state; const char* str; str = "/some/table/path/to-match-with"; state = RunRegexp(scanner, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("/to-match-with")); } SIMPLE_UNIT_TEST(Serialization) { const char* regex = "google_id\\s*=\\s*[\'\"]([a-z0-9]+)[\'\"]\\s*;"; CapturingScanner scanner2 = Compile(regex, 1); SlowCapturingScanner slowScanner2 = SlowCompile(regex, 1); BufferOutput wbuf, wbuf2; ::Save(&wbuf, scanner2); ::Save(&wbuf2, slowScanner2); MemoryInput rbuf(wbuf.Buffer().Data(), wbuf.Buffer().Size()); MemoryInput rbuf2(wbuf2.Buffer().Data(), wbuf2.Buffer().Size()); CapturingScanner scanner; SlowCapturingScanner slowScanner; ::Load(&rbuf, scanner); ::Load(&rbuf2, slowScanner); State state; SlowCapturingScanner::State slowState; const char* str; str = "google_id = 'abcde';"; state = RunRegexp(scanner, str); slowState = RunRegexp(slowScanner, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("abcde")); SlowCapturingScanner::SingleState final; UNIT_ASSERT(slowScanner.GetCapture(slowState, final)); ystring ans(str, final.GetBegin(), final.GetEnd() - final.GetBegin()); UNIT_ASSERT_EQUAL(ans, ystring("abcde")); str = "google_id != 'abcde';"; state = RunRegexp(scanner, str); slowState = RunRegexp(slowScanner, str); UNIT_ASSERT(!state.Captured()); UNIT_ASSERT(!slowScanner.GetCapture(slowState, final)); CapturingScanner scanner3; const size_t MaxTestOffset = 2 * sizeof(Pire::Impl::MaxSizeWord); TVector<char> buf2(wbuf.Buffer().Size() + sizeof(size_t) + MaxTestOffset); const void* ptr = Pire::Impl::AlignUp(&buf2[0], sizeof(size_t)); memcpy((void*) ptr, wbuf.Buffer().Data(), wbuf.Buffer().Size()); const void* tail = scanner3.Mmap(ptr, wbuf.Buffer().Size()); UNIT_ASSERT_EQUAL(tail, (const void*) ((size_t)ptr + wbuf.Buffer().Size())); str = "google_id = 'abcde';"; state = RunRegexp(scanner3, str); UNIT_ASSERT(state.Captured()); UNIT_ASSERT_EQUAL(Captured(state, str), ystring("abcde")); str = "google_id != 'abcde';"; state = RunRegexp(scanner3, str); UNIT_ASSERT(!state.Captured()); ptr = (const void*) ((const char*) wbuf.Buffer().Data() + 1); try { scanner3.Mmap(ptr, wbuf.Buffer().Size()); UNIT_ASSERT(!"CapturingScanner failed to check for misaligned mmaping"); } catch (Pire::Error&) {} for (size_t offset = 1; offset < MaxTestOffset; ++offset) { ptr = Pire::Impl::AlignUp(&buf2[0], sizeof(size_t)) + offset; memcpy((void*) ptr, wbuf.Buffer().Data(), wbuf.Buffer().Size()); try { scanner3.Mmap(ptr, wbuf.Buffer().Size()); if (offset % sizeof(size_t) != 0) { UNIT_ASSERT(!"CapturingScanner failed to check for misaligned mmaping"); } else { str = "google_id = 'abcde';"; state = RunRegexp(scanner3, str); UNIT_ASSERT(state.Captured()); } } catch (Pire::Error&) {} } } SIMPLE_UNIT_TEST(Empty) { Pire::CapturingScanner sc; UNIT_ASSERT(sc.Empty()); UNIT_CHECKPOINT(); RunRegexp(sc, "a string"); // Just should not crash // Test Save/Load/Mmap BufferOutput wbuf; ::Save(&wbuf, sc); MemoryInput rbuf(wbuf.Buffer().Data(), wbuf.Buffer().Size()); Pire::CapturingScanner sc3; ::Load(&rbuf, sc3); UNIT_CHECKPOINT(); RunRegexp(sc3, "a string"); const size_t MaxTestOffset = 2 * sizeof(Pire::Impl::MaxSizeWord); TVector<char> buf2(wbuf.Buffer().Size() + sizeof(size_t) + MaxTestOffset); const void* ptr = Pire::Impl::AlignUp(&buf2[0], sizeof(size_t)); memcpy((void*) ptr, wbuf.Buffer().Data(), wbuf.Buffer().Size()); Pire::CapturingScanner sc4; const void* tail = sc4.Mmap(ptr, wbuf.Buffer().Size()); UNIT_ASSERT_EQUAL(tail, (const void*) ((size_t)ptr + wbuf.Buffer().Size())); UNIT_CHECKPOINT(); RunRegexp(sc4, "a string"); } void MakeSlowCapturingTest(const char* regexp, const char* text, size_t position, bool ans, const ystring& captured = ystring(""), const Pire::Encoding& encoding = Pire::Encodings::Utf8()) { Pire::SlowCapturingScanner sc = SlowCompile(regexp, position, encoding); SlowCapturingScanner::State st = RunRegexp(sc, text); SlowCapturingScanner::SingleState fin; bool ifCaptured = sc.GetCapture(st, fin); if (ans) { UNIT_ASSERT(ifCaptured); ystring answer(text, fin.GetBegin(), fin.GetEnd() - fin.GetBegin()); UNIT_ASSERT_EQUAL(answer, captured); } else { UNIT_ASSERT(!ifCaptured); } } SIMPLE_UNIT_TEST(SlowCapturingNonGreedy) { const char* regexp = ".*?(pref.*suff)"; const char* text = "pref ala bla pref cla suff dla"; MakeSlowCapturingTest(regexp, text, 1, true, ystring("pref ala bla pref cla suff")); } SIMPLE_UNIT_TEST(SlowCaptureGreedy) { const char* regexp = ".*(pref.*suff)"; const char* text = "pref ala bla pref cla suff dla"; MakeSlowCapturingTest(regexp, text, 1, true, ystring("pref cla suff")); } SIMPLE_UNIT_TEST(SlowCaptureInOr) { const char* regexp = "(A)|A"; const char* text = "A"; MakeSlowCapturingTest(regexp, text, 1, true, ystring("A")); const char* regexp2 = "A|(A)"; MakeSlowCapturingTest(regexp2, text, 1, false); } SIMPLE_UNIT_TEST(SlowCapturing) { const char* regexp = "^http://vk(ontakte[.]ru|[.]com)/id(\\d+)([^0-9]|$)"; const char* text = "http://vkontakte.ru/id100500"; MakeSlowCapturingTest(regexp, text, 2, true, ystring("100500")); } SIMPLE_UNIT_TEST(Utf_8) { const char* regexp = "\xd0\x97\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb2\xd1\x81\xd1\x82\xd0\xb2\xd1\x83\xd0\xb9\xd1\x82\xd0\xb5, ((\\s|\\w|[()]|-)+)!"; const char* text =" \xd0\x97\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb2\xd1\x81\xd1\x82\xd0\xb2\xd1\x83\xd0\xb9\xd1\x82\xd0\xb5, \xd0\xa3\xd0\xb2\xd0\xb0\xd0\xb6\xd0\xb0\xd0\xb5\xd0\xbc\xd1\x8b\xd0\xb9 (-\xd0\xb0\xd1\x8f)! "; const char* ans = "\xd0\xa3\xd0\xb2\xd0\xb0\xd0\xb6\xd0\xb0\xd0\xb5\xd0\xbc\xd1\x8b\xd0\xb9 (-\xd0\xb0\xd1\x8f)"; MakeSlowCapturingTest(regexp, text, 1, true, ystring(ans)); } }
32.86859
221
0.682789
orivej
d18b025b3d6fc867cc719e0b4b463f3d71b7c9a9
2,597
cpp
C++
thirdparty/basalt/thirdparty/ros/ros_comm/test/test_roscpp/test/src/wait_for_message.cpp
Bookiebookie/LieSpline
b617bdf6b37164562387d0257145e9230d28e2e7
[ "BSD-3-Clause" ]
2
2021-05-22T09:46:00.000Z
2022-03-25T09:56:22.000Z
thirdparty/basalt/thirdparty/ros/ros_comm/test/test_roscpp/test/src/wait_for_message.cpp
Bookiebookie/LieSpline
b617bdf6b37164562387d0257145e9230d28e2e7
[ "BSD-3-Clause" ]
null
null
null
thirdparty/basalt/thirdparty/ros/ros_comm/test/test_roscpp/test/src/wait_for_message.cpp
Bookiebookie/LieSpline
b617bdf6b37164562387d0257145e9230d28e2e7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. 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. */ /* Author: Josh Faust */ #include <string> #include <sstream> #include <fstream> #include <gtest/gtest.h> #include <time.h> #include <stdlib.h> #include "ros/ros.h" #include <test_roscpp/TestArray.h> using namespace ros; using namespace test_roscpp; TEST(Roscpp, waitForMessage) { ros::NodeHandle nh; ros::Publisher pub = nh.advertise<TestArray>("test", 1, true); pub.publish(TestArray()); TestArrayConstPtr msg = topic::waitForMessage<TestArray>("test"); ASSERT_TRUE(msg); } TEST(Roscpp, waitForMessageWithTimeout) { ros::NodeHandle nh; ros::Time start = ros::Time::now(); TestArrayConstPtr msg = topic::waitForMessage<TestArray>("test", ros::Duration(1.0)); ros::Time end = ros::Time::now(); ros::Duration dur = end - start; ASSERT_GE(dur, ros::Duration(1.0)); ASSERT_FALSE(msg); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "wait_for_message"); ros::NodeHandle nh; return RUN_ALL_TESTS(); }
33.294872
87
0.730073
Bookiebookie
d18b14c2cb9cfb6988cdc5125b7fe9b0eef637a1
3,501
cc
C++
chrome/browser/search/hotword_service_factory.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chrome/browser/search/hotword_service_factory.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chrome/browser/search/hotword_service_factory.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/search/hotword_service_factory.h" #include "base/command_line.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/hotword_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" using content::BrowserContext; using content::BrowserThread; // static HotwordService* HotwordServiceFactory::GetForProfile(BrowserContext* context) { return static_cast<HotwordService*>( GetInstance()->GetServiceForBrowserContext(context, true)); } // static HotwordServiceFactory* HotwordServiceFactory::GetInstance() { return base::Singleton<HotwordServiceFactory>::get(); } // static bool HotwordServiceFactory::IsServiceAvailable(BrowserContext* context) { HotwordService* hotword_service = GetForProfile(context); return hotword_service && hotword_service->IsServiceAvailable(); } // static bool HotwordServiceFactory::IsHotwordAllowed(BrowserContext* context) { HotwordService* hotword_service = GetForProfile(context); return hotword_service && hotword_service->IsHotwordAllowed(); } // static bool HotwordServiceFactory::IsAlwaysOnAvailable() { #if defined(OS_CHROMEOS) if (HotwordService::IsHotwordHardwareAvailable()) return true; #endif base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); return command_line->HasSwitch(switches::kEnableExperimentalHotwordHardware); } // static int HotwordServiceFactory::GetCurrentError(BrowserContext* context) { HotwordService* hotword_service = GetForProfile(context); if (!hotword_service) return 0; return hotword_service->error_message(); } HotwordServiceFactory::HotwordServiceFactory() : BrowserContextKeyedServiceFactory( "HotwordService", BrowserContextDependencyManager::GetInstance()) { // No dependencies. } HotwordServiceFactory::~HotwordServiceFactory() { } void HotwordServiceFactory::UpdateMicrophoneState() { // In order to trigger the monitor, just call getAudioCaptureDevices. content::MediaStreamDevices devices = MediaCaptureDevicesDispatcher::GetInstance()->GetAudioCaptureDevices(); } void HotwordServiceFactory::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* prefs) { prefs->RegisterBooleanPref(prefs::kHotwordAudioLoggingEnabled, false, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); prefs->RegisterStringPref(prefs::kHotwordPreviousLanguage, std::string(), user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); // Per-device settings (do not sync). prefs->RegisterBooleanPref(prefs::kHotwordSearchEnabled, false); prefs->RegisterBooleanPref(prefs::kHotwordAlwaysOnSearchEnabled, false); prefs->RegisterBooleanPref(prefs::kHotwordAlwaysOnNotificationSeen, false); } KeyedService* HotwordServiceFactory::BuildServiceInstanceFor( BrowserContext* context) const { return new HotwordService(Profile::FromBrowserContext(context)); }
36.092784
80
0.773493
google-ar
d18cea7cecb037520353bed7d78354a36a16e22e
1,094
cpp
C++
src/tile/Recovery.cpp
rbtnn/tile
8b0b896b6e69128e68a4b134d7b0fbf617894fb1
[ "MIT" ]
1
2015-01-08T21:58:32.000Z
2015-01-08T21:58:32.000Z
src/tile/Recovery.cpp
rbtnn/tile
8b0b896b6e69128e68a4b134d7b0fbf617894fb1
[ "MIT" ]
null
null
null
src/tile/Recovery.cpp
rbtnn/tile
8b0b896b6e69128e68a4b134d7b0fbf617894fb1
[ "MIT" ]
null
null
null
#include <tile/common_headers.h> #include <tile/common_functions.h> #include <tile/wndproc_functions.h> #include <tile/Recovery.h> namespace Tile{ void Recovery::save(HWND const& hwnd_){ auto it = rects.find(hwnd_); if(it == std::end(rects)){ RECT rect; ::GetWindowRect(hwnd_, &rect); rects.insert(std::map<HWND, RECT>::value_type(hwnd_, rect)); styles.insert(std::map<HWND, LONG>::value_type(hwnd_, ::GetWindowLong(hwnd_, GWL_STYLE))); exstyles.insert(std::map<HWND, LONG>::value_type(hwnd_, ::GetWindowLong(hwnd_, GWL_EXSTYLE))); } } void Recovery::load(HWND const& hwnd_){ auto it = rects.find(hwnd_); if(it != std::end(rects)){ RECT const rect = rects[hwnd_]; LONG const width = rect.right - rect.left; LONG const height = rect.bottom - rect.top; ::SetWindowPos(hwnd_, HWND_NOTOPMOST, rect.left, rect.top, width, height, SWP_NOACTIVATE); ::SetWindowLong(hwnd_, GWL_STYLE, styles[hwnd_]); ::SetWindowLong(hwnd_, GWL_EXSTYLE, exstyles[hwnd_]); ::ShowWindow(hwnd_, SW_SHOWNORMAL); } } }
35.290323
100
0.662706
rbtnn
d18d8dd0c5dde502ca871623aaa726f80e9494c6
681
cpp
C++
src/game/client/hl2/c_basehlcombatweapon.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/client/hl2/c_basehlcombatweapon.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/client/hl2/c_basehlcombatweapon.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "c_basehlcombatweapon.h" #include "igamemovement.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_CLIENTCLASS_DT( C_HLMachineGun, DT_HLMachineGun, CHLMachineGun ) END_RECV_TABLE() IMPLEMENT_CLIENTCLASS_DT( C_HLSelectFireMachineGun, DT_HLSelectFireMachineGun, CHLSelectFireMachineGun ) END_RECV_TABLE() IMPLEMENT_CLIENTCLASS_DT( C_BaseHLBludgeonWeapon, DT_BaseHLBludgeonWeapon, CBaseHLBludgeonWeapon ) END_RECV_TABLE()
32.428571
104
0.687225
cstom4994
d18dad187d1681d93bb60d9045bcfcc87ecc5f3d
14,175
cpp
C++
Source/Structures/ModeMapper.cpp
vsicurella/SuperVirtualKeyboard
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
[ "Unlicense" ]
22
2019-06-26T12:41:49.000Z
2022-02-11T14:48:18.000Z
Source/Structures/ModeMapper.cpp
vsicurella/SuperVirtualKeyboard
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
[ "Unlicense" ]
18
2019-06-22T21:49:21.000Z
2021-05-15T01:33:57.000Z
Source/Structures/ModeMapper.cpp
vsicurella/SuperVirtualKeyboard
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
[ "Unlicense" ]
null
null
null
/* ============================================================================== ModeMapper.cpp Created: 30 May 2019 8:02:42pm Author: Vincenzo ============================================================================== */ #include "ModeMapper.h" ModeMapper::ModeMapper() { mappingNode = ValueTree(IDs::midiMapNode); setMappingStyle(0); setMapOrdersParameters(0, 0, 0, 0); } ModeMapper::ModeMapper(ValueTree modeMappingNodeIn) { mappingNode = modeMappingNodeIn; mappingStyle = mappingNode[IDs::autoMappingStyle]; mapByOrderNum1 = mappingNode[IDs::mode1OrderMapping]; mapByOrderNum2 = mappingNode[IDs::mode2OrderMapping]; mapByOrderOffset1 = mappingNode[IDs::mode1OrderOffsetMapping]; mapByOrderOffset2 = mappingNode[IDs::mode2OrderOffsetMapping]; } ValueTree ModeMapper::getMappingNode() { return mappingNode; } int ModeMapper::getMode1OrderNum() const { return mapByOrderNum1; } int ModeMapper::getMode2OrderNum() const { return mapByOrderNum2; } int ModeMapper::getMode1OrderOffset() const { return mapByOrderOffset1; } int ModeMapper::getMode2OrderOffset() const { return mapByOrderOffset2; } void ModeMapper::setMappingStyle(int mapTypeIn) { mappingStyle = mapTypeIn; mappingNode.setProperty(IDs::autoMappingStyle, mapTypeIn, nullptr); } void ModeMapper::setMapOrdersParameters(int order1, int order2, int offset1, int offset2) { setMode1OrderNum(order1); setMode2OrderNum(order2); setMode1OrderOffset(offset1); setMode2OrderOffset(offset2); } void ModeMapper::setMode1OrderNum(int orderNumber) { mapByOrderNum1 = orderNumber; mappingNode.setProperty(IDs::mode1OrderMapping, mapByOrderNum1, nullptr); } void ModeMapper::setMode2OrderNum(int orderNumber) { mapByOrderNum2 = orderNumber; mappingNode.setProperty(IDs::mode2OrderMapping, mapByOrderNum2, nullptr); } void ModeMapper::setMode1OrderOffset(int orderOffset) { mapByOrderOffset1 = orderOffset; mappingNode.setProperty(IDs::mode1OrderOffsetMapping, mapByOrderOffset1, nullptr); } void ModeMapper::setMode2OrderOffset(int orderOffset) { mapByOrderOffset2 = orderOffset; mappingNode.setProperty(IDs::mode2OrderOffsetMapping, mapByOrderOffset2, nullptr); } void ModeMapper::setPreviousOrderNoteMap(NoteMap prevNoteMapIn) { previousOrderMap = prevNoteMapIn; } NoteMap ModeMapper::map(const Mode& mode1, const Mode& mode2, NoteMap prevMap) { return map(mode1, mode2, mappingStyle, mapByOrderNum1, mapByOrderNum2, mapByOrderOffset1, mapByOrderOffset2, prevMap); } NoteMap ModeMapper::map(const Mode& mode1, const Mode& mode2, int mapStyleIn, int order1, int order2, int offset1, int offset2, NoteMap prevMap) { NoteMap mapOut; if (mapStyleIn < 0) mapStyleIn = mappingStyle; else setMappingStyle(mapStyleIn); mappingNode.setProperty(IDs::autoMappingStyle, mappingStyle, nullptr); switch (mappingStyle) { case ModeToScale: mapOut = mapToMode1Scale(mode1, mode2); break; case ModeByOrder: setMapOrdersParameters(order1, order2, offset1, offset2); previousOrderMap = prevMap; mapOut = mapByOrder(mode1, mode2, mapByOrderNum1, mapByOrderNum2, mapByOrderOffset1, mapByOrderOffset2, previousOrderMap); break; default: mapOut = mapFull(mode1, mode2); break; } return mapOut; } Array<int> ModeMapper::getSelectedPeriodMap(const Mode& mode1, const Mode& mode2) const { Array<int> mapOut; NoteMap fullMap; switch (mappingStyle) { case ModeToScale: if (mode1.getScaleSize() == mode2.getModeSize()) mapOut = getScaleToModePeriodMap(mode1, mode2); else // TODO: improve mapOut = mapFull(mode1, mode2).getValues(); break; case ModeByOrder: // TODO: improve mapOut = mapFull(mode1, mode2, previousOrderMap.getValues()).getValues(); break; default: // ModeToMode if (mode1.getModeSize() == mode2.getModeSize()) mapOut = getModeToModePeriodMap(mode1, mode2); else mapOut = degreeMapFullMode(mode1, mode2); break; } return mapOut; } NoteMap ModeMapper::mapFull(const Mode& mode1, const Mode& mode2, Array<int> degreeMapIn) { if (degreeMapIn.size() != mode1.getOrders().size()) degreeMapIn = degreeMapFullMode(mode1, mode2); else degreeMapIn = getModeToModePeriodMap(mode1, mode2); NoteMap mappingOut; int midiNote; for (int m = 0; m < mappingOut.getSize(); m++) { midiNote = degreeMapIn[m]; if (midiNote >= 0) { mappingOut.setValue(m, midiNote); } else { mappingOut.setValue(m, -1); } } //DBG("Root note from mode 1 is " + String(mode1.getRootNote()) + // " and it produces the note " + String(mappingOut.getValue(mode1.getRootNote())) + // ". Root note from mode 2 is " + String(mode2.getRootNote())); return mappingOut; } NoteMap ModeMapper::mapByOrder(const Mode& mode1, const Mode& mode2, int mode1Order, int mode2Order, int mode1Offset, int mode2Offset, NoteMap prevMap) { mode1Order = jlimit(0, mode1.getMaxStep() - 1, mode1Order); mode2Order = jlimit(0, mode2.getMaxStep() - 1, mode2Order); Array<int> midiNotesFrom = mode1.getNotesOfOrder(mode1Order); Array<int> midiNotesTo = mode2.getNotesOfOrder(mode2Order); mode1Offset = jlimit(0, midiNotesFrom.size() - 1, mode1Offset); mode2Offset = jlimit(0, midiNotesTo.size() - 1, mode2Offset); int rootNoteFrom = mode1.getRootNote(); int rootNoteTo = mode2.getRootNote(); int rootIndexFrom = mode1.getNotesOfOrder().indexOf(rootNoteFrom); int rootIndexTo = mode2.getNotesOfOrder().indexOf(rootNoteTo); int rootIndexOffset = rootIndexTo - rootIndexFrom + mode2Offset - mode1Offset; int mode1Index, mode2Index; int noteFrom, noteTo; for (int m = 0; m < midiNotesFrom.size(); m++) { // might make more sense to not have a mode1Offset mode1Index = totalModulus(m + mode1Offset, midiNotesFrom.size()); mode2Index = totalModulus(m + rootIndexOffset + mode2Offset, midiNotesTo.size()); noteFrom = midiNotesFrom[mode1Index]; noteTo = midiNotesTo[mode2Index]; if (noteFrom > 0) prevMap.setValue(noteFrom, noteTo); } return prevMap; } NoteMap ModeMapper::mapToMode1Period(const Mode& mode1, const Mode& mode2, Array<int> degreeMapIn) { // ensure degree map is the same size as Mode1 Period if (degreeMapIn.size() != mode1.getScaleSize()) degreeMapIn = getModeToModePeriodMap(mode1, mode2); int rootNoteFrom = mode1.getRootNote(); int rootNoteTo = mode2.getRootNote(); int rootNoteOffset = rootNoteTo - rootNoteFrom; int degreeOffset = rootNoteTo - (ceil(rootNoteTo / (float) mode2.getScaleSize())) * degreeMapIn.size(); int midiOffset = (int)(ceil(rootNoteTo / (float) mode2.getScaleSize())) * mode2.getScaleSize() - rootNoteTo + rootNoteOffset; //DBG("Degree Offset is " + String(degreeOffset)); //DBG("Midi Offset is " + String(midiOffset)); NoteMap mappingOut; int mapIndex; int periods; int midiNote; for (int m = 0; m < mappingOut.getSize(); m++) { mapIndex = m - degreeOffset; if (mapIndex >= 0) { periods = mapIndex / degreeMapIn.size(); midiNote = degreeMapIn[mapIndex % degreeMapIn.size()] + periods * mode2.getScaleSize() - midiOffset; } else midiNote = -1; mappingOut.setValue(m, midiNote); //if (m == rootNoteFrom) // DBG("Root Note From (" + String(rootNoteFrom) + ") produces note " + String(mappingOut.getValue(rootNoteFrom)) + " and comapre that to the Root note to (" + String(rootNoteTo) + ")"); } return mappingOut; } NoteMap ModeMapper::mapToMode1Scale(const Mode& mode1, const Mode& mode2, int mode2Order) { Array<int> mode2ModalNotes = mode2.getNotesOfOrder(mode2Order); int mode1RootIndex = mode1.getRootNote(); int mode2RootIndex = mode2ModalNotes.indexOf(mode2.getRootNote()); int rootIndexOffset = mode2RootIndex - mode1RootIndex; NoteMap mappingOut; int degToAdd; int mode2ModeIndex = 0; for (int m = 0; m < mode1.getOrders().size(); m++) { mode2ModeIndex = m + rootIndexOffset; if (mode2ModeIndex < 0) { degToAdd = mode2ModeIndex; } else if (mode2ModeIndex >= mode2ModalNotes.size()) { degToAdd = 128; } else { degToAdd = mode2ModalNotes[mode2ModeIndex]; } mappingOut.setValue(m, degToAdd); //if (m == mode1.getRootNote()) // DBG("Root Note From (" + String(mode1.getRootNote()) + ") produces note " + String(mappingOut.getValue(mode1.getRootNote())) + " and comapre that to the Root note to (" + String(mode2.getRootNote()) + ")"); } return mappingOut; } NoteMap ModeMapper::stdMidiToMode(const Mode& modeMapped, int rootNoteStd) { Mode meantone7_12(STD_TUNING_MODE_NODE); if (modeMapped.getModeSize() == meantone7_12.getModeSize()) return mapToMode1Period(meantone7_12, modeMapped); else return mapFull(meantone7_12, modeMapped); } Array<int> ModeMapper::getModeToModePeriodMap(const Mode& mode1, const Mode& mode2) { Array<int> degreeMapOut; Array<int> mode1Steps = mode1.getSteps(); Array<int> mode2Steps = mode2.getSteps(); int mode1ModeSize = mode1.getModeSize(); int mode2ModeSize = mode2.getModeSize(); int mode2ScaleIndex = 0; int degToAdd; int degSub; float stepFraction; float mode1Step; float mode2Step; for (int m1 = 0; m1 < mode2ModeSize; m1++) { mode1Step = mode1Steps[m1 % mode1ModeSize]; mode2Step = mode2Steps[m1]; degreeMapOut.add(mode2ScaleIndex); for (int d1 = 1; d1 < mode1Step; d1++) { stepFraction = d1 / mode1Step; // round up to the next mode degree degSub = mode2Step; // find closest degree for (int d2 = 1; d2 < mode2Step; d2++) { if (abs(d2 / mode2Step - stepFraction) < abs(degSub / mode2Step - stepFraction)) degSub = d2; } // resulting degree is the sum of previous steps, plus the next closest sub degree within the modal step degToAdd = mode2ScaleIndex + degSub; degreeMapOut.add(degToAdd); } mode2ScaleIndex += mode2Step; } //DBGArray(degreeMapOut, "Mode1 -> Mode2 Scale Degrees"); return degreeMapOut; } Array<int> ModeMapper::getScaleToModePeriodMap(const Mode& mode1, const Mode& mode2) { Array<int> degreeMapOut; Array<int> mode2Steps = mode2.getSteps(); int mode2ScaleIndex = 0; for (int i = 0; i < mode2Steps.size(); i++) { degreeMapOut.add(mode2ScaleIndex); mode2ScaleIndex += mode2Steps[i]; } //DBGArray(degreeMapOut, "Mode1 -> Mode2 Scale Degrees"); return degreeMapOut; } Array<int> ModeMapper::degreeMapFullMode(const Mode& mode1, const Mode& mode2) { Array<int> degreeMapOut; //DBG("Mode1 Root: " + String(mode1.getRootNote()) + "\tMode2Root: " + String(mode2.getRootNote())); Array<int> mode1Steps = Mode::foldOrdersToSteps(mode1.getOrders()); Array<int> mode2Steps = Mode::foldOrdersToSteps(mode2.getOrders()); Array<int> mode1MidiNotes = Mode::sumArray(mode1Steps, 0, true); Array<int> mode2MidiNotes = Mode::sumArray(mode2Steps, 0, true); int mode1RootIndex = mode1MidiNotes.indexOf(mode1.getRootNote()); int mode2RootIndex = mode2MidiNotes.indexOf(mode2.getRootNote()); int rootIndexOffset = mode2RootIndex - mode1RootIndex; //DBG("Mode1 Root Index: " + String(mode1RootIndex) + "\tMode2Root: " + String(mode2RootIndex)); //DBGArray(mode2MidiNotes, "Mode2 Midi Notes"); int mode2ScaleIndex = 0; if (rootIndexOffset > 0) { mode2ScaleIndex = sumUpToIndex(mode2Steps, rootIndexOffset); } int degToAdd, degSub; float stepFraction; float mode1Step, mode2Step; int mode2ModeIndex = 0; for (int m = 0; m < mode1Steps.size(); m++) { mode2ModeIndex = m + rootIndexOffset; // this is assuming that the order will always start at 0 mode1Step = mode1Steps[m]; if (mode2ModeIndex < 0) { mode2Step = 0; degToAdd = mode2ModeIndex; } else if (mode2ModeIndex >= mode2Steps.size()) { mode2Step = 0; degToAdd = 128; } else { mode2Step = mode2Steps[mode2ModeIndex]; degToAdd = mode2ScaleIndex; } degreeMapOut.add(degToAdd); for (int d1 = 1; d1 < mode1Step; d1++) { stepFraction = d1 / mode1Step; // round up to the next mode degree degSub = mode2Step; // find closest degree for (int d2 = 1; d2 < mode2Step; d2++) { if (abs(d2 / mode2Step - stepFraction) < abs(degSub / mode2Step - stepFraction)) degSub = d2; } // resulting degree is the sum of previous steps, plus the next closest sub degree within the modal step degToAdd = mode2ScaleIndex + degSub; if (mode2ModeIndex < 0) degreeMapOut.add(mode2ModeIndex); else degreeMapOut.add(degToAdd); } mode2ScaleIndex += mode2Step; } return degreeMapOut; }
29.106776
220
0.621869
vsicurella
d18dfda5a300940a36a693815729262068d573ec
519
cpp
C++
golang/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp
Hubstation/100challenges
68189cde28cadc91bcabe2d12a68703ce913099f
[ "MIT" ]
43
2020-08-30T18:12:35.000Z
2022-03-08T05:03:05.000Z
golang/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp
sangam14/challenges
d71cbb3960bc3adb43311959ca5694c1de63401c
[ "MIT" ]
15
2020-08-30T18:12:24.000Z
2020-10-08T17:02:50.000Z
golang/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp
sangam14/challenges
d71cbb3960bc3adb43311959ca5694c1de63401c
[ "MIT" ]
24
2020-08-31T15:07:24.000Z
2021-02-28T09:56:46.000Z
// Forward declaration of guess API. // @param num, your guess // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 int guess(int num); class Solution { public: int guessNumber(int n) { int left = 1, right = n; int mid; while (left <= right) { mid = left + (right-left)/2; cout << mid << endl; if (guess(mid) == 0) break; else if (guess(mid) > 0) left = mid+1; else right = mid-1; } return mid; } };
25.95
81
0.535645
Hubstation
d19131e69731fa7a7bc8d6efc64169f17569cc7a
445
cpp
C++
oclint-rules/lib/util/StdUtil.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
3,128
2015-01-01T06:00:31.000Z
2022-03-29T23:43:20.000Z
oclint-rules/lib/util/StdUtil.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
432
2015-01-03T15:43:08.000Z
2022-03-29T02:32:48.000Z
oclint-rules/lib/util/StdUtil.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
454
2015-01-06T03:11:12.000Z
2022-03-22T05:49:38.000Z
#include "oclint/util/StdUtil.h" #include <algorithm> bool isUnderscore(char aChar) { return aChar == '_'; } std::string removeUnderscores(std::string str) { str.erase(remove_if(str.begin(), str.end(), &::isUnderscore), str.end()); return str; } std::string capitalizeFirstLetter(std::string str) { if(str.length() > 0) { std::transform(str.begin(), str.begin() + 1, str.begin(), ::toupper); } return str; }
21.190476
77
0.631461
BGU-AiDnD
d19738d3084cd0541338794eb0104cc4a8292104
15,644
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgAnimation/Interpolator.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgAnimation/Interpolator.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgAnimation/Interpolator.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/Matrixf> #include <osg/Quat> #include <osg/Vec2> #include <osg/Vec3> #include <osg/Vec4> #include <osgAnimation/CubicBezier> #include <osgAnimation/Interpolator> #include <osgAnimation/Vec3Packed> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif TYPE_NAME_ALIAS(osgAnimation::TemplateStepInterpolator< double COMMA double >, osgAnimation::DoubleStepInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateStepInterpolator< float COMMA float >, osgAnimation::FloatStepInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateStepInterpolator< osg::Vec2 COMMA osg::Vec2 >, osgAnimation::Vec2StepInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateStepInterpolator< osg::Vec3 COMMA osg::Vec3 >, osgAnimation::Vec3StepInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateStepInterpolator< osg::Vec3 COMMA osgAnimation::Vec3Packed >, osgAnimation::Vec3PackedStepInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateStepInterpolator< osg::Vec4 COMMA osg::Vec4 >, osgAnimation::Vec4StepInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateStepInterpolator< osg::Quat COMMA osg::Quat >, osgAnimation::QuatStepInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateLinearInterpolator< double COMMA double >, osgAnimation::DoubleLinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateLinearInterpolator< float COMMA float >, osgAnimation::FloatLinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateLinearInterpolator< osg::Vec2 COMMA osg::Vec2 >, osgAnimation::Vec2LinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateLinearInterpolator< osg::Vec3 COMMA osg::Vec3 >, osgAnimation::Vec3LinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateLinearInterpolator< osg::Vec3 COMMA osgAnimation::Vec3Packed >, osgAnimation::Vec3PackedLinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateLinearInterpolator< osg::Vec4 COMMA osg::Vec4 >, osgAnimation::Vec4LinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateSphericalLinearInterpolator< osg::Quat COMMA osg::Quat >, osgAnimation::QuatSphericalLinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateLinearInterpolator< osg::Matrixf COMMA osg::Matrixf >, osgAnimation::MatrixLinearInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateCubicBezierInterpolator< float COMMA osgAnimation::FloatCubicBezier >, osgAnimation::FloatCubicBezierInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateCubicBezierInterpolator< double COMMA osgAnimation::DoubleCubicBezier >, osgAnimation::DoubleCubicBezierInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateCubicBezierInterpolator< osg::Vec2 COMMA osgAnimation::Vec2CubicBezier >, osgAnimation::Vec2CubicBezierInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateCubicBezierInterpolator< osg::Vec3 COMMA osgAnimation::Vec3CubicBezier >, osgAnimation::Vec3CubicBezierInterpolator) TYPE_NAME_ALIAS(osgAnimation::TemplateCubicBezierInterpolator< osg::Vec4 COMMA osgAnimation::Vec4CubicBezier >, osgAnimation::Vec4CubicBezierInterpolator) BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateCubicBezierInterpolator< double COMMA osgAnimation::DoubleCubicBezier >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateCubicBezierInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osgAnimation::DoubleCubicBezier > &, keyframes, IN, float, time, IN, double &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateCubicBezierInterpolator< float COMMA osgAnimation::FloatCubicBezier >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateCubicBezierInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osgAnimation::FloatCubicBezier > &, keyframes, IN, float, time, IN, float &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateCubicBezierInterpolator< osg::Vec2 COMMA osgAnimation::Vec2CubicBezier >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateCubicBezierInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osgAnimation::Vec2CubicBezier > &, keyframes, IN, float, time, IN, osg::Vec2 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateCubicBezierInterpolator< osg::Vec3 COMMA osgAnimation::Vec3CubicBezier >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateCubicBezierInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osgAnimation::Vec3CubicBezier > &, keyframes, IN, float, time, IN, osg::Vec3 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateCubicBezierInterpolator< osg::Vec4 COMMA osgAnimation::Vec4CubicBezier >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateCubicBezierInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osgAnimation::Vec4CubicBezier > &, keyframes, IN, float, time, IN, osg::Vec4 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateLinearInterpolator< double COMMA double >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< double > &, keyframes, IN, float, time, IN, double &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateLinearInterpolator< float COMMA float >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< float > &, keyframes, IN, float, time, IN, float &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateLinearInterpolator< osg::Matrixf COMMA osg::Matrixf >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Matrixf > &, keyframes, IN, float, time, IN, osg::Matrixf &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateLinearInterpolator< osg::Vec2 COMMA osg::Vec2 >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Vec2 > &, keyframes, IN, float, time, IN, osg::Vec2 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateLinearInterpolator< osg::Vec3 COMMA osg::Vec3 >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Vec3 > &, keyframes, IN, float, time, IN, osg::Vec3 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateLinearInterpolator< osg::Vec3 COMMA osgAnimation::Vec3Packed >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osgAnimation::Vec3Packed > &, keyframes, IN, float, time, IN, osg::Vec3 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateLinearInterpolator< osg::Vec4 COMMA osg::Vec4 >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Vec4 > &, keyframes, IN, float, time, IN, osg::Vec4 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateSphericalLinearInterpolator< osg::Quat COMMA osg::Quat >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateSphericalLinearInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Quat > &, keyframes, IN, float, time, IN, osg::Quat &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateStepInterpolator< double COMMA double >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateStepInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< double > &, keyframes, IN, float, time, IN, double &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateStepInterpolator< float COMMA float >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateStepInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< float > &, keyframes, IN, float, time, IN, float &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateStepInterpolator< osg::Quat COMMA osg::Quat >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateStepInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Quat > &, keyframes, IN, float, time, IN, osg::Quat &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateStepInterpolator< osg::Vec2 COMMA osg::Vec2 >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateStepInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Vec2 > &, keyframes, IN, float, time, IN, osg::Vec2 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateStepInterpolator< osg::Vec3 COMMA osg::Vec3 >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateStepInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Vec3 > &, keyframes, IN, float, time, IN, osg::Vec3 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateStepInterpolator< osg::Vec3 COMMA osgAnimation::Vec3Packed >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateStepInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osgAnimation::Vec3Packed > &, keyframes, IN, float, time, IN, osg::Vec3 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgAnimation::TemplateStepInterpolator< osg::Vec4 COMMA osg::Vec4 >) I_DeclaringFile("osgAnimation/Interpolator"); I_BaseType(osgAnimation::TemplateInterpolatorBase); I_Constructor0(____TemplateStepInterpolator, "", ""); I_Method3(void, getValue, IN, const osgAnimation::TemplateKeyframeContainer< osg::Vec4 > &, keyframes, IN, float, time, IN, osg::Vec4 &, result, Properties::NON_VIRTUAL, __void__getValue__C5_TemplateKeyframeContainerT1_KEY__R1__float__TYPE_R1, "", ""); END_REFLECTOR
47.406061
165
0.73338
UM-ARM-Lab
d19ac18a784ff2d5e63066a3d2b0f7cef6c14515
3,582
cpp
C++
lib/test/ContactTest.cpp
luocf/Elastos.SDK.ElephantWallet.Contact
361167b010483b0cc99ed094e376d4486a9fe001
[ "MIT" ]
null
null
null
lib/test/ContactTest.cpp
luocf/Elastos.SDK.ElephantWallet.Contact
361167b010483b0cc99ed094e376d4486a9fe001
[ "MIT" ]
null
null
null
lib/test/ContactTest.cpp
luocf/Elastos.SDK.ElephantWallet.Contact
361167b010483b0cc99ed094e376d4486a9fe001
[ "MIT" ]
null
null
null
#include <ElephantContact.hpp> #include <Elastos.SDK.Keypair.C/Elastos.Wallet.Utility.h> #include <memory> #include <fstream> #include <iostream> #include <thread> #include <signal.h> #include <DateTime.hpp> #include <Platform.hpp> #include <Log.hpp> #include <MD5.hpp> #include "ContactTestCmd.hpp" #include "P2PNetworkBase.hpp" #include "P2PNetworkSdk.hpp" #include "P2PNetworkBridge.hpp" #include "MicroServiceTest.hpp" const char* keypairLanguage = "english"; const char* keypairWords = ""; std::string gSavedMnemonic; std::string gCachedMnemonic; std::thread gCmdPipeMonitor; bool gQuitFlag = false; void loop(const char* fifoFilePath); void signalHandler(int sig); std::shared_ptr<elastos::MicroServiceTest> mMicroServiceTest; int main(int argc, char **argv) { signal(SIGSEGV, signalHandler); signal(SIGABRT, signalHandler); const char* nickname = "Friend"; const char* fifoFilePath = (argc > 1 ? argv[1] : nullptr); if(fifoFilePath != nullptr) { // gSavedMnemonic = "bachelor sail glove swing despair lawsuit exhibit travel slot practice latin glass"; nickname = "Me"; } else { gSavedMnemonic = "month business urban nurse joy derive acquire snap venue hello city buyer"; } elastos::P2PNetworkBridge& p2pNetworkBridge = elastos::P2PNetworkBridge::getInstance(); //设置使用p2p network sdk 或者p2p network carrier p2pNetworkBridge.SetP2PNetwork(std::make_shared<elastos::P2PNetworkSdk>()); mMicroServiceTest = std::make_shared<elastos::MicroServiceTest>(); std::string publicKey = "02bc11aa5c35acda6f6f219b94742dd9a93c1d11c579f98f7e3da05ad910a48306"; mMicroServiceTest->Create(publicKey, "/tmp/elastos.sdk.contact/test"); mMicroServiceTest->Start(); Log::I(Log::TAG, "Start Contact Test."); Log::I(Log::TAG, "%s\n", (argc > 1 ? argv[1]:"")); gCachedMnemonic.clear(); loop(fifoFilePath); return 0; } void processCmd(const std::string& cmdLine) { /*if (cmdLine.empty() == true) { std::cout << "# "; std::this_thread::sleep_for(std::chrono::milliseconds(100)); return; } Log::I(Log::TAG, "==> Received Command: %s", cmdLine.c_str()); std::string errMsg; int ret = ContactTestCmd::Do(contact, cmdLine, errMsg); if (ret < 0) { Log::E(Log::TAG, "ErrCode(%d): %s", ret, errMsg.c_str()); } else { Log::I(Log::TAG, "Success to exec: %s", cmdLine.c_str()); } std::cout << "# ";*/ } void monitorCmdPipe(const char* fifoFilePath) { if (fifoFilePath == nullptr) { return; } auto funcPipeMonitor = [=] { while (true) { std::string cmdLine; std::ifstream fifoStream(fifoFilePath, std::ifstream::in); std::getline(fifoStream, cmdLine); fifoStream.close(); if (cmdLine == "q" || cmdLine == "quit") { gQuitFlag = true; return; } //processCmd(cmdLine, contact); }; }; gCmdPipeMonitor = std::thread (funcPipeMonitor); } void loop(const char* fifoFilePath) { monitorCmdPipe(fifoFilePath); while (true) { std::string cmdLine; std::getline(std::cin, cmdLine); if (cmdLine == "q" || cmdLine == "quit") { gQuitFlag = true; return; } //processCmd(cmdLine, contact); } } void signalHandler(int sig) { std::cerr << "Error: signal " << sig << std::endl; std::string backtrace = elastos::Platform::GetBacktrace(); std::cerr << backtrace << std::endl; exit(sig); }
27.984375
112
0.633445
luocf
d19c8a04153b320011d0028c51e948cd0d6faf8c
2,575
hpp
C++
modules/core/base/include/nt2/predicates/functions/scalar/isequaln.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/core/base/include/nt2/predicates/functions/scalar/isequaln.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/base/include/nt2/predicates/functions/scalar/isequaln.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_PREDICATES_FUNCTIONS_SCALAR_ISEQUALN_HPP_INCLUDED #define NT2_PREDICATES_FUNCTIONS_SCALAR_ISEQUALN_HPP_INCLUDED #include <nt2/predicates/functions/isequaln.hpp> #include <nt2/include/functions/is_equal_with_equal_nans.hpp> #include <boost/simd/include/functions/all.hpp> namespace nt2 { namespace ext { BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_ , (A0) , (scalar_<unspecified_<A0> >) (scalar_<unspecified_<A0> >) ) { typedef bool result_type; BOOST_FORCEINLINE result_type operator()(const A0& a0, const A0& a1) const { return is_equal_with_equal_nans(a0,a1); } }; BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_ , (A0)(A1) , (unspecified_<A0>) (unspecified_<A1>) ) { typedef bool result_type; BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& a1) const { return a0 == a1; } }; BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_ , (A0)(A1)(X) , ((simd_< unspecified_<A0>, X>)) ((simd_< unspecified_<A1>, X>)) ) { typedef bool result_type; BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& a1) const { return boost::simd::all(is_equal_with_equal_nans(a0, a1)); } }; BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_ , (A0)(A1)(X)(T0)(N0)(T1)(N1) , ((expr_< simd_< unspecified_<A0>, X>, T0, N0>)) ((expr_< simd_< unspecified_<A1>, X>, T1, N1>)) ) { typedef bool result_type; BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& a1) const { return boost::simd::all(is_equal_with_equal_nans(a0, a1))(); } }; } } #endif
32.1875
80
0.503689
psiha
d19d0410333d65dbb1a1d5a7d8399a55b605bc3c
3,325
cpp
C++
marsyas-vamp/marsyas/src/marsyas/marsystems/PatchMatrix.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/marsyas/marsystems/PatchMatrix.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/marsyas/marsystems/PatchMatrix.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
/* ** Copyright (C) 1998-2006 George Tzanetakis <gtzan@cs.uvic.ca> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "../common_source.h" #include "PatchMatrix.h" using namespace Marsyas; //#define MTLB_DBG_LOG PatchMatrix::PatchMatrix(mrs_string name):MarSystem("PatchMatrix", name) { //Add any specific controls needed by PatchMatrix //(default controls all MarSystems should have //were already added by MarSystem::addControl(), //called by :MarSystem(name) constructor). //If no specific controls are needed by a MarSystem //there is no need to implement and call this addControl() //method (see for e.g. Rms.cpp) addControls(); use_consts_=false; use_weights_=false; } PatchMatrix::PatchMatrix(const PatchMatrix& a) : MarSystem(a) { // For any MarControlPtr in a MarSystem // it is necessary to perform this getctrl // in the copy constructor in order for cloning to work ctrl_weights_ = getctrl("mrs_realvec/weights"); ctrl_consts_ = getctrl("mrs_realvec/consts"); use_consts_=a.use_consts_; use_weights_=a.use_weights_; } PatchMatrix::~PatchMatrix() { } MarSystem* PatchMatrix::clone() const { return new PatchMatrix(*this); } void PatchMatrix::addControls() { //Add specific controls needed by this MarSystem. addctrl("mrs_realvec/consts", realvec(), ctrl_consts_); addctrl("mrs_realvec/weights", realvec(), ctrl_weights_); //setControlState("mrs_realvec/consts",true); setControlState("mrs_realvec/weights",true); } void PatchMatrix::myUpdate(MarControlPtr sender) { MarSystem::myUpdate(sender); if(ctrl_weights_->to<mrs_realvec>().getSize()!=0) { use_weights_=true; ctrl_onObservations_->setValue(ctrl_weights_->to<mrs_realvec>().getRows(),NOUPDATE); } } void PatchMatrix::myProcess(realvec& in, realvec& out) { //get a local copy of the current PatchMatrix control's values //(they will be used for this entire processing, even if it's //changed by a different thread) mrs_realvec PatchMatrixValue = ctrl_weights_->to<mrs_realvec>(); mrs_realvec patchConstValues = ctrl_consts_->to<mrs_realvec>(); if(PatchMatrixValue.getSize()!=0) use_weights_=true; if(patchConstValues.getSize()!=0) use_consts_=true; #ifdef MARSYAS_MATLAB #ifdef MTLB_DBG_LOG MATLAB_PUT(in, "in"); MATLAB_EVAL("figure(11),plot(in'),axis('tight'),grid on"); #endif #endif if (use_weights_) { mrs_realvec::matrixMulti(PatchMatrixValue,in,out); } if (use_consts_) { out += patchConstValues; } #ifdef MARSYAS_MATLAB #ifdef MTLB_DBG_LOG MATLAB_PUT(out, "out"); MATLAB_EVAL("figure(12),plot(out'),axis('tight'),grid on"); #endif #endif }
25
88
0.731729
jaouahbi
d19d1daa41c2ed4687505e33e53667bf6024f8a9
416
cpp
C++
p1918_1.cpp
Alex-Amber/LuoguAlgorithmProblems
ae8abdb6110badc9faf03af1af42ea562ca1170c
[ "MIT" ]
null
null
null
p1918_1.cpp
Alex-Amber/LuoguAlgorithmProblems
ae8abdb6110badc9faf03af1af42ea562ca1170c
[ "MIT" ]
null
null
null
p1918_1.cpp
Alex-Amber/LuoguAlgorithmProblems
ae8abdb6110badc9faf03af1af42ea562ca1170c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; unordered_map<int, int> um; int main() { ios::sync_with_stdio(false); cin.tie(0); int N; cin >> N; for (int i = 1; i <= N; i++) { int a; cin >> a; um[a] = i; } int Q; cin >> Q; while (Q) { Q--; int m; cin >> m; cout << (um.count(m) ? um[m] : 0) << "\n"; } return 0; }
16
50
0.40625
Alex-Amber
d19e593f4e8a48266f278e9dd7cae4aaab0c9713
4,655
cpp
C++
src/TacticsVictory/local/Editor/GUI/GUI.cpp
Sasha7b9/U-Cube
442927ff1391bfe78cdf520ad303c7dc29086b46
[ "MIT" ]
null
null
null
src/TacticsVictory/local/Editor/GUI/GUI.cpp
Sasha7b9/U-Cube
442927ff1391bfe78cdf520ad303c7dc29086b46
[ "MIT" ]
null
null
null
src/TacticsVictory/local/Editor/GUI/GUI.cpp
Sasha7b9/U-Cube
442927ff1391bfe78cdf520ad303c7dc29086b46
[ "MIT" ]
null
null
null
// (c) Aleksandr Shevchenko e-mail : Sasha7b9@tut.by #include "stdafx.h" #include "FileSystem/ConfigurationFile_v.h" #include "GUI/Cursor_.h" #include "GUI/GUI.h" #include "GUI/Controls/DropDownListWithTextAndButton_.h" #include "GUI/Controls/GovernorFloat_.h" #include "GUI/Controls/Label_.h" #include "GUI/Controls/Buttons/ButtonSwitch_.h" #include "GUI/Controls/Buttons/ButtonToggled_.h" #include "GUI/Controls/Sliders/Slider_.h" #include "GUI/Controls/Sliders/SliderInt_.h" #include "GUI/Controls/Sliders/SliderWithTextAndButtons_.h" #include "GUI/Menu/PageConfirmExit_.h" #include "GUI/Windows/Console_.h" #include "GUI/Windows/WindowVariables_.h" #include "Scene/Cameras/Camera_.h" GUI::GUI(GUI **self) : GUIT((GUIT **)self) { Create(); *self = this; } GUI::~GUI() { } static float GetPosCameraY() { if (TheCamera == nullptr) { return 0.0f; } return TheCamera->GetPosition().y_; } static void SetPosCameraY(float y) { Vector3 position = TheCamera->GetPosition(); position.y_ = y; TheCamera->SetPosition(position); } static float GetPosCameraX() { return TheCamera->GetPosition().x_; } static void SetPosCameraX(float x) { Vector3 position = TheCamera->GetPosition(); position.x_ = x; TheCamera->SetPosition(position); } static float GetPosCameraZ() { return TheCamera->GetPosition().z_; } static void SetPosCameraZ(float z) { Vector3 position = TheCamera->GetPosition(); position.z_ = z; TheCamera->SetPosition(position); } static float GetCameraPitch() { Quaternion angle = TheCamera->GetNode()->GetRotation(); return angle.PitchAngle(); } static float GetCameraYaw() { Quaternion angle = TheCamera->GetNode()->GetRotation(); return angle.YawAngle(); } static float GetSpeedNetIN() { // if(TheClient->IsConnected()) // { // Connection *connection = TheClient->GetServerConnection(); // return connection->GetBytesInPerSec() / 1e3f; // } // else // { // Vector<SharedPtr<Connection>> connections = TheServer->GetConnections(); // if(connections.Size()) // { // float speed = 0.0f; // for(Connection *connection : connections) // { // speed += connection->GetBytesInPerSec(); // } // return speed / 1e3f; // } // } return 0.0f; } static float GetSpeedNetOUT() { // if(TheClient->GetServerConnection()) // { // Connection *connection = TheClient->GetServerConnection(); // return connection->GetBytesOutPerSec() / 1e3f; // } // else // { // Vector<SharedPtr<Connection>> connections = TheServer->GetConnections(); // if(connections.Size()) // { // float speed = 0.0f; // for(Connection *connection : connections) // { // speed += connection->GetBytesOutPerSec(); // } // return speed / 1e3f; // } // } return 0.0f; } void GUI::Create() { TheConsole = new ConsoleT(); TheUIRoot->AddChild(TheConsole); TheWindowVars = new WindowVariables(); TheUIRoot->AddChild(TheWindowVars); TheWindowVars->SetVisible(false); TheWindowVars->SetPosition(1000, 500); TheWindowVars->AddFunctionFloat("Camera pos Y", GetPosCameraY, SetPosCameraY); TheWindowVars->AddFunctionFloat("Camera pos X", GetPosCameraX, SetPosCameraX); TheWindowVars->AddFunctionFloat("Camera pos Z", GetPosCameraZ, SetPosCameraZ); TheWindowVars->AddFunctionFloat("Camera pitch", GetCameraPitch, nullptr); TheWindowVars->AddFunctionFloat("Camera yaw", GetCameraYaw, nullptr); TheWindowVars->AddFunctionFloat("Net speed in, kB/s", GetSpeedNetIN, nullptr); TheWindowVars->AddFunctionFloat("Net speed out, kB/s", GetSpeedNetOUT, nullptr); TheLocalization->SetLanguage("en"); TheCursor = TheUIRoot->CreateChild<CursorT>("CursorT"); TheLocalization->SetLanguage(TheSettings.GetInt("language") == 0 ? "en" : "ru"); } void GUI::SetVisibleWindow(Control *window, bool visible) { window->SetVisible(visible); if(visible) { while(!TheOpenedWindow.Empty()) { window = TheOpenedWindow.Back(); window->SetVisible(false); TheOpenedWindow.Remove(window); } TheOpenedWindow.Push(window); } else { TheOpenedWindow.Remove(window); } } void GUI::SetUnvisibleAllWindows() { while(!TheOpenedWindow.Empty()) { Control *window = TheOpenedWindow.Back(); window->SetVisible(false); TheOpenedWindow.Remove(window); } }
23.159204
84
0.645113
Sasha7b9
d1a00add84a3d5353b9893b8cb6dcbfb35350be8
2,915
cpp
C++
src/HealthReceiver.cpp
Telecominfraproject/wlan-cloud-analytics
0856e256e99d5f7be18a8b5cd7d543900b99751e
[ "BSD-3-Clause" ]
null
null
null
src/HealthReceiver.cpp
Telecominfraproject/wlan-cloud-analytics
0856e256e99d5f7be18a8b5cd7d543900b99751e
[ "BSD-3-Clause" ]
null
null
null
src/HealthReceiver.cpp
Telecominfraproject/wlan-cloud-analytics
0856e256e99d5f7be18a8b5cd7d543900b99751e
[ "BSD-3-Clause" ]
null
null
null
// // Created by stephane bourque on 2022-03-15. // #include "HealthReceiver.h" #include "VenueWatcher.h" #include "fmt/core.h" namespace OpenWifi { int HealthReceiver::Start() { Running_ = true; Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) { this->HealthReceived(Key,Payload); }; HealthWatcherId_ = KafkaManager()->RegisterTopicWatcher(KafkaTopics::HEALTHCHECK, F); Worker_.start(*this); return 0; } void HealthReceiver::Stop() { Running_ = false; KafkaManager()->UnregisterTopicWatcher(KafkaTopics::HEALTHCHECK, HealthWatcherId_); Queue_.wakeUpAll(); Worker_.join(); } void HealthReceiver::run() { Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); while(Note && Running_) { auto Msg = dynamic_cast<HealthMessage *>(Note.get()); if(Msg!= nullptr) { try { nlohmann::json msg = nlohmann::json::parse(Msg->Payload()); if (msg.contains(uCentralProtocol::PAYLOAD)) { auto payload = msg[uCentralProtocol::PAYLOAD]; uint64_t SerialNumber = Utils::SerialNumberToInt(Msg->Key()); std::lock_guard G(Mutex_); for(const auto &[venue,devices]:Notifiers_) { if(devices.find(SerialNumber)!=cend(devices)) { auto health_data = std::make_shared<nlohmann::json>(payload); venue->PostHealth(SerialNumber, health_data); break; } } } } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { } } else { } Note = Queue_.waitDequeueNotification(); } } void HealthReceiver::Register(const std::vector <uint64_t> &SerialNumber, VenueWatcher *VW) { std::lock_guard G(Mutex_); std::set<uint64_t> NewSerialNumbers; std::copy(SerialNumber.begin(),SerialNumber.end(),std::inserter(NewSerialNumbers,NewSerialNumbers.begin())); auto it = Notifiers_.find(VW); if(it==end(Notifiers_)) Notifiers_[VW]=NewSerialNumbers; else it->second = NewSerialNumbers; } void HealthReceiver::DeRegister(VenueWatcher *VW) { std::lock_guard G(Mutex_); Notifiers_.erase(VW); } void HealthReceiver::HealthReceived(const std::string &Key, const std::string &Payload) { std::lock_guard G(Mutex_); poco_debug(Logger(),fmt::format("Device({}): Health message.", Key)); Queue_.enqueueNotification( new HealthMessage(Key,Payload)); } }
36.4375
137
0.551973
Telecominfraproject
d1a17facf3be385e3591301104754add8c060250
4,834
cpp
C++
gamechannel/chaintochannel.cpp
spaceexpanse/libxgame
f604e81d152d8c697846a3a01278e5305a4d6d3e
[ "MIT" ]
null
null
null
gamechannel/chaintochannel.cpp
spaceexpanse/libxgame
f604e81d152d8c697846a3a01278e5305a4d6d3e
[ "MIT" ]
null
null
null
gamechannel/chaintochannel.cpp
spaceexpanse/libxgame
f604e81d152d8c697846a3a01278e5305a4d6d3e
[ "MIT" ]
null
null
null
// Copyright (C) 2018-2022 The Xaya developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chaintochannel.hpp" #include "protoutils.hpp" #include "proto/metadata.pb.h" #include "proto/stateproof.pb.h" #include <xayautil/base64.hpp> #include <jsonrpccpp/common/errors.h> #include <jsonrpccpp/common/exception.h> #include <glog/logging.h> namespace xaya { ChainToChannelFeeder::ChainToChannelFeeder (ChannelGspRpcClient& r, SynchronisedChannelManager& cm) : rpc(r), manager(cm) { auto cmLocked = manager.Read (); channelIdHex = cmLocked->GetChannelId ().ToHex (); lastBlock.SetNull (); } ChainToChannelFeeder::~ChainToChannelFeeder () { Stop (); CHECK (loop == nullptr); } namespace { /** * Decodes a JSON value (which must be a base64-encoded string) into a * protocol buffer instance of the given type. */ template <typename Proto> Proto DecodeProto (const Json::Value& val) { CHECK (val.isString ()); Proto res; CHECK (ProtoFromBase64 (val.asString (), res)); return res; } } // anonymous namespace void ChainToChannelFeeder::UpdateOnce () { const auto data = rpc.getchannel (channelIdHex); if (data["state"] != "up-to-date") { LOG (WARNING) << "Channel GSP is in state " << data["state"] << ", not updating channel"; return; } const auto& newBlockVal = data["blockhash"]; if (newBlockVal.isNull ()) { /* This will typically not happen, since we already check the return value of waitforchange. But there are two situations where we could get here: On the initial update, and (very unlikely) if the existing state gets detached between the waitforchange call and when we call getchannel. */ LOG (WARNING) << "GSP has no current state yet"; return; } CHECK (newBlockVal.isString ()); CHECK (lastBlock.FromHex (newBlockVal.asString ())); const auto& heightVal = data["height"]; CHECK (heightVal.isUInt ()); const unsigned height = heightVal.asUInt (); LOG (INFO) << "New on-chain best block: " << lastBlock.ToHex () << " at height " << height; const auto& channel = data["channel"]; if (channel.isNull ()) { LOG (INFO) << "Channel " << channelIdHex << " is not known on-chain"; auto cmLocked = manager.Access (); cmLocked->ProcessOnChainNonExistant (lastBlock, height); return; } CHECK (channel.isObject ()); CHECK_EQ (channel["id"].asString (), channelIdHex); const auto meta = DecodeProto<proto::ChannelMetadata> (channel["meta"]["proto"]); const auto proof = DecodeProto<proto::StateProof> (channel["state"]["proof"]); BoardState reinitState; CHECK (DecodeBase64 (channel["reinit"]["base64"].asString (), reinitState)); unsigned disputeHeight = 0; const auto& disputeVal = channel["disputeheight"]; if (!disputeVal.isNull ()) { CHECK (disputeVal.isUInt ()); disputeHeight = disputeVal.asUInt (); } auto cmLocked = manager.Access (); cmLocked->ProcessOnChain (lastBlock, height, meta, reinitState, proof, disputeHeight); LOG (INFO) << "Updated channel from on-chain state: " << channelIdHex; } void ChainToChannelFeeder::RunLoop () { UpdateOnce (); while (!stopLoop) { const std::string lastBlockHex = lastBlock.ToHex (); std::string newBlockHex; try { newBlockHex = rpc.waitforchange (lastBlockHex); } catch (const jsonrpc::JsonRpcException& exc) { /* Especially timeouts are fine, we should just ignore them. A relatively small timeout is needed in order to not block too long when waiting for shutting down the loop. */ VLOG (1) << "Error calling waitforchange: " << exc.what (); CHECK_EQ (exc.GetCode (), jsonrpc::Errors::ERROR_CLIENT_CONNECTOR); continue; } if (newBlockHex.empty ()) { VLOG (1) << "GSP does not have any state yet"; continue; } if (newBlockHex == lastBlockHex) { VLOG (1) << "We are already at newest block"; continue; } UpdateOnce (); } } void ChainToChannelFeeder::Start () { LOG (INFO) << "Starting chain-to-channel feeder loop..."; CHECK (loop == nullptr) << "Feeder loop is already running"; stopLoop = false; loop = std::make_unique<std::thread> ([this] () { RunLoop (); }); } void ChainToChannelFeeder::Stop () { if (loop == nullptr) return; LOG (INFO) << "Stopping chain-to-channel feeder loop..."; stopLoop = true; loop->join (); loop.reset (); } } // namespace xaya
25.046632
80
0.627431
spaceexpanse
d1a3ecacda23163b4a5176ba1e33b4b1015aa144
1,736
cpp
C++
AlgorithmsandDataStructures/7thLab/g(DividersOfPermutation).cpp
ShuffleZZZ/ITMO
29db54d96afef0558550471c58f695c962e1f747
[ "MIT" ]
11
2020-04-23T15:48:18.000Z
2022-02-11T10:16:40.000Z
AlgorithmsandDataStructures/7thLab/g(DividersOfPermutation).cpp
ShuffleZZZ/ITMO
29db54d96afef0558550471c58f695c962e1f747
[ "MIT" ]
13
2020-02-28T01:16:06.000Z
2020-07-20T19:05:34.000Z
AlgorithmsandDataStructures/7thLab/g(DividersOfPermutation).cpp
ShuffleZZZ/ITMO
29db54d96afef0558550471c58f695c962e1f747
[ "MIT" ]
10
2018-12-02T15:03:03.000Z
2022-01-10T18:31:00.000Z
#include <fstream> using namespace std; int ans = 0; int eratosfen[168] = {2,3,5,7,11,13,17,19,23,29,31,37, 41,43,47,53,59,61,67,71,73,79,83,89, 97,101,103,107,109,113,127,131,137,139,149,151, 157,163,167,173,179,181,191,193,197,199,211,223, 227,229,233,239,241,251,257,263,269,271,277,281, 283,293,307,311,313,317,331,337,347,349,353,359, 367,373,379,383,389,397,401,409,419,421,431,433, 439,443,449,457,461,463,467,479,487,491,499,503, 509,521,523,541,547,557,563,569,571,577,587,593, 599,601,607,613,617,619,631,641,643,647,653,659, 661,673,677,683,691,701,709,719,727,733,739,743, 751,757,761,769,773,787,797,809,811,821,823,827, 829,839,853,857,859,863,877,881,883,887,907,911, 919,929,937,941,947,953,967,971,977,983,991,997}; bool permu(int *a, int n) { int j = n - 2; while ((j != -1) and (a[j] >= a[j + 1])) --j; if (j == -1) return 0; int k = n - 1; while (a[j] >= a[k]) --k; swap(a[j], a[k]); int l = j + 1, r = n - 1; while (l < r) swap(a[l++], a[r--]); return 1; } void check(int res) { if (res == 0) { ++ans; return; } int amount = 1, i = 0, was = 1; while (res != 1) { if (res % eratosfen[i] == 0) { ++amount; res /= eratosfen[i]; } else { was *= amount; amount = 1; ++i; } } was *= amount; if (was % 3 == 0) ++ans; } int main() { ifstream in; in.open("beautiful.in"); ofstream out; out.open("beautiful.out"); int n, r; in >> n >> r; int a[n]; unsigned long long res = 0; for (int i = 0; i < n; i++) a[i] = i + 1; for (int i = 0; i < n - 1; ++i) res += a[i] * a[i + 1]; res %= r; check(res); while(permu(a, n)) { res = 0; for (int i = 0; i < n - 1; ++i) res += a[i] * a[i + 1]; res %= r; check(res); } out << ans; in.close(); out.close(); }
22.842105
57
0.562788
ShuffleZZZ
d1a87f9ce2a21490608be2d075b3d9f5433f3c2e
1,316
cpp
C++
Codes/SimpleResult.cpp
liyuan-rey/UltraReplace
9b67541ac0c4a7d46e86f61a2c9148f05e1b5052
[ "MIT" ]
1
2018-03-26T04:48:22.000Z
2018-03-26T04:48:22.000Z
Codes/SimpleResult.cpp
liyuan-rey/UltraReplace
9b67541ac0c4a7d46e86f61a2c9148f05e1b5052
[ "MIT" ]
null
null
null
Codes/SimpleResult.cpp
liyuan-rey/UltraReplace
9b67541ac0c4a7d46e86f61a2c9148f05e1b5052
[ "MIT" ]
1
2018-03-26T04:48:26.000Z
2018-03-26T04:48:26.000Z
// SimpleResult.cpp: implementation of the CSimpleResult class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ur.h" #include "SimpleResult.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CSimpleResult::CSimpleResult() { } CSimpleResult::~CSimpleResult() { } CSimpleResult::CSimpleResult(const CSimpleResult & rhs) { m_strTaskName = rhs.m_strTaskName; Clean(); m_arrAccessErr.Copy(rhs.m_arrAccessErr); m_arrMatch.Copy(rhs.m_arrMatch); m_arrBackupErr.Copy(rhs.m_arrBackupErr); } CSimpleResult& CSimpleResult::operator = (const CSimpleResult& rhs) { if(this == &rhs) return *this; m_strTaskName = rhs.m_strTaskName; Clean(); m_arrAccessErr.Copy(rhs.m_arrAccessErr); m_arrMatch.Copy(rhs.m_arrMatch); m_arrBackupErr.Copy(rhs.m_arrBackupErr); return *this; } void CSimpleResult::Clean() { m_arrAccessErr.RemoveAll(); m_arrAccessErr.FreeExtra(); m_arrMatch.RemoveAll(); m_arrMatch.FreeExtra(); m_arrBackupErr.RemoveAll(); m_arrBackupErr.FreeExtra(); }
21.225806
71
0.601064
liyuan-rey
d1aef86ac4f6edd736f8f5c751f8ff3a63dc34e2
1,845
cpp
C++
util_file.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
3
2018-09-03T20:55:24.000Z
2020-10-04T04:36:30.000Z
util_file.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
4
2018-09-06T04:12:41.000Z
2020-10-06T14:43:14.000Z
util_file.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
null
null
null
#include <sys/types.h> #include <sys/stat.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "scoped.hpp" #include "util_file.hpp" namespace util { template < typename T > class generic_free { public: void operator()(T* arg) { free(arg); } }; template <> class scoped_functor< FILE > { public: void operator()(FILE* arg) { fclose(arg); } }; bool get_file_size( const char* const filename, size_t& size) { assert(0 != filename); struct stat filestat; if (-1 == stat(filename, &filestat)) { fprintf(stderr, "%s cannot stat file '%s'\n", __FUNCTION__, filename); return false; } if (!S_ISREG(filestat.st_mode)) { fprintf(stderr, "%s encountered a non-regular file '%s'\n", __FUNCTION__, filename); return false; } size = filestat.st_size; return true; } char* get_buffer_from_file( const char* const filename, size_t& size, const size_t roundToIntegralMultiple) { assert(0 != filename); assert(0 == (roundToIntegralMultiple & roundToIntegralMultiple - 1)); if (!get_file_size(filename, size)) { fprintf(stderr, "%s cannot get size of file '%s'\n", __FUNCTION__, filename); return 0; } const scoped_ptr< FILE, scoped_functor > file(fopen(filename, "rb")); if (0 == file()) { fprintf(stderr, "%s cannot open file '%s'\n", __FUNCTION__, filename); return 0; } const size_t roundTo = roundToIntegralMultiple - 1; scoped_ptr< char, generic_free > source( reinterpret_cast< char* >(malloc((size + roundTo) & ~roundTo))); if (0 == source()) { fprintf(stderr, "%s cannot allocate memory for file '%s'\n", __FUNCTION__, filename); return 0; } if (1 != fread(source(), size, 1, file())) { fprintf(stderr, "%s cannot read from file '%s'\n", __FUNCTION__, filename); return 0; } char* const ret = source(); source.reset(); return ret; } } // namespace util
19.62766
87
0.669919
blu
d1af1a5e3aced8e32979c69a0efe799f4aa4d042
31
hpp
C++
src/boost_units_pow.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_units_pow.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_units_pow.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/units/pow.hpp>
15.5
30
0.741935
miathedev
d1b1293664431df2a42048829525e7e63dc37cb3
4,187
cxx
C++
src/IO/ImageBase/ProcessImageChunks/Code.cxx
kian-weimer/ITKSphinxExamples
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
[ "Apache-2.0" ]
34
2015-01-26T19:38:36.000Z
2021-02-04T02:15:41.000Z
src/IO/ImageBase/ProcessImageChunks/Code.cxx
kian-weimer/ITKSphinxExamples
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
[ "Apache-2.0" ]
142
2016-01-22T15:59:25.000Z
2021-03-17T15:11:19.000Z
src/IO/ImageBase/ProcessImageChunks/Code.cxx
kian-weimer/ITKSphinxExamples
ff614cbba28831d1bf2a0cfaa5a2f1949a627c1b
[ "Apache-2.0" ]
32
2015-01-26T19:38:41.000Z
2021-03-17T15:28:14.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkMedianImageFilter.h" int main(int argc, char * argv[]) { if (argc != 3) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0]; std::cerr << " <InputFileName> <OutputFileName>"; std::cerr << std::endl; return EXIT_FAILURE; } const char * inputFileName = argv[1]; const char * outputFileName = argv[2]; const int xDiv = 6; const int yDiv = 4; const int zDiv = 1; // 1 for 2D input constexpr unsigned int Dimension = 3; using PixelType = unsigned char; using ImageType = itk::Image<PixelType, Dimension>; const auto input = itk::ReadImage<ImageType>(inputFileName); ImageType::RegionType fullRegion = input->GetLargestPossibleRegion(); ImageType::SizeType fullSize = fullRegion.GetSize(); // when reading image from file, start index is always 0 ImageType::IndexType start; ImageType::IndexType end; ImageType::SizeType size; using MedianType = itk::MedianImageFilter<ImageType, ImageType>; MedianType::Pointer median = MedianType::New(); median->SetInput(input); median->SetRadius(2); using WriterType = itk::ImageFileWriter<ImageType>; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputFileName); // Use for loops to split the image into chunks. // This way of splitting gives us easy control over it. // For example, we could make the regions always be of equal size // in order to create samples for a deep learning algorithm. // ImageRegionSplitterMultidimensional has a similar // functionality to what is implemented below. for (int z = 0; z < zDiv; z++) { start[2] = fullSize[2] * double(z) / zDiv; end[2] = fullSize[2] * (z + 1.0) / zDiv; size[2] = end[2] - start[2]; for (int y = 0; y < yDiv; y++) { start[1] = fullSize[1] * double(y) / yDiv; end[1] = fullSize[1] * (y + 1.0) / yDiv; size[1] = end[1] - start[1]; for (int x = 0; x < xDiv; x++) { start[0] = fullSize[0] * double(x) / xDiv; end[0] = fullSize[0] * (x + 1.0) / xDiv; size[0] = end[0] - start[0]; ImageType::RegionType region; region.SetIndex(start); region.SetSize(size); // now that we have our chunk, request the filter to only process that median->GetOutput()->SetRequestedRegion(region); median->Update(); ImageType::Pointer result = median->GetOutput(); // only needed in case of further manual processing result->DisconnectPipeline(); // possible additional non-ITK pipeline processing writer->SetInput(result); // convert region into IO region itk::ImageIORegion ioRegion(Dimension); ioRegion.SetIndex(0, start[0]); ioRegion.SetIndex(1, start[1]); ioRegion.SetIndex(2, start[2]); ioRegion.SetSize(0, region.GetSize()[0]); ioRegion.SetSize(1, region.GetSize()[1]); ioRegion.SetSize(2, region.GetSize()[2]); // tell the writer this is only a chunk of a larger image writer->SetIORegion(ioRegion); try { writer->Update(); } catch (itk::ExceptionObject & error) { std::cerr << "Exception for chunk: " << x << ' ' << y << ' ' << z << error << std::endl; return EXIT_FAILURE; } } } } return EXIT_SUCCESS; }
31.719697
98
0.60855
kian-weimer
d1b4ac06bed47059c890b3262ed186eda852e980
3,013
cpp
C++
third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/layout/LayoutTestHelper.h" #include "core/frame/FrameHost.h" #include "core/html/HTMLIFrameElement.h" #include "platform/scroll/ScrollbarTheme.h" namespace blink { RenderingTest::RenderingTest(FrameLoaderClient* frameLoaderClient) : m_frameLoaderClient(frameLoaderClient) { } void RenderingTest::SetUp() { Page::PageClients pageClients; fillWithEmptyClients(pageClients); DEFINE_STATIC_LOCAL(EmptyChromeClient, chromeClient, (EmptyChromeClient::create())); pageClients.chromeClient = &chromeClient; m_pageHolder = DummyPageHolder::create(IntSize(800, 600), &pageClients, m_frameLoaderClient.release(), settingOverrider()); Settings::setMockScrollbarsEnabled(true); RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(true); EXPECT_TRUE(ScrollbarTheme::theme().usesOverlayScrollbars()); // This ensures that the minimal DOM tree gets attached // correctly for tests that don't call setBodyInnerHTML. document().view()->updateAllLifecyclePhases(); } void RenderingTest::TearDown() { if (m_subframe) { m_subframe->detach(FrameDetachType::Remove); static_cast<SingleChildFrameLoaderClient*>(document().frame()->client())->setChild(nullptr); document().frame()->host()->decrementSubframeCount(); } // We need to destroy most of the Blink structure here because derived tests may restore // RuntimeEnabledFeatures setting during teardown, which happens before our destructor // getting invoked, breaking the assumption that REF can't change during Blink lifetime. m_pageHolder = nullptr; } Document& RenderingTest::setupChildIframe(const AtomicString& iframeElementId, const String& htmlContentOfIframe) { // TODO(pdr): This should be refactored to share code with the actual setup // instead of partially duplicating it here (e.g., LocalFrame::createView). HTMLIFrameElement& iframe = *toHTMLIFrameElement(document().getElementById(iframeElementId)); m_childFrameLoaderClient = FrameLoaderClientWithParent::create(document().frame()); m_subframe = LocalFrame::create(m_childFrameLoaderClient.get(), document().frame()->host(), &iframe); m_subframe->setView(FrameView::create(m_subframe.get(), IntSize(500, 500))); m_subframe->init(); m_subframe->view()->setParentVisible(true); m_subframe->view()->setSelfVisible(true); iframe.setWidget(m_subframe->view()); static_cast<SingleChildFrameLoaderClient*>(document().frame()->client())->setChild(m_subframe.get()); document().frame()->host()->incrementSubframeCount(); Document& frameDocument = *iframe.contentDocument(); frameDocument.setBaseURLOverride(KURL(ParsedURLString, "http://test.com")); frameDocument.body()->setInnerHTML(htmlContentOfIframe, ASSERT_NO_EXCEPTION); return frameDocument; } } // namespace blink
43.666667
127
0.750415
Wzzzx
d1b4ad15588bf24b1fded5dc21b5b0c568eacb66
2,267
cpp
C++
acmicpc.net/source/17141.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
7
2019-06-26T07:03:32.000Z
2020-11-21T16:12:51.000Z
acmicpc.net/source/17141.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
null
null
null
acmicpc.net/source/17141.cpp
tdm1223/Algorithm
994149afffa21a81e38b822afcfc01f677d9e430
[ "MIT" ]
9
2019-02-28T03:34:54.000Z
2020-12-18T03:02:40.000Z
// 17141. 연구소 2 // 2020.02.29 // BFS #include<iostream> #include<vector> #include<algorithm> #include<queue> using namespace std; int ans = 987654321; int map[51][51]; int arr[10]; int arrVisit[10]; int n, m; int dist[51][51]; int visit[51][51]; int dx[4] = { 0,0,1,-1 }; int dy[4] = { 1,-1,0,0 }; vector<pair<int, int>> v; // visit와 dist 초기화 void Init() { for (int i = 0; i < 51; i++) { fill(visit[i], visit[i] + 51, 0); fill(dist[i], dist[i] + 51, 0); } } // 바이러스 퍼뜨리는 함수 void Spread() { Init(); queue<pair<int, int>> q; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // 벽이면 방문표시하고 dist를 -1로 바꿈. if (map[i][j] == 1) { visit[i][j] = 1; dist[i][j] = -1; } } } // 바이러스 선택하여 방문표시하고 큐에 넣음 for (int i = 0; i < v.size(); i++) { for (int j = 0; j < m; j++) { if (arr[j] == i) { q.push({ v[i].first,v[i].second }); visit[v[i].first][v[i].second] = 1; } } } // BFS 실행 while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int xx = x + dx[i]; int yy = y + dy[i]; // 범위를 벗어남 if (xx < 0 || yy < 0 || xx >= n || yy >= n) { continue; } // 벽 if (map[xx][yy] == 1) { continue; } // 아직 방문하지 않았다면 방문체크 후 시간 증가 if (!visit[xx][yy]) { dist[xx][yy] = dist[x][y] + 1; visit[xx][yy] = 1; q.push({ xx,yy }); } } } int cnt = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // 벽이 아니고 방문을 안한 칸이 있다면 바이러스 퍼뜨리기 불가능 if (map[i][j] != 1 && visit[i][j] == 0) { return; } else { cnt = max(cnt, dist[i][j]); } } } // 최소 시간 갱신 ans = min(ans, cnt); } // 2가 있는 들어가있는 것들 중 m개 선택하는 함수 void go(int cnt, int idx) { if (cnt == m) { // 모두 선택했다면 바이러스를 퍼뜨림 Spread(); return; } for (int i = idx; i < v.size(); i++) { if (!arrVisit[i]) { arrVisit[i] = 1; arr[cnt] = i; go(cnt + 1, i); arrVisit[i] = 0; } } } int main() { cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> map[i][j]; if (map[i][j] == 2) { v.push_back({ i,j }); } } } go(0, 0); if (ans == 987654321) { cout << -1 << endl; } else { cout << ans << endl; } return 0; }
13.656627
46
0.44861
tdm1223
d1b53265c8fc85cdc4228d1f7394b6b83917e388
16,303
cpp
C++
VivienneTests/test_ept_breakpoint_OLD_remove.cpp
fengjixuchui/VivienneVMM
0d8ecef1123d0ea1620c7156f3ea0f4c1aab1447
[ "MIT" ]
621
2018-07-29T17:01:54.000Z
2022-03-28T19:20:25.000Z
VivienneTests/test_ept_breakpoint_OLD_remove.cpp
fengjixuchui/VivienneVMM
0d8ecef1123d0ea1620c7156f3ea0f4c1aab1447
[ "MIT" ]
15
2019-01-06T03:57:20.000Z
2021-05-29T02:56:31.000Z
VivienneTests/test_ept_breakpoint_OLD_remove.cpp
fengjixuchui/VivienneVMM
0d8ecef1123d0ea1620c7156f3ea0f4c1aab1447
[ "MIT" ]
147
2018-07-29T17:10:09.000Z
2022-03-11T17:00:56.000Z
#include "test_ept_breakpoint.h" /* - set multiple breakpoint types at same address */ #include <Psapi.h> #include <cstdio> #include "memory.h" #include "../VivienneCL/log.h" #include "../VivienneCL/ntdll.h" #include "..\VivienneCL\driver_io.h" #define FILLER_BUFFER_SIZE (PAGE_SIZE * 5) //ULONG_PTR g_VarA = 0; //UCHAR g_FillerBuffer[FILLER_BUFFER_SIZE] = {}; //ULONG_PTR g_VarB = 0; UCHAR g_VarA[PAGE_SIZE] = {}; UCHAR g_FillerBuffer[FILLER_BUFFER_SIZE] = {}; UCHAR g_VarB[PAGE_SIZE] = {}; HANDLE g_hProcess = NULL; typedef struct _WSI_VIRTUAL_ATTRIBUTES_TEST { PSAPI_WORKING_SET_EX_BLOCK Initial; PSAPI_WORKING_SET_EX_BLOCK AfterVirtualLock; PSAPI_WORKING_SET_EX_BLOCK AfterVirtualUnlock; PSAPI_WORKING_SET_EX_BLOCK AfterForcedOutPage; PSAPI_WORKING_SET_EX_BLOCK AfterFree; } WSI_VIRTUAL_ATTRIBUTES_TEST, *PWSI_VIRTUAL_ATTRIBUTES_TEST; //_Check_return_ //BOOL //PrintWorkingSetInfoByAddress( // _In_ ULONG_PTR Address //) //{ // PSAPI_WORKING_SET_EX_INFORMATION WorkingSetInfo = {}; // BOOL status = TRUE; // // // // // Initialize the target virtual address for the working set query. // // // WorkingSetInfo.VirtualAddress = (PVOID)Address; // // status = QueryWorkingSetEx( // GetCurrentProcess(), // &WorkingSetInfo, // sizeof(WorkingSetInfo)); // if (!status) // { // ERR_PRINT("QueryWorkingSetEx failed: %u\n", GetLastError()); // goto exit; // } // // INF_PRINT("WSI: %p", Address); // INF_PRINT(" Flags: %p", WorkingSetInfo.VirtualAttributes.Flags); // if (WorkingSetInfo.VirtualAttributes.Valid) // { // INF_PRINT(" Valid: %p", WorkingSetInfo.VirtualAttributes.Valid); // INF_PRINT(" ShareCount: %p", WorkingSetInfo.VirtualAttributes.ShareCount); // INF_PRINT(" Win32Protection: %p", WorkingSetInfo.VirtualAttributes.Win32Protection); // INF_PRINT(" Shared: %p", WorkingSetInfo.VirtualAttributes.Shared); // INF_PRINT(" Node: %p", WorkingSetInfo.VirtualAttributes.Node); // INF_PRINT(" Locked: %p", WorkingSetInfo.VirtualAttributes.Locked); // INF_PRINT(" LargePage: %p", WorkingSetInfo.VirtualAttributes.LargePage); // INF_PRINT(" Reserved: %p", WorkingSetInfo.VirtualAttributes.Reserved); // INF_PRINT(" Bad: %p", WorkingSetInfo.VirtualAttributes.Bad); // INF_PRINT(" ReservedUlong: %p", WorkingSetInfo.VirtualAttributes.ReservedUlong); // } // else // { // INF_PRINT(" Valid: %p", WorkingSetInfo.VirtualAttributes.Valid); // INF_PRINT(" Reserved0: %p", WorkingSetInfo.VirtualAttributes.Invalid.Reserved0); // INF_PRINT(" Shared: %p", WorkingSetInfo.VirtualAttributes.Invalid.Shared); // INF_PRINT(" Reserved1: %p", WorkingSetInfo.VirtualAttributes.Invalid.Reserved1); // INF_PRINT(" Bad: %p", WorkingSetInfo.VirtualAttributes.Invalid.Bad); // } // //exit: // return status; //} VOID PrintWorkingSetInfo( _In_ ULONG_PTR Address, _In_ PPSAPI_WORKING_SET_EX_BLOCK pAttributes ) { INF_PRINT(" WSI: %p", Address); INF_PRINT(" Flags: %p", pAttributes->Flags); if (pAttributes->Valid) { INF_PRINT(" Valid: %p", pAttributes->Valid); INF_PRINT(" ShareCount: %p", pAttributes->ShareCount); INF_PRINT(" Win32Protection: %p", pAttributes->Win32Protection); INF_PRINT(" Shared: %p", pAttributes->Shared); INF_PRINT(" Node: %p", pAttributes->Node); INF_PRINT(" Locked: %p", pAttributes->Locked); INF_PRINT(" LargePage: %p", pAttributes->LargePage); INF_PRINT(" Reserved: %p", pAttributes->Reserved); INF_PRINT(" Bad: %p", pAttributes->Bad); INF_PRINT(" ReservedUlong: %p", pAttributes->ReservedUlong); } else { INF_PRINT(" Valid: %p", pAttributes->Valid); INF_PRINT(" Reserved0: %p", pAttributes->Invalid.Reserved0); INF_PRINT(" Shared: %p", pAttributes->Invalid.Shared); INF_PRINT(" Reserved1: %p", pAttributes->Invalid.Reserved1); INF_PRINT(" Bad: %p", pAttributes->Invalid.Bad); } } VOID PrintWorkingSetInfoShort( _In_ PSTR pszPrefix, _In_ PPSAPI_WORKING_SET_EX_BLOCK pAttributes ) { INF_PRINT("%p %s", pAttributes->Flags, pszPrefix); } VOID PrintWsiTest( _In_ ULONG_PTR Address, _In_ PWSI_VIRTUAL_ATTRIBUTES_TEST pWsiTest ) { PrintWorkingSetInfoShort("Initial", &pWsiTest->Initial); PrintWorkingSetInfoShort("AfterVirtualLock", &pWsiTest->AfterVirtualLock); PrintWorkingSetInfoShort("AfterVirtualUnlock", &pWsiTest->AfterVirtualUnlock); PrintWorkingSetInfoShort("AfterForcedOutPage", &pWsiTest->AfterForcedOutPage); PrintWorkingSetInfoShort("AfterFree", &pWsiTest->AfterFree); //INF_PRINT("Initial"); //PrintWorkingSetInfo(Address, &pWsiTest->Initial); //INF_PRINT("AfterVirtualLock"); //PrintWorkingSetInfo(Address, &pWsiTest->AfterVirtualLock); //INF_PRINT("AfterVirtualUnlock"); //PrintWorkingSetInfo(Address, &pWsiTest->AfterVirtualUnlock); //INF_PRINT("AfterForcedOutPage"); //PrintWorkingSetInfo(Address, &pWsiTest->AfterForcedOutPage); //INF_PRINT("AfterFree"); //PrintWorkingSetInfo(Address, &pWsiTest->AfterFree); } _Check_return_ BOOL GetWorkingSetInfo( _In_ ULONG_PTR Address, _Out_ PPSAPI_WORKING_SET_EX_BLOCK pAttributes ) { PSAPI_WORKING_SET_EX_INFORMATION WorkingSetInfo = {}; BOOL status = TRUE; *pAttributes = {}; // // Initialize the target virtual address for the working set query. // WorkingSetInfo.VirtualAddress = (PVOID)Address; status = QueryWorkingSetEx( GetCurrentProcess(), &WorkingSetInfo, sizeof(WorkingSetInfo)); if (!status) { ERR_PRINT("QueryWorkingSetEx failed: %u\n", GetLastError()); goto exit; } *pAttributes = WorkingSetInfo.VirtualAttributes; exit: return status; } VOID TestEptBreakpoint() { WSI_VIRTUAL_ATTRIBUTES_TEST WsiTest = {}; PVOID pAddress = NULL; BOOL fValid = FALSE; HANDLE LogHandle = NULL; PEPT_BREAKPOINT_LOG pLog = NULL; BOOL status = TRUE; INF_PRINT("Executing: %s", __FUNCTION__); pAddress = VirtualAlloc(NULL, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!pAddress) { ERR_PRINT("VirtualAlloc failed: %u", GetLastError()); goto exit; } if (!GetWorkingSetInfo((ULONG_PTR)pAddress, &WsiTest.Initial)) { ERR_PRINT("GetWorkingSetInfo failed: %u", GetLastError()); goto exit; } INF_PRINT(" pAddress: %p", pAddress); //*(PULONG_PTR)pAddress = 1; status = IsVirtualAddressValid(pAddress, &fValid); if (!status) { ERR_PRINT("IsVirtualAddressValid failed: %u", GetLastError()); goto exit; } // if (fValid) { INF_PRINT("Target address is valid."); } else { INF_PRINT("Target address is invalid. Paging it in..."); status = VivienneIoSetEptBreakpoint( GetCurrentProcessId(), //TARGET_PID, (ULONG_PTR)pAddress, //TARGET_ADDRESS, EptBreakpointTypeWrite, EptBreakpointSizeByte, EptBreakpointLogTypeSimple, 100, &LogHandle, &pLog); if (!status) { ERR_PRINT("VivienneIoSetEptBreakpoint failed: %u", GetLastError()); goto exit; } if (!GetWorkingSetInfo((ULONG_PTR)pAddress, &WsiTest.AfterVirtualLock)) { ERR_PRINT("GetWorkingSetInfo failed: %u", GetLastError()); goto exit; } status = IsVirtualAddressValid(pAddress, &fValid); if (!status) { ERR_PRINT("IsVirtualAddressValid failed: %u", GetLastError()); goto exit; } // if (!fValid) { INF_PRINT("Target address is invalid. Paging it in..."); *(PULONG_PTR)pAddress = 0; status = IsVirtualAddressValid(&pAddress, &fValid); if (!status) { ERR_PRINT("IsVirtualAddressValid failed: %u", GetLastError()); goto exit; } if (!fValid) { ERR_PRINT("Target address is still invalid."); goto exit; } if (!GetWorkingSetInfo((ULONG_PTR)pAddress, &WsiTest.AfterVirtualUnlock)) { ERR_PRINT("GetWorkingSetInfo failed: %u", GetLastError()); goto exit; } INF_PRINT("good"); } } PrintWsiTest((ULONG_PTR)pAddress, &WsiTest); getchar(); //INF_PRINT("locking page VirtualLock"); status = VirtualLock(pAddress, 8); if (!status) { ERR_PRINT("VirtualLock failed: %u", GetLastError()); goto exit; } if (!GetWorkingSetInfo((ULONG_PTR)pAddress, &WsiTest.AfterVirtualLock)) { ERR_PRINT("GetWorkingSetInfo failed: %u", GetLastError()); goto exit; } //INF_PRINT("Setting ept breakpoint."); //#define TARGET_PID 1256 //#define TARGET_ADDRESS 0x140007380 // //status = VivienneIoSetEptBreakpoint( // GetCurrentProcessId(), // //TARGET_PID, // (ULONG_PTR)pAddress, // //TARGET_ADDRESS, // EptBreakpointTypeWrite, // EptBreakpointSizeByte, // EptBreakpointLogTypeSimple, // 100, // &LogHandle, // &pLog); //if (!status) //{ // ERR_PRINT("VivienneIoSetEptBreakpoint failed: %u", GetLastError()); // goto exit; //} status = VirtualUnlock(pAddress, 8); if (!status) { ERR_PRINT("VirtualUnlock failed: %u", GetLastError()); goto exit; } if (!GetWorkingSetInfo((ULONG_PTR)pAddress, &WsiTest.AfterVirtualUnlock)) { ERR_PRINT("GetWorkingSetInfo failed: %u", GetLastError()); goto exit; } status = VirtualUnlock(pAddress, 8); // //Sleep(5000); // if (status) { ERR_PRINT("VirtualUnlock succeeded.\n"); goto exit; } // if (GetLastError() != ERROR_NOT_LOCKED) { ERR_PRINT("VirtualUnlock failed: %u", GetLastError()); goto exit; } if (!GetWorkingSetInfo((ULONG_PTR)pAddress, &WsiTest.AfterForcedOutPage)) { ERR_PRINT("GetWorkingSetInfo failed: %u", GetLastError()); goto exit; } status = VirtualFree(pAddress, 0, MEM_RELEASE); if (!status) { ERR_PRINT("VirtualFree failed: %u", GetLastError()); goto exit; } if (!GetWorkingSetInfo((ULONG_PTR)pAddress, &WsiTest.AfterFree)) { ERR_PRINT("GetWorkingSetInfo failed: %u", GetLastError()); goto exit; } PrintWsiTest((ULONG_PTR)pAddress, &WsiTest); getchar(); exit: return; } //VOID //TestEptBreakpoint() //{ // HANDLE LogHandle = NULL; // PEPT_BREAKPOINT_LOG pLog = NULL; // PUCHAR pTarget = NULL; // BOOL fValid = FALSE; // BOOL status = TRUE; // // INF_PRINT("Executing: %s", __FUNCTION__); // // pTarget = g_VarA; // // g_VarA[16] = 0x11; // g_VarA[17] = 0x22; // g_VarA[18] = 0x11; // g_VarA[19] = 0x22; // g_VarA[20] = 0x11; // g_VarA[21] = 0x22; // g_VarA[22] = 0x11; // g_VarA[23] = 0x22; // // //INF_PRINT(" g_VarA: %p", &g_VarA); // ////printf(" g_FillerBuffer: %p", &g_FillerBuffer); // //INF_PRINT(" g_VarB: %p", &g_VarB); // //INF_PRINT(" Delta: %p", (ULONG_PTR)&g_VarB - (ULONG_PTR)&g_VarA); // INF_PRINT(" pTarget: %p", pTarget); // // //EbmSimpleReadAccess(); // // // // status = IsVirtualAddressValid(pTarget, &fValid); // if (!status) // { // ERR_PRINT("IsVirtualAddressValid failed: %u", GetLastError()); // goto exit; // } // // if (fValid) // { // INF_PRINT("Target address is valid."); // } // else // { // INF_PRINT("Target address is invalid. Paging it in..."); // // *pTarget = 0; // // status = IsVirtualAddressValid(&g_VarA, &fValid); // if (!status) // { // ERR_PRINT("IsVirtualAddressValid failed: %u", GetLastError()); // goto exit; // } // // if (!fValid) // { // ERR_PRINT("Target address is still invalid."); // goto exit; // } // } // // if (!PrintWorkingSetInfo((ULONG_PTR)pTarget)) // { // ERR_PRINT("PrintWorkingSetInfo failed: %u", GetLastError()); // goto exit; // } // // INF_PRINT("locking page"); // // status = VirtualLock(pTarget, 8); // if (!status) // { // ERR_PRINT("VirtualLock failed: %u", GetLastError()); // goto exit; // } // // if (!PrintWorkingSetInfo((ULONG_PTR)pTarget)) // { // ERR_PRINT("PrintWorkingSetInfo failed: %u", GetLastError()); // goto exit; // } // // return; // // fflush(stdout); // Sleep(1000); // fflush(stdout); // // // INF_PRINT("Setting ept breakpoint."); // //#define TARGET_PID 1256 //#define TARGET_ADDRESS 0x140007380 // // status = VivienneIoSetEptBreakpoint( // GetCurrentProcessId(), // //TARGET_PID, // (ULONG_PTR)pTarget, // //TARGET_ADDRESS, // EptBreakpointTypeWrite, // EptBreakpointSizeByte, // EptBreakpointLogTypeSimple, // 100, // &LogHandle, // &pLog); // if (!status) // { // ERR_PRINT("VivienneIoSetEptBreakpoint failed: %u", GetLastError()); // goto exit; // } // // fflush(stdout); // Sleep(1000); // fflush(stdout); // // // if (!PrintWorkingSetInfo((ULONG_PTR)pTarget)) // { // ERR_PRINT("PrintWorkingSetInfo failed: %u", GetLastError()); // goto exit; // } // // fflush(stdout); // Sleep(1000); // fflush(stdout); // // getchar(); // // return; // // // // //g_hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, TARGET_PID); // //if (!g_hProcess) // //{ // // ERR_PRINT("OpenProcess failed: %u", GetLastError()); // // goto exit; // //} // // //status = ReadProcessMemory(g_hProcess, (PVOID)TARGET_ADDRESS, &g_VarB, 16, NULL); // //if (!status) // //{ // // ERR_PRINT("ReadProcessMemory failed: %u", GetLastError()); // // goto exit; // //} // // // // INF_PRINT("Handle: %p", LogHandle); // INF_PRINT("Log: %p", pLog); // INF_PRINT(" ProcessId: %Iu", pLog->ProcessId); // INF_PRINT(" Address: %p", pLog->Address); // INF_PRINT(" BreakpointStatus: %d", pLog->BreakpointStatus); // INF_PRINT(" BreakpointType: %d", pLog->BreakpointType); // INF_PRINT(" BreakpointSize: %d", pLog->BreakpointSize); // INF_PRINT(" MaxIndex: %u", pLog->MaxIndex); // INF_PRINT(" NumberOfElements: %u", pLog->NumberOfElements); // // // // INF_PRINT("Triggering ept breakpoint..."); // fflush(stdout); // Sleep(10000); // fflush(stdout); // // // *pTarget = 0x99; // g_VarA[30] = 0x77; // // Sleep(5000); // // // status = VirtualUnlock((PVOID)pTarget, 0x2000); // // // Sleep(5000); // // // if (status) // { // ERR_PRINT("VirtualUnlock succeeded.\n"); // goto exit; // } // // // if (GetLastError() != ERROR_NOT_LOCKED) // { // ERR_PRINT("VirtualUnlock failed: %u", GetLastError()); // goto exit; // } // // Sleep(5000); // // status = IsVirtualAddressValid(pTarget, &fValid); // if (!status) // { // ERR_PRINT("IsVirtualAddressValid failed: %u", GetLastError()); // goto exit; // } // // // if (fValid) // { // __debugbreak(); // ERR_PRINT("target address is resident.\n"); // goto exit; // } // // // // INF_PRINT("done. sleeping..."); // Sleep(5000); // // __debugbreak(); // // // //exit: // return; //}
26.126603
99
0.5802
fengjixuchui
d1b55514ebfe363caa60361125f6df4a50a9ba1c
573
cpp
C++
src/14/14729.cpp
youngdaLee/Baekjoon
7d858d557dbbde6603fe4e8af2891c2b0e1940c0
[ "MIT" ]
11
2020-09-20T15:17:11.000Z
2022-03-17T12:43:33.000Z
src/14/14729.cpp
youngdaLee/Baekjoon
7d858d557dbbde6603fe4e8af2891c2b0e1940c0
[ "MIT" ]
3
2021-10-30T07:51:36.000Z
2022-03-09T05:19:23.000Z
src/14/14729.cpp
youngdaLee/Baekjoon
7d858d557dbbde6603fe4e8af2891c2b0e1940c0
[ "MIT" ]
13
2021-01-21T03:19:08.000Z
2022-03-28T10:44:58.000Z
/** * 14729. 칠무해 * * 작성자: xCrypt0r * 언어: C++14 * 사용 메모리: 39,160 KB * 소요 시간: 3,260 ms * 해결 날짜: 2021년 9월 29일 */ #include <iostream> #include <algorithm> #include <iomanip> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int N; cin >> N; float score[N]; for (int i = 0; i < N; ++i) { cin >> score[i]; } sort(score, score + N, less<float>()); cout << fixed << setprecision(3); for (int i = 0; i < 7; ++i) { cout << score[i] << '\n'; } }
13.642857
42
0.497382
youngdaLee
d1b9533804319bacf4c4605fe212b515b0d9d8da
824
hpp
C++
libs/fnd/cmath/include/bksge/fnd/cmath/is_negative.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/cmath/include/bksge/fnd/cmath/is_negative.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/cmath/include/bksge/fnd/cmath/is_negative.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file is_negative.hpp * * @brief is_negative 関数の定義 * * @author myoukaku */ #ifndef BKSGE_FND_CMATH_IS_NEGATIVE_HPP #define BKSGE_FND_CMATH_IS_NEGATIVE_HPP #include <bksge/fnd/cmath/detail/is_negative_impl.hpp> #include <bksge/fnd/concepts/arithmetic.hpp> #include <bksge/fnd/concepts/detail/require.hpp> #include <bksge/fnd/config.hpp> namespace bksge { /** * @brief 負の値かどうか調べる * * @tparam Arithmetic 算術型 * * @param x 調べる値 * * @return x < 0 ならtrue,そうでないならならfalse. * * x が 0 の場合、falseを返す。 * x が NaN の場合、falseを返す。 */ template <BKSGE_REQUIRES_PARAM(bksge::arithmetic, Arithmetic)> inline BKSGE_CONSTEXPR bool is_negative(Arithmetic x) BKSGE_NOEXCEPT { return detail::is_negative_impl(x); } } // namespace bksge #endif // BKSGE_FND_CMATH_IS_NEGATIVE_HPP
19.619048
63
0.703883
myoukaku
d1bad56dc0c7b3921031748396f21510c7980f94
5,139
hh
C++
include/seastar/util/std-compat.hh
elazarl/seastar
a79d4b337a5229b4ba4a1613a6436627ed67b03d
[ "Apache-2.0" ]
6
2020-03-23T03:22:58.000Z
2021-05-12T11:42:16.000Z
include/seastar/util/std-compat.hh
elazarl/seastar
a79d4b337a5229b4ba4a1613a6436627ed67b03d
[ "Apache-2.0" ]
null
null
null
include/seastar/util/std-compat.hh
elazarl/seastar
a79d4b337a5229b4ba4a1613a6436627ed67b03d
[ "Apache-2.0" ]
1
2021-06-17T10:14:17.000Z
2021-06-17T10:14:17.000Z
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2018 ScyllaDB */ #pragma once #ifdef SEASTAR_USE_STD_OPTIONAL_VARIANT_STRINGVIEW #include <optional> #include <string_view> #include <variant> #else #include <experimental/optional> #include <experimental/string_view> #include <boost/variant.hpp> #endif #if __cplusplus >= 201703L && __has_include(<filesystem>) #include <filesystem> #else #include <experimental/filesystem> #endif namespace seastar { /// \cond internal namespace compat { #ifdef SEASTAR_USE_STD_OPTIONAL_VARIANT_STRINGVIEW template <typename T> using optional = std::optional<T>; using nullopt_t = std::nullopt_t; inline constexpr auto nullopt = std::nullopt; template <typename T> inline constexpr optional<std::decay_t<T>> make_optional(T&& value) { return std::make_optional(std::forward<T>(value)); } template <typename CharT, typename Traits = std::char_traits<CharT>> using basic_string_view = std::basic_string_view<CharT, Traits>; template <typename CharT, typename Traits = std::char_traits<CharT>> std::string string_view_to_string(const basic_string_view<CharT, Traits>& v) { return std::string(v); } template <typename... Types> using variant = std::variant<Types...>; template <std::size_t I, typename... Types> constexpr std::variant_alternative_t<I, variant<Types...>>& get(variant<Types...>& v) { return std::get<I>(v); } template <std::size_t I, typename... Types> constexpr const std::variant_alternative_t<I, variant<Types...>>& get(const variant<Types...>& v) { return std::get<I>(v); } template <std::size_t I, typename... Types> constexpr std::variant_alternative_t<I, variant<Types...>>&& get(variant<Types...>&& v) { return std::get<I>(v); } template <std::size_t I, typename... Types> constexpr const std::variant_alternative_t<I, variant<Types...>>&& get(const variant<Types...>&& v) { return std::get<I>(v); } template <typename U, typename... Types> constexpr U& get(variant<Types...>& v) { return std::get<U>(v); } template <typename U, typename... Types> constexpr const U& get(const variant<Types...>& v) { return std::get<U>(v); } template <typename U, typename... Types> constexpr U&& get(variant<Types...>&& v) { return std::get<U>(v); } template <typename U, typename... Types> constexpr const U&& get(const variant<Types...>&& v) { return std::get<U>(v); } template <typename U, typename... Types> constexpr U* get_if(variant<Types...>* v) { return std::get_if<U>(v); } template <typename U, typename... Types> constexpr const U* get_if(const variant<Types...>* v) { return std::get_if<U>(v); } #else template <typename T> using optional = std::experimental::optional<T>; using nullopt_t = std::experimental::nullopt_t; constexpr auto nullopt = std::experimental::nullopt; template <typename T> inline constexpr optional<std::decay_t<T>> make_optional(T&& value) { return std::experimental::make_optional(std::forward<T>(value)); } template <typename CharT, typename Traits = std::char_traits<CharT>> using basic_string_view = std::experimental::basic_string_view<CharT, Traits>; template <typename CharT, typename Traits = std::char_traits<CharT>> std::string string_view_to_string(const basic_string_view<CharT, Traits>& v) { return v.to_string(); } template <typename... Types> using variant = boost::variant<Types...>; template<typename U, typename... Types> U& get(variant<Types...>& v) { return boost::get<U, Types...>(v); } template<typename U, typename... Types> U&& get(variant<Types...>&& v) { return boost::get<U, Types...>(v); } template<typename U, typename... Types> const U& get(const variant<Types...>& v) { return boost::get<U, Types...>(v); } template<typename U, typename... Types> const U&& get(const variant<Types...>&& v) { return boost::get<U, Types...>(v); } template<typename U, typename... Types> U* get_if(variant<Types...>* v) { return boost::get<U, Types...>(v); } template<typename U, typename... Types> const U* get_if(const variant<Types...>* v) { return boost::get<U, Types...>(v); } #endif #if defined(__cpp_lib_filesystem) namespace filesystem = std::filesystem; #elif defined(__cpp_lib_experimental_filesystem) namespace filesystem = std::experimental::filesystem; #else #error No filesystem header detected. #endif using string_view = basic_string_view<char>; } // namespace compat /// \endcond } // namespace seastar
26.626943
101
0.70792
elazarl
d1bbc53a1160a3a001ca9b527334240a5478f9a4
2,802
cpp
C++
src/handler/list.cpp
npolar/reshp
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
[ "MIT" ]
null
null
null
src/handler/list.cpp
npolar/reshp
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
[ "MIT" ]
1
2015-01-13T10:15:56.000Z
2015-01-13T10:15:56.000Z
src/handler/list.cpp
npolar/reshp
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * *\ |* ╔═╗ v0.4 *| |* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *| |* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *| |* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *| |* * * * * * * * * ╚═╝ * *| |* Manipulation tool for *| |* ESRI Shapefiles *| |* * * * * * * * * * * * *| |* http://www.npolar.no/ *| \* * * * * * * * * * * * */ #include "../handler.hpp" #include "../polygon.hpp" #include <vector> namespace reshp { void handler::list(const std::string& shapefile, const bool full) { reshp::shp shp; if(!shp.load(shapefile)) return; printf("Filename: %s\n", shapefile.c_str()); printf("Version: %i\n", shp.header.version); printf("Type: %s\n", shp::typestr(shp.header.type)); printf("Bounding: [%.4f, %.4f] [%.4f, %.4f]\n", shp.header.box[0], shp.header.box[1], shp.header.box[2], shp.header.box[3]); printf("Records: %lu\n\n", shp.records.size()); for(unsigned i = 0; i < shp.records.size(); ++i) { const char* type = shp::typestr(shp.records[i].type); printf(" record %05i (%s)", shp.records[i].number, type); if(shp.records[i].polygon) { reshp::polygon poly(*shp.records[i].polygon); unsigned rings = poly.rings.size(); unsigned points = 0; for(unsigned r = 0; r < rings; ++r) points += poly.rings[r].segments.size(); if(full) { printf(": %i point%c", points, (points == 1 ? ' ' : 's')); printf(", %i ring%c\n", rings, (rings == 1 ? ' ' : 's')); for(unsigned r = 0; r < poly.rings.size(); ++r) { printf(" ring %i (%s, %lu segments):\n", r, (poly.rings[r].type == reshp::polygon::ring::inner ? "inner" : "outer"), poly.rings[r].segments.size()); for(unsigned s = 0; s < poly.rings[r].segments.size(); ++s) { printf(" [%8.4f, %8.4f] -> [%8.4f, %8.4f]\n", poly.rings[r].segments[s].start.x, poly.rings[r].segments[s].start.y, poly.rings[r].segments[s].end.x, poly.rings[r].segments[s].end.y); } } } else { printf(":%*s%5i point%c", int(13 - strlen(type)), " ", points, (points == 1 ? ' ' : 's')); printf(", %5i ring%c\n", rings, (rings == 1 ? ' ' : 's')); } } else printf("\n"); } // records } // handler::list() } // namespace reshp
38.916667
215
0.390079
npolar
d1bfa1f4463cb16e84bb1b2a8c7f2058dbcaf576
207
cpp
C++
src/player.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
null
null
null
src/player.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
1
2015-05-29T04:49:09.000Z
2015-05-29T04:49:09.000Z
src/player.cpp
warlord500/space_invaders2
71d5acc30f95352b325ada61cb9b1389c9732961
[ "MIT" ]
null
null
null
#include "player.h" player::player(int lives,const sf::Texture& texture,const sf::Vector2f& pos) : sprite(texture), lives(lives) { this->sprite.setPosition(pos); } player::~player() { //dtor }
15.923077
95
0.657005
warlord500
d1c04c48d1e548478df18de8485b93004cf294d0
533
cpp
C++
recursion/pailndrome.cpp
AyushVerma-code/DSA-in-C-
4694ad771a1cff8dd81cb127887804d7c67fcb83
[ "MIT" ]
1
2021-06-01T03:20:42.000Z
2021-06-01T03:20:42.000Z
recursion/pailndrome.cpp
AyushVerma-code/DSA-in-C-
4694ad771a1cff8dd81cb127887804d7c67fcb83
[ "MIT" ]
null
null
null
recursion/pailndrome.cpp
AyushVerma-code/DSA-in-C-
4694ad771a1cff8dd81cb127887804d7c67fcb83
[ "MIT" ]
null
null
null
bool checkPalindrome(char input[]) { bool check =1; int c; for(int i=0;input[i]!='\0';i++) { c=c+1; } int arr[100]; for(int i=0;i<c;i++) { arr[i]=input[i]; } for(int i=0;i<c;i++) { if(arr[i]!=arr[c-1-i]) { check=0; break; } } if(check) return 1; else return 0; }
18.37931
39
0.281426
AyushVerma-code
d1c2db20771197a50b5e506ad1f77be20d10b5fc
697
cpp
C++
uri/beginner/sum_of_consecutive_odd_numbers_2.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
uri/beginner/sum_of_consecutive_odd_numbers_2.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
uri/beginner/sum_of_consecutive_odd_numbers_2.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> #include <utility> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int test_cases; cin >> test_cases; for (unsigned int i {0}; i < test_cases; ++i) { int lower; int upper; cin >> lower >> upper; if (lower > upper) { swap(lower, upper); } if (lower % 2) { ++lower; } int sum {0}; for (int i {lower + 1}; i < upper; i += 2) { sum += i; } cout << sum << '\n'; } return 0; }
14.22449
50
0.460545
Rkhoiwal
d1c442451157f85c16d588f4a6c76c3638144cb8
9,210
cc
C++
Fireworks/Macros/eve_macros.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Fireworks/Macros/eve_macros.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Fireworks/Macros/eve_macros.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include <vector> #include <list> #include <string> #include <cmath> #include <TEveElement.h> #include <TEveGeoNode.h> #include <TGeoNode.h> #include "eve_macros.h" // get the name from an object derived from both TEveElement and TNamed const char* get_name( const TEveElement * element ) { // try as a TEveGeoNode or TEveGeoShape if (const TEveGeoNode * node = dynamic_cast<const TEveGeoNode *>( element )) return node->GetName(); if (const TEveGeoShape * shape = dynamic_cast<const TEveGeoShape *>( element )) return shape->GetName(); // try to access the element as a generic named object if (const TNamed * named = dynamic_cast<const TNamed *>( element )) return named->GetName(); return 0; } // get the title from an object derived from both TEveElement and TNamed const char* get_title( const TEveElement * element ) { // try as a TEveGeoNode or TEveGeoShape if (const TEveGeoNode * node = dynamic_cast<const TEveGeoNode *>( element )) return node->GetTitle(); if (const TEveGeoShape * shape = dynamic_cast<const TEveGeoShape *>( element )) return shape->GetTitle(); // try to access the element as a generic named object if (const TNamed * named = dynamic_cast<const TNamed *>( element )) return named->GetTitle(); return 0; } // force a node to expand its internal reprsentation, so all children are actually present void expand_node( TEveElement * element ) { // force a TEveGeoNode to load all its children if (TEveGeoNode * node = dynamic_cast<TEveGeoNode *>( element )) { if (node->GetNChildren() == 0 && node->GetNode()->GetVolume()->GetNdaughters() > 0) { TIter next(node->GetNode()->GetVolume()->GetNodes()); TGeoNode* dnode; while ((dnode = (TGeoNode*) next()) != 0) { TEveGeoNode* node_re = new TEveGeoNode(dnode); node->AddElement(node_re); } } return; } // a TEveGeoShape is always exanded //if (TEveGeoShape * shape __attribute__ ((unused)) = dynamic_cast<TEveGeoShape *>( element )) { // return; //} // a generic TEveElement has no knwledge on children expansion return; } // retrieves a TShape from a TEveElement const TGeoShape * get_shape( const TEveElement * element ) { // a TEveGeoNode, can look into its TGeoNode and retrieve the shape if (const TEveGeoNode * node = dynamic_cast<const TEveGeoNode *>( element )) { return node->GetNode()->GetVolume()->GetShape(); } // a TEveGeoShape owns its shape if (const TEveGeoShape * shape = dynamic_cast<const TEveGeoShape *>( element )) { TEveGeoShape * nc_shape = const_cast<TEveGeoShape *>( shape ); return const_cast<const TGeoShape *>( nc_shape->GetShape() ); } // a TEveElement is too generic, no way to get a shape return 0; } // overloaded non-const TShape retrieval, allowed from a TGeoShape only TGeoShape * get_shape( TEveElement * element ) { // a TEveGeoNode cannot modify its shape //if (const TEveGeoNode * node __attribute__ ((unused)) = dynamic_cast<const TEveGeoNode *>( element )) { // return 0; //} // a TEveGeoShape owns its shape, and can modifiy it if (TEveGeoShape * shape = dynamic_cast<TEveGeoShape *>( element )) { return shape->GetShape(); } // a TEveElement is too generic, no way to get a shape return 0; } // return a copy of the local-to-global transformation applied to a TEveElement TGeoMatrix * get_transform( const TEveElement * element ) { if (const TEveGeoNode * node = dynamic_cast<const TEveGeoNode *>( element )) { // a TEveGeoNode is a proxy to a TGeoNode, which knows its relative transformation wrt. its parent // so we follow the TEveGeoNode hierarchy up to a TEveGeoTopNode, then jump to its TGeoManager, and go back down the branches to the TEveGeoNode's TGeoNode std::vector< const TEveGeoNode * > nodes; const TEveGeoTopNode * top = 0; while ((top = dynamic_cast<const TEveGeoTopNode *>( node )) == 0) { // save the current node nodes.push_back(node); // check that the node actually has any parents TEveGeoNode * nc_node = const_cast<TEveGeoNode *>( node ); if (nc_node->BeginParents() == nc_node->EndParents()) return 0; // assume the firt parent is the good one, and check that the parent type is correct node = dynamic_cast<const TEveGeoNode *>( * nc_node->BeginParents() ); if (node == 0) return 0; } // reached the top level node, start from its (optional) global transormation TGeoHMatrix * matrix = new TGeoHMatrix(); (const_cast<TEveGeoTopNode *>(top))->RefGlobalTrans().SetGeoHMatrix( *matrix ); for (unsigned int i = 0; i < nodes.size(); ++i) *matrix *= *(nodes[i]->GetNode()->GetMatrix()); return matrix; } if (const TEveGeoShape * shape = dynamic_cast<const TEveGeoShape *>( element )) { // a TEveGeoShape knows the absolute transformation of its shape TGeoHMatrix * matrix = new TGeoHMatrix(); (const_cast<TEveGeoShape *>(shape))->RefHMTrans().SetGeoHMatrix( *matrix ); return matrix; } return 0; } // clone a TEveGeoShape or TEveGeoNode into a new TEveGeoShape, and add it as a child to a parent if one is given TEveGeoShape * clone( const TEveElement * element, TEveElement * parent /* = 0 */) { TEveGeoShape* shape = new TEveGeoShape( get_name(element), get_title(element) ); std::unique_ptr<TGeoMatrix> matrix( get_transform(element) ); shape->SetTransMatrix( matrix.get() ); delete matrix; TEveGeoShapeExtract extract; // FIXME put name and title here... extract.SetShape( (TGeoShape *) get_shape(element)->Clone() ); extract.SetTrans( trans.Array() ); extract.SetRnrSelf( true ); extract.SetRnrElements( true ); TEveGeoShape * clone = TEveGeoShape::ImportShapeExtract( &extract, parent ); return clone; } // set an element's color and alpha, and possibly its children's up to levels levels deep void set_color( TEveElement * element, Color_t color, float alpha /* = 1.0 */, unsigned int levels /* = 0 */) { if (not element) return; // set this node's color element->SetMainColor( color ); if (alpha > 1.) alpha = 1.; if (alpha < 0.) alpha = 0.; unsigned char transparency = (unsigned char) roundf(100. - (alpha * 100.)); element->SetMainTransparency( transparency ); if (levels > 0) { // set the node's children's color expand_node( element ); for (std::list<TEveElement*>::iterator i = element->BeginChildren(); i != element->EndChildren(); ++i) set_color( *i, color, alpha, levels - 1); } // notify the element that it has changed element->ElementChanged(true, true); } // check if a node has any children or if it's a leaf node bool is_leaf_node( const TEveElement * element ) { // a TEveGeoNode can have unaccounted-for children if (const TEveGeoNode * node = dynamic_cast<const TEveGeoNode *>( element )) { return ((node->GetNChildren() == 0) and (node->GetNode()->GetVolume()->GetNdaughters() == 0)); } // a TEveGeoShape always knows its children if (const TEveGeoShape * shape = dynamic_cast<const TEveGeoShape *>( element )) { return (shape->GetNChildren() == 0); } // default implementation return (element->GetNChildren() == 0); } // toggle an elements's children visibility, based on their name // names are checked only up to their length, so for example tec:TEC will match both tec:TEC_1 and tec:TEC_2 void set_children_visibility( TEveElement * element, const std::string & node_name, const std::vector<std::string> & children_name, bool visibility ) { // try to access the element as a named thingy const char * name = get_name( element ); if (not name or strncmp(name, node_name.c_str(), node_name.size())) // unnamed node, or wrong node return; for (std::list<TEveElement *>::iterator j = element->BeginChildren(); j != element->EndChildren(); ++j) { TEveElement * child = *j; name = get_name( child ); if (not name) // unnamed node, ignore it continue; for (unsigned int i = 0; i < children_name.size(); ++i) if (not strncmp(name, children_name[i].c_str(), children_name[i].size())) { // change this child visibility if (is_leaf_node( child )) { child->SetRnrSelf( visibility ); child->SetRnrChildren( false ); } else { child->SetRnrSelf( false ); child->SetRnrChildren( visibility ); } break; } } // notify the element that is had changed element->ElementChanged(true, true); } // set Tracker's Endcaps visibility void set_tracker_endcap_visibility( TEveElement * tracker, bool visibility ) { std::vector<std::string> endcap; endcap.push_back("tec:TEC"); endcap.push_back("tidf:TIDF"); endcap.push_back("tidb:TIDB"); endcap.push_back("pixfwd:PixelForwardZPlus"); endcap.push_back("pixfwd:PixelForwardZMinus"); set_children_visibility( tracker, "tracker:Tracker", endcap, visibility ); } // show Tracker's Endcaps void show_tracker_endcap( TEveElement * tracker ) { set_tracker_endcap_visibility( tracker, true ); } // hide Tracker's Endcaps void hide_tracker_endcap( TEveElement * tracker ) { set_tracker_endcap_visibility( tracker, false ); }
36.987952
159
0.682845
ckamtsikis
d1c5a4281855f6b72f04a3cc88298b26b103cbec
2,493
cpp
C++
tests/unit/streamifyUnit.cpp
edwardcwang/coreir
f71c5864c21cf82112dc641ab0400aac778685c9
[ "BSD-3-Clause" ]
null
null
null
tests/unit/streamifyUnit.cpp
edwardcwang/coreir
f71c5864c21cf82112dc641ab0400aac778685c9
[ "BSD-3-Clause" ]
null
null
null
tests/unit/streamifyUnit.cpp
edwardcwang/coreir
f71c5864c21cf82112dc641ab0400aac778685c9
[ "BSD-3-Clause" ]
null
null
null
#include "coreir.h" #include "coreir/libs/aetherlinglib.h" #include "coreir/libs/commonlib.h" #include <execinfo.h> #include <stdio.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include <math.h> using namespace std; using namespace CoreIR; void handler(int sig) { void *array[10]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 10); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } int main() { signal(SIGSEGV, handler); // install our handler Context* c = newContext(); CoreIRLoadLibrary_commonlib(c); CoreIRLoadLibrary_aetherlinglib(c); uint parallelInputs = 4; uint inputWidth = 8; Type* twoArrays = c->Record({ {"container",c->Record({ {"el1", c->BitIn()->Arr(inputWidth)}, {"el0", c->BitIn()->Arr(inputWidth)} })} }); //Type of module Type* oneInManyOutGenType = c->Record({ {"in", twoArrays->Arr(parallelInputs)}, {"out", c->Out(twoArrays->Arr(parallelInputs))}, {"en", c->BitIn()}, {"ready", c->Bit()}, {"valid", c->Bit()}, {"reset", c->BitIn()} }); Module* testModule = c->getGlobal()->newModuleDecl("testModule",oneInManyOutGenType); ModuleDef* testDef = testModule->newModuleDef(); Values streamifyParams{ {"arrayLength", Const::make(c, parallelInputs)}, {"elementType", Const::make(c, twoArrays)} }; testDef->addInstance("streamify", "aetherlinglib.streamify", streamifyParams); testDef->addInstance("arrayify", "aetherlinglib.arrayify", streamifyParams); testDef->connect("self.in", "streamify.in"); testDef->connect("streamify.out", "arrayify.in"); testDef->connect("arrayify.out", "self.out"); testDef->connect("self.en", "streamify.en"); testDef->connect("self.en", "arrayify.en"); testDef->connect("self.reset", "streamify.reset"); testDef->connect("self.reset", "arrayify.reset"); testDef->connect("streamify.ready", "self.ready"); testDef->connect("arrayify.valid", "self.valid"); testModule->setDef(testDef); testModule->print(); c->runPasses({"rungenerators", "verifyconnectivity"}); testModule->print(); deleteContext(c); return 0; }
29.678571
89
0.601685
edwardcwang
d1c5ac82de2e5da13eeca1b4598d12470b6f2ed3
3,636
cpp
C++
TA.NexDome.Rotator/HomeSensor.cpp
morzineIT/DomeProjectESP8266
c18ff2ee27ad3b38ce1bcc271369438f830eafd7
[ "MIT" ]
3
2019-08-27T02:11:00.000Z
2021-01-16T16:31:52.000Z
TA.NexDome.Rotator/HomeSensor.cpp
thegrapesofwrath/Firmware
162cc2cdf081e26d0d6f3235b953f99edf01a982
[ "MIT" ]
41
2019-08-28T21:32:18.000Z
2022-03-02T13:42:19.000Z
TA.NexDome.Rotator/HomeSensor.cpp
thegrapesofwrath/Firmware
162cc2cdf081e26d0d6f3235b953f99edf01a982
[ "MIT" ]
4
2020-03-18T16:06:17.000Z
2021-06-15T04:29:42.000Z
/* * Provides interrupt processing for the home sensor. * * The home sensor synchronizes the dome rotation step position when it is triggered. * When rotating in the positive direction, we synchronise to the falling edge. * When rotating in the negative direction, we synchronise to the rising edge. * When not rotating, activity is ignored. * * Note: some fields have to be static because they are used during interrupts */ #include "NexDome.h" #include "HomeSensor.h" #pragma region static fields used within interrupt service routines MicrosteppingMotor *HomeSensor::motor; Home *HomeSensor::homeSettings; uint8_t HomeSensor::sensorPin; volatile HomingPhase HomeSensor::phase; #pragma endregion /* * Creates a new HomeSensor instance. * Note: sensorPin must correspond to a digital input pin that is valid for attaching interrupts. * Not all pins on all platforms support attaching interrupts. * Arduino Leonardo supports pins 0, 1, 2, 3, 7 */ HomeSensor::HomeSensor(MicrosteppingMotor *stepper, Home *settings, const uint8_t sensorPin, CommandProcessor &processor) : commandProcessor(processor) { motor = stepper; HomeSensor::homeSettings = settings; HomeSensor::sensorPin = sensorPin; } /* * Triggered as an interrupt whenever the home sensor pin changes state. * Synchronizes the current motor stop position to the calibrated home position. */ void HomeSensor::onHomeSensorChanged() { const auto state = digitalRead(sensorPin); if (state == 0 && phase == Detecting) foundHome(); } /* * Configures the hardware pin ready for use and attaches the interrupt. */ void HomeSensor::init() { pinMode(sensorPin, INPUT_PULLUP); setPhase(Idle); attachInterrupt(digitalPinToInterrupt(sensorPin), onHomeSensorChanged, CHANGE); } /// <summary> /// Indicates whether the dome is currently in the home position /// (only valid after a successful homing operation and before and slews occur) /// </summary> bool HomeSensor::atHome() { return phase == AtHome; } void HomeSensor::setPhase(HomingPhase newPhase) { phase = newPhase; #ifdef DEBUG_HOME std::cout << "Phase " << phase << std::endl; #endif } /* * Rotates up to 2 full rotations clockwise while attempting to detect the home sensor. * Ignored if a homing operation is already in progress. */ void HomeSensor::findHome(int direction) { if (phase == Idle || phase == AtHome) { const auto distance = 2 * homeSettings->microstepsPerRotation; // Allow 2 full rotations only setPhase(Detecting); motor->moveToPosition(distance); } } /* * Stops a homing operation in progress. */ void HomeSensor::cancelHoming() { setPhase(Idle); if (motor->isMoving()) motor->SoftStop(); } /* * Once the home sensor has been detected, we instruct the motor to soft-stop. * We also set the flag performPostHomeSlew. * At some point in the future, the onMotorStopped method will be called, which will * then initiate the final slew to return exactly to the home sensor position. */ void HomeSensor::foundHome() { setPhase(Stopping); motor->SetCurrentPosition(homeSettings->position); motor->SoftStop(); } /* * Handles the onMotorStopped event. Action depends on the homing phase. */ void HomeSensor::onMotorStopped() const { #ifdef DEBUG_HOME std::cout << "Hstop " << phase << std::endl; #endif if (phase == Reversing) { setPhase(AtHome); return; } if (phase == Stopping) { setPhase(Reversing); const auto target = commandProcessor.targetStepPosition(homeSettings->position); motor->moveToPosition(target); return; } setPhase(Idle); } bool HomeSensor::homingInProgress() { return !(phase == Idle || phase == AtHome); }
26.347826
121
0.738999
morzineIT
d1c888d02354f2a553a501b070682772d53e3b41
950
cpp
C++
codeforces/593A.cpp
hiyouga/CPP-Learning
e05324bc73ae91a09d51145ecd21af78487405f2
[ "MIT" ]
null
null
null
codeforces/593A.cpp
hiyouga/CPP-Learning
e05324bc73ae91a09d51145ecd21af78487405f2
[ "MIT" ]
null
null
null
codeforces/593A.cpp
hiyouga/CPP-Learning
e05324bc73ae91a09d51145ecd21af78487405f2
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; int main() { int n; cin >> n; bool can_p[n]; int tot[26], cnt[n][26]; string lne[n]; memset(tot, 0, sizeof(tot)); memset(cnt, 0, sizeof(cnt)); for(int i = 0; i < n; i++){ cin >> lne[i]; int typ = 0; can_p[i] = true; for(int j = 0; lne[i][j] != '\0'; j++){ if(!cnt[i][lne[i][j]-'a']){ typ++; } cnt[i][lne[i][j]-'a']++; } if(typ > 2){ can_p[i] = false; } //cout << typ << can_p[i] << endl; } int max_s = 0; for(int i = 0; i < 25; i++){ for(int j = i + 1; j < 26; j++){ int s = 0; for(int p = 0; p < n; p++){ bool flag = true; if(can_p[p]){ for(int q = 0; q < 26; q++){ if(cnt[p][q] && (q != i && q != j)){ flag = false; } } if(flag){ //cout << i << j << lne[p] << endl; s += cnt[p][i] + cnt[p][j]; } } } max_s = max(max_s, s); } } cout << max_s << endl; return 0; }
17.924528
42
0.430526
hiyouga
d1c8c85928668b948689ab36bb95a7bca28b20b4
3,425
cpp
C++
src/main.cpp
Rocik/btree-file-index
04cb787c903a18e606b2f03f0cce345d879086f5
[ "MIT" ]
null
null
null
src/main.cpp
Rocik/btree-file-index
04cb787c903a18e606b2f03f0cce345d879086f5
[ "MIT" ]
null
null
null
src/main.cpp
Rocik/btree-file-index
04cb787c903a18e606b2f03f0cce345d879086f5
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include "btree.h" using namespace std; static bool running = true; static void printDiskStats() { int reads = DiskFile::getStatReads(); int writes = DiskFile::getStatWrites(); char const* plurarReads = reads == 1 ? "" : "s"; char const* plurarWrites = writes == 1 ? "" : "s"; printf("[FILES] %d read%s and %d write%s\n", reads, plurarReads, writes, plurarWrites); DiskFile::resetStats(); } static void loadCommands(istream& stream, BTree& btree); static void loadTestFile(const char* filename, BTree& btree) { fstream stream(filename, ios_base::in); loadCommands(stream, btree); } static void loadCommands(istream& stream, BTree& btree) { int key, value; string str; if (!running) return; char c; do { stream >> c; if (stream.eof()) return; switch (c) { // Read more commands from file // <filename:string> case 'f': { stream >> str; loadTestFile(str.c_str(), btree); break; } // Inserting record // <key:int> <value:int> case 'w': { stream >> key; stream >> value; if (key <= 0) { printf("[INSERT] Key %d is incorrect, must be a Natural number", key); break; } if (value <= 0) { printf("[INSERT] Value %d is incorrect, must be a Natural number", value); break; } Record record(key, value); if (btree.insert(record)) printf("[INSERT] Key %d with value %d\n", key, value); else printf("[INSERT] Key %d could not be inserted, it exists\n", key); break; } // Reading record // <key:int> case 'o': { stream >> key; if (key <= 0) { printf("[READ] Key %d is incorrect, must be a Natural number", key); break; } shared_ptr<Record> record; if (btree.read(key, &record)) printf("[READ] Found key %d with value %d\n", key, record->getValue()); else printf("[READ] Key %d was not found\n", key); break; } // Updating record // <key:int> <value:int> case 'a': { stream >> key; stream >> value; if (key <= 0) { printf("[UPDATE] Key %d is incorrect, must be a Natural number", key); break; } if (value <= 0) { printf("[UPDATE] Value %d is incorrect, must be a Natural number", value); break; } Record record(key, value); if (btree.update(record)) printf("[UPDATE] Key %d with value %d\n", key, value); else printf("[UPDATE] Key %d could not be updated, not found\n", key); break; } // Deleting record // <key:int> case 'u': { stream >> key; if (key <= 0) { printf("[DELETE] Key %d is incorrect, must be a Natural number", key); break; } if (btree.remove(key)) printf("[DELETE] Key %d\n", key); else printf("[DELETE] Key %d could not be deleted, not found\n", key); break; } // Viewing whole file and index sorted by key value case 'p': { btree.printInKeyOrder(); break; } // Do not save to files and remove any case 'd': { btree.dispose(); continue; } case 'q': running = false; return; default: printf("[ERROR] Unknown command: %c (%d)\n", c, c); break; } if (stream.eof()) return; printDiskStats(); } while (running && c != 0); } int main() { string name = string("sample"); BTree tree(name, 3); //loadTestFile("test_commands.txt", tree); loadCommands(cin, tree); return 0; }
19.241573
78
0.585109
Rocik
d1c9774c9ec0af6b432f98e28d681408c664d91e
1,430
hpp
C++
src/converter_omerc.hpp
barendgehrels/tissot
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
[ "BSL-1.0" ]
1
2015-05-17T11:15:43.000Z
2015-05-17T11:15:43.000Z
src/converter_omerc.hpp
barendgehrels/tissot
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
[ "BSL-1.0" ]
null
null
null
src/converter_omerc.hpp
barendgehrels/tissot
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
[ "BSL-1.0" ]
null
null
null
#ifndef TISSOT_CONVERTER_OMERC_HPP #define TISSOT_CONVERTER_OMERC_HPP // Tissot, converts projecton source code (Proj4) to Boost.Geometry // (or potentially other source code) // // Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands. // // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "tissot_structs.hpp" #include "tissot_util.hpp" #include "converter_base.hpp" namespace boost { namespace geometry { namespace proj4converter { class converter_cpp_bg_omerc : public converter_cpp_bg_default { public : converter_cpp_bg_omerc(projection_properties& prop) : m_prop(prop) { } void convert() { // Initialize variable (for gcc warning) // (actually there are many more uninitialized - we should possibly // initialize all of them, TODO) BOOST_FOREACH(derived& der, m_prop.derived_projections) { BOOST_FOREACH(std::string& line, der.constructor_lines) { boost::replace_all(line, ", alpha_c;", ", alpha_c=0.0;"); } } } private : projection_properties& m_prop; }; }}} // namespace boost::geometry::proj4converter #endif // TISSOT_CONVERTER_OMERC_HPP
26.981132
79
0.65035
barendgehrels
d1cc585c2d44523c40ef470398aa0d302f58ee19
26,631
cc
C++
base/simple_reg.cc
haveTryTwo/csutil
7cb071f6927db4c52832d3074fb69f273968d66e
[ "BSD-2-Clause" ]
9
2015-08-14T08:59:06.000Z
2018-08-20T13:46:46.000Z
base/simple_reg.cc
haveTryTwo/csutil
7cb071f6927db4c52832d3074fb69f273968d66e
[ "BSD-2-Clause" ]
null
null
null
base/simple_reg.cc
haveTryTwo/csutil
7cb071f6927db4c52832d3074fb69f273968d66e
[ "BSD-2-Clause" ]
1
2018-08-20T13:46:29.000Z
2018-08-20T13:46:29.000Z
// Copyright (c) 2015 The CSUTIL 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 <stdio.h> #include <string.h> #include <assert.h> #include "simple_reg.h" namespace base { enum OpCode {/*{{{*/ kInvalid = 0, kEnd = 1, kBOL = 2, kEOL = 3, kAny = 4, kAnyOf = 5, kAnyExcept = 6, kBranch = 7, kBack = 8, kNothing = 9, kPrecise = 10, kParenStart = 11, kParenEnd = 12, };/*}}}*/ const uint32_t kStartValidPos = sizeof(RegNode); const uint32_t kMaxRegNfaLen = 0xffff; const uint32_t kMaxParenNum = 20; const std::string kMetaOperators = "^$()[*+?|.\\"; RegExp::RegExp(const std::string &reg_str) : reg_str_(reg_str) {/*{{{*/ reg_parse_index_ = 0; paren_num_ = 0; just_check_bol_ = false; check_str_index_ = 0; }/*}}}*/ RegExp::~RegExp() {/*{{{*/ }/*}}}*/ Code RegExp::Init() {/*{{{*/ uint32_t invalid_node_start_pos = 0; Code ret = AppendNode(kInvalid, &invalid_node_start_pos); if (ret != base::kOk) return ret; uint32_t cur_node_start_pos = 0; ret = Compile(false, &cur_node_start_pos); if (ret != kOk) return ret; ret = CheckIfBOL(); if (ret != kOk) return ret; return ret; }/*}}}*/ Code RegExp::Check(const std::string &str) {/*{{{*/ check_str_ = str; Code ret = kOk; uint32_t cur_node_pos = kStartValidPos; if (just_check_bol_) { ret = Match(0, cur_node_pos); return ret; } for (uint32_t check_index = 0; check_index < check_str_.size(); ++check_index) { ret = Match(check_index, cur_node_pos); if (ret == kOk) return ret; if (ret != kRegNotMatch) return ret; } return ret; }/*}}}*/ Code RegExp::Match(uint32_t check_str_index, uint32_t cur_node_pos) {/*{{{*/ if (cur_node_pos < kStartValidPos) return kInvalidParam; Code ret = kOk; uint32_t next_node_start_pos = 0; bool no_next_node = false; while (true) {/*{{{*/ ret = GetNextNodePos(cur_node_pos, &next_node_start_pos); if (ret == kNoNextNode) { no_next_node = true; } else if (ret != kOk) { return ret; } const RegNode *cur_node = (const RegNode*)(reg_nfa_.data()+cur_node_pos); switch (cur_node->opcode) {/*{{{*/ case kBOL: if (check_str_index != 0) return kRegNotMatch; break; case kEOL: if (check_str_index != check_str_.size()) return kRegNotMatch; break; case kAny: if (check_str_index >= check_str_.size()) return kRegNotMatch; check_str_index++; break; case kAnyOf: {/*{{{*/ uint32_t cur_node_operand_pos = 0; ret = GetOperandPos(cur_node_pos, &cur_node_operand_pos); if (ret != kOk) return ret; const char* locate_pointer = strchr(reg_nfa_.data()+cur_node_operand_pos, *(check_str_.data()+check_str_index)); if (locate_pointer == NULL) return kRegNotMatch; check_str_index++; }/*}}}*/ break; case kAnyExcept: {/*{{{*/ uint32_t cur_node_operand_pos = 0; ret = GetOperandPos(cur_node_pos, &cur_node_operand_pos); if (ret != kOk) return ret; const char* locate_pointer = strchr(reg_nfa_.data()+cur_node_operand_pos, *(check_str_.data()+check_str_index)); if (locate_pointer != NULL) return kRegNotMatch; check_str_index++; }/*}}}*/ break; case kPrecise: {/*{{{*/ uint32_t cur_node_operand_pos = 0; ret = GetOperandPos(cur_node_pos, &cur_node_operand_pos); if (ret != kOk) return ret; size_t cur_precise_size = strlen(reg_nfa_.data()+cur_node_operand_pos); size_t cur_check_str_left_size = check_str_.size()-check_str_index; if (cur_check_str_left_size < cur_precise_size) return kRegNotMatch; int equal_flag = memcmp(reg_nfa_.data()+cur_node_operand_pos, check_str_.data()+check_str_index, cur_precise_size); if (equal_flag != 0) return kRegNotMatch; check_str_index += cur_precise_size; }/*}}}*/ break; case kNothing: break; case kBack: break; case kParenStart: case kParenEnd: if (no_next_node) return kInvalidRegNfa; ret = Match(check_str_index, next_node_start_pos); return ret; break; case kBranch: {/*{{{*/ if (no_next_node) return kInvalidRegNfa; const RegNode* next_node = (const RegNode*)(reg_nfa_.data()+next_node_start_pos); if (next_node->opcode != kBranch) { ret = GetOperandPos(cur_node_pos, &next_node_start_pos); if (ret != kOk) return ret; break; } else {/*{{{*/ while (true) { uint32_t tmp_operand_pos = 0; ret = GetOperandPos(cur_node_pos, &tmp_operand_pos); if (ret != kOk) return ret; ret = Match(check_str_index, tmp_operand_pos); if (ret == kOk) return ret; if (ret != kRegNotMatch) return ret; cur_node_pos = next_node_start_pos; ret = GetNextNodePos(cur_node_pos, &next_node_start_pos); if (ret != kOk) return ret; // TODO: kNoNextNode next_node = (const RegNode*)(reg_nfa_.data()+next_node_start_pos); if (next_node->opcode != kBranch) { ret = GetOperandPos(cur_node_pos, &next_node_start_pos); if (ret != kOk) return ret; break; } } break; }/*}}}*/ }/*}}}*/ break; case kEnd: return kOk; break; default: return kRegNotMatch; break; }/*}}}*/ if (no_next_node) break; cur_node_pos = next_node_start_pos; }/*}}}*/ return kRegNotMatch; }/*}}}*/ Code RegExp::Compile(bool paren, uint32_t *node_start_pos) {/*{{{*/ if (node_start_pos == NULL) return kInvalidParam; Code ret = kOk; uint32_t paren_node_start_pos = 0; if (paren) { paren_num_++; if (paren_num_ >= kMaxParenNum) return kParenNumExceed; ret = AppendNode(kParenStart, &paren_node_start_pos); if (ret != kOk) return ret; } uint32_t branch_node_start_pos = 0; ret = ProcessBaranch(&branch_node_start_pos); if (ret != base::kOk) return ret; uint32_t cur_node_start_pos = branch_node_start_pos; if (paren) { ret = LinkNode(paren_node_start_pos, branch_node_start_pos); if (ret != kOk) return ret; cur_node_start_pos = paren_node_start_pos; } char ch = *(reg_str_.data()+reg_parse_index_); while (ch == '|') { reg_parse_index_++; uint32_t new_branch_node_start_pos = 0; ret = ProcessBaranch(&new_branch_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, new_branch_node_start_pos); if (ret != kOk) return ret; ch = *(reg_str_.data()+reg_parse_index_); } uint32_t end_node_start_pos = 0; if (paren) { ret = AppendNode(kParenEnd, &end_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, end_node_start_pos); } else { ret = AppendNode(kEnd, &end_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, end_node_start_pos); } uint32_t tmp_cur_node_start_pos = cur_node_start_pos; uint32_t next_node_start_pos = 0; while (true) { ret = GetNextNodePos(tmp_cur_node_start_pos, &next_node_start_pos); if (ret == kNoNextNode) { ret = kOk; break; } if (ret != kOk) return ret; LinkOperandNode(tmp_cur_node_start_pos, end_node_start_pos); tmp_cur_node_start_pos = next_node_start_pos; } ch = *(reg_str_.data()+reg_parse_index_); if (paren) { if (ch != ')') return kInvalidMetaOperator; reg_parse_index_++; } else { if (ch != '\0') return kInvalidRegEnd; } *node_start_pos = cur_node_start_pos; return ret; }/*}}}*/ Code RegExp::ProcessBaranch(uint32_t *node_start_pos) {/*{{{*/ if (node_start_pos == NULL) return kInvalidParam; uint32_t branch_node_start_pos = 0; Code ret = AppendNode(kBranch, &branch_node_start_pos); if (ret != base::kOk) return ret; uint32_t pre_node_start_pos = 0; uint32_t cur_node_start_pos = 0; char ch = *(reg_str_.data()+reg_parse_index_); while (ch != '\0' && ch != '|' && ch != ')') { ret = ProcessBlock(&cur_node_start_pos); if (ret != base::kOk) return ret; if (pre_node_start_pos != 0) { ret = LinkNode(pre_node_start_pos, cur_node_start_pos); if (ret != base::kOk) return ret; } pre_node_start_pos = cur_node_start_pos; ch = *(reg_str_.data()+reg_parse_index_); } if (pre_node_start_pos == 0) { uint32_t nothing_node_start_pos = 0; ret = AppendNode(kNothing, &nothing_node_start_pos); if (ret != kOk) return ret; } *node_start_pos = branch_node_start_pos; return ret; }/*}}}*/ Code RegExp::ProcessBlock(uint32_t *node_start_pos) {/*{{{*/ if (node_start_pos == NULL) return kInvalidParam; uint32_t cur_node_start_pos = 0; Code ret = ProcessChar(&cur_node_start_pos); if (ret != kOk) return ret; char ch = *(reg_str_.data()+reg_parse_index_); if (!IsRepetitionOp(ch)) { *node_start_pos = cur_node_start_pos; return ret; } // repetition operator if (ch == '*') {/*{{{*/ ret = InsertNode(cur_node_start_pos, kBranch); if (ret != kOk) return ret; uint32_t back_node_start_pos = 0; ret = AppendNode(kBack, &back_node_start_pos); if (ret != kOk) return ret; ret = LinkOperandNode(cur_node_start_pos, back_node_start_pos); if (ret != kOk) return ret; ret = LinkOperandNode(cur_node_start_pos, cur_node_start_pos); if (ret != kOk) return ret; uint32_t new_branch_node_start_pos = 0; ret = AppendNode(kBranch, &new_branch_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, new_branch_node_start_pos); if (ret != kOk) return ret; uint32_t nothing_node_start_pos = 0; ret = AppendNode(kNothing, &nothing_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, nothing_node_start_pos); if (ret != kOk) return ret; }/*}}}*/ else if (ch == '+') {/*{{{*/ uint32_t cur_branch_node_start_pos = 0; ret = AppendNode(kBranch, &cur_branch_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, cur_branch_node_start_pos); if (ret != kOk) return ret; uint32_t back_node_start_pos = 0; ret = AppendNode(kBack, &back_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(back_node_start_pos, cur_node_start_pos); if (ret != kOk) return ret; uint32_t new_branch_node_start_pos = 0; ret = AppendNode(kBranch, &new_branch_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_branch_node_start_pos, new_branch_node_start_pos); if (ret != kOk) return ret; uint32_t nothing_node_start_pos = 0; ret = AppendNode(kNothing, &nothing_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(new_branch_node_start_pos, nothing_node_start_pos); if (ret != kOk) return ret; }/*}}}*/ else if (ch == '?') {/*{{{*/ ret = InsertNode(cur_node_start_pos, kBranch); if (ret != kOk) return ret; uint32_t new_branch_node_start_pos = 0; ret = AppendNode(kBranch, &new_branch_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, new_branch_node_start_pos); if (ret != kOk) return ret; uint32_t nothing_node_start_pos =0; ret = AppendNode(kNothing, &nothing_node_start_pos); if (ret != kOk) return ret; ret = LinkNode(cur_node_start_pos, nothing_node_start_pos); if (ret != kOk) return ret; ret = LinkOperandNode(cur_node_start_pos, nothing_node_start_pos); if (ret != kOk) return ret; }/*}}}*/ reg_parse_index_++; ch = *(reg_str_.data()+reg_parse_index_); if (IsRepetitionOp(ch)) return kInvalidRegExp; *node_start_pos = cur_node_start_pos; return ret; }/*}}}*/ Code RegExp::ProcessChar(uint32_t *node_start_pos) {/*{{{*/ if (node_start_pos == NULL) return kInvalidParam; char ch = *(reg_str_.data()+reg_parse_index_); reg_parse_index_++; uint32_t cur_node_start_pos = 0; Code ret = kOk; switch (ch) {/*{{{*/ case '^': ret = AppendNode(kBOL, &cur_node_start_pos); if (ret != kOk) return ret; break; case '$': ret = AppendNode(kEOL, &cur_node_start_pos); if (ret != kOk) return ret; break; case '.': ret = AppendNode(kAny, &cur_node_start_pos); if (ret != kOk) return ret; break; case '[': {/*{{{*/ ch = *(reg_str_.data()+reg_parse_index_); if (ch == '^') { ret = AppendNode(kAnyExcept, &cur_node_start_pos); if (ret != kOk) return ret; reg_parse_index_++; } else { ret = AppendNode(kAnyOf, &cur_node_start_pos); if (ret != kOk) return ret; } ch = *(reg_str_.data()+reg_parse_index_); if (ch == ']' || ch == '-') { ret = AppendChar(ch); if (ret != kOk) return ret; reg_parse_index_++; } ch = *(reg_str_.data()+reg_parse_index_); reg_parse_index_++; while (ch != '\0' && ch != ']') { if (ch != '-') { ret = AppendChar(ch); if (ret != kOk) return ret; } else if ((ch = *(reg_str_.data()+reg_parse_index_)) == ']' || ch == '\0') { ret = AppendChar('-'); if (ret != kOk) return ret; } else { char start_ch = *(reg_str_.data()+reg_parse_index_-2); char end_ch = ch; if (start_ch > end_ch) return kInvalidRange; for (char in_ch = start_ch+1; in_ch <= end_ch; ++in_ch) { ret = AppendChar(in_ch); if (ret != kOk) return ret; } reg_parse_index_++; } ch = *(reg_str_.data()+reg_parse_index_); reg_parse_index_++; } if (ch != ']') return kInvalidInBracket; ret = AppendChar('\0'); if (ret != kOk) return ret; break; }/*}}}*/ case '(': ret = Compile(true, &cur_node_start_pos); if (ret != kOk) return ret; break; case ')': case '|': case '*': case '+': case '?': return kInvalidMetaOperator; break; case '\0': return kInvalidRegEnd; break; case '\\': ch = *(reg_str_.data()+reg_parse_index_); if (ch == '\0') return kInvalidRegEnd; ret = AppendNode(kPrecise, &cur_node_start_pos); if (ret != kOk) return ret; ret = AppendChar(ch); if (ret != kOk) return ret; ret = AppendChar('\0'); if (ret != kOk) return ret; reg_parse_index_++; break; default: { reg_parse_index_--; size_t precise_str_len = strcspn(reg_str_.data()+reg_parse_index_, kMetaOperators.c_str()); if (precise_str_len == 0) return kInvalidRegExp; uint32_t precise_index_end = reg_parse_index_ + precise_str_len; if (precise_str_len > 1 && IsRepetitionOp(*(reg_str_.data()+precise_index_end))) precise_str_len--; ret = AppendNode(kPrecise, &cur_node_start_pos); if (ret != kOk) return ret; while (precise_str_len > 0) { ret = AppendChar(*(reg_str_.data() + reg_parse_index_)); if (ret != kOk) return ret; reg_parse_index_++; precise_str_len--; } ret = AppendChar('\0'); if (ret != kOk) return ret; break; } }/*}}}*/ *node_start_pos = cur_node_start_pos; return ret; }/*}}}*/ Code RegExp::InsertNode(uint32_t insert_pos, char opcode) {/*{{{*/ if (insert_pos < kStartValidPos) return kInvalidParam; RegNode insert_node = {opcode, 0}; reg_nfa_.insert(insert_pos, (const char*)(&insert_node), sizeof(insert_node)); return kOk; }/*}}}*/ Code RegExp::AppendNode(char opcode, uint32_t *node_start_pos) {/*{{{*/ if (node_start_pos == NULL) return kInvalidParam; RegNode reg_node; reg_node.opcode = opcode; reg_node.next_pos = 0; *node_start_pos = reg_nfa_.size(); reg_nfa_.append((const char*)(void*)&reg_node, sizeof(reg_node)); if (reg_nfa_.size() >= kMaxRegNfaLen) return kInvalidLength; return base::kOk; }/*}}}*/ Code RegExp::AppendChar(char ch) {/*{{{*/ reg_nfa_.append(1, ch); return kOk; }/*}}}*/ Code RegExp::LinkNode(uint32_t first_node_pos, uint32_t second_node_pos) {/*{{{*/ uint32_t first_empty_next_node_pos = 0; Code ret = GetFirstEmptyNextNodePos(first_node_pos, &first_empty_next_node_pos); if (ret != kOk) return ret; const RegNode* first_empty_next_node = (const RegNode*)(reg_nfa_.data()+first_empty_next_node_pos); uint32_t distance = 0; const RegNode* second_node = (const RegNode*)(reg_nfa_.data()+second_node_pos); if (first_empty_next_node->opcode == kBack) { distance = (const char*)first_empty_next_node - (const char*)second_node; } else { distance = (const char*)second_node - (const char*)first_empty_next_node; } (const_cast<RegNode*>(first_empty_next_node))->next_pos = distance; return base::kOk; }/*}}}*/ Code RegExp::LinkOperandNode(uint32_t first_node_pos, uint32_t second_node_pos) {/*{{{*/ const RegNode* first_node = (const RegNode*)(reg_nfa_.data()+first_node_pos); if (first_node->opcode != kBranch) return kOk; uint32_t operand_pos = 0; Code ret = GetOperandPos(first_node_pos, &operand_pos); if (ret != kOk) return ret; return LinkNode(operand_pos, second_node_pos); }/*}}}*/ Code RegExp::GetFirstEmptyNextNodePos(uint32_t node_pos, uint32_t *first_empty_next_node_pos) {/*{{{*/ if (first_empty_next_node_pos == NULL) return kInvalidParam; const RegNode* first_empty_next_node = (const RegNode*)(reg_nfa_.data()+node_pos); while (first_empty_next_node->next_pos != 0) { if (first_empty_next_node->opcode == kBack) { first_empty_next_node = (const RegNode*)((const char*)first_empty_next_node-first_empty_next_node->next_pos); } else { first_empty_next_node = (const RegNode*)((const char*)first_empty_next_node+first_empty_next_node->next_pos); } } *first_empty_next_node_pos = (const char*)first_empty_next_node - reg_nfa_.data(); return kOk; }/*}}}*/ bool RegExp::IsRepetitionOp(char reg_ch) {/*{{{*/ return (reg_ch == '*' || reg_ch == '+' || reg_ch == '?'); }/*}}}*/ Code RegExp::GetOperandPos(uint32_t node_pos, uint32_t *operand_pos) {/*{{{*/ if (node_pos < kStartValidPos || operand_pos == NULL) return kInvalidParam; *operand_pos = node_pos + sizeof(RegNode); return kOk; }/*}}}*/ Code RegExp::GetNextNodePos(uint32_t node_pos, uint32_t *next_node_pos) {/*{{{*/ if (next_node_pos == NULL) return kInvalidParam; uint32_t tmp_next_node_pos = 0; const RegNode* cur_node = (const RegNode*)(reg_nfa_.data()+node_pos); if (cur_node->next_pos == 0) return kNoNextNode; if (cur_node->opcode == kBack) { tmp_next_node_pos = node_pos - cur_node->next_pos; } else { tmp_next_node_pos = node_pos + cur_node->next_pos; } *next_node_pos = tmp_next_node_pos; return kOk; }/*}}}*/ Code RegExp::CheckIfBOL() {/*{{{*/ if (reg_nfa_.size() < kStartValidPos) return kNotInit; Code ret = kOk; const RegNode *reg_node = (const RegNode*)(reg_nfa_.data()+kStartValidPos); if (reg_node->opcode == kBranch && reg_node->next_pos != 0) { uint32_t next_node_pos = kStartValidPos + reg_node->next_pos; const RegNode *next_reg_node = (const RegNode*)(reg_nfa_.data()+next_node_pos); if (next_reg_node->opcode == kEnd) { uint32_t next_opcode_node_pos = 0; ret = GetOperandPos(kStartValidPos, &next_opcode_node_pos); if (ret != kOk) return ret; const RegNode *next_opcode_node = (const RegNode*)(reg_nfa_.data()+next_opcode_node_pos); if (next_opcode_node->opcode == kBOL) { just_check_bol_ = true; } } } return ret; }/*}}}*/ Code RegExp::PrintNfa() {/*{{{*/ if (reg_nfa_.size() < kStartValidPos) return kNotInit; return PrintNfa(reg_nfa_); }/*}}}*/ Code RegExp::PrintNfa(const std::string &nfa) {/*{{{*/ if (nfa.size() < kStartValidPos) return kNotInit; Code ret = kOk; uint32_t start_pos = 0; while (start_pos < nfa.size()) {/*{{{*/ const RegNode* reg_node = (const RegNode*)(nfa.data()+start_pos); start_pos += sizeof(RegNode); switch (reg_node->opcode) { case kInvalid: PrintRegNodeInfo("kInvalid", reg_node->next_pos); break; case kBOL: PrintRegNodeInfo("kBOL", reg_node->next_pos); break; case kEOL: PrintRegNodeInfo("kEOL", reg_node->next_pos); break; case kAny: PrintRegNodeInfo("kAny", reg_node->next_pos); break; case kAnyOf: PrintRegNodeInfo("kAnyOf", reg_node->next_pos); PrintString(reg_nfa_.data()+start_pos, &start_pos); break; case kAnyExcept: PrintRegNodeInfo("kAnyExcept", reg_node->next_pos); PrintString(reg_nfa_.data()+start_pos, &start_pos); break; case kParenStart: PrintRegNodeInfo("kParenStart", reg_node->next_pos); break; case kParenEnd: PrintRegNodeInfo("kParenEnd", reg_node->next_pos); break; case kPrecise: PrintRegNodeInfo("kPrecise", reg_node->next_pos); PrintString(reg_nfa_.data()+start_pos, &start_pos); break; case kBranch: PrintRegNodeInfo("kBranch", reg_node->next_pos); break; case kBack: PrintRegNodeInfo("kBack", reg_node->next_pos); break; case kEnd: PrintRegNodeInfo("kEnd", reg_node->next_pos); break; case kNothing: PrintRegNodeInfo("kNothing", reg_node->next_pos); break; default: ret = kInvalidRegEnd; break; } }/*}}}*/ return ret; }/*}}}*/ Code RegExp::GetRegNfa(std::string *reg_nfa) {/*{{{*/ if (reg_nfa == NULL) return kInvalidParam; *reg_nfa = reg_nfa_; return kOk; }/*}}}*/ Code RegExp::GetCheckIfBOL(bool *check_if_bol) {/*{{{*/ if (check_if_bol == NULL) return kInvalidParam; *check_if_bol = just_check_bol_; return kOk; }/*}}}*/ void RegExp::PrintRegNodeInfo(const std::string &opcode_info, uint16_t next_pos) {/*{{{*/ fprintf(stderr, "%s\n", opcode_info.c_str()); fprintf(stderr, "0x%02x\n", next_pos&0x00ff); fprintf(stderr, "0x%02x\n", (next_pos>>8)&0x00ff); }/*}}}*/ void RegExp::PrintString(const char *str, uint32_t *next_pos) {/*{{{*/ assert(str != NULL && next_pos != NULL); const char *tmp_str = str; while (*tmp_str != '\0') { fprintf(stderr, "%c\n", *tmp_str); tmp_str++; } fprintf(stderr, "\\0\n"); tmp_str++; *next_pos += tmp_str - str; }/*}}}*/ }
30.787283
121
0.537344
haveTryTwo
d1cd2c3833c6c157b12421690df1a2082416f76a
2,779
cpp
C++
clever_algorithms/demos/compact_genetic_algorithm.cpp
GreatV/CleverAlgorithms
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
[ "MIT" ]
2
2021-11-08T00:26:09.000Z
2021-12-21T08:16:43.000Z
clever_algorithms/demos/compact_genetic_algorithm.cpp
GreatV/CleverAlgorithms
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
[ "MIT" ]
null
null
null
clever_algorithms/demos/compact_genetic_algorithm.cpp
GreatV/CleverAlgorithms
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
[ "MIT" ]
null
null
null
#include <iostream> #include <random> #include <vector> #include <string> #include <algorithm> #include <cfloat> std::random_device rd; std::mt19937 generator(rd()); std::uniform_real_distribution<> distribution(0.0, 1.0); auto random_ = []() { return distribution(generator); }; using candidate_solution = struct candidate_solution_st { std::string bit_string; double fitness = DBL_MIN; }; double onemax(const std::string& bit_string) { double sum = 0.0; for (auto& item : bit_string) { if (item == '1') { sum++; } } return sum; } void random_bit_string(std::string& bit_string, const size_t size) { bit_string.clear(); for (size_t i = 0; i < size; ++i) { bit_string.push_back(random_() < 0.5 ? '1' : '0'); } } void generate_candidate(candidate_solution& candidate, const std::vector<double>& vector) { candidate.bit_string.resize(vector.size()); for (size_t i = 0; i < vector.size(); ++i) { const auto& p = vector[i]; candidate.bit_string[i] = random_() < p ? '1' : '0'; } candidate.fitness = onemax(candidate.bit_string); } void update_vector(std::vector<double>& vector, const candidate_solution& winner, const candidate_solution& loser, const size_t pop_size) { for (size_t i = 0; i < vector.size(); ++i) { if (winner.bit_string[i] != loser.bit_string[i]) { if (winner.bit_string[i] == '1') { vector[i] += 1.0 / pop_size; } else { vector[i] -= 1.0 / pop_size; } } } } void search(candidate_solution& best, const size_t num_bits, const size_t max_iterations, const size_t pop_size) { std::vector<double> vector(num_bits); for (auto& v : vector) { v = 0.5; } for (size_t iter = 0; iter < max_iterations; ++iter) { candidate_solution c1, c2; generate_candidate(c1, vector); generate_candidate(c2, vector); candidate_solution winner = c1.fitness > c2.fitness ? c1 : c2; candidate_solution loser = c1.fitness > c2.fitness ? c2 : c1; if (iter == 0) { best = winner; } if (winner.fitness > best.fitness) { best = winner; } update_vector(vector, winner, loser, pop_size); std::cout << " > gen " << iter + 1 << ", f = " << best.fitness << ", b = " << best.bit_string << std::endl; if (static_cast<size_t>(best.fitness) == num_bits) { break; } } } int main(int argc, char* argv[]) { // problem configuration const size_t num_bits = 32; // algorithm configuration const size_t max_iter = 200; const size_t pop_size = 20; // execute the algorithm candidate_solution best; search(best, num_bits, max_iter, pop_size); std::cout << "Done! Solution: f = " << best.fitness; std::cout << ", b = " << best.bit_string << std::endl; return 0; }
19.992806
89
0.627204
GreatV
d1ce7c0aff261a6f275e2eab27052dbd68e1ebd8
32,710
cxx
C++
main/chart2/source/controller/dialogs/ObjectNameProvider.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/chart2/source/controller/dialogs/ObjectNameProvider.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/chart2/source/controller/dialogs/ObjectNameProvider.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_chart2.hxx" #include "ObjectNameProvider.hxx" #include "ResId.hxx" #include "Strings.hrc" #include "macros.hxx" #include "AxisHelper.hxx" #include "ChartModelHelper.hxx" #include "DiagramHelper.hxx" #include "DataSeriesHelper.hxx" #include "TitleHelper.hxx" #include "AxisIndexDefines.hxx" #include "ExplicitCategoriesProvider.hxx" #include "CommonConverters.hxx" #include "NumberFormatterWrapper.hxx" #include "RegressionCurveHelper.hxx" #include <rtl/math.hxx> #include <tools/debug.hxx> #include <tools/string.hxx> #include <com/sun/star/chart2/XTitle.hpp> #include <com/sun/star/chart2/XRegressionCurveContainer.hpp> //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Any; using rtl::OUString; namespace { OUString lcl_getDataSeriesName( const rtl::OUString& rObjectCID, const Reference< frame::XModel >& xChartModel ) { OUString aRet; Reference< XDiagram > xDiagram( ChartModelHelper::findDiagram( xChartModel ) ); Reference< XDataSeries > xSeries( ObjectIdentifier::getDataSeriesForCID( rObjectCID , xChartModel ), uno::UNO_QUERY ); if( xDiagram.is() && xSeries.is() ) { Reference< XChartType > xChartType( DiagramHelper::getChartTypeOfSeries( xDiagram, xSeries ) ); if( xChartType.is() ) { aRet = ::chart::DataSeriesHelper::getDataSeriesLabel( xSeries, xChartType->getRoleOfSequenceForSeriesLabel() ) ; } } return aRet; } OUString lcl_getFullSeriesName( const rtl::OUString& rObjectCID, const Reference< frame::XModel >& xChartModel ) { OUString aRet = String(SchResId(STR_TIP_DATASERIES)); OUString aWildcard( C2U("%SERIESNAME") ); sal_Int32 nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), lcl_getDataSeriesName( rObjectCID, xChartModel ) ); return aRet; } void lcl_addText( OUString& rOut, const OUString& rSeparator, const OUString& rNext ) { if( !rOut.isEmpty() && !rNext.isEmpty() ) rOut+=rSeparator; if( !rNext.isEmpty() ) rOut+=rNext; } OUString lcl_getDataPointValueText( const Reference< XDataSeries >& xSeries, sal_Int32 nPointIndex, const Reference< XCoordinateSystem >& xCooSys, const Reference< frame::XModel >& xChartModel ) { OUString aRet; Reference<data::XDataSource> xDataSource( uno::Reference<data::XDataSource>( xSeries, uno::UNO_QUERY ) ); if(!xDataSource.is()) return aRet; Sequence< Reference< data::XLabeledDataSequence > > aDataSequences( xDataSource->getDataSequences() ); rtl::OUString aX, aY, aY_Min, aY_Max, aY_First, aY_Last, a_Size; double fValue = 0; uno::Reference< util::XNumberFormatsSupplier > xNumberFormatsSupplier( xChartModel, uno::UNO_QUERY ); NumberFormatterWrapper aNumberFormatterWrapper( xNumberFormatsSupplier ); sal_Int32 nLabelColor = 0;//dummy bool bColorChanged;//dummy for(sal_Int32 nN = aDataSequences.getLength();nN--;) { uno::Reference<data::XDataSequence> xDataSequence( aDataSequences[nN]->getValues()); if( !xDataSequence.is() ) continue; Sequence< Any > aData( xDataSequence->getData() ); if( nPointIndex >= aData.getLength() ) continue; uno::Reference<beans::XPropertySet> xProp(xDataSequence, uno::UNO_QUERY ); if( xProp.is()) { try { uno::Any aARole = xProp->getPropertyValue( C2U( "Role" ) ); rtl::OUString aRole; aARole >>= aRole; if( aRole.equals(C2U("values-x")) ) { aData[nPointIndex]>>= fValue; sal_Int32 nNumberFormatKey = xDataSequence->getNumberFormatKeyByIndex( nPointIndex ); aX = aNumberFormatterWrapper.getFormattedString( nNumberFormatKey, fValue, nLabelColor, bColorChanged ); } else if( aRole.equals(C2U("values-y")) ) { aData[nPointIndex]>>= fValue; sal_Int32 nNumberFormatKey = xDataSequence->getNumberFormatKeyByIndex( nPointIndex ); aY = aNumberFormatterWrapper.getFormattedString( nNumberFormatKey, fValue, nLabelColor, bColorChanged ); } else if( aRole.equals(C2U("values-first")) ) { aData[nPointIndex]>>= fValue; sal_Int32 nNumberFormatKey = xDataSequence->getNumberFormatKeyByIndex( nPointIndex ); aY_First = aNumberFormatterWrapper.getFormattedString( nNumberFormatKey, fValue, nLabelColor, bColorChanged ); } else if( aRole.equals(C2U("values-min")) ) { aData[nPointIndex]>>= fValue; sal_Int32 nNumberFormatKey = xDataSequence->getNumberFormatKeyByIndex( nPointIndex ); aY_Min = aNumberFormatterWrapper.getFormattedString( nNumberFormatKey, fValue, nLabelColor, bColorChanged ); } else if( aRole.equals(C2U("values-max")) ) { aData[nPointIndex]>>= fValue; sal_Int32 nNumberFormatKey = xDataSequence->getNumberFormatKeyByIndex( nPointIndex ); aY_Max = aNumberFormatterWrapper.getFormattedString( nNumberFormatKey, fValue, nLabelColor, bColorChanged ); } else if( aRole.equals(C2U("values-last")) ) { aData[nPointIndex]>>= fValue; sal_Int32 nNumberFormatKey = xDataSequence->getNumberFormatKeyByIndex( nPointIndex ); aY_Last = aNumberFormatterWrapper.getFormattedString( nNumberFormatKey, fValue, nLabelColor, bColorChanged ); } else if( aRole.equals(C2U("values-size")) ) { aData[nPointIndex]>>= fValue; sal_Int32 nNumberFormatKey = xDataSequence->getNumberFormatKeyByIndex( nPointIndex ); a_Size = aNumberFormatterWrapper.getFormattedString( nNumberFormatKey, fValue, nLabelColor, bColorChanged ); } } catch( uno::Exception& e ) { ASSERT_EXCEPTION( e ); } } } if( aX.isEmpty() ) { aRet = ExplicitCategoriesProvider::getCategoryByIndex( xCooSys, xChartModel, nPointIndex ); } else { aRet = aX; } OUString aSeparator(C2U(" ")); lcl_addText( aRet, aSeparator, aY ); lcl_addText( aRet, aSeparator, aY_First ); lcl_addText( aRet, aSeparator, aY_Min ); lcl_addText( aRet, aSeparator, aY_Max ); lcl_addText( aRet, aSeparator, aY_Last ); lcl_addText( aRet, aSeparator, a_Size ); return aRet; } } //end anonymous namespace rtl::OUString ObjectNameProvider::getName( ObjectType eObjectType, bool bPlural ) { rtl::OUString aRet; switch( eObjectType ) { case OBJECTTYPE_PAGE: aRet=String(SchResId(STR_OBJECT_PAGE)); break; case OBJECTTYPE_TITLE: { if(bPlural) aRet=String(SchResId(STR_OBJECT_TITLES)); else aRet=String(SchResId(STR_OBJECT_TITLE)); } break; case OBJECTTYPE_LEGEND: aRet=String(SchResId(STR_OBJECT_LEGEND)); break; case OBJECTTYPE_LEGEND_ENTRY: aRet=String(SchResId(STR_OBJECT_LEGEND_SYMBOL));//@todo change string if we do differenciate symbol and legend entry in future break; case OBJECTTYPE_DIAGRAM: aRet=String(SchResId(STR_OBJECT_DIAGRAM)); break; case OBJECTTYPE_DIAGRAM_WALL: aRet=String(SchResId(STR_OBJECT_DIAGRAM_WALL)); break; case OBJECTTYPE_DIAGRAM_FLOOR: aRet=String(SchResId(STR_OBJECT_DIAGRAM_FLOOR)); break; case OBJECTTYPE_AXIS: { if(bPlural) aRet=String(SchResId(STR_OBJECT_AXES)); else aRet=String(SchResId(STR_OBJECT_AXIS)); } break; case OBJECTTYPE_AXIS_UNITLABEL: aRet=String(SchResId(STR_OBJECT_LABEL));//@todo maybe a more concrete name break; case OBJECTTYPE_GRID: case OBJECTTYPE_SUBGRID: //maybe todo: different names for subgrids { if(bPlural) aRet=String(SchResId(STR_OBJECT_GRIDS)); else aRet=String(SchResId(STR_OBJECT_GRID)); } break; case OBJECTTYPE_DATA_SERIES: { if(bPlural) aRet=String(SchResId(STR_OBJECT_DATASERIES_PLURAL)); else aRet=String(SchResId(STR_OBJECT_DATASERIES)); } break; case OBJECTTYPE_DATA_POINT: { if(bPlural) aRet=String(SchResId(STR_OBJECT_DATAPOINTS)); else aRet=String(SchResId(STR_OBJECT_DATAPOINT)); } break; case OBJECTTYPE_DATA_LABELS: aRet=String(SchResId(STR_OBJECT_DATALABELS)); break; case OBJECTTYPE_DATA_LABEL: aRet=String(SchResId(STR_OBJECT_LABEL)); break; case OBJECTTYPE_DATA_ERRORS: aRet=String(SchResId(STR_OBJECT_ERROR_BARS));//@todo? maybe distinguish plural singular break; case OBJECTTYPE_DATA_ERRORS_X: aRet=String(SchResId(STR_OBJECT_ERROR_BARS));//@todo? maybe specialize in future break; case OBJECTTYPE_DATA_ERRORS_Y: aRet=String(SchResId(STR_OBJECT_ERROR_BARS));//@todo? maybe specialize in future break; case OBJECTTYPE_DATA_ERRORS_Z: aRet=String(SchResId(STR_OBJECT_ERROR_BARS));//@todo? maybe specialize in future break; case OBJECTTYPE_DATA_AVERAGE_LINE: aRet=String(SchResId(STR_OBJECT_AVERAGE_LINE)); break; case OBJECTTYPE_DATA_CURVE: { if(bPlural) aRet=String(SchResId(STR_OBJECT_CURVES)); else aRet=String(SchResId(STR_OBJECT_CURVE)); } break; case OBJECTTYPE_DATA_STOCK_RANGE: //aRet=String(SchResId()); break; case OBJECTTYPE_DATA_STOCK_LOSS: aRet=String(SchResId(STR_OBJECT_STOCK_LOSS)); break; case OBJECTTYPE_DATA_STOCK_GAIN: aRet=String(SchResId(STR_OBJECT_STOCK_GAIN)); break; case OBJECTTYPE_DATA_CURVE_EQUATION: aRet=String(SchResId(STR_OBJECT_CURVE_EQUATION)); break; default: //OBJECTTYPE_UNKNOWN ; } return aRet; } rtl::OUString ObjectNameProvider::getAxisName( const rtl::OUString& rObjectCID , const uno::Reference< frame::XModel >& xChartModel ) { rtl::OUString aRet; Reference< XAxis > xAxis( ObjectIdentifier::getObjectPropertySet( rObjectCID , xChartModel ), uno::UNO_QUERY ); sal_Int32 nCooSysIndex = 0; sal_Int32 nDimensionIndex = 0; sal_Int32 nAxisIndex = 0; AxisHelper::getIndicesForAxis( xAxis, ChartModelHelper::findDiagram( xChartModel ), nCooSysIndex, nDimensionIndex, nAxisIndex ); switch(nDimensionIndex) { case 0://x-axis if( nAxisIndex == 0 ) aRet=String(SchResId(STR_OBJECT_AXIS_X)); else aRet=String(SchResId(STR_OBJECT_SECONDARY_X_AXIS)); break; case 1://y-axis if( nAxisIndex == 0 ) aRet=String(SchResId(STR_OBJECT_AXIS_Y)); else aRet=String(SchResId(STR_OBJECT_SECONDARY_Y_AXIS)); break; case 2://z-axis aRet=String(SchResId(STR_OBJECT_AXIS_Z)); break; default://axis aRet=String(SchResId(STR_OBJECT_AXIS)); break; } return aRet; } OUString ObjectNameProvider::getTitleNameByType( TitleHelper::eTitleType eType ) { OUString aRet; switch(eType) { case TitleHelper::MAIN_TITLE: aRet=String(SchResId(STR_OBJECT_TITLE_MAIN)); break; case TitleHelper::SUB_TITLE: aRet=String(SchResId(STR_OBJECT_TITLE_SUB)); break; case TitleHelper::X_AXIS_TITLE: aRet=String(SchResId(STR_OBJECT_TITLE_X_AXIS)); break; case TitleHelper::Y_AXIS_TITLE: aRet=String(SchResId(STR_OBJECT_TITLE_Y_AXIS)); break; case TitleHelper::Z_AXIS_TITLE: aRet=String(SchResId(STR_OBJECT_TITLE_Z_AXIS)); break; case TitleHelper::SECONDARY_X_AXIS_TITLE: aRet=String(SchResId(STR_OBJECT_TITLE_SECONDARY_X_AXIS)); break; case TitleHelper::SECONDARY_Y_AXIS_TITLE: aRet=String(SchResId(STR_OBJECT_TITLE_SECONDARY_Y_AXIS)); break; default: DBG_ERROR("unknown title type"); break; } if( aRet.isEmpty() ) aRet=String(SchResId(STR_OBJECT_TITLE)); return aRet; } OUString ObjectNameProvider::getTitleName( const OUString& rObjectCID , const Reference< frame::XModel >& xChartModel ) { OUString aRet; Reference< XTitle > xTitle( ObjectIdentifier::getObjectPropertySet( rObjectCID , xChartModel ), uno::UNO_QUERY ); if( xTitle.is() ) { TitleHelper::eTitleType eType; if( TitleHelper::getTitleType( eType, xTitle, xChartModel ) ) aRet = ObjectNameProvider::getTitleNameByType( eType ); } if( aRet.isEmpty() ) aRet=String(SchResId(STR_OBJECT_TITLE)); return aRet; } rtl::OUString ObjectNameProvider::getGridName( const rtl::OUString& rObjectCID , const uno::Reference< frame::XModel >& xChartModel ) { rtl::OUString aRet; sal_Int32 nCooSysIndex = -1; sal_Int32 nDimensionIndex = -1; sal_Int32 nAxisIndex = -1; Reference< XAxis > xAxis( ObjectIdentifier::getAxisForCID( rObjectCID , xChartModel ) ); AxisHelper::getIndicesForAxis( xAxis, ChartModelHelper::findDiagram( xChartModel ) , nCooSysIndex , nDimensionIndex, nAxisIndex ); bool bMainGrid = (ObjectIdentifier::getObjectType( rObjectCID ) == OBJECTTYPE_GRID); if( bMainGrid ) { switch(nDimensionIndex) { case 0://x-axis aRet=String(SchResId(STR_OBJECT_GRID_MAJOR_X)); break; case 1://y-axis aRet=String(SchResId(STR_OBJECT_GRID_MAJOR_Y)); break; case 2://z-axis aRet=String(SchResId(STR_OBJECT_GRID_MAJOR_Z)); break; default://axis aRet=String(SchResId(STR_OBJECT_GRID)); break; } } else { switch(nDimensionIndex) { case 0://x-axis aRet=String(SchResId(STR_OBJECT_GRID_MINOR_X)); break; case 1://y-axis aRet=String(SchResId(STR_OBJECT_GRID_MINOR_Y)); break; case 2://z-axis aRet=String(SchResId(STR_OBJECT_GRID_MINOR_Z)); break; default://axis aRet=String(SchResId(STR_OBJECT_GRID)); break; } } return aRet; } rtl::OUString ObjectNameProvider::getHelpText( const rtl::OUString& rObjectCID, const Reference< chart2::XChartDocument >& xChartDocument, bool bVerbose ) { return getHelpText( rObjectCID, Reference< frame::XModel >( xChartDocument, uno::UNO_QUERY ), bVerbose ); } rtl::OUString ObjectNameProvider::getHelpText( const rtl::OUString& rObjectCID, const Reference< frame::XModel >& xChartModel, bool bVerbose ) { rtl::OUString aRet; ObjectType eObjectType( ObjectIdentifier::getObjectType(rObjectCID) ); if( OBJECTTYPE_AXIS == eObjectType ) { aRet=ObjectNameProvider::getAxisName( rObjectCID, xChartModel ); } else if( OBJECTTYPE_GRID == eObjectType || OBJECTTYPE_SUBGRID == eObjectType ) { aRet=ObjectNameProvider::getGridName( rObjectCID, xChartModel ); } else if( OBJECTTYPE_TITLE == eObjectType ) { aRet=ObjectNameProvider::getTitleName( rObjectCID, xChartModel ); } else if( OBJECTTYPE_DATA_SERIES == eObjectType ) { aRet = lcl_getFullSeriesName( rObjectCID, xChartModel ); } else if( OBJECTTYPE_DATA_POINT == eObjectType ) { if( bVerbose ) { OUString aNewLine(C2U("\n")); aRet=String(SchResId(STR_TIP_DATAPOINT_INDEX)); aRet+=aNewLine; aRet+=String(SchResId(STR_TIP_DATASERIES)); aRet+=aNewLine; aRet+=String(SchResId(STR_TIP_DATAPOINT_VALUES)); } else aRet=String(SchResId(STR_TIP_DATAPOINT)); Reference< XDiagram > xDiagram( ChartModelHelper::findDiagram( xChartModel ) ); Reference< XDataSeries > xSeries( ObjectIdentifier::getDataSeriesForCID( rObjectCID , xChartModel ), uno::UNO_QUERY ); if( xDiagram.is() && xSeries.is() ) { sal_Int32 nPointIndex( ObjectIdentifier::getParticleID(rObjectCID).toInt32() ); //replace data point index sal_Int32 nIndex = -1; OUString aWildcard( C2U("%POINTNUMBER") ); nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) { aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), OUString::valueOf(nPointIndex+1) ); } //replace data series index aWildcard = C2U("%SERIESNUMBER"); nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) { ::std::vector< Reference< chart2::XDataSeries > > aSeriesVector( DiagramHelper::getDataSeriesFromDiagram( xDiagram ) ); sal_Int32 nSeriesIndex = -1; for( nSeriesIndex=aSeriesVector.size();nSeriesIndex--;) { if( aSeriesVector[nSeriesIndex] == xSeries ) { break; } } OUString aReplacement( OUString::valueOf(nSeriesIndex+1) ); aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), aReplacement ); } //replace point values aWildcard = C2U("%POINTVALUES"); nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), lcl_getDataPointValueText( xSeries,nPointIndex, DataSeriesHelper::getCoordinateSystemOfSeries(xSeries, xDiagram), xChartModel ) ); //replace series name aWildcard = C2U("%SERIESNAME"); nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), lcl_getDataSeriesName( rObjectCID, xChartModel ) ); } } /* else if( OBJECTTYPE_DIAGRAM == eObjectType ) { //todo different names for different diagram types ??? //or different names for series of different charttypes } */ else if( OBJECTTYPE_DATA_CURVE == eObjectType ) { if( bVerbose ) { aRet = String( SchResId( STR_OBJECT_CURVE_WITH_PARAMETERS )); Reference< chart2::XDataSeries > xSeries( ObjectIdentifier::getDataSeriesForCID( rObjectCID , xChartModel )); Reference< chart2::XRegressionCurveContainer > xCurveCnt( xSeries, uno::UNO_QUERY ); if( xCurveCnt.is()) { Reference< chart2::XRegressionCurve > xCurve( RegressionCurveHelper::getFirstCurveNotMeanValueLine( xCurveCnt )); if( xCurve.is()) { try { Reference< chart2::XRegressionCurveCalculator > xCalculator( xCurve->getCalculator(), uno::UNO_QUERY_THROW ); RegressionCurveHelper::initializeCurveCalculator( xCalculator, xSeries, xChartModel ); // replace formula sal_Int32 nIndex = -1; OUString aWildcard( C2U("%FORMULA") ); nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), xCalculator->getRepresentation()); // replace r^2 aWildcard = C2U("%RSQUARED"); nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) { sal_Unicode aDecimalSep( '.' ); //@todo: enable this code when a localized decimal //separator is also available for the formula // SvtSysLocale aSysLocale; // OUString aSep( aSysLocale.GetLocaleData().getNumDecimalSep()); // if( aSep.getLength() == 1 ) // aDecimalSep = aSep.toChar(); double fR( xCalculator->getCorrelationCoefficient()); aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), ::rtl::math::doubleToUString( fR*fR, rtl_math_StringFormat_G, 4, aDecimalSep, true )); } } catch( const uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } } } else { // non-verbose aRet = ObjectNameProvider::getName( eObjectType, false ); } } else if( OBJECTTYPE_DATA_AVERAGE_LINE == eObjectType ) { if( bVerbose ) { aRet = String( SchResId( STR_OBJECT_AVERAGE_LINE_WITH_PARAMETERS )); Reference< chart2::XDataSeries > xSeries( ObjectIdentifier::getDataSeriesForCID( rObjectCID , xChartModel )); Reference< chart2::XRegressionCurveContainer > xCurveCnt( xSeries, uno::UNO_QUERY ); if( xCurveCnt.is()) { Reference< chart2::XRegressionCurve > xCurve( RegressionCurveHelper::getMeanValueLine( xCurveCnt )); if( xCurve.is()) { try { Reference< chart2::XRegressionCurveCalculator > xCalculator( xCurve->getCalculator(), uno::UNO_QUERY_THROW ); RegressionCurveHelper::initializeCurveCalculator( xCalculator, xSeries, xChartModel ); sal_Unicode aDecimalSep( '.' ); // replace average value // SvtSysLocale aSysLocale; // OUString aSep( aSysLocale.GetLocaleData().getNumDecimalSep()); // if( aSep.getLength() == 1 ) // aDecimalSep = aSep.toChar(); sal_Int32 nIndex = -1; OUString aWildcard( C2U("%AVERAGE_VALUE") ); nIndex = aRet.indexOf( aWildcard ); // as the curve is constant, the value at any x-value is ok if( nIndex != -1 ) { const double fMeanValue( xCalculator->getCurveValue( 0.0 )); aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), ::rtl::math::doubleToUString( fMeanValue, rtl_math_StringFormat_G, 4, aDecimalSep, true )); } // replace standard deviation aWildcard = C2U("%STD_DEVIATION"); nIndex = aRet.indexOf( aWildcard ); if( nIndex != -1 ) { const double fStdDev( xCalculator->getCorrelationCoefficient()); aRet = aRet.replaceAt( nIndex, aWildcard.getLength(), ::rtl::math::doubleToUString( fStdDev, rtl_math_StringFormat_G, 4, aDecimalSep, true )); } } catch( const uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } } } else { // non-verbose aRet = ObjectNameProvider::getName( eObjectType, false ); } } else { aRet = ObjectNameProvider::getName( eObjectType, false ); } return aRet; } rtl::OUString ObjectNameProvider::getSelectedObjectText( const rtl::OUString & rObjectCID, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument >& xChartDocument ) { rtl::OUString aRet; ObjectType eObjectType( ObjectIdentifier::getObjectType(rObjectCID) ); Reference< frame::XModel > xChartModel( xChartDocument, uno::UNO_QUERY ); if( OBJECTTYPE_DATA_POINT == eObjectType ) { aRet = String( SchResId( STR_STATUS_DATAPOINT_MARKED )); Reference< XDiagram > xDiagram( ChartModelHelper::findDiagram( xChartModel ) ); Reference< XDataSeries > xSeries( ObjectIdentifier::getDataSeriesForCID( rObjectCID , xChartModel ), uno::UNO_QUERY ); if( xDiagram.is() && xSeries.is() ) { sal_Int32 nPointIndex( ObjectIdentifier::getParticleID(rObjectCID).toInt32() ); // replace data point index replaceParamterInString( aRet, C2U("%POINTNUMBER"), OUString::valueOf( nPointIndex + 1 )); // replace data series index { ::std::vector< Reference< chart2::XDataSeries > > aSeriesVector( DiagramHelper::getDataSeriesFromDiagram( xDiagram ) ); sal_Int32 nSeriesIndex = -1; for( nSeriesIndex=aSeriesVector.size();nSeriesIndex--;) { if( aSeriesVector[nSeriesIndex] == xSeries ) break; } replaceParamterInString( aRet, C2U("%SERIESNUMBER"), OUString::valueOf( nSeriesIndex + 1 ) ); } // replace point value replaceParamterInString( aRet, C2U("%POINTVALUES"), lcl_getDataPointValueText( xSeries, nPointIndex, DataSeriesHelper::getCoordinateSystemOfSeries(xSeries, xDiagram), xChartModel ) ); } } else { // use the verbose text including the formula for trend lines const bool bVerbose( OBJECTTYPE_DATA_CURVE == eObjectType || OBJECTTYPE_DATA_AVERAGE_LINE == eObjectType ); const OUString aHelpText( getHelpText( rObjectCID, xChartModel, bVerbose )); if( !aHelpText.isEmpty() ) { aRet = String( SchResId( STR_STATUS_OBJECT_MARKED )); replaceParamterInString( aRet, C2U("%OBJECTNAME"), aHelpText ); } } return aRet; } rtl::OUString ObjectNameProvider::getNameForCID( const rtl::OUString& rObjectCID, const uno::Reference< chart2::XChartDocument >& xChartDocument ) { ObjectType eType( ObjectIdentifier::getObjectType( rObjectCID )); Reference< frame::XModel > xModel( xChartDocument, uno::UNO_QUERY ); switch( eType ) { case OBJECTTYPE_AXIS: return getAxisName( rObjectCID, xModel ); case OBJECTTYPE_TITLE: return getTitleName( rObjectCID, xModel ); case OBJECTTYPE_GRID: case OBJECTTYPE_SUBGRID: return getGridName( rObjectCID, xModel ); case OBJECTTYPE_DATA_SERIES: return lcl_getFullSeriesName( rObjectCID, xModel ); //case OBJECTTYPE_LEGEND_ENTRY: case OBJECTTYPE_DATA_POINT: case OBJECTTYPE_DATA_LABELS: case OBJECTTYPE_DATA_LABEL: case OBJECTTYPE_DATA_ERRORS: case OBJECTTYPE_DATA_ERRORS_X: case OBJECTTYPE_DATA_ERRORS_Y: case OBJECTTYPE_DATA_ERRORS_Z: case OBJECTTYPE_DATA_CURVE: case OBJECTTYPE_DATA_AVERAGE_LINE: case OBJECTTYPE_DATA_CURVE_EQUATION: { rtl::OUString aRet = lcl_getFullSeriesName( rObjectCID, xModel ); aRet += C2U(" "); if( eType == OBJECTTYPE_DATA_POINT || eType == OBJECTTYPE_DATA_LABEL ) { aRet += getName( OBJECTTYPE_DATA_POINT ); sal_Int32 nPointIndex = ObjectIdentifier::getIndexFromParticleOrCID( rObjectCID ); aRet += C2U(" "); aRet += OUString::valueOf(nPointIndex+1); if( eType == OBJECTTYPE_DATA_LABEL ) { aRet += C2U(" "); aRet += getName( OBJECTTYPE_DATA_LABEL ); } } else aRet += getName( eType ); return aRet; } default: break; } return getName( eType ); } rtl::OUString ObjectNameProvider::getName_ObjectForSeries( ObjectType eObjectType, const rtl::OUString& rSeriesCID, const uno::Reference< chart2::XChartDocument >& xChartDocument ) { uno::Reference< frame::XModel> xChartModel( xChartDocument, uno::UNO_QUERY ); Reference< XDataSeries > xSeries( ObjectIdentifier::getDataSeriesForCID( rSeriesCID , xChartModel ), uno::UNO_QUERY ); if( xSeries.is() ) { OUString aRet = String(SchResId(STR_OBJECT_FOR_SERIES)); replaceParamterInString( aRet, C2U("%OBJECTNAME"), getName( eObjectType, false /*bPlural*/ ) ); replaceParamterInString( aRet, C2U("%SERIESNAME"), lcl_getDataSeriesName( rSeriesCID, xChartModel ) ); return aRet; } else return ObjectNameProvider::getName_ObjectForAllSeries( eObjectType ); } rtl::OUString ObjectNameProvider::getName_ObjectForAllSeries( ObjectType eObjectType ) { OUString aRet = String(SchResId(STR_OBJECT_FOR_ALL_SERIES)); replaceParamterInString( aRet, C2U("%OBJECTNAME"), getName( eObjectType, true /*bPlural*/ ) ); return aRet; } //............................................................................. } //namespace chart //.............................................................................
39.220624
191
0.568053
Grosskopf
d1cedcdd1430101a4631874c7807cefb6dae37d4
14,948
cpp
C++
main/pod_archiver.cpp
an-erd/blePOD
2f56763487b485b61d87e600e8b095702851b078
[ "MIT" ]
null
null
null
main/pod_archiver.cpp
an-erd/blePOD
2f56763487b485b61d87e600e8b095702851b078
[ "MIT" ]
2
2019-04-04T11:51:37.000Z
2019-04-04T11:52:20.000Z
main/pod_archiver.cpp
an-erd/blePOD
2f56763487b485b61d87e600e8b095702851b078
[ "MIT" ]
1
2020-04-02T13:43:27.000Z
2020-04-02T13:43:27.000Z
#include <string.h> #include "esp_vfs_fat.h" #include "driver/sdmmc_host.h" #include "driver/sdspi_host.h" #include "sdmmc_cmd.h" #include "pod_main.h" static const char* TAG = "POD_ARCHIVER"; // data buffers to keep in RAM // => CONFIG_SDCARD_NUM_BUFFERS=4 and CONFIG_SDCARD_BUFFER_SIZE=65536 static buffer_element_t buffers[CONFIG_SDCARD_NUM_BUFFERS][CONFIG_SDCARD_BUFFER_SIZE] EXT_RAM_ATTR; static uint8_t current_buffer; // buffer to write next elements to static uint32_t used_in_buffer[CONFIG_SDCARD_NUM_BUFFERS]; // position in resp. buffer static uint8_t next_buffer_to_write; // next buffer to write to static int s_ref_file_nr = -2; static bool new_file = true; EventGroupHandle_t pod_sd_evg; // static archiver buffer event group #define BUFFER_BLEADV_BIT (BIT0) static EventGroupHandle_t buffer_evg; // forward declaration void pod_archiver_set_to_next_buffer(); static void clean_buffer(uint8_t num_buffer) { memset(buffers[num_buffer], 0, sizeof(buffers[num_buffer])+1); used_in_buffer[num_buffer] = 0; } void pod_archiver_initialize() { buffer_evg = xEventGroupCreate(); for (int i = 0; i < CONFIG_SDCARD_NUM_BUFFERS; i++){ clean_buffer(i); } current_buffer = 0; next_buffer_to_write = 0; } //TF card test begin void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ ESP_LOGD(TAG, "listDir() > , Listing directory: %s\n", dirname); File root = fs.open(dirname); if(!root){ ESP_LOGW(TAG, "listDir(), Failed to open directory"); return; } if(!root.isDirectory()){ ESP_LOGW(TAG, "listDir(), Not a directory"); return; } File file = root.openNextFile(); while(file){ if(file.isDirectory()){ ESP_LOGD(TAG, "listDir(), DIR: %s", file.name()); if(levels){ listDir(fs, file.name(), levels -1); } } else { ESP_LOGD(TAG, "listDir(), FILE: %s, SIZE: %u", file.name(), file.size()); } file = root.openNextFile(); } ESP_LOGD(TAG, "listDir() <"); } void readFile(fs::FS &fs, const char * path) { ESP_LOGD(TAG, "readFile() >, Reading file: %s", path); File file = fs.open(path); if(!file){ ESP_LOGW(TAG, "readFile(), Failed to open file for reading"); return; } ESP_LOGD(TAG, "readFile(), Read from file: "); while(file.available()){ int ch = file.read(); ESP_LOGD(TAG, "readFile(): %c", ch); } ESP_LOGD(TAG, "readFile() <"); } void writeFile(fs::FS &fs, const char * path, const char * message){ ESP_LOGD(TAG, "writeFile() >, Writing file: %s", path); File file = fs.open(path, FILE_WRITE); if(!file){ ESP_LOGW(TAG, "writeFile(), Failed to open file for writing"); return; } if(file.print(message)){ ESP_LOGD(TAG, "writeFile() <, file written"); } else { ESP_LOGE(TAG, "writeFile() <, write failed"); } } //TF card test end static int read_sd_card_file_refnr() { // file handle and buffer to read FILE* f; char line[64]; int file_nr = -1; struct stat st; ESP_LOGD(TAG, "read_sd_card_file_refnr() >"); if (stat("/sd/refnr.txt", &st) == 0) { f = fopen("/sd/refnr.txt", "r"); if (f == NULL) { ESP_LOGE(TAG, "read_sd_card_file_refnr(): Failed to open file for reading"); return -1; } } else { f = fopen("/sd/refnr.txt", "w"); if (f == NULL) { ESP_LOGE(TAG, "read_sd_card_file_refnr(): Failed to open file for writing"); return -1; } fprintf(f, "0\n"); // start new file with (file_nr=) 0 fclose(f); ESP_LOGD(TAG, "read_sd_card_file_refnr(): New file refnr.txt written"); f = fopen("/sd/refnr.txt", "r"); if (f == NULL) { ESP_LOGE(TAG, "read_sd_card_file_refnr(): Failed to open file for reading (2)"); return -1; } } fgets(line, sizeof(line), f); fclose(f); // strip newline char* pos = strchr(line, '\n'); if (pos) { *pos = '\0'; } ESP_LOGD(TAG, "read_sd_card_file_refnr(): Read from file: '%s'", line); sscanf(line, "%d", (int*)&file_nr); s_ref_file_nr = file_nr; ESP_LOGD(TAG, "read_sd_card_file_refnr() <, file_nr = %d", file_nr); return file_nr; } static int write_sd_card_file_refnr(int new_refnr) { // file handle and buffer to read FILE* f; // char line[64]; struct stat st; ESP_LOGD(TAG, "write_sd_card_file_refnr() >, new_refnr = %d", new_refnr); if (stat("/sd/refnr.txt", &st) == 0) { ESP_LOGD(TAG, "write_sd_card_file_refnr(), stat = 0"); f = fopen("/sd/refnr.txt", "w"); if (f == NULL) { ESP_LOGE(TAG, "write_sd_card_file_refnr() <, Failed to open file for writing"); return -1; } fprintf(f, "%d\n", new_refnr); fclose(f); ESP_LOGD(TAG, "write_sd_card_file_refnr() <, File written"); } return new_refnr; } int write_out_buffers(bool write_only_completed) { // file handle and buffer to read FILE* f; char line[64]; int file_nr; char strftime_buf[64]; ESP_LOGD(TAG, "write_out_buffers() >"); // Read the last file number from file. If it does not exist, create a new and start with "0". // If it exists, read the value and increase by 1. file_nr = read_sd_card_file_refnr(); if(file_nr < 0) ESP_LOGE(TAG, "write_out_buffers(): Ref. file could not be read or created - ABORT"); // generate a new reference number if requested and store in file for upcoming use if(new_file){ file_nr++; new_file = false; write_sd_card_file_refnr(file_nr); } // generate new file name sprintf(line, CONFIG_SDCARD_FILE_NAME, file_nr); ESP_LOGD(TAG, "write_out_buffers(): generated file name '%s'", line); f = fopen(line, "a"); if(f == NULL) { f = fopen(line, "w"); if (f == NULL) { ESP_LOGE(TAG, "write_out_buffers(): Failed to open file for writing"); return 0; } ESP_LOGD(TAG, "write_out_buffers(): Created new file for write"); } else { ESP_LOGD(TAG, "write_out_buffers(): Opening file for append"); } if(!write_only_completed){ // switch to next buffer to ensure no conflict of new incoming data current_buffer = (current_buffer + 1) % CONFIG_SDCARD_NUM_BUFFERS; used_in_buffer[current_buffer] = 0; // just to be sure } while( next_buffer_to_write != current_buffer ){ // write buffer next_buffer_to_write // ESP_LOGD(TAG, "write_out_buffers(): write buffers[%u][0..%u]", next_buffer_to_write, used_in_buffer[next_buffer_to_write]); // for(uint32_t i = 0; i < used_in_buffer[next_buffer_to_write]; i++){ // // check for timestamp: strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo); // // TODO // if(buffers[next_buffer_to_write][i].timeinfo.tm_year != 0){ // strftime(strftime_buf, sizeof(strftime_buf), "%c", &buffers[next_buffer_to_write][i].timeinfo); // fprintf(f, "%u:%u,%s,%u,%u,%u\r\n", next_buffer_to_write, i, strftime_buf, // buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT); // ESP_LOGD(TAG, "write_out_buffers(): Write: %u:%u,%s,%u,%u,%u\n", next_buffer_to_write, i, strftime_buf, // buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT); // } else { // fprintf(f, "%u:%u,,%u,%u,%u\r\n", next_buffer_to_write, i, // buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT); // ESP_LOGD(TAG, "write_out_buffers(): Write: %u:%u,,,%u,%u,%u\n", next_buffer_to_write, i, // buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT); // } // } clean_buffer(next_buffer_to_write); next_buffer_to_write = (next_buffer_to_write + 1) % CONFIG_SDCARD_NUM_BUFFERS; } ESP_LOGD(TAG, "write_out_buffers(): Closing file"); fclose(f); ESP_LOGD(TAG, "write_out_buffers() <"); return 1; } void pod_archiver_set_next_element() { // int complete = xEventGroupWaitBits(dispod_sd_evg, POD_SD_WRITE_COMPLETED_BUFFER_EVT, pdFALSE, pdFALSE, 0) & POD_SD_WRITE_COMPLETED_BUFFER_EVT; // ESP_LOGD(TAG, "pod_archiver_set_next_element >: current_buffer %u, used in current buffer %u, size %u, complete %u", // current_buffer, used_in_buffer[current_buffer], CONFIG_SDCARD_BUFFER_SIZE, complete); used_in_buffer[current_buffer]++; if(used_in_buffer[current_buffer] == CONFIG_SDCARD_BUFFER_SIZE){ pod_archiver_set_to_next_buffer(); } // buffers[current_buffer][used_in_buffer[current_buffer]].timeinfo.tm_year = 0; // buffers[current_buffer][used_in_buffer[current_buffer]].cad = 0; // buffers[current_buffer][used_in_buffer[current_buffer]].GCT = 0; // buffers[current_buffer][used_in_buffer[current_buffer]].str = 9; // TODO check, wheter this case happens?! // complete = xEventGroupWaitBits(dispod_sd_evg, DISPOD_SD_WRITE_COMPLETED_BUFFER_EVT, pdFALSE, pdFALSE, 0) & DISPOD_SD_WRITE_COMPLETED_BUFFER_EVT; // ESP_LOGD(TAG, "dispod_archiver_set_next_element <: current_buffer %u, used in current buffer %u, size %u, complete %u", // current_buffer, used_in_buffer[current_buffer], CONFIG_SDCARD_BUFFER_SIZE, complete); } void pod_archiver_set_to_next_buffer() { ESP_LOGD(TAG, "pod_archiver_set_to_next_buffer >: current_buffer %u, used in current buffer %u ", current_buffer, used_in_buffer[current_buffer]); if( used_in_buffer[current_buffer] != 0) { // set to next (free) buffer and write (all and maybe incomplete) buffer but current current_buffer = (current_buffer + 1) % CONFIG_SDCARD_NUM_BUFFERS; used_in_buffer[current_buffer] = 0; xEventGroupSetBits(pod_sd_evg, POD_SD_WRITE_COMPLETED_BUFFER_EVT); } else { // do nothing because current buffer is empty ESP_LOGD(TAG, "pod_archiver_set_to_next_buffer: current_buffer empty, do nothing"); } ESP_LOGD(TAG, "pod_archiver_set_to_next_buffer <: current_buffer %u, used in current buffer %u ", current_buffer, used_in_buffer[current_buffer]); } void pod_archiver_check_full_element() { EventBits_t uxBits; // uxBits = xEventGroupWaitBits(buffer_evg, BUFFER_RSC_BIT | BUFFER_CUSTOM_BIT, pdTRUE, pdTRUE, 0); // if( (uxBits & (BUFFER_RSC_BIT | BUFFER_CUSTOM_BIT) ) == (BUFFER_RSC_BIT | BUFFER_CUSTOM_BIT) ){ // pod_archiver_set_next_element(); // } } void dispod_archiver_add_bleadv_values(/* TODO */) { // buffers[current_buffer][used_in_buffer[current_buffer]].GCT = new_GCT; // buffers[current_buffer][used_in_buffer[current_buffer]].str = new_str; // xEventGroupSetBits(buffer_evg, BUFFER_CUSTOM_BIT); pod_archiver_check_full_element(); } void pod_archiver_add_time(tm timeinfo) { char strftime_buf[64]; buffers[current_buffer][used_in_buffer[current_buffer]].timeinfo = timeinfo; strftime(strftime_buf, sizeof(strftime_buf), "%c", &buffers[current_buffer][used_in_buffer[current_buffer]].timeinfo); ESP_LOGD(TAG, "pod_archiver_add_time(): TIME: %s", strftime_buf); } void pod_archiver_set_new_file() { new_file = true; } void pod_archiver_task(void *pvParameters) { ESP_LOGI(TAG, "pod_archiver_task: started"); EventBits_t uxBits; bool write_only_completed = true; for (;;) { uxBits = xEventGroupWaitBits(pod_sd_evg, POD_SD_WRITE_COMPLETED_BUFFER_EVT | POD_SD_WRITE_ALL_BUFFER_EVT | POD_SD_PROBE_EVT | POD_SD_GENERATE_TESTDATA_EVT, pdTRUE, pdFALSE, portMAX_DELAY); ESP_LOGD(TAG, "pod_archiver_task(): uxBits = %u", uxBits); if(uxBits & POD_SD_PROBE_EVT){ xEventGroupClearBits(pod_sd_evg, POD_SD_PROBE_EVT); ESP_LOGD(TAG, "DISPOD_SD_PROBE_EVT: DISPOD_SD_PROBE_EVT"); ESP_LOGI(TAG, "SD card info %d, card size kb %llu, total kb %llu used kb %llu, used %3.1f perc.", SD.cardType(), SD.cardSize()/1024, SD.totalBytes()/1024, SD.usedBytes()/1024, (SD.usedBytes() / (float) SD.totalBytes())); // TF card test // listDir(SD, "/", 0); // writeFile(SD, "/hello.txt", "Hello world"); // readFile(SD, "/hello.txt"); if(SD.cardType() != CARD_NONE){ xEventGroupSetBits(pod_evg, POD_SD_AVAILABLE_BIT); pod_screen_status_update_sd(&pod_screen_status, SD_AVAILABLE); xEventGroupSetBits(pod_display_evg, POD_DISPLAY_UPDATE_BIT); ESP_ERROR_CHECK(esp_event_post_to(pod_loop_handle, WORKFLOW_EVENTS, POD_SD_INIT_DONE_EVT, NULL, 0, portMAX_DELAY)); } else { xEventGroupClearBits(pod_evg, POD_SD_AVAILABLE_BIT); pod_screen_status_update_sd(&pod_screen_status, SD_NOT_AVAILABLE); xEventGroupSetBits(pod_evg, POD_DISPLAY_UPDATE_BIT); ESP_ERROR_CHECK(esp_event_post_to(pod_loop_handle, WORKFLOW_EVENTS, POD_SD_INIT_DONE_EVT, NULL, 0, portMAX_DELAY)); } } if((uxBits & POD_SD_WRITE_COMPLETED_BUFFER_EVT) == POD_SD_WRITE_COMPLETED_BUFFER_EVT){ write_only_completed = !( (uxBits & POD_SD_WRITE_ALL_BUFFER_EVT) == POD_SD_WRITE_ALL_BUFFER_EVT); ESP_LOGD(TAG, "pod_archiver_task: POD_SD_WRITE_COMPLETED_BUFFER_EVT, write_only_completed=%d", write_only_completed); if( xEventGroupWaitBits(pod_evg, POD_SD_AVAILABLE_BIT, pdFALSE, pdFALSE, portMAX_DELAY) & POD_SD_AVAILABLE_BIT){ write_out_buffers(write_only_completed); } else { ESP_LOGE(TAG, "pod_archiver_task: write out completed buffers but no SD mounted"); } } if((uxBits & POD_SD_GENERATE_TESTDATA_EVT) == POD_SD_GENERATE_TESTDATA_EVT){ ESP_LOGD(TAG, "dispod_archiver_task: POD_SD_GENERATE_TESTDATA_EVT start"); for(int i=0; i < CONFIG_SDCARD_NUM_BUFFERS; i++){ for(int j=0; j < CONFIG_SDCARD_BUFFER_SIZE; j++){ if(j%2){ // pod_archiver_add_RSCValues(180); } else { // pod_archiver_add_customValues(352,1); } if((i==(CONFIG_SDCARD_NUM_BUFFERS-1)) && j == (CONFIG_SDCARD_BUFFER_SIZE-4)) break; } } ESP_LOGD(TAG, "pod_archiver_task: POD_SD_GENERATE_TESTDATA_EVT done"); } } }
38.230179
151
0.640888
an-erd
d1cf8b2fa29cd7c71130d8327c1348a397e69437
3,063
cpp
C++
server/homeserver/network/json/JsonApi.Scripting.cpp
williamkoehler/home-server
ce99af73ea2e53fea3939fe0c4442433e65ac670
[ "MIT" ]
1
2021-07-05T21:11:59.000Z
2021-07-05T21:11:59.000Z
server/homeserver/network/json/JsonApi.Scripting.cpp
williamkoehler/home-server
ce99af73ea2e53fea3939fe0c4442433e65ac670
[ "MIT" ]
null
null
null
server/homeserver/network/json/JsonApi.Scripting.cpp
williamkoehler/home-server
ce99af73ea2e53fea3939fe0c4442433e65ac670
[ "MIT" ]
null
null
null
#include "JsonApi.hpp" #include "../../scripting/ScriptManager.hpp" #include "../../scripting/Script.hpp" namespace server { // Scripting void JsonApi::BuildJsonScriptSources(rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator) { assert(output.IsObject()); Ref<ScriptManager> scriptManager = ScriptManager::GetInstance(); assert(scriptManager != nullptr); boost::shared_lock_guard lock(scriptManager->mutex); // ScriptSources rapidjson::Value ScriptSourceListJson = rapidjson::Value(rapidjson::kArrayType); boost::unordered::unordered_map<identifier_t, Ref<ScriptSource>>& scriptSourceList = scriptManager->scriptSourceList; for (auto [id, scriptSource] : scriptSourceList) { assert(scriptSource != nullptr); rapidjson::Value scriptSourceJson = rapidjson::Value(rapidjson::kObjectType); BuildJsonScriptSource(scriptSource, scriptSourceJson, allocator); ScriptSourceListJson.PushBack(scriptSourceJson, allocator); } output.AddMember("scriptsources", ScriptSourceListJson, allocator); } void JsonApi::BuildJsonScriptSource(Ref<ScriptSource> source, rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator) { assert(source != nullptr); assert(output.IsObject()); boost::lock_guard lock(source->mutex); output.AddMember("name", rapidjson::Value(source->name.c_str(), source->name.size()), allocator); output.AddMember("id", rapidjson::Value(source->sourceID), allocator); std::string lang = StringifyScriptLanguage(source->language); output.AddMember("language", rapidjson::Value(lang.c_str(), lang.size(), allocator), allocator); std::string usage = StringifyScriptUsage(source->usage); output.AddMember("usage", rapidjson::Value(usage.c_str(), usage.size(), allocator), allocator); } void JsonApi::DecodeJsonScriptSource(Ref<ScriptSource> source, rapidjson::Value& input) { assert(source != nullptr); assert(input.IsObject()); // Decode script properties if they exist { rapidjson::Value::MemberIterator nameIt = input.FindMember("name"); if (nameIt != input.MemberEnd() && nameIt->value.IsString()) source->SetName(std::string(nameIt->value.GetString(), nameIt->value.GetStringLength())); } } void JsonApi::BuildJsonScriptSourceData(Ref<ScriptSource> source, rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator) { assert(source != nullptr); assert(output.IsObject()); boost::lock_guard lock(source->mutex); output.AddMember("data", rapidjson::Value((const char*)source->data.data(), source->data.size(), allocator), allocator); } void JsonApi::DecodeJsonScriptSourceData(Ref<ScriptSource> source, rapidjson::Value& input) { assert(source != nullptr); assert(input.IsObject()); // Decode script properties if they exist { rapidjson::Value::MemberIterator sourceIt = input.FindMember("data"); if (sourceIt != input.MemberEnd() && sourceIt->value.IsString()) source->SetData(std::string_view((const char*)sourceIt->value.GetString(), sourceIt->value.GetStringLength())); } } }
36.035294
139
0.738818
williamkoehler
d1d2bafc4134151f41e0cc3a356e0f41b2c79e16
11,260
cpp
C++
3rdParty/iresearch/tests/utils/attributes_tests.cpp
0xflotus/arangodb
1de6a7aff9183920cb8d2241c9c226b30bcf4d05
[ "Apache-2.0" ]
1
2019-08-11T04:06:49.000Z
2019-08-11T04:06:49.000Z
3rdParty/iresearch/tests/utils/attributes_tests.cpp
0xflotus/arangodb
1de6a7aff9183920cb8d2241c9c226b30bcf4d05
[ "Apache-2.0" ]
null
null
null
3rdParty/iresearch/tests/utils/attributes_tests.cpp
0xflotus/arangodb
1de6a7aff9183920cb8d2241c9c226b30bcf4d05
[ "Apache-2.0" ]
1
2021-07-12T06:29:34.000Z
2021-07-12T06:29:34.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 by EMC Corporation, 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. /// /// Copyright holder is EMC Corporation /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include "tests_shared.hpp" #include "utils/attributes.hpp" NS_LOCAL template< typename T > inline T* copy_attribute(irs::attribute_store& dst, const irs::attribute_store& src) { typedef typename std::enable_if<std::is_base_of<irs::attribute, T>::value, T> ::type type; type* dsta = nullptr; const type* srca = src.get<type>().get(); if( srca) { *(dsta = dst.emplace<type>().get()) = *srca; } return dsta; } NS_END using namespace iresearch; namespace tests { struct attribute : iresearch::stored_attribute { DECLARE_ATTRIBUTE_TYPE(); DECLARE_FACTORY_DEFAULT(); virtual void clear() { value = 0; } int value = 5; bool operator==(const attribute& rhs ) const { return value == rhs.value; } }; DEFINE_ATTRIBUTE_TYPE(tests::attribute); DEFINE_FACTORY_DEFAULT(attribute); struct invalid_attribute : iresearch::stored_attribute { DECLARE_ATTRIBUTE_TYPE(); DECLARE_FACTORY_DEFAULT(); virtual void clear() { value = 0; } int value = 5; }; DEFINE_ATTRIBUTE_TYPE(tests::invalid_attribute); DEFINE_FACTORY_DEFAULT(invalid_attribute); } // tests TEST(attributes_tests, duplicate_register) { struct dummy_attribute: public irs::attribute { DECLARE_ATTRIBUTE_TYPE() { static irs::attribute::type_id type("dummy_attribute"); return type; } }; static bool initial_expected = true; // check required for tests with repeat (static maps are not cleared between runs) if (initial_expected) { ASSERT_FALSE(irs::attribute::type_id::exists("dummy_attribute")); ASSERT_EQ(nullptr, irs::attribute::type_id::get("dummy_attribute")); irs::attribute_registrar initial(dummy_attribute::type()); ASSERT_EQ(!initial_expected, !initial); } initial_expected = false; // next test iteration will not be able to register the same attribute irs::attribute_registrar duplicate(dummy_attribute::type()); ASSERT_TRUE(!duplicate); ASSERT_TRUE(irs::attribute::type_id::exists("dummy_attribute")); ASSERT_NE(nullptr, irs::attribute::type_id::get("dummy_attribute")); } TEST(attributes_tests, store_ctor) { irs::attribute_store attrs; ASSERT_EQ(0, attrs.size()); ASSERT_EQ(flags{}, attrs.features()); { attrs.emplace<tests::attribute>(); irs::attribute_store attrs1( std::move(attrs)); ASSERT_EQ(1, attrs1.size()); ASSERT_EQ(flags{tests::attribute::type()}, attrs1.features()); ASSERT_TRUE(attrs1.contains<tests::attribute>()); } ASSERT_EQ(0, attrs.size()); ASSERT_EQ(flags{}, attrs.features()); ASSERT_FALSE(attrs.contains<tests::attribute>()); } TEST(attributes_tests, store_copy) { irs::attribute_store src; auto& added = src.emplace<tests::attribute>(); added->value = 10; // copy attribute irs::attribute_store dst; tests::attribute* copied = copy_attribute<tests::attribute>(dst, src); ASSERT_NE(nullptr, copied); ASSERT_NE(&*added, copied); ASSERT_EQ(*added, *copied); /* copy invalid attribute */ tests::invalid_attribute* missed_copied = copy_attribute<tests::invalid_attribute>(src,dst); ASSERT_FALSE(missed_copied); } TEST(attributes_tests, store_add_get_clear_state_clear) { irs::attribute_store attrs; auto& added = attrs.emplace<tests::attribute>(); ASSERT_FALSE(!added); ASSERT_EQ(1, attrs.size()); ASSERT_TRUE(attrs.contains<tests::attribute>()); ASSERT_EQ(flags{added->type()}, attrs.features()); // add attribute { auto& added1 = attrs.emplace<tests::attribute>(); ASSERT_EQ(&*added, &*added1); ASSERT_EQ(1, attrs.size()); ASSERT_TRUE(attrs.contains<tests::attribute>()); ASSERT_EQ(flags{added->type()}, attrs.features()); } // get attribute { auto& added1 = added; //const_cast<const irs::attribute_store&>(attrs).get(added->type()); ASSERT_FALSE(!added1); auto& added2 = const_cast<const irs::attribute_store&>(attrs).get<tests::attribute>(); ASSERT_FALSE(!added2); ASSERT_EQ(added.get(), added2.get()); ASSERT_EQ(reinterpret_cast<void*>(added1.get()), added2.get()); } // // clear state // attrs.visit([]( // const attribute::type_id&, // attribute_store::ref<void>& ref // )->bool { // reinterpret_cast<attribute*>(ref.get())->clear(); // return true; // }); // ASSERT_EQ(0, added->value); //add attribute attrs.emplace<tests::invalid_attribute>(); ASSERT_EQ(2, attrs.size()); ASSERT_TRUE(attrs.contains<tests::invalid_attribute>()); ASSERT_EQ(flags({tests::attribute::type(), tests::invalid_attribute::type()}), attrs.features()); /* remove attribute */ attrs.remove<tests::invalid_attribute>(); ASSERT_EQ(1, attrs.size()); ASSERT_FALSE(attrs.contains<tests::invalid_attribute>()); ASSERT_EQ(flags{added->type()}, attrs.features()); /* clear */ attrs.clear(); ASSERT_EQ(0, attrs.size()); ASSERT_FALSE(attrs.contains<tests::attribute>()); ASSERT_EQ(flags{}, attrs.features()); } TEST(attributes_tests, store_visit) { irs::attribute_store attrs; // add first attribute ASSERT_FALSE(!attrs.emplace<tests::attribute>()); ASSERT_EQ(1, attrs.size()); ASSERT_TRUE(attrs.contains<tests::attribute>()); ASSERT_EQ(flags{tests::attribute::type()}, attrs.features()); // add second attribute ASSERT_FALSE(!attrs.emplace<tests::invalid_attribute>()); ASSERT_EQ(2, attrs.size()); ASSERT_TRUE(attrs.contains<tests::invalid_attribute>()); ASSERT_EQ(flags({tests::attribute::type(), tests::invalid_attribute::type()}), attrs.features()); // visit 2 attributes { std::unordered_set<const attribute::type_id*> expected; auto visitor = [&expected](const attribute::type_id& type_id, const attribute_store::ref<attribute>::type&)->bool { return 1 == expected.erase(&type_id); }; expected.insert(&(tests::attribute::type())); expected.insert(&(tests::invalid_attribute::type())); ASSERT_TRUE(attrs.visit(visitor)); ASSERT_TRUE(expected.empty()); } } TEST(attributes_tests, view_ctor) { irs::attribute_view attrs; ASSERT_EQ(0, attrs.size()); ASSERT_EQ(flags{}, attrs.features()); { tests::attribute value; attrs.emplace(value); irs::attribute_view attrs1(std::move(attrs)); ASSERT_EQ(1, attrs1.size()); ASSERT_EQ(flags{tests::attribute::type()}, attrs1.features()); ASSERT_TRUE(attrs1.contains<tests::attribute>()); ASSERT_EQ(&value, attrs1.get<tests::attribute>()->get()); } ASSERT_EQ(0, attrs.size()); ASSERT_EQ(flags{}, attrs.features()); ASSERT_FALSE(attrs.contains<tests::attribute>()); } TEST(attributes_tests, view_add_placeholder) { irs::attribute_view attrs; auto& added = attrs.emplace<tests::attribute>(); ASSERT_TRUE(!added); ASSERT_EQ(1, attrs.size()); ASSERT_TRUE(attrs.contains<tests::attribute>()); ASSERT_EQ(nullptr, attrs.get<tests::attribute>()->get()); tests::attribute value; added = &value; ASSERT_FALSE(!added); ASSERT_EQ(&value, attrs.get<tests::attribute>()->get()); } TEST(attributes_tests, view_add_get_clear_state_clear) { irs::attribute_view attrs; tests::attribute value0; auto& added = attrs.emplace(value0); ASSERT_FALSE(!added); ASSERT_EQ(1, attrs.size()); ASSERT_TRUE(attrs.contains<tests::attribute>()); ASSERT_EQ(&value0, attrs.get<tests::attribute>()->get()); ASSERT_EQ(flags{added->type()}, attrs.features()); // add attribute { tests::attribute value; auto& added1 = attrs.emplace(value); ASSERT_EQ(added.get(), added1.get()); ASSERT_EQ(1, attrs.size()); ASSERT_TRUE(attrs.contains<tests::attribute>()); ASSERT_EQ(&value0, attrs.get<tests::attribute>()->get()); ASSERT_EQ(flags{added->type()}, attrs.features()); } // get attribute { auto& added1 = added; //const_cast<const irs::attribute_view&>(attrs).get(added->type()); ASSERT_FALSE(!added1); auto& added2 = const_cast<const irs::attribute_view&>(attrs).get<tests::attribute>(); ASSERT_FALSE(!added2); ASSERT_EQ(added.get(), added2.get()); ASSERT_EQ(reinterpret_cast<const void*>(added1.get()), added2.get()); } // // clear state // attrs.visit([]( // const attribute::type_id&, // attribute_view::ref<void>& ref // )->bool { // reinterpret_cast<attribute*>(ref.get())->clear(); // return true; // }); // ASSERT_EQ(0, added->value); // add attribute tests::invalid_attribute value1; attrs.emplace(value1); ASSERT_EQ(2, attrs.size()); ASSERT_TRUE(attrs.contains<tests::invalid_attribute>()); ASSERT_EQ(&value1, attrs.get<tests::invalid_attribute>()->get()); ASSERT_EQ(flags({tests::attribute::type(), tests::invalid_attribute::type()}), attrs.features()); // remove attribute attrs.remove<tests::invalid_attribute>(); ASSERT_EQ(1, attrs.size()); ASSERT_FALSE(attrs.contains<tests::invalid_attribute>()); ASSERT_EQ(flags{added->type()}, attrs.features()); // clear attrs.clear(); ASSERT_EQ(0, attrs.size()); ASSERT_FALSE(attrs.contains<tests::attribute>()); ASSERT_EQ(flags{}, attrs.features()); } TEST(attributes_tests, view_visit) { irs::attribute_view attrs; tests::attribute value0; tests::invalid_attribute value1; // add first attribute ASSERT_FALSE(!attrs.emplace(value0)); ASSERT_EQ(1, attrs.size()); ASSERT_TRUE(attrs.contains<tests::attribute>()); ASSERT_EQ(&value0, attrs.get<tests::attribute>()->get()); ASSERT_EQ(flags{tests::attribute::type()}, attrs.features()); // add second attribute ASSERT_FALSE(!attrs.emplace(value1)); ASSERT_EQ(2, attrs.size()); ASSERT_TRUE(attrs.contains<tests::invalid_attribute>()); ASSERT_EQ(&value1, attrs.get<tests::invalid_attribute>()->get()); ASSERT_EQ(flags({tests::attribute::type(), tests::invalid_attribute::type()}), attrs.features()); // visit 2 attributes { std::unordered_set<const attribute::type_id*> expected; auto visitor = [&expected](const attribute::type_id& type_id, const attribute_view::ref<attribute>::type&)->bool { return 1 == expected.erase(&type_id); }; expected.insert(&(tests::attribute::type())); expected.insert(&(tests::invalid_attribute::type())); ASSERT_TRUE(attrs.visit(visitor)); ASSERT_TRUE(expected.empty()); } } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // -----------------------------------------------------------------------------
31.629213
119
0.670515
0xflotus
d1d563b4128702f0adb51bb7ae5c81cfb253799a
2,856
cpp
C++
tests/fasttrack_write_test.cpp
hassansalehe/EmbedSanitizer
51051b164c382b02d63e13183b869bbfa9e96e20
[ "BSD-3-Clause" ]
16
2018-08-04T08:15:09.000Z
2022-03-21T12:53:14.000Z
tests/fasttrack_write_test.cpp
hassansalehe/EmbedSanitizer
51051b164c382b02d63e13183b869bbfa9e96e20
[ "BSD-3-Clause" ]
16
2021-05-29T22:27:18.000Z
2021-07-18T20:41:58.000Z
tests/fasttrack_write_test.cpp
hassansalehe/embedsanitizer
51051b164c382b02d63e13183b869bbfa9e96e20
[ "BSD-3-Clause" ]
4
2018-08-04T08:00:25.000Z
2021-05-30T07:40:23.000Z
///////////////////////////////////////////////////// // // Copyright (c) 2017 - 2021 Hassan Salehe Matar // // See LICENSE file for information about the license. // // Unit tests for write function of fasttrack. // //////////////////////////////////////////////////// #include <gtest/gtest.h> #include "etsan/fasttrack.h" TEST(FasttrackWriteTestFixture, ftWriteCheckWritesCountIncremented) { VS.reads = 0; VS.writes = 0; constexpr bool no_race_found = false; VarState variable_state; variable_state.Racy = true; ThreadState thread_state; EXPECT_EQ(no_race_found, ft_write(variable_state, thread_state)); EXPECT_EQ(0, VS.reads); EXPECT_EQ(1, VS.writes); } TEST(FasttrackWriteTestFixture, ftWriteCheckNoRaceSameEpoch) { VS.reads = 0; VS.writes = 0; constexpr bool no_race_found = false; VarState variable_state; variable_state.Racy = false; variable_state.W = 1; ThreadState thread_state; thread_state.C.reserve(1); thread_state.tid = 0; thread_state.epoch = variable_state.W; EXPECT_EQ(no_race_found, ft_write(variable_state, thread_state)); EXPECT_EQ(1, VS.writes); EXPECT_EQ(0, VS.reads); } TEST(FasttrackWriteTestFixture, ftWriteDetectNewRace) { VS.reads = 0; VS.writes = 0; constexpr bool race_found = true; constexpr unsigned int num_threads = 5; constexpr int tid1 = 3; constexpr int tid2 = 1; VarState variable_state; variable_state.W = (tid2 << 24) + 124; ThreadState thread_state; thread_state.tid = tid1; NumThreads = num_threads; thread_state.C.reserve(num_threads); thread_state.C[tid2] = 123; EXPECT_EQ(race_found, ft_write(variable_state, thread_state)); EXPECT_EQ(0, VS.reads); EXPECT_EQ(1, VS.writes); // EXPECT_EQ(num_threads, variable_state.Rvc.size()); } TEST(FasttrackWriteTestFixture, ftWriteCheckUpdateOnSharedRead) { VS.reads = 0; constexpr unsigned int num_threads = 5; constexpr int tid = 3; VarState variable_state; variable_state.R = READ_SHARED; variable_state.Rvc.reserve(num_threads); ThreadState thread_state; thread_state.tid = tid; thread_state.epoch = 42; thread_state.C.reserve(num_threads); ft_write(variable_state, thread_state); EXPECT_EQ(thread_state.epoch, variable_state.W); } TEST(FasttrackWriteTestFixture, ftWriteCheckExclusive) { VS.reads = 0; constexpr bool race_found = true; constexpr unsigned int num_threads = 5; constexpr int tid = 3; constexpr int tid2 = 1; VarState variable_state; variable_state.R = (tid2 << 24) + 0; variable_state.W = (tid2 << 24) + 1; ThreadState thread_state; thread_state.tid = tid; thread_state.epoch = 42; thread_state.C.reserve(num_threads); thread_state.C[tid2] = variable_state.W - 1; //(x.W > C[tid2]) EXPECT_EQ(race_found, ft_write(variable_state, thread_state)); EXPECT_EQ(thread_state.epoch, variable_state.W); }
25.5
69
0.708683
hassansalehe
d1d8dd3d30b5376b65872a62e0ca2070f5118964
4,082
cpp
C++
emulator/src/mame/machine/inder_vid.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/machine/inder_vid.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/machine/inder_vid.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:David Haywood /* Inder / Dinamic Video */ #include "emu.h" #include "machine/inder_vid.h" #include "screen.h" DEFINE_DEVICE_TYPE(INDER_VIDEO, inder_vid_device, "indervd", "Inder / Dinamic TMS Video") inder_vid_device::inder_vid_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, INDER_VIDEO, tag, owner, clock), /* device_video_interface(mconfig, *this, false), */ m_vram(*this, "vram"), m_palette(*this, "palette"), m_tms(*this, "tms"), m_bpp_mode(8) { } void inder_vid_device::megaphx_tms_map(address_map &map) { map(0x00000000, 0x003fffff).ram().share("vram"); // vram? map(0x04000000, 0x0400000f).w("ramdac", FUNC(ramdac_device::index_w)).umask16(0x00ff); map(0x04000010, 0x0400001f).rw("ramdac", FUNC(ramdac_device::pal_r), FUNC(ramdac_device::pal_w)).umask16(0x00ff); map(0x04000030, 0x0400003f).w("ramdac", FUNC(ramdac_device::index_r_w)).umask16(0x00ff); map(0x04000090, 0x0400009f).nopw(); map(0x7fc00000, 0x7fffffff).ram().mirror(0x80000000); map(0xc0000000, 0xc00001ff).rw("tms", FUNC(tms34010_device::io_register_r), FUNC(tms34010_device::io_register_w)); } TMS340X0_SCANLINE_RGB32_CB_MEMBER(inder_vid_device::scanline) { uint16_t *vram = &m_vram[(params->rowaddr << 8) & 0x3ff00]; uint32_t *dest = &bitmap.pix32(scanline); const pen_t *paldata = m_palette->pens(); int coladdr = params->coladdr; int x; if (m_bpp_mode == 8) { for (x = params->heblnk; x < params->hsblnk; x += 2) { uint16_t pixels = vram[coladdr++ & 0xff]; dest[x + 0] = paldata[pixels & 0xff]; dest[x + 1] = paldata[pixels >> 8]; } } else if (m_bpp_mode == 4) { for (x = params->heblnk; x < params->hsblnk; x += 4) { uint16_t pixels = vram[coladdr++ & 0xff]; dest[x + 3] = paldata[((pixels & 0xf000) >> 12)]; dest[x + 2] = paldata[((pixels & 0x0f00) >> 8)]; dest[x + 1] = paldata[((pixels & 0x00f0) >> 4)]; dest[x + 0] = paldata[((pixels & 0x000f) >> 0)]; } } else { fatalerror("inder_vid_device unsupported mode, not 4bpp or 8bpp"); } } TMS340X0_TO_SHIFTREG_CB_MEMBER(inder_vid_device::to_shiftreg) { if (m_shiftfull == 0) { //printf("read to shift regs address %08x\n", address); memcpy(shiftreg, &m_vram[(address & ~0x1fff) >> 4], 0x400); // & ~0x1fff is needed for round 6 m_shiftfull = 1; } } TMS340X0_FROM_SHIFTREG_CB_MEMBER(inder_vid_device::from_shiftreg) { // printf("write from shift regs address %08x\n", address); memcpy(&m_vram[(address & ~0x1fff) >> 4], shiftreg, 0x400); m_shiftfull = 0; } WRITE_LINE_MEMBER(inder_vid_device::m68k_gen_int) { cpu_device *maincpu = (cpu_device*)machine().device("maincpu"); if (state) maincpu->set_input_line(4, ASSERT_LINE); else maincpu->set_input_line(4, CLEAR_LINE); } void inder_vid_device::ramdac_map(address_map &map) { map(0x000, 0x3ff).rw("ramdac", FUNC(ramdac_device::ramdac_pal_r), FUNC(ramdac_device::ramdac_rgb888_w)); } MACHINE_CONFIG_START(inder_vid_device::device_add_mconfig) MCFG_CPU_ADD("tms", TMS34010, XTAL(40'000'000)) MCFG_CPU_PROGRAM_MAP(megaphx_tms_map) MCFG_TMS340X0_HALT_ON_RESET(true) /* halt on reset */ MCFG_TMS340X0_PIXEL_CLOCK(XTAL(40'000'000)/12) /* pixel clock */ MCFG_TMS340X0_PIXELS_PER_CLOCK(2) /* pixels per clock */ MCFG_TMS340X0_SCANLINE_RGB32_CB(inder_vid_device, scanline) /* scanline updater (RGB32) */ MCFG_TMS340X0_OUTPUT_INT_CB(WRITELINE(inder_vid_device, m68k_gen_int)) MCFG_TMS340X0_TO_SHIFTREG_CB(inder_vid_device, to_shiftreg) /* write to shiftreg function */ MCFG_TMS340X0_FROM_SHIFTREG_CB(inder_vid_device, from_shiftreg) /* read from shiftreg function */ MCFG_SCREEN_ADD("inder_screen", RASTER) MCFG_SCREEN_RAW_PARAMS(XTAL(40'000'000)/12, 424, 0, 338-1, 262, 0, 246-1) MCFG_SCREEN_UPDATE_DEVICE("tms", tms34010_device, tms340x0_rgb32) MCFG_PALETTE_ADD("palette", 256) MCFG_RAMDAC_ADD("ramdac", ramdac_map, "palette") MCFG_RAMDAC_SPLIT_READ(1) MACHINE_CONFIG_END void inder_vid_device::device_start() { } void inder_vid_device::device_reset() { m_shiftfull = 0; }
29.366906
115
0.72048
rjw57
d1dc4cac45a41455171ed2735fe0ccb3d0328347
198
hpp
C++
lib/src/include/deskgap/shell.hpp
perjonsson/DeskGap
5e74de37c057de3bac3ac16b3fabdb79b934d21e
[ "MIT" ]
1,910
2019-02-08T05:41:48.000Z
2022-03-24T23:41:33.000Z
lib/src/include/deskgap/shell.hpp
perjonsson/DeskGap
5e74de37c057de3bac3ac16b3fabdb79b934d21e
[ "MIT" ]
73
2019-02-13T02:58:20.000Z
2022-03-02T05:49:34.000Z
lib/src/include/deskgap/shell.hpp
ci010/DeskGap
b3346fea3dd3af7df9a0420131da7f4ac1518092
[ "MIT" ]
88
2019-02-13T12:41:00.000Z
2022-03-25T05:04:31.000Z
#ifndef DESKGAP_SHELL_HPP #define DESKGAP_SHELL_HPP #include <string> namespace DeskGap { class Shell { public: static bool OpenExternal(const std::string& path); }; } #endif
14.142857
58
0.686869
perjonsson
d1e19fa80bce25417580c52feb9e6f87d52b607d
550
hpp
C++
src/Test.hpp
Vasile2k/ImageSubjectFocus
0eed32df07b74eb89a1e1130975aa4ddec2adf32
[ "Apache-2.0" ]
3
2020-01-02T23:35:01.000Z
2021-01-25T11:02:06.000Z
src/Test.hpp
Vasile2k/ImageSubjectFocus
0eed32df07b74eb89a1e1130975aa4ddec2adf32
[ "Apache-2.0" ]
null
null
null
src/Test.hpp
Vasile2k/ImageSubjectFocus
0eed32df07b74eb89a1e1130975aa4ddec2adf32
[ "Apache-2.0" ]
null
null
null
#pragma once #include "ImageColor.hpp" namespace isf { /** * In order to perform the tests include this file somewhere in the project * This never gets executed but is evaluated at compile time * If everything is good it will do nothing * Else it will throw a compile-time error */ class Test { private: Test() = delete; bool testPacking() { static_assert(sizeof(isf::ImageU8Color) == 3, "Packing does not work correctly"); static_assert(sizeof(isf::ImageDoubleColor) == 3 * sizeof(double), "Packing does not work correctly"); } }; }
23.913043
104
0.72
Vasile2k
d1e26208e76d4e2bd62d6d94b39e4f05b8dbee32
500
hh
C++
src/const.hh
jroivas/nolang
761655bf851a978fb8426cc8f465e53cc86dec28
[ "MIT" ]
2
2021-04-13T20:16:04.000Z
2022-02-17T02:46:40.000Z
src/const.hh
jroivas/nolang
761655bf851a978fb8426cc8f465e53cc86dec28
[ "MIT" ]
null
null
null
src/const.hh
jroivas/nolang
761655bf851a978fb8426cc8f465e53cc86dec28
[ "MIT" ]
null
null
null
#pragma once #include "statement.hh" #include "assignment.hh" #include "typeident.hh" namespace nolang { class Const : public Statement { public: Const(TypeIdent *i, Assignment *v) : Statement("Const", ""), m_ident(i), m_assignment(v) {} const TypeIdent *ident() const { return m_ident; } const Assignment *assignment() const { return m_assignment; } protected: TypeIdent *m_ident; Assignment *m_assignment; }; }
14.705882
40
0.608
jroivas
d1e2fa5a6f899afe2a0fdfe5d080d379d34a43a8
375
cpp
C++
src/io/github/technicalnotes/programming/examples/3-even.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
src/io/github/technicalnotes/programming/examples/3-even.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
src/io/github/technicalnotes/programming/examples/3-even.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <numeric> using namespace std; int main() { vector<int> myVec(10); // initialize the vector with 1 to 10 sequence iota(begin(myVec), end(myVec), 1); for (auto i : myVec) { if (i % 2 == 0) { cout << i << " "; } } cout << endl; return 0; }
17.857143
51
0.477333
chiragbhatia94
d1e58215c9eb14c35c07f401f88efa685b16fd25
1,039
hpp
C++
src/Filesystem/File.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
src/Filesystem/File.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
src/Filesystem/File.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
/** * @file File.hpp * * @copyright Copyright (c) 2020 Innovatrics s.r.o. All rights reserved. * * @maintainer Tomas Krupa <tomas.krupa@innovatrics.com> * @created 10.08.2020 * */ #pragma once #include <fstream> #include <utility> #include <vector> class Path; /** * @brief File * * Defines basic file operations and attributes. */ template<class TDerived> class File { public: void open() { static_cast<TDerived*>(this)->open(); } void close() { static_cast<TDerived*>(this)->close(); } void write(const std::string& data) { static_cast<TDerived*>(this)->write(data); } std::vector<unsigned char> read() { return static_cast<TDerived*>(this)->read(); } bool isOpen() { return static_cast<TDerived*>(this)->isOpen(); } const Path& getPath() const noexcept { static_cast<TDerived*>(this)->getPath(); } virtual ~File() = default; File(const File&) = delete; File(File&&) = delete; File& operator=(const File&) = delete; File& operator=(File&&) = delete; protected: File() = default; };
19.980769
84
0.655438
tomas-krupa
d1e9946bba956b1a55af9c44e4b10e9978e5179a
1,045
cpp
C++
models/memory/CaffDRAM/Dreq.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
8
2016-01-22T18:28:48.000Z
2021-05-07T02:27:21.000Z
models/memory/CaffDRAM/Dreq.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
3
2016-04-15T02:58:58.000Z
2017-01-19T17:07:34.000Z
models/memory/CaffDRAM/Dreq.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
10
2015-12-11T04:16:55.000Z
2019-05-25T20:58:13.000Z
/* * Dreq.cpp * * Created on: Jun 14, 2011 * Author: rishirajbheda */ #include "Dreq.h" #include "math.h" namespace manifold { namespace caffdram { Dreq::Dreq(unsigned long int reqAddr, unsigned long int currentTime, const Dsettings* dramSetting) { // TODO Auto-generated constructor stub this->generateId(reqAddr, dramSetting); this->originTime = currentTime + dramSetting->t_CMD; this->endTime = currentTime + dramSetting->t_CMD; } Dreq::~Dreq() { // TODO Auto-generated destructor stub } void Dreq::generateId(unsigned long int reqAddr, const Dsettings* dramSetting) { this->rowId = (reqAddr>>(dramSetting->rowShiftBits))&(dramSetting->rowMask); this->bankId = (reqAddr>>(dramSetting->bankShiftBits))&(dramSetting->bankMask); this->rankId = (reqAddr>>(dramSetting->rankShiftBits))&(dramSetting->rankMask); if (dramSetting->numChannels == 1) { this->chId = 0; } else { this->chId = (reqAddr>>(dramSetting->channelShiftBits))%(dramSetting->numChannels); } } } //namespace caffdram } //namespace manifold
22.234043
100
0.711005
Basseuph
d1ea87a6fc86855cccec5e871f6ed3852b7b77c7
11,361
cc
C++
media_perception/proto_mojom_conversion.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
media_perception/proto_mojom_conversion.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
media_perception/proto_mojom_conversion.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2018 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 "media_perception/proto_mojom_conversion.h" #include <utility> #include <vector> namespace chromeos { namespace media_perception { namespace mojom { PixelFormat ToMojom(mri::PixelFormat format) { switch (format) { case mri::PixelFormat::I420: return PixelFormat::I420; case mri::PixelFormat::MJPEG: return PixelFormat::MJPEG; case mri::PixelFormat::FORMAT_UNKNOWN: return PixelFormat::FORMAT_UNKNOWN; } return PixelFormat::FORMAT_UNKNOWN; } VideoStreamParamsPtr ToMojom(const mri::VideoStreamParams& params) { VideoStreamParamsPtr params_ptr = VideoStreamParams::New(); params_ptr->width_in_pixels = params.width_in_pixels(); params_ptr->height_in_pixels = params.height_in_pixels(); params_ptr->frame_rate_in_frames_per_second = params.frame_rate_in_frames_per_second(); params_ptr->pixel_format = ToMojom(params.pixel_format()); return params_ptr; } VideoDevicePtr ToMojom(const mri::VideoDevice& device) { VideoDevicePtr device_ptr = VideoDevice::New(); device_ptr->id = device.id(); device_ptr->display_name = device.display_name(); device_ptr->model_id = device.model_id(); std::vector<VideoStreamParamsPtr> supported_configurations; for (const mri::VideoStreamParams& params : device.supported_configurations()) { supported_configurations.push_back(ToMojom(params)); } device_ptr->supported_configurations = std::move(supported_configurations); if (device.has_configuration()) { device_ptr->configuration = ToMojom(device.configuration()); } device_ptr->in_use = device.in_use(); return device_ptr; } VirtualVideoDevicePtr ToMojom(const mri::VirtualVideoDevice& device) { VirtualVideoDevicePtr device_ptr = VirtualVideoDevice::New(); if (device.has_video_device()) device_ptr->video_device = ToMojom(device.video_device()); return device_ptr; } AudioStreamParamsPtr ToMojom(const mri::AudioStreamParams& params) { AudioStreamParamsPtr params_ptr = AudioStreamParams::New(); params_ptr->frequency_in_hz = params.frequency_in_hz(); params_ptr->num_channels = params.num_channels(); return params_ptr; } AudioDevicePtr ToMojom(const mri::AudioDevice& device) { AudioDevicePtr device_ptr = AudioDevice::New(); device_ptr->id = device.id(); device_ptr->display_name = device.display_name(); std::vector<AudioStreamParamsPtr> supported_configurations; for (const mri::AudioStreamParams& params : device.supported_configurations()) { supported_configurations.push_back(ToMojom(params)); } device_ptr->supported_configurations = std::move(supported_configurations); if (device.has_configuration()) { device_ptr->configuration = ToMojom(device.configuration()); } return device_ptr; } DeviceType ToMojom(mri::DeviceType type) { switch (type) { case mri::DeviceType::VIDEO: return DeviceType::VIDEO; case mri::DeviceType::AUDIO: return DeviceType::AUDIO; case mri::DeviceType::VIRTUAL_VIDEO: return DeviceType::VIRTUAL_VIDEO; case mri::DeviceType::DEVICE_TYPE_UNKNOWN: return DeviceType::TYPE_UNKNOWN; } return DeviceType::TYPE_UNKNOWN; } DeviceTemplatePtr ToMojom(const mri::DeviceTemplate& device_template) { DeviceTemplatePtr template_ptr = DeviceTemplate::New(); template_ptr->template_name = device_template.template_name(); template_ptr->device_type = ToMojom(device_template.device_type()); return template_ptr; } PipelineStatus ToMojom(mri::PipelineStatus status) { switch (status) { case mri::PipelineStatus::STARTED: return PipelineStatus::STARTED; case mri::PipelineStatus::RUNNING: return PipelineStatus::RUNNING; case mri::PipelineStatus::SUSPENDED: return PipelineStatus::SUSPENDED; case mri::PipelineStatus::ERROR: return PipelineStatus::ERROR; case mri::PIPELINE_STATUS_UNKNOWN: return PipelineStatus::UNKNOWN; } return PipelineStatus::UNKNOWN; } PipelineErrorType ToMojom(mri::PipelineErrorType error_type) { switch (error_type) { case mri::PipelineErrorType::CONFIGURATION: return PipelineErrorType::CONFIGURATION; case mri::PipelineErrorType::STARTUP: return PipelineErrorType::STARTUP; case mri::PipelineErrorType::RUNTIME: return PipelineErrorType::RUNTIME; case mri::PipelineErrorType::CONTENT: return PipelineErrorType::CONTENT; case mri::PIPELINE_ERROR_TYPE_UNKNOWN: return PipelineErrorType::UNKNOWN; } return PipelineErrorType::UNKNOWN; } PipelineErrorPtr ToMojom(const mri::PipelineError& error) { PipelineErrorPtr error_ptr = PipelineError::New(); error_ptr->error_type = ToMojom(error.error_type()); error_ptr->error_source = error.error_source(); error_ptr->error_string = error.error_string(); return error_ptr; } PipelineStatePtr ToMojom(const mri::PipelineState& state) { PipelineStatePtr state_ptr = PipelineState::New(); state_ptr->status = ToMojom(state.status()); state_ptr->error = ToMojom(state.error()); return state_ptr; } } // namespace mojom } // namespace media_perception } // namespace chromeos namespace mri { PixelFormat ToProto( chromeos::media_perception::mojom::PixelFormat format) { switch (format) { case chromeos::media_perception::mojom::PixelFormat::I420: return PixelFormat::I420; case chromeos::media_perception::mojom::PixelFormat::MJPEG: return PixelFormat::MJPEG; case chromeos::media_perception::mojom::PixelFormat::FORMAT_UNKNOWN: return PixelFormat::FORMAT_UNKNOWN; } return PixelFormat::FORMAT_UNKNOWN; } VideoStreamParams ToProto( const chromeos::media_perception::mojom::VideoStreamParamsPtr& params_ptr) { VideoStreamParams params; if (params_ptr.is_null()) return params; params.set_width_in_pixels(params_ptr->width_in_pixels); params.set_height_in_pixels(params_ptr->height_in_pixels); params.set_frame_rate_in_frames_per_second( params_ptr->frame_rate_in_frames_per_second); params.set_pixel_format( ToProto(params_ptr->pixel_format)); return params; } VideoDevice ToProto( const chromeos::media_perception::mojom::VideoDevicePtr& device_ptr) { VideoDevice device; if (device_ptr.is_null()) return device; device.set_id(device_ptr->id); device.set_display_name(*device_ptr->display_name); device.set_model_id(*device_ptr->model_id); for (int i = 0; i < device_ptr->supported_configurations.size(); i++) { mri::VideoStreamParams* params = device.add_supported_configurations(); *params = ToProto(device_ptr->supported_configurations[i]); } if (!device_ptr->configuration.is_null()) { mri::VideoStreamParams* params = device.mutable_configuration(); *params = ToProto(device_ptr->configuration); } device.set_in_use(device_ptr->in_use); return device; } VirtualVideoDevice ToProto( const chromeos::media_perception::mojom::VirtualVideoDevicePtr& device_ptr) { VirtualVideoDevice device; if (device_ptr.is_null()) return device; VideoDevice* video_device = device.mutable_video_device(); *video_device = ToProto(device_ptr->video_device); return device; } AudioStreamParams ToProto( const chromeos::media_perception::mojom::AudioStreamParamsPtr& params_ptr) { AudioStreamParams params; if (params_ptr.is_null()) return params; params.set_frequency_in_hz(params_ptr->frequency_in_hz); params.set_num_channels(params_ptr->num_channels); return params; } AudioDevice ToProto( const chromeos::media_perception::mojom::AudioDevicePtr& device_ptr) { AudioDevice device; if (device_ptr.is_null()) return device; device.set_id(device_ptr->id); device.set_display_name(*device_ptr->display_name); for (int i = 0; i < device_ptr->supported_configurations.size(); i++) { mri::AudioStreamParams* params = device.add_supported_configurations(); *params = ToProto(device_ptr->supported_configurations[i]); } if (!device_ptr->configuration.is_null()) { mri::AudioStreamParams* params = device.mutable_configuration(); *params = ToProto(device_ptr->configuration); } return device; } DeviceType ToProto( const chromeos::media_perception::mojom::DeviceType type) { switch (type) { case chromeos::media_perception::mojom::DeviceType::VIDEO: return DeviceType::VIDEO; case chromeos::media_perception::mojom::DeviceType::AUDIO: return DeviceType::AUDIO; case chromeos::media_perception::mojom::DeviceType::VIRTUAL_VIDEO: return DeviceType::VIRTUAL_VIDEO; case chromeos::media_perception::mojom::DeviceType::TYPE_UNKNOWN: return DeviceType::DEVICE_TYPE_UNKNOWN; } return DeviceType::DEVICE_TYPE_UNKNOWN; } DeviceTemplate ToProto( const chromeos::media_perception::mojom::DeviceTemplatePtr& template_ptr) { DeviceTemplate device_template; if (template_ptr.is_null()) return device_template; device_template.set_template_name(template_ptr->template_name); device_template.set_device_type(ToProto(template_ptr->device_type)); return device_template; } PipelineStatus ToProto( chromeos::media_perception::mojom::PipelineStatus status) { switch (status) { case chromeos::media_perception::mojom::PipelineStatus::STARTED: return PipelineStatus::STARTED; case chromeos::media_perception::mojom::PipelineStatus::RUNNING: return PipelineStatus::RUNNING; case chromeos::media_perception::mojom::PipelineStatus::SUSPENDED: return PipelineStatus::SUSPENDED; case chromeos::media_perception::mojom::PipelineStatus::ERROR: return PipelineStatus::ERROR; case chromeos::media_perception::mojom::PipelineStatus::UNKNOWN: return PipelineStatus::PIPELINE_STATUS_UNKNOWN; } return PipelineStatus::PIPELINE_STATUS_UNKNOWN; } PipelineErrorType ToProto( chromeos::media_perception::mojom::PipelineErrorType error_type) { switch (error_type) { case chromeos::media_perception::mojom::PipelineErrorType::CONFIGURATION: return PipelineErrorType::CONFIGURATION; case chromeos::media_perception::mojom::PipelineErrorType::STARTUP: return PipelineErrorType::STARTUP; case chromeos::media_perception::mojom::PipelineErrorType::RUNTIME: return PipelineErrorType::RUNTIME; case chromeos::media_perception::mojom::PipelineErrorType::CONTENT: return PipelineErrorType::CONTENT; case chromeos::media_perception::mojom::PipelineErrorType::UNKNOWN: return PipelineErrorType::PIPELINE_ERROR_TYPE_UNKNOWN; } return PipelineErrorType::PIPELINE_ERROR_TYPE_UNKNOWN; } PipelineError ToProto( const chromeos::media_perception::mojom::PipelineErrorPtr& error_ptr) { PipelineError error; if (error_ptr.is_null()) return error; error.set_error_type(ToProto(error_ptr->error_type)); error.set_error_source(*error_ptr->error_source); error.set_error_string(*error_ptr->error_string); return error; } PipelineState ToProto( const chromeos::media_perception::mojom::PipelineStatePtr& state_ptr) { PipelineState state; if (state_ptr.is_null()) return state; state.set_status(ToProto(state_ptr->status)); *state.mutable_error() = ToProto(state_ptr->error); return state; } } // namespace mri
34.323263
80
0.756447
emersion
d1edac4c6a6e1a90c456b39611001a5b349c568f
3,710
cpp
C++
waveform2csv.cpp
Iaggelis/waveform_playground
363746500a0ee0b9dc45bc2d7a5b1623001d523b
[ "MIT" ]
null
null
null
waveform2csv.cpp
Iaggelis/waveform_playground
363746500a0ee0b9dc45bc2d7a5b1623001d523b
[ "MIT" ]
null
null
null
waveform2csv.cpp
Iaggelis/waveform_playground
363746500a0ee0b9dc45bc2d7a5b1623001d523b
[ "MIT" ]
null
null
null
#include "pft.hpp" #include <ROOT/RDataFrame.hxx> #include <TMath.h> #include <filesystem> using RDF = ROOT::RDataFrame; namespace fs = std::filesystem; template <typename... Types> void print_log(FILE* stream, Types... args) { pft::println(stream, "[LOG] ", args...); } void print_usage() { pft::println(stderr, "waveform2csv usage:"); pft::println(stderr, "If [mode] = 1, save each event in a separate " "file"); pft::println(stderr, "If [mode] = -a, save all the events in a file"); pft::println(stderr, "By default save all the events unless a separate file " "is given with the id of events to be saved."); pft::println(stderr, "./wave2csv [mode] [filename.root]"); pft::println(stderr, "./wave2csv [mode] [filename.root] [events-to-save.txt]"); } void print_time_vec(FILE* stream, const Vec<f64>& times) { fprintf(stream, " %zu", times.size()); for (auto&& t : times) { fprintf(stream, " %f", t); } } auto main(i32 argc, c8* argv[]) -> i32 { if (argc < 3) { print_usage(); pft::panic("Wrong Arguments Given"); } auto mode = 0; RDF df("t", argv[2]); auto df_aux = df.Define("xs", [](TGraph& graph) { auto points = graph.GetX(); const auto n = graph.GetN(); return Vec<f64>(points, points + n); }, {"Waveform"}) .Define("ys", [](TGraph& graph) { auto points = graph.GetY(); const auto n = graph.GetN(); return Vec<f64>(points, points + n); }, {"Waveform"}); const auto starting_time = df_aux.Take<Vec<f64>>("LightSource_time").GetValue(); const auto xs = df_aux.Take<Vec<f64>>("xs").GetValue(); const auto ys = df_aux.Take<Vec<f64>>("ys").GetValue(); pft::StringView output_filename; auto events_to_save = Vec<i32>(); if (argc == 3) { events_to_save = pft::arange<i32>(0, xs.size()); } else if (argc == 4) { pft::println(stdout, "asdf", argv[1]); if (!strcmp(argv[1], "-a")) { output_filename = argv[3]; events_to_save = pft::arange<i32>(0, xs.size()); } else { mode = pft::to_i32(argv[1]); events_to_save = pft::map(pft::to_i32, pft::readlines(argv[3])); } } else { pft::panic("THE HECK DUDE?"); } const auto folder_name = "tmp_wf"; print_log(stdout, "Creating folder: ", folder_name); fs::create_directory(folder_name); const fs::path p1 = folder_name; fs::current_path(p1); FILE* fp = nullptr; if (mode == 1) { for (const auto& event : events_to_save) { const std::string filename = "waveform_" + std::to_string(event) + ".txt"; pft::println(stdout, "Saving event: ", event); fp = fopen(filename.data(), "w"); for (const auto& [x, y] : pft::zip_to_pair(xs[event], ys[event])) { fprintf(fp, "%f %f\n", x, y); } fclose(fp); } } else { // const std::string filename = output_filename; print_log(stdout, "Writing to file: ", output_filename); fp = fopen(output_filename.data(), "w"); for (const auto& event : events_to_save) { print_log(stdout, "Saving event: ", event); fprintf(fp, "%d %zu", event, xs[event].size()); print_time_vec(fp, starting_time[event]); fprintf(fp, "\n"); for (const auto& [x, y] : pft::zip_to_pair(xs[event], ys[event])) { fprintf(fp, "%f %f\n", x, y); } } fclose(fp); } return 0; }
31.440678
80
0.536388
Iaggelis
d1f3be2f98486c2cc6ab4f353a2938953e2c009b
6,293
cpp
C++
tests/network/ipv6_address_tests.cpp
miraiworks/url
515c6d3f27cabe9fdb6718da82927c3f019d899c
[ "BSL-1.0" ]
null
null
null
tests/network/ipv6_address_tests.cpp
miraiworks/url
515c6d3f27cabe9fdb6718da82927c3f019d899c
[ "BSL-1.0" ]
null
null
null
tests/network/ipv6_address_tests.cpp
miraiworks/url
515c6d3f27cabe9fdb6718da82927c3f019d899c
[ "BSL-1.0" ]
null
null
null
// Copyright 2018-20 Glyn Matthews. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt of copy at // http://www.boost.org/LICENSE_1_0.txt) #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <skyr/network/ipv6_address.hpp> TEST_CASE("ipv6_address_tests", "[ipv6]") { using namespace std::string_literals; SECTION("zero_test") { auto address = std::array<unsigned short, 8>{{0, 0, 0, 0, 0, 0, 0, 0}}; auto instance = skyr::ipv6_address(address); CHECK("::" == instance.serialize()); } SECTION("loopback_test") { auto address = std::array<unsigned short, 8>{{0, 0, 0, 0, 0, 0, 0, 1}}; auto instance = skyr::ipv6_address(address); CHECK("::1" == instance.serialize()); } SECTION("ipv6_address_test_1") { const auto address = "1080:0:0:0:8:800:200C:417A"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("1080::8:800:200c:417a" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_2") { const auto address = "2001:db8:85a3:8d3:1319:8a2e:370:7348"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8:85a3:8d3:1319:8a2e:370:7348" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_3") { const auto address = "2001:db8:85a3:0:0:8a2e:370:7334"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8:85a3::8a2e:370:7334" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_4") { const auto address = "2001:db8:85a3::8a2e:370:7334"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8:85a3::8a2e:370:7334" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_5") { const auto address = "2001:0db8:0000:0000:0000:0000:1428:57ab"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8::1428:57ab" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_6") { const auto address = "2001:0db8:0000:0000:0000::1428:57ab"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8::1428:57ab" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_7") { const auto address = "2001:0db8:0:0:0:0:1428:57ab"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8::1428:57ab" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_8") { const auto address = "2001:0db8:0:0::1428:57ab"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8::1428:57ab" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_9") { const auto address = "2001:0db8::1428:57ab"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8::1428:57ab" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_10") { const auto address = "2001:db8::1428:57ab"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("2001:db8::1428:57ab" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_11") { const auto address = "::ffff:0c22:384e"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("::ffff:c22:384e" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_12") { const auto address = "fe80::"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("fe80::" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_address_test_13") { const auto address = "::ffff:c000:280"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("::ffff:c000:280" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_loopback_test_1") { const auto address = "0000:0000:0000:0000:0000:0000:0000:0001"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("::1" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_v4inv6_test_1") { const auto address = "::ffff:12.34.56.78"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("::ffff:c22:384e" == instance.value().serialize()); CHECK(!validation_error); } SECTION("ipv6_v4inv6_test_2") { const auto address = "::ffff:192.0.2.128"s; bool validation_error = false; auto instance = skyr::parse_ipv6_address(address, &validation_error); REQUIRE(instance); CHECK("::ffff:c000:280" == instance.value().serialize()); CHECK(!validation_error); } SECTION("loopback_test") { auto address = std::array<unsigned short, 8>{{0, 0, 0, 0, 0, 0, 0, 1}}; auto instance = skyr::ipv6_address(address); std::array<unsigned char, 16> bytes{ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }}; CHECK(bytes == instance.to_bytes()); } }
35.156425
82
0.679485
miraiworks
d1f9414360261e1bb63dff5e5f754a818d210ece
1,562
cpp
C++
Find_pivot_index.cpp
Sonu589/Hacktoberfest-2025
06397aa12a41967cb112722666e384007d87dbc4
[ "MIT" ]
1
2021-10-04T07:14:40.000Z
2021-10-04T07:14:40.000Z
Find_pivot_index.cpp
Sonu589/Hacktoberfest-2025
06397aa12a41967cb112722666e384007d87dbc4
[ "MIT" ]
11
2022-01-24T20:42:11.000Z
2022-02-27T23:58:24.000Z
Find_pivot_index.cpp
Sonu589/Hacktoberfest-2025
06397aa12a41967cb112722666e384007d87dbc4
[ "MIT" ]
1
2021-10-05T04:40:26.000Z
2021-10-05T04:40:26.000Z
#include<bits/stdc++.h> #define ps(x, y) fixed << setprecision(y) << x #define BOOST ios_base::sync_with_stdio(false); cin.tie(NULL); #define vi vector<int> #define pb push_back #define pob pop_back #define f first #define s second #define all(x) (x).begin(),(x).end() #define mp make_pair #define rall(v) v.rbegin(), v.rend() #define next next_permutation #define perv prev_permutation #define lb lower_bound #define ub upper_bound #define bs binary_search #define setbit(x) __builtin_popcount(x) #define w(t) while (t--) #define pq priority_queue #define FOR(i,a,b) for ( i = (a); i < (b); ++i) #define FORN(i,a) FOR(i,0,a) #define ROF(i,a,b) for ( i = (b)-1; i >= (a); --i) #define ROFN(i,a) ROF(i,0,a) #define trav(a,x) for (auto& a: x) using namespace std; #define int long long int inf = 1000000005; int mod = 1000000007; int32_t main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("outputt.txt", "w", stdout); #endif int n; //size of array cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; vector<int>pre(n),suf(n); for(int i=0;i<n;i++) cin>>a[i]; pre[0]=a[0]; suf[n-1]=a[n-1]; for(int i=1;i<n;i++) pre[i]=pre[i-1]+a[i]; for(int i=n-2;i>=0;i--) suf[i]=suf[i+1]+a[i]; int ans=-1; for(int i=1;i<n-1;i++){ if(pre[i-1]==suf[i+1]) { ans=i; break; } } if(ans==-1) cout<<"Pivot index not found"; else cout<<ans<<endl; return 0; } /*Time complexity calculating suffix and prefix sums takes o(n) and then calculating pivot index also taking o(n) hence the overall complexity is O(n) */
21.108108
132
0.636364
Sonu589
d1fbe1ce96c03f1bf73fcda3db546b6e4f91947a
889
cpp
C++
leetcode.com/0650 2 Keys Keyboard/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0650 2 Keys Keyboard/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0650 2 Keys Keyboard/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; // key is know how to prune // no, 1000*1000 dp, no need to prune? class Solution { private: int dfs(int n, int cur_n, int clip_len, vector<vector<int>>& dp) { if (n == cur_n) return 0; if (~dp[clip_len][cur_n]) return dp[clip_len][cur_n]; int res = -2; if (cur_n * 2 <= n) { // copy + paste res = dfs(n, cur_n * 2, cur_n, dp); if (res != -2) res += 2; } if (cur_n + clip_len <= n) { // paste int tmp = dfs(n, cur_n + clip_len, clip_len, dp); if (tmp != -2) { if (res == -2 || tmp + 1 < res) res = tmp + 1; } } return dp[clip_len][cur_n] = res; } public: int minSteps(int n) { if (n == 1) return 0; vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1)); // already copied + pasted once return 2 + dfs(n, 2, 1, dp); } };
24.694444
68
0.526434
sky-bro
d1fd6d3f89f18b58f12ed9b004c44644edaee289
12,127
hpp
C++
SDK/PUBG_WeaponAttachmentSlotWidget_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_WeaponAttachmentSlotWidget_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_WeaponAttachmentSlotWidget_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
#pragma once // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_WeaponAttachmentSlotWidget_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotItem struct UWeaponAttachmentSlotWidget_C_GetSlotItem_Params { TScriptInterface<class USlotInterface> SlotItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotContainer struct UWeaponAttachmentSlotWidget_C_GetSlotContainer_Params { TScriptInterface<class USlotContainerInterface> SlotContainer; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.CheckFirstAttachableSlot struct UWeaponAttachmentSlotWidget_C_CheckFirstAttachableSlot_Params { bool bAttachable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.CheckAttachableByFocusSlot struct UWeaponAttachmentSlotWidget_C_CheckAttachableByFocusSlot_Params { bool bAttachable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.InputB struct UWeaponAttachmentSlotWidget_C_InputB_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.InputA struct UWeaponAttachmentSlotWidget_C_InputA_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.SetFocus struct UWeaponAttachmentSlotWidget_C_SetFocus_Params { bool* NewFocus; // (Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDrop struct UWeaponAttachmentSlotWidget_C_OnDrop_Params { struct FGeometry* MyGeometry; // (Parm, IsPlainOldData) struct FPointerEvent* PointerEvent; // (Parm) class UDragDropOperation** Operation; // (Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetOptoins struct UWeaponAttachmentSlotWidget_C_GetOptoins_Params { class FString Options; // (Parm, OutParm, ZeroConstructor) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetDragDroppingAttachableItem struct UWeaponAttachmentSlotWidget_C_GetDragDroppingAttachableItem_Params { class UAttachableItem* DragDroppingAttachableItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnPrepass_2 struct UWeaponAttachmentSlotWidget_C_OnPrepass_2_Params { class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.On_AttachmentIcon_Prepass_1 struct UWeaponAttachmentSlotWidget_C_On_AttachmentIcon_Prepass_1_Params { class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsSlotMouseOver_Bp struct UWeaponAttachmentSlotWidget_C_IsSlotMouseOver_Bp_Params { bool IsMouseOver; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnPrepass_1 struct UWeaponAttachmentSlotWidget_C_OnPrepass_1_Params { class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetItem_Bp struct UWeaponAttachmentSlotWidget_C_GetItem_Bp_Params { class UItem* Item; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsSlotSubOn_Bp struct UWeaponAttachmentSlotWidget_C_IsSlotSubOn_Bp_Params { bool SubOn; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsSlotOn_Bp struct UWeaponAttachmentSlotWidget_C_IsSlotOn_Bp_Params { bool IsOn; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsOhterSlotMouseOver struct UWeaponAttachmentSlotWidget_C_IsOhterSlotMouseOver_Params { bool IsOver; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsAttachable struct UWeaponAttachmentSlotWidget_C_IsAttachable_Params { bool IsAttachable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetAttachmentItem struct UWeaponAttachmentSlotWidget_C_GetAttachmentItem_Params { class UAttachableItem* AttachmentItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.HasAttachmentSlot struct UWeaponAttachmentSlotWidget_C_HasAttachmentSlot_Params { bool HasAttachmentSlot; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.MainPrepass_1 struct UWeaponAttachmentSlotWidget_C_MainPrepass_1_Params { class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDragDetected struct UWeaponAttachmentSlotWidget_C_OnDragDetected_Params { struct FGeometry* MyGeometry; // (Parm, IsPlainOldData) struct FPointerEvent* PointerEvent; // (ConstParm, Parm, OutParm, ReferenceParm) class UDragDropOperation* Operation; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnMouseButtonDown struct UWeaponAttachmentSlotWidget_C_OnMouseButtonDown_Params { struct FGeometry* MyGeometry; // (Parm, IsPlainOldData) struct FPointerEvent* MouseEvent; // (ConstParm, Parm, OutParm, ReferenceParm) struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotVisibility struct UWeaponAttachmentSlotWidget_C_GetSlotVisibility_Params { ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotIcon struct UWeaponAttachmentSlotWidget_C_GetSlotIcon_Params { struct FSlateBrush ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetAttachmentNameText struct UWeaponAttachmentSlotWidget_C_GetAttachmentNameText_Params { struct FText ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDragEnter struct UWeaponAttachmentSlotWidget_C_OnDragEnter_Params { struct FGeometry* MyGeometry; // (Parm, IsPlainOldData) struct FPointerEvent* PointerEvent; // (Parm) class UDragDropOperation** Operation; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDragLeave struct UWeaponAttachmentSlotWidget_C_OnDragLeave_Params { struct FPointerEvent* PointerEvent; // (Parm) class UDragDropOperation** Operation; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnMouseEnter struct UWeaponAttachmentSlotWidget_C_OnMouseEnter_Params { struct FGeometry* MyGeometry; // (Parm, IsPlainOldData) struct FPointerEvent* MouseEvent; // (ConstParm, Parm, OutParm, ReferenceParm) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnMouseLeave struct UWeaponAttachmentSlotWidget_C_OnMouseLeave_Params { struct FPointerEvent* MouseEvent; // (ConstParm, Parm, OutParm, ReferenceParm) }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.Construct struct UWeaponAttachmentSlotWidget_C_Construct_Params { }; // Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.ExecuteUbergraph_WeaponAttachmentSlotWidget struct UWeaponAttachmentSlotWidget_C_ExecuteUbergraph_WeaponAttachmentSlotWidget_Params { int* EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
52.497835
173
0.590336
realrespecter
d1fe62e2430daf2ace41b847550a606aa673bf88
862
cpp
C++
benchmarks/Bloat/Bloat.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
benchmarks/Bloat/Bloat.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
benchmarks/Bloat/Bloat.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include <Core/Core.h> #include <vector> #include <map> using namespace Upp; using namespace std; //#define TEST_STL //#define TEST_UPP struct Foo : Moveable<Foo> { int a, b; Foo(int a, int b) : a(a), b(b) {} Foo() {} }; CONSOLE_APP_MAIN { { std::string key = "key"; vector<int> fa; fa.push_back(10); map<string, int> fb; fb[key] = 10; #ifdef TEST_STL vector<Foo> x; x.push_back(Foo(1, 2)); map<int, Foo> map1; map1[20].a = 10; map<std::string, Foo> map2; map2[key].a = 10; #endif } { String key = "key"; Vector<int> fa; fa.Add(10); VectorMap<String, int> fb; fb.GetAdd(key) = 10; #ifdef TEST_UPP Vector<Foo> x; x.Add(Foo(1, 2)); VectorMap<int, Foo> map1; map1.GetAdd(20).a = 10; VectorMap<String, Foo> map2; map2.GetAdd(key).a = 10; #endif } }
15.672727
35
0.563805
dreamsxin
d1feafac92a68a86e577cf6feb72a128b38daeca
702
hpp
C++
soapy/src/driver/CustomEventTypes.hpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
soapy/src/driver/CustomEventTypes.hpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
soapy/src/driver/CustomEventTypes.hpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
#pragma once #define NOOP_EV (0) #define REQUEST_FINE_SYNC_EV (1) #define RADIO_ENTERED_BG_EV (2) #define REQUEST_TDMA_EV (3) #define FINISHED_TDMA_EV (4) #define UDP_SEQUENCE_DROP_EV (5) #define REQUEST_MAPMOV_DEBUG (6) #define FSM_PING_EV (7) #define FSM_PONG_EV (8) #define EXIT_DATA_MODE_EV (9) #define CHECK_TDMA_EV (10) #define DUPLEX_FINE_SYNC (11) /// List all custom event types here /// NOTE if you are adding a new event type, please be aware /// that RadioEstimate and EventDspFsm FILTER and DROP events by default /// see : /// - RadioEstimate::handleCustomEvent /// - EventDsp::handleCustomEventRx /// - EventDsp::handleCustomEventTx #define MAKE_EVENT(x,y) (custom_event_t){(x),(y)}
27
72
0.757835
siglabsoss
06005216a53a429e6deabb7ea0a7de2f3c21ec9d
12,374
cpp
C++
src/sound/k054539.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
33
2015-08-10T11:13:47.000Z
2021-08-30T10:00:46.000Z
src/sound/k054539.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
13
2015-08-25T03:53:08.000Z
2022-03-30T18:02:35.000Z
src/sound/k054539.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
40
2015-08-25T05:09:21.000Z
2022-02-08T05:02:30.000Z
/********************************************************* Konami 054539 PCM Sound Chip A lot of information comes from Amuse. Big thanks to them. *********************************************************/ #include "driver.h" #include "k054539.h" #include <math.h> /* Registers: 00..ff: 20 bytes/channel, 8 channels 00..02: pitch (lsb, mid, msb) 03: volume (0=max, 0x40=-36dB) 04: 05: pan (1-f right, 10 middle, 11-1f left) 06: 07: 08..0a: loop (lsb, mid, msb) 0c..0e: start (lsb, mid, msb) (and current position ?) 100.1ff: effects? 13f: pan of the analog input (1-1f) 200..20f: 2 bytes/channel, 8 channels 00: type (b2-3), reverse (b5) 01: loop (b0) 214: keyon (b0-7 = channel 0-7) 215: keyoff "" 22c: channel active? "" 22d: data read/write port 22e: rom/ram select (00..7f == rom banks, 80 = ram) 22f: enable pcm (b0), disable registers updating (b7) */ #define MAX_K054539 2 struct K054539_channel { UINT32 pos; UINT32 pfrac; INT32 val; INT32 pval; }; struct K054539_chip { unsigned char regs[0x230]; unsigned char *ram; int cur_ptr; int cur_limit; unsigned char *cur_zone; void *timer; unsigned char *rom; UINT32 rom_size; UINT32 rom_mask; int stream; struct K054539_channel channels[8]; }; static struct { const struct K054539interface *intf; double freq_ratio; double voltab[256]; double pantab[0xf]; struct K054539_chip chip[MAX_K054539]; } K054539_chips; static int K054539_regupdate(int chip) { return !(K054539_chips.chip[chip].regs[0x22f] & 0x80); } static void K054539_keyon(int chip, int channel) { if(K054539_regupdate(chip)) K054539_chips.chip[chip].regs[0x22c] |= 1 << channel; } static void K054539_keyoff(int chip, int channel) { if(K054539_regupdate(chip)) K054539_chips.chip[chip].regs[0x22c] &= ~(1 << channel); } static void K054539_update(int chip, INT16 **buffer, int length) { static INT16 dpcm[16] = { 0<<8, 1<<8, 4<<8, 9<<8, 16<<8, 25<<8, 36<<8, 49<<8, -64<<8, -49<<8, -36<<8, -25<<8, -16<<8, -9<<8, -4<<8, -1<<8 }; int ch; unsigned char *samples; UINT32 rom_mask; if(!Machine->sample_rate) return; memset(buffer[0], 0, length*2); memset(buffer[1], 0, length*2); if(!(K054539_chips.chip[chip].regs[0x22f] & 1)) return; samples = K054539_chips.chip[chip].rom; rom_mask = K054539_chips.chip[chip].rom_mask; for(ch=0; ch<8; ch++) if(K054539_chips.chip[chip].regs[0x22c] & (1<<ch)) { unsigned char *base1 = K054539_chips.chip[chip].regs + 0x20*ch; unsigned char *base2 = K054539_chips.chip[chip].regs + 0x200 + 0x2*ch; struct K054539_channel *chan = (struct K054539_channel*)K054539_chips.chip[chip].channels + ch; INT16 *bufl = buffer[0]; INT16 *bufr = buffer[1]; UINT32 cur_pos = (base1[0x0c] | (base1[0x0d] << 8) | (base1[0x0e] << 16)) & rom_mask; INT32 cur_pfrac; INT32 cur_val, cur_pval, rval; INT32 delta = (base1[0x00] | (base1[0x01] << 8) | (base1[0x02] << 16)) * K054539_chips.freq_ratio; INT32 fdelta; int pdelta; int pan = base1[0x05] >= 0x11 && base1[0x05] <= 0x1f ? base1[0x05] - 0x11 : 0x18 - 0x11; int vol = base1[0x03] & 0x7f; double lvol = K054539_chips.voltab[vol] * K054539_chips.pantab[pan]; double rvol = K054539_chips.voltab[vol] * K054539_chips.pantab[0xe - pan]; if(base2[0] & 0x20) { delta = -delta; fdelta = +0x10000; pdelta = -1; } else { fdelta = -0x10000; pdelta = +1; } if(cur_pos != chan->pos) { chan->pos = cur_pos; cur_pfrac = 0; cur_val = 0; cur_pval = 0; } else { cur_pfrac = chan->pfrac; cur_val = chan->val; cur_pval = chan->pval; } #define UPDATE_CHANNELS \ do { \ rval = (cur_pval*cur_pfrac + cur_val*(0x10000 - cur_pfrac)) >> 16; \ *bufl++ += (INT16)(rval*lvol); \ *bufr++ += (INT16)(rval*rvol); \ } while(0) switch(base2[0] & 0xc) { case 0x0: { // 8bit pcm int i; for(i=0; i<length; i++) { cur_pfrac += delta; while(cur_pfrac & ~0xffff) { cur_pfrac += fdelta; cur_pos += pdelta; cur_pval = cur_val; cur_val = (INT16)(samples[cur_pos] << 8); if(cur_val == (INT16)0x8000) { if(base2[1] & 1) { cur_pos = (base1[0x08] | (base1[0x09] << 8) | (base1[0x0a] << 16)) & rom_mask; cur_val = (INT16)(samples[cur_pos] << 8); if(cur_val != (INT16)0x8000) continue; } K054539_keyoff(chip, ch); goto end_channel_0; } } UPDATE_CHANNELS; } end_channel_0: break; } case 0x4: { // 16bit pcm lsb first int i; cur_pos >>= 1; for(i=0; i<length; i++) { cur_pfrac += delta; while(cur_pfrac & ~0xffff) { cur_pfrac += fdelta; cur_pos += pdelta; cur_pval = cur_val; cur_val = (INT16)(samples[cur_pos<<1] | samples[(cur_pos<<1)|1]<<8); if(cur_val == (INT16)0x8000) { if(base2[1] & 1) { cur_pos = ((base1[0x08] | (base1[0x09] << 8) | (base1[0x0a] << 16)) & rom_mask) >> 1; cur_val = (INT16)(samples[cur_pos<<1] | samples[(cur_pos<<1)|1]<<8); if(cur_val != (INT16)0x8000) continue; } K054539_keyoff(chip, ch); goto end_channel_4; } } UPDATE_CHANNELS; } end_channel_4: cur_pos <<= 1; break; } case 0x8: { // 4bit dpcm int i; cur_pos <<= 1; cur_pfrac <<= 1; if(cur_pfrac & 0x10000) { cur_pfrac &= 0xffff; cur_pos |= 1; } for(i=0; i<length; i++) { cur_pfrac += delta; while(cur_pfrac & ~0xffff) { cur_pfrac += fdelta; cur_pos += pdelta; cur_pval = cur_val; cur_val = samples[cur_pos>>1]; if(cur_val == 0x88) { if(base2[1] & 1) { cur_pos = ((base1[0x08] | (base1[0x09] << 8) | (base1[0x0a] << 16)) & rom_mask) << 1; cur_val = samples[cur_pos>>1]; if(cur_val != 0x88) goto next_iter; } K054539_keyoff(chip, ch); goto end_channel_8; } next_iter: if(cur_pos & 1) cur_val >>= 4; else cur_val &= 15; cur_val = cur_pval + dpcm[cur_val]; if(cur_val < -32768) cur_val = -32768; else if(cur_val > 32767) cur_val = 32767; } UPDATE_CHANNELS; } end_channel_8: cur_pfrac >>= 1; if(cur_pos & 1) cur_pfrac |= 0x8000; cur_pos >>= 1; break; } default: logerror("Unknown sample type %x for channel %d\n", base2[0] & 0xc, ch); break; } chan->pos = cur_pos; chan->pfrac = cur_pfrac; chan->pval = cur_pval; chan->val = cur_val; if(K054539_regupdate(chip)) { base1[0x0c] = cur_pos & 0xff; base1[0x0d] = (cur_pos >> 8) & 0xff; base1[0x0e] = (cur_pos >> 16) & 0xff; } } } static void K054539_irq(int chip) { if(K054539_chips.chip[chip].regs[0x22f] & 0x20) K054539_chips.intf->irq[chip] (); } static void K054539_init_chip(int chip, const struct MachineSound *msound) { char buf[2][50]; const char *bufp[2]; int vol[2]; int i; memset(K054539_chips.chip[chip].regs, 0, sizeof(K054539_chips.chip[chip].regs)); K054539_chips.chip[chip].ram = (unsigned char *)malloc(0x4000); K054539_chips.chip[chip].cur_ptr = 0; K054539_chips.chip[chip].rom = memory_region(K054539_chips.intf->region[chip]); K054539_chips.chip[chip].rom_size = memory_region_length(K054539_chips.intf->region[chip]); K054539_chips.chip[chip].rom_mask = 0xffffffffU; for(i=0; i<32; i++) if((1U<<i) >= K054539_chips.chip[chip].rom_size) { K054539_chips.chip[chip].rom_mask = (1U<<i) - 1; break; } if(K054539_chips.intf->irq[chip]) // One or more of the registers must be the timer period // And anyway, this particular frequency is probably wrong K054539_chips.chip[chip].timer = timer_pulse(TIME_IN_HZ(500), 0, K054539_irq); else K054539_chips.chip[chip].timer = 0; sprintf(buf[0], "%s.%d L", sound_name(msound), chip); sprintf(buf[1], "%s.%d R", sound_name(msound), chip); bufp[0] = buf[0]; bufp[1] = buf[1]; vol[0] = MIXER(K054539_chips.intf->mixing_level[chip][0], MIXER_PAN_LEFT); vol[1] = MIXER(K054539_chips.intf->mixing_level[chip][1], MIXER_PAN_RIGHT); K054539_chips.chip[chip].stream = stream_init_multi(2, bufp, vol, Machine->sample_rate, chip, K054539_update); } static void K054539_stop_chip(int chip) { free(K054539_chips.chip[chip].ram); if (K054539_chips.chip[chip].timer) timer_remove(K054539_chips.chip[chip].timer); } static void K054539_w(int chip, offs_t offset, data8_t data) { data8_t old = K054539_chips.chip[chip].regs[offset]; K054539_chips.chip[chip].regs[offset] = data; switch(offset) { case 0x13f: { int pan = data >= 0x11 && data <= 0x1f ? data - 0x11 : 0x18 - 0x11; if(K054539_chips.intf->apan[chip]) K054539_chips.intf->apan[chip](K054539_chips.pantab[pan], K054539_chips.pantab[0xe - pan]); break; } case 0x214: { int ch; for(ch=0; ch<8; ch++) if(data & (1<<ch)) K054539_keyon(chip, ch); break; } case 0x215: { int ch; for(ch=0; ch<8; ch++) if(data & (1<<ch)) K054539_keyoff(chip, ch); break; } case 0x22d: if(K054539_chips.chip[chip].regs[0x22e] == 0x80) K054539_chips.chip[chip].cur_zone[K054539_chips.chip[chip].cur_ptr] = data; K054539_chips.chip[chip].cur_ptr++; if(K054539_chips.chip[chip].cur_ptr == K054539_chips.chip[chip].cur_limit) K054539_chips.chip[chip].cur_ptr = 0; break; case 0x22e: K054539_chips.chip[chip].cur_zone = data == 0x80 ? K054539_chips.chip[chip].ram : K054539_chips.chip[chip].rom + 0x20000*data; K054539_chips.chip[chip].cur_limit = data == 0x80 ? 0x4000 : 0x20000; K054539_chips.chip[chip].cur_ptr = 0; break; default: if(old != data) { if((offset & 0xff00) == 0) { int chanoff = offset & 0x1f; if(chanoff < 4 || chanoff == 5 || (chanoff >=8 && chanoff <= 0xa) || (chanoff >= 0xc && chanoff <= 0xe)) break; } if(1 || ((offset >= 0x200) && (offset <= 0x210))) break; logerror("K054539 %03x = %02x\n", offset, data); } break; } } #if 0 static void reset_zones(void) { int chip; for(chip=0; chip<K054539_chips.intf->num; chip++) { int data = K054539_chips.chip[chip].regs[0x22e]; K054539_chips.chip[chip].cur_zone = data == 0x80 ? K054539_chips.chip[chip].ram : K054539_chips.chip[chip].rom + 0x20000*data; K054539_chips.chip[chip].cur_limit = data == 0x80 ? 0x4000 : 0x20000; } } #endif static data8_t K054539_r(int chip, offs_t offset) { switch(offset) { case 0x22d: if(K054539_chips.chip[chip].regs[0x22f] & 0x10) { data8_t res = K054539_chips.chip[chip].cur_zone[K054539_chips.chip[chip].cur_ptr]; K054539_chips.chip[chip].cur_ptr++; if(K054539_chips.chip[chip].cur_ptr == K054539_chips.chip[chip].cur_limit) K054539_chips.chip[chip].cur_ptr = 0; return res; } else return 0; case 0x22c: break; default: logerror("K054539 read %03x\n", offset); break; } return K054539_chips.chip[chip].regs[offset]; } int K054539_sh_start(const struct MachineSound *msound) { int i; K054539_chips.intf = (const K054539interface*)msound->sound_interface; if(Machine->sample_rate) K054539_chips.freq_ratio = (double)(K054539_chips.intf->clock) / (double)(Machine->sample_rate); else K054539_chips.freq_ratio = 1.0; // Factor the 1/4 for the number of channels in the volume (1/8 is too harsh, 1/2 gives clipping) // vol=0 -> no attenuation, vol=0x40 -> -36dB for(i=0; i<256; i++) K054539_chips.voltab[i] = pow(10.0, (-36.0 * (double)i / (double)0x40) / 20.0) / 4.0; // Pan table for the left channel // Right channel is identical with inverted index // Formula is such that pan[i]**2+pan[0xe-i]**2 = 1 (constant output power) // and pan[0] = 1 (full panning) for(i=0; i<0xf; i++) K054539_chips.pantab[i] = sqrt(0xe - i) / sqrt(0xe); for(i=0; i<K054539_chips.intf->num; i++) K054539_init_chip(i, msound); return 0; } void K054539_sh_stop(void) { int i; for(i=0; i<K054539_chips.intf->num; i++) K054539_stop_chip(i); } WRITE_HANDLER( K054539_0_w ) { K054539_w(0, offset, data); } READ_HANDLER( K054539_0_r ) { return K054539_r(0, offset); } WRITE_HANDLER( K054539_1_w ) { K054539_w(1, offset, data); } READ_HANDLER( K054539_1_r ) { return K054539_r(1, offset); }
25.725572
111
0.61702
gameblabla
0601761766c8fe5a175bb2a8dfcd86904818a68b
2,587
cpp
C++
Antiplagiat/Antiplagiat/bin/Debug/u45549_518_E_9997035.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
1
2015-07-04T14:45:32.000Z
2015-07-04T14:45:32.000Z
Antiplagiat/Antiplagiat/bin/Debug/u45549_518_E_9997035.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
Antiplagiat/Antiplagiat/bin/Debug/u45549_518_E_9997035.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef pair<int, int> pii; typedef long long int LL; typedef vector<int> VI; #define sd(x) scanf("%d", &x) #define MP make_pair #define PB push_back #define F first #define S second #define INF 1023456789 #define MOD 1000000007 #define D double #define LD long double #define N 212345 int getNext(){ int ret = 0, sign = 1; char ch = ' '; while((ch < '0' || ch > '9') && ch != '?' && ch != '-'){ ch = getchar(); } if(ch == '?'){ return -INF; } if(ch == '-'){ sign = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ ret *= 10; ret += ch - '0'; ch = getchar(); } return ret * sign; } int getFirstVal(int l, int r, int k){ if(-(k / 2) > l && (k - 1) / 2 < r){ return -k / 2; } if(abs(l) > abs(r)){ return r - k; } else{ return l + 1; } } int a[N]; vector<int> vec; int main(){ int n, k, l, j, i, p, s; cin>>n>>k; for(i = 0; i < n; i++){ a[i] = getNext(); } for(i = 0; i < k; i++){ vec.clear(); vec.PB(-INF); for(j = i; j < n; j += k){ vec.PB(a[j]); } l = 1; s = vec.size(); vec.PB(INF); while(l < s){ if(vec[l] != -INF){ l++; continue; } for(j = l + 1; j < s; j++){ if(vec[j] != -INF){ break; } } if(vec[j] - vec[l - 1] - 1 < j - l){ cout<<"Incorrect sequence"<<endl; return 0; } if(vec[l - 1] >= 0){ for(p = l; p < j; p++){ vec[p] = vec[p - 1] + 1; } } else if(vec[j] <= 0){ for(p = j - 1; p >= l; p--){ vec[p] = vec[p + 1] - 1; } } else{ vec[l] = getFirstVal(vec[l - 1], vec[j], j - l); for(p = l + 1; p < j; p++){ vec[p] = vec[p - 1] + 1; } } l = j + 1; } l = 1; for(j = i; j < n; j += k){ a[j] = vec[l]; l++; } } for(j = k; j < n; j++){ if(a[j] <= a[j - k]){ cout<<"Incorrect sequence"<<endl; return 0; } } for(i = 0; i < n; i++){ printf("%d", a[i]); printf(i < n - 1 ? " " : "\n"); } return 0; }
21.204918
64
0.333591
DmitryTheFirst
06029cf8718ffe62d3ded80fa521f4cdac2da3d1
6,106
cpp
C++
hi_components/eq_plot/FilterInfo.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
9
2020-04-16T01:17:27.000Z
2022-02-25T14:13:10.000Z
hi_components/eq_plot/FilterInfo.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
hi_components/eq_plot/FilterInfo.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
6
2020-05-11T22:23:15.000Z
2022-02-24T16:52:44.000Z
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HISE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * Some parts of this file are written by Sean Enderby. * * =========================================================================== */ namespace hise { using namespace juce; //============================================================================== FilterResponse::FilterResponse (double magnitudeInit, double phaseInit) { magnitudeValue = magnitudeInit; phaseValue = phaseInit; } FilterResponse::~FilterResponse() { } //=============================================================================== FilterInfo::FilterInfo() { fs = 44100; numeratorCoeffs.resize (1, 0); numeratorCoeffs [0] = 1; denominatorCoeffs.resize (1, 0); denominatorCoeffs [0] = 1; numNumeratorCoeffs = 1; numDenominatorCoeffs = 1; enabled = true; gainValue = 1; } FilterInfo::~FilterInfo() { } void FilterInfo::setSampleRate (double sampleRate) { fs = sampleRate; } void FilterInfo::setGain (double gain) { gainValue = gain; } FilterResponse FilterInfo::getResponse (double inputFrequency) const { std::complex <double> normalisedFrequency (0, (2 * double_Pi * inputFrequency / fs)); std::complex <double> z = pow (double_E, normalisedFrequency); std::complex <double> num (0, 0); std::complex <double> den (0, 0); for (int numOrder = 0; numOrder < numNumeratorCoeffs; numOrder++) { num += numeratorCoeffs [numOrder] / pow (z, numOrder); } for (int denOrder = 0; denOrder < numDenominatorCoeffs; denOrder++) { den += denominatorCoeffs [denOrder] / pow (z, denOrder); } std::complex <double> transferFunction = num / den; return FilterResponse (abs (transferFunction) * gainValue, arg (transferFunction)); } void FilterInfo::zeroCoeffs() { for (int numOrder = 0; numOrder < numNumeratorCoeffs; numOrder++) { numeratorCoeffs [numOrder] = 0; } for (int denOrder = 1; denOrder < numDenominatorCoeffs; denOrder++) { denominatorCoeffs [denOrder] = 0; } denominatorCoeffs [0] = 1; } void FilterInfo::setCoefficients(int /*filterNum*/, double /*sampleRate*/, IIRCoefficients newCoefficients) { numNumeratorCoeffs = 3; numDenominatorCoeffs = 3; numeratorCoeffs.resize (3, 0); denominatorCoeffs.resize (3, 0); zeroCoeffs(); for (int numOrder = 0; numOrder < 3; numOrder++) { numeratorCoeffs [numOrder] = newCoefficients.coefficients[numOrder]; } for (int denOrder = 1; denOrder < 3; denOrder++) { denominatorCoeffs [denOrder] = newCoefficients.coefficients [denOrder + 2]; } gainValue = 1; } void FilterInfo::setFilter (double frequency, FilterType filterType) { numNumeratorCoeffs = 3; numDenominatorCoeffs = 3; numeratorCoeffs.resize (3, 0); denominatorCoeffs.resize (3, 0); zeroCoeffs(); switch (filterType) { case LowPass: coefficients = IIRCoefficients::makeLowPass (fs, frequency); break; case HighPass: coefficients = IIRCoefficients::makeHighPass (fs, frequency); break; default: break; } for (int numOrder = 0; numOrder < 3; numOrder++) { numeratorCoeffs [numOrder] = coefficients.coefficients[numOrder]; } for (int denOrder = 1; denOrder < 3; denOrder++) { denominatorCoeffs [denOrder] = coefficients.coefficients [denOrder + 2]; } gainValue = 1; } void FilterInfo::setEqBand (double frequency, double Q, float gain, BandType eqType) { numNumeratorCoeffs = 3; numDenominatorCoeffs = 3; numeratorCoeffs.resize (3, 0); denominatorCoeffs.resize (3, 0); //gain = Decibels::decibelsToGain(gain); zeroCoeffs(); switch (eqType) { case LowShelf: coefficients = IIRCoefficients::makeLowShelf (fs, frequency, Q, gain); break; case HighShelf: coefficients = IIRCoefficients::makeHighShelf (fs, frequency, Q, gain); break; case Peak: coefficients = IIRCoefficients::makePeakFilter (fs, frequency, Q, gain); break; default: break; } for (int numOrder = 0; numOrder < 3; numOrder++) { numeratorCoeffs [numOrder] = coefficients.coefficients [numOrder]; } for (int denOrder = 1; denOrder < 3; denOrder++) { denominatorCoeffs [denOrder] = coefficients.coefficients [denOrder + 2]; } gainValue = 1; } void FilterInfo::setCustom (std::vector <double> numCoeffs, std::vector <double> denCoeffs) { numNumeratorCoeffs = (int)numCoeffs.size(); numDenominatorCoeffs = (int)denCoeffs.size(); numeratorCoeffs = numCoeffs; denominatorCoeffs = denCoeffs; } } // namespace hise
26.094017
107
0.600393
romsom
0603be8069b9d685151cfed0143520a6a8e5c200
16,343
cpp
C++
Documents/RacimoAire/Libreria/ADS1115/ads1115.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/Libreria/ADS1115/ads1115.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/Libreria/ADS1115/ads1115.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
/**************************************************************************/ /* Distributed with a free-will license. Use it any way you want, profit or free, provided it fits in the licenses of its associated works. ADS1115 This code is designed to work with the ADS1115_I2CADC I2C Mini Module available from ControlEverything.com. https://www.controleverything.com/content/Analog-Digital-Converters?sku=ADS1115_I2CADC#tabs-0-product_tabset-2 */ /**************************************************************************/ #include "ads1115.h" #include <QDebug> /**************************************************************************/ /* Abstract away platform differences in Arduino wire library */ /**************************************************************************/ /* Instantiates a new ADS1115 class with appropriate properties */ /**************************************************************************/ ADS1115::ADS1115(Crpigpio *cGPIO, uint8_t i2cAddress) { RA_cGPIO = cGPIO; ads_i2cAddress = i2cAddress; ads_conversionDelay = ADS1115_CONVERSIONDELAY; ads_osmode = OSMODE_SINGLE; ads_gain = GAIN_TWOTHIRDS; ads_mode = MODE_CONTIN; ads_rate = RATE_128; /*ads_compmode = COMPMODE_TRAD; ads_comppol = COMPPOL_LOW; ads_complat = COMPLAT_NONLAT; ads_compque = COMPQUE_NONE; */ RA_cGPIO->OpenI2C(1,ads_i2cAddress,0); Measure_SingleEnded(0); } ADS1115::~ADS1115() { RA_cGPIO->CloseI2C(); delete RA_cGPIO; } /**************************************************************************/ /* Writes 16-bits to the specified destination register */ /**************************************************************************/ void ADS1115::writeRegister(uint8_t reg, uint16_t value) { uint16_t value2= (value>>8 & 0xff) | (value<<8); m_InitOk = RA_cGPIO->WriteDeviceI2C(reg,value2); } /**************************************************************************/ /* Reads 16-bits to the specified destination register */ /**************************************************************************/ int16_t ADS1115::readRegister(uint8_t reg) { int16_t ReturnData; char buf[2]; RA_cGPIO->ReadDeviceI2C(reg, &buf[0], 2); ReturnData = ( buf[0] << 8 ) | buf[1]; //if((ReturnData & 0x8000) > 0) //{ // ReturnData = ReturnData >> 1; // ReturnData= ~ReturnData + 1 ; // ReturnData= (-1)* ReturnData; //} return ReturnData; } int ADS1115::getInitOk() const { return m_InitOk; } /**************************************************************************/ /* Sets the Operational status/single-shot conversion start This determines the operational status of the device */ /**************************************************************************/ void ADS1115::setOSMode(adsOSMode_t osmode) { ads_osmode = osmode; } /**************************************************************************/ /* Gets the Operational status/single-shot conversion start */ /**************************************************************************/ adsOSMode_t ADS1115::getOSMode() { return ads_osmode; } /**************************************************************************/ /* Sets the gain and input voltage range This configures the programmable gain amplifier */ /**************************************************************************/ void ADS1115::setGain(adsGain_t gain) { ads_gain = gain; } /**************************************************************************/ /* Gets a gain and input voltage range */ /**************************************************************************/ adsGain_t ADS1115::getGain() { return ads_gain; } /**************************************************************************/ /* Sets the Device operating mode This controls the current operational mode of the ADS1115 */ /**************************************************************************/ void ADS1115::setMode(adsMode_t mode) { ads_mode = mode; } /**************************************************************************/ /* Gets the Device operating mode */ /**************************************************************************/ adsMode_t ADS1115::getMode() { return ads_mode; } /**************************************************************************/ /* Sets the Date Rate This controls the data rate setting */ /**************************************************************************/ void ADS1115::setRate(adsRate_t rate) { ads_rate = rate; } /**************************************************************************/ /* Gets the Date Rate */ /**************************************************************************/ adsRate_t ADS1115::getRate() { return ads_rate; } /**************************************************************************/ /* Sets the Comparator mode This controls the comparator mode of operation */ /**************************************************************************/ void ADS1115::setCompMode(adsCompMode_t compmode) { ads_compmode = compmode; } /**************************************************************************/ /* Gets the Comparator mode */ /**************************************************************************/ adsCompMode_t ADS1115::getCompMode() { return ads_compmode; } /**************************************************************************/ /* Sets the Comparator polarity This controls the polarity of the ALERT/RDY pin */ /**************************************************************************/ void ADS1115::setCompPol(adsCompPol_t comppol) { ads_comppol = comppol; } /**************************************************************************/ /* Gets the Comparator polarity */ /**************************************************************************/ adsCompPol_t ADS1115::getCompPol() { return ads_comppol; } /**************************************************************************/ /* Sets the Latching comparator This controls whether the ALERT/RDY pin latches once asserted or clears once conversions are within the margin of the upper and lower threshold values */ /**************************************************************************/ void ADS1115::setCompLat(adsCompLat_t complat) { ads_complat = complat; } /**************************************************************************/ /* Gets the Latching comparator */ /**************************************************************************/ adsCompLat_t ADS1115::getCompLat() { return ads_complat; } /**************************************************************************/ /* Sets the Comparator queue and disable This perform two functions. It can disable the comparator function and put the ALERT/RDY pin into a high state. It also can control the number of successive conversions exceeding the upper or lower thresholds required before asserting the ALERT/RDY pin */ /**************************************************************************/ void ADS1115::setCompQue(adsCompQue_t compque) { ads_compque = compque; } /**************************************************************************/ /* Gets the Comparator queue and disable */ /**************************************************************************/ adsCompQue_t ADS1115::getCompQue() { return ads_compque; } /**************************************************************************/ /* Sets the low threshold value */ /**************************************************************************/ void ADS1115::setLowThreshold(int16_t threshold) { ads_lowthreshold = threshold; writeRegister(ADS1115_REG_POINTER_LOWTHRESH, ads_lowthreshold); } /**************************************************************************/ /* Gets the low threshold value */ /**************************************************************************/ int16_t ADS1115::getLowThreshold() { return ads_lowthreshold; } /**************************************************************************/ /* Sets the high threshold value */ /**************************************************************************/ void ADS1115::setHighThreshold(int16_t threshold) { ads_highthreshold = threshold; writeRegister(ADS1115_REG_POINTER_HITHRESH, ads_highthreshold); } /**************************************************************************/ /* Gets the high threshold value */ /**************************************************************************/ int16_t ADS1115::getHighThreshold() { return ads_highthreshold; } /**************************************************************************/ /* Reads the conversion results, measuring the voltage for a single-ended ADC reading from the specified channel Negative voltages cannot be applied to this circuit because the ADS1115 can only accept positive voltages */ /**************************************************************************/ uint16_t ADS1115::Measure_SingleEnded(uint8_t channel) { if (channel > 3) { return 0; } // Start with default values uint16_t config=0; config = ADS1115_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val) ADS1115_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val) ADS1115_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val) ADS1115_REG_CONFIG_CMODE_TRAD; // Traditional comparator (default val) // Set Operational status/single-shot conversion start config |= ads_osmode; // Set PGA/voltage range config |= ads_gain; // Set Device operating mode config |= ads_mode; // Set Data rate config |= ads_rate; // Set single-ended input channel switch (channel) { case (0): config |= ADS1115_REG_CONFIG_MUX_SINGLE_0; break; case (1): config |= ADS1115_REG_CONFIG_MUX_SINGLE_1; break; case (2): config |= ADS1115_REG_CONFIG_MUX_SINGLE_2; break; case (3): config |= ADS1115_REG_CONFIG_MUX_SINGLE_3; break; } // Write config register to the ADC writeRegister(ADS1115_REG_POINTER_CONFIG, config); // Wait for the conversion to complete QThread::msleep(ads_conversionDelay); // Read the conversion results // 16-bit unsigned results for the ADS1115 return readRegister(ADS1115_REG_POINTER_CONVERT); } /**************************************************************************/ /* Reads the conversion results, measuring the voltage difference between the P (AIN#) and N (AIN#) input Generates a signed value since the difference can be either positive or negative */ /**************************************************************************/ int16_t ADS1115::Measure_Differential(uint8_t channel) { // Start with default values uint16_t config = ADS1115_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val) ADS1115_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val) ADS1115_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val) ADS1115_REG_CONFIG_CMODE_TRAD; // Traditional comparator (default val) // Set Operational status/single-shot conversion start config |= ads_osmode; // Set PGA/voltage range config |= ads_gain; // Set Device operating mode config |= ads_mode; // Set Data rate config |= ads_rate; // Set Differential input channel switch (channel) { case (01): config |= ADS1115_REG_CONFIG_MUX_DIFF_0_1; // AIN0 = P, AIN1 = N break; case (03): config |= ADS1115_REG_CONFIG_MUX_DIFF_0_3; // AIN0 = P, AIN3 = N break; case (13): config |= ADS1115_REG_CONFIG_MUX_DIFF_1_3; // AIN1 = P, AIN3 = N break; case (23): config |= ADS1115_REG_CONFIG_MUX_DIFF_2_3; // AIN2 = P, AIN3 = N break; } // Write config register to the ADC writeRegister(ADS1115_REG_POINTER_CONFIG, config); // Wait for the conversion to complete QThread::msleep(ads_conversionDelay); // Read the conversion results uint16_t raw_adc = readRegister(ADS1115_REG_POINTER_CONVERT); return (int16_t)raw_adc; } /**************************************************************************/ /* Sets up the comparator causing the ALERT/RDY pin to assert (go from high to low) when the ADC value exceeds the specified upper or lower threshold ADC is single-ended input channel */ /**************************************************************************/ int16_t ADS1115::Comparator_SingleEnded(uint8_t channel) { // Start with default values uint16_t config; // Set Operational status/single-shot conversion start config |= ads_osmode; // Set PGA/voltage range config |= ads_gain; // Set Device operating mode config |= ads_mode; // Set Data rate config |= ads_rate; // Set Comparator mode config |= ads_compmode; // Set Comparator polarity config |= ads_comppol; // Set Latching comparator config |= ads_complat; // Set Comparator queue and disable config |= ads_compque; // Set single-ended input channel switch (channel) { case (0): config |= ADS1115_REG_CONFIG_MUX_SINGLE_0; break; case (1): config |= ADS1115_REG_CONFIG_MUX_SINGLE_1; break; case (2): config |= ADS1115_REG_CONFIG_MUX_SINGLE_2; break; case (3): config |= ADS1115_REG_CONFIG_MUX_SINGLE_3; break; } // Write config register to the ADC writeRegister(ADS1115_REG_POINTER_CONFIG, config); // Wait for the conversion to complete QThread::msleep(ads_conversionDelay); // Read the conversion results uint16_t raw_adc = readRegister(ADS1115_REG_POINTER_CONVERT); return (int16_t)raw_adc; } /**************************************************************************/ /* Sets up the comparator causing the ALERT/RDY pin to assert (go from high to low) when the ADC value exceeds the specified upper or lower threshold ADC is Differential input channel */ /**************************************************************************/ int16_t ADS1115::Comparator_Differential(uint8_t channel) { // Start with default values uint16_t config; // Set Operational status/single-shot conversion start config |= ads_osmode; // Set PGA/voltage range config |= ads_gain; // Set Device operating mode config |= ads_mode; // Set Data rate config |= ads_rate; // Set Comparator mode config |= ads_compmode; // Set Comparator polarity config |= ads_comppol; // Set Latching comparator config |= ads_complat; // Set Comparator queue and disable config |= ads_compque; // Set Differential input channel switch (channel) { case (01): config |= ADS1115_REG_CONFIG_MUX_DIFF_0_1; // AIN0 = P, AIN1 = N break; case (03): config |= ADS1115_REG_CONFIG_MUX_DIFF_0_3; // AIN0 = P, AIN3 = N break; case (13): config |= ADS1115_REG_CONFIG_MUX_DIFF_1_3; // AIN1 = P, AIN3 = N break; case (23): config |= ADS1115_REG_CONFIG_MUX_DIFF_2_3; // AIN2 = P, AIN3 = N break; } // Write config register to the ADC writeRegister(ADS1115_REG_POINTER_CONFIG, config); // Wait for the conversion to complete QThread::msleep(ads_conversionDelay); // Read the conversion results uint16_t raw_adc = readRegister(ADS1115_REG_POINTER_CONVERT); return (int16_t)raw_adc; }
29.76867
111
0.478248
JoseSalamancaCoy
0606f7b62eabf2c92c1d0d10c90f152dad5fded2
10,938
cpp
C++
Speedometer.cpp
jimenezjose/Speedometer
42a1f46e42641f826b6c00317f5b40c19acd742c
[ "MIT" ]
null
null
null
Speedometer.cpp
jimenezjose/Speedometer
42a1f46e42641f826b6c00317f5b40c19acd742c
[ "MIT" ]
null
null
null
Speedometer.cpp
jimenezjose/Speedometer
42a1f46e42641f826b6c00317f5b40c19acd742c
[ "MIT" ]
null
null
null
/**************************************************************************** Jose Jorge Jimenez-Olivas August 6, 2018 File Name: Speedometer.cpp Description: Emulate a speedometer by calculating the number of revolutions per unit time on an RC-Car. ****************************************************************************/ #include "Speedometer.h" /*************************************************************************** % Constructor : Speedometer % File : Speedometer.cpp % Parameters: sensorPin -- Arduino socket connected to the photoresistor % ledPin -- Pin for the backlight led ***************************************************************************/ Speedometer :: Speedometer( const int8_t sensorPin, const int8_t ledPin ) : _SensorPin( sensorPin ), _LedPin( ledPin ) { threshold = SPEEDOMETER_DEFAULT_THRESHOLD; resetData(); pinMode( sensorPin, INPUT ); pinMode( ledPin, OUTPUT ); digitalWrite( ledPin, HIGH ); } /*************************************************************************** % Routine Name : task % File : Speedometer.cpp % Parameters: None % Description : Main function that handles when to start and stop sampling. % After the sample has been collected, rpm logic is invoked. % Return: Nothing ***************************************************************************/ void Speedometer :: task() { if( stanDev == 0 ) { /* sampling light intensity values */ calibrate(); return; } else if( stanDev < NOISE_DEVIATION + 1 ) { /* wheel was not rotating - biased data set, + 1 to ignore decimals */ Serial.println( "reseting" ); resetData(); return; } runSpeedometer(); } /*************************************************************************** % Routine Name : runSpeedometer % File : Speedometer.cpp % Parameters: None % Description : Calculates the instantaneous RPM based on the current light % intensity. % Return: Nothing ***************************************************************************/ void Speedometer :: runSpeedometer() { static bool inPeak = false; /* currLight surpassed Z_Score threshold */ static int32_t revolutions = 0; /* current tire revolutions */ static int16_t prevLight = 0; /* last valid light reading */ int16_t currLight = analogRead( _SensorPin ); /* current light reading */ double Z_Score = 0; /* current light standing */ /* Noise control -- avoid currLight to bounce between two adjacent values */ if( abs(currLight - prevLight) > NOISE_DEVIATION ) { /* current light reading is valid - update new prevLight */ prevLight = currLight; } else { /* reset currLight to last valid reading - light in noise range */ currLight = prevLight; } Z_Score = (currLight - mean) / stanDev; if( inPeak == false && Z_Score > threshold ) { /* 1 revolution noted, beginning of light peak */ revolutions++; totalRevs++; inPeak = true; } else if( inPeak == true && Z_Score <= threshold ) { /* end of light peak -- ready for the next revolution */ inPeak = false; } uint32_t currentMillis = millis(); if( revolutions || currentMillis - previousMillis > 7500 ) { /* calculate current rpm -- time interupt of 7.5 seconds*/ double dt = currentMillis - previousMillis; dt = dt * (1.0 / 1000) * (1.0 / 60); rpm = revolutions / dt; /* reset deltas */ previousMillis = currentMillis; revolutions = 0; if( rpm > maxRPM ) { maxRPM = rpm; } } Serial.print( totalRevs ); Serial.print( "\t" ); Serial.print( currLight ); Serial.print( "\t" ); Serial.print( mean + threshold * stanDev ); Serial.print( "\t" ); Serial.println( rpm ); //Serial.print( "\t" ); //Serial.println( currentMillis - previousMillis ); } /*************************************************************************** % Routine Name : calibrate % File : Speedometer.cpp % Parameters: None % Description : Samples real time light intensity values to calculate and % approximate the population mean and standard deviation for % future program reference. % Return: Nothing ***************************************************************************/ void Speedometer :: calibrate() { if( populateData() ) { /* data sample has successfully been collected */ mean = calcMean(); stanDev = calcStanDev( mean ); } else { /* new data is being collected - necessary for forced recalibration */ mean = 0; stanDev = 0; } } /*************************************************************************** % Routine Name : populateData % File : Speedometer.cpp % Parameters: None % Description : At every 50 millisecond interval, a data element is % collected from the reading of the light sensor pin. % Return: true - sample has finished being collected % false - sample is in the process of being collected ***************************************************************************/ bool Speedometer :: populateData() { uint8_t sampleSize = SPEEDOMETER_SAMPLE_SIZE; uint32_t currentMillis = millis(); if( currentMillis - previousMillis > 75 ) { /* delay implemented to emulate a random sample */ previousMillis = currentMillis; dataIndex = dataIndex % sampleSize; /* wrap overloaded index */ data[ dataIndex ] = analogRead( _SensorPin ); dataIndex++; /* wrap avoided - for valid return */ Serial.println( data[ dataIndex - 1 ] ); } /* dataIndex will be off by one, to indicate end of sample collection */ return (dataIndex == sampleSize); } /*************************************************************************** % Routine Name : calcMean % File : Speedometer.cpp % Parameters: None % Description : Calculate the sample mean from the data set collected % Return: Sample mean. ***************************************************************************/ double Speedometer :: calcMean() { uint8_t sampleSize = SPEEDOMETER_SAMPLE_SIZE; uint32_t total = 0; for( uint8_t index = 0; index < sampleSize; index++ ) { /* accumulate data point values */ total += data[ index ]; } return total / sampleSize; } /*************************************************************************** % Routine Name : calcStanDev % File : Speedometer.cpp % Parameters: sampleMean -- mean of collected sample % Description : Calculated an unbiased estimation of the population % standard deviation. % Return: Unbiased standard deviation. ***************************************************************************/ double Speedometer :: calcStanDev( double sampleMean ) { uint32_t sampleSize = SPEEDOMETER_SAMPLE_SIZE; uint32_t deviations = 0; /* current deviations */ for( uint8_t index = 0; index < sampleSize; index++ ) { /* squaring deviations for treating all differences equally */ deviations += sq( data[index] - sampleMean ); } /* unbiased estimation of population standard deviation */ return sqrt( deviations / (sampleSize - 1) ); } /*************************************************************************** % Routine Name : resetData % File : Speedometer.cpp % Parameters: None % Description : Resets all sample influenced data. % Return: Nothing ***************************************************************************/ void Speedometer :: resetData() { mean = 0; stanDev = 0; dataIndex = 0; previousMillis = millis(); totalRevs = 0; maxRPM = 0; } /*************************************************************************** % Routine Name : isCalibrating % File : Speedometer.cpp % Parameters: None % Description : sample set is currently being collected. % Return: true - sample is being collected. false - otherwise. ***************************************************************************/ bool Speedometer :: isCalibrating() { return dataIndex != SPEEDOMETER_SAMPLE_SIZE; } /*************************************************************************** % Routine Name : setThreshold % File : Speedometer.cpp % Parameters: newThreshold -- new revolutuion threshold, in terms of % standard deviations from sample mean. % Description : Mutator method to alter the threshold value. % Return: Nothing ***************************************************************************/ void Speedometer :: setThreshold( double newThreshold ) { threshold = newThreshold; } /*************************************************************************** % Routine Name : getRPM % File : Speedometer.cpp % Parameters: None % Description : Accessor method for instantaeous RPM % Return: Current revolutions per minute rate ***************************************************************************/ int32_t Speedometer :: getRPM() { return rpm; } /*************************************************************************** % Routine Name : getMaxRPM % File : Speedometer.cpp % Parameters: None % Description : Accessor method to get the current max rpm value. % Return: Current max rpm. ***************************************************************************/ int32_t Speedometer :: getMaxRPM() { return maxRPM; } /*************************************************************************** % Routine Name : getThreshold % File : Speedometer.cpp % Parameters: None % Description : Accessor method to the revolution threshold. % Return: Revolution threshold % (in terms of standard deviations from the mean) ***************************************************************************/ double Speedometer :: getThreshold() { return threshold; } /*************************************************************************** % Routine Name : getMean % File : Speedometer.cpp % Parameters: None % Description : Accessor method to the sample mean % Return: Sample mean ***************************************************************************/ double Speedometer :: getMean() { return mean; } /*************************************************************************** % Routine Name : getStanDev % File : Speedometer.cpp % Parameters: None % Description : Accessor method to the unbiased standard deviation % Return: Sample standard deviation ***************************************************************************/ double Speedometer :: getStanDev() { return stanDev; }
35.398058
80
0.497349
jimenezjose
0609fc2003497e8358cb980b81bacb40259b4a25
3,856
cc
C++
components/ui_devtools/viz/frame_sink_element.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/ui_devtools/viz/frame_sink_element.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/ui_devtools/viz/frame_sink_element.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/ui_devtools/viz/frame_sink_element.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "components/ui_devtools/Protocol.h" #include "components/ui_devtools/ui_element_delegate.h" #include "components/viz/service/frame_sinks/compositor_frame_sink_support.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" #include "components/viz/service/surfaces/surface.h" #include "components/viz/service/surfaces/surface_manager.h" namespace ui_devtools { FrameSinkElement::FrameSinkElement( const viz::FrameSinkId& frame_sink_id, viz::FrameSinkManagerImpl* frame_sink_manager, UIElementDelegate* ui_element_delegate, UIElement* parent, bool is_root, bool has_created_frame_sink) : VizElement(UIElementType::FRAMESINK, ui_element_delegate, parent), frame_sink_id_(frame_sink_id), frame_sink_manager_(frame_sink_manager), is_root_(is_root), has_created_frame_sink_(has_created_frame_sink) { // DOMAgentViz handles all of the FrameSink events, so it owns all of the // FrameSinkElements. set_owns_children(false); } FrameSinkElement::~FrameSinkElement() {} std::vector<UIElement::ClassProperties> FrameSinkElement::GetCustomPropertiesForMatchedStyle() const { std::vector<UIElement::ClassProperties> ret; std::vector<UIElement::UIProperty> properties; // Hierarchical information about the FrameSink. properties.emplace_back("Is root", is_root_ ? "true" : "false"); properties.emplace_back("Has created frame sink", has_created_frame_sink_ ? "true" : "false"); // LastUsedBeingFrameArgs information. const viz::CompositorFrameSinkSupport* support = frame_sink_manager_->GetFrameSinkForId(frame_sink_id_); if (support) { const viz::BeginFrameArgs args = static_cast<const viz::BeginFrameObserver*>(support) ->LastUsedBeginFrameArgs(); properties.emplace_back("SourceId", base::NumberToString(args.frame_id.source_id)); properties.emplace_back( "SequenceNumber", base::NumberToString(args.frame_id.sequence_number)); properties.emplace_back( "FrameType", std::string(viz::BeginFrameArgs::TypeToString(args.type))); } ret.emplace_back("FrameSink", properties); return ret; } void FrameSinkElement::GetBounds(gfx::Rect* bounds) const { const viz::CompositorFrameSinkSupport* support = frame_sink_manager_->GetFrameSinkForId(frame_sink_id_); if (!support) { *bounds = gfx::Rect(); return; } // Get just size of last activated surface that corresponds to this frame // sink. viz::Surface* srfc = frame_sink_manager_->surface_manager()->GetSurfaceForId( support->last_activated_surface_id()); if (srfc) *bounds = gfx::Rect(srfc->size_in_pixels()); else *bounds = gfx::Rect(); } void FrameSinkElement::SetBounds(const gfx::Rect& bounds) {} void FrameSinkElement::GetVisible(bool* visible) const { // Currently not real data. *visible = true; } void FrameSinkElement::SetVisible(bool visible) {} std::vector<std::string> FrameSinkElement::GetAttributes() const { return {"FrameSinkId", frame_sink_id_.ToString(), "Title", (frame_sink_manager_->GetFrameSinkDebugLabel(frame_sink_id_)).data()}; } std::pair<gfx::NativeWindow, gfx::Rect> FrameSinkElement::GetNodeWindowAndScreenBounds() const { return {}; } // static const viz::FrameSinkId& FrameSinkElement::From(const UIElement* element) { DCHECK_EQ(UIElementType::FRAMESINK, element->type()); return static_cast<const FrameSinkElement*>(element)->frame_sink_id_; } } // namespace ui_devtools
35.376147
80
0.742998
sarang-apps
060bda52d453953943802a786c7da9bbd467e5e8
467
cc
C++
nlp/processed/column/TC2673.cc
lionell/laboratories
751e60d1851c45b98d1580c9631fd92afbdf02b0
[ "MIT" ]
2
2019-10-01T09:41:15.000Z
2021-06-06T17:46:13.000Z
nlp/processed/column/TC2673.cc
lionell/laboratories
751e60d1851c45b98d1580c9631fd92afbdf02b0
[ "MIT" ]
1
2018-05-18T18:20:46.000Z
2018-05-18T18:20:46.000Z
nlp/processed/column/TC2673.cc
lionell/laboratories
751e60d1851c45b98d1580c9631fd92afbdf02b0
[ "MIT" ]
8
2017-01-20T15:44:06.000Z
2021-11-28T20:00:49.000Z
#include <cstdio> #include <algorithm> static const int MAX_N=10000000; int a[MAX_N],b[MAX_N],c[MAX_N]; int main() { int N; long long S=0; std::scanf("%d",&N); for(int i=0;i<N;++i) std::scanf("%d",&(c[i])); for(int i=0;i<N;++i) a[i]=std::max(i==0?0:a[i-1],c[i]); for(int i=N-1;i>=0;--i) b[i]=std::max(i==N-1?0:b[i+1],c[i]); for(int i=0;i<N;++i) S+=std::min(a[i],b[i])-c[i]; std::printf("%lld",S); return 0; }
23.35
65
0.492505
lionell
060bf33a5baa649811745c1a7cd1363a608a57e5
1,744
hpp
C++
src/gui/MissionView/MissionView.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2022-03-31T12:15:15.000Z
2022-03-31T12:15:15.000Z
src/gui/MissionView/MissionView.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
null
null
null
src/gui/MissionView/MissionView.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2021-12-29T10:38:07.000Z
2021-12-29T10:38:07.000Z
#ifndef TEMPL_GUI_MISSION_VIEW_HPP #define TEMPL_GUI_MISSION_VIEW_HPP #include <QTreeWidget> #include <QWidget> #include <QProcess> #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsGridLayout> #include <QTreeView> #include <QStandardItem> #include <QDomNode> #include <graph_analysis/Graph.hpp> #include "../../Mission.hpp" namespace templ { namespace gui { class MissionView : public QTreeView { Q_OBJECT public: MissionView(QWidget* parent = NULL); ~MissionView(); QString getClassName() const { return "templ::gui::MissionView"; } Mission::Ptr getMission() const { return mpMission; } private: QStandardItem* mpItem; Mission::Ptr mpMission; QString mFilename; void updateVisualization(); void loadXML(const QString& missionSpec); void refreshView(); QStandardItem* createRoot(const QString& name); QStandardItem* createChild(QStandardItem* item, const QDomNode& node); void setItem(QStandardItemModel* model); void preOrder(QDomNode node, QStandardItemModel* model, QStandardItem* item = 0); public slots: void on_planMission_clicked(); // Adding/Removing Constraints void on_addConstraintButton_clicked(); void on_removeConstraintButton_clicked(); /** * Loading/Storing Missions * \return True, when mission was loaded, false otherwise */ bool loadMission(const QString& settingsLabel ="IOMission", const QString& filename = ""); void on_saveButton_clicked(); void on_updateButton_clicked(); void on_clearButton_clicked(); const QString& getFilename() const { return mFilename; } }; } // end namespace gui } // end namespace templ #endif // TEMPL_GUI_MISSION_VIEW_HPP
23.567568
94
0.71961
tomcreutz
06128ecab2fb2e6e66d9ab7e857e99f65e846911
19,663
cc
C++
lib/backprojecting_layer/backprojecting_op.cc
aditya2592/PoseCNN
a763120ce0ceb55cf3432980287ef463728f8052
[ "MIT" ]
655
2018-03-21T19:55:45.000Z
2022-03-25T20:41:21.000Z
lib/backprojecting_layer/backprojecting_op.cc
yuxng/FCN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
[ "MIT" ]
122
2018-04-04T13:57:49.000Z
2022-03-18T09:28:44.000Z
lib/backprojecting_layer/backprojecting_op.cc
yuxng/FCN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
[ "MIT" ]
226
2018-03-22T01:40:04.000Z
2022-03-17T11:56:14.000Z
/* Copyright 2015 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. ==============================================================================*/ // Backprojecting Op #include <stdio.h> #include <cfloat> #include <math.h> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_shape.h" using namespace tensorflow; typedef Eigen::ThreadPoolDevice CPUDevice; REGISTER_OP("Backproject") .Attr("T: {float, double}") .Attr("grid_size: int") .Attr("kernel_size: int") .Attr("threshold: float") .Input("bottom_data: T") .Input("bottom_label: T") .Input("bottom_depth: T") .Input("bottom_meta_data: T") .Input("bottom_label_3d: T") .Output("top_data: T") .Output("top_label: T") .Output("top_flag: T"); REGISTER_OP("BackprojectGrad") .Attr("T: {float, double}") .Attr("grid_size: int") .Attr("kernel_size: int") .Attr("threshold: float") .Input("bottom_data: T") .Input("bottom_depth: T") .Input("bottom_meta_data: T") .Input("grad: T") .Output("output: T"); template <typename Device, typename T> class BackprojectOp : public OpKernel { public: explicit BackprojectOp(OpKernelConstruction* context) : OpKernel(context) { // Get the grid size OP_REQUIRES_OK(context, context->GetAttr("grid_size", &grid_size_)); // Check that grid size is positive OP_REQUIRES(context, grid_size_ >= 0, errors::InvalidArgument("Need grid_size >= 0, got ", grid_size_)); // Get the kernel size OP_REQUIRES_OK(context, context->GetAttr("kernel_size", &kernel_size_)); // Check that kernel size is positive OP_REQUIRES(context, kernel_size_ >= 0, errors::InvalidArgument("Need kernel_size >= 0, got ", kernel_size_)); // Get the threshold OP_REQUIRES_OK(context, context->GetAttr("threshold", &threshold_)); // Check that threshold is positive OP_REQUIRES(context, threshold_ >= 0, errors::InvalidArgument("Need threshold >= 0, got ", threshold_)); } // bottom_data: (batch_size, height, width, channels) void Compute(OpKernelContext* context) override { // Grab the input tensor const Tensor& bottom_data = context->input(0); auto bottom_data_flat = bottom_data.flat<T>(); const Tensor& bottom_label = context->input(1); auto bottom_label_flat = bottom_label.flat<T>(); const Tensor& bottom_depth = context->input(2); auto im_depth = bottom_depth.flat<T>(); // format of the meta_data // intrinsic matrix: meta_data[0 ~ 8] // inverse intrinsic matrix: meta_data[9 ~ 17] // pose_world2live: meta_data[18 ~ 29] // pose_live2world: meta_data[30 ~ 41] // voxel step size: meta_data[42, 43, 44] // voxel min value: meta_data[45, 46, 47] const Tensor& bottom_meta_data = context->input(3); auto meta_data = bottom_meta_data.flat<T>(); const Tensor& bottom_label_3d = context->input(4); auto bottom_label_3d_flat = bottom_label_3d.flat<T>(); // data should have 4 dimensions. OP_REQUIRES(context, bottom_data.dims() == 4, errors::InvalidArgument("data must be 4-dimensional")); OP_REQUIRES(context, bottom_label.dims() == 4, errors::InvalidArgument("label must be 4-dimensional")); OP_REQUIRES(context, bottom_depth.dims() == 4, errors::InvalidArgument("depth must be 4-dimensional")); OP_REQUIRES(context, bottom_meta_data.dims() == 4, errors::InvalidArgument("meta data must be 4-dimensional")); OP_REQUIRES(context, bottom_label_3d.dims() == 5, errors::InvalidArgument("label 3D must be 5-dimensional")); // batch size int batch_size = bottom_data.dim_size(0); // height int height = bottom_data.dim_size(1); // width int width = bottom_data.dim_size(2); // number of channels int num_channels = bottom_data.dim_size(3); int num_classes = bottom_label.dim_size(3); int num_meta_data = bottom_meta_data.dim_size(3); // Create output tensors // top_data int dims[5]; dims[0] = batch_size; dims[1] = grid_size_; dims[2] = grid_size_; dims[3] = grid_size_; dims[4] = num_channels; TensorShape output_shape; TensorShapeUtils::MakeShape(dims, 5, &output_shape); Tensor* top_data_tensor = NULL; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &top_data_tensor)); auto top_data = top_data_tensor->template flat<T>(); // top flag TensorShape output_shape_flag; TensorShapeUtils::MakeShape(dims, 5, &output_shape_flag); Tensor* top_flag_tensor = NULL; OP_REQUIRES_OK(context, context->allocate_output(2, output_shape_flag, &top_flag_tensor)); auto top_flag = top_flag_tensor->template flat<T>(); // top label dims[4] = num_classes; TensorShape output_shape_label; TensorShapeUtils::MakeShape(dims, 5, &output_shape_label); Tensor* top_label_tensor = NULL; OP_REQUIRES_OK(context, context->allocate_output(1, output_shape_label, &top_label_tensor)); auto top_label = top_label_tensor->template flat<T>(); int index_meta_data = 0; for(int n = 0; n < batch_size; n++) { int index_batch = n * grid_size_ * grid_size_ * grid_size_; for(int d = 0; d < grid_size_; d++) { int index_depth = d * grid_size_ * grid_size_; for(int h = 0; h < grid_size_; h++) { int index_height = h * grid_size_; for(int w = 0; w < grid_size_; w++) { // voxel location in 3D T X = d * meta_data(index_meta_data + 42) + meta_data(index_meta_data + 45); T Y = h * meta_data(index_meta_data + 43) + meta_data(index_meta_data + 46); T Z = w * meta_data(index_meta_data + 44) + meta_data(index_meta_data + 47); // apply pose_world2live T X1 = meta_data(index_meta_data + 18) * X + meta_data(index_meta_data + 19) * Y + meta_data(index_meta_data + 20) * Z + meta_data(index_meta_data + 21); T Y1 = meta_data(index_meta_data + 22) * X + meta_data(index_meta_data + 23) * Y + meta_data(index_meta_data + 24) * Z + meta_data(index_meta_data + 25); T Z1 = meta_data(index_meta_data + 26) * X + meta_data(index_meta_data + 27) * Y + meta_data(index_meta_data + 28) * Z + meta_data(index_meta_data + 29); // apply the intrinsic matrix T x1 = meta_data(index_meta_data + 0) * X1 + meta_data(index_meta_data + 1) * Y1 + meta_data(index_meta_data + 2) * Z1; T x2 = meta_data(index_meta_data + 3) * X1 + meta_data(index_meta_data + 4) * Y1 + meta_data(index_meta_data + 5) * Z1; T x3 = meta_data(index_meta_data + 6) * X1 + meta_data(index_meta_data + 7) * Y1 + meta_data(index_meta_data + 8) * Z1; int px = round(x1 / x3); int py = round(x2 / x3); // initialization for(int c = 0; c < num_channels; c++) top_data((index_batch + index_depth + index_height + w) * num_channels + c) = 0; for(int c = 0; c < num_classes; c++) top_label((index_batch + index_depth + index_height + w) * num_classes + c) = 0; // check a neighborhood around (px, py) int count = 0; for (int x = px - kernel_size_; x <= px + kernel_size_; x++) { for (int y = py - kernel_size_; y <= py + kernel_size_; y++) { if (x >= 0 && x < width && y >= 0 && y < height) { int index_pixel = n * height * width + y * width + x; T depth = im_depth(index_pixel); // distance of this voxel to camera center T dvoxel = Z1; // check if the voxel is on the surface if (fabs(depth - dvoxel) < threshold_) { count++; // data for(int c = 0; c < num_channels; c++) top_data((index_batch + index_depth + index_height + w) * num_channels + c) += bottom_data_flat(index_pixel * num_channels + c); // label for(int c = 0; c < num_classes; c++) top_label((index_batch + index_depth + index_height + w) * num_classes + c) += bottom_label_flat(index_pixel * num_classes + c); } } } } if (count == 0) { // flag for (int c = 0; c < num_channels; c++) top_flag((index_batch + index_depth + index_height + w) * num_channels + c) = 0; // label for(int c = 0; c < num_classes; c++) top_label((index_batch + index_depth + index_height + w) * num_classes + c) = bottom_label_3d_flat((index_batch + index_depth + index_height + w) * num_classes + c); } else { // data and flag for (int c = 0; c < num_channels; c++) { top_data((index_batch + index_depth + index_height + w) * num_channels + c) /= count; top_flag((index_batch + index_depth + index_height + w) * num_channels + c) = 1; } // label for(int c = 0; c < num_classes; c++) top_label((index_batch + index_depth + index_height + w) * num_classes + c) /= count; } // end checking neighborhood } } } index_meta_data += num_meta_data; } } private: int grid_size_; int kernel_size_; float threshold_; }; REGISTER_KERNEL_BUILDER(Name("Backproject").Device(DEVICE_CPU).TypeConstraint<float>("T"), BackprojectOp<CPUDevice, float>); REGISTER_KERNEL_BUILDER(Name("Backproject").Device(DEVICE_CPU).TypeConstraint<double>("T"), BackprojectOp<CPUDevice, double>); bool BackprojectForwardLaucher( const float* bottom_data, const float* bottom_label, const float* bottom_depth, const float* bottom_meta_data, const float* bottom_label_3d, const int batch_size, const int height, const int width, const int channels, const int num_classes, const int num_meta_data, const int grid_size, const int kernel_size, const float threshold, float* top_data, float* top_label, float* top_flag, const Eigen::GpuDevice& d); static void BackprojectingKernel( OpKernelContext* context, const Tensor* bottom_data, const Tensor* bottom_label, const Tensor* bottom_depth, const Tensor* bottom_meta_data, const Tensor* bottom_label_3d, const int batch_size, const int height, const int width, const int channels, const int num_classes, const int num_meta_data, const int grid_size, const int kernel_size, const float threshold, const TensorShape& tensor_output_shape, const TensorShape& tensor_output_shape_label, const TensorShape& tensor_output_shape_flag) { Tensor* top_data = nullptr; Tensor* top_label = nullptr; Tensor* top_flag = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, tensor_output_shape, &top_data)); OP_REQUIRES_OK(context, context->allocate_output(1, tensor_output_shape_label, &top_label)); OP_REQUIRES_OK(context, context->allocate_output(2, tensor_output_shape_flag, &top_flag)); if (!context->status().ok()) { return; } BackprojectForwardLaucher( bottom_data->flat<float>().data(), bottom_label->flat<float>().data(), bottom_depth->flat<float>().data(), bottom_meta_data->flat<float>().data(), bottom_label_3d->flat<float>().data(), batch_size, height, width, channels, num_classes, num_meta_data, grid_size, kernel_size, threshold, top_data->flat<float>().data(), top_label->flat<float>().data(), top_flag->flat<float>().data(), context->eigen_device<Eigen::GpuDevice>()); } template <class T> class BackprojectOp<Eigen::GpuDevice, T> : public OpKernel { public: typedef Eigen::GpuDevice Device; explicit BackprojectOp(OpKernelConstruction* context) : OpKernel(context) { // Get the grid size OP_REQUIRES_OK(context, context->GetAttr("grid_size", &grid_size_)); // Check that grid size is positive OP_REQUIRES(context, grid_size_ >= 0, errors::InvalidArgument("Need grid_size >= 0, got ", grid_size_)); // Get the kernel size OP_REQUIRES_OK(context, context->GetAttr("kernel_size", &kernel_size_)); // Check that kernel size is positive OP_REQUIRES(context, kernel_size_ >= 0, errors::InvalidArgument("Need kernel_size >= 0, got ", kernel_size_)); // Get the threshold OP_REQUIRES_OK(context, context->GetAttr("threshold", &threshold_)); // Check that threshold is positive OP_REQUIRES(context, threshold_ >= 0, errors::InvalidArgument("Need threshold >= 0, got ", threshold_)); } void Compute(OpKernelContext* context) override { // Grab the input tensor const Tensor& bottom_data = context->input(0); const Tensor& bottom_label = context->input(1); const Tensor& bottom_depth = context->input(2); const Tensor& bottom_meta_data = context->input(3); const Tensor& bottom_label_3d = context->input(4); // data should have 4 dimensions. OP_REQUIRES(context, bottom_data.dims() == 4, errors::InvalidArgument("data must be 4-dimensional")); OP_REQUIRES(context, bottom_label.dims() == 4, errors::InvalidArgument("label must be 4-dimensional")); OP_REQUIRES(context, bottom_depth.dims() == 4, errors::InvalidArgument("depth must be 4-dimensional")); OP_REQUIRES(context, bottom_meta_data.dims() == 4, errors::InvalidArgument("meta data must be 4-dimensional")); OP_REQUIRES(context, bottom_label_3d.dims() == 5, errors::InvalidArgument("label 3D must be 5-dimensional")); // batch size int batch_size = bottom_data.dim_size(0); // height int height = bottom_data.dim_size(1); // width int width = bottom_data.dim_size(2); // Number of channels int num_channels = bottom_data.dim_size(3); int num_classes = bottom_label.dim_size(3); int num_meta_data = bottom_meta_data.dim_size(3); // Create output tensors // top_data int dims[5]; dims[0] = batch_size; dims[1] = grid_size_; dims[2] = grid_size_; dims[3] = grid_size_; dims[4] = num_channels; TensorShape output_shape; TensorShapeUtils::MakeShape(dims, 5, &output_shape); // top flag TensorShape output_shape_flag; TensorShapeUtils::MakeShape(dims, 5, &output_shape_flag); // top label dims[4] = num_classes; TensorShape output_shape_label; TensorShapeUtils::MakeShape(dims, 5, &output_shape_label); BackprojectingKernel(context, &bottom_data, &bottom_label, &bottom_depth, &bottom_meta_data, &bottom_label_3d, batch_size, height, width, num_channels, num_classes, num_meta_data, grid_size_, kernel_size_, threshold_, output_shape, output_shape_label, output_shape_flag); } private: int grid_size_; int kernel_size_; float threshold_; }; REGISTER_KERNEL_BUILDER(Name("Backproject").Device(DEVICE_GPU).TypeConstraint<float>("T"), BackprojectOp<Eigen::GpuDevice, float>); bool BackprojectBackwardLaucher(const float* top_diff, const float* bottom_depth, const float* bottom_meta_data, const int batch_size, const int height, const int width, const int channels, const int num_meta_data, const int grid_size, float* bottom_diff, const Eigen::GpuDevice& d); static void BackprojectingGradKernel( OpKernelContext* context, const Tensor* bottom_depth, const Tensor* bottom_meta_data, const Tensor* out_backprop, const int batch_size, const int height, const int width, const int channels, const int num_meta_data, const int grid_size, const TensorShape& tensor_output_shape) { Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, tensor_output_shape, &output)); if (!context->status().ok()) { return; } BackprojectBackwardLaucher( out_backprop->flat<float>().data(), bottom_depth->flat<float>().data(), bottom_meta_data->flat<float>().data(), batch_size, height, width, channels, num_meta_data, grid_size, output->flat<float>().data(), context->eigen_device<Eigen::GpuDevice>()); } // compute gradient template <class Device, class T> class BackprojectGradOp : public OpKernel { public: explicit BackprojectGradOp(OpKernelConstruction* context) : OpKernel(context) { // Get the grid size OP_REQUIRES_OK(context, context->GetAttr("grid_size", &grid_size_)); // Check that grid size is positive OP_REQUIRES(context, grid_size_ >= 0, errors::InvalidArgument("Need grid_size >= 0, got ", grid_size_)); // Get the kernel size OP_REQUIRES_OK(context, context->GetAttr("kernel_size", &kernel_size_)); // Check that kernel size is positive OP_REQUIRES(context, kernel_size_ >= 0, errors::InvalidArgument("Need kernel_size >= 0, got ", kernel_size_)); // Get the threshold OP_REQUIRES_OK(context, context->GetAttr("threshold", &threshold_)); // Check that threshold is positive OP_REQUIRES(context, threshold_ >= 0, errors::InvalidArgument("Need threshold >= 0, got ", threshold_)); } void Compute(OpKernelContext* context) override { // Grab the input tensor const Tensor& bottom_data = context->input(0); const Tensor& bottom_depth = context->input(1); const Tensor& bottom_meta_data = context->input(2); const Tensor& out_backprop = context->input(3); // data should have 4 dimensions. OP_REQUIRES(context, bottom_data.dims() == 4, errors::InvalidArgument("data must be 4-dimensional")); OP_REQUIRES(context, bottom_depth.dims() == 4, errors::InvalidArgument("depth must be 4-dimensional")); OP_REQUIRES(context, bottom_meta_data.dims() == 4, errors::InvalidArgument("meta data must be 4-dimensional")); // batch size int batch_size = bottom_data.dim_size(0); // height int height = bottom_data.dim_size(1); // width int width = bottom_data.dim_size(2); // number of channels int num_channels = bottom_data.dim_size(3); int num_meta_data = bottom_meta_data.dim_size(3); // construct the output shape TensorShape output_shape = bottom_data.shape(); BackprojectingGradKernel( context, &bottom_depth, &bottom_meta_data, &out_backprop, batch_size, height, width, num_channels, num_meta_data, grid_size_, output_shape); } private: int grid_size_; int kernel_size_; float threshold_; }; REGISTER_KERNEL_BUILDER(Name("BackprojectGrad").Device(DEVICE_GPU).TypeConstraint<float>("T"), BackprojectGradOp<Eigen::GpuDevice, float>);
41.135983
181
0.650003
aditya2592
061478842688533a52c569a891f65709f1ec7aae
1,019
hpp
C++
src/rendering.hpp
IsaacWoods/Islands
d4b14b34884ca3f7ba1a97670dfef653b207befa
[ "MIT" ]
null
null
null
src/rendering.hpp
IsaacWoods/Islands
d4b14b34884ca3f7ba1a97670dfef653b207befa
[ "MIT" ]
null
null
null
src/rendering.hpp
IsaacWoods/Islands
d4b14b34884ca3f7ba1a97670dfef653b207befa
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017, Isaac Woods. * See LICENCE.md */ #pragma once #include <gl3w.hpp> #include <maths.hpp> #include <asset.hpp> #include <entity.hpp> // --- Mesh --- struct Mesh { Mesh(const MeshData& meshData); ~Mesh(); unsigned int numElements; GLuint vao; GLuint vbo; GLuint ebo; }; void DrawMesh(Mesh& mesh); // --- Shaders --- struct Shader { Shader(const char* basePath); ~Shader(); GLuint handle; unsigned int textureCount; }; void UseShader(Shader& shader); template<typename T> void SetUniform(Shader& shader, const char* name, const T& value); // --- Textures --- struct Texture { Texture(const char* path); ~Texture(); GLuint handle; unsigned int width; unsigned int height; }; // --- Rendering --- struct Renderer { Renderer(unsigned int width, unsigned int height); void StartFrame(); void RenderEntity(Entity* entity); void EndFrame(); unsigned int width; unsigned int height; Shader shader; Mat<4u> projection; };
15.676923
87
0.651619
IsaacWoods
06152794f908bf3e64221aa248a849a27758b2a4
5,957
cxx
C++
main/io/test/testcomponent.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/io/test/testcomponent.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/io/test/testcomponent.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_io.hxx" //------------------------------------------------------ // testcomponent - Loads a service and its testcomponent from dlls performs a test. // Expands the dll-names depending on the actual environment. // Example : testcomponent stardiv.uno.io.Pipe stm // // Therefor the testcode must exist in teststm and the testservice must be named test.stardiv.uno.io.Pipe // #include <stdio.h> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/test/XSimpleTest.hpp> #include <cppuhelper/servicefactory.hxx> using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::test; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; // Needed to switch on solaris threads int main (int argc, char **argv) { if( argc < 3) { printf( "usage : testcomponent service dll [additional dlls]\n" ); exit( 0 ); } // create service manager Reference< XMultiServiceFactory > xSMgr = createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ) ); Reference < XImplementationRegistration > xReg; Reference < XSimpleRegistry > xSimpleReg; try { // Create registration service Reference < XInterface > x = xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) ); xReg = Reference< XImplementationRegistration > ( x , UNO_QUERY ); } catch( Exception & ) { printf( "Couldn't create ImplementationRegistration service\n" ); exit(1); } sal_Char szBuf[1024]; OString sTestName; try { // Load dll for the tested component for( int n = 2 ; n <argc ; n ++ ) { OUString aDllName = OStringToOUString( argv[n] , RTL_TEXTENCODING_ASCII_US ); xReg->registerImplementation( OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ), aDllName, xSimpleReg ); } } catch( Exception &e ) { printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() ); exit(1); } try { // Load dll for the test component sTestName = "test"; sTestName += argv[2]; #if defined(SAL_W32) || defined(SAL_OS2) OUString aDllName = OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ); #else OUString aDllName = OUString::createFromAscii("lib"); aDllName += OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ); aDllName += OUString::createFromAscii(".so"); #endif xReg->registerImplementation( OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ) , aDllName, xSimpleReg ); } catch( Exception & e ) { printf( "Couldn't reach dll %s\n" , szBuf ); exit(1); } // Instantiate test service sTestName = "test."; sTestName += argv[1]; Reference < XInterface > xIntTest = xSMgr->createInstance( OStringToOUString( sTestName , RTL_TEXTENCODING_ASCII_US ) ); Reference< XSimpleTest > xTest( xIntTest , UNO_QUERY ); if( ! xTest.is() ) { printf( "Couldn't instantiate test service \n" ); exit( 1 ); } sal_Int32 nHandle = 0; sal_Int32 nNewHandle; sal_Int32 nErrorCount = 0; sal_Int32 nWarningCount = 0; // loop until all test are performed while( nHandle != -1 ) { // Instantiate serivce Reference< XInterface > x = xSMgr->createInstance( OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) ); if( ! x.is() ) { printf( "Couldn't instantiate service !\n" ); exit( 1 ); } // do the test try { nNewHandle = xTest->test( OStringToOUString( argv[1] , RTL_TEXTENCODING_ASCII_US ) , x , nHandle ); } catch( Exception & e ) { OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); printf( "testcomponent : uncaught exception %s\n" , o.getStr() ); exit(1); } catch( ... ) { printf( "testcomponent : uncaught unknown exception\n" ); exit(1); } // print errors and warning Sequence<OUString> seqErrors = xTest->getErrors(); Sequence<OUString> seqWarnings = xTest->getWarnings(); if( seqWarnings.getLength() > nWarningCount ) { printf( "Warnings during test %d!\n" , nHandle ); for( ; nWarningCount < seqWarnings.getLength() ; nWarningCount ++ ) { OString o = OUStringToOString( seqWarnings.getArray()[nWarningCount], RTL_TEXTENCODING_ASCII_US ); printf( "Warning\n%s\n---------\n" , o.getStr() ); } } if( seqErrors.getLength() > nErrorCount ) { printf( "Errors during test %d!\n" , nHandle ); for( ; nErrorCount < seqErrors.getLength() ; nErrorCount ++ ) { OString o = OUStringToOString( seqErrors.getArray()[nErrorCount], RTL_TEXTENCODING_ASCII_US ); printf( "%s\n" , o.getStr() ); } } nHandle = nNewHandle; } if( xTest->testPassed() ) { printf( "Test passed !\n" ); } else { printf( "Test failed !\n" ); } Reference <XComponent > rComp( xSMgr , UNO_QUERY ); rComp->dispose(); return 0; }
27.836449
105
0.671479
Grosskopf
0615fe2d21d35e02f9957a6dcc70cad407e9469e
1,867
cpp
C++
modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.cpp
Oskg/pp_2021_autumn
c05d35f4d4b324cc13e58188b4a0c0174f891976
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.cpp
Oskg/pp_2021_autumn
c05d35f4d4b324cc13e58188b4a0c0174f891976
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.cpp
Oskg/pp_2021_autumn
c05d35f4d4b324cc13e58188b4a0c0174f891976
[ "BSD-3-Clause" ]
3
2022-02-23T14:20:50.000Z
2022-03-30T09:00:02.000Z
// Copyright 2021 Vitulin Ivan 381908-1 #include <mpi.h> #include <vector> #include <random> #include <algorithm> #include "../../../modules/task_1/vitulin_i_sum_vector_elements/sum_vector_elements.h" std::vector<int> getRandomVectorElements(int vector_size, int k) { std::random_device dev; std::mt19937 gen(dev()); std::vector<int> vect(vector_size); for (int i = 0; i < vector_size; i++) { vect[i] = gen() % k; } return vect; } int getSumOfVectorElementsSequentially(std::vector<int> vect) { const int vector_size = vect.size(); int sum_vect_elements = 0; for (int i = 0; i < vector_size; i++) { sum_vect_elements += vect[i]; } return sum_vect_elements; } int getSumOfVectorElementsParallelly(std::vector<int> global_vector, int count_size_vec) { int ProcessNum, ProcessRank; MPI_Comm_size(MPI_COMM_WORLD, &ProcessNum); MPI_Comm_rank(MPI_COMM_WORLD, &ProcessRank); int addition = ProcessNum - count_size_vec % ProcessNum; for (int i = 0; i < addition; i++) { global_vector.push_back(0); count_size_vec++; } int local_part = count_size_vec / ProcessNum; std::vector<int> local_vector(local_part); if (ProcessRank == 0) { for (int i = 1; i < ProcessNum; i++) { MPI_Send(&global_vector[0] + i * local_part, local_part, MPI_INT, i, 1, MPI_COMM_WORLD); } local_vector = std::vector<int>(global_vector.begin(), global_vector.begin() + local_part); } else { MPI_Status status; MPI_Recv(&local_vector[0], local_part, MPI_INT, 0, 1, MPI_COMM_WORLD, &status); } int global_sum_elements = 0; int local_sum_elements = getSumOfVectorElementsSequentially(local_vector); MPI_Reduce(&local_sum_elements, &global_sum_elements, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); return global_sum_elements; }
35.226415
100
0.677022
Oskg
061635a4452d766021fcb322ad836e7e98c9d49d
1,942
cpp
C++
src/main.cpp
dleliuhin/cservice_template
63d47faee1065e3615c47ebfd222b49cbd8b7bd8
[ "DOC" ]
null
null
null
src/main.cpp
dleliuhin/cservice_template
63d47faee1065e3615c47ebfd222b49cbd8b7bd8
[ "DOC" ]
null
null
null
src/main.cpp
dleliuhin/cservice_template
63d47faee1065e3615c47ebfd222b49cbd8b7bd8
[ "DOC" ]
1
2021-08-06T22:15:04.000Z
2021-08-06T22:15:04.000Z
/*! \file main.cpp * \brief Entry app file. * * \authors Dmitrii Leliuhin * \date July 2020 * * Details. * */ //======================================================================================= #include "subscribe.h" #include "config.h" #include "core.h" #include "publish.h" #ifdef GUI #include "view.h" #endif #include "args_parser/arguments.h" #include "vapplication.h" #include "vthread.h" #include <iostream> //======================================================================================= /*! \fn int main( int argc, char **argv ) * \brief Entry point. * * Execution of the program starts here. * * \param[in] argc Number of arguments. * \param[in] argv List of arguments. * * \return App exit status. */ int main( int argc, char **argv ) { // Parse config && create PID service::arguments sargs( argc, argv, "cservice_template", Config::by_default() ); Config config; { config.capture( sargs.settings() ); config.logs.setup(); } //----------------------------------------------------------------------------------- // Link signals -> slots Subscribe subscriber( config ); Publish publisher( config ); Core core( config ); subscriber.received.link( &core, &Core::run ); core.processed.link( &publisher, &Publish::send ); //----------------------------------------------------------------------------------- // GUI in separate thread #ifdef GUI vthread thread; thread.invoke( [&] { View viewer( sargs.app_name() ); core.plot_data.link( &viewer, &View::plot ); viewer.run(); } ); #endif //----------------------------------------------------------------------------------- vapplication::poll(); return EXIT_SUCCESS; } //=======================================================================================
22.847059
89
0.427909
dleliuhin
06195fc4d3b2d3ace8a68c46f5f6bbdfeef5bc79
1,022
cpp
C++
assignment_4/src/main.cpp
gabryon99/spm-2122
a4684d3a1182eff40293779e676117f1e28338d8
[ "Unlicense" ]
null
null
null
assignment_4/src/main.cpp
gabryon99/spm-2122
a4684d3a1182eff40293779e676117f1e28338d8
[ "Unlicense" ]
null
null
null
assignment_4/src/main.cpp
gabryon99/spm-2122
a4684d3a1182eff40293779e676117f1e28338d8
[ "Unlicense" ]
null
null
null
#include <assignmentconfig.h> #include <argparse/argparse.hpp> #include <spmutility.hpp> #include <threadpool.hpp> int main(int argc, char **argv) { using namespace std::chrono_literals; argparse::ArgumentParser program(Assignment_PROJECT_NAME); auto nw = std::thread::hardware_concurrency(); program.add_argument("-nw", "--parallel-degree") .help("Parallel degree of the program") .default_value(nw) .scan<'i', int>(); try { program.parse_args(argc, argv); } catch (const std::runtime_error &err) { std::fprintf(stderr, "Got an exception during parsing: %s\n", err.what()); return EXIT_FAILURE; } spm::threadpool pool(program.get<int>("-nw")); auto task_3s = pool.submit( [](int time) -> int { std::this_thread::sleep_for(1s * time); return time; }, 3); std::cout << "Value got: " << task_3s->get() << "\n"; pool.shutdown(); return EXIT_SUCCESS; }
26.205128
69
0.591977
gabryon99