hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
0a750d73521961c3018afd4169f4b16dbc4806e5
1,672
cxx
C++
sw/vtk_scripts/translate_stl/translate_stl.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
4
2019-05-30T01:52:12.000Z
2021-09-29T21:12:13.000Z
sw/vtk_scripts/translate_stl/translate_stl.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
null
null
null
sw/vtk_scripts/translate_stl/translate_stl.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
2
2019-08-30T23:36:13.000Z
2019-11-08T16:52:01.000Z
#include "../common/vtk_common.h" #include <vtkPolyData.h> #include <vtkSTLReader.h> #include <vtkSmartPointer.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkTransform.h> #include <vtkTransformFilter.h> #include <vtkTriangleFilter.h> #include <vtkPolyData.h> #include <vtkTransformPolyDataFilter.h> int main ( int argc, char *argv[] ) { // printf("argc=%d\n",argc); if ( argc != 5 ) { shared_print_version(); cout << "Required parameters: [STL] [x][y][z]" << endl; cout << "OUTPUT: writes to [STL]-xlate.stl" << endl; return EXIT_FAILURE; } std::string inputFilename = argv[1]; float tx = atof(argv[2]); float ty = atof(argv[3]); float tz = atof(argv[4]); vtkSmartPointer<vtkSTLReader> reader = vtkSmartPointer<vtkSTLReader>::New(); if (!read_stl(&reader,inputFilename,true)) return -1; // Set up the transform filter vtkSmartPointer<vtkTransform> translation = vtkSmartPointer<vtkTransform>::New(); translation->Translate(tx,ty,tz); vtkSmartPointer<vtkTransformPolyDataFilter> transformFilter = vtkSmartPointer<vtkTransformPolyDataFilter>::New(); transformFilter->SetInputConnection(reader->GetOutputPort()); transformFilter->SetTransform(translation); transformFilter->Update(); // write to output STL vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); polyData = transformFilter->GetOutput(); if (!write_stl(inputFilename, polyData, "xlate", true)) return -1; return EXIT_SUCCESS; }
30.4
117
0.691986
[ "transform" ]
0a856a6c981a61706e814274064b9caad82b6f46
5,575
cpp
C++
python/dev/cpp/basic/src/gecko.cpp
MomsFriendlyRobotCompany/gecko
f340381113bdb423a39d47aaee61e013bb9e002a
[ "MIT" ]
3
2019-06-13T07:52:12.000Z
2020-07-05T13:28:43.000Z
python/dev/cpp/basic/src/gecko.cpp
MomsFriendlyRobotCompany/gecko
f340381113bdb423a39d47aaee61e013bb9e002a
[ "MIT" ]
23
2017-07-07T01:29:33.000Z
2018-11-23T18:41:08.000Z
python/dev/cpp/basic/src/gecko.cpp
MomsFriendlyRobotCompany/gecko
f340381113bdb423a39d47aaee61e013bb9e002a
[ "MIT" ]
null
null
null
#include "gecko.hpp" #include <iostream> #include <string> #include <stdio.h> #include "transport.hpp" #include "network.hpp" #include "rep_req.pb.h" #include "signals.hpp" #include "time.hpp" #include "helpers.hpp" using namespace std; // using namespace gecko; using namespace msg; /* This holds the static info for this thread/process. User will never call this but just access it via the functions below. */ class Singleton: public SigCapture { public: static Singleton& get() { // Since it's a static variable, if the class has already been created, // it won't be created again. // And it **is** thread-safe in C++11. static Singleton myInstance; // Return a reference to our instance. return myInstance; } // delete copy and move constructors and assign operators Singleton(Singleton const&) = delete; // Copy construct Singleton(Singleton&&) = delete; // Move construct Singleton& operator=(Singleton const&) = delete; // Copy assign Singleton& operator=(Singleton &&) = delete; // Move assign // Any other public methods. void print(){ cout << "[GeckoCore]--------------------------" << endl; cout << " Status: " << ((core_found) ? "Core Found" : "Core Unknown") << endl; cout << " Core: " << core_addr << endl; cout << " Host: " << host_addr << endl; } string core_addr; // address geckocore runs at string host_addr; // address of the system this process/thread runs at vector<Subscriber*> subs; bool initialized; // has geckocore been initialized yet? bool core_found; protected: Singleton(): initialized(false), core_found(false) { cout << "GeckoCore: constructor" << endl; } ~Singleton() { cout << "GeckoCore: destructor" << endl; for (auto const& p: subs) delete p; subs.clear(); } }; ////////////////////////////////////////////////////////////////////////// /* core: tcp://x.x.x.x:port return: found core true/false */ bool pingCore(string& core){ Request req(core); zmq::message_t msg("ping", 4); zmq::message_t resp = req.get(msg); string s(static_cast<char*>(resp.data()), resp.size()); // bool ret = false; // if (s == "ok") ret = true; // return ret; return (s == "ok"); } /* core: x.x.x.x:port topic: topic name return: tcp://1.2.3.4:1234 */ string getTopic(string& core, string& topic){ Request req(core); string msg = string("get:") + topic; zmq::message_t m((void*)msg.data(), msg.size()); // resp = tcp://1.2.3.4:1234 zmq::message_t resp = req.get(m); string addr(static_cast<char*>(resp.data()), resp.size()); cout << "getTopic: " << addr << endl; return addr; } /** core: tcp://1.2.3.4:1234 topic: topic name return: success true/false */ bool setTopic(const string& core, const string& topic){ Request req(core); string msg = string("set:") + topic; zmq::message_t m((void*)msg.data(), msg.size()); // resp = ok/fail zmq::message_t resp = req.get(m); string status(static_cast<char*>(resp.data()), resp.size()); return (status == "ok"); } void gecko::init(int argc, char* argv[]){ // do getop to find core printf("\n*** FIXME ***\n"); init(); } void gecko::init(const string& c){ if (Singleton::get().core_found) return; HostInfo h = HostInfo(); Singleton::get().host_addr = h.addr; if (c.empty()) Singleton::get().core_addr = zmqTCP(h.addr, ":11311"); else Singleton::get().core_addr = zmqTCP(c, ":11311"); bool found = pingCore(Singleton::get().core_addr); if (found) Singleton::get().core_found = true; else { cout << "*** Couldn't find GeckoCore [" << Singleton::get().core_addr << "] ***" << endl; // exit(1); } Singleton::get().print(); } bool gecko::ok(){ return Singleton::get().isOk(); } Publisher* gecko::advertise(string topic, int queue, bool bind){ string addr = zmqTCP(Singleton::get().host_addr ); // bind to next available port Publisher *p = new Publisher(addr, true); return p; } Subscriber* gecko::subscribe(string topic, void(*cb)(zmq::message_t&), int queue, bool bind){ // Singleton gc = Singleton::Instance(); Request req(Singleton::get().core_addr); // zmq::message_t reqt(topic.c_str(), topic.size()); // zmq::message_t respt = req.get(reqt); // // string m(static_cast<char*>(respt.data()), respt.size()); // vector<string> toks = split(m, ':'); // host:topic:addr:port // // string addr = zmqTCP(toks[2], toks[3]); string addr = getTopic(Singleton::get().core_addr, topic); Subscriber *s = new Subscriber(addr, topic, bind); if(cb != nullptr) s->setCallback(cb); Singleton::get().subs.push_back(s); return s; } void gecko::spin(int hertz){ Rate rate(hertz); while(gecko::ok()){ // for(int i=0; i < Singleton::get().subs.size(); ++i){ // zmq::message_t msg = Singleton::get().subs[i]->recv(); // } for (auto const& p: Singleton::get().subs){ zmq::message_t msg = p->recv_nb(); p->callback(msg); } rate.sleep(); } // clean up // for(int i=0; i < Singleton::get().subs.size(); ++i) delete Singleton::get().subs[i]; for (auto const& p: Singleton::get().subs) delete p; Singleton::get().subs.clear(); } void gecko::loginfo(std::string msg){ cout << "[INFO]: " << msg << endl; }
28.299492
97
0.582601
[ "vector" ]
0a8ac161586348596889dfb8b0f5dc5f77f60eee
2,708
cpp
C++
src/search_engine/relja_retrival/v2/indexing/train/flat_desc_file.cpp
alexanderwilkinson/visenew
8e494355b0f88466c0abb4b8f3bfecc150b91111
[ "ImageMagick", "BSD-2-Clause" ]
43
2017-07-06T23:44:39.000Z
2022-03-25T06:53:29.000Z
src/search_engine/relja_retrival/v2/indexing/train/flat_desc_file.cpp
alexanderwilkinson/visenew
8e494355b0f88466c0abb4b8f3bfecc150b91111
[ "ImageMagick", "BSD-2-Clause" ]
2
2018-11-09T03:52:14.000Z
2020-03-25T14:08:33.000Z
src/search_engine/relja_retrival/v2/indexing/train/flat_desc_file.cpp
alexanderwilkinson/visenew
8e494355b0f88466c0abb4b8f3bfecc150b91111
[ "ImageMagick", "BSD-2-Clause" ]
9
2017-07-27T10:55:55.000Z
2020-12-15T13:42:43.000Z
/* ==== Author: Relja Arandjelovic (relja@robots.ox.ac.uk) Visual Geometry Group, Department of Engineering Science University of Oxford ==== Copyright: The library belongs to Relja Arandjelovic and the University of Oxford. No usage or redistribution is allowed without explicit permission. */ #include "flat_desc_file.h" #include "desc_to_hell.h" namespace buildIndex { flatDescsFile::flatDescsFile(std::string const descsFn, bool const doHellinger) : doHellinger_(doHellinger) { f_= fopen(descsFn.c_str(), "rb"); ASSERT(f_!=NULL); uint64_t fileSize= util::fileSize(descsFn); int temp_; temp_= fread(&numDims_, sizeof(numDims_), 1, f_); temp_= fread(&dtypeCode_, sizeof(dtypeCode_), 1, f_); REMOVE_UNUSED_WARNING(temp_); ASSERT( dtypeCode_==0 || dtypeCode_==4 ); uint8_t size= dtypeCode_==0 ? 1 : sizeof(float); ASSERT( (fileSize-5) % (numDims_*size) == 0 ); numDescs_= static_cast<uint32_t>( (fileSize-5) / (numDims_*size) ); fd_= fileno(f_); } void flatDescsFile::getDescs(uint32_t start, uint32_t end, float *&descs) const { ASSERT(end>=start); descs= new float[(end-start)*numDims_]; int temp_; if (dtypeCode_==0){ uint8_t *descsRaw= new uint8_t[(end-start)*numDims_]; #ifdef _WIN32 _fseeki64(f_, static_cast<uint64_t>(start)* numDims_ + 5, SEEK_SET); temp_ = fread(descsRaw, sizeof(uint8_t), (end - start) * numDims_, f_); #elif __APPLE__ temp_ = pread(fd_, descsRaw, (end - start) * numDims_, static_cast<uint64_t>(start)* numDims_ + 5); #else temp_ = pread64(fd_, descsRaw, (end - start) * numDims_, static_cast<uint64_t>(start)* numDims_ + 5); #endif uint8_t const *inIter= descsRaw; float *outIter= descs; float *outIterEnd= descs + (end-start)*numDims_; for (; outIter!=outIterEnd; ++inIter, ++outIter) *outIter= static_cast<float>(*inIter); delete []descsRaw; } else if (dtypeCode_==4) { #ifdef _WIN32 _fseeki64(f_, static_cast<uint64_t>(start) * numDims_ * sizeof(float) + 5, SEEK_SET); temp_ = fread(descs, sizeof(uint8_t), (end - start) * numDims_ * sizeof(float), f_); #elif __APPLE__ temp_ = pread(fd_, descs, (end - start) * numDims_ * sizeof(float), 5 + start * numDims_ * sizeof(float)); #else temp_ = pread64(fd_, descs, (end - start) * numDims_ * sizeof(float), 5 + start * numDims_ * sizeof(float)); #endif } else { ASSERT(0); } if (doHellinger_){ float *thisDesc= descs; for (; start!=end; ++start, thisDesc+=numDims_) descToHell::convertToHell(numDims_, thisDesc); } REMOVE_UNUSED_WARNING(temp_); } };
28.208333
116
0.650665
[ "geometry" ]
0a905869a009a575e12c3a1e7f5fced3f12e985d
6,151
cpp
C++
test/unit/phys/models/material_hamiltonians/material_lattice_NiO_test.cpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
2
2019-12-18T17:13:00.000Z
2021-07-30T01:45:30.000Z
test/unit/phys/models/material_hamiltonians/material_lattice_NiO_test.cpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
1
2020-08-13T11:03:54.000Z
2020-08-13T11:03:54.000Z
test/unit/phys/models/material_hamiltonians/material_lattice_NiO_test.cpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
1
2019-11-15T16:06:32.000Z
2019-11-15T16:06:32.000Z
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Urs R. Haehner (haehneru@itp.phys.ethz.ch) // // This file tests the specialization of material_lattice for NiO. #include "dca/phys/models/material_hamiltonians/material_lattice.hpp" #include <cmath> #include <complex> #include <vector> #include "gtest/gtest.h" #include "dca/function/domains.hpp" #include "dca/function/function.hpp" #include "dca/phys/domains/cluster/cluster_domain.hpp" #include "dca/phys/domains/cluster/cluster_domain_initializer.hpp" #include "dca/phys/domains/cluster/symmetries/point_groups/no_symmetry.hpp" #include "dca/phys/domains/cluster/cluster_domain_aliases.hpp" #include "dca/phys/parameters/model_parameters.hpp" // Helper structs since we can only template tests on types. namespace dca { namespace testing { // dca::testing:: struct NiOSymmetricStruct { static constexpr phys::models::material_name_type type = phys::models::NiO_symmetric; }; struct NiOUnsymmetricStruct { static constexpr phys::models::material_name_type type = phys::models::NiO_unsymmetric; }; } // testing } // dca template <typename T> class MaterialLatticeNiOTest : public ::testing::Test {}; typedef ::testing::Types<dca::testing::NiOSymmetricStruct, dca::testing::NiOUnsymmetricStruct> NiOTypes; TYPED_TEST_CASE(MaterialLatticeNiOTest, NiOTypes); TYPED_TEST(MaterialLatticeNiOTest, Initialize_H_0) { using namespace dca; using Lattice = phys::models::material_lattice<TypeParam::type, phys::domains::no_symmetry<3>>; using BandDmn = func::dmn<8, int>; using SpinDmn = func::dmn<2, int>; using BandSpinDmn = func::dmn_variadic<func::dmn_0<BandDmn>, func::dmn_0<SpinDmn>>; using KDmn = func::dmn<3, std::vector<double>>; const double a = Lattice::latticeConstant(); KDmn::set_elements({{0., 0., 0.}, {0., M_PI / a, 0.}, {M_PI / a, M_PI / a, M_PI / a}}); func::function<std::complex<double>, func::dmn_variadic<BandSpinDmn, BandSpinDmn, func::dmn_0<KDmn>>> H_0; phys::params::ModelParameters<phys::models::TightBindingModel<Lattice>> params; params.set_t_ij_file_name(DCA_SOURCE_DIR "/include/dca/phys/models/material_hamiltonians/NiO/t_ij_NiO.txt"); Lattice::initialize_H_0(params, H_0); // All imaginary parts should be smaller than 10^-3. for (int b1 = 0; b1 < BandDmn::dmn_size(); ++b1) for (int s1 = 0; s1 < SpinDmn::dmn_size(); ++s1) for (int b2 = 0; b2 < BandDmn::dmn_size(); ++b2) for (int s2 = 0; s2 < SpinDmn::dmn_size(); ++s2) for (int k = 0; k < KDmn::dmn_size(); ++k) EXPECT_LE(std::abs(H_0(b1, s1, b2, s2, k).imag()), 1.e-3); // All matrix elements with different spin indices should be zero. for (int b1 = 0; b1 < BandDmn::dmn_size(); ++b1) for (int b2 = 0; b2 < BandDmn::dmn_size(); ++b2) for (int k = 0; k < KDmn::dmn_size(); ++k) { EXPECT_DOUBLE_EQ(0., H_0(b1, 0, b2, 1, k).real()); EXPECT_DOUBLE_EQ(0., H_0(b1, 1, b2, 0, k).real()); } // Check some nonvanishing Hamiltonian matrix elements. EXPECT_DOUBLE_EQ(-1.7838558854405486, H_0(0, 0, 0, 0, 0).real()); EXPECT_DOUBLE_EQ(-4.452512149016615, H_0(5, 1, 5, 1, 2).real()); EXPECT_DOUBLE_EQ(1.428376402198317, H_0(6, 1, 5, 1, 2).real()); } TYPED_TEST(MaterialLatticeNiOTest, Initialize_H_interaction) { using namespace dca; using Lattice = phys::models::material_lattice<TypeParam::type, phys::domains::no_symmetry<3>>; using BandDmn = func::dmn<8, int>; using SpinDmn = func::dmn<2, int>; using BandSpinDmn = func::dmn_variadic<func::dmn_0<BandDmn>, func::dmn_0<SpinDmn>>; using CDA = dca::phys::ClusterDomainAliases<Lattice::DIMENSION>; using RClusterType = typename CDA::RClusterType; using RClusterDmn= typename CDA::RClusterDmn; const std::vector<std::vector<int>> DCA_cluster{{-2, 0, 0}, {0, -2, 0}, {0, 0, 2}}; phys::domains::cluster_domain_initializer<RClusterDmn>::execute(Lattice::initialize_r_DCA_basis(), DCA_cluster); // Get index of origin and check it. const int origin = RClusterType::origin_index(); ASSERT_DOUBLE_EQ(0., RClusterDmn::get_elements()[origin][0]); ASSERT_DOUBLE_EQ(0., RClusterDmn::get_elements()[origin][1]); ASSERT_DOUBLE_EQ(0., RClusterDmn::get_elements()[origin][2]); func::function<double, func::dmn_variadic<BandSpinDmn, BandSpinDmn, RClusterDmn>> H_interaction; phys::params::ModelParameters<phys::models::TightBindingModel<Lattice>> params; params.set_U_ij_file_name(DCA_SOURCE_DIR "/include/dca/phys/models/material_hamiltonians/NiO/U_ij_NiO.txt"); Lattice::initialize_H_interaction(H_interaction, params); // Check that the interaction is only on-site. for (int r = 0; r < RClusterDmn::dmn_size(); ++r) for (int s2 = 0; s2 < SpinDmn::dmn_size(); ++s2) for (int b2 = 0; b2 < BandDmn::dmn_size(); ++b2) for (int s1 = 0; s1 < SpinDmn::dmn_size(); ++s1) for (int b1 = 0; b1 < BandDmn::dmn_size(); ++b1) if (r != origin) EXPECT_DOUBLE_EQ(0., H_interaction(b1, s1, b2, s2, r)); // Check that there is no self-interaction (i.e. the diagonal in band and spin is zero). for (int s = 0; s < SpinDmn::dmn_size(); ++s) for (int b = 0; b < BandDmn::dmn_size(); ++b) EXPECT_DOUBLE_EQ(0., H_interaction(b, s, b, s, origin)); // Check that H_interaction is symmetric in band and spin (H_interaction is real). for (int s2 = 0; s2 < SpinDmn::dmn_size(); ++s2) for (int b2 = 0; b2 < BandDmn::dmn_size(); ++b2) for (int s1 = 0; s1 < s2; ++s1) for (int b1 = 0; b1 < b2; ++b1) EXPECT_DOUBLE_EQ(H_interaction(b1, s1, b2, s2, origin), H_interaction(b2, s2, b1, s1, origin)); // Check some values. EXPECT_DOUBLE_EQ(6.83, H_interaction(0, 0, 1, 0, origin)); EXPECT_DOUBLE_EQ(9.14, H_interaction(0, 0, 0, 1, origin)); EXPECT_DOUBLE_EQ(6.49, H_interaction(2, 0, 4, 0, origin)); }
40.735099
108
0.671761
[ "vector" ]
0a9896beb79242f20013dd1c4cdbecbb78320cb2
729
cpp
C++
reduce/run.cpp
DenisOstashov/cpp-advanced-hse
6e4317763c0a9c510d639ae1e5793a8e9549d953
[ "MIT" ]
null
null
null
reduce/run.cpp
DenisOstashov/cpp-advanced-hse
6e4317763c0a9c510d639ae1e5793a8e9549d953
[ "MIT" ]
null
null
null
reduce/run.cpp
DenisOstashov/cpp-advanced-hse
6e4317763c0a9c510d639ae1e5793a8e9549d953
[ "MIT" ]
null
null
null
#include <benchmark/benchmark.h> #include <reduce.h> #include <cstdint> #include <vector> #include <algorithm> #include "commons.h" const int kMaxSize = 1000 * 1000 * 100; uint32_t Gcd(uint32_t a, uint32_t b) { return !b ? a : Gcd(b, a % b); } const std::vector<uint32_t> kTest(GenTest<uint32_t>(kMaxSize)); const uint32_t kOkResult = std::accumulate(kTest.begin(), kTest.end(), 0u, Gcd); void Run(benchmark::State& state) { while (state.KeepRunning()) { auto result = Reduce(kTest.begin(), kTest.end(), 0u, Gcd); if (result != kOkResult) { state.SkipWithError("Incorrect reduce result"); } } } BENCHMARK(Run)->Unit(benchmark::kMillisecond)->UseRealTime(); BENCHMARK_MAIN();
25.137931
80
0.658436
[ "vector" ]
0a9e8a44759172adf5c0d6715d2acf202086c7eb
4,093
cpp
C++
src/ParametricState.cpp
virgilwjj/levenshtein_automaton
53dc79bf8d744768b4daf8bc16c5007cd2816269
[ "MIT" ]
1
2021-05-14T09:55:21.000Z
2021-05-14T09:55:21.000Z
src/ParametricState.cpp
virgilwjj/levenshtein_automaton
53dc79bf8d744768b4daf8bc16c5007cd2816269
[ "MIT" ]
null
null
null
src/ParametricState.cpp
virgilwjj/levenshtein_automaton
53dc79bf8d744768b4daf8bc16c5007cd2816269
[ "MIT" ]
null
null
null
#include <cstring> #include "../include/State.h" #include "../include/Position.h" #include "../include/ParametricState.h" #include <string> #include <algorithm> #include <stack> #include"typeinfo" namespace std { template<> struct std::hash<std::vector<int>> : public __hash_base<size_t, std::vector<int>> { size_t operator()(const std::vector<int> &__val) const noexcept { size_t s{0}; for (auto &e : __val) s += std::hash<int>()(e); return s; } }; } namespace la { ParametricState::ParametricState(State *state) { std::vector<Position*> stateMemberPositionArray = state->getMemberPositions(); int memberPositionCount = stateMemberPositionArray.size(); memberPositionBoundaryOffsetArray.resize(memberPositionCount); memberPositionEArray.resize(memberPositionCount); memberPositionTArray.resize(memberPositionCount); for (int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i]->getI() - stateMemberPositionArray[0]->getI(); memberPositionEArray[i] = stateMemberPositionArray[i]->getE(); memberPositionTArray[i] = stateMemberPositionArray[i]->getT(); } ///// } ParametricState::ParametricState(State *state, int transitionBoundaryOffset) : ParametricState{state}, transitionBoundaryOffset{transitionBoundaryOffset} {} int ParametricState::getLargestPositionOffset() { return memberPositionBoundaryOffsetArray[memberPositionBoundaryOffsetArray.size() - 1]; } int ParametricState::getTransitionBoundaryOffset() { return transitionBoundaryOffset; } State *ParametricState::createActualState(int minimalBoundary) { int memberPositionCount = memberPositionBoundaryOffsetArray.size(); std::vector<Position*> actualStateMemberPositionArray(memberPositionCount); for (int i = 0; i < memberPositionCount; i++) { int currentBoundaryOffset = memberPositionBoundaryOffsetArray[i]; int currentE = memberPositionEArray[i]; bool currentT = memberPositionTArray[i]; actualStateMemberPositionArray[i] = new Position(minimalBoundary + currentBoundaryOffset, currentE, currentT); } return new State(actualStateMemberPositionArray); } bool ParametricState::equals(ParametricState *obj) { bool areEqual = (this == obj); // 相等返回0,大于返回1,小于返回-1 if (!areEqual && obj != nullptr) { ParametricState *pState{obj}; areEqual = (this->memberPositionBoundaryOffsetArray == pState->memberPositionBoundaryOffsetArray) && (this->memberPositionEArray == pState->memberPositionEArray) && (this->memberPositionTArray == pState->memberPositionTArray); } return areEqual; } int ParametricState::hashCode() { int hash = 7; hash = 61 * hash + std::hash<std::vector<int>>()(this->memberPositionBoundaryOffsetArray); hash = 61 * hash + std::hash<std::vector<int>>()(this->memberPositionEArray); hash = 61 * hash + std::hash<std::vector<bool>>()(this->memberPositionTArray); return hash; } std::string ParametricState::toString() { std::string returnString = "i" + std::string (memberPositionTArray[0] ? "(t)" : "") + "#" + std::to_string(memberPositionEArray[0]) + ")"; int memberPositionCount = memberPositionBoundaryOffsetArray.size(); for (int i = 1; i < memberPositionCount; i++) { returnString += " (i + " + std::to_string(memberPositionBoundaryOffsetArray[i]) + ")" + (memberPositionTArray[i] ? "(t)" : "") + "(#" + std::to_string(memberPositionEArray[i]) + ")"; } if (transitionBoundaryOffset != 0) { returnString.append(" "+ std::to_string(transitionBoundaryOffset)); } return returnString; } }
34.982906
194
0.635231
[ "vector" ]
0a9e93dface6bfee4aaeabd72911b173e5f7ba49
887
cpp
C++
mainwindow.cpp
honoriocassiano/sketch-based-quadrangulation
7480b05aa8f2cb1dfbaf4e249a8184702700c2a2
[ "MIT" ]
null
null
null
mainwindow.cpp
honoriocassiano/sketch-based-quadrangulation
7480b05aa8f2cb1dfbaf4e249a8184702700c2a2
[ "MIT" ]
null
null
null
mainwindow.cpp
honoriocassiano/sketch-based-quadrangulation
7480b05aa8f2cb1dfbaf4e249a8184702700c2a2
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "application.h" #include "qdebug.h" #include "qfiledialog.h" #include "utils.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->loadMeshButton, SIGNAL(clicked()), this, SLOT(loadMesh())); connect(this, SIGNAL(notifyStatusBar(QString)), ui->statusBar, SLOT(showMessage(QString))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::loadMesh() { QString fileName = QFileDialog::getOpenFileName( this, tr("Open Mesh"), "./", tr("Poly Model (*.ply *.obj *.off)")); if (!fileName.isEmpty()) { // qDebug() << fileName; Application app; Status status = app.loadMesh(fileName.toStdString()); emit notifyStatusBar(QString::fromStdString(status.message)); } }
25.342857
75
0.64487
[ "mesh", "model" ]
0aacd254781683544c1d438b8c84c8132abd16ee
1,112
cpp
C++
atcoder/arc/arc021_c.cpp
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
1
2018-11-12T15:18:55.000Z
2018-11-12T15:18:55.000Z
atcoder/arc/arc021_c.cpp
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
null
null
null
atcoder/arc/arc021_c.cpp
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> P; typedef pair<ll, ll> Pll; typedef vector<int> Vi; typedef tuple<int, int, int> T; #define FOR(i,s,x) for(int i=s;i<(int)(x);i++) #define REP(i,x) FOR(i,0,x) #define ALL(c) c.begin(), c.end() #define DUMP( x ) cerr << #x << " = " << ( x ) << endl ll K, N; ll A[100010], D[100010]; bool check(ll V) { ll cnt = 0; REP(i, N) { if (V + D[i] - A[i] > 0) { cnt +=(ll)floor(1.0 * (V + D[i] - A[i]) / D[i]); } if (cnt >= K) return true; } return false; } int main() { scanf("%lld %lld", &K, &N); REP(i, N) scanf("%lld %lld", A+i, D+i); ll left = 0, right = (ll)1e11; while (left + 1 < right) { ll mid = (left + right) / 2; if (check(mid)) { right = mid; } else { left = mid; } } ll V = right, ans = 0, cnt = 0; REP(i, N) { if (V + D[i] - A[i] > 0) { ll c = (ll)floor(1.0 * (V + D[i] - A[i]) / D[i]); ans += c * A[i] + D[i] * (c * (c - 1) / 2); cnt += c; } } ans -= V * (cnt - K); printf("%lld\n", ans); return 0; }
20.592593
55
0.466727
[ "vector" ]
0ab09aea3357d332f4ab24da20e32d38a8d2d829
4,042
cpp
C++
client/src/ClientProtocolExecutor.cpp
kosiacz3q/IRC
bef36e8321b15763c1826c903f9a976a5f51ba58
[ "MIT" ]
null
null
null
client/src/ClientProtocolExecutor.cpp
kosiacz3q/IRC
bef36e8321b15763c1826c903f9a976a5f51ba58
[ "MIT" ]
null
null
null
client/src/ClientProtocolExecutor.cpp
kosiacz3q/IRC
bef36e8321b15763c1826c903f9a976a5f51ba58
[ "MIT" ]
null
null
null
#include "ClientProtocolExecutor.h" #include <unistd.h> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include "jsonParserFwd.h" #include "coreFwd.h" ClientProtocolExecutor::ClientProtocolExecutor( core::IQueueHandlerPtr queueHandler, core::IDisplayerPtr displayer, IRequestResponseManagerPtr requestResponseManager, core::ClientDataPtr clientData, MessageListenerControllerPtr messageController, NotificationsHandlerPtr notificationsHandler) : _queueHandler(queueHandler), _displayer(displayer), _running(false), _reading(false), _pendingCommands(core::AtomicContainer<std::string>(getpid() % 9999)), _requestCounter(0), _requestResponseManager(requestResponseManager), _clientData(clientData), _messageController(messageController), _notificationsHandler(notificationsHandler) { } ClientProtocolExecutor::~ClientProtocolExecutor() { } void ClientProtocolExecutor::addCommand(std::string command) { _pendingCommands.pushBack(command); } void ClientProtocolExecutor::execute() { _running = true; while (_running) { if (!_pendingCommands.empty()) { handleCommand(_pendingCommands.popFirst()); } } if(_readerThreadPtr) _readerThreadPtr->join(); } void ClientProtocolExecutor::readRoutine() { while (_messageController->isReadingEnable()) { auto income = std::string(_queueHandler->getMessage(_clientData->Id).c_str()); if(!income.empty() && _messageController->isReadingEnable()) { rapidjson::Document incomingRequest; incomingRequest.Parse(income.c_str()); if(incomingRequest.HasMember("request_id") && incomingRequest.HasMember("status")) { auto responseHandler = _commandToHandler.find(_requestResponseManager->getHandler(incomingRequest["request_id"].GetInt())); if (std::string("UNKNOWN_REQUEST").compare(incomingRequest["status"].GetString()) == 0) { _displayer->displayLine("Unknown request"); } else if (responseHandler != _commandToHandler.end()) { responseHandler->second->handleResponse(incomingRequest); } else { _displayer->displayLine("Unknown request id"); } } else if(incomingRequest.HasMember("notification_id")) { _notificationsHandler->handle(incomingRequest); } else { _displayer->displayLine("Corrupted server response"); } } } } void ClientProtocolExecutor::handleCommand(std::string command) { if (!command.empty() && command[0] == '#') { boost::char_separator<char> sep(" "); boost::tokenizer<boost::char_separator<char>> tokens(command, sep); if (tokens.begin()->compare("#exit") == 0) { handleCommand("#disconnect"); _running = false; } else { if (_commandToHandler.find(*tokens.begin()) != _commandToHandler.end()) { boost::trim(command); auto ddd = *tokens.begin(); auto handler = _commandToHandler.find(*tokens.begin())->second; command += " "; auto feed = command.substr((command).find_first_of(" \t")+1); handler->handle(feed); } else { handleCommand("#help " + *tokens.begin()); } } } else if (!command.empty()) { handleCommand("#sendMessage " + command); } } void ClientProtocolExecutor::registerCommand(ICommandHandlerPtr handler ) { _commandToHandler.insert(std::pair<std::string, ICommandHandlerPtr>(handler->getCommand(), handler)); _commandToHandler.insert(std::pair<std::string, ICommandHandlerPtr>(handler->getResponseCommand(), handler)); } std::vector<std::string> ClientProtocolExecutor::getCommands() { auto result = std::vector<std::string>(); for (auto commanditer = _commandToHandler.begin(); commanditer != _commandToHandler.end(); ++commanditer ) { if (commanditer->first.find("response") >= commanditer->first.size()) result.push_back(commanditer->second->getInfo()); } result.push_back("#exit [exit]"); return result; } void ClientProtocolExecutor::startReading() { _readerThreadPtr = std::shared_ptr<std::thread>(new std::thread(&ClientProtocolExecutor::readRoutine, *this)); }
24.950617
127
0.716477
[ "vector" ]
0ab243dfd618b21f6b9528de2519155dea6fff4b
243
hpp
C++
src/hash/hasher_base.hpp
tum-db/partitioned-filters
56c20102715a442cbec9ecb732d41de15b31c828
[ "MIT" ]
5
2021-08-16T17:48:45.000Z
2022-03-10T22:53:54.000Z
src/hash/hasher_base.hpp
tum-db/partitioned-filters
56c20102715a442cbec9ecb732d41de15b31c828
[ "MIT" ]
null
null
null
src/hash/hasher_base.hpp
tum-db/partitioned-filters
56c20102715a442cbec9ecb732d41de15b31c828
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <parameter/parameter.hpp> namespace filters::hash { using HashingMode = parameter::HashingMode; template<HashingMode, typename Vector, size_t> struct Hasher { }; } // filters::hash
16.2
50
0.699588
[ "vector" ]
0aba949ad6fa0fad56d75e6ca72cad80c7edca77
2,533
cpp
C++
aws-cpp-sdk-ce/source/model/NetworkResourceUtilization.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-ce/source/model/NetworkResourceUtilization.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-ce/source/model/NetworkResourceUtilization.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ce/model/NetworkResourceUtilization.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace CostExplorer { namespace Model { NetworkResourceUtilization::NetworkResourceUtilization() : m_networkInBytesPerSecondHasBeenSet(false), m_networkOutBytesPerSecondHasBeenSet(false), m_networkPacketsInPerSecondHasBeenSet(false), m_networkPacketsOutPerSecondHasBeenSet(false) { } NetworkResourceUtilization::NetworkResourceUtilization(JsonView jsonValue) : m_networkInBytesPerSecondHasBeenSet(false), m_networkOutBytesPerSecondHasBeenSet(false), m_networkPacketsInPerSecondHasBeenSet(false), m_networkPacketsOutPerSecondHasBeenSet(false) { *this = jsonValue; } NetworkResourceUtilization& NetworkResourceUtilization::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("NetworkInBytesPerSecond")) { m_networkInBytesPerSecond = jsonValue.GetString("NetworkInBytesPerSecond"); m_networkInBytesPerSecondHasBeenSet = true; } if(jsonValue.ValueExists("NetworkOutBytesPerSecond")) { m_networkOutBytesPerSecond = jsonValue.GetString("NetworkOutBytesPerSecond"); m_networkOutBytesPerSecondHasBeenSet = true; } if(jsonValue.ValueExists("NetworkPacketsInPerSecond")) { m_networkPacketsInPerSecond = jsonValue.GetString("NetworkPacketsInPerSecond"); m_networkPacketsInPerSecondHasBeenSet = true; } if(jsonValue.ValueExists("NetworkPacketsOutPerSecond")) { m_networkPacketsOutPerSecond = jsonValue.GetString("NetworkPacketsOutPerSecond"); m_networkPacketsOutPerSecondHasBeenSet = true; } return *this; } JsonValue NetworkResourceUtilization::Jsonize() const { JsonValue payload; if(m_networkInBytesPerSecondHasBeenSet) { payload.WithString("NetworkInBytesPerSecond", m_networkInBytesPerSecond); } if(m_networkOutBytesPerSecondHasBeenSet) { payload.WithString("NetworkOutBytesPerSecond", m_networkOutBytesPerSecond); } if(m_networkPacketsInPerSecondHasBeenSet) { payload.WithString("NetworkPacketsInPerSecond", m_networkPacketsInPerSecond); } if(m_networkPacketsOutPerSecondHasBeenSet) { payload.WithString("NetworkPacketsOutPerSecond", m_networkPacketsOutPerSecond); } return payload; } } // namespace Model } // namespace CostExplorer } // namespace Aws
24.12381
86
0.789183
[ "model" ]
0abb925083e2ea2fac8698f69d34494e4a9c7b26
820
hpp
C++
graph_tree/project_selection.hpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
graph_tree/project_selection.hpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
graph_tree/project_selection.hpp
hotman78/cpplib
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
[ "CC0-1.0" ]
null
null
null
#include<atcoder/maxflow.hpp> #include<vector> #include<map> template<typename T> struct project_selection{ int n; atcoder::mf_graph<T>g; std::vector<T>a,b; std::map<pair<int,int>,T>m; project_selection(int n):n(n),g(n+2),a(n),b(n){} // i in set1 penalty void penalty1(int i,T x){ assert(i<n); a[i]+=x; } // i in set2 penalty void penalty2(int i,T x){ assert(i<n); b[i]+=x; } // i in set1, j in set2 penalty void penalty3(int i,int j,T x){ assert(i<n); assert(j<n); m[make_pair(i,j)]+=x; } T min_penalty(){ for(int i=0;i<n;++i)g.add_edge(n,i,a[i]); for(int i=0;i<n;++i)g.add_edge(i,n+1,b[i]); for(auto [s,t]:m)g.add_edge(s.first,s.second,t); return g.flow(n,n+1); } };
24.848485
56
0.529268
[ "vector" ]
0ac8b71fa979dc8c9acb46fb5734baa09a832fee
2,453
cpp
C++
src/Gui/Widgets/Button.cpp
AndrzejWoronko/WebPassWare
9af0df61a9279f1ffe8561714656265f4bec7939
[ "MIT" ]
null
null
null
src/Gui/Widgets/Button.cpp
AndrzejWoronko/WebPassWare
9af0df61a9279f1ffe8561714656265f4bec7939
[ "MIT" ]
null
null
null
src/Gui/Widgets/Button.cpp
AndrzejWoronko/WebPassWare
9af0df61a9279f1ffe8561714656265f4bec7939
[ "MIT" ]
null
null
null
#include "Button.h" #include "Style.h" /************************************************************ CButtonPrivate Class *************************************************************/ CButtonPrivate::CButtonPrivate(const QString &text, const QString &tipText, const QString &icon, QSize shape) { m_text = text; m_tipText = tipText; m_icon = icon; m_shape = shape; } CButtonPrivate::CButtonPrivate() { } bool CButtonPrivate::isNullIcon() { return m_icon.isNull() || m_icon.isEmpty(); } /************************************************************ CButton Class *************************************************************/ CButton::CButton(CButtonPrivate structure, QWidget *parent, QSize iconSize) : QPushButton(parent) { m_structure = structure; setOptions(); if(!m_structure.isNullIcon()) setIconPolicy(m_structure.getIcon(), iconSize); } void CButton::setOptions() { this->setText(m_structure.getText()); this->setStatusTip(m_structure.getTipText()); this->setToolTip(m_structure.getTipText()); this->setCursor(QCursor(Qt::PointingHandCursor)); if (m_structure.getShape().width() != -1 && m_structure.getShape().height() != -1) { this->setMinimumSize(m_structure.getShape().width(), m_structure.getShape().height()); this->setMaximumSize(m_structure.getShape().width(), m_structure.getShape().height()); } //this->setFocusPolicy(Qt::NoFocus); if (!m_structure.getText().isEmpty()) { m_buttonName = QString("BUTTON_%1").arg(m_structure.getText().toUpper()); m_buttonName.remove("&"); this->setObjectName(m_buttonName); } } void CButton::setIconPolicy(const QString &iconName, QSize iconSize) { QSize iconSizeLocal = iconSize; if (CStyle::iconFromStyleExist(iconName)) this->setIcon(CStyle::iconFromStyle(iconName)); else this->setIcon(QIcon::fromTheme(iconName)); if (iconSizeLocal.isEmpty()) { int size = m_structure.getShape().height() * 0.7; iconSizeLocal = QSize(size, size); } if(!m_structure.getText().isEmpty()) this->setIconSize(iconSize); else this->setIconSize(QSize(BUTTON_ICON_MIN_SIZE_DX, BUTTON_ICON_MIN_SIZE_DY)); } void CButton::setIconFromTheme(const QString &iconName) { this->setIcon(QIcon::fromTheme(iconName)); } QString CButton::getText(void) { return m_structure.getText(); }
27.561798
109
0.604158
[ "shape" ]
0ad0845e8c81fe51fe66e6a0aef901f843fa28db
4,554
cpp
C++
src/argument_processor_main.cpp
sea-kg/reversehash
77bd44f589cd38dff7bd4b97963134ae27a16a95
[ "MIT" ]
null
null
null
src/argument_processor_main.cpp
sea-kg/reversehash
77bd44f589cd38dff7bd4b97963134ae27a16a95
[ "MIT" ]
4
2016-05-30T18:37:26.000Z
2017-02-18T06:59:24.000Z
src/argument_processor_main.cpp
sea-kg/reversehash
77bd44f589cd38dff7bd4b97963134ae27a16a95
[ "MIT" ]
null
null
null
#include "argument_processor_main.h" #include <wsjcpp_core.h> #include "bna_test_sin.h" #include "bna_test_sin1.h" // --------------------------------------------------------------------- // ArgumentProcessorMain ArgumentProcessorMain::ArgumentProcessorMain() : WsjcppArgumentProcessor({"main"}, "Experiment for reversing md5-hash function", "Experiment for reversing md5-hash function") { TAG = "ArgumentProcessorMain"; // registrySingleArgument("--single", "What exactly do this single param?"); // registryParameterArgument("-param", "N", "What need this param?"); // registryExample("here example of command"); registryProcessor(new ArgumentProcessorTestSin()); registryProcessor(new ArgumentProcessorTestSin1()); // registryProcessor(new ArgumentProcessorStartServer()); } // --------------------------------------------------------------------- bool ArgumentProcessorMain::applySingleArgument(const std::string &sProgramName, const std::string &sArgumentName) { WsjcppLog::err(TAG, "Not implemented"); return false; } // --------------------------------------------------------------------- bool ArgumentProcessorMain::applyParameterArgument( const std::string &sProgramName, const std::string &sArgumentName, const std::string &sValue ) { WsjcppLog::err(TAG, "Not implemented"); return false; } // --------------------------------------------------------------------- int ArgumentProcessorMain::exec(const std::vector<std::string> &vRoutes, const std::vector<std::string> &vSubParams) { WsjcppLog::err(TAG, "Not implemented"); return -1; } // --------------------------------------------------------------------- // ArgumentProcessorMain ArgumentProcessorStartServer::ArgumentProcessorStartServer() : WsjcppArgumentProcessor({"start-server"}, "Start server", "Start server for visualizaion") { TAG = "ArgumentProcessorStartServer"; // registrySingleArgument("--single", "What exactly do this single param?"); // registryParameterArgument("-param", "N", "What need this param?"); // registryExample("here example of command"); // registryProcessor(new ArgumentProcessorOtherProcessor()); } // --------------------------------------------------------------------- bool ArgumentProcessorStartServer::applySingleArgument(const std::string &sProgramName, const std::string &sArgumentName) { WsjcppLog::err(TAG, "Not implemented"); return false; } // --------------------------------------------------------------------- bool ArgumentProcessorStartServer::applyParameterArgument( const std::string &sProgramName, const std::string &sArgumentName, const std::string &sValue ) { WsjcppLog::err(TAG, "Not implemented"); return false; } // --------------------------------------------------------------------- int ArgumentProcessorStartServer::exec(const std::vector<std::string> &vRoutes, const std::vector<std::string> &vSubParams) { WsjcppLog::err(TAG, "Not implemented"); // "Server starting on 43735 port" return -1; } // --------------------------------------------------------------------- // ArgumentProcessorTestSin ArgumentProcessorTestSin::ArgumentProcessorTestSin() : WsjcppArgumentProcessor({"test-sin"}, "test-sin", "test-sin") { TAG = "ArgumentProcessorTestSin"; // registrySingleArgument("--single", "What exactly do this single param?"); // registryParameterArgument("-param", "N", "What need this param?"); // registryExample("here example of command"); // registryProcessor(new ArgumentProcessorOtherProcessor()); } int ArgumentProcessorTestSin::exec(const std::vector<std::string> &vRoutes, const std::vector<std::string> &vSubParams) { BNATestSin testsin; testsin.run(); return -1; } // --------------------------------------------------------------------- // ArgumentProcessorTestSin ArgumentProcessorTestSin1::ArgumentProcessorTestSin1() : WsjcppArgumentProcessor({"test-sin1"}, "test-sin1", "test-sin1") { TAG = "ArgumentProcessorTestSin1"; // registrySingleArgument("--single", "What exactly do this single param?"); // registryParameterArgument("-param", "N", "What need this param?"); // registryExample("here example of command"); // registryProcessor(new ArgumentProcessorOtherProcessor()); } int ArgumentProcessorTestSin1::exec(const std::vector<std::string> &vRoutes, const std::vector<std::string> &vSubParams) { BNATestSin1 testsin1; testsin1.run(); return -1; }
34.5
125
0.603865
[ "vector" ]
bd5ab32217d2b852118f87e857c53cbadd55e451
17,014
cc
C++
daemon/index_primitive.cc
maaku/HyperDex
6b408e7458ce59631f7f5e9daa72f4a03984f9d8
[ "BSD-3-Clause" ]
1
2018-12-29T02:17:44.000Z
2018-12-29T02:17:44.000Z
daemon/index_primitive.cc
maaku/HyperDex
6b408e7458ce59631f7f5e9daa72f4a03984f9d8
[ "BSD-3-Clause" ]
null
null
null
daemon/index_primitive.cc
maaku/HyperDex
6b408e7458ce59631f7f5e9daa72f4a03984f9d8
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013, Cornell University // 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 HyperDex 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. // e #include <e/endian.h> // HyperDex #include "daemon/datalayer_encodings.h" #include "daemon/datalayer_iterator.h" #include "daemon/index_primitive.h" using hyperdex::datalayer; using hyperdex::index_primitive; index_primitive :: index_primitive() { } index_primitive :: ~index_primitive() throw () { } void index_primitive :: index_changes(const region_id& ri, uint16_t attr, index_info* key_ii, const e::slice& key, const e::slice* old_value, const e::slice* new_value, leveldb::WriteBatch* updates) { std::vector<char> scratch; leveldb::Slice slice; if (old_value && new_value && *old_value == *new_value) { return; } if (old_value) { index_entry(ri, attr, key_ii, key, *old_value, &scratch, &slice); updates->Delete(slice); } if (new_value) { index_entry(ri, attr, key_ii, key, *new_value, &scratch, &slice); updates->Put(slice, leveldb::Slice()); } } void index_primitive :: index_entry(const region_id& ri, uint16_t attr, std::vector<char>* scratch, leveldb::Slice* slice) { size_t sz = sizeof(uint8_t) + sizeof(uint64_t) + sizeof(uint16_t); if (scratch->size() < sz) { scratch->resize(sz); } char* ptr = &scratch->front(); ptr = e::pack8be('i', ptr); ptr = e::pack64be(ri.get(), ptr); ptr = e::pack16be(attr, ptr); assert(ptr == &scratch->front() + sz); *slice = leveldb::Slice(&scratch->front(), sz); } void index_primitive :: index_entry(const region_id& ri, uint16_t attr, const e::slice& value, std::vector<char>* scratch, leveldb::Slice* slice) { size_t val_sz = this->encoded_size(value); size_t sz = sizeof(uint8_t) + sizeof(uint64_t) + sizeof(uint16_t) + val_sz; if (scratch->size() < sz) { scratch->resize(sz); } char* ptr = &scratch->front(); ptr = e::pack8be('i', ptr); ptr = e::pack64be(ri.get(), ptr); ptr = e::pack16be(attr, ptr); ptr = this->encode(value, ptr); assert(ptr == &scratch->front() + sz); *slice = leveldb::Slice(&scratch->front(), sz); } void index_primitive :: index_entry(const region_id& ri, uint16_t attr, index_info* key_ii, const e::slice& key, const e::slice& value, std::vector<char>* scratch, leveldb::Slice* slice) { size_t key_sz = key_ii->encoded_size(key); size_t val_sz = this->encoded_size(value); bool variable = !key_ii->encoding_fixed() && !this->encoding_fixed(); size_t sz = sizeof(uint8_t) + sizeof(uint64_t) + sizeof(uint16_t) + val_sz + key_sz + (variable ? sizeof(uint32_t) : 0); if (scratch->size() < sz) { scratch->resize(sz); } char* ptr = &scratch->front(); ptr = e::pack8be('i', ptr); ptr = e::pack64be(ri.get(), ptr); ptr = e::pack16be(attr, ptr); ptr = this->encode(value, ptr); ptr = key_ii->encode(key, ptr); if (variable) { ptr = e::pack32be(key_sz, ptr); } assert(ptr == &scratch->front() + sz); *slice = leveldb::Slice(&scratch->front(), sz); } namespace { using hyperdex::index_info; using hyperdex::leveldb_iterator_ptr; using hyperdex::leveldb_snapshot_ptr; using hyperdex::range; using hyperdex::region_id; bool decode_entry(const leveldb::Slice& in, index_info* val_ii, index_info* key_ii, region_id* ri, uint16_t* attr, e::slice* val, e::slice* key) { const size_t prefix_sz = sizeof(uint8_t) + sizeof(uint64_t) + sizeof(uint16_t); if (in.size() < prefix_sz) { return false; } const char* ptr = in.data(); uint8_t type; uint64_t region; ptr = e::unpack8be(ptr, &type); ptr = e::unpack64be(ptr, &region); ptr = e::unpack16be(ptr, attr); if (type != 'i') { return false; } *ri = region_id(region); size_t rem = in.size() - prefix_sz; if (val_ii->encoding_fixed()) { size_t sz = val_ii->encoded_size(e::slice()); if (sz > rem) { return false; } *val = e::slice(in.data() + prefix_sz, sz); *key = e::slice(in.data() + prefix_sz + val->size(), rem - sz); } else if (key_ii->encoding_fixed()) { size_t sz = key_ii->encoded_size(e::slice()); if (sz > rem) { return false; } *val = e::slice(in.data() + prefix_sz, rem - sz); *key = e::slice(in.data() + prefix_sz + val->size(), sz); } else { if (rem < sizeof(uint32_t)) { return false; } uint32_t key_sz; e::unpack32be(in.data() + in.size() - sizeof(uint32_t), &key_sz); if (key_sz + sizeof(uint32_t) > rem) { return false; } *val = e::slice(in.data() + prefix_sz, rem - sizeof(uint32_t) - key_sz); *key = e::slice(in.data() + prefix_sz + val->size(), key_sz); } return true; } class range_iterator : public datalayer::index_iterator { public: range_iterator(leveldb_snapshot_ptr snap, const region_id& ri, const range& r, index_primitive* val_ii, index_info* key_ii); virtual ~range_iterator() throw (); public: virtual bool valid(); virtual void next(); virtual uint64_t cost(leveldb::DB*); virtual e::slice key(); virtual std::ostream& describe(std::ostream&) const; virtual e::slice internal_key(); virtual bool sorted(); virtual void seek(const e::slice& internal_key); private: range_iterator(const range_iterator&); range_iterator& operator = (const range_iterator&); private: leveldb_iterator_ptr m_iter; region_id m_ri; range m_range; index_primitive* m_val_ii; index_info* m_key_ii; std::vector<char> m_scratch; bool m_invalid; }; range_iterator :: range_iterator(leveldb_snapshot_ptr s, const region_id& ri, const range& r, index_primitive* val_ii, index_info* key_ii) : index_iterator(s) , m_iter() , m_ri(ri) , m_range(r) , m_val_ii(val_ii) , m_key_ii(key_ii) , m_scratch() , m_invalid(false) { leveldb::ReadOptions opts; opts.fill_cache = true; opts.verify_checksums = true; opts.snapshot = s.get(); m_iter.reset(s, s.db()->NewIterator(opts)); leveldb::Slice slice; if (m_range.has_start) { m_val_ii->index_entry(m_ri, m_range.attr, m_range.start, &m_scratch, &slice); } else { m_val_ii->index_entry(m_ri, m_range.attr, &m_scratch, &slice); } m_iter->Seek(slice); } range_iterator :: ~range_iterator() throw () { } bool range_iterator :: valid() { while (!m_invalid && m_iter->Valid()) { leveldb::Slice _k = m_iter->key(); region_id ri; uint16_t attr; e::slice v; e::slice k; if (!decode_entry(_k, m_val_ii, m_key_ii, &ri, &attr, &v, &k)) { m_invalid = true; return false; } if (m_ri < ri || m_range.attr < attr) { m_invalid = true; return false; } // if there is a start, and the current value is less than it, advance // the iterator if (m_range.has_start) { size_t sz = std::min(m_range.start.size(), v.size()); int cmp = memcmp(m_range.start.data(), v.data(), sz); if (cmp > 0 || (cmp == 0 && m_range.start.size() > v.size())) { m_iter->Next(); continue; } } // if there is an end, and the current value is greater than it, advance // the iterator. If all possible subsequent values are greater than it, // advance to the end if (m_range.has_end) { size_t sz = std::min(m_range.end.size(), v.size()); int cmp = memcmp(m_range.end.data(), v.data(), sz); if (cmp < 0) { m_invalid = true; return false; } if (cmp == 0 && m_range.end.size() < v.size()) { m_iter->Next(); continue; } // XXX this will iterate to the end, unnecessarily } return true; } return false; } void range_iterator :: next() { m_iter->Next(); } uint64_t range_iterator :: cost(leveldb::DB* db) { assert(this->sorted()); leveldb::Slice upper; if (m_range.has_end) { m_val_ii->index_entry(m_ri, m_range.attr, m_range.end, &m_scratch, &upper); } else { m_val_ii->index_entry(m_ri, m_range.attr, &m_scratch, &upper); } hyperdex::encode_bump(&m_scratch.front(), &m_scratch.front() + m_scratch.size()); // create the range leveldb::Range r; r.start = m_iter->key(); r.limit = upper; // ask leveldb for the size of the range uint64_t ret; db->GetApproximateSizes(&r, 1, &ret); return ret; } e::slice range_iterator :: key() { e::slice ik = this->internal_key(); size_t decoded_sz = m_key_ii->decoded_size(ik); if (m_scratch.size() < decoded_sz) { m_scratch.resize(decoded_sz); } m_key_ii->decode(ik, &m_scratch.front()); return e::slice(&m_scratch.front(), decoded_sz); } std::ostream& range_iterator :: describe(std::ostream& out) const { return out << "primitive range_iterator()"; } e::slice range_iterator :: internal_key() { leveldb::Slice _k = m_iter->key(); region_id ri; uint16_t attr; e::slice v; e::slice k; decode_entry(_k, m_val_ii, m_key_ii, &ri, &attr, &v, &k); return k; } bool range_iterator :: sorted() { return m_range.has_start && m_range.has_end && m_range.start == m_range.end; } void range_iterator :: seek(const e::slice& ik) { assert(sorted()); leveldb::Slice slice; m_val_ii->index_entry(m_ri, m_range.attr, m_key_ii, ik, m_range.start, &m_scratch, &slice); m_iter->Seek(slice); } class key_iterator : public datalayer::index_iterator { public: key_iterator(leveldb_snapshot_ptr snap, const region_id& ri, const range& r, index_info* key_ii); virtual ~key_iterator() throw (); public: virtual bool valid(); virtual void next(); virtual uint64_t cost(leveldb::DB*); virtual e::slice key(); virtual std::ostream& describe(std::ostream&) const; virtual e::slice internal_key(); virtual bool sorted(); virtual void seek(const e::slice& internal_key); private: key_iterator(const key_iterator&); key_iterator& operator = (const key_iterator&); private: leveldb_iterator_ptr m_iter; region_id m_ri; range m_range; index_info* m_key_ii; std::vector<char> m_scratch; bool m_invalid; }; key_iterator :: key_iterator(leveldb_snapshot_ptr s, const region_id& ri, const range& r, index_info* key_ii) : index_iterator(s) , m_iter() , m_ri(ri) , m_range(r) , m_key_ii(key_ii) , m_scratch() , m_invalid(false) { assert(m_range.attr == 0); leveldb::ReadOptions opts; opts.fill_cache = true; opts.verify_checksums = true; opts.snapshot = s.get(); m_iter.reset(s, s.db()->NewIterator(opts)); leveldb::Slice slice; if (m_range.has_start) { encode_key(m_ri, m_range.type, m_range.start, &m_scratch, &slice); } else { encode_object_region(m_ri, &m_scratch, &slice); } m_iter->Seek(slice); } key_iterator :: ~key_iterator() throw () { } bool key_iterator :: valid() { while (!m_invalid && m_iter->Valid()) { leveldb::Slice _k = m_iter->key(); region_id ri; e::slice k; if (!decode_key(_k, &ri, &k) || m_ri < ri) { m_invalid = true; return false; } if (!m_range.has_end) { return true; } size_t sz = std::min(m_range.end.size(), k.size()); int cmp = memcmp(m_range.end.data(), k.data(), sz); if (cmp > 0 || (cmp == 0 && m_range.end.size() < k.size())) { m_invalid = true; return false; } return true; } return false; } void key_iterator :: next() { m_iter->Next(); } uint64_t key_iterator :: cost(leveldb::DB* db) { assert(this->sorted()); leveldb::Slice upper; if (m_range.has_end) { encode_key(m_ri, m_range.type, m_range.end, &m_scratch, &upper); } else { encode_object_region(m_ri, &m_scratch, &upper); } hyperdex::encode_bump(&m_scratch.front(), &m_scratch.front() + m_scratch.size()); // create the range leveldb::Range r; r.start = m_iter->key(); r.limit = upper; // ask leveldb for the size of the range uint64_t ret; db->GetApproximateSizes(&r, 1, &ret); return ret; } e::slice key_iterator :: key() { e::slice ik = this->internal_key(); size_t decoded_sz = m_key_ii->decoded_size(ik); if (m_scratch.size() < decoded_sz) { m_scratch.resize(decoded_sz); } m_key_ii->decode(ik, &m_scratch.front()); return e::slice(&m_scratch.front(), decoded_sz); } std::ostream& key_iterator :: describe(std::ostream& out) const { return out << "key_iterator()"; } e::slice key_iterator :: internal_key() { region_id ri; e::slice k; leveldb::Slice _k = m_iter->key(); decode_key(_k, &ri, &k); return k; } bool key_iterator :: sorted() { return true; } void key_iterator :: seek(const e::slice& ik) { leveldb::Slice slice; encode_key(m_ri, m_range.type, ik, &m_scratch, &slice); m_iter->Seek(slice); } } // namespace datalayer::index_iterator* index_primitive :: iterator_from_range(leveldb_snapshot_ptr snap, const region_id& ri, const range& r, index_info* key_ii) { if (r.invalid) { return NULL; } if (r.attr != 0) { return new range_iterator(snap, ri, r, this, key_ii); } else { return new key_iterator(snap, ri, r, key_ii); } }
25.168639
95
0.554661
[ "vector" ]
bd6f4f20782cdbaa4e5fdc1cb4ecd23bca762bb1
6,187
cpp
C++
test/screen-point-to-ray.cpp
mortennobel/SimpleRenderEngine
fb00a04cb38e2227adf4bdb17e1b38ec160632c2
[ "MIT" ]
313
2017-01-13T10:54:58.000Z
2022-03-18T03:08:53.000Z
test/screen-point-to-ray.cpp
AntonyChan818/SimpleRenderEngine
7e52507ecf6e93c1ddce7f9c2175acb159f49492
[ "MIT" ]
13
2016-09-29T12:50:23.000Z
2019-04-21T05:17:33.000Z
test/screen-point-to-ray.cpp
AntonyChan818/SimpleRenderEngine
7e52507ecf6e93c1ddce7f9c2175acb159f49492
[ "MIT" ]
61
2016-08-31T07:34:42.000Z
2022-03-16T23:02:11.000Z
#include <iostream> #include "sre/Texture.hpp" #include "sre/Renderer.hpp" #include "sre/Material.hpp" #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/euler_angles.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> #include <sre/SDLRenderer.hpp> #include <sre/impl/GL.hpp> #include <glm/gtc/random.hpp> using namespace sre; class ScreenPointToRayExample{ public: ScreenPointToRayExample(){ r.init(); camera.lookAt(eye,at,{0,1,0}); camera.setPerspectiveProjection(fov,near,far); mesh = Mesh::create() .withSphere() .build(); planeMesh = Mesh::create() .withCube(10) .build(); worldLights.addLight(Light::create() .withDirectionalLight(glm::normalize(glm::vec3(1,1,1))) .build()); // Add fake shadows worldLights.addLight(Light::create() .withPointLight(p1-glm::vec3(0,0.8,0)) .withColor({-3.0f,-3.0f,-3.0f}) .withRange(4) .build()); worldLights.addLight(Light::create() .withPointLight(p2-glm::vec3(0,0.8,0)) .withColor({-3.0f,-3.0f,-3.0f}) .withRange(4) .build()); mat1 = Shader::getStandardBlinnPhong()->createMaterial(); mat1->setColor({1,1,1,1}); mat1->setSpecularity(Color(0,0,0,0)); mat2 = Shader::getStandardBlinnPhong()->createMaterial(); mat2->setColor({1,0,0,1}); mat2->setSpecularity(Color(0,0,0,0)); matPlane = Shader::getStandardBlinnPhong()->createMaterial(); matPlane->setColor({1,1,1,1}); matPlane->setSpecularity(Color(0,0,0,0)); r.mouseEvent = [&](SDL_Event event){ if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button==SDL_BUTTON_RIGHT){ glm::vec2 pos = {event.button.x,event.button.y}; pos.y = Renderer::instance->getWindowSize().y - pos.y; // flip y axis auto res = camera.screenPointToRay(pos); raycastOrigin = res[0]; raycastDirection =res[1]; points = {{raycastOrigin, raycastOrigin+raycastDirection}}; float dist1 = rayToSphere(res, p1); if (dist1<1){ updateMaterial(mat1); } float dist2 = rayToSphere(res, p2); if (dist2<1){ updateMaterial(mat2); } } }; r.frameUpdate = [&](float deltaTime){ update(deltaTime); }; r.frameRender = [&](){ render(); }; r.startEventLoop(); } void updateMaterial(std::shared_ptr<Material>& mat){ Color color (glm::linearRand(0.0f, 1.0f),glm::linearRand(0.0f, 1.0f),glm::linearRand(0.0f, 1.0f)); mat->setColor(color); } void cameraGUI(){ ImGui::Checkbox("Perspective projection", &perspective); if (perspective){ ImGui::DragFloat("FOV", &fov,1,1,179); } else { ImGui::DragFloat("OrthoSize", &orthoSize,0.1,0.1,10); } ImGui::DragFloat("Near", &near,0.1,-10,10); ImGui::DragFloat("Far", &far,0.1,0.1,100); if (perspective){ camera.setPerspectiveProjection(fov,near,far); } else { camera.setOrthographicProjection(orthoSize,near,far); } ImGui::DragFloat3("eye", &eye.x,0.1,-10,10); ImGui::DragFloat3("at", &at.x,0.1,-10,10); camera.lookAt(eye,at,{0,1,0}); ImGui::DragFloat2("viewportOffset",&viewportOffset.x,0.05,0,1); ImGui::DragFloat2("viewportSize", &viewportSize.x,0.05,0,1); camera.setViewport(viewportOffset,viewportSize); } void update(float deltaTime){ time += deltaTime; } float rayToSphere(std::array<glm::vec3, 2> ray, glm::vec3 sphereCenter){ float d = dot(sphereCenter-ray[0], ray[1]); if (d < 0){ d = 0; } glm::vec3 closestPoint = d* ray[1] + ray[0]; return glm::distance(closestPoint, sphereCenter); } void render(){ auto rp = RenderPass::create() .withCamera(camera) .withWorldLights(&worldLights) .withClearColor(true,{1,0,0,1}) .build(); rp.draw(mesh, pos1, mat1); checkGLError(); rp.draw(mesh, pos2, mat2); checkGLError(); ImGui::LabelText("Rightclick to shoot ray", ""); rp.draw(planeMesh, glm::translate(glm::vec3{0,-1.0f,0})*glm::scale(glm::vec3{1,.01f,1}), matPlane); ImGui::LabelText("raycastOrigin", "%.1f,%.1f,%.1f", raycastOrigin.x,raycastOrigin.y,raycastOrigin.z); ImGui::LabelText("raycastDirection", "%.1f,%.1f,%.1f", raycastDirection.x,raycastDirection.y,raycastDirection.z); rp.drawLines(points); cameraGUI(); } private: float time; SDLRenderer r; Camera camera; std::shared_ptr<Mesh> mesh; std::shared_ptr<Mesh> planeMesh; WorldLights worldLights; // camera properties bool perspective=true; float fov = 60; float near = 0.1; float far = 100; float orthoSize = 2; glm::vec2 viewportOffset = glm::vec2{0}; glm::vec2 viewportSize = glm::vec2{1}; glm::vec3 eye = {0,0,3}; glm::vec3 at = {0,0,0}; std::shared_ptr<Material> mat1; std::shared_ptr<Material> mat2; std::shared_ptr<Material> matPlane; glm::vec3 p1 = {-1,0,0}; glm::vec3 p2 = {1,0,0}; glm::mat4 pos1 = glm::translate(glm::mat4(1),p1); glm::mat4 pos2 = glm::translate(glm::mat4(1),p2); glm::vec3 raycastOrigin{0}; glm::vec3 raycastDirection{0}; std::vector<glm::vec3> points{{raycastOrigin, raycastOrigin+raycastDirection}}; }; int main() { std::make_unique<ScreenPointToRayExample>(); return 0; }
31.406091
121
0.541135
[ "mesh", "render", "vector", "transform" ]
bd74dd808b63a5ba756952a4952cd8de37c9106f
2,746
cpp
C++
src/gemini_main.cpp
gemini3d/GEMINI
4655db755101a127bf1bfeddefd6c021f39b1bdb
[ "Apache-2.0" ]
9
2019-06-17T20:51:31.000Z
2020-03-12T17:46:00.000Z
src/gemini_main.cpp
gemini3d/gemini
4655db755101a127bf1bfeddefd6c021f39b1bdb
[ "Apache-2.0" ]
11
2020-04-08T22:24:40.000Z
2020-07-15T14:06:41.000Z
src/gemini_main.cpp
mattzett/GEMINI
4655db755101a127bf1bfeddefd6c021f39b1bdb
[ "Apache-2.0" ]
3
2018-10-10T16:01:08.000Z
2018-12-17T16:08:50.000Z
// MAIN PROGRAM FOR GEMINI3D #include <iostream> #include <filesystem> #include <vector> #include <sstream> #include <mpi.h> #include "gemini3d.h" #include "iniparser.h" #include "filesystem.h" namespace fs = std::filesystem; int main(int argc, char **argv) { struct params s; int myid; int ierr = MPI_Init(&argc, &argv); // CLI if (argc < 2) { std::cerr << "Gemini3D: please give simulation output directory e.g. ~/data/my_sim" << std::endl; return EXIT_FAILURE; } // simulation directory char odir[4096]; expanduser(argv[1], odir); fs::path out_dir(odir); if(! fs::is_directory(out_dir)) { std::cerr << "Gemini3D simulation output directory does not exist: " << out_dir << std::endl; return EXIT_FAILURE; } // Read gemini_config.ini, if it exists auto ini_file = out_dir / "inputs/gemini_config.ini"; if(fs::is_regular_file(ini_file)) { dictionary *ini; int b,i ; double d; const char *txt; ini = iniparser_load(ini_file.string().c_str()); if (ini==NULL) { std::cerr << "gemini3d_ini: cannot parse file: " << ini_file << std::endl; return EXIT_FAILURE; } std::string ini_str, t_str; std::vector<int> ymd; ini_str = iniparser_getstring(ini, "base:ymd", ""); if(ini_str.empty()) { std::cerr << "gemini3d_ini: base:ymd not found in " << ini_file << std::endl; return EXIT_FAILURE; } std::stringstream sini(ini_str); while(std::getline(sini, t_str, ',')) ymd.push_back(stoi(t_str)); if(ymd.size() != 3) { std::cerr << "gemini3d_ini: base:ymd must have 3 elements: " << ini_str << std::endl; return EXIT_FAILURE; } iniparser_freedict(ini); // close the file s.fortran_nml = false; } else { s.fortran_nml = true; } // Prepare Gemini3D struct strncpy(s.out_dir, out_dir.string().c_str(), LMAX); s.fortran_cli = false; s.debug = false; s.dryrun = false; int lid2in = -1, lid3in = -1; MPI_Comm_rank(MPI_COMM_WORLD,&myid); for (int i = 2; i < argc; i++) { if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "-debug") == 0) s.debug = true; if (strcmp(argv[i], "-dryrun") == 0) s.dryrun = true; if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0) { MPI_Finalize(); help_gemini_bin(); return EXIT_SUCCESS; } if (strcmp(argv[i], "-manual_grid") == 0) { if (argc < i+1) { MPI_Finalize(); std::cerr << "-manual_grid lid2in lid3in" << std::endl; return EXIT_FAILURE; } lid2in = atoi(argv[i]); lid3in = atoi(argv[i+1]); } } gemini_main(&s, &lid2in, &lid3in); ierr = MPI_Finalize(); if (ierr != 0) return EXIT_FAILURE; return EXIT_SUCCESS; }
24.517857
101
0.602331
[ "vector" ]
bd7820242c764466283b8ba849677ac5d8a60955
2,004
cpp
C++
Junior_Core/Src/Source/DefaultMeshLink.cpp
DeltaGoldenFlag/JuniorEngine
9581f863d5bd412a4ab48b7ea893151798829856
[ "BSD-3-Clause" ]
1
2019-06-13T00:14:02.000Z
2019-06-13T00:14:02.000Z
Junior_Core/Src/Source/DefaultMeshLink.cpp
DeltaGoldenFlag/JuniorEngine
9581f863d5bd412a4ab48b7ea893151798829856
[ "BSD-3-Clause" ]
null
null
null
Junior_Core/Src/Source/DefaultMeshLink.cpp
DeltaGoldenFlag/JuniorEngine
9581f863d5bd412a4ab48b7ea893151798829856
[ "BSD-3-Clause" ]
null
null
null
/* * Author: David Wong * Email: david.wongcascante@digipen.edu * File name: DefaultMeshLink.cpp * Description: Links this game object to the DefaultMesh to render it on screen * Created: 4 May 2018 * Last Modified: 4 May 2019 */ // Includes #include "DefaultMeshLink.h" #include "DefaultMesh.h" // Default Mesh #include "Graphics.h" // Graphics #include "GameObject.h" // Game Object #include "Transform.h" // Transform #include "Sprite.h" // Sprite // Public Member Functions Junior::DefaultMeshLink::DefaultMeshLink(bool loadMeshData) : defaultProgramDir("..//Assets//Shaders//starter"), renderJob_(nullptr), sprite_(nullptr) { // Get a new render job if (loadMeshData) { Graphics& graphics = Graphics::GetInstance(); renderJob_ = graphics.GetMesh<DefaultMesh>(defaultProgramDir)->GetNewRenderJob(); } } Junior::DefaultMeshLink::DefaultMeshLink(const DefaultMeshLink& other) : defaultProgramDir("..//Assets//Shaders//starter"), renderJob_(nullptr), transform_(nullptr), sprite_(nullptr) { // Get a new render job Graphics& graphics = Graphics::GetInstance(); renderJob_ = graphics.GetMesh<DefaultMesh>(defaultProgramDir)->GetNewRenderJob(); } void Junior::DefaultMeshLink::Initialize() { // Get all the necessary components transform_ = owner_->GetComponent<Transform>(); sprite_ = owner_->GetComponent<Sprite>(); } void Junior::DefaultMeshLink::Update(double) { // Update the transform if it exists if (transform_) { renderJob_->transformation_ = transform_->GetGlobalTransformation(); } // Update the sprite if it exists if (sprite_) { Vec3 atlasOffset = sprite_->GetAtlasOffset(); Vec3 atlasScale = sprite_->GetAtlasScale(); renderJob_->uvTranslationAndScale_ = Vec3(atlasOffset.x_, atlasOffset.y_, atlasScale.x_, atlasScale.y_); } } void Junior::DefaultMeshLink::Unload() { if (renderJob_) { Graphics& graphics = Graphics::GetInstance(); graphics.GetMesh<DefaultMesh>(defaultProgramDir)->RemoveRenderJob(renderJob_); delete renderJob_; } }
28.628571
112
0.742515
[ "mesh", "render", "object", "transform" ]
bd817603febf08599f3acf11130bfa3f3007eec5
2,798
cpp
C++
Medium/752 - Open the Lock.cpp
WangZixuan/Leetcode
4593e8b48c4ce810567473a825735ffde3f7a0f0
[ "WTFPL" ]
11
2015-08-06T15:43:48.000Z
2022-02-16T01:30:24.000Z
Medium/752 - Open the Lock.cpp
WangZixuan/Leetcode
4593e8b48c4ce810567473a825735ffde3f7a0f0
[ "WTFPL" ]
1
2015-08-17T13:33:55.000Z
2015-08-27T03:43:47.000Z
Medium/752 - Open the Lock.cpp
WangZixuan/Leetcode
4593e8b48c4ce810567473a825735ffde3f7a0f0
[ "WTFPL" ]
2
2021-09-30T14:39:05.000Z
2021-10-02T11:02:20.000Z
/* Open the Lock You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. Example 1: Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" Output: 6 Explanation: A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102". Example 2: Input: deadends = ["8888"], target = "0009" Output: 1 Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". Example 3: Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" Output: -1 Explanation: We can't reach the target without getting stuck. Example 4: Input: deadends = ["0000"], target = "8888" Output: -1 Note: The length of deadends will be in the range [1, 500]. target will not be in the list deadends. Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'. @author Zixuan @date 2018/1/6 */ #include <queue> #include <vector> #include <set> #include <string> using namespace std; class Solution { public: int openLock(vector<string>& deadends, string target) { if (find(deadends.begin(), deadends.end(), "0000") != deadends.end() || find(deadends.begin(), deadends.end(), target) != deadends.end()) return -1; queue<string> paths; paths.push("0000,0"); set<string> existed{ "0000" }; existed.insert(deadends.begin(), deadends.end()); //BFS while (!paths.empty()) { auto str = paths.front(); auto pass = str.substr(0, 4); auto count = str.substr(5); if (pass == target) return stoi(count); for (auto i = 0; i < 4;++i) for (auto j = -1; j <= 1; ++j) { auto c = (pass[i] + 10 - '0' + j) % 10; auto n = pass; n[i] = c + '0'; if (pass != n && existed.find(n) == existed.end()) { paths.push(n + "," + to_string(stoi(count) + 1)); existed.insert(n); } } paths.pop(); } return -1; } };
29.145833
173
0.639385
[ "vector" ]
bd837d2b4d4992951fadcf5edb3ba931adf8b705
7,630
hpp
C++
c++/include/objtools/data_loaders/genbank/cache/reader_cache.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/include/objtools/data_loaders/genbank/cache/reader_cache.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/include/objtools/data_loaders/genbank/cache/reader_cache.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef READER_CACHE__HPP_INCLUDED #define READER_CACHE__HPP_INCLUDED /* $Id: reader_cache.hpp 390318 2013-02-26 21:04:57Z vasilche $ * =========================================================================== * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * =========================================================================== * * Author: Eugene Vasilchenko, Anatoliy Kuznetsov * * File Description: Cached extension of data reader from ID1 * */ #include <objtools/data_loaders/genbank/reader.hpp> #include <corelib/ncbi_tree.hpp> #include <vector> BEGIN_NCBI_SCOPE class IBLOB_Cache; class IIntCache; class ICache; class IReader; class IWriter; class CByteSource; BEGIN_SCOPE(objects) class CSeq_id; class CID2_Reply_Data; class CLoadLockSeq_ids; /// structure for common cache reader&writer implementation struct NCBI_XREADER_CACHE_EXPORT SCacheInfo { typedef vector<int> TIdCacheData; static const int IDS_MAGIC; ////////////////////////////////////////////////////////////////// // Keys manipulation methods: /// Return Id cache key string based on CSeq_id of gi static string GetIdKey(const CSeq_id& id); static string GetIdKey(const CSeq_id_Handle& id); static string GetIdKey(int gi); /// Id cache subkeys: // Seq-id/gi -> blob_id & contents info static void GetBlob_idsSubkey(const SAnnotSelector* sel, string& subkey, string& true_subkey); // Seq-id -> gi (1 int) static const char* GetGiSubkey(void); // Seq-id -> acc (string: fasta) static const char* GetAccVerSubkey(void); // Seq-id -> label (string) static const char* GetLabelSubkey(void); // Seq-id -> taxid (1 int) static const char* GetTaxIdSubkey(void); // Seq-id -> list of Seq-id, binary ASN.1 static const char* GetSeq_idsSubkey(void); // blob_id -> blob version (1 int) static const char* GetBlobVersionSubkey(void); /// Return BLOB cache key string based on Sat() and SatKey() static string GetBlobKey(const CBlob_id& blob_id); /// BLOB cache subkeys: enum { kMain_ChunkId = -1, // not a chunk, but main Seq-entry kMasterWGS_ChunkId = kMax_Int-1, // chunk with master WGS descr kDelayedMain_ChunkId= kMax_Int // main Seq-entry with delayed ext annot }; static string GetBlobSubkey(CLoadLockBlob& blob, int chunk_id = kMain_ChunkId); static int GetDebugLevel(void); typedef CTreePair<string, string> TParamPair; typedef TParamPair::TPairTreeNode TParams; enum EReaderOrWriter { eCacheReader, eCacheWriter }; enum EIdOrBlob { eIdCache, eBlobCache }; static ICache *CreateCache(const TParams* params, EReaderOrWriter reader_or_writer, EIdOrBlob id_or_blob); }; class NCBI_XREADER_CACHE_EXPORT CCacheHolder { public: CCacheHolder(void); ~CCacheHolder(void); void SetBlobCache(ICache* blob_cache); void SetIdCache(ICache* id_cache); ICache* GetIdCache(void) const { return m_IdCache; } ICache* GetBlobCache(void) const { return m_BlobCache; } protected: ICache* m_BlobCache; ICache* m_IdCache; private: // to prevent copying CCacheHolder(const CCacheHolder&); void operator=(const CCacheHolder&); }; class NCBI_XREADER_CACHE_EXPORT CCacheReader : public CReader, public CCacheHolder, public SCacheInfo { public: CCacheReader(void); CCacheReader(const TPluginManagerParamTree* params, const string& driver_name); ////////////////////////////////////////////////////////////////// // Overloaded loading methods: bool LoadStringSeq_ids(CReaderRequestResult& result, const string& seq_id); bool LoadSeq_idSeq_ids(CReaderRequestResult& result, const CSeq_id_Handle& seq_id); bool LoadSeq_idGi(CReaderRequestResult& result, const CSeq_id_Handle& seq_id); bool LoadSeq_idAccVer(CReaderRequestResult& result, const CSeq_id_Handle& seq_id); bool LoadSeq_idLabel(CReaderRequestResult& result, const CSeq_id_Handle& seq_id); bool LoadSeq_idTaxId(CReaderRequestResult& result, const CSeq_id_Handle& seq_id); bool LoadSeq_idBlob_ids(CReaderRequestResult& result, const CSeq_id_Handle& seq_id, const SAnnotSelector* sel); bool LoadAccVers(CReaderRequestResult& result, const TIds& ids, TLoaded& loaded, TIds& ret); bool LoadGis(CReaderRequestResult& result, const TIds& ids, TLoaded& loaded, TGis& ret); bool LoadLabels(CReaderRequestResult& result, const TIds& ids, TLoaded& loaded, TLabels& ret); bool LoadTaxIds(CReaderRequestResult& result, const TIds& ids, TLoaded& loaded, TTaxIds& ret); bool LoadBlobVersion(CReaderRequestResult& result, const TBlobId& blob_id); bool LoadBlob(CReaderRequestResult& result, const TBlobId& blob_id); bool LoadChunk(CReaderRequestResult& result, const TBlobId& blob_id, TChunkId chunk_id); bool ReadSeq_ids(CReaderRequestResult& result, const string& key, CLoadLockSeq_ids& ids); int GetRetryCount(void) const; bool MayBeSkippedOnErrors(void) const; int GetMaximumConnectionsLimit(void) const; virtual void InitializeCache(CReaderCacheManager& cache_manager, const TPluginManagerParamTree* params); virtual void ResetCache(void); protected: void x_AddConnectionSlot(TConn conn); void x_RemoveConnectionSlot(TConn conn); void x_DisconnectAtSlot(TConn conn, bool failed); void x_ConnectAtSlot(TConn conn); void x_ProcessBlob(CReaderRequestResult& result, const TBlobId& blob_id, TChunkId chunk_id, CNcbiIstream& stream); ESwitch m_JoinedBlobVersion; }; SCacheInfo::TParams* GetCacheParams(const SCacheInfo::TParams* src_params, SCacheInfo::EReaderOrWriter reader_or_writer, SCacheInfo::EIdOrBlob id_or_blob); END_SCOPE(objects) END_NCBI_SCOPE #endif // READER_CACHE__HPP_INCLUDED
33.911111
79
0.637221
[ "vector" ]
bd89d6cf0efe082891138afd81d29e6a9c6da81e
26,646
cc
C++
src/Bambus/Output/Output_Utils.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
10
2015-03-20T18:25:56.000Z
2020-06-02T22:00:08.000Z
src/Bambus/Output/Output_Utils.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
5
2015-05-14T17:51:20.000Z
2020-07-19T04:17:47.000Z
src/Bambus/Output/Output_Utils.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
10
2015-05-17T16:01:23.000Z
2020-05-20T08:13:43.000Z
#include <iostream> #include "Output_Utils.hh" #include "Utilities_Bundler.hh" #include "universals_AMOS.hh" #include "Library_AMOS.hh" #include "Fragment_AMOS.hh" #include "Overlap_AMOS.hh" #include "Contig_AMOS.hh" #include "ContigLink_AMOS.hh" #include "ContigEdge_AMOS.hh" #include "Scaffold_AMOS.hh" #include "Motif_AMOS.hh" using namespace Bundler; namespace Output { AMOS::Bank_t *global_edge_bank = NULL; struct EdgeOrderCmp { bool operator () (const AMOS::ID_t & a, const AMOS::ID_t & b) { assert(global_edge_bank); AMOS::ContigEdge_t ctgA, ctgB; global_edge_bank->fetch(a, ctgA); global_edge_bank->fetch(b, ctgB); if (ctgA.getContigs().first != ctgB.getContigs().first) { if (ctgA.getContigs().first < ctgB.getContigs().first) return true; if (ctgA.getContigs().first > ctgB.getContigs().first) return false; } if (ctgA.getContigs().second != ctgB.getContigs().second) { if (ctgA.getContigs().second < ctgB.getContigs().second) return true; if (ctgA.getContigs().second > ctgB.getContigs().second) return false; } if (!isBadEdge(ctgA)) return true; return false; } }; AMOS::ID_t translateCLKtoFRG(AMOS::Bank_t &link_bank, AMOS::ID_t linkID); void outputEdge(std::ofstream &stream, AMOS::Bank_t &edge_bank, AMOS::ID_t iid, const char *start, const char *end, const char *direction); void outputEdges(std::ostream &stream, AMOS::Bank_t &edge_bank, AMOS::ID_t currCtg, int32_t edgeTypes[], int32_t debug); void outputLibrary(const std::string &outputPrefix, int32_t debug); void outputEvidenceXML(const std::string &bank, AMOS::Bank_t &contig_bank, const std::string &outputPrefix, int32_t debug); void outputOutXML(const std::string &bank, AMOS::Bank_t &edge_bank, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, int32_t debug); void outputAGP(AMOS::Bank_t &contig_bank, AMOS::BankStream_t &scf_stream, const std::string& outputPrefix, int32_t debug); void outputDOT(AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::Scaffold_t *node, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, int32_t debug); void outputDOT(AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::Scaffold_t *node, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, bool allEdges, int32_t debug); void outputMotifs(AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::BankStream_t &motif_stream, const std::string &outputPrefix, int32_t debug); void outputBAMBUS(const std::string &bank, AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, int32_t debug); void outputAGP(AMOS::Bank_t &contig_bank, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, int32_t debug) { AMOS::Contig_t ctg; std::string outputFile = outputPrefix + ".agp"; std::ofstream stream; stream.open(outputFile.c_str(), std::ios::out); stream << "# DESCRIPTION: WGS SCAFFOLDS GENERATED FROM AMOS BANK" << std::endl; AMOS::Scaffold_t scf; AMOS::ID_t maxIID = contig_bank.getMaxIID(); while (scf_stream >> scf) { int32_t counter = 0; int32_t lastEnd = 0; for (std::vector<AMOS::Tile_t>::const_iterator tileIt = scf.getContigTiling().begin(); tileIt < scf.getContigTiling().end(); tileIt++) { // output the gap if (lastEnd != 0 && (tileIt->offset - lastEnd != 0)) { stream << scf.getIID(); stream << "\t" << lastEnd << "\t" << tileIt->offset; stream << "\t" << counter; stream << "\t" << (tileIt->offset - lastEnd + 1); stream << "\tfragment\tyes"; stream << std::endl; counter++; } std::string sign = "+"; if (tileIt->range.isReverse()) { sign = "-"; } stream << scf.getIID(); stream << "\t" << (tileIt->offset+1) << "\t" << (tileIt->offset+tileIt->range.getLength()); stream << "\t" << counter << "\tW"; int32_t outputID = 0; if (tileIt->source <= maxIID) { contig_bank.fetch(tileIt->source, ctg); if (ctg.getEID().size() != 0) { stream << "\t" << ctg.getEID(); outputID = 1; } } if (outputID == 0) stream << "\t" << tileIt->source; stream << "\t" << tileIt->range.getLo()+1 << "\t" << tileIt->range.getHi(); stream << "\t" << sign; stream << std::endl; counter++; lastEnd = tileIt->offset+tileIt->range.getLength()+1; } } stream.close(); } void outputEdge(std::ostream &stream, AMOS::Bank_t &edge_bank, AMOS::ID_t iid, const char *start, const char *end, const char *direction) { AMOS::ContigEdge_t outputEdge; edge_bank.fetch(iid, outputEdge); stream << outputEdge.getContigs().first << ":" << start << "->" << outputEdge.getContigs().second << ":" << end; stream << " [ label=\"" << outputEdge.getIID() << " orientation=" << outputEdge.getAdjacency() << " weight=" << outputEdge.getContigLinks().size() << " distance=" << outputEdge.getSize() << " stdev=" << outputEdge.getSD(); if (outputEdge.getStatus() == BAD_TRNS) { stream << " (REDUNDANT) "; } else if (isBadEdge(outputEdge)) { stream << " (UNUSED) "; } stream << "\" dir=\"" << direction << "\" fontsize = 8 solid color=\"black\" ]\n"; } void outputEdges(std::ostream &stream, AMOS::Bank_t &edge_bank, AMOS::ID_t currCtg, int32_t edgeTypes[], int32_t debug) { if (currCtg != 0) { if (edgeTypes[3] != 0) { outputEdge(stream, edge_bank, edgeTypes[3], "w", "w", "back"); } if (edgeTypes[2] != 0) { outputEdge(stream, edge_bank, edgeTypes[2], "e", "e", "forward"); } if (edgeTypes[1] != 0) { outputEdge(stream, edge_bank, edgeTypes[1], "w", "e", "back"); } if (edgeTypes[0] != 0) { outputEdge(stream, edge_bank, edgeTypes[0], "e", "w", "forward"); } else if (debug >= 3) { std::cerr << "WARNING: NO GOOD EDGE BETWEEN CONTIGS" << std::endl; } } } void outputDOT(AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::Scaffold_t *node, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, int32_t debug) { outputDOT(contig_bank, edge_bank, node, scf_stream, outputPrefix, false, debug); } void outputDOT(AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::Scaffold_t *node, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, bool allEdges, int32_t debug) { AMOS::Contig_t ctg; AMOS::ID_t maxIID = contig_bank.getMaxIID(); std::string outputFile = outputPrefix + ".dot"; std::ofstream stream; stream.open(outputFile.c_str(), std::ios::out); stream << "digraph ROOT {" << std::endl; stream << " rankdir = LR" << std::endl; stream << " rotate = 90" << std::endl; stream << " ranksep = 0.01" << std::endl; stream << " nodesep = 0.01" << std::endl; stream << " fontsize = 8" << std::endl; stream << " margin = \".01,.01\"" << std::endl; stream << " ratio = fill" << std::endl; stream << " size = \"11,8.5\"" << std::endl; HASHMAP::hash_map<AMOS::ID_t, int32_t, HASHMAP::hash<AMOS::ID_t>, HASHMAP::equal_to<AMOS::ID_t> > visited; while (scf_stream >> (*node)) { AMOS::ID_t scfID = AMOS::NULL_ID; if (dynamic_cast<AMOS::Scaffold_t *>(node) != NULL) { scfID = node->getIID(); } else if (dynamic_cast<AMOS::Motif_t *>(node) != NULL) { scfID = (dynamic_cast<AMOS::Motif_t *>(node))->getScf(); } else { std::cerr << "Error: Unknown object type passed to output " << node->getNCode() << std::endl; continue; } HASHMAP::hash_map<AMOS::ID_t, int32_t, HASHMAP::hash<AMOS::ID_t>, HASHMAP::equal_to<AMOS::ID_t> > ctginscf; HASHMAP::hash_map<AMOS::ID_t, contigOrientation, HASHMAP::hash<AMOS::ID_t>, HASHMAP::equal_to<AMOS::ID_t> > ctgori; stream << "subgraph cluster_" << scfID << "{" << std::endl; stream << "\tlabel = \"" << scfID << "\"" << std::endl; for (std::vector<AMOS::Tile_t>::const_iterator tileIt = node->getContigTiling().begin(); tileIt < node->getContigTiling().end(); tileIt++) { ctginscf[tileIt->source] = 1; ctgori[tileIt->source] = (tileIt->range.isReverse() ? REV : FWD); int32_t angle = -90; if (tileIt->range.isReverse()) { angle = 90; } int32_t outputID = 0; stream << "\t" << tileIt->source << " [label=\"" ; if (tileIt->source <= maxIID) { contig_bank.fetch(tileIt->source, ctg); if (ctg.getEID().size() != 0) { stream << ctg.getEID(); outputID = 1; } } if (outputID == 0) stream << tileIt->source; stream << " position=(" << tileIt->offset << "," << tileIt->offset + tileIt->range.getLength() - 1; stream << ") length=" << tileIt->range.getLength() << "\" height=0.2, fontsize=8, shape=\"house\", "; stream << "orientation=" << angle << " ]" << std::endl; } AMOS::ID_t currCtg = 0; AMOS::ID_t secondCtg = 0; int32_t edgeTypes[4]; // sort before output global_edge_bank = &edge_bank; sort(node->getContigEdges().begin(), node->getContigEdges().end(), EdgeOrderCmp()); global_edge_bank = NULL; for (std::vector<AMOS::ID_t>::const_iterator edgeIt = node->getContigEdges().begin(); edgeIt < node->getContigEdges().end(); edgeIt++) { AMOS::ContigEdge_t cte; edge_bank.fetch(*edgeIt, cte); if (allEdges == false && (ctginscf[cte.getContigs().first] != 1 || ctginscf[cte.getContigs().second] != 1)) { continue; } if (currCtg != cte.getContigs().first || secondCtg != cte.getContigs().second) { outputEdges(stream, edge_bank, currCtg, edgeTypes, debug); currCtg = cte.getContigs().first; secondCtg = cte.getContigs().second; memset(edgeTypes, 0, sizeof(int32_t)*4); } if (visited[cte.getIID()] == 0) { // output the edges based on the orient of the contigs contigOrientation edgeFirstCtgOrient = ctgori[cte.getContigs().first]; contigOrientation edgeSecondCtgOrient = ctgori[cte.getContigs().second]; contigOrientation first = FWD; if (cte.getAdjacency() == AMOS::ContigEdge_t::ANTINORMAL || cte.getAdjacency() == AMOS::ContigEdge_t::OUTIE) { first = REV; } contigOrientation secondCtgOrient = getOrientation(first, cte); if (debug >= 3) { std::cerr << "****The firstOrient is " << edgeFirstCtgOrient << " and second is " << edgeSecondCtgOrient << std::endl; std::cerr << "The edge type is " << cte.getAdjacency() << " and we initialized first to be " << first << std::endl; std::cerr << "****The orient we get are " << first << " and second is " << secondCtgOrient << std::endl; } if (first == edgeFirstCtgOrient && secondCtgOrient == edgeSecondCtgOrient) { edgeTypes[0] = (edgeTypes[0] == 0 || !isBadEdge(cte.getIID(), edge_bank) ? cte.getIID() : edgeTypes[0]); if (debug >= 3) { std::cerr << "*** MAIN EDGE BETWEEN " << cte.getContigs().first << " AND " << cte.getContigs().second << " IS " << cte.getAdjacency() <<std::endl; } } else if (first != edgeFirstCtgOrient && secondCtgOrient == edgeSecondCtgOrient) { if (debug >= 3) { std::cerr << "*** D, S EDGE BETWEEN " << cte.getContigs().first << " AND " << cte.getContigs().second << " IS " << cte.getAdjacency() <<std::endl;} edgeTypes[1] = (edgeTypes[1] == 0 || !isBadEdge(cte.getIID(), edge_bank) ? cte.getIID() : edgeTypes[1]); } else if (first == edgeFirstCtgOrient && secondCtgOrient != edgeSecondCtgOrient) { if (debug >= 3) { std::cerr << "*** S, D EDGE BETWEEN " << cte.getContigs().first << " AND " << cte.getContigs().second << " IS " << cte.getAdjacency() <<std::endl; } edgeTypes[2] = (edgeTypes[2] == 0 || !isBadEdge(cte.getIID(), edge_bank) ? cte.getIID() : edgeTypes[2]); } else { if (debug >= 3) { std::cerr << "*** D, D EDGE BETWEEN " << cte.getContigs().first << " AND " << cte.getContigs().second << " IS " << cte.getAdjacency() <<std::endl; } edgeTypes[3] = (edgeTypes[3] == 0 || !isBadEdge(cte.getIID(), edge_bank) ? cte.getIID() : edgeTypes[3]); } } else { std::cerr << "IN SCAFFOLD " << scfID << " ENCOUNTERED EDGE " << cte.getIID() << "THAT IVE ALREADY SEEN!!" << std::endl; assert(0); } visited[cte.getIID()] = 1; } outputEdges(stream, edge_bank, currCtg, edgeTypes, debug); stream << "}" << std::endl; } stream << "}" << std::endl; stream.close(); } void outputMotifs(AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::BankStream_t &motif_stream, const std::string &outputPrefix, int32_t debug) { if (motif_stream.getSize() == 0) { return; } // output the dot file of motifs AMOS::Motif_t *motif = new AMOS::Motif_t(); outputDOT(contig_bank, edge_bank, motif, motif_stream, outputPrefix + ".noreduce", true, debug); motif_stream.seekg(0,AMOS::BankStream_t::BEGIN); // output the set of motifs std::string outputFile = outputPrefix + ".sets"; std::ofstream stream; stream.open(outputFile.c_str(), std::ios::out); while (motif_stream >> (*motif)) { stream << motif->getEID() << " :"; for (std::vector<AMOS::Tile_t>::const_iterator tileIt = motif->getContigTiling().begin(); tileIt < motif->getContigTiling().end(); tileIt++) { stream << " " << tileIt->source; } stream << std::endl; } stream.close(); delete motif; } AMOS::ID_t translateCLKtoFRG(AMOS::Bank_t &link_bank, AMOS::ID_t linkID) { // for fragment-based links, translate their ID to the source AMOS::ContigLink_t clk; link_bank.fetch(linkID, clk); std::pair<AMOS::ID_t, AMOS::NCode_t> source = clk.getSource(); AMOS::ID_t iid = linkID; if (source.second == AMOS::Fragment_t::NCODE) { iid = source.first; } return iid; } void outputLibrary(const std::string &bank, const std::string &outputPrefix, int32_t debug) { AMOS::BankStream_t library_stream (AMOS::Library_t::NCODE); if (!library_stream.exists(bank)){ std::cerr << "No library account found in bank " << bank << std::endl; exit(1); } try { library_stream.open(bank, AMOS::B_READ); } catch (AMOS::Exception_t & e) { std::cerr << "Failed to open library account in bank " << bank << ": " << std::endl << e << std::endl; exit(1); } std::string outputFile = outputPrefix + ".library"; std::ofstream stream; stream.open(outputFile.c_str(), std::ios::out); AMOS::Library_t lib; while (library_stream >> lib) { stream << lib.getEID() << " " << lib.getIID() << std::endl; } stream.close(); library_stream.close(); } void outputEvidenceXML(const std::string &bank, AMOS::Bank_t &contig_bank, const std::string &outputPrefix, int32_t debug) { AMOS::BankStream_t library_stream (AMOS::Library_t::NCODE); if (!library_stream.exists(bank)){ std::cerr << "No library account found in bank " << bank << std::endl; exit(1); } try { library_stream.open(bank, AMOS::B_READ); } catch (AMOS::Exception_t & e) { std::cerr << "Failed to open library account in bank " << bank << ": " << std::endl << e << std::endl; exit(1); } AMOS::BankStream_t frag_stream (AMOS::Fragment_t::NCODE); if (!frag_stream.exists(bank)){ std::cerr << "No fragment account found in bank " << bank << std::endl; exit(1); } try { frag_stream.open(bank, AMOS::B_READ); } catch (AMOS::Exception_t & e) { std::cerr << "Failed to open fragment account in bank " << bank << ": " << std::endl << e << std::endl; exit(1); } AMOS::BankStream_t link_stream (AMOS::ContigLink_t::NCODE); if (!link_stream.exists(bank)){ std::cerr << "No contig link account found in bank " << bank << std::endl; exit(1); } try { link_stream.open(bank, AMOS::B_READ); } catch (AMOS::Exception_t & e) { std::cerr << "Failed to open contig link account in bank " << bank << ": " << std::endl << e << std::endl; exit(1); } std::string outputFile = outputPrefix + ".evidence.xml"; std::ofstream stream; stream.open(outputFile.c_str(), std::ios::out); time_t t; time(&t); stream << "<?xml version=\"1.0\" ?>" << std::endl; stream << std::endl; stream << "<EVIDENCE ID=\"" + outputPrefix << "\"" << std::endl; stream << "\t\tDATE=\"" << ctime(&t) << "\"" << std::endl; stream << "\t\tPROJECT=\"catXML\"" << std::endl; stream << "\t\tPARAMETERS=\"" << outputFile << "\"" << std::endl; stream << ">" << std::endl; // output libraries // build a map for library to fragments AMOS::Fragment_t frg; HASHMAP::hash_map<AMOS::ID_t, std::vector<AMOS::Fragment_t>, HASHMAP::hash<AMOS::ID_t>, HASHMAP::equal_to<AMOS::ID_t> > lib2frg; while (frag_stream >> frg) { lib2frg[frg.getLibrary()].push_back(frg); } AMOS::Library_t lib; while (library_stream >> lib) { double min = lib.getDistribution().mean - (3*lib.getDistribution().sd); double max = lib.getDistribution().mean + (3*lib.getDistribution().sd); stream << "\t<LIBRARY ID=\"" << lib.getIID() << "\" NAME=\"" << lib.getEID() << "\" MIN=\"" << min << "\" MAX=\"" << max << "\">" << std::endl; for (std::vector<AMOS::Fragment_t>::const_iterator i = lib2frg[lib.getIID()].begin(); i < lib2frg[lib.getIID()].end(); i++) { stream << "\t\t<INSERT ID=\"ins_" << i->getIID() << "\" NAME=\"" << i->getEID() << "\">" << std::endl; stream << "\t\t\t<SEQUENCE ID=\"seq_" << i->getMatePair().first << "\" NAME=\"" << i->getEID() << "_L\"></SEQUENCE>" << std::endl; stream << "\t\t\t<SEQUENCE ID=\"seq_" << i->getMatePair().second << "\" NAME=\"" << i->getEID() << "_R\"></SEQUENCE>" << std::endl; stream << "\t\t</INSERT>" << std::endl; } stream << "\t</LIBRARY>" << std::endl; } frag_stream.close(); library_stream.close(); // output contigs for (AMOS::IDMap_t::const_iterator ci = contig_bank.getIDMap().begin(); ci; ci++) { AMOS::Contig_t ctg; contig_bank.fetch(ci->iid, ctg); stream << "\t<CONTIG ID=\"contig_" << ctg.getIID() << "\" NAME=\"" << ctg.getEID() << "\" LEN=\"" << ctg.getLength() << "\">" << std::endl; const std::vector<AMOS::Tile_t> &tiling = ctg.getReadTiling(); for (std::vector<AMOS::Tile_t>::const_iterator i = tiling.begin(); i < tiling.end(); i++) { stream << "\t\t<SEQUENCE ID=\"seq_" << i->source << "\" ORI=\"" << (i->range.isReverse() ? "EB" : "BE") << "\" ASM_LEND=\"" << i->offset << "\" ASM_REND=\"" << i->getRightOffset() << "\"></SEQUENCE>" << std::endl; } stream << "\t</CONTIG>" << std::endl; } // here we output any CTE between contigs that are not the result of link data AMOS::ContigLink_t clk; while (link_stream >> clk) { if (clk.getSource().second != AMOS::Fragment_t::NCODE) { stream << "\t<LINK ID=\"link_" << clk.getIID() << "\" SIZE=\"" << clk.getSize() << "\"TYPE=\"" << clk.getType() << "\">" << std::endl; std::string oriCtgA = "BE"; std::string oriCtgB = "BE"; switch (clk.getAdjacency()) { case AMOS::Link_t::NORMAL: oriCtgA = oriCtgB = "BE"; break; case AMOS::Link_t::ANTINORMAL: oriCtgA = oriCtgB = "EB"; break; case AMOS::Link_t::OUTIE: oriCtgA = "EB"; oriCtgB = "BE"; break; case AMOS::Link_t::INNIE: oriCtgA = "BE"; oriCtgB = "EB"; break; }; stream << "\t\t<CONTIG ID=\"" << clk.getContigs().first << "\"ORI=\"" << oriCtgA << "\">" << std::endl; stream << "\t\t<CONTIG ID=\"" << clk.getContigs().second << "\"ORI=\"" << oriCtgB << "\">" << std::endl; } } stream << "</EVIDENCE>" << std::endl; stream.close(); link_stream.close(); } void outputOutXML(const std::string &bank, AMOS::Bank_t &edge_bank, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, int32_t debug) { AMOS::Bank_t link_bank (AMOS::ContigLink_t::NCODE); if (!link_bank.exists(bank)){ std::cerr << "No contig link account found in bank " << bank << std::endl; exit(1); } try { link_bank.open(bank, AMOS::B_READ); } catch (AMOS::Exception_t & e) { std::cerr << "Failed to open contig link account in bank " << bank << ": " << std::endl << e << std::endl; exit(1); } HASHMAP::hash_map<AMOS::ID_t, int, HASHMAP::hash<AMOS::ID_t>, HASHMAP::equal_to<AMOS::ID_t> > outputLinks; std::string outputFile = outputPrefix + ".out.xml"; std::ofstream stream; stream.open(outputFile.c_str(), std::ios::out); stream << "<GROUPING>" << std::endl; AMOS::Scaffold_t scf; while (scf_stream >> scf) { stream << "\t<SCAFFOLD ID = \"scaff_" << scf.getIID() << "\">" << std::endl; // output the contigs for (std::vector<AMOS::Tile_t>::const_iterator tileIt = scf.getContigTiling().begin(); tileIt < scf.getContigTiling().end(); tileIt++) { std::string ori = "BE"; if (tileIt->range.isReverse()) { ori = "EB"; } stream << "\t\t<CONTIG ID=\"contig_" << tileIt->source << "\"" << std::endl; stream << "\tX=\"" << tileIt->offset << "\"" << std::endl; stream << "\tORI=\"" << ori << "\"" << std::endl; stream << "></CONTIG>" << std::endl; } // output the links in the scaffold for (std::vector<AMOS::ID_t>::const_iterator edgeIt = scf.getContigEdges().begin(); edgeIt < scf.getContigEdges().end(); edgeIt++) { AMOS::ContigEdge_t cte; edge_bank.fetch(*edgeIt, cte); if (!isBadEdge(cte)) { std::vector<AMOS::ID_t>::const_iterator linkIt = cte.getContigLinks().begin(); for (; linkIt < cte.getContigLinks().end(); linkIt++) { stream << "\t\t<LINK ID=\"ins_" << translateCLKtoFRG(link_bank, *linkIt) << "\"" << std::endl; stream << "\tVALID=\"VALID\"" << std::endl; stream << "\tTAG=\"T\"" << std::endl; stream << "></LINK>" << std::endl; // store list of links weve output outputLinks[(*linkIt)] = 1; } } } stream << "\t</SCAFFOLD>" << std::endl; } // output the bad edges stream << "\t<UNUSED>" << std::endl; for (AMOS::IDMap_t::const_iterator ci = edge_bank.getIDMap().begin(); ci; ci++) { AMOS::ContigEdge_t cte; edge_bank.fetch(ci->iid, cte); std::string status; if (!isBadEdge(cte)) { continue; } switch (cte.getStatus()) { case BAD_THRESH: case BAD_RPT: status = "UNSEEN"; break; case BAD_SKIP: case BAD_SCF: status = "UNUSED"; break; case BAD_DST: status = "LEN"; break; case BAD_ORI: status = "ORI"; break; case BAD_TRNS: status = "TRANSITIVE"; break; default: assert(0); break; } for (std::vector<AMOS::ID_t>::const_iterator linkIt = cte.getContigLinks().begin(); linkIt < cte.getContigLinks().end(); linkIt++) { stream << "\t\t<LINK ID=\"ins_" << translateCLKtoFRG(link_bank, *linkIt) << "\"" << std::endl; stream << "\t\t\tVALID=\"" << status << "\"" << std::endl; stream << "\t\t\tTAG=\"T\"" << std::endl; stream << "\t\t></LINK>" << std::endl; outputLinks[(*linkIt)] = 1; } } // finally make sure all links have been output for (AMOS::IDMap_t::const_iterator ci = link_bank.getIDMap().begin(); ci; ci++) { if (outputLinks[ci->iid] != 1) { stream << "\t\t<LINK ID=\"ins_" << translateCLKtoFRG(link_bank, ci->iid) << "\"" << std::endl; stream << "\t\t\tVALID=\"" << "UNUSED" << "\"" << std::endl; stream << "\t\t\tTAG=\"T\"" << std::endl; stream << "\t\t></LINK>" << std::endl; } } stream << "\t</UNUSED>" << std::endl; stream << "</GROUPING>" << std::endl; stream.close(); link_bank.close(); } void outputBAMBUS( const std::string &bank, AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::BankStream_t &scf_stream, const std::string &outputPrefix, int32_t debug) { outputLibrary(bank, outputPrefix, debug); outputEvidenceXML(bank, contig_bank, outputPrefix, debug); outputOutXML(bank, edge_bank, scf_stream, outputPrefix, debug); } void outputResults( const std::string &bank, AMOS::Bank_t &contig_bank, AMOS::Bank_t &edge_bank, AMOS::BankStream_t &motif_stream, AMOS::BankStream_t &scf_stream, outputType type, const std::string &outputPrefix, int32_t debug) { AMOS::Scaffold_t * scf = new AMOS::Scaffold_t(); if (scf_stream.getSize() == 0) { return; } switch (type) { case AGP: outputAGP(contig_bank, scf_stream, outputPrefix, debug); break; case DOT: outputDOT(contig_bank, edge_bank, scf, scf_stream, outputPrefix, debug); break; case MOTIFS: outputMotifs(contig_bank, edge_bank, motif_stream, outputPrefix, debug); break; case BAMBUS: outputBAMBUS(bank, contig_bank, edge_bank, scf_stream, outputPrefix, debug); break; } delete scf; } }
39.949025
225
0.563049
[ "object", "shape", "vector", "solid" ]
bd96c29250242698af85b7302213577d67170ed3
6,848
hxx
C++
interface/sqlite_statement.hxx
ANSAKsoftware/ansak-lib
93eff12a50464f3071b27c8eb16336f93d0d04c6
[ "BSD-2-Clause" ]
null
null
null
interface/sqlite_statement.hxx
ANSAKsoftware/ansak-lib
93eff12a50464f3071b27c8eb16336f93d0d04c6
[ "BSD-2-Clause" ]
null
null
null
interface/sqlite_statement.hxx
ANSAKsoftware/ansak-lib
93eff12a50464f3071b27c8eb16336f93d0d04c6
[ "BSD-2-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Arthur N. Klassen // 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. // // 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. // /////////////////////////////////////////////////////////////////////////// // // 2014.11.01 // // May you do good and not evil. // May you find forgiveness for yourself and forgive others. // May you share freely, never taking more than you give. // /////////////////////////////////////////////////////////////////////////// // // sqlite_statement.hxx -- A class to wrap individual SQLite statements // once prepared against a particular database, to // bind data values into it, to retrieve results out. // /////////////////////////////////////////////////////////////////////////// #pragma once #include <sqlite3.h> #include <string> #include <vector> #include <memory> namespace ansak { class SqliteDB; class SqliteStatement; typedef std::shared_ptr<SqliteStatement> SqliteStatementPtr; /////////////////////////////////////////////////////////////////////////// // class sqliteStatement -- wrapper for a SQLITE3 statement, including // binding-in, retrieving out, executing, resetting class SqliteStatement { friend class SqliteDB; protected: //======================================================================= // Constructor, private -- called only by SqliteDB::prepare SqliteStatement(); public: static const bool resetOnlyStatement = true; //======================================================================= // Copy Constructor, assignment deleted SqliteStatement(const SqliteStatement& src) = delete; SqliteStatement& operator=(const SqliteStatement& src) const = delete; //======================================================================= // Destructor virtual ~SqliteStatement(); //======================================================================= // setBeginTransaction // // Set this statement's first execution to be the one that starts a // transaction. No checking against current transaction states in the SQLite // database is done here. The caller is expected to be sensible virtual void setBeginTransaction() = 0; //======================================================================= // setEndTransaction // // Set this statement's "done" execution to be the one that ends a // transaction. No checking against current transaction states in the SQLite // database is done here. The caller is expected to be sensible virtual void setEndTransaction() = 0; //======================================================================= // id // // Returns a serial number for the statement across the whole process. virtual int id() const = 0; //======================================================================= // bind // // Bind a double, int, long long, string or 0-terminated char*, // vector<char> or length-terminated char* for the different data type into // a compiled statement. virtual void bind ( int n, // I - a 0-based index into the statement double d // I - a value to bind into the statement ) = 0; virtual void bind(int n, int i) = 0; virtual void bind(int n, long long i64) = 0; virtual void bind(int n, const std::string& text) = 0; virtual void bind(int n, const char* text) = 0; virtual void bind(int n, std::vector<char>& data) = 0; virtual void bind(int n, const char* data, int dataLength) = 0; //======================================================================= // setupRetrieval // // Set up the retreival of a double, int, long long, string or 0-terminated // char*, vector<char> or length-terminated char* for the different data // type out of a query's columns. Optionally, detect whether a value is // null. virtual void setupRetrieval ( int n, // I - a 0-based index into the columns double& d, // O - (via operator()) where to store the value bool* pIsNull = 0 // O - whether a column is NULL ) = 0; virtual void setupRetrieval(int n, int& i, bool* pIsNull = 0) = 0; virtual void setupRetrieval(int n, long long& i64, bool* pIsNull = 0) = 0; virtual void setupRetrieval(int n, std::string& text, bool* pIsNull = 0) = 0; virtual void setupRetrieval(int n, std::vector<char>& data, bool* pIsNull = 0) = 0; //======================================================================= // operator() // // Executes the query for each row of the query. Pushes back true when a // query is done, false otherwise, optional either way. virtual void operator() ( bool* done = 0 // O - sets the value true if the query has completed ) = 0; //======================================================================= // reset // // Clears the binds and retrieves and resets the execution of a query so that // it can be done again. virtual void reset ( bool minimalReset = false // I - reset only the statement, not retrieves, binds ) = 0; //======================================================================= // sql // // Returns the originally prepared SQL statement. virtual std::string sql() = 0; }; }
36.817204
93
0.544393
[ "vector" ]
bda79d7e14d25777e354a169e64ab15671818674
523
cpp
C++
5e/C++11/400_shared_ptr.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
5e/C++11/400_shared_ptr.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
5e/C++11/400_shared_ptr.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
1
2022-01-25T15:51:34.000Z
2022-01-25T15:51:34.000Z
#include <memory> #include <iostream> #include <list> #include <vector> using namespace std; int main(void) { shared_ptr<string> p1; shared_ptr<list<int>> p2; if(p1 && p1->empty()) *p1 = "hi"; shared_ptr<int> p3 = make_shared<int>(42); shared_ptr<string> p4 = make_shared<string>(10, '9'); shared_ptr<int> p5 = make_shared<int>(); auto p6 = make_shared<vector<string>>(); auto p = make_shared<int>(42); auto q(p); auto r = make_shared<int>(42); r = q; return 0; }
20.92
57
0.604207
[ "vector" ]
bdaa22f471698b243ca0789c3e6c44bb40d05250
23,214
cpp
C++
PuyoPuyo/PuyoPuyoGame.cpp
Yosbi/PuyoPuyo
d0a0e9717f7918f8ee174f4eb52ca45a1f19288f
[ "MIT" ]
null
null
null
PuyoPuyo/PuyoPuyoGame.cpp
Yosbi/PuyoPuyo
d0a0e9717f7918f8ee174f4eb52ca45a1f19288f
[ "MIT" ]
null
null
null
PuyoPuyo/PuyoPuyoGame.cpp
Yosbi/PuyoPuyo
d0a0e9717f7918f8ee174f4eb52ca45a1f19288f
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------- // file: PuyoPuyoGame.cpp // Author: Yosbi Alves // mail: yosbi@outlook.com // phone: +584248157737 //----------------------------------------------------------------------- //Desc: This is the class for the game, it acts as a world-controller and // having the main game logic implemented //-------------------------------------------------------------------------- #include "PuyoPuyoGame.h" #include "resource.h" //========================================================= // Name: PuyoPuyoGame // Desc: constructor, init the initial game state //========================================================= PuyoPuyoGame::PuyoPuyoGame(HINSTANCE hAppInst, HWND hMainWnd) { // Save input parameters. m_hAppInst = hAppInst; m_hMainWnd = hMainWnd; // Set seed for the randor number generator srand((unsigned int)time(0)); // The game is initially paused. m_bPaused = true; // The game is not initially over m_bGameOver = false; // Init the score m_nScore = 0; // Create the sprites: m_GameBoard = new Sprite(m_hAppInst, "res/back.bmp" , "res/backmask.bmp", 0.0f, 0.0f); m_BlueSphere = new Sprite(m_hAppInst, "res/blue.bmp" , "res/mask.bmp", 0.0f, 0.0f); m_GreenSphere = new Sprite(m_hAppInst, "res/green.bmp" , "res/mask.bmp", 0.0f, 0.0f); m_RedSphere = new Sprite(m_hAppInst, "res/red.bmp" , "res/mask.bmp", 0.0f, 0.0f); m_YellowSphere = new Sprite(m_hAppInst, "res/yellow.bmp" , "res/mask.bmp", 0.0f, 0.0f); // init the board for (int y = 0; y < nGameBoardHeight; y++) { for (int x = 0; x < nGameBoardWidth; x++) { GameBoard[y][x].m_spheretype = NONE; GameBoard[y][x].m_bChecked = false; } } newPlayerSpheres(); } //========================================================= // Name: PuyoPuyoGame // Desc: destructor //========================================================= PuyoPuyoGame::~PuyoPuyoGame() { delete m_GameBoard; delete m_BlueSphere; delete m_GreenSphere; delete m_RedSphere; delete m_YellowSphere; } //========================================================= // Name: pause // Desc: this method pause or unpause the game //========================================================= void PuyoPuyoGame::pause() { m_bPaused = !m_bPaused; } //========================================================= // Name: draw // Desc: this method draws all the sprites in the backbuffer // it draws depending on the GameBoard state //========================================================= void PuyoPuyoGame::draw(HDC hBackBufferDC, HDC hSpriteDC) { // Draw the sprites: // Draw the game board m_GameBoard->draw(hBackBufferDC, hSpriteDC); // Draw the spheres for (int y = 2; y < nGameBoardHeight; y++) { for (int x = 0; x < nGameBoardWidth; x++) { // if they are in a visible position // transform the GameBoar's position in screen position float nPosX = ( (float)x * 300) / 6; float nPosY = ( ( (float)y - 2) * 600) / 12; switch(GameBoard[y][x].m_spheretype) { case RED: m_RedSphere->update(nPosX, nPosY); m_RedSphere->draw(hBackBufferDC, hSpriteDC); break; case GREEN: m_GreenSphere->update(nPosX, nPosY); m_GreenSphere->draw(hBackBufferDC, hSpriteDC); break; case BLUE: m_BlueSphere->update(nPosX, nPosY); m_BlueSphere->draw(hBackBufferDC, hSpriteDC); break; case YELLOW: m_YellowSphere->update(nPosX, nPosY); m_YellowSphere->draw(hBackBufferDC, hSpriteDC); break; } } } // Draw the player's score char score[24]; sprintf_s(score, "Score: %d", m_nScore); SetBkMode(hBackBufferDC, TRANSPARENT); TextOut(hBackBufferDC, 2, 0, score, (int)strlen(score)); // If it is game over print the "game over" message if (m_bGameOver) { char msg1[] = "GAME OVER!"; char msg2[] = "Press enter to play again!"; sprintf_s(score, "Your score: %d", m_nScore); TextOut(hBackBufferDC, (300 / 2) - 50, 150, msg1, (int)strlen(msg1)); TextOut(hBackBufferDC, (300 / 2) - 85, 165, msg2, (int)strlen(msg2)); TextOut(hBackBufferDC, (300 / 2) - 50, 180, score, (int)strlen(score)); } // If it is paused print the "Game paused" message if (m_bPaused) { char msg1[] = "Game paused..."; char msg2[] = "Press enter to play!"; SetBkMode(hBackBufferDC, TRANSPARENT); TextOut(hBackBufferDC, (300 / 2) - 55, 150, msg1, (int)strlen(msg1)); TextOut(hBackBufferDC, (300 / 2) - 70, 165, msg2, (int)strlen(msg2)); } } //========================================================= // Name: getRandonSphere // Desc: this method returns a randon sphere color to put // in the start zone //========================================================= SPHERETYPE PuyoPuyoGame::getRandonSphere() { return (SPHERETYPE)(1 + (rand() % 4)); // randon number between 1 and 4 } //========================================================= // Name: update // Desc: This method handles the update of all the GameBoard. // Also if both of the player's spheres has fallen down // then it makes the call to check for spheres links //========================================================= void PuyoPuyoGame::update() { if (!m_bGameOver) { if (!m_bPaused) { // If any of the player`s spheres still falling then if ((m_playerSphere1.m_bFalling) || (m_playerSphere2.m_bFalling)) { updateBoard(); } // When both of the player's spheres has fallen I check for the spheres's links if ((!m_playerSphere1.m_bFalling) && (!m_playerSphere2.m_bFalling)) { // if there are no more updates on the board if (updateBoard() == false) { // and if there are no links if (checkLinks() == false) { m_bNewPlayerSpheres = true; } } } // if new pair of spheres is needed if (m_bNewPlayerSpheres) { // get a new pair of spheres for the player newPlayerSpheres(); } } } } //========================================================= // Name: checkLinks // Desc: this method check if there are links in the spheres // if there are, then it erase the balls and return // true //========================================================= bool PuyoPuyoGame::checkLinks() { // if there has been a erase then this value will be true, // it is used as a return value to check if we need a new // pair of player's spheres or not bool bErase = false; // check the gameboard from the botton to the top for (int y = nGameBoardHeight - 1; y >= 2; y--) { for (int x = 0; x < nGameBoardWidth; x++) { // If I have no checked this slot and is not empty if ((GameBoard[y][x].m_bChecked == false) && (GameBoard[y][x].m_spheretype != NONE)) { // This vector is used to store the pointers to all the spheres of the same color that // we are checking now std::vector<BoardSlot*> vecBoardSlot; // Call this recursive method that will search for all the ocurrences of spheres of // same color and then store them in the vector vecBoardSlot check(x, y, vecBoardSlot); // if there are more than 4 slot of the same color, erase them if (vecBoardSlot.size() >= 4) { // there exitst at least one erase bErase = true; // this is the counter that will count the score that was achieved in this move int nScoreCounter = 0; for (std::vector<BoardSlot*>::iterator it = vecBoardSlot.begin(); it < vecBoardSlot.end(); it++) { (*it)->m_spheretype = NONE; // <-- erase the sphere nScoreCounter++; } // Add the score achieved by this move to the general score m_nScore += nScoreCounter - 3; // The score adds one from 4 } } } } // return the board to a no-checked state for (int y = nGameBoardHeight - 1; y >= 0; y--) { for (int x = 0; x < nGameBoardWidth; x++) { GameBoard[y][x].m_bChecked = false; } } return bErase; } //========================================================= // Name: check // Desc: recursive method that will search for all the ocurrences of spheres of // same color and then store them in the vector vecBoardSlot //========================================================= void PuyoPuyoGame::check(int x, int y, std::vector<BoardSlot*>& vecBoardSlot) { // first set this slot as checked GameBoard[y][x].m_bChecked = true; // Store the pointer to this slot in the vector vecBoardSlot.push_back(&GameBoard[y][x]); // Now I look for other nodes with the same color in this order: DOWN LEFT UP RIGHT // Looking RIGHT if (x < nGameBoardHeight - 1) { // if the down slot has not been checked and is the same color as this if ((GameBoard[y][x + 1].m_bChecked == false) && (GameBoard[y][x + 1].m_spheretype == GameBoard[y][x].m_spheretype)) { // I check it check(x + 1, y , vecBoardSlot); } } // Looking UP (must be less that two because the playable field beggins at the slot 2) if (y > 2) { // if the down slot has not been checked and is the same color as this if ((GameBoard[y - 1][x].m_bChecked == false) && (GameBoard[y - 1][x].m_spheretype == GameBoard[y][x].m_spheretype)) { // I check it check(x, y - 1 , vecBoardSlot); } } // Looking LEFT if (x > 0) { // if the down slot has not been checked and is the same color as this if ((GameBoard[y][x - 1].m_bChecked == false) && (GameBoard[y][x - 1].m_spheretype == GameBoard[y][x].m_spheretype)) { // I check it check(x - 1, y , vecBoardSlot); } } // Looking DOWN if (y < nGameBoardHeight - 1) { // if the down slot has not been checked and is the same color as this if ((GameBoard[y + 1][x].m_bChecked == false) && (GameBoard[y + 1][x].m_spheretype == GameBoard[y][x].m_spheretype)) { // I check it check(x, y + 1, vecBoardSlot); } } } //========================================================= // Name: updateBoard // Desc: This method updates the board, it returns true // if there has been at least a movement on the board //========================================================= bool PuyoPuyoGame::updateBoard() { // the movement only can occur when it is not paused if (m_bPaused) return false; bool bMovement = false; for (int y = nGameBoardHeight - 1; y >= 0 ; y--) { for (int x = 0; x < nGameBoardWidth; x++) { // if there is a space below this sphere and it is a blank space if ((y < nGameBoardHeight - 1) && (GameBoard[y + 1][x].m_spheretype == NONE) && (GameBoard[y][x].m_spheretype != NONE)) { // there has been a movement bMovement = true; // move the ball down GameBoard[y + 1][x].m_spheretype = GameBoard[y][x].m_spheretype; GameBoard[y][x].m_spheretype = NONE; // if the updated is the sphere of the player if ((m_playerSphere1.m_nX == x) && (m_playerSphere1.m_nY == y)) { m_playerSphere1.m_nY = y + 1; } if ((m_playerSphere2.m_nX == x) && (m_playerSphere2.m_nY == y)) { m_playerSphere2.m_nY = y + 1; } } else // if there is not space in blank to move { // if this is any of the player's spheres then set the falling state to false if ((m_playerSphere1.m_nX == x) && (m_playerSphere1.m_nY == y)) { m_playerSphere1.m_bFalling = false; } if ((m_playerSphere2.m_nX == x) && (m_playerSphere2.m_nY == y)) { m_playerSphere2.m_bFalling = false; } } } } return bMovement; } //========================================================= // Name: newPlayerSpheres // Desc: This method bring a new pair of random player's // spheres into the game, if it cannot put the // new pair then it is game over! //========================================================= void PuyoPuyoGame::newPlayerSpheres() { // if there is still space to put spheres if ((GameBoard[1][2].m_spheretype == NONE) && (GameBoard[0][2].m_spheretype == NONE)) { // Setting the first sphere to fall GameBoard[1][2].m_spheretype = getRandonSphere(); GameBoard[0][2].m_spheretype = getRandonSphere(); // saving the sphere of the user m_playerSphere1.setPos(2, 1); m_playerSphere1.m_bFalling = true; m_playerSphere1.m_position = DOWN; m_playerSphere2.setPos(2, 0); m_playerSphere2.m_bFalling = true; m_playerSphere2.m_position = UP; // Now we dont need a new pair m_bNewPlayerSpheres = false; } else { // The game is over! m_bGameOver = true; } } //========================================================= // Name: rotate // Desc: rotate the secondary sphere to the clockwise or // counter clockwise depending of the user input //========================================================= void PuyoPuyoGame::rotate(SPHEREPOSITION wantedRot) { // If the game is not paused if (m_bPaused) return; // Rotation can only happen if both player's sphere are falling if ( (!m_playerSphere1.m_bFalling) || (!m_playerSphere2.m_bFalling) ) return; // getting the next position for the secondary sphere switch (getNextPosition(wantedRot)) { case UP: { GameBoard[m_playerSphere1.m_nY - 1][m_playerSphere1.m_nX].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE, m_playerSphere2.setPos(m_playerSphere1.m_nX, m_playerSphere1.m_nY - 1); m_playerSphere2.m_position = UP; m_playerSphere1.m_position = DOWN; break; } case LEFT: { // if there is no room in the gameboard to rotate or there is a slot occupied if ((m_playerSphere2.m_nX == 0) || (GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX - 1].m_spheretype != NONE)) { // check if the primary sphere can be moved to the right if (GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX + 1].m_spheretype == NONE) { GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX + 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE, m_playerSphere2.setPos(m_playerSphere1.m_nX, m_playerSphere1.m_nY); m_playerSphere2.m_position = LEFT; m_playerSphere1.m_nX++; m_playerSphere1.m_position = RIGHT; } } else // rotate normally { GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX - 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE, m_playerSphere2.setPos(m_playerSphere1.m_nX - 1, m_playerSphere1.m_nY); m_playerSphere2.m_position = LEFT; m_playerSphere1.m_position = RIGHT; } break; } case DOWN: { // Check if the slot below is not ocuppied and if there is room in the gameboard if ((GameBoard[m_playerSphere1.m_nY + 1][m_playerSphere1.m_nX].m_spheretype == NONE) && (m_playerSphere1.m_nY < nGameBoardHeight - 1)) { GameBoard[m_playerSphere1.m_nY + 1][m_playerSphere1.m_nX].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE, m_playerSphere2.setPos(m_playerSphere1.m_nX, m_playerSphere1.m_nY + 1); m_playerSphere2.m_position = DOWN; m_playerSphere1.m_position = UP; } break; } case RIGHT: { // if there is no room in the gameboard to rotate or there is a slot occupied if ((m_playerSphere2.m_nX == nGameBoardWidth - 1) || (GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX + 1].m_spheretype != NONE)) { // check if the primary sphere can be moved to the left if (GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX - 1].m_spheretype == NONE) { GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX - 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE, m_playerSphere2.setPos(m_playerSphere1.m_nX, m_playerSphere1.m_nY); m_playerSphere2.m_position = RIGHT; m_playerSphere1.m_nX--; m_playerSphere1.m_position = LEFT; } } else // rotate normally { GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX + 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE, m_playerSphere2.setPos(m_playerSphere1.m_nX + 1, m_playerSphere1.m_nY); m_playerSphere2.m_position = RIGHT; m_playerSphere1.m_position = LEFT; } break; } } } //========================================================= // Name: getNextPosition // Desc: this method returns the next position of the // secondary player's sphere depending on the // user's input //========================================================= SPHEREPOSITION PuyoPuyoGame::getNextPosition(SPHEREPOSITION wantedRot) { switch (m_playerSphere2.m_position) { case UP: { if (wantedRot == LEFT) return LEFT; else return RIGHT; break; } case LEFT: { if (wantedRot == LEFT) return DOWN; else return UP; break; } case DOWN: { if (wantedRot == LEFT) return RIGHT; else return LEFT; break; } case RIGHT: { if (wantedRot == LEFT) return UP; else return DOWN; break; } } return wantedRot; } //========================================================= // Name: move // Desc: move the spheres right or left depending on the // user's input //========================================================= void PuyoPuyoGame::move(SPHEREPOSITION wantedPos) { // If the game is not paused if (m_bPaused) return; // left or right movement can only happen if both player's sphere are falling if ( (!m_playerSphere1.m_bFalling) || (!m_playerSphere2.m_bFalling) ) return; // if movement is left if ((wantedPos == LEFT) && (canMove(LEFT))) { // if sphere1 is left then move it first if (m_playerSphere1.m_position == LEFT) { GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX - 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX - 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE; } // if the sphere 2 is left the move it first else if (m_playerSphere2.m_position == RIGHT) { GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX - 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX - 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype = NONE; } // if one is above the other it does not matter the order of movement else { GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX - 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX - 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype = NONE; } m_playerSphere1.m_nX--; m_playerSphere2.m_nX--; } // if movement is right else if ((wantedPos == RIGHT) && (canMove(RIGHT))) { // if sphere1 is left then move it first if (m_playerSphere1.m_position == RIGHT) { GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX + 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX + 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE; } // if the sphere 2 is left the move it first else if (m_playerSphere2.m_position == RIGHT) { GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX + 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX + 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype = NONE; } // if one is above the other it does not matter the order of movement else { GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX + 1].m_spheretype = GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype; GameBoard[m_playerSphere2.m_nY][m_playerSphere2.m_nX].m_spheretype = NONE; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX + 1].m_spheretype = GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype; GameBoard[m_playerSphere1.m_nY][m_playerSphere1.m_nX].m_spheretype = NONE; } m_playerSphere1.m_nX++; m_playerSphere2.m_nX++; } } //========================================================= // Name: canMove // Desc: return true if the player's spheres can be moved // left or right (depending on the user's input) //========================================================= bool PuyoPuyoGame::canMove(SPHEREPOSITION wantedPos) { int x1 = m_playerSphere1.m_nX; int y1 = m_playerSphere1.m_nY; int x2 = m_playerSphere2.m_nX; int y2 = m_playerSphere2.m_nY; // if the wanted pos is right if (wantedPos == LEFT) { // If the spheres will not go outside boundaries if ((x1 > 0 ) && (x2 > 0 )) { // If any of the balls dont colide with other ball ignoring themselves if ( ( (GameBoard[y1][x1 - 1].m_spheretype == NONE) || ((y1 == y2) && (x1 - 1 == x2)) ) && ( (GameBoard[y2][x2 - 1].m_spheretype == NONE) || ((y1 == y2) && (x2 - 1 == x1)) ) ) { return true; } } } else if (wantedPos == RIGHT) { // If the spheres will not go outside boundaries if ((x1 < nGameBoardWidth - 1) && (x2 < nGameBoardWidth - 1)) { // If any of the balls dont colide with other ball ignoring themselves if ( ( (GameBoard[y1][x1 + 1].m_spheretype == NONE) || ((y1 == y2) && (x1 + 1 == x2)) ) && ( (GameBoard[y2][x2 + 1].m_spheretype == NONE) || ((y1 == y2) && (x2 + 1 == x1)) ) ) { return true; } } } return false; }
34.803598
146
0.611484
[ "vector", "transform" ]
bdb54c2b8913cea5668a7b3a74b2d14f4df8612f
3,064
cc
C++
brave/common/extensions/crypto_bindings.cc
kewde/muon
43661f9a8ceefda8e3aba0e8944a72995aa53281
[ "MIT" ]
1,027
2016-12-24T13:05:29.000Z
2022-02-21T11:07:32.000Z
brave/common/extensions/crypto_bindings.cc
imagineagents/muon
666af3b6e29afb928a2f50061fb5c5afad78a9c1
[ "MIT" ]
366
2016-12-24T05:58:54.000Z
2018-12-31T23:02:03.000Z
brave/common/extensions/crypto_bindings.cc
imagineagents/muon
666af3b6e29afb928a2f50061fb5c5afad78a9c1
[ "MIT" ]
122
2017-01-14T23:48:49.000Z
2022-03-09T01:51:53.000Z
// Copyright (c) 2017 The Brave 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 "brave/common/extensions/crypto_bindings.h" #include <memory> #include <string> #include "base/base64.h" #include "components/os_crypt/os_crypt.h" #include "extensions/renderer/script_context.h" #include "extensions/renderer/v8_helpers.h" #include "gin/converter.h" #include "v8/include/v8.h" namespace brave { CryptoBindings::CryptoBindings( extensions::ScriptContext* context) : extensions::ObjectBackedNativeHandler(context) {} CryptoBindings::~CryptoBindings() {} void CryptoBindings::AddRoutes() { RouteHandlerFunction( "EncryptString", base::Bind(&CryptoBindings::EncryptString, base::Unretained(this))); RouteHandlerFunction( "DecryptString", base::Bind(&CryptoBindings::DecryptString, base::Unretained(this))); } // static v8::Local<v8::Object> CryptoBindings::API( extensions::ScriptContext* context) { context->module_system()->RegisterNativeHandler( "muon_crypto", std::unique_ptr<extensions::NativeHandler>( new CryptoBindings(context))); v8::Local<v8::Object> crypto = v8::Object::New(context->isolate()); context->module_system()->SetNativeLazyField( crypto, "encryptString", "muon_crypto", "EncryptString"); context->module_system()->SetNativeLazyField( crypto, "decryptString", "muon_crypto", "DecryptString"); return crypto; } void CryptoBindings::EncryptString( const v8::FunctionCallbackInfo<v8::Value>& args) { auto isolate = context()->isolate(); if (args.Length() != 1) { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`plaintext` is a required field")); return; } std::string plaintext = *v8::String::Utf8Value(args[0]); std::string ciphertext; if (OSCrypt::EncryptString(plaintext, &ciphertext)) { std::string encoded_cipher; base::Base64Encode(ciphertext, &encoded_cipher); args.GetReturnValue().Set(gin::ConvertToV8(isolate, encoded_cipher)); } else { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`EncryptString` failed")); } } void CryptoBindings::DecryptString( const v8::FunctionCallbackInfo<v8::Value>& args) { auto isolate = context()->isolate(); if (args.Length() != 1) { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`ciphertext` is a required field")); return; } std::string encoded_cipher = *v8::String::Utf8Value(args[0]); std::string ciphertext; if (!base::Base64Decode(encoded_cipher, &ciphertext)) { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "ciphertext should be in base64 format")); return; } std::string plaintext; if (OSCrypt::DecryptString(ciphertext, &plaintext)) { args.GetReturnValue().Set(gin::ConvertToV8(isolate, plaintext)); } else { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`DecryptString` failed")); } } } // namespace brave
31.587629
74
0.700392
[ "object" ]
bdb890052f90b08915aff6d1a554a55e0b4854bc
8,188
cpp
C++
src/axom/sidre/examples/sidre_mfem_datacollection_restart.cpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
86
2019-04-12T20:39:37.000Z
2022-01-28T17:06:08.000Z
src/axom/sidre/examples/sidre_mfem_datacollection_restart.cpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
597
2019-04-25T22:36:16.000Z
2022-03-31T20:21:54.000Z
src/axom/sidre/examples/sidre_mfem_datacollection_restart.cpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
21
2019-06-27T15:53:08.000Z
2021-09-30T20:17:41.000Z
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) /** * @file sidre_mfem_datacollection_restart.cpp * @brief This example code is a basic demonstration of Sidre's * MFEMSidreDataCollection class for restarting a simulation. * * To reload from a file, the cycle number to reload can be * specified as a command-line argument. * * For example, run * @code{.sh} * ./sidre_mfem_datacollection_restart # generates cycles 0-9 * # then... * ./sidre_mfem_datacollection_restart 9 # loads cycle 9 and continues * @endcode */ #include "axom/config.hpp" // Datacollection header #include "axom/sidre/core/MFEMSidreDataCollection.hpp" #include <memory> // for unique_ptr // Create a simple compiler define for whether we're using MPI #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) #define EXAMPLE_USES_MPI #include "mpi.h" #else #undef EXAMPLE_USES_MPI #endif // MFEM includes - needed to set up simulation #include "mfem.hpp" #include "axom/CLI11.hpp" // Stores the state of the simulation - a mesh, fields, and associated objects class SimulationState { public: // Initializes the simulation, using an existing file with specified cycle if // cycle_to_load is specified (>= 0) SimulationState(axom::sidre::MFEMSidreDataCollection& dc, const int cycle_to_load) : m_datacoll(dc) { #ifdef EXAMPLE_USES_MPI MPI_Comm_rank(m_datacoll.GetComm(), &m_rank); #endif // Check if this is a restart run if(cycle_to_load >= 0) { // If it is, we can load everything in and "unwrap" to fill in the state reloadSim(cycle_to_load); } // Otherwise it's a nominal run so we have to create everything // In a realistic simulation this is where an input file might be used else { setupNewSim(); } } ~SimulationState() { if(m_owns_data) { delete m_mesh; delete m_fecoll; delete m_fespace; delete m_soln_field; delete m_qspace; delete m_qfunc; } } // A simulated "step" of the simulation void step(double dt) { // Update simulation state variables double t = m_datacoll.GetTime(); t += dt; m_datacoll.SetTime(t); const int cycle = m_datacoll.GetCycle(); m_datacoll.SetCycle(cycle + 1); // Calculate the next iteration of the solution field... // For simplicity, every element in the field is set to the current time *m_soln_field = t; } private: // Simulation state setup void setupNewSim() { SLIC_INFO_IF(m_rank == 0, "Starting a new simulation"); // Everything here is managed by the SimulationState object m_owns_data = true; // Build a 2D mesh with 100 square elements m_mesh = new mfem::Mesh(10, 10, mfem::Element::QUADRILATERAL); #ifdef EXAMPLE_USES_MPI mfem::Mesh* tmp_mesh = m_mesh; m_mesh = new mfem::ParMesh(MPI_COMM_WORLD, *tmp_mesh); delete tmp_mesh; #endif // Set up the DataCollection with the newly created mesh m_datacoll.SetMesh(m_mesh); // Set up the FiniteElementSpace - needed for the grid functions // Initialize with H1 elements of order 1 m_fecoll = new mfem::H1_FECollection(/*order=*/1, m_mesh->Dimension()); #ifdef EXAMPLE_USES_MPI auto par_mesh = dynamic_cast<mfem::ParMesh*>(m_mesh); m_fespace = new mfem::ParFiniteElementSpace(par_mesh, m_fecoll); #else m_fespace = new mfem::FiniteElementSpace(m_mesh, m_fecoll); #endif // Initialize the solution field // Set the data to nullptr so the datacollection will initialize it with // its own managed data (needed for a restart) #ifdef EXAMPLE_USES_MPI auto par_fespace = dynamic_cast<mfem::ParFiniteElementSpace*>(m_fespace); m_soln_field = new mfem::ParGridFunction(par_fespace, static_cast<double*>(nullptr)); #else m_soln_field = new mfem::GridFunction(m_fespace, nullptr); #endif m_datacoll.RegisterField("solution", m_soln_field); // Intialize to zero as our "initial conditions" *m_soln_field = 0.0; // Initialize a quadrature function (per-qpt data) m_qspace = new mfem::QuadratureSpace(m_mesh, /*order=*/1); // Set the data to nullptr so the datacollection will initialize it with // its own managed data (needed for a restart) m_qfunc = new mfem::QuadratureFunction(m_qspace, nullptr); m_datacoll.RegisterQField("qpt_data", m_qfunc); *m_qfunc = 0.0; // Set t = 0 state info m_datacoll.SetCycle(0); // Iteration counter m_datacoll.SetTime(0.0); // Simulation time } // Sets up the state with non-owning pointers void reloadSim(const int cycle_to_load) { m_datacoll.Load(cycle_to_load); SLIC_INFO_IF(m_rank == 0, "Reading in existing data and restarting from iteration " << m_datacoll.GetCycle() << " at time " << m_datacoll.GetTime()); // The Mesh, GridFunction, etc, objects already exist and can be accessed m_mesh = m_datacoll.GetMesh(); m_soln_field = m_datacoll.GetField("solution"); m_fespace = m_soln_field->FESpace(); m_fecoll = m_fespace->FEColl(); m_qfunc = m_datacoll.GetQField("qpt_data"); m_qspace = m_qfunc->GetSpace(); } // FEM-related objects needed as part of a simulation // In a real simulation these would be exposed via accessors mfem::Mesh* m_mesh {nullptr}; const mfem::FiniteElementCollection* m_fecoll {nullptr}; mfem::FiniteElementSpace* m_fespace {nullptr}; mfem::GridFunction* m_soln_field {nullptr}; mfem::QuadratureSpace* m_qspace {nullptr}; mfem::QuadratureFunction* m_qfunc {nullptr}; bool m_owns_data {false}; // A reference to the datacollection so it can be updated with time/cycle // information on each time step axom::sidre::MFEMSidreDataCollection& m_datacoll; // The MPI rank, used to display messages on just one node int m_rank {0}; }; int main(int argc, char* argv[]) { #ifdef EXAMPLE_USES_MPI MPI_Init(&argc, &argv); #endif // Initialize the datacollection // Needs to be configured to own the mesh data so all mesh data is saved to datastore/output file const bool owns_mesh_data = true; axom::sidre::MFEMSidreDataCollection dc("sidre_mfem_datacoll_restart_ex", nullptr, owns_mesh_data); #ifdef EXAMPLE_USES_MPI dc.SetComm(MPI_COMM_WORLD); #endif // Command-line argument to load in a specific cycle - optional axom::CLI::App app {"Example of Axom's MFEMSidreDataCollection for restarts"}; int cycle_to_load = -1; std::vector<std::string> sidre_protocols = {"sidre_conduit_json", "sidre_json", "conduit_bin", "conduit_json", "json"}; #ifdef AXOM_USE_HDF5 std::string protocol = "sidre_hdf5"; sidre_protocols.push_back("sidre_hdf5"); sidre_protocols.push_back("conduit_hdf5"); #else std::string protocol = "sidre_conduit_json"; #endif app.add_option("--cycle", cycle_to_load) ->description("Optional simulation cycle to load") ->capture_default_str(); app.add_option("--protocol", protocol) ->description("Optional sidre protocol to use for checkpoints and restarts") ->check(axom::CLI::IsMember(sidre_protocols)) ->capture_default_str(); CLI11_PARSE(app, argc, argv); // Initialize the simulation data structures SimulationState sim_state(dc, cycle_to_load); // This is where the time-dependent operator would be set up... // Save initial state of simulation dc.Save("sidre_mfem_datacoll_restart_ex", protocol); // Sample time parameters const int n_iter = 10; const int n_checkpoint = 5; const double dt = 0.05; for(int i = 0; i < n_iter; i++) { sim_state.step(dt); if(i % n_checkpoint == 0) { // then save it at each checkpoint dc.Save("sidre_mfem_datacoll_restart_ex", protocol); } } #ifdef EXAMPLE_USES_MPI MPI_Finalize(); #endif }
31.6139
99
0.680142
[ "mesh", "object", "vector" ]
bdb8dc550d8c67db0235feaf7d4c58c5db150aa6
3,915
cc
C++
vos/p2/sub/data_transfer/DataSourceSocket.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
16
2020-10-21T05:56:26.000Z
2022-03-31T10:02:01.000Z
vos/p2/sub/data_transfer/DataSourceSocket.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
null
null
null
vos/p2/sub/data_transfer/DataSourceSocket.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
2
2021-03-09T01:51:08.000Z
2021-03-23T00:23:24.000Z
// Copyright (c) 1999, California Institute of Technology // U. S. Government sponsorship under NASA contract is acknowledged ////////////////////////////////////////////////////////////////////////////// // // DataSourceSocket.cc // // ////////////////////////////////////////////////////////////////////////////// #include <string.h> #include "DataSourceSocket.h" #include "return_status.h" #define DEV_DEBUG 0 ////////////////////////////////////////////////////////////////////////////// // // establish // // Create a new socket allowing others to connect. Does not return // until the other end of the socket has been connected. // ////////////////////////////////////////////////////////////////////////////// int DataSourceSocket::establish( int PortNumber) { int status; if (_source.connected()) { strcpy(_errorMessage,"Connection already exists"); return RTN_EXISTS_ERROR; } status = _source.create( PortNumber ); if (RTN_FAILURE(status)) { strcpy(_errorMessage,"Could not create socket"); _errorReason = _source.errorReason(); return status; } _active = 1; return RTN_NORMAL; } ////////////////////////////////////////////////////////////////////////////// // // connect // // Connect to an existing socket, created by another entity. // ////////////////////////////////////////////////////////////////////////////// int DataSourceSocket::connect( char *HostName, int PortNumber) { int status; if (_source.connected()) { strcpy(_errorMessage,"Connection already exists"); return RTN_EXISTS_ERROR; } status = _source.open(HostName, PortNumber); if (RTN_FAILURE(status)) { strcpy(_errorMessage,"Could not connect to socket"); _errorReason = _source.errorReason(); return status; } _active = 1; return RTN_NORMAL; } ////////////////////////////////////////////////////////////////////////////// // // fill // // Transfers the data from the buffer controlled by the base-class to // the socket. Timeouts are controlled by the SocketBase object. // // In order to support the 'reload' method, the _offset may be a // non-zero value, meaning there is some retained data at the beginning // of the buffer // ////////////////////////////////////////////////////////////////////////////// int DataSourceSocket::_fill( int MinLength, int TimeOut) { int Available, ReadLength, RtnStatus; if (!_source.connected()) { strcpy(_errorMessage,"Not connection to socket"); return RTN_ALLOCATE_ERROR; } Available = _capacity - (_offset + _stored); if (MinLength > Available) // Is there room in the buffer return (RTN_INSUFF_MEMORY); /*** *** Fill as much of the buffer from the socket as possible **/ ReadLength = Available; RtnStatus = _source.read((_buffer+_offset+_stored), &ReadLength, 0); _stored += ReadLength; if (!RTN_SUCCESS(RtnStatus)) { _errorReason = _source.errorReason(); strcpy(_errorMessage,"Untimed socket read not successful"); #if DEV_DEBUG cerr << _errorMessage << "; " << strerror(_errorReason) << endl; #endif if (RTN_EOD == RtnStatus || RTN_FAILURE(RtnStatus)) return RtnStatus; } /*** *** If not enough data obtained, wait until TIME-out for what was requested **/ if (ReadLength < MinLength) // Quick-fill did not get minimum { MinLength -= ReadLength; // Account for part of the minimum ReadLength = MinLength; RtnStatus = _source.read((_buffer+_stored+_offset), &ReadLength, TimeOut); _stored += ReadLength; if (!RTN_SUCCESS(RtnStatus)) { _errorReason = _source.errorReason(); strcpy(_errorMessage,"Timed socket read not successful"); #if DEV_DEBUG cerr << _errorMessage << "; " << strerror(_errorReason) << endl; #endif if (RTN_EOD == RtnStatus || RTN_FAILURE(RtnStatus)) return RtnStatus; } } if (ReadLength >= MinLength) RtnStatus = RTN_NORMAL; return RtnStatus; }
26.815068
78
0.579566
[ "object" ]
bdbd8b9d9190ca156db65445dfdc52441108297d
14,511
cpp
C++
sp/src/game/server/hl1/hl1_npc_talker.cpp
AgentAgrimar/source-sdk-trilogy
39929158e07468610563a3566d8c4ef5efdd9643
[ "Unlicense" ]
9
2017-10-03T18:56:06.000Z
2022-02-13T18:16:58.000Z
sp/src/game/server/hl1/hl1_npc_talker.cpp
AgentAgrimar/source-sdk-trilogy
39929158e07468610563a3566d8c4ef5efdd9643
[ "Unlicense" ]
3
2016-06-21T17:40:13.000Z
2016-11-08T08:20:50.000Z
sp/src/game/server/hl1/hl1_npc_talker.cpp
AgentAgrimar/source-sdk-trilogy
39929158e07468610563a3566d8c4ef5efdd9643
[ "Unlicense" ]
6
2016-09-24T15:24:43.000Z
2019-03-31T08:20:21.000Z
//========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "cbase.h" #include "hl1_npc_talker.h" #include "scripted.h" #include "soundent.h" #include "animation.h" #include "EntityList.h" #include "AI_Navigator.h" #include "AI_Motor.h" #include "player.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "NPCevent.h" #include "ai_interactions.h" #include "doors.h" #include "effect_dispatch_data.h" #include "te_effect_dispatch.h" #include "hl1_ai_basenpc.h" #include "soundemittersystem/isoundemittersystembase.h" ConVar hl1_debug_sentence_volume( "hl1_debug_sentence_volume", "0" ); ConVar hl1_fixup_sentence_sndlevel( "hl1_fixup_sentence_sndlevel", "1" ); //#define TALKER_LOOK 0 BEGIN_DATADESC( CHL1NPCTalker ) DEFINE_ENTITYFUNC( Touch ), DEFINE_FIELD( m_bInBarnacleMouth, FIELD_BOOLEAN ), END_DATADESC() void CHL1NPCTalker::RunTask( const Task_t *pTask ) { switch ( pTask->iTask ) { case TASK_HL1TALKER_FOLLOW_WALK_PATH_FOR_UNITS: { float distance; distance = (m_vecLastPosition - GetLocalOrigin()).Length2D(); // Walk path until far enough away if ( distance > pTask->flTaskData || GetNavigator()->GetGoalType() == GOALTYPE_NONE ) { TaskComplete(); GetNavigator()->ClearGoal(); // Stop moving } break; } case TASK_TALKER_CLIENT_STARE: case TASK_TALKER_LOOK_AT_CLIENT: { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); // track head to the client for a while. if ( m_NPCState == NPC_STATE_IDLE && !IsMoving() && !GetExpresser()->IsSpeaking() ) { if ( pPlayer ) { IdleHeadTurn( pPlayer ); } } else { // started moving or talking TaskFail( "moved away" ); return; } if ( pTask->iTask == TASK_TALKER_CLIENT_STARE ) { // fail out if the player looks away or moves away. if ( ( pPlayer->GetAbsOrigin() - GetAbsOrigin() ).Length2D() > TALKER_STARE_DIST ) { // player moved away. TaskFail( NO_TASK_FAILURE ); } Vector vForward; AngleVectors( GetAbsAngles(), &vForward ); if ( UTIL_DotPoints( pPlayer->GetAbsOrigin(), GetAbsOrigin(), vForward ) < m_flFieldOfView ) { // player looked away TaskFail( "looked away" ); } } if ( gpGlobals->curtime > m_flWaitFinished ) { TaskComplete( NO_TASK_FAILURE ); } break; } case TASK_WAIT_FOR_MOVEMENT: { if ( GetExpresser()->IsSpeaking() && GetSpeechTarget() != NULL) { // ALERT(at_console, "walking, talking\n"); IdleHeadTurn( GetSpeechTarget(), GetExpresser()->GetTimeSpeechComplete() - gpGlobals->curtime ); } else if ( GetEnemy() ) { IdleHeadTurn( GetEnemy() ); } BaseClass::RunTask( pTask ); break; } case TASK_FACE_PLAYER: { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer ) { //GetMotor()->SetIdealYaw( pPlayer->GetAbsOrigin() ); IdleHeadTurn( pPlayer ); if ( gpGlobals->curtime > m_flWaitFinished && GetMotor()->DeltaIdealYaw() < 10 ) { TaskComplete(); } } else { TaskFail( FAIL_NO_PLAYER ); } break; } case TASK_TALKER_EYECONTACT: { if (!IsMoving() && GetExpresser()->IsSpeaking() && GetSpeechTarget() != NULL) { // ALERT( at_console, "waiting %f\n", m_flStopTalkTime - gpGlobals->time ); IdleHeadTurn( GetSpeechTarget(), GetExpresser()->GetTimeSpeechComplete() - gpGlobals->curtime ); } BaseClass::RunTask( pTask ); break; } default: { if ( GetExpresser()->IsSpeaking() && GetSpeechTarget() != NULL) { IdleHeadTurn( GetSpeechTarget(), GetExpresser()->GetTimeSpeechComplete() - gpGlobals->curtime ); } else if ( GetEnemy() && m_NPCState == NPC_STATE_COMBAT ) { IdleHeadTurn( GetEnemy() ); } else if ( GetFollowTarget() ) { IdleHeadTurn( GetFollowTarget() ); } BaseClass::RunTask( pTask ); break; } } } bool CHL1NPCTalker::ShouldGib( const CTakeDamageInfo &info ) { if ( info.GetDamageType() & DMG_NEVERGIB ) return false; if ( ( g_pGameRules->Damage_ShouldGibCorpse( info.GetDamageType() ) && m_iHealth < GIB_HEALTH_VALUE ) || ( info.GetDamageType() & DMG_ALWAYSGIB ) ) return true; return false; } void CHL1NPCTalker::StartTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_HL1TALKER_FOLLOW_WALK_PATH_FOR_UNITS: { GetNavigator()->SetMovementActivity( ACT_WALK ); break; } default: BaseClass::StartTask( pTask ); break; } } int CHL1NPCTalker::SelectSchedule ( void ) { switch( m_NPCState ) { case NPC_STATE_PRONE: { if (m_bInBarnacleMouth) { return SCHED_HL1TALKER_BARNACLE_CHOMP; } else { return SCHED_HL1TALKER_BARNACLE_HIT; } } } return BaseClass::SelectSchedule(); } void CHL1NPCTalker::Precache() { BaseClass::Precache(); PrecacheScriptSound( "Barney.Close" ); } bool CHL1NPCTalker::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt) { if (interactionType == g_interactionBarnacleVictimDangle) { // Force choosing of a new schedule ClearSchedule( "NPC talker being eaten by a barnacle" ); m_bInBarnacleMouth = true; return true; } else if ( interactionType == g_interactionBarnacleVictimReleased ) { SetState ( NPC_STATE_IDLE ); CPASAttenuationFilter filter( this ); CSoundParameters params; if ( GetParametersForSound( "Barney.Close", params, NULL ) ) { EmitSound_t ep( params ); ep.m_nPitch = GetExpresser()->GetVoicePitch(); EmitSound( filter, entindex(), ep ); } m_bInBarnacleMouth = false; SetAbsVelocity( vec3_origin ); SetMoveType( MOVETYPE_STEP ); return true; } else if ( interactionType == g_interactionBarnacleVictimGrab ) { if ( GetFlags() & FL_ONGROUND ) { SetGroundEntity( NULL ); } if ( GetState() == NPC_STATE_SCRIPT ) { if ( m_hCine ) { m_hCine->CancelScript(); } } SetState( NPC_STATE_PRONE ); ClearSchedule( "NPC talker grabbed by a barnacle" ); CTakeDamageInfo info; PainSound( info ); return true; } return false; } void CHL1NPCTalker::StartFollowing( CBaseEntity *pLeader ) { if ( !HasSpawnFlags( SF_NPC_GAG ) ) { if ( m_iszUse != NULL_STRING ) { PlaySentence( STRING( m_iszUse ), 0.0f ); } else { Speak( TLK_STARTFOLLOW ); } SetSpeechTarget( pLeader ); } BaseClass::StartFollowing( pLeader ); } int CHL1NPCTalker::PlayScriptedSentence( const char *pszSentence, float delay, float volume, soundlevel_t soundlevel, bool bConcurrent, CBaseEntity *pListener ) { if( hl1_debug_sentence_volume.GetBool() ) { Msg( "SENTENCE: %s Vol:%f SndLevel:%d\n", GetDebugName(), volume, soundlevel ); } if( hl1_fixup_sentence_sndlevel.GetBool() ) { if( soundlevel < SNDLVL_TALKING ) { soundlevel = SNDLVL_TALKING; } } return BaseClass::PlayScriptedSentence( pszSentence, delay, volume, soundlevel, bConcurrent, pListener ); } Disposition_t CHL1NPCTalker::IRelationType( CBaseEntity *pTarget ) { if ( pTarget->IsPlayer() ) { if ( HasMemory( bits_MEMORY_PROVOKED ) ) { return D_HT; } } return BaseClass::IRelationType( pTarget ); } void CHL1NPCTalker::Touch( CBaseEntity *pOther ) { if ( m_NPCState == NPC_STATE_SCRIPT ) return; BaseClass::Touch(pOther); } void CHL1NPCTalker::StopFollowing( void ) { if ( !(m_afMemory & bits_MEMORY_PROVOKED) ) { if ( !HasSpawnFlags( SF_NPC_GAG ) ) { if ( m_iszUnUse != NULL_STRING ) { PlaySentence( STRING( m_iszUnUse ), 0.0f ); } else { Speak( TLK_STOPFOLLOW ); } SetSpeechTarget( GetFollowTarget() ); } } BaseClass::StopFollowing(); } void CHL1NPCTalker::TraceAttack(const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator) { if ( info.GetDamage() >= 1.0 && !(info.GetDamageType() & DMG_SHOCK ) ) { UTIL_BloodImpact( ptr->endpos, vecDir, BloodColor(), 4 ); } BaseClass::TraceAttack( info, vecDir, ptr, pAccumulator ); } void CHL1NPCTalker::FollowerUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { // Don't allow use during a scripted_sentence if ( GetUseTime() > gpGlobals->curtime ) return; if ( m_hCine && !m_hCine->CanInterrupt() ) return; if ( pCaller != NULL && pCaller->IsPlayer() ) { // Pre-disaster followers can't be used if ( m_spawnflags & SF_NPC_PREDISASTER ) { SetSpeechTarget( pCaller ); DeclineFollowing(); return; } } BaseClass::FollowerUse( pActivator, pCaller, useType, value ); } int CHL1NPCTalker::TranslateSchedule( int scheduleType ) { return BaseClass::TranslateSchedule( scheduleType ); } float CHL1NPCTalker::PickLookTarget( bool bExcludePlayers, float minTime, float maxTime ) { return random->RandomFloat( 5.0f, 10.0f ); } void CHL1NPCTalker::IdleHeadTurn( CBaseEntity *pTarget, float flDuration, float flImportance ) { // Must be able to turn our head if (!(CapabilitiesGet() & bits_CAP_TURN_HEAD)) return; // If the target is invalid, or we're in a script, do nothing if ( ( !pTarget ) || ( m_NPCState == NPC_STATE_SCRIPT ) ) return; // Fill in a duration if we haven't specified one if ( flDuration == 0.0f ) { flDuration = random->RandomFloat( 2.0, 4.0 ); } // Add a look target AddLookTarget( pTarget, 1.0, flDuration ); } void CHL1NPCTalker::SetHeadDirection( const Vector &vTargetPos, float flInterval) { #ifdef TALKER_LOOK // Draw line in body, head, and eye directions Vector vEyePos = EyePosition(); Vector vHeadDir = HeadDirection3D(); Vector vBodyDir = BodyDirection2D(); //UNDONE <<TODO>> // currently eye dir just returns head dir, so use vTargetPos for now //Vector vEyeDir; w //EyeDirection3D(&vEyeDir); NDebugOverlay::Line( vEyePos, vEyePos+(50*vHeadDir), 255, 0, 0, false, 0.1 ); NDebugOverlay::Line( vEyePos, vEyePos+(50*vBodyDir), 0, 255, 0, false, 0.1 ); NDebugOverlay::Line( vEyePos, vTargetPos, 0, 0, 255, false, 0.1 ); #endif } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL1NPCTalker::CorpseGib( const CTakeDamageInfo &info ) { CEffectData data; data.m_vOrigin = WorldSpaceCenter(); data.m_vNormal = data.m_vOrigin - info.GetDamagePosition(); VectorNormalize( data.m_vNormal ); data.m_flScale = RemapVal( m_iHealth, 0, -500, 1, 3 ); data.m_flScale = clamp( data.m_flScale, 1, 3 ); data.m_nMaterial = 1; data.m_nHitBox = -m_iHealth; data.m_nColor = BloodColor(); DispatchEffect( "HL1Gib", data ); CSoundEnt::InsertSound( SOUND_MEAT, GetAbsOrigin(), 256, 0.5f, this ); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CHL1NPCTalker::OnObstructingDoor( AILocalMoveGoal_t *pMoveGoal, CBaseDoor *pDoor, float distClear, AIMoveResult_t *pResult ) { // If we can't get through the door, try and open it if ( BaseClass::OnObstructingDoor( pMoveGoal, pDoor, distClear, pResult ) ) { if ( IsMoveBlocked( *pResult ) && pMoveGoal->directTrace.vHitNormal != vec3_origin ) { // Can't do anything if the door's locked if ( !pDoor->m_bLocked && !pDoor->HasSpawnFlags(SF_DOOR_NONPCS) ) { // Tell the door to open variant_t emptyVariant; pDoor->AcceptInput( "Open", this, this, emptyVariant, USE_TOGGLE ); *pResult = AIMR_OK; } } return true; } return false; } // HL1 version - never return Ragdoll as the automatic schedule at the end of a // scripted sequence int CHL1NPCTalker::SelectDeadSchedule() { // Alread dead (by animation event maybe?) // Is it safe to set it to SCHED_NONE? if ( m_lifeState == LIFE_DEAD ) return SCHED_NONE; CleanupOnDeath(); return SCHED_DIE; } AI_BEGIN_CUSTOM_NPC( monster_hl1talker, CHL1NPCTalker ) DECLARE_TASK( TASK_HL1TALKER_FOLLOW_WALK_PATH_FOR_UNITS ) //========================================================= // > SCHED_HL1TALKER_MOVE_AWAY_FOLLOW //========================================================= DEFINE_SCHEDULE ( SCHED_HL1TALKER_FOLLOW_MOVE_AWAY, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_TARGET_FACE" " TASK_STORE_LASTPOSITION 0" " TASK_MOVE_AWAY_PATH 100" " TASK_HL1TALKER_FOLLOW_WALK_PATH_FOR_UNITS 100" " TASK_STOP_MOVING 0" " TASK_FACE_PLAYER 0" " TASK_SET_ACTIVITY ACT_IDLE" "" " Interrupts" ) //========================================================= // > SCHED_HL1TALKER_IDLE_SPEAK_WAIT //========================================================= DEFINE_SCHEDULE ( SCHED_HL1TALKER_IDLE_SPEAK_WAIT, " Tasks" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" // Stop and talk " TASK_FACE_PLAYER 0" "" " Interrupts" " COND_NEW_ENEMY" " COND_LIGHT_DAMAGE" " COND_HEAVY_DAMAGE" " COND_HEAR_DANGER" ) //========================================================= // > SCHED_HL1TALKER_BARNACLE_HIT //========================================================= DEFINE_SCHEDULE ( SCHED_HL1TALKER_BARNACLE_HIT, " Tasks" " TASK_STOP_MOVING 0" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_BARNACLE_HIT" " TASK_SET_SCHEDULE SCHEDULE:SCHED_HL1TALKER_BARNACLE_PULL" "" " Interrupts" ) //========================================================= // > SCHED_HL1TALKER_BARNACLE_PULL //========================================================= DEFINE_SCHEDULE ( SCHED_HL1TALKER_BARNACLE_PULL, " Tasks" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_BARNACLE_PULL" "" " Interrupts" ) //========================================================= // > SCHED_HL1TALKER_BARNACLE_CHOMP //========================================================= DEFINE_SCHEDULE ( SCHED_HL1TALKER_BARNACLE_CHOMP, " Tasks" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_BARNACLE_CHOMP" " TASK_SET_SCHEDULE SCHEDULE:SCHED_HL1TALKER_BARNACLE_CHEW" "" " Interrupts" ) //========================================================= // > SCHED_HL1TALKER_BARNACLE_CHEW //========================================================= DEFINE_SCHEDULE ( SCHED_HL1TALKER_BARNACLE_CHEW, " Tasks" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_BARNACLE_CHEW" ) AI_END_CUSTOM_NPC()
23.518639
160
0.631865
[ "vector" ]
bdbdffeb82e31052ccb549b3716ac53eb561dab1
3,149
cpp
C++
test/basicserver/TestCommands.cpp
resosafe/boxbackup
c56291558de634f3fe6675aeb381ba99f68b78cb
[ "BSD-3-Clause" ]
133
2015-02-22T23:56:53.000Z
2022-03-13T19:24:21.000Z
test/basicserver/TestCommands.cpp
resosafe/boxbackup
c56291558de634f3fe6675aeb381ba99f68b78cb
[ "BSD-3-Clause" ]
93
2015-08-31T15:35:07.000Z
2021-04-27T21:41:13.000Z
test/basicserver/TestCommands.cpp
resosafe/boxbackup
c56291558de634f3fe6675aeb381ba99f68b78cb
[ "BSD-3-Clause" ]
19
2015-08-31T14:13:34.000Z
2021-12-12T15:20:17.000Z
#include "Box.h" #ifdef HAVE_SYSLOG_H #include <syslog.h> #endif #include "autogen_TestProtocol.h" #include "CollectInBufferStream.h" #include "MemLeakFindOn.h" std::auto_ptr<TestProtocolMessage> TestProtocolReplyable::HandleException(BoxException& e) const { throw; } std::auto_ptr<TestProtocolMessage> TestProtocolHello::DoCommand(TestProtocolReplyable &rProtocol, TestContext &rContext) const { if(mNumber32 != 41 || mNumber16 != 87 || mNumber8 != 11 || mText != "pingu") { return std::auto_ptr<TestProtocolMessage>(new TestProtocolError(0, 0)); } return std::auto_ptr<TestProtocolMessage>(new TestProtocolHello(12,89,22,std::string("Hello world!"))); } std::auto_ptr<TestProtocolMessage> TestProtocolLists::DoCommand(TestProtocolReplyable &rProtocol, TestContext &rContext) const { return std::auto_ptr<TestProtocolMessage>(new TestProtocolListsReply(mLotsOfText.size())); } std::auto_ptr<TestProtocolMessage> TestProtocolQuit::DoCommand(TestProtocolReplyable &rProtocol, TestContext &rContext) const { return std::auto_ptr<TestProtocolMessage>(new TestProtocolQuit); } std::auto_ptr<TestProtocolMessage> TestProtocolSimple::DoCommand(TestProtocolReplyable &rProtocol, TestContext &rContext) const { return std::auto_ptr<TestProtocolMessage>(new TestProtocolSimpleReply(mValue+1)); } class UncertainBufferStream : public CollectInBufferStream { public: // make the collect in buffer stream pretend not to know how many bytes are left pos_type BytesLeftToRead() { return IOStream::SizeOfStreamUnknown; } }; std::auto_ptr<TestProtocolMessage> TestProtocolGetStream::DoCommand(TestProtocolReplyable &rProtocol, TestContext &rContext) const { // make a new stream object std::auto_ptr<CollectInBufferStream> apStream( mUncertainSize?(new UncertainBufferStream):(new CollectInBufferStream)); // Data. int values[24273]; int v = mStartingValue; for(int l = 0; l < 3; ++l) { for(int x = 0; x < 24273; ++x) { values[x] = v++; } apStream->Write(values, sizeof(values)); } // Finished apStream->SetForReading(); // Get it to be sent rProtocol.SendStreamAfterCommand((std::auto_ptr<IOStream>)apStream); return std::auto_ptr<TestProtocolMessage>(new TestProtocolGetStream(mStartingValue, mUncertainSize)); } std::auto_ptr<TestProtocolMessage> TestProtocolSendStream::DoCommand( TestProtocolReplyable &rProtocol, TestContext &rContext, IOStream& rDataStream) const { if(mValue != 0x73654353298ffLL) { return std::auto_ptr<TestProtocolMessage>(new TestProtocolError(0, 0)); } // Get a stream bool uncertain = (rDataStream.BytesLeftToRead() == IOStream::SizeOfStreamUnknown); // Count how many bytes in it int bytes = 0; char buffer[125]; while(rDataStream.StreamDataLeft()) { bytes += rDataStream.Read(buffer, sizeof(buffer)); } // tell the caller how many bytes there were return std::auto_ptr<TestProtocolMessage>(new TestProtocolGetStream(bytes, uncertain)); } std::auto_ptr<TestProtocolMessage> TestProtocolString::DoCommand(TestProtocolReplyable &rProtocol, TestContext &rContext) const { return std::auto_ptr<TestProtocolMessage>(new TestProtocolString(mTest)); }
28.889908
130
0.770403
[ "object" ]
bdbebc021db0e1ce6236374b2a47a6cf130c5174
1,026
hpp
C++
include/xnn/layers/noise/dropout.hpp
ktnyt/xdfa
962ef8f99150556272ff87c7b37494fd87f5fe79
[ "MIT" ]
null
null
null
include/xnn/layers/noise/dropout.hpp
ktnyt/xdfa
962ef8f99150556272ff87c7b37494fd87f5fe79
[ "MIT" ]
null
null
null
include/xnn/layers/noise/dropout.hpp
ktnyt/xdfa
962ef8f99150556272ff87c7b37494fd87f5fe79
[ "MIT" ]
null
null
null
#ifndef __XNN_LAYERS_NOISE_DROPOUT_HPP__ #define __XNN_LAYERS_NOISE_DROPOUT_HPP__ #include "xnn/functions/noise/dropout.hpp" #include "xnn/layer.hpp" #include "xtensor/xarray.hpp" #include "xtensor/xrandom.hpp" namespace xnn { namespace layers { namespace noise { class Dropout final : public Layer<float> { class Impl : public Layer<float>::Impl { public: Impl(float ratio) : ratio(ratio) {} xt::xarray<float> forward(const xt::xarray<float>& x) override { if (x.shape() != mask.shape()) { mask = xt::random::rand(x.shape(), 0.0, 1.0) < ratio; } return functions::noise::dropout(x, mask); } xt::xarray<float> backward(const xt::xarray<float>& dy) override { return functions::noise::dropout(dy, mask); } private: float ratio; xt::xarray<bool> mask; }; public: Dropout(float ratio) : Layer<float>(std::make_shared<Impl>(ratio)) {} }; } // namespace noise } // namespace layers } // namespace xnn #endif // __XNN_LAYERS_NOISE_DROPOUT_HPP__
23.318182
71
0.666667
[ "shape" ]
bdc463d2e174fc0f03b3279e970bd9f1d233e175
1,349
cpp
C++
codeforces/Edu#62/C/s.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
4
2020-02-02T08:34:46.000Z
2021-10-01T11:21:17.000Z
codeforces/Edu#62/C/s.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
1
2021-09-04T14:03:50.000Z
2021-09-04T14:03:50.000Z
codeforces/Edu#62/C/s.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
null
null
null
// #include <bits/stdc++.h> /* codeforces printf %Lf problem #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <queue> #include <stack> #include <deque> #include <utility> #include <tuple> #include <functional> #include <numeric> #include <map> #include <set> #include <list> using namespace std; typedef long long ll; int main(void){ ios_base::sync_with_stdio(false); cin.tie(NULL); // cout.tie(NULL); // SLOW? cout<<setprecision(8)<<fixed; // code start int n, k; vector<pair<int, int>> v; scanf("%d %d", &n, &k); for(int i=0;i<n;i++){ int t, b; scanf("%d %d", &t, &b); v.emplace_back(b, t); } sort(v.begin(), v.end(), greater<pair<int, int>>()); ll mb = 0; ll sum = 0; ll max = 0; priority_queue<int, vector<int>, greater<int>> pq; for(int i=0;i<n;i++){ mb = v[i].first; sum += v[i].second; pq.push(v[i].second); if(i>=k){ sum -= pq.top(); pq.pop(); } ll cur = mb * sum; max = max > cur ? max : cur ; } printf("%lld", max); return 0; }
19.838235
56
0.554485
[ "vector" ]
bdccb5ae99f66a9c9441bed8536e57be6d5dec62
1,496
hpp
C++
ThirdParty-mod/java2cpp/java/util/EventListener.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/util/EventListener.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/util/EventListener.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.util.EventListener ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_EVENTLISTENER_HPP_DECL #define J2CPP_JAVA_UTIL_EVENTLISTENER_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } #include <java/lang/Object.hpp> namespace j2cpp { namespace java { namespace util { class EventListener; class EventListener : public object<EventListener> { public: J2CPP_DECLARE_CLASS explicit EventListener(jobject jobj) : object<EventListener>(jobj) { } operator local_ref<java::lang::Object>() const; }; //class EventListener } //namespace util } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_EVENTLISTENER_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_EVENTLISTENER_HPP_IMPL #define J2CPP_JAVA_UTIL_EVENTLISTENER_HPP_IMPL namespace j2cpp { java::util::EventListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } J2CPP_DEFINE_CLASS(java::util::EventListener,"java/util/EventListener") } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_EVENTLISTENER_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
21.371429
83
0.657754
[ "object" ]
bdd16bbc82a312b8bd5f6b5f66257d808e2b14d2
1,787
cpp
C++
program/testcluster.cpp
andrewprock/kmcluster
ca044e9e805a855415eca4c1e3ee3c80241de6bb
[ "BSD-3-Clause" ]
1
2019-09-05T09:22:30.000Z
2019-09-05T09:22:30.000Z
program/testcluster.cpp
andrewprock/kmcluster
ca044e9e805a855415eca4c1e3ee3c80241de6bb
[ "BSD-3-Clause" ]
null
null
null
program/testcluster.cpp
andrewprock/kmcluster
ca044e9e805a855415eca4c1e3ee3c80241de6bb
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <kmcluster/KMeansCluster.h> // compile: g++ testcluster.cpp ../random/rand_isaac.cpp -I../.. -o cluster using namespace std; using namespace boost; int main (int argc, char ** argv) { string fname = argv[1]; int nClusters = atoi(argv[2]); rps::KMeansClusterND clusters (nClusters); // we support two different file types // .txt is just a flat file with one 2D point per line ifstream fin (fname.c_str()); if (!fin) { cerr << "could not open file: " << fname << endl; exit(-1); } if (boost::ends_with (fname, ".txt")) { do { double x,y; fin >> x >> y; if (!fin.eof ()) { rps::PointND pt(x,y); clusters.add (pt); } } while (!fin.eof()); } // we also support a csv format where each line is a // labeled points, with the label stored in the first // field of the csv else if (boost::ends_with (fname, ".csv")) { //cout << "doing csv\n"; string line; while (!fin.eof()) { getline (fin, line); // filer out empty lines if (line.size() == 0) continue; vector<string> fields; boost::split (fields, line, boost::is_any_of(",")); vector<double> pt; for (size_t i=1; i<fields.size(); i++) pt.push_back (lexical_cast<double>(fields[i])); clusters.add (rps::PointND(fields[0], pt)); } } //srand (); clusters.cluster (); //cout << clusters.str () << endl; cout << clusters.clusterSets () << endl; }
22.910256
76
0.538892
[ "vector" ]
7525cad4783dc268cd4735009dfee555d02a9757
2,770
cc
C++
analyze/hash_table.cc
pcwerk/jurassic
514a4be5c3e99fe8776a7c3dba768cfdb8f0a893
[ "Apache-2.0" ]
1
2017-10-25T21:27:13.000Z
2017-10-25T21:27:13.000Z
analyze/hash_table.cc
pcwerk/jurassic
514a4be5c3e99fe8776a7c3dba768cfdb8f0a893
[ "Apache-2.0" ]
11
2016-04-27T15:49:01.000Z
2016-09-29T20:29:58.000Z
analyze/hash_table.cc
pcwerk/jurassic
514a4be5c3e99fe8776a7c3dba768cfdb8f0a893
[ "Apache-2.0" ]
null
null
null
// --*-c++-*-- #include <algorithm> #include <iostream> #include <string> #include <sstream> #include <fstream> #include "utility.h" #include "hash_table.h" HashTable::HashTable(const std::string &filename) { initOneColumn(filename); } void HashTable::initOneColumn(std::string const &filename) { std::ifstream infile(filename); std::string line; while (std::getline(infile, line)) { #if 0 std::istringstream iss(line); #endif std::string key = line; #if 0 if (!(iss >> key)) { break; } #endif std::transform(key.begin(), key.end(), key.begin(), ::toupper); pTable[key] = key; } } void HashTable::initTwoColumns(std::string const &filename) { std::ifstream infile(filename); std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); std::string key, value; if (!(iss >> key >> value)) { break; } std::transform(key.begin(), key.end(), key.begin(), ::toupper); pTable[key] = value; } } void HashTable::set(const std::string &key, const std::string &value) { pTable[key] = value; } void HashTable::set(const std::string &key, const int value) { pTable[key] = intToString(value); } void HashTable::set(const std::string &key, const long value) { pTable[key] = longToString(value); } void HashTable::set(const std::string &key, const double value) { pTable[key] = doubleToString(value); } const bool HashTable::has(const std::string &key) { if (pTable.find(key) == pTable.end()) return false; else return true; } const bool HashTable::hasCaseIgnore(const std::string &k) { std::string key = k; std::transform(key.begin(), key.end(), key.begin(), ::toupper); if (pTable.find(key) == pTable.end()) return false; else return true; } const std::string HashTable::get(const std::string &key) { if (pTable.find(key) == pTable.end()) return std::string(""); else return pTable[key]; } const std::string HashTable::getCaseIgnore(const std::string &k) { std::string key = k; std::transform(key.begin(), key.end(), key.begin(), ::toupper); if (pTable.find(key) == pTable.end()) return ""; else return pTable[key]; } const std::string HashTable::toString(const std::string spacing) { std::ostringstream oss; for (std::unordered_map<std::string, std::string>::iterator p = pTable.begin(); p!= pTable.end(); ++p) { std::string key = p->first; std::string value = p->second; pTable[key] = value; oss << spacing << key << " " << value << "\n"; } return oss.str(); } const int HashTable::size() { return pTable.size(); } HashTable::Iterator HashTable::begin() { return pTable.begin(); } HashTable::Iterator HashTable::end() { return pTable.end(); }
19.64539
69
0.633213
[ "transform" ]
752b909aa2ca1f866e59b975df1c51993372c5c1
4,457
cpp
C++
src/wordscheck.cpp
FFreestyler/EnglishWords
b8666404fa5e72e7cf447d33d1a8cd5d9c2115cd
[ "MIT" ]
7
2020-05-17T06:00:37.000Z
2020-05-30T02:58:46.000Z
src/wordscheck.cpp
FFreestyler/EnglishWords
b8666404fa5e72e7cf447d33d1a8cd5d9c2115cd
[ "MIT" ]
7
2020-05-15T08:02:34.000Z
2020-05-27T15:49:57.000Z
src/wordscheck.cpp
FFreestyler/EnglishWords
b8666404fa5e72e7cf447d33d1a8cd5d9c2115cd
[ "MIT" ]
null
null
null
#include "menu.hpp" #include <SFML/Graphics.hpp> #include <fstream> #include <vector> using namespace sf; using namespace std; void wordscheck(RenderWindow& window) { Texture menuTexture1, menuTexture2, menuTexture3; menuTexture1.loadFromFile("images/nextButtonSmall.png"); menuTexture2.loadFromFile("images/ex.png"); menuTexture3.loadFromFile("images/backButtonSmall.png"); Sprite button1(menuTexture1), button2(menuTexture2), button3(menuTexture3); bool isMenu = 1; int MenuNum = 0; button1.setPosition(510, 430); button2.setPosition(260, 430); button3.setPosition(10, 430); Image FirstCloud; FirstCloud.loadFromFile("images/Cloud.png"); Texture FCloudTexture; FCloudTexture.loadFromImage(FirstCloud); Sprite FCloudSprite; FCloudSprite.setTexture(FCloudTexture); FCloudSprite.setPosition(-65, 35); Image SecondCloud; SecondCloud.loadFromFile("images/SCloud.png"); Texture SCloudTexture; SCloudTexture.loadFromImage(SecondCloud); Sprite SCloudSprite; SCloudSprite.setTexture(SCloudTexture); SCloudSprite.setPosition(550, 200); Font font; font.loadFromFile("font.ttf"); Text text("", font, 30); text.setStyle(Text::Bold); text.setPosition(260, 80); sf::Clock clock; const int wordquantity = 11; sf::String words[2][wordquantity]; char testnumber = '1'; ifstream wordsfile; string tmpstr, path; path = "tests/"; path += testnumber; path += ".txt"; wordsfile.open(path.c_str()); int wordnumber = 0; while (!wordsfile.eof()) { wordsfile >> tmpstr; words[0][wordnumber] = sf::String(tmpstr); wordsfile >> tmpstr; words[1][wordnumber] = sf::String(tmpstr); wordnumber++; } wordsfile.close(); while (isMenu) { MenuNum = 0; Event event; if (IntRect(260, 430, 173, 32).contains(Mouse::getPosition(window))) { MenuNum = 1; } if (testnumber != '9') { if (IntRect(510, 430, 173, 32) .contains(Mouse::getPosition(window))) { MenuNum = 2; } } if (testnumber != '1') { if (IntRect(10, 430, 173, 32) .contains(Mouse::getPosition(window))) { MenuNum = 3; } } while (window.pollEvent(event)) { if (event.type == Event::Closed) { isMenu = false; exit(1999); window.close(); } if (event.type == Event::MouseButtonReleased) { if (event.mouseButton.button == Mouse::Left) { if (MenuNum == 1) { isMenu = false; } else { if (MenuNum == 2) { testnumber++; } if (MenuNum == 3) { testnumber--; } ifstream wordsfile; path = "tests/"; path += testnumber; path += ".txt"; wordsfile.open(path.c_str()); int wordnumber = 0; while (!wordsfile.eof()) { wordsfile >> tmpstr; words[0][wordnumber] = sf::String(tmpstr); wordsfile >> tmpstr; words[1][wordnumber] = sf::String(tmpstr); wordnumber++; } wordsfile.close(); } } } } window.setTitle("English Words"); window.clear(sf::Color(71, 202, 221)); window.draw(FCloudSprite); window.draw(SCloudSprite); if (testnumber != '9') { window.draw(button1); } if (testnumber != '1') { window.draw(button3); } window.draw(button2); for (int wordcounter = 1; wordcounter < 10; ++wordcounter) { text.setString( words[1][wordcounter - 1] + " - " + words[0][wordcounter - 1]); text.setPosition(220, wordcounter * 40); window.draw(text); } window.display(); } menu(window); }
29.322368
79
0.496298
[ "vector" ]
7538ed5687bc726446b8f3c195c08d5c43cbbf22
2,733
cpp
C++
Algorithms/modifying/unique.cpp
kant/Always-be-learning
7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5
[ "Unlicense" ]
null
null
null
Algorithms/modifying/unique.cpp
kant/Always-be-learning
7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5
[ "Unlicense" ]
null
null
null
Algorithms/modifying/unique.cpp
kant/Always-be-learning
7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5
[ "Unlicense" ]
null
null
null
#include <iostream> #include <algorithm> #include <iterator> #include <array> #include <vector> #include "auxiliary.h" template< class ForwardIt > constexpr ForwardIt unique( ForwardIt first, ForwardIt last ); template< class ForwardIt, class BinaryPredicate > constexpr ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPredicate p ); template< class InputIt, class OutputIt > constexpr OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first ); template< class InputIt, class OutputIt, class BinaryPredicate > constexpr OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first, BinaryPredicate p ); /* std::unique Eliminates all but the first element from every group of duplicate (equal) elements in the range [first, last) and returns a past-the-end iterator for the new logical end of the range first form: Elements are compared using operator== second form: Elements are compared using the given BinaryPredicate p std::unique_copy Copies the elements from the range [first, last), to another range beginning at d_first in such a way that there are no consecutive equal elements. Only the first element of each group of equal elements is copied. */ int main() { std::array<int, 17> source = { 1, 4, 4, 6, 1, 2, 2, 3, 1, 6, 6, 6, 5, 7, 5, 4, 4 }; std::vector<int> coll; std::copy(cbegin(source), cend(source), std::back_inserter(coll)); print_elements(coll, "coll: "); // remove consecutive duplicates auto it = std::unique(coll.begin(), coll.end()); // print elements not removed std::cout << "coll, duplicates removed: "; std::copy(coll.begin(), it, std::ostream_iterator<int>(std::cout, ", ")); std::cout << "\n\n"; // reinitialize std::copy(cbegin(source), cend(source), coll.begin()); print_elements(coll, "coll reinitialized: "); // remove elements if there was a previous greater one it = std::unique(coll.begin(), coll.end(), [](int a, int b){ return a > b; }); coll.erase(it, coll.end()); print_elements(coll, "coll with consecutive lesser elements removed: "); std::cout << "\n"; std::vector<int> coll2; // initialize coll2 while removing consecutive duplicates std::unique_copy(source.cbegin(), source.cend(), std::back_inserter(coll2)); print_elements(coll2, "coll2 unique initialized: "); std::cout << "coll2 elements without consecutive differing by one: "; std::unique_copy(coll2.cbegin(), coll2.cend(), std::ostream_iterator<int>(std::cout, ", "), [](int a, int b){ return a+1 == b || a-1 == b; }); std::cout << "\n"; }
36.932432
99
0.658617
[ "vector" ]
753c98109ac341f9f0b37bdd732f448bd6ef74e4
1,012
cpp
C++
src/build.cpp
huntdog1541/Chirp
b7ed55f3911fd7fbff42524dfa1675cefae4d6d3
[ "MIT" ]
null
null
null
src/build.cpp
huntdog1541/Chirp
b7ed55f3911fd7fbff42524dfa1675cefae4d6d3
[ "MIT" ]
null
null
null
src/build.cpp
huntdog1541/Chirp
b7ed55f3911fd7fbff42524dfa1675cefae4d6d3
[ "MIT" ]
null
null
null
#include "build.h" #include "cli/log.h" #include "cli.h" #include "parser.h" #include "parser/lexer.h" #include "parser/syntax.h" #include "gen/gen_ir.h" #include "gen/gen_asm.h" #include "simple_tree_drawer.hpp" #include <iostream> std::string compile(std::string source) { cli::log(cli::log_level::debug, "Debug messages are now visible"); std::vector<token> tokens = lexer::tokenize(source); parser p_env; p_env.setTokens(tokens); tree parseTree; auto root = std::make_unique<node>("root"); parseTree.setRoot(std::move(root)); syntax::parse(&p_env,&parseTree); if(cli::draw_tree()){ cli::log(cli::log_level::log, "Drawing syntax tree"); simple_tree_drawer("test").draw(parseTree); } std::vector<ir::operation> intermediate; intermediate = gen::make_ir(&parseTree); std::string output; output = gen::make_asm(intermediate); cli::log(cli::log_level::success, "Code analysis succesfull"); return output; } void build() { }
22.488889
70
0.667984
[ "vector" ]
753d63730abe9c3947f1aa0fbab95e02fec96f1a
308
cpp
C++
Array/Array.cpp
paulburgess1357/Blind75
5201ffb938892a48243cdb8b6781a02e7face64c
[ "MIT" ]
null
null
null
Array/Array.cpp
paulburgess1357/Blind75
5201ffb938892a48243cdb8b6781a02e7face64c
[ "MIT" ]
null
null
null
Array/Array.cpp
paulburgess1357/Blind75
5201ffb938892a48243cdb8b6781a02e7face64c
[ "MIT" ]
null
null
null
#include <iostream> #include "1_TwoSum.h" int main(){ //std::vector<int> input{ 3, 2, 3 }; //std::cout << "Hello World!\n"; //TwoSum::Solution sol; //sol.twoSum2(input, 6); std::vector<int> atest; atest.resize(500); atest[499] = 100; std::cout << atest[499] << std::endl; }
20.533333
41
0.561688
[ "vector" ]
753fcbbb529b8d94ab511e07b39d956d19662391
29,178
cpp
C++
test/runtime/SimulatorCiphertextFactoryTest.cpp
moritzwinger/ABC
2d1f507dc7188b13767cce8050b8aa9daa7c1625
[ "MIT" ]
null
null
null
test/runtime/SimulatorCiphertextFactoryTest.cpp
moritzwinger/ABC
2d1f507dc7188b13767cce8050b8aa9daa7c1625
[ "MIT" ]
null
null
null
test/runtime/SimulatorCiphertextFactoryTest.cpp
moritzwinger/ABC
2d1f507dc7188b13767cce8050b8aa9daa7c1625
[ "MIT" ]
null
null
null
#include <algorithm> #include "gtest/gtest.h" #include "include/ast_opt/runtime/SimulatorCiphertext.h" #include "include/ast_opt/ast/ExpressionList.h" #include "include/ast_opt/runtime/SimulatorCiphertextFactory.h" #include "include/ast_opt/runtime/Cleartext.h" #include "ast_opt/utilities/PlaintextNorm.h" #ifdef HAVE_SEAL_BFV class SimulatorCiphertextFactoryTest : public ::testing::Test { protected: const int numCiphertextSlots = 16384; std::unique_ptr<SimulatorCiphertextFactory> scf; void SetUp() override { scf = std::make_unique<SimulatorCiphertextFactory>(numCiphertextSlots); } // calculates initial noise heuristic of a freshly encrypted ciphertext uint64_t calcInitNoiseHeuristic() { uint64_t plain_modulus = scf->getContext().first_context_data()->parms().plain_modulus().value(); uint64_t poly_modulus = scf->getContext().first_context_data()->parms().poly_modulus_degree(); mpz_t result_noise; mpz_init(result_noise); mpz_t plain_mod; mpz_init(plain_mod); mpz_init_set_ui(plain_mod, plain_modulus); mpz_t poly_mod; mpz_init(poly_mod); mpz_init_set_ui(poly_mod, poly_modulus); // summand_one = n * (t-1) / 2 mpz_t summand_one; mpz_init(summand_one); mpz_sub_ui(summand_one, plain_mod, 1); mpz_mul(summand_one, summand_one, poly_mod); mpz_div_ui(summand_one, summand_one, 2); // summand_two = 2 * sigma * sqrt(12 * n ^2 + 9 * n) mpz_t summand_two; mpz_init(summand_two); mpz_pow_ui(summand_two, poly_mod, 2); mpz_mul_ui(summand_two, summand_two, 12); mpz_t poly_mod_times_nine; mpz_init(poly_mod_times_nine); mpz_mul_ui(poly_mod_times_nine, poly_mod, 9); mpz_add(summand_two, summand_two, poly_mod_times_nine); mpz_sqrt(summand_two, summand_two); mpz_mul_ui(summand_two, summand_two, long(6.4)); // sigma = 3.2 mpz_t sum; // sum = summand_1 + summand_2 mpz_init(sum); mpz_add(sum, summand_one, summand_two); // result_noise = t * sum mpz_mul(result_noise, sum, plain_mod); size_t coeff_modulus_significant_bit_count = scf->getContext().first_context_data()->total_coeff_modulus_bit_count(); size_t log_noise = mpz_sizeinbase(result_noise, 2); return std::max(int(coeff_modulus_significant_bit_count - log_noise - 1), 0); } // calculates noise heuristics for ctxt-ctxt add uint64_t calcAddNoiseHeuristic() { // calc init noise heur for ctxt1 and ctxt2 uint64_t plain_modulus = scf->getContext().first_context_data()->parms().plain_modulus().value(); uint64_t poly_modulus = scf->getContext().first_context_data()->parms().poly_modulus_degree(); mpz_t init_noise; mpz_init(init_noise); mpz_t plain_mod; mpz_init(plain_mod); mpz_init_set_ui(plain_mod, plain_modulus); mpz_t poly_mod; mpz_init(poly_mod); mpz_init_set_ui(poly_mod, poly_modulus); // summand_one = n * (t-1) / 2 mpz_t summand_one; mpz_init(summand_one); mpz_sub_ui(summand_one, plain_mod, 1); mpz_mul(summand_one, summand_one, poly_mod); mpz_div_ui(summand_one, summand_one, 2); // summand_two = 2 * sigma * sqrt(12 * n ^2 + 9 * n) mpz_t summand_two; mpz_init(summand_two); mpz_pow_ui(summand_two, poly_mod, 2); mpz_mul_ui(summand_two, summand_two, 12); mpz_t poly_mod_times_nine; mpz_init(poly_mod_times_nine); mpz_mul_ui(poly_mod_times_nine, poly_mod, 9); mpz_add(summand_two, summand_two, poly_mod_times_nine); mpz_sqrt(summand_two, summand_two); mpz_mul_ui(summand_two, summand_two, long(6.4)); // sigma = 3.2 mpz_t sum; // sum = summand_1 + summand_2 mpz_init(sum); mpz_add(sum, summand_one, summand_two); // result_noise = t * sum mpz_mul(init_noise, sum, plain_mod); mpz_t result_noise; mpz_init(result_noise); mpz_add(result_noise, init_noise, init_noise); size_t coeff_modulus_significant_bit_count = scf->getContext().first_context_data()->total_coeff_modulus_bit_count(); size_t log_noise = mpz_sizeinbase(result_noise, 2); return std::max(int(coeff_modulus_significant_bit_count - log_noise - 1), 0); } // calculates noise heuristics for ctxt-ctxt mult uint64_t calcMultNoiseHeuristic() { // calc init noise heur for ctxt1 and ctxt2 uint64_t plain_modulus = scf->getContext().first_context_data()->parms().plain_modulus().value(); uint64_t poly_modulus = scf->getContext().first_context_data()->parms().poly_modulus_degree(); mpz_t init_noise; mpz_init(init_noise); mpz_t plain_mod; mpz_init(plain_mod); mpz_init_set_ui(plain_mod, plain_modulus); mpz_t poly_mod; mpz_init(poly_mod); mpz_init_set_ui(poly_mod, poly_modulus); // summand_one = n * (t-1) / 2 mpz_t summand_one; mpz_init(summand_one); mpz_sub_ui(summand_one, plain_mod, 1); mpz_mul(summand_one, summand_one, poly_mod); mpz_div_ui(summand_one, summand_one, 2); // summand_two = 2 * sigma * sqrt(12 * n ^2 + 9 * n) mpz_t summand_two; mpz_init(summand_two); mpz_pow_ui(summand_two, poly_mod, 2); mpz_mul_ui(summand_two, summand_two, 12); mpz_t poly_mod_times_nine; mpz_init(poly_mod_times_nine); mpz_mul_ui(poly_mod_times_nine, poly_mod, 9); mpz_add(summand_two, summand_two, poly_mod_times_nine); mpz_sqrt(summand_two, summand_two); mpz_mul_ui(summand_two, summand_two, long(6.4)); // sigma = 3.2 mpz_t sum; // sum = summand_1 + summand_2 mpz_init(sum); mpz_add(sum, summand_one, summand_two); // result_noise = t * sum mpz_mul(init_noise, sum, plain_mod); mpz_t result_noise; mpz_init(result_noise); mpz_t coeff_mod; mpz_init(coeff_mod); mpz_init_set_ui(coeff_mod, *scf->getContext().first_context_data()->total_coeff_modulus()); // some powers of n and other things mpz_t poly_mod_squared; mpz_init(poly_mod_squared); mpz_pow_ui(poly_mod_squared, poly_mod, 2); mpz_t poly_mod_cubed; mpz_init(poly_mod_cubed); mpz_pow_ui(poly_mod_cubed, poly_mod, 3); mpz_t poly_mod_squared_times_two; mpz_init(poly_mod_squared_times_two); mpz_mul_ui(poly_mod_squared_times_two, poly_mod, 2); mpz_t poly_mod_cubed_times_four; mpz_init(poly_mod_cubed_times_four); mpz_mul_ui(poly_mod_cubed_times_four, poly_mod_cubed, 4); mpz_t poly_mod_cubed_times_four_div_three; mpz_init(poly_mod_cubed_times_four_div_three); mpz_div_ui(poly_mod_cubed_times_four_div_three, poly_mod_cubed_times_four, 3); // summand_one = t * sqrt(3n + 2n^2) (v1 + v2) mpz_t sum_one; mpz_init(sum_one); mpz_mul_ui(sum_one, poly_mod, 3); mpz_add(sum_one, sum_one, poly_mod_squared_times_two); mpz_sqrt(sum_one, sum_one); mpz_mul(sum_one, sum_one, plain_mod); mpz_t noise_sum; mpz_init(noise_sum); mpz_add(noise_sum, init_noise, init_noise); mpz_mul(sum_one, sum_one, noise_sum); //summand_two = 3 * v1 * v2 / q mpz_t sum_two; mpz_init(sum_two); mpz_mul(sum_two, init_noise, init_noise); mpz_mul_ui(sum_two, sum_two, 3); mpz_div(sum_two, sum_two, coeff_mod); //summand_three = t * sqrt(3d+2d^2+4d^3/3) mpz_t summand_three; mpz_init(summand_three); mpz_mul_ui(summand_three, poly_mod, 3); mpz_add(summand_three, summand_three, poly_mod_squared_times_two); mpz_add(summand_three, summand_three, poly_mod_cubed_times_four_div_three); mpz_sqrt(summand_three, summand_three); mpz_mul(summand_three, summand_three, plain_mod); // result_noise = summand_1 * summand_2 + summand_3 mpz_add(result_noise, sum_one, sum_two); mpz_add(result_noise, result_noise, summand_three); size_t coeff_modulus_significant_bit_count = scf->getContext().first_context_data()->total_coeff_modulus_bit_count(); size_t log_noise = mpz_sizeinbase(result_noise, 2); return std::max(int(coeff_modulus_significant_bit_count - log_noise - 1), 0); } uint64_t calcAddPlainNoiseHeuristic(AbstractCiphertext &abstractCiphertext, ICleartext &operand) { //noise is old_noise + r_t(q) * plain_max_coeff_count * plain_max_abs_value std::unique_ptr<seal::Plaintext> plaintext = scf->createPlaintext(dynamic_cast<Cleartext<int> *>(&operand)->getData()); int64_t rtq = scf->getContext().first_context_data()->coeff_modulus_mod_plain_modulus(); int64_t plain_max_abs_value = plaintext_norm(*plaintext); int64_t plain_max_coeff_count = plaintext->nonzero_coeff_count(); uint64_t plain_modulus = scf->getContext().first_context_data()->parms().plain_modulus().value(); uint64_t poly_modulus = scf->getContext().first_context_data()->parms().poly_modulus_degree(); // calc init noise mpz_t init_noise; mpz_init(init_noise); mpz_t plain_mod; mpz_init(plain_mod); mpz_init_set_ui(plain_mod, plain_modulus); mpz_t poly_mod; mpz_init(poly_mod); mpz_init_set_ui(poly_mod, poly_modulus); // summand_one = n * (t-1) / 2 mpz_t summand_one; mpz_init(summand_one); mpz_sub_ui(summand_one, plain_mod, 1); mpz_mul(summand_one, summand_one, poly_mod); mpz_div_ui(summand_one, summand_one, 2); // summand_two = 2 * sigma * sqrt(12 * n ^2 + 9 * n) mpz_t summand_two; mpz_init(summand_two); mpz_pow_ui(summand_two, poly_mod, 2); mpz_mul_ui(summand_two, summand_two, 12); mpz_t poly_mod_times_nine; mpz_init(poly_mod_times_nine); mpz_mul_ui(poly_mod_times_nine, poly_mod, 9); mpz_add(summand_two, summand_two, poly_mod_times_nine); mpz_sqrt(summand_two, summand_two); mpz_mul_ui(summand_two, summand_two, long(6.4)); // sigma = 3.2 mpz_t sum; // sum = summand_1 + summand_2 mpz_init(sum); mpz_add(sum, summand_one, summand_two); // result_noise = t * sum mpz_mul(init_noise, sum, plain_mod); // calc heuristic mpz_t result_noise; mpz_init(result_noise); mpz_t rt_q; mpz_init(rt_q); mpz_init_set_ui(rt_q, rtq); mpz_t plain_coeff_ct; mpz_init(plain_coeff_ct); mpz_init_set_ui(plain_coeff_ct, plain_max_coeff_count); mpz_t plain_abs; mpz_init(plain_abs); mpz_init_set_ui(plain_abs, plain_max_abs_value); mpz_mul(result_noise, rt_q, plain_coeff_ct); mpz_mul(result_noise, result_noise, plain_abs); mpz_add(result_noise, result_noise, init_noise); size_t coeff_modulus_significant_bit_count = scf->getContext().first_context_data()->total_coeff_modulus_bit_count(); size_t log_noise = mpz_sizeinbase(result_noise, 2); return std::max(int(coeff_modulus_significant_bit_count - log_noise - 1), 0); } uint64_t calcMultiplyPlainNoiseHeuristic(AbstractCiphertext &abstractCiphertext, ICleartext &operand) { std::unique_ptr<seal::Plaintext> plaintext = scf->createPlaintext(dynamic_cast<Cleartext<int> *>(&operand)->getData()); int64_t rtq = scf->getContext().first_context_data()->coeff_modulus_mod_plain_modulus(); int64_t plain_max_abs_value = plaintext_norm(*plaintext); int64_t plain_max_coeff_count = plaintext->nonzero_coeff_count(); uint64_t plain_modulus = scf->getContext().first_context_data()->parms().plain_modulus().value(); uint64_t poly_modulus = scf->getContext().first_context_data()->parms().poly_modulus_degree(); // calc init noise mpz_t init_noise; mpz_init(init_noise); mpz_t plain_mod; mpz_init(plain_mod); mpz_init_set_ui(plain_mod, plain_modulus); mpz_t poly_mod; mpz_init(poly_mod); mpz_init_set_ui(poly_mod, poly_modulus); // summand_one = n * (t-1) / 2 mpz_t summand_one; mpz_init(summand_one); mpz_sub_ui(summand_one, plain_mod, 1); mpz_mul(summand_one, summand_one, poly_mod); mpz_div_ui(summand_one, summand_one, 2); // summand_two = 2 * sigma * sqrt(12 * n ^2 + 9 * n) mpz_t summand_two; mpz_init(summand_two); mpz_pow_ui(summand_two, poly_mod, 2); mpz_mul_ui(summand_two, summand_two, 12); mpz_t poly_mod_times_nine; mpz_init(poly_mod_times_nine); mpz_mul_ui(poly_mod_times_nine, poly_mod, 9); mpz_add(summand_two, summand_two, poly_mod_times_nine); mpz_sqrt(summand_two, summand_two); mpz_mul_ui(summand_two, summand_two, long(6.4)); // sigma = 3.2 mpz_t sum; // sum = summand_1 + summand_2 mpz_init(sum); mpz_add(sum, summand_one, summand_two); // result_noise = t * sum mpz_mul(init_noise, sum, plain_mod); //calc heuristic // noise is old_noise * plain_max_coeff_count * plain_max_abs_value (SEAL Manual) mpz_t plain_coeff_ct; mpz_init(plain_coeff_ct); mpz_init_set_ui(plain_coeff_ct, plain_max_coeff_count); mpz_t plain_abs; mpz_init(plain_abs); mpz_init_set_ui(plain_abs, plain_max_abs_value); mpz_t result_noise; mpz_init(result_noise); mpz_mul(result_noise, plain_abs, plain_coeff_ct); mpz_mul(result_noise, result_noise, init_noise); size_t coeff_modulus_significant_bit_count = scf->getContext().first_context_data()->total_coeff_modulus_bit_count(); size_t log_noise = mpz_sizeinbase(result_noise, 2); return std::max(int(coeff_modulus_significant_bit_count - log_noise - 1), 0); } uint64_t calcModSwitchHeuristic(AbstractCiphertext &abstractCiphertext) { mpz_t result_noise; mpz_init(result_noise); mpz_t plain_mod; mpz_init(plain_mod); mpz_init_set_ui(plain_mod, scf->getContext().first_context_data()->parms().plain_modulus().value()); mpz_t poly_mod; mpz_init(poly_mod); mpz_init_set_ui(poly_mod, scf->getContext().first_context_data()->parms().poly_modulus_degree()); mpz_t coeff_mod; mpz_init(coeff_mod); mpz_init_set_ui(coeff_mod, *scf->getContext().first_context_data()->total_coeff_modulus()); // calc init noise mpz_t init_noise; mpz_init(init_noise); // summand_one = n * (t-1) / 2 mpz_t summand_one; mpz_init(summand_one); mpz_sub_ui(summand_one, plain_mod, 1); mpz_mul(summand_one, summand_one, poly_mod); mpz_div_ui(summand_one, summand_one, 2); // summand_two = 2 * sigma * sqrt(12 * n ^2 + 9 * n) mpz_t summand_two; mpz_init(summand_two); mpz_pow_ui(summand_two, poly_mod, 2); mpz_mul_ui(summand_two, summand_two, 12); mpz_t poly_mod_times_nine; mpz_init(poly_mod_times_nine); mpz_mul_ui(poly_mod_times_nine, poly_mod, 9); mpz_add(summand_two, summand_two, poly_mod_times_nine); mpz_sqrt(summand_two, summand_two); mpz_mul_ui(summand_two, summand_two, long(6.4)); // sigma = 3.2 mpz_t sum; // sum = summand_1 + summand_2 mpz_init(sum); mpz_add(sum, summand_one, summand_two); // result_noise = t * sum mpz_mul(init_noise, sum, plain_mod); // get last q_i auto &context_data = *scf->getContext().key_context_data(); auto coeff_modulus = context_data.parms().coeff_modulus(); std::size_t coeff_modulus_size = coeff_modulus.size(); mpz_t last_prime; mpz_init(last_prime); mpz_init_set_ui(last_prime, coeff_modulus[coeff_modulus_size - 1].value()); // last primefactor of coeff modulus mpz_t new_coeff_modulus; // calculate t/(p * q) sqrt(3n+2n^2) = t * q_i / (q^2) sqrt(3n+2n^2) mpz_t summand; mpz_init(summand); // 2n^2 mpz_t poly_mod_squared; mpz_init(poly_mod_squared); mpz_pow_ui(poly_mod_squared, poly_mod, 2); mpz_t poly_mod_squared_times_two; mpz_init(poly_mod_squared_times_two); mpz_mul_ui(poly_mod_squared_times_two, poly_mod, 2); // sqrt(3n+2n^2) mpz_mul_ui(summand, poly_mod, 3); mpz_add(summand, summand, poly_mod_squared_times_two); mpz_sqrt(summand, summand); // t * sqrt(3n+2n^2) mpz_mul(summand, summand, plain_mod); // t * q_i * sqrt(3n+2n^2) mpz_mul(summand, summand, last_prime); // q^2 mpz_t coeff_mod_squared; mpz_init(coeff_mod_squared); mpz_pow_ui(coeff_mod_squared, coeff_mod, 2); // t * q_i / (q^2) sqrt(3n+2n^2) mpz_div(summand, summand, coeff_mod_squared); // resultnoise = operand._noise + summand mpz_add(result_noise, summand, init_noise); size_t coeff_modulus_significant_bit_count = scf->getContext().first_context_data()->total_coeff_modulus_bit_count(); size_t log_noise = mpz_sizeinbase(result_noise, 2); return std::max(int(coeff_modulus_significant_bit_count - log_noise - 1), 0); } void checkCiphertextData( AbstractCiphertext &abstractCiphertext, const std::vector<int64_t> &expectedValues) { // decrypt ciphertext std::vector<int64_t> result; scf->decryptCiphertext(abstractCiphertext, result); // check that the decrypted ciphertext has the expected size EXPECT_EQ(result.size(), numCiphertextSlots); // check that provided values are in decryption result for (int i = 0; i < expectedValues.size(); ++i) { EXPECT_EQ(expectedValues.at(i), result.at(i)); } // check that all remaining ciphertext slots are filled with last value of given input for (int i = expectedValues.size(); i < result.size(); ++i) { ASSERT_EQ(expectedValues.back(), result.at(i)); } } void checkCiphertextNoise(const AbstractCiphertext &abstractCiphertext, double expected_noise) { std::cout << "Noise Budget after op: " << (dynamic_cast<const SimulatorCiphertext&>(abstractCiphertext)).noiseBits() << std::endl; EXPECT_EQ((dynamic_cast<const SimulatorCiphertext&>(abstractCiphertext)).noiseBits(), expected_noise); } }; TEST_F(SimulatorCiphertextFactoryTest, createCiphertext) { /* NOLINT */ // create ciphertext std::vector<int64_t> data = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt = scf->createCiphertext(data); checkCiphertextData(*ctxt, data); } // ======================================= // == create fresh ciphertext // ======================================= TEST_F(SimulatorCiphertextFactoryTest, createFresh) { // create ciphertexts std::vector<int64_t> data = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt = scf->createCiphertext(data); uint64_t expected_noise = calcInitNoiseHeuristic(); checkCiphertextNoise(*ctxt, expected_noise); } // ======================================= // == CTXT-CTXT operations with returned result // ======================================= TEST_F(SimulatorCiphertextFactoryTest, add) { /* NOLINT */ // create ciphertexts std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int64_t> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data2); auto ctxtResult = ctxt1->add(*ctxt2); uint64_t expected_noise = calcAddNoiseHeuristic(); checkCiphertextNoise(*ctxtResult, expected_noise); // make sure that operands are not changed checkCiphertextData(*ctxt1, data1); checkCiphertextData(*ctxt2, data2); } TEST_F(SimulatorCiphertextFactoryTest, sub) { /* NOLINT */ // create ciphertexts std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int64_t> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data2); auto ctxtResult = ctxt1->subtract(*ctxt2); uint64_t expected_noise = calcAddNoiseHeuristic(); checkCiphertextNoise(*ctxtResult, expected_noise); // make sure that operands are not changed checkCiphertextData(*ctxt1, data1); checkCiphertextData(*ctxt2, data2); } TEST_F(SimulatorCiphertextFactoryTest, multiply) { /* NOLINT */ // create ciphertexts std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int64_t> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data2); auto ctxtResult = ctxt1->multiply(*ctxt2); uint64_t expected_noise = calcMultNoiseHeuristic(); checkCiphertextNoise(*ctxtResult, expected_noise); // make sure that operands are not changed checkCiphertextData(*ctxt1, data1); checkCiphertextData(*ctxt2, data2); } // ======================================= // == CTXT-CTXT in-place operations // ======================================= TEST_F(SimulatorCiphertextFactoryTest, addInplace) { /* NOLINT */ // create ciphertexts std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int64_t> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data2); uint64_t expected_noise = calcAddNoiseHeuristic(); ctxt1->addInplace(*ctxt2); checkCiphertextNoise(*ctxt1, expected_noise); } TEST_F(SimulatorCiphertextFactoryTest, subtractInplace) { /* NOLINT */ // create ciphertexts std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int64_t> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data2); uint64_t expected_noise = calcAddNoiseHeuristic(); ctxt1->subtractInplace(*ctxt2); checkCiphertextNoise(*ctxt1, expected_noise); } TEST_F(SimulatorCiphertextFactoryTest, multiplyInplace) { /* NOLINT */ // create ciphertexts std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int64_t> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data2); uint64_t expected_noise = calcMultNoiseHeuristic(); ctxt1->multiplyInplace(*ctxt2); checkCiphertextNoise(*ctxt1, expected_noise); } // ======================================= // == CTXT-PLAIN operations with returned result // ======================================= Cleartext<int> createCleartextSim(const std::vector<int> &literalIntValues) { std::vector<std::unique_ptr<AbstractExpression>> result; for (const auto &val : literalIntValues) { result.emplace_back(std::make_unique<LiteralInt>(val)); } return Cleartext<int>(literalIntValues); } TEST_F(SimulatorCiphertextFactoryTest, addPlain) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; auto operandVector = createCleartextSim(data2); uint64_t expected_noise = calcAddPlainNoiseHeuristic(*ctxt1,operandVector); auto ctxtResult = ctxt1->addPlain(operandVector); checkCiphertextNoise(*ctxtResult, expected_noise); // make sure that ciphertext operand is not changed checkCiphertextData(*ctxt1, data1); } TEST_F(SimulatorCiphertextFactoryTest, subPlain) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; auto operandVector = createCleartextSim(data2); auto ctxtResult = ctxt1->subtractPlain(operandVector); uint64_t expected_noise = calcAddPlainNoiseHeuristic(*ctxt1,operandVector); checkCiphertextNoise(*ctxtResult, expected_noise); // make sure that ciphertext operand is not changed checkCiphertextData(*ctxt1, data1); } TEST_F(SimulatorCiphertextFactoryTest, multiplyPlain) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; auto operandVector = createCleartextSim(data2); auto ctxtResult = ctxt1->multiplyPlain(operandVector); uint64_t expected_noise = calcMultiplyPlainNoiseHeuristic(*ctxt1,operandVector); checkCiphertextNoise(*ctxtResult, expected_noise); // make sure that ciphertext operand is not changed checkCiphertextData(*ctxt1, data1); } // ======================================= // == CTXT-PLAIN in-place operations // ======================================= TEST_F(SimulatorCiphertextFactoryTest, addPlainInplace) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; auto operandVector = createCleartextSim(data2); uint64_t expected_noise = calcAddPlainNoiseHeuristic(*ctxt1,operandVector); ctxt1->addPlainInplace(operandVector); checkCiphertextNoise(*ctxt1, expected_noise); } TEST_F(SimulatorCiphertextFactoryTest, subPlainInplace) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; auto operandVector = createCleartextSim(data2); uint64_t expected_noise = calcAddPlainNoiseHeuristic(*ctxt1,operandVector); ctxt1->subtractPlainInplace(operandVector); checkCiphertextNoise(*ctxt1, expected_noise); } TEST_F(SimulatorCiphertextFactoryTest, multiplyPlainInplace) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; auto operandVector = createCleartextSim(data2); uint64_t expected_noise = calcMultiplyPlainNoiseHeuristic(*ctxt1,operandVector); ctxt1->multiplyPlainInplace(operandVector); checkCiphertextNoise(*ctxt1, expected_noise); } TEST_F(SimulatorCiphertextFactoryTest, modSwitch) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; auto operandVector = createCleartextSim(data2); uint64_t expected_noise = calcModSwitchHeuristic(*ctxt1); dynamic_cast<SimulatorCiphertext &>(*ctxt1).modSwitch(); //std::cout << "NoiseBudget after Modswitch: " << // (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; checkCiphertextNoise(*ctxt1, expected_noise); } TEST_F(SimulatorCiphertextFactoryTest, modSwitchNTimes) { /* NOLINT */ // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data1); uint64_t expected_noise = calcModSwitchHeuristic(*ctxt1); std::cout << "Fresh: " << dynamic_cast<SimulatorCiphertext &>(*ctxt1).getNoiseBudget() << std::endl; dynamic_cast<SimulatorCiphertext &>(*ctxt1).modSwitch(); dynamic_cast<SimulatorCiphertext &>(*ctxt1).modSwitch(); dynamic_cast<SimulatorCiphertext &>(*ctxt2).modSwitch(2); //std::cout << "NoiseBudget after Modswitch: " << // (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; checkCiphertextNoise(*ctxt1, dynamic_cast<SimulatorCiphertext &>(*ctxt2).getNoiseBudget()); } TEST_F(SimulatorCiphertextFactoryTest, xToPowerFourTimesYBad) { // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt3 = scf->createCiphertext(data2); std::cout << "x^4: The 'bad' way:" << std::endl; std::cout << "NoiseBudget(x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; // x * x ctxt1->multiplyInplace(*ctxt1); std::cout << "NoiseBudget(x * x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; // x * x * x ctxt1->multiplyInplace(*ctxt1); std::cout << "NoiseBudget(x * x * x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; // x * x * x * x ctxt1->multiplyInplace(*ctxt1); std::cout << "NoiseBudget(x * x * x * x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; std::cout << std::endl; } TEST_F(SimulatorCiphertextFactoryTest, xToPowerFourTimesYGood) { // create ciphertext std::vector<int64_t> data1 = {3, 3, 1, 4, 5, 9}; std::unique_ptr<AbstractCiphertext> ctxt1 = scf->createCiphertext(data1); std::unique_ptr<AbstractCiphertext> ctxt2 = scf->createCiphertext(data1); std::vector<int> data2 = {0, 1, 2, 1, 10, 21}; std::unique_ptr<AbstractCiphertext> ctxt3 = scf->createCiphertext(data2); std::cout << "x^4: The 'good' way:" << std::endl; std::cout << "NoiseBudget(x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; // x * x ctxt1->multiplyInplace(*ctxt1); std::cout << "NoiseBudget(x * x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; // x * x * x ctxt2->multiplyInplace(*ctxt2); std::cout << "NoiseBudget(x * x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; // x * x * x * x ctxt1->multiplyInplace(*ctxt2); std::cout << "NoiseBudget(x * x) * (x * x): " << (dynamic_cast<const SimulatorCiphertext&>(*ctxt1)).noiseBits() << std::endl; } #endif
40.637883
134
0.710261
[ "vector", "3d" ]
754878b1ef4192a5a401f55179aca0fd45fc4a2f
30,399
hpp
C++
src/libraries/core/fields/fvPatchFields/basic/generic/genericFvPatchField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fields/fvPatchFields/basic/generic/genericFvPatchField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fields/fvPatchFields/basic/generic/genericFvPatchField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2015 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::genericFvPatchField Description A generic version of calculatedFvPatchField, useful as a fallback for handling unknown patch types. \*---------------------------------------------------------------------------*/ #ifndef genericFvPatchField_H #define genericFvPatchField_H #include "calculatedFvPatchField.hpp" #include "HashPtrTable.hpp" #include "fvPatchFieldMapper.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class genericFvPatch Declaration \*---------------------------------------------------------------------------*/ template<class Type> class genericFvPatchField : public calculatedFvPatchField<Type> { // Private data word actualTypeName_; dictionary dict_; HashPtrTable<scalarField> scalarFields_; HashPtrTable<vectorField> vectorFields_; HashPtrTable<sphericalTensorField> sphericalTensorFields_; HashPtrTable<symmTensorField> symmTensorFields_; HashPtrTable<tensorField> tensorFields_; public: //- Runtime type information TypeName("generic"); // Constructors //- Construct from patch and internal field genericFvPatchField ( const fvPatch&, const DimensionedField<Type, volMesh>& ); //- Construct from patch, internal field and dictionary genericFvPatchField ( const fvPatch&, const DimensionedField<Type, volMesh>&, const dictionary& ); //- Construct by mapping given patchField<Type> onto a new patch genericFvPatchField ( const genericFvPatchField<Type>&, const fvPatch&, const DimensionedField<Type, volMesh>&, const fvPatchFieldMapper& ); //- Construct as copy genericFvPatchField ( const genericFvPatchField<Type>& ); //- Construct and return a clone virtual tmp<fvPatchField<Type> > clone() const { return tmp<fvPatchField<Type> > ( new genericFvPatchField<Type>(*this) ); } //- Construct as copy setting internal field reference genericFvPatchField ( const genericFvPatchField<Type>&, const DimensionedField<Type, volMesh>& ); //- Construct and return a clone setting internal field reference virtual tmp<fvPatchField<Type> > clone ( const DimensionedField<Type, volMesh>& iF ) const { return tmp<fvPatchField<Type> > ( new genericFvPatchField<Type>(*this, iF) ); } // Member functions // Mapping functions //- Map (and resize as needed) from self given a mapping object virtual void autoMap ( const fvPatchFieldMapper& ); //- Reverse map the given fvPatchField onto this fvPatchField virtual void rmap ( const fvPatchField<Type>&, const labelList& ); // Evaluation functions //- Return the matrix diagonal coefficients corresponding to the // evaluation of the value of this patchField with given weights virtual tmp<Field<Type> > valueInternalCoeffs ( const tmp<scalarField>& ) const; //- Return the matrix source coefficients corresponding to the // evaluation of the value of this patchField with given weights virtual tmp<Field<Type> > valueBoundaryCoeffs ( const tmp<scalarField>& ) const; //- Return the matrix diagonal coefficients corresponding to the // evaluation of the gradient of this patchField tmp<Field<Type> > gradientInternalCoeffs() const; //- Return the matrix source coefficients corresponding to the // evaluation of the gradient of this patchField tmp<Field<Type> > gradientBoundaryCoeffs() const; //- Write virtual void write(Ostream&) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class Type> CML::genericFvPatchField<Type>::genericFvPatchField ( const fvPatch& p, const DimensionedField<Type, volMesh>& iF ) : calculatedFvPatchField<Type>(p, iF) { FatalErrorInFunction << "Not Implemented\n " << "Trying to construct an genericFvPatchField on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << abort(FatalError); } template<class Type> CML::genericFvPatchField<Type>::genericFvPatchField ( const fvPatch& p, const DimensionedField<Type, volMesh>& iF, const dictionary& dict ) : calculatedFvPatchField<Type>(p, iF, dict, false), actualTypeName_(dict.lookup("type")), dict_(dict) { if (!dict.found("value")) { FatalIOErrorInFunction(dict) << "\n Cannot find 'value' entry" << " on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << nl << " which is required to set the" " values of the generic patch field." << nl << " (Actual type " << actualTypeName_ << ")" << nl << "\n Please add the 'value' entry to the write function " "of the user-defined boundary-condition\n" << exit(FatalIOError); } forAllConstIter(dictionary, dict_, iter) { if (iter().keyword() != "type" && iter().keyword() != "value") { if ( iter().isStream() && iter().stream().size() ) { ITstream& is = iter().stream(); // Read first token token firstToken(is); if ( firstToken.isWord() && firstToken.wordToken() == "nonuniform" ) { token fieldToken(is); if (!fieldToken.isCompound()) { if ( fieldToken.isLabel() && fieldToken.labelToken() == 0 ) { scalarFields_.insert ( iter().keyword(), new scalarField(0) ); } else { FatalIOErrorInFunction(dict) << "\n token following 'nonuniform' " "is not a compound" << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } } else if ( fieldToken.compoundToken().type() == token::Compound<List<scalar> >::typeName ) { scalarField* fPtr = new scalarField; fPtr->transfer ( dynamicCast<token::Compound<List<scalar> > > ( fieldToken.transferCompoundToken(is) ) ); if (fPtr->size() != this->size()) { FatalIOErrorInFunction(dict) << "\n size of field " << iter().keyword() << " (" << fPtr->size() << ')' << " is not the same size as the patch (" << this->size() << ')' << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } scalarFields_.insert(iter().keyword(), fPtr); } else if ( fieldToken.compoundToken().type() == token::Compound<List<vector> >::typeName ) { vectorField* fPtr = new vectorField; fPtr->transfer ( dynamicCast<token::Compound<List<vector> > > ( fieldToken.transferCompoundToken(is) ) ); if (fPtr->size() != this->size()) { FatalIOErrorInFunction(dict) << "\n size of field " << iter().keyword() << " (" << fPtr->size() << ')' << " is not the same size as the patch (" << this->size() << ')' << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } vectorFields_.insert(iter().keyword(), fPtr); } else if ( fieldToken.compoundToken().type() == token::Compound<List<sphericalTensor> >::typeName ) { sphericalTensorField* fPtr = new sphericalTensorField; fPtr->transfer ( dynamicCast < token::Compound<List<sphericalTensor> > > ( fieldToken.transferCompoundToken(is) ) ); if (fPtr->size() != this->size()) { FatalIOErrorInFunction(dict) << "\n size of field " << iter().keyword() << " (" << fPtr->size() << ')' << " is not the same size as the patch (" << this->size() << ')' << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } sphericalTensorFields_.insert(iter().keyword(), fPtr); } else if ( fieldToken.compoundToken().type() == token::Compound<List<symmTensor> >::typeName ) { symmTensorField* fPtr = new symmTensorField; fPtr->transfer ( dynamicCast < token::Compound<List<symmTensor> > > ( fieldToken.transferCompoundToken(is) ) ); if (fPtr->size() != this->size()) { FatalIOErrorInFunction(dict) << "\n size of field " << iter().keyword() << " (" << fPtr->size() << ')' << " is not the same size as the patch (" << this->size() << ')' << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } symmTensorFields_.insert(iter().keyword(), fPtr); } else if ( fieldToken.compoundToken().type() == token::Compound<List<tensor> >::typeName ) { tensorField* fPtr = new tensorField; fPtr->transfer ( dynamicCast<token::Compound<List<tensor> > > ( fieldToken.transferCompoundToken(is) ) ); if (fPtr->size() != this->size()) { FatalIOErrorInFunction(dict) << "\n size of field " << iter().keyword() << " (" << fPtr->size() << ')' << " is not the same size as the patch (" << this->size() << ')' << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } tensorFields_.insert(iter().keyword(), fPtr); } else { FatalIOErrorInFunction(dict) << "\n compound " << fieldToken.compoundToken() << " not supported" << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } } else if ( firstToken.isWord() && firstToken.wordToken() == "uniform" ) { token fieldToken(is); if (!fieldToken.isPunctuation()) { scalarFields_.insert ( iter().keyword(), new scalarField ( this->size(), fieldToken.number() ) ); } else { // Read as scalarList. is.putBack(fieldToken); scalarList l(is); if (l.size() == vector::nComponents) { vector vs(l[0], l[1], l[2]); vectorFields_.insert ( iter().keyword(), new vectorField(this->size(), vs) ); } else if (l.size() == sphericalTensor::nComponents) { sphericalTensor vs(l[0]); sphericalTensorFields_.insert ( iter().keyword(), new sphericalTensorField(this->size(), vs) ); } else if (l.size() == symmTensor::nComponents) { symmTensor vs(l[0], l[1], l[2], l[3], l[4], l[5]); symmTensorFields_.insert ( iter().keyword(), new symmTensorField(this->size(), vs) ); } else if (l.size() == tensor::nComponents) { tensor vs ( l[0], l[1], l[2], l[3], l[4], l[5], l[6], l[7], l[8] ); tensorFields_.insert ( iter().keyword(), new tensorField(this->size(), vs) ); } else { FatalIOErrorInFunction(dict) << "\n unrecognised native type " << l << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << exit(FatalIOError); } } } } } } } template<class Type> CML::genericFvPatchField<Type>::genericFvPatchField ( const genericFvPatchField<Type>& ptf, const fvPatch& p, const DimensionedField<Type, volMesh>& iF, const fvPatchFieldMapper& mapper ) : calculatedFvPatchField<Type>(ptf, p, iF, mapper), actualTypeName_(ptf.actualTypeName_), dict_(ptf.dict_) { forAllConstIter ( HashPtrTable<scalarField>, ptf.scalarFields_, iter ) { scalarFields_.insert ( iter.key(), new scalarField(*iter(), mapper) ); } forAllConstIter ( HashPtrTable<vectorField>, ptf.vectorFields_, iter ) { vectorFields_.insert ( iter.key(), new vectorField(*iter(), mapper) ); } forAllConstIter ( HashPtrTable<sphericalTensorField>, ptf.sphericalTensorFields_, iter ) { sphericalTensorFields_.insert ( iter.key(), new sphericalTensorField(*iter(), mapper) ); } forAllConstIter ( HashPtrTable<symmTensorField>, ptf.symmTensorFields_, iter ) { symmTensorFields_.insert ( iter.key(), new symmTensorField(*iter(), mapper) ); } forAllConstIter ( HashPtrTable<tensorField>, ptf.tensorFields_, iter ) { tensorFields_.insert ( iter.key(), new tensorField(*iter(), mapper) ); } } template<class Type> CML::genericFvPatchField<Type>::genericFvPatchField ( const genericFvPatchField<Type>& ptf ) : calculatedFvPatchField<Type>(ptf), actualTypeName_(ptf.actualTypeName_), dict_(ptf.dict_), scalarFields_(ptf.scalarFields_), vectorFields_(ptf.vectorFields_), sphericalTensorFields_(ptf.sphericalTensorFields_), symmTensorFields_(ptf.symmTensorFields_), tensorFields_(ptf.tensorFields_) {} template<class Type> CML::genericFvPatchField<Type>::genericFvPatchField ( const genericFvPatchField<Type>& ptf, const DimensionedField<Type, volMesh>& iF ) : calculatedFvPatchField<Type>(ptf, iF), actualTypeName_(ptf.actualTypeName_), dict_(ptf.dict_), scalarFields_(ptf.scalarFields_), vectorFields_(ptf.vectorFields_), sphericalTensorFields_(ptf.sphericalTensorFields_), symmTensorFields_(ptf.symmTensorFields_), tensorFields_(ptf.tensorFields_) {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Type> void CML::genericFvPatchField<Type>::autoMap ( const fvPatchFieldMapper& m ) { calculatedFvPatchField<Type>::autoMap(m); forAllIter ( HashPtrTable<scalarField>, scalarFields_, iter ) { iter()->autoMap(m); } forAllIter ( HashPtrTable<vectorField>, vectorFields_, iter ) { iter()->autoMap(m); } forAllIter ( HashPtrTable<sphericalTensorField>, sphericalTensorFields_, iter ) { iter()->autoMap(m); } forAllIter ( HashPtrTable<symmTensorField>, symmTensorFields_, iter ) { iter()->autoMap(m); } forAllIter ( HashPtrTable<tensorField>, tensorFields_, iter ) { iter()->autoMap(m); } } template<class Type> void CML::genericFvPatchField<Type>::rmap ( const fvPatchField<Type>& ptf, const labelList& addr ) { calculatedFvPatchField<Type>::rmap(ptf, addr); const genericFvPatchField<Type>& dptf = refCast<const genericFvPatchField<Type> >(ptf); forAllIter ( HashPtrTable<scalarField>, scalarFields_, iter ) { HashPtrTable<scalarField>::const_iterator dptfIter = dptf.scalarFields_.find(iter.key()); if (dptfIter != dptf.scalarFields_.end()) { iter()->rmap(*dptfIter(), addr); } } forAllIter ( HashPtrTable<vectorField>, vectorFields_, iter ) { HashPtrTable<vectorField>::const_iterator dptfIter = dptf.vectorFields_.find(iter.key()); if (dptfIter != dptf.vectorFields_.end()) { iter()->rmap(*dptfIter(), addr); } } forAllIter ( HashPtrTable<sphericalTensorField>, sphericalTensorFields_, iter ) { HashPtrTable<sphericalTensorField>::const_iterator dptfIter = dptf.sphericalTensorFields_.find(iter.key()); if (dptfIter != dptf.sphericalTensorFields_.end()) { iter()->rmap(*dptfIter(), addr); } } forAllIter ( HashPtrTable<symmTensorField>, symmTensorFields_, iter ) { HashPtrTable<symmTensorField>::const_iterator dptfIter = dptf.symmTensorFields_.find(iter.key()); if (dptfIter != dptf.symmTensorFields_.end()) { iter()->rmap(*dptfIter(), addr); } } forAllIter ( HashPtrTable<tensorField>, tensorFields_, iter ) { HashPtrTable<tensorField>::const_iterator dptfIter = dptf.tensorFields_.find(iter.key()); if (dptfIter != dptf.tensorFields_.end()) { iter()->rmap(*dptfIter(), addr); } } } template<class Type> CML::tmp<CML::Field<Type> > CML::genericFvPatchField<Type>::valueInternalCoeffs ( const tmp<scalarField>& ) const { FatalErrorInFunction << "\n " "valueInternalCoeffs cannot be called for a genericFvPatchField" " (actual type " << actualTypeName_ << ")" << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << "\n You are probably trying to solve for a field with a " "generic boundary condition." << exit(FatalError); return *this; } template<class Type> CML::tmp<CML::Field<Type> > CML::genericFvPatchField<Type>::valueBoundaryCoeffs ( const tmp<scalarField>& ) const { FatalErrorInFunction << "\n " "valueBoundaryCoeffs cannot be called for a genericFvPatchField" " (actual type " << actualTypeName_ << ")" << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << "\n You are probably trying to solve for a field with a " "generic boundary condition." << exit(FatalError); return *this; } template<class Type> CML::tmp<CML::Field<Type> > CML::genericFvPatchField<Type>::gradientInternalCoeffs() const { FatalErrorInFunction << "\n " "gradientInternalCoeffs cannot be called for a genericFvPatchField" " (actual type " << actualTypeName_ << ")" << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << "\n You are probably trying to solve for a field with a " "generic boundary condition." << exit(FatalError); return *this; } template<class Type> CML::tmp<CML::Field<Type> > CML::genericFvPatchField<Type>::gradientBoundaryCoeffs() const { FatalErrorInFunction << "\n " "gradientBoundaryCoeffs cannot be called for a genericFvPatchField" " (actual type " << actualTypeName_ << ")" << "\n on patch " << this->patch().name() << " of field " << this->dimensionedInternalField().name() << " in file " << this->dimensionedInternalField().objectPath() << "\n You are probably trying to solve for a field with a " "generic boundary condition." << exit(FatalError); return *this; } template<class Type> void CML::genericFvPatchField<Type>::write(Ostream& os) const { os.writeKeyword("type") << actualTypeName_ << token::END_STATEMENT << nl; forAllConstIter(dictionary, dict_, iter) { if (iter().keyword() != "type" && iter().keyword() != "value") { if ( iter().isStream() && iter().stream().size() && iter().stream()[0].isWord() && iter().stream()[0].wordToken() == "nonuniform" ) { if (scalarFields_.found(iter().keyword())) { scalarFields_.find(iter().keyword())() ->writeEntry(iter().keyword(), os); } else if (vectorFields_.found(iter().keyword())) { vectorFields_.find(iter().keyword())() ->writeEntry(iter().keyword(), os); } else if (sphericalTensorFields_.found(iter().keyword())) { sphericalTensorFields_.find(iter().keyword())() ->writeEntry(iter().keyword(), os); } else if (symmTensorFields_.found(iter().keyword())) { symmTensorFields_.find(iter().keyword())() ->writeEntry(iter().keyword(), os); } else if (tensorFields_.found(iter().keyword())) { tensorFields_.find(iter().keyword())() ->writeEntry(iter().keyword(), os); } } else { iter().write(os); } } } this->writeEntry("value", os); } #endif // ************************************************************************* //
31.501554
80
0.429159
[ "object", "vector" ]
75558795e8c245ce722d8ba34f02d7098d1374bb
16,526
cpp
C++
src/main.cpp
ozzyjrs/linux
980cbb0fb55cb0c5b81a233f837c41aad47721f8
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/main.cpp
ozzyjrs/linux
980cbb0fb55cb0c5b81a233f837c41aad47721f8
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/main.cpp
ozzyjrs/linux
980cbb0fb55cb0c5b81a233f837c41aad47721f8
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include <iostream> #include <dlfcn.h> #include <stdarg.h> #include <cstring> #include <memory> #include <string> #include <vector> #include <sstream> #include <dirent.h> #include <subhook.h> #include "gles_symbols.h" #include "android_symbols.h" #include "egl_symbols.h" #include "fmod_symbols.h" #include "../mcpe/gl.h" #include "../mcpe/AppPlatform.h" #include "../mcpe/MinecraftClient.h" #include "LinuxAppPlatform.h" #include "LinuxStore.h" #include "../mcpe/Mouse.h" #include "../mcpe/Keyboard.h" extern "C" { #include <eglut.h> #include "../hybris/include/hybris/dlfcn.h" #include "../hybris/include/hybris/hook.h" #include "../hybris/src/jb/linker.h" void ANativeWindow_setBuffersGeometry() { } void AAssetManager_open() { } void AAsset_getLength() { } void AAsset_getBuffer() { } void AAsset_close() { } void ALooper_pollAll() { } void ANativeActivity_finish() { } void AInputQueue_getEvent() { } void AKeyEvent_getKeyCode() { } void AInputQueue_preDispatchEvent() { } void AInputQueue_finishEvent() { } void AKeyEvent_getAction() { } void AMotionEvent_getAxisValue() { } void AKeyEvent_getRepeatCount() { } void AKeyEvent_getMetaState() { } void AInputEvent_getDeviceId() { } void AInputEvent_getType() { } void AInputEvent_getSource() { } void AMotionEvent_getAction() { } void AMotionEvent_getPointerId() { } void AMotionEvent_getX() { } void AMotionEvent_getY() { } void AMotionEvent_getPointerCount() { } void AConfiguration_new() { } void AConfiguration_fromAssetManager() { } void AConfiguration_getLanguage() { } void AConfiguration_getCountry() { } void ALooper_prepare() { } void ALooper_addFd() { } void AInputQueue_detachLooper() { } void AConfiguration_delete() { } void AInputQueue_attachLooper() { } void __android_log_print(int prio, const char *tag, const char *fmt, ...) { va_list args; va_start(args, fmt); std::cout << "[" << tag << "] "; vprintf(fmt, args); std::cout << std::endl; va_end(args); } } std::string getCWD() { char _cwd[MAXPATHLEN]; getcwd(_cwd, MAXPATHLEN); return std::string(_cwd) + "/"; } bool loadLibrary(std::string path) { void* handle = hybris_dlopen((getCWD() + "libs/" + path).c_str(), RTLD_LAZY); if (handle == nullptr) { std::cout << "failed to load library " << path << ": " << hybris_dlerror() << "\n"; return false; } return true; } void* loadLibraryOS(std::string path, const char** symbols) { void* handle = dlopen(path.c_str(), RTLD_LAZY); if (handle == nullptr) { std::cout << "failed to load library " << path << ": " << dlerror() << "\n"; return nullptr; } std::cout << "oslib: " << path << ": " << (int) handle << "\n"; int i = 0; while (true) { const char* sym = symbols[i]; if (sym == nullptr) break; void* ptr = dlsym(handle, sym); hybris_hook(sym, ptr); i++; } return handle; } void androidStub() { std::cout << "warn: android call\n"; } void eglStub() { std::cout << "warn: egl call\n"; } void stubSymbols(const char** symbols, void* stubfunc) { int i = 0; while (true) { const char* sym = symbols[i]; if (sym == nullptr) break; hybris_hook(sym, stubfunc); i++; } } std::unique_ptr<LinuxStore> createStoreHookFunc(const std::string& idk, StoreListener& listener) { std::cout << "creating fake store <" << idk << ">\n"; return std::unique_ptr<LinuxStore>(new LinuxStore()); } class HTTPRequest; class LinuxHttpRequestInternal { public: void* vtable; int filler1; HTTPRequest* request; void destroy() { std::cout << "destroying http request\n"; } }; void constructLinuxHttpRequestInternal(LinuxHttpRequestInternal* requestInternal, HTTPRequest* request) { void** vt = (void**) ::operator new(8); vt[0] = (void*) &LinuxHttpRequestInternal::destroy; vt[1] = (void*) &LinuxHttpRequestInternal::destroy; requestInternal->vtable = vt; requestInternal->request = request; } void sendLinuxHttpRequestInternal(LinuxHttpRequestInternal* requestInternal) { std::cout << "send http request\n"; // TODO: Implement it } void abortLinuxHttpRequestInternal(LinuxHttpRequestInternal* requestInternal) { std::cout << "abort http request\n"; // TODO: Implement it } static MinecraftClient* client; bool moveMouseToCenter = false; static void minecraft_idle() { int cx = eglutGetWindowWidth() / 2; int cy = eglutGetWindowHeight() / 2; if (moveMouseToCenter) { eglutWarpMousePointer(cx, cy); moveMouseToCenter = false; } eglutPostRedisplay(); } static void minecraft_draw() { client->update(); } float pixelSize = 2.f; static void minecraft_reshape(int w, int h) { client->setSize(w, h, pixelSize); } static void minecraft_mouse(int x, int y) { if (LinuxAppPlatform::mousePointerHidden) { int cx = eglutGetWindowWidth() / 2; int cy = eglutGetWindowHeight() / 2; if (x != cy || y != cy) { Mouse::feed(0, 0, x, y, x - cx, y - cy); moveMouseToCenter = true; } } else { Mouse::feed(0, 0, x, y, 0, 0); } } static void minecraft_mouse_button(int x, int y, int btn, int action) { int mcBtn = (btn == 1 ? 1 : (btn == 2 ? 3 : (btn == 3 ? 2 : (btn == 5 ? 4 : btn)))); Mouse::feed((char) mcBtn, (char) (action == EGLUT_MOUSE_PRESS ? (btn == 5 ? -120 : (btn == 4 ? 120 : 1)) : 0), x, y, 0, 0); } int getKeyMinecraft(int keyCode) { if (keyCode == 65505) return 16; if (keyCode >= 97 && keyCode <= 122) return (keyCode + 65 - 97); if (keyCode >= 65470 && keyCode <= 65481) return (keyCode + 112 - 65470); return keyCode; } static void minecraft_keyboard_special(int key, int action) { int mKey = getKeyMinecraft(key); if (action == EGLUT_KEY_PRESS) { Keyboard::inputs->push_back({1, mKey}); Keyboard::states[mKey] = 1; if (key >= 32 && key <= 127) { std::stringstream ss; ss << (char) key; Keyboard::Keyboard_feedText(ss.str(), false); } else if (key == 65288) { Keyboard::Keyboard_feedText("\x08", false); } } else { Keyboard::inputs->push_back({0, mKey}); Keyboard::states[mKey] = 0; } } void patchCallInstruction(void* patchOff, void* func, bool jump) { unsigned char* data = (unsigned char*) patchOff; printf("original: %i %i %i %i %i\n", data[0], data[1], data[2], data[3], data[4]); data[0] = (unsigned char) (jump ? 0xe9 : 0xe8); int ptr = ((int) func) - (int) patchOff - 5; memcpy(&data[1], &ptr, sizeof(int)); printf("post patch: %i %i %i %i %i\n", data[0], data[1], data[2], data[3], data[4]); } void unhookFunction(void* hook) { SubHook* shook = (SubHook*) hook; shook->Remove(); delete shook; } void* hookFunction(void* symbol, void* hook, void** original) { SubHook* ret = new SubHook(); ret->Install(symbol, hook); *original = ret->GetTrampoline(); return ret; } void* loadMod(std::string path) { void* handle = hybris_dlopen((getCWD() + "mods/" + path).c_str(), RTLD_LAZY); if (handle == nullptr) { std::cout << "failed to load mod: " << path << "\n"; return nullptr; } void (*initFunc)(); initFunc = (void (*)()) hybris_dlsym(handle, "mod_init"); if (((void*) initFunc) == nullptr) { std::cout << "warn: mod " << path << " doesn't have a init function\n"; return handle; } initFunc(); return handle; } std::string getOSLibraryPath(std::string libName) { std::string p = std::string("/usr/lib/i386-linux-gnu/") + libName; if (access(p.c_str(), F_OK) != -1) { return p; } p = std::string("/usr/lib32/") + libName; if (access(p.c_str(), F_OK) != -1) { return p; } p = std::string("/lib32/") + libName; if (access(p.c_str(), F_OK) != -1) { return p; } std::cout << "could not find os library: " << libName << "\n"; abort(); } using namespace std; int main(int argc, char *argv[]) { int windowWidth = 720; int windowHeight = 480; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--scale") == 0) { i++; pixelSize = std::stof(argv[i]); } else if (strcmp(argv[i], "-sw") == 0 || strcmp(argv[i], "--window") == 0) { i++; windowWidth = std::stoi(argv[i]); } else if (strcmp(argv[i], "-sh") == 0 || strcmp(argv[i], "--height") == 0) { i++; windowHeight = std::stoi(argv[i]); } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { std::cout << "Help\n"; std::cout << "--help Shows this help information\n"; std::cout << "--scale <scale> Sets the pixel scale\n"; std::cout << "--width <width> Sets the window width\n"; std::cout << "--height <height> Sets the window height\n\n"; std::cout << "EGL Options\n"; std::cout << "-display <display> Sets the display\n"; std::cout << "-info Shows info about the display\n\n"; std::cout << "MCPE arguments:\n"; std::cout << "edu <true|false>\n"; std::cout << "mcworld <world>\n"; return 0; } } std::cout << "loading MCPE\n"; void* glesLib = loadLibraryOS(getOSLibraryPath("libGLESv2.so"), gles_symbols); void* fmodLib = loadLibraryOS((getCWD() + "libs/native/libfmod.so.7.7").c_str(), fmod_symbols); if (glesLib == nullptr || fmodLib == nullptr) return -1; stubSymbols(android_symbols, (void*) androidStub); stubSymbols(egl_symbols, (void*) eglStub); hybris_hook("mcpelauncher_hook", (void*) hookFunction); hybris_hook("mcpelauncher_unhook", (void*) unhookFunction); hybris_hook("__android_log_print", (void*) __android_log_print); if (!loadLibrary("libc.so") || !loadLibrary("libstdc++.so") || !loadLibrary("libm.so") || !loadLibrary("libz.so")) return -1; // load stub libraries if (!loadLibrary("libandroid.so") || !loadLibrary("liblog.so") || !loadLibrary("libEGL.so") || !loadLibrary("libGLESv2.so") || !loadLibrary("libOpenSLES.so") || !loadLibrary("libfmod.so")) return -1; // load libgnustl_shared if (!loadLibrary("libgnustl_shared.so")) return -1; if (!loadLibrary("libmcpelauncher_mod.so")) return -1; void* handle = hybris_dlopen((getCWD() + "libs/libminecraftpe.so").c_str(), RTLD_LAZY); if (handle == nullptr) { std::cout << "failed to load MCPE: " << hybris_dlerror() << "\n"; return -1; } unsigned int libBase = ((soinfo*) handle)->base; std::cout << "loaded MCPE (at " << libBase << ")\n"; DIR *dir; struct dirent *ent; std::vector<void*> mods; if ((dir = opendir ("mods/")) != NULL) { std::cout << "loading mods\n"; while ((ent = readdir (dir)) != NULL) { if (ent->d_name[0] == '.') continue; std::string fileName (ent->d_name); int len = fileName.length(); if (len < 4 || fileName[len - 3] != '.' || fileName[len - 2] != 's' || fileName[len - 1] != 'o') continue; std::cout << "loading: " << fileName << "\n"; void* mod = loadMod(fileName); if (mod != nullptr) mods.push_back(mod); } closedir(dir); std::cout << "loaded " << mods.size() << " mods\n"; } std::cout << "apply patches\n"; /* unsigned int patchOff = (unsigned int) hybris_dlsym(handle, "_ZN12StoreFactory11createStoreER13StoreListener") + 66; patchCallInstruction((void*) patchOff, (void*) &createStoreHookFunc, false); patchOff = (unsigned int) hybris_dlsym(handle, "_ZN11HTTPRequestC2ERKSs") + 154; patchCallInstruction((void*) patchOff, (void*) &constructLinuxHttpRequestInternal, false); patchOff = (unsigned int) hybris_dlsym(handle, "_ZN11HTTPRequest4sendEv") + 26; patchCallInstruction((void*) patchOff, (void*) &sendLinuxHttpRequestInternal, false); patchOff = (unsigned int) hybris_dlsym(handle, "_ZN11HTTPRequest5abortEv") + 26; patchCallInstruction((void*) patchOff, (void*) &abortLinuxHttpRequestInternal, false); */ unsigned int patchOff = (unsigned int) hybris_dlsym(handle, "_ZN12AndroidStore21createGooglePlayStoreERKSsR13StoreListener"); patchCallInstruction((void*) patchOff, (void*) &createStoreHookFunc, true); patchOff = (unsigned int) hybris_dlsym(handle, "_ZN26HTTPRequestInternalAndroidC2ER11HTTPRequest"); patchCallInstruction((void*) patchOff, (void*) &constructLinuxHttpRequestInternal, true); patchOff = (unsigned int) hybris_dlsym(handle, "_ZN26HTTPRequestInternalAndroid4sendEv"); patchCallInstruction((void*) patchOff, (void*) &sendLinuxHttpRequestInternal, true); patchOff = (unsigned int) hybris_dlsym(handle, "_ZN26HTTPRequestInternalAndroid5abortEv"); patchCallInstruction((void*) patchOff, (void*) &abortLinuxHttpRequestInternal, true); std::cout << "patches applied!\n"; // load symbols for gl gl::getOpenGLVendor = (std::string (*)()) hybris_dlsym(handle, "_ZN2gl15getOpenGLVendorEv"); gl::getOpenGLRenderer = (std::string (*)()) hybris_dlsym(handle, "_ZN2gl17getOpenGLRendererEv"); gl::getOpenGLVersion = (std::string (*)()) hybris_dlsym(handle, "_ZN2gl16getOpenGLVersionEv"); gl::getOpenGLExtensions = (std::string (*)()) hybris_dlsym(handle, "_ZN2gl19getOpenGLExtensionsEv"); // init linux app platform AppPlatform::myVtable = (void**) hybris_dlsym(handle, "_ZTV11AppPlatform"); AppPlatform::_singleton = (AppPlatform**) hybris_dlsym(handle, "_ZN11AppPlatform10mSingletonE"); AppPlatform::AppPlatform_construct = (void (*)(AppPlatform*)) hybris_dlsym(handle, "_ZN11AppPlatformC2Ev"); AppPlatform::AppPlatform__fireAppFocusGained = (void (*)(AppPlatform*)) hybris_dlsym(handle, "_ZN11AppPlatform19_fireAppFocusGainedEv"); std::cout << "init app platform vtable\n"; LinuxAppPlatform::initVtable(AppPlatform::myVtable, 77); std::cout << "init app platform\n"; LinuxAppPlatform* platform = new LinuxAppPlatform(); std::cout << "app platform initialized\n"; Mouse::feed = (void (*)(char, char, short, short, short, short)) hybris_dlsym(handle, "_ZN5Mouse4feedEccssss"); Keyboard::inputs = (std::vector<KeyboardAction>*) hybris_dlsym(handle, "_ZN8Keyboard7_inputsE"); Keyboard::states = (int*) hybris_dlsym(handle, "_ZN8Keyboard7_statesE"); Keyboard::Keyboard_feedText = (void (*)(const std::string&, bool)) hybris_dlsym(handle, "_ZN8Keyboard8feedTextERKSsb"); std::cout << "init window\n"; eglutInitWindowSize(windowWidth, windowHeight); eglutInitAPIMask(EGLUT_OPENGL_ES2_BIT); eglutInit(argc, argv); eglutCreateWindow("MCPE"); // init MinecraftClient App::App_init = (void (*)(App*, AppContext&)) hybris_dlsym(handle, "_ZN3App4initER10AppContext"); MinecraftClient::MinecraftClient_construct = (void (*)(MinecraftClient*, int, char**)) hybris_dlsym(handle, "_ZN15MinecraftClientC2EiPPc"); MinecraftClient::MinecraftClient_update = (void (*)(MinecraftClient*)) hybris_dlsym(handle, "_ZN15MinecraftClient6updateEv"); MinecraftClient::MinecraftClient_setSize = (void (*)(MinecraftClient*, int, int, float)) hybris_dlsym(handle, "_ZN15MinecraftClient7setSizeEiif"); AppContext ctx; ctx.platform = platform; ctx.doRender = true; std::cout << "create minecraft client\n"; client = new MinecraftClient(argc, argv); std::cout << "init minecraft client\n"; client->init(ctx); std::cout << "initialized lib\n"; for (void* mod : mods) { void (*initFunc)(MinecraftClient*) = (void (*)(MinecraftClient*)) hybris_dlsym(mod, "mod_set_minecraft"); if ((void*) initFunc != nullptr) initFunc(client); } eglutIdleFunc(minecraft_idle); eglutReshapeFunc(minecraft_reshape); eglutDisplayFunc(minecraft_draw); eglutMouseFunc(minecraft_mouse); eglutMouseButtonFunc(minecraft_mouse_button); eglutKeyboardFunc(NULL); eglutSpecialFunc(minecraft_keyboard_special); // init //(*AppPlatform::_singleton)->_fireAppFocusGained(); client->setSize(windowWidth, windowHeight, pixelSize); eglutMainLoop(); return 0; }
35.848156
192
0.626225
[ "vector" ]
755ff6ab6dc4e24b58a7646afbcb6017cd3ebb5d
6,540
cpp
C++
Libraries/Physics/PositionCorrectionFragments.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Physics/PositionCorrectionFragments.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Physics/PositionCorrectionFragments.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Zero { namespace Physics { bool ShouldSolvePosition(Contact* contact) { return true; } bool ShouldSolvePosition(Joint* joint) { PhysicsSolverConfig* config = joint->mSolver->mSolverConfig; JointConfigOverride* configOverride = joint->mNode->mConfigOverride; uint jointType = joint->GetJointType(); // Normally we check the config values for joints to determine if it // should apply post stabilization or baumgarte. Custom joints determine this // via each constraint's SolvePosition bool which is set from script so just // check how many position constraints there are. if (jointType == CustomJoint::StaticGetJointType()) return joint->PositionMoleculeCount() != 0; if (configOverride != nullptr) { if (configOverride->mPositionCorrectionType == ConstraintPositionCorrection::Baumgarte) return false; else if (configOverride->mPositionCorrectionType == ConstraintPositionCorrection::PostStabilization) return true; } if (config->mJointBlocks[jointType].mPositionCorrectionType == ConstraintPositionCorrection::Baumgarte) return false; if (config->mJointBlocks[jointType].mPositionCorrectionType == ConstraintPositionCorrection::PostStabilization) return true; return config->mPositionCorrectionType == PhysicsSolverPositionCorrection::PostStabilization; } void CollectContactsToSolve(IConstraintSolver::ContactList& inputList, IConstraintSolver::ContactList& contactsToSolve, PhysicsSolverConfig* config) { // if the global + contact config say to use position correction then // solve all contacts with position correction PhysicsSolverPositionCorrection::Enum globalCorrection = config->mPositionCorrectionType; ConstraintPositionCorrection::Enum contactCorrection = config->mContactBlock.GetPositionCorrectionType(); if ((globalCorrection == PhysicsSolverPositionCorrection::PostStabilization && contactCorrection != ConstraintPositionCorrection::Baumgarte) || (contactCorrection == ConstraintPositionCorrection::PostStabilization)) contactsToSolve.Swap(inputList); } void ContactUpdate(Contact* contact, Collider* c0, Collider* c1) { ProfileScopeTree("Contacts", "SolvePositions", Color::BlueViolet); Manifold* manifold = contact->mManifold; for (uint i = 0; i < manifold->ContactCount; ++i) { ManifoldPoint& point = manifold->Contacts[i]; point.WorldPoints[0] = JointHelpers::BodyRToWorldPoint(c0, point.BodyPoints[0]); point.WorldPoints[1] = JointHelpers::BodyRToWorldPoint(c1, point.BodyPoints[1]); point.Penetration = Math::Dot(point.WorldPoints[0] - point.WorldPoints[1], point.Normal); } } void UpdateHierarchyTransform(RigidBody* body) { { PhysicsNode* node = body->mPhysicsNode; // figure out if we need to include our parent's transform WorldTransformation* parentTransformation = nullptr; if (node->mParent) parentTransformation = node->mParent->GetTransform(); WorldTransformation* nodeTransform = node->GetTransform(); nodeTransform->ComputeTransformation(parentTransformation, node); body->mRotationQuat = Math::ToQuaternion(nodeTransform->GetWorldRotation()); } RigidBody::CompositeColliderRange childColliders = body->mColliders.All(); for (; !childColliders.Empty(); childColliders.PopFront()) { Collider& collider = childColliders.Front(); PhysicsNode* node = collider.mPhysicsNode; // figure out if we need to include our parent's transform WorldTransformation* parentTransformation = nullptr; if (node->mParent) parentTransformation = node->mParent->GetTransform(); WorldTransformation* transform = node->GetTransform(); transform->ComputeTransformation(parentTransformation, node); collider.CacheWorldValues(); } RigidBody::BodyRange childBodies = body->mChildBodies.All(); for (; !childBodies.Empty(); childBodies.PopFront()) { RigidBody& childBody = childBodies.Front(); UpdateHierarchyTransform(&childBody); childBody.mRotationQuat = Math::ToQuaternion(childBody.mPhysicsNode->GetTransform()->GetWorldRotation()); } } void ApplyPositionCorrection(RigidBody* body, Vec3Param linearOffset, Vec3Param angularOffset) { // We need to use the kinematic body for velocity correction //(since we need its velocity), but we don't want to updated it during // position correction (we don't want to update based upon its center of // mass). This is also convenient because there's no reason to position // correct kinematics anyways. if (body != nullptr && body->GetKinematic() == false) { // translation is very simple to update, just offset by the linear offset body->UpdateCenterMass(linearOffset); // orientation is a bit trickier, we treat the angular offset like an // angular velocity that we're applying with a timestep of 1 and then we // integrate that angular velocity to get a new orientation Quat rot = body->GetWorldRotationQuat(); Quat w = Quat(angularOffset.x, angularOffset.y, angularOffset.z, 0); rot = (w * rot) * real(0.5); body->UpdateOrientation(rot); // Below is no longer needed because the transforms need to be updated // before solving (since they're out of date on the first iteration due to // position correction). No extra work needs to be done afterwards either // because publish will grab the updated values on the body and the // individual children values aren't important. // Unfortunately, position correction needs up-to-date positions which // is a bit trickier with hierarchies. Each node in the hierarchy stores a // cached body-to-world transform that needs to be updated after each // position correction. For now just directly update the hierarchy and maybe // later worry about a more efficient way (post transforms?) // ProfileScopeTree("Hierarchy", "SolvePositions", Color::PeachPuff); // UpdateHierarchyTransform(body); } } void ApplyPositionCorrection(RigidBody* b0, RigidBody* b1, Vec3Param linearOffset0, Vec3Param angularOffset0, Vec3Param linearOffset1, Vec3Param angularOffset1) { ApplyPositionCorrection(b0, linearOffset0, angularOffset0); ApplyPositionCorrection(b1, linearOffset1, angularOffset1); } } // namespace Physics } // namespace Zero
40.122699
113
0.729358
[ "transform" ]
756571f8e216f9b7b1609c627fe115053587ca7c
11,880
cpp
C++
src/Grid.cpp
bilalmajeed/YA2048
44209be90e59e6e21d98472c6610c9d55b11c15a
[ "MIT" ]
null
null
null
src/Grid.cpp
bilalmajeed/YA2048
44209be90e59e6e21d98472c6610c9d55b11c15a
[ "MIT" ]
null
null
null
src/Grid.cpp
bilalmajeed/YA2048
44209be90e59e6e21d98472c6610c9d55b11c15a
[ "MIT" ]
null
null
null
#include "Grid.hpp" #include "Util.hpp" #include <cmath> Grid::Grid(const sf::Vector2f& position, const sf::Vector2f& size) : NUM_CELLS(4) , CELL_WIDTH(size.x / NUM_CELLS) , CELL_HEIGHT(size.y / NUM_CELLS) , CELL_PADDING(5.f) , m_Size(size) , m_Background({ size.x + CELL_PADDING * NUM_CELLS, size.y + CELL_PADDING * NUM_CELLS }) , m_CellShapes(NUM_CELLS, std::vector<sf::RectangleShape>(NUM_CELLS)) , m_CellTexts(NUM_CELLS, std::vector<sf::Text>(NUM_CELLS)) , m_Cells(NUM_CELLS, std::vector<int>(NUM_CELLS, 0)) , m_GameOver(false) , m_Score(0) , m_IsCombining(NUM_CELLS, std::vector<bool>(NUM_CELLS, false)) { setPosition(position.x - CELL_PADDING * NUM_CELLS / 2, position.y); m_Font.loadFromFile("res/fonts/Ubuntu-M.ttf"); m_Background.setFillColor(sf::Color(32, 32, 32)); initCellColors(); initCellShapes(); createLines(); createStartingCells(); } void Grid::moveUp() { int numMoves = 0; for (int x = 0; x < NUM_CELLS; ++x) { for (int y = 1; y < NUM_CELLS; ++y) { if (isCellEmpty(x, y)) continue; int highestY = getHighestCellFrom(x, y); if (highestY != y) { moveCell(x, y, x, highestY); createAnimation({ x, y }, { x, highestY }); ++numMoves; } if ((highestY > 0) && cellsEqual(x, highestY, x, highestY - 1)) combineCells(x, highestY, x, highestY - 1); } } completeMove(numMoves); } void Grid::moveDown() { int numMoves = 0; for (int x = 0; x < NUM_CELLS; ++x) { for (int y = NUM_CELLS - 2; y >= 0; --y) { if (isCellEmpty(x, y)) continue; int lowestY = getLowestCellFrom(x, y); if (lowestY != y) { moveCell(x, y, x, lowestY); createAnimation({ x, y }, { x, lowestY }); ++numMoves; } if ((lowestY < NUM_CELLS - 1) && cellsEqual(x, lowestY, x, lowestY + 1)) combineCells(x, lowestY, x, lowestY + 1); } } completeMove(numMoves); } void Grid::moveLeft() { int numMoves = 0; for (int x = 1; x < NUM_CELLS; ++x) { for (int y = 0; y < NUM_CELLS; ++y) { if (isCellEmpty(x, y)) continue; int leftmostX = getLeftmostCellFrom(x, y); if (leftmostX != x) { moveCell(x, y, leftmostX, y); createAnimation({ x, y }, { leftmostX, y }); ++numMoves; } if ((leftmostX > 0) && cellsEqual(leftmostX, y, leftmostX - 1, y)) combineCells(leftmostX, y, leftmostX - 1, y); } } completeMove(numMoves); } void Grid::moveRight() { int numMoves = 0; for (int x = NUM_CELLS - 2; x >= 0; --x) { for (int y = 0; y < NUM_CELLS; ++y) { if (isCellEmpty(x, y)) continue; int rightmostX = getRightmostCellFrom(x, y); if (rightmostX != x) { moveCell(x, y, rightmostX, y); createAnimation({ x, y }, { rightmostX, y }); ++numMoves; } if ((rightmostX < NUM_CELLS - 1) && cellsEqual(rightmostX, y, rightmostX + 1, y)) combineCells(rightmostX, y, rightmostX + 1, y); } } completeMove(numMoves); } void Grid::completeMove(int numMoves) { if ((numMoves == 0) && isGridFull()) { m_GameOver = true; //dont need if statement cuz isGridFull is always true thats what the //first if statement is for } else if (numMoves != 0) { //does not spawn more squares if no boxes are able to move createNewCell(); } } void Grid::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); drawBackground(target, states); drawAnimShapes(target, states); drawLines(target, states); drawCells(target, states); drawCellsText(target, states); } void Grid::drawBackground(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(m_Background, states); } void Grid::drawLines(sf::RenderTarget& target, sf::RenderStates states) const { for (auto& line : m_Lines) target.draw(line, states); } void Grid::drawCells(sf::RenderTarget& target, sf::RenderStates states) const { updateCombineAnimation(); for (int x = 0; x < NUM_CELLS; ++x) { for (int y = 0; y < NUM_CELLS; ++y) { m_CellShapes[x][y].setFillColor(m_CellColors[m_Cells[x][y]]); target.draw(m_CellShapes[x][y], states); } } } void Grid::drawCellsText(sf::RenderTarget& target, sf::RenderStates states) const { for (int x = 0; x < NUM_CELLS; ++x) { for (int y = 0; y < NUM_CELLS; ++y) { m_CellTexts[x][y].setString((m_Cells[x][y] != 0 ? std::to_string(m_Cells[x][y]) : "")); auto tx = ((CELL_WIDTH + CELL_PADDING) * x) + (CELL_WIDTH / 2.f); auto ty = ((CELL_HEIGHT + CELL_PADDING) * y) + (CELL_HEIGHT / 2.f); auto localBounds = m_CellTexts[x][y].getLocalBounds(); m_CellTexts[x][y].setOrigin(localBounds.left + localBounds.width / 2.f, localBounds.top + localBounds.height / 2.f); m_CellTexts[x][y].setPosition(tx, ty); target.draw(m_CellTexts[x][y], states); } } } void Grid::drawAnimShapes(sf::RenderTarget& target, sf::RenderStates states) const { for (auto& pair : m_AnimShapes) { auto displacement = pair.first.end - pair.first.start; auto lengthDisplacement = std::sqrt(std::pow(displacement.x, 2) + std::pow(displacement.y, 2)); auto normalized = sf::Vector2f(displacement.x / lengthDisplacement, displacement.y / lengthDisplacement); auto& shape = pair.second; shape.move(normalized * 20.f); auto shapePos = shape.getPosition(); int shapeTileX = std::round(shapePos.x / (CELL_WIDTH + CELL_PADDING)); int shapeTileY = std::round(shapePos.y / (CELL_HEIGHT + CELL_PADDING)); int tileX = std::round(pair.first.end.x / (CELL_WIDTH + CELL_PADDING)); int tileY = std::round(pair.first.end.y / (CELL_HEIGHT + CELL_PADDING)); auto alphaIncrement = 255 / (lengthDisplacement / (normalized.x == 0.f ? normalized.y * 20.f : normalized.x * 20.f)); auto newColor = shape.getFillColor(); if (newColor.a < 255) newColor.a += alphaIncrement; shape.setFillColor(newColor); if ((tileX == shapeTileX) && (tileY == shapeTileY)) { m_CellShapes[tileX][tileY].setSize({ CELL_WIDTH, CELL_HEIGHT }); m_CellTexts[tileX][tileY].setCharacterSize(30); // TODO: Remove shape, not just hide. shape.setSize({ 0.f, 0.f }); } target.draw(shape, states); } } void Grid::createAnimation(const sf::Vector2f& start, const sf::Vector2f& end) { auto startPos = tileToWorld({ start.x, start.y }); auto endPos = tileToWorld({ end.x, end.y }); AnimData animData(startPos, endPos); sf::RectangleShape shape; shape.setSize({ CELL_WIDTH, CELL_HEIGHT }); auto color = m_CellColors[m_Cells[end.x][end.y]]; color.a = 0; shape.setFillColor(color); shape.setPosition(startPos); m_CellShapes[end.x][end.y].setSize({ 0.f, 0.f }); m_CellTexts[end.x][end.y].setCharacterSize(0); m_AnimShapes.push_back(std::make_pair(animData, shape)); } void Grid::updateCombineAnimation() const { for (int x = 0; x < NUM_CELLS; ++x) { for (int y = 0; y < NUM_CELLS; ++y) { if (m_IsCombining[x][y]) { auto shapeSize = m_CellShapes[x][y].getSize(); if (shapeSize.x < CELL_WIDTH && shapeSize.y < CELL_HEIGHT) { // TODO: Replace magic number with constant! shapeSize.x += CELL_WIDTH / 10.f; shapeSize.y += CELL_HEIGHT / 10.f; } else { shapeSize = { CELL_WIDTH, CELL_HEIGHT }; m_CellTexts[x][y].setString(std::to_string(m_Cells[x][y])); } m_CellShapes[x][y].setSize(shapeSize); } } } } void Grid::reset(std::string type) { m_GameOver = false; if (type == "again") { m_Score = 0; m_CellShapes = std::vector<std::vector<sf::RectangleShape>>(NUM_CELLS, std::vector<sf::RectangleShape>(NUM_CELLS)); m_CellTexts = std::vector<std::vector<sf::Text>>(NUM_CELLS, std::vector<sf::Text>(NUM_CELLS)); m_Cells = std::vector<std::vector<int>>(NUM_CELLS, std::vector<int>(NUM_CELLS, 0)); createStartingCells(); initCellShapes(); } } int Grid::getRightmostCellFrom(int x, int y) const { int rightmostX = x; for (int i = x; i < NUM_CELLS; ++i) { if (isCellEmpty(i, y) && i > rightmostX) rightmostX = i; } return rightmostX; } int Grid::getLeftmostCellFrom(int x, int y) const { int leftmostX = x; for (int i = x; i >= 0; --i) { if (isCellEmpty(i, y) && i < leftmostX) leftmostX = i; } return leftmostX; } int Grid::getHighestCellFrom(int x, int y) const { int highestY = y; for (int i = y; i >= 0; --i) { if (isCellEmpty(x, i) && i < highestY) highestY = i; } return highestY; } int Grid::getLowestCellFrom(int x, int y) const { int lowestY = y; for (int i = y; i < NUM_CELLS; ++i) { if (isCellEmpty(x, i) && i > lowestY) lowestY = i; } return lowestY; } void Grid::moveCell(int x, int y, int x1, int y1) { m_Cells[x1][y1] = m_Cells[x][y]; m_Cells[x][y] = 0; } void Grid::combineCells(int x, int y, int x1, int y1) { m_Cells[x][y] = 0; m_Cells[x1][y1] *= 2; m_Score += m_Cells[x1][y1]; m_CellShapes[x1][y1].setSize({ 0.f, 0.f }); m_CellTexts[x1][y1].setString(""); m_IsCombining[x1][y1] = true; } sf::Vector2f Grid::tileToWorld(const sf::Vector2f& pos) const { auto x = pos.x * (CELL_WIDTH + CELL_PADDING); auto y = pos.y * (CELL_HEIGHT + CELL_PADDING); return { x, y }; } sf::Vector2f Grid::worldToTile(const sf::Vector2f& pos) const { auto x = pos.x / (CELL_WIDTH + CELL_PADDING); auto y = pos.y / (CELL_HEIGHT + CELL_PADDING); return { x, y }; } int Grid::getScore() const { return m_Score; } bool Grid::isGameOver() const { return m_GameOver; } void Grid::createNewCell() { auto availableCells = getFreeCells(); auto randIndex = Random::genInt(0, availableCells.size() - 1); auto cellPos = availableCells[randIndex]; m_Cells[cellPos.x][cellPos.y] = 2; } bool Grid::cellsEqual(int x, int y, int x1, int y1) const { return m_Cells[x][y] == m_Cells[x1][y1]; } bool Grid::isCellEmpty(int x, int y) const { return m_Cells[x][y] == 0; } bool Grid::isGridFull() const { return getFreeCells().size() == 0; } std::vector<sf::Vector2f> Grid::getFreeCells() const { std::vector<sf::Vector2f> freeCells; for (int x = 0; x < NUM_CELLS; ++x) { for (int y = 0; y < NUM_CELLS; ++y) { if (isCellEmpty(x, y)) freeCells.push_back({ static_cast<float>(x), static_cast<float>(y) }); } } return freeCells; } void Grid::createLines() { for (int i = 0; i < NUM_CELLS + 1; ++i) { createVerticalLine(i); createHorizontalLine(i); } } void Grid::createVerticalLine(int column) { sf::RectangleShape line; line.setFillColor(sf::Color(128, 128, 128)); line.setPosition(-CELL_PADDING + (CELL_WIDTH + CELL_PADDING) * column, -CELL_PADDING); line.setSize({ CELL_PADDING, m_Size.y + CELL_PADDING * NUM_CELLS }); m_Lines.push_back(line); } void Grid::createHorizontalLine(int row) { sf::RectangleShape line; line.setFillColor(sf::Color(128, 128, 128)); line.setPosition(0.f, -CELL_PADDING + (CELL_HEIGHT + CELL_PADDING) * row); line.setSize({ m_Size.x + CELL_PADDING * NUM_CELLS, CELL_PADDING }); m_Lines.push_back(line); } void Grid::createStartingCells() { for (int i = 0; i < 2; ++i) createNewCell(); } void Grid::initCellShapes() { for (int x = 0; x < NUM_CELLS; ++x) { for (int y = 0; y < NUM_CELLS; ++y) { m_CellShapes[x][y].setPosition((CELL_WIDTH + CELL_PADDING) * x, (CELL_HEIGHT + CELL_PADDING) * y); m_CellShapes[x][y].setSize({ CELL_WIDTH, CELL_HEIGHT }); m_CellShapes[x][y].setFillColor(m_CellColors[m_Cells[x][y]]); m_CellTexts[x][y].setFont(m_Font); m_CellTexts[x][y].setColor(sf::Color::Black); } } } void Grid::initCellColors() { m_CellColors[0] = sf::Color(0, 0, 0, 0); m_CellColors[2] = sf::Color(85, 98, 112); m_CellColors[4] = sf::Color(78, 205, 196); m_CellColors[8] = sf::Color(199, 244, 100); m_CellColors[16] = sf::Color(255, 107, 107); m_CellColors[32] = sf::Color(196, 77, 88); m_CellColors[64] = sf::Color(73, 10, 61); m_CellColors[128] = sf::Color(189, 21, 80); m_CellColors[256] = sf::Color(233, 127, 2); m_CellColors[512] = sf::Color(248, 202, 0); m_CellColors[1024] = sf::Color(138, 155, 15); m_CellColors[2048] = sf::Color(255, 229, 69); }
23.157895
119
0.64798
[ "shape", "vector", "transform" ]
75755f50baa20a74a6ef9fbcae9d07fc7bd8971d
2,760
cc
C++
src/physics/HeightmapShape.cc
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2016-01-17T20:41:39.000Z
2018-05-01T12:02:58.000Z
src/physics/HeightmapShape.cc
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/physics/HeightmapShape.cc
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2015-09-29T02:30:16.000Z
2022-03-30T12:11:22.000Z
/* * Copyright 2011 Nate Koenig & Andrew Howard * * 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. * */ /* Desc: Heightmap shape * Author: Nate Keonig, Andrew Howard * Date: 8 May 2003 */ #include <string.h> #include <math.h> #include "common/Image.hh" #include "common/Exception.hh" #include "physics/HeightmapShape.hh" using namespace gazebo; using namespace physics; ////////////////////////////////////////////////// HeightmapShape::HeightmapShape(CollisionPtr _parent) : Shape(_parent) { this->AddType(Base::HEIGHTMAP_SHAPE); } ////////////////////////////////////////////////// HeightmapShape::~HeightmapShape() { } ////////////////////////////////////////////////// void HeightmapShape::Update() { } ////////////////////////////////////////////////// void HeightmapShape::Load(sdf::ElementPtr _sdf) { Base::Load(_sdf); // Use the image to get the size of the heightmap this->img.Load(this->sdf->GetValueString("filename")); if (this->img.GetWidth() != this->img.GetHeight() || !math::isPowerOfTwo(this->img.GetWidth()-1)) { gzthrow("Heightmap image size must be square, with a size of 2^n-1\n"); } } ////////////////////////////////////////////////// void HeightmapShape::Init() { } ////////////////////////////////////////////////// std::string HeightmapShape::GetFilename() const { return this->sdf->GetValueString("filename"); } ////////////////////////////////////////////////// math::Vector3 HeightmapShape::GetSize() const { return this->sdf->GetValueVector3("size"); } ////////////////////////////////////////////////// math::Vector3 HeightmapShape::GetOrigin() const { return this->sdf->GetValueVector3("origin"); } ////////////////////////////////////////////////// void HeightmapShape::FillShapeMsg(msgs::Geometry &_msg) { _msg.set_type(msgs::Geometry::HEIGHTMAP); msgs::Set(_msg.mutable_heightmap()->mutable_image(), common::Image(this->GetFilename())); msgs::Set(_msg.mutable_heightmap()->mutable_size(), this->GetSize()); msgs::Set(_msg.mutable_heightmap()->mutable_origin(), this->GetOrigin()); } ////////////////////////////////////////////////// void HeightmapShape::ProcessMsg(const msgs::Geometry & /*_msg*/) { gzerr << "TODO: not implement yet."; }
26.538462
75
0.579348
[ "geometry", "shape" ]
7584ceb8ae52787499a66a393c4aaf705db6cafb
636
cpp
C++
Challenge-2020-06/random_pick_with_weight.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-06/random_pick_with_weight.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-06/random_pick_with_weight.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
#include "header.h" class Solution { vector<int> sum; public: Solution(vector<int>& w) { sum = w; for (int i = 1; i < w.size(); i++) { sum[i] = sum[i-1] + w[i]; } } int pickIndex() { int pos = rand() % sum.back(); int start = 0, end = sum.size() - 1; int mid = start + (end - start) / 2; while (start < end) { if (sum[mid] <= pos) { start = mid + 1; } else { end = mid; } mid = start + (end - start) / 2; } return end; } };
20.516129
44
0.363208
[ "vector" ]
758eff819468e6be42f4df15979d928a5be78239
2,476
hpp
C++
brfv4_mac_examples/brfv4/examples/face_tracking/track_multiple_faces.hpp
Tastenkunst/brfv4_mac_examples
21a0aa182df6285386be308e6880468a3c239c24
[ "BSD-3-Clause" ]
23
2017-06-30T17:08:15.000Z
2022-02-21T19:02:39.000Z
brfv4_mac_examples/brfv4/examples/face_tracking/track_multiple_faces.hpp
Tastenkunst/brfv4_mac_examples
21a0aa182df6285386be308e6880468a3c239c24
[ "BSD-3-Clause" ]
1
2019-02-20T04:04:20.000Z
2019-02-20T04:04:20.000Z
brfv4_mac_examples/brfv4/examples/face_tracking/track_multiple_faces.hpp
Tastenkunst/brfv4_mac_examples
21a0aa182df6285386be308e6880468a3c239c24
[ "BSD-3-Clause" ]
4
2018-03-27T04:48:02.000Z
2019-06-12T11:35:05.000Z
#ifndef __brf__cpp__BRFCppExample_hpp #define __brf__cpp__BRFCppExample_hpp namespace brf { class BRFCppExample: public BRFBasicCppExample { public: int numFacesToTrack; public: BRFCppExample() : BRFBasicCppExample(), numFacesToTrack(2) { } public: void initCurrentExample(brf::BRFManager& brfManager, brf::Rectangle& resolution) { brf::trace("BRFv4 - basic - face tracking - track multiple faces" + brf::to_string("\n")+ "Detect and track " + brf::to_string(numFacesToTrack) + " faces and draw their 68 facial landmarks."); // By default everything necessary for a single face tracking app // is set up for you in brfManager.init. // But here we tell BRFv4 to track multiple faces. In this case two. // While the first face is getting tracked the face detection // is performed in parallel and is looking for a second face. brfManager.setNumFacesToTrack(numFacesToTrack); // Relax starting conditions to eventually find more faces. double maxFaceSize = resolution.height; if(resolution.width < resolution.height) { maxFaceSize = resolution.width; } brfManager.setFaceDetectionParams( maxFaceSize * 0.20, maxFaceSize * 1.00, 12, 8); brfManager.setFaceTrackingStartParams( maxFaceSize * 0.20, maxFaceSize * 1.00, 32, 35, 32); brfManager.setFaceTrackingResetParams( maxFaceSize * 0.15, maxFaceSize * 1.00, 40, 55, 32); } public: void updateCurrentExample(brf::BRFManager& brfManager, brf::DrawingUtils& draw) { brfManager.update(); // Drawing the results: draw.clear(); // Get all faces. We get numFacesToTrack faces in that array. std::vector< std::shared_ptr<brf::BRFFace> >& faces = brfManager.getFaces(); for(size_t i = 0; i < faces.size(); i++) { brf::BRFFace& face = *faces[i]; // Every face has it's own states. // While the first face might already be tracking, // the second face might just try to detect a face. if(face.state == brf::BRFState::FACE_DETECTION) { // Face detection results: a rough rectangle used to start the face tracking. draw.drawRects(brfManager.getMergedDetectedFaces(), false, 2.0, 0xffd200, 1.0); } else if( face.state == brf::BRFState::FACE_TRACKING_START || face.state == brf::BRFState::FACE_TRACKING) { // Face tracking results: 68 facial feature points. draw.drawTriangles( face.vertices, face.triangles, false, 1.0, 0x00a0ff, 0.4); draw.drawVertices( face.vertices, 2.0, false, 0x00a0ff, 0.4); } } }; }; } #endif // __brf__cpp__BRFCppExample_hpp
29.47619
105
0.726575
[ "vector" ]
75967bed2f0b7a91d478663cf9bde3188f8af1cc
1,326
cc
C++
example/main.cc
horance-liu/smart_ocr
dc483b994fff8e5ceabcf2140d9704bd22f3f3bc
[ "Apache-2.0" ]
null
null
null
example/main.cc
horance-liu/smart_ocr
dc483b994fff8e5ceabcf2140d9704bd22f3f3bc
[ "Apache-2.0" ]
null
null
null
example/main.cc
horance-liu/smart_ocr
dc483b994fff8e5ceabcf2140d9704bd22f3f3bc
[ "Apache-2.0" ]
1
2021-05-21T01:21:26.000Z
2021-05-21T01:21:26.000Z
/* * Copyright (c) 2021, Horance Liu and the respective contributors * All rights reserved. * * Use of this source code is governed by a Apache 2.0 license that can be found * in the LICENSE file. */ #include "smart_ocr/sequence.h" #include <fstream> #include <iterator> #include <algorithm> #include <vector> #include <memory> namespace { auto close = [](std::ifstream* s) { s->close(); }; using FileStream = std::unique_ptr<std::ifstream, decltype(close)>; void exec(const char* file) { FileStream in { new std::ifstream(file), close }; std::vector<Sequence> seqs { std::istream_iterator<Sequence>(*in), std::istream_iterator<Sequence>() }; std::copy(seqs.cbegin(), seqs.cend(), std::ostream_iterator<Sequence>(std::cout, "\n") ); } void usage(const char* prog) { std::cout << "Usage: " << prog << " path_to_usecase_in" << std::endl; } } int main(int argc, char** argv) { try { if (argc < 2) { usage(argv[0]); return EXIT_FAILURE; } exec(argv[1]); return EXIT_SUCCESS; } catch (const std::invalid_argument& e) { std::cerr << "bad format: " << e.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "unknown exception" << std::endl; return EXIT_FAILURE; } }
20.71875
82
0.604827
[ "vector" ]
759b21a2027673e98dd7d6df3c5786409b6a2c46
27,591
cpp
C++
dp/rix/fx/src/ManagerUniform.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
217
2015-01-06T09:26:53.000Z
2022-03-23T14:03:18.000Z
dp/rix/fx/src/ManagerUniform.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
10
2015-01-25T12:42:05.000Z
2017-11-28T16:10:16.000Z
dp/rix/fx/src/ManagerUniform.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
44
2015-01-13T01:19:41.000Z
2022-02-21T21:35:08.000Z
// Copyright (c) 2012-2016, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <iostream> #include <GroupDataUniform.h> #include <GroupDataBuffered.h> #include <GroupDataBufferedCombined.h> #include <ManagerUniform.h> #include <ParameterGroupSpecInfo.h> #include <dp/rix/fx/inc/BufferManagerIndexed.h> #include <dp/rix/fx/inc/BufferManagerOffset.h> #include <dp/fx/inc/ExtensionSnippet.h> #include <dp/fx/inc/EnumSpecSnippet.h> #include <dp/fx/inc/FileSnippet.h> #include <dp/fx/inc/ParameterGroupDataPrivate.h> #include <dp/fx/inc/ParameterGroupSnippet.h> #include <dp/fx/inc/StringSnippet.h> #include <dp/fx/inc/VersionSnippet.h> #include <dp/util/Array.h> #include <dp/util/HashGeneratorMurMur.h> #include <dp/util/File.h> #include <dp/util/Memory.h> #include <boost/scoped_array.hpp> #include <typeinfo> using namespace dp::rix::core; namespace dp { namespace rix { namespace fx { /************************************************************************/ /* ManagerUniform::Program */ /************************************************************************/ class ManagerUniform::Program : public dp::rix::fx::Program { public: Program( ManagerUniform *manager, dp::fx::EffectSpecSharedPtr const & effectSpec , Manager::SystemSpecs const & systemSpecs , char const * technique, dp::rix::core::ContainerDescriptorHandle * userDescriptors, size_t numDescriptors , SourceFragments const & sourceFragments ); static void getShaderSource( dp::fx::ShaderPipelineConfiguration const & configuration , dp::fx::ShaderPipelineSharedPtr const & pipeline , dp::rix::fx::Manager::SystemSpecs const & systemSpecs , dp::fx::Domain domain , std::string& source , std::string& entrypoint ); dp::rix::core::ProgramPipelineSharedHandle m_programPipeline; std::vector<SmartParameterGroupSpecInfoHandle> m_parameterGroupSpecInfos; }; ManagerUniform::Program::Program( ManagerUniform *manager , dp::fx::EffectSpecSharedPtr const & effectSpec , Manager::SystemSpecs const & systemSpecs , char const * technique , dp::rix::core::ContainerDescriptorHandle * userDescriptors , size_t numDescriptors , SourceFragments const & sourceFragments ) { DP_ASSERT( manager && effectSpec ); DP_ASSERT( effectSpec->getType() == dp::fx::EffectSpec::Type::PIPELINE ); DP_ASSERT( userDescriptors || numDescriptors == 0 ); { /************************************************************************/ /* create the program */ /************************************************************************/ dp::fx::ShaderPipelineConfiguration configuration( effectSpec->getName() ); configuration.setManager( manager->getManagerType() ); configuration.setTechnique( technique ); // Required to find the matching signature of the vertex shader. for ( SourceFragments::const_iterator it = sourceFragments.begin(); it != sourceFragments.end(); ++it ) { configuration.addSourceCode( it->first, it->second ); } dp::fx::ShaderPipelineSharedPtr shaderPipeline = dp::fx::EffectLibrary::instance()->generateShaderPipeline( configuration ); #if !defined(NDEBUG) const dp::fx::ShaderPipeline::iterator itStageVertex = shaderPipeline->getStage( dp::fx::Domain::VERTEX ); const dp::fx::ShaderPipeline::iterator itStageFragment = shaderPipeline->getStage( dp::fx::Domain::FRAGMENT ); DP_ASSERT( itStageVertex != shaderPipeline->endStages() ); DP_ASSERT( itStageFragment != shaderPipeline->endStages() ); #endif std::vector<std::string> shaderStringSources; std::vector<char const*> shaderSources; std::vector<dp::rix::core::ShaderType> shaderEnums; for ( dp::fx::ShaderPipeline::iterator it = shaderPipeline->beginStages();it != shaderPipeline->endStages(); ++it ) { std::string source; std::string entryPoint; getShaderSource(configuration, shaderPipeline, systemSpecs, (*it).domain, source, entryPoint ); switch ( (*it).domain ) { case dp::fx::Domain::VERTEX: shaderEnums.push_back( dp::rix::core::ShaderType::VERTEX_SHADER ); break; case dp::fx::Domain::FRAGMENT: shaderEnums.push_back( dp::rix::core::ShaderType::FRAGMENT_SHADER ); break; case dp::fx::Domain::GEOMETRY: shaderEnums.push_back( dp::rix::core::ShaderType::GEOMETRY_SHADER ); break; case dp::fx::Domain::TESSELLATION_CONTROL: shaderEnums.push_back( dp::rix::core::ShaderType::TESS_CONTROL_SHADER ); break; case dp::fx::Domain::TESSELLATION_EVALUATION: shaderEnums.push_back( dp::rix::core::ShaderType::TESS_EVALUATION_SHADER ); break; default: throw std::runtime_error( "unexpected shader type" ); break; } shaderStringSources.push_back( source ); // For each SystemSpec of the current stage for ( std::vector<std::string>::const_iterator itSystemSpec = (*it).systemSpecs.begin(); itSystemSpec != (*it).systemSpecs.end(); ++itSystemSpec ) { // check if there's a systemSpec for the given string Manager::SystemSpecs::const_iterator itSystemSpec2 = systemSpecs.find( *itSystemSpec ); if ( itSystemSpec2 != systemSpecs.end() ) { // Global SystemSpecs are being used to generate the parameter header for the source code, but they're not supposed to generate // ContainerDescriptors for the GeometryInstances. Thus skip them here. if ( !itSystemSpec2->second.m_isGlobal ) { dp::fx::EffectSpecSharedPtr const & effectSpec = itSystemSpec2->second.m_effectSpec; for ( dp::fx::EffectSpec::iterator itParameterGroupSpec = effectSpec->beginParameterGroupSpecs(); itParameterGroupSpec != effectSpec->endParameterGroupSpecs(); ++itParameterGroupSpec ) { m_parameterGroupSpecInfos.push_back(manager->getParameterGroupSpecInfo(*itParameterGroupSpec)); } } } } } // generate vector of char const* for sources for ( size_t index = 0; index < shaderStringSources.size(); ++index ) { shaderSources.push_back( shaderStringSources[index].c_str() ); } DP_ASSERT( !shaderSources.empty() ); dp::rix::core::ProgramShaderCode programShaderCode( shaderSources.size(), &shaderSources[0], &shaderEnums[0] ); /************************************************************************/ /* Add descriptors */ /************************************************************************/ std::vector<dp::rix::core::ContainerDescriptorSharedHandle> descriptors; std::copy( userDescriptors, userDescriptors + numDescriptors, std::back_inserter(descriptors)); // ensure that a spec gets inserted only once even if it is being used by multiple domains. std::set<dp::fx::ParameterGroupSpecSharedPtr> usedSpecs; for ( dp::fx::EffectSpec::iterator it = effectSpec->beginParameterGroupSpecs(); it != effectSpec->endParameterGroupSpecs(); ++it ) { if ( usedSpecs.insert(*it).second ) { m_parameterGroupSpecInfos.push_back(manager->getParameterGroupSpecInfo(*it)); } } for ( size_t index = 0;index < m_parameterGroupSpecInfos.size(); ++index ) { // TODO get array of descriptors here... if ( m_parameterGroupSpecInfos[index]->m_bufferManager ) { if ( typeid(*m_parameterGroupSpecInfos[index]->m_bufferManager.get()) == typeid(BufferManagerIndexed) ) { BufferManagerIndexed* bufferManager = dp::rix::core::handleCast<BufferManagerIndexed>(m_parameterGroupSpecInfos[index]->m_bufferManager.get()); descriptors.push_back(bufferManager->getBufferDescriptor()); descriptors.push_back(bufferManager->getIndexDescriptor()); } else if ( typeid(*m_parameterGroupSpecInfos[index]->m_bufferManager.get()) == typeid(BufferManagerOffset) ) { BufferManagerOffset* bufferManager = dp::rix::core::handleCast<BufferManagerOffset>(m_parameterGroupSpecInfos[index]->m_bufferManager.get()); descriptors.push_back(bufferManager->getBufferDescriptor()); } else { DP_ASSERT( !"unsupported BufferManager" ); } } else { descriptors.push_back(m_parameterGroupSpecInfos[index]->m_descriptor); } } dp::rix::core::ProgramDescription description( programShaderCode, descriptors.empty() ? nullptr : &descriptors[0], descriptors.size() ); dp::rix::core::ProgramSharedHandle programs[] = { manager->getRenderer()->programCreate( description ) }; m_programPipeline = manager->getRenderer()->programPipelineCreate( programs, sizeof dp::util::array( programs ) ); } } void ManagerUniform::Program::getShaderSource( dp::fx::ShaderPipelineConfiguration const & configuration , dp::fx::ShaderPipelineSharedPtr const & pipeline , dp::rix::fx::Manager::SystemSpecs const & systemSpecs , dp::fx::Domain domain , std::string& source , std::string& /*entrypoint*/ ) { std::vector<dp::fx::SnippetSharedPtr> shaderSnippets; dp::fx::ShaderPipeline::Stage const & stage = *pipeline->getStage( domain ); // generate header only if a body had been generated if ( stage.source ) { std::vector<dp::fx::SnippetSharedPtr> headerSnippets; headerSnippets.push_back( std::make_shared<dp::fx::VersionSnippet>() ); headerSnippets.push_back( std::make_shared<dp::fx::ExtensionSnippet>() ); std::vector<dp::fx::SnippetSharedPtr> pgsSnippets; // gather all parameter groups for ( std::vector<dp::fx::ParameterGroupSpecSharedPtr>::const_iterator it = stage.parameterGroupSpecs.begin(); it != stage.parameterGroupSpecs.end(); ++it ) { pgsSnippets.push_back( std::make_shared<dp::fx::ParameterGroupSnippet>( *it ) ); } for( std::vector<std::string>::const_iterator it = stage.systemSpecs.begin(); it != stage.systemSpecs.end(); ++it ) { dp::rix::fx::Manager::SystemSpecs::const_iterator itSystemSpec = systemSpecs.find(*it); if ( itSystemSpec == systemSpecs.end() ) { throw std::runtime_error( std::string("Missing SystemSpec " + *it + " for effect " + configuration.getName() ) ); } for ( std::vector<dp::fx::ParameterGroupSpecSharedPtr>::const_iterator it = itSystemSpec->second.m_effectSpec->beginParameterGroupSpecs(); it != itSystemSpec->second.m_effectSpec->endParameterGroupSpecs(); ++it ) { pgsSnippets.push_back( std::make_shared<dp::fx::ParameterGroupSnippet>( *it ) ); } } // get the enums from shader and pgs snippets std::set<dp::fx::EnumSpecSharedPtr> enumSpecs; for ( std::vector<dp::fx::SnippetSharedPtr>::const_iterator it = shaderSnippets.begin(); it != shaderSnippets.end(); ++it ) { std::set<dp::fx::EnumSpecSharedPtr> const & snippetEnums = (*it)->getRequiredEnumSpecs(); if ( ! snippetEnums.empty() ) { enumSpecs.insert( snippetEnums.begin(), snippetEnums.end() ); } } for ( std::vector<dp::fx::SnippetSharedPtr>::const_iterator it = pgsSnippets.begin(); it != pgsSnippets.end(); ++it ) { const std::set<dp::fx::EnumSpecSharedPtr> & snippetEnums = (*it)->getRequiredEnumSpecs(); if ( ! snippetEnums.empty() ) { enumSpecs.insert( snippetEnums.begin(), snippetEnums.end() ); } } // insert enumSpecs from source body enumSpecs.insert( stage.source->getRequiredEnumSpecs().begin(), stage.source->getRequiredEnumSpecs().end() ); for ( std::set<dp::fx::EnumSpecSharedPtr>::const_iterator it = enumSpecs.begin(); it != enumSpecs.end(); ++it ) { headerSnippets.push_back( std::make_shared<dp::fx::EnumSpecSnippet>( *it ) ); } // add snippets from renderer std::vector<dp::fx::SnippetSharedPtr> sources; std::vector<std::string> const& codeSnippets = configuration.getSourceCodes(domain); for( size_t index = 0;index < codeSnippets.size(); ++index ) { sources.push_back( std::make_shared<dp::fx::StringSnippet>( codeSnippets[index] ) ); } // generate code from header, pgs, and shader dp::fx::GeneratorConfiguration config; config.manager = configuration.getManager(); sources.push_back( stage.source ); source = generateSnippets( headerSnippets, config ) + generateSnippets( pgsSnippets, config ) + generateSnippets( sources, config ); } } class ManagerUniform::Instance : public dp::rix::fx::Instance { public: virtual void setProgram( dp::rix::core::Renderer * renderer, ManagerUniform::ProgramSharedHandle ) = 0; virtual bool useGroupData( dp::rix::core::Renderer * renderer, dp::rix::fx::GroupDataHandle groupHandle ) = 0; }; /************************************************************************/ /* InstanceGeometryInstance */ /************************************************************************/ class InstanceGeometryInstance : public ManagerUniform::Instance { public: InstanceGeometryInstance(core::GeometryInstanceHandle gi) : m_gi(gi) { } virtual void setProgram( dp::rix::core::Renderer * renderer, ManagerUniform::ProgramSharedHandle program); virtual bool useGroupData( dp::rix::core::Renderer * renderer, dp::rix::fx::GroupDataHandle groupHandle ); private: ManagerUniform::ProgramSharedHandle m_program; core::GeometryInstanceSharedHandle m_gi; }; void InstanceGeometryInstance::setProgram( dp::rix::core::Renderer * renderer, ManagerUniform::ProgramSharedHandle program ) { m_program = program; renderer->geometryInstanceSetProgramPipeline( m_gi, m_program->m_programPipeline ); } bool InstanceGeometryInstance::useGroupData( dp::rix::core::Renderer * renderer, dp::rix::fx::GroupDataHandle groupHandle ) { GroupDataBaseHandle groupData = handleCast<GroupDataBase>(groupHandle); if (handleIsTypeOf<GroupDataBufferedCombined>(groupData ) ) { ((GroupDataBufferedCombined*)(groupData))->useContainers( m_gi ); } else { renderer->geometryInstanceUseContainer( m_gi, groupData->m_container ); } return true; } class InstanceRenderGroup : public ManagerUniform::Instance { public: InstanceRenderGroup(core::RenderGroupHandle renderGroup) : m_renderGroup(renderGroup) { } virtual void setProgram( dp::rix::core::Renderer* renderer, ManagerUniform::ProgramSharedHandle); virtual bool useGroupData( dp::rix::core::Renderer* renderer, dp::rix::fx::GroupDataHandle groupHandle ); private: ManagerUniform::ProgramSharedHandle m_program; dp::rix::core::RenderGroupHandle m_renderGroup; }; void InstanceRenderGroup::setProgram( dp::rix::core::Renderer * renderer, ManagerUniform::ProgramSharedHandle program ) { m_program = program; renderer->renderGroupSetProgramPipeline( m_renderGroup, m_program->m_programPipeline ); } bool InstanceRenderGroup::useGroupData( dp::rix::core::Renderer * renderer, dp::rix::fx::GroupDataHandle groupHandle ) { GroupDataBaseHandle groupData = handleCast<GroupDataBase>(groupHandle); if (handleIsTypeOf<GroupDataBufferedCombined>(groupData ) ) { ((GroupDataBufferedCombined*)(groupData))->useContainers( m_renderGroup ); } else { renderer->renderGroupUseContainer( m_renderGroup, groupData->m_container ); } return true; } ////////////////////////////////////////////////////////////////////////// // System ManagerUniformSharedPtr ManagerUniform::create( core::Renderer* renderer, dp::fx::Manager managerType ) { return( std::shared_ptr<ManagerUniform>( new ManagerUniform( renderer, managerType ) ) ); } ManagerUniform::ManagerUniform( core::Renderer* renderer, dp::fx::Manager managerType ) : m_renderer( renderer ) , m_managerType( managerType ) { } ManagerUniform::~ManagerUniform() { } void ManagerUniform::runPendingUpdates() { for ( DirtyGroupContainer::iterator it = m_dirtyGroups.begin(); it != m_dirtyGroups.end(); ++it ) { DP_ASSERT( handleIsTypeOf<GroupDataBase>( it->get() ) ); GroupDataBaseHandle groupData = handleCast<GroupDataBase>( it->get() ); groupData->update(); } m_dirtyGroups.clear(); for ( std::vector<SmartBufferManager>::iterator it = m_bufferManagers.begin(); it != m_bufferManagers.end(); ++it ) { (*it)->update(); } } /************************************************************************/ /* GroupData */ /************************************************************************/ dp::rix::fx::GroupDataSharedHandle ManagerUniform::groupDataCreate( dp::fx::ParameterGroupSpecSharedPtr const& group ) { SmartParameterGroupSpecInfoHandle pgsi = getParameterGroupSpecInfo( group ); dp::fx::ParameterGroupLayoutSharedPtr layout = pgsi->m_groupLayout; switch( layout->getManager() ) { case dp::fx::Manager::UNIFORM: case dp::fx::Manager::UNIFORM_BUFFER_OBJECT_RIX: case dp::fx::Manager::SHADER_STORAGE_BUFFER_OBJECT_RIX: return new GroupDataUniform( this, pgsi ); case dp::fx::Manager::SHADERBUFFER: return new GroupDataBufferedCombined( this, pgsi ); case dp::fx::Manager::SHADER_STORAGE_BUFFER_OBJECT: if ( layout->isInstanced() ) { return new GroupDataBufferedCombined( this, pgsi ); } else { return new GroupDataBuffered( this, pgsi ); } case dp::fx::Manager::UNIFORM_BUFFER_OBJECT_RIX_FX: return new GroupDataBufferedCombined( this, pgsi ); default: DP_ASSERT( !"unsupported manager" ); return nullptr; } } void ManagerUniform::groupDataSetValue( dp::rix::fx::GroupDataSharedHandle const& groupDataHandle , const dp::fx::ParameterGroupSpec::iterator& parameter , const dp::rix::core::ContainerData& data ) { GroupDataBaseHandle groupData = handleCast<GroupDataBase>(groupDataHandle.get()); if ( groupData->setValue( parameter, data ) ) { m_dirtyGroups.push_back( groupDataHandle ); } } ////////////////////////////////////////////////////////////////////////// // Instance dp::rix::fx::InstanceHandle ManagerUniform::instanceCreate( dp::rix::core::GeometryInstanceHandle gi ) { InstanceHandle instance = new InstanceGeometryInstance( gi ); return instance; } dp::rix::fx::InstanceHandle ManagerUniform::instanceCreate( dp::rix::core::RenderGroupHandle renderGroup ) { InstanceHandle instance = new InstanceRenderGroup( renderGroup ); return instance; } dp::rix::fx::ProgramSharedHandle ManagerUniform::programCreate( const dp::fx::EffectSpecSharedPtr& effectSpec , Manager::SystemSpecs const & systemSpecs , const char *technique , dp::rix::core::ContainerDescriptorHandle *userDescriptors , size_t numDescriptors , SourceFragments const& sourceFragments ) { std::string key = effectSpec->getName() + "@" + technique; ProgramMap::iterator it = m_programs.find( key ); if ( it == m_programs.end() ) { dp::rix::fx::ProgramSharedHandle handle; DP_ASSERT( m_managerType != dp::fx::Manager::UNKNOWN ); if ( dp::fx::EffectLibrary::instance()->effectHasTechnique( effectSpec, technique, true ) ) { handle = new ManagerUniform::Program( this, effectSpec, systemSpecs, technique, userDescriptors, numDescriptors, sourceFragments ); } m_programs[key] = handle; return handle; } return it->second; } std::map<dp::fx::Domain,std::string> ManagerUniform::getShaderSources( dp::fx::EffectSpecSharedPtr const & effectSpec , bool depthPass , dp::rix::fx::Manager::SystemSpecs const & systemSpecs , SourceFragments const & sourceFragments ) const { DP_ASSERT( effectSpec->getType() == dp::fx::EffectSpec::Type::PIPELINE ); dp::fx::ShaderPipelineConfiguration configuration( effectSpec->getName() ); configuration.setManager( m_managerType ); for ( SourceFragments::const_iterator it = sourceFragments.begin(); it != sourceFragments.end(); ++it ) { configuration.addSourceCode( it->first, it->second ); } if ( depthPass ) { configuration.setTechnique( "depthPass" ); } else { configuration.setTechnique( "forward" ); // Required to find the matching signature of the vertex shader. } dp::fx::ShaderPipelineSharedPtr shaderPipeline = dp::fx::EffectLibrary::instance()->generateShaderPipeline( configuration ); std::map<dp::fx::Domain,std::string> sources; for ( dp::fx::ShaderPipeline::iterator it = shaderPipeline->beginStages() ; it != shaderPipeline->endStages() ; ++it ) { std::string source; std::string entryPoint; Program::getShaderSource( configuration, shaderPipeline, systemSpecs, (*it).domain, source, entryPoint ); sources[it->domain] = source; } return( sources ); } void ManagerUniform::instanceSetProgram( dp::rix::fx::InstanceHandle instanceHandle, dp::rix::fx::ProgramHandle programHandle ) { DP_ASSERT( handleIsTypeOf<Instance>( instanceHandle ) ); InstanceHandle instance = handleCast<Instance>(instanceHandle); DP_ASSERT( handleIsTypeOf<Program>( programHandle ) ); ProgramHandle program = handleCast<Program>( programHandle ); instance->setProgram( getRenderer(), program ); } bool ManagerUniform::instanceUseGroupData( dp::rix::fx::InstanceHandle instanceHandle, dp::rix::fx::GroupDataHandle groupHandle ) { InstanceHandle instance = handleCast<Instance>(instanceHandle); return instance->useGroupData( getRenderer(), groupHandle ); } SmartParameterGroupSpecInfoHandle ManagerUniform::getParameterGroupSpecInfo( const dp::fx::ParameterGroupSpecSharedPtr& spec ) { ParameterGroupSpecInfoMap::iterator it = m_groupInfos.find(spec); if ( it == m_groupInfos.end() ) { SmartParameterGroupSpecInfoHandle specInfo = new ParameterGroupSpecInfo( spec, getManagerType(), getRenderer() ); m_groupInfos[spec] = specInfo; // keep track of BufferManagers for update function if ( specInfo->m_bufferManager ) { m_bufferManagers.push_back( specInfo->m_bufferManager ); } return specInfo; } return it->second; } dp::rix::core::Renderer* ManagerUniform::getRenderer() const { return m_renderer; } dp::fx::Manager ManagerUniform::getManagerType() const { return m_managerType; } } } }
44.216346
202
0.584285
[ "geometry", "vector" ]
759e2d5a4120bc6803ef2a181ba1fc39f287da91
15,575
cpp
C++
argus/samples/userAutoWhiteBalance/main.cpp
gwli/JetPack_tegra_multimedia_api_sample
554e27757a707515f8505006bac2ef7f37c42e44
[ "Unlicense" ]
2
2020-01-09T21:20:13.000Z
2020-05-26T11:22:02.000Z
argus/samples/userAutoWhiteBalance/main.cpp
gwli/JetPack_tegra_multimedia_api_sample
554e27757a707515f8505006bac2ef7f37c42e44
[ "Unlicense" ]
null
null
null
argus/samples/userAutoWhiteBalance/main.cpp
gwli/JetPack_tegra_multimedia_api_sample
554e27757a707515f8505006bac2ef7f37c42e44
[ "Unlicense" ]
1
2020-05-20T02:33:52.000Z
2020-05-20T02:33:52.000Z
/* * Copyright (c) 2016-2017, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Error.h" #include <stdio.h> #include <stdlib.h> #include <Argus/Argus.h> #include <Argus/Ext/BayerAverageMap.h> #include <EGLStream/EGLStream.h> #include "PreviewConsumer.h" #include "Options.h" #include <algorithm> #define EXIT_IF_TRUE(val,msg) \ {if ((val)) {printf("%s\n",msg); return EXIT_FAILURE;}} #define EXIT_IF_NULL(val,msg) \ {if (!val) {printf("%s\n",msg); return EXIT_FAILURE;}} #define EXIT_IF_NOT_OK(val,msg) \ {if (val!=Argus::STATUS_OK) {printf("%s\n",msg); return EXIT_FAILURE;}} using namespace Argus; namespace ArgusSamples { // Globals and derived constants. EGLDisplayHolder g_display; const float BAYER_CLIP_COUNT_MAX = 0.25f; const float BAYER_MISSING_SAMPLE_TOLERANCE = 0.10f; const int CAPTURE_COUNT = 300; const uint32_t DEFAULT_CAMERA_INDEX = 0; struct ExecuteOptions { uint32_t cameraIndex; uint32_t useAverageMap; }; /* * Program: userAutoWhiteBalance * Function: To display 101 preview images to the device display to illustrate a * Grey World White Balance technique for adjusting the White Balance in real time * through the use of setWbGains() and setAwbMode(AWB_MODE_MANUAL) calls. */ static bool execute(const ExecuteOptions& options) { BayerTuple<float> precedingAverages(1.0f, 1.5f, 1.5f, 1.5f); // Initialize the window and EGL display. Window &window = Window::getInstance(); PROPAGATE_ERROR(g_display.initialize(window.getEGLNativeDisplay())); /* * Set up Argus API Framework, identify available camera devices, create * a capture session for the first available device, and set up the event * queue for completed events */ UniqueObj<CameraProvider> cameraProvider(CameraProvider::create()); ICameraProvider *iCameraProvider = interface_cast<ICameraProvider>(cameraProvider); EXIT_IF_NULL(iCameraProvider, "Cannot get core camera provider interface"); printf("Argus Version: %s\n", iCameraProvider->getVersion().c_str()); std::vector<CameraDevice*> cameraDevices; EXIT_IF_NOT_OK(iCameraProvider->getCameraDevices(&cameraDevices), "Failed to get camera devices"); EXIT_IF_NULL(cameraDevices.size(), "No camera devices available"); if (cameraDevices.size() <= options.cameraIndex) { printf("Camera device specified on the command line is not available\n"); return EXIT_FAILURE; } UniqueObj<CaptureSession> captureSession( iCameraProvider->createCaptureSession(cameraDevices[options.cameraIndex])); ICaptureSession *iSession = interface_cast<ICaptureSession>(captureSession); EXIT_IF_NULL(iSession, "Cannot get Capture Session Interface"); IEventProvider *iEventProvider = interface_cast<IEventProvider>(captureSession); EXIT_IF_NULL(iEventProvider, "iEventProvider is NULL"); std::vector<EventType> eventTypes; eventTypes.push_back(EVENT_TYPE_CAPTURE_COMPLETE); UniqueObj<EventQueue> queue(iEventProvider->createEventQueue(eventTypes)); IEventQueue *iQueue = interface_cast<IEventQueue>(queue); EXIT_IF_NULL(iQueue, "event queue interface is NULL"); /* * Creates the stream between the Argus camera image capturing * sub-system (producer) and the image acquisition code (consumer) * preview thread. A consumer object is created from the stream * to be used to request the image frame. A successfully submitted * capture request activates the stream's functionality to eventually * make a frame available for acquisition, in the preview thread, * and then display it on the device screen. */ UniqueObj<OutputStreamSettings> streamSettings(iSession->createOutputStreamSettings()); IOutputStreamSettings *iStreamSettings = interface_cast<IOutputStreamSettings>(streamSettings); EXIT_IF_NULL(iStreamSettings, "Cannot get OutputStreamSettings Interface"); iStreamSettings->setPixelFormat(PIXEL_FMT_YCbCr_420_888); iStreamSettings->setResolution(Size2D<uint32_t>(640,480)); iStreamSettings->setEGLDisplay(g_display.get()); UniqueObj<OutputStream> stream(iSession->createOutputStream(streamSettings.get())); IStream *iStream = interface_cast<IStream>(stream); EXIT_IF_NULL(iStream, "Cannot get OutputStream Interface"); PreviewConsumerThread previewConsumerThread( iStream->getEGLDisplay(), iStream->getEGLStream()); PROPAGATE_ERROR(previewConsumerThread.initialize()); PROPAGATE_ERROR(previewConsumerThread.waitRunning()); UniqueObj<Request> request(iSession->createRequest(CAPTURE_INTENT_PREVIEW)); IRequest *iRequest = interface_cast<IRequest>(request); EXIT_IF_NULL(iRequest, "Failed to get capture request interface"); EXIT_IF_NOT_OK(iRequest->enableOutputStream(stream.get()), "Failed to enable stream in capture request"); IAutoControlSettings* iAutoControlSettings = interface_cast<IAutoControlSettings>(iRequest->getAutoControlSettings()); EXIT_IF_NULL(iAutoControlSettings, "Failed to get AutoControlSettings interface"); if (options.useAverageMap) { // Enable BayerAverageMap generation in the request. Ext::IBayerAverageMapSettings *iBayerAverageMapSettings = interface_cast<Ext::IBayerAverageMapSettings>(request); EXIT_IF_NULL(iBayerAverageMapSettings, "Failed to get BayerAverageMapSettings interface"); iBayerAverageMapSettings->setBayerAverageMapEnable(true); } EXIT_IF_NOT_OK(iSession->repeat(request.get()), "Unable to submit repeat() request"); /* * Using the image capture event metadata, acquire the bayer histogram and then compute * a weighted average for each channel. Use these weighted averages to create a White * Balance Channel Gain array to use for setting the manual white balance of the next * capture request. */ int frameCaptureLoop = 0; while (frameCaptureLoop < CAPTURE_COUNT) { // Keep PREVIEW display window serviced window.pollEvents(); const uint64_t ONE_SECOND = 1000000000; // WAR Bug 200317271 // update waitForEvents time from 1s to 2s // to ensure events are queued up properly iEventProvider->waitForEvents(queue.get(), 2*ONE_SECOND); EXIT_IF_TRUE(iQueue->getSize() == 0, "No events in queue"); frameCaptureLoop += iQueue->getSize(); const Event* event = iQueue->getEvent(iQueue->getSize() - 1); const IEventCaptureComplete *iEventCaptureComplete = interface_cast<const IEventCaptureComplete>(event); EXIT_IF_NULL(iEventCaptureComplete, "Failed to get EventCaptureComplete Interface"); const CaptureMetadata *metaData = iEventCaptureComplete->getMetadata(); const ICaptureMetadata* iMetadata = interface_cast<const ICaptureMetadata>(metaData); EXIT_IF_NULL(iMetadata, "Failed to get CaptureMetadata Interface"); BayerTuple<float> bayerTotals(0.0f); BayerTuple<float> bayerAverages(0.0f); if (!options.useAverageMap) { const IBayerHistogram* bayerHistogram = interface_cast<const IBayerHistogram>(iMetadata->getBayerHistogram()); std::vector< BayerTuple<uint32_t> > histogram; EXIT_IF_NOT_OK(bayerHistogram->getHistogram(&histogram), "Failed to get histogram"); for (int channel = 0; channel < BAYER_CHANNEL_COUNT; channel++) { for (uint32_t bin = 0; bin < histogram.size(); bin++) { bayerTotals[channel] += histogram[bin][channel]; bayerAverages[channel] += histogram[bin][channel] * (float)bin; } if (bayerTotals[channel]) bayerAverages[channel] /= bayerTotals[channel]; } printf("Histogram "); } else { const Ext::IBayerAverageMap* iBayerAverageMap = interface_cast<const Ext::IBayerAverageMap>(metaData); EXIT_IF_NULL(iBayerAverageMap, "Failed to get IBayerAverageMap interface"); Array2D< BayerTuple<float> > averages; EXIT_IF_NOT_OK(iBayerAverageMap->getAverages(&averages), "Failed to get averages"); Array2D< BayerTuple<uint32_t> > clipCounts; EXIT_IF_NOT_OK(iBayerAverageMap->getClipCounts(&clipCounts), "Failed to get clip counts"); uint32_t pixelsPerBinPerChannel = iBayerAverageMap->getBinSize().width() * iBayerAverageMap->getBinSize().height() / BAYER_CHANNEL_COUNT; EXIT_IF_NULL(pixelsPerBinPerChannel, "Zero pixels per bin channel"); // Using the BayerAverageMap, get the average instensity across the checked area uint32_t usedBins = 0; for (uint32_t x = 0; x < averages.size().width(); x++) { for (uint32_t y = 0; y < averages.size().height(); y++) { /* * Bins with excessively high clip counts many contain * misleading averages, since clipped pixels are ignored * in the averages, and so these bins are ignored. * */ if ((float)clipCounts(x, y).r() / pixelsPerBinPerChannel <= BAYER_CLIP_COUNT_MAX && (float)clipCounts(x, y).gEven() / pixelsPerBinPerChannel <= BAYER_CLIP_COUNT_MAX && (float)clipCounts(x, y).gOdd() / pixelsPerBinPerChannel <= BAYER_CLIP_COUNT_MAX && (float)clipCounts(x, y).b() / pixelsPerBinPerChannel <= BAYER_CLIP_COUNT_MAX) { bayerTotals += averages(x, y); usedBins++; } } } EXIT_IF_NULL(usedBins, "No used bins"); /* * This check is to determine if enough BayerAverageMap samples * have been collected to give a valid enough evaluation of the * white balance adjustment. If not enough samples, then the * most previous valid results are used. If valid, then the valid * set is stored for future use. */ if ((float)usedBins / (averages.size().width() * averages.size().height()) < ( 1.0f - BAYER_MISSING_SAMPLE_TOLERANCE )) { printf("Clipped sensor sample percentage of %0.1f%%" " exceed tolerance of %0.1f%%\n" "Using last valid BayerAverageMap intensity values\n", (1.0f - (float)usedBins / (averages.size().width() * averages.size().height())) * 100, BAYER_MISSING_SAMPLE_TOLERANCE * 100); bayerAverages = precedingAverages; } else { for (int channel=0; channel<BAYER_CHANNEL_COUNT; channel++) { bayerAverages[channel] = bayerTotals[channel] / usedBins; precedingAverages[channel] = bayerAverages[channel]; } } printf("BayerAverageMap "); } float maxGain = 0; for (int channel = 0; channel < BAYER_CHANNEL_COUNT; channel++) { maxGain = std::max(maxGain, bayerAverages[channel]); } float whiteBalanceGains[BAYER_CHANNEL_COUNT]; for (int channel = 0; channel < BAYER_CHANNEL_COUNT; channel++) { whiteBalanceGains[channel] = maxGain / bayerAverages[channel]; } printf("Intensity: r:%0.3f gO:%0.3f gE:%0.3f b:%0.3f " "WBGains: r:%0.3f gO:%0.3f gE:%0.3f b:%0.3f\n", bayerAverages[0], bayerAverages[1], bayerAverages[2], bayerAverages[3], whiteBalanceGains[0], whiteBalanceGains[1], whiteBalanceGains[2], whiteBalanceGains[3]); BayerTuple<float> bayerGains(whiteBalanceGains[0], whiteBalanceGains[1], whiteBalanceGains[2], whiteBalanceGains[3]); iAutoControlSettings->setWbGains(bayerGains); iAutoControlSettings->setAwbMode(AWB_MODE_MANUAL); EXIT_IF_NOT_OK(iSession->repeat(request.get()), "Unable to submit repeat() request"); } iSession->stopRepeat(); iSession->waitForIdle(); // Destroy the output streams (stops consumer threads). stream.reset(); // Wait for the consumer threads to complete. PROPAGATE_ERROR(previewConsumerThread.shutdown()); // Shut down Argus. cameraProvider.reset(); return EXIT_SUCCESS; } }; // namespace ArgusSamples int main(int argc, char **argv) { printf("Executing Argus Sample: %s\n", basename(argv[0])); ArgusSamples::Value<uint32_t> cameraIndex(ArgusSamples::DEFAULT_CAMERA_INDEX); ArgusSamples::Value<uint32_t> useAverageMap(false); ArgusSamples::Options options(basename(argv[0])); PROPAGATE_ERROR(options.addOption(ArgusSamples::createValueOption ("device", 'd', "INDEX", "Camera index.", cameraIndex))); options.addOption(ArgusSamples::createValueOption ("useaveragemap", 'a', "[0 or 1]", "Use Average Map (instead of Bayer Histogram).", useAverageMap)); if (!options.parse(argc, argv)) return EXIT_FAILURE; if (options.requestedExit()) return EXIT_SUCCESS; ArgusSamples::ExecuteOptions executeOptions; executeOptions.cameraIndex = cameraIndex.get(); executeOptions.useAverageMap = useAverageMap.get(); if (!ArgusSamples::execute(executeOptions)) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
41.756032
108
0.655474
[ "object", "vector" ]
759ef845123846a0dea889d64495d3433e6e3483
3,128
cc
C++
references/aoapc-book/TrainingGuide/exercises/ch4/03-GeometricAlgorithms2D/UVa10084.cc
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
TG/exercises/ch4/03-GeometricAlgorithms2D/UVa10084.cc
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
TG/exercises/ch4/03-GeometricAlgorithms2D/UVa10084.cc
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
// UVa10084 Hotter Colder // 陈锋 #include<cmath> #include<algorithm> #include<cstring> #include<cstdio> #include<vector> using namespace std; const double eps = 1e-8; int dcmp(double x) { if(fabs(x) < eps) return 0; else return x < 0 ? -1 : 1; } struct Point { double x, y; Point(double x = 0, double y = 0):x(x),y(y) { } }; typedef Point Vector; Vector operator + (const Vector& A, const Vector& B) { return Vector(A.x+B.x, A.y+B.y); } Vector operator - (const Point& A, const Point& B) { return Vector(A.x-B.x, A.y-B.y); } Vector operator * (const Vector& A, double p) { return Vector(A.x*p, A.y*p); } double Dot(const Vector& A, const Vector& B) { return A.x*B.x + A.y*B.y; } double Cross(const Vector& A, const Vector& B) { return A.x*B.y - A.y*B.x; } double Length(const Vector& A) { return sqrt(Dot(A, A)); } Vector Normal(const Vector& A) { double L = Length(A); return Vector(-A.y/L, A.x/L); } // 调用前请确保两条直线P+tv和Q+tw有惟一交点。这当且仅当Cross(v,w)非零 Point GetLineIntersection(const Point& P, const Vector& v, const Point& Q, const Vector& w) { Vector u = P-Q; double t = Cross(w, u) / Cross(v, w); return P+v*t; } bool OnSegment(const Point& p, const Point& a1, const Point& a2) { return dcmp(Cross(a1-p, a2-p)) == 0 && dcmp(Dot(a1-p, a2-p)) < 0; } typedef vector<Point> Polygon; double PolygonArea(const Polygon& p) { int n = p.size(); double area = 0; for(int i = 1; i < n-1; i++) area += Cross(p[i]-p[0], p[i+1]-p[0]); return area/2; } Polygon CutPolygon(const Polygon& poly, const Point& A, const Point& B) { Polygon newpoly; int n = poly.size(); for(int i = 0; i < n; i++) { const Point& C = poly[i], D = poly[(i+1)%n]; Vector AB = B-A; if(dcmp(Cross(AB, C-A)) >= 0) newpoly.push_back(C); if(dcmp(Cross(AB, C-D)) != 0) { Point ip = GetLineIntersection(A, AB, C, D-C); if(OnSegment(ip, C, D)) newpoly.push_back(ip); } } return newpoly; } /********************************************************************/ int main() { Polygon p; double x, y; char buf[16]; Point prev; p.push_back(Point(0.0, 0.0)); p.push_back(Point(10.0, 0.0)); p.push_back(Point(10.0, 10.0)); p.push_back(Point(0.0, 10.0)); bool empty = false; while(true) { if(scanf("%lf%lf%s", &x, &y, buf) != 3) break; if(empty) { puts("0.00"); continue; } if(!strcmp(buf, "Same") || dcmp(PolygonArea(p) == 0)) { empty = true; puts("0.00"); continue; } Point cur(x, y); Point A((prev.x + x)*0.5, (prev.y+y)*0.5); Vector t = cur - prev; if(0 == strcmp(buf, "Colder")) p = CutPolygon(p, A, A + Vector(-t.y, t.x)); else if(!strcmp(buf, "Hotter")) p = CutPolygon(p, A, A + Vector(t.y, -t.x)); if(p.size() < 3) { empty = true; puts("0.00"); continue; } double area = PolygonArea(p); printf("%.2lf\n", fabs(area)); prev = cur; } return 0; }
29.233645
104
0.527174
[ "vector" ]
b5a504094a6ee91f5471db90947d30c6ac0d61d6
2,336
cpp
C++
old_ml/Common/data.cpp
uwroute/study
8c3fad3db9bc5b30006b98688d03db5788372f9d
[ "Apache-2.0" ]
null
null
null
old_ml/Common/data.cpp
uwroute/study
8c3fad3db9bc5b30006b98688d03db5788372f9d
[ "Apache-2.0" ]
null
null
null
old_ml/Common/data.cpp
uwroute/study
8c3fad3db9bc5b30006b98688d03db5788372f9d
[ "Apache-2.0" ]
null
null
null
/*============================================================================= # # Author: route - uwnroute@126.com # # Last modified: Fri 03 Apr 2015 12:05:16 PM CST [10.146.36.174] # # Filename: data.cpp # # Description: # =============================================================================*/ #include <fstream> #include <string> #include "log.h" #include "string_util.h" #include "data.h" using namespace Common; #define CHECK_AND_DELETE(p) \ if (p) \ { \ delete p; \ p = NULL; \ } DataSet::~DataSet() { CHECK_AND_DELETE(samples); CHECK_AND_DELETE(index); CHECK_AND_DELETE(label); label_size = 0; sample_size = 0; } int DataSet::load(const char* data_file) { LOG_DEBUG("Start compute fea_size and sample_size in %s", data_file); std::ifstream infile(data_file); std::string line; getline(infile, line); while (!infile.eof()) { std::vector<std::string> tmp; splitString(line, tmp, ' '); sample_size += tmp.size(); sample_size++; label_size++; getline(infile, line); } infile.close(); LOG_INFO("[sample_size=%u] and [label_size=%u]", sample_size, label_size); if (sample_size == label_size) { LOG_ERROR("[sample_size=%u] = [label_size=%u]", sample_size, label_size); return -1; } samples = new Feature[sample_size]; if (!sample) { LOG_ERROR("Can't new %d bytes for sample!", sample_size*sizeof(Feature)); return -1; } index = new uint32_t[label_size]; if (!index) { LOG_ERROR("Can't new %d bytes for index!", label_size*sizeof(uint32_t)); return -1; } label = new uint32_t[label_size]; if (!label) { LOG_ERROR("Can't new %d bytes for label!", label_size*sizeof(uint32_t)); return -1; } std::ifstream infile(data_file); getline(infile, line); uint32_t label_i = 0; uint32_t sample_i = 0; while (!infile.eof()) { index[label_i] = sample_i; std::vector<std::string> vec; splitString(line, vec, ' '); label[label_i] = atof(vec[0]); Feature* fea = sample + sample_i; for (size_t i=1; i<vec.size(); ++i) { if (!sscanf(vec[i].c_str(), "%lu:%lf", &(fea->index), &(fea->value))) { continue; } fea_num = std::max(fea_num, fea->index); ++fea; ++sample_i; } getline(infile, line); } LOG_INFO("load %u feas and %u samples", sample_size, label_size); }
22.901961
79
0.588613
[ "vector" ]
b5a56ab7bcc1d6b4b569d888a97a632a30533915
1,583
cpp
C++
src/towerdefense/levels/LevelTowerAreaRect.cpp
jkorn2324/Tower-Defense
f1b6c07c7937594f67024595623e39fefdc529e5
[ "MIT" ]
null
null
null
src/towerdefense/levels/LevelTowerAreaRect.cpp
jkorn2324/Tower-Defense
f1b6c07c7937594f67024595623e39fefdc529e5
[ "MIT" ]
null
null
null
src/towerdefense/levels/LevelTowerAreaRect.cpp
jkorn2324/Tower-Defense
f1b6c07c7937594f67024595623e39fefdc529e5
[ "MIT" ]
null
null
null
#include "LevelTowerAreaRect.h" #include "Level.h" namespace TowerDefense { LevelTowerAreaRect::LevelTowerAreaRect(const Vector2& size, const Vector2& pos) { this->size = size; this->pos = pos; } bool LevelTowerAreaRect::IsWithinBounds(const Vector2 &point) const { Vector2 min = GetMin(); Vector2 max = GetMax(); return point.x >= min.x && point.x <= max.x && point.y >= min.y && point.y <= max.y; } Vector2 LevelTowerAreaRect::GetMin() const { Vector2 min(pos); min.y -= size.y; return min; } Vector2 LevelTowerAreaRect::GetMax() const { Vector2 max(pos); max.x += size.x; return max; } LevelTowersAreaManager::LevelTowersAreaManager(Level *level) { mLevel = level; mTowerAreas = std::vector<LevelTowerAreaRect*>(); } LevelTowersAreaManager::~LevelTowersAreaManager() { for(const auto& levelTower : mTowerAreas) { delete levelTower; } mTowerAreas.clear(); } void LevelTowersAreaManager::AddTowerArea(const Vector2 &size, const Vector2 &pos) { LevelTowerAreaRect* rect = new LevelTowerAreaRect(size, pos); mTowerAreas.push_back(rect); } bool LevelTowersAreaManager::CanPlaceTower(const Vector2 &point) const { for(const auto& rect : mTowerAreas) { if(rect->IsWithinBounds(point)) { return true; } } return false; } }
23.279412
86
0.573594
[ "vector" ]
b5b739370de36618d05345ed77c8fca0072ef55d
4,318
cpp
C++
matrix/unit-test/test-EM_vector_vector.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
140
2015-01-02T21:28:55.000Z
2015-12-22T01:25:03.000Z
matrix/unit-test/test-EM_vector_vector.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
160
2016-11-07T18:37:33.000Z
2020-03-10T22:57:07.000Z
matrix/unit-test/test-EM_vector_vector.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
25
2016-11-14T04:31:29.000Z
2020-07-28T04:58:44.000Z
#include "vector_vector.h" #include "data_frame.h" #include "EM_vv_store.h" #include "local_vv_store.h" #include "local_vec_store.h" #include "factor.h" #include "sparse_matrix.h" using namespace fm; class adj_apply: public gr_apply_operate<local_vec_store> { public: virtual void run(const void *key, const local_vec_store &val, local_vec_store &vec) const { vec.resize(val.get_length()); memcpy(vec.get_raw_arr(), val.get_raw_arr(), val.get_length() * val.get_entry_size()); } virtual const scalar_type &get_key_type() const { return get_scalar_type<int>(); } virtual const scalar_type &get_output_type() const { return get_scalar_type<int>(); } virtual size_t get_num_out_eles() const { return 0; } }; class set_label_operate: public type_set_vec_operate<factor_value_t> { factor f; size_t num_same_label; public: set_label_operate(const factor &_f, size_t tot_num_eles): f(_f) { num_same_label = tot_num_eles / f.get_num_levels(); } virtual void set(factor_value_t *arr, size_t num_eles, off_t start_idx) const { for (size_t i = 0; i < num_eles; i++) arr[i] = (start_idx + i) / num_same_label; } }; class part_apply_operate: public gr_apply_operate<local_vv_store> { const scalar_type &val_type; public: part_apply_operate(const scalar_type &type): val_type(type) { } virtual void run(const void *key, const local_vv_store &val, local_vec_store &vec) const { assert(val.get_type() == val_type); assert(vec.get_type() == get_scalar_type<size_t>()); vec.resize(1); size_t num = 0; for (size_t i = 0; i < val.get_length(); i++) num += val.get_length(i); vec.set<size_t>(0, num); } virtual const scalar_type &get_key_type() const { return get_scalar_type<factor_value_t>(); } virtual const scalar_type &get_output_type() const { return get_scalar_type<size_t>(); } virtual size_t get_num_out_eles() const { return 1; } }; vector_vector::ptr create_vv() { detail::smp_vec_store::ptr store = detail::smp_vec_store::create(8000000, get_scalar_type<int>()); #pragma omp parallel for for (size_t i = 0; i < store->get_length(); i++) store->set<int>(i, random() % 1000000); vector::ptr vec = vector::create(store); data_frame::ptr res = vec->groupby(adj_apply(), false); std::vector<detail::vec_store::const_ptr> vvs(1); vvs[0] = res->get_vec("agg"); detail::EM_vv_store::ptr em_vv = detail::EM_vv_store::create(store->get_type()); em_vv->append(vvs.begin(), vvs.end()); return vector_vector::create(em_vv); } void test_groupby() { printf("test groupby\n"); vector_vector::ptr vv = create_vv(); factor f(50); factor_vector::ptr labels = factor_vector::create(f, vv->get_num_vecs(), -1, false, set_label_operate(f, vv->get_num_vecs())); assert(!labels->is_in_mem()); labels->sort(); vector_vector::ptr gr_res = vv->groupby(*labels, part_apply_operate( vv->get_type())); printf("There are %ld vectors\n", gr_res->get_num_vecs()); std::map<factor_value_t, size_t> label_map; local_vec_store::const_ptr llabels = labels->get_data().get_portion(0, labels->get_length()); for (size_t i = 0; i < llabels->get_length(); i++) { factor_value_t label = llabels->get<factor_value_t>(i); if (label_map.find(label) == label_map.end()) label_map.insert(std::pair<factor_value_t, size_t>(label, 0)); label_map[label]++; } assert(gr_res->get_num_vecs() == label_map.size()); size_t vec_idx = 0; size_t label_idx = 0; local_vv_store::const_ptr lres = local_vv_store::cast( gr_res->get_data().get_portion(0, gr_res->get_num_vecs())); for (auto it = label_map.begin(); it != label_map.end(); it++) { factor_value_t label = it->first; size_t num_label_vecs = it->second; size_t num_eles = 0; for (size_t i = 0; i < num_label_vecs; i++) { assert(llabels->get<factor_value_t>(vec_idx) == label); num_eles += vv->get_length(vec_idx); vec_idx++; } assert(num_eles == *(size_t *) lres->get_raw_arr(label_idx)); label_idx++; } assert(vec_idx == vv->get_num_vecs()); assert(label_idx == gr_res->get_num_vecs()); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "test conf_file\n"); exit(1); } std::string conf_file = argv[1]; config_map::ptr configs = config_map::create(conf_file); init_flash_matrix(configs); test_groupby(); destroy_flash_matrix(); }
28.596026
81
0.703103
[ "vector" ]
b5b8e16b339de0f749b829a482bc115c99f98724
5,222
cpp
C++
test.cpp
supelec-lstm/PinaPL_lstm
96462ed2f8f880ccfc33424eb6a273522b90b049
[ "MIT" ]
null
null
null
test.cpp
supelec-lstm/PinaPL_lstm
96462ed2f8f880ccfc33424eb6a273522b90b049
[ "MIT" ]
null
null
null
test.cpp
supelec-lstm/PinaPL_lstm
96462ed2f8f880ccfc33424eb6a273522b90b049
[ "MIT" ]
null
null
null
// Copyright PinaPL // // test.cpp // PinaPL // #include <Eigen/Dense> #include <vector> #include <fstream> #include <string> #include "weights.hpp" #include "cell.hpp" #include "test.hpp" #include "iostream" void single_cell_test() { int input_size = 4; int output_size = 4; std::cout << "sequence_size is 4, word is warp" << std::endl; std::cout << "a b c d e f g h i j k l m n o p q r s t u v w x y z" << std::endl << "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0" << std::endl << "1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0" << std::endl << "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0" << std::endl << "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0" << std::endl; Weights* cell_weight = new Weights(input_size, output_size); Cell cell = Cell(cell_weight); std::vector<Eigen::MatrixXd> inputs; Eigen::MatrixXd inputW(input_size, 1); inputW << 1, 0, 0, 0; Eigen::MatrixXd inputA(input_size, 1); inputA << 0, 1, 0, 0; Eigen::MatrixXd inputR(input_size, 1); inputR << 0, 0, 1, 0; Eigen::MatrixXd inputP(input_size, 1); inputP << 0, 0, 0, 1; inputs.push_back(inputW); inputs.push_back(inputA); inputs.push_back(inputR); inputs.push_back(inputP); std::vector<Eigen::MatrixXd> deltas; for (int j=0; j < 1000; j++) { std::cout << "run :" << j << std::endl; for (int i=0; i < 3; ++i) { Eigen::MatrixXd input = inputs.at(i); cell.compute(&input); Eigen::MatrixXd output = cell.cell_out.back(); Eigen::MatrixXd delta(output_size, 1); delta = (output-inputs.at(i+1)).cwiseProduct(output-inputs.at(i+1)); deltas.push_back(delta); } for (int i=3-1; i >= 0; --i) { cell.compute_gate_gradient(&deltas.at(i), i); // std::cout << "gate gradient input gate" << std::endl; // std::cout << cell.delta_input_gate_out.at(3-i) << std::endl; } double lambda = -0.1; cell.compute_weight_gradient(); // std::cout << "====== delta poids input_gate ======" << std::endl; // std::cout << cell_weight->delta_weight_in_input_gate << std::endl; // std::cout << cell.weights->delta_weight_st_input_gate << std::endl; cell.update_weights(lambda); deltas.clear(); cell.reset(); } cell.compute(&inputW); std::cout << "Result of learning :" << std::endl; std::cout << cell.cell_out.back() << std::endl; cell.compute(&inputA); std::cout << "------------------" << std::endl; std::cout << cell.cell_out.back() << std::endl; cell.compute(&inputR); std::cout << "------------------" << std::endl; std::cout << cell.cell_out.back() << std::endl; } void single_cell_grammar_test() { int input_size = 7; int output_size = 7; int words_to_learn = 5; Weights* cell_weight = new Weights(input_size, output_size); Cell cell = Cell(cell_weight); std::ifstream file("reber_test_1M.txt"); std::string str; std::vector<Eigen::MatrixXd> deltas; while ((std::getline(file, str)) && (0 < words_to_learn)) { int lenght_word = str.length(); for (int i = 0; i < lenght_word-1; ++i) { Eigen::MatrixXd in = get_input(str.at(i)); Eigen::MatrixXd expected = get_input(str.at(i+1)); cell.compute(&in); deltas.push_back((expected - cell.cell_out.back()) .cwiseProduct((expected - cell.cell_out.back()))); } for (int i = lenght_word - 2 ; i >= 0; --i) { Eigen::MatrixXd delta = deltas.at(i); cell.compute_gate_gradient(&delta, i); } cell.compute_weight_gradient(); cell.update_weights(0.3); cell.reset(); words_to_learn -= 1; } Eigen::MatrixXd B = get_input('B'); Eigen::MatrixXd P = get_input('P'); Eigen::MatrixXd V = get_input('V'); Eigen::MatrixXd E = get_input('E'); std::cout << "==================" << std::endl; cell.compute(&B); std::cout << cell.cell_out.back() << std::endl; std::cout << "------------------" << std::endl; cell.compute(&P); std::cout << cell.cell_out.back() << std::endl; std::cout << "------------------" << std::endl; cell.compute(&V); std::cout << cell.cell_out.back() << std::endl; std::cout << "------------------" << std::endl; cell.compute(&V); std::cout << cell.cell_out.back() << std::endl; } Eigen::MatrixXd get_input(char letter) { Eigen::MatrixXd in(7, 1); switch (letter) { case 'B': in << 1, 0, 0, 0, 0, 0, 0; break; case 'T': in << 0, 1, 0, 0, 0, 0, 0; break; case 'P': in << 0, 0, 1, 0, 0, 0, 0; break; case 'S': in << 0, 0, 0, 1, 0, 0, 0; break; case 'X': in << 0, 0, 0, 0, 1, 0, 0; break; case 'V': in << 1, 0, 0, 0, 0, 1, 0; break; case 'E': in << 1, 0, 0, 0, 0, 0, 1; break; } return in; }
28.227027
80
0.511298
[ "vector" ]
b5bebb8a15babcddf1b6982030b6d6cad140c415
16,035
cpp
C++
src/HSADebugAgent/AgentProcessPacket.cpp
HSAFoundation/HSA-Debugger-Source-AMD
47d41b74bfb51f1bec02763feb7ab752ce80272a
[ "MIT" ]
2
2017-05-22T17:22:22.000Z
2019-05-16T01:45:06.000Z
src/HSADebugAgent/AgentProcessPacket.cpp
HSAFoundation/HSA-Debugger-Source-AMD
47d41b74bfb51f1bec02763feb7ab752ce80272a
[ "MIT" ]
2
2016-01-28T15:22:07.000Z
2016-01-28T15:43:42.000Z
src/HSADebugAgent/AgentProcessPacket.cpp
HSAFoundation/HSA-Debugger-Source-AMD
47d41b74bfb51f1bec02763feb7ab752ce80272a
[ "MIT" ]
2
2016-02-07T18:46:52.000Z
2020-05-03T22:18:06.000Z
//============================================================================== // Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools /// \file /// \brief Agent processing, functions to consume FIFO packets and configure expression evaluation //============================================================================== #include <iostream> #include <cassert> // \todo including cstdint seems to need a -std=c++11 compiler switch on gcc // Maye better to avoid C++11 for now. #include <cstdbool> #include <stdint.h> #include <cstddef> #include <cstring> #include <sstream> #include <stdio.h> // Use some stl vectors for maintaining breakpoint handles #include <algorithm> #include <vector> // Agent includes #include "AgentBreakpointManager.h" #include "AgentContext.h" #include "AgentFocusWaveControl.h" #include "AgentLogging.h" #include "AgentNotifyGdb.h" #include "AgentProcessPacket.h" #include "AgentUtils.h" #include "CommunicationControl.h" // Add DBE (Version decided by Makefile) #include "AMDGPUDebug.h" static void DBEDeleteBreakpoint(HwDbgAgent::AgentContext* pActiveContext, const HsailCommandPacket& ipPacket) { if (!pActiveContext->HasHwDebugStarted()) { AgentErrorLog("DBEDeleteBreakpoint:BeginDebugging has not occured\n"); } else { HwDbgAgent::AgentBreakpointManager* pBpManager = pActiveContext->GetBpManager(); HsailAgentStatus status; status = pBpManager->DeleteBreakpoint(pActiveContext->GetActiveHwDebugContext(), ipPacket); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AgentErrorLog("DBEDeleteBreakpoint: Could not delete breakpoint\n"); } } return; } static void DBECreateBreakpoint(HwDbgAgent::AgentContext* pActiveContext, const HsailCommandPacket& ipPacket) { HwDbgAgent::AgentBreakpointManager* pBpManager = pActiveContext->GetBpManager(); HwDbgAgent::HsailBkptType bpType = HwDbgAgent::HSAIL_BREAKPOINT_TYPE_PC_BP; if ((char)0 != ipPacket.m_kernelName[0]) { bpType = HwDbgAgent::HSAIL_BREAKPOINT_TYPE_KERNEL_NAME_BP; } HsailAgentStatus status; status = pBpManager->CreateBreakpoint(pActiveContext->GetActiveHwDebugContext(), ipPacket, bpType); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AgentErrorLog("DBECreateBreakpoint: Could not create a breakpoint\n"); } } static void DBEDisablePCBreakpoint(HwDbgAgent::AgentContext* pActiveContext, const HsailCommandPacket& ipPacket) { if (!pActiveContext->HasHwDebugStarted()) { AgentErrorLog("DBEDisablePCBreakpoint:should not Disable breakpoint without BeginDebugging\n"); } else { HwDbgAgent::AgentBreakpointManager* pBpManager = pActiveContext->GetBpManager(); HsailAgentStatus status; status = pBpManager->DisablePCBreakpoint(pActiveContext->GetActiveHwDebugContext(), ipPacket); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AgentErrorLog("DBEDisablePCBreakpoint: Could not disable a breakpoint\n"); } } return; } static void DBEEnablePCBreakpoint(HwDbgAgent::AgentContext* pActiveContext, const HsailCommandPacket& ipPacket) { if (!pActiveContext->HasHwDebugStarted()) { AgentErrorLog("DBE: We should not Enable breakpoint without BeginDebugging \n"); } else { HwDbgAgent::AgentBreakpointManager* pBpManager = pActiveContext->GetBpManager(); HsailAgentStatus status; status = pBpManager->EnablePCBreakpoint(pActiveContext->GetActiveHwDebugContext(), ipPacket); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AgentErrorLog("DBEEnablePCBreakpoint: Could not enable a breakpoint\n"); } } return; } static void DBEMomentaryBreakpoint(HwDbgAgent::AgentContext* pActiveContext, const HsailCommandPacket& ipPacket) { HwDbgAgent::AgentBreakpointManager* pBpManager = pActiveContext->GetBpManager(); HsailAgentStatus status; status = pBpManager->CreateMomentaryBreakpoints(pActiveContext->GetActiveHwDebugContext(), ipPacket); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AgentErrorLog("DBEMomentaryBreakpoint: Could not create a momentary breakpoint\n"); } } // Global pointer to active context used for the expression evaluator // Can be fixed soon by checking a static variable in the function HwDbgAgent::AgentContext* g_ActiveContext = nullptr; void SetEvaluatorActiveContext(HwDbgAgent::AgentContext* activeContext) { g_ActiveContext = activeContext; } // Global pointer to kernel parameters buffers used for the var eval // isaMemoryRegion type void* g_KernelParametersBuffer = nullptr; void SetKernelParametersBuffers(const hsa_kernel_dispatch_packet_t* pAqlPacket) { if (nullptr == pAqlPacket) { g_KernelParametersBuffer = nullptr; } else { g_KernelParametersBuffer = (void*)pAqlPacket->kernarg_address; } } void KillHsailDebug(bool isQuitIssued) { AGENT_LOG("KillHsailDebug: isQuitIssued: " << isQuitIssued); HsailAgentStatus status = g_ActiveContext->KillDispatch(isQuitIssued); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AGENT_ERROR("KillDispatch: Killing the dispatch by expression evaluation"); } status = g_ActiveContext->EndDebugging(); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AGENT_ERROR("KillDispatch: Ending debugging from within expression evaluation"); } } bool GetPrivateMemory(HwDbgDim3 workGroup, HwDbgDim3 workItem, size_t base, size_t offset, size_t numByteToRead, void* pMemOut, size_t* pNumBytesOut) { bool retVal = false; HwDbgDim3 workGroupId; workGroupId.x = workGroup.x; workGroupId.y = workGroup.y; workGroupId.z = workGroup.z; HwDbgDim3 workItemId; workItemId.x = workItem.x; workItemId.y = workItem.y; workItemId.z = workItem.z; HwDbgStatus status = HWDBG_STATUS_SUCCESS; if (g_ActiveContext == nullptr) { AgentErrorLog("GetPrivateMemory: Active context is nullptr\n"); (*(int*)pMemOut) = 0; return false; } /* char buffer[256]; sprintf(buffer,"GPM WG:%d,%d,%d WI:%d,%d,%d realLocation:%ld\n", workGroup.x, workGroup.y, workGroup.z, workItem.x, workItem.y, workItem.z, (size_t)pMemOut); AgentLog(buffer); sprintf(buffer,"GPM AC:%x, DX:%x, base:%ld, base+offset:%ld, bytes to read:%ld\n", g_ActiveContext, (void*)g_ActiveContext->GetActiveHwDebugContext(), base, base+offset, numByteToRead); AgentLog(buffer); sprintf(buffer,"Address:%x\n", pMemOut); AgentLog(buffer);*/ status = HwDbgReadMemory(g_ActiveContext->GetActiveHwDebugContext(), 1 /* IMR_Scratch */, workGroupId, workItemId, base + offset, numByteToRead, pMemOut, pNumBytesOut); if (status != HWDBG_STATUS_SUCCESS) { AgentErrorLog("GetPrivateMemory: Error in Printing\n"); AgentErrorLog(GetDBEStatusString(status).c_str()); } else { retVal = true; } return retVal; } enum LocationRegister { LOC_REG_REGISTER, ///< A register holds the value LOC_REG_STACK, ///< The frame pointer holds the value LOC_REG_NONE, ///< No registers are to be used in getting the value LOC_REG_UNINIT, ///< Default / max value }; // This function is called by the expression evaluator void SetHsailThreadCmdInfo(unsigned int wgX, unsigned int wgY, unsigned int wgZ, unsigned int wiX, unsigned int wiY, unsigned int wiZ) { char buffer[256]; HwDbgDim3 focusWg; focusWg.x = wgX; focusWg.y = wgY; focusWg.z = wgZ; HwDbgDim3 focusWI; focusWI.x = wiX; focusWI.y = wiY; focusWI.z = wiZ; HsailAgentStatus status = g_ActiveContext->m_pFocusWaveControl->SetFocusWave(nullptr, &focusWg, &focusWI); sprintf(buffer, "SetHsailThreadCmdInfo: got here wg:%d %d %d, wi:%d %d %d \n", focusWg.x, focusWg.y, focusWg.z, focusWI.x, focusWI.y, focusWI.z); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AgentErrorLog("Could not change focus wave from GDB command\n"); AgentErrorLog(buffer); } AgentLog(buffer); } void* gVariableValueForRelease = nullptr; void FreeVarValue(void) { free(gVariableValueForRelease); gVariableValueForRelease = nullptr; } void* GetVarValue(int reg_type, size_t var_size, unsigned int reg_num, bool deref_value, unsigned int offset, unsigned int resource, unsigned int isa_memory_region, unsigned int piece_offset, unsigned int piece_size, int const_add) { // Results /* prepare the largest primitive buffer but the GetPrivateMemory will get the var_size */ void* variableValues = malloc(8); memset(variableValues, 0, 8); // unsigned int valueStride = 0; // 1. Get the base location: static const size_t zero = 0; const void* loc = nullptr; // size_t locStride = 0; /* offset for step 2 */ size_t totalOffset = 0; /* gdb later turns this to nullptr so we need a copy for releasing this */ gVariableValueForRelease = variableValues; if (nullptr == variableValues) { return nullptr; } switch (reg_type) { case LOC_REG_REGISTER: { } break; case LOC_REG_STACK: { } break; case LOC_REG_NONE: { loc = &zero; } break; case LOC_REG_UNINIT: { // This is currently the information for some unsupported locations, (e.g. __local T* parameters): return nullptr; } break; default: { AGENT_LOG("hsail-printf unsupported reg type"); } break; } /* 2. Dereference and apply offset as needed: */ /* currently ignoring array offset */ totalOffset = offset; if (deref_value) { // Note: This assumes for dereferenced types that the values of the base pointer are all the same. // A more "correct" method would be to iterate all the active work items, get the value for each, // then copy that into a buffer. size_t realLocation = *((size_t*)loc) + totalOffset + piece_offset; // Since we applied the piece offset here (to get the correct value), we can reset the piece offset we will use to parse to 0: piece_offset = 0; switch (isa_memory_region) { case 0: // = IMR_Global { // Global Memory: memcpy(variableValues, ((void*)realLocation), var_size); // valueStride = (unsigned int)var_size; } break; case 1: // = IMR_Scratch { // Private memory: size_t locVarSize; /* for some reason only in the first time allocation if I do not erase the variableValues than the data that is received from GetPrivateMemory is faulty. freeing and allocating the memory solves this problem. This a temporary solution */ HwDbgDim3 focusWg; HwDbgDim3 focusWi; HsailAgentStatus status = g_ActiveContext->m_pFocusWaveControl->GetFocus(focusWg, focusWi); if (status != HSAIL_AGENT_STATUS_SUCCESS) { AGENT_ERROR("Could not get focus parameters"); } bool rc = GetPrivateMemory(focusWg, focusWi, (size_t)realLocation, 0, var_size, variableValues, &locVarSize); if (rc) { // Only signify success if we actually asked for and got a value from the DBE: /* valueStride = (unsigned int)locVarSize; return value is used in original ref function */ } } break; case 2: // = IMR_Group { // Local memory: // Not currently supported return nullptr; } break; case 3: // = IMR_ExtUserData { // Uri, 21/05/13 - As a workaround to getting an ExtUserData (32-bit aligned OpenCL arguments buffer) pointer // And having to read from the AQL (64-bit aligned HSA arguments buffer), we need to double the offset here, // As this works properly for most parameters. // Should be revised (as parameters larger than 32-bit will not work) or removed when the compiler moves to AQL offsets. realLocation *= 2; } case 4: // = IMR_AQL case 5: // = IMR_FuncArg { // assume kernel argument is not nullptr but value is 0? // Kernel arguments: // Add the offset to the kernel args base pointer: realLocation += (size_t)g_KernelParametersBuffer; memcpy(variableValues, ((void*)realLocation), var_size); /* valueStride = (unsigned int)var_size; return value is used in original ref function */ } break; } } else { /* valueStride = 0; return value is used in original ref function */ variableValues = (void*)((size_t)loc + totalOffset); } variableValues = (void*)((size_t)variableValues + piece_offset); return (void*)(*(size_t*)variableValues); } void AgentProcessPacket(HwDbgAgent::AgentContext* pActiveContext, const HsailCommandPacket& packet) { switch (packet.m_command) { // \todo What is the earliest time that this packet can be sent ? // Is it theoretically possible for GDB to send this packet ? // This packet is not needed since we do the setup in the predispatch case HSAIL_COMMAND_BEGIN_DEBUGGING: pActiveContext->PrintDBEVersion(); AgentErrorLog("Unsupported command packet error"); break; case HSAIL_COMMAND_KILL_ALL_WAVES: AgentErrorLog("Unsupported command packet error"); break; case HSAIL_COMMAND_CREATE_BREAKPOINT: DBECreateBreakpoint(pActiveContext, packet); break; case HSAIL_COMMAND_DISABLE_BREAKPOINT: DBEDisablePCBreakpoint(pActiveContext, packet); break; case HSAIL_COMMAND_DELETE_BREAKPOINT: DBEDeleteBreakpoint(pActiveContext, packet); break; case HSAIL_COMMAND_MOMENTARY_BREAKPOINT: DBEMomentaryBreakpoint(pActiveContext, packet); break; case HSAIL_COMMAND_CONTINUE: pActiveContext->m_ReadyToContinue = true; break; case HSAIL_COMMAND_ENABLE_BREAKPOINT: DBEEnablePCBreakpoint(pActiveContext, packet); break; case HSAIL_COMMAND_SET_LOGGING: pActiveContext->SetLogging(packet.m_loggingInfo); break; case HSAIL_COMMAND_UNKNOWN: pActiveContext->PrintDBEVersion(); AgentErrorLog("Incomplete command packet error"); break; default: pActiveContext->PrintDBEVersion(); AgentErrorLog("Incomplete command packet error"); break; } }
31.752475
231
0.615217
[ "vector" ]
b5bfbdefdb707d5d722cca665498a7dcd0b6dcb6
4,978
cc
C++
src/sequence_diagram/visitor/translation_unit_visitor.cc
dgoffredo/clang-uml
3b0a454e4e85aee06168439660f0fd71dc4b7a75
[ "Apache-2.0" ]
10
2021-11-16T01:08:05.000Z
2022-03-15T23:51:11.000Z
src/sequence_diagram/visitor/translation_unit_visitor.cc
dgoffredo/clang-uml
3b0a454e4e85aee06168439660f0fd71dc4b7a75
[ "Apache-2.0" ]
8
2021-11-16T21:29:41.000Z
2022-03-21T21:22:00.000Z
src/sequence_diagram/visitor/translation_unit_visitor.cc
dgoffredo/clang-uml
3b0a454e4e85aee06168439660f0fd71dc4b7a75
[ "Apache-2.0" ]
2
2021-12-04T20:20:06.000Z
2022-02-08T06:33:27.000Z
/** * src/sequence_diagram/visitor/translation_unit_visitor.cc * * Copyright (c) 2021 Bartek Kryza <bkryza@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "translation_unit_visitor.h" #include "translation_unit_context.h" #include <cppast/cpp_function.hpp> #include <cppast/cpp_member_function.hpp> #include <cppast/visitor.hpp> namespace clanguml::sequence_diagram::visitor { translation_unit_visitor::translation_unit_visitor( cppast::cpp_entity_index &idx, clanguml::sequence_diagram::model::diagram &diagram, const clanguml::config::sequence_diagram &config) : ctx{idx, diagram, config} { } void translation_unit_visitor::process_activities(const cppast::cpp_function &e) { using clanguml::sequence_diagram::model::activity; using clanguml::sequence_diagram::model::diagram; using clanguml::sequence_diagram::model::message; using clanguml::sequence_diagram::model::message_t; using cppast::cpp_entity; using cppast::cpp_entity_kind; using cppast::cpp_function; using cppast::cpp_member_function; using cppast::cpp_member_function_call; using cppast::visitor_info; for (const auto &function_call_ptr : e.function_calls()) { const auto &function_call = static_cast<const cpp_member_function_call &>(*function_call_ptr); message m; m.type = message_t::kCall; if (!ctx.entity_index() .lookup_definition(function_call.get_caller_id()) .has_value()) continue; if (!ctx.entity_index() .lookup_definition(function_call.get_caller_method_id()) .has_value()) continue; if (!ctx.entity_index() .lookup_definition(function_call.get_callee_id()) .has_value()) continue; if (!ctx.entity_index() .lookup_definition(function_call.get_callee_method_id()) .has_value()) continue; const auto &caller = ctx.entity_index() .lookup_definition(function_call.get_caller_id()) .value(); m.from = cx::util::ns(caller) + "::" + caller.name(); if (!ctx.config().should_include(m.from)) continue; if (caller.kind() == cpp_entity_kind::function_t) m.from += "()"; m.from_usr = type_safe::get(function_call.get_caller_method_id()); const auto &callee = ctx.entity_index() .lookup_definition(function_call.get_callee_id()) .value(); m.to = cx::util::ns(callee) + "::" + callee.name(); if (callee.kind() == cpp_entity_kind::function_t) m.to += "()"; if (!ctx.config().should_include(m.to)) continue; m.to_usr = type_safe::get(function_call.get_callee_method_id()); const auto &callee_method = static_cast<const cppast::cpp_member_function &>( ctx.entity_index() .lookup_definition(function_call.get_callee_method_id()) .value()); m.message = callee_method.name(); m.return_type = cppast::to_string(callee_method.return_type()); if (ctx.diagram().sequences.find(m.from_usr) == ctx.diagram().sequences.end()) { activity a; a.usr = m.from_usr; a.from = m.from; ctx.diagram().sequences.insert({m.from_usr, std::move(a)}); } LOG_DBG("Adding sequence {} -{}()-> {}", m.from, m.message, m.to); ctx.diagram().sequences[m.from_usr].messages.emplace_back(std::move(m)); } } void translation_unit_visitor::operator()(const cppast::cpp_entity &file) { using cppast::cpp_entity; using cppast::cpp_entity_kind; using cppast::cpp_function; using cppast::cpp_member_function; using cppast::cpp_member_function_call; using cppast::visitor_info; cppast::visit(file, [&, this](const cpp_entity &e, visitor_info info) { if (e.kind() == cpp_entity_kind::function_t) { const auto &function = static_cast<const cpp_function &>(e); process_activities(function); } else if (e.kind() == cpp_entity_kind::member_function_t) { const auto &member_function = static_cast<const cpp_function &>(e); process_activities(member_function); } }); } }
33.409396
80
0.632583
[ "model" ]
b5c0a8ddcccbd1c74da0f95d400b959e4e9ae4a3
1,029
cpp
C++
qtor-core/src/FormattedDelegate.cpp
dmlys/qtor
dae69de53d23518f823d534339f7a4c696d9b3b4
[ "BSL-1.0" ]
null
null
null
qtor-core/src/FormattedDelegate.cpp
dmlys/qtor
dae69de53d23518f823d534339f7a4c696d9b3b4
[ "BSL-1.0" ]
null
null
null
qtor-core/src/FormattedDelegate.cpp
dmlys/qtor
dae69de53d23518f823d534339f7a4c696d9b3b4
[ "BSL-1.0" ]
null
null
null
#include <qtor/FormattedDelegate.hqt> #include <ext/utility.hpp> namespace qtor { void FormattedDelegate::InitStyle(QStyleOptionViewItem & option, const QModelIndex & index) const { m_model = dynamic_cast<const AbstractItemModel *>(index.model()); //QVariant fmtvar = m_model->property("formatter"); //QVariant metavar = m_model->property("meta"); //m_fmt = qvariant_cast<formatter *>(fmtvar); //m_meta = qvariant_cast<model_meta *>(metavar); m_fmt = m_model->GetFormatter().get(); m_meta = m_model->GetMeta().get(); m_cur_idx = index; base_type::InitStyle(option, index); } QString FormattedDelegate::displayText(const QVariant & value, const QLocale & locale) const { auto old_locale = m_fmt->get_locale(); m_fmt->set_locale(locale); auto view_index = m_cur_idx.column(); auto meta_index = m_model->ViewToMetaIndex(view_index); auto item_type = m_meta->item_type(meta_index); auto str = m_fmt->format_item_short(value, item_type); m_fmt->set_locale(old_locale); return str; } }
27.810811
98
0.725948
[ "model" ]
b5cc51f5b517eb5f9dd3fefda56c7c560270659c
513
hpp
C++
src/Graphics/shaderpreprocessor.hpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
2
2018-01-12T10:26:07.000Z
2018-02-02T19:03:00.000Z
src/Graphics/shaderpreprocessor.hpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
null
null
null
src/Graphics/shaderpreprocessor.hpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <functional> #include "shader.hpp" class ShaderPreprocessor { public: static std::string InterleaveLineDirectives(std::string shaderSource, std::string name); static std::string DoPreprocess(const std::string &shaderSource, const std::map<std::size_t, std::string> &filemap); static std::string DoPreprocess(const std::string &shaderSource, const std::map<std::size_t, std::string> &filemap, std::vector<std::size_t> &processedFiles); };
28.5
162
0.74269
[ "vector" ]
b5cf196b02ceac914af4548b0c5793a6c6cae71a
7,010
cpp
C++
src/ofApp.cpp
fonicartist/meshViewer
8d596decf240c5852a8814f0d4164710f518e112
[ "MIT" ]
1
2020-03-29T02:52:53.000Z
2020-03-29T02:52:53.000Z
src/ofApp.cpp
fonicartist/meshViewer
8d596decf240c5852a8814f0d4164710f518e112
[ "MIT" ]
null
null
null
src/ofApp.cpp
fonicartist/meshViewer
8d596decf240c5852a8814f0d4164710f518e112
[ "MIT" ]
null
null
null
// CS 116A Project 1 - Meshes // // by Victor La #include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ // Setup cameras cam.setDistance(10); cam.setPosition(glm::vec3(0, 0, 20)); cam.setNearClip(.1); cam.setFov(65.5); // approx equivalent to 28mm in 35mm format cam.disableMouseInput(); // default camera is the wide shot theCam = &cam; _currentCamera = 0; // Camera 2, a still camera looking from the front frontCam.setNearClip(.1); frontCam.setFov(70); frontCam.setPosition(glm::vec3(0, 5, 15)); frontCam.lookAt(glm::vec3(0, 5, 0)); // Camera 3, looks at the origin from the right side rightCam.setNearClip(.1); rightCam.setFov(70); rightCam.setPosition(glm::vec3(15, 10, 0)); rightCam.lookAt(glm::vec3(0, 5, 0)); // Camera 4, looks at the origin from the left side leftCam.setNearClip(.1); leftCam.setFov(70); leftCam.setPosition(glm::vec3(-15, 10, 0)); leftCam.lookAt(glm::vec3(0, 5, 0)); // Set up test geometry, an inverted pyramid with a triangular base testMesh.vertices.push_back(glm::vec3(-6, 6, 6)); testMesh.vertices.push_back(glm::vec3(6, 6, 6)); testMesh.vertices.push_back(glm::vec3(0, 6, -6)); testMesh.vertices.push_back(glm::vec3(0, -6, 0)); testMesh.faces.push_back(Face(0, 1, 2)); testMesh.faces.push_back(Face(1, 2, 3)); testMesh.faces.push_back(Face(2, 0, 3)); testMesh.faces.push_back(Face(0, 1, 3)); } //-------------------------------------------------------------- void ofApp::update(){ switch (_currentCamera) { case easy: theCam = &cam; break; case front: theCam = &frontCam; break; case right: theCam = &rightCam; break; case left: theCam = &leftCam; break; default: break; } } //-------------------------------------------------------------- void ofApp::draw(){ // Draw a black background ofBackground(ofColor::black); // Begin drawing in the camera theCam->begin(); ofPushMatrix(); // Draw world axis drawAxis(glm::vec3(0, 0, 0)); // Set drawing color to white ofSetColor(ofColor::white); // Draw test Mesh if enabled and another object hasn't been loaded yet if (bTestMeshVisible && !bObjLoaded) { // testMesh.draw(); // Draw sphere ofNoFill(); ofDrawSphere(glm::vec3(.5, .5, .5), 1); } else if (bObjLoaded) objMesh.draw(); // Draw selected vertex if (bSelected) { ofSetColor(ofColor::red); ofFill(); ofDrawSphere(intersectPoint, .04); } // End drawing in the camera ofPopMatrix(); theCam->end(); // Framerate string str; str += "Frame Rate: " + std::to_string(ofGetFrameRate()); ofSetColor(ofColor::white); ofDrawBitmapString(str, ofGetWindowWidth() - 205, 15); } // Draw an XYZ axis in RGB at world location for reference. // void ofApp::drawAxis(glm::vec3 location) { ofPushMatrix(); ofTranslate(location); ofSetLineWidth(1.0); // X Axis ofSetColor(ofColor(255, 0, 0)); ofDrawLine(ofPoint(0, 0, 0), ofPoint(1, 0, 0)); // Y Axis ofSetColor(ofColor(0, 255, 0)); ofDrawLine(ofPoint(0, 0, 0), ofPoint(0, 1, 0)); // Z Axis ofSetColor(ofColor(0, 0, 255)); ofDrawLine(ofPoint(0, 0, 0), ofPoint(0, 0, 1)); ofPopMatrix(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch (key) { case 'B': case 'b': bTestMeshVisible = !bTestMeshVisible; break; case 'C': case 'c': if (cam.getMouseInputEnabled()) cam.disableMouseInput(); else cam.enableMouseInput(); break; case 'F': case 'f': ofToggleFullscreen(); break; case 'T': case 't': changeCamera(); default: break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ bool bInteresects = false; glm::vec3 screen3dPoint = theCam->screenToWorld(glm::vec3(x, y, 0)); glm::vec3 rayOrigin = theCam->getPosition(); glm::vec3 rayDir = glm::normalize(screen3dPoint - rayOrigin); glm::vec3 intersectPos, intersectNormal; // Check intersection with sphere if OBJ file is not loaded if (!bObjLoaded) bInteresects = glm::intersectRaySphere(rayOrigin, rayDir, glm::vec3(.5, .5, .5), 1, intersectPoint, intersectNormal); // Check intersection if loaded obj file else bInteresects = objMesh.intersects(rayOrigin, rayDir, intersectPoint, intersectNormal); if (bInteresects) { cout << "Hit!" << endl; bSelected = true; } else { cout << "Missed!" << endl; bSelected = false; } cout << "3D screen position: " << screen3dPoint << endl; } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ objMesh = Mesh(); bool isQuad = false; string line, val, xstr, ystr, zstr, wstr; int verts = 0, faces = 0; // Load obj into an ifstream variable ifstream myfile(dragInfo.files.at(0)); ifstream file(dragInfo.files.at(0), ios::binary | ios::ate); // Loop through and read file while (getline(myfile, line)) { stringstream ss(line); ss >> val >> xstr >> ystr >> zstr >> wstr; // Read in vertices if (val.substr(0, val.find(' ')) == "v") { float x = stof(xstr), y = stof(ystr), z = stof(zstr); //cout << "Pushing vertex (" << x << ", " << y << ", " << z << ")\n"; verts += 3; objMesh.vertices.push_back(glm::vec3(x, y, z)); } // Read in faces else if (val[0] == 'f') { int x = stoi(xstr.substr(0, xstr.find('/'))) - 1, y = stoi(ystr.substr(0, ystr.find('/'))) - 1, z = stoi(zstr.substr(0, zstr.find('/'))) - 1, w; if (!wstr.empty()) { w = stoi(wstr.substr(0, wstr.find('/'))) - 1; objMesh.faces.push_back(Face(x, y, z, w)); } else objMesh.faces.push_back(Face(x, y, z)); //cout << "Pushing Triangle (" << x << ", " << y << ", " << z << ")\n"; faces++; } } bObjLoaded = true; cout << "Number of vertices: " << verts << endl; cout << "Number of faces: " << faces << endl; cout << "Size of model loaded: " << sizeof(objMesh) / 1000.0 << "kb" << endl; } // Swap between the two cameras based on enumeration // void ofApp::changeCamera() { _currentCamera++; if (_currentCamera == 4) _currentCamera = 0; }
24.089347
88
0.557204
[ "mesh", "geometry", "object", "model", "3d" ]
b5d55bb8c05d311d412028a20fb579249ace8599
1,005
cpp
C++
cpp-leetcode/leetcode401-binary-watch_bit_operation.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
45
2021-07-25T00:45:43.000Z
2022-03-24T05:10:43.000Z
cpp-leetcode/leetcode401-binary-watch_bit_operation.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
null
null
null
cpp-leetcode/leetcode401-binary-watch_bit_operation.cpp
yanglr/LeetCodeOJ
27dd1e4a2442b707deae7921e0118752248bef5e
[ "MIT" ]
15
2021-07-25T00:40:52.000Z
2021-12-27T06:25:31.000Z
#include<algorithm> #include<string> #include<vector> #include <iostream> using namespace std; class Solution { public: vector<string> readBinaryWatch(int turnedOn) { // h: 小时, m: 分钟. 00:00 -> 11:59 vector<string> res = {}; for (int h = 0; h < 12; h++) { for (int m = 0; m < 60; m++) { if (count1(h) + count1(m) == turnedOn) { string mStr = m < 10 ? "0" + to_string(m) : to_string(m); res.push_back(to_string(h) + ":" + mStr); } } } return res; } int count1(int n) { int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; } }; // Test int main() { Solution sol; int count = 6; auto res = sol.readBinaryWatch(count); for (auto str : res) cout << str << endl; return 0; }
20.9375
77
0.41592
[ "vector" ]
b5d8ec898c8a4f1a9060908b22a72a36111001bf
8,061
cpp
C++
generalizedassignmentsolver/instance.cpp
fontanf/GAP
4fea39fbd34548a9820dd5c426580920d8d4b873
[ "MIT" ]
1
2019-07-22T16:29:12.000Z
2019-07-22T16:29:12.000Z
generalizedassignmentsolver/instance.cpp
fontanf/gap
4fea39fbd34548a9820dd5c426580920d8d4b873
[ "MIT" ]
null
null
null
generalizedassignmentsolver/instance.cpp
fontanf/gap
4fea39fbd34548a9820dd5c426580920d8d4b873
[ "MIT" ]
null
null
null
#include "generalizedassignmentsolver/instance.hpp" #include "generalizedassignmentsolver/solution.hpp" using namespace generalizedassignmentsolver; Instance::Instance(AgentIdx m): capacities_(m, 0) { } void Instance::set_capacities(const std::vector<Weight>& t) { for (AgentIdx i = 0; i < (AgentIdx)t.size(); ++i) set_capacity(i, t[i]); } void Instance::add_item() { ItemIdx j = items_.size(); items_.push_back({}); items_[j].j = j; items_[j].alternatives.resize(number_of_agents()); for (AgentIdx i = 0; i < number_of_agents(); ++i) { items_[j].alternatives[i].j = j; items_[j].alternatives[i].i = i; } } void Instance::add_item(const std::vector<std::pair<Weight, Cost>>& a) { ItemIdx j = number_of_items(); add_item(); for (AgentIdx i = 0; i < (AgentIdx)a.size(); ++i) set_alternative(j, i, a[i].first, a[i].second); } void Instance::set_alternative(ItemIdx j, AgentIdx i, Weight weight, Cost cost) { // Update the weight and the cost of the alternative. items_[j].alternatives[i].weight = weight; items_[j].alternatives[i].cost = cost; // Update the total weight of the item. items_[j].total_weight += weight; // Update the total cost of the item. items_[j].total_cost += cost; // Update the minimum costl of the item. if (items_[j].i_minimum_cost != -1 && items_[j].minimum_cost > cost) sum_of_minimum_costs_ -= items_[j].minimum_cost; if (items_[j].i_minimum_cost == -1 || items_[j].minimum_cost > cost) { items_[j].i_minimum_cost = i; items_[j].minimum_cost = cost; sum_of_minimum_costs_ += cost; } // Update the minimum weight of the item. if (items_[j].i_minimum_weight == -1 || items_[j].minimum_weight > weight) { items_[j].i_minimum_weight = i; items_[j].minimum_weight = weight; } // Update the maximum cost of the item. if (items_[j].maximum_cost < cost) { items_[j].i_maximum_cost = i; items_[j].maximum_cost = cost; } // Update to maximum weight of the item. if (items_[j].maximum_weight < weight) { items_[j].i_maximum_weight = i; items_[j].maximum_weight = weight; } // Update the maximum cost of the instance. if (maximum_cost_ < cost) maximum_cost_ = cost; // Update the maximum weight of the instance. if (maximum_weight_ < weight) maximum_weight_ = weight; // Update the total cost of the instance. total_cost_ += cost; } void Instance::set_optimal_solution(Solution& solution) { optimal_solution_ = std::make_unique<Solution>(solution); } void Instance::clear() { name_ = ""; items_.clear(); capacities_.clear(); maximum_cost_ = 0; total_cost_ = 0; maximum_weight_ = 0; sum_of_minimum_costs_ = 0; optimal_solution_ = NULL; } Instance::Instance(std::string instance_path, std::string format): name_(instance_path) { std::ifstream file(instance_path); if (!file.good()) { throw std::runtime_error( "Unable to open file \"" + instance_path + "\"."); } if (format == "orlibrary") { read_orlibrary(file); } else if (format == "standard") { read_standard(file); } else { throw std::invalid_argument( "Unknown instance format \"" + format + "\"."); } file.close(); } void Instance::read_orlibrary(std::ifstream& file) { ItemIdx n; AgentIdx m; file >> m >> n; capacities_.resize(m); items_.reserve(n); for (ItemPos j = 0; j < n; ++j) add_item(); for (AgentIdx i = 0; i < m; ++i) for (ItemPos j = 0; j < n; ++j) file >> items_[j].alternatives[i].cost; for (AgentIdx i = 0; i < m; ++i) for (ItemPos j = 0; j < n; ++j) file >> items_[j].alternatives[i].weight; for (AgentIdx i = 0; i < m; ++i) for (ItemPos j = 0; j < n; ++j) set_alternative(j, i, items_[j].alternatives[i].weight, items_[j].alternatives[i].cost); Weight t = -1; for (AgentIdx i = 0; i < m; ++i) { file >> t; set_capacity(i, t); } } void Instance::read_standard(std::ifstream& file) { ItemIdx n; AgentIdx m; file >> m >> n; capacities_.resize(m); Weight t = -1; for (AgentIdx i = 0; i < m; ++i) { file >> t; set_capacity(i, t); } items_.reserve(n); Weight w; Cost c; for (ItemPos j = 0; j < n; ++j) { add_item(); for (AgentIdx i = 0; i < m; ++i) { file >> w >> c; set_alternative(j, i, w, c); } } } Instance::~Instance() { } Instance::Instance(const Instance& instance): name_(instance.name_), items_(instance.items_), capacities_(instance.capacities_), maximum_cost_(instance.maximum_cost_), total_cost_(instance.total_cost_), maximum_weight_(instance.maximum_weight_), sum_of_minimum_costs_(instance.sum_of_minimum_costs_) { if (instance.optimal_solution_ != NULL) { optimal_solution_ = std::make_unique<Solution>(*this); *optimal_solution_ = *instance.optimal_solution_; } } Instance& Instance::operator=(const Instance& instance) { if (this != &instance) { name_ = instance.name_; items_ = instance.items_; capacities_ = instance.capacities_; maximum_cost_ = instance.maximum_cost_; total_cost_ = instance.total_cost_; maximum_weight_ = instance.maximum_weight_; sum_of_minimum_costs_ = instance.sum_of_minimum_costs_; if (instance.optimal_solution_ != NULL) { optimal_solution_ = std::make_unique<Solution>(*this); *optimal_solution_ = *instance.optimal_solution_; } } return *this; } Cost Instance::optimum() const { return optimal_solution()->cost(); } std::ostream& generalizedassignmentsolver::operator<<(std::ostream& os, const Alternative& alternative) { os << "(" << alternative.i << " " << alternative.cost << " " << alternative.weight << " " << alternative.efficiency() << ")"; return os; } std::ostream& generalizedassignmentsolver::operator<<(std::ostream& os, const Instance& instance) { os << "m " << instance.number_of_agents() << " n " << instance.number_of_items() << std::endl; os << "c"; for (AgentIdx i = 0; i < instance.number_of_agents(); ++i) os << " " << instance.capacity(i); os << std::endl; for (ItemPos j = 0; j < instance.number_of_items(); ++j) { os << j << ": " << std::flush; os << std::endl; } return os; } void Instance::write(std::string filename) { std::ofstream file(filename); file << number_of_agents() << " " << number_of_items() << std::endl; for (AgentIdx i = 0; i < number_of_agents(); ++i) { for (ItemIdx j = 0; j < number_of_items(); ++j) file << item(j).alternatives[i].cost << " "; file << std::endl; } for (AgentIdx i = 0; i < number_of_agents(); ++i) { for (ItemIdx j = 0; j < number_of_items(); ++j) file << item(j).alternatives[i].weight << " "; file << std::endl; } for (AgentIdx i = 0; i < number_of_agents(); ++i) file << capacity(i) << " "; file << std::endl; file.close(); } void generalizedassignmentsolver::init_display( const Instance& instance, optimizationtools::Info& info) { FFOT_VER(info, "=====================================" << std::endl << " Generalized Assignment Solver " << std::endl << "=====================================" << std::endl << std::endl << "Instance" << std::endl << "--------" << std::endl << "Number of items: " << instance.number_of_items() << std::endl << "Number of agents: " << instance.number_of_agents() << std::endl << std::endl); }
29.636029
103
0.575983
[ "vector" ]
b5e1a50580502934e46bb2765e4d94e47d768e35
1,093
hpp
C++
include/LTRE/core/primitive.hpp
yumcyaWiz/LTRE
dd65125bb133c345a10a3cf3d4c2a330b38ee82b
[ "MIT" ]
3
2021-08-15T08:59:21.000Z
2021-11-27T08:23:37.000Z
include/LTRE/core/primitive.hpp
yumcyaWiz/LTRE
dd65125bb133c345a10a3cf3d4c2a330b38ee82b
[ "MIT" ]
null
null
null
include/LTRE/core/primitive.hpp
yumcyaWiz/LTRE
dd65125bb133c345a10a3cf3d4c2a330b38ee82b
[ "MIT" ]
1
2021-12-09T15:43:57.000Z
2021-12-09T15:43:57.000Z
#ifndef _LTRE_PRIMITIVE_H #define _LTRE_PRIMITIVE_H #include <memory> #include "LTRE/core/material.hpp" #include "LTRE/light/area-light.hpp" #include "LTRE/shape/shape.hpp" namespace LTRE { class Primitive { private: std::shared_ptr<Shape> shape; std::shared_ptr<Material> material; std::shared_ptr<AreaLight> areaLight; public: Primitive(const std::shared_ptr<Shape>& shape, const std::shared_ptr<Material>& material, const std::shared_ptr<AreaLight>& areaLight = nullptr); std::shared_ptr<AreaLight> getAreaLightPtr() const; AABB aabb() const; bool intersect(const Ray& ray, IntersectInfo& info) const; bool intersectP(const Ray& ray) const; Vec3 evaluateBSDF(const Vec3& wo, const Vec3& wi, const SurfaceInfo& info) const; Vec3 sampleBSDF(const Vec3& wo, const SurfaceInfo& info, Sampler& sampler, Vec3& wi, float& pdf) const; bool hasArealight() const; Vec3 Le(const Vec3& wi, const SurfaceInfo& info) const; Vec3 baseColor(const SurfaceInfo& info) const; }; } // namespace LTRE #endif
25.418605
76
0.699909
[ "shape" ]
b5ea7cf4739ddc22fa86c60efe587379a2f7ca52
1,392
cpp
C++
chapter_13/pp230.cpp
hbatagelo/a_tour_of_cpp
11b177ff9ae25df8945c2a7b01a1abfa6e8f3f92
[ "Unlicense" ]
null
null
null
chapter_13/pp230.cpp
hbatagelo/a_tour_of_cpp
11b177ff9ae25df8945c2a7b01a1abfa6e8f3f92
[ "Unlicense" ]
null
null
null
chapter_13/pp230.cpp
hbatagelo/a_tour_of_cpp
11b177ff9ae25df8945c2a7b01a1abfa6e8f3f92
[ "Unlicense" ]
null
null
null
#include <algorithm> #include <iostream> #include <ostream> #include <string> #include <utility> #include <vector> struct Record { std::string name; int number{}; }; // Compare names auto less = [](const Record& r1, const Record& r2) { return r1.name < r2.name; }; std::ostream& operator<<(std::ostream& stream, const Record& r) { return stream << r.name; } // Assume that v is sorted on its "name" field void f(const std::vector<Record>& v) { auto er = std::equal_range(v.begin(), v.end(), Record{"Reg"}, less); // Print all equal records for (auto p = er.first; p != er.second; ++p) { std::cout << *p << '\n'; // Assume that << is defined for Record } } // Using structured binding // Assume that v is sorted on its "name" field void f2(const std::vector<Record>& v) { auto [first, last] = std::equal_range(v.begin(), v.end(), Record{"Reg"}, less); // Print all equal records for (auto p = first; p != last; ++p) { std::cout << *p << '\n'; // Assume that << is defined for Record } } //////////////////////////////////////////////////////////////////////////////// int main() { std::vector<Record> v{{"David Hume", 123456}, {"Reg", 42}, {"Karl Popper", 234567}, {"Bertrand Arthur William Russell", 345678}}; std::sort(v.begin(), v.end(), less); f(v); f2(v); }
24.857143
80
0.543822
[ "vector" ]
b5eb9c766fcf1bc60a76ba762de84c92b80211a2
5,169
cpp
C++
Src/ModelSpecificAnalysis/plotTXtoLe.cpp
AspdenGroup/PeleAnalysis_Aspden
4259efa97a65a646a4e1bc3493cd9dae1e7024c5
[ "BSD-3-Clause-LBNL" ]
4
2019-04-24T13:33:35.000Z
2021-08-24T07:11:22.000Z
Src/ModelSpecificAnalysis/plotTXtoLe.cpp
AspdenGroup/PeleAnalysis_Aspden
4259efa97a65a646a4e1bc3493cd9dae1e7024c5
[ "BSD-3-Clause-LBNL" ]
4
2020-02-25T01:58:46.000Z
2022-02-01T20:22:49.000Z
Src/ModelSpecificAnalysis/plotTXtoLe.cpp
AspdenGroup/PeleAnalysis_Aspden
4259efa97a65a646a4e1bc3493cd9dae1e7024c5
[ "BSD-3-Clause-LBNL" ]
6
2018-11-05T11:53:20.000Z
2021-03-22T10:44:54.000Z
#include <string> #include <iostream> #include <set> #include <AMReX_ParmParse.H> #include <AMReX_MultiFab.H> #include <AMReX_DataServices.H> #include <AMReX_BCRec.H> #include <AMReX_Interpolater.H> #include <WritePlotFile.H> #include <AMReX_BLFort.H> #include <mechanism.h> #include <chemistry_file.H> #include <util.H> #include <util_F.H> #include <Transport_F.H> #include <Fuego_EOS.H> using namespace amrex; using namespace analysis_util; static void print_usage (int, char* argv[]) { std::cerr << "usage:\n"; std::cerr << argv[0] << " infile infile=f1 [options] \n\tOptions:\n"; exit(1); } std::string getFileRoot(const std::string& infile) { vector<std::string> tokens = Tokenize(infile,std::string("/")); return tokens[tokens.size()-1]; } int main (int argc, char* argv[]) { Initialize(argc,argv); { if (argc < 2) print_usage(argc,argv); ParmParse pp; if (pp.contains("help")) print_usage(argc,argv); if (pp.contains("verbose")) AmrData::SetVerbose(true); std::string plotFileName; pp.get("infile",plotFileName); DataServices::SetBatchMode(); Amrvis::FileType fileType(Amrvis::NEWPLT); DataServices dataServices(plotFileName, fileType); if( ! dataServices.AmrDataOk()) { DataServices::Dispatch(DataServices::ExitRequest, NULL); // ^^^ this calls ParallelDescriptor::EndParallel() and exit() } AmrData& amrData = dataServices.AmrDataRef(); init_mech(); int finestLevel = amrData.FinestLevel(); pp.query("finestLevel",finestLevel); int Nlev = finestLevel + 1; int idXin = -1; int idTin = -1; int idRin = -1; Vector<std::string> spec_names = GetSpecNames(); const Vector<std::string>& plotVarNames = amrData.PlotVarNames(); const std::string spName= "X(" + spec_names[0] + ")"; const std::string TName = "temp"; const std::string RName = "density"; for (int i=0; i<plotVarNames.size(); ++i) { if (plotVarNames[i] == spName) idXin = i; if (plotVarNames[i] == TName) idTin = i; if (plotVarNames[i] == RName) idRin = i; } if (idXin<0 || idTin<0 || idRin<0) Print() << "Cannot find required data in pltfile" << std::endl; const int nCompIn = NUM_SPECIES + 2; const int idLeout = 0; const int nCompOut = idLeout + NUM_SPECIES; Vector<std::string> outNames(nCompOut); Vector<std::string> inNames(nCompIn); Vector<int> destFillComps(nCompIn); const int idXlocal = 0; // Xs start here const int idTlocal = NUM_SPECIES; // T starts here const int idRlocal = NUM_SPECIES+1; // R starts here for (int i=0; i<NUM_SPECIES; ++i) { destFillComps[i] = idXlocal + i; inNames[i] = "X(" + spec_names[i] + ")"; outNames[idLeout + i] = "Le(" + spec_names[i] + ")"; } destFillComps[idTlocal] = idTlocal; destFillComps[idRlocal] = idRlocal; inNames[idTlocal] = TName; inNames[idRlocal] = RName; Vector<std::unique_ptr<MultiFab>> outdata(Nlev); const int nGrow = 0; int b[3] = {1, 1, 1}; for (int lev=0; lev<Nlev; ++lev) { const BoxArray ba = amrData.boxArray(lev); const DistributionMapping dm(ba); outdata[lev].reset(new MultiFab(ba,dm,nCompOut,nGrow)); MultiFab indata(ba,dm,nCompIn,nGrow); Print() << "Reading data for level " << lev << std::endl; amrData.FillVar(indata,lev,inNames,destFillComps); Print() << "Data has been read for level " << lev << std::endl; for (MFIter mfi(indata,TilingIfNotGPU()); mfi.isValid(); ++mfi) { const Box& bx = mfi.tilebox(); Array4<Real> const& X = indata.array(mfi); Array4<Real> const& T = indata.array(mfi); Array4<Real> const& R = indata.array(mfi); Array4<Real> const& Le = (*outdata[lev]).array(mfi); AMREX_PARALLEL_FOR_3D ( bx, i, j, k, { Real Yl[NUM_SPECIES]; Real Xl[NUM_SPECIES]; Real rhoDl[NUM_SPECIES]; for (int n=0; n<NUM_SPECIES; ++n) { Xl[n] = X(i,j,k,idXlocal+n); } CKXTY(Xl,Yl); Real lambda; Real xi; Real mu; get_transport_coeffs(b, b, Yl, b, b, &T(i,j,k,idTlocal), b, b, &R(i,j,k,idRlocal), b, b, rhoDl, b, b, &mu, b, b, &xi, b, b, &lambda, b, b); Real Cpmix; CKCPBS(&T(i,j,k,idTlocal),Yl,&Cpmix); for (int n=0; n<NUM_SPECIES; ++n) { Le(i,j,k,idLeout+n) = rhoDl[n] / (lambda / Cpmix); } }); } Print() << "Derive finished for level " << lev << std::endl; } std::string outfile(getFileRoot(plotFileName) + "_Le"); Print() << "Writing new data to " << outfile << std::endl; const bool verb = false; WritePlotFile(GetVecOfPtrs(outdata),amrData,outfile,verb,outNames); } Finalize(); return 0; }
29.706897
71
0.568775
[ "vector" ]
b5edf5ed2247eab883d3ede3fc078054b25a29d8
827
hpp
C++
Includes/BabaIsAgent/Network/TrtNetwork.hpp
JYPark09/BabaIsAgent
69afdc14af3e7a131b31600dcf13858df7c30c5e
[ "MIT" ]
25
2019-08-04T13:54:48.000Z
2021-01-25T06:28:02.000Z
Includes/BabaIsAgent/Network/TrtNetwork.hpp
JYPark09/BabaIsAgent
69afdc14af3e7a131b31600dcf13858df7c30c5e
[ "MIT" ]
24
2019-08-05T04:58:28.000Z
2021-01-16T15:56:03.000Z
Includes/BabaIsAgent/Network/TrtNetwork.hpp
JYPark09/BabaIsAgent
69afdc14af3e7a131b31600dcf13858df7c30c5e
[ "MIT" ]
3
2019-08-05T16:57:45.000Z
2020-01-05T12:54:32.000Z
#ifndef BABA_IS_AGENT_TRT_NETWORK_HPP #define BABA_IS_AGENT_TRT_NETWORK_HPP #ifdef USE_TENSORRT #include <BabaIsAgent/Common/Config.hpp> #include <BabaIsAgent/Network/Network.hpp> #include <NvInfer.h> namespace BabaIsAgent::Network { class TrtNetwork final : public Network { public: TrtNetwork(int gpuId); ~TrtNetwork(); void Initialize(const std::string& weightFileName) override; void Evaluate(const std::vector<Tensor>& inputs, std::vector<Tensor>& policy, Tensor& value) override; private: nvinfer1::IRuntime* runtime_{ nullptr }; nvinfer1::ICudaEngine* engine_{ nullptr }; nvinfer1::IExecutionContext* context_{ nullptr }; std::vector<void*> buffers_; int gpuId_; }; } // namespace BabaIsAgent::Network #endif // USE_TENSORRT #endif // BABA_IS_AGENT_TRT_NETWORK_HPP
21.763158
71
0.738815
[ "vector" ]
b5f90d55b1b9bc6851fd42d8b099e8a04e218b11
2,596
hpp
C++
include/locic/Support/MakeString.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
80
2015-02-19T21:38:57.000Z
2016-05-25T06:53:12.000Z
include/locic/Support/MakeString.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
8
2015-02-20T09:47:20.000Z
2015-11-13T07:49:17.000Z
include/locic/Support/MakeString.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
6
2015-02-20T11:26:19.000Z
2016-04-13T14:30:39.000Z
#ifndef LOCIC_MAKESTRING_HPP #define LOCIC_MAKESTRING_HPP #include <map> #include <memory> #include <string> #include <vector> namespace locic{ std::string makeStringImpl(const char * format, ...); template <typename... Args> std::string makeString(const char * format, const Args&... args) { return makeStringImpl(format, args...); } template <typename T> inline std::string typeToString(const T& value) { return value.toString(); } template <typename T> inline std::string typeToString(T* const value) { return value->toString(); } template <typename T> inline std::string typeToString(const std::unique_ptr<T>& value) { return value->toString(); } inline std::string typeToString(const std::string& value) { return value; } template <typename T> std::string makeArrayString(const T& array){ auto s = makeString("Array [size = %llu] {", static_cast<unsigned long long>(array.size())); for(size_t i = 0; i < array.size(); i++){ if(i > 0) s += ", "; s += makeString("%llu: %s", static_cast<unsigned long long>(i), array.at(i).toString().c_str()); } s += "}"; return s; } template <typename T> std::string makeArrayPtrString(const T& array){ auto s = makeString("Array [size = %llu] {", static_cast<unsigned long long>(array.size())); for(size_t i = 0; i < array.size(); i++){ if(i > 0) s += ", "; s += makeString("%llu: %s", static_cast<unsigned long long>(i), array.at(i)->toString().c_str()); } s += "}"; return s; } template <typename T> std::string makeMapString(const T& map){ auto s = makeString("Map [size = %llu] {", static_cast<unsigned long long>(map.size())); bool isFirst = true; for (const auto& pair: map) { if (isFirst) { isFirst = false; } else { s += ", "; } s += makeString("%s: %s", typeToString(pair.first).c_str(), typeToString(pair.second).c_str()); } s += "}"; return s; } template <typename T> std::string makeNameArrayString(const T& array){ std::string s = makeString("Array[size = %llu]{", static_cast<unsigned long long>(array.size())); for(size_t i = 0; i < array.size(); i++){ if(i > 0) s += ", "; s += makeString("%llu: %s", static_cast<unsigned long long>(i), array.at(i)->nameToString().c_str()); } s += "}"; return s; } std::string escapeString(const std::string& string); std::string formatMessage(const std::string& message); std::vector<std::string> splitString(const std::string& str, const std::string& separator); } #endif
21.633333
92
0.615948
[ "vector" ]
bd0c537aea1497c89a523e6773ae0f524facf7e0
1,875
cpp
C++
util.cpp
dhruvsawhney/SystemMonitor
d2717102d790caf9d2da39218d9a3a84f69e0c32
[ "MIT" ]
null
null
null
util.cpp
dhruvsawhney/SystemMonitor
d2717102d790caf9d2da39218d9a3a84f69e0c32
[ "MIT" ]
null
null
null
util.cpp
dhruvsawhney/SystemMonitor
d2717102d790caf9d2da39218d9a3a84f69e0c32
[ "MIT" ]
null
null
null
#include "util.h" #include <sstream> #include <fstream> #include <iterator> string Util::convertToTime (long int input_seconds){ long minutes = input_seconds / 60; long hours = minutes / 60; long seconds = int(input_seconds%60); minutes = int(minutes%60); string result = std::to_string(hours) + ":" + std::to_string(minutes) + ":" + std::to_string(seconds); return result; } // constructing string for given percentage // 50 bars is uniformly streched 0 - 100 % // meaning: every 2% is one bar(|) string Util::getProgressBar(string percent){ string result = "0%% "; int _size= 50; int boundaries; try { boundaries = (stof(percent)/100)*_size; } catch (...){ boundaries = 0; } for(int i=0;i<_size;i++){ if(i<=boundaries){ result +="|"; } else{ result +=" "; } } result +=" " + percent.substr(0,5) + " /100%%"; return result; } // wrapper for creating streams void Util::getStream(string path, std::ifstream& stream){ stream.open (path, std::ifstream::in); if (!stream && !stream.is_open()){ stream.close(); throw std::runtime_error("Non - existing PID"); } } bool Util::isNumber(string& text){ for (int i = 0; i < text.length(); ++i) { if (!isdigit(text[i])) { return false; } } return true; } vector<vector<string>> Util::fileContent(string path){ vector<vector<string>> contentList; std::ifstream file; Util::getStream(path, file); string result; string line; while(getline(file, line)){ std::istringstream iss(line); std::vector<string> words((std::istream_iterator<std::string>(iss)), std::istream_iterator<std::string>()); contentList.push_back(words); } return contentList; }
22.590361
102
0.583467
[ "vector" ]
bd0cfc04edbc95088bff92bce7ba2c4cbc994550
12,453
cpp
C++
lib/stock.cpp
EpicVoyage/rsiscan
0ab639f70b71115e478a26e33fb7c7f9e231608f
[ "MIT" ]
null
null
null
lib/stock.cpp
EpicVoyage/rsiscan
0ab639f70b71115e478a26e33fb7c7f9e231608f
[ "MIT" ]
null
null
null
lib/stock.cpp
EpicVoyage/rsiscan
0ab639f70b71115e478a26e33fb7c7f9e231608f
[ "MIT" ]
1
2018-06-21T04:13:44.000Z
2018-06-21T04:13:44.000Z
#include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <algorithm> #include <chrono> #include <boost/log/trivial.hpp> #include <boost/date_time/gregorian/gregorian.hpp> #include "lib/comma_separated_values.h" #include "lib/stock.h" /** * Class setup. */ stockinfo::stockinfo(const stockinfo &init): orig_filename(nullptr), dirty(false) { copy(init); } /** * Class clean-up. */ stockinfo::~stockinfo() { long x, sz = data.size();; for (x = 0; x < sz; x++) { free(data[x].date); } if (orig_filename != nullptr) { free(orig_filename); } } /** * Load a CSV file into the data struct. */ bool stockinfo::load_csv(const char *filename) { comma_separated_values csv; struct stock *s; struct stat buf; char *tmp, *ret = nullptr; long x, rows; FILE *re; // Ensure that the file exists before we load it. if (stat(filename, &buf)) { BOOST_LOG_TRIVIAL(trace) << "Unable to load CSV file: " << filename; return false; } // Prep for the save_csv command. x = strlen(filename); orig_filename = (char *)malloc(x + 1); strcpy(orig_filename, filename); dirty = false; BOOST_LOG_TRIVIAL(trace) << "Reading stock data from: " << filename; // Load the entire file into memory. re = fopen(filename, "r"); tmp = (char *)malloc(2048); while (fgets(tmp, 2048, re) != NULL) { if (ret == nullptr) { ret = (char *)malloc(strlen(tmp) + 1); *ret = '\0'; } else ret = (char *)realloc(ret, strlen(ret) + strlen(tmp) + 1); strcat(ret, tmp); } // File cleanup. fclose(re); free(tmp); // Parse any CSV data in the file. if (ret != nullptr) { s = csv.parse(ret, &rows); for (x = 0; x < rows; x++) { s[x].timestamp = parse_csv_time(s[x].date); data.push_back(s[x]); } // Free the file memory. free(ret); } uniq(); BOOST_LOG_TRIVIAL(trace) << "Loaded records: " << data.size(); return true; } /** * Save the data struct as CSV data. * * @param filename. Optional if load_csv() was called first. * @return boolean. True if save was successful. */ bool stockinfo::save_csv(const char *filename) { const char *fn = (filename == nullptr) ? orig_filename : filename; long x, sz; FILE *wr; // We cannot save unless we have a filename. if (fn == nullptr) { BOOST_LOG_TRIVIAL(trace) << "No filename provided. Unable to save."; return false; } // Do not re-save if nothing has changed. if (!dirty && (strcmp(fn, orig_filename) == 0)) { BOOST_LOG_TRIVIAL(trace) << "No changes since we read the file. Skipping save operation."; return false; } BOOST_LOG_TRIVIAL(trace) << "Writing stock data to: " << filename; // Prepare to write. nosig(); wr = fopen(filename, "w"); sz = data.size(); // Write the data. for (x = 0; x < sz; x++) { if (data[x].date) fprintf(wr, "%s,%g,%g,%g,%g,%li\n", data[x].date, data[x].open, data[x].high, data[x].low, data[x].close, data[x].volume); } // Clean up. fclose(wr); sig(); return true; } /** * Insert stock element at the desired pos. Moves any later elements up by 1, which can be slow. * * @param struct stock s The element to insert. * @param long pos The place to insert s (default: 0). * @return A pointer to this class instance. */ stockinfo &stockinfo::insert_at(const struct stock s, const long pos) { struct stock tmp; // Make our own copy of the data. memcpy(&tmp, &s, sizeof(s)); if (s.date != nullptr) { tmp.date = (char *)malloc(strlen(s.date)); strcpy(tmp.date, s.date); // Parse the date into a timestamp, if needed. tmp.timestamp = parse_csv_time(tmp.date); } // Retrieve an iterator that points to our insertion point. std::vector<struct stock>::iterator p = data.begin(); p += pos; // Insert tmp. data.insert(p, tmp); // The data structure should be saved. dirty = true; return *this; } /** * Return the number of items in the data struct. */ const long stockinfo::length() const { return data.size(); } const long stockinfo::length() { return data.size(); } /** * Remove the first element and return it. */ struct stock stockinfo::shift() { struct stock ret; if (data.size() > 0) { memcpy(&ret, &data[0], sizeof(data[0])); if (data[0].date != nullptr) { ret.date = (char *)malloc(strlen(data[0].date)); strcpy(ret.date, data[0].date); } } return ret; } /** * Allow us to read data from the data struct. * * @param index The desired data point. * @return The data point requested. nullptr if index does not exist. */ const struct stock *stockinfo::operator [](const long index) const { if (index < 0 || index >= data.size()) { if (data.size() == 0) { BOOST_LOG_TRIVIAL(trace) << "Tried to access record " << index << " but no records exist!"; } else { BOOST_LOG_TRIVIAL(trace) << "Tried to access record " << index << " but highest record is " << data.size() - 1 << "!"; } return nullptr; } return &data[index]; } const struct stock *stockinfo::operator [](const long index) { // Scott Meyers on reducing code duplication. https://stackoverflow.com/a/123995/850782 return const_cast<struct stock *>(static_cast<const stockinfo &>(*this)[index]); } /** * Add a struct stock to the end of the data element. * * @return Pointer to the current class instance. */ stockinfo &stockinfo::operator +=(const struct stock s) { struct stock tmp; // Make our own copy of the data. memcpy(&tmp, &s, sizeof(s)); if (s.date != nullptr) { tmp.date = (char *)malloc(strlen(s.date)); strcpy(tmp.date, s.date); // Parse the date into a timestamp, if needed. tmp.timestamp = parse_csv_time(tmp.date); } // Insert tmp. data.push_back(tmp); // The data structure should be saved. dirty = true; return *this; } stockinfo &stockinfo::operator =(const stockinfo &s) { copy(s); return *this; } /** * Sort the data structure by timestamp, then check for duplicate timestamps. * * @return Pointer to the current class instance. */ stockinfo &stockinfo::uniq() { long x, length; // The data must be sorted by timestamp before we can check for duplicate timestamps. sort(); // Check neighbors for duplicate timestamps. length = data.size() - 1; for (x = 0; x < length; x++) { // Determine if the next element matches the current timestamp. if (data[x].timestamp == data[x+1].timestamp) { BOOST_LOG_TRIVIAL(info) << "Removing duplicate: " << x; // Remove the duplicate element. std::vector<struct stock>::iterator p = data.begin(); p += x; data.erase(p); // We have modified the data structure. dirty = true; // Decrease the run length since we removed an element. length--; } } return *this; } /** * Sort the data structure by timestamp, in descending order. * * @todo Should we update set the dirty flag? * @return Pointer to the current class instance. */ stockinfo &stockinfo::sort() { std::sort(data.begin(), data.end(), [](const auto& lhs, const auto& rhs) { return lhs.timestamp > rhs.timestamp; }); return *this; } /** * NOTE: data must be sorted before this is called. */ template<class T> stockinfo stockinfo::rollup_iterator(T &iterator, int number) { boost::gregorian::date d; bool add = false, init = true; struct stock tmp; struct tm last; long x, length; stockinfo ret; boost::gregorian::date current_date; length = data.size(); BOOST_LOG_TRIVIAL(info) << "Rollup size: " << length; // Go back to the last [number iterator period] on record. if (length > 0) { localtime_r(&data[0].timestamp, &last); current_date = boost::gregorian::date(last.tm_year + 1900, last.tm_mon + 1, last.tm_mday); x = 0; while (iterator > current_date) { multi_decrement(iterator, number); x++; } BOOST_LOG_TRIVIAL(info) << "First date is " << (x * number) << " periods back."; } // Loop through the dates and collect them. for (x = 0; x < length; x++) { localtime_r(&data[x].timestamp, &last); current_date = boost::gregorian::date(last.tm_year + 1900, last.tm_mon + 1, last.tm_mday); // Is it time to switch to decrement the iterator? if (iterator >= current_date) { BOOST_LOG_TRIVIAL(info) << "Decrement iterator."; multi_decrement(iterator, number); init = true; // New week. if (add) ret += tmp; } if (init) { // Re-set the object data for the new week.. tmp.open = data[x].open; tmp.high = data[x].high; tmp.low = data[x].low; tmp.close = data[x].close; tmp.volume = data[x].volume; BOOST_LOG_TRIVIAL(info) << "Set high: " << data[x].high << ", low: " << data[x].low << ", volume = " << data[x].volume; init = false; } else { // Update the existing week. if (data[x].high > tmp.high) { BOOST_LOG_TRIVIAL(info) << "Bumped high to: " << data[x].high; tmp.high = data[x].high; } if (data[x].low < tmp.low) { BOOST_LOG_TRIVIAL(info) << "Bumped low to: " << data[x].low; tmp.low = data[x].low; } BOOST_LOG_TRIVIAL(info) << "Added volume: " << data[x].volume; tmp.open = data[x].open; tmp.volume += data[x].volume; } // Capture the earliest day of the week. tmp.timestamp = data[x].timestamp; tmp.date = data[x].date; // Start saving after the first run. add = true; } if (add) ret += tmp; return ret; } template<class T> T &stockinfo::multi_decrement(T &iterator, int number) { for (int x = 0; x < number; x++) { --iterator; } return iterator; } /** * Roll daily data up into larger time periods. Sorts the data first. * * @todo Allow choice of weekly alignment day. * * @param int number. Default: 1 * @param timeperiods period. Default: week. * @param bool align_week Default: false. If set to true, iterate on Sundays. * @return New stockinfo object. */ stockinfo stockinfo::rollup(int number, timeperiods period, bool align_week) { if (data.size() < 2) { return *this; } // This only works if the data is in order. It does not necessarily have to be unique... sort(); struct tm first; localtime_r(&data[0].timestamp, &first); boost::gregorian::date d(first.tm_year + 1900, first.tm_mon + 1, first.tm_mday); if (align_week) { BOOST_LOG_TRIVIAL(info) << "Boost Sunday alignment start: " << d; auto at_saturday = boost::gregorian::greg_weekday(boost::gregorian::Sunday); d = next_weekday(d, at_saturday); BOOST_LOG_TRIVIAL(info) << "Boost Sunday alignment finish: " << d; } boost::gregorian::day_iterator itr_day(d); boost::gregorian::week_iterator itr_week(d); boost::gregorian::month_iterator itr_month(d); boost::gregorian::year_iterator itr_year(d); stockinfo ret; switch (period) { case day: ret = rollup_iterator(itr_day, number); break; case week: ret = rollup_iterator(itr_week, number); break; case month: ret = rollup_iterator(itr_month, number); break; case year: ret = rollup_iterator(itr_year, number); break; default: // TODO: Return default. ret = *this; break; } return ret; } stockinfo stockinfo::weekly(bool align_week) { return rollup(1, week, align_week); } /** * Parse YYYY-MM-DD or d-Mmm-YY dates into something machine-readable. * * @param char *date The date to parse. * @return time_t */ time_t stockinfo::parse_csv_time(const char *date) { struct tm parsed; time_t ret = 0; if (date == nullptr) { return ret; } // Zero out the time sections. We don't care about them yet (TODO?) parsed.tm_hour = 0; parsed.tm_min = 0; parsed.tm_sec = 1; parsed.tm_isdst = -1; // Yahoo's format was: %Y-%m-%d. Google's is %d-%B-%y. if (!strptime(date, "%Y-%m-%d", &parsed)) { if (!strptime(date, "%d-%B-%y", &parsed)) { BOOST_LOG_TRIVIAL(info) << "Failed to parse date: " << date; return ret; } } // Convert <struct tm> into <time_t>. ret = mktime(&parsed); return ret == -1 ? 0 : ret; } /** * Prevent the interruption of critical tasks. */ void stockinfo::nosig() { signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGTERM, SIG_IGN); signal(SIGPIPE, SIG_IGN); return; } /** * Allow the program to be halted again. */ void stockinfo::sig() { signal(SIGINT, SIG_DFL); signal(SIGHUP, SIG_DFL); signal(SIGTERM, SIG_DFL); signal(SIGPIPE, SIG_DFL); return; } void stockinfo::copy(const stockinfo &s) { struct stock tmp; long x, length; length = s.length(); for (x = 0; x < length; x++) { memcpy(&tmp, s[x], sizeof(tmp)); if (s[x]->date) { tmp.date = (char *)malloc(strlen(s[x]->date)); strcpy(tmp.date, s[x]->date); } data.push_back(tmp); } if (length > 0) dirty = true; }
23.320225
125
0.647796
[ "object", "vector" ]
bd12119801fe88ec9159651f2ca5cd8720de096e
3,624
cpp
C++
affine_transformations/translation2d.cpp
jeffreyforkfolder/lecture-demos
0a0a2eecc45fe91520c0960a76d1d39841a6f0cb
[ "BSD-3-Clause" ]
null
null
null
affine_transformations/translation2d.cpp
jeffreyforkfolder/lecture-demos
0a0a2eecc45fe91520c0960a76d1d39841a6f0cb
[ "BSD-3-Clause" ]
1
2019-10-28T14:26:40.000Z
2019-10-28T14:26:40.000Z
affine_transformations/translation2d.cpp
jeffreyforkfolder/lecture-demos
0a0a2eecc45fe91520c0960a76d1d39841a6f0cb
[ "BSD-3-Clause" ]
null
null
null
//Illustration of 2-D translation // Andreas Unterweger, 2017-2018 //This code is licensed under the 3-Clause BSD License. See LICENSE file for details. #include <iostream> #include <opencv2/viz.hpp> #include "conf_viz.hpp" using namespace std; using namespace cv; using namespace viz; using namespace vizutils; static constexpr auto transformed_object_name = "Transformed object"; static constexpr auto letter_size = 0.1; static void AddCoordinateSystem(ConfigurableVisualization &visualization) { WCoordinateSystem coordinate_system(4 * letter_size); visualization.objects.insert(make_pair("Coordinate system", coordinate_system)); } static void Add2DObjects(ConfigurableVisualization &visualization) { constexpr auto text = "A"; WText3D original_object(text, Point3d(0, letter_size, 0), letter_size, false, Color::gray()); original_object.setRenderingProperty(OPACITY, 0.5); WText3D transformed_object(text, Point3d(0, letter_size, 0), letter_size, false); visualization.objects.insert(make_pair("Original object", original_object)); visualization.objects.insert(make_pair(transformed_object_name, transformed_object)); } static void AddObjects(ConfigurableVisualization &visualization) { AddCoordinateSystem(visualization); Add2DObjects(visualization); } static constexpr auto x_offset_trackbar_name = "X offset"; static constexpr auto y_offset_trackbar_name = "Y offset"; static constexpr decltype(x_offset_trackbar_name) trackbar_names[] { x_offset_trackbar_name, y_offset_trackbar_name }; static void ApplyTransformations(ConfigurableVisualization &visualization) { const auto x_offset_percent = visualization.GetTrackbarValue(x_offset_trackbar_name); const auto y_offset_percent = visualization.GetTrackbarValue(y_offset_trackbar_name); const Vec3d offset(x_offset_percent / 100.0, y_offset_percent / 100.0, 0); const auto transformation = Affine3d::Identity().translate(offset); auto &transformed_object = visualization.objects[transformed_object_name]; transformed_object.setPose(transformation); } static void AddControls(ConfigurableVisualization &visualization) { for (const auto &trackbar_name : trackbar_names) visualization.AddTrackbar(trackbar_name, ApplyTransformations, 50, -50); } int main(const int argc, const char * const argv[]) { if (argc != 1) { cout << "Illustrates translation in two dimensions." << endl; cout << "Usage: " << argv[0] << endl; return 1; } auto visualization_window_name = "2-D translation"; auto control_window_name = "2-D translation parameters"; ConfigurableVisualization visualization(visualization_window_name, control_window_name); AddObjects(visualization); AddControls(visualization); visualization.ShowWindows([&visualization](const Affine3d &pose) { const auto old_camera = visualization.GetCamera(); const auto focal_length = old_camera.getFocalLength() / 2; //Reduce focal length so that object is not clipped Camera camera(focal_length[0], focal_length[1], old_camera.getPrincipalPoint()[0], old_camera.getPrincipalPoint()[1], old_camera.getWindowSize()); camera.setClip(Vec2d(-0.01, 0)); //Only show small portion of space (effectively hides the z axis) visualization.SetCamera(camera); return pose; }); return 0; }
41.181818
192
0.709161
[ "object" ]
bd13a2bec59dc867e2e8ac3bb31cf659870f02c4
1,916
hpp
C++
include/geometry/geometry.hpp
mfdeakin/Geometry
4cb1768aa8dcdefe8ed6f21861af33909c8beed1
[ "Unlicense" ]
2
2015-12-01T22:44:42.000Z
2020-10-07T00:48:41.000Z
include/geometry/geometry.hpp
mfdeakin/Geometry
4cb1768aa8dcdefe8ed6f21861af33909c8beed1
[ "Unlicense" ]
null
null
null
include/geometry/geometry.hpp
mfdeakin/Geometry
4cb1768aa8dcdefe8ed6f21861af33909c8beed1
[ "Unlicense" ]
null
null
null
#ifndef _GEOMETRY_HPP_ #define _GEOMETRY_HPP_ #include "cudadef.h" namespace Geometry { enum PointLocation { PT_INSIDE = -1, PT_ON = 0, PT_OUTSIDE = 1 }; template <int, typename> class Origin; template <int, typename> class Vector; template <int, typename> class Solid; template <int, typename> class Point; template <int, typename> class Line; template <int dim, typename fptype> class Quadric; constexpr float defAbsPrecision = 9.5367431640625e-7; template <int _dim, typename fptype> class GeometryBase { public: CUDA_CALLABLE virtual ~GeometryBase(){}; static_assert(_dim >= 0, "The dimension of a geometric object " "cannot be negative!"); static constexpr const int dim = _dim; }; /* A solid is a well defined geometric object which * is positioned relative to an origin, * and which has a defined interior and exterior, * and possibly surface */ template <int dim, typename fptype> class Solid : public GeometryBase<dim, fptype> { public: CUDA_CALLABLE Solid() : origin(Origin<dim, fptype>::uOrigin()) {} template <typename srctype> CUDA_CALLABLE Solid(const Solid<dim, srctype> &s) : origin(s.origin) {} template <typename srctype> CUDA_CALLABLE Solid(const Origin<dim, srctype> &o) : origin(o) {} CUDA_CALLABLE virtual ~Solid(){}; CUDA_CALLABLE Solid<dim, fptype> &operator=( const Solid<dim, fptype> &s) { origin = s.origin; return *this; } CUDA_CALLABLE virtual PointLocation ptLocation( const Point<dim, fptype> &test, fptype absPrecision = defAbsPrecision) const = 0; CUDA_CALLABLE virtual void shiftOrigin( const Origin<dim, fptype> &newOrigin) { origin = newOrigin; } CUDA_CALLABLE Origin<dim, fptype> getOrigin() const { return origin; } template <int, typename> friend class Solid; protected: Origin<dim, fptype> origin; }; }; #endif
20.168421
55
0.691023
[ "geometry", "object", "vector", "solid" ]
bd197cc71e1bae09348e64ea78a550ca6ae69dcb
1,792
cpp
C++
src/output_file.cpp
nnorm/cpu_rtx
0c2ae259a114f5cddfba10547ced375527333ff3
[ "Unlicense" ]
null
null
null
src/output_file.cpp
nnorm/cpu_rtx
0c2ae259a114f5cddfba10547ced375527333ff3
[ "Unlicense" ]
null
null
null
src/output_file.cpp
nnorm/cpu_rtx
0c2ae259a114f5cddfba10547ced375527333ff3
[ "Unlicense" ]
null
null
null
#include <output_file.h> #include <assert.h> #include <fstream> #include <algorithm> void write_ppm_ascii(char const* path, std::vector<std::vector<glm::vec3>> const& data, int width, int height) { std::ofstream outputFile(path); assert("Could not open output file" && outputFile.is_open()); //write header outputFile << "P3 " << width << " " << height << " " << "255\n"; //write file data in plain text for (int py = height - 1; py >= 0; py--) { for (int px = 0; px < width; px++) { glm::vec3 color = data[px][py]; color.r = std::min(std::max(0.0f, color.r), 1.0f); color.g = std::min(std::max(0.0f, color.g), 1.0f); color.b = std::min(std::max(0.0f, color.b), 1.0f); color *= 255.99f; glm::ivec3 ic = glm::ivec3(int(color.x), int(color.y), int(color.z)); outputFile << ic.r << " " << ic.g << " " << ic.b << " \n"; } } outputFile << std::endl; //close file outputFile.close(); } void write_ppm_binary(char const * path, std::vector<std::vector<glm::vec3>> const & data, int width, int height) { std::ofstream outputFile(path, std::ofstream::binary); assert("Could not open output file" && outputFile.is_open()); //write header outputFile << "P6 " << width << " " << height << " " << "255\n"; //compute binary color data and write for (int py = height - 1; py >= 0; py--) { for (int px = 0; px < width; px++) { glm::vec3 color = data[px][py]; color.r = std::min(std::max(0.0f, color.r), 1.0f); color.g = std::min(std::max(0.0f, color.g), 1.0f); color.b = std::min(std::max(0.0f, color.b), 1.0f); color *= 255.99f; glm::ivec3 ic = glm::ivec3(int(color.x), int(color.y), int(color.z)); outputFile << (unsigned char)ic.r << (unsigned char)ic.g << (unsigned char)ic.b; } } //close file outputFile.close(); }
28.903226
113
0.594308
[ "vector" ]
bd26490d4cd1dc9c14e8787b8bea8f00de7772e7
10,204
cpp
C++
Src/Widget/QvtkBiopsyWidget.cpp
wuzhuobin/QvtkProject
30bfc798aca0e79043438aa16840464e6731e38c
[ "RSA-MD" ]
1
2018-09-10T12:14:43.000Z
2018-09-10T12:14:43.000Z
Src/Widget/QvtkBiopsyWidget.cpp
wuzhuobin/QvtkProject
30bfc798aca0e79043438aa16840464e6731e38c
[ "RSA-MD" ]
3
2018-05-22T11:00:59.000Z
2018-12-07T09:36:19.000Z
Src/Widget/QvtkBiopsyWidget.cpp
wuzhuobin/QvtkProject
30bfc798aca0e79043438aa16840464e6731e38c
[ "RSA-MD" ]
null
null
null
// me #include "QvtkBiopsyWidget.h" #include "QvtkProp.h" #include "QvtkImageSlice.h" #include "QvtkOrthogonalViewer.h" #include "QvtkBiopsyData.h" #include "QvtkPolyData.h" #include "vtkWidgetSet2.h" #include "ui_QvtkBiopsyWidget.h" #include "QvtkScene.h" // vtk #include <vtkObjectFactory.h> #include <vtkSmartPointer.h> #include <vtkPointHandleRepresentation3D.h> #include <vtkBoundedPlanePointPlacer.h> #include <vtkFocalPlanePointPlacer.h> #include <vtkWidgetSet.h> #include <vtkLineRepresentation.h> #include <vtkCallbackCommand.h> #include <vtkWidgetEvent.h> #include <vtkWidgetCallbackMapper.h> #include <vtkTubeFilter.h> #include <vtkLineSource.h> #include <vtkPolyDataMapper.h> #include <vtkPointPlacer.h> #include <vtkPointHandleRepresentation3D.h> #include <vtkFieldData.h> #include <vtkDoubleArray.h> #include <vtkLineWidget2.h> #include <vtkLineRepresentation.h> #include <vtkPlane.h> // qt #include <QDebug> namespace Q { namespace vtk { class BiopsyWidgetRepresentation : public vtkLineRepresentation { public: static BiopsyWidgetRepresentation* New(); vtkTypeMacro(BiopsyWidgetRepresentation, vtkLineRepresentation); virtual void PrintSelf(ostream& os, vtkIndent indent) override; vtkGetObjectMacro(TubeFilter, vtkTubeFilter); protected: BiopsyWidgetRepresentation(); virtual ~BiopsyWidgetRepresentation() override; vtkTubeFilter* TubeFilter; }; vtkStandardNewMacro(BiopsyWidgetRepresentation); void BiopsyWidgetRepresentation::PrintSelf(ostream & os, vtkIndent indent) { vtkLineRepresentation::PrintSelf(os, indent); } BiopsyWidgetRepresentation::BiopsyWidgetRepresentation() { this->TubeFilter = vtkTubeFilter::New(); this->TubeFilter->SetNumberOfSides(10); this->TubeFilter->SetInputConnection(this->LineSource->GetOutputPort()); this->LineMapper->SetInputConnection(this->TubeFilter->GetOutputPort()); this->SetResolution(2); this->SetDirectionalLine(true); this->SetDistanceAnnotationVisibility(true); } BiopsyWidgetRepresentation::~BiopsyWidgetRepresentation() { this->TubeFilter->Delete(); } vtkStandardNewMacro(BiopsyWidget); const QString BiopsyWidget::RADIUS("RADIUS"); const QString BiopsyWidget::NORMAL("NORMAL"); const QString BiopsyWidget::TAG("Biopsy tube"); void BiopsyWidget::PrintSelf(ostream & os, vtkIndent indent) { vtkLineWidget2::PrintSelf(os, indent); } void BiopsyWidget::setCustomEnable(bool flag) { UniqueUiInteractorObserver::setCustomEnable(flag); if (flag) { const QList<Prop*>& props = this->getViewer()->getProps(); this->SetProjectionNormal(this->getViewer()->getOrientation()); const double* pos = this->getViewer()->getCursorPosition(); this->SetProjectionPosition(pos[0], pos[1], pos[2]); QObject::connect(this->getViewer(), &OrthogonalViewer::OrientationChanged, this, &BiopsyWidget::SetProjectionNormal); QObject::connect(this->getViewer(), &OrthogonalViewer::cursorPositionChanged, this, &BiopsyWidget::SetProjectionPosition); if (!this->m_biopsyData) { qCritical() << "BiopsyData is a nullptr. " << "The BiopsyWidget cannot access the data. "; return; } double point1[3]; double point2[3]; memcpy(point1, pos, sizeof(point1)); memcpy(point2, pos, sizeof(point2)); if (this->m_biopsyData->getPolyData()->GetPoints() && this->m_biopsyData->getPolyData()->GetPoints()->GetNumberOfPoints() > 1) { this->m_biopsyData->getPolyData()->GetPoint(0, point1); this->m_biopsyData->getPolyData()->GetPoint(1, point2); } this->GetLineRepresentation()->SetPoint1WorldPosition(point1); this->GetLineRepresentation()->SetPoint2WorldPosition(point2); if (this->m_biopsyData->getPolyData()->GetFieldData()->GetArray(RADIUS.toStdString().c_str())) { double radius = this->m_biopsyData->getPolyData()->GetFieldData()->GetArray(RADIUS.toStdString().c_str())->GetTuple1(0); this->SetRadius(radius); } else { this->SetRadius(2); } //QObject::connect(this->ui->doubleSpinBoxRadius, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), // this->m_biopsyData, &BiopsyData::setRadius); } else { QObject::disconnect(this->getViewer(), &OrthogonalViewer::OrientationChanged, this, &BiopsyWidget::SetProjectionNormal); QObject::disconnect(this->getViewer(), &OrthogonalViewer::cursorPositionChanged, this, &BiopsyWidget::SetProjectionPosition); if (this->m_biopsyData) { //QObject::connect(this->ui->doubleSpinBoxRadius, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), // this->m_biopsyData, &BiopsyData::setRadius); } } } void BiopsyWidget::install() { UNIQUE_UI_INSTALL(BiopsyWidget); } void BiopsyWidget::uninstall() { UNIQUE_UI_UNINSTALL(); } void BiopsyWidget::SetProjectionNormal(int normal) { switch (normal) { case OrthogonalViewer::ORIENTATION_YZ: case OrthogonalViewer::ORIENTATION_XZ: case OrthogonalViewer::ORIENTATION_XY: this->m_pointPlacer->SetProjectionNormal(normal); break; case OrthogonalViewer::SAGITTAL: case OrthogonalViewer::CORONAL: case OrthogonalViewer::AXIAL: default: { this->m_pointPlacer->SetProjectionNormalToOblique(); this->m_pointPlacer->GetObliquePlane()->SetNormal( this->getViewer()->getCurrentPlaneNormal()[0], this->getViewer()->getCurrentPlaneNormal()[1], this->getViewer()->getCurrentPlaneNormal()[2]); break; } } } void BiopsyWidget::SetProjectionPosition(double x, double y, double z) { synchronalCall(this, [x, y, z](InteractorObserver* ib) { BiopsyWidget* widget = static_cast<BiopsyWidget*>(ib); switch (widget->m_pointPlacer->GetProjectionNormal()) { case vtkBoundedPlanePointPlacer::XAxis: widget->m_pointPlacer->SetProjectionPosition(x); break; case vtkBoundedPlanePointPlacer::YAxis: widget->m_pointPlacer->SetProjectionPosition(y); break; case vtkBoundedPlanePointPlacer::ZAxis: widget->m_pointPlacer->SetProjectionPosition(z); break; case vtkBoundedPlanePointPlacer::Oblique: widget->m_pointPlacer->GetObliquePlane()->SetOrigin(x, y, z); default: break; } }); } void BiopsyWidget::SetRadius(double radius) { synchronalCall(this, [&radius](InteractorObserver* observer) { BiopsyWidget* widget = static_cast<BiopsyWidget*>(observer); reinterpret_cast<BiopsyWidgetRepresentation*>(widget->GetRepresentation())->GetTubeFilter()->SetRadius(radius); widget->Render(); }); this->ui->doubleSpinBoxRadius->setValue(radius); vtkSmartPointer<vtkDoubleArray> radiusArray = vtkSmartPointer<vtkDoubleArray>::New(); radiusArray->InsertNextValue(radius); radiusArray->SetName(RADIUS.toStdString().c_str()); this->m_biopsyData->getPolyData()->GetFieldData()->AddArray(radiusArray); } void BiopsyWidget::CreateDefaultRepresentation() { if (!this->WidgetRep) { BiopsyWidgetRepresentation* rep = BiopsyWidgetRepresentation::New(); this->SetWidgetRepresentation(rep); rep->Delete(); this->GetLineRepresentation()->SetDistanceAnnotationVisibility(true); this->GetLineRepresentation()->SetResolution(1); this->GetLineRepresentation()->GetPoint1Representation()->SetPointPlacer(this->m_pointPlacer); this->GetLineRepresentation()->GetPoint2Representation()->SetPointPlacer(this->m_pointPlacer); this->GetLineRepresentation()->GetLineHandleRepresentation()->SetPointPlacer(this->m_pointPlacer); } } void BiopsyWidget::SetWidgetSet(vtkWidgetSet2 * widgetSet) { if (this->WidgetSet == widgetSet) { return; } if (this->WidgetSet) { this->WidgetSet->UnRegister(this); } this->WidgetSet = widgetSet; if (this->WidgetSet) { this->WidgetSet->Register(this); this->WidgetSet->AddWidget(this); } } void BiopsyWidget::SetBiopsyData(PolyData * data) { this->m_biopsyData = data; } BiopsyWidget::BiopsyWidget() { this->m_pointPlacer = vtkBoundedPlanePointPlacer::New(); this->m_pointPlacer->SetObliquePlane(vtkSmartPointer<vtkPlane>::New()); this->WidgetSet = nullptr; this->m_biopsyData = nullptr; vtkWidgetSet2* widgetSet = vtkWidgetSet2::New(); this->SetWidgetSet(widgetSet); widgetSet->Delete(); this->CreateDefaultRepresentation(); this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, BiopsyWidget::MoveDispatcher); } BiopsyWidget::~BiopsyWidget() { this->m_pointPlacer->Delete(); } void BiopsyWidget::uniqueInstall() { connect(this->ui->doubleSpinBoxRadius, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &BiopsyWidget::SetRadius); } void BiopsyWidget::MoveDispatcher(vtkAbstractWidget * widget) { BiopsyWidget* self = static_cast<BiopsyWidget*>(widget); if (self->WidgetSet) { self->WidgetSet->DispatchAction(self, &BiopsyWidget::MoveAction); } else { vtkLineWidget2::MoveAction(widget); } } void BiopsyWidget::MoveAction(BiopsyWidget * dispatcher) { if (this == dispatcher) { vtkLineWidget2::MoveAction(this); if (dispatcher->WidgetState == Start) { return; } this->GetLineRepresentation()->GetPolyData(this->m_biopsyData->getPolyData()); double radius = reinterpret_cast<BiopsyWidgetRepresentation*>(this->GetRepresentation())->GetTubeFilter()->GetRadius(); vtkSmartPointer<vtkDoubleArray> radiusArray = vtkSmartPointer<vtkDoubleArray>::New(); radiusArray->InsertNextValue(radius); radiusArray->SetName(RADIUS.toStdString().c_str()); this->m_biopsyData->getPolyData()->GetFieldData()->AddArray(radiusArray); } else { if (dispatcher->WidgetState == Start) { return; } double* worldPos1 = dispatcher->GetLineRepresentation()->GetPoint1WorldPosition(); double* worldPos2 = dispatcher->GetLineRepresentation()->GetPoint2WorldPosition(); this->GetLineRepresentation()->SetPoint1WorldPosition(worldPos1); this->GetLineRepresentation()->SetPoint2WorldPosition(worldPos2); this->Render(); } } } }
32.600639
131
0.72305
[ "render" ]
bd2d1c5f818194b56510444ef088eb7efdbe809d
1,571
cpp
C++
Days 051 - 060/Day 51/ShuffleDeckWithSwaps.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 051 - 060/Day 51/ShuffleDeckWithSwaps.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 051 - 060/Day 51/ShuffleDeckWithSwaps.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
#include <iostream> #include <iterator> #include <random> #include <string> #include <utility> #include <vector> struct Card { static constexpr unsigned int CARDS_PER_DECK = 52; std::string value; std::string suit; explicit Card(std::string value, std::string suit) : value(value), suit(suit) { } }; unsigned int RandomNumber(unsigned int max) { static std::random_device randomSeed; static std::mt19937 randomEngine(randomSeed()); std::uniform_int_distribution<int> randomRange(1, max); return randomRange(randomEngine); } void ShuffleDeck(std::vector<Card>& deck) noexcept { for (unsigned int i = 0; i < deck.size(); i++) { unsigned int swapIndex = RandomNumber(Card::CARDS_PER_DECK) - 1; std::swap(deck[i], deck[swapIndex]); } } std::vector<Card> CreateDeck() { static const std::string values[] { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; static const std::string suits[] { "S", "H", "C", "D" }; std::vector<Card> deck; deck.reserve(Card::CARDS_PER_DECK); for (const auto& suit : suits) { for (const auto& value : values) { deck.emplace_back(value, suit); } } return deck; } void PrintDeck(const std::vector<Card>& deck) { for (unsigned int i = 0; i < deck.size(); i++) { std::cout << deck[i].value << deck[i].suit; if (i < deck.size() - 1) { std::cout << ", "; } } std::cout << "\n"; } int main(int argc, const char* argv[]) { std::vector<Card> deck = CreateDeck(); PrintDeck(deck); std::cout << "\n"; ShuffleDeck(deck); PrintDeck(deck); std::cin.get(); return 0; }
18.482353
104
0.631445
[ "vector" ]
bd2db21d6835157001d94fb0b9e77e05c5e08483
1,789
cpp
C++
src/StlAscii.cpp
zbacskai/obj2stl
ebe98c6948a0761b8a8f178ccdeae6ea8c237ff3
[ "MIT" ]
1
2021-12-21T10:42:50.000Z
2021-12-21T10:42:50.000Z
src/StlAscii.cpp
zbacskai/obj2stl
ebe98c6948a0761b8a8f178ccdeae6ea8c237ff3
[ "MIT" ]
8
2020-10-05T08:06:10.000Z
2020-10-05T08:12:08.000Z
src/StlAscii.cpp
zbacskai/obj2stl
ebe98c6948a0761b8a8f178ccdeae6ea8c237ff3
[ "MIT" ]
null
null
null
/** * * Copyright 2020 Zoltan Bacskai * **/ #include <stl/StlAscii.hpp> #include<iostream> #include <fstream> #include <iomanip> #include <cstring> #include <arpa/inet.h> namespace { void writeVertex(const trim::TriangleData& triangle, std::ofstream& ofile) { for (int i = 0; i < 3; ++i) { ofile << " vertex "; ofile << triangle(i, 0) << " "; ofile << triangle(i, 1) << " "; ofile << triangle(i, 2) << std::endl; } } void writeNormalVector(const trim::TriangleData& triangleNormal, std::ofstream& ofile) { ofile << triangleNormal(0,0) << " "; ofile << triangleNormal(0,1) << " "; ofile << triangleNormal(0,1) << std::endl; } void writeTriangle(const trim::TriangleData& triangle, const trim::TriangleData& triangleNormal, std::ofstream& ofile) { ofile << "facet normal "; writeNormalVector(triangleNormal, ofile); ofile << " outer loop" << std::endl; writeVertex(triangle, ofile); ofile << " endloop" << std::endl; ofile << "endfacet" << std::endl; } } namespace stl { namespace ascii { StlAscii::StlAscii(const char* fileName) : meshconvert::FileWriterInterface(fileName), fileName_(fileName) { } void StlAscii::write(const trim::TriangleModel &tm) { std::ofstream ofile; ofile.open (fileName_); ofile << std::setprecision(6); ofile << std::scientific; ofile << "solid test " << std::endl; auto& triangleNormals = tm.getTriangleNormals(); auto& triangles = tm.getTriangles(); for (unsigned int i = 0; i < triangles.size(); ++i) writeTriangle(triangles[i], triangleNormals[i], ofile); ofile.close(); } } // end of namespace ascii } // end of namespace stl
23.539474
106
0.600335
[ "solid" ]
bd312196ce1c1299b0574ea1814c2005c8f9e367
4,918
cpp
C++
Maple.App/Model/Netif.cpp
superben2010/Maple
09d48a98941b73593845eec0aa4d75fc7452293a
[ "Apache-2.0" ]
524
2021-03-13T16:07:16.000Z
2022-03-31T10:58:02.000Z
Maple.App/Model/Netif.cpp
superben2010/Maple
09d48a98941b73593845eec0aa4d75fc7452293a
[ "Apache-2.0" ]
24
2021-03-14T02:49:13.000Z
2022-02-13T13:38:51.000Z
Maple.App/Model/Netif.cpp
superben2010/Maple
09d48a98941b73593845eec0aa4d75fc7452293a
[ "Apache-2.0" ]
71
2021-03-15T04:08:32.000Z
2022-03-30T00:33:29.000Z
#include "pch.h" #include <WinSock2.h> #include <iphlpapi.h> #include "Netif.h" #if __has_include("Netif.g.cpp") #include "Netif.g.cpp" #endif constexpr auto WORKING_BUFFER_SIZE = 15000; constexpr auto ADDR_BUFFER_SIZE = 64; constexpr auto MAX_TRIES = 3; #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) #define FREE(x) HeapFree(GetProcessHeap(), 0, (x)) namespace winrt::Maple_App::implementation { Netif::Netif(const hstring& desc, const hstring& Addr) : m_desc(desc), m_addr(Addr) { } hstring Netif::Desc() { return m_desc; } hstring Netif::Addr() { return m_addr; } std::vector<Maple_App::Netif> Netif::EnumerateInterfaces() { /* Declare and initialize variables */ DWORD dwRetVal = 0; unsigned int i = 0; // Set the flags to pass to GetAdaptersAddresses ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME; // default to unspecified address family (both) ULONG family = AF_INET; PIP_ADAPTER_ADDRESSES pAddresses = NULL; ULONG outBufLen = 0; ULONG Iterations = 0; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL; // Allocate a 15 KB buffer to start with. outBufLen = WORKING_BUFFER_SIZE; std::array<WCHAR, ADDR_BUFFER_SIZE> addrBuf{}; auto sniffed = Netif::SniffOutboundAddress(); if (sniffed == L"192.168.3.1") { sniffed = {}; } do { pAddresses = (IP_ADAPTER_ADDRESSES*)MALLOC(outBufLen); if (pAddresses == NULL) { throw std::bad_alloc{}; } dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen); if (dwRetVal == ERROR_BUFFER_OVERFLOW) { FREE(pAddresses); pAddresses = NULL; } else { break; } Iterations++; } while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES)); if (dwRetVal != NO_ERROR) { if (pAddresses) { FREE(pAddresses); } return {}; } // If successful, output some information from the data we received std::vector<Maple_App::Netif> ret; pCurrAddresses = pAddresses; while (pCurrAddresses) { if (!(pCurrAddresses->Flags & IP_ADAPTER_IPV4_ENABLED)) { pCurrAddresses = pCurrAddresses->Next; continue; } const auto& friendlyName = to_hstring(pCurrAddresses->FriendlyName); pUnicast = pCurrAddresses->FirstUnicastAddress; if (pUnicast != NULL) { for (i = 0; pUnicast != NULL; i++) { // pUnicast->Address.lpSockaddr->sa_family; auto bufSize = static_cast<DWORD>(addrBuf.size()); if (FAILED(WSAAddressToStringW(pUnicast->Address.lpSockaddr, pUnicast->Address.iSockaddrLength, nullptr, addrBuf.data(), &bufSize))) { pUnicast = pUnicast->Next; continue; } if (bufSize > 0) { bufSize--; } hstring addr(addrBuf.data(), bufSize); hstring desc = addr == sniffed ? L"★" : L""; desc = desc + friendlyName + L" (" + addr + L")"; ret.emplace_back(winrt::make<Netif>(desc, addr)); pUnicast = pUnicast->Next; } } pCurrAddresses = pCurrAddresses->Next; } FREE(pAddresses); return ret; } hstring Netif::SniffOutboundAddress() { const auto s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (s == INVALID_SOCKET) { return {}; } sockaddr saddr{}; saddr.sa_family = AF_INET; saddr.sa_data[1] = 53; memset(&saddr.sa_data[2], 8, 4); if (connect(s, &saddr, sizeof(saddr)) == SOCKET_ERROR) { return {}; } sockaddr_storage localAddr{}; int localAddrLen = sizeof(localAddr); getsockname(s, (sockaddr*)&localAddr, &localAddrLen); localAddr.__ss_pad1[0] = 0; localAddr.__ss_pad1[1] = 0; std::array<WCHAR, ADDR_BUFFER_SIZE> addrBuf{}; auto bufSize = static_cast<DWORD>(addrBuf.size()); if (FAILED(WSAAddressToStringW((LPSOCKADDR)&localAddr, localAddrLen, nullptr, addrBuf.data(), &bufSize))) { return {}; } if (bufSize > 0) { bufSize--; } return hstring(addrBuf.data(), bufSize); } }
29.27381
154
0.540057
[ "vector" ]
bd32262c41e4a92aace98f143f4ea2f4b1a3acb0
13,242
cpp
C++
Modeler/modelerdraw.cpp
nat-chan/InteractiveCG
2f5a08e5868395ef409e9e6e2405e9ee94f051f6
[ "MIT" ]
1
2019-12-20T14:56:42.000Z
2019-12-20T14:56:42.000Z
Modeler/modelerdraw.cpp
nat-chan/InteractiveCG
2f5a08e5868395ef409e9e6e2405e9ee94f051f6
[ "MIT" ]
1
2018-11-13T12:01:52.000Z
2018-12-11T10:48:05.000Z
Modeler/modelerdraw.cpp
nat-chan/InteractiveCG
2f5a08e5868395ef409e9e6e2405e9ee94f051f6
[ "MIT" ]
null
null
null
#pragma warning(disable:4996) #include "modelerdraw.h" #include <FL/gl.h> #ifdef __APPLE__ #include <OpenGL/glu.h> #else #include <GL/glu.h> #endif #include <cstdio> #include <cstdlib> #include <string.h> using namespace std; // ******************************************************** // Support functions from previous version of modeler // ******************************************************** void _dump_current_modelview( void ) { ModelerDrawState *mds = ModelerDrawState::Instance(); if (mds->m_rayFile == NULL) { fprintf(stderr, "No .ray file opened for writing, bailing out.¥n"); exit(-1); } GLdouble mv[16]; glGetDoublev( GL_MODELVIEW_MATRIX, mv ); fprintf( mds->m_rayFile, "transform(¥n (%f,%f,%f,%f),¥n (%f,%f,%f,%f),¥n (%f,%f,%f,%f),¥n (%f,%f,%f,%f),¥n", mv[0], mv[4], mv[8], mv[12], mv[1], mv[5], mv[9], mv[13], mv[2], mv[6], mv[10], mv[14], mv[3], mv[7], mv[11], mv[15] ); } void _dump_current_material( void ) { ModelerDrawState *mds = ModelerDrawState::Instance(); if (mds->m_rayFile == NULL) { fprintf(stderr, "No .ray file opened for writing, bailing out.¥n"); exit(-1); } fprintf( mds->m_rayFile, "material={¥n diffuse=(%f,%f,%f);¥n ambient=(%f,%f,%f);¥n}¥n", mds->m_diffuseColor[0], mds->m_diffuseColor[1], mds->m_diffuseColor[2], mds->m_diffuseColor[0], mds->m_diffuseColor[1], mds->m_diffuseColor[2]); } // **************************************************************************** // Initially assign singleton instance to NULL ModelerDrawState* ModelerDrawState::m_instance = NULL; ModelerDrawState::ModelerDrawState() : m_drawMode(NORMAL), m_quality(MEDIUM) { float grey[] = {.5f, .5f, .5f, 1}; float white[] = {1,1,1,1}; float black[] = {0,0,0,1}; memcpy(m_ambientColor, black, 4 * sizeof(float)); memcpy(m_diffuseColor, grey, 4 * sizeof(float)); memcpy(m_specularColor, white, 4 * sizeof(float)); m_shininess = 0.5; m_rayFile = NULL; } // CLASS ModelerDrawState METHODS ModelerDrawState* ModelerDrawState::Instance() { // Return the singleton if it exists, otherwise, create it return (m_instance) ? (m_instance) : m_instance = new ModelerDrawState(); } // **************************************************************************** // Modeler functions for your use // **************************************************************************** // Set the current material properties void setAmbientColor(float r, float g, float b) { ModelerDrawState *mds = ModelerDrawState::Instance(); mds->m_ambientColor[0] = (GLfloat)r; mds->m_ambientColor[1] = (GLfloat)g; mds->m_ambientColor[2] = (GLfloat)b; mds->m_ambientColor[3] = (GLfloat)1.0; if (mds->m_drawMode == NORMAL) glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, mds->m_ambientColor); } void setDiffuseColor(float r, float g, float b, float a) { ModelerDrawState *mds = ModelerDrawState::Instance(); mds->m_diffuseColor[0] = (GLfloat)r; mds->m_diffuseColor[1] = (GLfloat)g; mds->m_diffuseColor[2] = (GLfloat)b; mds->m_diffuseColor[3] = (GLfloat)a; if (mds->m_drawMode == NORMAL) glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, mds->m_diffuseColor); else glColor3f(r,g,b); } void setSpecularColor(float r, float g, float b) { ModelerDrawState *mds = ModelerDrawState::Instance(); mds->m_specularColor[0] = (GLfloat)r; mds->m_specularColor[1] = (GLfloat)g; mds->m_specularColor[2] = (GLfloat)b; mds->m_specularColor[3] = (GLfloat)1.0; if (mds->m_drawMode == NORMAL) glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, mds->m_specularColor); } void setShininess(float s) { ModelerDrawState *mds = ModelerDrawState::Instance(); mds->m_shininess = (GLfloat)s; if (mds->m_drawMode == NORMAL) glMaterialf( GL_FRONT, GL_SHININESS, mds->m_shininess); } void setDrawMode(DrawModeSetting_t drawMode) { ModelerDrawState::Instance()->m_drawMode = drawMode; } void setQuality(QualitySetting_t quality) { ModelerDrawState::Instance()->m_quality = quality; } bool openRayFile(const char rayFileName[]) { ModelerDrawState *mds = ModelerDrawState::Instance(); fprintf(stderr, "Ray file format output is buggy (ehsu)¥n"); if (!rayFileName) return false; if (mds->m_rayFile) closeRayFile(); mds->m_rayFile = fopen(rayFileName, "w"); if (mds->m_rayFile != NULL) { fprintf( mds->m_rayFile, "SBT-raytracer 1.0¥n¥n" ); fprintf( mds->m_rayFile, "camera { fov=30; }¥n¥n" ); fprintf( mds->m_rayFile, "directional_light { direction=(-1,-1,-1); color=(0.7,0.7,0.7); }¥n¥n" ); return true; } else return false; } void _setupOpenGl() { ModelerDrawState *mds = ModelerDrawState::Instance(); switch (mds->m_drawMode) { case NORMAL: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glShadeModel(GL_SMOOTH); break; case FLATSHADE: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glShadeModel(GL_FLAT); break; case WIREFRAME: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glShadeModel(GL_FLAT); default: break; } } void closeRayFile() { ModelerDrawState *mds = ModelerDrawState::Instance(); if (mds->m_rayFile) fclose(mds->m_rayFile); mds->m_rayFile = NULL; } void drawSphere(double r) { ModelerDrawState *mds = ModelerDrawState::Instance(); _setupOpenGl(); if (mds->m_rayFile) { _dump_current_modelview(); fprintf(mds->m_rayFile, "scale(%f,%f,%f,sphere {¥n", r, r, r ); _dump_current_material(); fprintf(mds->m_rayFile, "}))¥n" ); } else { int divisions; GLUquadricObj* gluq; switch(mds->m_quality) { case HIGH: divisions = 32; break; case MEDIUM: divisions = 20; break; case LOW: divisions = 12; break; case POOR: divisions = 8; break; } gluq = gluNewQuadric(); gluQuadricDrawStyle( gluq, GLU_FILL ); gluQuadricTexture( gluq, GL_TRUE ); gluSphere(gluq, r, divisions, divisions); gluDeleteQuadric( gluq ); } } // p は楕円体の中心。v1, v2, v3 は楕円体の主軸で、互いに直交しており、 // p±v1, p±v2, p±v3なる点が楕円体の表面上にある。 // 上のコードでは、原点中心の単位球を描いて、(1,0,0)→v1, (0,1,0)→v2, (0,0,1)→v3 と座標変換して // p だけ平行移動している。 void drawEllipsoid(float *p, float *v1, float *v2, float *v3, int sect) { GLfloat mat[16]; mat[0] = v1[0]; mat[1] = v1[1]; mat[2] = v1[2]; mat[3] = 0; mat[4] = v2[0]; mat[5] = v2[1]; mat[6] = v2[2]; mat[7] = 0; mat[8] = v3[0]; mat[9] = v3[1]; mat[10] = v3[2]; mat[11] = 0; mat[12] = p[0]; mat[13] = p[1]; mat[14] = p[2]; mat[15] = 1; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(mat); glEnable(GL_NORMALIZE); // glutSolidSphere(1, sect, sect); drawSphere(sect); glDisable(GL_NORMALIZE); glPopMatrix(); } void drawBox( double x, double y, double z ) { ModelerDrawState *mds = ModelerDrawState::Instance(); _setupOpenGl(); if (mds->m_rayFile) { _dump_current_modelview(); fprintf(mds->m_rayFile, "scale(%f,%f,%f,translate(0.5,0.5,0.5,box {¥n", x, y, z ); _dump_current_material(); fprintf(mds->m_rayFile, "})))¥n" ); } else { /* remember which matrix mode OpenGL was in. */ int savemode; glGetIntegerv( GL_MATRIX_MODE, &savemode ); /* switch to the model matrix and scale by x,y,z. */ glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glScaled( x, y, z ); glBegin( GL_QUADS ); glNormal3d( 0.0, 0.0, -1.0 ); glVertex3d( 0.0, 0.0, 0.0 ); glVertex3d( 0.0, 1.0, 0.0 ); glVertex3d( 1.0, 1.0, 0.0 ); glVertex3d( 1.0, 0.0, 0.0 ); glNormal3d( 0.0, -1.0, 0.0 ); glVertex3d( 0.0, 0.0, 0.0 ); glVertex3d( 1.0, 0.0, 0.0 ); glVertex3d( 1.0, 0.0, 1.0 ); glVertex3d( 0.0, 0.0, 1.0 ); glNormal3d( -1.0, 0.0, 0.0 ); glVertex3d( 0.0, 0.0, 0.0 ); glVertex3d( 0.0, 0.0, 1.0 ); glVertex3d( 0.0, 1.0, 1.0 ); glVertex3d( 0.0, 1.0, 0.0 ); glNormal3d( 0.0, 0.0, 1.0 ); glVertex3d( 0.0, 0.0, 1.0 ); glVertex3d( 1.0, 0.0, 1.0 ); glVertex3d( 1.0, 1.0, 1.0 ); glVertex3d( 0.0, 1.0, 1.0 ); glNormal3d( 0.0, 1.0, 0.0 ); glVertex3d( 0.0, 1.0, 0.0 ); glVertex3d( 0.0, 1.0, 1.0 ); glVertex3d( 1.0, 1.0, 1.0 ); glVertex3d( 1.0, 1.0, 0.0 ); glNormal3d( 1.0, 0.0, 0.0 ); glVertex3d( 1.0, 0.0, 0.0 ); glVertex3d( 1.0, 1.0, 0.0 ); glVertex3d( 1.0, 1.0, 1.0 ); glVertex3d( 1.0, 0.0, 1.0 ); glEnd(); /* restore the model matrix stack, and switch back to the matrix mode we were in. */ glPopMatrix(); glMatrixMode( savemode ); } } void drawTextureBox( double x, double y, double z ) { // NOT IMPLEMENTED, SORRY (ehsu) } void drawCylinder( double h, double r1, double r2 ) { ModelerDrawState *mds = ModelerDrawState::Instance(); int divisions; _setupOpenGl(); switch(mds->m_quality) { case HIGH: divisions = 32; break; case MEDIUM: divisions = 20; break; case LOW: divisions = 12; break; case POOR: divisions = 8; break; } if (mds->m_rayFile) { _dump_current_modelview(); fprintf(mds->m_rayFile, "cone { height=%f; bottom_radius=%f; top_radius=%f;¥n", h, r1, r2 ); _dump_current_material(); fprintf(mds->m_rayFile, "})¥n" ); } else { GLUquadricObj* gluq; /* GLU will again do the work. draw the sides of the cylinder. */ gluq = gluNewQuadric(); gluQuadricDrawStyle( gluq, GLU_FILL ); gluQuadricTexture( gluq, GL_TRUE ); gluCylinder( gluq, r1, r2, h, divisions, divisions); gluDeleteQuadric( gluq ); if ( r1 > 0.0 ) { /* if the r1 end does not come to a point, draw a flat disk to cover it up. */ gluq = gluNewQuadric(); gluQuadricDrawStyle( gluq, GLU_FILL ); gluQuadricTexture( gluq, GL_TRUE ); gluQuadricOrientation( gluq, GLU_INSIDE ); gluDisk( gluq, 0.0, r1, divisions, divisions); gluDeleteQuadric( gluq ); } if ( r2 > 0.0 ) { /* if the r2 end does not come to a point, draw a flat disk to cover it up. */ /* save the current matrix mode. */ int savemode; glGetIntegerv( GL_MATRIX_MODE, &savemode ); /* translate the origin to the other end of the cylinder. */ glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glTranslated( 0.0, 0.0, h ); /* draw a disk centered at the new origin. */ gluq = gluNewQuadric(); gluQuadricDrawStyle( gluq, GLU_FILL ); gluQuadricTexture( gluq, GL_TRUE ); gluQuadricOrientation( gluq, GLU_OUTSIDE ); gluDisk( gluq, 0.0, r2, divisions, divisions); gluDeleteQuadric( gluq ); /* restore the matrix stack and mode. */ glPopMatrix(); glMatrixMode( savemode ); } } } void drawTriangle( double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3 ) { ModelerDrawState *mds = ModelerDrawState::Instance(); _setupOpenGl(); if (mds->m_rayFile) { _dump_current_modelview(); fprintf(mds->m_rayFile, "polymesh { points=((%f,%f,%f),(%f,%f,%f),(%f,%f,%f)); faces=((0,1,2));¥n", x1, y1, z1, x2, y2, z2, x3, y3, z3 ); _dump_current_material(); fprintf(mds->m_rayFile, "})¥n" ); } else { double a, b, c, d, e, f; /* the normal to the triangle is the cross product of two of its edges. */ a = x2-x1; b = y2-y1; c = z2-z1; d = x3-x1; e = y3-y1; f = z3-z1; glBegin( GL_TRIANGLES ); glNormal3d( b*f - c*e, c*d - a*f, a*e - b*d ); glVertex3d( x1, y1, z1 ); glVertex3d( x2, y2, z2 ); glVertex3d( x3, y3, z3 ); glEnd(); } } //1,2,3番目の点が張る平面上に4番目の点があることを仮定している void drawRectangle( double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double x4, double y4, double z4 ) { double a, b, c, d, e, f; a = x2-x1; b = y2-y1; c = z2-z1; d = x3-x1; e = y3-y1; f = z3-z1; glBegin( GL_QUADS ); glNormal3d( b*f - c*e, c*d - a*f, a*e - b*d ); glVertex3d( x1, y1, z1 ); glVertex3d( x2, y2, z2 ); glVertex3d( x3, y3, z3 ); glVertex3d( x4, y4, z4 ); glEnd(); } void drawTriangularPrism( double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double h ){ double a, b, c, d, e, f,nx, ny, nz; /* the normal to the triangle is the cross product of two of its edges. */ a = x2-x1; b = y2-y1; c = z2-z1; d = x3-x1; e = y3-y1; f = z3-z1; nx = b*f - c*e; ny = c*d - a*f; nz = a*e - b*d; glBegin( GL_TRIANGLES ); glNormal3d(nx, ny, nz); glVertex3d( x1, y1, z1 ); glVertex3d( x2, y2, z2 ); glVertex3d( x3, y3, z3 ); glEnd(); glBegin( GL_TRIANGLES ); glNormal3d(-nx, -ny, -nz);//逆の平面の法線は逆向き glVertex3d( x1, y1+h, z1 ); glVertex3d( x3, y3+h, z3 ); glVertex3d( x2, y2+h, z2 ); glEnd(); drawRectangle( x1 , y1 , z1 , x1 , y1+h , z1 , x2 , y2+h , z2 , x2 , y2 , z2); drawRectangle( x2 , y2 , z2 , x2 , y2+h , z2 , x3 , y3+h , z3 , x3 , y3 , z3); drawRectangle( x3 , y3 , z3 , x3 , y3+h , z3 , x1 , y1+h , z1 , x1 , y1 , z1); }
25.613153
117
0.586316
[ "model", "transform" ]
bd33d5aa0d9889225ada8191739463af242bfffd
9,027
cpp
C++
src/mixer.lib/mixer.gui.element.buttonImpl.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
src/mixer.lib/mixer.gui.element.buttonImpl.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
src/mixer.lib/mixer.gui.element.buttonImpl.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
#include "mixer.lib.h" #include "mixer.lib.inputContext.h" #include "mixer.lib.mesh.h" #include "mixer.lib.gpuMesh.h" #include "mixer.lib.videoDriver.h" #include "mixer.gui.h" #include "mixer.gui.contextImpl.h" #include "mixer.gui.textureAtlas.h" #include "mixer.gui.element.textImpl.h" #include "mixer.gui.element.buttonImpl.h" #include <stdarg.h> #include "miLib.h" extern miLib* g_lib; miGUIButtonImpl::miGUIButtonImpl(){} miGUIButtonImpl::~miGUIButtonImpl() { if (m_radioGroup) SetRadioGroup(0); if (m_meshGPU) miDestroy(m_meshGPU); if (m_borderMeshGPU) miDestroy(m_borderMeshGPU); } void miGUIButtonImpl::Update() { if (g_lib->m_GUIElementInInputFocus) return; bool mouseInRectBefore = m_isInActiveAreaRect; m_isInActiveAreaRect = MI_GUI_CURSOR_IN_RECT; if (m_isInActiveAreaRect) { g_lib->m_cursorInGUI = true; } else { if (m_onMouseLeave && mouseInRectBefore) m_onMouseLeave(this); } if (g_lib->m_inputContext->m_isLMBUp && !m_useAsCheckbox) m_isClicked = false; if (g_lib->m_GUIInputBlock) return; if (!m_ignoreInput && !m_isDisabled) { if (m_isInActiveAreaRect) { g_lib->m_GUIInputBlock = true; if (m_onMouseInRect) m_onMouseInRect(this); if (!mouseInRectBefore) { if (m_onMouseEnter) m_onMouseEnter(this); } if (g_lib->m_inputContext->m_isLMBDown) { if (m_onLMBDown) m_onLMBDown(this); if (m_useAsCheckbox) { if (m_isChecked) { Uncheck(); } else { Check(); } /*if (m_useAsRadiobutton) { for (u32 i = 0; i < m_radioFriends.m_size; ++i) { auto f = m_radioFriends.m_data[i]; if (f->m_useAsCheckbox && f->m_useAsRadiobutton) { if (f != this && f->m_isChecked) { if (f->m_onUncheck) f->m_onUncheck(f); f->m_isChecked = false; } } } } if (m_isChecked) { if(!m_radioDontUncheck) m_isChecked = false; if (m_onUncheck && !m_useAsRadiobutton) m_onUncheck(this); } else { m_isChecked = true; if (m_onCheck) m_onCheck(this); }*/ } else { m_isClicked = true; } g_lib->m_GUIElementInMouseFocus = (miGUIElement*)this; } if (g_lib->m_inputContext->m_isRMBDown) { if (m_onRMBDown) m_onRMBDown(this); } } if (g_lib->m_inputContext->m_isLMBUp) { if (m_onRelease && m_isInActiveAreaRect && (g_lib->m_GUIElementInMouseFocusIF == (miGUIElement*)this)) m_onRelease(this); } } } void miGUIButtonImpl::Draw(f32 dt) { if (m_onDraw) m_onDraw(this); f32 lerp_t = m_lerpTime * dt; if (m_isInActiveAreaRect && !m_isDisabled) { if (m_isAnimated) { if (m_isClicked || m_isChecked) { m_colorCurrent.m_data[0] = math::lerp(m_colorCurrent.m_data[0], m_colorPress.m_data[0], lerp_t); m_colorCurrent.m_data[1] = math::lerp(m_colorCurrent.m_data[1], m_colorPress.m_data[1], lerp_t); m_colorCurrent.m_data[2] = math::lerp(m_colorCurrent.m_data[2], m_colorPress.m_data[2], lerp_t); } else { m_colorCurrent.m_data[0] = math::lerp(m_colorCurrent.m_data[0], m_colorHover.m_data[0], lerp_t); m_colorCurrent.m_data[1] = math::lerp(m_colorCurrent.m_data[1], m_colorHover.m_data[1], lerp_t); m_colorCurrent.m_data[2] = math::lerp(m_colorCurrent.m_data[2], m_colorHover.m_data[2], lerp_t); } } else { if (m_isClicked || m_isChecked) m_colorCurrent = m_colorPress; else m_colorCurrent = m_colorHover; } } else { if (m_isAnimated) { if (m_isClicked || m_isChecked) { m_colorCurrent.m_data[0] = math::lerp(m_colorCurrent.m_data[0], m_colorPress.m_data[0], lerp_t); m_colorCurrent.m_data[1] = math::lerp(m_colorCurrent.m_data[1], m_colorPress.m_data[1], lerp_t); m_colorCurrent.m_data[2] = math::lerp(m_colorCurrent.m_data[2], m_colorPress.m_data[2], lerp_t); } else { m_colorCurrent.m_data[0] = math::lerp(m_colorCurrent.m_data[0], m_color.m_data[0], lerp_t); m_colorCurrent.m_data[1] = math::lerp(m_colorCurrent.m_data[1], m_color.m_data[1], lerp_t); m_colorCurrent.m_data[2] = math::lerp(m_colorCurrent.m_data[2], m_color.m_data[2], lerp_t); } } else { if (m_isClicked || m_isChecked) m_colorCurrent = m_colorPress; else m_colorCurrent = m_color; } } if (m_borderMeshGPU) { m_colorFinal = m_borderColor; g_lib->m_videoDriver->SetGUIShaderData(this); g_lib->m_videoDriver->SetMesh(m_borderMeshGPU); g_lib->m_videoDriver->SetTexture(0, g_lib->m_whiteTexture); g_lib->m_videoDriver->Draw(); } m_colorFinal = m_colorCurrent; g_lib->m_videoDriver->SetGUIShaderData(this); if (m_meshGPU) { g_lib->m_videoDriver->SetMesh(m_meshGPU); g_lib->m_videoDriver->SetTexture(0, g_lib->m_whiteTexture); g_lib->m_videoDriver->Draw(); } if (m_useIcon && m_textureAtlas) { auto UV = m_textureAtlas->GetUV(m_iconID); g_lib->m_videoDriver->DrawRectangle( v4f( m_buildAreaTransformed.x + m_offsetTransformed.x + m_iconOffset.x, m_buildAreaTransformed.y + m_offsetTransformed.y + m_iconOffset.y, m_buildAreaTransformed.x + m_iconSize.x + m_offsetTransformed.x + m_iconOffset.x, m_buildAreaTransformed.y + m_iconSize.y + m_offsetTransformed.y + m_iconOffset.y) , m_iconColor, m_iconColor, m_textureAtlas->GetTexture(), &UV); } auto tsz = m_text.size(); if (tsz) { miColor textColor = m_textColorBase; if (m_isDisabled) { textColor = m_textColorDisable; } else { if (m_isClicked) { textColor = m_textColorPress; } else if (m_isInActiveAreaRect) { textColor = m_textColorHover; } } g_lib->m_videoDriver->BeginDrawText(); g_lib->m_videoDriver->DrawText(m_text.data(), tsz, m_font, v2f(m_buildAreaTransformed.x + m_textOffset.x + m_offsetTransformed.x, m_buildAreaTransformed.y + m_textOffset.y + m_offsetTransformed.y), textColor); g_lib->m_videoDriver->EndDrawText(); } } void miGUIButtonImpl::Rebuild() { if(m_borderMeshGPU) miDestroy(m_borderMeshGPU); auto ba = m_buildAreaTransformed; if (m_borderSize) { m_borderMeshGPU = ((miGUIContextImpl*)m_context)->create_bg_mesh(m_buildAreaTransformed, m_cornersIndent, m_cornersIterations, 0); ba.x += m_borderSize; ba.y += m_borderSize; ba.z -= m_borderSize; ba.w -= m_borderSize; } if (m_meshGPU) miDestroy(m_meshGPU); m_meshGPU = ((miGUIContextImpl*)m_context)->create_bg_mesh(ba, m_cornersIndent, m_cornersIterations, 0); } void miGUIButtonImpl::SetTextColor(const miColor& base, const miColor& hover, const miColor& press, const miColor& disable) { m_textColorBase = base; m_textColorHover = hover; m_textColorPress = press; m_textColorDisable = disable; } void miGUIButtonImpl::SetText(const wchar_t* text, miGUIFont* font) { m_text.clear(); m_font = font; m_textOffset.set(0.f, 0.f); if (text && font) { m_text = text; v2f buttonCenter; buttonCenter.x = (f32(m_buildAreaTransformed.z - m_buildAreaTransformed.x) * 0.5f); buttonCenter.y = (f32(m_buildAreaTransformed.w - m_buildAreaTransformed.y) * 0.5f); auto textLen = font->GetTextLength(text); v2f textHalfLen; textHalfLen.x = textLen * 0.5f; textHalfLen.y = font->m_maxHeight * 0.5f; m_textOffset.x += buttonCenter.x - textHalfLen.x; m_textOffset.y += buttonCenter.y - textHalfLen.y; SetTextColor(m_textColorBase, m_textColorHover, m_textColorPress, m_textColorDisable); } } void miGUIButtonImpl::SetBorder(u32 size, const miColor& c) { m_borderSize = size; m_borderColor = c; Rebuild(); } void miGUIButtonImpl::SetIcon(miGUITextureAtlas* ta, u32 id, const v2f& size) { m_iconSize = size; m_textureAtlas = ta; m_iconID = id; m_useIcon = true; } void miGUIButtonImpl::Check() { if (m_useAsRadiobutton && m_radioGroup) { miGUIContextImpl* ctx = ((miGUIContextImpl*)m_context); if (ctx->m_radioGroupButton.m_head) { auto c = ctx->m_radioGroupButton.m_head; auto l = c->m_left; while (true) { auto cimpl = (miGUIButtonImpl*)c->m_data; if (cimpl != this && cimpl->m_radioGroup == m_radioGroup) { if (cimpl->m_onUncheck) cimpl->m_onUncheck(cimpl); cimpl->m_isChecked = false; } if (c == l) break; c = c->m_right; } } /*for (u32 i = 0; i < m_radioFriends.m_size; ++i) { auto f = m_radioFriends.m_data[i]; if (f->m_useAsCheckbox && f->m_useAsRadiobutton) { if (f != this && f->m_isChecked) { if (f->m_onUncheck) f->m_onUncheck(f); f->m_isChecked = false; } } }*/ } m_isChecked = true; if (m_onCheck) m_onCheck(this); } void miGUIButtonImpl::Uncheck() { if (m_isChecked) { if (!m_radioDontUncheck) m_isChecked = false; if (m_onUncheck && !m_useAsRadiobutton) m_onUncheck(this); } } void miGUIButtonImpl::SetRadioGroup(u32 o) { m_radioGroup = o; ((miGUIContextImpl*)m_context)->m_radioGroupButton.erase_first(this); if (m_radioGroup) ((miGUIContextImpl*)m_context)->m_radioGroupButton.push_back(this); }
23.086957
211
0.680182
[ "mesh" ]
bd370a49e09aae75c567e2408dce86bbbc7d53d6
1,488
cc
C++
onnxruntime/core/optimizer/transpose_optimizer/ort_transpose_optimizer.cc
SiriusKY/onnxruntime
3c5853dcbc9d5dda2476afa8c6105802d2b8e53d
[ "MIT" ]
669
2018-12-03T22:00:31.000Z
2019-05-06T19:42:49.000Z
onnxruntime/core/optimizer/transpose_optimizer/ort_transpose_optimizer.cc
SiriusKY/onnxruntime
3c5853dcbc9d5dda2476afa8c6105802d2b8e53d
[ "MIT" ]
440
2018-12-03T21:09:56.000Z
2019-05-06T20:47:23.000Z
onnxruntime/core/optimizer/transpose_optimizer/ort_transpose_optimizer.cc
SiriusKY/onnxruntime
3c5853dcbc9d5dda2476afa8c6105802d2b8e53d
[ "MIT" ]
140
2018-12-03T21:15:28.000Z
2019-05-06T18:02:36.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "ort_transpose_optimizer.h" #include <deque> #include "core/graph/graph_utils.h" #include "core/optimizer/initializer.h" #include "core/optimizer/utils.h" #include "core/providers/cpu/tensor/transpose.h" #include "optimizer_utils.h" using namespace ONNX_NAMESPACE; using namespace ::onnxruntime::common; using namespace onnx_layout_transformation; namespace onnxruntime { Status TransposeOptimizer::ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const { auto api_graph = MakeApiGraph(graph, cpu_allocator_, /*new_node_ep*/ nullptr); OptimizeResult result = onnx_layout_transformation::Optimize(*api_graph, /*allow_extended_ops*/ false); if (result.error_msg) { // currently onnx_layout_transformation::Optimize only fails if we hit an unsupported opset. // we don't want to fail loading the model just because we can't optimize Transpose ops, so just log a warning LOGS(logger, WARNING) << "Transpose optimizer failed: " << result.error_msg.value(); } if (result.graph_modified) { modified = true; } GraphViewer graph_viewer(graph); auto nodes = std::vector<std::unique_ptr<api::NodeRef>>(); for (auto index : graph_viewer.GetNodesInTopologicalOrder()) { ORT_RETURN_IF_ERROR(Recurse(*graph.GetNode(index), modified, graph_level, logger)); } return Status::OK(); } } // namespace onnxruntime
36.292683
122
0.755376
[ "vector", "model" ]
bd384e57f6409a06e52818b62f63095737c27aba
4,286
cpp
C++
Source/VoxelGraph/Private/VoxelNodes/VoxelWorldGeneratorSamplerNodes.cpp
SolarStormInteractive/VoxelPlugin
b0b8a1838262227fa586fbcb1b46a6184cdf1e8c
[ "MIT" ]
null
null
null
Source/VoxelGraph/Private/VoxelNodes/VoxelWorldGeneratorSamplerNodes.cpp
SolarStormInteractive/VoxelPlugin
b0b8a1838262227fa586fbcb1b46a6184cdf1e8c
[ "MIT" ]
null
null
null
Source/VoxelGraph/Private/VoxelNodes/VoxelWorldGeneratorSamplerNodes.cpp
SolarStormInteractive/VoxelPlugin
b0b8a1838262227fa586fbcb1b46a6184cdf1e8c
[ "MIT" ]
null
null
null
// Copyright 2020 Phyronnaz #include "VoxelNodes/VoxelWorldGeneratorSamplerNodes.h" #include "CppTranslation/VoxelVariables.h" #include "VoxelWorldGenerators/VoxelFlatWorldGenerator.h" #include "VoxelGraphGenerator.h" #include "VoxelWorldGenerators/VoxelWorldGeneratorInstance.inl" #include "NodeFunctions/VoxelNodeFunctions.h" EVoxelPinCategory UVoxelNode_WorldGeneratorSamplerBase::GetInputPinCategory(int32 PinIndex) const { const int32 NumDefaultInputPins = Super::GetMinInputPins(); if (PinIndex < NumDefaultInputPins) { return Super::GetInputPinCategory(PinIndex); } PinIndex -= NumDefaultInputPins; if (Seeds.IsValidIndex(PinIndex)) { return EC::Seed; } return EC::Float; } FName UVoxelNode_WorldGeneratorSamplerBase::GetInputPinName(int32 PinIndex) const { const int32 NumDefaultInputPins = Super::GetMinInputPins(); if (PinIndex < NumDefaultInputPins) { return Super::GetInputPinName(PinIndex); } PinIndex -= NumDefaultInputPins; if (Seeds.IsValidIndex(PinIndex)) { return Seeds[PinIndex]; } return "ERROR"; } int32 UVoxelNode_WorldGeneratorSamplerBase::GetMinInputPins() const { return Super::GetMinInputPins() + Seeds.Num(); } int32 UVoxelNode_WorldGeneratorSamplerBase::GetMaxInputPins() const { return GetMinInputPins(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// UVoxelNode_SingleWorldGeneratorSamplerBase::UVoxelNode_SingleWorldGeneratorSamplerBase() { WorldGenerator = UVoxelFlatWorldGenerator::StaticClass(); SetInputs( { "X", EC::Float, "X" }, { "Y", EC::Float, "Y" }, { "Z", EC::Float, "Z" }); } FText UVoxelNode_SingleWorldGeneratorSamplerBase::GetTitle() const { return FText::Format( VOXEL_LOCTEXT("World Generator: {0}"), FText::FromString(UniqueName.ToString())); } void UVoxelNode_SingleWorldGeneratorSamplerBase::LogErrors(FVoxelGraphErrorReporter& ErrorReporter) { Super::LogErrors(ErrorReporter); if (!WorldGenerator.IsValid()) { ErrorReporter.AddMessageToNode(this, "invalid world generator", EVoxelGraphNodeMessageType::Error); } } #if WITH_EDITOR bool UVoxelNode_SingleWorldGeneratorSamplerBase::TryImportFromProperty(UProperty* Property, UObject* Object) { if (auto* Prop = UE_25_SWITCH(Cast, CastField)<UStructProperty>(Property)) { if (Prop->GetCPPType(nullptr, 0) == "FVoxelWorldGeneratorPicker") { WorldGenerator = *Prop->ContainerPtrToValuePtr<FVoxelWorldGeneratorPicker>(Object); return true; } } return false; } #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// UVoxelNode_GetWorldGeneratorValue::UVoxelNode_GetWorldGeneratorValue() { SetOutputs({"", EC::Float, "Value"}); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// UVoxelNode_GetWorldGeneratorMaterial::UVoxelNode_GetWorldGeneratorMaterial() { SetOutputs({ "", EC::Material, "Material" }); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// UVoxelNode_GetWorldGeneratorCustomOutput::UVoxelNode_GetWorldGeneratorCustomOutput() { SetOutputs({ "", EC::Float, "Custom Output Value" }); } FText UVoxelNode_GetWorldGeneratorCustomOutput::GetTitle() const { return FText::FromString("Get World Generator Custom Output: " + OutputName.ToString()); }
31.514706
109
0.534531
[ "object" ]
bd418e6a71bf402224fcb5101d9573a5262c56c4
1,197
cpp
C++
codeforces/C - World Eater Brothers/Wrong answer on test 7.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - World Eater Brothers/Wrong answer on test 7.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - World Eater Brothers/Wrong answer on test 7.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Apr/20/2020 19:34 * solution_verdict: Wrong answer on test 7 language: GNU C++14 * run_time: 216 ms memory_used: 23800 KB * problem: https://codeforces.com/contest/238/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; vector<int>adj[N+2],sgn[N+2]; int cnt; void dfs(int node,int par) { for(int i=0;i<adj[node].size();i++) { if(adj[node][i]==par)continue; cnt+=sgn[node][i];dfs(adj[node][i],node); } } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; for(int i=1;i<n;i++) { int u,v;cin>>u>>v; adj[u].push_back(v);sgn[u].push_back(0); adj[v].push_back(u);sgn[v].push_back(1); } int ans=1e9; for(int i=1;i<=n;i++) { cnt=0;dfs(i,-1);ans=min(ans,cnt); } cout<<max(ans-1,0)<<endl; return 0; }
31.5
111
0.433584
[ "vector" ]
bd4ae26a3b8e3e8419a380319fa289e2b2bb3116
3,846
cc
C++
src/kudu/tablet/diff_scan-test.cc
granthenke/kudu
990bb4d134c8fd9bd4621cd2fb9827d47f623db7
[ "Apache-2.0" ]
2
2019-07-17T19:08:07.000Z
2019-07-17T19:13:25.000Z
src/kudu/tablet/diff_scan-test.cc
granthenke/kudu
990bb4d134c8fd9bd4621cd2fb9827d47f623db7
[ "Apache-2.0" ]
null
null
null
src/kudu/tablet/diff_scan-test.cc
granthenke/kudu
990bb4d134c8fd9bd4621cd2fb9827d47f623db7
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include <gtest/gtest.h> #include "kudu/common/common.pb.h" #include "kudu/common/iterator.h" #include "kudu/common/scan_spec.h" #include "kudu/common/schema.h" #include "kudu/tablet/local_tablet_writer.h" #include "kudu/tablet/mvcc.h" #include "kudu/tablet/rowset.h" #include "kudu/tablet/tablet-harness.h" #include "kudu/tablet/tablet-test-base.h" #include "kudu/tablet/tablet-test-util.h" #include "kudu/tablet/tablet.h" #include "kudu/util/test_macros.h" using std::string; using std::unique_ptr; using std::vector; namespace kudu { namespace tablet { class DiffScanTest : public TabletTestBase<IntKeyTestSetup<INT64>> { public: DiffScanTest() : Superclass(TabletHarness::Options::ClockType::HYBRID_CLOCK) {} private: using Superclass = TabletTestBase<IntKeyTestSetup<INT64>>; }; TEST_F(DiffScanTest, TestDiffScan) { auto tablet = this->tablet(); auto tablet_id = tablet->tablet_id(); MvccSnapshot snap1; tablet->mvcc_manager()->TakeSnapshot(&snap1); LocalTabletWriter writer(tablet.get(), &client_schema_); constexpr int64_t kRowKey = 1; ASSERT_OK(InsertTestRow(&writer, kRowKey, 1)); ASSERT_OK(tablet->Flush()); // 2. Delete the row and flush the DMS. ASSERT_OK(DeleteTestRow(&writer, kRowKey)); ASSERT_OK(tablet->FlushAllDMSForTests()); // 3. Insert the same row key (with another value) and flush the MRS. ASSERT_OK(InsertTestRow(&writer, kRowKey, 2)); ASSERT_OK(tablet->Flush()); // Ensure there is only 1 live row in the tablet (our reinsert). vector<string> rows; ASSERT_OK(DumpTablet(*tablet, tablet->schema()->CopyWithoutColumnIds(), &rows)); ASSERT_EQ(1, rows.size()) << "expected only one live row"; ASSERT_EQ("(int64 key=1, int32 key_idx=1, int32 val=2)", rows[0]); // 4. Do a diff scan from time snap1. ASSERT_OK(tablet->mvcc_manager()->WaitForApplyingTransactionsToCommit()); MvccSnapshot snap2; tablet->mvcc_manager()->TakeSnapshot(&snap2); RowIteratorOptions opts; opts.snap_to_include = snap2; opts.order = ORDERED; opts.include_deleted_rows = true; auto projection = tablet->schema()->CopyWithoutColumnIds(); opts.projection = &projection; unique_ptr<RowwiseIterator> row_iterator; ASSERT_OK(tablet->NewRowIterator(std::move(opts), &row_iterator)); ASSERT_TRUE(row_iterator); ScanSpec spec; ASSERT_OK(row_iterator->Init(&spec)); // For the time being, we should get two rows back, and they should both be // the same key. In reality, one has been deleted. // TODO(KUDU-2645): The result of this test should change once we properly // implement diff scans and the merge iterator is able to deduplicate ghosts. ASSERT_OK(tablet::IterateToStringList(row_iterator.get(), &rows)); ASSERT_EQ(2, rows.size()); EXPECT_EQ("(int64 key=1, int32 key_idx=1, int32 val=1)", rows[0]); EXPECT_EQ("(int64 key=1, int32 key_idx=1, int32 val=2)", rows[1]); } } // namespace tablet } // namespace kudu
34.035398
82
0.727769
[ "vector" ]
32e51e55c51bf95546ffcefdfde72820c3d68157
10,875
cc
C++
newweb/utility/http/connection_manager.cc
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
newweb/utility/http/connection_manager.cc
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
newweb/utility/http/connection_manager.cc
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <utility> #include <boost/bind.hpp> #include "connection_manager.hpp" #include "../easylogging++.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> using std::string; using std::pair; using std::queue; using std::list; using std::map; using std::make_pair; using std::shared_ptr; using std::make_shared; #define _LOG_PREFIX(inst) << "cnxman= " << (inst)->objId() << ": " /* "inst" stands for instance, as in, instance of a class */ #define vloginst(level, inst) VLOG(level) _LOG_PREFIX(inst) #define vlogself(level) vloginst(level, this) #define dvloginst(level, inst) DVLOG(level) _LOG_PREFIX(inst) #define dvlogself(level) dvloginst(level, this) #define loginst(level, inst) LOG(level) _LOG_PREFIX(inst) #define logself(level) loginst(level, this) namespace http { /***************************************************/ ConnectionManager::ConnectionManager(struct event_base *evbase, const in_addr_t& socks5_addr, const in_port_t& socks5_port, RequestErrorCb request_error_cb, const uint8_t max_persist_cnx_per_srv, const uint8_t max_retries_per_resource) : evbase_(evbase) , socks5_addr_(socks5_addr), socks5_port_(socks5_port) , max_persist_cnx_per_srv_(max_persist_cnx_per_srv) , max_retries_per_resource_(max_retries_per_resource) , timestamp_recv_first_byte_(0) , totaltxbytes_(0), totalrxbytes_(0) , is_resetting_(false) , notify_req_error_(request_error_cb) { CHECK(evbase_); CHECK(request_error_cb); CHECK(max_persist_cnx_per_srv > 0); CHECK_EQ(max_retries_per_resource_, 0) << "don't use retries for this project"; } /***************************************************/ void ConnectionManager::submit_request(Request *req) { vlogself(2) << "begin, req= " << req->objId() << ", res:" << req->webkit_resInstNum_; const NetLoc netloc(req->host_, req->port_); vlogself(2) << "netloc: " << netloc.first << ":" << netloc.second; if (!inMap(servers_, netloc)) { servers_[netloc] = make_shared<Server>(); } auto server = servers_[netloc]; server->requests_.push_back(req); vlogself(2) << "server queue size " << server->requests_.size(); shared_ptr<Connection> conn; auto& conns = server->connections_; // first, is there a connection with an empty queue for (auto& c : conns) { if (c->get_queue_size() == 0) { conn = c; vlogself(2) << "conn= " << c->objId() << " has empty queue -> use it"; goto done; } } vlogself(2) << "reaching here means no idle connection"; CHECK(!conn); // make sure conn IS NULL vlogself(2) << "there are " << conns.size()<< " connections to this netloc"; if (conns.size() < max_persist_cnx_per_srv_) { vlogself(2) << " --> create a new connection"; CHECK(!conn); conn.reset(new Connection( evbase_, netloc.first.c_str(), netloc.second, socks5_addr_, socks5_port_, nullptr, 0, boost::bind(&ConnectionManager::cnx_error_cb, this, _1, netloc), boost::bind(&ConnectionManager::cnx_eof_cb, this, _1, netloc), nullptr, nullptr, nullptr, this, false ), [=](Connection* c) { c->destroy(); }); CHECK(conn); vlogself(2) << " ... with objId() "<< conn->objId(); conn->set_request_done_cb( boost::bind(&ConnectionManager::cnx_request_done_cb, this, _1, _2, netloc)); conn->set_first_recv_byte_cb( boost::bind(&ConnectionManager::cnx_first_recv_byte_cb, this, _1)); conns.push_back(conn); goto done; } else { vlogself(2)<< "reached max persist cnx per srv -> do nothing now"; } done: if (conn) { CHECK(server->requests_.size() > 0); auto reqtosubmit = server->requests_.front(); vlogself(2) << "submit req= " << reqtosubmit->objId() << ", res:" << req->webkit_resInstNum_ << ": on conn= " << conn->objId(); conn->submit_request(reqtosubmit); server->requests_.pop_front(); } vlogself(2) << "done"; return; } /***************************************************/ void ConnectionManager::cnx_first_recv_byte_cb(Connection* conn) { vlogself(2) << "begin"; if (timestamp_recv_first_byte_ != 0) { vlogself(2) << "timestamp_recv_first_byte_ already set: " << timestamp_recv_first_byte_ << " --> do nothing"; return; } timestamp_recv_first_byte_ = common::gettimeofdayMs(nullptr); CHECK(timestamp_recv_first_byte_ > 0); vlogself(2) << "timestamp_recv_first_byte_: " << timestamp_recv_first_byte_; vlogself(2) << "done"; } /***************************************************/ void ConnectionManager::cnx_request_done_cb(Connection* conn, const Request* req, const NetLoc& netloc) { vlogself(2) << "begin, req= " << req->objId() << ", res:" << req->webkit_resInstNum_; // we don't free anything in here // see if there's a request waiting to be sent Request* reqtosubmit = nullptr; auto server = servers_[netloc]; CHECK(server); auto& requests = server->requests_; vlogself(2) << requests.size() << " waiting requests"; if (requests.empty()) { vlogself(2) << " --> do nothing"; goto done; } reqtosubmit = requests.front(); vlogself(2) << "submit req= " << reqtosubmit->objId() << ", res:" << req->webkit_resInstNum_ << " on conn= " << conn->objId(); conn->submit_request(reqtosubmit); requests.pop_front(); done: vlogself(2) << "done"; return; } /***************************************************/ void ConnectionManager::cnx_error_cb(Connection* conn, const NetLoc& netloc) { logself(WARNING) << "connection error"; handle_unusable_conn(conn, netloc); } /***************************************************/ void ConnectionManager::cnx_eof_cb(Connection* conn, const NetLoc& netloc) { if (!is_resetting_) { logself(WARNING) << "connection eof"; handle_unusable_conn(conn, netloc); } } /***************************************************/ void ConnectionManager::handle_unusable_conn(Connection *conn, const NetLoc& netloc) { vlogself(2) << "begin, conn= "<< conn->objId(); // we should mark any requests being handled by this connection as // error. for now, we don't attempt to request elsewhere. release_conn(conn, netloc); /* release_conn() only removes the conn from the list. it does not * yet delete the conn object. so we can still get its request * queues. * * retry_requests() honors the max_retries_per_resource_ */ retry_requests(conn->get_active_request_queue()); retry_requests(conn->get_pending_request_queue()); vlogself(2) << "done"; } /***************************************************/ bool ConnectionManager::retry_requests(queue<Request*> requests) { vlogself(2) << "begin, num reqs= " << requests.size(); while (!requests.empty()) { auto req = requests.front(); CHECK(req); vlogself(2) << "req= " << req->objId(); requests.pop(); if (req->get_num_retries() == max_retries_per_resource_) { logself(WARNING) << "req= " << req->objId() << "] has exhausted " << unsigned(max_retries_per_resource_) << " retries"; notify_req_error_(req); continue; } req->increment_num_retries(); logself(INFO) << "re-requesting req= "<<req->objId()<<" for the "<<req->get_num_retries()<<" time"; if (req->actual_resp_body_size() > 0) { /* the request "body_size()" represents number of * contiguous bytes from 0 that we have received. so, we * can use that as the next first_byte_pos. */ // req->set_first_byte_pos(req->get_body_size()); // vlogself(2) << "set first_byte_pos to %d", // req->get_first_byte_pos()); } this->submit_request(req); } vlogself(2) << "done"; return true; } /***************************************************/ void ConnectionManager::get_total_bytes(size_t& tx, size_t& rx) { vlogself(2) << "begin"; tx = totaltxbytes_; rx = totalrxbytes_; // pair<NetLoc, Server*> kv_pair; for (const auto& kv_pair : servers_) { vlogself(2) << "server [" << kv_pair.first.first << "]:" << kv_pair.first.second; const auto server = kv_pair.second; for (auto& c : server->connections_) { tx += c->get_total_num_sent_bytes(); rx += c->get_total_num_recv_bytes(); } } vlogself(2) << "done"; } /***************************************************/ void ConnectionManager::reset() { vlogself(1) << "begin resetting"; CHECK(!is_resetting_); is_resetting_ = true; // we don't touch the Request* pointers. // pair<NetLoc, Server*> kv_pair; servers_.clear(); timestamp_recv_first_byte_ = 0; totaltxbytes_ = totalrxbytes_ = 0; is_resetting_ = false; vlogself(1) << "done resetting"; } /***************************************************/ void ConnectionManager::release_conn(Connection *conn, const NetLoc& netloc) { vlogself(2) << "begin, releasing conn= "<< conn->objId(); // remove it from active connections CHECK(inMap(servers_, netloc)); auto& conns = servers_[netloc]->connections_; auto finditer = std::find_if( conns.begin(), conns.end(), [&](shared_ptr<Connection> const& p) { return p.get() == conn; }); CHECK(finditer != conns.end()); conns.erase(finditer); if (conns.size() == 0) { vlogself(2) << "list is now empty --> remove this list from map" << " " << servers_[netloc]->requests_.size(); for (auto req : servers_[netloc]->requests_) { notify_req_error_(req); } servers_.erase(netloc); } totaltxbytes_ += conn->get_total_num_sent_bytes(); totalrxbytes_ += conn->get_total_num_recv_bytes(); vlogself(2) << "totaltxbytes_ " << totaltxbytes_ << ", totalrxbytes_ " << totalrxbytes_; vlogself(2) << "done"; } } // end namespace http
30.041436
100
0.555034
[ "object" ]
32ed97a4ba7607bc16da4da9b748d9903ccf0363
6,043
cpp
C++
src/subcommand/gamsort_main.cpp
eldariont/vg
aa394a8477eb3f27ccfe421457e2e013e7907493
[ "BSL-1.0" ]
null
null
null
src/subcommand/gamsort_main.cpp
eldariont/vg
aa394a8477eb3f27ccfe421457e2e013e7907493
[ "BSL-1.0" ]
null
null
null
src/subcommand/gamsort_main.cpp
eldariont/vg
aa394a8477eb3f27ccfe421457e2e013e7907493
[ "BSL-1.0" ]
null
null
null
#include "../gamsorter.hpp" #include "../gam_index.hpp" #include "../stream.hpp" #include <getopt.h> #include "subcommand.hpp" #include "../index.hpp" /** * GAM sort main */ using namespace std; using namespace vg; using namespace vg::subcommand; void help_gamsort(char **argv) { cerr << "gamsort: sort a GAM file, or index a sorted GAM file" << endl << "Usage: " << argv[1] << " [Options] gamfile" << endl << "Options:" << endl << " -s / --sorted Input GAM is already sorted." << endl << " -i / --index FILE produce an index of the sorted GAM file" << endl << " -d / --dumb-sort use naive sorting algorithm (no tmp files, faster for small GAMs)" << endl << " -r / --rocks DIR Just use the old RocksDB-style indexing scheme for sorting, using the given database name." << endl << " -a / --aln-index Create the old RocksDB-style node-to-alignment index." << endl << " -p / --progress Show progress." << endl << " -t / --threads Use the specified number of threads." << endl << endl; } int main_gamsort(int argc, char **argv) { string index_filename; string rocksdb_filename; bool dumb_sort = false; bool is_sorted = false; bool do_aln_index = false; bool show_progress = false; // We limit the max threads, and only allow thread count to be lowered, to // prevent tcmalloc from giving each thread a very large heap for many // threads. // On my machine we can keep about 4 threads busy. size_t num_threads = 4; int c; optind = 2; // force optind past command positional argument while (true) { static struct option long_options[] = { {"index", required_argument, 0, 'i'}, {"dumb-sort", no_argument, 0, 'd'}, {"rocks", required_argument, 0, 'r'}, {"aln-index", no_argument, 0, 'a'}, {"is-sorted", no_argument, 0, 's'}, {"progress", no_argument, 0, 'p'}, {"threads", required_argument, 0, 't'}, {0, 0, 0, 0}}; int option_index = 0; c = getopt_long(argc, argv, "i:dhr:aspt:", long_options, &option_index); // Detect the end of the options. if (c == -1) break; switch (c) { case 'i': index_filename = optarg; break; case 'd': dumb_sort = true; break; case 's': is_sorted = true; break; case 'r': rocksdb_filename = optarg; break; case 'a': do_aln_index = true; break; case 'p': show_progress = true; break; case 't': num_threads = min(parse<size_t>(optarg), num_threads); break; case 'h': case '?': default: help_gamsort(argv); exit(1); } } if (argc < 3){ help_gamsort(argv); exit(1); } omp_set_num_threads(num_threads); get_input_file(optind, argc, argv, [&](istream& gam_in) { GAMSorter gs(show_progress); if (!rocksdb_filename.empty()) { // Do the sort the old way - write a big ol' // RocksDB index of alignments, then dump them // from that DB. Loses unmapped reads. Index rocks; unique_ptr<GAMIndex> index; if (!index_filename.empty()) { // Make a new-style GAM index also index = unique_ptr<GAMIndex>(new GAMIndex()); } // Index the alignments in RocksDB rocks.open_for_bulk_load(rocksdb_filename); int64_t aln_idx = 0; function<void(Alignment&)> lambda_reader = [&rocks](Alignment& aln) { rocks.put_alignment(aln); }; stream::for_each_parallel(gam_in, lambda_reader); // Set up the emitter stream::ProtobufEmitter<Alignment> output(cout); if (index.get() != nullptr) { output.on_group([&index](const vector<Alignment>& group, int64_t start_vo, int64_t past_end_vo) { // If we are making a sorted GAM index, record the group. // The index will outlive the emitter so this is safe to call in the emitter's destructor. index->add_group(group, start_vo, past_end_vo); }); } // Print them out again in order auto lambda_writer = [&output](const Alignment& aln) { output.write_copy(aln); }; rocks.for_each_alignment(lambda_writer); rocks.flush(); rocks.close(); if (index.get() != nullptr) { // Save the index ofstream index_out(index_filename); index->save(index_out); } } else { // Do a normal GAMSorter sort unique_ptr<GAMIndex> index; if (!index_filename.empty()) { // Make an index index = unique_ptr<GAMIndex>(new GAMIndex()); } if (dumb_sort) { // Sort in a single pass in memory gs.dumb_sort(gam_in, cout, index.get()); } else { // Sort using fan-in-limited temp file merging gs.stream_sort(gam_in, cout, index.get()); } if (index.get() != nullptr) { // Save the index ofstream index_out(index_filename); index->save(index_out); } } }); return 0; } static Subcommand vg_gamsort("gamsort", "Sort a GAM file or index a sorted GAM file.", main_gamsort);
33.203297
138
0.505709
[ "vector" ]
32fcbfb439a953d88d8d0c57205153d6bce8cf0c
797
cpp
C++
002/002.cpp
henriwoodcock/project-euler
1312b894b63eb34c6f99a5396a109103bd13fc10
[ "MIT" ]
null
null
null
002/002.cpp
henriwoodcock/project-euler
1312b894b63eb34c6f99a5396a109103bd13fc10
[ "MIT" ]
null
null
null
002/002.cpp
henriwoodcock/project-euler
1312b894b63eb34c6f99a5396a109103bd13fc10
[ "MIT" ]
null
null
null
/* 002 Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */ #include <iostream> #include <vector> int main() { std::vector<int> fib_list; fib_list.push_back(1); fib_list.push_back(2); int total; int new_num; total = 2; while(true){ new_num=fib_list.end()[-1] + fib_list.end()[-2]; if(new_num > 4000000){ break; } else { fib_list.push_back(new_num); if(new_num%2==0){ total += new_num; } } } std::cout << total << std::endl; return 0; }
22.138889
140
0.63739
[ "vector" ]
fd0d24a39300fca15b2158daf8fef0192e1899dc
8,691
cc
C++
src/sandbox/benchmark_sorting/atlas-benchmark-sorting.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
67
2018-03-01T06:56:49.000Z
2022-03-08T18:44:47.000Z
src/sandbox/benchmark_sorting/atlas-benchmark-sorting.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
93
2018-12-07T17:38:04.000Z
2022-03-31T10:04:51.000Z
src/sandbox/benchmark_sorting/atlas-benchmark-sorting.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
33
2018-02-28T17:06:19.000Z
2022-01-20T12:12:27.000Z
/* * (C) Copyright 2013 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 <cassert> #include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include <memory> #include <numeric> #include <sstream> #include <vector> #include "eckit/filesystem/PathName.h" #include "atlas/grid.h" #include "atlas/mesh.h" #include "atlas/mesh/actions/BuildHalo.h" #include "atlas/mesh/actions/BuildParallelFields.h" #include "atlas/mesh/actions/BuildPeriodicBoundaries.h" #include "atlas/meshgenerator.h" #include "atlas/output/detail/GmshIO.h" #include "atlas/parallel/mpi/mpi.h" #include "atlas/runtime/AtlasTool.h" #include "atlas/runtime/Log.h" #include "atlas/runtime/Trace.h" #include "atlas/util/Config.h" #include "atlas/array.h" #include "atlas/field/Field.h" #include "atlas/util/CoordinateEnums.h" #include "atlas/util/Unique.h" using Topology = atlas::mesh::Nodes::Topology; using atlas::util::UniqueLonLat; //------------------------------------------------------------------------------ using namespace atlas; using namespace atlas::grid; using atlas::util::Config; using eckit::PathName; //------------------------------------------------------------------------------ namespace atlas { struct Node { Node(gidx_t gid, int idx) { g = gid; i = idx; } gidx_t g; gidx_t i; bool operator<(const Node& other) const { return (g < other.g); } }; //------------------------------------------------------------------------------ void make_nodes_global_index_human_readable(const mesh::actions::BuildHalo& build_halo, mesh::Nodes& nodes, bool do_all) { ATLAS_TRACE(); // TODO: ATLAS-14: fix renumbering of EAST periodic boundary points // --> Those specific periodic points at the EAST boundary are not checked for // uid, // and could receive different gidx for different tasks UniqueLonLat compute_uid(nodes); // unused // int mypart = mpi::comm().rank(); int nparts = mpi::comm().size(); size_t root = 0; array::ArrayView<gidx_t, 1> nodes_glb_idx = array::make_view<gidx_t, 1>(nodes.global_index()); // nodes_glb_idx.dump( Log::info() ); Log::info() << std::endl; Log::info() << "min = " << nodes.global_index().metadata().getLong("min") << std::endl; Log::info() << "max = " << nodes.global_index().metadata().getLong("max") << std::endl; Log::info() << "human_readable = " << nodes.global_index().metadata().getBool("human_readable") << std::endl; gidx_t glb_idx_max = 0; std::vector<int> points_to_edit; if (do_all) { points_to_edit.resize(nodes_glb_idx.size()); for (idx_t i = 0; i < nodes_glb_idx.size(); ++i) { points_to_edit[i] = i; } } else { glb_idx_max = nodes.global_index().metadata().getLong("max", 0); points_to_edit.resize(build_halo.periodic_points_local_index_.size()); for (size_t i = 0; i < points_to_edit.size(); ++i) { points_to_edit[i] = build_halo.periodic_points_local_index_[i]; } } std::vector<gidx_t> glb_idx(points_to_edit.size()); for (size_t i = 0; i < points_to_edit.size(); ++i) { glb_idx[i] = nodes_glb_idx(i); } ATLAS_DEBUG_VAR(points_to_edit); ATLAS_DEBUG_VAR(points_to_edit.size()); ATLAS_TRACE("distributed_sort"); /* * Sorting following gidx will define global order of * gathered fields. Special care needs to be taken for * pole edges, as their centroid might coincide with * other edges */ int nb_nodes = glb_idx.size(); // 1) Gather all global indices, together with location std::vector<int> recvcounts(mpi::comm().size()); std::vector<int> recvdispls(mpi::comm().size()); ATLAS_TRACE_MPI(GATHER) { mpi::comm().gather(nb_nodes, recvcounts, root); } recvdispls[0] = 0; for (int jpart = 1; jpart < nparts; ++jpart) // start at 1 { recvdispls[jpart] = recvcounts[jpart - 1] + recvdispls[jpart - 1]; } int glb_nb_nodes = std::accumulate(recvcounts.begin(), recvcounts.end(), 0); std::vector<gidx_t> glb_idx_gathered(glb_nb_nodes); ATLAS_TRACE_MPI(GATHER) { mpi::comm().gatherv(glb_idx.data(), glb_idx.size(), glb_idx_gathered.data(), recvcounts.data(), recvdispls.data(), root); } // 2) Sort all global indices, and renumber from 1 to glb_nb_edges std::vector<Node> node_sort; node_sort.reserve(glb_nb_nodes); for (size_t jnode = 0; jnode < glb_idx_gathered.size(); ++jnode) { node_sort.emplace_back(glb_idx_gathered[jnode], jnode); } ATLAS_TRACE_SCOPE("local_sort") { std::sort(node_sort.begin(), node_sort.end()); } gidx_t gid = glb_idx_max; for (size_t jnode = 0; jnode < node_sort.size(); ++jnode) { if (jnode == 0) { ++gid; } else if (node_sort[jnode].g != node_sort[jnode - 1].g) { ++gid; } int inode = node_sort[jnode].i; glb_idx_gathered[inode] = gid; } // 3) Scatter renumbered back ATLAS_TRACE_MPI(SCATTER) { mpi::comm().scatterv(glb_idx_gathered.data(), recvcounts.data(), recvdispls.data(), glb_idx.data(), glb_idx.size(), root); } for (int jnode = 0; jnode < nb_nodes; ++jnode) { nodes_glb_idx(points_to_edit[jnode]) = glb_idx[jnode]; } // nodes_glb_idx.dump( Log::info() ); // Log::info() << std::endl; } } // namespace atlas //----------------------------------------------------------------------------- class Tool : public AtlasTool { int execute(const Args& args) override; std::string briefDescription() override { return "Tool to generate a python script that plots the grid-distribution " "of a given grid"; } std::string usage() override { return name() + " (--grid=name) [--help]"; } public: Tool(int argc, char** argv); private: std::string key; PathName path_in; PathName path_out; }; //----------------------------------------------------------------------------- Tool::Tool(int argc, char** argv): AtlasTool(argc, argv) { add_option(new SimpleOption<std::string>( "grid", "Grid unique identifier\n" + indent() + " Example values: N80, F40, O24, L32")); add_option(new SimpleOption<long>("halo", "size of halo")); add_option(new SimpleOption<bool>("do-all", "Renumber all points")); } //----------------------------------------------------------------------------- int Tool::execute(const Args& args) { Trace t(Here(), "main"); key = ""; args.get("grid", key); std::string path_in_str = ""; if (args.get("grid", path_in_str)) { path_in = path_in_str; } StructuredGrid grid; if (key.size()) { try { grid = Grid(key); } catch (eckit::Exception&) { } } else { Log::error() << "No grid specified." << std::endl; } if (!grid) { return failed(); } Log::debug() << "Domain: " << grid.domain() << std::endl; Log::debug() << "Periodic: " << grid.periodic() << std::endl; MeshGenerator meshgenerator("structured", Config("partitioner", "equal_regions")); size_t halo = args.getLong("halo", 0); bool do_all = args.getBool("do-all", false); ATLAS_DEBUG_VAR(do_all); size_t iterations = 1; mpi::comm().barrier(); for (size_t j = 0; j < 1; ++j) { ATLAS_TRACE("outer_iteration"); Mesh mesh = meshgenerator.generate(grid); atlas::mesh::actions::build_periodic_boundaries(mesh); Log::info() << "building halo" << std::endl; atlas::mesh::actions::BuildHalo build_halo(mesh); build_halo(halo); Trace::Barriers set_barrier(true); Trace::Tracing set_channel(Log::info()); for (size_t i = 0; i < iterations; ++i) { make_nodes_global_index_human_readable(build_halo, mesh.nodes(), do_all); } } t.stop(); Log::info() << Trace::report(Config("indent", 2)("decimals", 2) // ("depth",5) ); return success(); } //------------------------------------------------------------------------------ int main(int argc, char** argv) { Tool tool(argc, argv); return tool.start(); }
31.26259
113
0.579565
[ "mesh", "vector" ]
fd138e14dbdda127f688964d8f30ad92336687eb
23,051
cpp
C++
llvm/llvm/lib/Analysis/CFGHierPrinter.cpp
pooyaww/HLS
da538325ea9cb410672be6bb15d6c2e6220bfeb3
[ "Apache-2.0" ]
1
2021-04-29T08:23:03.000Z
2021-04-29T08:23:03.000Z
llvm/llvm/lib/Analysis/CFGHierPrinter.cpp
pooyaww/HLS
da538325ea9cb410672be6bb15d6c2e6220bfeb3
[ "Apache-2.0" ]
null
null
null
llvm/llvm/lib/Analysis/CFGHierPrinter.cpp
pooyaww/HLS
da538325ea9cb410672be6bb15d6c2e6220bfeb3
[ "Apache-2.0" ]
1
2021-08-02T01:23:35.000Z
2021-08-02T01:23:35.000Z
// (c) Copyright 2016-2020 Xilinx, 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 "llvm/Analysis/CFGHierPrinter.h" #include "llvm/Pass.h" #include "llvm/Support/FileSystem.h" #include "llvm/IR/Dominators.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/ADT/APInt.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Type.h" #include <sstream> using namespace llvm; cl::opt<std::string> CFGHierType("cfg-hier-type", cl::Hidden, cl::desc("The option to specify " "the type of the graph " "either \"csim\" or \"csynth\".")); cl::opt<bool> DumpAllBB("dump-all-bb", cl::desc("dump all the basic block"), cl::Hidden, cl::init(false)); cl::opt<std::string> CFGHierUserfilelist("cfg-hier-userfilelist", cl::Hidden, cl::desc("The option to specify the list of user file, " "check if function is defined by user")); namespace { struct CFGHierOnlyPrinterLegacyPass : public FunctionPass { static char ID; // Pass identification, replacement for typeid static bool isUserfileListInitialized; static std::vector<std::string> UserfileList; CFGHierOnlyPrinterLegacyPass() : FunctionPass(ID) { initializeCFGHierOnlyPrinterLegacyPassPass(*PassRegistry::getPassRegistry()); } virtual bool runOnFunction(Function &F) { //std::string Filename = "cfg." + F.getName().str() + ".dot"; //std::string Filename = "cfg_" + moveFuncNamePara(getDemangleName(&F)) + "_csim.dot"; //std::string Filename = "cfg_" + moveFuncNamePara(getDemangleName(&F)) + "_" + CFGHierType + ".dot"; std::string Filename = "cfg_" + F.getName().str() + "_" + CFGHierType + ".dot"; int FID = getFunctionID(&F); if(FID > 0) Filename = "cfg_" + std::to_string(FID) + "_" + CFGHierType + ".dot"; errs() << "Writing '" << Filename << "'..."; CFGHierOnlyPrinterLegacyPass::initializeUserfileList(); // Preprocess on BBs, insert new BB only with br instruction splitNonSISOBBs(&F); std::error_code EC; raw_fd_ostream File(Filename, EC, sys::fs::F_Text); // Initilization for necessary variables for CFG dump HierGraphFunction HG; initHierGraphFunction(&F, &HG); if (!EC) WriteHierGraph(File, &HG, true); else errs() << " error opening file for writing!"; errs() << "\n"; return false; } void print(raw_ostream &OS, const Module* = 0) const {} virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<llvm::LoopInfoWrapperPass>(); } static std::string getFullPathFileName(Function* F) { std::string res = ""; if (DISubprogram *SP = F->getSubprogram()) { if (DIFile * SourceFile = SP->getFile()) { std::string FileName = SourceFile->getFilename(); if(!FileName.empty()) { if(!llvm::sys::path::is_absolute(FileName)) { std::string DirName = SourceFile->getDirectory(); FileName = DirName + "/" + FileName; } res = getRealPath(FileName); } } } return res; } // boost::filesystem::canonical() and std::filesystem::canonical() // are the safe alternative to realpath static std::string getRealPath(std::string &FileName) { std::string Res = ""; #if defined(_WIN32) || defined(_WIN64) Res = FileName; #else char RealPath[PATH_MAX + 1]; RealPath[PATH_MAX] = 0; if (::realpath(FileName.c_str(), RealPath)) Res = RealPath; #endif return Res; } static bool splitString(std::string &str, std::vector<std::string> &result, char delimiter) { bool Changed = false; std::stringstream ss(str); // Turn the string into a stream. std::string tok; while(getline(ss, tok, delimiter)) { result.push_back(tok); Changed = true; } return Changed; } static void initializeUserfileList() { if(isUserfileListInitialized) return ; UserfileList.clear(); isUserfileListInitialized = true; if(CFGHierUserfilelist.empty()) return ; std::vector<std::string> OldUserFileList; splitString(CFGHierUserfilelist , OldUserFileList, ' '); for (unsigned i = 0; i < OldUserFileList.size(); ++i) { std::string FileName = getRealPath(OldUserFileList[i]); if(!FileName.empty()) UserfileList.push_back(FileName); } return ; } static bool isFunctionDefinedByUser(Function *F) { std::string FileName = getFullPathFileName(F); return std::find(UserfileList.begin(), UserfileList.end(), FileName) != UserfileList.end(); } bool isSISOBB(BasicBlock *BB) { if(!BB) return false; pred_iterator PI = pred_begin(BB), PE = pred_end(BB); succ_iterator SI = succ_begin(BB), SE = succ_end(BB); if(PI == PE || SI == SE) return false; else if(++PI == PE && ++SI == SE) return true; else return false; } bool isSIMOBB(BasicBlock *BB) { if(!BB) return false; pred_iterator PI = pred_begin(BB), PE = pred_end(BB); succ_iterator SI = succ_begin(BB), SE = succ_end(BB); if(PI == PE || SI == SE) return false; else if(++PI == PE && ++SI != SE) return true; else return false; } bool isMISOBB(BasicBlock *BB) { if(!BB) return false; pred_iterator PI = pred_begin(BB), PE = pred_end(BB); succ_iterator SI = succ_begin(BB), SE = succ_end(BB); if(PI == PE || SI == SE) return false; else if(++PI != PE && ++SI == SE) return true; else return false; } bool isMIMOBB(BasicBlock *BB) { if(!BB) return false; pred_iterator PI = pred_begin(BB), PE = pred_end(BB); succ_iterator SI = succ_begin(BB), SE = succ_end(BB); if(PI == PE || SI == SE) return false; else if(++PI != PE && ++SI != SE) return true; else return false; } bool isMultiPred(BasicBlock *BB) { if(!BB) return false; pred_iterator PI = pred_begin(BB), PE = pred_end(BB); if(PI == PE) return false; if(++PI != PE) return true; return false; } bool isMultiSucc(BasicBlock *BB) { if(!BB) return false; succ_iterator SI = succ_begin(BB), SE = succ_end(BB); if(SI == SE) return false; if(++SI != SE) return true; return false; } bool shouldSkip(BasicBlock *BB) { if(!BB) return true; if(BB->getTerminator() == nullptr) return true; // TODO: Added check if there call and mem options in BB return false; } bool shouldAddPredFake(BasicBlock *BB) { if(!BB) return false; if(isMultiPred(BB)) return true; if(&BB->getParent()->getEntryBlock() == BB) return true; return false; } bool shouldAddSuccFake(BasicBlock *BB) { if(!BB) return false; if(isMultiSucc(BB)) return true; if(isa<ReturnInst>(BB->getTerminator())) return true; return false; } BasicBlock *addPredFake(BasicBlock *BB, DominatorTree *DT, LoopInfo *LI) { std::string OldName = BB->getName(); BB->setName(OldName + ".predFake"); BasicBlock *NewBB = SplitBlock(BB, &*(BB->begin()), DT, LI); NewBB->setName(OldName); movePHIs(NewBB, BB); return NewBB; } BasicBlock *addSuccFake(BasicBlock *BB, DominatorTree *DT, LoopInfo *LI) { std::string OldName = BB->getName(); BasicBlock *NewBB = SplitBlock(BB, BB->getTerminator(), DT, LI); NewBB->setName(OldName + ".succFake"); return NewBB; } void movePHIs(BasicBlock *From, BasicBlock *To) { for (PHINode &PN : From->phis()) PN.moveBefore(To->getTerminator()); } void resolveLoopBBs(Loop* L, std::set<BasicBlock*> &visited) { if(!L) return; // Here not set Loop Latch NOT SISO as hidden BasicBlock *latch = L->getLoopLatch(); if(latch && !isSISOBB(latch)) visited.insert(latch); } bool initHierGraphFunction(Function *F, HierGraphFunction *HG) { HG->F = F; HG->LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); HG->TopBBs.clear(); //1. Record BBs outside of each loop, for sub graph as hier-CFG std::set<BasicBlock*> visited; for (LoopInfo::iterator I = HG->LI->begin(), E = HG->LI->end(); I != E; ++I) { Loop* L = *I; for (auto BI = L->block_begin(); BI != L->block_end(); BI++) { BasicBlock* BB = *BI; visited.insert(BB); } } for (Function::iterator BI = F->begin(); BI != F->end(); ++BI) { BasicBlock* BB = &(*BI); if (visited.count(BB) == 0) { HG->TopBBs.push_back(BB); } } //2. Record BBs as hidden visited.clear(); visited.insert(&(F->getEntryBlock())); //entry block for (LoopInfo::iterator I = HG->LI->begin(), E = HG->LI->end(); I != E; ++I) { //Latch block Loop* L = *I; resolveLoopBBs(L, visited); std::vector<Loop*> SubLoops(L->begin(), L->end()); for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) { resolveLoopBBs(SubLoops[i], visited); } } for (Function::iterator BI = F->begin(); BI != F->end(); ++BI) { BasicBlock* BB = &(*BI); if (visited.count(BB) == 0) { //1. not entry block //2. not loop latch, prehead block //3. SISO block if(!DumpAllBB && isSISOBB(BB)) { HG->HiddenBBs.insert(BB); } visited.insert(BB); } } //3. Record execution time for each BB HG->BBExeNum.clear(); collectBBExeInfo(F, HG->BBExeNum); return true; } /// splitNonSISOBBs - Splite non-SISO BBs to move most inst to hidden BBs. /// 1. collect NonSISOBBs /// 2. spilt NonSISOBBs: clear implementation to add fake node. /// 2.1 check if we should skip this BB, if yes, skip. /// the conditions for skipping node: /// (a) BB is null /// (b) Terminator is null /// (c) TODO: Added check if there call and memop in BB /// 2.2 check if we should add pred fake node for this BB, if yes, add pred fake node. /// the conditions for adding pred fake node: /// (a) entry block /// (b) have multipred /// 2.3 check if we should add succ fake node for this BB, if yes, add succ fake node. /// the conditions for adding succ fake node: /// (a) return block /// (b) have multisucc bool splitNonSISOBBs(Function *F) { LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); DominatorTree *DT = NULL; bool Changed = false; // 1. collect NonSISOBBs std::set<BasicBlock*> NonSISOBBs; for (Function::iterator BI = F->begin(); BI != F->end(); ++BI) { BasicBlock* BB = &(*BI); if(BB && !isSISOBB(BB)) NonSISOBBs.insert(BB); } // 2. spilt NonSISOBBs for (BasicBlock *BB : NonSISOBBs) { // 2.1 check if we should skip this BB if(shouldSkip(BB)) continue; BasicBlock *TmpBB = BB; // 2.2 check if we should add pred fake node for this BB if(shouldAddPredFake(TmpBB)) { TmpBB = addPredFake(TmpBB, DT, LI); Changed = true; } // 2.3 check if we should add succ fake node for this BB if(shouldAddSuccFake(TmpBB)){ TmpBB = addSuccFake(TmpBB, DT, LI); Changed = true; } } return Changed; } /// collectBBExeInfo - collect execusion times for each BB /// 1. collect BBs, from Entry, with BFS order /// 2. For each BB /// (a) If entry BB, set value directly /// (b) Add the values of all preBBs OR succBBs /// (c) If cannot caculate, caculate it next time void collectBBExeInfo(Function *F, std::map<BasicBlock*, uint64_t> &BBExeNum) { uint64_t FuncExeNum = getFuncExeNum(F); // 1. collect BBs under BFS order std::vector<BasicBlock *> BBList; BasicBlock *entry = &(F->getEntryBlock()); scanBFS(entry, BBList); // 2. For each BB, record its execution times // (2.1) First iteration std::vector<BasicBlock *> missing; for (unsigned i = 0; i < BBList.size(); ++i) { BasicBlock *BB = BBList[i]; if (!BB) continue; // (a) entry BB, execution number is directly function number if (entry == BB) { BBExeNum[BB] = FuncExeNum; #ifdef Debug_Dump_Profiling setExeNumMetadata(entry, FuncExeNum); #endif continue; } // (b) others depend on pre BB profiling values else { bool changed = setExeNumber(BB, BBExeNum); if (!changed) missing.push_back(BB); continue; } } // (2.2) multi iterations only for missing ones: bool changed = !(missing.empty()); while (changed) { changed = false; for (unsigned i = 0; i < missing.size(); ++i) { BasicBlock *BB = missing[i]; if (BBExeNum.count(BB) > 0) continue; changed = setExeNumber(BB, BBExeNum); } } #ifdef Debug_Dump_Profiling // 3. only for debug printBBExeNum(BBList, BBExeNum); #endif } // collect BBs under BFS order void scanBFS(BasicBlock *Start, std::vector<BasicBlock *> &BBList) { std::set<BasicBlock *> visited; std::vector<BasicBlock *> temp; // start from Entry BB if (!Start) return; temp.push_back(Start); while (!temp.empty()) { BasicBlock *current = temp[0]; temp.erase(temp.begin()); if (visited.insert(current).second) { BBList.push_back(current); for (succ_iterator SI = succ_begin(current), E = succ_end(current); SI != E; ++SI) { BasicBlock *next = *SI; if (next) temp.push_back(next); } } } return; } uint64_t getProfileMetadata(BasicBlock *currentBB, unsigned OperandID) { if (!hasProfileMetadata(currentBB)) return 0; Instruction *terminator = currentBB->getTerminator(); if (!terminator) return 0; if (OperandID == 0) return 0; // return the corresponding metadata value MDNode *ProfileData = terminator->getMetadata(LLVMContext::MD_prof); if (ProfileData) { uint64_t result = mdconst::extract<ConstantInt>(ProfileData->getOperand(OperandID))->getZExtValue(); return result; } return 0; } uint64_t getFuncExeNum(Function *F) { if(!F) return 0; MDNode *ProfileData = F->getMetadata(LLVMContext::MD_prof); if (ProfileData) { uint64_t result = mdconst::extract<ConstantInt>(ProfileData->getOperand(1))->getZExtValue(); return result; } return 0; } // return the ith succBB id // -1 is the invalid value; 0 is only for unconditional br int getSuccID(BasicBlock *currentBB, BasicBlock *succBB) { if (!currentBB || !succBB) return -1; Instruction *terminator = currentBB->getTerminator(); if (BranchInst *br = dyn_cast<BranchInst>(terminator)) { // (1) br directly, so 0th if (br->isUnconditional()) { return 0; } // (2) condition br, find same for (unsigned i = 0; i < br->getNumSuccessors(); ++i) { if (br->getSuccessor(i) == succBB) { // (i + 1) because profiling metadata int value starts from 1 return (i + 1); } } } else if (SwitchInst *sw = dyn_cast<SwitchInst>(terminator)) { // (3) switch, find same succ bb for (unsigned i = 0; i < sw->getNumSuccessors(); ++i) { if (sw->getSuccessor(i) == succBB) { // (i + 1) because profiling metadata int value starts from 1 return (i + 1); } } } else { // not br or switch, like ret return -1; } return -1; } uint64_t getProfileWeight(BasicBlock *currentBB, BasicBlock *succBB) { if (hasProfileMetadata(currentBB) == false) return 0; int ID = getSuccID(currentBB, succBB); if (ID <= 0) return 0; return getProfileMetadata(currentBB, ID); } bool setExeNumber(BasicBlock *BB, std::map<BasicBlock*, uint64_t> &BBExeNum) { // Try to obtain value from pre OR succ BB if (setExeNumber_Forward(BB, BBExeNum)) return true; else if (setExeNumber_Backward(BB, BBExeNum)) return true; else return false; } // execution times: add from multi pre BB bool setExeNumber_Forward(BasicBlock *BB, std::map<BasicBlock*, uint64_t> &BBExeNum) { uint64_t result = 0; for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { BasicBlock *preBB = *PI; if (!preBB) continue; if (hasProfileMetadata(preBB)) { // If profiling info exists in pre BB, use it directly result = result + (getProfileWeight(preBB, BB) - 1); continue; } else if (BBExeNum.count(preBB) > 0) { // pre BB has no profiling info, but we have caculated its exe number. result = result + BBExeNum[preBB]; continue; } else { // pre BB has no profiling info, and also no caculated exe number // then do nothing: this BB will be caculated next time return false; } } // Caculation is done, record it BBExeNum[BB] = result; #ifdef Debug_Dump_Profiling setExeNumMetadata(BB, result); #endif return true; } // execution times: add from multi succ BB bool setExeNumber_Backward(BasicBlock *BB, std::map<BasicBlock*, uint64_t> &BBExeNum) { uint64_t result = 0; for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) { BasicBlock *succBB = *SI; if (hasProfileMetadata(BB)) { // If profiling info exists in current BB, use it directly result = result + (getProfileWeight(BB, succBB) - 1); continue; } else if (BBExeNum.count(succBB) > 0) { // pre BB has no profiling info, but we have caculated its exe number. result = result + BBExeNum[succBB]; continue; } else { // succ BB has no profiling info, and also no caculated exe number // then do nothing: this BB will be caculated next time return false; } } // Caculation is done, record it BBExeNum[BB] = result; #ifdef Debug_Dump_Profiling setExeNumMetadata(BB, result); #endif return true; } // If the terminator instruction contains profiling info, return true bool hasProfileMetadata(BasicBlock *BB) { if (!BB) return false; if (Instruction *terminator = BB->getTerminator()) { MDNode *MD = terminator->getMetadata("prof"); if (MD) return true; } return false; } // set execution number to the BB terminator instruction void setExeNumMetadata(BasicBlock *BB, uint64_t value) { if (!BB) return; auto &Ctx = BB->getParent()->getContext(); Instruction *terminator = BB->getTerminator(); if (terminator) { terminator->setMetadata("exe_num", MDNode::get(Ctx, ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), value)))); } return; } // dump BBExeNum info to std output void printBBExeNum(std::vector<BasicBlock *> &BBList, std::map<BasicBlock *, uint64_t> &BBExeNum) { std::vector<BasicBlock *> missing; llvm::errs()<<"Execution times for each BB:\n"; llvm::errs()<<"===============================\n"; for (unsigned i = 0; i < BBList.size(); ++i) { BasicBlock *BB = BBList[i]; if (BBExeNum.count(BB) > 0) { llvm::errs()<<"BB:"<<BB->getName()<<"\t"; llvm::errs()<<BBExeNum[BB]<<"\n"; } else missing.push_back(BB); } llvm::errs()<<"===============================\n"; llvm::errs()<<"Missing BBs:\n"; for (unsigned i = 0; i < missing.size(); ++i) llvm::errs()<<missing[i]->getName()<<"\t"; llvm::errs()<<"\n"; llvm::errs()<<"===============================\n\n"; return; } }; } bool CFGHierOnlyPrinterLegacyPass::isUserfileListInitialized = false; std::vector<std::string> CFGHierOnlyPrinterLegacyPass::UserfileList; char CFGHierOnlyPrinterLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(CFGHierOnlyPrinterLegacyPass, "dot-cfg-hier-only", "Print Hier CFG of function to 'dot' file (with no function bodies)", false, true) INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) INITIALIZE_PASS_END(CFGHierOnlyPrinterLegacyPass, "dot-cfg-hier-only", "Print Hier CFG of function to 'dot' file (with no function bodies)", false, true) FunctionPass *llvm::createCFGHierOnlyPrinterLegacyPassPass () { return new CFGHierOnlyPrinterLegacyPass(); } bool llvm::isFunctionDefinedByUser(Function *F) { return CFGHierOnlyPrinterLegacyPass::isFunctionDefinedByUser(F); } void llvm::initializeUserfileList() { return CFGHierOnlyPrinterLegacyPass::initializeUserfileList(); }
32.883024
108
0.573771
[ "vector" ]
fd14bc731538cca66615576261bd2ee82e74b027
4,525
hpp
C++
include/window.hpp
Bicyclette/Waterpixels
ca8ba58e25adc04f7b8c75e58546d551fd055610
[ "MIT" ]
null
null
null
include/window.hpp
Bicyclette/Waterpixels
ca8ba58e25adc04f7b8c75e58546d551fd055610
[ "MIT" ]
null
null
null
include/window.hpp
Bicyclette/Waterpixels
ca8ba58e25adc04f7b8c75e58546d551fd055610
[ "MIT" ]
2
2021-05-26T16:44:52.000Z
2021-11-16T04:13:23.000Z
#ifndef APP_HPP #define APP_HPP #include <QApplication> #include <QtWidgets> #include <QObject> #include <QPixmap> #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsItem> #include <QPainter> #include <QDir> #include <iostream> #include <vector> #include <cmath> #include <clprogram.hpp> #include <thread> #include <memory> #include <utility> #include <limits> #include <algorithm> #include <queue> #include <set> #include <ctime> #include <cstdlib> #include <omp.h> struct Image { QPainter painter; QPixmap original; QPixmap smooth; QPixmap gradient; QPixmap regularizedGradient; QPixmap contours; QPixmap result; QGraphicsPixmapItem* originalItem; QGraphicsPixmapItem* smoothItem; QGraphicsPixmapItem* gradientItem; QGraphicsPixmapItem* regularizedGradientItem; QGraphicsPixmapItem* resultItem; unsigned char* originalRAW; std::unique_ptr<unsigned char[]> smoothRAW; unsigned char* gradientRAW; unsigned char* regularizedGradientRAW; std::unique_ptr<int[]> labelsMap; std::unique_ptr<unsigned char[]> contoursRAW; int width; int height; std::string name; }; struct Grid { int step; float rho; int cellCenters; QPixmap hexagonGrid; QPixmap markers; QPixmap distanceFromMarkers; QGraphicsPixmapItem* hexagonGridItem; QGraphicsPixmapItem* markersItem; QGraphicsPixmapItem* distanceFromMarkersItem; unsigned char* hexagonGridRAW; unsigned char* markersRAW; unsigned char* distanceFromMarkersRAW; std::vector<QPolygon> cells; // stride between cells is 12 => 6 points with x and y data }; class Window : public QMainWindow { Q_OBJECT public: Window(); ~Window(); void resetImageData(); public slots: void openImg(); void saveDoc(); void computeHexagonGrid(); void computeWaterpixels(); void showOriginalImage(); void hideOriginalImage(); void showSmooth(); void hideSmooth(); void showGrid(); void hideGrid(); void showGradient(); void hideGradient(); void showMarkers(); void hideMarkers(); void showDistanceMarkers(); void hideDistanceMarkers(); void showRegularizedGradient(); void hideRegularizedGradient(); void showContours(); void hideContours(); private: void createActions(); void createMenus(); void createStatusBar(); bool loadImage(const QString & path); void drawCell(const int x, const int y, const int slicesX, const int slicesY, const int hexWidth); void computeSmooth(); void computeLabGradient(); void computeCellMarkers(); void computeDistanceFromMarkers(); void computeRegularizedGradient(); void computeWatershed(); void initBasins(std::vector<std::vector<int>> & basins); void printBasins(std::vector<std::vector<int>> & basins, bool details = false); bool validIndex(int index); QMenu* menuFile; QMenu* menuImage; QMenu* menuLayer; QAction* openImageAction; QAction* saveDocAction; QAction* quitAction; QAction* computeGridAction; QAction* computeWaterpixelsAction; QAction* showOriginalImageAction; QAction* hideOriginalImageAction; QAction* showSmoothAction; QAction* hideSmoothAction; QAction* showGridAction; QAction* hideGridAction; QAction* showGradientAction; QAction* hideGradientAction; QAction* showMarkersAction; QAction* hideMarkersAction; QAction* showDistanceMarkersAction; QAction* hideDistanceMarkersAction; QAction* showRegGradientAction; QAction* hideRegGradientAction; QAction* showContoursAction; QAction* hideContoursAction; QStatusBar* status; QGraphicsScene* scene; QGraphicsView* view; CLProgram program; struct Image img; struct Grid grid; double start; double end; }; void computeCellMarkersThread( const int thr, const int numThreads, int width, int cellCenters, std::vector<int>& indices, std::vector<int>& indicesCount, unsigned char* gradient, unsigned char* markers); int growRegion( const int width, const int seedIndex, const int startIndex, const int endIndex, std::vector<int>& indices, unsigned char* gradient, const int minGradient, bool indexVisited[]); /** * return index of the found seed in the indices tab */ int validSeed(const int startIndex, const int endIndex, const int seedIndex, std::vector<int>& indices); void colorMaxRegion( const int width, const int seedIndex, const int startIndex, const int endIndex, std::vector<int>& indices, unsigned char* gradient, const int minGradient, unsigned char* markers, bool indexVisited[]); #endif
22.40099
104
0.743646
[ "vector" ]
fd16c8222eb313fd5987da9013984a8c32b60dda
17,436
cc
C++
cc/jwt/raw_jwt_test.cc
Maxmood-sec/tink
cb380f363b9ed33c75ba19da4a2e491fabe87ae6
[ "Apache-2.0" ]
1
2021-08-20T10:49:03.000Z
2021-08-20T10:49:03.000Z
cc/jwt/raw_jwt_test.cc
Maxmood-sec/tink
cb380f363b9ed33c75ba19da4a2e491fabe87ae6
[ "Apache-2.0" ]
2
2021-07-15T16:48:43.000Z
2021-08-20T01:44:20.000Z
cc/jwt/raw_jwt_test.cc
Maxmood-sec/tink
cb380f363b9ed33c75ba19da4a2e491fabe87ae6
[ "Apache-2.0" ]
1
2021-07-08T23:25:31.000Z
2021-07-08T23:25:31.000Z
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// #include "tink/jwt/raw_jwt.h" #include <string> #include "gtest/gtest.h" #include "absl/strings/escaping.h" #include "absl/time/time.h" #include "tink/util/test_matchers.h" #include "tink/util/test_util.h" using ::crypto::tink::test::IsOk; using ::crypto::tink::test::IsOkAndHolds; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::UnorderedElementsAreArray; namespace crypto { namespace tink { TEST(RawJwt, GetTypeHeaderIssuerSubjectJwtIdOK) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .SetTypeHeader("typeHeader") .SetIssuer("issuer") .SetSubject("subject") .SetJwtId("jwt_id") .WithoutExpiration() .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_TRUE(jwt.HasTypeHeader()); EXPECT_THAT(jwt.GetTypeHeader(), IsOkAndHolds("typeHeader")); EXPECT_TRUE(jwt.HasIssuer()); EXPECT_THAT(jwt.GetIssuer(), IsOkAndHolds("issuer")); EXPECT_TRUE(jwt.HasSubject()); EXPECT_THAT(jwt.GetSubject(), IsOkAndHolds("subject")); EXPECT_TRUE(jwt.HasJwtId()); EXPECT_THAT(jwt.GetJwtId(), IsOkAndHolds("jwt_id")); } TEST(RawJwt, TimestampsOK) { absl::Time nbf = absl::FromUnixSeconds(1234567890); absl::Time iat = absl::FromUnixSeconds(1234567891); absl::Time exp = absl::FromUnixSeconds(1234567892); util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .SetNotBefore(nbf) .SetIssuedAt(iat) .SetExpiration(exp) .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_TRUE(jwt.HasNotBefore()); auto nbf_or = jwt.GetNotBefore(); ASSERT_THAT(nbf_or.status(), IsOk()); EXPECT_THAT(nbf_or.ValueOrDie(), Eq(nbf)); EXPECT_TRUE(jwt.HasIssuedAt()); auto iat_or = jwt.GetIssuedAt(); ASSERT_THAT(iat_or.status(), IsOk()); EXPECT_THAT(iat_or.ValueOrDie(), Eq(iat)); EXPECT_TRUE(jwt.HasExpiration()); auto exp_or = jwt.GetExpiration(); ASSERT_THAT(exp_or.status(), IsOk()); EXPECT_THAT(exp_or.ValueOrDie(), Eq(exp)); } TEST(RawJwt, ExpWithMillisAlwaysRoundDown) { absl::Time exp = absl::FromUnixMillis(123999); util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().SetExpiration(exp).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_TRUE(jwt.HasExpiration()); auto exp_or = jwt.GetExpiration(); ASSERT_THAT(exp_or.status(), IsOk()); EXPECT_THAT(exp_or.ValueOrDie(), Eq(absl::FromUnixSeconds(123))); } TEST(RawJwt, NbfWithMillisAlwaysRoundDown) { absl::Time nbf = absl::FromUnixMillis(123999); util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().SetNotBefore(nbf).WithoutExpiration().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_TRUE(jwt.HasNotBefore()); auto nbf_or = jwt.GetNotBefore(); ASSERT_THAT(nbf_or.status(), IsOk()); EXPECT_THAT(nbf_or.ValueOrDie(), Eq(absl::FromUnixSeconds(123))); } TEST(RawJwt, IatWithMillisAlwaysRoundDown) { absl::Time iat = absl::FromUnixMillis(123999); util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().SetIssuedAt(iat).WithoutExpiration().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_TRUE(jwt.HasIssuedAt()); auto iat_or = jwt.GetIssuedAt(); ASSERT_THAT(iat_or.status(), IsOk()); EXPECT_THAT(iat_or.ValueOrDie(), Eq(absl::FromUnixSeconds(123))); } TEST(RawJwt, LargeExpirationWorks) { absl::Time large = absl::FromUnixSeconds(253402300799); // year 9999 util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .SetNotBefore(large) .SetIssuedAt(large) .SetExpiration(large) .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_TRUE(jwt.HasExpiration()); EXPECT_TRUE(jwt.HasIssuedAt()); EXPECT_TRUE(jwt.HasNotBefore()); EXPECT_THAT(jwt.GetExpiration().ValueOrDie(), Eq(large)); EXPECT_THAT(jwt.GetIssuedAt().ValueOrDie(), Eq(large)); EXPECT_THAT(jwt.GetNotBefore().ValueOrDie(), Eq(large)); } TEST(RawJwt, TooLargeTimestampsFail) { absl::Time too_large = absl::FromUnixSeconds(253402300800); // year 10000 EXPECT_FALSE(RawJwtBuilder().SetExpiration(too_large).Build().ok()); EXPECT_FALSE( RawJwtBuilder().SetIssuedAt(too_large).WithoutExpiration().Build().ok()); EXPECT_FALSE( RawJwtBuilder().SetNotBefore(too_large).WithoutExpiration().Build().ok()); } TEST(RawJwt, NegativeTimestampsFail) { absl::Time neg = absl::FromUnixMillis(-1); EXPECT_FALSE(RawJwtBuilder().SetExpiration(neg).Build().ok()); EXPECT_FALSE( RawJwtBuilder().SetIssuedAt(neg).WithoutExpiration().Build().ok()); EXPECT_FALSE( RawJwtBuilder().SetNotBefore(neg).WithoutExpiration().Build().ok()); } TEST(RawJwt, SetExpirationAndWithoutExpirationFail) { absl::Time exp = absl::FromUnixMillis(12345); EXPECT_FALSE( RawJwtBuilder().SetExpiration(exp).WithoutExpiration().Build().ok()); } TEST(RawJwt, NeitherSetExpirationNorWithoutExpirationFail) { EXPECT_FALSE(RawJwtBuilder().Build().ok()); } TEST(RawJwt, AddGetAudiencesOK) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .AddAudience("audience1") .AddAudience("audience2") .WithoutExpiration() .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); std::vector<std::string> expected = {"audience1", "audience2"}; EXPECT_TRUE(jwt.HasAudiences()); EXPECT_THAT(jwt.GetAudiences(), IsOkAndHolds(expected)); } TEST(RawJwt, GetCustomClaimOK) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .WithoutExpiration() .AddNullClaim("null_claim") .AddBooleanClaim("boolean_claim", true) .AddNumberClaim("number_claim", 123.456) .AddStringClaim("string_claim", "a string") .AddJsonObjectClaim("object_claim", R"({ "number": 123.456})") .AddJsonArrayClaim("array_claim", R"([1, "one", 1.2, true])") .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_TRUE(jwt.IsNullClaim("null_claim")); EXPECT_TRUE(jwt.HasBooleanClaim("boolean_claim")); EXPECT_THAT(jwt.GetBooleanClaim("boolean_claim"), IsOkAndHolds(true)); EXPECT_TRUE(jwt.HasNumberClaim("number_claim")); EXPECT_THAT(jwt.GetNumberClaim("number_claim"), IsOkAndHolds(123.456)); EXPECT_TRUE(jwt.HasStringClaim("string_claim")); EXPECT_THAT(jwt.GetStringClaim("string_claim"), IsOkAndHolds("a string")); EXPECT_TRUE(jwt.HasJsonObjectClaim("object_claim")); EXPECT_THAT(jwt.GetJsonObjectClaim("object_claim"), IsOkAndHolds(R"({"number":123.456})")); EXPECT_TRUE(jwt.HasJsonArrayClaim("array_claim")); EXPECT_THAT(jwt.GetJsonArrayClaim("array_claim"), IsOkAndHolds(R"([1,"one",1.2,true])")); std::vector<std::string> expected_claim_names = { "object_claim", "number_claim", "boolean_claim", "array_claim", "null_claim", "string_claim"}; EXPECT_THAT(jwt.CustomClaimNames(), UnorderedElementsAreArray(expected_claim_names)); } TEST(RawJwt, HasCustomClaimIsFalseForWrongType) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .WithoutExpiration() .AddNullClaim("null_claim") .AddBooleanClaim("boolean_claim", true) .AddNumberClaim("number_claim", 123.456) .AddStringClaim("string_claim", "a string") .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_FALSE(jwt.IsNullClaim("boolean_claim")); EXPECT_FALSE(jwt.HasBooleanClaim("number_claim")); EXPECT_FALSE(jwt.HasNumberClaim("string_claim")); EXPECT_FALSE(jwt.HasStringClaim("null_claim")); } TEST(RawJwt, HasAlwaysReturnsFalseForRegisteredClaims) { absl::Time now = absl::Now(); util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .SetIssuer("issuer") .SetSubject("subject") .SetJwtId("jwt_id") .SetNotBefore(now - absl::Seconds(300)) .SetIssuedAt(now) .SetExpiration(now + absl::Seconds(300)) .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_FALSE(jwt.HasStringClaim("iss")); EXPECT_FALSE(jwt.HasStringClaim("sub")); EXPECT_FALSE(jwt.HasStringClaim("jti")); EXPECT_FALSE(jwt.HasNumberClaim("nbf")); EXPECT_FALSE(jwt.HasNumberClaim("iat")); EXPECT_FALSE(jwt.HasNumberClaim("exp")); EXPECT_THAT(jwt.CustomClaimNames(), IsEmpty()); } TEST(RawJwt, GetRegisteredCustomClaimNotOK) { absl::Time now = absl::Now(); util::StatusOr<RawJwt> jwt_or = RawJwtBuilder() .SetIssuer("issuer") .SetSubject("subject") .SetJwtId("jwt_id") .SetNotBefore(now - absl::Seconds(300)) .SetIssuedAt(now) .SetExpiration(now + absl::Seconds(300)) .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_FALSE(jwt.GetStringClaim("iss").ok()); EXPECT_FALSE(jwt.GetStringClaim("sub").ok()); EXPECT_FALSE(jwt.GetStringClaim("jti").ok()); EXPECT_FALSE(jwt.GetNumberClaim("nbf").ok()); EXPECT_FALSE(jwt.GetNumberClaim("iat").ok()); EXPECT_FALSE(jwt.GetNumberClaim("exp").ok()); } TEST(RawJwt, SetRegisteredCustomClaimNotOK) { EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddStringClaim("iss", "issuer") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddStringClaim("sub", "issuer") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddStringClaim("jti", "issuer") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddNumberClaim("nbf", 123) .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddNumberClaim("iat", 123) .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddNumberClaim("exp", 123) .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddBooleanClaim("iss", true) .Build() .ok()); EXPECT_FALSE( RawJwtBuilder().WithoutExpiration().AddNullClaim("iss").Build().ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonObjectClaim("iss", "{\"1\": 2}") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonArrayClaim("iss", "[1,2]") .Build() .ok()); } TEST(RawJwt, SetInvalidJsonObjectClaimNotOK) { EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonObjectClaim("obj", "invalid") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonObjectClaim("obj", R"("string")") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonObjectClaim("obj", "42") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonObjectClaim("obj", "[1,2]") .Build() .ok()); } TEST(RawJwt, SetInvalidJsonArrayClaimNotOK) { EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonArrayClaim("arr", "invalid") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonArrayClaim("arr", R"("string")") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonArrayClaim("arr", "42") .Build() .ok()); EXPECT_FALSE(RawJwtBuilder() .WithoutExpiration() .AddJsonArrayClaim("arr", R"({"1": 2})") .Build() .ok()); } TEST(RawJwt, EmptyTokenHasAndIsReturnsFalse) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().WithoutExpiration().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_FALSE(jwt.HasTypeHeader()); EXPECT_FALSE(jwt.HasIssuer()); EXPECT_FALSE(jwt.HasSubject()); EXPECT_FALSE(jwt.HasAudiences()); EXPECT_FALSE(jwt.HasJwtId()); EXPECT_FALSE(jwt.HasExpiration()); EXPECT_FALSE(jwt.HasNotBefore()); EXPECT_FALSE(jwt.HasIssuedAt()); EXPECT_FALSE(jwt.IsNullClaim("null_claim")); EXPECT_FALSE(jwt.HasBooleanClaim("boolean_claim")); EXPECT_FALSE(jwt.HasNumberClaim("number_claim")); EXPECT_FALSE(jwt.HasStringClaim("string_claim")); EXPECT_FALSE(jwt.HasJsonObjectClaim("object_claim")); EXPECT_FALSE(jwt.HasJsonArrayClaim("array_claim")); } TEST(RawJwt, EmptyTokenGetReturnsNotOK) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().WithoutExpiration().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); EXPECT_FALSE(jwt.GetTypeHeader().ok()); EXPECT_FALSE(jwt.GetIssuer().ok()); EXPECT_FALSE(jwt.GetSubject().ok()); EXPECT_FALSE(jwt.GetAudiences().ok()); EXPECT_FALSE(jwt.GetJwtId().ok()); EXPECT_FALSE(jwt.GetExpiration().ok()); EXPECT_FALSE(jwt.GetNotBefore().ok()); EXPECT_FALSE(jwt.GetIssuedAt().ok()); EXPECT_FALSE(jwt.IsNullClaim("null_claim")); EXPECT_FALSE(jwt.GetBooleanClaim("boolean_claim").ok()); EXPECT_FALSE(jwt.GetNumberClaim("number_claim").ok()); EXPECT_FALSE(jwt.GetStringClaim("string_claim").ok()); EXPECT_FALSE(jwt.GetJsonObjectClaim("object_claim").ok()); EXPECT_FALSE(jwt.GetJsonArrayClaim("array_claim").ok()); } TEST(RawJwt, BuildCanBeCalledTwice) { auto builder = RawJwtBuilder() .SetIssuer("issuer") .SetSubject("subject") .WithoutExpiration(); util::StatusOr<RawJwt> jwt_or = builder.Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); builder.SetSubject("subject2"); util::StatusOr<RawJwt> jwt2_or = builder.Build(); ASSERT_THAT(jwt2_or.status(), IsOk()); auto jwt2 = jwt2_or.ValueOrDie(); EXPECT_THAT(jwt.GetIssuer(), IsOkAndHolds("issuer")); EXPECT_THAT(jwt.GetSubject(), IsOkAndHolds("subject")); EXPECT_THAT(jwt2.GetIssuer(), IsOkAndHolds("issuer")); EXPECT_THAT(jwt2.GetSubject(), IsOkAndHolds("subject2")); } TEST(RawJwt, GetJsonPayload) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().SetIssuer("issuer").WithoutExpiration().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); auto jwt = jwt_or.ValueOrDie(); ASSERT_THAT(jwt.GetJsonPayload(), IsOkAndHolds(R"({"iss":"issuer"})")); } TEST(RawJwt, GetExpirationJsonPayload) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().SetExpiration(absl::FromUnixSeconds(2218027244)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); EXPECT_THAT(jwt.GetJsonPayload(), IsOkAndHolds(R"({"exp":2218027244})")); } TEST(RawJwt, GetNanoExpirationJsonPayload) { util::StatusOr<RawJwt> jwt_or = RawJwtBuilder().SetExpiration(absl::FromUnixNanos(123456789012)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); EXPECT_THAT(jwt.GetJsonPayload(), IsOkAndHolds(R"({"exp":123})")); } } // namespace tink } // namespace crypto
37.416309
80
0.605299
[ "vector" ]
fd1b0ccb33a18a5e50b2aa69e8cc0b96d54edac3
774
cpp
C++
leetcode_solutions/others/leetcode_520.cpp
EatAllBugs/leetcode_cpp
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
[ "MIT" ]
4
2021-12-07T19:39:03.000Z
2021-12-23T09:15:08.000Z
leetcode_solutions/others/leetcode_520.cpp
EatAllBugs/leetcode_cpp
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
[ "MIT" ]
null
null
null
leetcode_solutions/others/leetcode_520.cpp
EatAllBugs/leetcode_cpp
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<limits.h> #include<algorithm> #include<numeric> #include<unordered_set> #include<cmath> using namespace std; /* 给定一个单词,你需要判断单词的大写使用是否正确。 我们定义,在以下情况时,单词的大写用法是正确的: 全部字母都是大写,比如"USA"。 单词中所有字母都不是大写,比如"leetcode"。 如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。 否则,我们定义这个单词没有正确使用大写字母。 */ class Solution { public: bool detectCapitalUse(string word) { int ans = 0; for (int i = 0; i < word.size(); i++) { if (word[i] == tolower(word[i])) { ans++; } } if (ans == word.size() || ans == 0 || (ans == 1 && word[0] != tolower(word[0]))) { return true; } return false; } }; int main() { string n = "FlaG"; Solution app; bool ans = app.detectCapitalUse(n); cout << ans << endl; return 0; }
18.428571
86
0.613695
[ "vector" ]
fd21029ab82a0e524d43108f013149b99c64a464
2,073
cc
C++
folding_libs/MELIBS/arpack++/examples/product/sym/symshft.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
1
2016-05-16T02:27:46.000Z
2016-05-16T02:27:46.000Z
arpack++/examples/product/sym/symshft.cc
red2901/sandbox
fae6c1624cc9957593d030f3b0306dbded29f0a2
[ "MIT" ]
null
null
null
arpack++/examples/product/sym/symshft.cc
red2901/sandbox
fae6c1624cc9957593d030f3b0306dbded29f0a2
[ "MIT" ]
null
null
null
/* ARPACK++ v1.2 2/18/2000 c++ interface to ARPACK code. MODULE SymShft.cc. Example program that illustrates how to solve a real symmetric standard eigenvalue problem in shift and invert mode using the ARSymStdEig class. 1) Problem description: In this example we try to solve A*x = x*lambda in shift and invert mode, where A is derived from the central difference discretization of the 1-dimensional Laplacian on [0,1] with zero Dirichlet boundary conditions. 2) Data structure used to represent matrix A: When using ARSymStdEig, the user is required to provide a class that contains a member function which computes the matrix-vector product w = OPv, where OP = inv[A - sigma*I]. In this example, this class is called SymMatrixB, and MultOPv is the function. 3) Included header files: File Contents ----------- ------------------------------------------- smatrixb.h The SymMatrixB class definition. arssym.h The ARSymStdEig class definition. symsol.h The Solution function. 4) ARPACK Authors: Richard Lehoucq Kristyn Maschhoff Danny Sorensen Chao Yang Dept. of Computational & Applied Mathematics Rice University Houston, Texas */ #include "arssym.h" #include "smatrixb.h" #include "symsol.h" template<class T> void Test(T type) { // Creating a symmetric matrix. SymMatrixB<T> A(100,0.0); // n = 100, shift = 0.0. // Defining what we need: the four eigenvectors of B nearest to 0.0. // A.MultOPv is the function that performs the product w <- OPv. ARSymStdEig<T, SymMatrixB<T> > dprob(A.ncols(), 4, &A, &SymMatrixB<T>::MultOPv, 0.0); // Finding eigenvalues and eigenvectors. dprob.FindEigenvectors(); // Printing solution. Solution(A, dprob); } // Test. int main() { // Solving a double precision problem with n = 100. Test((double)0.0); // Solving a single precision problem with n = 100. Test((float)0.0); } // main
23.827586
70
0.643512
[ "vector" ]
fd22df70bd897a54f14990fffac6271d71ebef85
1,979
hpp
C++
storage/country.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
1
2019-01-11T05:02:05.000Z
2019-01-11T05:02:05.000Z
storage/country.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
null
null
null
storage/country.hpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
1
2019-08-09T21:21:09.000Z
2019-08-09T21:21:09.000Z
#pragma once #include "storage/country_decl.hpp" #include "storage/simple_tree.hpp" #include "storage/storage_defines.hpp" #include "platform/local_country_file.hpp" #include "platform/country_defines.hpp" #include "defines.hpp" #include "geometry/rect2d.hpp" #include "base/buffer_vector.hpp" #include "std/string.hpp" #include "std/vector.hpp" namespace update { class SizeUpdater; } namespace storage { /// Serves as a proxy between GUI and downloaded files class Country { friend class update::SizeUpdater; /// Name in the country node tree string m_name; /// Flag to display string m_flag; /// stores squares with world pieces which are part of the country buffer_vector<platform::CountryFile, 1> m_files; public: Country() {} Country(string const & name, string const & flag = "") : m_name(name), m_flag(flag) {} bool operator<(Country const & other) const { return Name() < other.Name(); } void AddFile(platform::CountryFile const & file); size_t GetFilesCount() const { return m_files.size(); } /// This function valid for current logic - one file for one country (region). /// If the logic will be changed, replace GetFile with ForEachFile. platform::CountryFile const & GetFile() const { ASSERT_EQUAL(m_files.size(), 1, (m_name)); return m_files.front(); } string const & Name() const { return m_name; } string const & Flag() const { return m_flag; } uint64_t Size(MapOptions opt) const; }; typedef SimpleTree<Country> CountriesContainerT; /// @return version of country file or -1 if error was encountered int64_t LoadCountries(string const & jsonBuffer, CountriesContainerT & countries); void LoadCountryFile2CountryInfo(string const & jsonBuffer, map<string, CountryInfo> & id2info); void LoadCountryCode2File(string const & jsonBuffer, multimap<string, string> & code2file); bool SaveCountries(int64_t version, CountriesContainerT const & countries, string & jsonBuffer); } // namespace storage
27.109589
96
0.736736
[ "geometry", "vector" ]
fd285beb3f6954dae93b40122f753f6ad31a3ef7
1,789
cpp
C++
classes/gui/widgets/basic/activearea.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
24
2017-08-22T15:55:34.000Z
2022-03-06T11:41:31.000Z
classes/gui/widgets/basic/activearea.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
6
2018-07-21T12:17:55.000Z
2021-08-12T11:27:27.000Z
classes/gui/widgets/basic/activearea.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
9
2017-09-13T02:32:18.000Z
2022-03-06T11:41:32.000Z
/* The smooth Class Library * Copyright (C) 1998-2013 Robert Kausch <robert.kausch@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of "The Artistic License, Version 2.0". * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <smooth/gui/widgets/basic/activearea.h> #include <smooth/gui/widgets/hotspot/hotspot.h> #include <smooth/graphics/surface.h> const S::Short S::GUI::ActiveArea::classID = S::Object::RequestClassID(); S::GUI::ActiveArea::ActiveArea(const Color &iColor, const Point &iPos, const Size &iSize) : Widget(iPos, iSize) { type = classID; areaColor = iColor; if (GetWidth() == 0) SetWidth(80); if (GetHeight() == 0) SetHeight(20); hotspot = new Hotspot(Point(1, 1), GetSize() - Size(2, 2)); hotspot->onLeftButtonClick.Connect(&onAction); Add(hotspot); onChangeSize.Connect(&ActiveArea::OnChangeSize, this); } S::GUI::ActiveArea::~ActiveArea() { DeleteObject(hotspot); } S::Int S::GUI::ActiveArea::Paint(Int message) { if (!IsRegistered()) return Error(); if (!IsVisible()) return Success(); switch (message) { case SP_PAINT: { Surface *surface = GetDrawSurface(); Rect frame = Rect(GetRealPosition(), GetRealSize()); surface->Box(frame + Point(1, 1) - Size(2, 2), areaColor, Rect::Filled); surface->Frame(frame, FRAME_DOWN); } break; } return Success(); } S::Int S::GUI::ActiveArea::SetColor(const Color &nColor) { areaColor = nColor; Paint(SP_PAINT); return Success(); } S::Void S::GUI::ActiveArea::OnChangeSize(const Size &nSize) { hotspot->SetSize(nSize - Size(2, 2)); }
24.175676
111
0.688653
[ "object" ]
fd28d27393c36053257734c44a84cba25a684d02
14,300
cpp
C++
source/app/Application.cpp
aviktorov/pbr-sandbox
66a71c741dac2d2dd46668a506d02de88f05e399
[ "MIT" ]
19
2020-02-11T19:57:41.000Z
2022-02-20T14:11:33.000Z
source/app/Application.cpp
aviktorov/pbr-sandbox
66a71c741dac2d2dd46668a506d02de88f05e399
[ "MIT" ]
null
null
null
source/app/Application.cpp
aviktorov/pbr-sandbox
66a71c741dac2d2dd46668a506d02de88f05e399
[ "MIT" ]
5
2019-11-05T17:38:33.000Z
2022-03-04T12:49:58.000Z
#include "Application.h" #include "ApplicationResources.h" #include "IO.h" #include <render/shaders/Compiler.h> #include <render/backend/Driver.h> #include <scapes/visual/API.h> #include <scapes/visual/Components.h> #include "SwapChain.h" #include "RenderGraph.h" #include "SceneImporter.h" #include <GLFW/glfw3.h> #include <GLFW/glfw3native.h> #include "imgui.h" #include "imgui_impl_glfw.h" #include <algorithm> #include <iostream> #include <chrono> /* */ void Application::run() { initWindow(); initImGui(); initDriver(); initSwapChain(); initRenderScene(); initRenderers(); mainloop(); shutdownRenderers(); shutdownRenderScene(); shutdownSwapChain(); shutdownDriver(); shutdownImGui(); shutdownWindow(); } /* */ void Application::update() { static auto startTime = std::chrono::high_resolution_clock::now(); auto currentTime = std::chrono::high_resolution_clock::now(); float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count(); const glm::vec3 &up = {0.0f, 0.0f, 1.0f}; const glm::vec3 &zero = {0.0f, 0.0f, 0.0f}; const float viewport_width = static_cast<float>(width); const float viewport_height = static_cast<float>(height); const float aspect = viewport_width / viewport_height; const float zNear = 0.1f; const float zFar = 10000.0f; glm::vec3 cameraPos; cameraPos.x = static_cast<float>(glm::cos(camera_state.phi) * glm::cos(camera_state.theta) * camera_state.radius); cameraPos.y = static_cast<float>(glm::sin(camera_state.phi) * glm::cos(camera_state.theta) * camera_state.radius); cameraPos.z = static_cast<float>(glm::sin(camera_state.theta) * camera_state.radius); glm::vec4 cameraParams; cameraParams.x = zNear; cameraParams.y = zFar; cameraParams.z = 1.0f / zNear; cameraParams.w = 1.0f / zFar; camera_state.view = glm::lookAt(cameraPos, zero, up); camera_state.projection = glm::perspective(glm::radians(60.0f), aspect, zNear, zFar); // projection matrix is adjusted for OpenGL so we need to flip it for non-flipped backends :) if (!driver->isFlipped()) camera_state.projection[1][1] *= -1; // TODO: move to render graph // patch projection matrix for temporal supersampling const glm::vec2 &temporalSample = application_state.temporalSamples[application_state.currentTemporalFrame]; camera_state.projection[2][0] = temporalSample.x / width; camera_state.projection[2][1] = temporalSample.y / height; application_state.currentTemporalFrame = (application_state.currentTemporalFrame + 1) % ApplicationState::MAX_TEMPORAL_FRAMES; camera_state.iview = glm::inverse(camera_state.view); camera_state.iprojection = glm::inverse(camera_state.projection); camera_state.cameraPosWS = cameraPos; camera_state.cameraParams = cameraParams; application_state.currentTime = time; if (application_state.firstFrame) { camera_state.viewOld = camera_state.view; application_state.firstFrame = false; } bool reset_environment = false; ImGui::Begin("Material Parameters"); int oldCurrentEnvironment = application_state.currentEnvironment; if (ImGui::BeginCombo("Choose Your Destiny", application_resources->getIBLTexturePath(application_state.currentEnvironment))) { for (int i = 0; i < application_resources->getNumIBLTextures(); i++) { bool selected = (i == application_state.currentEnvironment); if (ImGui::Selectable(application_resources->getIBLTexturePath(i), &selected)) { application_state.currentEnvironment = i; reset_environment = true; } if (selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } ImGui::SliderFloat("Lerp User Material", &application_state.lerpUserValues, 0.0f, 1.0f); ImGui::SliderFloat("Metalness", &application_state.userMetalness, 0.0f, 1.0f); ImGui::SliderFloat("Roughness", &application_state.userRoughness, 0.0f, 1.0f); ImGui::SliderFloat("Radius", &render_graph->getSSAOKernel().cpu_data->radius, 0.0f, 100.0f); ImGui::SliderFloat("Intensity", &render_graph->getSSAOKernel().cpu_data->intensity, 0.0f, 100.0f); if (ImGui::SliderInt("Samples", (int*)&render_graph->getSSAOKernel().cpu_data->num_samples, 32, 256)) { render_graph->buildSSAOKernel(); } ImGui::SliderFloat("SSR Coarse Step Size", &render_graph->getSSRData().cpu_data->coarse_step_size, 0.0f, 200.0f); ImGui::SliderInt("SSR Num Coarse Steps", (int*)&render_graph->getSSRData().cpu_data->num_coarse_steps, 0, 128); ImGui::SliderInt("SSR Num Precision Steps", (int*)&render_graph->getSSRData().cpu_data->num_precision_steps, 0, 128); ImGui::SliderFloat("SSR Facing Threshold", (float*)&render_graph->getSSRData().cpu_data->facing_threshold, 0.0f, 1.0f); ImGui::SliderFloat("SSR Bypass Depth Threshold", (float*)&render_graph->getSSRData().cpu_data->bypass_depth_threshold, 0.0f, 5.0f); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); ImGui::Begin("GBuffer"); ImTextureID base_color_id = render_graph->fetchTextureID(render_graph->getGBuffer().base_color); ImTextureID normal_id = render_graph->fetchTextureID(render_graph->getGBuffer().normal); ImTextureID depth_id = render_graph->fetchTextureID(render_graph->getGBuffer().depth); ImTextureID shading_id = render_graph->fetchTextureID(render_graph->getGBuffer().shading); ImGui::BeginGroup(); ImGui::Image(base_color_id, ImVec2(256, 256)); ImGui::SameLine(); ImGui::Image(normal_id, ImVec2(256, 256)); ImGui::Image(depth_id, ImVec2(256, 256)); ImGui::SameLine(); ImGui::Image(shading_id, ImVec2(256, 256)); ImGui::EndGroup(); ImGui::End(); ImGui::Begin("LBuffer"); ImTextureID diffuse_id = render_graph->fetchTextureID(render_graph->getLBuffer().diffuse); ImTextureID specular_id = render_graph->fetchTextureID(render_graph->getLBuffer().specular); ImTextureID ssr_id = render_graph->fetchTextureID(render_graph->getSSRTrace().texture); ImTextureID ssao_blurred_id = render_graph->fetchTextureID(render_graph->getSSAOBlurred().texture); ImGui::BeginGroup(); ImGui::Image(diffuse_id, ImVec2(256, 256)); ImGui::SameLine(); ImGui::Image(specular_id, ImVec2(256, 256)); ImGui::Image(ssr_id, ImVec2(256, 256)); ImGui::SameLine(); ImGui::Image(ssao_blurred_id, ImVec2(256, 256)); ImGui::EndGroup(); ImGui::End(); if (reset_environment) { scapes::visual::components::SkyLight &comp = sky_light.getComponent<scapes::visual::components::SkyLight>(); comp.ibl_environment = application_resources->getIBLTexture(application_state.currentEnvironment); } } /* */ void Application::render() { render::backend::CommandBuffer *command_buffer = swap_chain->acquire(); if (!command_buffer) { recreateSwapChain(); return; } memcpy(camera_gpu_data, &camera_state, sizeof(CameraState)); memcpy(application_gpu_data, &application_state, sizeof(ApplicationState)); render_graph->render(command_buffer, swap_chain->getBackend(), application_bindings, camera_bindings); driver->submitSyncked(command_buffer, swap_chain->getBackend()); if (!swap_chain->present(command_buffer) || windowResized) { windowResized = false; recreateSwapChain(); } } void Application::postRender() { camera_state.viewOld = camera_state.view; // TODO: call render_scene->postRender(); } /* */ void Application::mainloop() { if (!window) return; while (!glfwWindowShouldClose(window)) { ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); update(); ImGui::Render(); render(); postRender(); glfwPollEvents(); } driver->wait(); } /* */ void Application::initWindow() { width = 800; height = 600; glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); window = glfwCreateWindow(width, height, "Scapes v1.0", nullptr, nullptr); glfwSetWindowUserPointer(window, this); glfwSetFramebufferSizeCallback(window, &Application::onFramebufferResize); glfwSetCursorPosCallback(window, &Application::onMousePosition); glfwSetMouseButtonCallback(window, &Application::onMouseButton); glfwSetScrollCallback(window, &Application::onScroll); } void Application::shutdownWindow() { glfwDestroyWindow(window); window = nullptr; } /* */ void Application::onFramebufferResize(GLFWwindow *window, int width, int height) { if (width == 0 || height == 0) return; Application *application = reinterpret_cast<Application *>(glfwGetWindowUserPointer(window)); assert(application != nullptr); application->windowResized = true; application->width = static_cast<uint32_t>(width); application->height = static_cast<uint32_t>(height); } void Application::onMousePosition(GLFWwindow* window, double mouseX, double mouseY) { Application *application = reinterpret_cast<Application *>(glfwGetWindowUserPointer(window)); assert(application != nullptr); if (application->input_state.rotating) { double deltaX = mouseX - application->input_state.lastMouseX; double deltaY = mouseY - application->input_state.lastMouseY; application->camera_state.phi -= deltaX * application->input_state.rotationSpeed; application->camera_state.theta += deltaY * application->input_state.rotationSpeed; application->camera_state.phi = std::fmod(application->camera_state.phi, glm::two_pi<double>()); application->camera_state.theta = std::clamp<double>(application->camera_state.theta, -glm::half_pi<double>(), glm::half_pi<double>()); } application->input_state.lastMouseX = mouseX; application->input_state.lastMouseY = mouseY; } void Application::onMouseButton(GLFWwindow* window, int button, int action, int mods) { Application *application = reinterpret_cast<Application *>(glfwGetWindowUserPointer(window)); assert(application != nullptr); if (button == GLFW_MOUSE_BUTTON_RIGHT) application->input_state.rotating = (action == GLFW_PRESS); } void Application::onScroll(GLFWwindow* window, double deltaX, double deltaY) { Application *application = reinterpret_cast<Application *>(glfwGetWindowUserPointer(window)); assert(application); application->camera_state.radius -= deltaY * application->input_state.scrollSpeed; } /* */ void Application::initRenderScene() { resource_manager = ResourceManager::create(); world = game::World::create(); visual_api = scapes::visual::API::create(resource_manager, world, driver, compiler); application_resources = new ApplicationResources(driver, visual_api); application_resources->init(); importer = new SceneImporter(world, visual_api); importer->importCGLTF("assets/scenes/blender_splash/blender_splash.glb", application_resources); sky_light = game::Entity(world); sky_light.addComponent<scapes::visual::components::SkyLight>( application_resources->getIBLTexture(0), application_resources->getFullscreenQuad(), application_resources->getShader(config::Shaders::FullscreenQuadVertex), application_resources->getShader(config::Shaders::SkylightDeferredFragment) ); } void Application::shutdownRenderScene() { delete application_resources; application_resources = nullptr; delete importer; importer = nullptr; scapes::visual::API::destroy(visual_api); visual_api = nullptr; game::World::destroy(world); world = nullptr; ResourceManager::destroy(resource_manager); resource_manager = nullptr; } /* */ void Application::initRenderers() { render_graph = new RenderGraph(driver, visual_api); render_graph->init(application_resources, width, height); const uint8_t num_columns = ApplicationState::MAX_TEMPORAL_FRAMES / 4; const uint8_t num_rows = ApplicationState::MAX_TEMPORAL_FRAMES / num_columns; // Halton 2,3 sequence const float halton2[4] = { 1.0f / 2.0f, 1.0f / 4.0f, 3.0f / 4.0f, 1.0f / 8.0f }; const float halton3[4] = { 1.0f / 3.0f, 2.0f / 3.0f, 1.0f / 9.0f, 4.0f / 9.0f }; for (uint8_t y = 0; y < num_rows; ++y) { for (uint8_t x = 0; x < num_columns; ++x) { glm::vec2 &sample = application_state.temporalSamples[x + y * num_columns]; sample.x = halton2[x]; sample.y = halton3[y]; sample = sample * 2.0f - 1.0f; } } camera_buffer = driver->createUniformBuffer(render::backend::BufferType::DYNAMIC, sizeof(CameraState)); camera_bindings = driver->createBindSet(); driver->bindUniformBuffer(camera_bindings, 0, camera_buffer); camera_gpu_data = driver->map(camera_buffer); application_buffer = driver->createUniformBuffer(render::backend::BufferType::DYNAMIC, sizeof(ApplicationState)); application_bindings = driver->createBindSet(); driver->bindUniformBuffer(application_bindings, 0, application_buffer); application_gpu_data = driver->map(application_buffer); } void Application::shutdownRenderers() { delete render_graph; render_graph = nullptr; driver->unmap(camera_buffer); driver->destroyUniformBuffer(camera_buffer); camera_buffer = nullptr; camera_gpu_data = nullptr; driver->destroyBindSet(camera_bindings); camera_bindings = nullptr; driver->unmap(application_buffer); driver->destroyUniformBuffer(application_buffer); application_buffer = nullptr; application_gpu_data = nullptr; driver->destroyBindSet(application_bindings); application_bindings = nullptr; } /* */ void Application::initImGui() { IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForVulkan(window, true); } void Application::shutdownImGui() { ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } /* */ void Application::initDriver() { file_system = new ApplicationFileSystem("assets/"); driver = render::backend::Driver::create("PBR Sandbox", "Scape", render::backend::Api::VULKAN); compiler = render::shaders::Compiler::create(render::shaders::ShaderILType::SPIRV, file_system); } void Application::shutdownDriver() { render::backend::Driver::destroy(driver); driver = nullptr; render::shaders::Compiler::destroy(compiler); compiler = nullptr; delete file_system; file_system = nullptr; } /* */ void Application::initSwapChain() { #if defined(SCAPES_PLATFORM_WIN32) void *nativeWindow = glfwGetWin32Window(window); #else void *nativeWindow = nullptr; #endif if (!swap_chain) swap_chain = new SwapChain(driver, nativeWindow); swap_chain->init(); } void Application::shutdownSwapChain() { delete swap_chain; swap_chain = nullptr; } void Application::recreateSwapChain() { driver->wait(); swap_chain->recreate(); render_graph->resize(width, height); application_state.firstFrame = true; }
29.124236
137
0.74958
[ "render" ]
fd29d28ec45acd294568e769abb1d0f24e2b0d37
5,782
hpp
C++
src/layer/common/pooling_layer-inl.hpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
114
2017-06-14T07:05:31.000Z
2021-06-13T05:30:49.000Z
src/layer/common/pooling_layer-inl.hpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
7
2017-11-17T08:16:55.000Z
2019-10-05T00:09:20.000Z
src/layer/common/pooling_layer-inl.hpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
40
2017-06-15T03:21:10.000Z
2021-10-31T15:03:30.000Z
#ifndef TEXTNET_LAYER_POOLING_LAYER_INL_HPP_ #define TEXTNET_LAYER_POOLING_LAYER_INL_HPP_ #include <iostream> #include <mshadow/tensor.h> #include "../layer.h" #include "../../utils/utils.h" namespace textnet { namespace layer { template<typename Reducer, typename xpu> class PoolingLayer : public Layer<xpu> { public: PoolingLayer(LayerType type) { this->layer_type = type; } virtual ~PoolingLayer(void) {} virtual int BottomNodeNum() { return 1; } virtual int TopNodeNum() { return 1; } virtual int ParamNodeNum() { return 0; } virtual void Require() { // default value, just set the value you want this->defaults["stride"] = SettingV(1); // require value, set to SettingV(), // it will force custom to set in config this->defaults["kernel_x"] = SettingV(); this->defaults["kernel_y"] = SettingV(); Layer<xpu>::Require(); } virtual void SetupLayer(std::map<std::string, SettingV> &setting, const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top, mshadow::Random<xpu> *prnd) { Layer<xpu>::SetupLayer(setting, bottom, top, prnd); utils::Check(bottom.size() == BottomNodeNum(), "PoolingLayer:bottom size problem."); utils::Check(top.size() == TopNodeNum(), "PoolingLayer:top size problem."); kernel_x = setting["kernel_x"].iVal(); kernel_y = setting["kernel_y"].iVal(); stride = setting["stride"].iVal(); } virtual void Reshape(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top, bool show_info = false) { utils::Check(bottom.size() == BottomNodeNum(), "PoolingLayer:bottom size problem."); utils::Check(top.size() == TopNodeNum(), "PoolingLayer:top size problem."); channel = bottom[0]->data.size(1); mshadow::Shape<4> shape_in = bottom[0]->data.shape_; mshadow::Shape<4> shape_out = mshadow::Shape4(shape_in[0], shape_in[1], (shape_in[2] - kernel_y) / stride + 1, (shape_in[3] - kernel_x) / stride + 1); mshadow::Shape<2> shape_len = bottom[0]->length.shape_; top[0]->Resize(shape_out, shape_len); // std::cout << shape_in[0] << "x" << shape_in[1] << "x" << shape_in[2] << "x" << shape_in[3] << std::endl; // std::cout << shape_out[0] << "x" << shape_out[1] << "x" << shape_out[2] << "x" << shape_out[3] << std::endl; if (show_info) { bottom[0]->PrintShape("bottom0"); top[0]->PrintShape("top0"); } } virtual void CheckReshape(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { // Check for reshape bool need_reshape = false; mshadow::Shape<4> shape_in = bottom[0]->data.shape_; mshadow::Shape<4> shape_out = mshadow::Shape4(shape_in[0], shape_in[1], (shape_in[2] - kernel_y) / stride + 1, (shape_in[3] - kernel_x) / stride + 1); if (! (shape_out == top[0]->data.shape_)) { need_reshape = true; } // Do reshape if (need_reshape) { this->Reshape(bottom, top); } } virtual void Forward(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { using namespace mshadow::expr; mshadow::Tensor<xpu, 4> bottom_data = bottom[0]->data; mshadow::Tensor<xpu, 4> top_data = top[0]->data; mshadow::Tensor<xpu, 2> top_len = top[0]->length; mshadow::Tensor<xpu, 2> bottom_len = bottom[0]->length; mshadow::Shape<2> pshape = top_data[0][0].shape_; for (int i = 0; i < top_len.shape_[0]; ++i) { top_len[i][0] = ((int)bottom_len[i][0] - kernel_y) / stride + 1; if (top_len[i][0] <= 0) { top_len[i][0] = 1; } if (bottom_len.shape_[1] == 2) { top_len[i][1] = ((int)bottom_len[i][1] - kernel_x) / stride + 1; if (top_len[i][1] <= 0) { top_len[i][1] = 1; } } } if (this->layer_type == kMaxPooling) { top_data = pool<Reducer>(bottom_data, pshape, kernel_y, kernel_x, stride); } else if (this->layer_type == kAvgPooling) { top_data = pool<Reducer>(bottom_data, pshape, kernel_y, kernel_x, stride) * (1.0f / (kernel_y*kernel_x)); } else if (this->layer_type == kSumPooling) { top_data = pool<Reducer>(bottom_data, pshape, kernel_y, kernel_x, stride); } else { utils::Error("Unknown pooling mode"); } } virtual void Backprop(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { using namespace mshadow::expr; mshadow::Tensor<xpu, 4> top_data = top[0]->data; mshadow::Tensor<xpu, 4> top_diff = top[0]->diff; mshadow::Tensor<xpu, 4> bottom_data = bottom[0]->data; mshadow::Tensor<xpu, 4> bottom_diff = bottom[0]->diff; if (this->prop_error[0]) { if (this->layer_type == kMaxPooling) { bottom_diff += unpool<Reducer>(bottom_data, top_data, top_diff, kernel_y, kernel_x, stride); } else if (this->layer_type == kAvgPooling) { bottom_diff += unpool<Reducer>(bottom_data, top_data, top_diff, kernel_y, kernel_x, stride) * (1.0f / (kernel_y*kernel_x)); } else if (this->layer_type == kSumPooling) { bottom_diff += unpool<Reducer>(bottom_data, top_data, top_diff, kernel_y, kernel_x, stride); } else { utils::Error("Unknown pooling mode"); } } } protected: int kernel_x; int kernel_y; int stride; int channel; }; // class PoolingLayer } // namespace layer } // namespace textnet #endif // LAYER_POOLING_LAYER_INL_HPP_
36.36478
115
0.586302
[ "shape", "vector" ]
fd4692a5792d259ae6c6afc950bf44f412cb6823
81,306
cpp
C++
relational_operators/tests/AggregationOperator_unittest.cpp
craig-chasseur/incubator-quickstep
00ca1e4b3a9c9838dcb9509058b8a40b0f573617
[ "Apache-2.0" ]
null
null
null
relational_operators/tests/AggregationOperator_unittest.cpp
craig-chasseur/incubator-quickstep
00ca1e4b3a9c9838dcb9509058b8a40b0f573617
[ "Apache-2.0" ]
null
null
null
relational_operators/tests/AggregationOperator_unittest.cpp
craig-chasseur/incubator-quickstep
00ca1e4b3a9c9838dcb9509058b8a40b0f573617
[ "Apache-2.0" ]
1
2021-12-04T18:48:44.000Z
2021-12-04T18:48:44.000Z
/** * Copyright 2011-2015 Quickstep Technologies LLC. * Copyright 2015-2016 Pivotal Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "catalog/CatalogAttribute.hpp" #include "catalog/CatalogDatabase.hpp" #include "catalog/CatalogRelation.hpp" #include "catalog/CatalogTypedefs.hpp" #include "expressions/Expressions.pb.h" #include "expressions/aggregation/AggregateFunction.hpp" #include "expressions/aggregation/AggregateFunction.pb.h" #include "expressions/aggregation/AggregateFunctionFactory.hpp" #include "expressions/aggregation/AggregationID.hpp" #include "expressions/predicate/ComparisonPredicate.hpp" #include "expressions/predicate/Predicate.hpp" #include "expressions/scalar/Scalar.hpp" #include "expressions/scalar/ScalarAttribute.hpp" #include "expressions/scalar/ScalarBinaryExpression.hpp" #include "expressions/scalar/ScalarLiteral.hpp" #include "query_execution/QueryContext.hpp" #include "query_execution/QueryContext.pb.h" #include "query_execution/QueryExecutionTypedefs.hpp" #include "query_execution/WorkOrdersContainer.hpp" #include "relational_operators/AggregationOperator.hpp" #include "relational_operators/FinalizeAggregationOperator.hpp" #include "relational_operators/WorkOrder.hpp" #include "storage/AggregationOperationState.pb.h" #include "storage/HashTable.pb.h" #include "storage/InsertDestination.hpp" #include "storage/InsertDestination.pb.h" #include "storage/StorageBlock.hpp" #include "storage/StorageBlockInfo.hpp" #include "storage/StorageBlockLayout.hpp" #include "storage/StorageManager.hpp" #include "storage/TupleStorageSubBlock.hpp" #include "threading/ThreadIDBasedMap.hpp" #include "types/DoubleType.hpp" #include "types/FloatType.hpp" #include "types/IntType.hpp" #include "types/LongType.hpp" #include "types/TypedValue.hpp" #include "types/containers/Tuple.hpp" #include "types/operations/binary_operations/BinaryOperationFactory.hpp" #include "types/operations/binary_operations/BinaryOperationID.hpp" #include "types/operations/comparisons/ComparisonFactory.hpp" #include "types/operations/comparisons/ComparisonID.hpp" #include "utility/PtrList.hpp" #include "gflags/gflags.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "tmb/id_typedefs.h" using std::unique_ptr; namespace quickstep { namespace { constexpr std::size_t kQueryId = 0; constexpr int kOpIndex = 0; } // namespace class Type; class AggregationOperatorTest : public ::testing::Test { public: static const tuple_id kNumTuples = 300; static const int kGroupByWidth = 20; static const int kGroupByRepeats = kNumTuples / kGroupByWidth; static const int kGroupBy1Size = 4; static const int kGroupBy2Size = kGroupByWidth / kGroupBy1Size; protected: static const char kStoragePath[]; static const char kDatabaseName[]; static const char kTableName[]; static const relation_id kTableId = 100; static const relation_id kResultTableId = kTableId + 1; static const int kTuplesOffset = 20; static const tuple_id kNumTuplesPerBlock = 10; // Constants to help in readablity of test instantiations. static const bool kExpression = true; static const bool kAttribute = false; static const bool kWithPredicate = true; static const bool kWithoutPredicate = false; static const int kPlaceholder = 0xbeef; virtual void SetUp() { thread_id_map_ = ClientIDMap::Instance(); bus_.Initialize(); const tmb::client_id worker_thread_client_id = bus_.Connect(); bus_.RegisterClientAsSender(worker_thread_client_id, kCatalogRelationNewBlockMessage); // Usually the worker thread makes the following call. In this test setup, // we don't have a worker thread hence we have to explicitly make the call. thread_id_map_->addValue(worker_thread_client_id); foreman_client_id_ = bus_.Connect(); bus_.RegisterClientAsReceiver(foreman_client_id_, kCatalogRelationNewBlockMessage); storage_manager_.reset(new StorageManager(kStoragePath)); // Create a database. db_.reset(new CatalogDatabase(nullptr, kDatabaseName)); // Create a table, owned by db_. table_ = new CatalogRelation(nullptr, kTableName, kTableId); db_->addRelation(table_); // Add attributes. const Type &long_type = LongType::InstanceNonNullable(); const Type &int_type = IntType::InstanceNonNullable(); const Type &float_type = FloatType::InstanceNonNullable(); const Type &double_type = DoubleType::InstanceNonNullable(); table_->addAttribute(new CatalogAttribute(table_, "GroupBy-0", int_type)); table_->addAttribute(new CatalogAttribute(table_, "GroupBy-1", int_type)); table_->addAttribute(new CatalogAttribute(table_, "IntType-0", int_type)); table_->addAttribute(new CatalogAttribute(table_, "IntType-1", int_type)); table_->addAttribute(new CatalogAttribute(table_, "LongType-0", long_type)); table_->addAttribute(new CatalogAttribute(table_, "LongType-1", long_type)); table_->addAttribute(new CatalogAttribute(table_, "FloatType-0", float_type)); table_->addAttribute(new CatalogAttribute(table_, "FloatType-1", float_type)); table_->addAttribute(new CatalogAttribute(table_, "DoubleType-0", double_type)); table_->addAttribute(new CatalogAttribute(table_, "DoubleType-1", double_type)); std::unique_ptr<StorageBlockLayout> layout( StorageBlockLayout::GenerateDefaultLayout(*table_, table_->isVariableLength())); // Insert tuples to table. std::unique_ptr<Tuple> tuple; MutableBlockReference storage_block; for (tuple_id i = 0; i < kNumTuples; i += kNumTuplesPerBlock) { // Create block block_id block_id = storage_manager_->createBlock(*table_, *layout); storage_block = storage_manager_->getBlockMutable(block_id, *table_); table_->addBlock(block_id); // Insert tuples tuple_id block_bound = i + kNumTuplesPerBlock < kNumTuples ? i + kNumTuplesPerBlock : kNumTuples; for (tuple_id tid = i; tid < block_bound; ++tid) { tuple.reset(createTuple(*table_, tid)); EXPECT_TRUE(storage_block->insertTupleInBatch(*tuple)); } storage_block->rebuild(); } } virtual void TearDown() { thread_id_map_->removeValue(); // Drop blocks from relations. const std::vector<block_id> table_blocks = table_->getBlocksSnapshot(); for (const block_id block : table_blocks) { storage_manager_->deleteBlockOrBlobFile(block); } const std::vector<block_id> result_table_blocks = result_table_->getBlocksSnapshot(); for (const block_id block : result_table_blocks) { storage_manager_->deleteBlockOrBlobFile(block); } } Tuple* createTuple(const CatalogRelation &relation, const std::int64_t val) { int group_by_id = val % kGroupByWidth; std::vector<TypedValue> attributes; attributes.push_back(TypedValue(static_cast<IntType::cpptype>(group_by_id % kGroupBy1Size))); attributes.push_back(TypedValue(static_cast<IntType::cpptype>(group_by_id / kGroupBy1Size))); attributes.push_back(TypedValue(static_cast<IntType::cpptype>(val))); attributes.push_back(TypedValue(static_cast<IntType::cpptype>(val))); attributes.push_back(TypedValue(static_cast<LongType::cpptype>(val))); attributes.push_back(TypedValue(static_cast<LongType::cpptype>(val))); attributes.push_back(TypedValue(static_cast<FloatType::cpptype>(0.1 * val))); attributes.push_back(TypedValue(static_cast<FloatType::cpptype>(0.1 * val))); attributes.push_back(TypedValue(static_cast<DoubleType::cpptype>(0.1 * val))); attributes.push_back(TypedValue(static_cast<DoubleType::cpptype>(0.1 * val))); return new Tuple(std::move(attributes)); } PtrList<Scalar>* makeGroupByAttributes() { PtrList<Scalar> *attributes = new PtrList<Scalar>(); attributes->push_back(new ScalarAttribute(*table_->getAttributeByName("GroupBy-0"))); attributes->push_back(new ScalarAttribute(*table_->getAttributeByName("GroupBy-1"))); return attributes; } Predicate* makeLessThanPredicate(int value) { Scalar *left = new ScalarAttribute(*table_->getAttributeByName("IntType-0")); Scalar *right = new ScalarLiteral(TypedValue(value), IntType::InstanceNonNullable()); return new ComparisonPredicate(ComparisonFactory::GetComparison(ComparisonID::kLess), left, right); } void setupTest(const std::string &stem, const AggregationID agg_type, const bool is_expression, const bool with_predicate, const Type &result_type, const int predicate_value) { // Setup results table, owned by db_. result_table_ = new CatalogRelation(nullptr, "result_table", kResultTableId); db_->addRelation(result_table_); result_table_->addAttribute(new CatalogAttribute(result_table_, "result-0", result_type)); result_table_->addAttribute(new CatalogAttribute(result_table_, "result-1", result_type)); // Setup the aggregation state proto in the query context proto. serialization::QueryContext query_context_proto; query_context_proto.set_query_id(0); // dummy query ID. const QueryContext::aggregation_state_id aggr_state_index = query_context_proto.aggregation_states_size(); serialization::AggregationOperationState *aggr_state_proto = query_context_proto.add_aggregation_states(); aggr_state_proto->set_relation_id(table_->getID()); // Add an aggregate. serialization::Aggregate *aggr_proto = aggr_state_proto->add_aggregates(); aggr_proto->mutable_function()->CopyFrom(AggregateFunctionFactory::Get(agg_type).getProto()); aggr_proto->set_is_distinct(false); if (is_expression) { unique_ptr<ScalarBinaryExpression> exp( new ScalarBinaryExpression(BinaryOperationFactory::GetBinaryOperation(BinaryOperationID::kAdd), new ScalarAttribute(*table_->getAttributeByName(stem + "-0")), new ScalarAttribute(*table_->getAttributeByName(stem + "-1")))); aggr_proto->add_argument()->CopyFrom(exp->getProto()); } else { unique_ptr<ScalarAttribute> attr(new ScalarAttribute(*table_->getAttributeByName(stem + "-0"))); aggr_proto->add_argument()->CopyFrom(attr->getProto()); } // Add another aggregate. aggr_proto = aggr_state_proto->add_aggregates(); aggr_proto->mutable_function()->CopyFrom(AggregateFunctionFactory::Get(agg_type).getProto()); aggr_proto->set_is_distinct(false); if (is_expression) { unique_ptr<ScalarBinaryExpression> exp( new ScalarBinaryExpression(BinaryOperationFactory::GetBinaryOperation(BinaryOperationID::kMultiply), new ScalarAttribute(*table_->getAttributeByName(stem + "-0")), new ScalarAttribute(*table_->getAttributeByName(stem + "-1")))); aggr_proto->add_argument()->CopyFrom(exp->getProto()); } else { unique_ptr<ScalarAttribute> attr(new ScalarAttribute(*table_->getAttributeByName(stem + "-1"))); aggr_proto->add_argument()->CopyFrom(attr->getProto()); } if (with_predicate) { unique_ptr<Predicate> predicate(makeLessThanPredicate(predicate_value)); aggr_state_proto->mutable_predicate()->CopyFrom(predicate->getProto()); } std::size_t estimated_entries = 0.1*table_->estimateTupleCardinality(); aggr_state_proto->set_estimated_num_entries(estimated_entries); // Create Operators. op_.reset(new AggregationOperator(0, *table_, true, aggr_state_index)); // Setup the InsertDestination proto in the query context proto. const QueryContext::insert_destination_id insert_destination_index = query_context_proto.insert_destinations_size(); serialization::InsertDestination *insert_destination_proto = query_context_proto.add_insert_destinations(); insert_destination_proto->set_insert_destination_type(serialization::InsertDestinationType::BLOCK_POOL); insert_destination_proto->set_relation_id(result_table_->getID()); insert_destination_proto->set_relational_op_index(kOpIndex); finalize_op_.reset( new FinalizeAggregationOperator(kQueryId, aggr_state_index, *result_table_, insert_destination_index)); // Set up the QueryContext. query_context_.reset(new QueryContext(query_context_proto, *db_, storage_manager_.get(), foreman_client_id_, &bus_)); // Note: We treat these two operators as different query plan DAGs. The // index for each operator should be set, so that the WorkOrdersContainer // class' checks about operator index are successful. op_->setOperatorIndex(kOpIndex); finalize_op_->setOperatorIndex(kOpIndex); } void setupTestGroupBy(const std::string &stem, const AggregationID agg_type, const bool with_predicate, const Type &result_type, const int predicate_value) { // Setup results table, owned by db_. const Type &int_type = IntType::InstanceNonNullable(); result_table_ = new CatalogRelation(nullptr, "result_table", kResultTableId); db_->addRelation(result_table_); result_table_->addAttribute(new CatalogAttribute(result_table_, "GroupBy-0", int_type)); result_table_->addAttribute(new CatalogAttribute(result_table_, "GroupBy-1", int_type)); result_table_->addAttribute(new CatalogAttribute(result_table_, "result-0", result_type)); result_table_->addAttribute(new CatalogAttribute(result_table_, "result-1", result_type)); // Setup the aggregation state proto in the query context proto. serialization::QueryContext query_context_proto; query_context_proto.set_query_id(0); // dummy query ID. const QueryContext::aggregation_state_id aggr_state_index = query_context_proto.aggregation_states_size(); serialization::AggregationOperationState *aggr_state_proto = query_context_proto.add_aggregation_states(); aggr_state_proto->set_relation_id(table_->getID()); // Add an aggregate. serialization::Aggregate *aggr_proto = aggr_state_proto->add_aggregates(); aggr_proto->mutable_function()->CopyFrom(AggregateFunctionFactory::Get(agg_type).getProto()); aggr_proto->set_is_distinct(false); unique_ptr<ScalarAttribute> attr(new ScalarAttribute(*table_->getAttributeByName(stem + "-0"))); aggr_proto->add_argument()->CopyFrom(attr->getProto()); // Add another aggregate. aggr_proto = aggr_state_proto->add_aggregates(); aggr_proto->mutable_function()->CopyFrom(AggregateFunctionFactory::Get(agg_type).getProto()); aggr_proto->set_is_distinct(false); attr.reset(new ScalarAttribute(*table_->getAttributeByName(stem + "-1"))); aggr_proto->add_argument()->CopyFrom(attr->getProto()); if (with_predicate) { unique_ptr<Predicate> predicate(makeLessThanPredicate(predicate_value)); aggr_state_proto->mutable_predicate()->CopyFrom(predicate->getProto()); } unique_ptr<PtrList<Scalar>> group_by_expressions(makeGroupByAttributes()); for (const Scalar &group_by_expression : *group_by_expressions) { aggr_state_proto->add_group_by_expressions()->CopyFrom(group_by_expression.getProto()); } std::size_t estimated_entries = 0.1 * table_->estimateTupleCardinality(); aggr_state_proto->set_estimated_num_entries(estimated_entries); // Also need to set the HashTable implementation for GROUP BY. aggr_state_proto->set_hash_table_impl_type( serialization::HashTableImplType::LINEAR_OPEN_ADDRESSING); // Create Operators. op_.reset(new AggregationOperator(0, *table_, true, aggr_state_index)); // Setup the InsertDestination proto in the query context proto. const QueryContext::insert_destination_id insert_destination_index = query_context_proto.insert_destinations_size(); serialization::InsertDestination *insert_destination_proto = query_context_proto.add_insert_destinations(); insert_destination_proto->set_insert_destination_type(serialization::InsertDestinationType::BLOCK_POOL); insert_destination_proto->set_relation_id(result_table_->getID()); insert_destination_proto->set_relational_op_index(kOpIndex); finalize_op_.reset( new FinalizeAggregationOperator(kQueryId, aggr_state_index, *result_table_, insert_destination_index)); // Set up the QueryContext. query_context_.reset(new QueryContext(query_context_proto, *db_, storage_manager_.get(), foreman_client_id_, &bus_)); // Note: We treat these two operators as different query plan DAGs. The // index for each operator should be set, so that the WorkOrdersContainer // class' checks about operator index are successful. op_->setOperatorIndex(kOpIndex); finalize_op_->setOperatorIndex(kOpIndex); } void execute() { const std::size_t op_index = 0; WorkOrdersContainer op_container(1, 0); op_->getAllWorkOrders(&op_container, query_context_.get(), storage_manager_.get(), foreman_client_id_, &bus_); while (op_container.hasNormalWorkOrder(op_index)) { WorkOrder *work_order = op_container.getNormalWorkOrder(op_index); work_order->execute(); delete work_order; } finalize_op_->informAllBlockingDependenciesMet(); WorkOrdersContainer finalize_op_container(1, 0); const std::size_t finalize_op_index = 0; finalize_op_->getAllWorkOrders(&finalize_op_container, query_context_.get(), storage_manager_.get(), foreman_client_id_, &bus_); while (finalize_op_container.hasNormalWorkOrder(finalize_op_index)) { WorkOrder *work_order = finalize_op_container.getNormalWorkOrder(finalize_op_index); work_order->execute(); delete work_order; } } template <class T> void checkResult(T expected0, T expected1, std::function<void(T, TypedValue)> test) { DCHECK(query_context_); InsertDestination *insert_destination = query_context_->getInsertDestination(finalize_op_->getInsertDestinationID()); DCHECK(insert_destination); const std::vector<block_id> result = insert_destination->getTouchedBlocks(); ASSERT_EQ(1u, result.size()); BlockReference block = storage_manager_->getBlock(result[0], insert_destination->getRelation()); const TupleStorageSubBlock &sub_block = block->getTupleStorageSubBlock(); ASSERT_EQ(1, sub_block.numTuples()); ASSERT_TRUE(sub_block.hasTupleWithID(0)); const TypedValue actual0 = sub_block.getAttributeValueTyped(0, result_table_->getAttributeByName("result-0")->getID()); const TypedValue actual1 = sub_block.getAttributeValueTyped(0, result_table_->getAttributeByName("result-1")->getID()); test(expected0, actual0); test(expected1, actual1); // Drop the block. block.release(); storage_manager_->deleteBlockOrBlobFile(result[0]); } template <class FinalDataType> void testAggregationOperator(const std::string &stem, const AggregationID agg_type, const bool is_expression, const bool with_predicate, const typename FinalDataType::cpptype expected0, const typename FinalDataType::cpptype expected1, std::function<void(typename FinalDataType::cpptype, TypedValue)> check_fn, const int predicate_value = 30) { setupTest(stem, agg_type, is_expression, with_predicate, FinalDataType::InstanceNullable(), predicate_value); execute(); checkResult<typename FinalDataType::cpptype>(expected0, expected1, check_fn); } void checkGroupByResult(std::function<void(int, const TypedValue &, const TypedValue &)> check_fn, std::size_t num_tuples) { DCHECK(query_context_); InsertDestination *insert_destination = query_context_->getInsertDestination(finalize_op_->getInsertDestinationID()); DCHECK(insert_destination); const std::vector<block_id> result = insert_destination->getTouchedBlocks(); std::size_t total_tuples = 0; for (size_t bid = 0; bid < result.size(); ++bid) { BlockReference block = storage_manager_->getBlock(result[bid], insert_destination->getRelation()); const TupleStorageSubBlock &sub_block = block->getTupleStorageSubBlock(); ASSERT_TRUE(sub_block.isPacked()); for (tuple_id tid = 0; tid < sub_block.numTuples(); ++tid) { const TypedValue group_by_1 = sub_block.getAttributeValueTyped(tid, result_table_->getAttributeByName("GroupBy-0")->getID()); const TypedValue group_by_2 = sub_block.getAttributeValueTyped(tid, result_table_->getAttributeByName("GroupBy-1")->getID()); int group_by_id = group_by_1.getLiteral<int>() + (group_by_2.getLiteral<int>() * kGroupBy1Size); const TypedValue actual0 = sub_block.getAttributeValueTyped(tid, result_table_->getAttributeByName("result-0")->getID()); const TypedValue actual1 = sub_block.getAttributeValueTyped(tid, result_table_->getAttributeByName("result-1")->getID()); check_fn(group_by_id, actual0, actual1); } total_tuples += sub_block.numTuples(); // Drop the block. block.release(); storage_manager_->deleteBlockOrBlobFile(result[bid]); } EXPECT_EQ(num_tuples, total_tuples); } template <class FinalDataType> void testAggregationOperatorWithGroupBy(const std::string &stem, const AggregationID agg_type, const bool with_predicate, std::function<void(int, const TypedValue &, const TypedValue &)> check_fn, std::size_t num_tuples, const int predicate_value = kGroupByWidth * (kGroupByRepeats >> 1)) { setupTestGroupBy(stem, agg_type, with_predicate, FinalDataType::InstanceNullable(), predicate_value); execute(); checkGroupByResult(check_fn, num_tuples); } // This map is needed for InsertDestination and some WorkOrders that send // messages to Foreman directly. To know the reason behind the design of this // map, see the note in InsertDestination.hpp. ClientIDMap *thread_id_map_; MessageBusImpl bus_; tmb::client_id foreman_client_id_; std::unique_ptr<QueryContext> query_context_; std::unique_ptr<StorageManager> storage_manager_; std::unique_ptr<CatalogDatabase> db_; // The following two CatalogRelations are owned by db_. CatalogRelation *table_, *result_table_; std::unique_ptr<AggregationOperator> op_; std::unique_ptr<FinalizeAggregationOperator> finalize_op_; }; const char AggregationOperatorTest::kDatabaseName[] = "database"; const char AggregationOperatorTest::kTableName[] = "table"; const char AggregationOperatorTest::kStoragePath[] = "./aggregation_operator_test_data"; namespace { // Summation 1, 2, ..., n std::int64_t Summation(int n) { return (n + 1) * n / 2; } // Summation 1*1, 2*2, 3*3, ..., n*n std::int64_t SummationSquares(int n) { return n * (n + 1) * (2 * n + 1) / 6; } template <class T> void CheckLiteral(T expected, TypedValue actual) { EXPECT_EQ(expected, actual.getLiteral<T>()); } template <class T> void CheckNear(T expected, TypedValue actual) { EXPECT_NEAR(expected, actual.getLiteral<T>(), expected * 1e-5); } } // namespace TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Sum_withoutPredicate) { // Sum of IntType is LongType. testAggregationOperator<LongType>("IntType", AggregationID::kSum, kAttribute, kWithoutPredicate, Summation(299), Summation(299), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Sum_withoutPredicate) { testAggregationOperator<LongType>("LongType", AggregationID::kSum, kAttribute, kWithoutPredicate, Summation(299), Summation(299), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Sum_withoutPredicate) { // Sum of FloatType is DoubleType. testAggregationOperator<DoubleType>("FloatType", AggregationID::kSum, kAttribute, kWithoutPredicate, 0.1 * Summation(299), 0.1 * Summation(299), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Sum_withoutPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kSum, kAttribute, kWithoutPredicate, 0.1 * Summation(299), 0.1 * Summation(299), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("IntType", AggregationID::kAvg, kAttribute, kWithoutPredicate, Summation(299) / 300.0, Summation(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("LongType", AggregationID::kAvg, kAttribute, kWithoutPredicate, Summation(299) / 300.0, Summation(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("FloatType", AggregationID::kAvg, kAttribute, kWithoutPredicate, 0.1 * Summation(299) / 300.0, 0.1 * Summation(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kAvg, kAttribute, kWithoutPredicate, 0.1 * Summation(299) / 300.0, 0.1 * Summation(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Max_withoutPredicate) { testAggregationOperator<IntType>( "IntType", AggregationID::kMax, kAttribute, kWithoutPredicate, 299, 299, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Max_withoutPredicate) { testAggregationOperator<LongType>( "LongType", AggregationID::kMax, kAttribute, kWithoutPredicate, 299, 299, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Max_withoutPredicate) { testAggregationOperator<FloatType>( "FloatType", AggregationID::kMax, kAttribute, kWithoutPredicate, 29.9, 29.9, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Max_withoutPredicate) { testAggregationOperator<DoubleType>( "DoubleType", AggregationID::kMax, kAttribute, kWithoutPredicate, 29.9, 29.9, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Min_withoutPredicate) { testAggregationOperator<IntType>( "IntType", AggregationID::kMin, kAttribute, kWithoutPredicate, 0, 0, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Min_withoutPredicate) { testAggregationOperator<LongType>( "LongType", AggregationID::kMin, kAttribute, kWithoutPredicate, 0, 0, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Min_withoutPredicate) { testAggregationOperator<FloatType>( "FloatType", AggregationID::kMin, kAttribute, kWithoutPredicate, 0, 0, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Min_withoutPredicate) { testAggregationOperator<DoubleType>( "DoubleType", AggregationID::kMin, kAttribute, kWithoutPredicate, 0, 0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_Count_withoutPredicate) { testAggregationOperator<LongType>("DoubleType", AggregationID::kCount, kAttribute, kWithoutPredicate, 300, 300, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Sum_withoutPredicate) { // Sum of IntType is LongType. testAggregationOperator<LongType>("IntType", AggregationID::kSum, kExpression, kWithoutPredicate, 2 * Summation(299), SummationSquares(299), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Sum_withoutPredicate) { testAggregationOperator<LongType>("LongType", AggregationID::kSum, kExpression, kWithoutPredicate, 2 * Summation(299), SummationSquares(299), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Sum_withoutPredicate) { // Sum of FloatType is DoubleType. testAggregationOperator<DoubleType>("FloatType", AggregationID::kSum, kExpression, kWithoutPredicate, 2 * 0.1 * Summation(299), 0.01 * SummationSquares(299), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Sum_withoutPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kSum, kExpression, kWithoutPredicate, 2 * 0.1 * Summation(299), 0.01 * SummationSquares(299), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("IntType", AggregationID::kAvg, kExpression, kWithoutPredicate, 2 * Summation(299) / 300.0, SummationSquares(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("LongType", AggregationID::kAvg, kExpression, kWithoutPredicate, 2 * Summation(299) / 300.0, SummationSquares(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("FloatType", AggregationID::kAvg, kExpression, kWithoutPredicate, 2 * 0.1 * Summation(299) / 300.0, 0.01 * SummationSquares(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Avg_withoutPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kAvg, kExpression, kWithoutPredicate, 2 * 0.1 * Summation(299) / 300.0, 0.01 * SummationSquares(299) / 300.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Max_withoutPredicate) { testAggregationOperator<IntType>("IntType", AggregationID::kMax, kExpression, kWithoutPredicate, 2 * 299, 299 * 299, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Max_withoutPredicate) { testAggregationOperator<LongType>("LongType", AggregationID::kMax, kExpression, kWithoutPredicate, 2 * 299, 299 * 299, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Max_withoutPredicate) { testAggregationOperator<FloatType>("FloatType", AggregationID::kMax, kExpression, kWithoutPredicate, 2 * 29.9, 29.9 * 29.9, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Max_withoutPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kMax, kExpression, kWithoutPredicate, 2 * 29.9, 29.9 * 29.9, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Min_withoutPredicate) { testAggregationOperator<IntType>( "IntType", AggregationID::kMin, kExpression, kWithoutPredicate, 0, 0, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Min_withoutPredicate) { testAggregationOperator<LongType>( "LongType", AggregationID::kMin, kExpression, kWithoutPredicate, 0, 0, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Min_withoutPredicate) { testAggregationOperator<FloatType>( "FloatType", AggregationID::kMin, kExpression, kWithoutPredicate, 0, 0, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Min_withoutPredicate) { testAggregationOperator<DoubleType>( "DoubleType", AggregationID::kMin, kExpression, kWithoutPredicate, 0, 0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_Count_withoutPredicate) { testAggregationOperator<LongType>("DoubleType", AggregationID::kCount, kExpression, kWithoutPredicate, 300, 300, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Sum_withPredicate) { // Sum of IntType is LongType. testAggregationOperator<LongType>("IntType", AggregationID::kSum, kAttribute, kWithPredicate, Summation(29), Summation(29), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Sum_withPredicate) { testAggregationOperator<LongType>("LongType", AggregationID::kSum, kAttribute, kWithPredicate, Summation(29), Summation(29), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Sum_withPredicate) { // Sum of FloatType is DoubleType. testAggregationOperator<DoubleType>("FloatType", AggregationID::kSum, kAttribute, kWithPredicate, 0.1 * Summation(29), 0.1 * Summation(29), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Sum_withPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kSum, kAttribute, kWithPredicate, 0.1 * Summation(29), 0.1 * Summation(29), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Avg_withPredicate) { testAggregationOperator<DoubleType>("IntType", AggregationID::kAvg, kAttribute, kWithPredicate, Summation(29) / 30.0, Summation(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Avg_withPredicate) { testAggregationOperator<DoubleType>("LongType", AggregationID::kAvg, kAttribute, kWithPredicate, Summation(29) / 30.0, Summation(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Avg_withPredicate) { testAggregationOperator<DoubleType>("FloatType", AggregationID::kAvg, kAttribute, kWithPredicate, 0.1 * Summation(29) / 30.0, 0.1 * Summation(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Avg_withPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kAvg, kAttribute, kWithPredicate, 0.1 * Summation(29) / 30.0, 0.1 * Summation(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Max_withPredicate) { testAggregationOperator<IntType>( "IntType", AggregationID::kMax, kAttribute, kWithPredicate, 29, 29, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Max_withPredicate) { testAggregationOperator<LongType>( "LongType", AggregationID::kMax, kAttribute, kWithPredicate, 29, 29, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Max_withPredicate) { testAggregationOperator<FloatType>( "FloatType", AggregationID::kMax, kAttribute, kWithPredicate, 2.9, 2.9, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Max_withPredicate) { testAggregationOperator<DoubleType>( "DoubleType", AggregationID::kMax, kAttribute, kWithPredicate, 2.9, 2.9, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Min_withPredicate) { testAggregationOperator<IntType>( "IntType", AggregationID::kMin, kAttribute, kWithPredicate, 0, 0, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Min_withPredicate) { testAggregationOperator<LongType>( "LongType", AggregationID::kMin, kAttribute, kWithPredicate, 0, 0, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Min_withPredicate) { testAggregationOperator<FloatType>( "FloatType", AggregationID::kMin, kAttribute, kWithPredicate, 0, 0, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Min_withPredicate) { testAggregationOperator<DoubleType>( "DoubleType", AggregationID::kMin, kAttribute, kWithPredicate, 0, 0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarAttribute_Count_withPredicate) { testAggregationOperator<LongType>( "DoubleType", AggregationID::kCount, kAttribute, kWithPredicate, 30, 30, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Sum_withPredicate) { // Sum of IntType is LongType. testAggregationOperator<LongType>("IntType", AggregationID::kSum, kExpression, kWithPredicate, 2 * Summation(29), SummationSquares(29), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Sum_withPredicate) { testAggregationOperator<LongType>("LongType", AggregationID::kSum, kExpression, kWithPredicate, 2 * Summation(29), SummationSquares(29), CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Sum_withPredicate) { // Sum of FloatType is DoubleType. testAggregationOperator<DoubleType>("FloatType", AggregationID::kSum, kExpression, kWithPredicate, 2 * 0.1 * Summation(29), 0.01 * SummationSquares(29), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Sum_withPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kSum, kExpression, kWithPredicate, 2 * 0.1 * Summation(29), 0.01 * SummationSquares(29), CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Avg_withPredicate) { testAggregationOperator<DoubleType>("IntType", AggregationID::kAvg, kExpression, kWithPredicate, 2 * Summation(29) / 30.0, SummationSquares(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Avg_withPredicate) { testAggregationOperator<DoubleType>("LongType", AggregationID::kAvg, kExpression, kWithPredicate, 2 * Summation(29) / 30.0, SummationSquares(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Avg_withPredicate) { testAggregationOperator<DoubleType>("FloatType", AggregationID::kAvg, kExpression, kWithPredicate, 2 * 0.1 * Summation(29) / 30.0, 0.01 * SummationSquares(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Avg_withPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kAvg, kExpression, kWithPredicate, 2 * 0.1 * Summation(29) / 30.0, 0.01 * SummationSquares(29) / 30.0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Max_withPredicate) { testAggregationOperator<IntType>("IntType", AggregationID::kMax, kExpression, kWithPredicate, 2 * 29, 29 * 29, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Max_withPredicate) { testAggregationOperator<LongType>("LongType", AggregationID::kMax, kExpression, kWithPredicate, 2 * 29, 29 * 29, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Max_withPredicate) { testAggregationOperator<FloatType>("FloatType", AggregationID::kMax, kExpression, kWithPredicate, 2 * 2.9, 2.9 * 2.9, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Max_withPredicate) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kMax, kExpression, kWithPredicate, 2 * 2.9, 2.9 * 2.9, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_IntType_Min_withPredicate) { testAggregationOperator<IntType>( "IntType", AggregationID::kMin, kExpression, kWithPredicate, 0, 0, CheckLiteral<IntType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_LongType_Min_withPredicate) { testAggregationOperator<LongType>( "LongType", AggregationID::kMin, kExpression, kWithPredicate, 0, 0, CheckLiteral<LongType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_FloatType_Min_withPredicate) { testAggregationOperator<FloatType>( "FloatType", AggregationID::kMin, kExpression, kWithPredicate, 0, 0, CheckNear<FloatType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_DoubleType_Min_withPredicate) { testAggregationOperator<DoubleType>( "DoubleType", AggregationID::kMin, kExpression, kWithPredicate, 0, 0, CheckNear<DoubleType::cpptype>); } TEST_F(AggregationOperatorTest, ScalarExpression_Count_withPredicate) { testAggregationOperator<LongType>( "DoubleType", AggregationID::kCount, kExpression, kWithPredicate, 30, 30, CheckLiteral<LongType::cpptype>); } namespace { template <class T> void CheckNull(T dummy, TypedValue actual) { EXPECT_TRUE(actual.isNull()); } } // namespace TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Sum_zeroRows) { // Sum of IntType is LongType. testAggregationOperator<LongType>("IntType", AggregationID::kSum, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<LongType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Sum_zeroRows) { testAggregationOperator<LongType>("LongType", AggregationID::kSum, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<LongType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Sum_zeroRows) { // Sum of FloatType is DoubleType. testAggregationOperator<DoubleType>("FloatType", AggregationID::kSum, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Sum_zeroRows) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kSum, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Avg_zeroRows) { testAggregationOperator<DoubleType>("IntType", AggregationID::kAvg, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Avg_zeroRows) { testAggregationOperator<DoubleType>("LongType", AggregationID::kAvg, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Avg_zeroRows) { testAggregationOperator<DoubleType>("FloatType", AggregationID::kAvg, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Avg_zeroRows) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kAvg, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Max_zeroRows) { testAggregationOperator<IntType>("IntType", AggregationID::kMax, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<IntType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Max_zeroRows) { testAggregationOperator<LongType>("LongType", AggregationID::kMax, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<LongType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Max_zeroRows) { testAggregationOperator<FloatType>("FloatType", AggregationID::kMax, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<FloatType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Max_zeroRows) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kMax, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_IntType_Min_zeroRows) { testAggregationOperator<IntType>("IntType", AggregationID::kMin, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<IntType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_LongType_Min_zeroRows) { testAggregationOperator<LongType>("LongType", AggregationID::kMin, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<LongType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_FloatType_Min_zeroRows) { testAggregationOperator<FloatType>("FloatType", AggregationID::kMin, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<FloatType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_DoubleType_Min_zeroRows) { testAggregationOperator<DoubleType>("DoubleType", AggregationID::kMin, kAttribute, kWithPredicate, kPlaceholder, kPlaceholder, CheckNull<DoubleType::cpptype>, -1); } TEST_F(AggregationOperatorTest, ScalarAttribute_Count_zeroRows) { // Count of zero rows is 0 unlike other aggregate functions. testAggregationOperator<LongType>("DoubleType", AggregationID::kCount, kAttribute, kWithPredicate, 0, 0, CheckLiteral<LongType::cpptype>, -1); } namespace { // Computes the sum of arthemetic series: a, a + d, a + 2*d, ..., a + (n-1)*d std::int64_t ArthemeticSum(int a, int d, int n) { return n * (2 * a + (n - 1) * d) / 2; } template <class T, bool with_predicate> void GroupBy_SumCheckIntegral(int group_by_id, const TypedValue &value1, const TypedValue &value2) { size_t num_repeats = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { num_repeats = AggregationOperatorTest::kGroupByRepeats >> 1; } std::int64_t sum = ArthemeticSum(group_by_id, AggregationOperatorTest::kGroupByWidth, num_repeats); EXPECT_EQ(sum, value1.getLiteral<T>()); EXPECT_EQ(sum, value2.getLiteral<T>()); } template <class T, bool with_predicate> void GroupBy_SumCheckFloat(int group_by_id, const TypedValue &value1, const TypedValue &value2) { size_t num_repeats = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { num_repeats = AggregationOperatorTest::kGroupByRepeats >> 1; } double sum = 0.1 * ArthemeticSum( group_by_id, AggregationOperatorTest::kGroupByWidth, num_repeats); EXPECT_NEAR(sum, value1.getLiteral<T>(), 1e-5 * sum); EXPECT_NEAR(sum, value2.getLiteral<T>(), 1e-5 * sum); } } // namespace TEST_F(AggregationOperatorTest, GroupBy_Sum_IntType_withoutPredicate) { testAggregationOperatorWithGroupBy<LongType>("IntType", AggregationID::kSum, kWithoutPredicate, GroupBy_SumCheckIntegral<LongType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Sum_LongType_withoutPredicate) { testAggregationOperatorWithGroupBy<LongType>("LongType", AggregationID::kSum, kWithoutPredicate, GroupBy_SumCheckIntegral<LongType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Sum_FloatType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>("FloatType", AggregationID::kSum, kWithoutPredicate, GroupBy_SumCheckFloat<DoubleType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Sum_DoubleType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>("DoubleType", AggregationID::kSum, kWithoutPredicate, GroupBy_SumCheckFloat<DoubleType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Sum_LongType_withPredicate) { testAggregationOperatorWithGroupBy<LongType>("LongType", AggregationID::kSum, kWithPredicate, GroupBy_SumCheckIntegral<LongType::cpptype, kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Sum_IntType_withPredicate) { testAggregationOperatorWithGroupBy<LongType>("IntType", AggregationID::kSum, kWithPredicate, GroupBy_SumCheckIntegral<LongType::cpptype, kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Sum_FloatType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>("FloatType", AggregationID::kSum, kWithPredicate, GroupBy_SumCheckFloat<DoubleType::cpptype, kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Sum_DoubleType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>("DoubleType", AggregationID::kSum, kWithPredicate, GroupBy_SumCheckFloat<DoubleType::cpptype, kWithPredicate>, kGroupByWidth); } namespace { template <bool with_predicate> void GroupBy_AvgCheckIntegral(int group_by_id, const TypedValue &value1, const TypedValue &value2) { size_t num_repeats = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { num_repeats = AggregationOperatorTest::kGroupByRepeats >> 1; } double avg = ArthemeticSum(group_by_id, AggregationOperatorTest::kGroupByWidth, num_repeats) / static_cast<double>(num_repeats); EXPECT_NEAR(avg, value1.getLiteral<DoubleType::cpptype>(), 1e-5 * avg); EXPECT_NEAR(avg, value2.getLiteral<DoubleType::cpptype>(), 1e-5 * avg); } template <bool with_predicate> void GroupBy_AvgCheckFloat(int group_by_id, const TypedValue &value1, const TypedValue &value2) { size_t num_repeats = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { num_repeats = AggregationOperatorTest::kGroupByRepeats >> 1; } double avg = 0.1 * ArthemeticSum(group_by_id, AggregationOperatorTest::kGroupByWidth, num_repeats) / static_cast<double>(num_repeats); EXPECT_NEAR(avg, value1.getLiteral<DoubleType::cpptype>(), 1e-5 * avg); EXPECT_NEAR(avg, value2.getLiteral<DoubleType::cpptype>(), 1e-5 * avg); } } // namespace TEST_F(AggregationOperatorTest, GroupBy_Avg_IntType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "IntType", AggregationID::kAvg, kWithoutPredicate, GroupBy_AvgCheckIntegral<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Avg_LongType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "LongType", AggregationID::kAvg, kWithoutPredicate, GroupBy_AvgCheckIntegral<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Avg_FloatType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "FloatType", AggregationID::kAvg, kWithoutPredicate, GroupBy_AvgCheckFloat<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Avg_DoubleType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "DoubleType", AggregationID::kAvg, kWithoutPredicate, GroupBy_AvgCheckFloat<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Avg_IntType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "IntType", AggregationID::kAvg, kWithPredicate, GroupBy_AvgCheckIntegral<kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Avg_LongType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "LongType", AggregationID::kAvg, kWithPredicate, GroupBy_AvgCheckIntegral<kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Avg_FloatType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "FloatType", AggregationID::kAvg, kWithPredicate, GroupBy_AvgCheckFloat<kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Avg_DoubleType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "DoubleType", AggregationID::kAvg, kWithPredicate, GroupBy_AvgCheckFloat<kWithPredicate>, kGroupByWidth); } namespace { template <class T, bool with_predicate> void GroupBy_MaxCheckIntegral(int group_by_id, const TypedValue &value1, const TypedValue &value2) { size_t num_repeats = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { num_repeats = AggregationOperatorTest::kGroupByRepeats >> 1; } T max = (AggregationOperatorTest::kGroupByWidth * (num_repeats - 1)) + group_by_id; EXPECT_EQ(max, value1.getLiteral<T>()); EXPECT_EQ(max, value2.getLiteral<T>()); } template <bool with_predicate> void GroupBy_MaxCheckFloat(int group_by_id, const TypedValue &value1, const TypedValue &value2) { size_t num_repeats = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { num_repeats = AggregationOperatorTest::kGroupByRepeats >> 1; } float max = 0.1 * ((AggregationOperatorTest::kGroupByWidth * (num_repeats - 1)) + group_by_id); EXPECT_FLOAT_EQ(max, value1.getLiteral<float>()); EXPECT_FLOAT_EQ(max, value2.getLiteral<float>()); } template <bool with_predicate> void GroupBy_MaxCheckDouble(int group_by_id, const TypedValue &value1, const TypedValue &value2) { size_t num_repeats = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { num_repeats = AggregationOperatorTest::kGroupByRepeats >> 1; } double max = 0.1 * ((AggregationOperatorTest::kGroupByWidth * (num_repeats - 1)) + group_by_id); EXPECT_DOUBLE_EQ(max, value1.getLiteral<double>()); EXPECT_DOUBLE_EQ(max, value2.getLiteral<double>()); } } // namespace TEST_F(AggregationOperatorTest, GroupBy_Max_IntType_withoutPredicate) { testAggregationOperatorWithGroupBy<IntType>("IntType", AggregationID::kMax, kWithoutPredicate, GroupBy_MaxCheckIntegral<IntType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Max_LongType_withoutPredicate) { testAggregationOperatorWithGroupBy<LongType>("LongType", AggregationID::kMax, kWithoutPredicate, GroupBy_MaxCheckIntegral<LongType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Max_FloatType_withoutPredicate) { testAggregationOperatorWithGroupBy<FloatType>( "FloatType", AggregationID::kMax, kWithoutPredicate, GroupBy_MaxCheckFloat<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Max_DoubleType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>("DoubleType", AggregationID::kMax, kWithoutPredicate, GroupBy_MaxCheckDouble<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Max_IntType_withPredicate) { testAggregationOperatorWithGroupBy<IntType>("IntType", AggregationID::kMax, kWithPredicate, GroupBy_MaxCheckIntegral<IntType::cpptype, kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Max_LongType_withPredicate) { testAggregationOperatorWithGroupBy<LongType>("LongType", AggregationID::kMax, kWithPredicate, GroupBy_MaxCheckIntegral<LongType::cpptype, kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Max_FloatType_withPredicate) { testAggregationOperatorWithGroupBy<FloatType>( "FloatType", AggregationID::kMax, kWithPredicate, GroupBy_MaxCheckFloat<kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Max_DoubleType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>("DoubleType", AggregationID::kMax, kWithPredicate, GroupBy_MaxCheckDouble<kWithPredicate>, kGroupByWidth); } namespace { template <class T, bool with_predicate> void GroupBy_MinCheckIntegral(int group_by_id, const TypedValue &value1, const TypedValue &value2) { T min = group_by_id; EXPECT_EQ(min, value1.getLiteral<T>()); EXPECT_EQ(min, value2.getLiteral<T>()); } template <bool with_predicate> void GroupBy_MinCheckFloat(int group_by_id, const TypedValue &value1, const TypedValue &value2) { float min = 0.1 * group_by_id; EXPECT_FLOAT_EQ(min, value1.getLiteral<float>()); EXPECT_FLOAT_EQ(min, value2.getLiteral<float>()); } template <bool with_predicate> void GroupBy_MinCheckDouble(int group_by_id, const TypedValue &value1, const TypedValue &value2) { double min = 0.1 * group_by_id; EXPECT_DOUBLE_EQ(min, value1.getLiteral<double>()); EXPECT_DOUBLE_EQ(min, value2.getLiteral<double>()); } } // namespace TEST_F(AggregationOperatorTest, GroupBy_Min_IntType_withoutPredicate) { testAggregationOperatorWithGroupBy<IntType>("IntType", AggregationID::kMin, kWithoutPredicate, GroupBy_MinCheckIntegral<IntType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Min_LongType_withoutPredicate) { testAggregationOperatorWithGroupBy<LongType>("LongType", AggregationID::kMin, kWithoutPredicate, GroupBy_MinCheckIntegral<LongType::cpptype, kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Min_FloatType_withoutPredicate) { testAggregationOperatorWithGroupBy<FloatType>( "FloatType", AggregationID::kMin, kWithoutPredicate, GroupBy_MinCheckFloat<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Min_DoubleType_withoutPredicate) { testAggregationOperatorWithGroupBy<DoubleType>("DoubleType", AggregationID::kMin, kWithoutPredicate, GroupBy_MinCheckDouble<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Min_IntType_withPredicate) { testAggregationOperatorWithGroupBy<IntType>("IntType", AggregationID::kMin, kWithPredicate, GroupBy_MinCheckIntegral<IntType::cpptype, kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Min_LongType_withPredicate) { testAggregationOperatorWithGroupBy<LongType>("LongType", AggregationID::kMin, kWithPredicate, GroupBy_MinCheckIntegral<LongType::cpptype, kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Min_FloatType_withPredicate) { testAggregationOperatorWithGroupBy<FloatType>( "FloatType", AggregationID::kMin, kWithPredicate, GroupBy_MinCheckFloat<kWithPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Min_DoubleType_withPredicate) { testAggregationOperatorWithGroupBy<DoubleType>( "DoubleType", AggregationID::kMin, kWithPredicate, GroupBy_MinCheckDouble<kWithPredicate>, kGroupByWidth); } namespace { template <bool with_predicate> void GroupBy_CountCheck(int group_by_id, const TypedValue &value1, const TypedValue &value2) { LongType::cpptype count = AggregationOperatorTest::kGroupByRepeats; if (with_predicate) { count = AggregationOperatorTest::kGroupByRepeats >> 1; } EXPECT_EQ(count, value1.getLiteral<LongType::cpptype>()); EXPECT_EQ(count, value2.getLiteral<LongType::cpptype>()); } } // namespace TEST_F(AggregationOperatorTest, GroupBy_Count_withoutPredicate) { testAggregationOperatorWithGroupBy<LongType>( "DoubleType", AggregationID::kCount, kWithoutPredicate, GroupBy_CountCheck<kWithoutPredicate>, kGroupByWidth); } TEST_F(AggregationOperatorTest, GroupBy_Count_withPredicate) { testAggregationOperatorWithGroupBy<LongType>( "DoubleType", AggregationID::kCount, kWithPredicate, GroupBy_CountCheck<kWithPredicate>, kGroupByWidth); } namespace { void GroupBy_NoCall(int group_by_id, const TypedValue &value1, const TypedValue &value2) { EXPECT_TRUE(false); } TEST_F(AggregationOperatorTest, GroupBy_Sum_LongType_zeroRows) { testAggregationOperatorWithGroupBy<LongType>( "LongType", AggregationID::kSum, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Sum_IntType_zeroRows) { testAggregationOperatorWithGroupBy<LongType>( "IntType", AggregationID::kSum, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Sum_FloatType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "FloatType", AggregationID::kSum, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Sum_DoubleType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "DoubleType", AggregationID::kSum, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Avg_IntType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "IntType", AggregationID::kAvg, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Avg_LongType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "LongType", AggregationID::kAvg, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Avg_FloatType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "FloatType", AggregationID::kAvg, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Avg_DoubleType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "DoubleType", AggregationID::kAvg, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Max_IntType_zeroRows) { testAggregationOperatorWithGroupBy<IntType>( "IntType", AggregationID::kMax, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Max_LongType_zeroRows) { testAggregationOperatorWithGroupBy<LongType>( "LongType", AggregationID::kMax, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Max_FloatType_zeroRows) { testAggregationOperatorWithGroupBy<FloatType>( "FloatType", AggregationID::kMax, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Max_DoubleType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "DoubleType", AggregationID::kMax, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Min_IntType_zeroRows) { testAggregationOperatorWithGroupBy<IntType>( "IntType", AggregationID::kMin, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Min_LongType_zeroRows) { testAggregationOperatorWithGroupBy<LongType>( "LongType", AggregationID::kMin, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Min_FloatType_zeroRows) { testAggregationOperatorWithGroupBy<FloatType>( "FloatType", AggregationID::kMin, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Min_DoubleType_zeroRows) { testAggregationOperatorWithGroupBy<DoubleType>( "DoubleType", AggregationID::kMin, kWithPredicate, GroupBy_NoCall, 0, -1); } TEST_F(AggregationOperatorTest, GroupBy_Count_zeroRows) { testAggregationOperatorWithGroupBy<LongType>( "DoubleType", AggregationID::kCount, kWithPredicate, GroupBy_NoCall, 0, -1); } } // namespace } // namespace quickstep int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); // Honor FLAGS_buffer_pool_slots in StorageManager. gflags::ParseCommandLineFlags(&argc, &argv, true); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
44.772026
116
0.600374
[ "vector" ]
fd525cfac1ca17cd5a6d4382a2bceb6c053e9a86
4,341
cpp
C++
src/search_engine/relja_retrival/external/KMCode_relja/descriptor/KoenDescriptor.cpp
alexanderwilkinson/visenew
8e494355b0f88466c0abb4b8f3bfecc150b91111
[ "ImageMagick", "BSD-2-Clause" ]
43
2017-07-06T23:44:39.000Z
2022-03-25T06:53:29.000Z
src/search_engine/relja_retrival/external/KMCode_relja/descriptor/KoenDescriptor.cpp
alexanderwilkinson/visenew
8e494355b0f88466c0abb4b8f3bfecc150b91111
[ "ImageMagick", "BSD-2-Clause" ]
2
2018-11-09T03:52:14.000Z
2020-03-25T14:08:33.000Z
src/search_engine/relja_retrival/external/KMCode_relja/descriptor/KoenDescriptor.cpp
alexanderwilkinson/visenew
8e494355b0f88466c0abb4b8f3bfecc150b91111
[ "ImageMagick", "BSD-2-Clause" ]
9
2017-07-27T10:55:55.000Z
2020-12-15T13:42:43.000Z
#include "koenDescriptor.h" void KoenDescriptor::computeComponents(DARY *img_in){ if(img_in==NULL){return;} DARY * imgn = new DARY(PATCH_SIZE,PATCH_SIZE); normalizeAffine(img_in,imgn); normalize(imgn,imgn->x()>>1,imgn->y()>>1,imgn->x()>>1); float xt=x,yt=y,c_scalet=c_scale; c_scale=6.7; x=imgn->x()>>1;y=imgn->y()>>1; ((JetLocal*)this)->computeComponents(imgn); x=xt;y=yt;c_scale=c_scalet; delete imgn; int nb_inv=12; double *val = new double[nb_inv]; /* invariant f */ /* invariant LwLw=fx*fx + fy*fy */ val[ 0] = (vec[1]*vec[1]+vec[2]*vec[2]); float temp = sqrt(val[0]); temp=temp*temp*temp; /* invariant Lvv+Lww = fxx + fyy */ val[ 1] = (vec[3]+vec[5]); /*invariant Lww=fx*fxx*fx+2*fx*fxy*fy+fy*fyy*fy */ val[ 2] = (vec[1] * vec[1] * vec[3] + 2 * vec[1] * vec[2] * vec[4] + vec[2] * vec[2] * vec[5]); /*invariant fxx*fxx+2*fxy*fxy+fyy*fyy */ val[ 3] = (vec[3] * vec[3] + 2 * vec[4] * vec[4] + vec[5] * vec[5]); /* invariant of third order Lvvv (see p.321 paper of Romeny) */ /* (fxxxfyfyfy-3fxxyfxfyfy+3fxyyfxfxfy-fyyyfxfxfx)/temp */ val[ 4] = ((vec[6]*vec[2]*vec[2]*vec[2]-3*vec[7]* vec[1]*vec[2]*vec[2]+ 3*vec[8]*vec[1]*vec[1]*vec[2]-vec[9]* vec[1]*vec[1]*vec[1]))/temp ; /* invariant of third order Lvvw (see p.321 paper of Romeny) */ /* (fxxxfxfyfy+fxxy(-2fxfxfy+fyfyfy)+fxyy(-2fxfyfy+fxfxfx)+fyyyfxfxfy)/temp */ val[ 5] = ((vec[6]*vec[1]*vec[2]*vec[2] + vec[7]* (-2*vec[1]*vec[1]*vec[2]+vec[2]*vec[2]*vec[2]) + vec[8]*(-2*vec[1]*vec[2]*vec[2]+vec[1]*vec[1]*vec[1]) + vec[9]*vec[1]*vec[1]*vec[2]))/temp ; /* invariant of third order Lvww (see p.321 paper of Romeny) */ /* (fxxy(-fxfxfx+2fxfyfy)+fxyy(-2fxfxfy+fyfyfy)-fyyyfxfyfy+fxxxfxfxfy)/temp */ val[ 6] = ((vec[7]*(-vec[1]*vec[1]*vec[1]+ 2*vec[1]*vec[2]*vec[2])+ vec[8]*(-2*vec[1]*vec[1]*vec[2]+vec[2]*vec[2]*vec[2])- vec[9]*vec[1]*vec[2]*vec[2]+vec[6]*vec[1]*vec[1]*vec[2]))/temp ; /* invariant of third order Lwww (see p.321 paper of Romeny) */ /* (fxxxfxfxfx+3fxxyfxfxfy+3fxyyfxfyfy+fyyyfyfyfy)/temp */ val[ 7] = ((vec[6]*vec[1]*vec[1]*vec[1]+ 3*vec[7]*vec[1]*vec[1]*vec[2]+3*vec[8]*vec[1]*vec[2]*vec[2]+ vec[9]*vec[2]*vec[2]*vec[2]))/temp ; /* invariant of third order Lvw (see p.321 paper of Romeny) */ /* (fxxfxfy+fxyfyfy-fxyfxfx-fyyfxfy)/temp */ val[ 8] = (vec[3]*vec[1]*vec[2]+vec[4]*vec[2]*vec[2]-vec[4]*vec[1]*vec[1]- vec[5]*vec[1]*vec[2])/temp ; /* invariant of third order Lvv (see p.321 paper of Romeny) */ /* (fxxfyfy-2fxyfxfy+fyyfxfx)/temp */ val[ 9] = (vec[3]*vec[2]*vec[2]-2*vec[4]*vec[1]*vec[2]+vec[5]*vec[1]*vec[1])/temp ; /* invariant of third order Lvvvv (see p.321 paper of Romeny) */ /* (fxxxxfyfyfyfy-4fxyyyfxfxfxfy-4fxxxyfxfyfyfy+6fxxyyfxfxfyfy+fxfxfxfxfyyyy)/temp */ val[ 10] = (vec[10]*vec[2]*vec[2]*vec[2]*vec[2]-4*vec[13]*vec[1]*vec[1]*vec[1]*vec[2]- 4*vec[11]*vec[1]*vec[2]*vec[2]*vec[2]+6*vec[12]*vec[1]*vec[1]*vec[2]*vec[2]+ vec[14]*vec[1]*vec[1]*vec[1]*vec[1])/temp ; /* invariant of third order Lwwww (see p.321 paper of Romeny) */ /* (fxxxxfxfxfxfx+4fxyyyfxfyfyfy+4fxxxyfxfxfxfy+6fxxyyfxfxfyfy+fyfyfyfyfyyyy)/temp */ val[ 11] = (vec[10]*vec[1]*vec[1]*vec[1]*vec[1]+4*vec[13]*vec[1]*vec[2]*vec[2]*vec[2]+ 4*vec[11]*vec[1]*vec[1]*vec[1]*vec[2]+6*vec[12]*vec[1]*vec[1]*vec[2]*vec[2]+ vec[14]*vec[2]*vec[2]*vec[2]*vec[2])/temp ; allocVec(nb_inv); for(int i=0;i<size;i++)vec[i]=val[i]; delete[] val; state=1; changeBase(koen_base); int koen_pca_size=12; //pca(koen_pca_size,koen_pca_avg, koen_pca_base); } void computeKoenDescriptors(DARY *image, vector<CornerDescriptor *> &desc){ initPatchMask(PATCH_SIZE); KoenDescriptor * ds=new KoenDescriptor(); for(unsigned int c=0;c<desc.size();c++){ cout << "\rkoen descriptor "<< c<< " of "<< desc.size()<< flush; ds->copy(desc[c]); ds->computeComponents(image); desc[c]->copy((CornerDescriptor*)ds); } for(unsigned int c=0;c<desc.size();c++){ if(!desc[c]->isOK()){ //desc.erase((std::vector<CornerDescriptor*>::iterator)&desc[c]); desc.erase(desc.begin() + c); c--; } } cout<<endl; }
37.747826
87
0.576595
[ "vector" ]
fd5d493422c267e3840fc0410c96fe5aaa3b3c6d
6,811
hpp
C++
algo/include/algo_math.hpp
alex011235/algo
ce36c2673e037a12278117cb036550bee82ecadf
[ "MIT" ]
2
2015-08-16T23:45:23.000Z
2015-10-13T08:12:00.000Z
algo/include/algo_math.hpp
alex011235/algorithm
ce36c2673e037a12278117cb036550bee82ecadf
[ "MIT" ]
1
2021-03-21T16:33:53.000Z
2021-03-21T16:33:53.000Z
algo/include/algo_math.hpp
alex011235/algo
ce36c2673e037a12278117cb036550bee82ecadf
[ "MIT" ]
null
null
null
/// /// \brief Source file for math algorithms. /// \author alex011235 /// \date 2020-04-19 /// \link <a href=https://github.com/alex011235/algo>Algo, Github</a> /// /// Change list: /// 2015-08-27 Random numbers /// 2016-04-05 Knapsack, GCD, LCM, Bin, Prime numbers /// 2016-10-16 Pascal's triangle, ClockAngle /// #ifndef ALGORITHM_MATHS_MATHS_ALGORITHMS_HPP_ #define ALGORITHM_MATHS_MATHS_ALGORITHMS_HPP_ #include <algorithm> #include <cstdlib> #include <vector> namespace algo::math::discrete { using PTriangle = std::vector<std::vector<int>>; /// \brief Returns the rows of Pascal's Triangle. /// \param depth The number of rows. /// \return The rows of Pascal's Triangle, each item in the vector is one row. /// \link <a href="https://en.wikipedia.org/wiki/Pascal%27s_triangle">Pascal's triangle, Wikipedia.</a> PTriangle PascalsTriangle(int depth); /// \brief Computes the angle between the hour and minute hands. /// \param h The position of the hour hand, e.g. 12. /// \param m The position of the minute hand, e.g. 59. /// \return The angle between the hour and minute hands. Return -1 for faulty input. int ClockAngle(int h, int m); // Struct for item in knapsack struct Item { int value, weight; }; // Knapsack items using Items = std::vector<Item>; /// \brief Finds the maximum capacity for the knapsack problem. /// \param items Items possible to put in the knapsack. /// \param capacity Maximum capacity for the knapsack. /// \return Maximum knapsack capacity. /// \link <a href="https://en.wikipedia.org/wiki/Knapsack_problem">Knapsack, Wikipedia.</a> /// \link <a href="https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/"> Knapsack, GeeksforGeeks.</a> int Knapsack(const Items& items, unsigned capacity); /// \brief Computes the greatest common divisor, using the Euclidean algorithm. /// \tparam T Type used. /// \param a First number. /// \param b Second number. /// \return GCD(a, b) /// \link <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">GCD, Wikipedia.</a> /// \link <a href="https://en.wikipedia.org/wiki/Euclidean_algorithm">Euclidean algorithm, Wikipedia.</a> constexpr auto GCD = [](auto a, auto b) { // Euclidean algorithm: decltype(a) c = 0; while (b != 0) { c = a % b; a = b; b = c; } return a; }; /// \brief Computes the least common multiple using the properties of GCD: LCM(a,b) = a*b/GCD(a,b) constexpr auto LCM = [](auto a, auto b) { return std::abs(a * b) / GCD(a, b); }; /// \brief Computes the binomial coefficient of a and b. nCk, n Choose k is the same computation. /// \tparam T Type used. /// \param n First number. /// \param k Second number. /// \return BIN(a, b) /// \link <a href="https://en.wikipedia.org/wiki/Binomial_coefficient">Binomial coefficient, Wikipedia.</a> constexpr auto BIN = [](auto n, auto k) { decltype(n) c = 0; if (k > n) { return c; } c = 1; if ((k == 0) || (k == n)) { return c; } k = std::min(k, n - k); for (decltype(k) i = 0; i < k; i++) { c = c * (n - i) / (i + 1); } return c; }; }// namespace algo::math::discrete namespace algo::math::random_num { namespace cont { /// \brief Returns a random number sampled from a uniform distribution with lower and upper limits a and b. /// \param a Lower limit. /// \param b Upper Limit /// \return A random uniform number x such that a < x < b. /// \link <a href="https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)">Uniform distribution, Wikipedia.</a> double Uniform(double a, double b); /// \brief Returns a random number from the uniform distribution between 0 and 1. /// \return U(0, 1) random number. double Random(); /// \brief Returns an exponentially distributed random number. /// \param lambda Rate parameter, must be greater than zero. /// \param upper_limit The upper limit. /// \return See brief. /// \link <a href="https://en.wikipedia.org/wiki/Exponential_distribution">Exponential distribution, Wikipedia.</a> double Exp(double lambda); /// \brief Returns a normal distributed random number, N(mu, sigma). The random number is computed using the /// Box-Muller transform. /// \param mu Mean value. /// \param sigma Standard deviation. /// \return N(mu, sigma) random number. /// \link <a href="https://en.wikipedia.org/wiki/Normal_distribution">Normal distribution, Wikipedia.</a> double Normal(double mu, double sigma); /// \brief Returns a random number sampled from the Weibull distribution. /// \param lambda Scale parameter. /// \param k Shape parameter. /// \return See brief. /// \line <a href="https://en.wikipedia.org/wiki/Weibull_distribution">Weibull distribution, Wikipedia.</a> double Weibull(double lambda, double k); }// namespace cont namespace discr { /// \brief Returns a random number sampled from the Binomial distribution. /// \quote The binomial distribution is frequently used to model the number of successes in a sample of size /// n drawn with replacement from a population of size N. - _Wikipedia_ /// \param n Number of independent experiments. /// \param p The probability of the experiment. /// \return Binomial(n,p) /// \link <a href="https://en.wikipedia.org/wiki/Binomial_distribution">Binomial distribution, Wikipedia.</a> int Binomial(int n, double p); /// \brief Returns a random number sampled from the Poisson distribution. /// \param lambda Expected number of occurrences. /// \return Poisson(lambda) random number. /// \link <a href="https://en.wikipedia.org/wiki/Poisson_distribution">Poisson distribution, Wikipedia.</a> int Poisson(double lambda); /// \brief Returns a random number sampled from the geometric distribution. /// \quote The geometric distribution gives the probability that the first occurrence of success requires /// k independent trials, each with success probability p. - _Wikipedia_ /// \param p Success probability. /// \return Geometric(p) /// \link <a href="https://en.wikipedia.org/wiki/Geometric_distribution">Geometric distribution, Wikipedia.</a> int Geometric(double p); }// namespace discr }// namespace algo::math::random_num namespace algo::math::prime { /// \brief Checks if n is a prime number. /// \tparam T Type used. /// \param n Input number. /// \return True if n is a prime number, otherwise false. template<typename T> bool IsPrime(T n); /// \brief Returns prime numbers less than n in a vector. This implementation is based on the Sieve of Eratosthenes /// algorithm for computing prime numbers. /// \tparam T The type used. /// \param n The maximum prime number (limit). /// \return A vector<T> of prime numbers. /// \link <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes, Wikipedia.</a> template<typename T> std::vector<T> GetPrimes(unsigned int n); }// namespace algo::math::prime #endif//ALGORITHM_MATHS_MATHS_ALGORITHMS_HPP_
35.659686
120
0.706357
[ "shape", "vector", "model", "transform" ]
fd5e5550ce3f291fcee979f993767c30025518db
17,329
cpp
C++
src/engine_core/wme_base/3DUtils.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
3
2021-03-28T00:11:48.000Z
2022-01-12T13:10:52.000Z
src/engine_core/wme_base/3DUtils.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
src/engine_core/wme_base/3DUtils.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme #include "dcgf.h" #include ".\3DUtils.h" ////////////////////////////////////////////////////////////////////////// BOOL C3DUtils::IntersectTriangle(const D3DXVECTOR3& orig, const D3DXVECTOR3& dir, D3DXVECTOR3& v0, D3DXVECTOR3& v1, D3DXVECTOR3& v2, FLOAT* t, FLOAT* u, FLOAT* v) { // Find vectors for two edges sharing vert0 D3DXVECTOR3 edge1 = v1 - v0; D3DXVECTOR3 edge2 = v2 - v0; // Begin calculating determinant - also used to calculate U parameter D3DXVECTOR3 pvec; D3DXVec3Cross( &pvec, &dir, &edge2 ); // If determinant is near zero, ray lies in plane of triangle FLOAT det = D3DXVec3Dot( &edge1, &pvec ); if( det < 0.0001f ) return FALSE; // Calculate distance from vert0 to ray origin D3DXVECTOR3 tvec = orig - v0; // Calculate U parameter and test bounds *u = D3DXVec3Dot( &tvec, &pvec ); if( *u < 0.0f || *u > det ) return FALSE; // Prepare to test V parameter D3DXVECTOR3 qvec; D3DXVec3Cross( &qvec, &tvec, &edge1 ); // Calculate V parameter and test bounds *v = D3DXVec3Dot( &dir, &qvec ); if( *v < 0.0f || *u + *v > det ) return FALSE; // Calculate t, scale parameters, ray intersects triangle *t = D3DXVec3Dot( &edge2, &qvec ); FLOAT fInvDet = 1.0f / det; *t *= fInvDet; *u *= fInvDet; *v *= fInvDet; D3DXVECTOR3 intersection; D3DXVECTOR3 dest = orig + dir; D3DXPLANE plane; D3DXPlaneFromPoints(&plane, &v0, &v1, &v2); D3DXPlaneIntersectLine(&intersection, &plane, &orig, &dest); *t = intersection.x; *u = intersection.y; *v = intersection.z; return TRUE; } ////////////////////////////////////////////////////////////////////////// D3DXMATRIX* C3DUtils::MatrixSetTranslation(D3DXMATRIX* mat, D3DXVECTOR3* vec) { mat->_41 = vec->x; mat->_42 = vec->y; mat->_43 = vec->z; return mat; } ////////////////////////////////////////////////////////////////////////// D3DXMATRIX* C3DUtils::MatrixSetRotation(D3DXMATRIX* mat, D3DXVECTOR3* vec) { double cr = cos(vec->x); double sr = sin(vec->x); double cp = cos(vec->y); double sp = sin(vec->y); double cy = cos(vec->z); double sy = sin(vec->z); mat->_11 = (float)(cp*cy); mat->_12 = (float)(cp*sy); mat->_13 = (float)(-sp); double srsp = sr*sp; double crsp = cr*sp; mat->_21 = (float)(srsp*cy-cr*sy); mat->_22 = (float)(srsp*sy+cr*cy); mat->_23 = (float)(sr*cp); mat->_31 = (float)(crsp*cy+sr*sy); mat->_32 = (float)(crsp*sy-sr*cy); mat->_33 = (float)(cr*cp); return mat; } ////////////////////////////////////////////////////////////////////////// // object picking ////////////////////////////////////////////////////////////////////////// D3DXVECTOR3 C3DUtils::PickMakeRay(float FOV, LPDIRECT3DDEVICE Device, int MouseX, int MouseY, float Range) { D3DXVECTOR3 LineEnd,CameraSpacePos; float NMouseX, NMouseY, det; D3DXMATRIX matView; D3DVIEWPORT viewport; Device->GetViewport(&viewport); NMouseX = 1.0 - 2.0*MouseX/viewport.Width; NMouseY = 1.0 - 2.0*MouseY/viewport.Height; float AspectRatio = viewport.Width / viewport.Height; //is FOV in radians CameraSpacePos.y = (NMouseY*tan(FOV/2.0)); CameraSpacePos.x = ((-NMouseX/AspectRatio)*tan(FOV/2.0)); LineEnd.x = Range*CameraSpacePos.x; LineEnd.y = Range*CameraSpacePos.y; LineEnd.z = Range; Device->GetTransform(D3DTS_VIEW, &matView); D3DXMatrixInverse(&matView,&det,&matView); D3DXVec3TransformCoord(&LineEnd,&LineEnd,&matView); return LineEnd; } ////////////////////////////////////////////////////////////////////////// bool C3DUtils::PickGetIntersect (D3DXVECTOR3 linestart, D3DXVECTOR3 lineend, D3DXVECTOR3 v0, D3DXVECTOR3 v1, D3DXVECTOR3 v2,D3DXVECTOR3* intersection, float* distance) { // compute plane's normal D3DXVECTOR3 vertex; D3DXVECTOR3 normal; D3DXVECTOR3 edge1 = v1 - v0; D3DXVECTOR3 edge2 = v2 - v1; D3DXVec3Cross(&normal, &edge1, &edge2); D3DXVec3Normalize(&normal, &normal); vertex = v0; D3DXVECTOR3 direction,L1; float linelength,dist_from_plane,percentage; direction.x=lineend.x-linestart.x;// calculate the lines direction vector direction.y=lineend.y-linestart.y; direction.z=lineend.z-linestart.z; linelength=D3DXVec3Dot(&direction,&normal); // This gives us the line length (the blue dot L3 + L4 in figure d) if (fabsf(linelength) < 0.00001) return false; L1.x=vertex.x-linestart.x;// calculate vector L1 (the PINK line in figure d) L1.y=vertex.y-linestart.y; L1.z=vertex.z-linestart.z; dist_from_plane=D3DXVec3Dot(&L1,&normal); // gives the distance from the plane (ORANGE Line L3 in figure d) percentage=dist_from_plane/linelength; // How far from Linestart , intersection is as a percentage of 0 to 1 if (percentage< 0.0) return false; else if (percentage > 1.0) return false; *distance=percentage;//record the distance from beginning of ray (0.0 -1.0) intersection->x=linestart.x+direction.x*percentage;// add the percentage of the line to line start intersection->y=linestart.y+direction.y*percentage; intersection->z=linestart.z+direction.z*percentage; return true; } ////////////////////////////////////////////////////////////////////////// void C3DUtils::DecomposeMatrixSimple(const D3DXMATRIX* Mat, D3DXVECTOR3* TransVec, D3DXVECTOR3* ScaleVec, D3DXQUATERNION* RotQ) { *TransVec = D3DXVECTOR3(Mat->_41, Mat->_42, Mat->_43); *ScaleVec = D3DXVECTOR3(sqrtf(Mat->_11*Mat->_11+Mat->_21*Mat->_21+Mat->_31*Mat->_31), sqrtf(Mat->_12*Mat->_12+Mat->_22*Mat->_22+Mat->_32*Mat->_32), sqrtf(Mat->_13*Mat->_13+Mat->_23*Mat->_23+Mat->_33*Mat->_33)); D3DXQUATERNION Q; D3DXQuaternionRotationMatrix(&Q, Mat); *RotQ = Q; } ////////////////////////////////////////////////////////////////////////// void C3DUtils::DecomposeMatrix(const D3DXMATRIX* Mat, D3DXVECTOR3* TransVec, D3DXVECTOR3* ScaleVec, D3DXQUATERNION* RotQ) { enum unmatrix_indices { U_SCALEX, U_SCALEY, U_SCALEZ, U_SHEARXY, U_SHEARXZ, U_SHEARYZ, U_ROTATEX, U_ROTATEY, U_ROTATEZ, U_TRANSX, U_TRANSY, U_TRANSZ, U_PX, U_PY, U_PZ, U_PW }; double unMatrixValues[16]; register int i,j; D3DXMATRIX locmat; D3DXMATRIX pmat, invpmat, tinvpmat; /* Vector4 type and functions need to be added to the common set. */ D3DXVECTOR4 prhs, psol; D3DXVECTOR3 row[3], pdum3; locmat = *Mat; /* Normalize the matrix. */ if ( locmat.m[3][3] == 0 ) return; for ( i=0; i<4;i++ ) for ( j=0; j<4; j++ ) locmat.m[i][j] /= locmat.m[3][3]; /* pmat is used to solve for perspective, but it also provides * an easy way to test for singularity of the upper 3x3 component. */ pmat = locmat; for ( i=0; i<3; i++ ) pmat.m[i][3] = 0; pmat.m[3][3] = 1; if ( D3DXMatrixDeterminant(&pmat) == 0.0 ) return; /* First, isolate perspective. This is the messiest. */ if ( locmat.m[0][3] != 0 || locmat.m[1][3] != 0 || locmat.m[2][3] != 0 ) { /* prhs is the right hand side of the equation. */ prhs.x = locmat.m[0][3]; prhs.y = locmat.m[1][3]; prhs.z = locmat.m[2][3]; prhs.w = locmat.m[3][3]; /* Solve the equation by inverting pmat and multiplying * prhs by the inverse. (This is the easiest way, not * necessarily the best.) * inverse function (and det4x4, above) from the Matrix * Inversion gem in the first volume. */ //inverse( &pmat, &invpmat ); FLOAT det; D3DXMatrixInverse(&invpmat,&det,&pmat); //TransposeMatrix4( &invpmat, &tinvpmat ); D3DXMatrixTranspose(&tinvpmat, &invpmat); //V4MulPointByMatrix(&prhs, &tinvpmat, &psol); D3DXVec4Transform(&psol,&prhs,&tinvpmat); /* Stuff the answer away. */ unMatrixValues[U_PX] = psol.x; unMatrixValues[U_PY] = psol.y; unMatrixValues[U_PZ] = psol.z; unMatrixValues[U_PW] = psol.w; /* Clear the perspective partition. */ locmat.m[0][3] = locmat.m[1][3] = locmat.m[2][3] = 0; locmat.m[3][3] = 1; } else /* No perspective. */ unMatrixValues[U_PX] = unMatrixValues[U_PY] = unMatrixValues[U_PZ] = unMatrixValues[U_PW] = 0; /* Next take care of translation (easy). */ for ( i=0; i<3; i++ ) { unMatrixValues[U_TRANSX + i] = locmat.m[3][i]; locmat.m[3][i] = 0; } /* Now get scale and shear. */ for ( i=0; i<3; i++ ) { row[i].x = locmat.m[i][0]; row[i].y = locmat.m[i][1]; row[i].z = locmat.m[i][2]; } /* Compute X scale factor and normalize first row. */ unMatrixValues[U_SCALEX] = D3DXVec3Length(&row[0]); row[0] = *D3DXVec3Scale(&row[0],&row[0], 1.0); /* Compute XY shear factor and make 2nd row orthogonal to 1st. */ unMatrixValues[U_SHEARXY] = D3DXVec3Dot(&row[0], &row[1]); (void)V3Combine(&row[1], &row[0], &row[1], 1.0, -unMatrixValues[U_SHEARXY]); /* Now, compute Y scale and normalize 2nd row. */ unMatrixValues[U_SCALEY] = D3DXVec3Length(&row[1]); D3DXVec3Scale(&row[1], &row[1], 1.0); unMatrixValues[U_SHEARXY] /= unMatrixValues[U_SCALEY]; /* Compute XZ and YZ shears, orthogonalize 3rd row. */ unMatrixValues[U_SHEARXZ] = D3DXVec3Dot(&row[0], &row[2]); (void)V3Combine(&row[2], &row[0], &row[2], 1.0, -unMatrixValues[U_SHEARXZ]); unMatrixValues[U_SHEARYZ] = D3DXVec3Dot(&row[1], &row[2]); (void)V3Combine(&row[2], &row[1], &row[2], 1.0, -unMatrixValues[U_SHEARYZ]); /* Next, get Z scale and normalize 3rd row. */ unMatrixValues[U_SCALEZ] = D3DXVec3Length(&row[2]); D3DXVec3Scale(&row[2], &row[2], 1.0); unMatrixValues[U_SHEARXZ] /= unMatrixValues[U_SCALEZ]; unMatrixValues[U_SHEARYZ] /= unMatrixValues[U_SCALEZ]; /* At this point, the matrix (in rows[]) is orthonormal. * Check for a coordinate system flip. If the determinant * is -1, then negate the matrix and the scaling factors. */ if ( D3DXVec3Dot( &row[0], D3DXVec3Cross(&pdum3, &row[1], &row[2]) ) < 0 ) for ( i = 0; i < 3; i++ ) { unMatrixValues[U_SCALEX+i] *= -1; row[i].x *= -1; row[i].y *= -1; row[i].z *= -1; } /* Now, get the rotations out, as described in the gem. */ unMatrixValues[U_ROTATEY] = asin(-row[0].z); if ( cos(unMatrixValues[U_ROTATEY]) != 0 ) { unMatrixValues[U_ROTATEX] = atan2(row[1].z, row[2].z); unMatrixValues[U_ROTATEZ] = atan2(row[0].y, row[0].x); } else { unMatrixValues[U_ROTATEX] = atan2(-row[2].x, row[1].y); unMatrixValues[U_ROTATEZ] = 0; } /* All done! */ *TransVec = D3DXVECTOR3((float)unMatrixValues[U_TRANSX], (float)unMatrixValues[U_TRANSY], (float)unMatrixValues[U_TRANSZ]); *ScaleVec = D3DXVECTOR3((float)unMatrixValues[U_SCALEX], (float)unMatrixValues[U_SCALEY], (float)unMatrixValues[U_SCALEZ]); D3DXQUATERNION Qtemp; D3DXQuaternionRotationAxis(RotQ, &D3DXVECTOR3(1, 0, 0), (float)unMatrixValues[U_ROTATEX]); D3DXQuaternionRotationAxis(&Qtemp, &D3DXVECTOR3(0, 1, 0), (float)unMatrixValues[U_ROTATEY]); D3DXQuaternionMultiply(RotQ, RotQ, &Qtemp); D3DXQuaternionRotationAxis(&Qtemp, &D3DXVECTOR3(0, 0, 1), (float)unMatrixValues[U_ROTATEZ]); D3DXQuaternionMultiply(RotQ, RotQ, &Qtemp); } ////////////////////////////////////////////////////////////////////////// D3DXVECTOR3* C3DUtils::V3Combine (const D3DXVECTOR3* a, const D3DXVECTOR3* b, D3DXVECTOR3* result, double ascl, double bscl) { result->x = (float)((ascl * a->x) + (bscl * b->x)); result->y = (float)((ascl * a->y) + (bscl * b->y)); result->z = (float)((ascl * a->z) + (bscl * b->z)); return(result); } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::SetFixedVertexShader(LPDIRECT3DDEVICE Device, DWORD FVF) { #ifdef WME_D3D9 Device->SetVertexShader(NULL); return Device->SetFVF(FVF); #else return Device->SetVertexShader(FVF); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::SetStreamSource(LPDIRECT3DDEVICE Device, UINT StreamNumber, LPDIRECT3DVERTEXBUFFER pStreamData, UINT Stride) { #ifdef WME_D3D9 return Device->SetStreamSource(StreamNumber, pStreamData, 0, Stride); #else return Device->SetStreamSource(StreamNumber, pStreamData, Stride); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::SetIndices(LPDIRECT3DDEVICE Device, LPDIRECT3DINDEXBUFFER pIndexData) { #ifdef WME_D3D9 return Device->SetIndices(pIndexData); #else return Device->SetIndices(pIndexData, 0); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::CreateDepthStencilSurface(LPDIRECT3DDEVICE Device, UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, LPDIRECT3DSURFACE* ppSurface) { #ifdef WME_D3D9 return Device->CreateDepthStencilSurface(Width, Height, Format, MultiSample, 0, FALSE, ppSurface, NULL); #else return Device->CreateDepthStencilSurface(Width, Height, Format, MultiSample, ppSurface); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::GetRenderTarget(LPDIRECT3DDEVICE Device, LPDIRECT3DSURFACE* ppRenderTarget, LPDIRECT3DSURFACE* ppZStencilSurface) { #ifdef WME_D3D9 Device->GetRenderTarget(0, ppRenderTarget); return Device->GetDepthStencilSurface(ppZStencilSurface); #else Device->GetRenderTarget(ppRenderTarget); return Device->GetDepthStencilSurface(ppZStencilSurface); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::SetRenderTarget(LPDIRECT3DDEVICE Device, LPDIRECT3DSURFACE pRenderTarget, LPDIRECT3DSURFACE pZStencilSurface) { #ifdef WME_D3D9 Device->SetRenderTarget(0, pRenderTarget); return Device->SetDepthStencilSurface(pZStencilSurface); #else return Device->SetRenderTarget(pRenderTarget, pZStencilSurface); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::SetTextureStageState(LPDIRECT3DDEVICE Device, DWORD Stage, DWORD State, DWORD Value) { #ifdef WME_D3D9 // some state which was here got pushed into sampler state in D3D9 switch (State) { case D3DTSS_ADDRESSU: return Device->SetSamplerState(Stage, D3DSAMP_ADDRESSU, Value); case D3DTSS_ADDRESSV: return Device->SetSamplerState(Stage, D3DSAMP_ADDRESSV, Value); case D3DTSS_BORDERCOLOR: return Device->SetSamplerState(Stage, D3DSAMP_BORDERCOLOR, Value); case D3DTSS_MAGFILTER: return Device->SetSamplerState(Stage, D3DSAMP_MAGFILTER, Value); case D3DTSS_MINFILTER: return Device->SetSamplerState(Stage, D3DSAMP_MINFILTER, Value); case D3DTSS_MIPFILTER: return Device->SetSamplerState(Stage, D3DSAMP_MIPFILTER, Value); case D3DTSS_MIPMAPLODBIAS: return Device->SetSamplerState(Stage, D3DSAMP_MIPMAPLODBIAS, Value); case D3DTSS_MAXMIPLEVEL: return Device->SetSamplerState(Stage, D3DSAMP_MAXMIPLEVEL, Value); case D3DTSS_MAXANISOTROPY: return Device->SetSamplerState(Stage, D3DSAMP_MAXANISOTROPY, Value); default: return Device->SetTextureStageState(Stage, (D3DTEXTURESTAGESTATETYPE)State, Value); } #else return Device->SetTextureStageState(Stage, (D3DTEXTURESTAGESTATETYPE)State, Value); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::CreateImageSurface(LPDIRECT3DDEVICE Device, UINT Width, UINT Height, D3DFORMAT Format, LPDIRECT3DSURFACE* ppSurface) { #ifdef WME_D3D9 return Device->CreateOffscreenPlainSurface(Width, Height, Format, D3DPOOL_SCRATCH, ppSurface, NULL); #else return Device->CreateImageSurface(Width, Height, Format, ppSurface); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::GetFrontBuffer(LPDIRECT3DDEVICE Device, LPDIRECT3DSURFACE pDestSurface) { #ifdef WME_D3D9 return Device->GetFrontBufferData(0, pDestSurface); #else return Device->GetFrontBuffer(pDestSurface); #endif } ////////////////////////////////////////////////////////////////////////// UINT C3DUtils::GetAdapterModeCount(LPDIRECT3D d3d, UINT Adapter, D3DFORMAT Format) { #ifdef WME_D3D9 return d3d->GetAdapterModeCount(Adapter, Format); #else return d3d->GetAdapterModeCount(Adapter); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::EnumAdapterModes(LPDIRECT3D d3d, UINT Adapter, D3DFORMAT Format, UINT Mode, D3DDISPLAYMODE* pMode) { #ifdef WME_D3D9 return d3d->EnumAdapterModes(Adapter, Format, Mode, pMode); #else return d3d->EnumAdapterModes(Adapter, Mode, pMode); #endif } ////////////////////////////////////////////////////////////////////////// HRESULT C3DUtils::DrawIndexedPrimitive(LPDIRECT3DDEVICE Device, D3DPRIMITIVETYPE Type, UINT MinIndex, UINT NumVertices, UINT StartIndex, UINT PrimitiveCount) { #ifdef WME_D3D9 return Device->DrawIndexedPrimitive(Type, 0, MinIndex, NumVertices, StartIndex, PrimitiveCount); #else return Device->DrawIndexedPrimitive(Type, MinIndex, NumVertices, StartIndex, PrimitiveCount); #endif }
32.390654
175
0.626003
[ "object", "vector" ]
5b7496fe9901ba9e3e2ce516b118560d60a0c7e4
1,432
hpp
C++
caffe/include/caffe/layers/power_file_layer.hpp
shaoxiaohu/Face-Alignment-with-Two-Stage-Re-initialization-
ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b
[ "MIT" ]
199
2015-12-02T07:05:25.000Z
2021-09-06T06:52:54.000Z
include/caffe/power_file_layer.hpp
zmlshiwo/GuidedNet
4c87d392addc38700caf2856b450f2c74a79e122
[ "MIT" ]
20
2016-06-01T10:31:08.000Z
2020-04-02T07:46:51.000Z
include/caffe/power_file_layer.hpp
zmlshiwo/GuidedNet
4c87d392addc38700caf2856b450f2c74a79e122
[ "MIT" ]
95
2015-11-19T03:52:46.000Z
2020-04-07T08:57:45.000Z
#ifndef POWER_FILE_LAYER_HPP_ #define POWER_FILE_LAYER_HPP_ #include <boost/shared_ptr.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <cmath> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { template <typename Dtype> class PowerFileLayer : public Layer<Dtype> { public: explicit PowerFileLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "PowerFile"; } virtual inline int ExactNumBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); private: Blob<Dtype> shift_; }; } // namespace caffe #endif // CAFFE_COMMON_HPP_
29.22449
78
0.724162
[ "vector" ]
5b75111d4f34c7302aae67bf1eac735996226bc1
21,319
cc
C++
tce/src/applibs/ProGe/ProGeScriptGenerator.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
tce/src/applibs/ProGe/ProGeScriptGenerator.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
tce/src/applibs/ProGe/ProGeScriptGenerator.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* Copyright (c) 2002-2011 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file ProGeScriptGenerator.cc * * Implementation of ProGeScriptGenerator class. * * @author Esa M��tt� 2007 (esa.maatta-no.spam-tut.fi) * @author Otto Esko 2008 (otto.esko-no.spam-tut.fi) * @author Pekka J��skel�inen 2011 * @author Vinogradov Viacheslav(added Verilog generating) 2012 * @note rating: red */ #include <iostream> #include <vector> #include <list> #include <string> #include <fstream> #include "CompilerWarnings.hh" IGNORE_CLANG_WARNING("-Wkeyword-macro") #include <boost/regex.hpp> POP_CLANG_DIAGS #include "ProGeScriptGenerator.hh" #include "HDBManager.hh" #include "CachedHDBManager.hh" #include "HDBRegistry.hh" #include "FileSystem.hh" #include "MachineImplementation.hh" #include "UnitImplementationLocation.hh" #include "FUEntry.hh" #include "FUImplementation.hh" #include "RFEntry.hh" #include "RFImplementation.hh" using namespace ProGe; using IDF::MachineImplementation; using IDF::FUImplementationLocation; using IDF::RFImplementationLocation; using std::string; using std::endl; using std::list; const string MAGICAL_RUNTIME_CONSTANT = "52390ns"; /** * The constructor. * * Script generating needs a IDF file and hdb files mentioned there. Working * directory is assumed to be the destination directory for script files. * * @param dstDir Directory where to generate scripts. * @param progeOutDir Directory where ProGes output vhdl files lie. * @param testBenchDir Directory where a test bench files are located. * @param projectRoot Directory that is project root, needed if relative dirs * wanted to generated scripts. Useful if other dirs given are under this * directory. */ ProGeScriptGenerator::ProGeScriptGenerator( const ProGe::HDL language, const IDF::MachineImplementation& idf, const std::string& dstDir, const std::string& progeOutDir, const std::string& sharedOutDir, const std::string& testBenchDir, const std::string& toplevelEntity = "tta0") : dstDir_(dstDir), progeOutDir_(progeOutDir), sharedOutDir_(sharedOutDir), testBenchDir_(testBenchDir), workDir_("work"), vhdlDir_("vhdl"), verDir_("verilog"), gcuicDir_("gcu_ic"), tbDir_("tb"), modsimCompileScriptName_("modsim_compile.sh"), ghdlCompileScriptName_("ghdl_compile.sh"), iverilogCompileScriptName_("iverilog_compile.sh"), modsimSimulateScriptName_("modsim_simulate.sh"), ghdlSimulateScriptName_("ghdl_simulate.sh"), iverilogSimulateScriptName_("iverilog_simulate.sh"), testbenchName_("testbench"), toplevelEntity_(toplevelEntity), idf_(idf), language_(language){ fetchFiles(); prepareFiles(); } /** * The destructor. */ ProGeScriptGenerator::~ProGeScriptGenerator() { } /** * Generates all scripts to destination dir (dstDir_). * * @exception IOException */ void ProGeScriptGenerator::generateAll() { generateModsimCompile(); if(language_==VHDL) generateGhdlCompile(); else generateIverilogCompile(); generateModsimSimulate(); if(language_==VHDL) generateGhdlSimulate(); else generateIverilogSimulate(); } /** * Generates a script for compilation using modelsim. * * @exception IOException */ void ProGeScriptGenerator::generateModsimCompile() { string dstFile = dstDir_ + FileSystem::DIRECTORY_SEPARATOR + modsimCompileScriptName_; createExecutableFile(dstFile); std::ofstream stream(dstFile.c_str(), std::ofstream::out); generateStart(stream); stream << "rm -rf " << workDir_ << endl; stream << "vlib " << workDir_ << endl; stream << "vmap" << endl; stream << endl; string program = ((language_==VHDL)?"vcom":"vlog +incdir+verilog +incdir+gcu_ic +incdir+tb"); outputScriptCommands(stream, vhdlFiles_, program,""); stream << endl; outputScriptCommands(stream, gcuicFiles_, program,""); stream << endl; outputScriptCommands(stream, testBenchFiles_, program,""); stream.close(); } /** * Generates a script for compilation using ghdl. * * @exception IOException */ void ProGeScriptGenerator::generateGhdlCompile() { string dstFile = dstDir_ + FileSystem::DIRECTORY_SEPARATOR + ghdlCompileScriptName_; createExecutableFile(dstFile); std::ofstream stream(dstFile.c_str(), std::ofstream::out); generateStart(stream); stream << "rm -rf " << workDir_ << endl; stream << "mkdir -p work" << endl; stream << "rm -rf bus.dump" << endl; stream << "rm -rf " << testbenchName_ << endl; stream << endl; string program = "ghdl -i --workdir=" + workDir_; outputScriptCommands(stream, vhdlFiles_, program,""); stream << endl; outputScriptCommands(stream, gcuicFiles_, program,""); stream << endl; outputScriptCommands(stream, testBenchFiles_, program,""); stream << endl; // compile command for ghdl stream << "ghdl -m --workdir=" << workDir_ << " --ieee=synopsys -fexplicit " << testbenchName_ << endl; stream.close(); } /** * Generates a script for compilation using iVerilog. * * @exception IOException */ void ProGeScriptGenerator::generateIverilogCompile() { string dstFile = dstDir_ + FileSystem::DIRECTORY_SEPARATOR + iverilogCompileScriptName_; createExecutableFile(dstFile); std::ofstream stream(dstFile.c_str(), std::ofstream::out); generateStart(stream); stream << "rm -rf " << testbenchName_ << endl << endl << "iverilog -g2001 -D _IVERILOG_ " << "-Itb -Iverilog -Igcu_ic "; outputScriptCommands(stream, vhdlFiles_, ""," \\"); outputScriptCommands(stream, gcuicFiles_, ""," \\"); outputScriptCommands(stream, testBenchFiles_, ""," \\"); stream << "-s " << testbenchName_ << " \\" << endl; stream << "-o " << testbenchName_ << endl; stream.close(); } /** * Generates a script for simulating using modelsims vsim. */ void ProGeScriptGenerator::generateModsimSimulate() { string dstFile = dstDir_ + FileSystem::DIRECTORY_SEPARATOR + modsimSimulateScriptName_; createExecutableFile(dstFile); std::ofstream stream(dstFile.c_str(), std::ofstream::out); generateStart(stream); stream << "vsim " << testbenchName_ << " -c -do 'run " << MAGICAL_RUNTIME_CONSTANT << "; exit'" << endl; stream.close(); } /** * Generates a script for simulating using ghdl. * * @exception IOException */ void ProGeScriptGenerator::generateGhdlSimulate() { string dstFile = dstDir_ + FileSystem::DIRECTORY_SEPARATOR + ghdlSimulateScriptName_; createExecutableFile(dstFile); std::ofstream stream(dstFile.c_str(), std::ofstream::out); generateStart(stream); stream << "if [ -e " << testbenchName_ << " ]; then" << endl << " ./" << testbenchName_ << " --assert-level=none --stop-time=" << MAGICAL_RUNTIME_CONSTANT << endl << "else" << endl << " # Newer GHDL versions does not produce binary." << endl << " ghdl -r --workdir=work --ieee=synopsys " << testbenchName_ << " --assert-level=none --stop-time=" << MAGICAL_RUNTIME_CONSTANT << endl << "fi" << endl; stream.close(); } /** * Generates a script for simulating using iVerilog. * * @exception IOException */ void ProGeScriptGenerator::generateIverilogSimulate() { string dstFile = dstDir_ + FileSystem::DIRECTORY_SEPARATOR + iverilogSimulateScriptName_; createExecutableFile(dstFile); std::ofstream stream(dstFile.c_str(), std::ofstream::out); generateStart(stream); stream << "./" << testbenchName_ << " --assert-level=none --stop-time=" << MAGICAL_RUNTIME_CONSTANT << endl; stream.close(); } /** * Creates a script file given as parameter and sets permissions. * * @param Name of the script file to be created * @exception IOException */ void ProGeScriptGenerator::createExecutableFile(const std::string& fileName) { FileSystem::removeFileOrDirectory(fileName); bool isCreated = FileSystem::createFile(fileName); if (!isCreated) { string errorMsg = "Unable to create file " + fileName; throw IOException(__FILE__, __LINE__, __func__, errorMsg); } FileSystem::setFileExecutable(fileName); } /** * Generates the start of the shell script. * * @param stream Stream where output is put. */ void ProGeScriptGenerator::generateStart(std::ostream& stream) { stream << "#! /bin/sh" << endl; stream << "# This script was automatically generated." << endl << endl; } /** * Outputs shell commands to stream. * * Creates script commands using list of files and command prefix and outputs * them to the given stream. * * @param stream Output stream. * @param files List of filenames to use. * @param cmdPrefix Prefix command. * @param cmdPostfix Prefix command. */ void ProGeScriptGenerator::outputScriptCommands( std::ostream& stream, const std::list<std::string>& files, const std::string& cmdPrefix, const std::string& cmdPostfix) { list<string>::const_iterator iter = files.begin(); while (iter != files.end()) { stream << cmdPrefix << " " << *iter++ << cmdPostfix << endl; } } /** * Regex find from a file. * * Finds text matching the given regex from file by line at a time. * Case is ignored when interpreting the regex. * * @param perlre Perl syntax regular expression. * @param matchRegion Region from the match appended to output list. * @param fileName Name and path of file name to be opened and read. * @param found List where matches are appended. */ void ProGeScriptGenerator::findText( const std::string& perlre, const unsigned int& matchRegion, const std::string& fileName, std::list<std::string>& found) { const int LINESIZE = 1000; const boost::regex re(perlre, boost::regex::perl|boost::regex::icase); char line[LINESIZE]; string::const_iterator begin; string::const_iterator end; string stemp; std::ifstream ifs( fileName.c_str() , std::ifstream::in ); boost::match_results<string::const_iterator> matches; while (ifs.good()) { ifs.getline(line, LINESIZE-1); stemp = string(line); begin = stemp.begin(); end = stemp.end(); if (boost::regex_search(begin, end, matches, re)) { found.push_back(string(matches[matchRegion].first, matches[matchRegion].second)); } } ifs.close(); } /** * Relative file name/path sort using a reference. * * Sorts file in one list according to other list,placing in beginning of * list, only relative order matters (which entry comes first). Algorithm * used does relative sort between two lists, the other is sorted according * to the other. * * @param toSort List to be sorted. * @param acSort List where reference order is taken from. */ void ProGeScriptGenerator::sortFilesFirst( std::list<std::string>& toSort, std::list<std::string>& acSort) { typedef std::list<std::string>::iterator listStrIt; listStrIt itAc1 = acSort.begin(); listStrIt itTo = toSort.begin(); listStrIt itTo2; while (itAc1 != acSort.end()) { // now check list to be sorted bool swapped = false; itTo2 = itTo; while (itTo2 != toSort.end()) { if (FileSystem::compareFileNames(*itTo2, *itAc1, dstDir_)) { // now change itTo2 and itTo places string temp = *itTo; *itTo = *itTo2; *itTo2 = temp; swapped = true; break; } ++itTo2; } if (swapped) { ++itTo; } ++itAc1; } } /** * Relative file name/path sort using a reference. * * Sorts file in one list according to other list, placing in end of list, * only relative order matters (which entry comes first). Algorithm used * does relative sort between two lists, the other is sorted according to * the other. * * @param toSort List to be sorted. * @param acSort List where reference order is taken from. */ void ProGeScriptGenerator::sortFilesLast( std::list<std::string>& toSort, std::list<std::string>& acSort) { typedef std::list<std::string>::iterator listStrIt; typedef std::list<std::string>::reverse_iterator rlistStrIt; listStrIt itAc1 = acSort.begin(); rlistStrIt itTo = toSort.rbegin(); rlistStrIt itTo2; while (itAc1 != acSort.end()) { // now check list to be sorted bool swapped = false; itTo2 = itTo; while (itTo2 != toSort.rend()) { if (FileSystem::compareFileNames(*itTo2, *itAc1,dstDir_)) { // now change itTo2 and itTo places string temp = *itTo; *itTo = *itTo2; *itTo2 = temp; swapped = true; break; } ++itTo2; } if (swapped) { ++itTo; } ++itAc1; } } /** * Gets compilation order for vhdl files from IDF/HDB files. * * @param order List of file names is relative compilation order. */ void ProGeScriptGenerator::getBlockOrder(std::list<std::string>& order) { std::set<string> uniqueFiles; // FU implementation HDL files for (int i = 0; i < idf_.fuImplementationCount(); i++) { const FUImplementationLocation& fuLoc = idf_.fuImplementation(i); string hdbFile = fuLoc.hdbFile(); HDB::CachedHDBManager& hdb = HDB::HDBRegistry::instance().hdb(hdbFile); HDB::FUEntry* fu = hdb.fuByEntryID(fuLoc.id()); const HDB::FUImplementation& fuImpl = fu->implementation(); for (int j = 0; j < fuImpl.implementationFileCount(); j++) { string file = FileSystem::fileOfPath(fuImpl.file(j).pathToFile()); if (uniqueFiles.find(file) == uniqueFiles.end()) { order.push_back(file); uniqueFiles.insert(file); } } } // RF implementation HDL files for (int i = 0; i < idf_.rfImplementationCount(); i++) { const RFImplementationLocation& rfLoc = idf_.rfImplementation(i); string hdbFile = rfLoc.hdbFile(); HDB::CachedHDBManager& hdb = HDB::HDBRegistry::instance().hdb(hdbFile); HDB::RFEntry* rf = hdb.rfByEntryID(rfLoc.id()); const HDB::RFImplementation& rfImpl = rf->implementation(); for (int j = 0; j < rfImpl.implementationFileCount(); j++) { string file = FileSystem::fileOfPath(rfImpl.file(j).pathToFile()); if (uniqueFiles.find(file) == uniqueFiles.end()) { order.push_back(file); uniqueFiles.insert(file); } } } } /** * Prefixes strings in a container with a string within a range. * * @param tlist Container of strings. * @param prefix Prefix to be added to strings in container. * @param start Starting location in a container, 0 is the first. * @param end Ending location in a container, size-1 is the last. */ void ProGeScriptGenerator::prefixStrings( std::list<std::string>& tlist, const std::string& prefix, int start, int end) { if (end == -1 || end >= static_cast<int>(tlist.size())) { end = tlist.size() - 1; } list<string>::iterator itl = tlist.begin(); for (int c = 0; c <= end; ++c, ++itl) { if (c >= start) { *itl = prefix + *itl; } } } /** * Gets file names from project directory. */ void ProGeScriptGenerator::fetchFiles() { // files that match are accepted string vhdlRegex = ((language_==VHDL)?".*\\.(vhd|vhdl|pkg)$":".*\\.(v)$"); // generate relative paths bool absolutePaths = false; // getting files from project dir string dirName = progeOutDir_ + FileSystem::DIRECTORY_SEPARATOR + ((language_==VHDL)?vhdlDir_:verDir_); if (FileSystem::fileIsDirectory(dirName)) { findFiles(vhdlRegex, FileSystem::directoryContents(dirName, absolutePaths), vhdlFiles_); // add the toplevelEntity + _imem_mau_pkg.vhdl to vhdlFiles_. // It is generated by PIG so it is not yet present. if(language_==VHDL){ string imemMauPkg = vhdlDir_ + FileSystem::DIRECTORY_SEPARATOR + toplevelEntity_ + "_imem_mau_pkg.vhdl"; vhdlFiles_.push_back(imemMauPkg); } } std::string sharedDir = sharedOutDir_ + FileSystem::DIRECTORY_SEPARATOR + ((language_==VHDL)?vhdlDir_:verDir_); if (sharedDir != dirName && FileSystem::fileIsDirectory(sharedDir)) { findFiles( vhdlRegex, FileSystem::directoryContents(sharedDir, absolutePaths), vhdlFiles_); } dirName = progeOutDir_ + FileSystem::DIRECTORY_SEPARATOR + gcuicDir_; if (FileSystem::fileIsDirectory(dirName)) { findFiles(vhdlRegex, FileSystem::directoryContents(dirName, absolutePaths), gcuicFiles_); } if (FileSystem::fileIsDirectory(testBenchDir_)) { FileSystem::findFromDirectoryRecursive(vhdlRegex, testBenchDir_, testBenchFiles_); } else { findFiles(vhdlRegex, FileSystem::directoryContents(dstDir_, absolutePaths), testBenchFiles_); } } /** * Prepares filename lists, generally sorts them. */ void ProGeScriptGenerator::prepareFiles() { const string DS = FileSystem::DIRECTORY_SEPARATOR; if(language_==VHDL){ string gcuIcDirName = progeOutDir_ + DS + gcuicDir_ + DS; list<string> gcuicFirstOrder; gcuicFirstOrder.push_back("gcu_opcodes_pkg.vhdl"); prefixStrings(gcuicFirstOrder, gcuIcDirName); sortFilesFirst(gcuicFiles_, gcuicFirstOrder); list<string> gcuicLastOrder; gcuicLastOrder.push_back("ic.vhdl"); prefixStrings(gcuicLastOrder, gcuIcDirName); sortFilesLast(gcuicFiles_, gcuicLastOrder); string vhdlDirName = progeOutDir_ + DS + vhdlDir_ + DS; list<string> vhdlFirstOrder; vhdlFirstOrder.push_back(toplevelEntity_ + "_imem_mau_pkg.vhdl"); vhdlFirstOrder.push_back("globals_pkg.vhdl"); vhdlFirstOrder.push_back("tce_util_pkg.vhdl"); string paramsPkg = toplevelEntity_ + "_params_pkg.vhdl"; vhdlFirstOrder.push_back(paramsPkg); // add FU and RF files in correct order getBlockOrder(vhdlFirstOrder); prefixStrings(vhdlFirstOrder, vhdlDirName); sortFilesFirst(vhdlFiles_, vhdlFirstOrder); list<string> vhdlLastOrder; string toplevelFile = toplevelEntity_ + ".vhdl"; vhdlLastOrder.push_back(toplevelFile); prefixStrings(vhdlLastOrder, vhdlDirName); sortFilesLast(vhdlFiles_, vhdlLastOrder); string tbDirName = progeOutDir_ + DS + tbDir_ + DS; list<string> testBenchLastOrder; testBenchLastOrder.push_back("testbench_cfg.vhdl"); testBenchLastOrder.push_back("testbench.vhdl"); testBenchLastOrder.push_back("proc_arch.vhdl"); testBenchLastOrder.push_back("proc_ent.vhdl"); testBenchLastOrder.push_back("testbench_constants_pkg.vhdl"); prefixStrings(testBenchLastOrder, tbDirName); sortFilesLast(testBenchFiles_, testBenchLastOrder); } else { //nothing to do here } // make dirs relative to dstDir_ list<string>::iterator itl; itl = vhdlFiles_.begin(); while (itl != vhdlFiles_.end()) { FileSystem::relativeDir(dstDir_, *itl++); } itl = gcuicFiles_.begin(); while (itl != gcuicFiles_.end()) { FileSystem::relativeDir(dstDir_, *itl++); } itl = testBenchFiles_.begin(); while (itl != testBenchFiles_.end()) { FileSystem::relativeDir(dstDir_, *itl++); } }
30.412268
80
0.646747
[ "vector" ]