blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
b5e70ccc7874ecb72d72a5aa70e54a7f5ca15176
22675f7a25e1e9825debcafb8933eeb5aa1857dc
/Client/src/GameView/Characters/Hud.cpp
896d378148a70176263c1d5858479f640f2d37f4
[]
no_license
SaFernandezC/taller-tpFinal-1c2021
adfebc425a86354a2d37af63f5c2d956df6e40bf
2c653f577bb6d79cb5b0528f453640163bb3003e
refs/heads/main
2023-06-20T03:06:31.348721
2021-07-20T20:32:05
2021-07-20T20:32:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,094
cpp
Hud.cpp
#include "Hud.h" Hud::Hud(Renderer& renderer, int window_width, int window_height):renderer(renderer), window_width(window_width), window_height(window_height), time_to_explode(-1){} void Hud::loadMedia(){ Color black_color = {0x00, 0x00, 0x00}; Color yellow = {0xFF, 0xFF, 0x00}; numbers.loadFromFile(renderer, HUD_NUMS_PATH, black_color, SDL_BLENDMODE_BLEND, 150); hud_symbols.loadFromFile(renderer, HUD_SIMBOLS_PATH, black_color, SDL_BLENDMODE_BLEND, 150); weapons[PositionType::AK47].loadFromFile(renderer, HUD_AK47_PATH, black_color, SDL_BLENDMODE_BLEND, 150); weapons[PositionType::M3].loadFromFile(renderer, HUD_M3_PATH, black_color, SDL_BLENDMODE_BLEND, 150); weapons[PositionType::AWP].loadFromFile(renderer, HUD_AWP_PATH, black_color, SDL_BLENDMODE_BLEND, 150); weapons[PositionType::GLOCK].loadFromFile(renderer, HUD_GLOCK_PATH, black_color, SDL_BLENDMODE_BLEND, 150); weapons[PositionType::KNIFE].loadFromFile(renderer, HUD_KNIFE_PATH, black_color, SDL_BLENDMODE_BLEND, 150); hud_symbols.setColor(yellow); numbers.setColor(yellow); for (auto it = weapons.begin(); it != weapons.end(); ++it) { it->second.setColor(yellow); } setClips(); } void Hud::setClips(){ /*clips[0] -> life_symbol*/ clips[0].x = 0; clips[0].y = 0; clips[0].w = 64; clips[0].h = 64; /*clips[1] -> money_symbol*/ clips[1].x = 460; clips[1].y = 0; clips[1].w = 40; clips[1].h = 64; /*clips[2] -> infinity_symbol*/ clips[2].x = 704; clips[2].y = 0; clips[2].w = 64; clips[2].h = 64; /*clips[3] -> bomb_symbol*/ clips[3].x = 382; clips[3].y = 0; clips[3].w = 70; clips[3].h = 64; /*clips[4] -> clock_symbol*/ clips[4].x = 128; clips[4].y = 0; clips[4].w = 64; clips[4].h = 64; /*clips[5] -> colon_symbol*/ clips[5].x = 474; clips[5].y = 0; clips[5].w = 24; clips[5].h = NUMBERS_HEIGHT; } void Hud::update_values(char life, int money, int ammo, char weapon_type, bool has_bomb){ this->life = (int)life; this->money = money; this->ammo = ammo; this->weapon_type = weapon_type; this->has_bomb = has_bomb; } void Hud::updateTimeToExplode(int time){ time_to_explode = time; } int Hud::numbers_offset(std::string& string, int& i){ int number = string[i] - 48; if(number != 0){ return number*NUMBERS_WIDTH + number*NUMBERS_OFFSET; } return number*NUMBERS_WIDTH; } void Hud::renderLife(){ std::string life_str = std::to_string(life); int offset = 0; int y_pos = window_height - NUMBERS_OFFSET - NUMBERS_HEIGHT; SDL_Rect clip = {0}; SDL_Rect quad = {0}; quad = {NUMBERS_OFFSET, y_pos, SYMBOL_WIDTH, SYMBOL_HEIGHT}; renderer.render(hud_symbols.getTexture(), &clips[0], &quad); for (int i = 0; i < (int)life_str.length(); i++) { offset = numbers_offset(life_str, i); clip = {offset, 0, NUMBERS_WIDTH, NUMBERS_HEIGHT}; //Con esto obtengo el numero a renderizar quad = {i*NUMBERS_WIDTH + NUMBERS_OFFSET + SYMBOL_WIDTH, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; renderer.render(numbers.getTexture(), &clip, &quad); } } void Hud::renderMoney(){ std::string money_str = std::to_string(money); int money_offset = 1; int offset = 0; int y_pos = window_height - NUMBERS_OFFSET - NUMBERS_HEIGHT; SDL_Rect clip = {0}; SDL_Rect quad = {0}; for (int i = (int)money_str.length() - 1; i >= 0; i--) { offset = numbers_offset(money_str, i); clip = {offset, 0, NUMBERS_WIDTH, NUMBERS_HEIGHT}; //Con esto obtengo el numero a renderizar quad = {window_width - NUMBERS_OFFSET - (money_offset)*NUMBERS_WIDTH, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; renderer.render(numbers.getTexture(), &clip, &quad); money_offset++; } quad = {window_width + NUMBERS_OFFSET - (money_offset)*NUMBERS_WIDTH, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; renderer.render(hud_symbols.getTexture(), &clips[1], &quad); } void Hud::renderAmmo(){ std::string ammo_str = std::to_string(ammo); int offset = 0; int i = 0; int y_pos = window_height - NUMBERS_OFFSET - NUMBERS_HEIGHT; SDL_Rect clip = {0}; SDL_Rect ammo_quad = {0}; SDL_Rect quad = {AMMO_OFFSET, y_pos, SYMBOL_WIDTH, SYMBOL_HEIGHT}; if(ammo == INIFNITY_AMMO){ renderer.render(hud_symbols.getTexture(), &clips[2], &quad); ammo_quad = {AMMO_OFFSET + NUMBERS_OFFSET + SYMBOL_WIDTH, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; } if(ammo != INIFNITY_AMMO){ for (i = 0; i < (int)ammo_str.length(); i++) { offset = numbers_offset(ammo_str, i); clip = {offset, 0, NUMBERS_WIDTH, NUMBERS_HEIGHT}; //Con esto obtengo el numero a renderizar quad = {i*NUMBERS_WIDTH + NUMBERS_OFFSET + AMMO_OFFSET, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; renderer.render(numbers.getTexture(), &clip, &quad); ammo_quad = {AMMO_OFFSET + (i+2)*NUMBERS_OFFSET + (i+1)*NUMBERS_WIDTH, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; } } offset = AMMO_POSITION*NUMBERS_WIDTH + AMMO_POSITION*NUMBERS_OFFSET; clip = {offset, 0, NUMBERS_WIDTH, NUMBERS_HEIGHT}; renderer.render(numbers.getTexture(), &clip, &ammo_quad); } void Hud::renderBomb(){ if(!has_bomb){ return; } SDL_Rect quad = {10, 10, 70, 64}; renderer.render(hud_symbols.getTexture(), &clips[3], &quad); } void Hud::renderWeapon(){ SDL_Rect quad = {window_width - 50, 10, weapons.at(weapon_type).get_w(), weapons.at(weapon_type).get_h()}; renderer.render(weapons.at(weapon_type).getTexture(), NULL, &quad); } #include <iostream> void Hud::renderTimeToExplode(){ /*El total va a tener 214 de ancho y 66 de alto*/ if(time_to_explode == NO_TIME){ return; } int mins = time_to_explode/60.0; int secs = (time_to_explode/60.0 - mins)*60; int y_pos = 10; int offset = 0; int i = 0; std::string mins_str = std::to_string(mins); std::string secs_str = std::to_string(secs); SDL_Rect clip = {0}; /*rederizo el reloj*/ SDL_Rect quad = {CLOCK_POSITION, y_pos, SYMBOL_WIDTH, SYMBOL_HEIGHT}; renderer.render(hud_symbols.getTexture(), &clips[4], &quad); /*rederizo los minutos*/ for (i = 0; i < (int)mins_str.length(); i++) { offset = numbers_offset(mins_str, i); clip = {offset, 0, NUMBERS_WIDTH, NUMBERS_HEIGHT}; quad = {i*NUMBERS_WIDTH + NUMBERS_OFFSET + SYMBOL_WIDTH + CLOCK_POSITION, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; renderer.render(numbers.getTexture(), &clip, &quad); } /*Renderizo los dos puntos*/ int x_pos = i*NUMBERS_WIDTH + NUMBERS_OFFSET + SYMBOL_WIDTH + CLOCK_POSITION; quad = {x_pos, y_pos, COLON_WIDTH, NUMBERS_HEIGHT}; renderer.render(numbers.getTexture(), &clips[5], &quad); /*rederizo los segundos*/ x_pos = x_pos + COLON_WIDTH; for (i = 0; i < (int)secs_str.length(); i++) { x_pos = x_pos + i*NUMBERS_WIDTH + NUMBERS_OFFSET; offset = numbers_offset(secs_str, i); clip = {offset, 0, NUMBERS_WIDTH, NUMBERS_HEIGHT}; quad = {x_pos, y_pos, NUMBERS_WIDTH, NUMBERS_HEIGHT}; renderer.render(numbers.getTexture(), &clip, &quad); } } void Hud::render(){ renderLife(); renderMoney(); renderAmmo(); renderBomb(); renderWeapon(); renderTimeToExplode(); } Hud::~Hud(){}
73b1797a9e1546f153d213f80b01549f2bdc637a
8832b04803f1657567cefb6708593ecd92a01432
/FAQ_C++/Strategy.cpp
2c31417b72f7c2fc9765fc453cd30f5d0f32a35f
[]
no_license
haspeleo/Algorithms-implementation
f7d41c1c8d83a4b6ef2d75225662af4a7782c0f7
78b5b0f7b6ae4f0211ad26051870b9608a99720a
refs/heads/master
2016-09-10T20:08:36.924676
2012-11-03T18:10:50
2012-11-03T18:10:50
2,006,372
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
Strategy.cpp
#include <iostream> #include "Strategy.h" using namespace std; /* void AlgorithmeA::execute() { cout << "Traitement A" << endl; } void AlgorithmeB::execute() { cout << "Traitement B" << endl; } void AlgorithmeB::execute() { cout << "Traitement B" << endl; } Element::Element(IStrategie* strategie) : strategie(strategie) { } void Element::execute() { this->strategie->execute(); } */
c0654d9fb027c6fe3656bd63e5ef7e9082846dce
fc361f9be95b553e4563ba0b6e11b78699157859
/projeto/cutvoxel.h
4fcc0c827fef30bbfd901d094306d27d147eeada
[]
no_license
davisouzaf/projetoProgramacao
d0ab32529c55369a707746237e6999c020641e57
58e859cbb1da5ddbd06519d6262e10573adc6aab
refs/heads/master
2020-07-16T23:22:07.888774
2019-11-25T16:02:33
2019-11-25T16:02:33
205,889,109
0
0
null
null
null
null
UTF-8
C++
false
false
692
h
cutvoxel.h
#ifndef CUTVOXEL_H #define CUTVOXEL_H #include "figurageometrica.h" /** * @brief A classe CutVoxel apaga um voxel na posição especificada * @details */ class CutVoxel:public FiguraGeometrica{ private: int x,y,z; public: /** * @brief CutVoxel é o construtor da classe * @param x * @param y * @param z * @details exemplo de utilização de CutVoxel: * <pre> * CutVoxel cv(1,1,1); //apaga um voxel na posição (1,1,1) * </pre> */ CutVoxel(int x,int y, int z); /** * @brief draw apaga o voxel para o objeto Sculptor * @param t */ void draw(Sculptor &t); }; #endif // CUTVOXEL_H
93367308202979c17db60ac6d79b8d2e393a8358
161e09a54e42370f807f48b5d4e95350ac0ee38a
/chaps/session_test.cc
7365c47ef078f3a2d412cea30c2b095139b6aea9
[ "BSD-3-Clause" ]
permissive
ansiwen/chromiumos-platform2
eed53bb36e0d51f3593b1b76fb4a437e961dae3c
5ade4272fa8cc7d4a2aa2442c5e8572329a36473
refs/heads/master
2021-01-19T16:41:28.950357
2017-03-03T22:04:40
2017-03-04T10:59:07
88,277,533
0
2
null
2017-04-14T15:07:57
2017-04-14T15:07:57
null
UTF-8
C++
false
false
40,606
cc
session_test.cc
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chaps/session_impl.h" #include <memory> #include <string> #include <vector> #include <base/logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <openssl/bn.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include "chaps/chaps_factory_mock.h" #include "chaps/chaps_utility.h" #include "chaps/handle_generator_mock.h" #include "chaps/object_mock.h" #include "chaps/object_pool_mock.h" #include "chaps/tpm_utility_mock.h" using std::string; using std::vector; using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; using ::testing::Return; using ::testing::SetArgumentPointee; using ::testing::StrictMock; namespace { void ConfigureObjectPool(chaps::ObjectPoolMock* op, int handle_base) { op->SetupFake(handle_base); EXPECT_CALL(*op, Insert(_)).Times(AnyNumber()); EXPECT_CALL(*op, Find(_, _)).Times(AnyNumber()); EXPECT_CALL(*op, FindByHandle(_, _)).Times(AnyNumber()); EXPECT_CALL(*op, Delete(_)).Times(AnyNumber()); EXPECT_CALL(*op, Flush(_)).WillRepeatedly(Return(true)); } chaps::ObjectPool* CreateObjectPoolMock() { chaps::ObjectPoolMock* op = new chaps::ObjectPoolMock(); ConfigureObjectPool(op, 100); return op; } chaps::Object* CreateObjectMock() { chaps::ObjectMock* o = new chaps::ObjectMock(); o->SetupFake(); EXPECT_CALL(*o, GetObjectClass()).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributes(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, FinalizeNewObject()).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(*o, Copy(_)).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(*o, IsTokenObject()).Times(AnyNumber()); EXPECT_CALL(*o, IsAttributePresent(_)).Times(AnyNumber()); EXPECT_CALL(*o, GetAttributeString(_)).Times(AnyNumber()); EXPECT_CALL(*o, GetAttributeInt(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, GetAttributeBool(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributeString(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributeInt(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributeBool(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, set_handle(_)).Times(AnyNumber()); EXPECT_CALL(*o, set_store_id(_)).Times(AnyNumber()); EXPECT_CALL(*o, handle()).Times(AnyNumber()); EXPECT_CALL(*o, store_id()).Times(AnyNumber()); EXPECT_CALL(*o, RemoveAttribute(_)).Times(AnyNumber()); return o; } bool FakeRandom(int num_bytes, string* random) { *random = string(num_bytes, 0); return true; } void ConfigureTPMUtility(chaps::TPMUtilityMock* tpm) { EXPECT_CALL(*tpm, IsTPMAvailable()).WillRepeatedly(Return(true)); EXPECT_CALL(*tpm, GenerateRandom(_, _)).WillRepeatedly(Invoke(FakeRandom)); } string bn2bin(BIGNUM* bn) { string bin; bin.resize(BN_num_bytes(bn)); bin.resize(BN_bn2bin(bn, chaps::ConvertStringToByteBuffer(bin.data()))); return bin; } } // namespace namespace chaps { // Test fixture for an initialized SessionImpl instance. class TestSession: public ::testing::Test { public: TestSession() { EXPECT_CALL(factory_, CreateObject()) .WillRepeatedly(InvokeWithoutArgs(CreateObjectMock)); EXPECT_CALL(factory_, CreateObjectPool(_, _, _)) .WillRepeatedly(InvokeWithoutArgs(CreateObjectPoolMock)); EXPECT_CALL(handle_generator_, CreateHandle()) .WillRepeatedly(Return(1)); ConfigureObjectPool(&token_pool_, 0); ConfigureTPMUtility(&tpm_); } void SetUp() { session_.reset(new SessionImpl(1, &token_pool_, &tpm_, &factory_, &handle_generator_, false)); } void GenerateSecretKey(CK_MECHANISM_TYPE mechanism, int size, const Object** obj) { CK_BBOOL no = CK_FALSE; CK_BBOOL yes = CK_TRUE; CK_ATTRIBUTE encdec_template[] = { {CKA_TOKEN, &no, sizeof(no)}, {CKA_ENCRYPT, &yes, sizeof(yes)}, {CKA_DECRYPT, &yes, sizeof(yes)}, {CKA_VALUE_LEN, &size, sizeof(size)} }; CK_ATTRIBUTE signverify_template[] = { {CKA_TOKEN, &no, sizeof(no)}, {CKA_SIGN, &yes, sizeof(yes)}, {CKA_VERIFY, &yes, sizeof(yes)}, {CKA_VALUE_LEN, &size, sizeof(size)} }; CK_ATTRIBUTE_PTR attr = encdec_template; if (mechanism == CKM_GENERIC_SECRET_KEY_GEN) attr = signverify_template; int handle = 0; ASSERT_EQ(CKR_OK, session_->GenerateKey(mechanism, "", attr, 4, &handle)); ASSERT_TRUE(session_->GetObject(handle, obj)); } void GenerateRSAKeyPair(bool signing, int size, const Object** pub, const Object** priv) { CK_BBOOL no = CK_FALSE; CK_BBOOL yes = CK_TRUE; CK_BYTE pubexp[] = {1, 0, 1}; CK_ATTRIBUTE pub_attr[] = { {CKA_TOKEN, &no, sizeof(no)}, {CKA_ENCRYPT, signing ? &no : &yes, sizeof(no)}, {CKA_VERIFY, signing ? &yes : &no, sizeof(no)}, {CKA_PUBLIC_EXPONENT, pubexp, 3}, {CKA_MODULUS_BITS, &size, sizeof(size)} }; CK_ATTRIBUTE priv_attr[] = { {CKA_TOKEN, &no, sizeof(CK_BBOOL)}, {CKA_DECRYPT, signing ? &no : &yes, sizeof(no)}, {CKA_SIGN, signing ? &yes : &no, sizeof(no)} }; int pubh = 0, privh = 0; ASSERT_EQ(CKR_OK, session_->GenerateKeyPair(CKM_RSA_PKCS_KEY_PAIR_GEN, "", pub_attr, 5, priv_attr, 3, &pubh, &privh)); ASSERT_TRUE(session_->GetObject(pubh, pub)); ASSERT_TRUE(session_->GetObject(privh, priv)); } int CreateObject() { CK_OBJECT_CLASS c = CKO_DATA; CK_BBOOL no = CK_FALSE; CK_ATTRIBUTE attr[] = { {CKA_CLASS, &c, sizeof(c)}, {CKA_TOKEN, &no, sizeof(no)} }; int h; session_->CreateObject(attr, 2, &h); return h; } protected: ObjectPoolMock token_pool_; ChapsFactoryMock factory_; StrictMock<TPMUtilityMock> tpm_; HandleGeneratorMock handle_generator_; std::unique_ptr<SessionImpl> session_; }; typedef TestSession TestSession_DeathTest; // Test that SessionImpl asserts as expected when not properly initialized. TEST(DeathTest, InvalidInit) { ObjectPoolMock pool; ChapsFactoryMock factory; TPMUtilityMock tpm; HandleGeneratorMock handle_generator; SessionImpl* session; EXPECT_CALL(factory, CreateObjectPool(_, _, _)).Times(AnyNumber()); EXPECT_DEATH_IF_SUPPORTED( session = new SessionImpl(1, NULL, &tpm, &factory, &handle_generator, false), "Check failed"); EXPECT_DEATH_IF_SUPPORTED( session = new SessionImpl(1, &pool, NULL, &factory, &handle_generator, false), "Check failed"); EXPECT_DEATH_IF_SUPPORTED( session = new SessionImpl(1, &pool, &tpm, NULL, &handle_generator, false), "Check failed"); EXPECT_DEATH_IF_SUPPORTED( session = new SessionImpl(1, &pool, &tpm, &factory, NULL, false), "Check failed"); (void)session; } // Test that SessionImpl asserts as expected when passed invalid arguments. TEST_F(TestSession_DeathTest, InvalidArgs) { OperationType invalid_op = kNumOperationTypes; EXPECT_DEATH_IF_SUPPORTED(session_->IsOperationActive(invalid_op), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->CreateObject(NULL, 0, NULL), "Check failed"); int i; EXPECT_DEATH_IF_SUPPORTED(session_->CreateObject(NULL, 1, &i), "Check failed"); i = CreateObject(); EXPECT_DEATH_IF_SUPPORTED(session_->CopyObject(NULL, 0, i, NULL), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->CopyObject(NULL, 1, i, &i), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->FindObjects(invalid_op, NULL), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->GetObject(1, NULL), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->OperationInit(invalid_op, 0, "", NULL), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->OperationInit(kEncrypt, CKM_AES_CBC, "", NULL), "Check failed"); string s; const Object* o; GenerateSecretKey(CKM_AES_KEY_GEN, 32, &o); ASSERT_EQ(CKR_OK, session_->OperationInit(kEncrypt, CKM_AES_ECB, "", o)); EXPECT_DEATH_IF_SUPPORTED(session_->OperationUpdate(invalid_op, "", &i, &s), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->OperationUpdate(kEncrypt, "", NULL, &s), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->OperationUpdate(kEncrypt, "", &i, NULL), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->OperationFinal(invalid_op, &i, &s), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->OperationFinal(kEncrypt, NULL, &s), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->OperationFinal(kEncrypt, &i, NULL), "Check failed"); EXPECT_DEATH_IF_SUPPORTED( session_->OperationSinglePart(invalid_op, "", &i, &s), "Check failed"); } // Test that SessionImpl asserts when out-of-memory during initialization. TEST(DeathTest, OutOfMemoryInit) { ObjectPoolMock pool; TPMUtilityMock tpm; ChapsFactoryMock factory; HandleGeneratorMock handle_generator; ObjectPool* null_pool = NULL; EXPECT_CALL(factory, CreateObjectPool(_, _, _)) .WillRepeatedly(Return(null_pool)); Session* session; EXPECT_DEATH_IF_SUPPORTED( session = new SessionImpl(1, &pool, &tpm, &factory, &handle_generator, false), "Check failed"); (void)session; } // Test that SessionImpl asserts when out-of-memory during object creation. TEST_F(TestSession_DeathTest, OutOfMemoryObject) { Object* null_object = NULL; EXPECT_CALL(factory_, CreateObject()) .WillRepeatedly(Return(null_object)); int tmp; EXPECT_DEATH_IF_SUPPORTED(session_->CreateObject(NULL, 0, &tmp), "Check failed"); EXPECT_DEATH_IF_SUPPORTED(session_->FindObjectsInit(NULL, 0), "Check failed"); } // Test that default session properties are correctly reported. TEST_F(TestSession, DefaultSetup) { EXPECT_EQ(1, session_->GetSlot()); EXPECT_FALSE(session_->IsReadOnly()); EXPECT_FALSE(session_->IsOperationActive(kEncrypt)); } // Test object management: create / copy / find / destroy. TEST_F(TestSession, Objects) { EXPECT_CALL(token_pool_, Insert(_)).Times(2); EXPECT_CALL(token_pool_, Find(_, _)).Times(1); EXPECT_CALL(token_pool_, Delete(_)).Times(1); CK_OBJECT_CLASS oc = CKO_SECRET_KEY; CK_ATTRIBUTE attr[] = {{CKA_CLASS, &oc, sizeof(oc)}}; int handle = 0; int invalid_handle = -1; // Create a new object. ASSERT_EQ(CKR_OK, session_->CreateObject(attr, 1, &handle)); EXPECT_GT(handle, 0); const Object* o; // Get the new object from the new handle. EXPECT_TRUE(session_->GetObject(handle, &o)); int handle2 = 0; // Copy an object (try invalid and valid handles). EXPECT_EQ(CKR_OBJECT_HANDLE_INVALID, session_->CopyObject(attr, 1, invalid_handle, &handle2)); ASSERT_EQ(CKR_OK, session_->CopyObject(attr, 1, handle, &handle2)); // Ensure handles are unique. EXPECT_TRUE(handle != handle2); EXPECT_TRUE(session_->GetObject(handle2, &o)); EXPECT_FALSE(session_->GetObject(invalid_handle, &o)); vector<int> v; // Find objects with calls out-of-order. EXPECT_EQ(CKR_OPERATION_NOT_INITIALIZED, session_->FindObjects(1, &v)); EXPECT_EQ(CKR_OPERATION_NOT_INITIALIZED, session_->FindObjectsFinal()); // Find the objects we've created (there should be 2). EXPECT_EQ(CKR_OK, session_->FindObjectsInit(attr, 1)); EXPECT_EQ(CKR_OPERATION_ACTIVE, session_->FindObjectsInit(attr, 1)); // Test multi-step finds by only allowing 1 result at a time. EXPECT_EQ(CKR_OK, session_->FindObjects(1, &v)); EXPECT_EQ(1, v.size()); EXPECT_EQ(CKR_OK, session_->FindObjects(1, &v)); EXPECT_EQ(2, v.size()); // We have them all but we'll query again to make sure it behaves properly. EXPECT_EQ(CKR_OK, session_->FindObjects(1, &v)); ASSERT_EQ(2, v.size()); // Check that the handles found are the same ones we know about. EXPECT_TRUE(v[0] == handle || v[1] == handle); EXPECT_TRUE(v[0] == handle2 || v[1] == handle2); EXPECT_EQ(CKR_OK, session_->FindObjectsFinal()); // Destroy an object (try invalid and valid handles). EXPECT_EQ(CKR_OBJECT_HANDLE_INVALID, session_->DestroyObject(invalid_handle)); EXPECT_EQ(CKR_OK, session_->DestroyObject(handle)); // Once destroyed, we should not be able to use the handle. EXPECT_FALSE(session_->GetObject(handle, &o)); } // Test multi-part and single-part cipher operations. TEST_F(TestSession, Cipher) { const Object* key_object = NULL; GenerateSecretKey(CKM_AES_KEY_GEN, 32, &key_object); EXPECT_EQ(CKR_OK, session_->OperationInit(kEncrypt, CKM_AES_CBC_PAD, string(16, 'A'), key_object)); string in(22, 'B'); string out, tmp; int maxlen = 0; // Check buffer-too-small semantics (and for each call following). EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationUpdate(kEncrypt, in, &maxlen, &tmp)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kEncrypt, in, &maxlen, &tmp)); out += tmp; // The first block is ready, check that we've received it. EXPECT_EQ(16, out.length()); maxlen = 0; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationFinal(kEncrypt, &maxlen, &tmp)); EXPECT_EQ(CKR_OK, session_->OperationFinal(kEncrypt, &maxlen, &tmp)); out += tmp; // Check that we've received the final block. EXPECT_EQ(32, out.length()); EXPECT_EQ(CKR_OK, session_->OperationInit(kDecrypt, CKM_AES_CBC_PAD, string(16, 'A'), key_object)); string in2; maxlen = 0; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationSinglePart(kDecrypt, out, &maxlen, &in2)); EXPECT_EQ(CKR_OK, session_->OperationSinglePart(kDecrypt, out, &maxlen, &in2)); EXPECT_EQ(22, in2.length()); // Check that what has been decrypted matches our original plain-text. EXPECT_TRUE(in == in2); } // Test multi-part and single-part digest operations. TEST_F(TestSession, Digest) { string in(30, 'A'); EXPECT_EQ(CKR_OK, session_->OperationInit(kDigest, CKM_SHA_1, "", NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kDigest, in.substr(0, 10), NULL, NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kDigest, in.substr(10, 10), NULL, NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kDigest, in.substr(20, 10), NULL, NULL)); int len = 0; string out; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationFinal(kDigest, &len, &out)); EXPECT_EQ(20, len); EXPECT_EQ(CKR_OK, session_->OperationFinal(kDigest, &len, &out)); EXPECT_EQ(CKR_OK, session_->OperationInit(kDigest, CKM_SHA_1, "", NULL)); string out2; len = 0; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationSinglePart(kDigest, in, &len, &out2)); EXPECT_EQ(CKR_OK, session_->OperationSinglePart(kDigest, in, &len, &out2)); EXPECT_EQ(20, len); // Check that both operations computed the same digest. EXPECT_TRUE(out == out2); } // Test HMAC sign and verify operations. TEST_F(TestSession, HMAC) { const Object* key_object = NULL; GenerateSecretKey(CKM_GENERIC_SECRET_KEY_GEN, 32, &key_object); string in(30, 'A'); EXPECT_EQ(CKR_OK, session_->OperationInit(kSign, CKM_SHA256_HMAC, "", key_object)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kSign, in.substr(0, 10), NULL, NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kSign, in.substr(10, 10), NULL, NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kSign, in.substr(20, 10), NULL, NULL)); int len = 0; string out; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationFinal(kSign, &len, &out)); EXPECT_EQ(CKR_OK, session_->OperationFinal(kSign, &len, &out)); EXPECT_EQ(CKR_OK, session_->OperationInit(kVerify, CKM_SHA256_HMAC, "", key_object)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, in, NULL, NULL)); // A successful verify implies both operations computed the same MAC. EXPECT_EQ(CKR_OK, session_->VerifyFinal(out)); } // Test empty multi-part operation. TEST_F(TestSession, FinalWithNoUpdate) { EXPECT_EQ(CKR_OK, session_->OperationInit(kDigest, CKM_SHA_1, "", NULL)); int len = 20; string out; EXPECT_EQ(CKR_OK, session_->OperationFinal(kDigest, &len, &out)); EXPECT_EQ(20, len); } // Test multi-part and single-part operations inhibit each other. TEST_F(TestSession, UpdateOperationPreventsSinglePart) { string in(30, 'A'); EXPECT_EQ(CKR_OK, session_->OperationInit(kDigest, CKM_SHA_1, "", NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kDigest, in.substr(0, 10), NULL, NULL)); int len = 0; string out; EXPECT_EQ(CKR_OPERATION_ACTIVE, session_->OperationSinglePart(kDigest, in.substr(10, 20), &len, &out)); // The error also terminates the operation. len = 0; EXPECT_EQ(CKR_OPERATION_NOT_INITIALIZED, session_->OperationFinal(kDigest, &len, &out)); } TEST_F(TestSession, SinglePartOperationPreventsUpdate) { string in(30, 'A'); EXPECT_EQ(CKR_OK, session_->OperationInit(kDigest, CKM_SHA_1, "", NULL)); string out; int len = 0; // Perform a single part operation but leave the output to be collected. EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationSinglePart(kDigest, in, &len, &out)); EXPECT_EQ(CKR_OPERATION_ACTIVE, session_->OperationUpdate(kDigest, in.substr(10, 10), NULL, NULL)); // The error also terminates the operation. EXPECT_EQ(CKR_OPERATION_NOT_INITIALIZED, session_->OperationSinglePart(kDigest, in, &len, &out)); } TEST_F(TestSession, SinglePartOperationPreventsFinal) { string in(30, 'A'); EXPECT_EQ(CKR_OK, session_->OperationInit(kDigest, CKM_SHA_1, "", NULL)); string out; int len = 0; // Perform a single part operation but leave the output to be collected. EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationSinglePart(kDigest, in, &len, &out)); len = 0; EXPECT_EQ(CKR_OPERATION_ACTIVE, session_->OperationFinal(kDigest, &len, &out)); // The error also terminates the operation. EXPECT_EQ(CKR_OPERATION_NOT_INITIALIZED, session_->OperationSinglePart(kDigest, in, &len, &out)); } // Test RSA PKCS #1 encryption. TEST_F(TestSession, RSAEncrypt) { const Object* pub = NULL; const Object* priv = NULL; GenerateRSAKeyPair(false, 1024, &pub, &priv); EXPECT_EQ(CKR_OK, session_->OperationInit(kEncrypt, CKM_RSA_PKCS, "", pub)); string in(100, 'A'); int len = 0; string out; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationSinglePart(kEncrypt, in, &len, &out)); EXPECT_EQ(CKR_OK, session_->OperationSinglePart(kEncrypt, in, &len, &out)); EXPECT_EQ(CKR_OK, session_->OperationInit(kDecrypt, CKM_RSA_PKCS, "", priv)); len = 0; string in2 = out; string out2; EXPECT_EQ(CKR_OK, session_->OperationUpdate(kDecrypt, in2, &len, &out2)); EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationFinal(kDecrypt, &len, &out2)); EXPECT_EQ(CKR_OK, session_->OperationFinal(kDecrypt, &len, &out2)); EXPECT_EQ(in.length(), out2.length()); // Check that what has been decrypted matches our original plain-text. EXPECT_TRUE(in == out2); } // Test RSA PKCS #1 sign / verify. TEST_F(TestSession, RSASign) { const Object* pub = NULL; const Object* priv = NULL; GenerateRSAKeyPair(true, 1024, &pub, &priv); // Sign / verify without a built-in hash. EXPECT_EQ(CKR_OK, session_->OperationInit(kSign, CKM_RSA_PKCS, "", priv)); string in(100, 'A'); int len = 0; string sig; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationSinglePart(kSign, in, &len, &sig)); EXPECT_EQ(CKR_OK, session_->OperationSinglePart(kSign, in, &len, &sig)); EXPECT_EQ(CKR_OK, session_->OperationInit(kVerify, CKM_RSA_PKCS, "", pub)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, in, NULL, NULL)); EXPECT_EQ(CKR_OK, session_->VerifyFinal(sig)); // Sign / verify with a built-in SHA-256 hash. EXPECT_EQ(CKR_OK, session_->OperationInit(kSign, CKM_SHA256_RSA_PKCS, "", priv)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kSign, in.substr(0, 50), NULL, NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kSign, in.substr(50, 50), NULL, NULL)); string sig2; len = 0; EXPECT_EQ(CKR_BUFFER_TOO_SMALL, session_->OperationFinal(kSign, &len, &sig2)); EXPECT_EQ(CKR_OK, session_->OperationFinal(kSign, &len, &sig2)); EXPECT_EQ(CKR_OK, session_->OperationInit(kVerify, CKM_SHA256_RSA_PKCS, "", pub)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, in.substr(0, 20), NULL, NULL)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, in.substr(20, 80), NULL, NULL)); EXPECT_EQ(CKR_OK, session_->VerifyFinal(sig2)); } // Test that requests for unsupported mechanisms are handled correctly. TEST_F(TestSession, MechanismInvalid) { const Object* key = NULL; // Use a valid key so that key errors don't mask mechanism errors. GenerateSecretKey(CKM_AES_KEY_GEN, 16, &key); // We don't support IDEA. EXPECT_EQ(CKR_MECHANISM_INVALID, session_->OperationInit(kEncrypt, CKM_IDEA_CBC, "", key)); // We don't support SHA-224. EXPECT_EQ(CKR_MECHANISM_INVALID, session_->OperationInit(kSign, CKM_SHA224_RSA_PKCS, "", key)); // We don't support MD2. EXPECT_EQ(CKR_MECHANISM_INVALID, session_->OperationInit(kDigest, CKM_MD2, "", NULL)); } // Test that operation / mechanism mismatches are handled correctly. TEST_F(TestSession, MechanismMismatch) { const Object* hmac = NULL; GenerateSecretKey(CKM_GENERIC_SECRET_KEY_GEN, 16, &hmac); const Object* aes = NULL; GenerateSecretKey(CKM_AES_KEY_GEN, 16, &aes); // Encrypt with a sign/verify mechanism. EXPECT_EQ(CKR_MECHANISM_INVALID, session_->OperationInit(kEncrypt, CKM_SHA_1_HMAC, "", hmac)); // Sign with an encryption mechanism. EXPECT_EQ(CKR_MECHANISM_INVALID, session_->OperationInit(kSign, CKM_AES_CBC_PAD, "", aes)); // Sign with a digest-only mechanism. EXPECT_EQ(CKR_MECHANISM_INVALID, session_->OperationInit(kSign, CKM_SHA_1, "", hmac)); // Digest with a sign+digest mechanism. EXPECT_EQ(CKR_MECHANISM_INVALID, session_->OperationInit(kDigest, CKM_SHA1_RSA_PKCS, "", NULL)); } // Test that mechanism / key type mismatches are handled correctly. TEST_F(TestSession, KeyTypeMismatch) { const Object* aes = NULL; GenerateSecretKey(CKM_AES_KEY_GEN, 16, &aes); const Object* rsapub = NULL; const Object* rsapriv = NULL; GenerateRSAKeyPair(true, 512, &rsapub, &rsapriv); // DES3 with an AES key. EXPECT_EQ(CKR_KEY_TYPE_INCONSISTENT, session_->OperationInit(kEncrypt, CKM_DES3_CBC, "", aes)); // AES with an RSA key. EXPECT_EQ(CKR_KEY_TYPE_INCONSISTENT, session_->OperationInit(kEncrypt, CKM_AES_CBC, "", rsapriv)); // HMAC with an RSA key. EXPECT_EQ(CKR_KEY_TYPE_INCONSISTENT, session_->OperationInit(kSign, CKM_SHA_1_HMAC, "", rsapriv)); // RSA with an AES key. EXPECT_EQ(CKR_KEY_TYPE_INCONSISTENT, session_->OperationInit(kSign, CKM_SHA1_RSA_PKCS, "", aes)); } // Test that key function permissions are correctly enforced. TEST_F(TestSession, KeyFunctionPermission) { const Object* encpub = NULL; const Object* encpriv = NULL; GenerateRSAKeyPair(false, 512, &encpub, &encpriv); const Object* sigpub = NULL; const Object* sigpriv = NULL; GenerateRSAKeyPair(true, 512, &sigpub, &sigpriv); // Try decrypting with a sign-only key. EXPECT_EQ(CKR_KEY_FUNCTION_NOT_PERMITTED, session_->OperationInit(kDecrypt, CKM_RSA_PKCS, "", sigpriv)); // Try signing with a decrypt-only key. EXPECT_EQ(CKR_KEY_FUNCTION_NOT_PERMITTED, session_->OperationInit(kSign, CKM_RSA_PKCS, "", encpriv)); } // Test that invalid mechanism parameters for ciphers are handled correctly. TEST_F(TestSession, BadIV) { const Object* aes = NULL; GenerateSecretKey(CKM_AES_KEY_GEN, 16, &aes); const Object* des = NULL; GenerateSecretKey(CKM_DES_KEY_GEN, 16, &des); const Object* des3 = NULL; GenerateSecretKey(CKM_DES3_KEY_GEN, 16, &des3); // AES expects 16 bytes and DES/DES3 expects 8 bytes. string bad_iv(7, 0); EXPECT_EQ(CKR_MECHANISM_PARAM_INVALID, session_->OperationInit(kEncrypt, CKM_AES_CBC, bad_iv, aes)); EXPECT_EQ(CKR_MECHANISM_PARAM_INVALID, session_->OperationInit(kEncrypt, CKM_DES_CBC, bad_iv, des)); EXPECT_EQ(CKR_MECHANISM_PARAM_INVALID, session_->OperationInit(kEncrypt, CKM_DES3_CBC, bad_iv, des3)); } // Test that invalid key size ranges are handled correctly. TEST_F(TestSession, BadKeySize) { const Object* key = NULL; GenerateSecretKey(CKM_AES_KEY_GEN, 16, &key); // AES keys can be 16, 24, or 32 bytes in length. const_cast<Object*>(key)->SetAttributeString(CKA_VALUE, string(33, 0)); EXPECT_EQ(CKR_KEY_SIZE_RANGE, session_->OperationInit(kEncrypt, CKM_AES_ECB, "", key)); const Object* pub = NULL; const Object* priv = NULL; GenerateRSAKeyPair(true, 512, &pub, &priv); // RSA keys can have a modulus size no smaller than 512. const_cast<Object*>(priv)->SetAttributeString(CKA_MODULUS, string(32, 0)); EXPECT_EQ(CKR_KEY_SIZE_RANGE, session_->OperationInit(kSign, CKM_RSA_PKCS, "", priv)); } // Test that invalid attributes for key pair generation are handled correctly. TEST_F(TestSession, BadRSAGenerate) { CK_BBOOL no = CK_FALSE; int size = 1024; CK_BYTE pubexp[] = {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; CK_ATTRIBUTE pub_attr[] = { {CKA_TOKEN, &no, sizeof(no)}, {CKA_PUBLIC_EXPONENT, pubexp, 12}, {CKA_MODULUS_BITS, &size, sizeof(size)} }; CK_ATTRIBUTE priv_attr[] = { {CKA_TOKEN, &no, sizeof(no)}, }; int pub, priv; // CKA_PUBLIC_EXPONENT too large. EXPECT_EQ(CKR_FUNCTION_FAILED, session_->GenerateKeyPair(CKM_RSA_PKCS_KEY_PAIR_GEN, "", pub_attr, 3, priv_attr, 1, &pub, &priv)); pub_attr[1].ulValueLen = 3; size = 20000; // CKA_MODULUS_BITS too large. EXPECT_EQ(CKR_KEY_SIZE_RANGE, session_->GenerateKeyPair(CKM_RSA_PKCS_KEY_PAIR_GEN, "", pub_attr, 3, priv_attr, 1, &pub, &priv)); // CKA_MODULUS_BITS missing. EXPECT_EQ(CKR_TEMPLATE_INCOMPLETE, session_->GenerateKeyPair(CKM_RSA_PKCS_KEY_PAIR_GEN, "", pub_attr, 2, priv_attr, 1, &pub, &priv)); } // Test that invalid attributes for key generation are handled correctly. TEST_F(TestSession, BadAESGenerate) { CK_BBOOL no = CK_FALSE; CK_BBOOL yes = CK_TRUE; int size = 33; CK_ATTRIBUTE attr[] = { {CKA_TOKEN, &no, sizeof(no)}, {CKA_ENCRYPT, &yes, sizeof(yes)}, {CKA_DECRYPT, &yes, sizeof(yes)}, {CKA_VALUE_LEN, &size, sizeof(size)} }; int handle = 0; // CKA_VALUE_LEN missing. EXPECT_EQ(CKR_TEMPLATE_INCOMPLETE, session_->GenerateKey(CKM_AES_KEY_GEN, "", attr, 3, &handle)); // CKA_VALUE_LEN out of range. EXPECT_EQ(CKR_KEY_SIZE_RANGE, session_->GenerateKey(CKM_AES_KEY_GEN, "", attr, 4, &handle)); } // Test that signature verification fails as expected for invalid signatures. TEST_F(TestSession, BadSignature) { string input(100, 'A'); string signature(20, 0); const Object* hmac; GenerateSecretKey(CKM_GENERIC_SECRET_KEY_GEN, 32, &hmac); const Object* rsapub, *rsapriv; GenerateRSAKeyPair(true, 1024, &rsapub, &rsapriv); // HMAC with bad signature length. EXPECT_EQ(CKR_OK, session_->OperationInit(kVerify, CKM_SHA256_HMAC, "", hmac)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, input, NULL, NULL)); EXPECT_EQ(CKR_SIGNATURE_LEN_RANGE, session_->VerifyFinal(signature)); // HMAC with bad signature. signature.resize(32); EXPECT_EQ(CKR_OK, session_->OperationInit(kVerify, CKM_SHA256_HMAC, "", hmac)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, input, NULL, NULL)); EXPECT_EQ(CKR_SIGNATURE_INVALID, session_->VerifyFinal(signature)); // RSA with bad signature length. EXPECT_EQ(CKR_OK, session_->OperationInit(kVerify, CKM_RSA_PKCS, "", rsapub)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, input, NULL, NULL)); EXPECT_EQ(CKR_SIGNATURE_LEN_RANGE, session_->VerifyFinal(signature)); // RSA with bad signature. signature.resize(128, 1); EXPECT_EQ(CKR_OK, session_->OperationInit(kVerify, CKM_RSA_PKCS, "", rsapub)); EXPECT_EQ(CKR_OK, session_->OperationUpdate(kVerify, input, NULL, NULL)); EXPECT_EQ(CKR_SIGNATURE_INVALID, session_->VerifyFinal(signature)); } TEST_F(TestSession, Flush) { ObjectMock token_object; EXPECT_CALL(token_object, IsTokenObject()).WillRepeatedly(Return(true)); ObjectMock session_object; EXPECT_CALL(session_object, IsTokenObject()).WillRepeatedly(Return(false)); EXPECT_CALL(token_pool_, Flush(_)) .WillOnce(Return(false)) .WillRepeatedly(Return(true)); EXPECT_FALSE(session_->FlushModifiableObject(&token_object)); EXPECT_TRUE(session_->FlushModifiableObject(&token_object)); EXPECT_TRUE(session_->FlushModifiableObject(&session_object)); } TEST_F(TestSession, GenerateRSAWithTPM) { EXPECT_CALL(tpm_, GenerateKey(_, _, _, _, _, _)).WillOnce(Return(true)); EXPECT_CALL(tpm_, GetPublicKey(_, _, _)).WillRepeatedly(Return(true)); CK_BBOOL no = CK_FALSE; CK_BBOOL yes = CK_TRUE; CK_BYTE pubexp[] = {1, 0, 1}; int size = 2048; CK_ATTRIBUTE pub_attr[] = { {CKA_TOKEN, &yes, sizeof(yes)}, {CKA_ENCRYPT, &no, sizeof(no)}, {CKA_VERIFY, &yes, sizeof(yes)}, {CKA_PUBLIC_EXPONENT, pubexp, 3}, {CKA_MODULUS_BITS, &size, sizeof(size)} }; CK_ATTRIBUTE priv_attr[] = { {CKA_TOKEN, &yes, sizeof(yes)}, {CKA_DECRYPT, &no, sizeof(no)}, {CKA_SIGN, &yes, sizeof(yes)} }; int pubh = 0, privh = 0; ASSERT_EQ(CKR_OK, session_->GenerateKeyPair(CKM_RSA_PKCS_KEY_PAIR_GEN, "", pub_attr, 5, priv_attr, 3, &pubh, &privh)); // There are a few sensitive attributes that MUST not exist. const Object* object = NULL; ASSERT_TRUE(session_->GetObject(privh, &object)); EXPECT_FALSE(object->IsAttributePresent(CKA_PRIVATE_EXPONENT)); EXPECT_FALSE(object->IsAttributePresent(CKA_PRIME_1)); EXPECT_FALSE(object->IsAttributePresent(CKA_PRIME_2)); EXPECT_FALSE(object->IsAttributePresent(CKA_EXPONENT_1)); EXPECT_FALSE(object->IsAttributePresent(CKA_EXPONENT_2)); EXPECT_FALSE(object->IsAttributePresent(CKA_COEFFICIENT)); } TEST_F(TestSession, GenerateRSAWithTPMInconsistentToken) { EXPECT_CALL(tpm_, GenerateKey(_, _, _, _, _, _)).WillOnce(Return(true)); EXPECT_CALL(tpm_, GetPublicKey(_, _, _)).WillRepeatedly(Return(true)); CK_BBOOL no = CK_FALSE; CK_BBOOL yes = CK_TRUE; CK_BYTE pubexp[] = {1, 0, 1}; int size = 2048; CK_ATTRIBUTE pub_attr[] = { {CKA_TOKEN, &no, sizeof(no)}, {CKA_ENCRYPT, &no, sizeof(no)}, {CKA_VERIFY, &yes, sizeof(yes)}, {CKA_PUBLIC_EXPONENT, pubexp, 3}, {CKA_MODULUS_BITS, &size, sizeof(size)} }; CK_ATTRIBUTE priv_attr[] = { {CKA_TOKEN, &yes, sizeof(yes)}, {CKA_DECRYPT, &no, sizeof(no)}, {CKA_SIGN, &yes, sizeof(yes)} }; // Attempt to generate a private key on the token, but public key not on the // token. int pubh = 0, privh = 0; ASSERT_EQ(CKR_OK, session_->GenerateKeyPair(CKM_RSA_PKCS_KEY_PAIR_GEN, "", pub_attr, 5, priv_attr, 3, &pubh, &privh)); const Object* public_object = NULL; const Object* private_object = NULL; ASSERT_TRUE(session_->GetObject(pubh, &public_object)); ASSERT_TRUE(session_->GetObject(privh, &private_object)); EXPECT_FALSE(public_object->IsTokenObject()); EXPECT_TRUE(private_object->IsTokenObject()); // Destroy the objects. EXPECT_EQ(CKR_OK, session_->DestroyObject(pubh)); EXPECT_EQ(CKR_OK, session_->DestroyObject(privh)); } TEST_F(TestSession, GenerateRSAWithNoTPM) { EXPECT_CALL(tpm_, IsTPMAvailable()).WillRepeatedly(Return(false)); CK_BBOOL no = CK_FALSE; CK_BBOOL yes = CK_TRUE; CK_BYTE pubexp[] = {1, 0, 1}; int size = 1024; CK_ATTRIBUTE pub_attr[] = { {CKA_TOKEN, &yes, sizeof(yes)}, {CKA_ENCRYPT, &no, sizeof(no)}, {CKA_VERIFY, &yes, sizeof(yes)}, {CKA_PUBLIC_EXPONENT, pubexp, 3}, {CKA_MODULUS_BITS, &size, sizeof(size)} }; CK_ATTRIBUTE priv_attr[] = { {CKA_TOKEN, &yes, sizeof(yes)}, {CKA_DECRYPT, &no, sizeof(no)}, {CKA_SIGN, &yes, sizeof(yes)} }; int pubh = 0, privh = 0; ASSERT_EQ(CKR_OK, session_->GenerateKeyPair(CKM_RSA_PKCS_KEY_PAIR_GEN, "", pub_attr, 5, priv_attr, 3, &pubh, &privh)); // For a software key, the sensitive attributes should exist. const Object* object = NULL; ASSERT_TRUE(session_->GetObject(privh, &object)); EXPECT_TRUE(object->IsAttributePresent(CKA_PRIVATE_EXPONENT)); EXPECT_TRUE(object->IsAttributePresent(CKA_PRIME_1)); EXPECT_TRUE(object->IsAttributePresent(CKA_PRIME_2)); EXPECT_TRUE(object->IsAttributePresent(CKA_EXPONENT_1)); EXPECT_TRUE(object->IsAttributePresent(CKA_EXPONENT_2)); EXPECT_TRUE(object->IsAttributePresent(CKA_COEFFICIENT)); } TEST_F(TestSession, ImportRSAWithTPM) { EXPECT_CALL(tpm_, WrapKey(_, _, _, _, _, _, _)).WillOnce(Return(true)); RSA* rsa = RSA_generate_key(2048, 0x10001, NULL, NULL); CK_OBJECT_CLASS priv_class = CKO_PRIVATE_KEY; CK_KEY_TYPE key_type = CKK_RSA; CK_BBOOL false_value = CK_FALSE; CK_BBOOL true_value = CK_TRUE; string id = "test_id"; string label = "test_label"; string n = bn2bin(rsa->n); string e = bn2bin(rsa->e); string d = bn2bin(rsa->d); string p = bn2bin(rsa->p); string q = bn2bin(rsa->q); string dmp1 = bn2bin(rsa->dmp1); string dmq1 = bn2bin(rsa->dmq1); string iqmp = bn2bin(rsa->iqmp); CK_ATTRIBUTE private_attributes[] = { {CKA_CLASS, &priv_class, sizeof(priv_class) }, {CKA_KEY_TYPE, &key_type, sizeof(key_type) }, {CKA_DECRYPT, &true_value, sizeof(true_value) }, {CKA_SIGN, &true_value, sizeof(true_value) }, {CKA_UNWRAP, &false_value, sizeof(false_value) }, {CKA_SENSITIVE, &true_value, sizeof(true_value) }, {CKA_TOKEN, &true_value, sizeof(true_value) }, {CKA_PRIVATE, &true_value, sizeof(true_value) }, {CKA_ID, string_as_array(&id), id.length() }, {CKA_LABEL, string_as_array(&label), label.length()}, {CKA_MODULUS, string_as_array(&n), n.length() }, {CKA_PUBLIC_EXPONENT, string_as_array(&e), e.length() }, {CKA_PRIVATE_EXPONENT, string_as_array(&d), d.length() }, {CKA_PRIME_1, string_as_array(&p), p.length() }, {CKA_PRIME_2, string_as_array(&q), q.length() }, {CKA_EXPONENT_1, string_as_array(&dmp1), dmp1.length() }, {CKA_EXPONENT_2, string_as_array(&dmq1), dmq1.length() }, {CKA_COEFFICIENT, string_as_array(&iqmp), iqmp.length() }, }; int handle = 0; ASSERT_EQ(CKR_OK, session_->CreateObject(private_attributes, arraysize(private_attributes), &handle)); // There are a few sensitive attributes that MUST be removed. const Object* object = NULL; ASSERT_TRUE(session_->GetObject(handle, &object)); EXPECT_FALSE(object->IsAttributePresent(CKA_PRIVATE_EXPONENT)); EXPECT_FALSE(object->IsAttributePresent(CKA_PRIME_1)); EXPECT_FALSE(object->IsAttributePresent(CKA_PRIME_2)); EXPECT_FALSE(object->IsAttributePresent(CKA_EXPONENT_1)); EXPECT_FALSE(object->IsAttributePresent(CKA_EXPONENT_2)); EXPECT_FALSE(object->IsAttributePresent(CKA_COEFFICIENT)); RSA_free(rsa); } TEST_F(TestSession, ImportRSAWithNoTPM) { EXPECT_CALL(tpm_, IsTPMAvailable()).WillRepeatedly(Return(false)); RSA* rsa = RSA_generate_key(2048, 0x10001, NULL, NULL); CK_OBJECT_CLASS priv_class = CKO_PRIVATE_KEY; CK_KEY_TYPE key_type = CKK_RSA; CK_BBOOL false_value = CK_FALSE; CK_BBOOL true_value = CK_TRUE; string id = "test_id"; string label = "test_label"; string n = bn2bin(rsa->n); string e = bn2bin(rsa->e); string d = bn2bin(rsa->d); string p = bn2bin(rsa->p); string q = bn2bin(rsa->q); string dmp1 = bn2bin(rsa->dmp1); string dmq1 = bn2bin(rsa->dmq1); string iqmp = bn2bin(rsa->iqmp); CK_ATTRIBUTE private_attributes[] = { {CKA_CLASS, &priv_class, sizeof(priv_class) }, {CKA_KEY_TYPE, &key_type, sizeof(key_type) }, {CKA_DECRYPT, &true_value, sizeof(true_value) }, {CKA_SIGN, &true_value, sizeof(true_value) }, {CKA_UNWRAP, &false_value, sizeof(false_value) }, {CKA_SENSITIVE, &true_value, sizeof(true_value) }, {CKA_TOKEN, &true_value, sizeof(true_value) }, {CKA_PRIVATE, &true_value, sizeof(true_value) }, {CKA_ID, string_as_array(&id), id.length() }, {CKA_LABEL, string_as_array(&label), label.length()}, {CKA_MODULUS, string_as_array(&n), n.length() }, {CKA_PUBLIC_EXPONENT, string_as_array(&e), e.length() }, {CKA_PRIVATE_EXPONENT, string_as_array(&d), d.length() }, {CKA_PRIME_1, string_as_array(&p), p.length() }, {CKA_PRIME_2, string_as_array(&q), q.length() }, {CKA_EXPONENT_1, string_as_array(&dmp1), dmp1.length() }, {CKA_EXPONENT_2, string_as_array(&dmq1), dmq1.length() }, {CKA_COEFFICIENT, string_as_array(&iqmp), iqmp.length() }, }; int handle = 0; ASSERT_EQ(CKR_OK, session_->CreateObject(private_attributes, arraysize(private_attributes), &handle)); // For a software key, the sensitive attributes should still exist. const Object* object = NULL; ASSERT_TRUE(session_->GetObject(handle, &object)); EXPECT_TRUE(object->IsAttributePresent(CKA_PRIVATE_EXPONENT)); EXPECT_TRUE(object->IsAttributePresent(CKA_PRIME_1)); EXPECT_TRUE(object->IsAttributePresent(CKA_PRIME_2)); EXPECT_TRUE(object->IsAttributePresent(CKA_EXPONENT_1)); EXPECT_TRUE(object->IsAttributePresent(CKA_EXPONENT_2)); EXPECT_TRUE(object->IsAttributePresent(CKA_COEFFICIENT)); RSA_free(rsa); } } // namespace chaps int main(int argc, char** argv) { ::testing::InitGoogleMock(&argc, argv); OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); return RUN_ALL_TESTS(); }
2335982d7db04aa6f4985e8a93f22541a7405789
7a3f61d60d9af4b4ff0a6f794fbe61d6ba29021d
/testTCPClient/testTCPClient/main.cpp
4c64ec085f4a5379a65ef64d7de4af0bbd0145ca
[]
no_license
clustc/ByteBuffer
80da10184d76d2c154ecbf60f7e500c17d82252e
05ae51cb92da70be59ef4d2abe270b6199d38c97
refs/heads/master
2021-05-11T23:47:11.039074
2018-01-15T08:49:05
2018-01-15T08:49:05
117,520,150
0
0
null
null
null
null
UTF-8
C++
false
false
150
cpp
main.cpp
#include "stdafx.h" #include "TCPClient.h" int _tmain(int argc, _TCHAR* argv[]) { TCPClient client; client.run(); system("pause"); return 0; }
71553c6d983fba28608e1aa66970612b1ee37d8a
188fb8ded33ad7a2f52f69975006bb38917437ef
/Fluid/processor5/0.09/p
df2f3025659d2207710ddcc51640e9e37a89ee25
[]
no_license
abarcaortega/Tuto_2
34a4721f14725c20471ff2dc8d22b52638b8a2b3
4a84c22efbb9cd2eaeda92883343b6910e0941e2
refs/heads/master
2020-08-05T16:11:57.674940
2019-10-04T09:56:09
2019-10-04T09:56:09
212,573,883
0
0
null
null
null
null
UTF-8
C++
false
false
6,297
p
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: dev | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.09"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 465 ( -65.2402 -56.9553 -48.6565 -40.6107 -33.2893 -26.8872 -21.4516 -16.9463 -13.2819 -10.343 -8.00788 -6.16161 -4.70254 -3.54493 -2.61874 -1.86805 -1.24895 -0.727395 -0.277595 0.119697 -65.7778 -57.402 -49.0139 -40.8843 -33.5018 -27.053 -21.5825 -17.0511 -13.3671 -10.4128 -8.06545 -6.20909 -4.74158 -3.57684 -2.64462 -1.88887 -1.26552 -0.740289 -0.286624 0.120862 -66.7862 -58.1936 -49.6064 -41.2924 -33.7676 -27.2235 -21.6926 -17.1249 -13.42 -10.4539 -8.09953 -6.23843 -4.76711 -3.59891 -2.66338 -1.90448 -1.27819 -0.75016 -0.293466 0.120046 -68.3819 -59.4121 -50.4885 -41.8759 -34.125 -27.4358 -21.8176 -17.2014 -13.4717 -10.4938 -8.1338 -6.26945 -4.79534 -3.6241 -2.68523 -1.92283 -1.2931 -0.761816 -0.302018 0.116026 -70.7297 -61.1736 -51.7315 -42.6724 -34.5948 -27.6998 -21.961 -17.2802 -13.5194 -10.5285 -8.16378 -6.29759 -4.82195 -3.64856 -2.70684 -1.94117 -1.30811 -0.773673 -0.311133 0.110268 -74.0582 -63.6281 -53.419 -43.7227 -35.2012 -28.0306 -22.133 -17.3689 -13.5693 -10.563 -8.19354 -6.32612 -4.84952 -3.6743 -2.7298 -1.96078 -1.32421 -0.786546 -0.321422 0.102604 -78.6144 -66.9234 -55.6206 -45.0554 -35.9627 -28.4399 -22.3416 -17.4735 -13.626 -10.6009 -8.22562 -6.35674 -4.87909 -3.70188 -2.75438 -1.98173 -1.34145 -0.800459 -0.332868 0.09316 -84.5607 -71.1303 -58.3451 -46.6728 -36.8836 -28.932 -22.5914 -17.5988 -13.694 -10.646 -8.26297 -6.39156 -4.9121 -3.73225 -2.78117 -2.00443 -1.36011 -0.815625 -0.345603 0.0819032 -91.8495 -76.1511 -61.4897 -48.5458 -37.9451 -29.4977 -22.8804 -17.7465 -13.7764 -10.7013 -8.30809 -6.43238 -4.94971 -3.76611 -2.81058 -2.02912 -1.38033 -0.832147 -0.359686 0.0688424 -100.106 -81.6853 -64.8785 -50.5849 -39.093 -30.1098 -23.1976 -17.9141 -13.8741 -10.7689 -8.36276 -6.48048 -4.99271 -3.80389 -2.84283 -2.05589 -1.40217 -0.850065 -0.375131 0.0540085 -108.619 -87.2458 -68.2975 -52.615 -40.23 -30.7202 -23.5218 -18.0938 -13.9853 -10.8487 -8.42752 -6.53626 -5.04128 -3.84558 -2.8778 -2.08462 -1.42552 -0.869309 -0.391884 0.0374775 -116.409 -92.2538 -71.3606 -54.401 -41.2271 -31.2641 -23.8228 -18.2723 -14.1043 -10.9384 -8.50111 -6.59885 -5.09469 -3.89057 -2.91502 -2.11494 -1.45014 -0.889705 -0.409825 0.0193669 -122.351 -95.9722 -73.5817 -55.6766 -41.9427 -31.6688 -24.0647 -18.4319 -14.2219 -11.0326 -8.58001 -6.66574 -5.15108 -3.93745 -2.95342 -2.14609 -1.47549 -0.910905 -0.428724 -0.000145583 -125.257 -97.6738 -74.5332 -56.2037 -42.2479 -31.8656 -24.2102 -18.5514 -14.3253 -11.1232 -8.65873 -6.73312 -5.20773 -3.98428 -2.99162 -2.17707 -1.50084 -0.932388 -0.448195 -0.0207324 -124.46 -96.9139 -73.9453 -55.8246 -42.0502 -31.7983 -24.2237 -18.6075 -14.399 -11.1999 -8.73069 -6.79686 -5.26219 -4.0297 -3.02895 -2.20764 -1.52623 -0.954295 -0.468403 -0.0424372 -149.076 -119.799 -93.568 -71.732 -54.4763 -41.2991 -31.4249 -24.0707 -18.5732 -14.4227 -11.2478 -8.78519 -6.84949 -5.3093 -4.07019 -3.06303 -2.23625 -1.55066 -0.976063 -0.489088 -0.0652169 -137.756 -111.317 -87.6661 -67.8915 -52.1283 -39.9472 -30.6934 -23.7032 -18.4082 -14.3648 -11.2432 -8.80496 -6.87847 -5.33998 -4.09917 -3.08912 -2.25947 -1.57171 -0.996029 -0.509214 -0.08848 -79.8219 -62.7879 -48.9654 -38.0692 -29.6203 -23.1119 -18.0953 -14.2079 -11.1718 -8.77895 -6.87579 -5.34861 -4.11278 -3.10462 -2.2756 -1.58831 -1.01355 -0.528432 -0.111979 -45.2527 -35.7779 -28.2403 -22.2962 -17.6204 -13.9354 -11.0181 -8.6946 -6.83168 -5.3278 -4.10554 -3.10549 -2.28172 -1.59835 -1.02716 -0.545768 -0.13509 -33.1976 -26.6035 -21.2695 -16.9806 -13.5382 -10.772 -8.54257 -6.73831 -5.27133 -4.07266 -3.08817 -2.2752 -1.59998 -1.03558 -0.560408 -0.157324 -20.0548 -16.1826 -13.0147 -10.4283 -8.31657 -6.58966 -5.17397 -4.00985 -3.04924 -2.25344 -1.59126 -1.03744 -0.57143 -0.178114 -12.3697 -9.98667 -8.0138 -6.382 -5.03192 -3.91368 -2.98583 -2.21413 -1.5704 -1.03142 -0.577942 -0.196913 -9.45147 -7.63492 -6.11402 -4.84304 -3.78181 -2.89571 -2.15534 -1.53583 -1.01631 -0.579098 -0.213196 -5.7868 -4.60689 -3.61305 -2.77747 -2.07565 -1.48631 -0.991106 -0.574147 -0.22649 -4.32474 -3.40751 -2.63056 -1.97428 -1.42099 -0.955032 -0.562478 -0.236389 -2.45539 -1.85106 -1.33945 -0.90761 -0.543652 -0.242579 -1.70655 -1.2418 -0.84869 -0.517432 -0.244849 -0.778478 -0.483804 -0.243107 -0.442982 -0.237381 -0.227816 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value uniform 0; } flap { type zeroGradient; } upperWall { type zeroGradient; } lowerWall { type zeroGradient; } frontAndBack { type empty; } procBoundary5to2 { type processor; value nonuniform List<scalar> 34 ( -122.144 -99.9053 -99.9053 -71.0065 -56.9564 -56.9564 -41.2532 -41.2532 -30.4341 -24.7632 -24.7632 -18.6814 -15.2405 -15.2405 -11.614 -11.614 -8.83084 -7.18369 -7.18369 -5.40358 -5.40358 -3.99942 -3.16651 -3.16651 -2.25322 -2.25322 -1.54194 -1.12862 -1.12862 -0.697527 -0.697527 -0.395406 -0.395406 -0.214677 ) ; } procBoundary5to4 { type processor; value nonuniform List<scalar> 18 ( -73.3611 -73.9984 -75.2407 -77.2407 -80.2166 -84.4859 -90.4118 -98.2609 -108.011 -119.211 -131.005 -142.227 -151.058 -155.649 -155.041 -155.041 -178.615 -164.71 ) ; } } // ************************************************************************* //
59342384bc28283fd01c0a874f0f61e0b904489d
c37c450c8f83d311ade0641a94910f6f09e6cded
/ch_11_more_classes_OOP/8_HTML_tables/HTMLTable.h
676baf4aaf6d6eefa1930402681d2307ed8f88a3
[]
no_license
JackCode/Early_Objects_Practice
60d62843cff5c56fc809d540f6ba2e4a079224f9
617bf59663329cc6aaca039dace66ca561bb7013
refs/heads/master
2022-11-22T17:55:52.528440
2022-11-18T02:20:12
2022-11-18T02:20:12
255,453,521
0
0
null
null
null
null
UTF-8
C++
false
false
751
h
HTMLTable.h
#ifndef HTML_TABLE_H #define HTML_TABLE_H #include <string> #include <vector> #include <iostream> using namespace std; class HTMLTable { public: struct Student { string studentName; int studentScore; }; HTMLTable(){}; HTMLTable(const vector<Student> &students) { this->classroom = students; } void set_headers(const vector<string> &headers) { this->headers = headers; } void add_row(const Student &row) { this->classroom.push_back(row); } friend ostream & operator<< (ostream &out, HTMLTable htmltable); private: vector<Student> classroom; // HTML Components vector<string> headers; void writeRow(ostream &out, string tag, vector<string> row); void writeRow(ostream &out, string tag, Student row); }; #endif
af7db47443c0e2acb77349fc2b5f4f388cee6526
c49eefe7b62109cc0afae883ddcff51dfc79c34e
/src/Dusk/Graphics/RenderContext.hpp
1e342d3f07dcabd72896830f4c3ce3f6f0a7ba68
[]
no_license
WhoBrokeTheBuild/Dusk-mk4
6e34cb988695f246a35a2e1ecccbb56463d59598
74dbb31dd8e398401c33351f66dc959092d7a0fe
refs/heads/master
2021-01-19T23:03:24.941271
2016-09-15T14:53:15
2016-09-15T14:53:15
88,917,544
0
0
null
null
null
null
UTF-8
C++
false
false
793
hpp
RenderContext.hpp
#ifndef DUSK_RENDER_CONTEXT_HPP #define DUSK_RENDER_CONTEXT_HPP #include <Dusk/Graphics/Texture.hpp> #include <Dusk/Graphics/Window.hpp> #include <Dusk/Types.hpp> #include <SFML/Graphics.hpp> namespace dusk { /// The object used to draw to the screen buffer /** The context that contains methods for drawing primitives and clearing the screen. */ class RenderContext { friend class Window; public: RenderContext() = delete; RenderContext(const RenderContext&) = delete; virtual ~RenderContext() = default; void Clear(); void Display(); void Draw(Texture* pTexture, Vector2f position); private: RenderContext(sf::RenderWindow* pWindow); sf::RenderWindow* mp_Window; }; // class RenderContext } // namespace dusk #endif // DUSK_RENDER_CONTEXT_HPP
f48f003a04e1f3e2536fe14340518cbf8cb3ebfb
dc4a282b7e604cb288375e7e2876ef36b6721aa8
/swexpertacademy/8278/8278.cpp
ced58ced268a6b3f93b8116b605dc931aae5cf39
[]
no_license
yjbong/problem-solving
89be67ba24ad7495d82dcb0788dd7db1b849996a
c775271098daa05fcac269fd15de502e60592d49
refs/heads/master
2023-04-02T18:47:22.920512
2023-03-21T17:28:02
2023-03-21T17:28:02
70,111,700
0
0
null
null
null
null
UHC
C++
false
false
1,655
cpp
8278.cpp
#include <cstdio> #define MAX_M 1000 typedef long long ll; int T; // 테스트 케이스 수 ll N, M; ll check[MAX_M][MAX_M]; // check[x][y] = 직전 두 값(Si-1, Si-2)을 M으로 나눈 나머지가 각각 x, y가 될 때의 i값 int main() { scanf("%d",&T); for(int z=1; z<=T; z++){ scanf("%lld %lld",&N,&M); printf("#%d ", z); if(M==1) { printf("0\n"); continue; } else if(N<=1){ printf("%lld\n", N); continue; } // check 초기화 for(int i=0; i<M; i++) for(int j=0; j<M; j++) check[i][j]=-1; ll bfr2; // Si-2를 M으로 나눈 나머지 ll bfr1; // Si-1을 M으로 나눈 나머지 // 주기 확인 ll start; // 주기가 시작하는 i ll length; // 주기의 길이 bfr2=0; bfr1=1; for(ll i=2; ; i++){ if(check[bfr1][bfr2]>=0) { //printf("S%lld and S%lld are same!\n", check[bfr1][bfr2], i); start=check[bfr1][bfr2]; length=i-start; break; } check[bfr1][bfr2]=i; ll now=(bfr1*bfr1*bfr1+bfr2*bfr2*bfr2)%M; bfr2=bfr1; bfr1=now; } // 주기성을 이용해서 N값을 축소 if(N>=start){ N%=length; while(N<start) N+=length; } // 수열의 N번째 수 출력 bfr2=0; bfr1=1; for(ll i=2; i<=N; i++){ ll now=(bfr1*bfr1*bfr1+bfr2*bfr2*bfr2)%M; if(i==N) printf("%lld\n", now); bfr2=bfr1; bfr1=now; } } return 0; }
851b5a71419a9d0e6323c7fc126303a6d0634cea
c40fff1a7432e08b8a8c4f94649cb0f39cdd4af2
/CSGPathTracer/Math/Geometry/intersection.h
6ea2a4b6e99ddffc01abb100584749f78b06af09
[ "MIT" ]
permissive
TomaszRewak/CSGPathTracer
ed0db6430af30b5a64fd00a2cd23514893a106da
4d388290cc3b90ccc1b8534e44ab0252f9b61b7d
refs/heads/master
2020-03-25T11:44:13.766002
2019-02-22T12:28:25
2019-02-22T12:28:25
143,746,171
0
1
null
2019-02-22T12:28:26
2018-08-06T15:14:10
C++
UTF-8
C++
false
false
516
h
intersection.h
#pragma once #include "point.h" namespace Math { struct Intersection { Math::Point position; Math::Vector normalVector; float distance; __device__ __host__ Intersection() : distance(INFINITY) { } __device__ __host__ explicit Intersection(float maxDistance) : distance(maxDistance) { } __device__ __host__ Intersection(const Math::Point& position, const Math::Vector& normalVector, float distance) : position(position), normalVector(normalVector), distance(distance) { } }; }
44ec259e2ad8ab846573fc4db487b287e641cbb2
2431af25c7e0ada19187b499d20d96178f1748a1
/FlightNodeTracker.h
e11262b4859f17e0bb19ae00ba87d31c0f6a28b1
[]
no_license
cswrigh2/Flight-Booking-System
babfcfefea2ff4aac0d8f3f55eba562f87566bd5
3f8538b7a543a9490b7b6ebc45111a776885c8bc
refs/heads/master
2020-07-12T05:39:18.960826
2014-03-29T23:11:31
2014-03-29T23:11:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
194
h
FlightNodeTracker.h
#ifndef FlightNodeTracker_h #define FlightNodeTracker_h #include "Common.h" #include "FlightNode.h" class FlightNodeTracker { public: FlightNode *current; FlightNodeTracker *next; }; #endif
0e51593c3784fa39dcb02974bf8c3f6e56df4dc8
8cad315164aa5010120320c5ac24cb1aa0772fb1
/cpp-module-05/ex01/Form.hpp
12cc85ad396bbff394869cdcf967c631cfea9d13
[]
no_license
thefullarcticfox/cpp_modules
50e804458a6eb605d7fed8e65f4d9d0c57c430f7
6c1a11c59807a899dc733495db86b498c286be89
refs/heads/master
2023-06-15T08:23:54.639049
2021-07-12T13:51:32
2021-07-12T13:51:32
346,848,151
0
0
null
null
null
null
UTF-8
C++
false
false
1,633
hpp
Form.hpp
#ifndef FORM_HPP # define FORM_HPP # include <iostream> # include <string> # include <exception> class Form; # include "Bureaucrat.hpp" class Form { private: const std::string name; bool _issigned; const int signgrade; const int execgrade; Form(); public: Form(const std::string& name, int signgrade, const int execgrade); virtual ~Form(); Form(const Form& other); Form& operator=(const Form& other); const std::string& getName(void) const; int getSignGrade(void) const; int getExecGrade(void) const; bool isSigned(void) const; void beSigned(const Bureaucrat& bur); class GradeTooHighException : public std::exception { public: GradeTooHighException(); virtual ~GradeTooHighException() throw(); GradeTooHighException(const GradeTooHighException& other); GradeTooHighException& operator=(const GradeTooHighException& other); virtual const char* what() const throw(); }; class GradeTooLowException : public std::exception { public: GradeTooLowException(); virtual ~GradeTooLowException() throw(); GradeTooLowException(const GradeTooLowException& other); GradeTooLowException& operator=(const GradeTooLowException& other); virtual const char* what() const throw(); }; class AlreadySignedException : public std::exception { public: AlreadySignedException(); virtual ~AlreadySignedException() throw(); AlreadySignedException(const AlreadySignedException& other); AlreadySignedException& operator=(const AlreadySignedException& other); virtual const char* what() const throw(); }; }; std::ostream& operator<<(std::ostream& os, const Form& bur); #endif
713f4ab3bf623b9b2d868751b673c39f9818c372
67872bb1d77c766445314177a31c2e8862034def
/VentMonFirmware/networking.cpp
a90d06ea67b4b85a8be18143f9298f2ad7043f1a
[ "MIT", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bencoombs/ventmon-ventilator-inline-test-monitor
f0a274b2fca3b269eeeff3eaf50c1e91f177f8c9
9a0d899b580f29ccfd6593ebbcdeb846d4091f3f
refs/heads/master
2022-11-19T04:34:03.767060
2020-07-19T01:59:42
2020-07-19T01:59:42
279,210,400
1
0
MIT
2020-07-13T04:30:39
2020-07-13T04:30:38
null
UTF-8
C++
false
false
5,943
cpp
networking.cpp
#include <PIRDS.h> #include <Ethernet.h> #include <WiFi.h> //#include <WiFiUdp.h> #include <EthernetUdp.h> #include <Dns.h> #include "display.h" // Set true to use wifi, false to use ethernet. //bool using_wifi = false; // NETWORKING #define PARAM_HOST "ventmon.coslabs.com" #define PARAM_PORT 6111 // Can these 2 variables be combined? #define LOCAL_PORT 6111 byte mac[6]; // MAC address char macs[18]; // Formatted MAC address char *log_host = strdup(PARAM_HOST); uint16_t log_port = PARAM_PORT; IPAddress log_host_ip_addr; // Ethernet EthernetUDP udp_client; bool ethernet_connected = false; // WIFI const char* ssid = "networkSSID"; const char* password = "networkPASS"; //WiFiUDP wifi_udp; void get_mac_addr() { WiFi.macAddress(mac); // Get MAC address of wifi chip // Format MAC address snprintf(macs, sizeof macs, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); Serial.print(F("MAC: ")); Serial.print(macs); Serial.println(); } void udp_init(bool using_wifi){ Serial.println("Starting UDP..."); // if (using_wifi){ // wifi_udp.begin(LOCAL_PORT); // Currently not transmitting to the Data Lake via Wifi. // } // else { udp_client.begin(LOCAL_PORT); DNSClient dns_client; dns_client.begin(Ethernet.dnsServerIP()); Serial.print("Serial: "); Serial.println(Ethernet.dnsServerIP()); if (dns_client.getHostByName(log_host, log_host_ip_addr) == 1) { Serial.print("DNS host is "); Serial.println(log_host_ip_addr); } else { Serial.print("DNS host failed to resolve."); } //} } void ethernet_init() { Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet get_mac_addr(); display_ethernet_starting(); ethernet_connected = false; delay(2000); Serial.print(F("Connecting to to Ethernet, hardware status: ")); Serial.println(Ethernet.hardwareStatus()); // Check the Ethernet hardware is connected. if (Ethernet.hardwareStatus() == EthernetNoHardware) { Serial.println(F("WARNING! Ethernet shield was not found!")); // Why is this triggering? } // Check the Ethernet cable is connected if (Ethernet.linkStatus() == LinkOFF) { Serial.println(F("WARNING! Ethernet cable is not connected!")); } else { // Start the Ethernet connection if (Ethernet.begin(mac) == 0) { // Ethernet failed to connect. Serial.print(F("WARNING! Ethernet failed to connect!")); } else { // Ethernet connected successfully. ethernet_connected = true; Serial.print(F("Ethernet connected!\nLocal IP: ")); Serial.println(Ethernet.localIP()); } } // OLED Display display_ethernet_connected(ethernet_connected); // Give time for user to view display and also let ethernet // initialize (if any is connected) delay(2000); if (!ethernet_connected) return; udp_init(false); } void networking_init(){ //wifi_init() ethernet_init(); } // WIFI // https://techtutorialsx.com/2017/06/29/esp32-arduino-getting-started-with-wifi/ /* char* translateEncryptionType(wifi_auth_mode_t encryptionType) { switch (encryptionType) { case (WIFI_AUTH_OPEN): return "Open"; case (WIFI_AUTH_WEP): return "WEP"; case (WIFI_AUTH_WPA_PSK): return "WPA_PSK"; case (WIFI_AUTH_WPA2_PSK): return "WPA2_PSK"; case (WIFI_AUTH_WPA_WPA2_PSK): return "WPA_WPA2_PSK"; case (WIFI_AUTH_WPA2_ENTERPRISE): return "WPA2_ENTERPRISE"; } } void scanNetworks() { int number_of_networks = WiFi.scanNetworks(); Serial.print("Number of networks found: "); Serial.println(number_of_networks); for (int i = 0; i < number_of_networks; i++) { Serial.print("Network name: "); Serial.println(WiFi.SSID(i)); Serial.print("Signal strength: "); Serial.println(WiFi.RSSI(i)); Serial.print("MAC address: "); Serial.println(WiFi.BSSIDstr(i)); Serial.print("Encryption type: "); String encryption_type_description = translateEncryptionType(WiFi.encryptionType(i)); Serial.println(encryption_type_description); Serial.println("-----------------------"); } } void wifi_init() { WiFi.begin(ssid, password); int retries = 10; while (WiFi.status() != WL_CONNECTED) { delay(1000); retries--; if (retries < 0) { Serial.println(F("ERROR! Failed to connect to Wifi!")); return; } Serial.println(F("Establishing connection to WiFi..")); } delay(1000); Serial.println(F("Connected to Wifi!")); get_mac_addr(); Serial.println(WiFi.localIP()); udp_init(); } */ bool send_data_message(Message ma) { if (!ethernet_connected){ return false; } unsigned char m[264]; fill_byte_buffer_message(&ma, m, 264); // I don't know how to compute this byte. m[263] = '\n'; if (udp_client.beginPacket(log_host_ip_addr, log_port) != 1) { Serial.println("Ethernet send_data_message begin failed!"); return false; } udp_client.write(m, 264); if (udp_client.endPacket() != 1) { Serial.println("Ethernet send_data_message end failed!"); return false; } return true; } bool send_data_measurement(Measurement ma) { if (!ethernet_connected){ return false; } unsigned char m[14]; fill_byte_buffer_measurement(&ma, m, 13); m[13] = '\n'; if (udp_client.beginPacket(log_host_ip_addr, log_port) != 1) { Serial.println("Ethernet send_data_measurement begin failed!"); return false; } udp_client.write(m, 14); if (udp_client.endPacket() != 1) { Serial.println("Ethernet send_data_measurement end failed!"); return false; } return true; }
59a79f91d8fe499cf07418d0982d64ee2c1cd84b
76dba61f664fe4a9ecf7fa5a926a43055e8b92d5
/miniapps/tools/get-values.cpp
8c54610edaf4951ccd165306e2cff9bc408cd73a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib" ]
permissive
mfem/mfem
4be8b3782f69af874a543565c25b3615188137a1
a15866e212b167ab83d5384e7326cdd3fa0723b2
refs/heads/master
2023-08-16T23:11:02.996304
2023-08-16T03:10:57
2023-08-16T03:10:57
37,287,688
1,442
548
BSD-3-Clause
2023-09-14T16:29:14
2015-06-11T21:42:21
C++
UTF-8
C++
false
false
10,843
cpp
get-values.cpp
// Copyright (c) 2010-2023, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // // -------------------------------------------------------------------- // Get Values Miniapp: Extract field values via DataCollection classes // -------------------------------------------------------------------- // // This miniapp loads previously saved data using DataCollection sub-classes, // see e.g. load-dc miniapp and Example 5/5p, and output field values at a // set of points. Currently, only the VisItDataCollection class is supported. // // Compile with: make get-values // // Serial sample runs: // > get-values -r ../../examples/Example5 -p "0 0 0.1 0" -fn pressure // // Parallel sample runs: // > mpirun -np 4 get-values -r ../electromagnetics/Volta-AMR-Parallel // -c 1 -p "0 0 0 0.1 0.1 0.1" -fn ALL // // Point locations can be specified on the command line using -p or within a // data file whose name can be given with option -pf. The data file format is: // // number_of_points space_dimension // x_0 y_0 ... // x_1 y_1 ... // etc. // // By default all available fields are evaluated. The list of fields can be // reduced by specifying the desired field names with -fn. The -fn option // takes a space separated list of field names surrounded by quotes. Field // names containing spaces, such as "Field 1" and "Field 2", can be entered as: // get-values -fn "Field\ 1 Field\ 2" // // By default the data is written to standard out. This can be overwritten // with the -o [filename] option. // // The output format contains comments as well as sizing information to aid in // subsequent processing. The bulk of the data consists of one line per point // with a 0-based integer index followed by the point coordinates and then the // field data. A legend, appearing before the bulk data, shows the order of // the fields along with the number of values per field (for vector data). // #include "mfem.hpp" #include <fstream> #include <set> #include <string> using namespace std; using namespace mfem; void parseFieldNames(const char * field_name_c_str, set<string> &field_names); void parsePoints(int spaceDim, const char *pts_file_c_str, Vector &pts); /// @cond Suppress_Doxygen_warnings void writeLegend(const DataCollection::FieldMapType &fields, const set<string> & field_names, int spaceDim); /// @endcond int main(int argc, char *argv[]) { #ifdef MFEM_USE_MPI Mpi::Init(); if (!Mpi::Root()) { mfem::out.Disable(); mfem::err.Disable(); } Hypre::Init(); #endif // Parse command-line options. const char *coll_name = NULL; int cycle = 0; int pad_digits_cycle = 6; int pad_digits_rank = 6; const char *field_name_c_str = "ALL"; const char *pts_file_c_str = ""; Vector pts; const char *out_file_c_str = ""; OptionsParser args(argc, argv); args.AddOption(&coll_name, "-r", "--root-file", "Set the VisIt data collection root file prefix.", true); args.AddOption(&cycle, "-c", "--cycle", "Set the cycle index to read."); args.AddOption(&pad_digits_cycle, "-pdc", "--pad-digits-cycle", "Number of digits in cycle."); args.AddOption(&pad_digits_rank, "-pdr", "--pad-digits-rank", "Number of digits in MPI rank."); args.AddOption(&pts, "-p", "--points", "List of points."); args.AddOption(&field_name_c_str, "-fn", "--field-names", "List of field names to get values from."); args.AddOption(&pts_file_c_str, "-pf", "--point-file", "Filename containing a list of points."); args.AddOption(&out_file_c_str, "-o", "--output-file", "Output filename."); args.Parse(); if (!args.Good()) { args.PrintUsage(mfem::out); return 1; } args.PrintOptions(mfem::out); #ifdef MFEM_USE_MPI VisItDataCollection dc(MPI_COMM_WORLD, coll_name); #else VisItDataCollection dc(coll_name); #endif dc.SetPadDigitsCycle(pad_digits_cycle); dc.SetPadDigitsRank(pad_digits_rank); dc.Load(cycle); if (dc.Error() != DataCollection::No_Error) { mfem::out << "Error loading VisIt data collection: " << coll_name << endl; return 1; } int spaceDim = dc.GetMesh()->SpaceDimension(); mfem::out << endl; mfem::out << "Collection Name: " << dc.GetCollectionName() << endl; mfem::out << "Space Dimension: " << spaceDim << endl; mfem::out << "Cycle: " << dc.GetCycle() << endl; mfem::out << "Time: " << dc.GetTime() << endl; mfem::out << "Time Step: " << dc.GetTimeStep() << endl; mfem::out << endl; typedef DataCollection::FieldMapType fields_t; const fields_t &fields = dc.GetFieldMap(); // Print the names of all fields. mfem::out << "fields: [ "; for (fields_t::const_iterator it = fields.begin(); it != fields.end(); ++it) { if (it != fields.begin()) { mfem::out << ", "; } mfem::out << it->first; } mfem::out << " ]" << endl; // Parsing desired field names set<string> field_names; parseFieldNames(field_name_c_str, field_names); // Print field names to be extracted mfem::out << "Extracting fields: "; for (set<string>::iterator it=field_names.begin(); it!=field_names.end(); it++) { mfem::out << " \"" << *it << "\""; } mfem::out << endl; parsePoints(spaceDim, pts_file_c_str, pts); int npts = pts.Size() / spaceDim; DenseMatrix pt_mat(pts.GetData(), spaceDim, npts); Array<int> elem_ids; Array<IntegrationPoint> ip; int nfound = dc.GetMesh()->FindPoints(pt_mat, elem_ids, ip); mfem::out << "Found " << nfound << " points." << endl; ofstream ofs; if (strcmp(out_file_c_str,"") != 0 #ifdef MFEM_USE_MPI && Mpi::Root() #endif ) { ofs.open(out_file_c_str); if (!ofs) { MFEM_ABORT("Failed to open output file: " << out_file_c_str << '\n'); } mfem::out.SetStream(ofs); } // Write legend showing the order of the fields and their sizes writeLegend(fields, field_names, spaceDim); mfem::out << "# Number of points\n" << nfound << endl; for (int e=0; e<elem_ids.Size(); e++) { if (elem_ids[e] >= 0) { mfem::out << e; for (int d=0; d<spaceDim; d++) { mfem::out << ' ' << pt_mat(d, e); } // Loop over all fields. for (fields_t::const_iterator it = fields.begin(); it != fields.end(); ++it) { if (field_names.find("ALL") != field_names.end() || field_names.find(it->first) != field_names.end()) { if (it->second->VectorDim() == 1) { mfem::out << ' ' << it->second->GetValue(elem_ids[e], ip[e]); } else { Vector val; it->second->GetVectorValue(elem_ids[e], ip[e], val); for (int d=0; d<it->second->VectorDim(); d++) { mfem::out << ' ' << val[d]; } } } } mfem::out << endl; } } if (ofs) { ofs.close(); } return 0; } void parseFieldNames(const char * field_name_c_str, set<string> &field_names) { string field_name_str(field_name_c_str); string field_name; for (string::iterator it=field_name_str.begin(); it!=field_name_str.end(); it++) { if (*it == '\\') { it++; field_name.push_back(*it); } else if (*it == ' ') { if (!field_name.empty()) { field_names.insert(field_name); } field_name.clear(); } else if (it == field_name_str.end() - 1) { field_name.push_back(*it); field_names.insert(field_name); } else { field_name.push_back(*it); } } if (field_names.size() == 0) { field_names.insert("ALL"); } } void parsePoints(int spaceDim, const char *pts_file_c_str, Vector &pts) { if (strcmp(pts_file_c_str,"") == 0) { return; } ifstream ifs(pts_file_c_str); if (!ifs) { MFEM_ABORT("Failed to open point file: " << pts_file_c_str << '\n'); } int o, n, dim; ifs >> n >> dim; MFEM_VERIFY(dim == spaceDim, "Mismatch in mesh's space dimension " "and point dimension."); if (pts.Size() > 0 && pts.Size() % spaceDim == 0) { int size = pts.Size() + n * dim; Vector tmp(size); for (int i=0; i<pts.Size(); i++) { tmp[i] = pts[i]; } o = pts.Size(); pts.Swap(tmp); } else { pts.SetSize(n * dim); o = 0; } for (int i=0; i<n; i++) { for (int d=0; d<dim; d++) { ifs >> pts[o + i * dim + d]; } } ifs.close(); } void writeLegend(const DataCollection::FieldMapType &fields, const set<string> & field_names, int spaceDim) { typedef DataCollection::FieldMapType fields_t; // Count the number of fields to be output int nfields = 1; for (fields_t::const_iterator it = fields.begin(); it != fields.end(); ++it) { if (field_names.find("ALL") != field_names.end() || field_names.find(it->first) != field_names.end()) { nfields++; } } // Write the legend showing each field name and its number of entries mfem::out << "# Number of fields" << endl << nfields << endl; mfem::out << "# Legend" << endl; mfem::out << "# \"Index\" \"Location\":" << spaceDim; for (fields_t::const_iterator it = fields.begin(); it != fields.end(); ++it) { if (field_names.find("ALL") != field_names.end() || field_names.find(it->first) != field_names.end()) { mfem::out << " \"" << it->first << "\":" << it->second->VectorDim(); } } mfem::out << endl; // Write the number of entries for each field without the names // which should be more convenient for parsing the output file. mfem::out << spaceDim; for (fields_t::const_iterator it = fields.begin(); it != fields.end(); ++it) { if (field_names.find("ALL") != field_names.end() || field_names.find(it->first) != field_names.end()) { mfem::out << " " << it->second->VectorDim(); } } mfem::out << endl; }
2202cac771d2c31cebb42c1fae04b0cbc5aa808a
e7c16164ceb387a4fba777be4744930c22bf6a31
/dbserver/profile/dbprofiler.cpp
659abb53f65d1454915f460b4a58cfaec68d5bf4
[]
no_license
freewayso/gameserver
a661415b18db93813b93126c7c3ecc62c69c6f3c
74738181e6b01b0f68414d27c1d2d9cd4b139a2e
refs/heads/main
2023-01-07T08:28:03.734762
2020-11-10T13:01:23
2020-11-10T13:01:23
311,651,825
2
0
null
null
null
null
UTF-8
C++
false
false
787
cpp
dbprofiler.cpp
#include "pch.h" #include "dbprofiler.h" #include "mysql/mysqlmgr.h" INSTANCE_SINGLETON(CDbProfiler) CDbProfiler::CDbProfiler() { } CDbProfiler::~CDbProfiler() { } bool CDbProfiler::Init() { StartTimer(); SetFileName("dbserver"); return true; } void CDbProfiler::Uninit() { StopTimer(); } void CDbProfiler::DoProfile(FILE* fp) { UINT32 dwThreadNum = CMysqlMgr::Instance()->GetThreadNum(); if(dwThreadNum == 0) return; for(UINT32 i = 0; i < dwThreadNum; ++i) { CMysqlThread* poThread = CMysqlMgr::Instance()->GetThread(i); if(poThread == NULL) continue; fprintf(fp, "db thread %u: TaskProcessed: %u, MaxTaskNumInQueue: %u\n", i, poThread->GetProcessedTask(), poThread->GetMaxTaskInQueue()); poThread->SetProcessedTask(0); poThread->SetMaxTaskInQueue(0); } }
d5909320cbfe39c25ec1010058b043405c6fbab7
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir521/dir3871/dir4221/dir4367/file4468.cpp
a52f8bf83756e85acde66a9317ea61debb754e42
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
111
cpp
file4468.cpp
#ifndef file4468 #error "macro file4468 must be defined" #endif static const char* file4468String = "file4468";
56874eea74e3872bd74ace05e128b50a255374f6
a79cb046e2ba8c0f483ccff4bce82048368f5970
/src/main.cpp
993c171673efb39d242a4bdc76e9434d3b1b777b
[]
no_license
Nickolas1987/image_viewer
5453d07ed70b33c56ebf98ce63179a69ede8cb00
1d0c1d48eaecb33bfd5e0010ae270805baa5fa88
refs/heads/main
2023-01-08T23:06:24.804873
2020-11-08T10:52:28
2020-11-08T10:52:28
310,605,274
0
0
null
null
null
null
UTF-8
C++
false
false
2,668
cpp
main.cpp
#include "app.h" #include "imagehandler.h" #include "image.h" using namespace image_viewer_np; /*Strings for interface*/ const std::unordered_map<std::string, App::COMMAND_TYPE> COMMAND_NAMES{ {"load", App::COMMAND_TYPE::LOAD}, {"ld", App::COMMAND_TYPE::LOAD}, {"store", App::COMMAND_TYPE::STORE}, {"st", App::COMMAND_TYPE::STORE}, {"blur", App::COMMAND_TYPE::BLUR}, {"resize", App::COMMAND_TYPE::RESIZE}, {"help", App::COMMAND_TYPE::HELP}, {"h", App::COMMAND_TYPE::HELP}, {"exit", App::COMMAND_TYPE::CLOSE}, {"quit", App::COMMAND_TYPE::CLOSE}, {"q", App::COMMAND_TYPE::CLOSE} }; const std::unordered_map<App::COMMAND_TYPE, std::string> ERRORS{ {App::COMMAND_TYPE::LOAD, "Load failed"}, {App::COMMAND_TYPE::STORE, "Store failed"}, {App::COMMAND_TYPE::BLUR, "Blur failed"}, {App::COMMAND_TYPE::RESIZE, "Resize failed"}, {App::COMMAND_TYPE::UNDEFINED, "Unknown command"}, }; const std::string HELP_STR = "ld, load filename key - load image \n" "st,store key filename - store image\n" "blur src dst size - blur image \n" "resize src dst width height - resize image \n" "q, quit - close"; int main(){ try { auto handler = std::unique_ptr<IImageHandler>(new ImageHandler<Image>()); App app(std::move(handler), COMMAND_NAMES, ERRORS, HELP_STR); app.run(); } catch (std::bad_alloc& e) { std::cout << e.what() << std::endl; } catch (std::runtime_error& e) { std::cout << e.what() << std::endl; } return 0; }
5398d7e54f82ae51a28a4e0e7d1ea48b252569fd
4eac9667d4b248a366462c60fd6f6d323b875fca
/Codeforces-D. Soldier and Number Game.cpp
8e72b78e42283bb5c80a89eb82acbddab783c8a6
[]
no_license
joy-mollick/Number-Theory
be4a884b1488f3910debc5ff2d9b4a837dfa41f5
8d678d6fc93a041b123a3ce5bc2fa2983d46074a
refs/heads/master
2021-06-27T05:47:06.437366
2021-01-02T20:07:13
2021-01-02T20:07:13
199,852,129
7
2
null
null
null
null
UTF-8
C++
false
false
872
cpp
Codeforces-D. Soldier and Number Game.cpp
#include<bits/stdc++.h> using namespace std; const int mx=5000001; int prime_fact[mx]={0}; long long dp[mx]={0}; void precal(){ for(int i=2;i<mx;i++) { if(prime_fact[i]==0) { for(int j=i;j<mx;j=j+i) { int temp=j; while(temp>1&&temp%i==0) { prime_fact[j]++; temp=temp/i; } //prime_fact[j]+=prime_fact[j-1]; } } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); precal(); long long sum=0; for(int i=0;i<mx;i++) { sum=sum+(long long)prime_fact[i]; //cout<<sum<<endl; dp[i]=sum; } int t,a,b; cin>>t; while(t--) { cin>>a>>b; cout<<dp[a]-dp[b]<<'\n'; } }
1281b256ecad5bbf12cb596acbe1c6736ff4d512
417f1635a1df67a179a37be1a7fc6b726d2c75af
/548B.cpp
5bbc3f13db0b4f69d2100c131cca10480ffc51f4
[]
no_license
paulot/codeforces
bf076130e11badebec11849ec6c843bfd320f46a
f12773005991333633b4a61896d7dde21bb0f44f
refs/heads/master
2021-01-19T04:32:58.990321
2017-06-30T08:01:10
2017-06-30T08:01:10
36,417,705
0
1
null
null
null
null
UTF-8
C++
false
false
737
cpp
548B.cpp
#include <iostream> using namespace std; bool state[500][500]; int row[500]; int n, m, q; int maxr(int r) { int rm = 0, gm = 0; for (int i = 0; i < m; i++) { if (state[r][i]) rm++; else rm = 0; gm = max(gm, rm); } return gm; } int getmax() { int ma = 0; for (int i = 0; i < n; i++) { ma = max(ma, row[i]); } return ma; } int main() { cin >> n >> m >> q; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> state[i][j]; } } for (int i = 0; i < n; i++) { row[i] = maxr(i); } for (int i = 0; i < q; i++) { int a, b; cin >> a >> b; a--;b--; state[a][b] = !state[a][b]; row[a] = maxr(a); cout << getmax() << endl; } return 0; }
0a0028e083960cf7767e22b0c94fb7f6059cee04
aef4c847697d7948fbbd73674c73191efff2e359
/isode++/code/iso/itu/osi/als/ssap/spdu/CDO.cpp
34a8bdd1686f909637483687c9891f2b2e2dc84e
[ "Apache-2.0" ]
permissive
Kampbell/ISODE
a80682dab1ee293a2711a687fc10660aae546933
37f161e65f11348ef6fca2925d399d611df9f31b
refs/heads/develop
2021-01-10T15:56:44.788906
2016-03-19T11:00:15
2016-03-19T11:00:15
52,000,870
8
0
null
null
null
null
UTF-8
C++
false
false
326
cpp
CDO.cpp
/* * CDO.cpp * * Created on: 22 nov. 2014 * Author: FrancisANDRE */ #include "als/ssap/spdu/CDO.h" namespace ALS { namespace SSAP { namespace SPDU { int CDO::encode() { return 0; } ReturnCode CDO::decode(NetworkBuffer& tsdu) { return OK; } } /* namespace SPDU */ } /* namespace SSAP */ } /* namespace ALS */
4973357d4bdda0a61bbe388c6edafde0ce0aba7d
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/Tracking/TrkEventCnv/TrkEventAthenaPool/src/VxContainerCnv.h
c65358da6b0a4925b9168edd8030353ec06dab0f
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
1,653
h
VxContainerCnv.h
/* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ //----------------------------------------------------------------------------- // // file: VertexContainerCnv.h // author: Kirill Prokofiev <Kirill.Prokofiev@cern.ch> // //----------------------------------------------------------------------------- #ifndef VXCONTAINER_CNV_H #define VXCONTAINER_CNV_H #include "GaudiKernel/MsgStream.h" #include "TrkEventCnvTools/ITrkEventCnvTool.h" #include "AtlasDetDescr/AtlasDetectorID.h" #include "AthenaPoolCnvSvc/T_AthenaPoolCustomCnv.h" #include "AthenaPoolCnvSvc/AthenaPoolCnvTPExtension.h" #include "VxVertex/VxContainer.h" // #include "TrkEventTPCnv/VxContainerCnv_tlp1.h" #include "TrkEventTPCnv/VxContainerCnv_tlp2.h" // typedef Trk::VxContainer_tlp1 VxContainer_PERS; typedef Trk::VxContainer_tlp2 VxContainer_PERS; typedef T_AthenaPoolCustomCnv<VxContainer, VxContainer_PERS> VxContainerCnvBase; class VxContainerCnv : public VxContainerCnvBase, public AthenaPoolCnvTPExtension { friend class CnvFactory<VxContainerCnv>; protected: public: VxContainerCnv( ISvcLocator *svcloc ); protected: virtual StatusCode initialize() override; virtual VxContainer_PERS *createPersistent( VxContainer *transCont) override; virtual VxContainer *createTransient() override; virtual AthenaPoolTopLevelTPCnvBase* getTopLevelTPCnv() override { return &m_TPConverter; } private: IMessageSvc *m_msgSvc; MsgStream m_log; // VxContainerCnv_tlp1 m_TPConverter; VxContainerCnv_tlp2 m_TPConverter; };//end of class definitions #endif // VXCONTAINER_CNV_H
20abad890b1328fd95690cb74b03f755163a9893
335666920a4a5cdcfc9b07b68faafc44ebfa7443
/CStation/widgets/sensorsdisplayform.h
c72329b96e82964d6bd22a92585abeb3d720d64e
[]
no_license
Pvg08/ESP_CStation
ad756824eb6d1bb72db2050828553558feeab6db
3c0354cc7ee3253931724331150829e0fb0d6f6c
refs/heads/master
2020-12-10T12:27:14.260080
2017-04-06T02:16:01
2017-04-06T02:16:01
38,884,014
0
1
null
2016-12-20T19:38:14
2015-07-10T14:18:45
C
UTF-8
C++
false
false
1,618
h
sensorsdisplayform.h
#ifndef SENSORSDISPLAYFORM_H #define SENSORSDISPLAYFORM_H #include <QDialog> #include "./sensorblock.h" #include "./ipcamviewer.h" #include "../server.h" namespace Ui { class SensorsDisplayForm; } class SensorsDisplayForm : public QDialog { Q_OBJECT public: explicit SensorsDisplayForm(Server* c_server, QWidget *parent = 0); ~SensorsDisplayForm(); quint16 getNextPageTimeout() const; void setNextPageTimeout(const quint16 &value); QString getSensorCodes() const; void setSensorCodes(const QString &value); QColor getBg_color() const; void setBg_color(const QColor &value); QColor getLabel_color() const; void setLabel_color(const QColor &value); QColor getValue_color() const; void setValue_color(const QColor &value); QColor getGraphics_color() const; void setGraphics_color(const QColor &value); quint64 getSensorGraphicsLogInterval() const; void setSensorGraphicsLogInterval(const quint64 &value); void setIPCamVisibility(bool isvisible); private slots: void update_blocks_list(); void new_sensor(Sensor* new_sensor); void showNextSensorsPage(); void sensorBlockClicked(); private: Ui::SensorsDisplayForm *ui; Server* server; QString sensor_codes; QColor bg_color, label_color, value_color, graphics_color; quint64 sensor_graphics_log_interval; bool fullscreen_block; quint16 display_block_id; quint16 next_page_timeout; QMap<unsigned, unsigned> sensor_counters; IPCamViewer *camviewer; virtual void showEvent(QShowEvent * event); }; #endif // SENSORSDISPLAYFORM_H
253929e4035d4821e88129b7bb2ef1c65f2a1ff7
21fe8b7b8c0b87ff9d271f6a8dcfa1891fc17715
/MSCvisus/MSCTest2DViewer/main_2d_viewer.cpp
40d9e5d828ec3d8180b9ad72a78587292bb6e151
[]
no_license
sam-lev/UnSupUnetMSCSegmentation
f2541bc7237b00b727cd6c62b7607f87b21e1bcd
8a9f996cf7bc7d1e7951deb14c9cb756ac79f48c
refs/heads/master
2022-03-31T04:10:32.161467
2020-01-19T05:13:38
2020-01-19T05:13:38
197,672,736
1
1
null
null
null
null
UTF-8
C++
false
false
91,671
cpp
main_2d_viewer.cpp
#include <iostream> #include "dump_image.h" #ifdef WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <OpenGL/glu.h> // openGL utilities #include <OpenGL/gl.h> // openGL declarations #ifdef WIN32 #include "freeglut.h" #else #include "glut.h" #endif #include "Matrix4.h" #ifdef WIN32 //#include "C:\local\CImg-1.3.2\CImg.h" #include "C:\Users\jediati\Desktop\JEDIATI\libraries\CImg-1.5.7\CImg.h" using namespace cimg_library; #endif #ifndef WIN32 #include <unistd.h> #endif #include <cmath> #include <algorithm> #include "mscArrayFactory.h" #include "mscDumbGradientField.h" #include "mscRegularRawDataHandler.h" #include "mscRegularGrid3DImplicitMeshHandler.h" #include "mscRegularGrid2DImplicitMeshHandler.h" #include "mscDumbStoringMeshFunction.h" #include "mscDumbStoringMinFunction.h" #include "mscSimpleGradientBuilder.h" #include "mscSimpleRandomGradientBuilder.h" #include "mscSimpleGradientUsingAlgorithms.h" #include "mscRegularGrid3DGradientField.h" #include "mscRegularGrid3DMeshFunction.h" #include "mscTwoWay3DGradientBuilder.h" #include "mscConvergentGradientBuilder.h" #include "mscNegatingMeshFunction.h" #include "mscComplementMeshHandler.h" #include "mscModifiedBoundaryMeshHandler.h" #include "mscCombinationGradientField.h" #include "mscBasicMSC.h" #include "mscNegatingDataHandler.h" #include <map> #include "mscTopoArray.h" #include "mscAssistedGradientBuilder.h" #include "mscSimpleConstrainedGradientBuilder.h" #define EPSILON 0.001 bool USE_SEG = false;; bool USE_SEG_LINES = false; bool USE_SEG_AMAP = false; bool USE_SEG_DMAP = false; int gX, gY, gZ; BasicMSC<float>* MSC; mscBasicGradientField* G_mscg; mscBasicGradientField* G_mscg_TEMP = NULL; mscBasicMeshHandler* G_mscmh; mscBasicMeshHandler* G_mscmh2; mscBasicMeshFunction<float>* G_mscf; mscConvergentGradientBuilder<float>* G_msccb; mscConvergentGradientBuilder<float>* G_msccb2; mscPreClassifier* classes; float red_scale(float s) { Vector4 v; v.vals[0] = s; //max(s, 1.0f-s); v.vals[1] = 1.0f-s; v.vals[2] = max(s, 1.0f-s); Normalize3(&v); return v.vals[0]; //return min(max(4.0*(0.5-s), 0.0), 1.0); } float green_scale(float s) { Vector4 v; v.vals[0] = s;//max(s, 1.0f-s); v.vals[1] = 1.0f-s; v.vals[2] = max(s, 1.0f-s); Normalize3(&v); return v.vals[1]; //return 0.2f; //return min(max(4.0*fabs(s-0.25)-1.0, 0.0), 1.0); } float blue_scale(float s) { Vector4 v; v.vals[0] = s;//max(s, 1.0f-s); v.vals[1] = 1.0f-s; v.vals[2] = max(s, 1.0f-s); Normalize3(&v); return v.vals[2]; // return 1.0-s; //return min(max(4.0*(0.75-s), 0.0), 1.0); } using namespace std; void Initialize_GLUT(int argc, char **argv); void draw_earth ( float x, float y, float z, float size ) { glEnable(GL_LIGHTING); glPushMatrix ( ); glTranslatef ( x, y, z ); //glScalef(size, size, size); GLUquadricObj* q = gluNewQuadric ( ); gluQuadricDrawStyle ( q, GLU_FILL ); gluQuadricNormals ( q, GLU_SMOOTH ); gluSphere ( q, size, 10, 10 ); gluDeleteQuadric ( q ); glPopMatrix ( ); glDisable(GL_LIGHTING); } int seed; int XMIN = 2; int YMIN = 2; int ZMIN = 2; int XMAX = 2; int YMAX = 2; int ZMAX = 2; float ballsize = 0.1f; float percp = 0.0f; template<class FType> struct gminmax { FType minval; FType maxval; float xmin; float xmax; float ymin; float ymax; }; bool gusecutoffhack = false; bool draw_flat = false; bool draw_edges = true; gminmax<float> fminmax; bool clearcolor = 1; bool g_draw_isolines = false; bool draw_gradient = false; float arrow_width = 0.1; float line_width = 2.0; float point_size = 4.0; //template <unsigned char Dim, class FType> //void centroid(UnstructuredSimplicialComplex<Dim, FType>* bcc, index_type cellid, float* verts) { // // for (int i = 0; i < 3; i++) verts[i] = 0.0f; // Simplex<FType>& s = bcc->cells[cellid]; // for (int i = 0; i < s.numberOfVerts; i++) { // BaseVertex<Dim>& v = bcc->verts[s.verts[i]]; // verts[0] += v.position[0]; // if (! draw_flat) // verts[1] += bcc->getValue(s.verts[i]); // else // verts[1] += bcc->getValue(cellid); // verts[2] += v.position[1]; // } // for (int i = 0; i < 3; i++) verts[i] /= s.numberOfVerts; // //}; void coordinates(CELL_INDEX_TYPE cellid, float* c){ c[0] = (float) (cellid % XMAX); c[1] = (float) ((cellid / XMAX) % YMAX); c[2] = (float) (cellid / (XMAX*YMAX)); } void coordinates2(int cellid, float* c){ c[0] = (float) (cellid % gX) * 2; c[1] = (float) ((cellid / gX) % gY) * 2; c[2] = (float) (cellid / (gX*gY)) * 2; } void drawArrow( CELL_INDEX_TYPE cellid) { if (G_mscg->get_critical(cellid)) return; if (! G_mscg->get_assigned(cellid)) return; CELL_INDEX_TYPE pair = G_mscg->get_pair(cellid); if (G_mscmh->dimension(pair) > G_mscmh->dimension(cellid)) return; float start[3]; float end[3]; coordinates(pair, start); coordinates(cellid, end); //instead of a line // glVertex3f(start[0], start[1]+ 2*EPSILON, start[2]); // glVertex3f(end[0], end[1]+ 2*EPSILON, end[2]); //let's use code for computing the worlds most expensive arrow. double diff[3]; diff[0] = end[0]-start[0]; diff[1] = end[1]-start[1]; diff[2] = end[2]-start[2]; double len = diff[0]*diff[0] + diff[1]*diff[1] + diff[2]*diff[2]; len = sqrt(len); diff[0] /= len; diff[1] /= len; diff[2] /= len; const float RADDEG = 57.29578; float Q = atan2 (diff[1], diff[0]) * RADDEG; float P = acos (diff[2]) * RADDEG; glColor3f(0.15,0.15,0.15); glPushMatrix(); GLUquadricObj *quadObj = gluNewQuadric(); GLUquadricObj *quadObj2 = gluNewQuadric(); GLUquadricObj *quadObj3 = gluNewQuadric(); GLUquadricObj *quadObj4 = gluNewQuadric(); gluQuadricDrawStyle ( quadObj, GLU_FILL ); gluQuadricNormals ( quadObj, GLU_SMOOTH ); gluQuadricDrawStyle ( quadObj2, GLU_FILL ); gluQuadricNormals ( quadObj2, GLU_SMOOTH ); gluQuadricDrawStyle ( quadObj3, GLU_FILL ); gluQuadricNormals ( quadObj3, GLU_SMOOTH ); gluQuadricDrawStyle ( quadObj4, GLU_FILL ); gluQuadricNormals ( quadObj4, GLU_SMOOTH ); glTranslatef(start[0],start[1],start[2]); glRotatef (Q,0,0,1); glRotatef (P,0,1,0); gluCylinder(quadObj,0.4*arrow_width,0.4*arrow_width,len-2*arrow_width,10,10); gluDisk(quadObj2,0,0.4*arrow_width,10,10); glTranslatef(0,0,len-2.5*arrow_width); gluCylinder(quadObj3,arrow_width,0,2.5*arrow_width,10,10); gluDisk(quadObj4,0,arrow_width,10,10); gluDeleteQuadric(quadObj); gluDeleteQuadric(quadObj2); gluDeleteQuadric(quadObj3); gluDeleteQuadric(quadObj4); glPopMatrix(); }; bool DRAW_BACKGROUND = true; bool DRAW_BACKGROUND2 = false; bool DRAW_BACKGROUND3 = false; bool DRAWASCLINES = false; bool DRAWDSCLINES = false; bool DRAWPOINTS = true; bool DRAWDIMASCMAN = false; bool DRAWGRAD = false; bool DRAW_ISOLINES = true; bool DRAW_PROBABILITIES1 = false; bool DRAW_PROBABILITIES2 = false; bool DRAW_GRID = false; bool draw_mt = false; bool flat_funct = false; bool redrawstuff = true; GLuint drawlist = -1; bool DRAWNUMERICALDE = false; bool DRAWNUMERICALDE_INIT = false; int* NUMDE_sources; int* NUMDE_dests; struct DE { node<float>* nup; node<float>* ndown; int size; int interior; int boundary; }; float distance(CELL_INDEX_TYPE id1, CELL_INDEX_TYPE id2) { float c1[3]; coordinates(id1, c1); float c2[3]; coordinates(id2, c2); return sqrt((c1[0]-c2[0])*(c1[0]-c2[0]) +(c1[1]-c2[1])*(c1[1]-c2[1])); }; void DrawDe() { CELL_INDEX_TYPE* aid= new CELL_INDEX_TYPE[G_mscmh->num_cells()](); CELL_INDEX_TYPE* did= new CELL_INDEX_TYPE[G_mscmh->num_cells()](); // get ascending man dimensions map< pair<CELL_INDEX_TYPE, CELL_INDEX_TYPE>, DE > pairmap; glBegin(GL_LINES); map<CELL_INDEX_TYPE, node<float>*>::iterator nit = MSC->nodes.begin(); while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (! MSC->isAlive(n)) continue; if (n->index != 0) continue; set<CELL_INDEX_TYPE> g; MSC->fillGeometry(n, g); for (set<CELL_INDEX_TYPE>::iterator geom = g.begin(); geom != g.end(); geom++) { CELL_INDEX_TYPE id0 = *geom; cellIterator it1; iteratorOperator& cofacets1 = G_mscmh->cofacets(id0, it1); for (cofacets1.begin(it1); cofacets1.valid(it1); cofacets1.advance(it1)) { CELL_INDEX_TYPE id1 = cofacets1.value(it1); g.insert(id1); cellIterator it2; iteratorOperator& cofacets2 = G_mscmh->cofacets(id1, it2); for (cofacets2.begin(it2); cofacets2.valid(it2); cofacets2.advance(it2)) { CELL_INDEX_TYPE id2 = cofacets2.value(it2); g.insert(id2); } } } // now g has ids of all cells in thingy. for(set<CELL_INDEX_TYPE>::iterator sit = g.begin(); sit != g.end(); sit++) { aid[*sit] = n->cellid; } set<CELL_INDEX_TYPE> maxs; arc<float>* a = n->firstarc; while (a != NULL) { if (! MSC->isAlive(a)) { a = a->lower_next; continue; } node<float>* n1 = a->upper; arc<float>* a1 = n1->firstarc; while (a1 != NULL) { if (! MSC->isAlive(a1) || a1->lower != n1) { if (a1->lower == n1) { a1 = a1->lower_next; } else { a1 = a1->upper_next; } continue; } maxs.insert(a1->upper->cellid); a1 = a1->lower_next; } a = a->lower_next; } // now maxs has all maxs attached to this min float c0[3]; coordinates(n->cellid, c0); for (set<CELL_INDEX_TYPE>::iterator sit = maxs.begin(); sit != maxs.end(); sit++) { float c1[3]; coordinates((*sit), c1); glColor4f(.5,0,1,.5); glVertex3f(c0[0], c0[1], c0[2]); glColor4f(1,0,.5,.5); glVertex3f(c1[0], c1[1], c1[2]); //also insert into pairmap DE t; t.ndown = n; t.nup = MSC->nodes[(*sit)]; t.size = 0; t.interior = 0; t.boundary = 0; pairmap[pair<CELL_INDEX_TYPE, CELL_INDEX_TYPE>(n->cellid, (*sit))] = t; } } glEnd(); nit = MSC->nodes.begin(); while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (! MSC->isAlive(n)) continue; if (n->index != 2) continue; set<CELL_INDEX_TYPE> g; MSC->fillGeometry(n, g); for (set<CELL_INDEX_TYPE>::iterator geom = g.begin(); geom != g.end(); geom++) { CELL_INDEX_TYPE id0 = *geom; cellIterator it1; iteratorOperator& facets1 = G_mscmh->facets(id0, it1); for (facets1.begin(it1); facets1.valid(it1); facets1.advance(it1)) { CELL_INDEX_TYPE id1 = facets1.value(it1); g.insert(id1); cellIterator it2; iteratorOperator& facets2 = G_mscmh->facets(id1, it2); for (facets2.begin(it2); facets2.valid(it2); facets2.advance(it2)) { CELL_INDEX_TYPE id2 = facets2.value(it2); g.insert(id2); } } } // now g has ids of all cells in thingy. for(set<CELL_INDEX_TYPE>::iterator sit = g.begin(); sit != g.end(); sit++) { did[*sit] = n->cellid; } } //now aid and did have ids of ascending and descending manifolds for (CELL_INDEX_TYPE i = 0; i < G_mscmh->num_cells(); i++) { CELL_INDEX_TYPE id1 = aid[i]; CELL_INDEX_TYPE id2 = did[i]; //printf("%d, %d\n", (int) id1, (int) id2); pair<CELL_INDEX_TYPE, CELL_INDEX_TYPE> p(id1, id2); if (pairmap.count(p) != 0) { DE& d = pairmap[p]; d.size++; bool isInterior = true; cellIterator fit; iteratorOperator& facets = G_mscmh->facets(i, fit); for (facets.begin(fit); facets.valid(fit); facets.advance(fit)) { CELL_INDEX_TYPE nid = facets.value(fit); if (aid[nid] != id1 || did[nid] != id2) isInterior = false; } iteratorOperator& cofacets = G_mscmh->cofacets(i, fit); for (cofacets.begin(fit); cofacets.valid(fit); cofacets.advance(fit)) { CELL_INDEX_TYPE nid = cofacets.value(fit); if (aid[nid] != id1 || did[nid] != id2) isInterior = false; } if(isInterior) { d.interior++; } else { d.boundary++; } } } // FILE* fout = fopen("DISSIPATIONELEMENTS.txt", "w"); // for (map< pair<CELL_INDEX_TYPE, CELL_INDEX_TYPE>, DE>::iterator it = pairmap.begin(); // it != pairmap.end(); it++) { // DE& d = (*it).second; // // float c1[3]; // coordinates(d.ndown->cellid, c1); // float c2[3]; // coordinates(d.nup->cellid, c2); // // fprintf(fout, "%f %f %f %d %f %d %d %f %f %f %f\n", d.ndown->value, d.nup->value, // d.nup->value - d.ndown->value, d.size, distance(d.nup->cellid, d.ndown->cellid), // d.interior, d.boundary, c1[0], c1[1], c2[0], c2[1]); // } // fclose(fout); delete[] aid; delete[] did; } struct TCOLOR { float r, g, b; int count; }; map<int, map<int, TCOLOR> > sd2c; vector<float> g_num_grad_pairs; struct MP { float c[2]; }; vector< vector<MP> > tlines; vector< MP> tlines2; void drawSEG() { if (USE_SEG_AMAP) { glBegin(GL_QUADS); cellIterator it; iteratorOperator& all = G_mscmh->d_cells_iterator(0, it); for (all.begin(it); all.valid(it); all.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) CELL_INDEX_TYPE cid = all.value(it); int v = classes->getId(cid); float col[3]; coordinates(v, col); #define PI 3.14159265f int dd = 60; float hd = 60.0f; float v1 = (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; float v2 = (sin((dd - (((int) col[1])%dd))/hd))*0.8f+.2f; float v3 = (sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))*0.8f+.2f; float R = 0.3 + (((v ) * 54247) % 167) / 255.0; float G = 0.3 + (((v ) * 68321) % 167) / 255.0; float B = 0.3 + (((v ) * 5373) % 167) / 255.0; glColor3f(R,G,B); float c[3]; coordinates(cid, c); glVertex3f(c[0]-1, c[1]-1, c[2]); glVertex3f(c[0]-1, c[1]+1, c[2]); glVertex3f(c[0]+1, c[1]+1, c[2]); glVertex3f(c[0]+1, c[1]-1, c[2]); } glEnd(); } if (USE_SEG_DMAP) { glBegin(GL_QUADS); cellIterator it; iteratorOperator& all = G_mscmh->d_cells_iterator(2, it); for (all.begin(it); all.valid(it); all.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) CELL_INDEX_TYPE cid = all.value(it); int v = classes->getId(cid); float col[3]; coordinates(v, col); #define PI 3.14159265f int dd = 60; float hd = 60.0f; //float v1 = (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; //float v2 = (sin((dd - (((int) col[1])%dd))/hd))*0.8f+.2f; //float v3 = (sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))*0.8f+.2f; float v1 = (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; float v2 = (sin(PI*((int) col[1]%dd)/((float) hd)))*0.8f+.2f; float v3 = (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; float R = 0.3 + (((v ) * 54247) % 167) / 255.0; float G = 0.3 + (((v ) * 68321) % 167) / 255.0; float B = 0.3 + (((v ) * 5373) % 167) / 255.0; glColor3f(R,G,B); float c[3]; coordinates(cid, c); glVertex3f(c[0]-1, c[1]-1, c[2]); glVertex3f(c[0]-1, c[1]+1, c[2]); glVertex3f(c[0]+1, c[1]+1, c[2]); glVertex3f(c[0]+1, c[1]-1, c[2]); } glEnd(); } //// //if (g_num_grad_pairs.size() == 0) { //// FILE* fin = fopen("grad_dests.raw", "rb"); //// g_num_grad_pairs.clear(); //// while (! feof(fin)) { //// float s; //// fread(&s, sizeof(float), 1, fin); //// g_num_grad_pairs.push_back( s); //// //printf("%d %f\n", (g_num_grad_pairs.size() -1)%4, //// // g_num_grad_pairs[g_num_grad_pairs.size()-1]); //// } //// fclose(fin); //// printf("read %d thingies\n", g_num_grad_pairs.size()/4); //// //} //// glBegin(GL_LINES); //// glColor4f(0,0,0, 0.2); //// for (int i = 0; i < g_num_grad_pairs.size(); i+=4) { //// float x = g_num_grad_pairs[i]*2; //// float y = g_num_grad_pairs[i+1]*2; //// float dx = g_num_grad_pairs[i+2]*2; //// float dy = g_num_grad_pairs[i+3]*2; //// //float n = sqrt(dx*dx + dy*dy) * 0.5; //// glVertex3f(x,y, 0); //// glVertex3f(dx,dy, 0); //// //glVertex3f(x+dx/n, y+dy/n, 0); //// } //// glEnd(); ////} if(USE_SEG_LINES) { printf("got here\n"); if (tlines.size() == 0) { FILE* fin = fopen("lines_out.raw", "rb"); while (! feof(fin)) { vector<MP> line; int num; fread(&num, sizeof(int), 1, fin); for (int i = 0; i < num; i++) { MP t; fread(t.c, sizeof(float), 2, fin); line.push_back(t); } tlines.push_back(line); } fclose(fin); } glLineWidth(3.0); glColor4f(0,0,0,0.2); for (int i = 0; i < tlines.size(); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < tlines[i].size(); j++) { glVertex3f(tlines[i][j].c[0]*2, tlines[i][j].c[1]*2, 0); } glEnd(); } //if (tlines2.size() == 0) { // FILE* fin = fopen("lines_out2.raw", "rb"); // if (fin != NULL) { // while (! feof(fin)) { // int num; // fread(&num, sizeof(int), 1, fin); // for (int i = 0; i < num; i++) { // MP t; // fread(t.c, sizeof(float), 2, fin); // tlines2.push_back(t); // } // } // fclose(fin); // } //} //glLineWidth(3.0); //glColor4f(0.1,0.4,0.2,0.7); //glBegin(GL_LINES); //for (int i = 0; i < tlines2.size(); i++) { // if(i % 2 == 0) glColor4f(0.1,0.4,0.2,0.2); // if(i % 2 == 1) glColor4f(0.1,0.4,0.2,0.7); // glVertex3f(tlines2[i].c[0]*2, tlines2[i].c[1]*2, 0); //} //glEnd(); } if (USE_SEG) { glBegin(GL_QUADS); cellIterator it; iteratorOperator& all = G_mscmh->all_cells_iterator(it); for (all.begin(it); all.valid(it); all.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) CELL_INDEX_TYPE cid = all.value(it); int v = G_mscg_TEMP->get_dim_asc_man(cid); if (v > 0) { if (v == 1) { glColor3f(1,0,0); } else if (v == 2) { glColor3f(0,0,1); } else { glColor3f(0,1,0); } float c[3]; coordinates(cid, c); glVertex3f(c[0]-0.5, c[1]-0.5, c[2]); glVertex3f(c[0]-0.5, c[1]+0.5, c[2]); glVertex3f(c[0]+0.5, c[1]+0.5, c[2]); glVertex3f(c[0]+0.5, c[1]-0.5, c[2]); } } glEnd(); } } int* global_dsc_ids = NULL; int* global_asc_ids = NULL; template <unsigned char Dim, class FType> void DumpAscMan(/*UnstructuredSimplicialComplex<Dim, FType>* bcc*/) { printf("dumping ids\n"); FILE* fdsc = fopen("dump_dsc.raw", "wb"); typename map<CELL_INDEX_TYPE, node<float>* >::iterator nit = MSC->nodes.begin(); if(global_dsc_ids == NULL) { global_dsc_ids = new int[(gX-1) * (gY-1)]; for (int i = 0; i < (gX-1) * (gY-1); i++) global_dsc_ids[i] = 0; } while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (! MSC->isAlive(n)) continue; if (n->index != 2) continue; set<CELL_INDEX_TYPE> g; MSC->fillGeometry(n, g); unsigned int value = ((n->cellid + 52341) * 347) % 253; if (value == -1) printf("SD:FLKJSFL:KDJSF:LDKSJ %d, %d\n", value, n->cellid); for (set<CELL_INDEX_TYPE>::iterator sit = g.begin(); sit != g.end(); sit++) { CELL_INDEX_TYPE currentcid = *sit; int x = (currentcid % XMAX) / 2; int y = (currentcid / XMAX) / 2; global_dsc_ids[x + y * (gX-1)] = value; } } fwrite(global_dsc_ids, (gX-1)*(gY-1), sizeof(int), fdsc); fclose(fdsc); for (int i = 0; i < (gX-1) * (gY-1); i++) { //if(global_dsc_ids[i] == -1) printf("WHnnnnnnOAthere -1\n"); } FILE* fasc = fopen("dump_asc.raw", "wb"); if(global_asc_ids == NULL) { global_asc_ids = new int[gX * gY]; for (int i = 0; i < gX*gY; i++) global_asc_ids[i] = 0; } nit = MSC->nodes.begin(); while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (! MSC->isAlive(n)) continue; if (n->index != 0) continue; set<CELL_INDEX_TYPE> g; MSC->fillGeometry(n, g); unsigned int value = ((n->cellid + 52341) * 347) % 253; for (set<CELL_INDEX_TYPE>::iterator sit = g.begin(); sit != g.end(); sit++) { CELL_INDEX_TYPE currentcid = *sit; int x = (currentcid % XMAX) / 2; int y = (currentcid / XMAX) / 2; global_asc_ids[x + y * (gX)] = value; //printf("[%d, %d] = %d, %d\n", x,y,n->cellid, gX); } } fwrite(global_asc_ids, (gX)*(gY), sizeof(int), fasc); fclose(fasc); for (int i = 0; i < gX*gY; i++) { //if (global_asc_ids[i] == -1) printf("wFFFFhaoascending -1\n"); } } template <unsigned char Dim, class FType> bool ArcTest(arc<FType>* a) { return true; } int* global_dsc_line_ids = NULL; int* global_asc_line_ids = NULL; template <unsigned char Dim, class FType> void DumpLines(/*UnstructuredSimplicialComplex<Dim, FType>* bcc*/) { printf("dumping ids, %d, %d\n", (gX-1) ,(gY-1)); FILE* fdsc = fopen("dump_asc_lines.raw", "wb"); if(global_asc_line_ids == NULL) { global_asc_line_ids = new int[(gX-1) * (gY-1)]; for (int i = 0; i < (gX-1) * (gY-1); i++) global_asc_line_ids[i] = 0; } for (int i = 0; i < MSC->arcs.size(); i++) { arc<float>* a = MSC->arcs[i]; if (! MSC->isAlive(a)) continue; if (a->lower->index == 0 && ! DRAWDSCLINES) continue; if (a->lower->index == 1 && ! DRAWASCLINES) continue; if (! ArcTest<Dim, FType>(a)) continue; if (a->lower->index != 1) continue; vector<CELL_INDEX_TYPE> g; MSC->fillGeometry(a, g); for (int j = 0; j < g.size(); j++) { if (G_mscmh->dimension(g[j]) != 2) continue; int x = (g[j] % XMAX) / 2; int y = (g[j] / XMAX) / 2; global_asc_line_ids[x + y * (gX-1)] =128; //global_dsc_line_ids[g[j]] = 128; } } fwrite(global_asc_line_ids, (gX-1)*(gY-1), sizeof(int), fdsc); fclose(fdsc); fdsc = fopen("dump_dsc_lines.raw", "wb"); if(global_dsc_line_ids == NULL) { global_dsc_line_ids = new int[gX * gY]; for (int i = 0; i < (gX) * (gY); i++) global_dsc_line_ids[i] = 0; } for (int i = 0; i < MSC->arcs.size(); i++) { arc<float>* a = MSC->arcs[i]; if (! MSC->isAlive(a)) continue; if (a->lower->index == 0 && ! DRAWDSCLINES) continue; if (a->lower->index == 1 && ! DRAWASCLINES) continue; if (! ArcTest<Dim, FType>(a)) continue; if (a->lower->index != 0) continue; vector<CELL_INDEX_TYPE> g; MSC->fillGeometry(a, g); for (int j = 0; j < g.size(); j++) { if (G_mscmh->dimension(g[j]) != 0) continue; int x = (g[j] % XMAX) / 2; int y = (g[j] / XMAX) / 2; global_dsc_line_ids[x + y * (gX)] =128; //global_dsc_line_ids[g[j]] = 128; } } fwrite(global_dsc_line_ids, (gX)*(gY), sizeof(int), fdsc); fclose(fdsc); //FILE* fasc = fopen("dump_asc_lines.raw", "wb"); //if(global_asc_line_ids == NULL) { // global_asc_line_ids = new int[gX * gY]; // for (int i = 0; i < gX*gY; i++) global_asc_line_ids[i] = 0; //} // nit = MSC->nodes.begin(); //while (nit != MSC->nodes.end()) { // node<float>* n = (*nit).second; // nit++; // // if (! MSC->isAlive(n)) continue; // if (n->index != 0) continue; // set<CELL_INDEX_TYPE> g; // MSC->fillGeometry(n, g); // for (set<CELL_INDEX_TYPE>::iterator sit = g.begin(); // sit != g.end(); sit++) { // CELL_INDEX_TYPE currentcid = *sit; // int x = (currentcid % XMAX) / 2; // int y = (currentcid / XMAX) / 2; // global_asc_ids[x + y * (gX)] = n->cellid; // //printf("[%d, %d] = %d, %d\n", x,y,n->cellid, gX); // } //} //fwrite(global_asc_ids, (gX)*(gY), sizeof(int), fasc); //fclose(fasc); } float myval = 1.0f; bool g_use_test = false; bool PassTest(arc<float>* a) { if (!g_use_test) return true; return a->lower->value < myval && a->upper->value < myval; } bool PassTest(node<float>* n) { if (!g_use_test) return true; return n->value < myval; } struct color { float r, g, b, a; color(float rr, float gg, float bb, float aa) : r(rr), g(gg), b(bb), a(aa){} color(){} }; map<node<float>*, color> node_cols; template <unsigned char Dim, class FType> void drawStuff(/*UnstructuredSimplicialComplex<Dim, FType>* bcc*/) { if (! redrawstuff) { glCallList(drawlist); return; } if (drawlist != -1) glDeleteLists(drawlist, 1); drawlist = glGenLists(1); glNewList(drawlist, GL_COMPILE_AND_EXECUTE); redrawstuff = false; //glBegin(GL_LINE_LOOP); //glColor3f(1,0,0); //glVertex3f(0,0,0); //glColor3f(0, 1, 0); //glVertex3f(0, YMAX-1, 0); //glColor3f(0,0,1); //glVertex3f(XMAX-1, YMAX-1, 0); // //glColor3f(1,1,0); //glVertex3f(XMAX-1, 0, 0); //glEnd(); mscSimpleGradientUsingAlgorithms<float>* alg = new mscSimpleGradientUsingAlgorithms<float>(G_mscf, G_mscmh, G_mscg, NULL); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1.0, 1.0); cellIterator it; if(DRAW_BACKGROUND) { glBegin(GL_QUADS); iteratorOperator& all = G_mscmh->all_cells_iterator(it); for (all.begin(it); all.valid(it); all.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) CELL_INDEX_TYPE cid = all.value(it); float sc = G_mscf->cell_value(cid); sc = (sc - fminmax.minval) / (fminmax.maxval - fminmax.minval); sc = sc*.8 + .2; glColor3f(sc+.01, sc, sc+.01); float c[3]; coordinates(cid, c); glVertex3f(c[0]-0.5, c[1]-0.5, c[2]); glVertex3f(c[0]-0.5, c[1]+0.5, c[2]); glVertex3f(c[0]+0.5, c[1]+0.5, c[2]); glVertex3f(c[0]+0.5, c[1]-0.5, c[2]); //glVertex3f(c[0], c[1], c[2]); } glEnd(); } glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // draw grid if (DRAW_BACKGROUND2 || DRAW_BACKGROUND3) { DumpAscMan<Dim,FType>(); } glBegin(GL_QUADS); typename map<CELL_INDEX_TYPE, node<float>* >::iterator nit = MSC->nodes.begin(); if (DRAW_BACKGROUND2) { while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (! MSC->isAlive(n)) continue; if (n->index != 2) continue; set<CELL_INDEX_TYPE> g; MSC->fillGeometry(n, g); float col[3]; coordinates(n->cellid, col); #define PI 3.14159265f int dd = 60; float hd = 60.0f; //float v1 = (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; //float v2 = (sin((dd - (((int) col[1])%dd))/hd))*0.8f+.2f; //float v3 = (sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))*0.8f+.2f; if (node_cols.count(n) == 0) { float v1 = (rand() % 100) / 100.0f; // (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; float v2 = (rand() % 100) / 100.0f; // (sin((dd - (((int) col[1])%dd))/hd))*0.8f+.2f; float v3 = (rand() % 100) / 100.0f; //(sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))*0.8f+.2f; node_cols[n] = color(v1, v2, v3, 1.0); } color& mycolor = node_cols[n]; glColor4f(mycolor.r, mycolor.g, mycolor.b, .6f); for (set<CELL_INDEX_TYPE>::iterator sit = g.begin(); sit != g.end(); sit++) { CELL_INDEX_TYPE currentcid = *sit; float c[3]; coordinates(currentcid, c); glVertex3f(c[0]-1.0, c[1]-1.0, c[2]); glVertex3f(c[0]-1.0, c[1]+1.0, c[2]); glVertex3f(c[0]+1.0, c[1]+1.0, c[2]); glVertex3f(c[0]+1.0, c[1]-1.0, c[2]); } } } if (DRAW_BACKGROUND3) { nit = MSC->nodes.begin(); while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (! MSC->isAlive(n)) continue; if (n->index != 0) continue; set<CELL_INDEX_TYPE> g; MSC->fillGeometry(n, g); float col[3]; coordinates(n->cellid, col); int dd = 60; float hd = 60.0f; //float v1 = (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; //float v2 = (sin((dd - (((int) col[1])%dd))/hd))*0.8f+.2f; //float v3 = (sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))*0.8f+.2f; //float v1 = ((rand()%100) * 0.01 + .3); //sin(PI*((int) col[0]%dd)/((float) hd)))/2.0+.4f; //float v2 =((rand()%100) * 0.01 + .3);// (sin((dd - (((int) col[1])%dd))/hd))/2.0+.4f; //float v3 = ((rand()%100) * 0.01 + .3);///*(sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))/2.0+*/.4f; if (node_cols.count(n) == 0) { float v1 = (rand() % 100) / 100.0f; // (sin(PI*((int) col[0]%dd)/((float) hd)))*0.8f+.2f; float v2 = (rand() % 100) / 100.0f; // (sin((dd - (((int) col[1])%dd))/hd))*0.8f+.2f; float v3 = (rand() % 100) / 100.0f; //(sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))*0.8f+.2f; node_cols[n] = color(v1, v2, v3, 1.0); } color& mycolor = node_cols[n]; glColor4f(mycolor.r, mycolor.g, mycolor.b, .6f); //float v1 = (sin(PI*((int) col[0]%dd)/((float) hd)))/2.0+.4f; //float v2 = (sin((dd - (((int) col[1])%dd))/hd))/2.0+.4f; //float v3 = /*(sin(PI*((((int) col[0])%dd)-((int) col[1])%dd)/hd))/2.0+*/.4f; // //glColor4f(v2,v3, v1, .6f); for (set<CELL_INDEX_TYPE>::iterator sit = g.begin(); sit != g.end(); sit++) { CELL_INDEX_TYPE currentcid = *sit; float c[3]; coordinates(currentcid, c); glVertex3f(c[0]-1.0, c[1]-1.0, c[2]); glVertex3f(c[0]-1.0, c[1]+1.0, c[2]); glVertex3f(c[0]+1.0, c[1]+1.0, c[2]); glVertex3f(c[0]+1.0, c[1]-1.0, c[2]); } } } glEnd(); if (DRAW_GRID) { glLineWidth(line_width*2.1); glBegin(GL_LINES); glColor4f(0,0,0, .8); for (int i = 0; i < XMAX; i+=2) { glVertex3f(i, 0, 0); glVertex3f(i, YMAX, 0); } for (int i = 0; i < YMAX; i+=2) { glVertex3f(0, i, 0); glVertex3f(XMAX, i, 0); } glEnd(); glLineWidth(line_width*1.1); } if (g_draw_isolines) { glBegin(GL_LINES); vector<float> isovals; isovals.push_back(1e-10); for (int i = 0; i < 50; i++) { //isovals.push_back(isovals[i] * 2.0); isovals.push_back(fminmax.minval + ((i+1)/ 51.0f) * (fminmax.maxval - fminmax.minval)); } //isovals[0] = 0.00000001; //isovals[1] = 0.0000001; //isovals[2] = 0.000001; //isovals[3] = 0.00001; //isovals[4] = 0.0001; //isovals[5] = 0.001; //isovals[6] = 0.01; //isovals[7] = 0.1; //isovals[8] = 1.0; //isovals[9] = 10.0; //isovals[10] = 100.0; if (DRAW_ISOLINES) { glColor4f(1,1,1, .2); iteratorOperator& mall = G_mscmh->d_cells_iterator(2, it); for (mall.begin(it); mall.valid(it); mall.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) CELL_INDEX_TYPE cid = mall.value(it); for (int i = 0; i < isovals.size(); i++) { cellIterator fit; iteratorOperator& facets = G_mscmh->facets(cid, fit); for (facets.begin(fit); facets.valid(fit); facets.advance(fit)) { CELL_INDEX_TYPE eid = facets.value(fit); if (G_mscf->cell_value(eid) >= isovals[i] && G_msccb->lowest_facet_value(eid) < isovals[i]) { float c[2][3]; float vf[2]; int vert = 0; cellIterator vit; iteratorOperator& viter = G_mscmh->facets(eid,vit); for (viter.begin(vit); viter.valid(vit); viter.advance(vit)) { CELL_INDEX_TYPE vid = viter.value(vit); vf[vert]= G_mscf->cell_value(vid); coordinates(vid, c[vert++]); } float t = (isovals[i] - vf[0]) / (vf[1] - vf[0]); glVertex3f(c[0][0] + t*(c[1][0] - c[0][0]), c[0][1] + t*(c[1][1] - c[0][1]), c[0][2] + t*(c[1][2] - c[0][2])); } } } } } glEnd(); } // cellIterator it2; //iteratorOperator& ait = G_mscmh->all_cells_iterator(it); //for (ait.begin(it); ait.valid(it); ait.advance(it)) { // CELL_INDEX_TYPE cid = ait.value(it); // // //if (G_mscmh->dimension(cid) == 1) { //->get_dim_asc_man(cid) != 2) // drawArrow(cid); // //} //} glLineWidth(line_width*0.5); //if (g_draw_num_grad) { drawSEG(); //} glLineWidth(line_width*1.1); glBegin(GL_QUADS); //if (DRAW_PROBABILITIES1) { // //vector<idfpair>& v = G_msccb->getmaxvals(); //for (int i = 0; i < v.size(); i++) { // idfpair p = v[i]; // if (G_mscmh->dimension(p.id) != 0) continue; // if (p.prob < .98) { // glColor4f(1, 0,0, 0.5*(1-p.prob)); // float c[3]; // coordinates(p.id, c); // glVertex3f(c[0]-1.0, c[1]-1.0, c[2]); // glVertex3f(c[0]-1.0, c[1]+1.0, c[2]); // glVertex3f(c[0]+1.0, c[1]+1.0, c[2]); // glVertex3f(c[0]+1.0, c[1]-1.0, c[2]); // } //} //} //if (DRAW_PROBABILITIES2) { // //if (G_msccb != G_msccb2) { // vector<idfpair>& v2 = G_msccb2->getmaxvals(); // for (int i = 0; i < v2.size(); i++) { // idfpair p = v2[i]; // if (G_mscmh->dimension(p.id) != 2) continue; // if (p.prob < .98) { // glColor4f(0, 0,1, 0.5*(1-p.prob)); // float c[3]; // coordinates(p.id, c); // glVertex3f(c[0]-1.0, c[1]-1.0, c[2]); // glVertex3f(c[0]-1.0, c[1]+1.0, c[2]); // glVertex3f(c[0]+1.0, c[1]+1.0, c[2]); // glVertex3f(c[0]+1.0, c[1]-1.0, c[2]); // } // } //} //} glEnd(); if(DRAWNUMERICALDE) { glLineWidth(0.5); glColor4f(0.1, 1.0, 0.1, 0.3); int numread = gX*gY; if (! DRAWNUMERICALDE_INIT) { FILE* fin = fopen("source_dest.raw", "rb"); NUMDE_sources = new int[numread]; NUMDE_dests = new int[numread]; fread(NUMDE_sources, sizeof(int), numread, fin); fread(NUMDE_dests, sizeof(int), numread, fin); fclose(fin); DRAWNUMERICALDE_INIT = true; for (int i = 0; i < numread; i++) { if (sd2c.count(NUMDE_sources[i]) == 0 || sd2c[NUMDE_sources[i]].count(NUMDE_dests[i]) == 0) { TCOLOR ccc; ccc.r = (rand() % 100) * 0.01f; ccc.g = (rand() % 100) * 0.01f; ccc.b = (rand() % 100) * 0.01f; ccc.count = 1; sd2c[NUMDE_sources[i]][NUMDE_dests[i]] = ccc; } else { sd2c[NUMDE_sources[i]][NUMDE_dests[i]].count++; } } FILE* fout = fopen("DISSIPATIONELEMENTS_num.txt", "w"); //for (map<int, map<int, TCOLOR> >::iterator it = sd2c.begin(); // it != sd2c.end(); it++) { // int src = (*it).first; // int srcCID = (src % gX)*2 + (src / gX)*2 * XMAX; // float srcF = G_mscf->cell_value(srcCID); // for (map<int, TCOLOR>::iterator it2 = (*it).second.begin(); // it2 != (*it).second.end(); it2++) { // int dst = (*it2).first; // int dstCID = (dst % gX)*2 + (dst / gX)*2 * XMAX; // float dstF = G_mscf->cell_value(dstCID); // TCOLOR& c = (*it2).second; // fprintf(fout, "%f %f %f %d %f %d %d %f %f %f %f\n", // dstF,srcF, srcF-dstF, // c.count, distance(srcCID, dstCID), 0, 0, // (dst % gX)*2.0f, (dst / gX)*2.0f, (src % gX)*2.0f, (src / gX)*2.0f); // } //} fclose(fout); } // it != paiint, rmap.end(); it++) { // DE& d = (*it).second; // // float c1[3]; // coordinates(d.ndown->cellid, c1); // float c2[3]; // coordinates(d.nup->cellid, c2); // // fprintf(fout, "%f %f %f %d %f %d %d %f %f %f %f\n", d.ndown->value, d.nup->value, // d.nup->value - d.ndown->value, d.size, distance(d.nup->cellid, d.ndown->cellid), // d.interior, d.boundary, c1[0], c1[1], c2[0], c2[1]); // } //glBegin(GL_LINES); //for (int i = 0; i < numread; i++) { // //glVertex3f((float) (i % gX) * 2, float (i / gX) * 2, 0); // glVertex3f((float) (NUMDE_sources[i] % gX) * 2, float (NUMDE_sources[i] / gX) * 2, 0); // //glVertex3f((float) (i % gX) * 2, float (i / gX) * 2, 0); // glVertex3f((float) (NUMDE_dests[i] % gX) * 2, float (NUMDE_dests[i] / gX) * 2, 0); //} //glEnd(); //glPointSize(2.0); glBegin(GL_QUADS); for (int i = 0; i < numread; i++) { TCOLOR& ttt = sd2c[NUMDE_sources[i]][NUMDE_dests[i]]; glColor4f(ttt.r, ttt.g, ttt.b, 0.4); float x = (i % gX) * 2.0f; float y = (i / gX) * 2.0f; glVertex3f(x-1.0, y-1.0, 0); glVertex3f(x-1.0, y+1.0, 0); glVertex3f(x+1.0, y+1.0, 0); glVertex3f(x+1.0, y-1.0, 0); //glVertex3f((float) (i % gX) * 2, float (i / gX) * 2, 0); } glEnd(); glLineWidth(line_width*2.5); glBegin(GL_LINES); glColor3f(1,0,0); for (map<int, map<int, TCOLOR> >::iterator it = sd2c.begin(); it != sd2c.end(); it++) { int src = (*it).first; float srcx = (src % gX)*2.0f; float srcy = (src / gX)*2.0f; for (map<int, TCOLOR>::iterator it2 = (*it).second.begin(); it2 != (*it).second.end(); it2++) { int dst = (*it2).first; float dstx = (dst % gX)*2.0f; float dsty = (dst / gX)*2.0f; glVertex3f(srcx, srcy, 0.0); glVertex3f(dstx, dsty, 0.0); } } glEnd(); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); //glPointSize(point_size); glPointSize(point_size); glBegin(GL_POINTS); for (map<int, map<int, TCOLOR> >::iterator it = sd2c.begin(); it != sd2c.end(); it++) { int src = (*it).first; float srcx = (src % gX)*2.0f; float srcy = (src / gX)*2.0f; for (map<int, TCOLOR>::iterator it2 = (*it).second.begin(); it2 != (*it).second.end(); it2++) { int dst = (*it2).first; float dstx = (dst % gX)*2.0f; float dsty = (dst / gX)*2.0f; glColor3f( 0, 0,0.6); glVertex3f(dstx, dsty, 0.0); glColor3f(0.6, 0, 0); glVertex3f(srcx, srcy, 0.0); } } glEnd(); glPointSize(point_size*.75); glBegin(GL_POINTS); for (map<int, map<int, TCOLOR> >::iterator it = sd2c.begin(); it != sd2c.end(); it++) { int src = (*it).first; float srcx = (src % gX)*2.0f; float srcy = (src / gX)*2.0f; for (map<int, TCOLOR>::iterator it2 = (*it).second.begin(); it2 != (*it).second.end(); it2++) { int dst = (*it2).first; float dstx = (dst % gX)*2.0f; float dsty = (dst / gX)*2.0f; glColor3f( .3, .3,1); glVertex3f(dstx, dsty, 0.0); glColor3f(1, 0.3, 0.3); glVertex3f(srcx, srcy, 0.0); } } glEnd(); //// glBegin(GL_QUADS); //// iteratorOperator& all2 = G_mscmh->d_cells_iterator(2,it); ////for (all2.begin(it); all2.valid(it); all2.advance(it)) { //// //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) //// //drawArrow(all.value(it)); //// CELL_INDEX_TYPE cid = all2.value(it); //// //// if (G_mscg->get_dim_asc_man(cid) == 2) continue; //// if (G_mscg->get_dim_asc_man(cid) == 1) glColor4f(.2, 1.0, .3,.6); //// if (G_mscg->get_dim_asc_man(cid) == 0) glColor4f(.4, 1.0, .7,.6); //// //// float c[3]; //// coordinates(cid, c); //// glVertex3f(c[0]-1.0, c[1]-1.0, c[2]); //// glVertex3f(c[0]-1.0, c[1]+1.0, c[2]); //// glVertex3f(c[0]+1.0, c[1]+1.0, c[2]); //// glVertex3f(c[0]+1.0, c[1]-1.0, c[2]); //// //glVertex3f(c[0], c[1], c[2]); ////} ////glEnd(); } //glBegin(GL_POINTS); //cellIterator fuck; //iteratorOperator& allfuck = G_mscmh->all_cells_iterator(fuck); //for (allfuck.begin(fuck); allfuck.valid(fuck); allfuck.advance(fuck)) { // CELL_INDEX_TYPE asdf = allfuck.value(fuck); // DIM_TYPE ddd = G_mscmh->boundary_value(asdf); // G_mscg_TEMP->get_dim_asc_man(asdf); // if (ddd != 0) { // float c[3]; // coordinates(asdf, c); // if (ddd == 1) { // glColor3f(1,0,0); // } else if (ddd == 2) { // glColor3f(0,0,1); // } else if (ddd == 3) { // glColor3f(0,1,0); // } else { // glColor3f(0,0,0); // } // glVertex3f(c[0], c[1], 0); // } //} //glEnd(); if(DRAWDIMASCMAN) { glBegin(GL_QUADS); iteratorOperator& all2 = G_mscmh->d_cells_iterator(2,it); for (all2.begin(it); all2.valid(it); all2.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) //drawArrow(all.value(it)); CELL_INDEX_TYPE cid = all2.value(it); if (G_mscg->get_dim_asc_man(cid) == 2) continue; if (G_mscg->get_dim_asc_man(cid) == 1) glColor4f(.2, 1.0, .3,.6); if (G_mscg->get_dim_asc_man(cid) == 0) glColor4f(.4, 1.0, .7,.6); float c[3]; coordinates(cid, c); glVertex3f(c[0]-1.0, c[1]-1.0, c[2]); glVertex3f(c[0]-1.0, c[1]+1.0, c[2]); glVertex3f(c[0]+1.0, c[1]+1.0, c[2]); glVertex3f(c[0]+1.0, c[1]-1.0, c[2]); //glVertex3f(c[0], c[1], c[2]); } glEnd(); } if(DRAWGRAD) { iteratorOperator& all3 = G_mscmh->all_cells_iterator(it); for (all3.begin(it); all3.valid(it); all3.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) drawArrow(all3.value(it)); } } // white out stuff! if (clearcolor) glColor3f(1,1, 1); else glColor3f(0,0,0); glBegin(GL_QUADS); glVertex3f(-2.0,-2.0, 0.0); glVertex3f(2.0+XMAX,-2.0, 0.0); glVertex3f(2.0+XMAX,0.0, 0.0); glVertex3f(-2.0,0.0, 0.0); glVertex3f(-2.0,YMAX+2.0, 0.0); glVertex3f(2.0+XMAX,YMAX+2.0, 0.0); glVertex3f(2.0+XMAX,YMAX-1.0, 0.0); glVertex3f(-2.0,YMAX-1.0, 0.0); glVertex3f(-2.0,-2.0, 0.0); glVertex3f(-2.0,YMAX+2.0, 0.0); glVertex3f(0.0,YMAX+2.0, 0.0); glVertex3f(0.0,-2.0, 0.0); glVertex3f(XMAX-1.0,-2.0, 0.0); glVertex3f(XMAX-1.0,YMAX+2.0, 0.0); glVertex3f(XMAX+2.0,YMAX+2.0, 0.0); glVertex3f(XMAX+2.0,-2.0, 0.0); glEnd(); // //glBegin(GL_QUADS); //for (){ // // float sc = G_mscf->cell_value(cid); // sc = (sc - fminmax.minval) / (fminmax.maxval - fminmax.minval); // glColor3f(sc, sc, sc); // float c[3]; // coordinates(cid, c); // glVertex3f(c[0]-0.5, c[1]-0.5, c[2]); // glVertex3f(c[0]-0.5, c[1]+0.5, c[2]); // glVertex3f(c[0]+0.5, c[1]+0.5, c[2]); // glVertex3f(c[0]+0.5, c[1]-0.5, c[2]); // //glVertex3f(c[0], c[1], c[2]); //} //glEnd(); glDisable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(0.0, 0.0); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glLineWidth(line_width*2.5); //if (DRAWPOINTS) DrawDe(); if (g_use_test) { glBegin(GL_LINES); glColor4f(0.6, 0, .8, 1.0); iteratorOperator& mall = G_mscmh->d_cells_iterator(2, it); for (mall.begin(it); mall.valid(it); mall.advance(it)) { //if (G_mscg->get_dim_asc_man(all.value(it)) != 3) CELL_INDEX_TYPE cid = mall.value(it); cellIterator fit; int countintersects = 0; iteratorOperator& facets = G_mscmh->facets(cid, fit); for (facets.begin(fit); facets.valid(fit); facets.advance(fit)) { CELL_INDEX_TYPE eid = facets.value(fit); // if (G_mscf->cell_value(eid) >= myval && // G_msccb->lowest_facet_value(eid) < myval) { float c[2][3]; float vf[2]; int vert = 0; cellIterator vit; iteratorOperator& viter = G_mscmh->facets(eid, vit); for (viter.begin(vit); viter.valid(vit); viter.advance(vit)) { CELL_INDEX_TYPE vid = viter.value(vit); vf[vert] = G_mscf->cell_value(vid); coordinates(vid, c[vert++]); } float t = (myval - vf[0]) / (vf[1] - vf[0]); if (t < 0 || t >= 1.0f) continue; glVertex3f(c[0][0] + t*(c[1][0] - c[0][0]), c[0][1] + t*(c[1][1] - c[0][1]), c[0][2] + t*(c[1][2] - c[0][2])); countintersects++; // } } if (countintersects % 2 == 1) { printf("WHOATHERE uneven stuff\n"); //glVertex3f(0, 0, 0); } } glEnd(); } glLineWidth(line_width*3.1); for (int i = 0; i < MSC->arcs.size(); i++) { arc<float>* a = MSC->arcs[i]; if (! MSC->isAlive(a) || ! PassTest(a)) continue; if (a->lower->index == 0 && ! DRAWDSCLINES) continue; if (a->lower->index == 1 && ! DRAWASCLINES) continue; if (! ArcTest<Dim, FType>(a)) continue; if (a->lower->index == 0) { glColor4f(.1, .2, 1,.8); //printf("ASDFL:KJSDFL:KJSDKL:FJSD\n"); } else { glColor4f(1, .2, .1,.8); } vector<CELL_INDEX_TYPE> g; MSC->fillGeometry(a, g); glBegin(GL_LINE_STRIP); for (int j = 0; j < g.size(); j++) { float c[3]; coordinates(g[j], c); glVertex3f(c[0], c[1], c[2]); } glEnd(); } glLineWidth(line_width*2.5); for (int i = 0; i < MSC->arcs.size(); i++) { arc<float>* a = MSC->arcs[i]; if (!MSC->isAlive(a) || !PassTest(a)) continue; if (a->lower->index == 0 && ! DRAWDSCLINES) continue; if (a->lower->index == 1 && ! DRAWASCLINES) continue; if (! ArcTest<Dim, FType>(a)) continue; if (a->lower->index == 0) { glColor4f(.6, .6, .9,.3); //printf("ASDFL:KJSDFL:KJSDKL:FJSD\n"); } else { glColor4f(.9, .6, .6,.3); } //glColor4f(1,1,1,.5); vector<CELL_INDEX_TYPE> g; MSC->fillGeometry(a, g); glBegin(GL_LINE_STRIP); for (int j = 0; j < g.size(); j++) { float c[3]; coordinates(g[j], c); glVertex3f(c[0], c[1], c[2]); } glEnd(); } glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glPointSize(point_size); if (DRAWPOINTS){ glBegin(GL_POINTS); map<CELL_INDEX_TYPE, node<float>*>::iterator nit = MSC->nodes.begin(); while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (! MSC->isAlive(n) || ! PassTest(n)) continue; switch(n->index) { case 0: glColor3f(0,0,.6); break; case 1: glColor3f(0,.6,0); break; case 2: glColor3f(.6,0,0); break; default: glColor3f(.3, .7, .7); } float c[3]; coordinates(n->cellid, c); glVertex3f(c[0], c[1], c[2]); //glVertex3f(c[0]-0.6, c[1]-0.6, c[2]); //glVertex3f(c[0]-0.6, c[1]+0.6, c[2]); //glVertex3f(c[0]+0.6, c[1]+0.6, c[2]); //glVertex3f(c[0]+0.6, c[1]-0.6, c[2]); } glEnd(); glPointSize(point_size*.75); glBegin(GL_POINTS); nit = MSC->nodes.begin(); while (nit != MSC->nodes.end()) { node<float>* n = (*nit).second; nit++; if (!MSC->isAlive(n) || !PassTest(n)) continue; switch(n->index) { case 0: glColor3f(.3,.3,1); break; case 1: glColor3f(.3,1,.3); break; case 2: glColor3f(1,.3,.3); break; default: glColor3f(.3, .7, .7); } float c[3]; coordinates(n->cellid, c); glVertex3f(c[0], c[1], c[2]); //glVertex3f(c[0]-0.6, c[1]-0.6, c[2]); //glVertex3f(c[0]-0.6, c[1]+0.6, c[2]); //glVertex3f(c[0]+0.6, c[1]+0.6, c[2]); //glVertex3f(c[0]+0.6, c[1]-0.6, c[2]); } glEnd(); } glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); //if (draw_gradient) { // // glLineWidth(arrow_width); // // glColor3f(0, 0, 0); // // glBegin(GL_LINES); // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); // glEnable(GL_LIGHTING); // for (int dd = 1; dd <= 2; dd++) { // it = bcc->getCellIterator(dd); // while (it.isValid()) { // index_type cellid = *it.loc; // drawArrow<Dim, FType>(bcc, cellid); // it++; // } // } // glDisable(GL_LIGHTING); // // glEnd(); //} glEndList(); glEndList(); }; // // // // // if (! redrawstuff) { // glCallList(drawlist); // return; // } // // if (drawlist != -1) // glDeleteLists(drawlist, 1); // // drawlist = glGenLists(1); // glNewList(drawlist, GL_COMPILE_AND_EXECUTE); // // redrawstuff = false; // // glEnable(GL_POLYGON_OFFSET_FILL); // glPolygonOffset(1.0, 1.0); // // //// TRIANGLES // // // glColor3f(.2, .2, .2); // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); // if(! draw_flat) glEnable(GL_LIGHTING); // glBegin(GL_TRIANGLES); // IndexIterator it = bcc->getCellIterator(Dim); // while (it.isValid()) { // index_type cellid = *it.loc; // //total hack! // Simplex<FType>& s = bcc->cells[cellid]; // if (s.numberOfVerts != 3) { // printf("SDJKFHDS:LJFSKL:D\n"); // } // // BaseVertex<Dim>& v1 = bcc->verts[s.verts[0] ]; // BaseVertex<Dim>& v2 = bcc->verts[s.verts[1] ]; // BaseVertex<Dim>& v3 = bcc->verts[s.verts[2] ]; // // bool is_assigned = bcc->getAssigned(cellid); // //if (bcc->getNumUFacets(cellid) == 1) { // // glColor3f(0,1,0); // //} // if (is_assigned) { // // // unsigned char asif = bcc->getDimAscMan(cellid); // if (asif == 2) { // glColor3f(0.8, 0.8, 0.0); // } else if (asif == 1){ // glColor3f(0.3, 0.3, 0.9); // } else { // glColor3f(1.0, 0, 0); // } // } // // if (drawbasincolor) { // float* c = bsn->livingCellColor(cellid, glivingcounter); // glColor3f(c[0],c[1],c[2]); // } // // if (!draw_flat) { // // normal for lighting // Vector4 vv1; // vv1.vals[0] = v1.position[0]; // vv1.vals[1] = bcc->getValue(s.verts[0]); // vv1.vals[2] = v1.position[1]; // vv1.vals[3] = 1.0f; // Vector4 vv2; // vv2.vals[0] = v2.position[0]; // vv2.vals[1] = bcc->getValue(s.verts[1]); // vv2.vals[2] = v2.position[1]; // vv2.vals[3] = 1.0f; // Vector4 vv3; // vv3.vals[0] = v3.position[0]; // vv3.vals[1] = bcc->getValue(s.verts[2]); // vv3.vals[2] = v3.position[1]; // vv3.vals[3] = 1.0f; // for (int i = 0; i < 4; i++) { // vv1.vals[i] = vv3.vals[i] - vv1.vals[i]; // vv2.vals[i] = vv3.vals[i] - vv2.vals[i]; // } // Normalize4(&vv1); // Normalize4(&vv2); // Vector4 n = Cross(vv1, vv2); // Normalize4(&n); // glNormal3f(n.vals[0], n.vals[1], n.vals[2]); // } // // unsigned char asif = bcc->getDimAscMan(cellid); // if (! drawbasincolor && ! is_assigned /*&& bcc->getNumUFacets(cellid) == 0*/ && flat_funct) { // float nval = ((float) bcc->getValue(cellid) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // glColor3f(r,g,b); // // // } // if (! drawbasincolor && ! is_assigned /*&& bcc->getNumUFacets(cellid) == 0*/ && ! flat_funct){ // float nval = ((float) bcc->getValue(s.verts[0]) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // glColor3f(r,g,b); // } // // if (! draw_flat) // glVertex3f(v1.position[0],bcc->getValue(s.verts[0]),v1.position[1]); // else // glVertex3f(v1.position[0],bcc->getValue(cellid),v1.position[1]); // // if (! drawbasincolor && ! is_assigned /*&& bcc->getNumUFacets(cellid) == 0 */&& ! flat_funct){ // float nval = ((float) bcc->getValue(s.verts[1]) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // glColor3f(r,g,b); // } // if (!draw_flat) // glVertex3f(v2.position[0],bcc->getValue(s.verts[1]),v2.position[1]); // else // glVertex3f(v2.position[0],bcc->getValue(cellid),v2.position[1]); // // if (! drawbasincolor && ! is_assigned /*&& bcc->getNumUFacets(cellid) == 0*/ && ! flat_funct){ // float nval = ((float) bcc->getValue(s.verts[2]) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // glColor3f(r,g,b); // } // // if (! draw_flat) // glVertex3f(v3.position[0],bcc->getValue(s.verts[2]),v3.position[1]); // else // glVertex3f(v3.position[0],bcc->getValue(cellid),v3.position[1]); // // // // it++; // } // glEnd(); // if (! draw_flat) glDisable(GL_LIGHTING); // // // // // // // // // // // // LINES // glDisable(GL_POLYGON_OFFSET_FILL); // glPolygonOffset(0.0, 0.0); // // glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // glEnable(GL_BLEND); // glLineWidth(line_width); // // // // if (draw_mt) { // vector<index_type> vts; // mt->gl_fill_vertices2(vts); // // for (int i = 0; i < vts.size(); i+=2) { // BaseVertex<Dim>& v1 = bcc->verts[vts[i]]; // index_type b = vts[i+1]; // glColor3f( // (((float) ((b*321+93)%31))) /31.0f, // (((float) ((b*421+91)%51))) /51.0f, // (((float) ((b*221+92)%71))) /71.0f); // draw_earth(v1.position[0],bcc->getValue(vts[i]),v1.position[1], ballsize*3); // } // vts.clear(); // mt->gl_fill_arcs(vts); // glBegin(GL_LINES); // for (int i = 0; i < vts.size(); i++) { // BaseVertex<Dim>& v1 = bcc->verts[vts[i]]; // glVertex3f(v1.position[0],bcc->getValue(vts[i]) + EPSILON,v1.position[1]); // } // glEnd(); // vts.clear(); // } // // if (draw_edges) { // // glBegin(GL_LINES); // glColor4f(0.6, 0.5, 0.5, 1.0); // it = bcc->getCellIterator(1); // while (it.isValid()) { // index_type cellid = *it.loc; // //total hack! // Simplex<FType>& s = bcc->cells[cellid]; // if (s.numberOfVerts != 2) { // printf("SDJKFHDS:LJFSKL:D\n"); // } // // if (gusecutoffhack && bsn->livingCellValue(cellid, glivingcounter) < 0.01f) { // it++; // continue; // } // // BaseVertex<Dim>& v1 = bcc->verts[s.verts[0] ]; // BaseVertex<Dim>& v2 = bcc->verts[s.verts[1] ]; // if (drawbasincolor) { // float* c = bsn->livingCellColor(cellid, glivingcounter); // glColor3f(c[0],c[1],c[2]); // // glVertex3f(v1.position[0],bcc->getValue(s.verts[0]) + EPSILON,v1.position[1]); // glVertex3f(v2.position[0],bcc->getValue(s.verts[1]) + EPSILON,v2.position[1]); // // } else if (!draw_flat) { // if (bcc->getNumUFacets(cellid) == 1) { // // //glColor4f(0,1, 0, 1.0); // // // if (bcc->getAssigned(cellid)) { // // // if (bcc->getCritical(cellid)) { // glColor4f(1,0,0, 1.0); // } else { // // // unsigned char asif = bcc->getDimAscMan(cellid); // if (asif == 2) { // glColor4f(.6, .6, 0, 1.0); // } else if (asif == 1){ // glColor4f(0.3, 0.3, 0.9, 1.0); // } else { // glColor4f(1.0, 0, 0, 1.0); // } // } // } // // // // float c[3]; // // centroid<Dim,FType>(bcc, cellid, c); // // draw_earth(c[0],c[1],c[2],ballsize); // glVertex3f(v1.position[0],bcc->getValue(s.verts[0]) + EPSILON,v1.position[1]); // // // glVertex3f(v2.position[0],bcc->getValue(s.verts[1]) + EPSILON,v2.position[1]); // // } else { // if (! flat_funct) { // float nval = ((float) bcc->getValue(s.verts[0]) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // float nval2 = ((float) bcc->getValue(s.verts[1]) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r2 = red_scale(nval2); // float g2 = green_scale(nval2); // float b2 = blue_scale(nval2); // // float a = 0.3f; // glColor4f(r+a,g+a,b+a, 0.2); // glVertex3f(v1.position[0],bcc->getValue(s.verts[0]) + EPSILON,v1.position[1]); // // glColor4f(r2+a, g2+a, b2+a, 0.2); // glVertex3f(v2.position[0],bcc->getValue(s.verts[1]) + EPSILON,v2.position[1]); // } else { // float nval = ((float) bcc->getValue(cellid) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // float a = 0.3f; // glColor4f(r+a,g+a,b+a, 0.2); // glVertex3f(v1.position[0],bcc->getValue(s.verts[0]) + EPSILON,v1.position[1]); // glVertex3f(v2.position[0],bcc->getValue(s.verts[1]) + EPSILON,v2.position[1]); // } // } // // // } else { // float nval = ((float) bcc->getValue(cellid) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // // float a = 0.3f; // glColor4f(r+a,g+a,b+a, 0.2); // glVertex3f(v1.position[0],bcc->getValue(cellid) + EPSILON,v1.position[1]); // glVertex3f(v2.position[0],bcc->getValue(cellid) + EPSILON,v2.position[1]); // } // // // it++; // } // glEnd(); // // } // glDisable(GL_BLEND); // // // // VERTICES // it = bcc->getCellIterator(0); // index_type sizeshit = it.size; // while (it.isValid()) { // index_type cellid = *it.loc; // //total hack! // Simplex<FType>& s = bcc->cells[cellid]; // // // BaseVertex<Dim>& v1 = bcc->verts[s.verts[0] ]; // // if (s.verts[0] != cellid) printf("ERORORORORORORO\n"); // // // if (gusecutoffhack && bsn->livingCellValue(cellid, glivingcounter) < 0.01f) { // it++; // continue; // } // // if (drawbasincolor && bcc->getCritical(cellid)) { // float* c = bsn->livingCellColor(cellid, glivingcounter); // glColor3f(c[0],c[1],c[2]); // draw_earth(v1.position[0],bcc->getValue(s.verts[0]),v1.position[1], ballsize); // // } else if (bcc->getAssigned(cellid)) { // // if (bcc->getCritical(cellid)) { // glColor3f(1,0,0); // draw_earth(v1.position[0],bcc->getValue(s.verts[0]),v1.position[1], ballsize); // } else { // glColor3f(.6, .6, 0); // //draw_earth(v1.position[0],bcc->getValue(s.verts[0]),v1.position[1], ballsize/2.0); // } // //printf("reder min%d = %f %f %f\n", cellid,v1.position[0],bcc->getValue(s.verts[0]),v1.position[1] ); // // } else { // float nval = ((float) bcc->getValue(s.verts[0]) - (float) fminmax.minval) // /((float) fminmax.maxval - (float) fminmax.minval); // float r = red_scale(nval); // float g = green_scale(nval); // float b = blue_scale(nval); // glColor3f(r,g,b); // //draw_earth(v1.position[0],bcc->getValue(s.verts[0]),v1.position[1], ballsize/2.0); // } // // it++; // } // // //}; float gpers; int main(int argc, char** argv) { if (argc < 6) { printf( "Usage: main_2d_viewer rawfilename X Y Z computemode [persistence]\n\ -- rawfilename is the name of a float32 binary file size X*Y*Z*4 bytes\n\ -- X Y Z are dimensions of the data (for the 2d viewer, Z=1\n\ -- computemod: 0=randomized, 1=steepest, 2-5=variations of accurate (hint: use 1)\n\ -- persistence: if a floating point number is supplied for persistence, the tool is COMMAND LINE ONLY and will dump nodes/arcs of the complex.\n"); return 1; } for (int i =0; i < argc; i++) { printf("%d=%s\n", i, argv[i]); } char* filename = argv[1]; int X, Y, Z; sscanf(argv[2], "%d", &X); sscanf(argv[3], "%d", &Y); sscanf(argv[4], "%d", &Z); gX = X; gY = Y; gZ = Z; XMIN = 0; XMAX = X*2-1; YMIN = 0; YMAX = Y*2-1; ZMIN = 0; ZMAX = 1; int userand; sscanf(argv[5], "%d", &userand); bool command_line_only = false; if (argc > 6) { sscanf(argv[6], "%f", &gpers); command_line_only = true; } mscSize stest(X, Y, Z); printf("stest=%d\n", (int) stest.count()); //FILE* fouttest = fopen("test.raw", "wb"); //for (int i = 0; i < 3*3*3; i++) { // float val = (float) test_func[i]; // fwrite(&val, sizeof(float), 1, fouttest); //} //fclose(fouttest); // declare array factory mscArrayFactory a(REGULAR_ARRAY); // load data mscRegularRawDataHandler<float>* test_data; test_data = new mscRegularRawDataHandler<float>(); test_data->load_data(filename, X*Y*Z, &a); //test_data->logify(); //test_data->negate(); mscNegatingDataHandler<float>* ndh = new mscNegatingDataHandler<float>(test_data); #ifdef WIN32 DWORD globalStart = GetTickCount(); #endif printf("Computing discrete gradient: \n"); // create mesh handler mscRegularGrid2DImplicitMeshHandler* bmsh = new mscRegularGrid2DImplicitMeshHandler(X,Y); // tests!!! //printf("Go there\n"); cellIterator it; iteratorOperator& fit = bmsh->cofacets(1, it); fit.begin(it); while (fit.valid(it)) { printf("neighbor=%llu\n", fit.value(it)); fit.advance(it); } // ? ultimitely, what do I have to do with the data to use ttk // ? why use 3d mesh function // ?mesh handler assigns face/coface where id of sattle v critical done // with gradient field? once assigned every other approach for 2d used? // ? For TTK, can it compute the triangulation or do I assign the triang- // ulation and it traverses. (How to build triangulation, can it build) // create mesh function mscRegularGrid3DMeshFunction<float>* bmf = new mscRegularGrid3DMeshFunction<float>(test_data, bmsh, &a); bmf->initialize(); mscRegularGrid3DGradientField* bgf = new mscRegularGrid3DGradientField(bmsh, &a); // test the gradient builder! mscSimpleGradientBuilder<float>* mscb = new mscSimpleGradientBuilder<float>(bmf, bmsh, bgf, &a); mscSimpleRandomGradientBuilder<float>* mscrb = new mscSimpleRandomGradientBuilder<float>(bmf, bmsh, bgf, &a); //mscTwoWay3DGradientBuilder<float>* msctwb = // new mscTwoWay3DGradientBuilder<float>(bmf, bmsh, bgf, &a); char gradname[2048]; sprintf(gradname, "%s.grad", argv[1]); if (!bgf->load_from_file(gradname)) { mscConvergentGradientBuilder<float>* msccb = new mscConvergentGradientBuilder<float>(bmf, bmsh, bgf, &a); G_msccb2 = msccb; G_msccb = msccb; if (userand == 0) { printf("using randomized gradient\n"); mscrb->computeGradient(); } else if (userand == 1) { printf("using greedy gradient\n"); mscb->computeGradient(); } else if (userand == 2) { printf("using convergent gradient - 1 pass\n"); msccb->computeGradient(); } else if (userand == 3) { printf("using convergent gradient - 2 pass\n"); msccb->computeGradient(); mscComplementMeshHandler* cmh = new mscComplementMeshHandler(bmsh); mscNegatingMeshFunction<float>* nmf = new mscNegatingMeshFunction<float>(bmf); mscModifiedBoundaryMeshHandler* mbmh = new mscModifiedBoundaryMeshHandler(cmh, bgf); mscRegularGrid3DGradientField* bgf2 = new mscRegularGrid3DGradientField(bmsh, &a); mscConvergentGradientBuilder<float>* msccb2 = new mscConvergentGradientBuilder<float>(nmf, mbmh, bgf2, &a); msccb2->computeGradient(); mscRegularGrid3DGradientField* tempgf = bgf; cellIterator it; iteratorOperator& all_cells = bmsh->all_cells_iterator(it); for (all_cells.begin(it); all_cells.valid(it); all_cells.advance(it)) { CELL_INDEX_TYPE cid = all_cells.value(it); bgf2->set_dim_asc_man(cid, bgf->get_dim_asc_man(cid)); } bgf = bgf2; bgf->resetMeshHandler(bmsh); //char ufilename1[1024]; //sprintf(ufilename1, "%s.asc", filename); //test_data->dump_vals(ufilename1, X, Y, Z, msccb->getmaxvals()); //sprintf(ufilename1, "%s.asc.prob", filename); //char ufilename2[1024]; //sprintf(ufilename2, "%s.dsc", filename); //test_data->dump_vals(ufilename2, X, Y, Z, msccb2->getmaxvals()); // sprintf(ufilename2, "%s.dsc.prob", filename); //char ufilename3[1024]; //sprintf(ufilename3, "%s.both", filename); //FILE* ff1 = fopen(ufilename1, "rb"); //FILE* ff2 = fopen(ufilename2, "rb"); //FILE* ffout = fopen(ufilename3, "wb"); //while (! feof(ff1)) { // float v1, v2; // fread(&v1, sizeof(float), 1, ff1); // fread(&v2, sizeof(float), 1, ff2); // float res = (0.5-0.5f*v1) + 0.5f - (0.5-0.5f*v2); // fwrite(&res, sizeof(float), 1, ffout); //} //fclose(ff1); //fclose(ff2); //fclose(ffout); G_msccb = msccb; G_msccb2 = msccb2; } else if (userand == 4) { printf("using convergent2 gradient - 2 pass\n"); mscComplementMeshHandler* cmh = new mscComplementMeshHandler(bmsh); mscNegatingMeshFunction<float>* nmf = new mscNegatingMeshFunction<float>(bmf); mscRegularGrid3DGradientField* bgf2 = new mscRegularGrid3DGradientField(bmsh, &a); mscConvergentGradientBuilder<float>* msccb2 = new mscConvergentGradientBuilder<float>(nmf, cmh, bgf2, &a); msccb2->computeGradient(); mscModifiedBoundaryMeshHandler* mbmh = new mscModifiedBoundaryMeshHandler(bmsh, bgf2); mscConvergentGradientBuilder<float>* msccb3 = new mscConvergentGradientBuilder<float>(bmf, mbmh, bgf, &a); msccb3->computeGradient(); G_msccb = msccb3; G_msccb2 = msccb2; //mscRegularGrid3DGradientField* tempgf = bgf; // //cellIterator it; //iteratorOperator& all_cells = bmsh->all_cells_iterator(it); //for (all_cells.begin(it); all_cells.valid(it); all_cells.advance(it)) { // CELL_INDEX_TYPE cid = all_cells.value(it); // bgf2->set_dim_asc_man(cid, bgf->get_dim_asc_man(cid)); //} //bgf = bgf2; //bgf->resetMeshHandler(bmsh); } else if (userand == 5) { printf("using convergent3 gradient - 2 pass\n"); mscComplementMeshHandler* cmh = new mscComplementMeshHandler(bmsh); //mscDumbStoringMinFunction<float>* dsminf = // new mscDumbStoringMinFunction<float>(test_data, bmsh, &a); //dsminf->initialize(); mscNegatingMeshFunction<float>* nmf = new mscNegatingMeshFunction<float>(bmf); mscRegularGrid3DGradientField* bgf2 = new mscRegularGrid3DGradientField(bmsh, &a); mscConvergentGradientBuilder<float>* msccb2 = new mscConvergentGradientBuilder<float>(nmf, cmh, bgf2, &a); msccb2->computeGradient(); mscModifiedBoundaryMeshHandler* mbmh = new mscModifiedBoundaryMeshHandler(bmsh, bgf2); mscConvergentGradientBuilder<float>* msccb3 = new mscConvergentGradientBuilder<float>(bmf, mbmh, bgf, &a); msccb3->computeGradient(); G_msccb = msccb3; G_msccb2 = msccb2; //mscRegularGrid3DGradientField* tempgf = bgf; // //cellIterator it; //iteratorOperator& all_cells = bmsh->all_cells_iterator(it); //for (all_cells.begin(it); all_cells.valid(it); all_cells.advance(it)) { // CELL_INDEX_TYPE cid = all_cells.value(it); // bgf2->set_dim_asc_man(cid, bgf->get_dim_asc_man(cid)); //} //bgf = bgf2; //bgf->resetMeshHandler(bmsh); } else if (userand == 6/* && argc > 6*/) { // READ IN SEGMENTATION //mscb->computeGradient(); USE_SEG = true; FILE* fseg = fopen("source_dest2.raw", "rb"); int numV = X * Y; int numC = (X - 1) * (Y - 1); int* ascID = new int[numV]; int* dscID = new int[numC]; fread(ascID, sizeof(int), numV, fseg); fread(dscID, sizeof(int), numC, fseg); fclose(fseg); G_mscg_TEMP = new mscRegularGrid3DGradientField(bmsh, &a); classes = new mscPreClassifier(ascID, dscID, bmsh); // THIS IS A MISNOMER all it actually does is set mscSimpleConstrainedGradientBuilder<float>* scgb = new mscSimpleConstrainedGradientBuilder<float>(classes, bmf, bmsh, G_mscg_TEMP, &a); scgb->computeGradient(); mscModifiedBoundaryMeshHandler* mbmh = new mscModifiedBoundaryMeshHandler(bmsh, G_mscg_TEMP); mscSimpleGradientBuilder<float>* mscb3 = new mscSimpleGradientBuilder<float>(bmf, mbmh, bgf, &a); mscb3->computeGradient(); //mscSimpleConstrainedGradientBuilder<float>* scgb2 = // new mscSimpleConstrainedGradientBuilder<float>(classes, bmf,mbmh,bgf, &a); //scgb2->computeGradient(); //#define HACK #ifdef HACK G_mscmh = mbmh; #endif } else if (userand == 7) { printf("using assised gradient computation\n"); mscAssistedGradientBuilder<float>* magb = new mscAssistedGradientBuilder<float>(bmf, bmsh, bgf, filename, &a); magb->computeGradient(); } //else if (userand == 7) { // printf("using constrained convergent gradient - 2 pass\n"); // USE_SEG = true; // FILE* fseg = fopen("source_dest2.raw", "rb"); // int numV = X * Y; // int numC = (X-1) * (Y-1); // int* ascID = new int[numV]; // int* dscID = new int[numC]; // fread(ascID, sizeof(int), numV, fseg); // fread(dscID, sizeof(int), numC, fseg); // fclose(fseg); // G_mscg_TEMP = // new mscRegularGrid3DGradientField(bmsh, &a); // // classes = new mscPreClassifier(ascID, dscID, bmsh); // // THIS IS A MISNOMER all it actually does is set // mscSimpleConstrainedGradientBuilder<float>* scgb = // new mscSimpleConstrainedGradientBuilder<float>(classes, bmf,bmsh,G_mscg_TEMP, &a); // scgb->computeGradient(); // mscModifiedBoundaryMeshHandler* mbmh = // new mscModifiedBoundaryMeshHandler(bmsh, G_mscg_TEMP); // mscConvergentGradientBuilder<float>* msccbX = // new mscConvergentGradientBuilder<float>(bmf, mbmh, bgf, &a); // msccbX->computeGradient(); // mscComplementMeshHandler* cmh = // new mscComplementMeshHandler(mbmh); // mscNegatingMeshFunction<float>* nmf = // new mscNegatingMeshFunction<float>(bmf); // mscModifiedBoundaryMeshHandler* mbmh2 = // new mscModifiedBoundaryMeshHandler(cmh, bgf); // mscRegularGrid3DGradientField* bgf2 = // new mscRegularGrid3DGradientField(bmsh, &a); // mscConvergentGradientBuilder<float>* msccb2 = // new mscConvergentGradientBuilder<float>(nmf, mbmh2, bgf2, &a); // msccb2->computeGradient(); // mscRegularGrid3DGradientField* tempgf = bgf; // cellIterator it; // iteratorOperator& all_cells = bmsh->all_cells_iterator(it); // for (all_cells.begin(it); all_cells.valid(it); all_cells.advance(it)) { // CELL_INDEX_TYPE cid = all_cells.value(it); // bgf2->set_dim_asc_man(cid, bgf->get_dim_asc_man(cid)); // } // bgf = bgf2; // bgf->resetMeshHandler(bmsh); // //char ufilename1[1024]; // //sprintf(ufilename1, "%s.asc", filename); // //test_data->dump_vals(ufilename1, X, Y, Z, msccb->getmaxvals()); // //sprintf(ufilename1, "%s.asc.prob", filename); // //char ufilename2[1024]; // //sprintf(ufilename2, "%s.dsc", filename); // //test_data->dump_vals(ufilename2, X, Y, Z, msccb2->getmaxvals()); // // sprintf(ufilename2, "%s.dsc.prob", filename); // //char ufilename3[1024]; // //sprintf(ufilename3, "%s.both", filename); // //FILE* ff1 = fopen(ufilename1, "rb"); // //FILE* ff2 = fopen(ufilename2, "rb"); // //FILE* ffout = fopen(ufilename3, "wb"); // //while (! feof(ff1)) { // // float v1, v2; // // fread(&v1, sizeof(float), 1, ff1); // // fread(&v2, sizeof(float), 1, ff2); // // float res = (0.5-0.5f*v1) + 0.5f - (0.5-0.5f*v2); // // fwrite(&res, sizeof(float), 1, ffout); // //} // //fclose(ff1); // //fclose(ff2); // //fclose(ffout); // G_msccb = msccb; // G_msccb2 = msccb2; // } bgf->output_to_file(gradname); } G_mscg = bgf; #ifdef HACK if(userand != 6) { #endif G_mscmh = bmsh; #ifdef HACK } #endif G_mscf = bmf; #ifdef WIN32 DWORD globalEnd = GetTickCount(); printf(" --Computed discrete gradient in %.3f seconds\n", (globalEnd - globalStart) / 1000.0); #endif #ifndef HACK if (userand == 6) { MSC = new RestrictedMSC<float>(bgf, G_mscmh, bmf, G_mscg_TEMP); printf("using restricted\n"); } else { #endif MSC = new BasicMSC<float>(bgf, G_mscmh, bmf); #ifndef HACK } #endif MSC->ComputeFromGrad(); MSC->ComputeHeirarchy(); MSC->WriteCancelHistory(); if (command_line_only) { MSC->setPercentPersistence(gpers); MSC->WriteComplex(argv[1]); return 1; } if (argc > 6) MSC->setAbsolutePersistence(gpers); else MSC->setPercentPersistence(5.0f); cellIterator ita; iteratorOperator& all = bmsh->all_cells_iterator( ita); //all.begin(ita); CELL_INDEX_TYPE cid = all.value(ita); fminmax.maxval = bmf->cell_value(0); fminmax.minval = bmf->cell_value(0); for (all.begin(ita); all.valid(ita); all.advance(ita)) { CELL_INDEX_TYPE cid = all.value(ita); float tmp = bmf->cell_value(cid); if (tmp > fminmax.maxval) fminmax.maxval = tmp; if (tmp < fminmax.minval) fminmax.minval = tmp; } printf("maxvalue = %f, minvalue = %f\n", fminmax.maxval, fminmax.minval); // const unsigned char purple[] = {255, 0, 255}; // cimg_library::CImg<unsigned char>(640, 400, 1, 3, 0).draw_text(100, 100, "Hello World", purple).display("my first casasfd"); /* int array[10]; for (int i=0; i<10; i++) { array[i] = 2*i+5; } IndexIterator ii(array, 5); while (ii.isValid()) { cout << *ii.loc << endl; ii++; }*/ Initialize_GLUT(argc, argv); return 0; } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ////////// //////////////// ////////// GLUT STUFF DOWN HERE //////////////// ////////// //////////////// ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// Matrix4 mat; float translateoff[3]; bool g_mouseActive; int mainWindow; // Initial size of graphics window. const int WIDTH = 1200; const int HEIGHT = 1200; // Current size of window. int width = WIDTH; int height = HEIGHT; // Mouse positions, normalized to [0,1]. double xMouse = 0.0; double yMouse = 0.0; // Bounds of viewing frustum. double nearPlane = 0.1; double farPlane = 30000; // Viewing angle. double fovy = 40.0; // Variables. double alpha = 0; // Set by idle function. double beta = 0; // Set by mouse X. double mdistance = - (farPlane - nearPlane) / 2; // Set by mouse Y. float dist; GLfloat light_diffuse[] = {0.8, 0.8, 0.8, 1.0}; /* Red diffuse light. */ GLfloat light_position[] = {1.0, 1.0, 1.0, 0.0}; /* Infinite light location. */ float diffuseLight[] = {0.8f, 0.8f, 0.8f, 1.0f}; float specularLight[] = {1.0f, 1.0f, 1.0f, 1.0f}; float LightPosition[] = {1.1f, 0.0f, 8.0f, 1.0f}; struct Quat { float x, y, z, w; }; Quat times(Quat a, Quat b) { Quat res; res.w = a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z; res.x = a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y; res.y = a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x; res.z = a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w; return res; } Quat rotation(Vector4 v, float angle) { Quat res; Normalize3(&v); res.w = cosf(angle/2.0); float tmp = sinf(angle/2.0); res.x = v.vals[0] * tmp; res.y = v.vals[1] * tmp; res.z = v.vals[2] * tmp; return res; } Matrix4 rotmatrix; Quat rotationtotal; void resetQuat(Quat &q) { q.x = 0; q.y = 0; q.z = 0; q.w = 1; } void setRotQuat(Matrix4 &m, Quat &q){ { float x2 = 2.0f * q.x, y2 = 2.0f * q.y, z2 = 2.0f * q.z; float xy = x2 * q.y, xz = x2 * q.z; float yy = y2 * q.y, yw = y2 * q.w; float zw = z2 * q.w, zz = z2 * q.z; m.vals[ 0] = 1.0f - ( yy + zz ); m.vals[ 1] = ( xy - zw ); m.vals[ 2] = ( xz + yw ); m.vals[ 3] = 0.0f; float xx = x2 * q.x, xw = x2 * q.w, yz = y2 * q.z; m.vals[ 4] = ( xy + zw ); m.vals[ 5] = 1.0f - ( xx + zz ); m.vals[ 6] = ( yz - xw ); m.vals[ 7] = 0.0f; m.vals[ 8] = ( xz - yw ); m.vals[ 9] = ( yz + xw ); m.vals[10] = 1.0f - ( xx + yy ); m.vals[11] = 0.0f; m.vals[12] = 0.0f; m.vals[13] = 0.0f; m.vals[14] = 0.0f; m.vals[15] = 1.0f; } } void reset_view() { resetQuat(rotationtotal); mat = MIdentity(); dist = 140*(XMAX-XMIN); } void render_view (){ resetQuat(rotationtotal); mat = MIdentity(); dist = 240*(ZMAX-ZMIN); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //glMultMatrixf(mat.vals); //glRotatef(-50, 0,1,0); Vector4 v; v.vals[0] = 0; v.vals[1] = 1; v.vals[2] = 0; rotationtotal = rotation(v, -50*PI/180.0); setRotQuat(rotmatrix, rotationtotal); glMultMatrixf(rotmatrix.vals); //glMultMatrixf(mat.vals); //glGetFloatv(GL_MODELVIEW_MATRIX, mat.vals); } float read_p_from_file() { FILE* fin = fopen("input_persistence.txt", "r"); float f; fscanf(fin, "%f\n", &f); //printf("read %f\n", f); fclose(fin); return f; } float read_t_from_file() { FILE* fin = fopen("input_value.txt", "r"); float f; fscanf(fin, "%f\n", &f); //printf("read %f\n", f); fclose(fin); return f * fminmax.maxval + fminmax.minval; } float oldf = -1.0; void myidle() { // cimg_library::cimg::sleep(10); #ifdef WIN32 Sleep(50); #else usleep(50); #endif float newf = read_p_from_file(); if (newf != oldf) { oldf = newf; MSC->setPercentPersistence(oldf); redrawstuff = true; glutPostRedisplay(); } if (g_use_test) { float ttestval = read_t_from_file(); if (ttestval != myval) { myval = ttestval; redrawstuff = true; glutPostRedisplay(); } } } bool dbbox = true; void display() { glPointSize(4.0); if (clearcolor) { glClearColor(1,1,1,1); } else { glClearColor(0,0,0,1); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // enable crystal ball transform here glTranslatef( 0,0,- dist / 100); glTranslatef(- translateoff[0], - translateoff[1], - translateoff[2]); setRotQuat(rotmatrix, rotationtotal); glMultMatrixf(rotmatrix.vals); glTranslatef(-(XMAX - XMIN)/2.0 - XMIN, -(YMAX - YMIN)/2.0 - YMIN, -(ZMAX - ZMIN)/2.0 - ZMIN); glEnable(GL_DEPTH_TEST); // draw the complex // if (dbbox) { // if (clearcolor) // glColor3f(.05, .05, .05); // else // glColor3f(.9,.9,.9); // glBegin(GL_LINES); // glVertex3f(0, 0, 0); // glVertex3f(XDIM-1 , 0, 0); // glVertex3f(0, YDIM-1, 0); // glVertex3f(XDIM-1 , YDIM-1, 0); // glVertex3f(0, 0, ZDIM-1); // glVertex3f(XDIM-1 , 0, ZDIM-1); // glVertex3f(0, YDIM-1, ZDIM-1); // glVertex3f(XDIM-1 , YDIM-1, ZDIM-1); // glVertex3f(0, 0, 0); // glVertex3f(0, YDIM-1, 0); // glVertex3f(XDIM-1, 0, 0); // glVertex3f(XDIM-1, YDIM-1, 0); // glVertex3f(0, 0, ZDIM-1); // glVertex3f(0, YDIM-1, ZDIM-1); // glVertex3f(XDIM-1, 0, ZDIM-1); // glVertex3f(XDIM-1, YDIM-1, ZDIM-1); // glVertex3f(0, 0, 0); // glVertex3f(0, 0, ZDIM-1); // glVertex3f(XDIM-1, 0, 0); // glVertex3f(XDIM-1, 0, ZDIM-1); // glVertex3f(0, YDIM-1, 0); // glVertex3f(0, YDIM-1, ZDIM-1); // glVertex3f(XDIM-1, YDIM-1, 0); // glVertex3f(XDIM-1, YDIM-1, ZDIM-1); // glEnd(); // } drawStuff<2, float>(); glutSwapBuffers(); } void *gl_copy_pixels = NULL; void reshapeMainWindow (int newWidth, int newHeight) { width = newWidth; height = newHeight; if (gl_copy_pixels != NULL) { delete(gl_copy_pixels); gl_copy_pixels = NULL; } glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fovy, GLfloat(width) / GLfloat(height), nearPlane, farPlane); glutPostRedisplay(); } int gcounter; void outputimage() { unsigned char *rpixels = new unsigned char[width*height*3]; unsigned char *mpixels = new unsigned char[width*height*3]; char name[1024]; sprintf(name, "im%d_%d.bmp", gcounter++, seed); glReadPixels(0,0,width,height, GL_RGB, GL_UNSIGNED_BYTE, rpixels); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int id1 = x + y*width; int id2 = x + (height - 1 - y)*width; mpixels[id1] = rpixels[id2*3]; mpixels[id1 +width*height] = rpixels[id2*3+1]; mpixels[id1 +2*width*height] = rpixels[id2*3+2]; } } #ifdef WIN32 CImg< unsigned char > img(mpixels, width, height,1, 3, false); img.save_bmp(name); #endif delete(rpixels); delete(mpixels); return; } void makeSequence() { //for (int i = 0; i < total_order.size(); i++) { // usc->setAssigned(total_order[i], false); //} //for (int i = 0; i < total_pqlist.size(); i++) { // usc->setNumUFacets(total_pqlist[i], 0); //} //int nc = total_counts[0]; //for (int i = 0; i < nc; i++) { // usc->setNumUFacets(total_pqlist[i], 1); //} //char fname[1024]; //int counter = 0; //for (int i = 0; i < 700/*total_order.size()*/; i++) { // sprintf(fname, "out/full_%05d.png", counter++); // printf("outputtting: %s\n", fname); // if (usc->getCritical(total_order[i])) { // for (int j = nc; j < nc+total_counts[i+1]; j++) { // usc->setNumUFacets(total_pqlist[j], 1); // } // nc += total_counts[i+1]; // usc->setAssigned(total_order[i], true); // usc->setNumUFacets(total_order[i], 0); // glutPostRedisplay(); // display(); // glutSwapBuffers(); // // outputimage(fname); // } else { // for (int j = nc; j < nc+total_counts[i+1]; j++) { // usc->setNumUFacets(total_pqlist[j], 1); // } // nc += total_counts[i+1]; // usc->setAssigned(total_order[i++], true); // for (int j = nc-1; j < nc+total_counts[i]; j++) { // usc->setNumUFacets(total_pqlist[j], 1); // } // nc += total_counts[i]; // usc->setAssigned(total_order[i], true); // display(); // glutSwapBuffers(); // //glutPostRedisplay(); // // outputimage(fname); // } //} } void graphicKeys (unsigned char key, int x, int y) { switch (key) { case 'o': outputimage(); break; case 't': draw_mt = ! draw_mt; redrawstuff = true; //bsn->dumpBasinCountPerPersistence("basins.txt"); break; case 'y': char tmpname[1024]; //sprintf(tmpname, "bsizes_%.6u.txt", glivingcounter); //bsn->dumpBasinSizes(tmpname, glivingcounter); break; case 'h': gusecutoffhack = ! gusecutoffhack; redrawstuff = true; break; case '1': MSC->setPercentPersistence(0); redrawstuff = true; break; case '2': MSC->setFirstNonzeroPersistence(2); redrawstuff = true; break; case '3': MSC->setPercentPersistence(2); redrawstuff = true; break; case '4': MSC->addPersistence(1); // glivingcounter = bsn->getDestrCount(0.01f); redrawstuff = true; break; case '5': MSC->addPersistence(-1); // glivingcounter = bsn->getDestrCount(0.05f); redrawstuff = true; break; case '6': MSC->setPercentPersistence(1); redrawstuff = true; break; case '7': MSC->setPercentPersistence(6); redrawstuff = true; break; case '8': MSC->setPercentPersistence(8); redrawstuff = true; break; case '9': MSC->setPercentPersistence(99); redrawstuff = true; break; case 'c': // drawbasincolor = !drawbasincolor; redrawstuff = true; break; case 'j': // if (glivingcounter > 0) // glivingcounter--; redrawstuff = true; break; case 'k': // if (glivingcounter < bsn->num_destroyed()) // glivingcounter++; redrawstuff = true; break; case 'A': DRAW_BACKGROUND2 = !DRAW_BACKGROUND2; redrawstuff = true; break; case 'D': DRAW_BACKGROUND3 = !DRAW_BACKGROUND3; redrawstuff = true; break; case 'b': DRAW_BACKGROUND = !DRAW_BACKGROUND; redrawstuff = true; break; case 'B': clearcolor = !clearcolor; redrawstuff = true; break; case 'm': { /* for (int i=0; i<1000; i++) { if (cutoff < total_order.size()) { if (usc->getCritical(total_order[cutoff])){ usc->setAssigned(total_order[cutoff], true); if (cutoff < total_order.size()-1) cutoff++; } else { usc->setAssigned(total_order[cutoff], true); cutoff++; usc->setAssigned(total_order[cutoff], true); cutoff++; } } } */ } redrawstuff = true; break; case 'n': DRAWPOINTS = !DRAWPOINTS; redrawstuff = true; break; case 'M': { // for (int i=0; i<1; i++) { // if (cutoff < total_order.size()) { //if (usc->getCritical(total_order[cutoff])){ // usc->setAssigned(total_order[cutoff], true); // if (cutoff < total_order.size()-1) cutoff++; //} else { // usc->setAssigned(total_order[cutoff], true); // cutoff++; // usc->setAssigned(total_order[cutoff], true); // cutoff++; // } // } // } } redrawstuff = true; break; case 's': makeSequence(); break; case 'i': g_draw_isolines = !g_draw_isolines; redrawstuff = true; break; case 'T': g_use_test = !g_use_test; redrawstuff = true; break; case 'p': DRAW_PROBABILITIES1 = !DRAW_PROBABILITIES1; redrawstuff = true; break; case 'P': DRAW_PROBABILITIES2 = !DRAW_PROBABILITIES2; redrawstuff = true; break; case '[': line_width *= 1.2f; redrawstuff = true; break; case ']': line_width /= 1.2f; redrawstuff = true; break; case '{': point_size *= 1.2f; redrawstuff = true; break; case '}': point_size /= 1.2f; redrawstuff = true; break; case 'e': draw_edges = !draw_edges; redrawstuff = true; break; case 'F': flat_funct = !flat_funct; redrawstuff = true; break; case 'f': draw_flat = !draw_flat; redrawstuff = true; break; case 'G': DRAW_GRID = !DRAW_GRID; redrawstuff = true; break; case 'K': DRAWNUMERICALDE = !DRAWNUMERICALDE; redrawstuff = true; break; case 'N': USE_SEG = !USE_SEG; redrawstuff = true; break; case '<': USE_SEG_LINES = !USE_SEG_LINES; redrawstuff = true; break; case '>': USE_SEG_AMAP = !USE_SEG_AMAP; redrawstuff = true; break; case '?': USE_SEG_DMAP = !USE_SEG_DMAP; redrawstuff = true; break; case 'g': draw_gradient = !draw_gradient; redrawstuff = true; break; case '(': arrow_width *= 1.2f; redrawstuff = true; break; case ')': arrow_width /= 1.2f; redrawstuff = true; break; case 'x': ballsize *= 1.2f; redrawstuff = true; break; case 'z': ballsize /= 1.2f; redrawstuff = true; break; //case 'w': // { // char filename[1024]; // sprintf(filename, "out.bmp"); // outputimage(filename); // break; // } case 'L': DumpLines<2,float>(); break; case 'a': DRAWASCLINES = ! DRAWASCLINES; redrawstuff = true; break; case 'd': DRAWDSCLINES = ! DRAWDSCLINES; redrawstuff = true; break; case 'r': reset_view(); break; case 'q': exit(1); break; } glutPostRedisplay(); } int xold; int yold; Vector4 vstart; int buttonstate; void mouseClicked (int button, int state, int x, int y) { xold = x; yold = y; //printf("Mouse Clicked! button = %d, %d x = %d y = %d\n", state, button, x, y); buttonstate= button; if (state == GLUT_DOWN) { g_mouseActive = true; } else { g_mouseActive = false; } glutPostRedisplay(); } void mouseMovement (int mx, int my) { //printf("%d, %d\n", mx, my); if (! g_mouseActive) return; if (buttonstate == 2) { int dd = XMAX-XMIN; dist += dd*(my - yold); yold = my; } if (buttonstate == 1 || buttonstate == 0) { float ldim = (width > height ? width : height); vstart.vals[0] = xold - .5 * width ; vstart.vals[1] = .5 * height - yold; if ((.5 * ldim) * (.5* ldim) - vstart.vals[0]*vstart.vals[0] - vstart.vals[1]*vstart.vals[1] <= 0) return; vstart.vals[2] = sqrt((.5 * ldim) * (.5* ldim) - vstart.vals[0]*vstart.vals[0] - vstart.vals[1]*vstart.vals[1]); Normalize3(&vstart); xold = mx; yold = my; // calculate the vectors; Vector4 vend; vend.vals[0] = mx - .5 * width ; vend.vals[1] = .5 * height - my; if ((.5 * ldim) * (.5* ldim) - vend.vals[0]*vend.vals[0] - vend.vals[1]*vend.vals[1] <= 0) return; vend.vals[2] = sqrt((.5 * ldim) * (.5* ldim) - vend.vals[0]*vend.vals[0] - vend.vals[1]*vend.vals[1]); Normalize3(&vend); translateoff[0] += -(XMAX-XMIN)* (vend.vals[0] - vstart.vals[0]); translateoff[1] += -(XMAX-XMIN)* (vend.vals[1] - vstart.vals[1]); translateoff[2] += -0* (vend.vals[2] - vstart.vals[2]); glutPostRedisplay(); } //if (buttonstate == 0) { // float ldim = (width > height ? width : height); // if (xold == mx && yold == my) return; // vstart.vals[0] = xold - .5 * width ; // vstart.vals[1] = .5 * height - yold; // if ((.5 * ldim) * (.5* ldim) - vstart.vals[0]*vstart.vals[0] - vstart.vals[1]*vstart.vals[1] < 0) return; // vstart.vals[2] = sqrt((.5 * ldim) * (.5* ldim) - vstart.vals[0]*vstart.vals[0] - vstart.vals[1]*vstart.vals[1]); // if (Normalize3(&vstart)== 0) return; // xold = mx; // yold = my; // // calculate the vectors; // Vector4 vend; // vend.vals[0] = mx - .5 * width ; // vend.vals[1] = .5 * height - my; // if ((.5 * ldim) * (.5* ldim) - vend.vals[0]*vend.vals[0] - vend.vals[1]*vend.vals[1] <= 0) return; // vend.vals[2] = sqrt((.5 * ldim) * (.5* ldim) - vend.vals[0]*vend.vals[0] - vend.vals[1]*vend.vals[1]); // if (Normalize3(&vend)== 0) return; // float alpha = InteriorAngle(vstart, vend); // if (alpha < 0.01) return; // Vector4 cp = Cross(vstart, vend); // if (Normalize3(&cp) == 0) return; // //update the crystal ball matrix // glMatrixMode(GL_MODELVIEW); // glLoadIdentity(); // rotationtotal = times( rotationtotal,rotation(cp, alpha*PI/-180.0)); // setRotQuat(rotmatrix, rotationtotal); // glMultMatrixf(rotmatrix.vals); //} glutPostRedisplay(); } void initScene() { glDepthMask(true); if (clearcolor) { glClearColor(1,1,1,1); } else { glClearColor(0,0,0,1); } glDisable(GL_CULL_FACE); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); glLineWidth(1); glEnable(GL_LINE_SMOOTH); // Enable our light. glEnable(GL_LIGHT0); // Set up the material information for our objects. Again this is just for show. glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularLight); glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 128); // initialize crystal ball mat = MIdentity(); dist = 300*(ZMAX-ZMIN); } void Initialize_GLUT(int argc, char **argv) { translateoff[0] =0.0; translateoff[1] =0.0; translateoff[2] =0.0; resetQuat(rotationtotal); g_mouseActive = false; // GLUT initialization. glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(width, height); glutInitWindowPosition(570, 80); mainWindow = glutCreateWindow("Morse3d Efficient Computation"); // glewInit(); glutDisplayFunc(display); glutReshapeFunc(reshapeMainWindow); glutKeyboardFunc(graphicKeys); glutMouseFunc (mouseClicked); //glutSpecialFunc(functionKeys); glutMotionFunc(mouseMovement); glutIdleFunc(myidle); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_POSITION, light_position); initScene(); // setGlobalMinMax(usc); glutMainLoop(); }
8d552fd362164f908830598c4fff6534f1c62f13
3033d31326bc844dbdbec57aab67bed61f6a57a0
/Src/Modules/Modeling/OracledWorldModelProvider/OracledWorldModelProvider.cpp
332709813c44928e3a508f7ef8eb55e3496d20b5
[ "BSD-2-Clause" ]
permissive
yelite/BHumanCodeRelease
4b96c94b50822bcb56aa6ebbad7dba28760cf497
d6df4573dfa6ad6a1ddfb7c7a46d1957ae1b516a
refs/heads/master
2021-01-24T14:22:00.174065
2014-09-28T01:54:07
2014-09-28T01:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,280
cpp
OracledWorldModelProvider.cpp
/** * @file Modules/Infrastructure/OracledWorldModelProvider.h * * This file implements a module that provides models based on simulated data. * * @author <a href="mailto:tlaue@uni-bremen.de">Tim Laue</a> */ #include "OracledWorldModelProvider.h" OracledWorldModelProvider::OracledWorldModelProvider(): lastBallModelComputation(0), lastRobotPoseComputation(0) { } void OracledWorldModelProvider::computeRobotPose() { if(lastRobotPoseComputation == theFrameInfo.time) return; DRAW_ROBOT_POSE("module:OracledWorldModelProvider:realRobotPose", theGroundTruthWorldState.ownPose, ColorRGBA::magenta); theRobotPose = theGroundTruthWorldState.ownPose + robotPoseOffset; theRobotPose.deviation = 1.f; theRobotPose.validity = 1.f; lastRobotPoseComputation = theFrameInfo.time; } void OracledWorldModelProvider::computeBallModel() { if(lastBallModelComputation == theFrameInfo.time || theGroundTruthWorldState.balls.size() == 0) return; computeRobotPose(); Vector2<> ballPosition = theGroundTruthWorldState.balls[0]; Vector2<float> velocity((ballPosition - lastBallPosition) / float(theFrameInfo.getTimeSince(theBallModel.timeWhenLastSeen)) * 1000.0f); theBallModel.estimate.position = theRobotPose.invert() * ballPosition; theBallModel.estimate.velocity = Vector2<>(velocity).rotate(-theRobotPose.rotation); theBallModel.lastPerception = theBallModel.estimate.position; theBallModel.timeWhenLastSeen = theFrameInfo.time; theBallModel.timeWhenDisappeared = theFrameInfo.time; lastBallPosition = ballPosition; lastBallModelComputation = theFrameInfo.time; } void OracledWorldModelProvider::update(BallModel& ballModel) { computeBallModel(); ballModel = theBallModel; } void OracledWorldModelProvider::update(GroundTruthBallModel& groundTruthBallModel) { computeBallModel(); groundTruthBallModel.lastPerception = theBallModel.lastPerception; groundTruthBallModel.estimate = theBallModel.estimate; groundTruthBallModel.timeWhenDisappeared = theBallModel.timeWhenDisappeared; groundTruthBallModel.timeWhenLastSeen = theBallModel.timeWhenLastSeen; } void OracledWorldModelProvider::update(ObstacleModel& obstacleModel) { computeRobotPose(); obstacleModel.obstacles.clear(); for(unsigned int i = 0; i<theGroundTruthWorldState.blueRobots.size(); ++i) robotToObstacle(theGroundTruthWorldState.blueRobots[i], obstacleModel); for(unsigned int i = 0; i<theGroundTruthWorldState.redRobots.size(); ++i) robotToObstacle(theGroundTruthWorldState.redRobots[i],obstacleModel); } void OracledWorldModelProvider::update(ExpObstacleModel& expObstacleModel) { computeRobotPose(); expObstacleModel.eobs.clear(); for(unsigned int i = 0; i < theGroundTruthWorldState.blueRobots.size(); ++i) robotToObstacle(theGroundTruthWorldState.blueRobots[i], expObstacleModel, false); for(unsigned int i = 0; i < theGroundTruthWorldState.redRobots.size(); ++i) robotToObstacle(theGroundTruthWorldState.redRobots[i], expObstacleModel, true); } void OracledWorldModelProvider::robotToObstacle(const GroundTruthWorldState::GroundTruthRobot& robot,ObstacleModel& obstacleModel) const { const float robotRadius(120.f); // Hardcoded as this code will vanish as soon as the new obstacle model has been finished ObstacleModel::Obstacle obstacle; obstacle.center = theRobotPose.invert() * robot.pose.translation; obstacle.leftCorner = obstacle.rightCorner = obstacle.closestPoint = obstacle.center; float distance = obstacle.center.abs(); if(distance > robotRadius) { obstacle.closestPoint.normalize(); obstacle.closestPoint *= (distance - robotRadius); } Vector2<> leftOffset = obstacle.center; leftOffset.normalize(); leftOffset *= robotRadius; Vector2<> rightOffset = leftOffset; leftOffset.rotateLeft(); rightOffset.rotateRight(); obstacle.leftCorner += leftOffset; obstacle.rightCorner += rightOffset; obstacle.type = ObstacleModel::Obstacle::ROBOT; obstacleModel.obstacles.push_back(obstacle); } void OracledWorldModelProvider::robotToObstacle(const GroundTruthWorldState::GroundTruthRobot& robot, ExpObstacleModel& expObstacleModel, const bool isRed) const { ExpObstacleModel::ExpObstacle obstacle; obstacle.center = theRobotPose.invert() * robot.pose.translation; obstacle.type = isRed ? ExpObstacleModel::ExpObstacle::ROBOTRED : ExpObstacleModel::ExpObstacle::ROBOTBLUE; obstacle.lastMeasurement = theFrameInfo.time; obstacle.seenCount = 14; obstacle.velocity = Vector2<>(1.f, 1.f); expObstacleModel.eobs.emplace_back(obstacle); } void OracledWorldModelProvider::update(RobotPose& robotPose) { DECLARE_DEBUG_DRAWING("module:OracledWorldModelProvider:realRobotPose", "drawingOnField"); computeRobotPose(); robotPose = theRobotPose; } void OracledWorldModelProvider::update(GroundTruthRobotPose& groundTruthRobotPose) { computeRobotPose(); groundTruthRobotPose.translation = theRobotPose.translation; groundTruthRobotPose.rotation = theRobotPose.rotation; groundTruthRobotPose.covariance = theRobotPose.covariance; groundTruthRobotPose.deviation = theRobotPose.deviation; groundTruthRobotPose.validity = theRobotPose.validity; groundTruthRobotPose.timestamp = theFrameInfo.time; } MAKE_MODULE(OracledWorldModelProvider,Cognition Infrastructure)
e2df070bfd5f235493c6d54ddffa6c79d28fc94f
661d438fae4bb60141e89ae59531fee9cc332279
/lib/Analysis.cpp
10a4e11565c481260615b668b1af6b684d393ca6
[ "BSD-3-Clause" ]
permissive
LLNL/typeforge
651332e722e3e272ae3adc67f92fdca1fc70ce36
e91c0447140040a9ae02f3a58af3621a00a5e242
refs/heads/master
2023-06-12T22:12:39.014512
2020-03-10T19:52:45
2020-03-10T19:53:33
229,631,812
2
1
null
null
null
null
UTF-8
C++
false
false
47,282
cpp
Analysis.cpp
/** * Copyright 2020 Lawrence Livermore National Security, LLC and other Typeforge developers. * See the top-level NOTICE file for details. * * SPDX-License-Identifier: BSD-3 */ #include "sage3basic.h" #include "SgNodeHelper.h" #include "Typeforge/Analysis.hpp" #include "Typeforge/ToolConfig.hpp" #include <boost/graph/graphviz.hpp> #include <iostream> #include <vector> #ifndef DEBUG__statics__isArrayPointerType # define DEBUG__statics__isArrayPointerType 0 #endif #ifndef DEBUG__statics__getNodeLabel # define DEBUG__statics__getNodeLabel 0 #endif #ifndef DEBUG__ignoreNode # define DEBUG__ignoreNode 0 #endif #ifndef DEBUG__isTypeBasedOn # define DEBUG__isTypeBasedOn 0 #endif #ifndef DEBUG__Analysis # define DEBUG__Analysis 0 #endif #ifndef DEBUG__incompatible_types # define DEBUG__incompatible_types 0 #endif #ifndef DEBUG__computeClustering # define DEBUG__computeClustering 0 #endif #ifndef DEBUG__Analysis__initialize # define DEBUG__Analysis__initialize DEBUG__Analysis #endif #ifndef DEBUG__Analysis__traverse # define DEBUG__Analysis__traverse DEBUG__Analysis #endif #ifndef DEBUG__Analysis__traverseVariableDeclarations # define DEBUG__Analysis__traverseVariableDeclarations DEBUG__Analysis__traverse #endif #ifndef DEBUG__Analysis__traverseFunctionDeclarations # define DEBUG__Analysis__traverseFunctionDeclarations DEBUG__Analysis__traverse #endif #ifndef DEBUG__Analysis__traverseFunctionDefinitions # define DEBUG__Analysis__traverseFunctionDefinitions DEBUG__Analysis__traverse #endif #ifndef DEBUG__Analysis__linkVariables # define DEBUG__Analysis__linkVariables DEBUG__Analysis #endif #ifndef DEBUG__Analysis__addEdge # define DEBUG__Analysis__addEdge DEBUG__Analysis #endif #ifndef DEBUG__Analysis__addNode # define DEBUG__Analysis__addNode DEBUG__Analysis #endif #ifndef DEBUG__Analysis__getScope # define DEBUG__Analysis__getScope DEBUG__Analysis #endif #ifndef DEBUG__Analysis__getType # define DEBUG__Analysis__getType DEBUG__Analysis #endif #ifndef DEBUG__Analysis__getPosition # define DEBUG__Analysis__getPosition DEBUG__Analysis #endif #ifndef DEBUG__Analysis__getClass # define DEBUG__Analysis__getClass DEBUG__Analysis #endif #ifndef DEBUG__Analysis__getHandle # define DEBUG__Analysis__getHandle DEBUG__Analysis #endif #ifndef DEBUG__Analysis__getNode # define DEBUG__Analysis__getNode DEBUG__Analysis #endif #ifndef DEBUG__Analysis__buildChildSets # define DEBUG__Analysis__buildChildSets DEBUG__Analysis #endif namespace Typeforge { using namespace std; SgType * stripType(SgType * type, bool strip_std_vector) { assert(type != NULL); #if DEBUG__isTypeBasedOn std::cout << "Typeforge::stripType" << std::endl; std::cout << " type = " << type << " ( " << type->class_name() << "): " << type->unparseToString() << "" << std::endl; #endif type = type->stripType( SgType::STRIP_ARRAY_TYPE | SgType::STRIP_POINTER_TYPE | SgType::STRIP_MODIFIER_TYPE | SgType::STRIP_REFERENCE_TYPE | SgType::STRIP_RVALUE_REFERENCE_TYPE ); SgTypedefType * td_type = isSgTypedefType(type); SgClassType * xtype = isSgClassType(type); if (td_type != nullptr) { type = stripType(td_type->get_base_type(), strip_std_vector); } else if (strip_std_vector && xtype != nullptr) { SgDeclarationStatement * decl_stmt = xtype->get_declaration(); assert(decl_stmt != nullptr); #if DEBUG__isTypeBasedOn std::cout << " decl_stmt = " << decl_stmt << " ( " << decl_stmt->class_name() << "): " << decl_stmt->unparseToString() << "" << std::endl; #endif SgTemplateInstantiationDecl * ti_decl = isSgTemplateInstantiationDecl(decl_stmt); if (ti_decl != nullptr) { #if DEBUG__isTypeBasedOn std::cout << " ->get_qualified_name() = " << ti_decl->get_qualified_name() << std::endl; std::cout << " ->get_name() = " << ti_decl->get_name() << std::endl; #endif SgTemplateClassDeclaration * td_decl = ti_decl->get_templateDeclaration(); assert(td_decl != nullptr); #if DEBUG__isTypeBasedOn std::cout << " td_decl = " << td_decl << " ( " << td_decl->class_name() << "): " << td_decl->unparseToString() << "" << std::endl; std::cout << " ->get_qualified_name() = " << td_decl->get_qualified_name() << std::endl; #endif if (td_decl->get_qualified_name() == "::std::vector") { auto tpl_args = ti_decl->get_templateArguments(); assert(tpl_args.size() > 0); SgType * tpl_type_arg = tpl_args[0]->get_type(); assert(tpl_type_arg != nullptr); type = stripType(tpl_type_arg, false); } } } return type; } bool isTypeBasedOn(SgType * type, SgType * base, bool strip_type) { if (base == nullptr) return true; assert(type != NULL); #if DEBUG__isTypeBasedOn std::cout << "Typeforge::isTypeBasedOn" << std::endl; std::cout << " type = " << type << " ( " << type->class_name() << "): " << type->unparseToString() << "" << std::endl; std::cout << " base = " << base << " ( " << base->class_name() << "): " << base->unparseToString() << "" << std::endl; #endif if (strip_type) { type = stripType(type, true); } return type == base; } Analysis::node_tuple_t::node_tuple_t(SgNode * n) : handle(), cname(n->class_name()), position(), scope(nullptr), type(nullptr) { // This object is used to unparse type properly SgUnparse_Info * uinfo = new SgUnparse_Info(); uinfo->set_SkipComments(); uinfo->set_SkipWhitespaces(); uinfo->set_SkipEnumDefinition(); uinfo->set_SkipClassDefinition(); uinfo->set_SkipFunctionDefinition(); uinfo->set_SkipBasicBlock(); uinfo->set_isTypeFirstPart(); #if DEBUG__statics__getNodeLabel std::cout << "Analysis::node_tuple_t::node_tuple_t(" << n->class_name() << " * n = " << n << "):" << std::endl; #endif SgLocatedNode * lnode = isSgLocatedNode(n); assert(lnode != nullptr); { SgLocatedNode * loc_node = lnode; if (SgDeclarationStatement * declstmt = isSgDeclarationStatement(loc_node)) { declstmt = declstmt->get_definingDeclaration(); if (declstmt != nullptr) { loc_node = declstmt; } } std::ostringstream oss; oss << loc_node->get_endOfConstruct()->get_filenameString() << ":" << loc_node->get_startOfConstruct()->get_raw_line() << ":" << loc_node->get_startOfConstruct()->get_raw_col() << ":" << loc_node->get_endOfConstruct()->get_raw_line() << ":" << loc_node->get_endOfConstruct()->get_raw_col(); position = oss.str(); } #if DEBUG__statics__getNodeLabel std::cout << " position = " << position << std::endl; #endif SgExpression * expr = isSgExpression(n); SgInitializedName * iname = isSgInitializedName(n); SgVariableDeclaration * vdecl = isSgVariableDeclaration(n); SgFunctionDeclaration * fdecl = isSgFunctionDeclaration(n); SgClassDeclaration * xdecl = isSgClassDeclaration(n); SgNamespaceDeclarationStatement * ndecl = isSgNamespaceDeclarationStatement(n); if (expr != nullptr) { handle = "?<" + position + ">"; type = expr->get_type(); scope = nullptr; // FIXME do we want to prepend the scope of the expression? } else if (ndecl != nullptr) { type = ndecl->get_type(); handle = ndecl->get_qualified_name().getString(); scope = nullptr; ndecl = nullptr; } else if (iname != nullptr) { SgFunctionParameterList * fplst = isSgFunctionParameterList(iname->get_parent()); assert(fplst != nullptr); fdecl = isSgFunctionDeclaration(fplst->get_parent()); assert(fdecl != nullptr); auto it = std::find(fplst->get_args().begin(), fplst->get_args().end(), iname); assert(it != fplst->get_args().end()); auto pos = it - fplst->get_args().begin(); std::ostringstream oss; oss << pos; handle = oss.str(); type = iname->get_type(); scope = nullptr; } else if (xdecl != nullptr) { type = xdecl->get_type(); handle = xdecl->get_qualified_name().getString(); scope = nullptr; fdecl = nullptr; } else if (fdecl != nullptr) { type = fdecl->get_type()->get_return_type(); std::ostringstream oss; oss << fdecl->get_qualified_name().getString() << "("; for (auto t : fdecl->get_type()->get_argument_list()->get_arguments()) { oss << globalUnparseToString(t, uinfo) << ","; } oss << ")" << handle; handle = oss.str(); scope = nullptr; fdecl = nullptr; } else if (vdecl != nullptr) { iname = SgNodeHelper::getInitializedNameOfVariableDeclaration(vdecl); handle = iname->get_name().getString(); type = iname->get_type(); scope = vdecl->get_scope(); assert(scope != nullptr); } else { assert(false); } #if DEBUG__statics__getNodeLabel std::cout << " type = " << type << " (" << ( type ? type->class_name() : "") << ") : " << ( type ? type->unparseToString() : "") << std::endl; std::cout << " scope = " << scope << " (" << ( scope ? scope->class_name() : "") << ")" << std::endl; #endif SgScopeStatement * ascope = isSgScopeStatement(scope); assert(scope == nullptr || ascope != nullptr); while ( ascope && !isSgFunctionDefinition(ascope) && !isSgClassDefinition(ascope) && !isSgNamespaceDefinitionStatement(ascope) && !isSgGlobal(ascope) ) { #if DEBUG__statics__getNodeLabel std::cout << " -> ascope = " << ascope << " (" << ascope->class_name() << ")" << std::endl; #endif SgScopeStatement * pscope = ascope->get_scope(); #if DEBUG__statics__getNodeLabel std::cout << " -> pscope = " << pscope << " (" << ( pscope ? pscope->class_name() : "" ) << ")" << std::endl; #endif #define DEBUG__build_qualname_for_non_named_scopes 0 #if DEBUG__build_qualname_for_non_named_scopes SgFunctionDefinition * pfdefn = isSgFunctionDefinition(pscope); SgClassDefinition * pxdefn = isSgClassDefinition(pscope); SgNamespaceDefinitionStatement * pndefn = isSgNamespaceDefinitionStatement(pscope); SgGlobal * pglob = isSgGlobal(pscope); #endif SgBasicBlock * pbb = isSgBasicBlock(pscope); std::ostringstream oss; if (pbb != nullptr) { auto stmts = pbb->getStatementList(); auto it = std::find(stmts.begin(), stmts.end(), ascope); assert(it != stmts.end()); auto pos = it - stmts.begin(); oss << pos << "::"; #if DEBUG__build_qualname_for_non_named_scopes } else if (pfdefn != nullptr) { oss << "{}::"; } else if (pxdefn != nullptr) { oss << "##::"; } else if (pndefn != nullptr) { oss << "$$::"; } else if (pglob != nullptr) { oss << "@@::"; } else { oss << "--::"; #endif } handle = oss.str() + handle; ascope = pscope; } if (SgClassDefinition * xdefn = isSgClassDefinition(ascope)) { xdecl = xdefn->get_declaration(); scope = xdecl; } else if (SgFunctionDefinition * fdefn = isSgFunctionDefinition(ascope)) { fdecl = fdefn->get_declaration(); scope = fdecl; } else if (SgNamespaceDefinitionStatement * ndefn = isSgNamespaceDefinitionStatement(ascope)) { ndecl = ndefn->get_namespaceDeclaration(); scope = ndecl; } if (ndecl != nullptr) { handle = ndecl->get_qualified_name().getString() + "::" + handle; } else if (xdecl != nullptr) { handle = xdecl->get_qualified_name().getString() + "::" + handle; } else if (fdecl != nullptr) { std::ostringstream oss; oss << fdecl->get_qualified_name().getString() << "("; for (auto t : fdecl->get_type()->get_argument_list()->get_arguments()) { oss << globalUnparseToString(t, uinfo) << ","; } oss << ")::" << handle; handle = oss.str(); } #if DEBUG__statics__getNodeLabel std::cout << " handle = " << handle << std::endl; #endif delete uinfo; } void Analysis::initialize(SgProject * p) { #if DEBUG__Analysis__initialize std::cout << "ENTER Analysis::initialize" << std::endl; std::cout << " p = " << p << std::endl; std::cout << " # nodes = " << node_map.size() << std::endl; std::cout << " # edges = " << edges.size() << std::endl; #endif if (p != nullptr) { assert(::Typeforge::project == nullptr || ::Typeforge::project == p); ::Typeforge::project = p; } assert(::Typeforge::project != nullptr); for (auto g : SgNodeHelper::listOfSgGlobal(project)) { traverse(g); } #if DEBUG__Analysis__initialize std::cout << "LEAVE Analysis::initialize" << std::endl; std::cout << " # nodes = " << node_map.size() << std::endl; std::cout << " # edges = " << edges.size() << std::endl; #endif } template <class T> bool is_not_disjoint(std::set<T> const & set1, std::set<T> const & set2) { if (set1.empty() || set2.empty()) return false; auto it1 = set1.begin(); auto it1End = set1.end(); auto it2 = set2.begin(); auto it2End = set2.end(); if (*it1 > *set2.rbegin() || *it2 > *set1.rbegin()) return false; while (it1 != it1End && it2 != it2End) { if (*it1 == *it2) return true; if (*it1 < *it2) it1++; else it2++; } return false; } static bool ignoreNode(SgNode * n) { assert(n != nullptr); #if DEBUG__ignoreNode std::cout << "::ignoreNode()" << std::endl; std::cout << " n = " << n << " ( " << n->class_name() << " )" << std::endl; #endif bool ignore = true; SgLocatedNode * lnode = isSgLocatedNode(n); if (lnode != nullptr) { ignore = !SgNodeHelper::nodeCanBeChanged(lnode); } #if DEBUG__ignoreNode std::cout << " => " << ignore << std::endl; #endif return ignore; } void Analysis::traverseVariableDeclarations(SgGlobal * g) { #if DEBUG__Analysis__traverseVariableDeclarations std::cout << "Analysis::traverseVariableDeclarations" << std::endl; std::cout << " g = " << g << std::endl; #endif std::list<SgVariableDeclaration *> listOfVars = SgNodeHelper::listOfGlobalVars(g); listOfVars.splice(listOfVars.end(), SgNodeHelper::listOfGlobalFields(g)); for (auto varDec : listOfVars) { if (ignoreNode(varDec)) { continue; } SgInitializedName* initName = SgNodeHelper::getInitializedNameOfVariableDeclaration(varDec); if (initName == nullptr) { continue; } addNode(varDec); } for (auto varDec : listOfVars) { SgInitializedName* initName = SgNodeHelper::getInitializedNameOfVariableDeclaration(varDec); if (initName == nullptr) { continue; } SgInitializer* init = initName->get_initializer(); if (init == nullptr) { continue; } SgType* keyType = initName->get_type(); if (keyType == nullptr) { continue; } linkVariables(varDec, init); } } void Analysis::traverseFunctionDeclarations(SgGlobal * g) { #if DEBUG__Analysis__traverseFunctionDeclarations std::cout << "Analysis::traverseFunctionDeclarations" << std::endl; std::cout << " g = " << g << std::endl; #endif std::set<SgFunctionDeclaration *> fdecls; for (auto fdecl : SgNodeHelper::listOfFunctionDeclarations(g)) { if (ignoreNode(fdecl)) { continue; } if (isSgTemplateFunctionDeclaration(fdecl) || isSgTemplateMemberFunctionDeclaration(fdecl)) { continue; } if (fdecl->get_qualified_name() == "::SQRT" || fdecl->get_qualified_name() == "::FABS" || fdecl->get_qualified_name() == "::CBRT") { continue; } SgFunctionDeclaration * fd = isSgFunctionDeclaration(fdecl->get_firstNondefiningDeclaration()); assert(fd != nullptr); fdecls.insert(fd); } for (auto fdecl : fdecls) { #if DEBUG__Analysis__traverseFunctionDeclarations std::cout << " fdecl = " << fdecl << " (" << fdecl->class_name() << ")" << std::endl; #endif addNode(fdecl); SgFunctionDeclaration * pfdecl = isSgFunctionDeclaration(fdecl->get_definingDeclaration()); if (pfdecl == nullptr) { pfdecl = fdecl; } for (auto iname : pfdecl->get_args()) { addNode(iname); } } } void Analysis::traverseFunctionDefinitions(SgGlobal * g) { #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << "Analysis::traverseFunctionDefinitions" << std::endl; std::cout << " g = " << g << std::endl; #endif list<SgFunctionDefinition*> listOfFunctionDefinitions = SgNodeHelper::listOfFunctionDefinitions(g); #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " listOfFunctionDefinitions.size() = " << listOfFunctionDefinitions.size() << std::endl; #endif for (auto funDef : listOfFunctionDefinitions) { if (ignoreNode(funDef)) continue; if (isSgTemplateFunctionDefinition(funDef)) continue; #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " funDef = " << funDef << " ( " << funDef->class_name() << " )" << std::endl; #endif RoseAst ast(funDef); for (auto i = ast.begin(); i != ast.end(); ++i) { auto n = *i; if (ignoreNode(n)) { continue; } #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " n = " << n << " ( " << n->class_name() << " )" << std::endl; #endif if (SgAssignOp * assignOp = isSgAssignOp(n)) { SgExpression * lhs = assignOp->get_lhs_operand(); #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " lhs = " << lhs << " ( " << (lhs ? lhs->class_name() : "") << " )" << std::endl; #endif SgDotExp * dotexp = isSgDotExp(lhs); SgArrowExp * arrexp = isSgArrowExp(lhs); while (dotexp || arrexp) { #if DEBUG__Analysis__traverseFunctionDefinitions if (dotexp) std::cout << " dotexp = " << dotexp << " ( " << (dotexp ? dotexp->class_name() : "") << " )" << std::endl; if (arrexp) std::cout << " arrexp = " << arrexp << " ( " << (arrexp ? arrexp->class_name() : "") << " )" << std::endl; #endif if (dotexp) lhs = dotexp->get_rhs_operand_i(); if (arrexp) lhs = arrexp->get_rhs_operand_i(); dotexp = isSgDotExp(lhs); arrexp = isSgArrowExp(lhs); } if (SgVarRefExp* varRef = isSgVarRefExp(lhs)) { #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " varRef = " << varRef << " ( " << (varRef ? varRef->class_name() : "") << " )" << std::endl; #endif SgVariableSymbol* varSym = varRef->get_symbol(); assert(varSym != nullptr); SgInitializedName * iname = varSym->get_declaration(); assert(iname != nullptr); if (ignoreNode(iname)) { continue; } SgVariableDeclaration * vdecl = isSgVariableDeclaration(iname->get_declaration()); if (vdecl != nullptr && ignoreNode(vdecl)) { continue; } if (vdecl != nullptr) { linkVariables(vdecl, assignOp->get_rhs_operand()); } else { linkVariables(iname, assignOp->get_rhs_operand()); } } else if (SgFunctionRefExp * fref = isSgFunctionRefExp(lhs)) { #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " fref = " << fref << " ( " << (fref ? fref->class_name() : "") << " )" << std::endl; #endif SgFunctionSymbol * fsym = fref->get_symbol(); assert(fsym != nullptr); SgFunctionDeclaration * fdecl = fsym->get_declaration(); assert(fdecl != nullptr); if (ignoreNode(fdecl)) { continue; } fdecl = isSgFunctionDeclaration(fdecl->get_firstNondefiningDeclaration()); assert(fdecl != nullptr); linkVariables(fdecl, assignOp->get_rhs_operand()); } else { // TODO other cases such as operation + * / ... } } else if (SgVariableDeclaration* varDec = isSgVariableDeclaration(n)) { SgInitializedName* initName = SgNodeHelper::getInitializedNameOfVariableDeclaration(varDec); if (initName == nullptr) { continue; } SgLocatedNode * lnode = isSgLocatedNode(n); if (lnode != nullptr && ignoreNode(lnode)) { continue; } addNode(varDec); SgInitializer* init = initName->get_initializer(); if (!init) { continue; } linkVariables(varDec, init); } else if (SgFunctionCallExp* callExp = isSgFunctionCallExp(n)) { SgExpression * callee = callExp->get_function(); assert(callee != nullptr); SgFunctionRefExp * fref = isSgFunctionRefExp(callee); SgMemberFunctionRefExp * mfref = isSgMemberFunctionRefExp(callee); while (callee != nullptr && fref == nullptr && mfref == nullptr) { #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " callee = " << callee << " ( " << callee->class_name() << " )" << std::endl; #endif SgBinaryOp * bop = isSgBinaryOp(callee); if (bop != nullptr) { callee = bop->get_rhs_operand_i(); } else { assert(false); } fref = isSgFunctionRefExp(callee); mfref = isSgMemberFunctionRefExp(callee); } #if DEBUG__Analysis__traverseFunctionDefinitions std::cout << " fref = " << fref << " ( " << ( fref ? fref->class_name() : "" ) << " )" << std::endl; std::cout << " mfref = " << mfref << " ( " << ( mfref ? mfref->class_name() : "" ) << " )" << std::endl; #endif SgFunctionSymbol * fsym = nullptr; if (fref != nullptr) { fsym = fref->get_symbol_i(); } else if (mfref != nullptr) { fsym = mfref->get_symbol_i(); } else { continue; } assert(fsym != nullptr); SgFunctionDeclaration * fdecl = fsym->get_declaration(); assert(fdecl != nullptr); if (fdecl->get_qualified_name() == "::SQRT" || fdecl->get_qualified_name() == "::FABS" || fdecl->get_qualified_name() == "::CBRT") { i.skipChildrenOnForward(); continue; } SgFunctionDeclaration * dfdecl = isSgFunctionDeclaration(fdecl->get_definingDeclaration()); if (dfdecl == nullptr) { dfdecl = fdecl; } if (ignoreNode(dfdecl)) { continue; } auto const & initNameList = dfdecl->get_parameterList()->get_args(); auto const & expList = callExp->get_args()->get_expressions(); auto initIter = initNameList.begin(); auto expIter = expList.begin(); while (initIter != initNameList.end()) { addNode(*initIter); linkVariables(*initIter, *expIter); ++initIter; ++expIter; } } else if(SgReturnStmt* ret = isSgReturnStmt(n)) { SgFunctionDeclaration * fdecl = isSgFunctionDeclaration(funDef->get_declaration()->get_firstNondefiningDeclaration()); assert(fdecl != nullptr); // FIXME These Lulesh functions have overloaded version for float, double, and long double if (fdecl->get_qualified_name() == "::SQRT" || fdecl->get_qualified_name() == "::FABS" || fdecl->get_qualified_name() == "::CBRT") { i.skipChildrenOnForward(); continue; } addNode(fdecl); linkVariables(fdecl, ret->get_expression()); } } } } // TODO lots of work in this function static bool incompatible_types(SgNode * k, SgNode * t) { assert(k != nullptr); assert(t != nullptr); #if DEBUG__incompatible_types std::cout << "::incompatible_types " << std::endl; std::cout << " k = " << k << " (" << k->class_name() << ")" << std::endl; std::cout << " t = " << t << " (" << t->class_name() << ")" << std::endl; #endif SgType * kt = ::Typeforge::typechain.getType(k); assert(kt != nullptr); #if DEBUG__incompatible_types std::cout << " kt = " << kt << " (" << kt->class_name() << ") = " << kt->unparseToString() << std::endl; #endif SgType * tt = ::Typeforge::typechain.getType(t); assert(tt != nullptr); #if DEBUG__incompatible_types std::cout << " tt = " << tt << " (" << tt->class_name() << ") = " << tt->unparseToString() << std::endl; #endif // case of exact same type but not reference/pointer if (kt == tt && !isSgReferenceType(kt) && !isSgPointerType(kt)) return false; auto strip_to_value_or_pointer = SgType::STRIP_MODIFIER_TYPE | SgType::STRIP_REFERENCE_TYPE | SgType::STRIP_RVALUE_REFERENCE_TYPE; auto strip_to_base = strip_to_value_or_pointer | SgType::STRIP_ARRAY_TYPE | SgType::STRIP_POINTER_TYPE; #if DEBUG__incompatible_types SgType * v_kt = kt->stripType(strip_to_value_or_pointer); #endif SgType * b_kt = kt->stripType(strip_to_base); SgType * v_tt = tt->stripType(strip_to_value_or_pointer); SgType * b_tt = tt->stripType(strip_to_base); #if DEBUG__incompatible_types std::cout << " v_kt = " << v_kt << " (" << v_kt->class_name() << ") = " << v_kt->unparseToString() << std::endl; std::cout << " b_kt = " << b_kt << " (" << b_kt->class_name() << ") = " << b_kt->unparseToString() << std::endl; std::cout << " v_tt = " << v_tt << " (" << v_tt->class_name() << ") = " << v_tt->unparseToString() << std::endl; std::cout << " b_tt = " << b_tt << " (" << b_tt->class_name() << ") = " << b_tt->unparseToString() << std::endl; #endif bool kt_is_vt = (kt->stripType(SgType::STRIP_MODIFIER_TYPE) == b_kt); #if DEBUG__incompatible_types bool kt_no_ptr = (v_kt == b_kt); bool tt_is_vt = (tt->stripType(SgType::STRIP_MODIFIER_TYPE) == b_tt); #endif bool tt_no_ptr = (v_tt == b_tt); #if DEBUG__incompatible_types std::cout << " kt_is_vt = " << kt_is_vt << std::endl; std::cout << " kt_no_ptr = " << kt_no_ptr << std::endl; std::cout << " tt_is_vt = " << tt_is_vt << std::endl; std::cout << " tt_no_ptr = " << tt_no_ptr << std::endl; #endif // case assign to value type: // typeof(K) is value type // typeof(T) is NOT ptr type // typeof(T) == [const|&|&&]* typeof(K) if (kt_is_vt && tt_no_ptr && b_tt == b_kt) return false; // case assign to reference type: // typeof(T) is value type // typeof(K) is NOT ptr type // typeof(K) == [&|&&]* typeof(T) //if (tt_is_vt && kt_no_ptr && b_tt == b_kt) return false; return true; } void Analysis::traverse(SgGlobal * g) { #if DEBUG__Analysis__traverse std::cout << "Analysis::traverse" << std::endl; std::cout << " g = " << g << std::endl; std::cout << " # nodes = " << node_map.size() << std::endl; std::cout << " # edges = " << edges.size() << std::endl; #endif traverseVariableDeclarations(g); traverseFunctionDeclarations(g); traverseFunctionDefinitions(g); #if DEBUG__Analysis__traverse std::cout << " # nodes = " << node_map.size() << std::endl; std::cout << " # edges = " << edges.size() << std::endl; #endif } // Searches through the expression for variables of the given type then links them with the key node provided // TODO traverse expression instead: we need the full path (stack is not enough for complex expressions) void Analysis::linkVariables(SgNode * key, SgExpression * expression) { #if DEBUG__Analysis__linkVariables std::cout << "Analysis::linkVariables():" << std::endl; std::cout << " key = " << key << " (" << (key != nullptr ? key->class_name() : "") << ")" << std::endl; std::cout << " expression = " << expression << " ( " << (expression != nullptr ? expression->class_name() : "") << " ) = " << expression->unparseToString() << std::endl; std::cout << " STACK = [ " << std::endl; for (auto i: stack) { std::cout << " " << i << " (" << (i != nullptr ? i->class_name() : "") << ") = " << i->unparseToString() << std::endl; } std::cout << " ]" << std::endl; #endif stack.push_back(expression); RoseAst ast(expression); for (auto i = ast.begin(); i != ast.end(); ++i) { if (SgExpression * exp = isSgExpression(*i)) { #if DEBUG__Analysis__linkVariables std::cout << " - exp = " << exp << " (" << exp->class_name() << ")" << std::endl; #endif if (exp != expression) { stack.push_back(exp); } SgNode * target = nullptr; if (SgFunctionCallExp * funCall = isSgFunctionCallExp(exp)) { SgFunctionDeclaration * fdecl = funCall->getAssociatedFunctionDeclaration(); assert(fdecl != nullptr); fdecl = isSgFunctionDeclaration(fdecl->get_firstNondefiningDeclaration()); assert(fdecl != nullptr); #if DEBUG__Analysis__linkVariables std::cout << " - fdecl = " << fdecl << " (" << fdecl->class_name() << ")" << std::endl; std::cout << " ->get_name() = " << fdecl->get_name() << std::endl; std::cout << " ->get_qualified_name() = " << fdecl->get_qualified_name() << std::endl; #endif // FIXME These Lulesh functions have overloaded version for float, double, and long double if (fdecl->get_qualified_name() == "::SQRT" || fdecl->get_qualified_name() == "::FABS" || fdecl->get_qualified_name() == "::CBRT") { i.skipChildrenOnForward(); continue; } if (fdecl->get_name() == "operator[]") { // case: refence: v[i] where typeof(v) is std::vector SgDotExp * dotexp = isSgDotExp(funCall->get_function()); assert(dotexp != nullptr); SgExpression * objexp = dotexp->get_lhs_operand_i(); assert(objexp != nullptr); if (SgArrowExp * arrexp = isSgArrowExp(objexp)) { // case: implicit "this->" assert(isSgThisExp(arrexp->get_lhs_operand_i())); objexp = arrexp->get_rhs_operand_i(); } SgVarRefExp * vref = isSgVarRefExp(objexp); assert(vref != nullptr); SgVariableSymbol * vsym = vref->get_symbol(); assert(vsym != nullptr); SgInitializedName * iname = vsym->get_declaration(); if (!SgNodeHelper::isFunctionParameterVariableSymbol(vsym)) { target = iname->get_declaration(); } else { target = iname; } } else if (SgTemplateInstantiationFunctionDecl * ti_fdecl = isSgTemplateInstantiationFunctionDecl(fdecl)) { // case: call to: template < ... , typename Tx , ... > Tx const & foo(...); SgTemplateFunctionDeclaration * t_fdecl = ti_fdecl->get_templateDeclaration(); assert(t_fdecl != nullptr); SgFunctionType * ftype = t_fdecl->get_type(); assert(ftype != nullptr); SgType * r_ftype = ftype->get_return_type(); assert(r_ftype != nullptr); SgNonrealType * nrtype = isSgNonrealType(::Typeforge::stripType(r_ftype, true)); if (nrtype != nullptr) { SgNonrealDecl * nrdecl = isSgNonrealDecl(nrtype->get_declaration()); assert(nrdecl != nullptr); if (nrdecl->get_is_template_param()) { target = funCall; } } } else { // TODO overloaded functions } if (target == nullptr) { target = fdecl; } #if DEBUG__Analysis__linkVariables std::cout << " - target = " << target << " (" << target->class_name() << ")" << std::endl; #endif // TODO: expressions used as argument of the function ? // - std::vector => forced link (use SgType node as immutable node in the graph) // - templated return type => might depend on other template parameters (implicit or explicit) // | template <typename R, typename P0, typename P1> // | R foo(P0 p0, P1 p1); // | // | float v = foo<float>(2., 3.f); // ::foo< float, double, float >( 2., 3.f ) // | float v = foo<float, float>(2., 3.f); // ::foo< float, float, float >( (float)2., 3.f ) // | float v = foo<float, double, double>(2., 3.f); // ::foo< float, double, double >( 2., (double)3.f ) // - normal function call i.skipChildrenOnForward(); } else if (SgVarRefExp* varRef = isSgVarRefExp(exp)) { SgVariableSymbol* varSym = varRef->get_symbol(); if (varSym) { SgInitializedName * refInitName = varSym->get_declaration(); target = refInitName; if (!SgNodeHelper::isFunctionParameterVariableSymbol(varSym)) { target = refInitName->get_declaration(); } } } else if (SgPntrArrRefExp* refExp = isSgPntrArrRefExp(exp)) { linkVariables(key, refExp->get_lhs_operand()); i.skipChildrenOnForward(); // TODO what about the RHS? (aka index) } else if (SgPointerDerefExp* refExp = isSgPointerDerefExp(exp)) { linkVariables(key, refExp->get_operand()); i.skipChildrenOnForward(); } else if (SgCommaOpExp* commaExp = isSgCommaOpExp(exp)) { linkVariables(key, commaExp->get_rhs_operand()); i.skipChildrenOnForward(); } if (target != nullptr) { addNode(target); if (incompatible_types(key, target)) { addEdge(key, target); } } if (exp != expression) { stack.pop_back(); } } } stack.pop_back(); } void Analysis::addEdge(SgNode * k, SgNode * t) { #if DEBUG__Analysis__addEdge std::cout << "Analysis::addEdge " << k << " (" << (k != nullptr ? k->class_name() : "") << ") -> " << t << " (" << (t != nullptr ? t->class_name() : "") << ")" << std::endl; std::cout << " STACK = [ " << std::endl; for (auto i: stack) { std::cout << " " << i << " (" << (i != nullptr ? i->class_name() : "") << ") = " << i->unparseToString() << std::endl; } std::cout << " ]" << std::endl; #endif assert(node_map.find(k) != node_map.end()); assert(node_map.find(t) != node_map.end()); edges[k][t].push_back(stack); } std::string Analysis::addNode(SgNode * n) { assert(n != nullptr); #if DEBUG__Analysis__addNode std::cout << "Analysis::addNode:" << std::endl; std::cout << " n = " << n << " ( " << n->class_name() << " )" << std::endl; #endif auto i = node_map.find(n); if (i != node_map.end()) { std::string h = i->second.handle; #if DEBUG__Analysis__addNode std::cout << " h = " << h << " (found)" << std::endl; #endif return h; } else { node_tuple_t nt(n); std::string const & h = nt.handle; #if DEBUG__Analysis__addNode std::cout << " h = " << h << " (created)" << std::endl; #endif assert(handle_map.find(h) == handle_map.end()); node_map.insert(std::pair<SgNode *, node_tuple_t>(n, nt)); handle_map.insert(std::pair<std::string, SgNode *>(h, n)); return h; } } SgNode * Analysis::getNode(std::string const & h) const { SgNode * n = nullptr; #if DEBUG__Analysis__getNode std::cout << "Analysis::getNode:" << std::endl; std::cout << " h = " << h << std::endl; #endif auto i = handle_map.find(h); if (i != handle_map.end()) { n = i->second; } #if DEBUG__Analysis__getNode std::cout << " n = " << n << " ( " << ( n != nullptr ? n->class_name() : "" ) << " )" << std::endl; #endif return n; } std::string Analysis::getHandle(SgNode * n) const { std::string h; #if DEBUG__Analysis__getHandle std::cout << "Analysis::getHandle:" << std::endl; std::cout << " n = " << n << " ( " << ( n != nullptr ? n->class_name() : "" ) << " )" << std::endl; #endif auto i = node_map.find(n); if (i != node_map.end()) { h = i->second.handle; } #if DEBUG__Analysis__getHandle std::cout << " h = " << h << std::endl; #endif return h; } std::string Analysis::getClass(SgNode * n) const { std::string r; #if DEBUG__Analysis__getClass std::cout << "Analysis::getClass:" << std::endl; std::cout << " n = " << n << " ( " << ( n != nullptr ? n->class_name() : "" ) << " )" << std::endl; #endif auto i = node_map.find(n); if (i != node_map.end()) { r = i->second.cname; } #if DEBUG__Analysis__getClass std::cout << " r = " << r << std::endl; #endif return r; } std::string Analysis::getPosition(SgNode * n) const { std::string r; #if DEBUG__Analysis__getPosition std::cout << "Analysis::getPosition:" << std::endl; std::cout << " n = " << n << " ( " << ( n != nullptr ? n->class_name() : "" ) << " )" << std::endl; #endif auto i = node_map.find(n); if (i != node_map.end()) { r = i->second.position; } #if DEBUG__Analysis__getPosition std::cout << " r = " << r << std::endl; #endif return r; } SgType * Analysis::getType(SgNode * n) const { SgType * t = nullptr; #if DEBUG__Analysis__getType std::cout << "Analysis::getType:" << std::endl; std::cout << " n = " << n << " ( " << ( n != nullptr ? n->class_name() : "" ) << " )" << std::endl; #endif auto i = node_map.find(n); if (i != node_map.end()) { t = i->second.type; } #if DEBUG__Analysis__getType std::cout << " t = " << t << " ( " << ( t != nullptr ? t->class_name() : "" ) << " )" << std::endl; #endif return t; } SgNode * Analysis::getScope(SgNode * n) const { SgNode * s = nullptr; #if DEBUG__Analysis__getScope std::cout << "Analysis::getScope:" << std::endl; std::cout << " n = " << n << " ( " << ( n != nullptr ? n->class_name() : "" ) << " )" << std::endl; #endif auto i = node_map.find(n); if (i != node_map.end()) { s = i->second.scope; } #if DEBUG__Analysis__getScope std::cout << " s = " << s << " ( " << ( s != nullptr ? s->class_name() : "" ) << " )" << std::endl; #endif return s; } void Analysis::buildChildSets(std::map<SgNode *, std::set<SgNode *> > & childsets, SgType * base) const { #if DEBUG__Analysis__buildChildSets std::cout << "Analysis::buildChildSets" << std::endl; #endif std::set< std::pair<SgNode *, SgNode *> > edges_of_interrest; for (auto n: node_map) { #if DEBUG__Analysis__buildChildSets std::cout << " - n.first = " << n.first << " ( " << n.first->class_name() << " )" << std::endl; #endif if (base != nullptr) { if ( !isTypeBasedOn(n.second.type, base, true) ) continue; #if DEBUG__Analysis__buildChildSets std::cout << " * selected" << std::endl; #endif } edges_of_interrest.insert(std::pair<SgNode *, SgNode *>(n.first,n.first)); } for (auto e: edges) { auto s = e.first; #if DEBUG__Analysis__buildChildSets std::cout << " - s = " << s << " ( " << s->class_name() << " )" << std::endl; #endif if (base != nullptr) { auto s_n_ = node_map.find(s); if (s_n_ != node_map.end()) { auto n = s_n_->second; if ( !isTypeBasedOn(n.type, base, true) ) continue; } #if DEBUG__Analysis__buildChildSets std::cout << " * selected" << std::endl; #endif } for (auto t_ : e.second) { auto t = t_.first; #if DEBUG__Analysis__buildChildSets std::cout << " - t = " << t << " ( " << t->class_name() << " )" << std::endl; #endif if (base != nullptr) { auto t_n_ = node_map.find(t); if (t_n_ != node_map.end()) { auto n = t_n_->second; if ( !isTypeBasedOn(n.type, base, true) ) continue; } #if DEBUG__Analysis__buildChildSets std::cout << " * selected" << std::endl; #endif } edges_of_interrest.insert(std::pair<SgNode *, SgNode *>(s,t)); } } for (auto e : edges_of_interrest) { auto s = e.first; auto t = e.second; childsets[s].insert(s); childsets[s].insert(t); childsets[t].insert(s); childsets[t].insert(t); } } template < typename T, typename S=std::set<T> > void computeClustering(std::map<T, S> const & childsets, std::vector<S> & clusters) { #if DEBUG__computeClustering std::cout << "computeClustering" << std::endl; #endif using P = std::pair< S , S >; std::vector<P> clustering; for (auto p : childsets) { clustering.push_back(P({p.first},p.second)); } while (clustering.size() > 0) { auto & nodeset = clustering[0].first; auto & tagset = clustering[0].second; bool has_changed = true; while (has_changed) { has_changed = false; size_t i = 1; while (i < clustering.size()) { if (is_not_disjoint(tagset, clustering[i].second)) { nodeset.insert(clustering[i].first.begin(), clustering[i].first.end()); tagset.insert(clustering[i].second.begin(), clustering[i].second.end()); clustering.erase(clustering.begin() + i); if (i > 1) { has_changed = true; } } else { ++i; } } } clusters.push_back(nodeset); clustering.erase(clustering.begin()); } } void Analysis::buildClusters(std::vector<std::set<SgNode *> > & clusters, SgType * base) const { std::map<SgNode *, std::set<SgNode *> > childsets; buildChildSets(childsets, base); computeClustering(childsets, clusters); } void Analysis::toDot(std::string const & fileName, SgType * base, bool detailed) const { SgUnparse_Info* uinfo = new SgUnparse_Info(); uinfo->set_SkipComments(); uinfo->set_SkipWhitespaces(); uinfo->set_SkipEnumDefinition(); uinfo->set_SkipClassDefinition(); uinfo->set_SkipFunctionDefinition(); uinfo->set_SkipBasicBlock(); // uinfo->set_isTypeFirstPart(); std::map<std::string, std::string> node_color_map = { { "SgInitializedName", "lightsalmon" }, { "SgVariableDeclaration", "cyan" }, { "SgFunctionDeclaration", "mediumpurple" }, { "SgMemberFunctionDeclaration", "wheat" }, { "SgTemplateInstantiationFunctionDecl", "palegreen" }, { "SgTemplateInstantiationMemberFunctionDecl", "lightcoral" }, { "SgClassDeclaration", "palevioletred" }, { "SgFunctionCallExp", "lightsteelblue" } }; fstream dotfile; dotfile.open(fileName, ios::out | ios::trunc); dotfile << "digraph {" << std::endl; dotfile << " ranksep=5;" << std::endl; std::vector< std::set<SgNode *> > clusters; buildClusters(clusters, base); size_t num_nodes = 0; for (auto C : clusters) { num_nodes += C.size(); } dotfile << " title=\"" << clusters.size() << " clusters with " << num_nodes << " possible transformations.\";" << std::endl; for (size_t i = 0; i < clusters.size(); ++i) { auto C = clusters[i]; dotfile << " subgraph cluster_" << i << " {" << std::endl; dotfile << " title=\"Cluster #" << i << " with " << C.size() << " possible transformations.\";" << std::endl; std::set<SgNode *> seen; for (auto n: C) { assert(n != nullptr); auto d = node_map.find(n); assert(d != node_map.end()); auto edges__ = edges.find(n); if (edges__ != edges.end()) { for (auto target_stack: edges__->second) { auto t = target_stack.first; auto i = node_map.find(t); assert(i != node_map.end()); seen.insert(n); seen.insert(t); #if 1 dotfile << " n_" << n << " -> n_" << t << ";" << std::endl; #else // TODO make so that one can choose to expand the stacks (nodes) // Following code only unparse the stacks in the edge's labels (not readable) auto stacks = target_stack.second; dotfile << "[label=\""; for (auto stack__: stacks) { for (auto s: stack__) { assert(s != nullptr); dotfile << s->unparseToString() << " - "; } dotfile << ""; } dotfile << "\"];" << std::endl; #endif } } } // TODO get paths through: // - automated: analyze all positions in graph [eventually] // - cmd-line [good first step] // - environment [I don't like that one much] std::vector<std::string> paths{ "/workspace/pipeline-tests/typeforge-tests/", "/opt/rose/vanderbrugge1/typeforge/native/release/install/include/edg/g++_HEADERS/hdrs7/" }; for (auto n : seen) { auto d = node_map.find(n); assert(d != node_map.end()); auto position = d->second.position; for (auto p : paths) { auto i = position.find(p); if (i == 0) { position = position.substr(p.size()); } } dotfile << " n_" << n << " [label=\""; if(detailed) { dotfile << d->second.handle; // dotfile << "\\n" << d->second.cname; dotfile << "\\n" << position; dotfile << "\\n" << globalUnparseToString(d->second.type, uinfo); } dotfile << "\""; dotfile << ", fillcolor=" << node_color_map[d->second.cname] << ", style=filled"; if ( isTypeBasedOn(d->second.type, base, true) ) { dotfile << ", penwidth=3"; } dotfile << "];" << std::endl; } dotfile << "}" << std::endl; // end cluster } dotfile << "}" << std::endl; // end graph dotfile.close(); delete uinfo; } void Analysis::getGlobals(std::vector<SgVariableDeclaration *> & decls, std::string const & location) const { for (auto p : node_map) { auto n = p.first; auto d = p.second; SgVariableDeclaration * vdecl = isSgVariableDeclaration(n); if (vdecl != nullptr && isSgGlobal(vdecl->get_scope())) { decls.push_back(vdecl); } } } void Analysis::getLocals(std::vector<SgVariableDeclaration *> & decls, std::string const & location) const { for (auto p : node_map) { auto n = p.first; auto d = p.second; SgVariableDeclaration * vdecl = isSgVariableDeclaration(n); if (vdecl != nullptr) { decls.push_back(vdecl); // TODO compare `location` } } } void Analysis::getFields(std::vector<SgVariableDeclaration *> & decls, std::string const & location) const { for (auto p : node_map) { auto n = p.first; auto d = p.second; SgVariableDeclaration * vdecl = isSgVariableDeclaration(n); if (vdecl != nullptr && false) { decls.push_back(vdecl); // TODO compare `location` } } } void Analysis::getFunctions(std::vector<SgFunctionDeclaration *> & decls, std::string const & location) const { for (auto p : node_map) { auto n = p.first; auto d = p.second; SgFunctionDeclaration * fdecl = isSgFunctionDeclaration(n); SgMemberFunctionDeclaration * mdecl = isSgMemberFunctionDeclaration(n); if (fdecl != nullptr && mdecl == nullptr) { decls.push_back(fdecl); // TODO compare `location` } } } void Analysis::getMethods(std::vector<SgFunctionDeclaration *> & decls, std::string const & location) const { for (auto p : node_map) { auto n = p.first; auto d = p.second; SgMemberFunctionDeclaration * mdecl = isSgMemberFunctionDeclaration(n); if (mdecl != nullptr) { decls.push_back(mdecl); // TODO compare `location` } } } void Analysis::getParameters(std::vector<SgInitializedName *> & decls, std::string const & location) const { for (auto p : node_map) { auto n = p.first; auto d = p.second; SgInitializedName * iname = isSgInitializedName(n); if (iname != nullptr) { decls.push_back(iname); // TODO compare `location` } } } void Analysis::getCallExp(std::vector<SgFunctionCallExp *> & exprs, std::string const & location) const { for (auto p : node_map) { auto n = p.first; auto d = p.second; SgFunctionCallExp * expr = isSgFunctionCallExp(n); if (expr != nullptr) { exprs.push_back(expr); // TODO compare `location` } } } SgProject * project; Analysis typechain; }
d9b4864b7b80d8ad3747dbc5c0782a61efd1dc5c
9ce5c27b87659936ac398e2e7f280c440cd4f0ac
/Hw2/CircularQueue/main.cpp
8736114b23ddb51ab8af9aafbd5cae59693be6aa
[]
no_license
RexCYJ/EECS2040-Data_Structure
1df998e91254d1b7efa96dce692b56ed51045e31
1ed1a1921ef5ab9553a455e8fcdfc99357b389e8
refs/heads/master
2023-06-12T23:05:08.751094
2021-06-28T18:44:40
2021-06-28T18:44:40
365,291,323
0
0
null
null
null
null
UTF-8
C++
false
false
1,837
cpp
main.cpp
#include <iostream> #include "Queue.h" using namespace std; // using std::cin; // using std::cout; int main(void) { Queue<int> A(10); Queue<int> B(5); char c; int input; B.Push(1000); B.Push(2000); B.Push(3000); B.Push(4000); cout << "Type your instructions below.\n"; cout << "e: exit\t\t\tf: return front\t\tr: return rear\t\tc: return capacity\n"; cout << "s: return size\t\tp: push a number\tP: pop the front\tm: merge\n"; cout << "d: display the queue\n\n>> Your instruction: "; cin >> c; while (c != 'e') { switch (c) { case 'f': cout << "\tthe front of queue A is " << A.Front() << endl; break; case 'r': cout << "\tthe rear of queue A is " << A.Rear() << endl; break; case 'c': cout << "\tthe capacity of queue A is " << A.Get_capacity() << endl; break; case 's': cout << "\tthe size of queue A is " << A.Get_size() << endl; break; case 'p': cin >> input; A.Push(input); cout << "\tpush " << input << " into queue A\n"; break; case 'P': cout << "\tpop out " << A.Front() << "\n"; A.Pop(); break; case 'm': cout << "\tmerge A with B(1000, 2000, 3000, 4000)\n"; cout << "\tthe result:\n" << A.merge(B); break; case 'd': cout << A; break; default: cout << "\tWarning: Invalid input!\n"; break; } cout << "\n>> Your instruction: "; cin >> c; } return 0; }
bdd1c7ababe0e7ccf9c83f4ac5311583aa3bcf79
b8723a2862a0bc34e02a44628a2f9434693ea7d1
/kattis/wheresmyinternet.cpp
38a420e38b6093ab2676e66cfa3ee4dd15b86768
[]
no_license
mario7lorenzo/cp
ea6d20bbde7ec7217b7bab45f635dda40d2e078b
253c16599a06cb676a3c94b4892279905486cf5d
refs/heads/master
2022-05-03T22:27:07.710681
2022-04-10T08:37:53
2022-04-10T08:37:53
158,787,709
0
0
null
null
null
null
UTF-8
C++
false
false
1,631
cpp
wheresmyinternet.cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define white 1 #define black -1 int dfs_num[200500]; map<int, vector<int>> al; unordered_set<int> saver; queue<int> q; void dfs(int x) { saver.insert(x); dfs_num[x-1] = black; for (int i = 0; i < al[x].size(); i++) { int vtx = al[x][i]; if (dfs_num[vtx-1] == white) { dfs(vtx); } } } // 1. DFS Implementation // int main() { // int n, m; // cin >> n >> m; // for (int i = 0; i < m; i++) { // int a, b; // cin >> a >> b; // al[a].push_back(b); // al[b].push_back(a); // } // for (int i = 0; i < n; i++) { // dfs_num[i] = white; // } // dfs(1); // if (saver.size() == n) { // cout << "Connected" << endl; // } // else { // for (int i = 1; i < n+1; i++) { // if (saver.find(i) == saver.end()) { // cout << i << endl; // } // } // } // } // 2. BFS Implementation int main() { int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; al[a].push_back(b); al[b].push_back(a); } for (int i = 0; i < n; i++) { dfs_num[i] = white; } q.push(1); saver.insert(1); while (!q.empty()) { for (int i = 0; i < al[q.front()].size(); i++) { if (dfs_num[al[q.front()][i]-1] == white) { saver.insert(al[q.front()][i]); q.push(al[q.front()][i]); dfs_num[al[q.front()][i]-1] = black; } } dfs_num[q.front()-1] = black; q.pop(); } if (saver.size() == n) { cout << "Connected" << endl; } else { for (int i = 1; i < n+1; i++) { if (saver.find(i) == saver.end()) { cout << i << endl; } } } }
e3e430ae1cf68954781f8cba07ea7b54ff312ec0
293bc62390ee1f28a985674d04ed58b4607974da
/WindowsService/win_service.cpp
a98c59665f2084ead06c9e99b977095f91bc9a23
[]
no_license
dd181818/WindowsService-2
3aa2dfbe8d3f358840be0ed84570ca2a6d9d94bc
42e21222e9169f315e4db3e41c923912a64153f6
refs/heads/master
2020-04-04T18:01:56.379687
2018-07-11T03:30:31
2018-07-11T03:30:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,131
cpp
win_service.cpp
#include "win_service.h" WinService & WinService::Instance() { // instantiated in first use, guaranteed to be destroyed static WinService instance; return instance; } void WinService::ServiceControlHandler(DWORD dwControlCode) { switch (dwControlCode) { case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_STOP: WinService::Instance().OnServiceStopped(); return; /* ...other control codes handler */ default: break; } WinService::Instance().SetServiceStatus(); } void WinService::ServiceMain(DWORD argc, LPTSTR * argv) { WinService::Instance().MyServiceMain(argc, argv); } bool WinService::SetServiceStatus() { return ::SetServiceStatus(m_hServiceHandle, &m_serviceStatus); } bool WinService::IsInstalled() { bool bResult = false; SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCM != NULL) { SC_HANDLE hService = OpenService(hSCM, m_strServiceName.data(), SERVICE_QUERY_CONFIG); if (hService != NULL) { bResult = true; CloseServiceHandle(hService); } CloseServiceHandle(hSCM); } return bResult; } void WinService::InstallService() { if (IsInstalled()) { printf("service have already install,please uninstall first\n"); return; } SC_HANDLE hControlManager = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); if (hControlManager) { TCHAR path[_MAX_PATH + 1]; if (GetModuleFileName(0, path, sizeof(path) / sizeof(path[0])) > 0) { SC_HANDLE hService = CreateService(hControlManager, m_strServiceName.data(), m_strServiceName.data(), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, path, 0, 0, 0, 0, 0); if (hService) { CloseServiceHandle(hService); } } CloseServiceHandle(hControlManager); } else { printf("open service control manager error\n"); } } void WinService::UninstallService() { if (!IsInstalled()) { printf("service not checked\n"); return; } DWORD dwOption = SC_MANAGER_CONNECT; SC_HANDLE hControlManager = OpenSCManager(0, 0, dwOption); if (hControlManager) { dwOption = SERVICE_QUERY_STATUS | DELETE; SC_HANDLE hService = OpenService(hControlManager, m_strServiceName.data(), dwOption); if (hService) { SERVICE_STATUS m_serviceStatus; if (QueryServiceStatus(hService, &m_serviceStatus)) { if (m_serviceStatus.dwCurrentState == SERVICE_STOPPED) { DeleteService(hService); } else { printf("please stop service first\n"); } } CloseServiceHandle(hService); } CloseServiceHandle(hControlManager); } } void WinService::MyServiceMain(DWORD argc, LPTSTR *argv) { // initialize service status m_serviceStatus.dwServiceType = SERVICE_WIN32; m_serviceStatus.dwCurrentState = SERVICE_STOPPED; m_serviceStatus.dwWin32ExitCode = NO_ERROR; m_serviceStatus.dwServiceSpecificExitCode = NO_ERROR; m_serviceStatus.dwControlsAccepted = 0; m_serviceStatus.dwCheckPoint = 0; m_serviceStatus.dwWaitHint = 0; m_hServiceHandle = RegisterServiceCtrlHandler(m_strServiceName.data(), ServiceControlHandler); if (m_hServiceHandle) { m_serviceStatus.dwCurrentState = SERVICE_START_PENDING; SetServiceStatus(); m_hEventStopService = CreateEvent(0, FALSE, FALSE, 0); // configure valid service action m_serviceStatus.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); m_serviceStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(); // access application logic, function returns followed by service stopping MainProcess(argc, argv); m_serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; SetServiceStatus(); CloseHandle(m_hEventStopService); m_hEventStopService = nullptr; // stopping service,deny disturbances m_serviceStatus.dwControlsAccepted &= ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); m_serviceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(); } } void WinService::MainProcess(DWORD argc, LPTSTR *argv) { if (argc > 1 && (strcmp(argv[1], "-console") == 0 || strcmp(argv[1], "-cli") == 0)) { // TODO:launch your application here char strCmd[1024] = "", strLastCmd[1024] = ""; while (true) { printf("Console Demo->"); fgets(strCmd, 128, stdin); if (strlen(strCmd) > 0) { strCmd[strlen(strCmd) - 1] = '\0'; } if (strcmp(strCmd, ".") == 0) { strcpy_s(strCmd, strLastCmd); // repeat the latest command } if (strcmp(strCmd, "quit") == 0 || strcmp(strCmd, "exit") == 0) { printf("Good bye!\n"); break; } strcpy_s(strLastCmd, strCmd); } } else { // TODO:launch your application here // if stop event has been trigger while (WaitForSingleObject(m_hEventStopService, 100) == WAIT_TIMEOUT) { } } // TODO:clean your application resources and quit here } bool WinService::RunService() { SERVICE_TABLE_ENTRY serviceTable[] = { { (LPSTR)m_strServiceName.data(), ServiceMain }, { 0, 0 } }; return StartServiceCtrlDispatcher(serviceTable); } void WinService::OnServiceStopped() { m_serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; SetServiceStatus(); SetEvent(m_hEventStopService); }
2c5e216425f650cb1b4190201afd50ceaf1e4d9c
950b506e3f8fd978f076a5b9a3a950f6f4d5607b
/cf/vkcup-2017/round-1/B.cpp
6072b43fe1c71a5cbd512c890b23db89ebd665e9
[]
no_license
Mityai/contests
2e130ebb8d4280b82e7e017037fc983063228931
5b406b2a94cc487b0c71cb10386d1b89afd1e143
refs/heads/master
2021-01-09T06:09:17.441079
2019-01-19T12:47:20
2019-01-19T12:47:20
80,909,953
4
0
null
null
null
null
UTF-8
C++
false
false
2,711
cpp
B.cpp
#define filesfl 0 #define consolefl 01 #define fname "keke" // evgenstf - batya #include <iostream> #include <fstream> #include <cstdlib> #include <cstdio> #include <ctime> #include <cassert> #include <stdint.h> #include <utility> #include <cmath> #include <algorithm> #include <set> #include <vector> #include <map> #include <string> #include <queue> #include <stack> #include <bitset> #include <unordered_set> #include <unordered_map> #define forn(i, n) for (ll i = 0; i < n; ++i) #define fornn(i, q, n) for (ll i = q; i < n; ++i) #define rforn(i, n) for (ll i = n; i >= 0; i--) #define rfornn(i, m, n) for (ll i = m; i >= n; i--) #define inb push_back #define outb pop_back #define X first #define Y second #define Z third #define mk make_pair #define _i "%d" #define _ll "%I64d" #define pii pair<ll, ll> #define times clock() * 1.0 / CLOCKS_PER_SEC #define all(v) v.begin(), v.end() #define nsc(n) scanf("%d", &n) #define nmsc(n, m) scanf("%d%d", &n, &m) typedef long double ld; typedef long long ll; typedef unsigned long long ull; typedef unsigned int uint; const int inf = 1e9 + 5; const ll linf = 1e18 + 5; const ld eps = 1e-9; const ll dd = 2e5 + 7; const ll maxn = 2e3 + 10; const ll mod = 1e9 + 7; using namespace std; int main() { ios_base::sync_with_stdio(0); #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #else if (filesfl) { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); } else { if (!consolefl) { freopen(fname".in", "r", stdin); freopen(fname".out", "w", stdout); } } #endif const int N = 50; vector<string> names(N); for (int i = 0; i < N; ++i) { names[i] = char('A' + (i >= 26)); names[i] += char('a' + i % 26); } int n, k; cin >> n >> k; int m = n - k + 1; vector<string> a(m); for (int i = 0; i < m; ++i) { cin >> a[i]; } vector<string> ans(n); for (int i = 0; i < k - 1; ++i) { ans[i] = names[i]; } for (int i = k - 1; i < n; ++i) { if (a[i - (k - 1)] == "YES") { for (int j = 0; j < N; ++j) { bool ok = true; for (int t = i - k + 1; t < i; ++t) { if (names[j] == ans[t]) { ok = false; break; } } if (ok) { ans[i] = names[j]; break; } } } else { ans[i] = ans[i - (k - 1)]; } } for (int i = 0; i < n; ++i) { cout << ans[i] << ' '; } cout << endl; }
f19d0a2675afe96140e0ee89bb716481d172e7b4
5bd1b0ba0da4d1c72106cfce765a3166f3c98dfd
/Tankerfield/Tankerfield/Obj_RewardBox.cpp
3152d07fd0f529484be73e600f37c6090f44602e
[ "MIT" ]
permissive
vsRushy/Tankerfield
e608c540d1419d5b6d02217896d6351462c48c2d
f5e3b75f1b428e3b80b0d54879b39bb5320b5418
refs/heads/master
2020-07-23T16:12:51.306570
2019-09-08T11:42:06
2019-09-08T11:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,992
cpp
Obj_RewardBox.cpp
#include "Brofiler/Brofiler.h" #include "PugiXml\src\pugixml.hpp" #include "Obj_RewardBox.h" #include "App.h" #include "M_Render.h" #include "M_Collision.h" #include "M_PickManager.h" #include "M_Map.h" #include "M_Audio.h" Obj_RewardBox::Obj_RewardBox(fPoint pos) : Object(pos) { coll = app->collision->AddCollider(pos, 2, 2, Collider::TAG::REWARD_BOX, 0.f, this); coll->AddRigidBody(Collider::BODY_TYPE::STATIC); frame.w = 2; frame.h = 2; life = 100; } Obj_RewardBox::~Obj_RewardBox() { } bool Obj_RewardBox::Start() { pugi::xml_node reward_box_node = app->config.child("object").child("reward_box"); reward_box_dead_sound_string = reward_box_node.child("sound").attribute("value").as_string(); reward_box_dead_sound_int = app->audio->LoadFx(reward_box_dead_sound_string); return true; } void Obj_RewardBox::OnTrigger(Collider * collider) { if (collider->GetTag() == Collider::TAG::BULLET || collider->GetTag() == Collider::TAG::FRIENDLY_BULLET) { GetDamage(collider->damage); } } bool Obj_RewardBox::Draw(float dt, Camera * camera) { app->render->DrawIsometricQuad(pos_map.x, pos_map.y, 2, 2, { 255,255,255,255 }, camera); return true; } void Obj_RewardBox::GetDamage(float damage) { if (life - damage <= 0 && life != 0) { life = 0; Dead(); } else { life -= damage; } } void Obj_RewardBox::Dead() { uint probability = rand() % 100; if (probability < 25) { app->pick_manager->CreatePickUp(pos_map, PICKUP_TYPE::ITEM); } else if (probability < 50) { fPoint offset{ 0.5f,0 }; app->pick_manager->CreatePickUp(pos_map - offset, PICKUP_TYPE::ITEM); app->pick_manager->CreatePickUp(pos_map + offset, PICKUP_TYPE::ITEM); } else if (probability < 80) { app->pick_manager->CreatePickUp(pos_map, PICKUP_TYPE::WEAPON); } else if (probability < 100) { app->pick_manager->CreatePickUp(pos_map, PICKUP_TYPE::WEAPON, 1); } my_spawn_point->occupied = false; to_remove = true; app->audio->PlayFx(reward_box_dead_sound_int); }
81d7fd3923729febd62a0c0d22e271307559387b
6ee6cc888f0a82e36fd1687fed4a109f0cb800a7
/leetcode/973.cpp
f6f1a18f8c25cf5f5c495c53eb05b4d0c87557f9
[]
no_license
Rayleigh0328/OJ
1977e3dfc05f96437749b6259eda4d13133d2c87
3d7caaf356c69868a2f4359377ec75e15dafb4c3
refs/heads/master
2021-01-21T04:32:03.645841
2019-12-01T06:33:44
2019-12-01T06:33:44
49,385,474
1
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
973.cpp
struct point{ int x, y; point(int xx, int yy):x(xx), y(yy){} }; int sq_dist(const point &p){ return p.x * p.x + p.y * p.y; } bool cmp(const point &p1, const point &p2){ return sq_dist(p1) < sq_dist(p2); } class Solution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int K) { vector<point> a; for (int i=0;i<points.size();++i) a.push_back(point(points[i][0], points[i][1])); sort(a.begin(), a.end(), cmp); vector<vector<int>> ans; for (int i=0; i<K; ++i){ vector<int> row{a[i].x, a[i].y}; ans.push_back(row); } return ans; } };
da61611ec5e5abad6dd2d5c5aba2d21be60eaa20
26e089cdfad6834f0792aef058c18620741309a5
/GLScene/sources/Renderables/InstancedMesh/GLSInstancedMesh_buffers.cpp
558e1057fb62223a9c186e39e92932e1d20a1fe5
[]
no_license
amasson42/GLSScene
fd2ec2127a07c15684fcda3188b897508e73adb4
5cc6661200e9ea3ee8b6e89f298fd4aa9c7d773d
refs/heads/master
2023-08-22T15:51:50.263599
2023-08-09T15:52:11
2023-08-09T15:52:11
129,882,209
1
0
null
2021-04-25T00:28:35
2018-04-17T09:44:32
C++
UTF-8
C++
false
false
2,349
cpp
GLSInstancedMesh_buffers.cpp
// // GLSInstanced_buffers.cpp // GLScene // // Created by Arthur Masson on 13/04/2018. // Copyright © 2018 Arthur Masson. All rights reserved. // #include "GLSMesh.hpp" namespace GLS { void InstancedMesh::generateBuffers() { Mesh::generateBuffers(); if (!Mesh::bufferGenerated()) return; glGenBuffers(1, &_transformsBuffer); if (_transformsBuffer == 0) { Mesh::deleteBuffers(); throw GLObjectCreationException(GLOBJECT_BUFFER); } glBindBuffer(GL_ARRAY_BUFFER, _transformsBuffer); glBindVertexArray(_elementsBuffer); glEnableVertexAttribArray(5); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)0); glEnableVertexAttribArray(6); glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(glm::vec4))); glEnableVertexAttribArray(7); glVertexAttribPointer(7, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(2 * sizeof(glm::vec4))); glEnableVertexAttribArray(8); glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(3 * sizeof(glm::vec4))); glVertexAttribDivisor(5, 1); glVertexAttribDivisor(6, 1); glVertexAttribDivisor(7, 1); glVertexAttribDivisor(8, 1); updateTransformsBufferValues(); } void InstancedMesh::deleteBuffers() { Mesh::deleteBuffers(); if (_transformsBuffer != 0) glDeleteBuffers(1, &_transformsBuffer); _transformsBuffer = 0; } bool InstancedMesh::bufferGenerated() const { return (Mesh::bufferGenerated() && _transformsBuffer != 0); } void InstancedMesh::updateTransformsBufferValues() { if (bufferGenerated()) { glBindVertexArray(_elementsBuffer); glBindBuffer(GL_ARRAY_BUFFER, _transformsBuffer); const size_t instancesCount = _instancesTransforms.size(); glm::mat4 *modelMatrices = new glm::mat4[instancesCount]; for (size_t i = 0; i < instancesCount; i++) modelMatrices[i] = _instancesTransforms[i].matrix(); glBufferData(GL_ARRAY_BUFFER, _instancesTransforms.size() * sizeof(glm::mat4), modelMatrices, GL_DYNAMIC_DRAW); delete [] modelMatrices; } } }
7a2b66b15b0618d7b0db9593b41ae27e35537b0e
53610da5165ac696e617a13005666eaca040177b
/ordinaryPipes/Lab.cpp
fc809d54f0c07b10252f5b93d61ba851831426ce
[]
no_license
NikkiNgNguyen/cecs326
9a69e320bc8529c5357ae672639d098f07e2418c
5e96dc1d3b7c681e14b3645e9eac1a0787c98838
refs/heads/master
2020-04-19T20:07:53.752154
2019-04-15T22:55:34
2019-04-15T22:55:34
168,407,016
0
1
null
null
null
null
UTF-8
C++
false
false
2,679
cpp
Lab.cpp
#include <sys/types.h> #include <iostream> #include <cstring> #include <unistd.h> using namespace std; int main(){ string write_msg, msg_read, write_operand; const short MSG_SIZE = 25; char msg_write[ MSG_SIZE ]; char read_msg[ MSG_SIZE ]; int fd[2]; pid_t pid; string operation[3]; pipe( fd ); //create pipe pid = fork(); //fork, req #1 if (pid > 0){ //in parent close ( fd[0] ); //close unused Read End for ( int i = 0; i < 3; i++ ){ cout << "PARENT: Enter a message to send: \n"; cin >> write_msg; cout << "PARENT, sending: " << write_msg << "\n" << endl; unsigned int size = write_msg.length(); write_msg.copy( msg_write, write_msg.length(), 0 ); write( fd[1], msg_write, MSG_SIZE ); for( int i = 0; i < MSG_SIZE; i++ ) msg_write[ i ] = '\0'; // overwrite the message local array //write( fd[1], msg_write, MSG_SIZE ); // overwrite the shared memory area } close( fd[1] ); //all done, close the pipe cout << "PARENT: exiting!\n" << endl; } else{ close( fd[1] ); //close unused write end for ( int j = 0; j < 3; j++ ){ read( fd[0], read_msg, MSG_SIZE ); msg_read = read_msg; operation[j] = msg_read; if ( j == 0 ){ cout << "CHILD: value A: " << stoi(msg_read) << "\n" << endl; if ( (stoi(msg_read) <= 0) || (stoi(msg_read) >= 100)){ cout << "Operator out of bounds \n" << endl; close ( fd[0] ); exit( 0 ); } } else if (j == 1){ if ((msg_read != "+") && (msg_read != "-")){ cout << "CHILD: operation invalid!\n" << endl; close ( fd[0] ); exit( 0 ); } else{ if (msg_read == "+"){ cout << "CHILD: operation addition\n" << endl; } else if (msg_read == "-"){ cout << "CHILD: operation subtraction\n" << endl; } } } else if ( j == 2 ){ cout << "CHILD: value B: " << stoi(msg_read) << "\n" << endl; if ((stoi(msg_read) <= 0) || (stoi(msg_read) >= 100)){ cout << "Operator out of bounds \n" << endl; close ( fd[0] ); exit( 0 ); } } } if(operation[1] == "+"){ int adding = stoi(operation[0]) + stoi(operation[2]); cout << operation[0] << " " << operation[1] << " " << operation[2] << " = " << adding << endl; } else if (operation[1] == "-"){ int subtracting = stoi(operation[0]) - stoi(operation[2]); cout << operation[0] << " " << operation[1] << " " << operation[2] << " = " << subtracting << endl; } cout << "CHILD: exiting!\n" << endl; close( fd[0] ); //all done, close the pipe! } exit( 0 ); }
a02fb8c0a5055f523e4791430c44c6d207fb5054
ebebda1f10b59d0bfa946d9e7bc9687349f95879
/src/piping.cpp
153124123c98c5363983ce372bd736b020dde3a9
[ "BSD-3-Clause" ]
permissive
bw-kiel/contraflow
7ebab038dfd87d408fa2539a16e6004b6eb09695
0199baf8b56735869b28ae526f78dcca117b2060
refs/heads/master
2021-04-17T09:29:06.632716
2020-03-20T22:08:04
2020-03-20T22:08:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
piping.cpp
#include "piping.h" #include "configuration.h" #include "interface.h" namespace contra { Piping::Piping(PipingData pipingData, FluidData fluidData) : fluid(fluidData), d_0_i(pipingData.d_0_i), d_0_o(pipingData.d_0_o), d_1_i(pipingData.d_1_i), d_1_o(pipingData.d_1_o), w(pipingData.w), lambda_0(pipingData.lambda_0), lambda_1(pipingData.lambda_1), d(0.) {} void Piping::configure(int type) { if(type == 0) configuration = new Configuration_U(this); else if(type == 1) configuration = new Configuration_2U(this); else if(type == 2) configuration = new Configuration_CX(this); else throw std::runtime_error("Segment factory: type unknown"); } void Piping::set_flow(double L) { configuration->set_flow(L); } Configuration* Piping::get_configuration() { return configuration; } }
0848d27de22edd941112d66479a30e224bee1251
7439f49b0f5652c09d8ab3dc700b9de142962864
/func/Funcao.h
db7da2bfb16bbf9a60253589d72ced9bcee67436
[]
no_license
metaheuristics/cgrasp
a211938fce994300d730916170f93798b564059d
6054abc1a66d2d5da277c684472a2e610e20a8f8
refs/heads/master
2016-09-06T15:52:38.466511
2013-05-17T19:32:02
2013-05-17T19:32:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,176
h
Funcao.h
#ifndef FUNCAO_H_ #define FUNCAO_H_ #include "ap.h" #include "real.h" class Funcao { protected: int cont; int contGrad; real minValue; real bestValue; public: static const int ROSENBROCK = 1; static const int ZAKHAROV = 2; static const int SUMSQUARES = 3; static const int BRANIN = 4; static const int EASOM = 5; static const int GOLDSTEINPRICE = 6; static const int SHEKEL = 7; static const int HARTMANN = 8; static const int SHUBERT = 9; static const int BEALE = 10; static const int BOOTH = 11; static const int BOHACHEVSKY = 12; static const int HUMP = 13; static const int MATYAS = 14; static const int SCHWEFEL = 15; static const int COLVILLE = 16; static const int PERM = 17; static const int PERM0 = 18; static const int POWERSUM = 19; static const int GRIEWANK = 20; static const int RASTRIGIN = 21; static const int TRID = 22; static const int POWELL = 23; static const int DIXONPRICE = 24; static const int ACKLEY = 25; static const int LEVY = 26; static const int SPHERE = 27; static const int SHIFTEDSPHERE = 28; static const int SHIFTEDSCHWEFEL = 29; static const int SHIFTEDSCHWEFELN = 30; static const int ROTATEDRASTRIGIN = 31; static const int ROTATEDWEIERSTRASS = 32; static const int ROTATEDEXPSCAFFERS = 33; // versoes paralelas das funcoes objetivo static const int PAR_SPHERE = 101; // metodos Funcao(); virtual ~Funcao(); virtual real calc(real *x); virtual real calc2(ap::real_1d_array x); virtual void calcGrad(ap::real_1d_array &x, ap::real_1d_array &g); virtual bool isNearOptimum(real fBest); virtual int getFnEvals(); virtual int getGradEvals(); virtual real getGap(); void setBestValue(real fX); }; #endif /*FUNCAO_H_*/
dee809dd6cd315a8acfaab604141ad706e39ec5d
314e5633c0478ac7b00d81a3d430e6444e6e1cf0
/OOP/exercise8/exercise4.cpp
5c1ededbc7c92cccf632223e3babc8cb0140ef2d
[]
no_license
Petrychho/studies
1db1df092af632719970313ded005297ad8781ca
a1d4fdc818f069849c6b604e1c9a43002d40627a
refs/heads/master
2021-09-11T01:21:26.064459
2018-04-05T15:15:01
2018-04-05T15:15:01
109,724,550
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,927
cpp
exercise4.cpp
#include <iostream> #include <string> using namespace std; class Publication { private: string book; float price; public: Publication(): book("N/A"), price(0.0) {}; void PutPublication() { cout << "Введите название книги: "; cin >> book; cout << "Введите цену книги: "; cin >> price; } void ShowPublication() { cout << book << endl; cout << "Цена книги: " << price << endl; } }; class Book : private Publication { private: int pages; public: Book() : Publication(), pages(0) {} void PutBook() { Publication::PutPublication(); cout << "Введите кол-во страниц: "; cin >> pages; } void ShowBook() { Publication::ShowPublication(); cout << "Число страниц в книге: " << pages << endl; } }; class Type : private Publication { private: int minutes; int seconds; char ch; public: Type() : Publication(), minutes(0), seconds(0) {} void PutTime() { Publication::PutPublication(); cout << "Введите время записи (мм:сс): "; cin >> minutes >> ch >> seconds; } void ShowTime() { Publication::ShowPublication(); cout << "Время аудиокниги: " << minutes << ':' << seconds << endl; } }; class Disk: private Publication { private: enum type {cd, dvd}; type cd_dvd; public: void PutDisk() { char ch; Publication::PutPublication(); cout << "CD или DVD(c/d): "; cin >> ch; switch(ch) { case 'c' : cd_dvd = cd; break; case 'd' : cd_dvd = dvd; break; } } void ShowDisk() { Publication::ShowPublication(); cout << "Тип диска: "; switch(cd_dvd) { case 0: cout << "CD" << endl; break; case 1: cout << "DVD" << endl; break; } } }; void main() { setlocale (LC_ALL, "Russian"); Disk C; C.PutDisk(); C.ShowDisk(); }
6414c19df76979c448486726234fb72aa486fddf
c87ef4aefec6b872392c99dbf905b0c9d67e1cab
/bintree/binary_tree.hpp
7dbf233b052a33b607a03e5d3b6da99b1bc00c76
[]
no_license
goodboybeau/data_structures
eefe4c470b94b4b987b06832d96378382ba47b55
204cea96ac985a297a36a2140d0e6fe6f4d3863f
refs/heads/master
2021-05-31T02:51:28.838028
2016-01-29T17:20:21
2016-01-29T17:20:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,594
hpp
binary_tree.hpp
#ifndef _BINARY_TREE_HPP_ #define _BINARY_TREE_HPP_ #include "include_c11.h" #include <scoped_lock.hpp> #include <memory> #include <atomic> #include <mutex> #include <iostream> #define DEBUG(s) std::cout << s << std::endl; std::flush(std::cout); template <typename T> struct node { node() = delete; node(const T& t) : data(t) , left(nullptr) , right(nullptr) {} node(const T* t) : data(*t) , left(nullptr) , right(nullptr) {} ~node() { if(this->left) { delete this->left; } if(this->right) { delete this->right; } } node<T>& operator=(const node<T>& other) { this->data = other.data; this->right = other.right; this->left = other.left; return *this; } T data; node<T>* left; node<T>* right; }; template <typename T> class BinaryTree { node<T>* root; std::mutex m; int size; public: BinaryTree() : root(nullptr) , size(0) {} ~BinaryTree() { if(this->root) { delete this->root; } } void insert(const T& t) { ScopedLock<std::mutex> sl(this->m); if (this->root == nullptr) { size ++; //DEBUG("new root"); this->root = new node<T>(t); return; } if (this->root->data == t) { //DEBUG("root is data"); return; } std::reference_wrapper<node<T>*> ref = std::ref(this->root); while((ref.get() != nullptr) && (ref.get()->data != t)) { if(t < ref.get()->data) { //DEBUG("left"); ref = std::ref(ref.get()->left); } else { //DEBUG("right"); ref = std::ref(ref.get()->right); } } if(ref.get() == nullptr) { //DEBUG("ref was null"); ref.get() = new node<T>(t); size ++; } else { //DEBUG("ref was not null"); } } static std::reference_wrapper<node<T>*> rec_search(const std::reference_wrapper<node<T>*> ref, const T& target) { if(ref.get() == nullptr || ref.get()->data == target) { return ref; } auto res = rec_search(std::ref(ref.get()->left), target); return res.get() == nullptr ? rec_search(std::ref(ref.get()->right), target) : res; } node<T>* search(const T& t) { return rec_search(std::ref(this->root), t).get(); } bool remove(const T& t) { auto res = this->search(t); if(!res) { return false; } node<T>* tmp; if(res->right || res->left) { tmp = res->right ? res->right : res->left; // res->right = tmp->right; // res->left = tmp->left; // res->data = tmp->data; *res = *tmp; tmp->left = tmp->right = nullptr; delete tmp; } --this->size; return true; } int getSize() { return this->size; } }; #endif /* _BINARY_TREE_HPP_ */
9d207c0dd49c3782634fc5b9392b1133eeb927cc
eedc3592e3f94aace892db75f97da3cdccff2dfc
/core/dictionary.h
387e91d070af32fac82b3c0df226209e41a253c7
[]
no_license
MatheusWoeffel/TwitterSentimentAnalysis
b54ceba26dff765cbff73e642ffdfc7f071e9601
4042ed69808b6d3373f83ff968f776ff692a2af8
refs/heads/master
2021-09-17T11:43:34.652459
2018-07-02T00:48:42
2018-07-02T00:48:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,996
h
dictionary.h
#include <vector> #include <iostream> #include "tinyutf8.h" #include <list> //Stores the information about the given word typedef struct wordData { utf8_string word; float weight; int occurrences; //Number of occurences int score; //Accumulated score wordData() : word(""), weight(0.0), occurrences(0), score(0) { } } wordData; //Estrutura utilizada durante o processo de rehashing typedef struct status{ bool ocupado; bool livre; bool realocado; status(): ocupado(false), livre(true), realocado (false) {} }STATUS; class Dictionary { private: int maxSize; int currentSize; std::vector <wordData> table; //Table that stores the registers public: //HASH E NÃO HUSH HUSH HUSH(pussycat dools) [Generates the place to where the word belongs] unsigned int hash1(utf8_string key); unsigned int hash2 (utf8_string key); //Change the size of the dictionary (maxsize), will be used in rehash void setMaxSize(int newSize); //Returns a bool that indicates if the dictionary needs re-hash or not; bool needReHash(); //Returns true if a given hash key is empty in the table bool isEmpty(unsigned int key); //Verify if the given number is prime bool isPrime(int number); //Finds the next prime number forwards actualNumber int nextPrime(int actualNumber); //Realoca posicao em nova tabela de um dado elemento void realocaPosicao(int posicao, std::vector <STATUS>& controle); //Re-hash funcion void resizeDictionary(); //Realiza o processo de rehash quando necessario void reHash(); public: //Default constructor for dictionary Dictionary(); //Insert wordData int insertWord(wordData newWord); //Retrieve wordData wordData retrieveWordData(utf8_string word); //Returns hash key for a given word int find(utf8_string word); };
453f11f751a58bbf97d7922bca596019add7c6f8
fba2a523abfa3904c212080c1d59cb05c81d262d
/calice_userlib/include/.svn/text-base/LinearFitResultLCIO.hh.svn-base
2dee561fabbe94a3e74e161fd1904e525f6e4701
[]
no_license
linghuiliu/CosmiTestLCIO
5f3ff6ae72514e56c8d5ae942ca394e3564d6405
0b8b076bd1fce8f74f1882ed6477b52894d4341a
refs/heads/master
2021-09-06T19:16:55.615298
2017-12-08T10:50:43
2017-12-08T10:50:43
110,945,118
0
1
null
null
null
null
UTF-8
C++
false
false
6,523
LinearFitResultLCIO.hh.svn-base
#ifndef LINEAR_FIT_RESULT_HH #define LINEAR_FIT_RESULT_HH 1 #include "UTIL/LCFixedObject.h" #include <cmath> #include <iostream> namespace CALICE { // helper enums: // NDF = number of degress of freedom enum EIntLFTValues {k_ID_IntLFT, k_NDF_IntLFT, kNIntLFTValues}; // no floats for the moment enum EFloatLFTValues {kNFloatLFTValues}; // first parameter offset, second slope. // error matrix: (A B) // (C D) enum EDoubleLFTValues {k_Offset_DoubleLFT, k_Slope_DoubleLFT, k_Chi2_DoubleLFT, k_ErrorMatrixA_DoubleLFT, k_ErrorMatrixB_DoubleLFT, k_ErrorMatrixC_DoubleLFT, k_ErrorMatrixD_DoubleLFT, kNDoubleLFTValues}; /** Class to store the result of a linear fit within the lcio framework. * * This class can be used for example to store the result of a * linear fit, e.g. TF1 root fit. * * Errors are stored in the error matrix. * * @author Sebastian Richter (sebastian.richter@desy.de) * @version 1.0 * @date 9 January 2009 */ class LinearFitResult : public lcio::LCFixedObject<kNIntLFTValues, kNFloatLFTValues, kNDoubleLFTValues> { public: LinearFitResult(lcio::LCObject* obj) : lcio::LCFixedObject<kNIntLFTValues, kNFloatLFTValues, kNDoubleLFTValues >(obj) {} LinearFitResult(int ID, double offset, double slope, double chi2, double eMA, double eMB, double eMC, double eMD, int ndf) { obj()->setIntVal(k_ID_IntLFT, ID); obj()->setDoubleVal(k_Offset_DoubleLFT, offset); obj()->setDoubleVal(k_Slope_DoubleLFT, slope); obj()->setDoubleVal(k_Chi2_DoubleLFT, chi2); obj()->setDoubleVal(k_ErrorMatrixA_DoubleLFT, eMA); obj()->setDoubleVal(k_ErrorMatrixB_DoubleLFT, eMB); obj()->setDoubleVal(k_ErrorMatrixC_DoubleLFT, eMC); obj()->setDoubleVal(k_ErrorMatrixD_DoubleLFT, eMD); obj()->setIntVal(k_NDF_IntLFT, ndf); } /** Evaluates the fit. * * @param x - point where the fit is evaluated: getOffset() + x * getSlope() * */ double eval(const double x) const { return getOffset() + x*getSlope(); } /** Get the identifier. */ int getID() const { return getIntVal(k_ID_IntLFT); } /** Get the number of degress of freedom of the fit. */ int getNDF() const { return getIntVal(k_NDF_IntLFT); } /** Get the offset/y-intercept of the fit. * * The offset is equivalent to eval(0). * */ double getOffset() const { return getDoubleVal(k_Offset_DoubleLFT); } /** Get the slope of the fit. */ double getSlope() const { return getDoubleVal(k_Slope_DoubleLFT); } /** Get the Chi2 of the fit. */ double getChi2() const { return getDoubleVal(k_Chi2_DoubleLFT); } /** Get the error matrix of the fit. * * The first parameter is the offset, the second one is the slope. * */ void getErrorMatrix(double errorMatrix[2][2]) const { errorMatrix[0][0] = getDoubleVal(k_ErrorMatrixA_DoubleLFT); errorMatrix[0][1] = getDoubleVal(k_ErrorMatrixB_DoubleLFT); errorMatrix[1][0] = getDoubleVal(k_ErrorMatrixC_DoubleLFT); errorMatrix[1][1] = getDoubleVal(k_ErrorMatrixD_DoubleLFT); } /** Get the error of the offset. */ double getOffsetError() const { static double errormatrix[2][2]; getErrorMatrix(errormatrix); return sqrt(errormatrix[0][0]); } /** Get the error of the slope. */ double getSlopeError() const { static double errormatrix[2][2]; getErrorMatrix(errormatrix); return sqrt(errormatrix[1][1]); } /** Sets an identifier. */ void setID(const int ID) { obj()->setIntVal(k_ID_IntLFT, ID); } /** Sets the number of degress of freedom. */ void setNDF(const int NDF) { obj()->setIntVal(k_NDF_IntLFT, NDF); } /** Sets the offset. */ void setOffset(const double offset) { obj()->setDoubleVal(k_Offset_DoubleLFT, offset); } /** Sets the slope. */ void setSlope(const double slope) { obj()->setDoubleVal(k_Slope_DoubleLFT, slope); } /** Sets the chi2. */ void setChi2(const double chi2) { obj()->setDoubleVal(k_Chi2_DoubleLFT, chi2); } /** Sets the full error matrix. */ void setErrorMatrix(const double array[2][2]) { obj()->setDoubleVal(k_ErrorMatrixA_DoubleLFT, array[0][0]); obj()->setDoubleVal(k_ErrorMatrixB_DoubleLFT, array[0][1]); obj()->setDoubleVal(k_ErrorMatrixC_DoubleLFT, array[1][0]); obj()->setDoubleVal(k_ErrorMatrixD_DoubleLFT, array[1][1]); } /** Sets the error of the offset. */ void setOffsetError(double offsetError) { obj()->setDoubleVal(k_ErrorMatrixA_DoubleLFT, offsetError * offsetError); } /** Sets the error of the slope. */ void setSlopeError(double slopeError) { obj()->setDoubleVal(k_ErrorMatrixD_DoubleLFT, slopeError * slopeError); } /** Get the type name. * * The type name is used to determine which class interprets the * LCGenericObject which holds the pure data. */ const std::string getTypeName() const { return "LinearFitResult"; } /** Get the data description. * * The data description gives the meaning of the data fields. * */ const std::string getDataDescription() const { return "i:ID,i:NDF,f:offset,f:slope,f:chi2,f:errorMatrix00," ",f:errorMatrix01," ",f:errorMatrix10," ",f:errorMatrix11"; } private: }; inline std::ostream& operator<<(std::ostream& out, const CALICE::LinearFitResult& lfr) { out << "ID: " << lfr.getID() << " offset: " << lfr.getOffset() << " slope: " << lfr.getSlope(); return out; } } #endif
308324a1d9177743c3ff5e170269349a89d956d2
ba1bb8d233cd3c2e8953f879d7c054307118f606
/SystemCImplementation/controller/stage_counter/stage_counter.hpp
b694c4da1bf4b9b8cd66224fc996a645656e2f37
[]
no_license
hzc9107/FFT_PROJECT
4f1869cebb2ba0858a5622e4c3583cfaf5acf37f
b2f7b0b2bdb1b5c4c007c0531ff20cd46be0c5c7
refs/heads/master
2021-09-16T00:23:38.268093
2018-06-13T20:19:28
2018-06-13T20:19:28
109,652,170
0
0
null
null
null
null
UTF-8
C++
false
false
759
hpp
stage_counter.hpp
#include<systemc> #ifndef STAGE_CNT_H #define STAGE_CNT_H template<unsigned int stage_width> SC_MODULE(stage_counter){ // Inputs sc_core::sc_in_clk clk; sc_core::sc_in<bool> reset, enable, stage_finish; // Outputs sc_core::sc_out<sc_dt::sc_uint<stage_width> > stage_cnt; // Internal Var sc_dt::sc_uint<stage_width> stage_cnt_reg; // Process void count_stage(); SC_CTOR(stage_counter){ SC_METHOD(count_stage); sensitive << clk.pos(); } }; template<unsigned int stage_width> void stage_counter<stage_width>::count_stage(){ if(reset){ stage_cnt_reg = 0; } else { if(enable && stage_finish){ ++stage_cnt_reg; } } stage_cnt.write(stage_cnt_reg); } #endif
e3396834e155e7144f3fda762e7af2279756c568
58b5ca0ad9d0db45bc4c47ea0c62e6424b779ba2
/Week_01/day-5/31/main.cpp
c2da26e5924dce34d33cdbe814d555a67f274eea
[]
no_license
green-fox-academy/znemeth
b72f48f4621c9434b1ae114c5b1c368cc21f87c1
eda20c847143812f77d3e5d44614be49cc6dcbbc
refs/heads/master
2020-04-16T18:51:54.696643
2019-07-25T14:27:37
2019-07-25T14:27:37
165,837,872
0
2
null
null
null
null
UTF-8
C++
false
false
639
cpp
main.cpp
#include <iostream> int main(int argc, char* args[]) { // Write a program that reads a number from the standard input, then draws a // square like this: // // // %%%%%% // % % // % % // % % // % % // %%%%%% // // The square should have as many lines as the number was int a = 6; for (int i=0; i<a; i++) { for (int j=0; j<a; j++) { if(i>0 && i<(a-1) && j>0 && j<(a-1)){ std::cout << " "; } else { std::cout << "*"; } } std::cout<< "\n" <<std::endl; }; return 0; }
00097d04e196faaffbcabe10b727c8283c311b93
7d0f691bd1b39033de8dc67e8712fc6863c4bdde
/src/hello.cpp
43ad69126082840e1b23852c707d610de0b63888
[]
no_license
LJLCarrien/nodeTest
3e702f8ffcca74bbdb3eac26d8c8d010382c5b61
8ccf5b97eed37c1f9374f9b9659e25dc784701e5
refs/heads/master
2022-12-15T09:12:50.909829
2020-09-03T10:14:28
2020-09-03T10:14:28
292,163,978
0
0
null
null
null
null
UTF-8
C++
false
false
2,593
cpp
hello.cpp
#include <node.h> using namespace v8; namespace demo { // using v8::FunctionCallbackInfo; // using v8::Isolate; // using v8::Local; // using v8::Number; // using v8::Object; // using v8::String; // using v8::Value; // Method1 实现一个 输出"hello world ONE !" 的方法 void Method1(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world ONE !")); } // Method2 实现一个 加一 的方法 void Method2(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); // 获取参数,js Number 类型转换成 v8 Number 类型 Local<Number> value = Local<Number>::Cast(args[0]); double num = value->NumberValue() + 1; // double 转 char*,这里我不知道有没有其他办法 char buf[128] = {0}; sprintf(buf, "%f", num); args.GetReturnValue().Set(String::NewFromUtf8(isolate, buf)); } //callback void CallThis(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); Local<Function> cb = Local<Function>::Cast(args[0]); cb->Call(Null(isolate), 0, nullptr); } void CallThisWithThis(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); Local<Function> cb = Local<Function>::Cast(args[0]); Local<Value> argv[1] = {args[1]}; cb->Call(Null(isolate), 1, argv); } //add void Add(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); if (args.Length() < 2) { return; } double value = args[0]->NumberValue() + args[1]->NumberValue(); Local<Number> num = Number::New(isolate, value); args.GetReturnValue().Set(num); } //whocalled void Whocalled(const FunctionCallbackInfo<Value> &args) { args.GetReturnValue().Set(args.Holder()); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "hello", Method1); NODE_SET_METHOD(exports, "addOne", Method2); //callback NODE_SET_METHOD(exports, "callthis", CallThis); // we'll create Add in a moment... NODE_SET_METHOD(exports, "callthis_withthis", CallThisWithThis); //add NODE_SET_METHOD(exports, "add", Add); //whocalled NODE_SET_METHOD(exports, "whocalled", Whocalled); } NODE_MODULE(addon, init) } // namespace demo
49442df5b4268ac9ab6f111df7c11ec7689ff6bd
6ef53083d8de65d54bc20ec1a06060458ec92ebe
/2.1/2.1.13/test2113.cpp
bd0407b3e7c4cb1c896f8bdd30e80591937c32d1
[]
no_license
lanecoder/leetcode
fa5c59dfd2344412bf8902dc1f68b02698478f31
419c9f814d25e54682fe13c658801a3c23ace239
refs/heads/master
2020-03-19T23:38:23.329400
2018-07-21T10:43:06
2018-07-21T10:43:06
137,013,712
0
0
null
null
null
null
UTF-8
C++
false
false
933
cpp
test2113.cpp
#include<iostream> #include<vector> #include<string> #include<algorithm> // the set [1,2,3...n] contains a total of !n unique permulation // by listing and labeling all of the permulation in order,we get // the following sequence(ie,for n=3): // "123" "132" "213" "231" "312" "321" // given n and k,return the kth permulation sequence // note:given n will be between 1 and 9 inclusive using namespace std; class Solution{ public: string find_kth(int n, int k){ string res; string num = "123456789"; vector<int> ve(n,1); for(int i = 1;i<n;i++)ve[i]=ve[i-1]*i; // !n --k; // match to the index of array for(int i = n;i>=1;i--){ int j = k / ve[i-1]; // hignest index of the kth permulation k %= ve[i-1]; // calc the new 'k' res.push_back(num[j]); num.erase(j,1); } return res; } }; int main(){ Solution s; string s1 = s.find_kth(4, 15); cout<<s1<<endl; return 0; }
f76be4f3a4a7919448ee743adf8632a4d766fb33
e1951b7f7a739b96e961797f8849e58dcb41f00d
/falcon/mpl/back_inserter.hpp
1769f4680c1f0b056dfe9f28383041be72803426
[ "MIT" ]
permissive
jonathanpoelen/falcon
fcf2a92441bb2a7fc0c025ff25a197d24611da71
5b60a39787eedf15b801d83384193a05efd41a89
refs/heads/master
2021-01-17T10:21:17.492484
2016-03-27T23:28:50
2016-03-27T23:28:50
6,459,776
2
0
null
null
null
null
UTF-8
C++
false
false
322
hpp
back_inserter.hpp
#ifndef FALCON_MPL_BACK_INSERTER_HPP #define FALCON_MPL_BACK_INSERTER_HPP #include <falcon/mpl/push_back.hpp> #include <falcon/mpl/inserter.hpp> #include <falcon/mpl/arg.hpp> namespace falcon { namespace mpl { template<typename Sequence> using back_inserter = inserter<Sequence, push_back<arg<1>, arg<2>>>; }} #endif
ce8056915350f1de5ada085d62d15b9af5ec5f68
443771b647250b420cde376f43d4c879ad0bd417
/test/project_euler/0001-0050/Problem12.cpp
e32646adaff6cb22db13bf2a5240a689d5377d22
[ "MIT" ]
permissive
wtmitchell/challenge_problems
09c07e6d4d5b2275da3e47721cd1538b0f4e2278
b0fd328af41901aa53f757f1dd84f44f71d7be44
refs/heads/master
2020-12-24T08:54:48.229896
2020-04-04T12:03:52
2020-04-04T12:03:52
13,024,003
2
0
null
null
null
null
UTF-8
C++
false
false
996
cpp
Problem12.cpp
#include <gtest/gtest.h> #include "project_euler/Factory.h" using project_euler::Factory::create; #include "project_euler/0001-0050/Problem12.h" using project_euler::Problem12; TEST(Problem12, bruteForce) { Problem12 p; EXPECT_EQ(28, p.bruteForce(5)); EXPECT_EQ(76576500, p.bruteForce(500)); } TEST(Problem12, faster) { Problem12 p; EXPECT_EQ(28, p.faster(5)); EXPECT_EQ(73920, p.faster(100)); EXPECT_EQ(76576500, p.faster(500)); EXPECT_EQ(842161320, p.faster(1000)); EXPECT_EQ(7589181600, p.faster(1500)); } TEST(Problem12, faster2) { Problem12 p; EXPECT_EQ(28, p.faster2(5)); EXPECT_EQ(73920, p.faster2(100)); EXPECT_EQ(76576500, p.faster2(500)); EXPECT_EQ(842161320, p.faster2(1000)); EXPECT_EQ(7589181600, p.faster2(1500)); } TEST(Problem12, ViaFactory) { auto p = create(12); p->solve(); EXPECT_EQ("The 12375th triangular number is the first triangular number with " "over 500 divisors. It is 76576500", p->answer()); }
d3ee06af6877d009064c77a3d5e174b6f73c1ecd
4363abbef1d9ae18ed418cea00cb6cf0ee78b4b7
/2-dimention array.cpp
92c652eacfbec03856d5f1e5fd70b83defa88e99
[]
no_license
michaelY386/Leetcode-problems
67c99cff90110188352f685b2b7176191db5308d
f4c89ef73a72008105da701b83fb70aa4e668036
refs/heads/master
2021-07-05T10:24:28.773123
2017-10-01T19:22:00
2017-10-01T19:22:00
104,435,839
0
0
null
null
null
null
UTF-8
C++
false
false
1,037
cpp
2-dimention array.cpp
#include <iostream> #include <cstdio> #include <vector> #include <cstdlib> using namespace std; void Traverse(int direction, int i, int j, vector<vector<int>>& matrix, vector<vector<int>>& flag) { const int dx[] = {0, 1, 0, -1}; const int dy[] = {1, 0, -1, 0}; int m = matrix.size(); int n = matrix[0].size(); if (flag[i][j] || i < 0 || j < 0 || i >= m || j >= n) { return; } while (!flag[i][j] && j < n && i < m & j >= 0 && i >= 0) { flag[i][j] = 1; printf("%d ", matrix[i][j]); i+=dx[direction]; j+=dy[direction]; } i-=dx[direction]; j-=dy[direction]; direction = (direction + 1) % 4; i+=dx[direction]; j+=dy[direction]; Traverse(direction, i, j, matrix, flag); } int main() { //given a vector<vector<int>> matrix vector<vector<int>> matrix; int m = matrix.size(); int n = matrix[0].size(); vector<vector<int>> flag(m + 1, vector<int>(n + 1, 0)); Traverse(0, 0, 0, matrix, flag); }
9b18076bb1f55762a474539fa9d6ca9760e2b0dc
529d526489190b75a700e3ebe4a176576766141c
/cpp/String/String/main.cpp
d9f64c05e65cb39cea41e98a4ce8df809191b1ae
[]
no_license
chongqichuizi/cpp_homework
306c975d2feca8338f46fb85c23cff6992b02131
6896027f5059f18b2ea8f9537f4873759599d2d5
refs/heads/master
2020-05-18T06:17:12.619594
2019-05-15T12:28:58
2019-05-15T12:28:58
184,229,887
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
647
cpp
main.cpp
#include <iostream> #include "String.h" using namespace std; int main() { String str1, str2, str3, temp; cout << "please input three strings:"<<endl; cin >> str1 >> str2 >> str3; cout << "str1 + str2 = " << str1 + str2 << endl; if (str2 > str3){ temp = str2; str2 = str3; str3 = temp; } if (str1 <= str2) cout << str1 << " " << str2 << " " << str3 << endl; else if (str1 <= str3) cout << str2 << " " << str1 << " " << str3 << endl; else cout << str2 << " " << str3 << " " << str1 << endl; //°´×Ö·ûÖð¸öÊä³östr3×Ö·û´® for (int i = 0; i < str3.Size(); ++i) cout << str3[i]; cout << endl; return 0; }
a6094183a4842714ca3e439a1ba987b13c4efec9
d5a4f0e7c362c432299f06e7e81908eb72df5226
/Cola2.cpp
6f75a3ae42d3e160062860501c4f576855d20fc0
[]
no_license
Brian022/Stack-and-Queue
9f8571d25288d9815094c9078c7e5d0663be3fea
74f1b55c9cb6d3d99f22b800d2b49f27026294b4
refs/heads/master
2020-06-06T07:32:06.226197
2019-06-26T17:19:38
2019-06-26T17:19:38
192,678,503
0
0
null
null
null
null
UTF-8
C++
false
false
2,089
cpp
Cola2.cpp
#include <iostream> using namespace std; template<typename T> class Cola; template<typename T> class Node { private: Node<T> *sgte; T data; public: Node(T data){this->data = data;} friend class Cola<T>; }; template<typename T> class Cola { private: Node<T> *first; Node<T> *actual; int tam =0; public: Cola() { first = NULL; } ~Cola() { while(!vacio()) { pop(); } } bool vacio() { if(first == NULL) { return true; } else return false; } int Size() { int tam = 0; Node<T> *actual = first; while(actual != NULL) { tam += 1; actual = actual->sgte; } return tam; } void push(T data) { Node<T> *nuevo = new Node<T>(data); if(first == NULL) { first = nuevo; first->sgte =NULL; } else { Node<T> *actual = first; while(actual->sgte != NULL){actual = actual->sgte;} actual->sgte = nuevo; } } void pop() { if(!vacio()) { Node<T> *actual = first; first = first->sgte; delete actual; } } void mostrar() { Node<T> *actual = first; while(actual != NULL) { cout<<actual->data<< "-> "; actual = actual->sgte; } } }; int main() { Cola<int> a; a.push(5); a.push(7); a.mostrar(); cout<<"Tamano = "<<a.Size()<<"\n"; a.pop(); a.pop(); a.pop(); a.push(4); a.mostrar(); cout<<"Tamano = "<<a.Size()<<"\n"; a.pop(); a.push(3); a.push(7); a.pop(); a.mostrar(); cout<<"Tamano = "<<a.Size()<<"\n"; return 0; }
182d15b4e86fd75f90515ffb604a2a3825f2bdb1
cc047b5c8a3a8049912a15d03e37fa4f68aaf37b
/9/Ćw 9,2.cpp
83b280a0a64e8e33fe44cc1b6b74a6f40c963062
[]
no_license
SeiperLu/Nauka
a046609f38478ddd5f1922a74eb1d3bd59bdd8d5
39411650c262b6b9232d9a0ab3859240a72c9f9e
refs/heads/master
2023-07-14T19:29:45.229810
2021-08-12T11:04:39
2021-08-12T11:04:39
343,428,592
0
0
null
null
null
null
UTF-8
C++
false
false
716
cpp
Ćw 9,2.cpp
#include<iostream> #include<cstring> using namespace std; void strcount(const string str); int main() { string input; char next; cout << "Wprowadz wiersz:\n"; getline(cin, input); while (cin) { strcount(input); cout << "Wprowadz nastepny wiersz (wiersz pusty konczy wprowadzanie):\n"; getline(cin, input); } cout << "Koniec\n"; cin.ignore(); return 0; } void strcount(const string str) { static int total = 0; int count = 0; cout << "\"" << str << "\" zawiera "; while(str[count] != '\0') count++; total += count; cout << count << " znakow\n"; cout << "Lacznie " << total << " znakow\n"; }
a48dc6703d9fba1302cd0e82b912f282ee279b1f
676259e3d88b159d388ab19f8b090a02a0785457
/Plataforma/saboteador_base/src/saboteador_hw_interface.cpp
faf82c88ad99df5ac16fbc7301bb294f899b4bd2
[]
no_license
jj-jc/Saboteador
a78df3e952a985c9e132d1cd79fb1bbc7bd5756d
3ffe7baa611828b1959b41033402be3ce46389bf
refs/heads/master
2023-08-20T18:58:20.552438
2021-05-27T08:53:26
2021-05-27T08:53:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,290
cpp
saboteador_hw_interface.cpp
#include <saboteador_base/saboteador_hw_interface.h> // ROS parameter loading #include <rosparam_shortcuts/rosparam_shortcuts.h> #include <std_msgs/Float32.h> //#include <std_msgs/Int32.h> #include <iomanip> namespace saboteador_base { SaboteadorHWInterface::SaboteadorHWInterface(ros::NodeHandle &nh, urdf::Model *urdf_model) : name_("hardware_interface") , nh_(nh) { // Initialization of the robot's resources (joints, sensors, actuators) and // interfaces can be done here or inside init(). // E.g. parse the URDF for joint names & interfaces, then initialize them // Check if the URDF model needs to be loaded if (urdf_model == NULL) loadURDF(nh, "robot_description"); else urdf_model_ = urdf_model; // Load rosparams ros::NodeHandle rpnh(nh_, name_); std::size_t error = 0; // Code API of rosparam_shortcuts: // http://docs.ros.org/en/noetic/api/rosparam_shortcuts/html/namespacerosparam__shortcuts.html#aa6536fe0130903960b1de4872df68d5d error += !rosparam_shortcuts::get(name_, rpnh, "joints", joint_names_); error += !rosparam_shortcuts::get(name_, nh_, "mobile_base_controller/wheel_radius", wheel_radius_); error += !rosparam_shortcuts::get(name_, nh_, "mobile_base_controller/linear/x/max_velocity", max_velocity_); rosparam_shortcuts::shutdownIfError(name_, error); wheel_diameter_ = 2.0 * wheel_radius_; //max_velocity_ = 0.2; // m/s // ros_control RobotHW needs velocity in rad/s but in the config its given in m/s max_velocity_ = linearToAngular(max_velocity_); // Setup publisher for the motor driver pub_left_motor_value_ = nh_.advertise<std_msgs::Float32>("motor_left", 10); pub_right_motor_value_ = nh_.advertise<std_msgs::Float32>("motor_right", 10); // Observación, sería mejor sub_encoders_ticks // Setup subscriber for the wheel encoders //sub_left_encoder_ticks_ = nh_.subscribe("encoder_ticks", 10, &SaboteadorHWInterface::encoderTicksCallback, this); sub_encoder_ticks_ = nh.subscribe("encoder_ticks", 10, &SaboteadorHWInterface::encoderTicksCallback, this); // Initialize the hardware interface init(nh_, nh_); } bool SaboteadorHWInterface::init(ros::NodeHandle &root_nh, ros::NodeHandle &robot_hw_nh) { ROS_INFO("Initializing saboteador Hardware Interface ..."); num_joints_ = joint_names_.size(); ROS_INFO("Number of joints: %d", (int)num_joints_); std::array<std::string, NUM_JOINTS> motor_names = {"left_motor", "right_motor"}; for (unsigned int i = 0; i < num_joints_; i++) { // Create a JointStateHandle for each joint and register them with the // JointStateInterface. hardware_interface::JointStateHandle joint_state_handle(joint_names_[i], &joint_positions_[i], &joint_velocities_[i], &joint_efforts_[i]); joint_state_interface_.registerHandle(joint_state_handle); // Create a JointHandle (read and write) for each controllable joint // using the read-only joint handles within the JointStateInterface and // register them with the JointVelocityInterface. hardware_interface::JointHandle joint_handle(joint_state_handle, &joint_velocity_commands_[i]); velocity_joint_interface_.registerHandle(joint_handle); // Initialize joint states with zero values joint_positions_[i] = 0.0; joint_velocities_[i] = 0.0; joint_efforts_[i] = 0.0; // unused with diff_drive_controller joint_velocity_commands_[i] = 0.0; // Initialize the pid controllers for the motors using the robot namespace std::string pid_namespace = "pid/" + motor_names[i]; ROS_INFO_STREAM("pid namespace: " << pid_namespace); ros::NodeHandle nh(root_nh, pid_namespace); // TODO implement builder pattern to initialize values otherwise it is hard to see which parameter is what. // feedforward, proportional, integral, derivative, i_max, i_min, antiwindup, out_max, out_min pids_[i].init(nh, 0.0, 7.0, 0.0, 0.00, 0.0, 0.0, false, 100.0, -100.0); // pids_[i].setOutputLimits(-max_velocity_, max_velocity_); } // Register the JointStateInterface containing the read only joints // with this robot's hardware_interface::RobotHW. registerInterface(&joint_state_interface_); // Register the JointVelocityInterface containing the read/write joints // with this robot's hardware_interface::RobotHW. registerInterface(&velocity_joint_interface_); //Observación encoder_ticks_[0] = 0; encoder_ticks_[1] = 0; ROS_INFO("... Done Initializing saboteador Hardware Interface"); return true; } void SaboteadorHWInterface::read(const ros::Time& time, const ros::Duration& period) { //ROS_INFO_THROTTLE(1, "Read"); ros::Duration elapsed_time = period; // Read from robot hw (motor encoders) // Fill joint_state_* members with read values double wheel_angles[2]; double wheel_angle_deltas[2] = {0,0}; /*for (std::size_t i = 0; i < num_joints_; ++i) { wheel_angles[i] = ticksToAngle(encoder_ticks_[i]); //double wheel_angle_normalized = normalizeAngle(wheel_angle); wheel_angle_deltas[i] = wheel_angles[i] - joint_positions_[i]; joint_positions_[i] += wheel_angle_deltas[i]; joint_velocities_[i] = wheel_angle_deltas[i] / period.toSec(); joint_efforts_[i] = 0.0; // unused with diff_drive_controller }*/ for (std::size_t i = 0; i < num_joints_; ++i){ wheel_angles[i] = ticksToAngle(encoder_ticks_[i]); joint_velocities_[i] = wheel_angles[i] / period.toSec(); joint_positions_[i] = 0.0; //unused joint_efforts_[i] = 0.0; // unused } const int width = 10; const char sep = ' '; std::stringstream ss; ss << std::left << std::setw(width) << std::setfill(sep) << "Read" << std::left << std::setw(width) << std::setfill(sep) << "ticks" << std::left << std::setw(width) << std::setfill(sep) << "angle" << std::left << std::setw(width) << std::setfill(sep) << "velocity" << std::endl; ss << std::left << std::setw(width) << std::setfill(sep) << "j0:" << std::left << std::setw(width) << std::setfill(sep) << encoder_ticks_[0] << std::left << std::setw(width) << std::setfill(sep) << wheel_angles[0] << std::left << std::setw(width) << std::setfill(sep) << joint_velocities_[0] << std::endl; ss << std::left << std::setw(width) << std::setfill(sep) << "j1:" << std::left << std::setw(width) << std::setfill(sep) << encoder_ticks_[1] << std::left << std::setw(width) << std::setfill(sep) << wheel_angles[1] << std::left << std::setw(width) << std::setfill(sep) << joint_velocities_[1]; ROS_INFO_STREAM(std::endl << ss.str()); //printState(); } void SaboteadorHWInterface::write(const ros::Time& time, const ros::Duration& period) { ros::Duration elapsed_time = period; // Write to robot hw // joint velocity commands from ros_control's RobotHW are in rad/s // Convert the velocity command to a percentage value for the motor // This maps the velocity to a percentage value which is used to apply // a percentage of the highest possible battery voltage to each motor. std_msgs::Float32 left_motor; std_msgs::Float32 right_motor; double pid_outputs[NUM_JOINTS]; double motor_cmds[NUM_JOINTS] = {0,0}; pid_outputs[0] = pids_[0](joint_velocities_[0], joint_velocity_commands_[0], period); pid_outputs[1] = pids_[1](joint_velocities_[1], joint_velocity_commands_[1], period); // Observación: La salida del PID debería ser directamente el motor_cmd ////////////////////////////////////////////////////////////////////// //motor_cmds[0] = pid_outputs[0] / max_velocity_ * 100.0; //motor_cmds[1] = pid_outputs[1] / max_velocity_ * 100.0; //left_motor.data = motor_cmds[0]; //right_motor.data = motor_cmds[1]; //////////////////////////////////////////////////////////////// left_motor.data = pid_outputs[0]; right_motor.data = pid_outputs[1]; // Calibrate motor commands to deal with different gear friction in the // left and right motors and possible differences in the wheels. // Add calibration offsets to motor output in low regions // To tune these offset values command the robot to drive in a straight line and // adjust if it isn't going straight. // int left_offset = 10; // int right_offset = 5; // int threshold = 55; // if (0 < left_motor.data && left_motor.data < threshold) // { // // the second part of the multiplication lets the offset decrease with growing motor values // left_motor.data += left_offset * (threshold - left_motor.data) / threshold; // } // if (0 < right_motor.data && right_motor.data < threshold) // { // // the second part of the multiplication lets the offset decrease with growing motor values // right_motor.data += right_offset * (threshold - right_motor.data) / threshold; // } pub_left_motor_value_.publish(left_motor); pub_right_motor_value_.publish(right_motor); const int width = 10; const char sep = ' '; std::stringstream ss; // Cortesía Antonio Carralero, error: to_string() // std::stringstream num_joints; // Header ss << std::left << std::setw(width) << std::setfill(sep) << "Write" << std::left << std::setw(width) << std::setfill(sep) << "vel_cmd" << std::left << std::setw(width) << std::setfill(sep) << "p_error" << std::left << std::setw(width) << std::setfill(sep) << "i_error" << std::left << std::setw(width) << std::setfill(sep) << "d_error" << std::left << std::setw(width) << std::setfill(sep) << "pid out" << std::endl; double p_error, i_error, d_error; for (int i = 0; i < NUM_JOINTS; ++i) { pids_[i].getCurrentPIDErrors(&p_error, &i_error, &d_error); // Joint i std::string j = "j" + std::to_string(i) + ":"; ss << std::left << std::setw(width) << std::setfill(sep) << j << std::left << std::setw(width) << std::setfill(sep) << joint_velocity_commands_[i] << std::left << std::setw(width) << std::setfill(sep) << p_error << std::left << std::setw(width) << std::setfill(sep) << i_error << std::left << std::setw(width) << std::setfill(sep) << d_error << std::left << std::setw(width) << std::setfill(sep) << pid_outputs[i] << std::endl; } ROS_INFO_STREAM(std::endl << ss.str()); } void SaboteadorHWInterface::loadURDF(const ros::NodeHandle &nh, std::string param_name) { std::string urdf_string; urdf_model_ = new urdf::Model(); // search and wait for robot_description on param server while (urdf_string.empty() && ros::ok()) { std::string search_param_name; if (nh.searchParam(param_name, search_param_name)) { ROS_INFO_STREAM_NAMED(name_, "Waiting for model URDF on the ROS param server at location: " << nh.getNamespace() << search_param_name); nh.getParam(search_param_name, urdf_string); } else { ROS_INFO_STREAM_NAMED(name_, "Waiting for model URDF on the ROS param server at location: " << nh.getNamespace() << param_name); nh.getParam(param_name, urdf_string); } usleep(100000); } if (!urdf_model_->initString(urdf_string)) ROS_ERROR_STREAM_NAMED(name_, "Unable to load URDF model"); else ROS_DEBUG_STREAM_NAMED(name_, "Received URDF from param server"); } void SaboteadorHWInterface::printState() { // WARNING: THIS IS NOT REALTIME SAFE // FOR DEBUGGING ONLY, USE AT YOUR OWN ROBOT's RISK! ROS_INFO_STREAM_THROTTLE(1, std::endl << printStateHelper()); } std::string SaboteadorHWInterface::printStateHelper() { std::stringstream ss; std::cout.precision(15); for (std::size_t i = 0; i < num_joints_; ++i) { ss << "j" << i << ": " << std::fixed << joint_positions_[i] << "\t "; ss << std::fixed << joint_velocities_[i] << "\t "; ss << std::fixed << joint_efforts_[i] << std::endl; } return ss.str(); } std::string SaboteadorHWInterface::printCommandHelper() { std::stringstream ss; std::cout.precision(15); ss << " position velocity effort \n"; for (std::size_t i = 0; i < num_joints_; ++i) { ss << std::fixed << joint_velocity_commands_[i] << "\t "; } return ss.str(); } /// Process updates from encoders void SaboteadorHWInterface::encoderTicksCallback(const diffbot_msgs::Encoder::ConstPtr& msg) { /// Update current encoder ticks in encoders array encoder_ticks_[0] = msg->encoders[0]; encoder_ticks_[1] = msg->encoders[1]; ROS_DEBUG_STREAM_THROTTLE(1, "Left encoder ticks: " << encoder_ticks_[0]); ROS_DEBUG_STREAM_THROTTLE(1, "Right encoder ticks: " << encoder_ticks_[1]); } double SaboteadorHWInterface::ticksToAngle(const int &ticks) const { // Convert number of encoder ticks to angle in radians // Nótese que double angle = (double)ticks * (2.0*M_PI / 3000.0); ROS_DEBUG_STREAM_THROTTLE(1, ticks << " ticks correspond to an angle of " << angle); return angle; } double SaboteadorHWInterface::normalizeAngle(double &angle) const { // https://stackoverflow.com/questions/11498169/dealing-with-angle-wrap-in-c-code angle = fmod(angle, 2.0*M_PI); if (angle < 0) angle += 2.0*M_PI; ROS_DEBUG_STREAM_THROTTLE(1, "Normalized angle: " << angle); return angle; } double SaboteadorHWInterface::linearToAngular(const double &distance) const { return distance / wheel_diameter_ * 2.0; } double SaboteadorHWInterface::angularToLinear(const double &angle) const { return angle * wheel_diameter_ / 2.0; } };
a2a1b1a10bcc0f1842ceb4d6189175931b4142e5
6e45a15f8fb5d919f573924b20a2c5f835776c48
/PacketGenerator/MessageManager.cpp
fd651b2b6c46a936dee364219bb0fec7ca7526ec
[]
no_license
433Project/PacketGenerator
c169a6db8ca37fba2ab3ef23be8240ad4d4e8308
6082d0c49d987bc56774f43a7ee363ec810549c2
refs/heads/master
2021-01-17T18:11:42.197178
2016-11-24T06:16:57
2016-11-24T06:16:57
71,208,362
0
0
null
2016-11-17T06:21:56
2016-10-18T04:18:15
C++
UTF-8
C++
false
false
794
cpp
MessageManager.cpp
#include "MessageManager.h" MessageManager::MessageManager(int packetSize) { this->packetSize = packetSize; } MessageManager::~MessageManager() { } void MessageManager::MakePacket(char* bytes, COMMAND comm, string data1) { flatbuffers::FlatBufferBuilder builder; flatbuffers::Offset<Body> body; if (data1.empty()) body = CreateBody(builder, comm, STATUS_NONE); else body = CreateBody(builder, comm, STATUS_NONE, builder.CreateString(data1)); builder.Finish(body); uint8_t* buf = builder.GetBufferPointer(); char* b = reinterpret_cast<char*>(buf); int len = builder.GetSize(); Header* h = new Header(len, PACKET_GENERATOR, 0, MONITORING_SERVER, 0); memset(bytes, 0, packetSize); memcpy(bytes, h, sizeof(Header)); memcpy(&bytes[sizeof(Header)], b, len); delete h; }
320dd41037bea6b2fb3ffeefa529880f62e5ec7a
8f9a6ca8f37eb4a85e4a0519bc76d6a4525493cc
/google-codejam/Qualification Round 2009/Alien Language/solution.cpp
437b4fa8ac331f14fd13b8c49a6e011bae55a982
[]
no_license
shivam04/codes
58057cc7c79171fdad6b597f744448573f581ea0
46f7c0f0f81304b2169a1a25ed7e95835d63e92c
refs/heads/master
2023-07-19T17:17:21.414147
2023-07-09T17:41:07
2023-07-09T17:41:07
75,619,021
5
1
null
null
null
null
UTF-8
C++
false
false
1,117
cpp
solution.cpp
#include <bits/stdc++.h> using namespace std; int ans(vector<string> words, string w[], int l) { int cnt = 0; int anss = 0; for(int i=0;i<l;i++) { int cnt = 0; for(int j=0;j<w[i].length();j++) { // fout<<w[i][j]<<" "<<words[j]<<"\n"; for(int k=0;k<words[j].length();k++) { if(words[j][k]==w[i][j]) { cnt++; break; } } } // fout<<cnt<<"\n"; if(cnt == w[i].length()) { anss++; } } return anss; } int main() { fstream fout,fin; fin.open("A-large-practice.txt",ios::in); fout.open("A-large-practice-output.txt",ios::out); int l,d,n; fin>>l>>d>>n; string w[d+1]; for(int i=0;i<d;i++) { fin>>w[i]; } for(int i=1;i<=n;i++) { string m; fin>>m; string temp = ""; vector<string> words; bool f = false; for(int j=0;j<m.length();j++) { if(m[j]=='(') { f = true; } else if(m[j]==')') { f = false; words.push_back(temp); temp = ""; } else { if(f) { temp+=m[j]; } else { string h = ""; h = h + m[j]; words.push_back(h); } } } fout<<"Case #"<<i<<": "<<ans(words, w,d)<<"\n"; } return 0; }
f4099a8268fab062ff45d50f687e170e86f78c59
c7850d478e1a62fc8b016225d7a748cf1b0cb81f
/tpf/modelos-nested/modelos/goodwin-minsky-matlab/atomics/chgPopulation_PopulationDEVS_BASIC_COUPLED_Population.h
22f732265784161e433b152e430245daee9a5431
[]
no_license
dioh/sed_2017_tps
8bac2bd824335581a33ad9b010747ea4af273130
c17d1d2d4b1d80bafe33053f7f2b58661b9bcc65
refs/heads/master
2021-09-14T07:35:57.009752
2018-05-09T19:16:33
2018-05-09T19:16:33
103,854,748
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
h
chgPopulation_PopulationDEVS_BASIC_COUPLED_Population.h
#ifndef _chgPopulation_PopulationDEVS_BASIC_COUPLED_Population_H_ #define _chgPopulation_PopulationDEVS_BASIC_COUPLED_Population_H_ #include <random> #include "atomic.h" #include "VTime.h" #define CHGPOPULATION_POPULATIONDEVS_BASIC_COUPLED_POPULATION "chgPopulation_PopulationDEVS_BASIC_COUPLED_Population" class chgPopulation_PopulationDEVS_BASIC_COUPLED_Population : public Atomic { public: chgPopulation_PopulationDEVS_BASIC_COUPLED_Population(const string &name = CHGPOPULATION_POPULATIONDEVS_BASIC_COUPLED_POPULATION ); virtual string className() const { return CHGPOPULATION_POPULATIONDEVS_BASIC_COUPLED_POPULATION ;} protected: Model &initFunction(); Model &externalFunction( const ExternalMessage & ); Model &internalFunction( const InternalMessage & ); Model &outputFunction( const CollectMessage & ); private: const Port &in_port_Betaa; const Port &in_port_Population; Port &out_port_chgPopulation_Population; double Betaa; double Population; bool isSet_Betaa; bool isSet_Population; }; #endif
e0387f65def40ae32f7494858b2608b23d6c91c5
eee4e1d7e3bd56bd0c24da12f727017d509f919d
/Case/case1/1100/nut
b1b8a95b6247c29f1dfe85f8b69c0e1b89312746
[]
no_license
mamitsu2/aircond5_play5
35ea72345d23c5217564bf191921fbbe412b90f2
f1974714161f5f6dad9ae6d9a77d74b6a19d5579
refs/heads/master
2021-10-30T08:59:18.692891
2019-04-26T01:48:44
2019-04-26T01:48:44
183,529,942
0
0
null
null
null
null
UTF-8
C++
false
false
9,555
nut
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "1100"; object nut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField nonuniform List<scalar> 458 ( 0.000708288 0.000731985 0.000693181 0.00071956 0.000745508 0.000769096 0.000790666 0.000810891 0.000830606 0.000850942 0.000869162 0.00088384 0.000895234 0.000905101 0.00091347 0.000313085 0.000366765 0.000380618 0.000302217 0.000215591 0.000181321 0.000174841 0.000163714 0.000158032 0.000176553 0.000188723 0.000206252 0.000223668 0.000248026 0.000291502 0.000340134 0.000372177 0.000342995 0.00116426 0.00197491 0.00153606 0.00190636 0.00205294 0.00220503 0.00235878 0.00250197 0.0026176 0.00268286 0.00270441 0.00265271 0.00248386 0.00213206 0.0015513 0.000981606 0.000945692 0.000658356 0.000494831 0.00103267 0.00123092 0.00123977 0.000987482 0.000698622 0.000463699 0.000251851 0.000197828 0.00022883 0.000287585 0.00044816 0.000710664 0.000938038 0.00131907 0.001544 0.00149832 0.000469868 0.00156856 0.00314845 0.00165724 0.00278165 0.00309076 0.00327615 0.00343477 0.00356828 0.00367401 0.00374554 0.00378797 0.00378507 0.0037037 0.00349512 0.00311048 0.00254931 0.00180995 0.00102616 0.000815244 0.00247068 0.00234533 0.00192577 0.0013854 0.000460005 0.000358642 0.00028937 0.00023101 0.000278809 0.000327816 0.000378403 0.000443778 0.000552379 0.00155775 0.00191526 0.00182294 0.000535365 0.00196162 0.0047123 0.00175618 0.00306712 0.00368462 0.00387185 0.00398987 0.0040766 0.00414305 0.00419494 0.00424125 0.00429338 0.0043398 0.00434343 0.00421974 0.00383403 0.0030578 0.00194936 0.00107024 0.00274743 0.0031134 0.00265529 0.00193438 0.0011969 0.000677378 0.000661555 0.000655998 0.000657921 0.000667945 0.000687731 0.000720368 0.000767817 0.000817472 0.0017113 0.00232226 0.00257306 0.00084805 0.00233772 0.00652769 0.00224859 0.00285284 0.00389943 0.00413216 0.0042146 0.00424947 0.00426123 0.00426974 0.00428968 0.00436229 0.00450174 0.00470956 0.00496133 0.00520372 0.00537107 0.00537669 0.0051589 0.00508857 0.00480689 0.00444075 0.00409691 0.00378667 0.00350788 0.00332473 0.00316344 0.00303591 0.00295992 0.00294426 0.0029815 0.00305668 0.00314808 0.00328345 0.00340701 0.00332046 0.00256989 0.00121979 0.00113902 0.00102214 0.00269954 0.0082674 0.00348311 0.00252518 0.0036216 0.00406502 0.00422671 0.00427927 0.00425895 0.00419847 0.00414201 0.00416461 0.00427063 0.00447448 0.00478483 0.00518295 0.00559895 0.00589239 0.00593944 0.00579193 0.00556167 0.00534906 0.00517415 0.00500021 0.00478297 0.00451436 0.00421143 0.00391446 0.003676 0.00353065 0.00347322 0.0034756 0.00351207 0.00357904 0.00371065 0.00390237 0.00393606 0.0038946 0.00304886 0.00116115 0.00304637 0.00960697 0.00581531 0.00312116 0.00275712 0.00323616 0.00375329 0.00409838 0.0042524 0.0041486 0.00400727 0.00395566 0.00397188 0.00406638 0.0042632 0.00458075 0.00498649 0.00536078 0.00557527 0.00561614 0.00557376 0.00553703 0.0055178 0.00548396 0.00539055 0.00520819 0.00492523 0.00456221 0.00419082 0.00389101 0.00368379 0.00354433 0.00344664 0.00337942 0.00334046 0.0033059 0.00319425 0.00303226 0.00295983 0.00118237 0.00313586 0.00982965 0.00755565 0.00565385 0.0041533 0.00342337 0.00342849 0.00375261 0.00405914 0.00398796 0.00384802 0.00374657 0.00369601 0.0036959 0.00375335 0.00388904 0.00412136 0.00441962 0.00469677 0.00489147 0.0050251 0.00515637 0.00529277 0.0054258 0.00553001 0.00557909 0.00552747 0.00532041 0.0049693 0.00457732 0.00419996 0.0038198 0.00343114 0.00305661 0.00271738 0.00239153 0.00209043 0.00183259 0.00161077 0.00120911 0.00305666 0.00368417 0.00403939 0.00413945 0.00396567 0.00366205 0.00342086 0.00330333 0.00327346 0.003272 0.00327863 0.00328481 0.00328788 0.00328969 0.00329726 0.00332502 0.00339416 0.00352032 0.00369545 0.00389385 0.00410155 0.00432442 0.00456608 0.00481778 0.00507201 0.00533554 0.00560625 0.00582196 0.00586762 0.00572233 0.00546237 0.00518439 0.00491356 0.0045872 0.00413057 0.00363223 0.00318063 0.00283574 0.0025536 0.00134877 0.00218645 0.00330515 0.00362357 0.00360468 0.00348807 0.00336777 0.00326761 0.0031835 0.00311521 0.003057 0.0030036 0.00295207 0.00290327 0.00286298 0.00284245 0.00285689 0.0029205 0.00304049 0.00321488 0.00343401 0.0036829 0.00394625 0.00421855 0.00451098 0.00484645 0.00522699 0.00555804 0.00575738 0.00576684 0.00562763 0.0054249 0.00522784 0.00510261 0.00503735 0.0047825 0.00417661 0.00372337 0.00135157 0.00211681 0.00354444 0.00374018 0.00367973 0.00355634 0.00341284 0.00327473 0.00315308 0.00303144 0.00290404 0.00278364 0.00267809 0.00259333 0.00253568 0.00251346 0.00253739 0.00261838 0.00276215 0.00296332 0.00320394 0.00345761 0.00369219 0.00389566 0.00406893 0.00421871 0.00435715 0.00450474 0.00465256 0.00475929 0.0047852 0.00472245 0.00458955 0.00440789 0.00400862 0.00337342 0.00259637 0.00234457 0.00114047 0.00175274 0.00187563 0.00198228 0.00210816 0.00201651 0.00187199 0.00175191 0.00163946 0.00153446 0.00143574 0.00134724 0.00126903 0.00119718 0.00112973 0.00106598 0.00100628 0.000951923 0.000905012 0.000868001 0.000842932 0.000830561 0.00082984 0.000838075 0.000852654 0.000868819 0.000883534 0.000896119 0.000907531 0.00092034 0.000935183 0.00095168 0.000968481 0.000982327 0.000985893 0.000967213 0.000936635 0.000893764 0.000835927 0.000884284 0.0010944 ) ; boundaryField { floor { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 36 ( 0.000110496 3.51468e-05 4.23483e-05 4.41854e-05 3.3666e-05 2.1608e-05 1.66681e-05 1.57203e-05 1.4076e-05 1.32314e-05 1.59764e-05 1.77543e-05 2.02855e-05 2.27698e-05 2.62061e-05 3.22271e-05 3.88232e-05 4.30947e-05 3.91998e-05 3.91997e-05 5.58515e-05 6.4213e-05 0.000102684 0.000146299 0.000136969 0.000123332 0.000110496 0.000118565 0.000114319 7.95978e-05 3.51467e-05 7.95978e-05 5.90257e-05 0.000123806 9.8729e-05 0.000128964 ) ; } ceiling { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 43 ( 0.000206302 0.000219832 0.000231498 0.000245213 0.000235268 0.000219472 0.000206246 0.000193769 0.000182033 0.000170919 0.000160883 0.000151953 0.000143696 0.000135892 0.000128468 0.000121469 0.000115056 0.000109487 0.000105068 0.000102063 0.000100574 0.000100486 0.000101474 0.000103223 0.000105158 0.000106917 0.000108419 0.000109779 0.000111303 0.000113066 0.000115021 0.000117008 0.000118642 0.000119062 0.000116857 0.000113238 0.000108141 0.000101219 0.000107013 0.000131779 0.000346083 0.000410884 0.00024609 ) ; } sWall { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value uniform 0.000206354; } nWall { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 6(0.000123337 0.000139531 0.000141982 0.000161378 0.00013714 0.000131787); } sideWalls { type empty; } glass1 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(8.57078e-05 0.000140021 0.000186091 0.000229615 0.000270379 0.000308939 0.000345394 0.000354738 0.000346492); } glass2 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 2(0.000145105 0.000161106); } sun { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 14 ( 8.57405e-05 8.86396e-05 8.38875e-05 8.71211e-05 9.02882e-05 9.31559e-05 9.57693e-05 9.8212e-05 0.000100586 0.000103029 0.000105211 0.000106965 0.000108324 0.0001095 ) ; } Table_master { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(5.45683e-05 4.12803e-05 3.19217e-05 2.38108e-05 3.04891e-05 3.71666e-05 4.39223e-05 5.24855e-05 6.63763e-05); } Table_slave { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(8.19459e-05 7.99942e-05 7.93071e-05 7.95445e-05 8.07819e-05 8.32182e-05 8.72186e-05 9.30004e-05 9.90062e-05); } inlet { type calculated; value uniform 0.000100623; } outlet { type calculated; value nonuniform List<scalar> 2(0.00175274 0.00187563); } } // ************************************************************************* //
090fd48fbda0427547293949bbe0fdea128f4818
79f281325b5fcce161905669c00ce8681b117fb3
/Tests.h
2e35dbb7bd444e7aa04f5bb3f6ada3e3e206fd13
[]
no_license
Mindaugas3/hash_generatorius
6f856277db6d8774059f57e5f100a9bb2daca61e
99c19827fbb2ecc99cb9182ce80d19e172ab2ebd
refs/heads/master
2022-12-29T09:15:59.698556
2020-10-19T15:53:12
2020-10-19T15:53:12
299,103,674
0
0
null
null
null
null
UTF-8
C++
false
false
951
h
Tests.h
// // Created by Mindaugas on 2020-10-08. // #ifndef HASH_GENERATORIUS_TESTS_H #define HASH_GENERATORIUS_TESTS_H #include "Converter.h" #include <vector> class Tests { //klase skirta failu dvejetainio ir sesioliktainio skirtumu palyginimui ir taip pat simboliu generavimui private: public: static void compareTwo(Converter conv1, Converter conv2); static float BinaryDifference(Converter conv1, Converter conv2); static float HexDifference(Converter conv1, Converter conv2); static void generateSymbols1000(); static void generatePairs(ofstream& basicOfstream, int length); static void checkCollission(vector<string> allHashes); static void makePairsFiles(); static void MeasureSha256(string value); static void generatePairsDiff(); static void makePairsSimiliar(ofstream& file, int length); static void checkDiff(vector<pair<Converter, Converter>> allPairs); }; #endif //HASH_GENERATORIUS_TESTS_H
9416d3ff941bb1a52b8d415431d0dcd7a8a2dea4
0e88892ac677c180d6aa9bb5665729a609d3a170
/src/core/memory/stack_allocator.h
d7e42d54f005879e9b7fd0fe1a4121d236d79c16
[ "MIT" ]
permissive
UIKit0/crown
630720672389903140392db772b70e1dd9f3c998
11e8631a0a80830695ba3594a952a2d0ac278d54
refs/heads/master
2020-12-03T03:34:41.998651
2015-12-12T13:54:29
2015-12-12T13:54:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
h
stack_allocator.h
/* * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #pragma once #include "allocator.h" namespace crown { /// Allocates memory linearly in a stack-like fashion from a /// predefined chunk. All deallocations must occur in LIFO /// order. /// /// @ingroup Memory class StackAllocator : public Allocator { public: StackAllocator(void* start, uint32_t size); ~StackAllocator(); /// @copydoc Allocator::allocate() void* allocate(uint32_t size, uint32_t align = Allocator::DEFAULT_ALIGN); /// @copydoc Allocator::deallocate() /// @note /// Deallocations must occur in LIFO order i.e. the /// last allocation must be freed for first. void deallocate(void* data); /// @copydoc Allocator::allocated_size() uint32_t allocated_size(const void* /*ptr*/) { return SIZE_NOT_TRACKED; } /// @copydoc Allocator::total_allocated() uint32_t total_allocated(); private: struct Header { uint32_t offset; uint32_t alloc_id; }; void* _physical_start; void* _top; uint32_t _total_size; uint32_t _allocation_count; }; } // namespace crown
8e268b1fbc82d4f61a89c5f8498c4dc1f4b1ee4e
94c0a7140191c79e79954d79e64d86a24241999a
/NEVista/System/File/FileDirectBinaryWriter.cpp
6d09e130f1d0bfa44733b2bfc136ca1a319e782e
[]
no_license
lemmingrad/NEVista
58e6d96358a9dee855300cc1cd1fbca4bff547c6
c1ca13fff5d0bca21bca4babcf16ded9193bcd03
refs/heads/master
2021-01-15T15:54:50.333313
2016-10-05T14:29:07
2016-10-05T14:29:07
2,606,111
1
0
null
null
null
null
UTF-8
C++
false
false
3,073
cpp
FileDirectBinaryWriter.cpp
//----------------------------------------------------------// // FILEDIRECTBINARYWRITER.CPP //----------------------------------------------------------// //-- Description // CFileDirectBinaryWriter class. Derived from // CFileDirectWriter. //----------------------------------------------------------// #include "FileDirectBinaryWriter.h" #include "Types.h" #include "SysFileIO.h" #include "SysString.h" //----------------------------------------------------------// // DEFINES //----------------------------------------------------------// //----------------------------------------------------------// // GLOBALS //----------------------------------------------------------// //----------------------------------------------------------// // CFileDirectBinaryWriter::CFileDirectBinaryWriter //----------------------------------------------------------// CFileDirectBinaryWriter::CFileDirectBinaryWriter(const s8* strFileName) : CFileDirectWriter(strFileName, Type::Binary) { } //----------------------------------------------------------// // CFileDirectBinaryWriter::CFileDirectBinaryWriter //----------------------------------------------------------// CFileDirectBinaryWriter::CFileDirectBinaryWriter(const IFixedString& strFileName) : CFileDirectWriter(strFileName, Type::Binary) { } //----------------------------------------------------------// // CFileDirectBinaryWriter::~CFileDirectBinaryWriter //----------------------------------------------------------// CFileDirectBinaryWriter::~CFileDirectBinaryWriter() { } //----------------------------------------------------------// // CFileDirectBinaryWriter::Validate //----------------------------------------------------------// bool CFileDirectBinaryWriter::Validate(void) const { return IsTypeAccess(Type::Binary, AccessMethod::DirectWrite); } //----------------------------------------------------------// // CFileDirectBinaryWriter::Open //----------------------------------------------------------// CFile::Error::Enum CFileDirectBinaryWriter::Open(void) { if (IS_TRUE(Validate())) { if (IS_FALSE(IsOpen())) { m_pFile = SysFileIO::Fopen(m_strFileName.ConstBuffer(), "wb"); m_nSize = 0; if (IS_TRUE(IsOpen())) { return Error::Ok; } return Error::FileOpenFailed; } return Error::FileAlreadyOpen; } return Error::Failed; } //----------------------------------------------------------// // CFileDirectBinaryWriter::Close //----------------------------------------------------------// CFile::Error::Enum CFileDirectBinaryWriter::Close(void) { if (IS_TRUE(IsOpen())) { SysFileIO::Fclose(m_pFile); } m_pFile = SysFileIO::INVALID_HANDLE; m_nSize = 0; return Error::Ok; } //----------------------------------------------------------// // CFileDirectBinaryWriter::Update //----------------------------------------------------------// CFile::Error::Enum CFileDirectBinaryWriter::Update(void) { return Error::Ok; } //----------------------------------------------------------// // EOF //----------------------------------------------------------//
cca5b4636d26f311e7136a226787ecc432c4cacf
4b478a68e29260e2e370f08f1a92ae0af77391c5
/Blliards/include/GPLS/DX11/CS.h
f9d40626c0d90e3272f6facad07f5e3b36b0ea39
[ "MIT" ]
permissive
winpass0601/Training
6f446f63374cee5854dd178234a5bad6fba65472
481eaf4697f971fe8aa01ae33ac70a928852b7e1
refs/heads/master
2021-01-13T15:08:58.063913
2016-12-12T11:37:35
2016-12-12T11:37:35
76,235,059
0
0
null
null
null
null
UTF-8
C++
false
false
601
h
CS.h
#pragma once #pragma warning(disable:4005) #include<./Macro.h> #include <D3D11_1.h> #include <./GPLS/DX11/Interfaces.h> namespace rinfw { namespace graphics { namespace gpls { class CS : public gplsi::IComputeShader, public gplsi::IBuffer, public gplsi::IShaderResourceView, public gplsi::IUnorderedAccessView{ public: CS(); CS(const CS &CS); CS(const CS &CS,bool shader,bool buffers,bool unorderedaccessview,bool srv); void Release(); bool setStatus(); bool setStatus(ID3D11DeviceContext *context); bool getStatus(); bool getStatus(ID3D11DeviceContext *context); private: }; } } }
8aad5230065a4bf0ccc9fd9a93e7d09d394c4c53
41a8bb6d83e336b2d00d008c3eca28defccde3a0
/app-pitch/pitchframe.h
2d918bf4f3bc8631f6e864eb229657dd4f8dd88d
[]
no_license
jocelyn-stericker/creator-live
2ec4197e416bf630cd53ceafcd10504f7e563554
958078804d061f60720d4e84cc17a977983e2cfa
refs/heads/master
2022-11-12T13:52:38.247316
2013-06-27T05:52:35
2018-06-14T02:17:07
10,294,551
2
0
null
null
null
null
UTF-8
C++
false
false
1,641
h
pitchframe.h
/******************************************************* Part of the Creator Live Music Production Suite. Copyright (C) Joshua Netterfield <joshua@nettek.ca> 2012 All rights reserved. *******************************************************/ #ifndef PITCHFRAME_H #define PITCHFRAME_H #include <QVBoxLayout> #include "pitchapp.h" #include <live/app> #include <live/appinterface> #include <live_widgets/appframe.h> #include <live_widgets/spinbox.h> namespace Ui { class PitchFrame; } class PitchFrame : public live_widgets::AppFrame { Q_OBJECT PitchApp* app; public: explicit PitchFrame(PitchApp* backend, AbstractTrack *parent = 0); bool expanding() const { return false; } signals: public slots: void syncState(); void setMore(bool more); void addRounding(); void removeRounding(); private: Ui::PitchFrame* ui; }; class PitchCreator : public QObject, public live::AppInterface { Q_OBJECT Q_INTERFACES(live::AppInterface) Q_PLUGIN_METADATA(IID "ca.nettek.live.pitch") public: PitchCreator() { } QString name() { return "ca.nettek.live.pitch"; } QString description() { return "Ooh! I sound like Micky Mouse..."; } live::ObjectPtr newBackend() { return new PitchApp(); } live::ObjectPtr loadBackend(const QByteArray &str) { return PitchApp::load(str); } live_widgets::AppFrame* newFrontend(live::ObjectPtr backend) { return new PitchFrame(static_cast<PitchApp*>(backend.data())); } QIcon icon() { return QIcon(":/icons/app_pitch.png"); } live::AppInterface* next() { return 0; } }; #endif // PITCHFRAME_H
e5c0f6ce99ac038465448f737505c25968838e09
3a36c4ed78a275cf8ca178b983c62bfd2eb7a39c
/hackerearth/circ_jun_19/1.cpp
7c7412efe8028d656bbdb76d6d44523280dabf2e
[ "Unlicense" ]
permissive
tuket/challenges
af7b5811bbb44bb0a21c80ff49ce4cee6fd88488
456979020c78dfcae2f8681245000bb64a6aaf38
refs/heads/master
2021-07-13T12:59:05.052206
2020-05-22T21:12:34
2020-05-22T21:12:34
147,118,768
0
0
null
null
null
null
UTF-8
C++
false
false
348
cpp
1.cpp
#include <iostream> #include <string> using namespace std; int main() { int n; cin >> n; string a, b; cin >> a >> b; int i; for(i=0; i<=n; i++) { int j; for(j=i; j<n; j++) { if(a[j] != b[j-i]) break; } if(j == n) break; } cout << i << endl; }
7a70df790958e8e8376be6ce09ada17a3f2966db
27466e78d3cd1ed168d96fd4c2fb26add1ec7cc3
/NVIS/Code/Render/Rendering/Spatial/Renderers/NEZoneCompartmentRenderer.cpp
215b0600ae74179e3fdc5ffce1d0c7ff8fdfa657
[]
no_license
gpudev0517/Fire-Simulator
37e1190d638a30c186ae1532975a56b23ffaac67
46581c19356e47a5c6fc8a9ee6f6478b96d02968
refs/heads/master
2023-04-26T02:54:53.458427
2021-05-14T10:16:10
2021-05-14T15:25:28
277,579,935
3
1
null
null
null
null
UTF-8
C++
false
false
11,023
cpp
NEZoneCompartmentRenderer.cpp
#include "NEZoneCompartmentRenderer.h" #include "Base/NEBase.h" #include "Mesh/NEZoneCompartment.h" #include "Rendering/Manager/NEGLManager.h" #include "Rendering/Manager/NEIGLSurface.h" #include "Rendering/Manager/NERenderManager.h" #include "Rendering/NEGLRenderer.h" #include "Resource/Mesh/NEIndexedTriMesh.h" #include "Rendering/Resource/NEMaterial.h" #include "Rendering/Resource/NEVertexBuffer.h" // // Zone Container Mesh Rendering // NEZoneCompartmentRenderer::NEZoneCompartmentRenderer() { } NEZoneCompartmentRenderer::~NEZoneCompartmentRenderer() { } void NEZoneCompartmentRenderer::connectToSpatial() { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(m_spatial); if (rigid == NULL) return; QObject::connect( rigid, SIGNAL(initObject()), this, SLOT(initObject()), Qt::ConnectionType::DirectConnection ); QObject::connect( rigid, SIGNAL(updateDrawingBuffers()), this, SLOT(updateDrawingBuffers()), Qt::ConnectionType::DirectConnection); } void NEZoneCompartmentRenderer::updateDrawingBuffers() { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(m_spatial); if (rigid == NULL) return; if(rigid->triangleMesh().numTriangles() > 0) rigid->triangleMesh().updateDrawingBuffers(GL_DYNAMIC_DRAW); } void NEZoneCompartmentRenderer::initObject() { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(m_spatial); if (rigid == NULL) return; if( NERENDERMAN.GLManager()->material( &rigid->triangleMesh() ) == 0) { NEMaterial* defaultMaterial = NERENDERMAN.materials()["DefaultMaterial"]; rigid->connectTo(reinterpret_cast<NENode*>(defaultMaterial), NE::kIOTriangleMesh, 0, 0); } } void NEZoneCompartmentRenderer::render(NESpatial* spatial, IGLSurface* surface) { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(spatial); if (rigid == NULL) return; if( rigid->RenderMode() == NESpatial::NERenderMode::Invisible ) return; if(NERENDERMAN.GLManager()->isBuffered( &rigid->triangleMesh() ) && rigid->Behavior() == NENode::Inactive && rigid->RenderMode() != NESpatial::Wireframe){ GL->glPushAttrib(GL_ALL_ATTRIB_BITS); //GL->glEnable(GL_BLEND); GL->glEnable(GL_DEPTH_TEST); GL->glEnable(GL_STENCIL_TEST); GL->glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); GL->glStencilFunc(GL_ALWAYS, 1, 0xFF); GL->glStencilMask(0xFF); NERENDERMAN.GLManager()->draw(&rigid->triangleMesh(), surface, rigid->DisplayMode() == NESpatial::BoundingBox, false, false , false,rigid->transform(), 1); GL->glPopAttrib(); GL->glPushAttrib(GL_ALL_ATTRIB_BITS); GL->glEnable(GL_STENCIL_TEST); GL->glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); GL->glStencilFunc(GL_NOTEQUAL, 1, 0xFF); GL->glStencilMask(0x00); //GL->glDisable(GL_DEPTH_TEST); NERENDERMAN.GLManager()->draw(&rigid->triangleMesh(), surface, rigid->DisplayMode() == NESpatial::BoundingBox, false, true,false ,rigid->transform(), 2); GL->glPopAttrib(); return; } if(NERENDERMAN.GLManager()->isBuffered( &rigid->triangleMesh() ) ) { if(rigid->RenderMode() == NESpatial::NERenderMode::Wireframe) { GL->glPushAttrib(GL_POLYGON_BIT); GL->glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); NERENDERMAN.GLManager()->drawRaw(&rigid->triangleMesh(), surface, false, rigid->DisplayMode() == NESpatial::BoundingBox); GL->glPopAttrib(); } else if(rigid->RenderMode() == NESpatial::NERenderMode::FlatShaded) { NERENDERMAN.GLManager()->drawFlat(&rigid->triangleMesh(), surface, rigid->DisplayMode() == NESpatial::BoundingBox); } else if (rigid->RenderMode() == NESpatial::NERenderMode::QuadWireframe || rigid->RenderMode() == NESpatial::NERenderMode::QuadWireframeOccluded || rigid->RenderMode() == NESpatial::NERenderMode::Occluded) { if(rigid->RenderMode() != NESpatial::Occluded) { GL->glPushAttrib(GL_ALL_ATTRIB_BITS); matrix44f modelMat = rigid->transform(); NERENDERMAN.GLManager()->drawQuadWireframe(&rigid->triangleMesh(), surface, rigid->Color(), modelMat, rigid->DisplayMode() == NESpatial::BoundingBox, false); GL->glPopAttrib(); } } else if (rigid->RenderMode() == NESpatial::NERenderMode::QuadWireframeHidden || rigid->RenderMode() == NESpatial::NERenderMode::Hidden) { if(rigid->RenderMode() != NESpatial::Hidden) { GL->glPushAttrib(GL_ALL_ATTRIB_BITS); matrix44f modelMat = rigid->transform(); NERENDERMAN.GLManager()->drawQuadWireframe(&rigid->triangleMesh(), surface, rigid->Color(), modelMat, rigid->DisplayMode() == NESpatial::BoundingBox, true); GL->glPopAttrib(); } } else if(rigid->RenderMode() == NESpatial::NERenderMode::SmoothShaded || rigid->RenderMode() == NESpatial::NERenderMode::QuadWireframeOnShaded) { NEMaterial* material = NERENDERMAN.GLManager()->material( const_cast< NEIndexedTriMesh *>( &rigid->triangleMesh() )); if(material) { { surface->setShaderProgram(material->shaderProgram()); GL->glUniform1i( GL->glGetUniformLocation( surface->shaderProgram()->programId(), "particleTextured" ), false ); } } GL->glPushAttrib(GL_ALL_ATTRIB_BITS); GL->glEnable(GL_BLEND); NERENDERMAN.GLManager()->draw(&rigid->triangleMesh(), surface, rigid->DisplayMode() == NESpatial::BoundingBox, false, true ,false ,rigid->transform()); GL->glPopAttrib(); if(rigid->RenderMode() == NESpatial::NERenderMode::QuadWireframeOnShaded) { GL->glPushAttrib(GL_ALL_ATTRIB_BITS); matrix44f modelMat = rigid->transform(); NERENDERMAN.GLManager()->drawQuadWireframe(&rigid->triangleMesh(), surface, rigid->SolidWireframeColor(), modelMat, rigid->DisplayMode() == NESpatial::BoundingBox, false); GL->glPopAttrib(); } } //rigid->SetScale(oldScale); } if(rigid->DrawSolidWireframe() && NERENDERMAN.GLManager()->isBuffered( &rigid->triangleMesh() )) { GL->glPushAttrib( GL_ALL_ATTRIB_BITS ); GL->glEnable(GL_LIGHTING); GL->glEnable(GL_DEPTH_TEST); GL->glDepthFunc(GL_LEQUAL); GL->glEnable(GL_BLEND); matrix44f modelMat = rigid->transform(); NERENDERMAN.GLManager()->drawSolidWireframe(&rigid->triangleMesh(), surface, rigid->SolidWireframeColor(), rigid->SolidWireframeThickness(), rigid->ContourThreshold(), modelMat); GL->glDisable(GL_BLEND); GL->glPopAttrib(); } } void NEZoneCompartmentRenderer::renderOnlyDepth(NESpatial* spatial, IGLSurface* surface) { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(spatial); if (rigid == NULL) return; if(rigid->RenderMode() == NESpatial::QuadWireframeOccluded || rigid->RenderMode() == NESpatial::Occluded) { GL->glPushAttrib(GL_ALL_ATTRIB_BITS); GL->glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); NERENDERMAN.GLManager()->draw(&rigid->triangleMesh(), surface, rigid->DisplayMode() == NESpatial::BoundingBox, false, true, false,rigid->transform()); GL->glPopAttrib(); } } void NEZoneCompartmentRenderer::renderPickable(NESpatial* spatial, IGLSurface* surface) { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(spatial); if (rigid == NULL) return; if( NEBASE.guiMode() == false ) return; if( rigid->RenderMode() == NESpatial::NERenderMode::Invisible ) return; if( NERENDERMAN.GLManager()->isBuffered( &rigid->triangleMesh() ) ) { if(rigid->RenderMode() == NESpatial::NERenderMode::Wireframe || rigid->RenderMode() == NESpatial::QuadWireframe || rigid->RenderMode() == NESpatial::QuadWireframeOccluded || rigid->RenderMode() == NESpatial::QuadWireframeHidden ) { GL->glPushAttrib(GL_POLYGON_BIT); GL->glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); NERENDERMAN.GLManager()->drawRaw(&rigid->triangleMesh(), surface, false, rigid->DisplayMode() == NESpatial::BoundingBox); GL->glPopAttrib(); } else { NERENDERMAN.GLManager()->draw(&rigid->triangleMesh(), surface, rigid->DisplayMode() == NESpatial::BoundingBox, true, true, false, matrix44f()); } } } void NEZoneCompartmentRenderer::renderPicked(NESpatial* spatial, IGLSurface* surface) { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(spatial); if (rigid == NULL) return; if( NEBASE.guiMode() == false ) return; if( rigid->RenderMode() == NESpatial::NERenderMode::Invisible ) return; if( NERENDERMAN.GLManager()->isBuffered( &rigid->triangleMesh() ) ) { if(rigid->RenderMode() == NESpatial::NERenderMode::Wireframe) { GL->glPushAttrib(GL_POLYGON_BIT); GL->glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); NERENDERMAN.GLManager()->drawRaw(&rigid->triangleMesh(), surface, false, rigid->DisplayMode() == NESpatial::BoundingBox); GL->glPopAttrib(); } else { matrix44f modelMat; modelMat.setToIdentity(); GL->glPushAttrib(GL_POLYGON_BIT); GL->glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); NERENDERMAN.GLManager()->drawQuadWireframe(&rigid->triangleMesh(), surface, QColor(Qt::green), modelMat, rigid->DisplayMode() == NESpatial::BoundingBox, false); GL->glPopAttrib(); //NERENDERMAN.GLManager()->draw(&rigid->triangleMesh(), surface, rigid->DisplayMode() == NESpatial::BoundingBox, true, true, false, matrix44f()); } } } void NEZoneCompartmentRenderer::renderInMotion(NESpatial* spatial, IGLSurface* surface) { NEZoneCompartment* rigid = qobject_cast<NEZoneCompartment*>(spatial); if (rigid == NULL) return; if(rigid->RenderMode() == NESpatial::NERenderMode::Invisible) return; if(NERENDERMAN.GLManager()->isBuffered( &rigid->triangleMesh() ) ) { if(rigid->RenderMode() != NESpatial::NERenderMode::Wireframe) { NERENDERMAN.GLManager()->drawInMotion(surface, &rigid->triangleMesh()); } } } NEZoneCompartmentRendererFactory::NEZoneCompartmentRendererFactory(NEManager* m): NERendererFactory( m ) { NERenderManager* rm = qobject_cast< NERenderManager* >(m); if( rm ) { rm->addRendererToMaps( this ); } } QString NEZoneCompartmentRendererFactory::nodeName() { return "Zone Compartment Renderer"; } NEObject *NEZoneCompartmentRendererFactory::createInstance() { return new NEZoneCompartmentRenderer(); }
f9e6577673440376c32f6a448fd7dbd4110bd9e8
33b8b8fca8025ad32f877a829ab894d4f106f244
/bg2e-modified/include/bg/render/vulkan_low_overhead_pipeline.hpp
49f1ce35992863a1ac7cd6ef5d6de4f6a52decb6
[]
no_license
FredyTP/TestSite
2a2e8b0efbe92b6be12f5783f250183c212fd989
2c7e1e0f3277b5776d7bee964b1ba79afff2ec57
refs/heads/master
2020-04-16T03:39:09.270311
2019-02-13T13:11:25
2019-02-13T13:11:25
165,239,256
0
0
null
null
null
null
UTF-8
C++
false
false
3,126
hpp
vulkan_low_overhead_pipeline.hpp
/* * bg2 engine license * Copyright (c) 2016 Fernando Serrano <ferserc1@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef _bg2e_render_vulkan_low_overhead_pipeline_hpp_ #define _bg2e_render_vulkan_low_overhead_pipeline_hpp_ #include <bg/render/low_overhead_pipeline.hpp> #include <bg/engine/vulkan.hpp> #include <bg/wnd/window_controller.hpp> namespace bg { namespace render { class BG2E_EXPORT VulkanLowOverheadPipeline : public LowOverheadPipeline { public: VulkanLowOverheadPipeline(bg::base::Context *, const BlendOptions &); virtual void resize(int w, int h); virtual void check(); virtual void mapInputBuffer(uint32_t bufferIndex, bg::base::PolyList * pl, void * memData, size_t size); virtual void drawPolyList(bg::base::PolyList * plist, uint32_t currentFrame); inline bg::engine::vulkan::vk::Pipeline * enginePipeline() { using namespace bg::engine::vulkan; return _cullMode == kCullModeBack ? _pipelinesCullBack[_primitiveTopology].getPtr() : _cullMode == kCullModeFront ? _pipelinesCullFront[_primitiveTopology].getPtr() : _pipelinesCullOff[_primitiveTopology].getPtr(); } inline void setPipelineLayout(bg::engine::vulkan::vk::PipelineLayout * lo) { _pipelineLayout = lo; } virtual void destroy(); protected: virtual ~VulkanLowOverheadPipeline(); void createPipeline(int w, int h, PrimitiveTopology t, CullFaceMode cullMode); std::unordered_map<int32_t, bg::ptr<bg::engine::vulkan::vk::Pipeline>> _pipelinesCullFront; std::unordered_map<int32_t, bg::ptr<bg::engine::vulkan::vk::Pipeline>> _pipelinesCullBack; std::unordered_map<int32_t, bg::ptr<bg::engine::vulkan::vk::Pipeline>> _pipelinesCullOff; bg::ptr<bg::engine::vulkan::vk::PipelineLayout> _pipelineLayout; bg::engine::vulkan::ShaderHelper * _shaderHelper = nullptr; uint32_t _width = 0; uint32_t _height = 0; void addShader(bg::engine::vulkan::vk::Pipeline * pl, const ShaderModuleData & data); }; } } #endif
9cb0220e8afe8a367470a8b0d0aad5d977b56d5f
48208f47129a304ff1864c43eb80204cf97e156c
/CardGame/temp/state_machine/StateMachine.h
4c8c4f2153e8af3f4947b37cd4b56642230447a4
[]
no_license
JimmyFromSYSU/CardGame
c2bb6acfd708191e5073a97a1b033e63f83d1ae4
2a822a9dead3cd607e3447597376bb618651c95c
refs/heads/master
2021-01-15T21:34:03.611606
2017-08-12T07:47:55
2017-08-13T06:57:47
99,878,084
2
1
null
null
null
null
UTF-8
C++
false
false
184
h
StateMachine.h
#ifndef CARD_GAME_STATE_MACHINE #define CARD_GAME_STATE_MACHINE #include "EventQueueListener.h" class StateMachine { }; #endif /* end of include guard: CARD_GAME_STATE_MACHINE */
e3814e7d0eafd8ffe4e77ba191faba51448a50c0
11d88efb3a4325654a3285bf12e8bb464fbd076a
/Code/Engine/Math/Vec3.hpp
ca4739c8322e0f3d49e7060ccb07a757e2a22d46
[ "MIT" ]
permissive
iomeone/Engine-1
eb465d4080bf8004023027cc8a7fe2539e43b558
0ca9720a00f51340c6eb6bba07d70972489663e8
refs/heads/master
2022-11-07T05:03:07.614714
2020-06-20T04:23:01
2020-06-20T04:23:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,624
hpp
Vec3.hpp
#pragma once #include <string> //------------------------------------------------------------------------------------------------------------------------------ struct Vec2; //------------------------------------------------------------------------------------------------------------------------------ struct Vec3 { public: // Construction/Destruction ~Vec3() {} // destructor: do nothing (for speed) Vec3() {} // default constructor: do nothing (for speed) Vec3( const Vec3& copyFrom ); // copy constructor (from another vec3) Vec3( const Vec2& copyFrom ); explicit Vec3( float initialX, float initialY, float initialZ ); // explicit constructor (from x, y, z) explicit Vec3(const char* asText); //Static Vectors const static Vec3 ZERO; const static Vec3 ONE; const static Vec3 FRONT; const static Vec3 FORWARD; const static Vec3 BACK; const static Vec3 LEFT; const static Vec3 RIGHT; const static Vec3 UP; const static Vec3 DOWN; static const Vec3 GetComponentMin(const Vec3& min, const Vec3& max); static const Vec3 GetComponentMinXY(const Vec3& min, const Vec3& max); static const Vec3 GetComponentMax(const Vec3& min, const Vec3& max); static const Vec3 GetComponentMaxXY(const Vec3& min, const Vec3& max); //Access Methods float GetLength() const; float GetLengthXY() const; float GetLengthXZ() const; float GetLengthYZ() const; float GetLengthSquared() const; float GetLengthSquaredXY() const; float GetAngleAboutZDegrees() const; float GetAngleAboutZRadians() const; float GetAngleAboutYDegrees() const; float GetAngleAboutYRadians() const; float GetAngleAboutXDegrees() const; float GetAngleAboutXRadians() const; float GetAngleDegreesXY() const; float GetAngleRadiansXY() const; const Vec3 GetRotatedAboutZDegrees(float degreesToRotateAroundZ) const; const Vec3 GetRotatedAboutZRadians(float radiansToRotateAroundZ) const; const Vec3 GetRotatedAboutYDegrees(float degreesToRotateAroundY) const; const Vec3 GetRotatedAboutYRadians(float radiansToRotateAroundY) const; const Vec3 GetRotatedAboutXDegrees(float degreesToRotateAroundX) const; const Vec3 GetRotatedAboutXRadians(float radiansToRotateAroundX) const; const Vec3 GetNormalized() const; std::string GetAsString() const; //Mutator methods void SetFromText(const char* asText); void ClampLengthXY(float maxLength); void SetLengthXY(float setLength); void Normalize(); const Vec3 ClampVector(Vec3& toClamp, const Vec3& minBound, const Vec3& maxBound); const static Vec3 LerpVector(Vec3& toLerp, const Vec3& lerpDestination, float lerpPercent); // Operators const Vec3 operator+( const Vec3& vecToAdd ) const; // vec3 + vec3 const Vec3 operator-( const Vec3& vecToSubtract ) const; // vec3 - vec3 const Vec3 operator*( float uniformScale ) const; // vec3 * float const Vec3 operator/( float inverseScale ) const; // vec3 / float void operator+=( const Vec3& vecToAdd ); // vec3 += vec3 void operator-=( const Vec3& vecToSubtract ); // vec3 -= vec3 void operator*=( const float uniformScale ); // vec3 *= float void operator/=( const float uniformDivisor ); // vec3 /= float void operator=( const Vec3& copyFrom ); // vec3 = vec3 bool operator==( const Vec3& compare ) const; // vec3 == vec3 bool operator!=( const Vec3& compare ) const; // vec3 != vec3 friend const Vec3 operator*( float uniformScale, const Vec3& vecToScale ); // float * vec3 public: float x; float y; float z; };
c1ebd6d892122bd71860bcd8244f14595aee0577
17b990be4f317e42be5fb98cab3a4e4f035a823d
/Platformer/pickup/flashingPickup.h
62aff632fc5ed850fffa580d8c8d9cce0adc6dd0
[]
no_license
adrian17/cavestory
ac0b7dbf6597e4c4eee4094d75e3f7bef7bac4d9
c351bf52f4ef762fdc8d79fb461b5badd11699e9
refs/heads/master
2021-01-01T05:51:59.933107
2015-01-12T12:48:02
2015-01-12T12:48:02
19,618,897
1
0
null
null
null
null
UTF-8
C++
false
false
954
h
flashingPickup.h
#pragma once #include "pickup/pickup.h" #include "sprite/sprite.h" #include "util/timer.h" #include <memory> class FlashingPickup : public Pickup { public: Rectangle collisionRectangle() const; bool update(const Units::MS dt, const Map &map); void draw(Graphics &graphics) const; int value() const { return value_; } PickupType type() const { return type_; } static std::shared_ptr<Pickup> HeartPickup(Graphics &graphics, Units::Game centerX, Units::Game centerY); static std::shared_ptr<Pickup> MultiHeartPickup(Graphics &graphics, Units::Game centerX, Units::Game centerY); private: FlashingPickup(Graphics &graphics, Units::Game centerX, Units::Game centerY, Units::Tile sourceX, Units::Tile sourceY, const Rectangle &rectangle, const int value, const PickupType type); Sprite sprite, flashSprite, dissipatingSprite; Units::Game x, y; Timer timer; const Rectangle &rectangle; const int value_; const PickupType type_; };
bdd69d242ebc18dea829dc252507abdcc5280e96
6b52b266551442f57b95e577438c88baa45f436b
/Deious/그래프와 BFS/알고스팟(1261).cpp
9a0d0f2a1353eba6f5cee9ec86b836b33cded3e3
[]
no_license
as-is-as/Basic
7db88e0e825c1d1c137ef5f5a55edd903965d1ae
b4a14d1149b381f41f3632e99782898f349e9959
refs/heads/master
2021-07-02T01:25:11.280205
2020-12-09T13:32:20
2020-12-09T13:32:20
195,760,874
3
3
null
2020-12-09T13:32:22
2019-07-08T07:40:17
C++
UTF-8
C++
false
false
1,106
cpp
알고스팟(1261).cpp
#include <iostream> #include <deque> using namespace std; int algoMap[101][101]; int breakCount[101][101]; bool check[101][101]; int dx[] = { 0, 0, 1, -1 }; int dy[] = { 1, -1, 0, 0 }; int n, m; int Bfs() { deque<pair<int, int>> d; d.push_back(make_pair(1, 1)); check[1][1] = true; while (!d.empty()) { int x = d.front().first; int y = d.front().second; d.pop_front(); if (x == m && y == n) { return breakCount[m][n]; } for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx > m || nx < 1 || ny > n || ny < 1) continue; if (!check[nx][ny]) { if(algoMap[nx][ny] == 0) { check[nx][ny] = true; breakCount[nx][ny] = breakCount[x][y]; d.push_front(make_pair(nx, ny)); } else { check[nx][ny] = true; breakCount[nx][ny] = breakCount[x][y] + 1; d.push_back(make_pair(nx, ny)); } } } } return 0; } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { scanf("%1d", &algoMap[i][j]); } } printf("%d", Bfs()); return 0; }
1d8c2cba82fb39829119f9c04a54e3d4e80acf93
6a49a58d0ac7a1bb5acfcbc0eac0fd6985146b2d
/Motor2D_1er/j1Map.cpp
2bc7ef6b64cfb6f3ecdd647b8a535169a10c16fb
[ "Unlicense" ]
permissive
xDragan/programacio_2
9f620dfdd6bf417b0cfe9ccfe7e6beedf9bf48c6
4a38c4986e85aba912a53c912c1ca79da7806c74
refs/heads/master
2020-01-23T22:01:38.140117
2015-08-20T22:47:42
2015-08-20T22:47:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,486
cpp
j1Map.cpp
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Render.h" #include "j1FileSystem.h" #include "j1Textures.h" #include "j1Map.h" #include "base64/base64.h" #include "zlib/include/zlib.h" #include "trim.h" #include "SDL/include/SDL.h" #include <math.h> #pragma comment( lib, "zlib/libx86/zdll.lib" ) j1Map::j1Map() : j1Module(), map_loaded(false) { name.create("map"); } // Destructor j1Map::~j1Map() {} // Called before render is available bool j1Map::Awake(j1IniReader* conf) { LOG("Loading Map Loader"); bool ret = true; folder.create(conf->GetString("folder", "")); return ret; } TileSet* j1Map::GetTilesetFromTileId(int id) const { p2List_item<TileSet*>* item = data.tilesets.start; TileSet* set = NULL; while(item) { if(id < item->data->firstgid) { set = item->prev->data; break; } set = item->data; item = item->next; } return set; } TileType* TileSet::GetTileType(int id) const { p2List_item<TileType*>* item = tile_types.start; int relative_id = id - firstgid; while(item) { if(item->data->id == relative_id) return item->data; item = item->next; } return NULL; } SDL_Rect TileSet::GetTileRect(int id) const { int relative_id = id - firstgid; SDL_Rect rect; rect.w = tile_width; rect.h = tile_height; rect.x = margin + ((rect.w + spacing) * (relative_id % num_tiles_width)); rect.y = margin + ((rect.h + spacing) * (relative_id / num_tiles_width)); return rect; } int Properties::Get(const char* value, int default_value) const { p2List_item<Property*>* item = list.start; while(item) { if(item->data->name == value) return item->data->value; item = item->next; } return default_value; } void j1Map::Draw() { if(map_loaded == false) return; // Render all layers with draw > 0 p2List_item<MapLayer*>* item; item = data.layers.start; App->render->SetBackgroundColor(data.background_color); for(item = data.layers.start; item != NULL; item = item->next) { MapLayer* layer = item->data; if(layer->properties.Get("Draw", 1) == 0) continue; for(int y = 0; y < data.height; ++y) { for(int x = 0; x < data.width; ++x) { int tile_id = layer->Get(x, y); TileSet* tileset = (tile_id > 0) ? GetTilesetFromTileId(tile_id) : NULL; if(tileset == NULL) continue; SDL_Rect r = tileset->GetTileRect(tile_id); iPoint pos = MapToWorld(x, y); App->render->Blit(tileset->texture, pos.x + tileset->offset_x, pos.y + tileset->offset_y, &r); //LOG("Rendering tile id %d at %d,%d rect x%d,y%d,w%d,h%d", tile_id, pos_x, pos_y, r.x, r.y, r.w, r.h); } } } } iPoint j1Map::MapToWorld(int x, int y) const { iPoint ret; if(data.type == MAPTYPE_ORTHOGONAL) { ret.x = x * data.tile_width; ret.y = y * data.tile_height; } else if(data.type == MAPTYPE_ISOMETRIC) { ret.x = (x-y) * (data.tile_width / 2); ret.y = (x+y) * (data.tile_height / 2); } else { LOG("Unknown map type"); ret.x = x; ret.y = y; } return ret; } iPoint j1Map::WorldToMap(int x, int y) const { iPoint ret; if(data.type == MAPTYPE_ORTHOGONAL) { ret.x = x / data.tile_width; ret.y = y / data.tile_height; } else if(data.type == MAPTYPE_ISOMETRIC) { x -= 8; // Tileset margins y -= 16; ret.x = (x / (data.tile_width / 2) + (y / (data.tile_height / 2))) / 2; ret.y = (y / (data.tile_height / 2) - (x / (data.tile_width / 2))) / 2; } else { LOG("Unknown map type"); ret.x = x; ret.y = y; } return ret; } // Called before quitting bool j1Map::CleanUp() { LOG("Unloading map"); // Remove all tilesets p2List_item<TileSet*>* item; item = data.tilesets.start; while(item != NULL) { RELEASE(item->data); item = item->next; } data.tilesets.clear(); // Remove all layers p2List_item<MapLayer*>* item2; item2 = data.layers.start; while(item2 != NULL) { RELEASE(item2->data); item2 = item2->next; } data.layers.clear(); map_file.reset(); return true; } // Load new map bool j1Map::Load(const char* file_name) { bool ret = true; p2String tmp("%s%s", folder.c_str(), file_name); char* buf; int size = App->fs->Load(tmp, &buf); pugi::xml_parse_result result = map_file.load_buffer(buf, size); RELEASE(buf); if(result == NULL) { LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description()); ret = false; } if(ret == true) { ret = LoadMap(); } pugi::xml_node tileset; for(tileset = map_file.child("map").child("tileset"); tileset; tileset = tileset.next_sibling("tileset")) { TileSet* set = new TileSet(); if(ret == true) { ret = LoadTileset(tileset, set); } if(ret == true) { ret = LoadTilesetDetails(tileset, set); } if(ret == true) { ret = LoadTilesetImage(tileset, set); } if(ret == true) { ret = LoadTilesetTerrains(tileset, set); } if(ret == true) { ret = LoadTilesetTileTypes(tileset, set); } data.tilesets.add(set); } if(ret == true) { pugi::xml_node layer; for(layer = map_file.child("map").child("layer"); layer && ret; layer = layer.next_sibling("layer")) { ret = LoadLayer(layer); } } if(ret == true) { LOG("Successfully parsed map XML file: %s", file_name); LOG("width: %d height: %d", data.width, data.height); LOG("tile_width: %d tile_height: %d", data.tile_width, data.tile_height); p2List_item<TileSet*>* item = data.tilesets.start; while(item != NULL) { TileSet* s = item->data; LOG("Tileset ----"); LOG("name: %s firstgid: %d", s->name, s->firstgid); LOG("tile width: %d tile height: %d", s->tile_width, s->tile_height); LOG("spacing: %d margin: %d", s->spacing, s->margin); item = item->next; } p2List_item<MapLayer*>* item2 = data.layers.start; while(item2 != NULL) { MapLayer* l = item2->data; LOG("Layer ----"); LOG("name: %s", l->name); LOG("width: %d height: %d", l->width, l->height); item2 = item2->next; } } map_loaded = ret; return ret; } // create walkability map bool j1Map::CreateWalkabilityMap(int& width, int& height, uchar** buffer) const { bool ret = false; p2List_item<MapLayer*>* item; item = data.layers.start; for(item = data.layers.start; item != NULL; item = item->next) { MapLayer* layer = item->data; if(layer->properties.Get("Walkability", 1) == 0) continue; uchar* map = new uchar[layer->width*layer->height]; for(int y = 0; y < data.height; ++y) { for(int x = 0; x < data.width; ++x) { int i = (y*layer->width) + x; map[i] = 1; int tile_id = layer->Get(x, y); TileSet* tileset = (tile_id > 0) ? GetTilesetFromTileId(tile_id) : NULL; if(tileset != NULL) { TileType* ts = tileset->GetTileType(tile_id); if(ts != NULL) { map[i] = ts->properties.Get("walkable", 1); } } } } *buffer = map; width = data.width; height = data.height; ret = true; break; } return ret; } // Load map general properties bool j1Map::LoadMap() { bool ret = true; pugi::xml_node map = map_file.child("map"); if(map == NULL) { LOG("Error parsing map xml file: Cannot find 'map' tag."); ret = false; } else { data.width = map.attribute("width").as_int(); data.height = map.attribute("height").as_int(); data.tile_width = map.attribute("tilewidth").as_int(); data.tile_height = map.attribute("tileheight").as_int(); p2String bg_color(map.attribute("backgroundcolor").as_string()); data.background_color.r = 0; data.background_color.g = 0; data.background_color.b = 0; data.background_color.a = 0; if(bg_color.length() > 0) { p2String red, green, blue; bg_color.sub_string(1, 2, red); bg_color.sub_string(3, 4, green); bg_color.sub_string(5, 6, blue); int v = 0; sscanf_s(red, "%x", &v); if(v >= 0 && v <= 255) data.background_color.r = v; sscanf_s(green, "%x", &v); if(v >= 0 && v <= 255) data.background_color.g = v; sscanf_s(blue, "%x", &v); if(v >= 0 && v <= 255) data.background_color.b = v; } p2String orientation(map.attribute("orientation").as_string()); if(orientation == "orthogonal") { data.type = MAPTYPE_ORTHOGONAL; } else if(orientation == "isometric") { data.type = MAPTYPE_ISOMETRIC; } else if(orientation == "staggered") { data.type = MAPTYPE_STAGGERED; } else { data.type = MAPTYPE_UNKNOWN; } } return ret; } bool j1Map::LoadTileset(pugi::xml_node& map, TileSet* set) { bool ret = true; //pugi::xml_node map = map_file.child("map").child("tileset"); if(map == NULL) { LOG("Error parsing map xml file: Cannot find 'tileset' tag."); ret = false; } else { set->firstgid = map.attribute("firstgid").as_int(); if(map.attribute("source").empty() == false) { pugi::xml_parse_result result = tileset_file.load_file(PATH(folder, map.attribute("source").as_string())); if(result == NULL) { LOG("Could not load tileset xml file. pugi error: %s", result.description()); ret = false; } } } return ret; } bool j1Map::LoadTilesetDetails(pugi::xml_node& tileset_node, TileSet* set) { bool ret = true; set->name = tileset_node.attribute("name").as_string(); set->tile_width = tileset_node.attribute("tilewidth").as_int(); set->tile_height = tileset_node.attribute("tileheight").as_int(); set->margin = tileset_node.attribute("margin").as_int(); set->spacing = tileset_node.attribute("spacing").as_int(); pugi::xml_node offset = tileset_node.child("tileoffset"); if(offset != NULL) { set->offset_x = offset.attribute("x").as_int(); set->offset_y = offset.attribute("y").as_int(); } else { set->offset_x = 0; set->offset_y = 0; } return ret; } bool j1Map::LoadTilesetImage(pugi::xml_node& tileset_node, TileSet* set) { bool ret = true; pugi::xml_node image = tileset_node.child("image"); if(image == NULL) { LOG("Error parsing tileset xml file: Cannot find 'image' tag."); ret = false; } else { set->texture = App->tex->Load(PATH(folder, image.attribute("source").as_string())); int w, h; SDL_QueryTexture(set->texture, NULL, NULL, &w, &h); set->tex_width = image.attribute("width").as_int(); if(set->tex_width <= 0) { set->tex_width = w; } set->tex_height = image.attribute("height").as_int(); if(set->tex_height <= 0) { set->tex_height = h; } set->num_tiles_width = set->tex_width / set->tile_width; set->num_tiles_height = set->tex_height / set->tile_height; } return ret; } bool j1Map::LoadTilesetTerrains(pugi::xml_node& tileset_node, TileSet* set) { bool ret = true; pugi::xml_node terrains = tileset_node.child("terraintypes"); if(terrains == NULL) { LOG("Map does not contain terrain type definitions"); //LOG("Error parsing tileset xml file: Cannot find 'terraintypes' tag."); //ret = false; } else { pugi::xml_node terrain; for(terrain = terrains.child("terrain"); terrain; terrain = terrain.next_sibling("terrain")) { TerrainType terrain_type; terrain_type.name = terrain.attribute("name").as_string(); terrain_type.tile = terrain.attribute("tile").as_int(); set->terrain_types.add(terrain_type); //LOG("terrain %s on tile %d", terrain_type.name, terrain_type.tile); } } return ret; } bool j1Map::LoadTilesetTileTypes(pugi::xml_node& tileset_node, TileSet* set) { bool ret = true; pugi::xml_node tile; for(tile = tileset_node.child("tile"); tile; tile = tile.next_sibling("tile")) { TileType* tile_type = new TileType(); tile_type->id = tile.attribute("id").as_int(); char types[MID_STR]; strncpy_s(types, tile.attribute("terrain").as_string(), MID_STR); char* tmp = NULL; char* item; item = strtok_s(types, ",", &tmp); int i = 0; while(item != NULL) { switch(i) { case 0: tile_type->top_left = &set->terrain_types[atoi(item)]; break; case 1: tile_type->top_right = &set->terrain_types[atoi(item)]; break; case 2: tile_type->bottom_left = &set->terrain_types[atoi(item)]; break; case 3: tile_type->bottom_right = &set->terrain_types[atoi(item)]; break; } item = strtok_s(NULL, ",", &tmp); ++i; } LoadProperties(tile, tile_type->properties); //Load any properties found set->tile_types.add(tile_type); /* LOG("tile id %d on terrains: %s %s %s %s", tile_type->id, tile_type->top_left->name, tile_type->top_right->name, tile_type->bottom_left->name, tile_type->bottom_right->name); p2List_item<Property*>* it = tile_type->properties.list.start; while(it) { LOG("--> %i: %s", it->data->value, it->data->name); it = it->next; } */ } return ret; } bool j1Map::LoadLayer(pugi::xml_node node) { bool ret = true; MapLayer* layer = new MapLayer(); layer->name = node.attribute("name").as_string(); layer->width = node.attribute("width").as_int(); layer->height = node.attribute("height").as_int(); LoadProperties(node, layer->properties); LOG("layer %s width %d height %d", layer->name, layer->width, layer->height); pugi::xml_node layer_data = node.child("data"); if(layer_data == NULL) { LOG("Error parsing map xml file: Cannot find 'layer/data' tag."); ret = false; RELEASE(layer); } else { // decode base 64 then unzip ... unsigned long buffer_len = 1 + strlen(layer_data.text().as_string()); char* buffer = new char[buffer_len]; strncpy_s(buffer, buffer_len, layer_data.text().as_string(), buffer_len); trim_inplace(buffer, "\n\r "); char* decoded; unsigned int decoded_len; decoded = b64_decode(buffer, &decoded_len); RELEASE_ARRAY(buffer); buffer_len = decoded_len * 20; buffer = new char[buffer_len]; int result = uncompress((Bytef*)buffer, &buffer_len, (Bytef*)decoded, decoded_len); free(decoded); if(result != Z_OK) { LOG("Could not decompress layer data, error code %d", result); ret = false; } else { layer->data = new unsigned __int32[buffer_len]; memcpy(layer->data, buffer, buffer_len); } RELEASE_ARRAY(buffer); } data.layers.add(layer); return ret; } // Load a group of properties from a node and fill a list with it bool j1Map::LoadProperties(pugi::xml_node& node, Properties& properties) { bool ret = false; pugi::xml_node data = node.child("properties"); if(data != NULL) { pugi::xml_node prop; for(prop = data.child("property"); prop; prop = prop.next_sibling("property")) { Property* p = new Property(); p->name = prop.attribute("name").as_string(); p->value = prop.attribute("value").as_int(); properties.list.add(p); } } return ret; }
3a8dafb3a06121eb4431028f8caa6135b8913e21
42136dbc35b311dd7a4665001539e48d44d5aa5e
/Source/Base/ECS/EntityManager.h
83c0fe795848cf64d80149ef3da712b433a0cd63
[]
no_license
mink365/RacingEngine
4b2564cf10488c7e04e6bd3461355e472b047040
0ab4f1ac7e0aa8ee50d214e34bee424714347b88
refs/heads/master
2020-12-24T16:32:24.022254
2016-12-15T06:15:58
2016-12-15T06:16:59
17,405,087
4
1
null
null
null
null
UTF-8
C++
false
false
835
h
EntityManager.h
#ifndef RE_ENTITYMANAGER_H #define RE_ENTITYMANAGER_H #include <vector> #include "Base/Singleton.h" #include "Base/Shared.h" #include "ComponentHandle.h" namespace re { class BaseComponent; class Entity; using EntityPtr = SharedPtr<Entity>; class EntityManager : public Singleton<EntityManager> { public: EntityManager(); void CacheComponent(SharedPtr<BaseComponent> comp) { this->components.push_back(comp); } public: std::vector<EntityPtr> nodes; std::vector<SharedPtr<BaseComponent>> components; }; template <class T, typename... Args> ComponentHandle<T> CreateComponent(Args... args) { auto p = Create<T>(args...); EntityManager::instance().CacheComponent(p); ComponentHandle<T> handle; handle.ptr = p; return handle; } } // namespace re #endif // RE_ENTITYMANAGER_H
ae8bbd09694686d6ea715811dbd2a0098fab652d
8333d50050d39fd05164bafdad6d353b9138a344
/source/Objects/SuperSectors.cpp
4d8adfc4c03ff51bc9837228e48edf21eceffa18
[ "BSD-2-Clause" ]
permissive
JanekMak/LevelMod
1e3c4e579a218bf6b0f78e162ece8403337b247f
f272fc2d5cb467c1f9d85790169fe6bc813e3288
refs/heads/master
2023-03-05T17:45:42.968693
2021-02-17T18:04:29
2021-02-17T18:04:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,741
cpp
SuperSectors.cpp
#define NO_DEFINES #define _CRT_SECURE_NO_WARNINGS #include "pch.h" #include "SuperSectors.h" #include "Model.h" bool updatingObjects = false; EXTERN std::vector<MovingObject> movingObjects;//List of Objects on the move MovingObject::MovingObject(SuperSector* _sector, Model* mdl) { debug_print("FOLLOW_MODEL\n"); model = mdl; state = MeshState::create; Type = FOLLOW_MODEL; link = NULL; sector = _sector; this->pScript = NULL; pos = (sector->bboxMax + sector->bboxMin) / 2.0f; angle = Vertex(0.0f, 0.0f, 0.0f); goal = Vertex(0, 0, 0); timer = 0.0f; float distance = 0.0f; speed = 0.0f; end = 0.0f; vertices = NULL; } bool MovingObject::Update(float delta) { bool update = false; static D3DXVECTOR3 direction, Velocity; static D3DXMATRIX nodeRotation, nodeTranslation, world; D3DXMatrixIdentity(&nodeRotation); D3DXMatrixIdentity(&nodeTranslation); D3DXMatrixIdentity(&world); //D3DXMatrixIdentity(&orient); //debug_print("MovingObject on the move(%f %f %f) dt:%f timer:%f end:%f\n", pos.x, pos.y, pos.z, delta, timer, end); timer += delta; switch (Type) { case MOVE_TO_POS: if (timer >= end) { if (pos != goal) { D3DXVECTOR3 relPos = goal - pos; sector->bboxMax += relPos; sector->bboxMin += relPos; for (DWORD i = 0; i < sector->numVertices; i++) { sector->vertices[i] += relPos; } update = true; } RemoveMovingObject(sector); debug_print("MovingObject final destination\n"); return update; } direction = goal - pos; D3DXVec3Normalize(&Velocity, &direction); Velocity *= speed * delta; sector->bboxMax += Velocity; sector->bboxMin += Velocity; for (DWORD i = 0; i < sector->numVertices; i++) { sector->vertices[i] += Velocity; } pos += Velocity; return true; case FOLLOW_PATH_LINKED: if (timer >= end)//we should be at the linked location now { if (pos != goal)//if we are not at the right location make us be { D3DXVECTOR3 relPos = goal - pos; sector->bboxMax += relPos; sector->bboxMin += relPos; for (DWORD i = 0; i < sector->numVertices; i++) { sector->vertices[i] += relPos; } pos += relPos; update = true;//Now we will update vertexbuffer even if angle is not changed } //Get the array of links CArray* links = link->GetArray(Checksums::Links); if (!links) { RemoveMovingObject(sector); debug_print("MovingObject final destination\n"); return update; } //If 1 link use it, else pick a random one int numLinks = links->GetNumItems(); if (numLinks == 1) link = Node::GetNodeStructByIndex((*links)[0]); else link = Node::GetNodeStructByIndex((*links)[Rnd(numLinks)]);//Pick a random path if (!link) { RemoveMovingObject(sector); debug_print("Couldn't find link[%d]...\n", (*links)[0]); return update; } //Get the position of the link CStructHeader* _pos; if (link->GetStruct(Checksums::Position, &_pos)) { //update the goal target position goal = *_pos->pVec; //reset timer to zero timer = 0; //calculate distance between current position and target position const D3DXVECTOR3& v = (pos - goal); float distance = D3DXVec3Length(&v); //calculate end time end = distance / speed; //Calculate the angle needed to look at a position, taken from thug1src but for some reason not working? //goalAngle = D3DXVECTOR3(0, -AngleY(orient,pos, goal), 0); goalAngle = D3DXVECTOR3(0, atan2f((pos.x - goal.x), (pos.z - goal.z)), 0); if (fabsf(goalAngle.y) > 2 * D3DX_PI) { goalAngle.y -= 2 * D3DX_PI; } /*if (goalAngle.y) { (*(Matrix*)&orient).RotateYLocal(goalAngle.y); //Use OrthoNormalizeAbout2 because other one was the games original normalize funciton which seems to be bugged? (*(Matrix*)&orient).OrthoNormalizeAbout2(Y); bboxMax = D3DXVECTOR3(-FLT_MAX, -FLT_MAX, -FLT_MAX); bboxMin = D3DXVECTOR3(FLT_MAX, FLT_MAX, FLT_MAX); sector->bboxMax = D3DXVECTOR3(FLT_MAX, FLT_MAX, FLT_MAX); sector->bboxMin = D3DXVECTOR3(-FLT_MAX, -FLT_MAX, -FLT_MAX); for (DWORD i = 0; i < sector->numVertices; i++) { vertices[i] -= pos; D3DXVec3TransformCoord(&sector->vertices[i], &vertices[i], &orient); sector->vertices[i] += pos; if (bboxMax.x < sector->vertices[i].x) bboxMax.x = sector->vertices[i].x; if (bboxMin.x > sector->vertices[i].x) bboxMin.x = sector->vertices[i].x; if (bboxMax.y < sector->vertices[i].y) bboxMax.y = sector->vertices[i].y; if (bboxMin.y > sector->vertices[i].y) bboxMin.y = sector->vertices[i].y; if (bboxMax.z < sector->vertices[i].z) bboxMax.z = sector->vertices[i].z; if (bboxMin.z > sector->vertices[i].z) bboxMin.z = sector->vertices[i].z; } sector->bboxMax = bboxMax; sector->bboxMin = bboxMin; angle = goalAngle; return true;//send state to update vertexbuffer }*/ //return the stored value since we might wanna update vertexbuffer if position was changed but not the angle return update; } RemoveMovingObject(sector); debug_print("Couldn't find node -> position[%d]...\n", (*links)[0]); return update; } else { direction = goal - pos; D3DXVec3Normalize(&Velocity, &direction); Velocity *= speed * delta; if (Velocity) { /*sector->bboxMax += Velocity; sector->bboxMin += Velocity;*/ pos += Velocity; if (angle.y == goalAngle.y) { sector->bboxMax += Velocity; sector->bboxMin += Velocity; for (DWORD i = 0; i < sector->numVertices; i++) { sector->vertices[i] += Velocity; } } else { bboxMax = D3DXVECTOR3(-FLT_MAX, -FLT_MAX, -FLT_MAX); bboxMin = D3DXVECTOR3(FLT_MAX, FLT_MAX, FLT_MAX); sector->bboxMax = D3DXVECTOR3(FLT_MAX, FLT_MAX, FLT_MAX); sector->bboxMin = D3DXVECTOR3(-FLT_MAX, -FLT_MAX, -FLT_MAX); /*D3DXVECTOR3 newAngle = goalAngle * timer / end; newAngle.y = ClampMin(newAngle.y, angle.y);*/ if (fabsf(angle.y - goalAngle.y) < 0.02f) { angle = goalAngle; } else { D3DXVECTOR3 newAngle = goalAngle - angle; /*if (fabsf(newAngle.y) > D3DX_PI) { newAngle.y = -newAngle.y;// +D3DX_PI; goalAngle.y = -goalAngle.y //goalAngle.y = -goalAngle.y+D3DX_PI; }*/ /*else if (newAngle.y < -D3DX_PI) { newAngle.y = newAngle.y - D3DX_PI; goalAngle.y = newAngle.y - D3DX_PI; }*/ D3DXVec3Normalize(&newAngle, &newAngle); newAngle *= 0.01f; angle += newAngle; } (*(Matrix*)&orient).RotateYLocal(angle.y); //Use OrthoNormalizeAbout2 because other one was the games original normalize funciton which seems to be bugged? (*(Matrix*)&orient).OrthoNormalizeAbout2(Y); for (DWORD i = 0; i < sector->numVertices; i++) { //sector->vertices[i] += Velocity; //vertices[i] -= o; D3DXVec3TransformCoord(&sector->vertices[i], &vertices[i], &orient); sector->vertices[i] += pos; if (bboxMax.x < sector->vertices[i].x) bboxMax.x = sector->vertices[i].x; if (bboxMin.x > sector->vertices[i].x) bboxMin.x = sector->vertices[i].x; if (bboxMax.y < sector->vertices[i].y) bboxMax.y = sector->vertices[i].y; if (bboxMin.y > sector->vertices[i].y) bboxMin.y = sector->vertices[i].y; if (bboxMax.z < sector->vertices[i].z) bboxMax.z = sector->vertices[i].z; if (bboxMin.z > sector->vertices[i].z) bboxMin.z = sector->vertices[i].z; } sector->bboxMax = bboxMax; sector->bboxMin = bboxMin; //angle = newAngle; } return true;//send state to update vertexbuffer } } break; case FOLLOW_MODEL: if (model->pos != pos) { D3DXMATRIX translation; D3DXMATRIX result; D3DXMatrixTranslation(&translation, model->pos.x, model->pos.y, model->pos.z); D3DXMatrixMultiply(&result, &model->rotation, &translation); //Move the bbox to origin sector->bboxMax = model->pos + (sector->bboxMax - pos); sector->bboxMin = model->pos - (sector->bboxMin + pos); //Rotate and move the bbox according to model D3DXVec3TransformCoord(&sector->bboxMax, &sector->bboxMax, &result); D3DXVec3TransformCoord(&sector->bboxMin, &sector->bboxMin, &result); //Check if the rotation made bbox flip axis if (sector->bboxMin.x > sector->bboxMax.x) { const float temp = sector->bboxMax.x; sector->bboxMax.x = sector->bboxMin.x; sector->bboxMin.x = temp; } if (sector->bboxMin.y > sector->bboxMax.y) { const float temp = sector->bboxMax.y; sector->bboxMax.y = sector->bboxMin.y; sector->bboxMin.y = temp; } if (sector->bboxMin.z > sector->bboxMax.z) { const float temp = sector->bboxMax.z; sector->bboxMax.z = sector->bboxMin.z; sector->bboxMin.z = temp; } //Rotate and move the vertices according to model using the origin vertices for (DWORD i = 0; i < sector->numVertices; i++) { D3DXVec3TransformCoord(&sector->vertices[i], &vertices[i], &result); } //Update local position pos = model->pos; } break; case ANGULAR_VELOCITY: if (acceleration.x || acceleration.y || acceleration.z || goalAngle.x || goalAngle.y || goalAngle.z) { goalAngle.x += acceleration.x * 0.33f;//multiply acceleration by 0.33, or else we will get too big angle float velocityAngle = max(goalAngle.x, 0.001f);//clamp the angle to be minimum 0.001 angle.x += velocityAngle;//add the velocity to current angle //the final angle now is 89.657394, but why is the object moving?? debug_print("currentAngle %f\n", angle.x * 180 / D3DX_PI);// , velocityAngle); D3DXMatrixRotationYawPitchRoll(&nodeRotation, 0, angle.x, 0); //make a new bbox in a temp location so we can keep the actual bbox bboxMax = D3DXVECTOR3(-FLT_MAX, -FLT_MAX, -FLT_MAX); bboxMin = D3DXVECTOR3(FLT_MAX, FLT_MAX, FLT_MAX); //temporarly make the actual bbox very big to prevent culling sector->bboxMax = D3DXVECTOR3(FLT_MAX, FLT_MAX, FLT_MAX); sector->bboxMin = D3DXVECTOR3(-FLT_MAX, -FLT_MAX, -FLT_MAX); for (DWORD i = 0; i < sector->numVertices; i++) { //Use the vertices that's translated to origin //sector->vertices[i] -= pos; D3DXVec3TransformCoord(&sector->vertices[i], &vertices[i], &nodeRotation); sector->vertices[i] += pos; //calculate the new bbox into the temp location if (bboxMax.x < sector->vertices[i].x) bboxMax.x = sector->vertices[i].x; if (bboxMin.x > sector->vertices[i].x) bboxMin.x = sector->vertices[i].x; if (bboxMax.y < sector->vertices[i].y) bboxMax.y = sector->vertices[i].y; if (bboxMin.y > sector->vertices[i].y) bboxMin.y = sector->vertices[i].y; if (bboxMax.z < sector->vertices[i].z) bboxMax.z = sector->vertices[i].z; if (bboxMin.z > sector->vertices[i].z) bboxMin.z = sector->vertices[i].z; } //set the actual bbox to be same as temp bbox sector->bboxMax = bboxMax; sector->bboxMin = bboxMin; return true;//Returns true to update vertexbuffer } break; } return false; }
cf3c48371a0a9eb5df73ad6560743da33407cada
da72d7ffe4d158b226e3b3d9aabe900d0d232394
/llvm/lib/CAS/CASOutputBackend.cpp
1e6643dc7c9e4e860634fcc595c1d41fda0c7370
[ "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
ddcc/llvm-project
19eb04c2de679abaa10321cc0b7eab1ff4465485
9376ccc31a29f2b3f3b33d6e907599e8dd3b1503
refs/heads/next
2023-03-20T13:20:42.024563
2022-08-05T20:02:46
2022-08-05T19:14:06
225,963,333
0
0
Apache-2.0
2021-08-12T21:45:43
2019-12-04T21:49:26
C++
UTF-8
C++
false
false
3,323
cpp
CASOutputBackend.cpp
//===- CASOutputBackend.cpp -------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/CAS/CASOutputBackend.h" #include "llvm/CAS/CASDB.h" #include "llvm/CAS/Utils.h" #include "llvm/Support/AlignOf.h" #include "llvm/Support/Allocator.h" using namespace llvm; using namespace llvm::cas; void CASOutputBackend::anchor() {} namespace { class CASOutputFile final : public vfs::OutputFileImpl { public: Error keep() override { return OnKeep(Path, Bytes); } Error discard() override { return Error::success(); } raw_pwrite_stream &getOS() override { return OS; } using OnKeepType = llvm::unique_function<Error(StringRef, StringRef)>; CASOutputFile(StringRef Path, OnKeepType OnKeep) : Path(Path.str()), OS(Bytes), OnKeep(std::move(OnKeep)) {} private: std::string Path; SmallString<16> Bytes; raw_svector_ostream OS; OnKeepType OnKeep; }; } // namespace CASOutputBackend::CASOutputBackend(std::shared_ptr<CASDB> CAS) : CASOutputBackend(*CAS) { this->OwnedCAS = std::move(CAS); } CASOutputBackend::CASOutputBackend(CASDB &CAS) : CAS(CAS) {} CASOutputBackend::~CASOutputBackend() = default; struct CASOutputBackend::PrivateImpl { // FIXME: Use a NodeBuilder here once it exists. SmallVector<ObjectRef> Refs; }; Expected<std::unique_ptr<vfs::OutputFileImpl>> CASOutputBackend::createFileImpl(StringRef ResolvedPath, Optional<vfs::OutputConfig> Config) { if (!Impl) Impl = std::make_unique<PrivateImpl>(); // FIXME: CASIDOutputBackend.createFile() should be called NOW (not inside // the OnKeep closure) so that if there are initialization errors (such as // output directory not existing) they're reported by createFileImpl(). // // The opened file can be kept inside \a CASOutputFile and forwarded. return std::make_unique<CASOutputFile>( ResolvedPath, [&](StringRef Path, StringRef Bytes) -> Error { Optional<ObjectProxy> PathBlob; Optional<ObjectProxy> BytesBlob; if (Error E = CAS.createProxy(None, Path).moveInto(PathBlob)) return E; if (Error E = CAS.createProxy(None, Bytes).moveInto(BytesBlob)) return E; // FIXME: Should there be a lock taken before accessing PrivateImpl? Impl->Refs.push_back(PathBlob->getRef()); Impl->Refs.push_back(BytesBlob->getRef()); return Error::success(); }); } Expected<ObjectProxy> CASOutputBackend::getCASProxy() { // FIXME: Should there be a lock taken before accessing PrivateImpl? if (!Impl) return CAS.createProxy(None, ""); SmallVector<ObjectRef> MovedRefs; std::swap(MovedRefs, Impl->Refs); return CAS.createProxy(MovedRefs, ""); } Error CASOutputBackend::addObject(StringRef Path, ObjectRef Object) { if (!Impl) Impl = std::make_unique<PrivateImpl>(); Optional<ObjectProxy> PathBlob; if (Error E = CAS.createProxy(None, Path).moveInto(PathBlob)) return E; Impl->Refs.push_back(PathBlob->getRef()); Impl->Refs.push_back(Object); return Error::success(); }
ca07c4eb0766cabde274400352ed9f9d97d885e5
92e1b4ad344d86983de13d95c5552dd1e46e43fb
/Luchador.cpp
b6fbcc8004bb1d4ff1d8538c3e0ee3cfa36d9ef5
[ "MIT" ]
permissive
ErickMartinez2/Lab9P3_ErickMartinez
3ea81fe3dbded8f1be3068b97ec72f6bd4d2e8e3
361ff73de87ca76fcb33a1b04cc1b9789f2e0160
refs/heads/master
2021-06-28T00:21:05.830001
2017-09-16T04:45:15
2017-09-16T04:45:15
103,683,613
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
cpp
Luchador.cpp
#include "Luchador.h" Luchador::Luchador() { } Luchador::Luchador(string pnombre) { nombre = pnombre; batallas_ganadas = 0; experiencia = 0; } string Luchador::getNombre() { return nombre; } void Luchador::setNombre(string pnombre) { nombre = pnombre; } int Luchador::getBatallas() { return batallas_ganadas; } void Luchador::setBatallas(int pbatallas) { batallas_ganadas = pbatallas; } int Luchador::getExperiencia() { return experiencia; } void Luchador::setExperiencia(int pexperiencia) { experiencia = pexperiencia; } int Luchador::getSalud() { return salud; } void Luchador::setSalud(int psalud) { salud = psalud; } double Luchador::getDefensaMagica() { return defensa_magica; } void Luchador::setDefensaMagica(double pdefensa_magica) { defensa_magica = pdefensa_magica; } double Luchador::getDefensaFisica() { return defensa_fisica; } void Luchador::setDefensaFisica(double pdefensa_fisica) { defensa_fisica = pdefensa_fisica; } vector<string> Luchador::getClases() { return clases_aprendidas; } void Luchador::setClases(vector<string> pclases) { clases_aprendidas = pclases; } int Luchador::getExperienciaNecesaria() { return experiencia_necesaria; } void Luchador::setExperienciaNecesaria(int pexperiencia_necesaria) { experiencia_necesaria = pexperiencia_necesaria; } int Luchador::getExperienciaEntregada() { return experiencia_entregada; } void Luchador::setExperienciaEntregada(int pexperiencia_entregada) { experiencia_entregada = pexperiencia_entregada; } bool Luchador::getDefensaM() { return defensam_activa; } void Luchador::setDefensaM(bool pdefensam_activa) { defensam_activa = pdefensam_activa; } bool Luchador::getDefensaF() { return defensaf_activa; } void Luchador::setDefensaF(bool pdefensaf_activa) { defensaf_activa = pdefensaf_activa; } int Luchador::AtaqueMagico() { return 0; } int Luchador::AtaqueFisico() { return 0; } void Luchador::Habilidad() { } void Luchador::HabilidadPasiva() { } void Luchador::Defensa() { }
2d14b9640cdd9742db36998bf06e350cfa0963a4
1fb357bb753988011e0f20c4ca8ec6227516b84b
/EW/src/LEP2AFBcharm.cpp
65094225fe8b0c7f9f5fc2138c04981bb52c77aa
[ "DOC" ]
permissive
silvest/HEPfit
4240dcb05938596558394e97131872269cfa470e
cbda386f893ed9d8d2d3e6b35c0e81ec056b65d2
refs/heads/master
2023-08-05T08:22:20.891324
2023-05-19T09:12:45
2023-05-19T09:12:45
5,481,938
18
11
null
2022-05-15T19:53:40
2012-08-20T14:03:58
C++
UTF-8
C++
false
false
317
cpp
LEP2AFBcharm.cpp
/* * Copyright (C) 2012 HEPfit Collaboration * * * For the licensing terms see doc/COPYING. */ #include "LEP2AFBcharm.h" double LEP2AFBcharm::computeThValue() { double AFB_c = SM.LEP2AFBcharm(s); #ifdef LEP2TEST AFB_c = myTEST.AFBcharmTEST(sqrt_s); #endif return AFB_c; }
0f23739b9b80950fdb3b794e4f1bba4b37f52144
cff92d6e527dd3bda671e896891d6ebd6e7fd6ec
/common/event_log.cc
96115e7c6cdb1b494b60e32238927c317383f90f
[ "BSD-3-Clause" ]
permissive
eLong-opensource/pyxis
d5e78f419078a9e5ecd62548890059845236a5c5
304820eb72bd62d3c211c3423f62dc87b535bb3c
refs/heads/master
2021-06-05T12:58:34.267022
2016-07-21T12:41:42
2016-07-21T12:41:42
63,775,973
2
0
null
null
null
null
UTF-8
C++
false
false
3,239
cc
event_log.cc
#include <toft/storage/path/path.h> #include <glog/logging.h> #include <gflags/gflags.h> #include <muduo/base/Timestamp.h> #include <stdio.h> #include <inttypes.h> #include <pyxis/proto/rpc.pb.h> #include <pyxis/proto/node.pb.h> #include <pyxis/common/watch_event.h> #include <pyxis/common/event_log.h> #include <pyxis/common/status.h> namespace pyxis { EventLog::EventLog(time_t flushInterval) : logFilePath_("log/event.log"), fp_(NULL), flushInterval_(flushInterval), lastflush_(time(NULL)), mutex_() { Reload(); } EventLog::~EventLog() { if (fp_ != NULL) { fclose(fp_); } } void EventLog::SetLogFile(const std::string& p) { logFilePath_ = p; } void EventLog::Reload() { if (fp_ != NULL) { fclose(fp_); } fp_ = fopen(logFilePath_.c_str(), "ae"); PCHECK(fp_ != NULL); } void EventLog::LogWatch(sid_t sid, const watch::Event& e) { Log("-", "wevent", sid, 0, e.String(), "", 0); } void EventLog::LogRpc(const std::string& addr, rpc::Request* req, rpc::Response* rep, double used) { std::string event; std::string param; getActionAndNode(req, &event, &param); Log(addr, event, req->sid(), req->xid(), param, Status::FromRpcError(rep->err()).ToString(), used); } void EventLog::LogSession(sid_t sid, toft::StringPiece what) { Log("-", "sess", sid, 0, what, "", 0); } Status EventLog::OnProcWrite(const store::ProcDB::ArgList& args, const std::string& value) { Reload(); return Status::OK(); } void EventLog::Log(toft::StringPiece addr, toft::StringPiece event, sid_t sid, uint64_t xid, toft::StringPiece param, toft::StringPiece err, double used) { muduo::MutexLockGuard guard(mutex_); muduo::string timestamp(muduo::Timestamp::now().toFormattedString()); int n = fprintf(fp_, "%s %s" " %020"PRIu64 " %05"PRIu64 " %-6s \"%s\" \"%s\" %f\n", timestamp.c_str(), addr.data(), sid, xid, event.data(), param.data(), err.data(), used); PCHECK(n > 0); time_t now = time(NULL); if (now - lastflush_ > flushInterval_) { fflush(fp_); } lastflush_ = now; } void EventLog::getActionAndNode(const rpc::Request* req, std::string* action, std::string* node) { if (req->has_ping()) { action->assign("ping"); node->assign("-"); } else if (req->has_register_()) { action->assign("reg"); node->assign("-"); } else if (req->has_unregister()) { action->assign("unreg"); node->assign("-"); } else if (req->has_stat()) { action->assign("stat"); node->assign(req->stat().path()); } else if (req->has_read()) { action->assign("read"); node->assign(req->read().path()); } else if (req->has_write()) { action->assign("write"); node->assign(req->write().path()); } else if (req->has_create()) { action->assign("create"); node->assign(req->create().path()); } else if (req->has_delete_()) { action->assign("delete"); node->assign(req->delete_().path()); } else if (req->has_watch()) { action->assign("watch"); node->assign(req->watch().path()); } else { action->assign("???"); node->assign("???"); } if (req->has_watch()) { *action += "w"; } } }
205ce47b6eafdb1eab8984ef20aceec58adc98d6
46087ddd70356ed4717dc23ea2bb9cc4e003dd63
/Codeforces Round #209 (Div. 2) - B. Permutation/Codeforces Round #209 (Div. 2) - B. Permutation/main.cpp
ac33fc934bdad7ed09500991dca0412cac3d2ddf
[]
no_license
smhemel/Codeforces-Online-Judge
dae1b6a128fe90923d3cb308b3288b6d5df4df4e
e143341ca0a0149ee088bfbce50dac923b6e3d47
refs/heads/master
2020-04-04T13:16:02.975187
2019-11-09T09:20:14
2019-11-09T09:20:14
155,955,102
0
0
null
null
null
null
UTF-8
C++
false
false
383
cpp
main.cpp
// // main.cpp // Codeforces Round #209 (Div. 2) - B. Permutation // // Created by S M HEMEL on 3/31/17. // Copyright © 2017 Eastern University. All rights reserved. // #include <iostream> using namespace std; int main() { int n,m; cin >> n >> m; m *= 2; n *= 2; cout << m; for(int i=1; i<n; i++) cout << " 0"; cout << endl; return 0; }
3bf49454f952809591a41a61bc6998c24f9f8af1
73bdf06846b5c0e71d446581264b7b1e67a3bdd6
/13214_The_Robots_Grid.cpp
5962d1b9a2b042006342cdf2d780e4646429efa6
[]
no_license
RasedulRussell/uva_problem_solve
0c11d7341316f4aca78e3c14a102aba8e65bd5e1
c3a2b8da544b9c05b2d459e81ee38c96f89eaffe
refs/heads/master
2021-06-13T09:10:42.936870
2021-03-24T15:49:15
2021-03-24T15:49:15
160,766,749
3
0
null
null
null
null
UTF-8
C++
false
false
1,152
cpp
13214_The_Robots_Grid.cpp
#include<bits/stdc++.h> using namespace std; #define int long long #define pii pair<int,int> #define x first #define y second #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0) #define MOD 1000000007 #define INF 100000000 #define nll cout << "\n" #define nl "\n" #define MAX 100005 #define print(v) cout << v << " " #define dbgv(v) cout << v << nl #define asdf(v) cout << v << nl #define pasdf(p) cout << p.x << " " << p.y << nl #define dbg cout << "dbg\n" #define vi vector<int> #define pb push_back #define con continue ///13214_The_Robots_Grid.cpp int32_t main(){ int dp[30][30]; memset(dp, 0, sizeof dp); for(int i = 0; i < 30; i++){ dp[0][i] = 1; } for(int j = 0; j < 30; j++){ dp[j][0] = 1; } for(int colam = 1; colam < 30; colam++){ for(int row = 1; row < 30; row++){ dp[row][colam] = dp[row][colam-1] + dp[row-1][colam]; } } int cs; cin >> cs; while(cs--){ int N, M; cin >> N >> M; cout << dp[N-1][M-1] << "\n"; } return 0; }
58cd303b7f97496be9eb2ed1c7fd4715779a166c
4265f9ead043ead518929a80797664ced14af5b2
/src/solo/bullet/SoloBulletStaticMeshCollider.cpp
07840c65fde6079b5b3fe293c5a4e9b6d6e0d10c
[ "Zlib" ]
permissive
DingYong4223/solo
d9bdbbfe63425958e7974eb612cb1658019501d0
9da1ad9c53083fe1f889ec724e4d6583189baf1e
refs/heads/master
2021-01-09T15:48:36.467994
2020-01-19T10:11:35
2020-01-19T10:11:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,092
cpp
SoloBulletStaticMeshCollider.cpp
/* * Copyright (c) Aleksey Fedotov * MIT license */ #include "SoloBulletStaticMeshCollider.h" #include "SoloDevice.h" #include "SoloMeshData.h" using namespace solo; BulletStaticMeshCollider::BulletStaticMeshCollider(sptr<MeshData> data): data_(data) { SL_DEBUG_PANIC(data_->indexData().empty(), "Collision mesh index data is empty"); mesh_ = std::make_unique<btIndexedMesh>(); mesh_->m_indexType = PHY_INTEGER; mesh_->m_vertexType = PHY_FLOAT; mesh_->m_numTriangles = data_->indexData().front().size() / 3; mesh_->m_numVertices = data_->vertexCount(); mesh_->m_triangleIndexBase = reinterpret_cast<const u8*>(data_->indexData().front().data()); mesh_->m_triangleIndexStride = 3 * sizeof(u32); mesh_->m_vertexBase = reinterpret_cast<const u8*>(data_->vertexData().data()); mesh_->m_vertexStride = 3 * sizeof(float); arr_ = std::make_unique<btTriangleIndexVertexArray>(); arr_->addIndexedMesh(*mesh_, PHY_INTEGER); // TODO support for 16-bit indices? shape_ = std::make_unique<btBvhTriangleMeshShape>(arr_.get(), true); }
5fb3a9c592e5bad17ab3591f1b7433c93471b61b
654e42a8405d0ee09910cf64dca8427d5ce7c680
/awt/JSeparator.h
fe15dacb8b5db3ec67d6d8477bf8bd9bcff585c2
[]
no_license
neattools/neattools
bbd94d46c4e5aeb1ab524bf63a9b1ac623e7fd58
ac63c05ba1d575797303e48558fa2383a5e8ccf7
refs/heads/master
2020-05-29T17:34:04.002088
2018-03-01T15:59:04
2018-03-01T15:59:04
17,801,058
0
0
null
2018-03-01T15:59:05
2014-03-16T14:29:07
C++
UTF-8
C++
false
false
452
h
JSeparator.h
#if !defined( _JSeparator_h ) #define _JSeparator_h #include "JCanvas.h" class #include "JAWT.hpp" JSeparator : public JCanvas { public: enum { HORIZONTAL, VERTICAL}; virtual const char* className() const; virtual JObject* clone() const; static JSeparator* create(JComponent* p, int _type); JSeparator(); int getType(); boolean setType(int _type); virtual boolean needRedraw(); protected: int type; }; #endif
6c637064aa58e9a3d4d06af9532ec7031b08d892
68d2d3a9789a8bf88d370c25984945c3c5f12872
/Dynamic Programming/EditDistance.cpp
2d6d2c5e6594581a2b53f6b8a5d3b64f21f1c3ec
[]
no_license
raghavkhator/CSES-problemset-solution
45e9d893304a4e2c8bf2cafa0ab7431d095fc9db
c16f44219a971d9a1e9fff27730cf73815b58b40
refs/heads/master
2023-01-02T13:19:10.539907
2020-10-28T13:48:52
2020-10-28T13:48:52
308,008,886
0
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
EditDistance.cpp
#include<bits/stdc++.h> #define ll long long using namespace std; int main(){ string s1,s2; s1 = "LOVE"; s2 = "MOVIE"; cin>>s1>>s2; vector<vector<int> > dp(s1.length()+1,vector<int>(s2.length()+1,0)); for(int i =0;i<=s1.length();i++) dp[i][0] = i; for(int i =0;i<=s2.length();i++) dp[0][i] = i; for(int i=1;i<=s1.length();i++){ for(int j=1;j<=s2.length();j++){ dp[i][j] = min(dp[i][j-1]+1,min(dp[i-1][j]+1,dp[i-1][j-1]+ (s1[i-1]!=s2[j-1]))); // if(s1[i-1]==s2[j-1]) dp[i][j] = dp[i-1][j-1]; // else dp[i][j] = min(dp[i][j-1],min(dp[i-1][j-1],dp[i][j-1])) +1; } } cout<<dp[s1.length()][s2.length()]; }
4dd04b8248cddc845569e8d1a1247e7ea7055780
fb5b25b4fbe66c532672c14dacc520b96ff90a04
/export/release/windows/obj/include/openfl/utils/_AGALMiniAssembler/OpCode.h
2162b1c3a6c95166cb78357598ac52b4dcab0d60
[ "Apache-2.0" ]
permissive
Tyrcnex/tai-mod
c3849f817fe871004ed171245d63c5e447c4a9c3
b83152693bb3139ee2ae73002623934f07d35baf
refs/heads/main
2023-08-15T07:15:43.884068
2021-09-29T23:39:23
2021-09-29T23:39:23
383,313,424
1
0
null
null
null
null
UTF-8
C++
false
false
2,920
h
OpCode.h
#ifndef INCLUDED_openfl_utils__AGALMiniAssembler_OpCode #define INCLUDED_openfl_utils__AGALMiniAssembler_OpCode #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_STACK_FRAME(_hx_pos_b6bb58d9c0266c23_804_new) HX_DECLARE_CLASS3(openfl,utils,_AGALMiniAssembler,OpCode) namespace openfl{ namespace utils{ namespace _AGALMiniAssembler{ class HXCPP_CLASS_ATTRIBUTES OpCode_obj : public ::hx::Object { public: typedef ::hx::Object super; typedef OpCode_obj OBJ_; OpCode_obj(); public: enum { _hx_ClassId = 0x60536c68 }; void __construct(::String name,int numRegister,int emitCode,int flags); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="openfl.utils._AGALMiniAssembler.OpCode") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,true,"openfl.utils._AGALMiniAssembler.OpCode"); } inline static ::hx::ObjectPtr< OpCode_obj > __new(::String name,int numRegister,int emitCode,int flags) { ::hx::ObjectPtr< OpCode_obj > __this = new OpCode_obj(); __this->__construct(name,numRegister,emitCode,flags); return __this; } inline static ::hx::ObjectPtr< OpCode_obj > __alloc(::hx::Ctx *_hx_ctx,::String name,int numRegister,int emitCode,int flags) { OpCode_obj *__this = (OpCode_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(OpCode_obj), true, "openfl.utils._AGALMiniAssembler.OpCode")); *(void **)__this = OpCode_obj::_hx_vtable; { HX_STACKFRAME(&_hx_pos_b6bb58d9c0266c23_804_new) HXLINE( 805) ( ( ::openfl::utils::_AGALMiniAssembler::OpCode)(__this) )->name = name; HXLINE( 806) ( ( ::openfl::utils::_AGALMiniAssembler::OpCode)(__this) )->numRegister = numRegister; HXLINE( 807) ( ( ::openfl::utils::_AGALMiniAssembler::OpCode)(__this) )->emitCode = emitCode; HXLINE( 808) ( ( ::openfl::utils::_AGALMiniAssembler::OpCode)(__this) )->flags = flags; } return __this; } static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~OpCode_obj(); HX_DO_RTTI_ALL; ::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp); ::hx::Val __SetField(const ::String &inString,const ::hx::Val &inValue, ::hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("OpCode",0e,57,b0,3f); } static void __boot(); static ::Dynamic __meta__; int emitCode; int flags; ::String name; int numRegister; virtual ::String toString(); ::Dynamic toString_dyn(); }; } // end namespace openfl } // end namespace utils } // end namespace _AGALMiniAssembler #endif /* INCLUDED_openfl_utils__AGALMiniAssembler_OpCode */
a612f30db7fa0384f3ff78f54cdf43a363315083
3d0d1d826e6877d77f99d7eca1d2426528efea54
/src/escalonamento.h
d14b46c4549e6c068b8f66debc9e75de284e769b
[]
no_license
Tiago370/escalonamento
4680b4b1b6906e0e586312a17af0f688264a44f3
cd125a22c0dde11ffd7c9034166a5fd32b493f7d
refs/heads/main
2023-06-04T18:29:21.473757
2021-06-23T19:03:13
2021-06-23T19:03:13
353,482,548
0
0
null
null
null
null
UTF-8
C++
false
false
1,026
h
escalonamento.h
#include<vector> #include<string> using namespace std; class Escalonamento{ public: void readInstance(char* arquiv); unsigned int getNumberTasks(); unsigned int getNumberMachines(); unsigned int getMakeSpan(); void setMakeSpan(unsigned int); vector<unsigned int>* getTasks(); void printMachine(); void setOrder(bool pOrder); bool getOrder(); void setRelativize(bool pRelativize); bool getRelativize(); void setSubtract(bool pSubtract); bool getSubtract(); //sensores unsigned int getNextTask(); unsigned int getNumberNextTask(); double getSensorMachine(unsigned int i); bool escalando(); void reset(); //controles void putTaskOnTheMachine(unsigned int i); Escalonamento(); ~Escalonamento(); private: vector<unsigned int> machine; vector<unsigned int> task; int nMachines; int nTasks; int nextTask; int numberNextTask; unsigned int makeSpan; bool escal; bool order; bool relativize; bool subtract; };
44a34948567583510704bf3d77c21ca79445120a
f126fab6f351c3a31ab90006a6f24cb6dab7e3ee
/TTT_Mult/GM_MP_Game.cpp
aec1fe001606efd27977afffb44a11165c098abb
[]
no_license
luedos/TTT_Mult
eba958b7052af99f793dc59f6819c3b09a29fc41
a4bee33d0c95cc2c9b3bfba7ee33c5f1921dd722
refs/heads/master
2021-05-08T02:21:57.378841
2018-01-26T15:27:48
2018-01-26T15:27:48
106,447,330
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
10,506
cpp
GM_MP_Game.cpp
#include "stdafx.h" #include "GameInclude/GM_MP_Game.h" #include "Game.h" GM_MP_Game::GM_MP_Game(Game* InGame, Graphics* InGraph) { MyGame = InGame; MyGraph = InGraph; IsMyTurn = true; MyIndex = 1; IsServer = true; ChangeGrid(5, 5, 3); } GM_MP_Game::~GM_MP_Game() { } void GM_MP_Game::GM_EventTick(float DeltaTime) { if (MyMultiplayer != nullptr) if (MyMultiplayer->ConnectionClosed) MyGame->LoadMainMenu(); } void GM_MP_Game::GM_Start() { IsMeReady = true; IsOponentReady = true; XWins = 0; OWins = 0; MyGraph->ClearEverything(); if (IsServer) MyMultiplayer = &MyServer; else MyMultiplayer = &MyClient; Coordinates TestCoord; TestCoord.bRelativeW = true; TestCoord.bRelativeX = true; TestCoord.bRelativeY = true; TestCoord.X = 0.3; TestCoord.Y = 0.3; TestCoord.W = 0.8; TestCoord.H = 60; MyGraph->AddStaticText("Loading...", { 225,225,225,225 }, &TestCoord); MyGraph->RenderEverything(1); if (IsServer) if (MyServer.ListenToConnection(IP.c_str(), PORT, IP.empty())) NewRound(); else MyGame->LoadMainMenu(); else if (!MyClient.ConnectTo(IP.c_str(), PORT)) MyGame->LoadMainMenu(); } void GM_MP_Game::LoadData(string* IPRef, int PORTRef) { IP = *IPRef; PORT = PORTRef; } void GM_MP_Game::NewRound() { MyGraph->ClearEverything(); XO_Buttons.clear(); if (IsServer) { if (!MyServer.SendPacket(P_StartGame)) cout << "Bad send : Packet" << endl; if (!MyServer.SendInt(XNumber)) cout << "Bad send : W" << endl; if (!MyServer.SendInt(YNumber)) cout << "Bad send : H" << endl; if (!MyServer.SendInt(Diagonal)) cout << "Bad send : D" << endl; if (!MyServer.SendBool(!IsMyTurn)) cout << "Bad send : Turn" << endl; int ClientIndex; if (MyIndex == 2) ClientIndex = 1; else ClientIndex = 2; if (!MyServer.SendInt(!(MyIndex - 1) + 1)) cout << "Bad send : Index" << endl; } Coordinates TestCoord; TestCoord.bRelativeX = true; TestCoord.bRelativeY = true; TestCoord.bRelativeW = true; TestCoord.bRelativeH = true; TestCoord.X = 0.2; TestCoord.Y = 0.01; SomeSomeString = "X - " + to_string(XWins) + " : O - " + to_string(OWins); MyGraph->AddStaticText(SomeSomeString.c_str(), { 225,225,225,225 }, &TestCoord); float XDiag, YDiag; if (YNumber > XNumber) { YDiag = 0.6 / YNumber; XDiag = YDiag * 4.f / 3.f; } else { XDiag = 0.8 / XNumber; YDiag = XDiag * 0.75f; } TestCoord.W = XDiag * XNumber; TestCoord.H = YDiag * YNumber; TestCoord.X = 0.5 - TestCoord.W / 2; TestCoord.Y = 0.4 - TestCoord.H / 2; MyGraph->AddStaticImage("../TTT_Mult/Textures/TTT_Grid.png", &TestCoord, &GridRect); Coordinates NewCoord = TestCoord; NewCoord.W = XDiag; NewCoord.H = YDiag; for (int y = 0; y < YNumber; y++) for (int x = 0; x < XNumber; x++) { NewCoord.X = x * XDiag + TestCoord.X; NewCoord.Y = y * YDiag + TestCoord.Y; XO_Buttons.push_back(MyGraph->AddTTTButton(&NewCoord)); } TestCoord.bRelativeH = false; TestCoord.H = 60; TestCoord.X = 0.1; TestCoord.Y = 0.7; TestCoord.W = 0.8; MyGraph->AddButton(MyGame, &Game::LoadMainMenu, "Exit Game", &TestCoord); } void GM_MP_Game::LoadForNewRound() { IsMeReady = true; MyGraph->ClearEverything(); XO_Buttons.clear(); if (!IsOponentReady) { Coordinates TestCoord; TestCoord.bRelativeX = true; TestCoord.bRelativeY = true; TestCoord.bRelativeW = true; TestCoord.bRelativeH = true; const char* WaitingChar; if (IsServer) WaitingChar = "Waiting for the client"; else WaitingChar = "Waiting for the server"; TestCoord.X = 0.05; TestCoord.Y = 0.3; MyGraph->AddStaticText(WaitingChar, { 225,225,225,225 }, &TestCoord); TestCoord.bRelativeH = false; TestCoord.H = 60; TestCoord.W = 0.8; TestCoord.X = 0.1; TestCoord.Y = 0.5; MyGraph->AddButton(MyGame, &Game::LoadMainMenu, "Exit", &TestCoord); if (IsServer) { if (!MyServer.SendPacket(P_StartGame)) cout << "Bad send : Packet" << endl; if (!MyServer.SendInt(XNumber)) cout << "Bad send : W" << endl; if (!MyServer.SendInt(YNumber)) cout << "Bad send : H" << endl; if (!MyServer.SendInt(Diagonal)) cout << "Bad send : D" << endl; if (!MyServer.SendBool(!IsMyTurn)) cout << "Bad send : Turn" << endl; int ClientIndex; if (MyIndex == 2) ClientIndex = 1; else ClientIndex = 2; if (!MyServer.SendInt(ClientIndex)) cout << "Bad send : Index" << endl; } else MyClient.SendPacket(P_StartGame); } else if (IsServer) NewRound(); else MyClient.SendPacket(P_StartGame); } void GM_MP_Game::GM_End() { if(MyMultiplayer != nullptr) MyMultiplayer->CloseMyConnection(); MyMultiplayer = nullptr; MyGraph->ClearEverything(); XO_Buttons.clear(); } void GM_MP_Game::GM_Event(SDL_Event * EventRef) { if (EventRef->type == SDL_MOUSEBUTTONUP) { int x, y; SDL_GetMouseState(&x, &y); cout << "Event" << endl; if(IsMyTurn && IsMeReady) for(int i = 0; i < XO_Buttons.size(); i++) if (XO_Buttons.at(i)->MyRect.x < x && XO_Buttons.at(i)->MyRect.y < y && XO_Buttons.at(i)->MyRect.x + XO_Buttons.at(i)->MyRect.w > x && XO_Buttons.at(i)->MyRect.y + XO_Buttons.at(i)->MyRect.h > y) { if (IsServer) { if (MakeTurn(i)) { cout << "Server Made turn" << endl; if (!MyServer.SendPacket(P_Turn)) cout << "Bad send : Packet" << endl; if (!MyServer.SendInt(i)) cout << "Bad send : Turn index" << endl; if (CanWinCheck(i,MyIndex - 1)) WinMenu(!(MyIndex-1)); IsMyTurn = false; } } else { cout << "Client made turn. " << endl; if (!MyClient.SendPacket(P_Turn)) cout << "Bad send : Packet" << endl; if (!MyClient.SendInt(i)) cout << "Bad send : Int Turn" << endl; } } } } bool GM_MP_Game::MakeTurn(int InIndex, bool Hard, bool IsOponent) { bool TestBoolLocal = true; int IndexToUse; if (IsOponent) { if (MyIndex == 1) IndexToUse = 2; else IndexToUse = 1; } else IndexToUse = MyIndex; if (!Hard) { bool TestBoolLocal = false; switch (MyPlaceRule) { case EPlaceRule::Regular: { TestBoolLocal = CanPlaceRegular(InIndex); break; } case EPlaceRule::Horse: { TestBoolLocal = CanPlaceHorse(InIndex, IsOponent); break; } default: { break; } } if (!TestBoolLocal) return false; } if (TestBoolLocal) { XO_Buttons.at(InIndex)->TTTIndex = IndexToUse; } return true; } void GM_MP_Game::WinMenu(bool IsX) { IsMeReady = false; IsOponentReady = false; Coordinates TestCoord; TestCoord.bRelativeW = true; TestCoord.bRelativeX = true; TestCoord.bRelativeY = true; TestCoord.X = 0.2; TestCoord.W = 0.6; TestCoord.Y = 0.3; TestCoord.H = 60; const char* CharToRender; if (IsX) { CharToRender = "X Wins"; if (IsServer) ++XWins; } else { CharToRender = "O Wins"; if (IsServer) ++OWins; } MyGraph->AddStaticText(CharToRender, { 0,225,0,225 }, &TestCoord, 2); TestCoord.Y = 0.5; MyGraph->AddButton(this, &GM_MP_Game::LoadForNewRound, "New Round", &TestCoord, { 70,70,70,180 }, { 30,30,30,200 }, { 50,50,50,200 }, 2); if (IsServer) { if (!MyServer.SendPacket(P_Win)) cout << "Bad send : Win Packet" << endl; if (!MyServer.SendInt(XWins)) cout << "Bad send : XWins" << endl; if (!MyServer.SendInt(OWins)) cout << "Bad send : OWins" << endl; if (!MyServer.SendBool(IsX)) cout << "Bad send : IsX"; } } bool GM_MP_Game::CanWinCheck(int Num, bool IsO) { int TestX, TestY; // XO_Buttons.at(Num)->TTTIndex // Проверка по +Х GetGridFromNum(Num, TestX, TestY); while (true) { if (TestX < XNumber) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) TestX++; else break; else break; } TestX--; int DiagNum = 0; while (true) { if (TestX >= 0) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) { DiagNum++; TestX--; } else break; else break; } if (DiagNum >= Diagonal) return true; // Проверка по +Х +Y GetGridFromNum(Num, TestX, TestY); while (true) { if (TestX < XNumber && TestY < YNumber) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) { TestX++; TestY++; } else break; else break; } TestX--; TestY--; DiagNum = 0; while (true) { if (TestX >= 0 && TestY >= 0) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) { DiagNum++; TestX--; TestY--; } else break; else break; } if (DiagNum >= Diagonal) return true; // Проверка по +Y GetGridFromNum(Num, TestX, TestY); while (true) { if (TestY < YNumber) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) TestY++; else break; else break; } TestY--; DiagNum = 0; while (true) { if (TestY >= 0) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) { DiagNum++; TestY--; } else break; else break; } if (DiagNum >= Diagonal) return true; // Проверка по -X +Y GetGridFromNum(Num, TestX, TestY); while (true) { if (TestX >= 0 && TestY < YNumber) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) { TestX--; TestY++; } else break; else break; } TestX++; TestY--; DiagNum = 0; while (true) { if (TestX < XNumber && TestY >= 0) if (IsO + 1 == XO_Buttons.at(GetNumFromGrid(TestX, TestY))->TTTIndex) { DiagNum++; TestX++; TestY--; } else break; else break; } if (DiagNum >= Diagonal) return true; return false; } bool GM_MP_Game::CanPlaceRegular(int Num) { return XO_Buttons.at(Num)->TTTIndex == 0; } bool GM_MP_Game::CanPlaceHorse(int Num, bool IsOponent) { if (XO_Buttons.at(Num)->TTTIndex != 0) return false; int IndexToUse; if (IsOponent) { if (MyIndex == 1) IndexToUse = 2; else IndexToUse = 1; } else IndexToUse = MyIndex; bool TestBool = true; for(int i = 0; i < XO_Buttons.size(); i++) if (XO_Buttons.at(i)->TTTIndex == IndexToUse) { TestBool = false; break; } if (TestBool) return true; int MyX, MyY, TestX, TestY; GetGridFromNum(Num, MyX, MyY); for (int i = 0; i < XO_Buttons.size(); i++) { GetGridFromNum(i, TestX, TestY); if (abs((TestX - MyX) * (TestY - MyY)) == 2) if (XO_Buttons.at(i)->TTTIndex == IndexToUse) return true; } return false; }
e66e763fd924c4e5120667edd1e0de91e1985ef5
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGJE/EMCALJetTasks/UserTasks/AliTrackContainerV0.cxx
f46e93d9399325317e747d00ca5d7ab4fe4de36f
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C++
false
false
4,843
cxx
AliTrackContainerV0.cxx
/************************************************************************* * Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <iostream> #include <vector> #include <TClonesArray.h> #include <AliLog.h> #include <AliAODTrack.h> #include <AliAODv0.h> #include "AliTrackContainerV0.h" /// \cond CLASSIMP ClassImp(AliTrackContainerV0); /// \endcond /// This is the default constructor, used for ROOT I/O purposes. AliTrackContainerV0::AliTrackContainerV0() : AliTrackContainer(), fFilterDaughterTracks(0), fEvent(0), fV0s(0), fDaughterVec() { // Constructor. fBaseClassName = "AliAODTrack"; SetClassName("AliAODTrack"); } /// This is the standard named constructor. /// /// \param name Name of the particle collection AliTrackContainerV0::AliTrackContainerV0(const char *name) : AliTrackContainer(name), fFilterDaughterTracks(0), fEvent(0), fV0s(0), fDaughterVec() { // Constructor. fBaseClassName = "AliAODTrack"; SetClassName("AliAODTrack"); } /// Get list of V0 candidates from AOD event. /// (pointer itself does not change, only the array it points to) /// /// \param event Pointer to the event. void AliTrackContainerV0::SetArray(const AliVEvent *event) { AliTrackContainer::SetArray(event); if (!fFilterDaughterTracks) return; fEvent = dynamic_cast<const AliAODEvent*>(event); } /// Preparation for next event. /// Run in each event (via AliAnalysisTaskEmcal::RetrieveEventObjects) void AliTrackContainerV0::NextEvent(const AliVEvent * event) { AliTrackContainer::NextEvent(event); if (fFilterDaughterTracks) { // V0s daughter tracks will be removed from track sample if (!fEvent) { AliWarning("fEvent is not valid!"); return; } fV0s = dynamic_cast<TClonesArray*>(fEvent->GetV0s()); if (!fV0s) { AliWarning("fV0s is not valid!"); return; } fDaughterVec.clear(); Int_t iNumV0s = fV0s->GetEntriesFast(); for(Int_t iV0 = 0; iV0 < iNumV0s; iV0++) ExtractDaughters(dynamic_cast<AliAODv0*>(fV0s->At(iV0))); } } /// Extract the V0 candidate daughter tracks and add them to daughter track list. /// /// \param cand Pointer to V0 candidate to be set. void AliTrackContainerV0::ExtractDaughters(AliAODv0* cand) { if (!cand) return; for (Int_t i = 0; i < 2; i++) { AliAODTrack* track = dynamic_cast<AliAODTrack*>(cand->GetDaughter(i)); if(!track) { AliWarning("Track is not valid! Skipping candidate."); return; } fDaughterVec.push_back(track->GetID()); } } /// Check whether the particle is a daughter of /// V0 candidate (in which case the particle is rejected); /// then calls the base class AcceptTrack(AliVTrack*) method. /// /// \param vp Pointer to track to be checked. /// \param rejectionReason Rejection reason. /// /// \return kTRUE if the particle is accepted, kFALSE otherwise. Bool_t AliTrackContainerV0::ApplyTrackCuts(const AliVTrack* vp, UInt_t &rejectionReason) const { const AliAODTrack* track = dynamic_cast<const AliAODTrack*>(vp); if (!track) return kFALSE; if (AliTrackContainer::ApplyTrackCuts(vp, rejectionReason)) { if (IsV0Daughter(track)) { // track is one of the V0 daughter - will be rejected return kFALSE; } else { return kTRUE; } } else { return kFALSE; } } /// Check whether the particle is among the daughter tracks of the V0 candidate /// /// \param track Pointer to input track to be checked. /// /// \return kTRUE if the particle is a daughter of V0 candidate, kFALSE otherwise Bool_t AliTrackContainerV0::IsV0Daughter(const AliAODTrack* track) const { Int_t trackID = track->GetID(); if(track->IsGlobalConstrained()){ // constrained tracks have a changed ID trackID = -1-trackID; } for(Int_t i = 0; i < fDaughterVec.size(); i++) { if(trackID == fDaughterVec[i]) { return kTRUE; } } return kFALSE; }
d45c50350e80061cea075c554045f06cdeaba533
6111401e3997bfdd31f991e0e551d4c0609e07e4
/video_player/main.cpp
ee3c06f91bee28967b7999473a8a49e1790be06f
[]
no_license
SimonFu/learning_opencv
91b074cc744971269bf8b018a66b738a77ad29b3
ae0b2e694794721bb0f3ae951cf2f40eb6b1fb7e
refs/heads/master
2020-04-08T19:46:46.407667
2018-12-05T07:15:38
2018-12-05T07:15:38
159,670,783
0
0
null
null
null
null
UTF-8
C++
false
false
826
cpp
main.cpp
#include <QCoreApplication> #include <QTimer> #include <QDebug> #include <opencv2/opencv.hpp> using namespace cv; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if(argc < 2) { qInfo() << "Usage: " << argv[0] << " [video file path]"; return -1; } VideoCapture capture(argv[1]); namedWindow("Video player"); QTimer timer; timer.setInterval(33); QObject::connect(&timer, &QTimer::timeout, [&](){ Mat frame; capture >> frame; if (frame.empty()) return; imshow("Video player", frame); }); timer.start(); QObject::connect(&a, &QCoreApplication::aboutToQuit, [&]{ qDebug() << "aboutToQuit"; capture.release(); destroyWindow("Video player"); }); return a.exec(); }
6608281b47ab1699e10f5b6f68af8b8119b6bb2c
a979c083b34cb85ccdd9e36df74280645dd28138
/kmymoney/widgets/widgethintframe.h
5b1f9baf7e636850274190d85c241cba1b924ef8
[]
no_license
rhabacker/kmymoney
9b386d2165c786279891273dcb57657205100479
0d5c7e80f6e7718756a288d45287e7f17fd9a1b4
refs/heads/master
2023-04-13T18:11:00.217195
2022-08-21T09:20:48
2022-08-24T04:56:52
69,508,455
0
0
null
2016-09-28T22:22:32
2016-09-28T22:22:31
null
UTF-8
C++
false
false
2,937
h
widgethintframe.h
/* SPDX-FileCopyrightText: 2015-2018 Thomas Baumgart <tbaumgart@kde.org> SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef WIDGETHINTFRAME_H #define WIDGETHINTFRAME_H #include "kmm_base_widgets_export.h" // ---------------------------------------------------------------------------- // QT Includes #include <QFrame> class QWidget; class QMetaMethod; // ---------------------------------------------------------------------------- // KDE Includes // ---------------------------------------------------------------------------- // Project Includes class KMM_BASE_WIDGETS_EXPORT WidgetHintFrame : public QFrame { Q_OBJECT public: enum FrameStyle { Error = 0, Warning, Info, }; Q_ENUM(FrameStyle) explicit WidgetHintFrame(QWidget* editWidget, FrameStyle style = Error, Qt::WindowFlags f = {}); ~WidgetHintFrame(); void attachToWidget(QWidget* w); void detachFromWidget(); bool isErroneous() const; QWidget* editWidget() const; /** * Shows the info frame around @a editWidget and in case @a tooltip * is not null (@sa QString::isNull()) the respective message will * be loaded into the @a editWidget's tooltip. In case @a tooltip is null * (the default) the @a editWidget's tooltip will not be changed. */ static void show(QWidget* editWidget, const QString& tooltip = QString()); /** * Hides the info frame around @a editWidget and in case @a tooltip * is not null (@sa QString::isNull()) the respective message will * be loaded into the @a editWidget's tooltip. In case @a tooltip is null * (the default) the @a editWidget's tooltip will not be changed. */ static void hide(QWidget* editWidget, const QString& tooltip = QString()); protected: bool eventFilter(QObject* o, QEvent* e) final override; Q_SIGNALS: void changed(); private: class Private; Private* const d; }; class KMM_BASE_WIDGETS_EXPORT WidgetHintFrameCollection : public QObject { Q_OBJECT public: explicit WidgetHintFrameCollection(QObject* parent = 0); ~WidgetHintFrameCollection(); void addFrame(WidgetHintFrame* frame); void addWidget(QWidget* w); void removeWidget(QWidget* w); /** * Connect the @a chainedCollection so that its result affects this * collection. Only one collection can be chained. * * @returns true if the connection was setup correctly. */ bool chainFrameCollection(WidgetHintFrameCollection* chainedCollection); protected: void connectNotify(const QMetaMethod& signal) override; protected Q_SLOTS: virtual void unchainFrameCollection(); virtual void frameDestroyed(QObject* o); virtual void changeChainedCollectionState(bool valid); virtual void updateWidgets(); Q_SIGNALS: void inputIsValid(bool valid); private: class Private; Private* const d; }; #endif // WIDGETHINTFRAME_H
2c5238b97c8ad32dfffcd69a32d9a0322ac224b4
de0ffd2462cd1ccd589fefaaf0769219be03577f
/Screen.cpp
06fd9faf2baa581ff7c95a1c8da1bbdedd18ee39
[]
no_license
EdgardoCuellar/DoublePendule
760f7bee3e2c6754c03fb3f412d16a17f0e6d33e
de2e4dab639d4fde5a6a8a33496f072bca2182ad
refs/heads/master
2023-08-27T02:33:04.581537
2021-10-05T12:54:44
2021-10-05T12:54:44
413,817,522
0
0
null
null
null
null
UTF-8
C++
false
false
6,319
cpp
Screen.cpp
#include "Screen.hpp" using namespace std; Screen::Screen() noexcept = default; Screen::~Screen() noexcept = default; void Screen::init(const char *title, int xpos, int ypos, int wigth, int height, bool fullscreen) { int flags = 0; if (fullscreen){ flags = SDL_WINDOW_FULLSCREEN; } if (SDL_Init(SDL_INIT_EVERYTHING) == 0){ cout << "All is init" << endl; window = SDL_CreateWindow(title, xpos, ypos, wigth, height, flags); if (window){ cout << "Window created" << endl; } renderer = SDL_CreateRenderer(window, -1, 0); if (renderer){ SDL_SetRenderDrawColor(renderer, 33, 33, 33, 255); cout << "Renderer create" << endl; } isRunning = true; } else{ isRunning = false; } centerP = Point(WITDH/2, HEIGHT/2 - 50, SIZEP/2, 2); createPendule(); } void Screen::handleEvents(){ SDL_Event event; SDL_PollEvent(&event); switch (event.type) { case SDL_QUIT: isRunning = false; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_SPACE: startPendule(); break; } } } void Screen::update(){ if (isStart){ float num1 = -G * (2 * SIZEP + SIZEP) * sin(pendules[0].getRadian()); float num2 = -SIZEP * G * sin(pendules[0].getRadian()-2*pendules[1].getRadian()); float num3 = -2*sin(pendules[0].getRadian()-pendules[1].getRadian())*SIZEP; float num4 = pendules[1].getSpeedDeg()*pendules[1].getSpeedDeg()*LENGHT+pendules[0].getSpeedDeg()*pendules[0].getSpeedDeg()*LENGHT*cos(pendules[0].getRadian()-pendules[1].getRadian()); float den = LENGHT * (2*SIZEP+SIZEP-SIZEP*cos(2*pendules[0].getRadian()-2*pendules[1].getRadian())); pendules[0].setAcc((num1 + num2 + num3*num4) / den); num1 = 2 * sin(pendules[0].getRadian()-pendules[1].getRadian()); num2 = (pendules[0].getSpeedDeg()*pendules[0].getSpeedDeg()*LENGHT*(SIZEP+SIZEP)); num3 = G * (SIZEP + SIZEP) * cos(pendules[0].getRadian()); num4 = pendules[1].getSpeedDeg()*pendules[1].getSpeedDeg()*LENGHT*SIZEP*cos(pendules[0].getRadian()-pendules[1].getRadian()); den = LENGHT * (2*SIZEP+SIZEP-SIZEP*cos(2*pendules[0].getRadian()-2*pendules[1].getRadian())); pendules[1].setAcc((num1*(num2+num3+num4)) / den); pendules[0].setPosX(static_cast<int>(centerP.getPosX() + LENGHT*sin(pendules[0].getRadian()))); pendules[0].setPosY(static_cast<int>(centerP.getPosY() + LENGHT*cos(pendules[0].getRadian()))); pendules[1].setPosX(static_cast<int>(pendules[0].getPosX() + LENGHT*sin(pendules[1].getRadian()))); pendules[1].setPosY(static_cast<int>(pendules[0].getPosY() + LENGHT*cos(pendules[1].getRadian()))); for (int i = 0; i < 2; ++i) { pendules[i].addSpeed(pendules[i].getAcc()); pendules[i].addDegre(pendules[i].getSpeedDeg()); pendules[i].addSpeed(-pendules[i].getSpeedDeg()*RESISTANCE); } trace.push_back({static_cast<int>(pendules[1].getPosX()), static_cast<int>(pendules[1].getPosY())}); if (TIMER != 0 && trace.size() > TIMER) trace.erase(trace.begin()); } } void Screen::render(){ // Background SDL_SetRenderDrawColor(renderer, COLORS[0][0], COLORS[0][1], COLORS[0][2], 255); SDL_RenderClear(renderer); if (isStart) displayTrace(); // Display all point displayPendule(); SDL_RenderPresent(renderer); } void Screen::clean(){ SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); SDL_Quit(); cout << "All clean up" << endl; } void Screen::createPendule() noexcept { pendules[0] = Pendule(centerP.getPosX() + LENGHT * sin(pendules[0].getRadian()), centerP.getPosY() + LENGHT * cos(pendules[0].getRadian()), SIZEP); pendules[1] = Pendule(pendules[0].getPosX() + LENGHT * sin(pendules[1].getRadian()), pendules[0].getPosY() + LENGHT * cos(pendules[1].getRadian()), SIZEP); } void Screen::displayPendule() noexcept { displayLine(); getPoints(centerP); getPoints(pendules[0]); getPoints(pendules[1]); } void Screen::displayLine() noexcept { SDL_SetRenderDrawColor(renderer, COLORS[3][0], COLORS[3][1], COLORS[3][2], 255); for (int i = -LINE_SIZE + 1; i < LINE_SIZE; ++i) { for (int j = -LINE_SIZE + 1; j < LINE_SIZE; ++j) { SDL_RenderDrawLine(renderer, static_cast<int>(centerP.getPosX())+i, static_cast<int>(centerP.getPosY())+j, static_cast<int>(pendules[0].getPosX())+i, static_cast<int>(pendules[0].getPosY())+j); } } for (int i = -LINE_SIZE; i < LINE_SIZE; ++i) { for (int j = -LINE_SIZE+1; j < LINE_SIZE; ++j) { SDL_RenderDrawLine(renderer, static_cast<int>(pendules[0].getPosX())+i, static_cast<int>(pendules[0].getPosY())+j, static_cast<int>(pendules[1].getPosX())+i, static_cast<int>(pendules[1].getPosY())+j); } } } void Screen::getPoints(Point &pt) noexcept { SDL_SetRenderDrawColor(renderer, COLORS[pt.getColor()][0], COLORS[pt.getColor()][1], COLORS[pt.getColor()][2], 255); vector<array<int, 2>> tmp = pt.getPoint(); for (int i = 0; i < tmp.size()/2; ++i) { SDL_RenderDrawLine(renderer, tmp[i*2][0], tmp[i*2][1], tmp[(i*2)+1][0], tmp[(i*2)+1][1]); } SDL_RenderDrawLine(renderer, static_cast<int>(pt.getPosX())-pt.getPosR(), static_cast<int>(pt.getPosY()), static_cast<int>(pt.getPosX())+pt.getPosR(), static_cast<int>(pt.getPosY())); } void Screen::displayTrace() noexcept { SDL_SetRenderDrawColor(renderer, COLORS[4][0], COLORS[4][1], COLORS[4][2], 255); for (int i = 0; i < trace.size()-1 ; ++i) { SDL_RenderDrawLine(renderer, trace[i][0], trace[i][1], trace[i+1][0], trace[i+1][1]); } } /*void Screen::createPoints(int nb) noexcept{ random_device rd; mt19937 mt(rd()); uniform_real_distribution<double> rdW(0, WITDH); uniform_real_distribution<double> rdH(0, HEIGHT); for (int i = 0; i < nb; ++i) { points.push_back(new Stars(rdW(mt), rdH(mt), sizeStars)); } }*/
38e7837c70fc92bef3745c86304b2d114d190b89
40b0530ef3eb345c49fc0d2face8bed9088a58c5
/v1.3/apps/hall/lib/hall-stm32/hall.cpp
46ecf75d83ac219ff28012cb9bcb04a608c8bc5a
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
Enjection/monty
1262974ab1c74b82fc0ce4cef7906b36eea77bdb
e7f2ecaf1b7f2ed0ce24f5aaa4c14e801d18dfde
refs/heads/main
2023-07-18T16:17:08.465840
2021-08-25T09:30:01
2021-08-25T09:30:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,530
cpp
hall.cpp
#include "hall.h" #include <cstring> extern uint32_t SystemCoreClock; // CMSIS namespace hall { uint8_t irqMap [100]; // TODO size according to real vector table Device* devMap [20]; // must be large enough to hold all device objects uint8_t devNext; volatile uint32_t Device::pending; constexpr auto SCB = io32<0xE000'E000>; void idle () { asm ("wfi"); } auto Pin::mode (int m) const -> int { #if STM32F1 RCC(0x18) |= (1<<_port) | (1<<0); // enable GPIOx and AFIO clocks x // FIXME wrong, mode bits have changed, and it changes return value if (m == 0b1000 || m == 0b1100) { gpio32(ODR)[_pin] = m & 0b0100; m = 0b1000; } gpio32(0x00).mask(4*_pin, 4) = m; // CRL/CRH #else // enable GPIOx clock #if STM32F3 RCC(0x14)[_port] = 1; #elif STM32F4 | STM32F7 RCC(0x30)[_port] = 1; asm ("dsb"); #elif STM32G0 RCC(0x34)[_port] = 1; #elif STM32H7 RCC(0xE0)[_port] = 1; asm ("dsb"); #elif STM32L0 RCC(0x2C)[_port] = 1; #elif STM32L4 RCC(0x4C)[_port] = 1; #endif gpio32(0x00).mask(2*_pin, 2) = m; // MODER gpio32(0x04).mask( _pin, 1) = m >> 2; // TYPER gpio32(0x08).mask(2*_pin, 2) = m >> 3; // OSPEEDR gpio32(0x0C).mask(2*_pin, 2) = m >> 5; // PUPDR gpio32(0x20).mask(4*_pin, 4) = m >> 8; // AFRL/AFRH #endif // STM32F1 return m; } auto Pin::mode (char const* desc) const -> int { int m = 0, a = 0; for (auto s = desc; *s != ',' && *s != 0; ++s) switch (*s) { // 1 pp ss t mm case 'A': m = 0b1'00'00'0'11; break; // m=11 analog case 'F': m = 0b1'00'00'0'00; break; // m=00 float case 'D': m |= 0b1'10'00'0'00; break; // m=00 pull-down case 'U': m |= 0b1'01'00'0'00; break; // m=00 pull-up case 'P': m = 0b1'00'01'0'01; break; // m=01 push-pull case 'O': m = 0b1'00'01'1'01; break; // m=01 open drain case 'L': m &= 0b1'11'00'1'11; break; // s=00 low speed case 'N': break; // s=01 normal speed case 'H': m ^= 0b0'00'11'0'00; break; // s=10 high speed case 'V': m |= 0b0'00'10'0'00; break; // s=11 very high speed default: if (*s < '0' || *s > '9' || a > 1) return -1; m = (m & ~0b11) | 0b10; // m=10 alt mode a = 10 * a + *s - '0'; case ',': break; // valid as terminator } return mode(m + (a<<8)); } auto Pin::config (char const* desc) -> int { if ('A' <= *desc && *desc <= 'O') { _port = *desc++ - 'A'; _pin = 0; while ('0' <= *desc && *desc <= '9') _pin = 10 * _pin + *desc++ - '0'; } return _port == 15 ? -1 : *desc++ != ':' ? 0 : mode(desc); } auto Pin::define (char const* d, Pin* v, int n) -> char const* { Pin dummy; int lastMode = 0; while (*d != 0) { if (--n < 0) v = &dummy; auto m = v->config(d); if (m < 0) break; if (m != 0) lastMode = m; else if (lastMode != 0) v->mode(lastMode); auto p = strchr(d, ','); if (p == nullptr) return n > 0 ? d : nullptr; d = p+1; ++v; } return d; } Device::Device () { //TODO ensure(devNext < sizeof devMap / sizeof *devMap); _id = devNext; devMap[devNext++] = this; } void Device::irqInstall (uint32_t irq) const { //TODO ensure(irq < sizeof irqMap); irqMap[irq] = _id; nvicEnable(irq); } void processAllPending () { uint32_t pend; { BlockIRQ crit; pend = Device::pending; Device::pending = 0; } for (int i = 0; i < devNext; ++i) if (pend & (1<<i)) devMap[i]->process(); } auto systemHz () -> uint32_t { return SystemCoreClock; } void systemReset () { for (uint32_t i = 0; i < systemHz() >> 15; ++i) {} SCB(0xD0C) = (0x5FA<<16) | (1<<2); // SCB AIRCR reset while (true) {} } namespace systick { volatile uint32_t ticks; uint8_t rate; extern "C" void expireTimers (uint16_t, uint16_t&); // TODO yuck struct Ticker : Device { void process () override { auto now = (uint16_t) millis(); uint16_t limit = 60'000; for (int i = 0; i < devNext; ++i) devMap[i]->expire(now, limit); init(limit < 100 ? limit : 100); } void expire (uint16_t now, uint16_t& limit) override { expireTimers(now, limit); } }; Ticker ticker; void init (uint8_t ms) { if (rate > 0) ticks = millis(); rate = ms; SCB(0x14) = (ms*(systemHz()/1000))/8-1; // reload value SCB(0x18) = 0; // current SCB(0x10) = 0b011; // control, ÷8 mode } void deinit () { ticks = millis(); SCB(0x10) = 0; rate = 0; } auto millis () -> uint32_t { while (true) { uint32_t t = ticks, n = SCB(0x18); if (t == ticks) return t + rate - (n*8)/(systemHz()/1000); } // ticked just now, spin one more time } auto micros () -> uint32_t { // scaled to work with any clock rate multiple of 100 kHz while (true) { uint32_t t = ticks, n = SCB(0x18); if (t == ticks) return (t%1000 + rate)*1000 - (n*80)/(systemHz()/100'000); } // ticked just now, spin one more time } extern "C" void SysTick_Handler () { ticks += rate; devMap[ticker._id]->interrupt(); } } namespace cycles { enum { CTRL=0x000,CYCCNT=0x004,LAR=0xFB0 }; enum { DEMCR=0xDFC }; void init () { DWT(LAR) = 0xC5ACCE55; SCB(DEMCR) = SCB(DEMCR) | (1<<24); // set TRCENA in DEMCR clear(); DWT(CTRL) = DWT(CTRL) | 1; } void deinit () { DWT(CTRL) = DWT(CTRL) & ~1; } } namespace watchdog { constexpr auto IWDG = io32<0x4000'3000>; enum { KR=0x00,PR=0x04,RLR=0x08,SR=0x0C }; uint8_t cause; // "semi public" auto resetCause () -> int { #if STM32F4 || STM32F7 enum { CSR=0x74, RMVF=24 }; #elif STM32L4 enum { CSR=0x94, RMVF=23 }; #endif if (cause == 0) { cause = RCC(CSR) >> 24; RCC(CSR)[RMVF] = 1; // clears all reset-cause flags } return cause & (1<<5) ? -1 : // iwdg cause & (1<<3) ? 2 : // por/bor cause & (1<<2) ? 1 : 0; // nrst, or other } void init (int rate) { while (IWDG(SR)[0]) {} // wait until !PVU IWDG(KR) = 0x5555; // unlock PR IWDG(PR) = rate; // max timeout, 0 = 400ms, 7 = 26s IWDG(KR) = 0xCCCC; // start watchdog } void reload (int n) { while (IWDG(SR)[1]) {} // wait until !RVU IWDG(KR) = 0x5555; // unlock PR IWDG(RLR) = n; kick(); } void kick () { IWDG(KR) = 0xAAAA; // reset the watchdog timout } } void debugPutc (void*, int c) { constexpr auto ITM8 = io8<0xE000'0000>; constexpr auto ITM = io32<0xE000'0000>; enum { TER=0xE00, TCR=0xE80, LAR=0xFB0 }; if ((ITM(TCR) & 1) && (ITM(TER) & 1)) { while ((ITM(0) & 1) == 0) {} ITM8(0) = c; } } extern "C" void irqDispatch () { uint8_t irq = SCB(0xD04); // ICSR auto idx = irqMap[irq-16]; devMap[idx]->interrupt(); } } // to re-generate "irqs.h", see the "all-irqs.sh" script #define IRQ(f) void f () __attribute__ ((alias ("irqDispatch"))); extern "C" { #include "irqs.h" }
31dc516094030978faaf60ecfe1b4a32f5552e71
5e69255c5f7400efee204851b1b6fccf606d7a32
/kvstore_client.h
60130524734751189322f624a0ff91fdc8734fb9
[ "MIT" ]
permissive
RaymondJune/csci499_RaymondJune
af8e8bf4e9afaddc0e5ecd8f7ae8f89e2c051355
01606fa3707492b28adf17d5b9c903e3687e1e97
refs/heads/master
2022-06-23T13:07:12.940035
2020-05-06T23:50:05
2020-05-06T23:50:05
236,248,003
1
1
null
2020-05-06T23:50:06
2020-01-26T00:15:32
C++
UTF-8
C++
false
false
1,164
h
kvstore_client.h
// // Created by Ruimin Zeng on 2/15/20. // #ifndef CS499_RAYMONDJUNE_KVSTORE_CLIENT_H #define CS499_RAYMONDJUNE_KVSTORE_CLIENT_H #include <grpcpp/grpcpp.h> #include "build/kvstore.grpc.pb.h" using grpc::Channel; using grpc::ClientContext; using grpc::ClientReaderWriter; using grpc::Status; using kvstore::GetReply; using kvstore::GetRequest; using kvstore::KeyValueStore; using kvstore::PutReply; using kvstore::PutRequest; using kvstore::RemoveReply; using kvstore::RemoveRequest; // client class with interfaces func can call to access key value store service class KeyValueStoreClient { public: explicit KeyValueStoreClient(std::shared_ptr<Channel> channel); // remove key-value pair from store bool Remove(const std::string& key); // put new key-value pair into store bool Put(const std::string& key, const std::string& value); // get the associated values for keys, if a key does not exist, an empty // string is returned std::vector<std::string> Get(const std::vector<std::string>& keys); private: // stub used to call actual rpc std::unique_ptr<KeyValueStore::Stub> stub_; }; #endif // CS499_RAYMONDJUNE_KVSTORE_CLIENT_H
166a18af6d4b4117caf360eade58af6eb43b512c
76726498127e40a9e1d9e4a2aad38613494bb7d2
/src/student_t.cpp
ed24b6a75401311e94ac2e8cd1dd524327cc1412
[]
no_license
bbbales2/math-benchmarks
ea413edbb5d481016bffcbb87cf307e043b5584b
207e6b5d29b055adcf650d297740092e96c690ec
refs/heads/master
2023-02-05T08:37:32.964850
2020-12-21T20:19:50
2020-12-21T20:19:50
294,805,502
0
2
null
null
null
null
UTF-8
C++
false
false
3,807
cpp
student_t.cpp
#include <benchmark/benchmark.h> #include <stan/math.hpp> #include <utility> #include "toss_me.hpp" #include "callback_bench_impl.hpp" template <typename T1, typename T2, typename T3, typename T4> struct init { auto operator()(benchmark::State& state) { using stan::math::exp; Eigen::VectorXd y_val = Eigen::VectorXd::Random(state.range(0)); Eigen::VectorXd nu_val = exp(Eigen::VectorXd::Random(state.range(0))); Eigen::VectorXd mu_val = Eigen::VectorXd::Random(state.range(0)); Eigen::VectorXd sigma_val = exp(Eigen::VectorXd::Random(state.range(0))); return std::make_tuple(bench_promote<T1>(y_val), bench_promote<T4>(nu_val), bench_promote<T2>(mu_val), bench_promote<T3>(sigma_val)); } }; template <typename Vectorizer, typename... Args> static void student_t_lpdf(benchmark::State& state) { auto run = [](const auto&... args) { return student_t_lpdf(args...); }; callback_bench_impl<Vectorizer>(init<Args...>(), run, state); } template <typename Vectorizer, typename... Args> static void student_t_cdf(benchmark::State& state) { auto run = [](const auto&... args) { return student_t_cdf(args...); }; callback_bench_impl<Vectorizer>(init<Args...>(), run, state); } template <typename Vectorizer, typename... Args> static void student_t_lcdf(benchmark::State& state) { auto run = [](const auto&... args) { return student_t_lcdf(args...); }; callback_bench_impl<Vectorizer>(init<Args...>(), run, state); } template <typename Vectorizer, typename... Args> static void student_t_lccdf(benchmark::State& state) { auto run = [](const auto&... args) { return student_t_lccdf(args...); }; callback_bench_impl<Vectorizer>(init<Args...>(), run, state); } using stan::math::var; int start_val = 2; int end_val = 1024; BENCHMARK(toss_me); BENCHMARK_TEMPLATE(student_t_lpdf,non_vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lpdf,vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_cdf,non_vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_cdf,vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lcdf,non_vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lcdf,vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lccdf,non_vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lccdf,vec,var,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lpdf,non_vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lpdf,vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_cdf,non_vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_cdf,vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lcdf,non_vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lcdf,vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lccdf,non_vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_TEMPLATE(student_t_lccdf,vec,double,var,var,var)->RangeMultiplier(2)->Range(start_val, end_val)->UseManualTime(); BENCHMARK_MAIN();
122e2bb05398a72183c20b014017be007957d369
2305606b976c1a17fd96b354d3e6ef9117cec4b8
/src/AssimpImporter.cpp
d01154fc6e0a5f46bb14dc88e152b6bec02459ee
[]
no_license
riveranb/ogre-assimp
ce700987af70a7b7cbb8169cc1d6f0f9047020f6
9c0cbfefeab09de7f51e8be3495a33b16a6eb9c9
refs/heads/Ogre_Assimp_Adaptor
2021-08-15T02:42:25.000720
2017-11-17T06:58:05
2017-11-17T06:58:05
106,502,156
1
0
null
2017-10-11T03:41:31
2017-10-11T03:41:31
null
UTF-8
C++
false
false
1,846
cpp
AssimpImporter.cpp
#include <iostream> #include "AssimpImporter.h" #include "AssimpLoader.h" #include "OgreMesh.h" #include "OgreMeshManager.h" #include "OgreMesh2.h" #include "OgreMeshManager2.h" namespace Demo { namespace assimp { Importer::Importer() { } bool Importer::createMeshV2(Ogre::MeshPtr & pdestmesh, const Ogre::String& meshname, const Ogre::String& filename, int quality) { // search if mesh is already created (by meshname) pdestmesh = Ogre::MeshManager::getSingleton().getByName(meshname); if (!pdestmesh.isNull()) { return true; } // create one manual pdestmesh = Ogre::MeshManager::getSingleton().createManual(meshname, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); AssimpLoader::AssetOptions opts; prepareLoadOptions(opts, filename); bool retCode = true; try { retCode = mLoader.convertV2(opts, pdestmesh, quality); } catch (Ogre::Exception& e) { Ogre::MeshManager::getSingleton().remove(pdestmesh); // remove generated pdestmesh.reset(); std::cerr << "[Assimp] FATAL ERROR: " << e.getDescription() << std::endl; std::cerr << "[Assimp] ABORTING loading!" << std::endl; retCode = false; } return retCode; } void Importer::prepareLoadOptions(AssimpLoader::AssetOptions & opts, const Ogre::String& filename) { //////////////////options////////////////////////// opts.quietMode = false; opts.customAnimationName = ""; opts.dest = ""; opts.animationSpeedModifier = 1.0; opts.lodValue = 250000; opts.lodFixed = 0; opts.lodPercent = 20; opts.numLods = 0; // no level of detail now opts.usePercent = true; // ignore program name char* source = 0; char* dest = 0; opts.params = AssimpLoader::LP_GENERATE_SINGLE_MESH; opts.source = filename; dest = "."; opts.dest = dest; /////////////////////////////////////////////////// } } }
8f63d0b45ee5722255080f333e191e32a7c6c3a5
0e17d3f47b50b6995093b71cd039acb8368d97e8
/SceneObject/ButtonDepr.h
17ee82878cb5a8ace0525c679063c8c87931cd54
[]
no_license
Krupnikas/christmasDefence
e22441471bd6bf1ef5596e65485558d0af2c8d70
04fd4e4401d92b37248de96a700d61239a1b620a
refs/heads/master
2021-01-19T00:19:57.196304
2019-12-11T21:33:36
2019-12-11T21:33:36
72,995,889
4
0
null
null
null
null
UTF-8
C++
false
false
691
h
ButtonDepr.h
#pragma once #include <SceneObject/SceneObject.h> #include <Game/Game.h> class CButtonDepr : public CSceneObject { Q_OBJECT public: CButtonDepr(); CButtonDepr(EButtonType Type, QRect ButtonRect, std::shared_ptr<QPixmap> Pixmap, CGame *Game, qreal ZOrder = 10, qreal Angle = 0); ~CButtonDepr(); EButtonType type; QRect buttonRect; virtual void show() override; void init(EButtonType Type, QRect ButtonRect, std::shared_ptr<QPixmap> Pixmap, CGame *Game, qreal ZOrder = 10, qreal Angle = 0); public slots: void onMousePressed(QMouseEvent *event); signals: void pressed(EButtonType Type); };
b7891b1ed091cffbb43db05602a128c4619dd1a9
9f075f47ecb22f95985add4224ae84357ce8e03c
/sandbox/src/global.h
d57ee45121e2dee0d898168b0157e78f9ac58d58
[ "Zlib" ]
permissive
ApiO/pgtech
5b2a2688a43f3fe839cf5ce732766a51108b9563
e7c03ea1a269a96fca27b60a417cf4a5759d40ba
refs/heads/master
2020-05-24T18:21:53.067826
2019-05-18T22:37:25
2019-05-18T22:37:25
187,404,856
0
0
null
null
null
null
UTF-8
C++
false
false
695
h
global.h
#pragma once #include <runtime/types.h> #include <runtime/memory_types.h> #include "camera.h" namespace app { struct Screen { pge::i32 width; pge::i32 height; pge::f32 w2; pge::f32 h2; }; extern Screen global_screen; extern pge::u64 global_simple_package; extern pge::u64 global_samp_ball_pkg; extern pge::u64 global_game_world; extern pge::u64 global_gui_world; extern pge::u64 global_viewport; extern pge::u32 global_pad_index; extern Camera global_game_camera; extern Camera global_gui_camera; extern char *global_font_name; extern bool global_debug_physic; extern char *global_sample_desciption; }
df571a6b0776b46c369ea61f0e46c8ed9f5457d9
b71556aee4654b48e91ba8124a3a8ded26de273e
/contest/USSTforces #22 (Div. 3)/C.cpp
ea25762c662949024e7648ad7a77472435b2d82f
[]
no_license
young-zy/algorithm
0255a327390c6b149870b34fbd34816dc002e82e
536eddd9a6bc03e81c566afa05c53f555eb14a86
refs/heads/master
2021-07-23T07:23:29.929221
2020-04-23T16:33:28
2020-04-23T16:33:28
149,439,464
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
C.cpp
#include<bits/stdc++.h> #define endl "\n" #define INF 0x3f3f3f3f using namespace std; int ch[5005][5005]; int sum[5005][5005] = {0}; long long a(int x1, int y1,int x2,int y2){ return (long long)sum[x2][y2] - sum[x1][y2] - sum[x2][y1] + sum[x1][y1]; } int main(){ // ios_base::sync_with_stdio(false); // cin.tie(NULL); int n,m; cin>>n>>m; memset(ch,0,sizeof(ch)); memset(sum,0,sizeof(sum)); for(int i = 1; i<=n ; i++){ for(int j = 1; j<=m; j++){ scanf(" %c",&ch[i][j]); ch[i][j] -= '0'; } } for(int i = 0; i <= 5000;i++){ for(int j = 0; j<=5000;j++){ sum[i][j] = (long long)sum[i-1][j] + sum[i][j-1]-sum[i-1][j-1] + ch[i][j]; } } // for(int i = 0; i<=n ; i++){ // for(int j = 0; j<=m ; j++){ // cout<<sum[i][j]<<" "; // } // cout<<endl; // } long long res = INF; for(int k = 2;k<max(n,m);k++){ long long ans = 0; for(int i = k ;i<n+k;i+=k){ for(int j = k ;j<m+k;j+=k){ ans += min(a(i-k,j-k,i,j),k*k-a(i-k,j-k,i,j)); } } res = min(res,ans); } cout<<res; return 0; }
f46bb41ac0c6721a8ed5e238ed4eb48340d351f3
211f86d4ae3465352f314a9d07cf5a62cbcb670e
/src/Molinete.cpp
c857ff522d8e3c36c6982f348e159288ec521ced
[ "Apache-2.0" ]
permissive
EddyVegaGarcia/tda-accesos-cpp
ef9cac10356ea660890db019dfe7b09dab1d4580
8644c43b6b5a2e76996b29f00ac4d6cafd96a3e4
refs/heads/master
2021-06-25T04:12:39.539894
2017-09-07T05:18:41
2017-09-07T05:18:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,113
cpp
Molinete.cpp
#include "Molinete.h" Molinete::Molinete() { personasQueEntraron = 0; personasQueSalieron = 0; maximaCantidadDePersonasDentro = 0; } Molinete::Molinete(int personasQueYaEstanDentro) { if (personasQueYaEstanDentro > 0) { personasQueEntraron = personasQueYaEstanDentro; } else { personasQueEntraron = 0; } personasQueSalieron = 0; maximaCantidadDePersonasDentro = personasQueEntraron; } void Molinete::dejarEntrar() { personasQueEntraron++; if (contarPersonasDentro() > maximaCantidadDePersonasDentro) { maximaCantidadDePersonasDentro = contarPersonasDentro(); } } void Molinete::dejarSalir() { if (existenPersonasDentro()) { personasQueSalieron++; } } int Molinete::contarPersonasDentro() { return personasQueEntraron - personasQueSalieron; } bool Molinete::existenPersonasDentro() { return (contarPersonasDentro() > 0); } int Molinete::contarTotalDePersonasQueEntraron() { return personasQueEntraron; } int Molinete::calcularMaximaCantidadDePersonasDentro() { return maximaCantidadDePersonasDentro; }
1c32586beb48b3cc0b02d0aa2d9a040e9a4e6106
56f252bb1cec2b15e668ed785e2e6ff4ff05dc5f
/include/octoon/input/iinput.h
9d8d88d4100d3a3da2376483c115dabdcb76a4a8
[]
no_license
EMinsight/octoon
31096ae3243143ddd7ee07aa587c985c37ea93a0
6297971996dab45fb35757d12dafe5733768dec7
refs/heads/master
2022-01-02T10:40:47.804455
2018-02-21T05:43:24
2018-02-21T05:43:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,125
h
iinput.h
#ifndef OCTOON_INPUT_BASE_H_ #define OCTOON_INPUT_BASE_H_ #include <octoon/input/iinput_device.h> #include <octoon/input/iinput_keyboard.h> #include <octoon/input/iinput_mouse.h> namespace octoon { namespace input { class OCTOON_EXPORT IInput : public runtime::RttiInterface { OctoonDeclareSubInterface(IInput, runtime::RttiInterface) public: IInput() = default; virtual ~IInput() = default; virtual bool open() noexcept = 0; virtual bool open(InputDevicePtr& device) noexcept = 0; virtual bool open(InputDevicePtr&& device) noexcept = 0; virtual void close() noexcept = 0; virtual void set_capture_object(WindHandle window) noexcept = 0; virtual WindHandle get_capture_object() const noexcept = 0; virtual float get_axis(InputAxis::Code axis) const noexcept = 0; virtual void set_mouse_pos(InputButton::mouse_t x, InputButton::mouse_t y) noexcept = 0; virtual void get_mouse_pos(InputButton::mouse_t& x, InputButton::mouse_t& y) const noexcept = 0; virtual bool is_key_down(InputKey::Code key) const noexcept = 0; virtual bool is_key_up(InputKey::Code key) const noexcept = 0; virtual bool is_key_pressed(InputKey::Code key) const noexcept = 0; virtual bool is_button_down(InputButton::Code key) const noexcept = 0; virtual bool is_button_up(InputButton::Code key) const noexcept = 0; virtual bool is_button_pressed(InputButton::Code key) const noexcept = 0; virtual void show_cursor(bool show) noexcept = 0; virtual bool is_show_cursor() const noexcept = 0; virtual void lock_cursor(bool lock) noexcept = 0; virtual bool is_locked_cursor() const noexcept = 0; virtual void obtain_mouse_capture() noexcept = 0; virtual void obtain_keyboard_capture() noexcept = 0; virtual void obtain_mouse_capture(InputMousePtr& mouse) noexcept = 0; virtual void obtain_mouse_capture(InputMousePtr&& mouse) noexcept = 0; virtual void obtain_keyboard_capture(InputKeyboardPtr& key) noexcept = 0; virtual void obtain_keyboard_capture(InputKeyboardPtr&& key) noexcept = 0; virtual void obtain_capture() noexcept = 0; virtual void release_mouse_capture() noexcept = 0; virtual void release_keyboard_capture() noexcept = 0; virtual void release_capture() noexcept = 0; virtual void reset() noexcept = 0; virtual void add_input_listener(InputListenerPtr& listener) noexcept = 0; virtual void add_input_listener(InputListenerPtr&& listener) noexcept = 0; virtual void remove_input_listener(InputListenerPtr& listener) noexcept = 0; virtual void remove_input_listener(InputListenerPtr&& listener) noexcept = 0; virtual void clear_input_listener() noexcept = 0; virtual bool send_input_event(const InputEvent& event) noexcept = 0; virtual bool post_input_event(const InputEvent& event) noexcept = 0; virtual void update_begin() noexcept = 0; virtual void update() noexcept = 0; virtual void update_end() noexcept = 0; virtual InputPtr clone() const noexcept = 0; private: IInput(const IInput&) noexcept = delete; IInput& operator=(const IInput&) noexcept = delete; }; } } #endif
3fb824ea836f68ff39ccf4e1cf81aba449859cd3
ea7c02f98b75b39b85019677a38d50a70bfe2de3
/OpenCVLearn/Lesson_01/Lesson_01/Chapter5/Learn_5_5.cpp
ac8085d6135c378c6438ec00596f9d92b21bfd09
[]
no_license
caixindong/New-Guy-In-CV
d0967261695ff434122e0fd60ac35084506bac79
ac125421764f19804d3dc1d679dba88a3199e87a
refs/heads/master
2021-05-09T08:10:01.554589
2018-05-03T11:56:48
2018-05-03T11:56:48
119,381,781
0
0
null
null
null
null
UTF-8
C++
false
false
1,357
cpp
Learn_5_5.cpp
// // Learn_5_5.cpp // Lesson_01 // // Created by 蔡欣东 on 2018/1/4. // Copyright © 2018年 蔡欣东. All rights reserved. // #include "Learn_5_5.hpp" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; static void on_ContrastAndBright(int,void*); int g_nContrastValue; int g_nBrightValue; Mat g_srcImg,g_disImg; void Learn_5_5::learn() { g_srcImg = imread("lena.jpeg"); g_disImg = Mat::zeros(g_srcImg.rows, g_srcImg.cols, g_srcImg.type()); g_nBrightValue = 80; g_nContrastValue = 80; namedWindow("效果",0); createTrackbar("对比度", "效果", &g_nContrastValue, 300, on_ContrastAndBright); // createTrackbar("亮度", "效果", &g_nBrightValue, 200, on_ContrastAndBright); on_ContrastAndBright(g_nContrastValue, 0); on_ContrastAndBright(g_nBrightValue, 0); while (char(waitKey(1)) != 'q') { } } static void on_ContrastAndBright(int,void*) { for (int i = 0; i < g_srcImg.rows; i++) { for (int j = 0; j < g_srcImg.cols; j++) { for (int z = 0; z < 3; z++) { g_disImg.at<Vec3b>(i,j)[z] = saturate_cast<uchar>((g_nContrastValue*0.01)*g_srcImg.at<Vec3b>(i,j)[z] + g_nBrightValue); } } } imshow("效果", g_disImg); }
610fd1cbf641f81ed3f5d52e1dfacf82e98dcaaa
11de28ee69acb540070358405e0b34670addb458
/Ch2/rankSort.cpp
d14026d7fd0435981f574eb8264a367c2e2c51b0
[]
no_license
yz53665/algorithms-C-plus
d94f87910a8f55f4c4b05f70c382b5816447b06b
72670df224474764e92e2aaa6706fb4266ff87a6
refs/heads/master
2023-04-04T21:51:10.967868
2021-04-14T10:36:42
2021-04-14T10:36:42
357,866,238
0
0
null
null
null
null
UTF-8
C++
false
false
2,066
cpp
rankSort.cpp
/* * filename: rankSort.cpp * description: 名次排序相关算法 * author: QRQ */ #include "../common/common.h" #include <algorithm> #include <iostream> template <class T> void rank(T arrayToRank[], const int& arrayLength, int rankToSave[]) { // 计算数组的名次, 名次=更小的数字个数+左侧相同的数字个数 for (int i = 0; i < arrayLength; ++i) { rankToSave[i] = 0; } for (int i = 1; i < arrayLength; ++i) { for (int j = 0; j < i; ++j) { if (arrayToRank[j] <= arrayToRank[i]) { rankToSave[i]++; } else { rankToSave[j]++; } } } } void testForRank(void) { int length = 5; int a[] = {3, 1, 5, 7, 4}; int r[length]; rank(a, length, r); printArray(a, length); std::cout << std::endl; } template <class T> void countSort(T arrayToSort[], const int& length, int rankRecord[]) { // 计数排序, 需要生成一个临时数组作为中转 T *tmpArray = new T [length]; for (int i = 0; i < length ; ++i) { tmpArray[rankRecord[i]] = arrayToSort[i]; } for (int i = 0; i < length ; ++i) { arrayToSort[i] = tmpArray[i]; } delete [] tmpArray; } void testForCountSort(void) { int length = 5; int a[] = {3, 5, 1, 4, 2}; int b[length]; rank(a, length, b); countSort(a, length, b); printArray(a, length); std::cout << std::endl; } template <class T> void inPalceSort(T arrayToSort[], const int& length, T rankRecord[]) { // 计数排序的改进版, 原地排序, 无需额外空间 for (int i = 0; i < length; ++i) { while (rankRecord[i] != i) { int tmpRank = rankRecord[i]; std::swap(arrayToSort[i], arrayToSort[tmpRank]); std::swap(rankRecord[i], rankRecord[tmpRank]); } } } void testForInPlaceSort(void) { int length = 10; int a[] = {3, 5, 4, 7, 1, 2, 9, 6, 8, 0}; int r[length]; rank(a, length, r); inPalceSort(a, length, r); printArray(a, length); std::cout << std::endl; } int main(void) { //testForRank(); // testForCountSort(); testForInPlaceSort(); return 0; }
efd4bb245fe478a567b0424aa4765bc42dda9548
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_1/processor17/15/p
3396a217fea5118cfd6b8a43c0882a5f16b1d07b
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
3,151
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "15"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 36 ( 0.0244557 0.00407174 -0.00312831 0.0360692 0.0376146 0.0963957 0.185266 0.302446 0.457512 0.571226 0.571226 0.457512 0.302446 0.185266 0.0963957 0.0376146 -0.00312831 0.0360692 0.00407173 0.0244557 0.036226 0.0378155 0.0390796 0.0400248 0.0406707 0.0410214 0.0410465 0.0321581 0.0343288 0.036226 0.0378155 0.0390796 0.0400248 0.0406707 0.0410214 0.0410465 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value nonuniform 0(); } cylinder { type zeroGradient; } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary17to14 { type processor; value nonuniform List<scalar> 2(0.0487334 0.0490378); } procBoundary17to15 { type processor; value nonuniform List<scalar> 17 ( 0.0655539 0.107035 0.0655539 0.0489547 0.0492053 0.0494125 0.0495423 0.0495598 0.0494387 0.0486779 0.0487334 0.0489547 0.0492052 0.0494125 0.0495423 0.0495598 0.0494387 ) ; } procBoundary17to16 { type processor; value nonuniform List<scalar> 33 ( 0.02996 0.0311553 0.0646175 0.0774813 0.0646175 0.0774813 0.13164 0.13164 0.203193 0.203193 0.308213 0.414077 0.414077 0.515522 0.668832 0.668832 0.515522 0.414077 0.414077 0.308213 0.203193 0.203193 0.13164 0.13164 0.0774813 0.0774813 0.107035 0.0646175 0.0646175 0.0311553 0.02996 0.0343288 0.0302325 ) ; } procBoundary17to18 { type processor; value nonuniform List<scalar> 30 ( -0.0534533 0.00547524 -0.0793345 -0.0321716 -0.0321716 -0.0527564 -0.0527564 -0.00819905 -0.00819905 0.0672619 0.0672619 0.201603 0.332561 0.332561 0.332561 0.332561 0.201602 0.0672619 0.0672619 -0.00819906 -0.00819906 -0.0527564 -0.0527564 -0.0793346 -0.0321716 -0.0321716 -0.0534533 0.00547523 0.0239356 0.0157192 ) ; } procBoundary17to19 { type processor; value nonuniform List<scalar> 16 ( -0.0150774 -0.0150774 0.0268008 0.0290136 0.0306575 0.0318003 0.0324835 0.0326742 0.0203152 0.0239356 0.0268008 0.0290136 0.0306575 0.0318003 0.0324834 0.0326742 ) ; } } // ************************************************************************* //
e108d72e4b233e9fab3d9e952685f5df9d53dc25
0574237636f4d9ee0099f77c79adf182ce69419d
/UVA/Huge Easy Contest 1/M - Crazy King.cpp
0cff24fd914712065e3b0bd94d099959742e16f6
[]
no_license
andreicoman11/code
77359bccd7cc451d6db5edbfea9b2bf81f44250f
c0e318e7c7e192f1d90e82e2468344b6a27a310f
refs/heads/master
2020-05-27T05:08:22.332100
2014-12-19T01:39:41
2014-12-19T01:39:41
28,082,193
4
0
null
null
null
null
UTF-8
C++
false
false
2,333
cpp
M - Crazy King.cpp
#include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <cstring> #include <cstdlib> #include <string> #include <vector> #include <algorithm> #include <cmath> #include <queue> #include <list> #include <set> #include <map> using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; #define pb push_back #define sz size() #define SORT(x) sort(x.begin(), x.end()) #define REVERSE(x) reverse(x.begin(), x.end()) #define REP(x, hi) for (int x=0; x<(hi); x++) #define FOR(x, lo, hi) for (int x=(lo); x<(hi); x++) char g[100][100]; int d[100][100]; int n, m; int hx[] = {-2, -2, -1, -1, 1, 1, 2, 2}; int hy[] = {-1, 1, -2, 2, -2, 2, -1, 1}; int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1}; void horsy(int x, int y) { REP(k, 8) { int x2 = x+hx[k]; int y2 = y+hy[k]; if( x2>=0 && y2>=0 && x2<n && y2<m && g[x2][y2]=='.' ) g[x2][y2] = 'H'; } } void printstuff() { REP(i, n) { REP(j, m) cout << g[i][j]; cout << endl; } cout << endl; REP(i, n) { REP(j, m) cout << d[i][j] << " "; cout << endl; } cout << endl; //system("pause"); } int main() { int runs; cin >> runs; for(int r = 1; r<=runs; r++) { cin >> n >> m; REP(i, n) scanf("%s", g[i]); int kx, ky, bx, by; REP(i,n) REP(j,m) if( g[i][j]=='Z' ) horsy(i, j); else if( g[i][j]=='A' ) { kx = i; ky = j; } else if( g[i][j]=='B' ) { bx = i; by = j; } memset(d, 0, sizeof(d)); queue<pair<int,int> > q; q.push( pair<int,int>(kx, ky) ); d[kx][ky] = 1; bool b = 0; while( !q.empty() && !b ) { int x = q.front().first; int y = q.front().second; q.pop(); for(int k=0; k<8; k++) { int x2 = x + dx[k]; int y2 = y + dy[k]; if( x2>=0 && y2>=0 && x2<n && y2<m && g[x2][y2]!='Z' && g[x2][y2]!='H' && d[x2][y2]==0 ) { d[x2][y2] = d[x][y] + 1; q.push( pair<int,int>(x2,y2) ); if( x2==bx && y2==by ) b = 1; } } } //printstuff(); if( b ) cout << "Minimal possible length of a trip is " << d[bx][by]-1 << endl; else cout << "King Peter, you can't go now!\n"; } return 0; }
225545b9ec95be5667bb64167ed363854309e29d
32bfbd6a6e424de779a9ea715a43c702fdb749f4
/Final Project Smoke/SmokeSim/SmokeSim/SourceCode/blurfilter.cpp
91ef202700cacdb0823fa8383ff6cad405ed927a
[ "Zlib" ]
permissive
shijingliu/CIS-563-Target-Driven-Smoke-Simulation
c44dd907c66b87d70f04b2e4f646edd4dc542460
84096986d0f1e0463e8b508f7d3f3c155e6cbe51
refs/heads/master
2020-05-31T10:21:43.700834
2014-06-14T22:41:50
2014-06-14T22:41:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,724
cpp
blurfilter.cpp
#include "blurfilter.h" #include "mac_grid.h" #include "constants.h" #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif BlurFilter::BlurFilter() : mCenter(0) { } void BlurFilter::SetSigma(double sigma) { assert(sigma > 0.0); int kernelSize = (int) (40 * sigma) * 2 + 1; mCenter = kernelSize / 2; mKernel.resize(kernelSize); double normFactor = 1.0 / (sqrt(2.0 * M_PI) * sigma); for(int i=0; i < kernelSize; ++i) { int x = i - mCenter; mKernel[i] = normFactor * exp(-x * x / (2.0 * sigma * sigma)); } } void BlurFilter::GaussianBlur(const GridData &src, GridData &dst) { // dst = src; //assert(src.NumRows() == dst.NumRows()); //assert(src.NumCols() == dst.NumCols()); //mTemp.Resize(src.NumRows(), src.NumCols()); //Smooth horizontally for(int j = 0; j < theDim[MACGrid::X]+2; j++) //1)think about the limit here, it could be wrong; 2)also don't know if z is the axis we want to ignore. { for(int i = 0; i < theDim[MACGrid::Y]+2; i++) { double newValue = 0.0; for(int cc = -mCenter; cc <= mCenter; ++cc) { if((((int)i + cc) >= 0) && (((int)i + cc) < theDim[MACGrid::Y] +2)) { newValue += src (i+cc, j, 1)*mKernel[mCenter+cc]; } } mTemp(i, j, 1) = newValue; } } // Smooth vertically. for(int i=0; i < theDim[MACGrid::Y] + 2; ++i) { for(int j=0; j < theDim[MACGrid::X] + 2; ++j) { double newValue = 0.0; for(int rr = -mCenter; rr <= mCenter; ++rr) { if((((int)j + rr)>= 0) && (((int) j + rr) < theDim[MACGrid::X]+2)) { newValue += mTemp(i, j+rr, 1) * mKernel[mCenter + rr]; } } dst(i, j, 1) = newValue + 1e-256; } } }
e8230d469e68e0d6e7dd25b61c577b4e3ee762bf
1ed1ed934e4175bb20024311a007d60ae784b046
/SN/SN.cpp
a5470e443f972c54a2b5f7bc6e041f792f2b9ff1
[]
no_license
kkkcoder/Code_in_thptchuyen.ntucoder.net
f568cddc01b641c9a6a3c033a4b48ca59bb6435e
c4c0e19ea56a6560014cbb6e4d7489fb16e8aad7
refs/heads/master
2023-07-16T16:15:39.421817
2021-08-29T15:56:35
2021-08-29T15:56:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
SN.cpp
#include <bits/stdc++.h> #define ll long long #define fo(i, a, b) for (long long i = a; i <= b; i++) #define nmax 1000005 #define fi first #define se second #define ii pair<int, int> const ll mod = 1e9 + 7; using namespace std; ll x, dem = 0, n, a[nmax], z = 0, b[nmax]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("SN.inp", "r", stdin); freopen("SN.out", "w", stdout); #endif // ONLINE_JUDGE cin >> n; fo(i, 1, n) cin >> a[i]; sort(a + 1, a + n + 1); fo(i, 1, n) { if (a[i] != a[i + 1]) { b[++z] = a[i]; } } //fo(i, 1, z) cout << b[i] << ' '; ll s = 1, t = 1; while (t <= (z + 1)) { if (b[t] == s) { t++; s++; } else { cout << s; return 0; } } }