blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
72c04a84ce12c94208252dd9240cee64cac8c533
8a100a50efe9df71962b2552bd9b75300958b1fe
/Receivers/RCX/Software/RCX_Mini/USER/RCX/RCX_Type.h
04c21d9711c6aefb76219287860b9ab3f66094b4
[ "MIT" ]
permissive
yu1741588584/X-CTRL
156d608a02a9953de3a92e1d0a0abc62ece74350
9d93a49688fd8526253c9c9119479d04fab8371b
refs/heads/master
2022-12-27T22:29:31.691813
2022-04-30T03:49:20
2022-04-30T03:49:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
771
h
#ifndef __RCX_TYPE_H #define __RCX_TYPE_H #include "stdint.h" #include "RCX_Config.h" #if( RCX_CHANNEL_NUM <= 0 || RCX_CHANNEL_NUM > 12 ) # error "RCX_CHANNEL_NUM must >0 and <= 12" #endif namespace RCX { /*强制单字节对齐*/ #pragma pack (1) /*通用通信格式 (32 Bytes)*/ typedef struct { /*数据包头 3 Bytes*/ struct { uint8_t ObjectType; uint8_t ObjectID; uint8_t HeartBeat; } Head; /*按键 1 Byte*/ uint8_t Key; /*通道 RCX_CHANNEL_NUM * 2 Bytes*/ int16_t Channel[RCX_CHANNEL_NUM]; /*用户数据*/ uint8_t UserData[27 - (RCX_CHANNEL_NUM * sizeof(uint16_t))]; /*CRC校验码 1 Byte*/ uint8_t CRC8; } PackCommon_t; #pragma pack () }/*end of namespace RCX*/ #endif
28372657de6417945664ee7d8fc8de56b405ed9a
202b1b82a2b7a70250415ba5d9bd1f6b277a6e84
/src/test/coins_tests.cpp
ddc4809f7abd0f00a639dff218241d009ed59dbe
[ "MIT" ]
permissive
cmkcoin/cmkcore
92cc4dcaf63b1d282ea2c2aa15ede822c9c7b0e7
5c2a3222ef901d1c6d9315177ba79e3f5094f2a6
refs/heads/master
2020-03-15T04:26:42.979962
2019-10-19T03:55:45
2019-10-19T03:55:45
131,965,565
1
0
null
null
null
null
UTF-8
C++
false
false
13,156
cpp
// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coins.h" #include "random.h" #include "uint256.h" #include "test/test_cmk.h" #include "main.h" #include "consensus/validation.h" #include <vector> #include <map> #include <boost/test/unit_test.hpp> namespace { class CCoinsViewTest : public CCoinsView { uint256 hashBestBlock_; std::map<uint256, CCoins> map_; public: bool GetCoins(const uint256& txid, CCoins& coins) const { std::map<uint256, CCoins>::const_iterator it = map_.find(txid); if (it == map_.end()) { return false; } coins = it->second; if (coins.IsPruned() && insecure_rand() % 2 == 0) { // Randomly return false in case of an empty entry. return false; } return true; } bool HaveCoins(const uint256& txid) const { CCoins coins; return GetCoins(txid, coins); } uint256 GetBestBlock() const { return hashBestBlock_; } bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Same optimization used in CCoinsViewDB is to only write dirty entries. map_[it->first] = it->second.coins; if (it->second.coins.IsPruned() && insecure_rand() % 3 == 0) { // Randomly delete empty entries on write. map_.erase(it->first); } } mapCoins.erase(it++); } if (!hashBlock.IsNull()) hashBestBlock_ = hashBlock; return true; } bool GetStats(CCoinsStats& stats) const { return false; } }; class CCoinsViewCacheTest : public CCoinsViewCache { public: CCoinsViewCacheTest(CCoinsView* base) : CCoinsViewCache(base) {} void SelfTest() const { // Manually recompute the dynamic usage of the whole data, and compare it. size_t ret = memusage::DynamicUsage(cacheCoins); for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) { ret += it->second.coins.DynamicMemoryUsage(); } BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret); } }; } BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup) static const unsigned int NUM_SIMULATION_ITERATIONS = 40000; // This is a large randomized insert/remove simulation test on a variable-size // stack of caches on top of CCoinsViewTest. // // It will randomly create/update/delete CCoins entries to a tip of caches, with // txids picked from a limited list of random 256-bit hashes. Occasionally, a // new tip is added to the stack of caches, or the tip is flushed and removed. // // During the process, booleans are kept to make sure that the randomized // operation hits all branches. BOOST_AUTO_TEST_CASE(coins_cache_simulation_test) { // Various coverage trackers. bool removed_all_caches = false; bool reached_4_caches = false; bool added_an_entry = false; bool removed_an_entry = false; bool updated_an_entry = false; bool found_an_entry = false; bool missed_an_entry = false; // A simple map to track what we expect the cache stack to represent. std::map<uint256, CCoins> result; // The cache stack. CCoinsViewTest base; // A CCoinsViewTest at the bottom. std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top. stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache. // Use a limited set of random transaction ids, so we do test overwriting entries. std::vector<uint256> txids; txids.resize(NUM_SIMULATION_ITERATIONS / 8); for (unsigned int i = 0; i < txids.size(); i++) { txids[i] = GetRandHash(); } for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) { // Do a random modification. { uint256 txid = txids[insecure_rand() % txids.size()]; // txid we're going to modify in this iteration. CCoins& coins = result[txid]; CCoinsModifier entry = stack.back()->ModifyCoins(txid); BOOST_CHECK(coins == *entry); if (insecure_rand() % 5 == 0 || coins.IsPruned()) { if (coins.IsPruned()) { added_an_entry = true; } else { updated_an_entry = true; } coins.nVersion = insecure_rand(); coins.vout.resize(1); coins.vout[0].nValue = insecure_rand(); *entry = coins; } else { coins.Clear(); entry->Clear(); removed_an_entry = true; } } // Once every 1000 iterations and at the end, verify the full cache. if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) { for (std::map<uint256, CCoins>::iterator it = result.begin(); it != result.end(); it++) { const CCoins* coins = stack.back()->AccessCoins(it->first); if (coins) { BOOST_CHECK(*coins == it->second); found_an_entry = true; } else { BOOST_CHECK(it->second.IsPruned()); missed_an_entry = true; } } BOOST_FOREACH(const CCoinsViewCacheTest *test, stack) { test->SelfTest(); } } if (insecure_rand() % 100 == 0) { // Every 100 iterations, flush an intermediate cache if (stack.size() > 1 && insecure_rand() % 2 == 0) { unsigned int flushIndex = insecure_rand() % (stack.size() - 1); stack[flushIndex]->Flush(); } } if (insecure_rand() % 100 == 0) { // Every 100 iterations, change the cache stack. if (stack.size() > 0 && insecure_rand() % 2 == 0) { //Remove the top cache stack.back()->Flush(); delete stack.back(); stack.pop_back(); } if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) { //Add a new cache CCoinsView* tip = &base; if (stack.size() > 0) { tip = stack.back(); } else { removed_all_caches = true; } stack.push_back(new CCoinsViewCacheTest(tip)); if (stack.size() == 4) { reached_4_caches = true; } } } } // Clean up the stack. while (stack.size() > 0) { delete stack.back(); stack.pop_back(); } // Verify coverage. BOOST_CHECK(removed_all_caches); BOOST_CHECK(reached_4_caches); BOOST_CHECK(added_an_entry); BOOST_CHECK(removed_an_entry); BOOST_CHECK(updated_an_entry); BOOST_CHECK(found_an_entry); BOOST_CHECK(missed_an_entry); } // This test is similar to the previous test // except the emphasis is on testing the functionality of UpdateCoins // random txs are created and UpdateCoins is used to update the cache stack // In particular it is tested that spending a duplicate coinbase tx // has the expected effect (the other duplicate is overwitten at all cache levels) BOOST_AUTO_TEST_CASE(updatecoins_simulation_test) { bool spent_a_duplicate_coinbase = false; // A simple map to track what we expect the cache stack to represent. std::map<uint256, CCoins> result; // The cache stack. CCoinsViewTest base; // A CCoinsViewTest at the bottom. std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top. stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache. // Track the txids we've used and whether they have been spent or not std::map<uint256, CAmount> coinbaseids; std::set<uint256> alltxids; std::set<uint256> duplicateids; for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) { { CMutableTransaction tx; tx.vin.resize(1); tx.vout.resize(1); tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate unsigned int height = insecure_rand(); // 1/10 times create a coinbase if (insecure_rand() % 10 == 0 || coinbaseids.size() < 10) { // 1/100 times create a duplicate coinbase if (insecure_rand() % 10 == 0 && coinbaseids.size()) { std::map<uint256, CAmount>::iterator coinbaseIt = coinbaseids.lower_bound(GetRandHash()); if (coinbaseIt == coinbaseids.end()) { coinbaseIt = coinbaseids.begin(); } //Use same random value to have same hash and be a true duplicate tx.vout[0].nValue = coinbaseIt->second; assert(tx.GetHash() == coinbaseIt->first); duplicateids.insert(coinbaseIt->first); } else { coinbaseids[tx.GetHash()] = tx.vout[0].nValue; } assert(CTransaction(tx).IsCoinBase()); } // 9/10 times create a regular tx else { uint256 prevouthash; // equally likely to spend coinbase or non coinbase std::set<uint256>::iterator txIt = alltxids.lower_bound(GetRandHash()); if (txIt == alltxids.end()) { txIt = alltxids.begin(); } prevouthash = *txIt; // Construct the tx to spend the coins of prevouthash tx.vin[0].prevout.hash = prevouthash; tx.vin[0].prevout.n = 0; // Update the expected result of prevouthash to know these coins are spent CCoins& oldcoins = result[prevouthash]; oldcoins.Clear(); // It is of particular importance here that once we spend a coinbase tx hash // it is no longer available to be duplicated (or spent again) // BIP 34 in conjunction with enforcing BIP 30 (at least until BIP 34 was active) // results in the fact that no coinbases were duplicated after they were already spent alltxids.erase(prevouthash); coinbaseids.erase(prevouthash); // The test is designed to ensure spending a duplicate coinbase will work properly // if that ever happens and not resurrect the previously overwritten coinbase if (duplicateids.count(prevouthash)) spent_a_duplicate_coinbase = true; assert(!CTransaction(tx).IsCoinBase()); } // Track this tx to possibly spend later alltxids.insert(tx.GetHash()); // Update the expected result to know about the new output coins CCoins &coins = result[tx.GetHash()]; coins.FromTx(tx, height); CValidationState dummy; UpdateCoins(tx, dummy, *(stack.back()), height); } // Once every 1000 iterations and at the end, verify the full cache. if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) { for (std::map<uint256, CCoins>::iterator it = result.begin(); it != result.end(); it++) { const CCoins* coins = stack.back()->AccessCoins(it->first); if (coins) { BOOST_CHECK(*coins == it->second); } else { BOOST_CHECK(it->second.IsPruned()); } } } if (insecure_rand() % 100 == 0) { // Every 100 iterations, flush an intermediate cache if (stack.size() > 1 && insecure_rand() % 2 == 0) { unsigned int flushIndex = insecure_rand() % (stack.size() - 1); stack[flushIndex]->Flush(); } } if (insecure_rand() % 100 == 0) { // Every 100 iterations, change the cache stack. if (stack.size() > 0 && insecure_rand() % 2 == 0) { stack.back()->Flush(); delete stack.back(); stack.pop_back(); } if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) { CCoinsView* tip = &base; if (stack.size() > 0) { tip = stack.back(); } stack.push_back(new CCoinsViewCacheTest(tip)); } } } // Clean up the stack. while (stack.size() > 0) { delete stack.back(); stack.pop_back(); } // Verify coverage. BOOST_CHECK(spent_a_duplicate_coinbase); } BOOST_AUTO_TEST_SUITE_END()
efdd9382602a1a3aa8ba1d2ee25e785738ddbfe3
95aa7ee0ad1a6425002b5643061e800de1a52c8a
/Graphic/Window/Keyboard.cpp
08892839d6cf0b8bbef969d35a05ece508a6c13c
[ "MIT" ]
permissive
denesik/Sandbox
8131783a509cedbd05b0c13f92867cb88833a08c
2c7b88950d36775818205113522173b96ce32290
refs/heads/master
2021-01-13T00:15:15.502903
2015-09-04T12:40:56
2015-09-04T12:40:56
40,732,720
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
cpp
// ============================================================================ // == Copyright (c) 2015, Smirnov Denis == // == See license.txt for more information == // ============================================================================ #include "Keyboard.h" #include <GLFW\glfw3.h> Keyboard::Keyboard() : mKeyState(GLFW_KEY_LAST + 1, GLFW_RELEASE) { } Keyboard::~Keyboard() { } void Keyboard::SetKey(int key, int , int action, int ) { if(key == GLFW_KEY_UNKNOWN) { //printf("glfw unknown key\n"); return; } mKeyState[key] = action; } bool Keyboard::IsKeyPress(int key) { if(mKeyState[key] == GLFW_PRESS) { mKeyState[key] = GLFW_REPEAT; return true; } return false; } bool Keyboard::IsKeyUp(int key) { if(mKeyState[key] == GLFW_RELEASE) return true; return false; } bool Keyboard::IsKeyDown(int key) { if(mKeyState[key] == GLFW_REPEAT || mKeyState[key] == GLFW_PRESS) return true; return false; }
bc2cfe34397e3fbbbd45d629904d28d4f5416774
e5422975481b1283b4a8a5207c2ff9a5e0d73ff1
/dlls/projectiles/proj_frostball.cpp
6287e8555fe5447270ff65e174d656661be1159a
[]
no_license
mittorn/hlwe_src
ae6ebd30c3dc2965f501b7e5ee460a7c7de58892
7abbe2ab834d636af4224a0bd0c192c958242b49
refs/heads/master
2021-01-13T16:30:25.223519
2015-12-01T19:07:15
2015-12-01T19:07:15
47,205,047
2
1
null
null
null
null
UTF-8
C++
false
false
3,143
cpp
#include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "weapons.h" #include "nodes.h" #include "soundent.h" #include "decals.h" #include "game.h" #include "projectiles.h" LINK_ENTITY_TO_CLASS( frostball, CFrostball ); void CFrostball::Killed (entvars_t *pevAttacker, int iGib) { FX_Trail( pev->origin, entindex(), PROJ_REMOVE ); UTIL_Remove( this ); } void CFrostball::ExplodeTouch( CBaseEntity *pOther ) { if ( UTIL_PointContents(pev->origin) == CONTENT_SKY ) { FX_Trail( pev->origin, entindex(), PROJ_REMOVE ); UTIL_Remove( this ); return; } if ( UTIL_PointContents(pev->origin) == CONTENT_WATER ) { entvars_t *pevOwner = VARS( pev->owner ); FX_Trail( pev->origin, entindex(), PROJ_ICE_DETONATE_WATER ); ::RadiusDamage( pev->origin, pev, pevOwner, pev->dmg/2, pev->dmg, CLASS_NONE, DMG_FREEZE ); UTIL_Remove( this ); return; } TraceResult tr; Vector vecSpot = pev->origin - pev->velocity.Normalize() * 32; UTIL_TraceLine( vecSpot, vecSpot + pev->velocity.Normalize() * 64, ignore_monsters, ENT(pev), &tr ); entvars_t *pevOwner = VARS( pev->owner ); ::RadiusDamage( pev->origin, pev, pevOwner, pev->dmg, pev->dmg*2.5, CLASS_NONE, DMG_FREEZE); UTIL_DecalTrace(&tr, DECAL_FROST_SCORCH1 + RANDOM_LONG(0,1)); FX_Trail( tr.vecEndPos + (tr.vecPlaneNormal * 12), entindex(), PROJ_ICE_DETONATE ); UTIL_Remove( this ); } void CFrostball:: Spawn( void ) { pev->movetype = MOVETYPE_FLY; pev->classname = MAKE_STRING( "frostball" ); pev->solid = SOLID_BBOX; SET_MODEL(ENT(pev), "sprites/anim_spr11.spr"); pev->rendermode = kRenderTransAdd; pev->renderamt = 255; UTIL_SetSize(pev, g_vecZero, g_vecZero ); pev->frame = 0; m_maxFrame = (float)MODEL_FRAMES(pev->modelindex)-1; } CFrostball *CFrostball::ShootFrostball( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity ) { CFrostball *pFrostball = GetClassPtr( (CFrostball *)NULL ); pFrostball->Spawn(); UTIL_SetOrigin( pFrostball->pev, vecStart ); pFrostball->pev->velocity = vecVelocity + gpGlobals->v_right * RANDOM_FLOAT(-50,50) + gpGlobals->v_up * RANDOM_FLOAT(-50,50); pFrostball->pev->angles = UTIL_VecToAngles(pFrostball->pev->velocity); pFrostball->pev->owner = ENT(pevOwner); pFrostball->SetTouch( ExplodeTouch ); pFrostball->pev->dmg = dmg_froster.value * (mp_wpn_power.value/100); pFrostball->SetThink ( Fly ); pFrostball->pev->nextthink = 0.1; FX_Trail(pFrostball->pev->origin, pFrostball->entindex(), PROJ_ICE ); return pFrostball; } void CFrostball::Fly( void ) { if ( UTIL_PointContents(pev->origin) == CONTENT_WATER ) { entvars_t *pevOwner = VARS( pev->owner ); FX_Trail( pev->origin, entindex(), PROJ_ICE_DETONATE_WATER ); ::RadiusDamage( pev->origin, pev, pevOwner, pev->dmg/2, pev->dmg, CLASS_NONE, DMG_FREEZE ); UTIL_Remove( this ); return; } if ( gpGlobals->time >= pev->framerate ) { if ( pev->frame++ ) { if ( pev->frame > m_maxFrame ) { pev->frame = 0; } } pev->framerate = gpGlobals->time + 0.03; } pev->nextthink = gpGlobals->time + 0.001; }
a527ecda263e0da28bd762e38df0b12375852d4d
4c5dfb3a58a0d61ec35a9109391ff9f29372e25c
/LeetCode/Symmetric_Tree.cpp
01aee522232ca91eadf3c098a22e852ce0895711
[]
no_license
bingbingzhenbang/LeetCode_Answers
2f9ed861e1b492198417fb90fca694ef09592d6d
2dee09505a8e942c4c08e285c8ac589894e504f5
refs/heads/master
2021-06-12T04:29:32.770480
2021-05-16T12:54:53
2021-05-16T12:54:53
65,536,300
5
2
null
null
null
null
UTF-8
C++
false
false
906
cpp
//Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). // // For example, this binary tree is symmetric: //1 // / \ // 2 2 // / \ / \ // 3 4 4 3 // // // // But the following is not: // //1 // / \ // 2 2 // \ \ // 3 3 // // // //Note: //Bonus points if you could solve it both recursively and iteratively. // #include "TreeNode.h" #include <cstdlib> bool isSubTreeSymmetric(struct TreeNode *p, struct TreeNode *q) { if (p == NULL && q == NULL) return true; else if (p != NULL && q != NULL && p->val == q->val) { if (isSubTreeSymmetric(p->left, q->right)) return isSubTreeSymmetric(p->right, q->left); else return false; } else return false; } bool isSymmetric(struct TreeNode* root) { if (root == NULL) return true; else return isSubTreeSymmetric(root->left, root->right); }
[ "bingbingbang@d554a37f-8442-4457-bea9-5f25c8c5069a" ]
bingbingbang@d554a37f-8442-4457-bea9-5f25c8c5069a
dcf7074a1bc854da1762032e3c879201554bd770
958264cf771e25bbd62734665d316b0135aa1dd0
/Assignment 7/Assignment 7/probe.cpp
6a7e408279acf4689d3408805748a7c7182ae5f6
[]
no_license
chom125/UW-Certification-C-C-Intro-Class
4907bc507d1366bb154e0fa9133d17f1de2a6d3e
affa848a956d5081653f9e93e8d1694294a400c5
refs/heads/master
2021-01-18T16:12:25.796698
2013-12-19T04:31:20
2013-12-19T04:31:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
cpp
// // probe.cpp // Assignment 7 // // Created by Steve Minor on 11/23/13. // Copyright (c) 2013 Steve Minor. All rights reserved. // #include "probe.h" void Probe::increment(){ total++; current++; } void Probe::decrement(){ current--; } //probe can't have static member data //Probe::Probe(){ // //increment(); //} // //Probe::Probe(Probe& p){ // increment(); //} // //Probe::~Probe(){ // //decrement(); //} // keep for demonstrative purposes but do not use void Probe::operator++(int i){ increment(); } // keep for demonstrative purposes but do not use void Probe::operator++(){ ++total; ++current; } // keep for demonstrative purposes but do not use void Probe::operator--(int i){ decrement(); } unsigned int Probe::getTotal(){ return total; } unsigned int Probe::getCurrent(){ return current; } std::ostream& operator<<(std::ostream& os, Probe& p){ std::cout << "total instances: " << p.getTotal() << std::endl; std::cout << "current instances: " << p.getCurrent() << std::endl; return os; };
61bb639a6cd30cb1f9e8e818477ce6b37bb2eee4
57d1d62e1a10282e8d4faa42e937c486102ebf04
/judges/uva/done/12653.cpp
045787047cdc706931af69cb993478be6af182ca
[]
no_license
diegoximenes/icpc
91a32a599824241247a8cc57a2618563f433d6ea
8c7ee69cc4a1f3514dddc0e7ae37e9fba0be8401
refs/heads/master
2022-10-12T11:47:10.706794
2022-09-24T04:03:31
2022-09-24T04:03:31
178,573,955
0
0
null
null
null
null
UTF-8
C++
false
false
911
cpp
#include<cstdio> #include<cstring> using namespace std; typedef unsigned long long ull; #define MAX 2 #define MOD 1000000 void mulMatrix(ull a[MAX][MAX], ull b[MAX][MAX], ull c[MAX][MAX], int n) { ull k; for(int i=0; i<n; ++i) for(int j=0; j<n; ++j) for(c[i][j] = k = 0; k<(ull)n; ++k) c[i][j] = (c[i][j] + (a[i][k]*b[k][j])%MOD)%MOD; } void powMatrix(ull b[MAX][MAX], ull r[MAX][MAX], int n, ull e) { ull temp[MAX][MAX]; for(int i=0; i<n; ++i) for(int j=0; j<n; ++j) r[i][j] = (i == j); if(!e) return; powMatrix(b, temp, n, e/2); mulMatrix(temp, temp, r, n); if(e%2 != 0) { mulMatrix(b, r, temp, n); memcpy(r, temp, sizeof(temp)); } } int main() { ull n, k, l; while(scanf("%lld %lld %lld", &n, &k, &l) == 3) { ull m[2][2] = {{k%MOD, l%MOD}, {1, 0}}, r[2][2]; powMatrix(m, r, 2, n/5 - 1); printf("%06lld\n", ((r[0][0]*(k%MOD))%MOD + r[0][1])%MOD); } return 0; }
1d354d916555e103fbb0c37a9439c7a500098043
1e73e280d1af2a77a3bece88f46e753aebd30e34
/engine/code/headers/ModuleCreation.hpp
9f7257fc609a26cd4f9ff4340613b2c5ba8722bd
[]
no_license
ricky395/LilEngine
3ac5a545ae1cf4f7d7038fe3f89f4b0ded553924
8dad9f8be50f68bb8dbc89e6668ce0c5bea39dc1
refs/heads/master
2023-04-25T15:52:25.567358
2021-05-06T16:02:46
2021-05-06T16:02:46
364,956,125
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,229
hpp
/// Author: Ricardo Roldán Fernández /// Date: 26/06/2018 #ifndef MODULE_CREATION_HEADER #define MODULE_CREATION_HEADER #include <map> #include <string> #include <memory> #include "Module.hpp" using namespace std; /// Factoría de creación de módulos class ModuleCreation { private: typedef shared_ptr< Module >(*Module_Factory) (Scene *); /// Módulos existentes std::map< string, Module_Factory > modules; /// Referencia a la propia clase static ModuleCreation * instance; private: /// Constructor ModuleCreation(); /// Constructor ModuleCreation(const ModuleCreation &) { } ModuleCreation & operator = (const ModuleCreation &) { return *this; } public: /// Destructor ~ModuleCreation() { modules.clear(); } /// Devuelve la instancia a la clase static ModuleCreation * Instance() { if (!instance) { instance = new ModuleCreation; } return instance; } /// Almacena un nuevo módulo /// param name nombre del módulo /// param factory callback del módulo void reg(const string & name, Module_Factory factory) { modules[name] = factory; } /// Crea un nuevo módulo shared_ptr<Module> createModule(const string & name, Scene * scene); }; #endif
e008f6b65913ecf6435063340c190470d17501e5
8612749e97784c5544276d3152b0a326b0ed7501
/gl/scene/scene.hpp
53457794a8ce391118b9df824a69ce754cff616c
[]
no_license
VladislavKhudziakov/-gl_sandbox
7aeabcb66508cbe5242e10cd2fc86f1c6597081d
2d6fef3533fab6e1302ce4b556a5385640e8fd86
refs/heads/master
2021-02-10T14:35:40.325726
2020-07-05T18:31:17
2020-07-05T18:31:17
244,390,375
0
0
null
null
null
null
UTF-8
C++
false
false
1,759
hpp
#pragma once #include <gl/scene/meshes.hpp> #include <gl/framebuffer_object.hpp> #include <gl/scene/attachment.hpp> #include <gl/scene/framebuffer.hpp> #include <gl/scene/pass.hpp> #include <gl/scene/parameter.hpp> #include <vector> namespace gl::scene { struct drawable { enum class topology { points, lines, line_loop, line_strip, triangles, triangle_strip, triangle_fan, lines_adj = 0x000A, triangles_adj = 0x000C }; uint32_t mesh_idx = -1; uint32_t material_idx = -1; drawable::topology topo = drawable::topology::triangles; }; struct render_command { enum class type { pass, draw, blit }; render_command::type type; uint32_t source_index; uint32_t dst_index; }; struct scene { std::vector<gl::scene::mesh> meshes; std::vector<gl::scene::material> materials; std::vector<gl::scene::drawable> drawables; std::vector<gl::scene::attachment> attachments; std::vector<gl::scene::framebuffer> framebuffers; std::vector<gl::scene::pass> passes; std::vector<gl::scene::texture> textures; std::vector<gl::scene::parameter> parameters; std::vector<gl::scene::render_command> commands; std::vector<gl::framebuffer_object> fbos; std::vector<gl::program> shaders; std::vector<gl::vertex_array_object> vertex_sources; }; void draw(const scene& s, const std::vector<uint32_t>&, uint32_t pass_idx); void draw(const scene& s, uint32_t surface_width, uint32_t surface_height); } // namespace gl::scene
[ "Vladislav Khudiakov" ]
Vladislav Khudiakov
6e07113dec2e28ac011db4016310956a95f471a5
9c33d3c86c6662efb51d5aa7ee8a2290cc8f99c9
/ESEmu Server - d3v/ConfManager/ConfigReader.h
b0e2db2d45b0d300f1d2843c38b82ed49ef3b983
[]
no_license
Project-ElChase/ESEmu-LUA
ab198c7d3e3141bcad547a9e1c4d7b54cb26bb47
f81a713bd5e19b5206428ee10f9a96e5812266ac
refs/heads/master
2020-08-21T09:30:20.091897
2017-03-05T01:01:21
2017-03-05T01:01:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,583
h
#pragma once extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } #include <string> #include <stdint.h> #pragma comment (lib, "lua52.lib") class ConfigManager { public: ConfigManager(); ~ConfigManager(); enum boolean_config_t { TEST_SERVER, LAST_BOOLEAN_CONFIG }; enum string_config_t { LICENSE_FILE, HS_CERTIFICATE, DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE, CLIENT_VERSION, SERVER_NAME, SERVER_IP, LAST_STRING_CONFIG }; enum integer_config_t { SERVER_CHANNELS, SERVER_LOGINS, SERVER_TYPE, SERVER_PORT, DB_PORT, MAX_CLIENTS, WORKER_THREADS, PRIORITY_LOW_BELOW, PRIORITY_LOW_ABOVE, PRIORITY_MEDIUM_BELOW, PRIORITY_MEDIUM_ABOVE, PRIORITY_HIGH_BELOW, PRIORITY_HIGH_ABOVE, PRIORITY_CRITICAL_BELOW, PRIORITY_CRITICAL_ABOVE, MAX_PINCODE_TRIALS, THREAD_MEMORY, LAST_INTEGER_CONFIG }; bool load(short Type); const std::string& getString(string_config_t _what) const; int32_t getNumber(integer_config_t _what) const; bool getBoolean(boolean_config_t _what) const; private: static std::string getGlobalString(lua_State* _L, const std::string& _identifier, const std::string& _default = ""); static int32_t getGlobalNumber(lua_State* _L, const std::string& _identifier, const int32_t _default = 0); static std::string getGlobalStringField(lua_State* _L, const std::string& _identifier, const int32_t _key, const std::string& _default = ""); bool m_isLoaded; std::string StringCFG[LAST_STRING_CONFIG]; int32_t IntegerCFG[LAST_INTEGER_CONFIG]; bool BoolCFG[LAST_BOOLEAN_CONFIG]; };
539b29116f5ca746df44ca4d86c22efd6f21d33d
fef6f2ff53c92f0444d48175d24494a2714034e2
/src/fe/subsystems/collision/bounds/circle.cpp
bfebdb518898e40d3772873fbaa7aa9ecb6021ae
[ "MIT" ]
permissive
TheCandianVendingMachine/TCVM_Flat_Engine
8c4dd5ef830e0a74e59e8a1ca53b920fd2d4b55a
13797b91f6f4199d569f80baa29e2584652fc4b5
refs/heads/master
2021-04-06T13:19:58.563508
2019-01-29T05:22:42
2019-01-29T05:22:42
83,399,316
1
0
null
null
null
null
UTF-8
C++
false
false
817
cpp
#include "fe/subsystems/collision/bounds/circle.hpp" #include "fe/subsystems/serializer/serializerID.hpp" void fe::circle::serialize(fe::serializerID &serializer) const { serializer.write("radius", m_radius); serializer.write("localPosX", m_offsetX); serializer.write("localPosY", m_offsetY); serializer.write("globalPosX", m_globalPositionX); serializer.write("globalPosY", m_globalPositionY); } void fe::circle::deserialize(fe::serializerID &serializer) { m_radius = serializer.read<float>("radius"); m_offsetX = serializer.read<float>("localPosX"); m_offsetY = serializer.read<float>("localPosY"); m_globalPositionX = serializer.read<float>("globalPosX"); m_globalPositionY = serializer.read<float>("globalPosY"); }
91888179b08d36b68ad585b882096b1b19303ffc
33b21c1367eef2f73c3a69c62186986e80602939
/522_longest-uncommon-subsequence-ii.cpp
fb21b5de6180a35671600a5db4318ab4f1f24035
[]
no_license
xmyqsh/leetcode2016
820357560c632188b116fb254183c21f0a956d60
abd8e36a79cdd7f7e0c5d6c362b0f106933c7c40
refs/heads/master
2021-07-06T07:48:36.474328
2020-09-18T03:07:40
2020-09-18T03:07:40
65,090,012
5
5
null
null
null
null
UTF-8
C++
false
false
897
cpp
class Solution { public: int findLUSlength(vector<string>& strs) { sort(strs.begin(), strs.end(), [](const string& s1, const string& s2) { return s1.size() > s2.size(); }); unordered_map<string, int> mp; for (auto str : strs) ++mp[str]; for (auto s1 : strs) { if (mp[s1] != 1) continue; int cnt = 0; for (auto s2 : strs) { if (s1.size() > s2.size()) break; if (isSub(s1, s2)) if (++cnt > 1) break; } if (cnt == 1) return s1.size(); } return -1; } bool isSub(const string& s1, const string& s2) { int i = 0, j = 0; for (; i != s1.size() && j != s2.size(); ++j) if (s1[i] == s2[j]) ++i; return i == s1.size(); } };
358da78decd1cd6b7aba993aa2a0fb48604ed411
432fdb991b1edb73457fdcb1a817fe6d3a5afef5
/chrome/browser/previews/previews_lite_page_redirect_url_loader.cc
024cf527de57f980e179bcb20f57bb47a1eccaea
[ "BSD-3-Clause" ]
permissive
nampud/chromium
40c431d53e5877f2a12b7fbb81253c6dcbc268b0
365dd0bd81d7ee32bcab0e4ede6e704ab6a2358c
refs/heads/master
2023-02-25T04:35:03.566375
2019-09-22T20:17:03
2019-09-22T20:17:03
210,211,364
0
1
BSD-3-Clause
2019-09-22T20:40:56
2019-09-22T20:40:56
null
UTF-8
C++
false
false
12,957
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/previews/previews_lite_page_redirect_url_loader.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/previews/previews_lite_page_navigation_throttle.h" #include "chrome/browser/profiles/profile.h" #include "components/previews/core/previews_experiments.h" #include "components/previews/core/previews_lite_page_redirect.h" #include "content/public/browser/browser_context.h" #include "content/public/common/previews_state.h" #include "net/http/http_status_code.h" #include "net/http/http_util.h" #include "net/url_request/redirect_util.h" #include "services/network/public/cpp/resource_request.h" namespace previews { namespace { // Used for mojo pipe size. Same constant as navigation code. constexpr size_t kRedirectDefaultAllocationSize = 512 * 1024; } // namespace PreviewsLitePageRedirectURLLoader::PreviewsLitePageRedirectURLLoader( content::BrowserContext* browser_context, const network::ResourceRequest& tentative_resource_request, HandleRequest callback) : modified_resource_request_(tentative_resource_request), callback_(std::move(callback)), binding_(this), origin_probe_finished_successfully_(false), litepage_request_finished_successfully_(false) { pref_service_ = browser_context ? Profile::FromBrowserContext(browser_context)->GetPrefs() : nullptr; } PreviewsLitePageRedirectURLLoader::~PreviewsLitePageRedirectURLLoader() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void PreviewsLitePageRedirectURLLoader::OnOriginProbeComplete(bool success) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // It is safe to delete the prober during this callback, so do so because it // is an expensive object to keep around. origin_connectivity_prober_.reset(); if (success) { origin_probe_finished_successfully_ = true; MaybeCallOnLitePageSuccess(); return; } OnLitePageFallback(); } void PreviewsLitePageRedirectURLLoader::StartOriginProbe( const GURL& original_url, const scoped_refptr<network::SharedURLLoaderFactory>& network_loader_factory) { net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("previews_litepage_origin_prober", R"( semantics { sender: "Previews Litepage Origin Prober" description: "Sends a HEAD request to the origin that the user is navigating to " "in order to establish network connectivity before attempting a " "preview of that site." trigger: "Requested on preview-eligible navigations when Lite mode and " "Previews are enabled and the network is slow." data: "None." destination: WEBSITE } policy { cookies_allowed: NO setting: "Users can control Lite mode on Android via the settings menu. " "Lite mode is not available on iOS, and on desktop only for " "developer testing." policy_exception_justification: "Not implemented." })"); // This probe is a single chance with a short timeout because it blocks the // navigation. AvailabilityProber::TimeoutPolicy timeout_policy; timeout_policy.base_timeout = previews::params::LitePageRedirectPreviewOriginProbeTimeout(); AvailabilityProber::RetryPolicy retry_policy; retry_policy.max_retries = 0; origin_connectivity_prober_ = std::make_unique<AvailabilityProber>( this, network_loader_factory, pref_service_, AvailabilityProber::ClientName::kLitepagesOriginCheck, original_url.GetOrigin(), AvailabilityProber::HttpMethod::kHead, net::HttpRequestHeaders(), retry_policy, timeout_policy, traffic_annotation, 10 /* max_cache_entries */, base::TimeDelta::FromHours(24) /* revalidate_cache_after */); origin_connectivity_prober_->SetOnCompleteCallback(base::BindRepeating( &PreviewsLitePageRedirectURLLoader::OnOriginProbeComplete, weak_ptr_factory_.GetWeakPtr())); origin_connectivity_prober_->SendNowIfInactive( false /* send_only_in_foreground */); } bool PreviewsLitePageRedirectURLLoader::ShouldSendNextProbe() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return true; } bool PreviewsLitePageRedirectURLLoader::IsResponseSuccess( net::Error net_error, const network::mojom::URLResponseHead* head, std::unique_ptr<std::string> body) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Any HTTP response is fine, so long as we got it. return net_error == net::OK && head && head->headers; } void PreviewsLitePageRedirectURLLoader::StartRedirectToPreview( const net::HttpRequestHeaders& chrome_proxy_headers, const scoped_refptr<network::SharedURLLoaderFactory>& network_loader_factory, int frame_tree_node_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); GURL original_url = modified_resource_request_.url; GURL lite_page_url = PreviewsLitePageNavigationThrottle::GetPreviewsURLForURL( modified_resource_request_.url); CreateRedirectInformation(lite_page_url); modified_resource_request_.headers.MergeFrom(chrome_proxy_headers); if (previews::params::LitePageRedirectShouldProbeOrigin()) { StartOriginProbe(original_url, network_loader_factory); } else { origin_probe_finished_successfully_ = true; } serving_url_loader_ = std::make_unique<PreviewsLitePageServingURLLoader>( base::BindOnce(&PreviewsLitePageRedirectURLLoader::OnResultDetermined, weak_ptr_factory_.GetWeakPtr())); // |serving_url_loader_| can be null after this call. serving_url_loader_->StartNetworkRequest( modified_resource_request_, network_loader_factory, frame_tree_node_id); } void PreviewsLitePageRedirectURLLoader::StartRedirectToOriginalURL( const GURL& original_url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CreateRedirectInformation(original_url); std::move(callback_).Run( nullptr, base::BindOnce(&PreviewsLitePageRedirectURLLoader:: StartHandlingRedirectToModifiedRequest, weak_ptr_factory_.GetWeakPtr())); } void PreviewsLitePageRedirectURLLoader::CreateRedirectInformation( const GURL& redirect_url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool insecure_scheme_was_upgraded = false; bool copy_fragment = true; redirect_info_ = net::RedirectInfo::ComputeRedirectInfo( modified_resource_request_.method, modified_resource_request_.url, modified_resource_request_.site_for_cookies, net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT, modified_resource_request_.referrer_policy, modified_resource_request_.referrer.spec(), net::HTTP_TEMPORARY_REDIRECT, redirect_url, base::nullopt, insecure_scheme_was_upgraded, copy_fragment); bool should_clear_upload = false; net::RedirectUtil::UpdateHttpRequest( modified_resource_request_.url, modified_resource_request_.method, redirect_info_, base::nullopt, base::nullopt, &modified_resource_request_.headers, &should_clear_upload); DCHECK(!should_clear_upload); modified_resource_request_.url = redirect_info_.new_url; modified_resource_request_.method = redirect_info_.new_method; modified_resource_request_.site_for_cookies = redirect_info_.new_site_for_cookies; modified_resource_request_.referrer = GURL(redirect_info_.new_referrer); modified_resource_request_.referrer_policy = redirect_info_.new_referrer_policy; } void PreviewsLitePageRedirectURLLoader::OnResultDetermined( ServingLoaderResult result, base::Optional<net::RedirectInfo> redirect_info, scoped_refptr<network::ResourceResponse> response) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!redirect_info || result == ServingLoaderResult::kRedirect); DCHECK(!response || result == ServingLoaderResult::kRedirect); switch (result) { case ServingLoaderResult::kSuccess: litepage_request_finished_successfully_ = true; MaybeCallOnLitePageSuccess(); return; case ServingLoaderResult::kFallback: OnLitePageFallback(); return; case ServingLoaderResult::kRedirect: OnLitePageRedirect(redirect_info.value(), response->head); return; } NOTREACHED(); } void PreviewsLitePageRedirectURLLoader::MaybeCallOnLitePageSuccess() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!callback_) return; if (!origin_probe_finished_successfully_ || !litepage_request_finished_successfully_) { return; } OnLitePageSuccess(); } void PreviewsLitePageRedirectURLLoader::OnLitePageSuccess() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(origin_probe_finished_successfully_); DCHECK(litepage_request_finished_successfully_); std::move(callback_).Run( std::move(serving_url_loader_), base::BindOnce(&PreviewsLitePageRedirectURLLoader:: StartHandlingRedirectToModifiedRequest, weak_ptr_factory_.GetWeakPtr())); } void PreviewsLitePageRedirectURLLoader::OnLitePageRedirect( const net::RedirectInfo& redirect_info, const network::ResourceResponseHead& response_head) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); redirect_info_ = redirect_info; response_head_ = response_head; std::move(callback_).Run( nullptr, base::BindOnce(&PreviewsLitePageRedirectURLLoader::StartHandlingRedirect, weak_ptr_factory_.GetWeakPtr())); } void PreviewsLitePageRedirectURLLoader::OnLitePageFallback() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (callback_) std::move(callback_).Run(nullptr, {}); } void PreviewsLitePageRedirectURLLoader::StartHandlingRedirectToModifiedRequest( const network::ResourceRequest& resource_request, network::mojom::URLLoaderRequest request, network::mojom::URLLoaderClientPtr client) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); response_head_.request_start = base::TimeTicks::Now(); response_head_.response_start = response_head_.request_start; std::string header_string = base::StringPrintf( "HTTP/1.1 %i Temporary Redirect\n" "Location: %s\n", net::HTTP_TEMPORARY_REDIRECT, modified_resource_request_.url.spec().c_str()); response_head_.headers = base::MakeRefCounted<net::HttpResponseHeaders>( net::HttpUtil::AssembleRawHeaders(header_string)); response_head_.encoded_data_length = 0; StartHandlingRedirect(resource_request, std::move(request), std::move(client)); } void PreviewsLitePageRedirectURLLoader::StartHandlingRedirect( const network::ResourceRequest& /* resource_request */, network::mojom::URLLoaderRequest request, network::mojom::URLLoaderClientPtr client) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!binding_.is_bound()); binding_.Bind(std::move(request)); binding_.set_connection_error_handler( base::BindOnce(&PreviewsLitePageRedirectURLLoader::OnConnectionClosed, weak_ptr_factory_.GetWeakPtr())); client_ = std::move(client); mojo::DataPipe pipe(kRedirectDefaultAllocationSize); if (!pipe.consumer_handle.is_valid()) { delete this; return; } client_->OnReceiveRedirect(redirect_info_, response_head_); } void PreviewsLitePageRedirectURLLoader::FollowRedirect( const std::vector<std::string>& removed_headers, const net::HttpRequestHeaders& modified_headers, const base::Optional<GURL>& new_url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Content should not hang onto old URLLoaders for redirects. NOTREACHED(); } void PreviewsLitePageRedirectURLLoader::SetPriority( net::RequestPriority priority, int32_t intra_priority_value) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Pass through. serving_url_loader_->SetPriority(priority, intra_priority_value); } void PreviewsLitePageRedirectURLLoader::PauseReadingBodyFromNet() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Pass through. serving_url_loader_->PauseReadingBodyFromNet(); } void PreviewsLitePageRedirectURLLoader::ResumeReadingBodyFromNet() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Pass through. serving_url_loader_->ResumeReadingBodyFromNet(); } void PreviewsLitePageRedirectURLLoader::OnConnectionClosed() { // This happens when content cancels the navigation. Close the network request // and client handle and destroy |this|. binding_.Close(); client_.reset(); delete this; } } // namespace previews
05865b8643fb74eb49baf83a88a85a1765bee10d
8f99599d341fdda1d4553452950b4832a630e812
/baekjoon/simul/17135.cpp
88de6da8e78ad08a068d4c2286d7a29f6cf03810
[]
no_license
JJungwoo/algorithm
7fc8e76a51bd81c59a06393aa158286c45190366
faadecb499dad06cd4552e1cd8ea482206affeb5
refs/heads/master
2022-05-20T00:14:31.950576
2022-03-16T14:10:32
2022-03-16T14:10:32
222,277,844
1
0
null
null
null
null
UHC
C++
false
false
3,293
cpp
/* [boj] 17135. 캐슬 디펜스 각각의 턴마다 궁수는 하나의 적을 공격하고, 모든 궁수는 동시에 공격한다 같은 적이 여러 궁수에게 공격당할수 있고 궁수가 공격하는 적은 거리가 D이하인 적중에 가장 가까운 적이고, 그러한 적이 여럿일 경우 가장 왼쪽에 적을 공격한다. 궁수의 공격이 끝나고 적이 이동한다. */ #include <iostream> #include <vector> #include <algorithm> #include <cmath> #define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; #define distance(sx, sy, dx, dy) (abs(sx - dx) + abs(sy - dy)) int n, m, d, ans; int map[15][15], copy_map[15][15]; bool visited[15]; struct monster { int x, y, d; }; bool compare(monster a, monster b) { if(a.d == b.d) return a.y < b.y; else return a.d < b.d; } vector<int> hunter; void copy() { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { copy_map[i][j] = map[i][j]; } } } void solve(int cnt) { if (cnt == 3) { int kill = 0; int size = hunter.size(); copy(); for (int i = n; i >= 1; i--) { // 아래에서 위로 올라감 vector<monster> monters[3]; for (int j = 0; j < 3; j++) { int sx = i, sy = hunter[j]; for (int x = 0; x < i; x++) { for (int y = 0; y < m; y++) { int dis = distance(sx, sy, x, y); if (copy_map[x][y] == 1 && dis <= d) { monters[j].push_back({ x,y,dis }); } } } if (monters[j].size() > 0) { sort(monters[j].begin(), monters[j].end(), compare); } } for (int j = 0; j < 3; j++) { if (monters[j].size() > 0) { int tx = monters[j][0].x, ty = monters[j][0].y; if (copy_map[tx][ty] != 0) { copy_map[tx][ty] = 0; kill++; } } } } if (ans < kill) { ans = kill; } return; } for (int i = 0; i < m; i++) { if (visited[i]) continue; visited[i] = true; hunter.push_back(i); solve(cnt + 1); hunter.pop_back(); visited[i] = false; } } int main() { io; cin >> n >> m >> d; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> map[i][j]; } } solve(0); cout << ans << "\n"; return 0; } /* #include <iostream> #include <vector> #include <algorithm> #include <queue> using namespace std; int n, m, d, ans; int map[16][16]; bool visited[16]; vector<int> archer; void move_monster() { for (int i = n-1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { if (map[i][j] == 1 && i == n - 1) { map[i][j] = 0; } else if(map[i][j] == 1) { swap(map[i][j], map[i + 1][j]); } } } } void print_map() { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << map[i][j] << " "; } cout << "\n"; } } void hunting_monster(int pos) { } void dfs(int cnt) { if (cnt == 3) { for (int i = 0; i < n; i++) { vector<pair<int, int> > killed; for (int j = 0; j < archer.size(); j++) { } } ans = max(ans, cnt); return; } for (int i = 0; i < m; i++) { if (visited[i]) continue; visited[i] = true; archer.push_back(i); dfs(cnt + 1); archer.pop_back(); visited[i] = false; } } int main() { cin >> n >> m >> d; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> map[i][j]; } } dfs(0); cout << ans << "\n"; return 0; } */
4e4424c4ce21ad8ee5baad1ea2879b48b39b2579
9cb42d00153b1154a6efd915ab3fb731167c5894
/wnditemvalues.h
7881322b287d0f5e8e40526caf38bb5081886a2a
[]
no_license
corra72/mudeditor
45f9bfeb8b80e20cc00e5f1d694973d0cc27a701
7cca359cc1b8c32ad678d0dd5717e629011919fc
refs/heads/master
2020-05-20T04:07:28.076528
2019-06-17T10:18:04
2019-06-17T10:18:04
185,375,884
1
0
null
null
null
null
UTF-8
C++
false
false
757
h
#ifndef TS_WNDITEMVALUES_H #define TS_WNDITEMVALUES_H #include <QDialog> #include "ui_guiitemvalues.h" #include "area.h" using namespace ts; class WndItemValues : public QDialog, private Ui::GuiItemValues { Q_OBJECT public: WndItemValues( const Area&, Item&, QWidget* ); virtual ~WndItemValues(); signals: void dataSaved(); protected slots: void saveData(); void somethingChanged(); void saveAndClose(); void editValue0(); void editValue1(); void editValue2(); void editValue3(); protected: void init(); void closeEvent( QCloseEvent* ); void loadData(); void refreshTitle(); void refreshPanel(); void enableValueButton( int, bool ); private: const Area& m_area; Item& m_item; }; #endif // TS_WNDITEMVALUES_H
590fe6690832cd7a48226bd41030547d1118f50d
f8b56b711317fcaeb0fb606fb716f6e1fe5e75df
/Internal/SDK/Title_AshenWinds_WarsmithoftheFlame_classes.h
d5f34cf991d49276a8f2b0feede7253ca4a9784b
[]
no_license
zanzo420/SoT-SDK-CG
a5bba7c49a98fee71f35ce69a92b6966742106b4
2284b0680dcb86207d197e0fab6a76e9db573a48
refs/heads/main
2023-06-18T09:20:47.505777
2021-07-13T12:35:51
2021-07-13T12:35:51
385,600,112
0
0
null
2021-07-13T12:42:45
2021-07-13T12:42:44
null
UTF-8
C++
false
false
824
h
#pragma once // Name: Sea of Thieves, Version: 2.2.0.2 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Title_AshenWinds_WarsmithoftheFlame.Title_AshenWinds_WarsmithOfTheFlame_C // 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0]) class UTitle_AshenWinds_WarsmithOfTheFlame_C : public UTitleDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Title_AshenWinds_WarsmithoftheFlame.Title_AshenWinds_WarsmithOfTheFlame_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
c09146eb2706b378cdfabf393f274e9698ef129d
35cbf0f7f26ce1d06c429a01c1d006ff201ce02f
/core/datastorage.cpp
bc5510456885fa5cbb8d446011b23357016608a1
[]
no_license
walterqin/weighbridge
384da46dd03c3787c30fa253a745674b900adcc7
0afe406e7394fcc529dddd82af66158ce5b8a9b1
refs/heads/master
2021-01-18T13:59:39.966713
2016-01-19T09:48:37
2016-01-19T09:48:37
42,099,107
0
1
null
null
null
null
UTF-8
C++
false
false
274
cpp
/** * @file datastorage.cpp * @brief 打印类的基类 * @ingroup core * @author walterqin([email protected]) * @date 2015-10-14 */ #include "datastorage.h" DataStorage::DataStorage(QObject *parent) : QObject(parent) { } DataStorage::~DataStorage() { }
62e58f17c2797440e4c40f3a160d03663183ae14
234e89b029bb89cd5a9141bfce995d57f5b0ad92
/src/network_functions.cpp
3f3194330e848e5076f0a576fb4b819c5a2503df
[]
no_license
Seenshade/PictureAnalysis
61fd9df5028b6a3d5bd65b2226f4fb77ad2517b6
3a399abe39f4ce4116840d0b886b6cd15f2b16ef
refs/heads/master
2023-08-27T01:01:04.364283
2021-10-27T13:39:28
2021-10-27T13:39:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
#include "network_functions.h" #include <QObject> #include <QNetworkReply> #include <QEventLoop> #include <QJsonObject> #include <QJsonDocument> #include <QJsonArray> QString GET(QNetworkAccessManager* mgr, const QNetworkRequest& request){ QNetworkReply* reply = mgr->get(request); QEventLoop loop; QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); reply->deleteLater(); QString response = QString::fromUtf8(reply->readAll()); return response; } QString POST(QNetworkAccessManager* mgr, const QNetworkRequest& request, QByteArray&& postData) { QNetworkReply* reply = mgr->post(request, postData); QEventLoop loop; QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); QString response = QString::fromUtf8(reply->readAll()); return response; } QJsonArray SendImage(QNetworkAccessManager* mgr, QString url, QString token, QByteArray&& image){ QUrl url_query(url); url_query.setQuery("fd_threshold=0.1&demographics=true"); QNetworkRequest request(url_query.toString()); request.setRawHeader("Authorization", "Bearer " + token.toUtf8()); request.setHeader(QNetworkRequest::ContentTypeHeader, "image/jpeg"); request.setRawHeader("accept", "application/json"); auto response = POST(mgr, request, std::move(image)); QJsonDocument response_json = QJsonDocument::fromJson(response.toUtf8()); auto data = response_json["data"].toArray(); return data; }
eadebeb6985d3bf6c39f33a4d7fa46928e38df06
076389ae543ee83723f2b05ce530df2bdd712da9
/template/understandingtemplates/test1.cpp
68c6309e076bf0cfd8c550757694f6517ef766bc
[]
no_license
zhudisheng/The-Cplusplus-programming-language
e31183d4e98ee8d3d285fa21f8b973630ff496f3
6369e0f6fb568534d6933b5245c8e267175920b9
refs/heads/master
2021-05-17T11:38:46.670776
2020-04-08T02:11:15
2020-04-08T02:11:15
250,759,088
1
0
null
null
null
null
UTF-8
C++
false
false
394
cpp
#include <iostream> #include <string> using namespace std; template<typename T1,typename T2,typename T3> T1 Add(T2 a,T3 b) { return static_cast<T1>(a+b); } int main() { int r1 = Add<int>(0.5,0.8); double r2 = Add<double,float>(0.5,0.8); float r3 = Add<float,float,float>(0.5,0.8); cout << "r1 = " << r1 << endl; cout << "r2 = " << r2 << endl; cout << "r3 = " << r3 << endl; return 0; }
a512c16058e5ea9ede618c17af1e120dd567d0a3
1564f6dfd34da8b822c00a18111ac6dec8e8b537
/login.cpp
da7b884bbb983b1da5555c10889d40a290d26dbd
[]
no_license
Shuang777/tippi_demo
aa989a04e9d2247c52410601d1bd18e7b60ed408
124cf3eb4d9686e2047f307f686bacfb1d083f76
refs/heads/master
2016-09-06T07:54:15.182934
2015-05-02T05:45:57
2015-05-02T05:45:57
34,651,502
0
0
null
null
null
null
UTF-8
C++
false
false
8,534
cpp
#include "login.h" #include "ui_login.h" #include "signup.h" #include "progressbar.h" #include <QtCore> #include <QtGui> #include <QMessageBox> #include <QFileDialog> #include <fstream> #include <QDesktopWidget> #include <sys/stat.h> #include <QDebug> #include "base/kaldi-common.h" using std::pair; using std::endl; using std::ofstream; using std::max; using std::min; login::login(QWidget *parent) : QMainWindow(parent), ui(new Ui::login), ivectorExtraction(true) { ui->setupUi(this); QImage* img=new QImage(":/images/chat.png"); QImage imgScaled=img->scaled(ui->logo->width(), ui->logo->height()); ui->logo->setPixmap(QPixmap::fromImage(imgScaled)); QIcon qicon(QPixmap::fromImage(imgScaled)); QWidget::setWindowIcon(qicon); dataDir = "/home/shuang/project/tippi/final/demo/data"; userInfoFile = dataDir + "/user_info"; tmpDir = dataDir + "/tmp"; fileDir = dataDir + "/files"; modelDir = "/home/shuang/project/tippi/final/demo/models"; testFile = tmpDir + "/test.wav"; trainFile1 = tmpDir + "/train1.wav"; trainFile2 = tmpDir + "/train2.wav"; string femaleIvecMdl = modelDir + "/female_final_derived.ie"; string femaleUbm = modelDir + "/female_final.ubm"; string maleIvecMdl = modelDir + "/male_final_derived.ie"; string maleUbm = modelDir + "/male_final.ubm"; ivectorExtraction.SetModels(femaleIvecMdl, femaleUbm, maleIvecMdl, maleUbm); mkdir(dataDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); mkdir(tmpDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); mkdir(fileDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); milSeconds = 2500; LoadUserInfo(); connect(ui->lineEdit, SIGNAL(returnPressed()),ui->loginButton,SLOT(click())); ui->menuBar->hide(); SetCenterOfApplication(); set_kaldi_env(); //ivecScoreTol = 0.08; ivecScoreTol = 0.3; ivecDisThreshold = 22; postScoreTol = 0.30; skipRecording = false; saveWavFile = false; } void login::SetCenterOfApplication() { QDesktopWidget* desktop = QApplication::desktop(); int width = desktop->width(); int height = desktop->height(); int mw = this->width(); int mh = this->height(); int centerW = (width/2) - (mw/2); int centerH = (height/2) - (mh/2); this->move(centerW, centerH); } login::~login() { delete ui; } void login::LoadUserInfo() { std::ifstream infile(userInfoFile); string username; char genderchar; Gender gender; while(infile >> username >> genderchar) { if (genderchar == '0') { gender = male; } else { gender = female; } usernameMap.insert(pair<string, Gender>(username,gender)); } } bool login::HasUser(string username) { return usernameMap.find(username) != usernameMap.end(); } void login::on_loginButton_clicked() { string username = ui->lineEdit->text().toStdString(); if (username == "super"){ ui->menuBar->show(); ui->lineEdit->setText(""); return; } if (username == "") { QMessageBox::information(this, "Info", "Please input username first."); return; } else if (usernameMap.find(username) == usernameMap.end()) { QMessageBox::information(this, "Info", "Username not found."); return; } if (!skipRecording) { progressbar recordprogress(this, milSeconds, testFile); recordprogress.setModal(true); recordprogress.exec(); if (saveWavFile) { string testFileDir = fileDir + "/" + username + "/tests"; mkdir(testFileDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); check_and_copy_files(testFile, testFileDir); } } string utt_id = "test"; compute_feat(utt_id, testFile); string feature_rspecifier = prep_feat(testFile); ivectorExtraction.SetGender(usernameMap[username]); ivectorExtraction.Extract(feature_rspecifier, testIvector, testPost); string ivecFile = prep_ivec_spec(testFile); ivectorExtraction.WriteIvector(ivecFile, utt_id, testIvector); string postFile = prep_post_spec(testFile); ivectorExtraction.WritePost(postFile, utt_id, testPost); bool checkPassed = Validate(username); // validate if the recored wav file match user's info if (checkPassed) { QMessageBox::information(this, "Info", "Login succeed!"); } else { QMessageBox::information(this, "Info", "Login failed, please try again."); } } bool login::Validate(std::string username) { string userDir = fileDir + "/" + username; string userIvec1 = userDir + "/train1.ivec.ark"; ivectorExtraction.ReadIvector(userIvec1, trainIvector1); string userIvec2 = userDir + "/train2.ivec.ark"; ivectorExtraction.ReadIvector(userIvec2, trainIvector2); string userPost1 = userDir + "/train1.post.ark"; ivectorExtraction.ReadPost(userPost1, trainPost1); string userPost2 = userDir + "/train2.post.ark"; ivectorExtraction.ReadPost(userPost2, trainPost2); double score1 = ivectorExtraction.Scoring(testIvector, trainIvector1); double score2 = ivectorExtraction.Scoring(testIvector, trainIvector2); double baseScore = ivectorExtraction.Scoring(trainIvector1, trainIvector2); qDebug() << "score against train1: " << score1; qDebug() << "score against train2: " << score2; qDebug() << "base score: " << baseScore; qDebug() << "min: " << min(score1, score2) << " vs threshold " << ivecDisThreshold; double scorePost1 = ivectorExtraction.Scoring(testPost, trainPost1); double scorePost2 = ivectorExtraction.Scoring(testPost, trainPost2); double baseScorePost = ivectorExtraction.Scoring(trainPost1, trainPost2); qDebug() << "scorePost1: " << scorePost1; qDebug() << "scorePost2: " << scorePost2; qDebug() << "baseScorePost: " << baseScorePost; qDebug() << "max / base: " << max(scorePost1, scorePost2) / baseScorePost << " vs threshold" << postScoreTol + 1; if ((min(score1, score2) < ivecDisThreshold) && (max(scorePost2, scorePost1) > (1 + postScoreTol) * baseScorePost)) return true; else return false; } void login::on_signupButton_clicked() { bool changePasswdMode = false; OpenSignupDiag(changePasswdMode); } void login::on_changeButton_clicked() { bool changePasswdMode = true; OpenSignupDiag(changePasswdMode); } void login::OpenSignupDiag(bool changePasswdMode) { signup signup_diag(this, milSeconds, &usernameMap, trainFile1, trainFile2, &ivectorExtraction, skipRecording, changePasswdMode, ivecDisThreshold); signup_diag.setModal(true); this->setVisible(false); newUsername = ""; connect(&signup_diag, SIGNAL(SendUsername(string)), this, SLOT(SetNewUsername(string))); signup_diag.exec(); ui->lineEdit->setText(""); this->setVisible(true); if (newUsername != "") { // canceled SaveNewUser(changePasswdMode); UpdateUserInfo(); } } void login::SaveNewUser(bool changePasswdMode) { string userDir = fileDir + "/" + newUsername; mkdir(userDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (changePasswdMode && saveWavFile) { string saveDir = userDir + "/trains"; mkdir(saveDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); check_and_copy_files(trainFile1, saveDir); check_and_copy_files(trainFile2, saveDir); } string trainFileSave1 = userDir + "/train1.wav"; move_files(trainFile1, trainFileSave1); string trainFileSave2 = userDir + "/train2.wav"; move_files(trainFile2, trainFileSave2); } void login::SetNewUsername(string username) { newUsername = username; } void login::UpdateUserInfo() { ofstream os; os.open(userInfoFile); for ( auto it = usernameMap.begin(); it != usernameMap.end(); ++it ) os << it->first << '\t' << it->second << endl; os.close(); } void login::on_lineEdit_returnPressed() { } void login::on_actionSave_wave_files_triggered() { saveWavFile = !saveWavFile; if (saveWavFile) { ui->actionSave_wave_files->setText("Overwrite wave files"); } else { ui->actionSave_wave_files->setText("Save wave files"); } } void login::on_actionSkip_recording_triggered() { skipRecording = !skipRecording; if (skipRecording) { ui->actionSkip_recording->setText("Record"); } else { ui->actionSkip_recording->setText("Skip Recording"); } }
a973b1e24235dd9e5d50663dd36de044fe6152f5
6f2386aa866261546e24139cea2b00b676f0c4e8
/Samples/Linux/TopsensExplorer/panel.cpp
56c5a32706dfde8b303a00b1c8be918b18b9477b
[ "Apache-2.0" ]
permissive
Topsens/3DVision
5fbb1af8de42bbe582c976413626597cf2103e4f
a694cf36df3883a5e2d55173e02d865972b8dee2
refs/heads/master
2023-05-04T19:44:29.126883
2021-05-24T08:26:15
2021-05-24T08:26:15
312,184,155
1
0
null
null
null
null
UTF-8
C++
false
false
3,223
cpp
#include "panel.h" #include "ui_panel.h" using namespace Topsens; Panel::Panel(QWidget *parent) : QWidget(parent), ui(new Ui::Panel) { ui->setupUi(this); ui->bnStop->setEnabled(false); this->ui->cbCres->setCurrentIndex(2); this->ui->cbDres->setCurrentIndex(2); this->ui->rbUsersYes->setChecked(true); this->ui->rbAlignNo->setChecked(true); this->ui->rbFlipYes->setChecked(true); this->ui->rbLand->setChecked(true); this->ui->rbRecordNo->setChecked(true); this->ui->rbGroundYes->setChecked(true); } Panel::~Panel() { delete ui; } void Panel::Count(uint32_t count) { this->ui->cbDevice->clear(); for (uint32_t i = 0; i < count; i++) { this->ui->cbDevice->addItem(QString::fromStdString(std::to_string(i))); } if (count) { this->ui->cbDevice->setCurrentIndex(0); this->Enable(); } else { this->Disable(); this->ui->bnRefresh->setEnabled(true); this->ui->bnStop->setEnabled(false); } } bool Panel::Align() const { return this->ui->rbAlignYes->isChecked(); } bool Panel::Flip() const { return this->ui->rbFlipYes->isChecked(); } bool Panel::Record() const { return this->ui->rbRecordYes->isChecked(); } bool Panel::GenUsers() const { return this->ui->rbUsersYes->isChecked(); } bool Panel::PaintGround() const { return this->ui->rbGroundYes->isChecked(); } Resolution Panel::ColorRes() const { return (Resolution)this->ui->cbCres->currentIndex(); } Resolution Panel::DepthRes() const { return (Resolution)this->ui->cbDres->currentIndex(); } Orientation Panel::Orientation() const { if (this->ui->rbLand->isChecked()) { return Topsens::Orientation::Landscape; } if (this->ui->rbClock->isChecked()) { return Topsens::Orientation::PortraitClockwise; } if (this->ui->rbAntic->isChecked()) { return Topsens::Orientation::PortraitAntiClockwise; } return Topsens::Orientation::Aerial; } void Panel::Enable() { this->ui->cbDevice->setEnabled(true); this->ui->cbCres->setEnabled(true); this->ui->cbDres->setEnabled(true); this->ui->gbUsers->setEnabled(true); this->ui->gbAlign->setEnabled(true); this->ui->gbFlip->setEnabled(true); this->ui->gbOrient->setEnabled(true); this->ui->gbRecord->setEnabled(true); this->ui->gbGround->setEnabled(true); this->ui->bnStart->setEnabled(true); this->ui->bnRefresh->setEnabled(true); this->ui->bnStop->setEnabled(false); } void Panel::Disable() { this->ui->cbDevice->setEnabled(false); this->ui->cbCres->setEnabled(false); this->ui->cbDres->setEnabled(false); this->ui->gbUsers->setEnabled(false); this->ui->gbAlign->setEnabled(false); this->ui->gbFlip->setEnabled(false); this->ui->gbOrient->setEnabled(false); this->ui->gbRecord->setEnabled(false); this->ui->gbGround->setEnabled(false); this->ui->bnStart->setEnabled(false); this->ui->bnRefresh->setEnabled(false); this->ui->bnStop->setEnabled(true); } void Panel::resizeEvent(QResizeEvent* e) { QWidget::resizeEvent(e); this->ui->hline->resize(this->width(), this->ui->hline->height()); }
a34ee48c2d21d2a9315fbc94f33a2929af4fb97a
ba8ded84e58cbdc1b8b886d5988fd59dcdb8b348
/Evaluators/initialize.h
cc6e5da2650b80ea069f556d020392803d59dc84
[]
no_license
ongyiumark/kalamanC
df3416807065ce379dff9d3b94b1e33167411ce1
117db16ae0a83fc819b4758fe11b33a30bdca5ae
refs/heads/master
2022-12-18T18:25:03.964370
2020-08-26T07:40:27
2020-08-26T07:40:27
287,806,444
0
0
null
2020-08-26T07:29:01
2020-08-15T18:50:44
C++
UTF-8
C++
false
false
205
h
#pragma once #include "evaluator.h" #include <string> namespace Evaluators { void initialize(); void run(std::string &script, bool show_tree=false, bool show_return=false, bool is_shell=false); }
e902aa2674561282db05b44eead4817888414070
1dd521e69331aefcce34c2c733ea8cc518d8fa5d
/src/Interface/Modules/Fields/ResampleRegularMeshDialog.h
aeb27bb0417b0b8e0661391aa54249219a360a37
[ "MIT" ]
permissive
Nahusa/SCIRun
b75d4d283d9cc6f802aed390d4c8d210a901ba2d
c54e714d4c7e956d053597cf194e07616e28a498
refs/heads/master
2020-03-23T20:23:00.688044
2018-08-15T17:48:35
2018-08-15T17:48:35
142,037,816
0
0
MIT
2018-07-23T16:04:23
2018-07-23T16:04:23
null
UTF-8
C++
false
false
1,977
h
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 INTERFACE_MODULES_RESAMPLE_REGULAR_MESH_H #define INTERFACE_MODULES_RESAMPLE_REGULAR_MESH_H #include "Interface/Modules/Fields/ui_resampleregularmesh.h" #include <Interface/Modules/Base/ModuleDialogGeneric.h> #include <Interface/Modules/Fields/share.h> namespace SCIRun { namespace Gui { class SCISHARE ResampleRegularMeshDialog : public ModuleDialogGeneric, public Ui::ResampleRegularMesh { Q_OBJECT public: ResampleRegularMeshDialog(const std::string& name, SCIRun::Dataflow::Networks::ModuleStateHandle state, QWidget* parent = 0); private Q_SLOTS: void setGaussianWidgetsEnabled(const QString& label); }; } } #endif
b2ca1ec9e7999ed2043d4093e1a764beddf0e94e
bf0278f3162f424769a24d72ca59f2e8ce59cd60
/sql/executor/ExFirstN.h
33c82cb4bc29f3036e6f6b0daed5711c5ba4fba5
[ "Apache-2.0" ]
permissive
hadr4ros/core
f0834bf62a38268a7f4ca5372c65acc5136749db
95d02634a4a9ef0440c369bf1cc31c85cb19cec6
refs/heads/master
2021-01-19T06:50:57.526104
2015-04-25T03:26:52
2015-04-25T03:26:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,873
h
/********************************************************************** // @@@ START COPYRIGHT @@@ // // (C) Copyright 1994-2014 Hewlett-Packard Development Company, L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // @@@ END COPYRIGHT @@@ **********************************************************************/ #ifndef EX_FIRSTN_H #define EX_FIRSTN_H /* -*-C++-*- ***************************************************************************** * * File: ex_firstn.h * Description: * * * Created: 7/10/95 * Language: C++ * * * * ***************************************************************************** */ #include "Int64.h" #include "NABoolean.h" #include "ComTdbFirstN.h" // ----------------------------------------------------------------------- // Classes defined in this file // ----------------------------------------------------------------------- class ExFirstNTdb; // ----------------------------------------------------------------------- // Classes referenced in this file // ----------------------------------------------------------------------- class ex_tcb; // ----------------------------------------------------------------------- // ExFirstNTdb // ----------------------------------------------------------------------- class ExFirstNTdb : public ComTdbFirstN { public: // --------------------------------------------------------------------- // Constructor is only called to instantiate an object used for // retrieval of the virtual table function pointer of the class while // unpacking. An empty constructor is enough. // --------------------------------------------------------------------- NA_EIDPROC ExFirstNTdb() {} NA_EIDPROC virtual ~ExFirstNTdb() {} // --------------------------------------------------------------------- // Build a TCB for this TDB. Redefined in the Executor project. // --------------------------------------------------------------------- NA_EIDPROC virtual ex_tcb *build(ex_globals *globals); private: // --------------------------------------------------------------------- // !!!!!!! IMPORTANT -- NO DATA MEMBERS ALLOWED IN EXECUTOR TDB !!!!!!!! // ********************************************************************* // The Executor TDB's are only used for the sole purpose of providing a // way to supplement the Compiler TDB's (in comexe) with methods whose // implementation depends on Executor objects. This is done so as to // decouple the Compiler from linking in Executor objects unnecessarily. // // When a Compiler generated TDB arrives at the Executor, the same data // image is "cast" as an Executor TDB after unpacking. Therefore, it is // a requirement that a Compiler TDB has the same object layout as its // corresponding Executor TDB. As a result of this, all Executor TDB's // must have absolutely NO data members, but only member functions. So, // if you reach here with an intention to add data members to a TDB, ask // yourself two questions: // // 1. Are those data members Compiler-generated? // If yes, put them in the ComTdbFirstn instead. // If no, they should probably belong to someplace else (like TCB). // // 2. Are the classes those data members belong defined in the executor // project? // If your answer to both questions is yes, you might need to move // the classes to the comexe project. // --------------------------------------------------------------------- }; // // Task control block // class ExFirstNTcb : public ex_tcb { friend class ExFirstNTdb; friend class ExFirstNPrivateState; const ex_tcb * childTcb_; ex_queue_pair qparent_; ex_queue_pair qchild_; // Stub to cancel() subtask used by scheduler. static ExWorkProcRetcode sCancel(ex_tcb *tcb) { return ((ExFirstNTcb *) tcb)->cancel(); } public: // Constructor NA_EIDPROC ExFirstNTcb(const ExFirstNTdb & firstn_tdb, const ex_tcb & child_tcb, // child queue pair ex_globals *glob ); NA_EIDPROC ~ExFirstNTcb(); enum FirstNStep { INITIAL_, PROCESS_FIRSTN_, PROCESS_LASTN_, DONE_, CANCEL_, ERROR_ }; NA_EIDPROC short moveChildDataToParent(); NA_EIDPROC void freeResources(); // free resources NA_EIDPROC short work(); // when scheduled to do work NA_EIDPROC virtual void registerSubtasks(); // register work procedures with scheduler NA_EIDPROC short cancel(); // for the fickle. NA_EIDPROC inline ExFirstNTdb & firstnTdb() const { return (ExFirstNTdb &) tdb; } NA_EIDPROC ex_queue_pair getParentQueue() const { return qparent_;} NA_EIDPROC virtual Int32 numChildren() const { return 1; } NA_EIDPROC virtual const ex_tcb* getChild(Int32 /*pos*/) const { return childTcb_; } }; /////////////////////////////////////////////////////////////////// class ExFirstNPrivateState : public ex_tcb_private_state { friend class ExFirstNTcb; ExFirstNTcb::FirstNStep step_; Int64 requestedLastNRows_; Int64 returnedLastNRows_; public: NA_EIDPROC ExFirstNPrivateState(const ExFirstNTcb * tcb); //constructor NA_EIDPROC ex_tcb_private_state * allocate_new(const ex_tcb * tcb); NA_EIDPROC ~ExFirstNPrivateState(); // destructor }; #endif
6aeafe729b3a4f2b478aedd8be64b1660e96616a
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-restbed-server/generated/model/OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo.cpp
14fdb07951d7186cbd6d0330409a5681e1b29a5e
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
3,563
cpp
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ #include "OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo.h" #include <string> #include <sstream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using boost::property_tree::ptree; using boost::property_tree::read_json; using boost::property_tree::write_json; namespace org { namespace openapitools { namespace server { namespace model { OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo() { m_Pid = ""; m_Title = ""; m_Description = ""; m_Bundle_location = ""; m_Service_location = ""; } OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::~OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo() { } std::string OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::toJsonString() { std::stringstream ss; ptree pt; pt.put("Pid", m_Pid); pt.put("Title", m_Title); pt.put("Description", m_Description); pt.put("Bundle_location", m_Bundle_location); pt.put("Service_location", m_Service_location); write_json(ss, pt, false); return ss.str(); } void OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::fromJsonString(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; read_json(ss,pt); m_Pid = pt.get("Pid", ""); m_Title = pt.get("Title", ""); m_Description = pt.get("Description", ""); m_Bundle_location = pt.get("Bundle_location", ""); m_Service_location = pt.get("Service_location", ""); } std::string OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::getPid() const { return m_Pid; } void OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::setPid(std::string value) { m_Pid = value; } std::string OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::getTitle() const { return m_Title; } void OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::setTitle(std::string value) { m_Title = value; } std::string OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::getDescription() const { return m_Description; } void OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::setDescription(std::string value) { m_Description = value; } std::shared_ptr<OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletProperties> OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::getProperties() const { return m_Properties; } void OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::setProperties(std::shared_ptr<OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletProperties> value) { m_Properties = value; } std::string OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::getBundleLocation() const { return m_Bundle_location; } void OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::setBundleLocation(std::string value) { m_Bundle_location = value; } std::string OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::getServiceLocation() const { return m_Service_location; } void OrgApacheSlingJcrWebdavImplServletsSimpleWebDavServletInfo::setServiceLocation(std::string value) { m_Service_location = value; } } } } }
df1892f05310479d5d0bc6520f906aa2c1f6560d
8f8ae70775eda42f71d0e6354b9caba4576f3310
/firefoamcases/cases/pyrolysis1D/constant/reactingCloud1Properties
73ca7925ecd1d0512a4edeb0243701ba7d19841b
[]
no_license
hong27/myFireFoamCases
6070bb35781717b58bdec2f1a35be79077ce8111
8709c8aa7f1aa1718f3fbf0c7cdc7b284f531c57
refs/heads/master
2020-06-14T01:38:28.073535
2019-07-02T12:03:25
2019-07-02T12:03:25
194,851,906
0
0
null
null
null
null
UTF-8
C++
false
false
3,213
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.2.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "constant"; object reactingCloud1Properties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // solution { active false; coupled yes; transient yes; cellValueSourceCorrection yes; sourceTerms { schemes { rho explicit 1; U explicit 1; Yi explicit 1; hs explicit 1; } } interpolationSchemes { rho cell; U cellPoint; mu cell; T cell; Cp cell; p cell; } integrationSchemes { U Euler; T analytical; } } constantProperties { parcelTypeId 1; rhoMin 1e-15; TMin 200; pMin 1000; minParticleMass 1e-15; rho0 1000; T0 300; Cp0 4187; youngsModulus 1e9; poissonsRatio 0.35; epsilon0 1; f0 0.5; Pr 0.7; Tvap 273; Tbp 373; constantVolume false; } subModels { particleForces { sphereDrag; gravity; } injectionModel reactingLookupTableInjection; dragModel sphereDrag; dispersionModel none; patchInteractionModel standardWallInteraction; heatTransferModel none; compositionModel singlePhaseMixture; phaseChangeModel none; stochasticCollisionModel none; postProcessingModel none; surfaceFilmModel thermoSurfaceFilm; radiation off; reactingLookupTableInjectionCoeffs { massTotal 1e-1; parcelBasisType mass; SOI 0.001; inputFile "parcelInjectionProperties"; duration 20.0; parcelsPerSecond 200; } standardWallInteractionCoeffs { type rebound; } singlePhaseMixtureCoeffs { phases ( liquid { H2O 1; } ); } thermoSurfaceFilmCoeffs { interactionType splashBai; deltaWet 0.0005; Adry 2630; Awet 1320; Cf 0.6; } } cloudFunctions {} // ************************************************************************* //
21bb12f5b9f95283d9f04fc0c2f8dd2d2030b190
c0bd82eb640d8594f2d2b76262566288676b8395
/src/game/Arenas.h
9fa5813feb732c6f4ad0e269b15b4f5b4e02e7da
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
1,265
h
// Copyright (C) 2004 WoW Daemon // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. class Arena : public Battleground { public: Arena(); ~Arena(); uint32 m_BGTime; uint32 m_MaxScore; std::set<GameObject*> m_Gates; void HandleBattlegroundAreaTrigger(Player *plr, uint32 TriggerID); void HandleBattlegroundEvent(Object *src, Object *dst, uint16 EventID, uint32 params1 = 0, uint32 params2 = 0); void SetupBattleground(); void SpawnBattleground(); void Remove(); void Start(); void EventUpdate(uint32 diff); };
9cb2e4acfd4bb4e90077100c77b9af8435a9a55d
9ecbc437bd1db137d8f6e83b7b4173eb328f60a9
/gcc-build/i686-pc-linux-gnu/libjava/java/sql/Date.h
0229f46c4e45027ca621ff3d1d6b4ca09be9cdd6
[]
no_license
giraffe/jrate
7eabe07e79e7633caae6522e9b78c975e7515fe9
764bbf973d1de4e38f93ba9b9c7be566f1541e16
refs/heads/master
2021-01-10T18:25:37.819466
2013-07-20T12:28:23
2013-07-20T12:28:23
11,545,290
1
0
null
null
null
null
UTF-8
C++
false
false
766
h
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __java_sql_Date__ #define __java_sql_Date__ #pragma interface #include <java/util/Date.h> extern "Java" { namespace java { namespace sql { class Date; } namespace text { class SimpleDateFormat; } } }; class ::java::sql::Date : public ::java::util::Date { public: Date (jint, jint, jint); Date (jlong); static ::java::sql::Date *valueOf (::java::lang::String *); virtual ::java::lang::String *toString (); public: // actually package-private static const jlong serialVersionUID = 1511598038487230103LL; private: static ::java::text::SimpleDateFormat *sdf; public: static ::java::lang::Class class$; }; #endif /* __java_sql_Date__ */
971764f6e8ef7bd370f50311da8abb3c9b2348fb
b4d991eaef412aaff8cc13c31418c91bb7c96ecd
/src/12.integer-to-roman/solution.cpp
b95a8216ff1586674d59821a04d194bc9e4812c0
[]
no_license
tiyee/LeetCode
994d504233593fc613abdc13194306eeaccca402
458aa57fd53ec67faf85ddde2787962fc86b90e0
refs/heads/master
2023-03-20T16:42:36.479091
2023-03-05T15:59:24
2023-03-05T15:59:24
141,676,267
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
cpp
/** 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/integer-to-roman 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ #include <iostream> #include <vector> using namespace std; class Solution { public: string intToRoman(int num) { vector<int> values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; vector<string> symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string ret = ""; for (size_t i = 0; i < 13; i++) { while (num >= values[i]) { num -= values[i]; ret += symbols[i]; } if (num == 0) { break; } } return ret; } }; int main() { int num = 4; std::cout << Solution().intToRoman(num) << std::endl; return 0; }
6c3768cab629bb9c3326c1543183856b8170edb2
464cd8249cd3b4e6b5901eabc23e2b87ba9e7fab
/After Life/build/Android/Preview/app/src/main/jni/Android.Base.Wrappers.g.cpp
43423e89d1cb184360c8fca7f5b544767526c328
[]
no_license
martin-morales/After-Life
25f95dd5e5b6069355358ff7c9bd5b1bc022ee7c
932ff16a632048678343f887f4c2fc44a072b9eb
refs/heads/master
2021-09-23T00:11:32.160761
2017-05-26T03:13:26
2017-05-26T03:13:26
91,754,404
0
0
null
2018-09-18T22:04:13
2017-05-19T01:53:31
C++
UTF-8
C++
false
false
17,770
cpp
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <Android.Base.JNI.h> #include <Android.Base.JNI.RefType.h> #include <Android.Base.Primitiv-2924c081.h> #include <Android.Base.Primitiv-2b9696be.h> #include <Android.Base.Primitiv-b7b09a.h> #include <Android.Base.Types.Bridge.h> #include <Android.Base.Wrappers.JWrapper.h> #include <Android.Base.Wrappers-88f7a41f.h> #include <Android.Base.Wrappers-90b493fe.h> #include <Android.Base.Wrappers-dff080bb.h> #include <jni.h> #include <Uno.Bool.h> #include <Uno.Exception.h> #include <Uno.Int.h> #include <Uno.Long.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.Type.h> //~ bool __JWrapper_Callbacks_Registered = false; void __JWrapper_Finalizer(JNIEnv *env , jclass clazz, jlong ptr) { uWeakObject* weak = (uWeakObject*)ptr; uAutoReleasePool pool; ::g::Android::Base::Wrappers::JWrapper* wrapper = (::g::Android::Base::Wrappers::JWrapper*)uLoadWeak(weak); uStoreWeak(&weak, 0); } void __Register_Finalizer() { JNIEnv* jni = ::g::Android::Base::JNI::GetEnvPtr(); JNINativeMethod nativeFunc = {(char* const)"Finalize", (char* const)"(J)V", (void *)&__JWrapper_Finalizer}; jclass cls = reinterpret_cast<jclass>(jni->NewGlobalRef(::g::Android::Base::JNI::LoadClass(::g::Android::Base::JNI::GetEnvPtr(), "com.Bindings.UnoHelper"))); jint attached = ::g::Android::Base::JNI::GetEnvPtr()->RegisterNatives(cls, &nativeFunc, 1); if (attached < 0) { U_THROW(::g::Uno::Exception::New2(uString::Utf8("Could not register the instantiation callback function",54))); } } //~ bool __JWrapper_WeakCallback(uWeakStateIntercept::Event e, uObject* obj) { ::g::Android::Base::JNI::CheckException(); ::g::Android::Base::Wrappers::JWrapper* wrapper = (::g::Android::Base::Wrappers::JWrapper*)obj; jobject jobj = wrapper->_javaObject; if (!jobj) return true; bool subclassed = wrapper->_subclassed; if (e == uWeakStateIntercept::OnLoad) { // retain went from 0 to 1 if (subclassed) { JNIEnv* jni = ::g::Android::Base::JNI::GetEnvPtr(); wrapper->_javaObject = jni->NewGlobalRef(jobj); jni->DeleteWeakGlobalRef(jobj); return true; } else { return true; } } else { // retain went from 1 to 0 if (subclassed) { JNIEnv* jni = ::g::Android::Base::JNI::GetEnvPtr(); wrapper->_javaObject = jni->NewWeakGlobalRef(jobj); jni->DeleteGlobalRef(jobj); return false; } else { JNIEnv* jni = ::g::Android::Base::JNI::GetEnvPtr(); jni->DeleteGlobalRef(jobj); return true; } } return false; } static uString* STRINGS[2]; static uType* TYPES[1]; namespace g{ namespace Android{ namespace Base{ namespace Wrappers{ // /Users/martinmorales/Library/Application Support/Fusetools/Packages/UnoCore/1.0.11/targets/android/uno/base/$.uno // ----------------------------------------------------------------------------------------------------------------- // public sealed extern class BindingSubclassAttribute :1116 // { static void BindingSubclassAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)BindingSubclassAttribute__New1_fn, 0, true, type, 0)); } uType* BindingSubclassAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(BindingSubclassAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Android.Base.Wrappers.BindingSubclassAttribute", options); type->fp_build_ = BindingSubclassAttribute_build; type->fp_ctor_ = (void*)BindingSubclassAttribute__New1_fn; return type; } // public BindingSubclassAttribute() :1118 void BindingSubclassAttribute__ctor_1_fn(BindingSubclassAttribute* __this) { __this->ctor_1(); } // public BindingSubclassAttribute New() :1118 void BindingSubclassAttribute__New1_fn(BindingSubclassAttribute** __retval) { *__retval = BindingSubclassAttribute::New1(); } // public BindingSubclassAttribute() [instance] :1118 void BindingSubclassAttribute::ctor_1() { ctor_(); } // public BindingSubclassAttribute New() [static] :1118 BindingSubclassAttribute* BindingSubclassAttribute::New1() { BindingSubclassAttribute* obj1 = (BindingSubclassAttribute*)uNew(BindingSubclassAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // /Users/martinmorales/Library/Application Support/Fusetools/Packages/UnoCore/1.0.11/targets/android/uno/base/$.uno // ----------------------------------------------------------------------------------------------------------------- // public abstract extern interface IJWrapper :1122 // { uInterfaceType* IJWrapper_typeof() { static uSStrong<uInterfaceType*> type; if (type != NULL) return type; type = uInterfaceType::New("Android.Base.Wrappers.IJWrapper", 0, 0); type->Reflection.SetFunctions(2, new uFunction("_GetJavaObject", NULL, NULL, offsetof(IJWrapper, fp__GetJavaObject), false, ::g::Android::Base::Primitives::ujobject_typeof(), 0), new uFunction("_IsSubclassed", NULL, NULL, offsetof(IJWrapper, fp__IsSubclassed), false, ::g::Uno::Bool_typeof(), 0)); return type; } // } // /Users/martinmorales/Library/Application Support/Fusetools/Packages/UnoCore/1.0.11/targets/android/uno/base/$.uno // ----------------------------------------------------------------------------------------------------------------- // public static extern class JavaObjectHelper :1241 // { static void JavaObjectHelper_build(uType* type) { ::STRINGS[0] = uString::Const("JObjectToJWrapper: Unknown unoRef detected: >"); ::STRINGS[1] = uString::Const("<"); ::TYPES[0] = ::g::Uno::Type_typeof(); type->Reflection.SetFunctions(1, new uFunction("JObjectToJWrapper", NULL, (void*)JavaObjectHelper__JObjectToJWrapper_fn, 0, true, ::g::Android::Base::Wrappers::IJWrapper_typeof(), 2, ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Uno::Bool_typeof())); } uClassType* JavaObjectHelper_typeof() { static uSStrong<uClassType*> type; if (type != NULL) return type; uTypeOptions options; options.TypeSize = sizeof(uClassType); type = uClassType::New("Android.Base.Wrappers.JavaObjectHelper", options); type->fp_build_ = JavaObjectHelper_build; return type; } // public static Android.Base.Wrappers.IJWrapper JObjectToJWrapper(Android.Base.Primitives.ujobject tmpRes, bool stackArg) :1244 void JavaObjectHelper__JObjectToJWrapper_fn(jobject* tmpRes, bool* stackArg, uObject** __retval) { *__retval = JavaObjectHelper::JObjectToJWrapper(*tmpRes, *stackArg); } // public static Android.Base.Wrappers.IJWrapper JObjectToJWrapper(Android.Base.Primitives.ujobject tmpRes, bool stackArg) [static] :1244 uObject* JavaObjectHelper::JObjectToJWrapper(jobject tmpRes, bool stackArg) { uStackFrame __("Android.Base.Wrappers.JavaObjectHelper", "JObjectToJWrapper(Android.Base.Primitives.ujobject,bool)"); ::g::Android::Base::JNI::CheckException(); int64_t unoRef = ::g::Android::Base::JNI::GetUnoRef(tmpRes); if (unoRef == 0LL) return NULL; else if (unoRef == -1LL) return (uObject*)::g::Android::Base::Wrappers::JWrapper::New2(tmpRes, ::g::Android::Base::Wrappers::JWrapper_typeof(), false, false, stackArg); else if (unoRef > 0LL) { ::g::Android::Base::Wrappers::JWrapper* res = (::g::Android::Base::Wrappers::JWrapper*)uLoadWeak((uWeakObject*)unoRef); JNIEnv* __cb_jni1 = ::g::Android::Base::JNI::GetEnvPtr(); if (__cb_jni1->GetObjectRefType(tmpRes)==JNILocalRefType && !stackArg) ::g::Android::Base::JNI::DeleteLocalRef1(tmpRes); return (uObject*)res; } else U_THROW(::g::Uno::Exception::New2(::g::Uno::String::op_Addition2(::g::Uno::String::op_Addition1(::STRINGS[0/*"JObjectToJW...*/], uBox<int64_t>(::g::Uno::Long_typeof(), unoRef)), ::STRINGS[1/*"<"*/]))); } // } // /Users/martinmorales/Library/Application Support/Fusetools/Packages/UnoCore/1.0.11/targets/android/uno/base/$.uno // ----------------------------------------------------------------------------------------------------------------- // public extern class JWrapper :1129 // { // ~JWrapper() :1169 static void JWrapper__Finalize_fn(JWrapper* __this) { uStackFrame __("Android.Base.Wrappers.JWrapper", "Finalize()"); __this->Dispose(false); } static void JWrapper_build(uType* type) { type->SetInterfaces( ::g::Android::Base::Wrappers::IJWrapper_typeof(), offsetof(JWrapper_type, interface0), ::g::Uno::IDisposable_typeof(), offsetof(JWrapper_type, interface1)); type->SetFields(0, ::g::Android::Base::Primitives::ujobject_typeof(), offsetof(::g::Android::Base::Wrappers::JWrapper, _javaObject), 0, ::g::Uno::Bool_typeof(), offsetof(::g::Android::Base::Wrappers::JWrapper, _subclassed), 0, ::g::Android::Base::Primitives::uweakptr_typeof(), offsetof(::g::Android::Base::Wrappers::JWrapper, _weakptr), 0, ::g::Uno::Bool_typeof(), offsetof(::g::Android::Base::Wrappers::JWrapper, disposed), 0); type->Reflection.SetFields(2, new uField("_javaObject", 0), new uField("_subclassed", 1)); type->Reflection.SetFunctions(5, new uFunction("_GetJavaObject", NULL, (void*)JWrapper___GetJavaObject_fn, 0, false, ::g::Android::Base::Primitives::ujobject_typeof(), 0), new uFunction("_IsSubclassed", NULL, (void*)JWrapper___IsSubclassed_fn, 0, false, ::g::Uno::Bool_typeof(), 0), new uFunction(".ctor", NULL, (void*)JWrapper__New1_fn, 0, true, type, 4, ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Uno::Type_typeof(), ::g::Uno::Bool_typeof(), ::g::Uno::Bool_typeof()), new uFunction(".ctor", NULL, (void*)JWrapper__New2_fn, 0, true, type, 5, ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Uno::Type_typeof(), ::g::Uno::Bool_typeof(), ::g::Uno::Bool_typeof(), ::g::Uno::Bool_typeof()), new uFunction("Wrap", NULL, (void*)JWrapper__Wrap_fn, 0, true, type, 3, ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Uno::Bool_typeof(), ::g::Uno::Bool_typeof())); } JWrapper_type* JWrapper_typeof() { static uSStrong<JWrapper_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Java::Object_typeof(); options.FieldCount = 4; options.InterfaceCount = 2; options.ObjectSize = sizeof(JWrapper); options.TypeSize = sizeof(JWrapper_type); type = (JWrapper_type*)uClassType::New("Android.Base.Wrappers.JWrapper", options); type->fp_build_ = JWrapper_build; type->fp_Finalize = (void(*)(uObject*))JWrapper__Finalize_fn; type->interface1.fp_Dispose = (void(*)(uObject*))JWrapper__UnoIDisposableDispose_fn; type->interface0.fp__GetJavaObject = (void(*)(uObject*, jobject*))JWrapper___GetJavaObject_fn; type->interface0.fp__IsSubclassed = (void(*)(uObject*, bool*))JWrapper___IsSubclassed_fn; return type; } // public JWrapper(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType) :1159 void JWrapper__ctor_1_fn(JWrapper* __this, jobject* obj, uType* typePtr, bool* typeHasFallbackClass, bool* resolveType) { __this->ctor_1(*obj, typePtr, *typeHasFallbackClass, *resolveType); } // public JWrapper(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType, bool stackArg) :1162 void JWrapper__ctor_2_fn(JWrapper* __this, jobject* obj, uType* typePtr, bool* typeHasFallbackClass, bool* resolveType, bool* stackArg) { __this->ctor_2(*obj, typePtr, *typeHasFallbackClass, *resolveType, *stackArg); } // protected extern void _DisposeJavaObject() :1217 void JWrapper___DisposeJavaObject_fn(JWrapper* __this) { __this->_DisposeJavaObject(); } // public Android.Base.Primitives.ujobject _GetJavaObject() :1189 void JWrapper___GetJavaObject_fn(JWrapper* __this, jobject* __retval) { *__retval = __this->_GetJavaObject(); } // public bool _IsSubclassed() :1194 void JWrapper___IsSubclassed_fn(JWrapper* __this, bool* __retval) { *__retval = __this->_IsSubclassed(); } // protected void Dispose(bool disposing) :1204 void JWrapper__Dispose_fn(JWrapper* __this, bool* disposing) { __this->Dispose(*disposing); } // public JWrapper New(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType) :1159 void JWrapper__New1_fn(jobject* obj, uType* typePtr, bool* typeHasFallbackClass, bool* resolveType, JWrapper** __retval) { *__retval = JWrapper::New1(*obj, typePtr, *typeHasFallbackClass, *resolveType); } // public JWrapper New(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType, bool stackArg) :1162 void JWrapper__New2_fn(jobject* obj, uType* typePtr, bool* typeHasFallbackClass, bool* resolveType, bool* stackArg, JWrapper** __retval) { *__retval = JWrapper::New2(*obj, typePtr, *typeHasFallbackClass, *resolveType, *stackArg); } // private void SetInternalObj(Android.Base.Primitives.ujobject obj, bool stackArg) :1142 void JWrapper__SetInternalObj_fn(JWrapper* __this, jobject* obj, bool* stackArg) { __this->SetInternalObj(*obj, *stackArg); } // private void Uno.IDisposable.Dispose() :1199 void JWrapper__UnoIDisposableDispose_fn(JWrapper* __this) { uStackFrame __("Android.Base.Wrappers.JWrapper", "Uno.IDisposable.Dispose()"); __this->Dispose(true); } // public static Android.Base.Wrappers.JWrapper Wrap(Android.Base.Primitives.ujobject obj, [bool resolveType], [bool typeHasFallbackClass]) :1174 void JWrapper__Wrap_fn(jobject* obj, bool* resolveType, bool* typeHasFallbackClass, JWrapper** __retval) { *__retval = JWrapper::Wrap(*obj, *resolveType, *typeHasFallbackClass); } // public JWrapper(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType) [instance] :1159 void JWrapper::ctor_1(jobject obj, uType* typePtr, bool typeHasFallbackClass, bool resolveType) { ctor_2(obj, typePtr, typeHasFallbackClass, resolveType, false); } // public JWrapper(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType, bool stackArg) [instance] :1162 void JWrapper::ctor_2(jobject obj, uType* typePtr, bool typeHasFallbackClass, bool resolveType, bool stackArg) { ctor_(); this->_weakptr = 0; ::g::Android::Base::Types::Bridge::SetWrapperType(this, obj, typePtr, typeHasFallbackClass, resolveType); SetInternalObj(obj, stackArg); } // protected extern void _DisposeJavaObject() [instance] :1217 void JWrapper::_DisposeJavaObject() { if (!this->_javaObject) return; ::g::Android::Base::JNI::DeleteGlobalRef(this->_javaObject); this->_javaObject = 0; } // public Android.Base.Primitives.ujobject _GetJavaObject() [instance] :1189 jobject JWrapper::_GetJavaObject() { return _javaObject; } // public bool _IsSubclassed() [instance] :1194 bool JWrapper::_IsSubclassed() { return _subclassed; } // protected void Dispose(bool disposing) [instance] :1204 void JWrapper::Dispose(bool disposing) { bool disposing_ = disposing; if (!disposed) { if (disposing_) _DisposeJavaObject(); disposed = true; } } // private void SetInternalObj(Android.Base.Primitives.ujobject obj, bool stackArg) [instance] :1142 void JWrapper::SetInternalObj(jobject obj, bool stackArg) { if (!__JWrapper_Callbacks_Registered) { __JWrapper_Callbacks_Registered = true; __Register_Finalizer(); } if (!_weakptr) { uStoreWeak(&_weakptr, this); uWeakStateIntercept::SetCallback(_weakptr, (uWeakStateIntercept::Callback)__JWrapper_WeakCallback); } if (obj) { _javaObject = ::g::Android::Base::JNI::NewGlobalRef1(obj); if (!stackArg && (::g::Android::Base::JNI::GetRefType1(obj) == 1)) ::g::Android::Base::JNI::DeleteLocalRef1(obj); } } // public JWrapper New(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType) [static] :1159 JWrapper* JWrapper::New1(jobject obj, uType* typePtr, bool typeHasFallbackClass, bool resolveType) { JWrapper* obj1 = (JWrapper*)uNew(JWrapper_typeof()); obj1->ctor_1(obj, typePtr, typeHasFallbackClass, resolveType); return obj1; } // public JWrapper New(Android.Base.Primitives.ujobject obj, Uno.Type typePtr, bool typeHasFallbackClass, bool resolveType, bool stackArg) [static] :1162 JWrapper* JWrapper::New2(jobject obj, uType* typePtr, bool typeHasFallbackClass, bool resolveType, bool stackArg) { JWrapper* obj2 = (JWrapper*)uNew(JWrapper_typeof()); obj2->ctor_2(obj, typePtr, typeHasFallbackClass, resolveType, stackArg); return obj2; } // public static Android.Base.Wrappers.JWrapper Wrap(Android.Base.Primitives.ujobject obj, [bool resolveType], [bool typeHasFallbackClass]) [static] :1174 JWrapper* JWrapper::Wrap(jobject obj, bool resolveType, bool typeHasFallbackClass) { return JWrapper::New1(obj, NULL, typeHasFallbackClass, resolveType); } // } }}}} // ::g::Android::Base::Wrappers
4d9e06470628589389922412b05719fcf16cd32e
84f3b7fb34523f418aa0c4372d006357579e26f3
/Classes/Friends/AddFriendScene.h
34e086de2f06e874c5f9265b8791034cafb651db
[]
no_license
webhunter/iGame
eac188f98945f90c39743a3ce2007442f7886074
b42194309adc3d40d374ca2ee0a741ebcd672dd5
refs/heads/master
2020-12-01T01:07:48.362183
2013-06-09T15:01:19
2013-06-09T15:01:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,734
h
#ifndef __ADDFRIENDSCENE_SCENE_H__ #define __ADDFRIENDSCENE_SCENE_H__ #include "cocos2d.h" #include "cocos-ext.h" #include "SimpleAudioEngine.h" #include "XmlParser.h" #include "MainGameScene.h" #include "MainSceneTemplate.h" #include "common.h" #include "StringExt.h" using namespace cocos2d; using namespace cocos2d::extension; class AddFriendScene : public MainLayerBase, public CCTableViewDataSource, public CCTableViewDelegate, public CCBSelectorResolver, public CCNodeLoaderListener, public CCBMemberVariableAssigner, public CCMessageDialogDelegate { public: AddFriendScene(); ~AddFriendScene(); // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // there's no 'id' in cpp, so we recommand to return the exactly class pointer static cocos2d::CCScene* scene(); // a selector callback void requestFinishedCallback(CCNode* pSender,void *p); void doSearchFriend(); void addFriendRequest(std::string &userinfo); CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(AddFriendScene, create); void buttonClicked(CCObject *pSender,CCControlEvent event); void toolBarTouchDownAction(CCObject *pSender, CCControlEvent pCCControlEvent); virtual SEL_MenuHandler onResolveCCBCCMenuItemSelector(CCObject * pTarget, const char* pSelectorName); virtual SEL_CCControlHandler onResolveCCBCCControlSelector(cocos2d::CCObject * pTarget, const char * pSelectorName); virtual bool onAssignCCBMemberVariable(CCObject* pTarget, const char* pMemberVariableName, CCNode* pNode); virtual void onNodeLoaded(CCNode * pNode, CCNodeLoader * pNodeLoader); virtual void scrollViewDidScroll(cocos2d::extension::CCScrollView* view) {}; virtual void scrollViewDidZoom(cocos2d::extension::CCScrollView* view) {} virtual void tableCellTouched(cocos2d::extension::CCTableView* table, CCTableViewCell* cell); virtual cocos2d::CCSize cellSizeForTable(cocos2d::extension::CCTableView *table); virtual CCTableViewCell* tableCellAtIndex(cocos2d::extension::CCTableView *table, unsigned int idx); virtual unsigned int numberOfCellsInTableView(CCTableView *table); virtual bool hasFixedCellSize(); virtual CCSize cellSizeForIndex(CCTableView *table, unsigned int idx); virtual void tableCellHighlight(CCTableView* table, CCTableViewCell* cell); virtual void tableCellUnhighlight(CCTableView* table, CCTableViewCell* cell); virtual void didClickButton(CCMessageDialog* dialog,unsigned int index); CCEditBox *m_txtSearchField; CCTableView* mTableViewFriend; unsigned int selectedindex; CCArray *mFriendList; }; #endif // __LOGINSCENE_SCENE_H__
7611bed6214e36fff6d832e562ca0eb95f036737
af1745bc13434dc830dc4b4b953a702478a30159
/src/engine/window.hpp
302c64bfdac3a19f6de49952f73d6c02c4e22f27
[]
no_license
rbnelr/voxel_game
79cabd92a8e8ff078c8bbcdd3ecf16daaa3675ba
203400c740a8e97fea80a32a282462ca98d6b632
refs/heads/master
2022-05-26T03:38:25.908930
2022-04-13T17:05:05
2022-04-13T17:05:11
119,690,474
7
0
null
null
null
null
UTF-8
C++
false
false
1,099
hpp
#pragma once #include "common.hpp" #include "input.hpp" #include "game.hpp" #include "renderer.hpp" struct Rect { int2 pos; int2 dim; }; struct GLFWwindow; struct Window { GLFWwindow* window = nullptr; Input input; bool fullscreen = false; // readonly bool borderless_fullscreen = true; // readonly, use borderless fullscreen as long as the cpu usage (gpu driver?) bug happens on my dev desktop Rect window_pos; int frame_counter = 0; std::unique_ptr<Game> game; RenderBackend render_backend = RenderBackend::OPENGL; bool switch_render_backend = false; std::unique_ptr<Renderer> renderer; DirectoyChangeNotifier file_changes = DirectoyChangeNotifier("./", true); bool switch_fullscreen (bool fullscreen, bool borderless_fullscreen); bool toggle_fullscreen (); // close down game after current frame void close (); void open_window (); void close_window (); void switch_renderer (); void run (); }; inline Window g_window; // global window, needed to allow Logger to be global, which needs frame_counter, prefer to pass window along if possible
723d7cba822a30bb51889520d85233d05d731be0
b4ef2184c6a2d26abaffe62c57686089ee71f429
/src/wifiserver.h
24eddefc325ae72e579881a53a6a2872ac6cd93c
[]
no_license
philip-w-howard/AgDrone
69a6f5c4ac1a8a9a00ec335d99f2559e99405b4d
901ab34f07ac0c939692534a6245faf1800ce3ea
refs/heads/master
2020-04-03T22:38:10.173784
2016-09-20T02:33:31
2016-09-20T02:33:31
39,169,876
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
/* * wifiserver.h * * Created on: Jul 23, 2015 * Author: philhow */ #pragma once #include "queue.h" #include "connection.h" class WifiServerConnection : public Connection { public: WifiServerConnection(queue_t *destQueue, int port); virtual ~WifiServerConnection(); virtual bool MakeConnection(); virtual void Disconnect(); virtual bool IsConnected(); protected: int mPort; bool mIsConnected; int mListenerFd; };
5da4e794ed165687cb4b10a9a3c1afade510b7c3
900589f74fee54e82ccff89cb25bb3ebed2f7afa
/Lab04/control_panel.h
d268d2f6d0dcaccb7dbdd54a716ff0881145c49c
[]
no_license
maxhha/bmstu-iu7-oop
896c3a3062648beae37fa106b0f62f32c0cc71c9
b8ba2507d81a183300337ca6d4733fd8257e84db
refs/heads/main
2023-06-03T10:59:01.090823
2021-06-18T15:46:04
2021-06-18T15:46:04
378,197,923
0
0
null
null
null
null
UTF-8
C++
false
false
575
h
#pragma once #include <QObject> #include <QVector> #include <constants.h> class ControlPanel : public QObject { Q_OBJECT enum panel_state { WATCH, WAIT }; public: explicit ControlPanel(QObject *parent = nullptr); void set_new_target(int floor); signals: void set_target(int floor, direction dir); public slots: void reach_floor(); void pass_floor(int floor); private: int cur_floor; int cur_target = -1; QVector<bool> is_target; panel_state current_state; direction cur_direction; bool next_target(int &floor); void find_new_target(); };
e850579554aaffec4ff100774a7ee2ac8e9c584c
d6421ed193d3ae11599b45d028ad372e63fa77fa
/Neural Network Testing/main.cpp
db2d2003fb041430ac6dbbcdc407edd359bd6236
[]
no_license
jchen187/Neural-Network-Testing
d30810ef245f5ce502b67bff6755f8e50bbc5ab0
13af0a76fe640e7be758fc10daaab61fe405a301
refs/heads/master
2021-01-10T08:54:48.085475
2015-12-12T18:33:10
2015-12-12T18:33:10
47,841,984
0
0
null
null
null
null
UTF-8
C++
false
false
12,513
cpp
// // main.cpp // Neural Network Testing // // Created by Johnny Chen on 12/9/15. // Copyright (c) 2015 JohnnyChen. All rights reserved. // #include <iostream> #include <fstream> //reading from file #include <vector> #include <math.h> //to use the activation function because we need e #include <iomanip> //for 3 decimal places using namespace std; string file1, file2, file3; //double microA = 0, microB = 0, microC = 0, microD = 0; //double overallAccuracy = 0, precision = 0, recall = 0, f1 = 0; //each output will have their own A,B,C,D, accurary ... vector<double> A, B, C, D; vector<double> overallAccuracy, precision, recall, f1; double microAccuracy = 0, microPrecision = 0, microRecall = 0, microf1 = 0; double macroAccuracy = 0, macroPrecision = 0, macroRecall = 0, macrof1 = 0; //from the first file int inputNodes, hiddenNodes, outputNodes; vector<vector<double>> weightsToHidden; vector<vector<double>> weightsToOutput; vector<vector<double>> network; //from the 2nd file int numTrainingExamples, inputs, outputs; vector<vector<double>> exampleInputs; vector<vector<double>> exampleOutputs; //0 or 1 vector<vector<double>> examples; void readFromFile1(string name); void readFromFile2(string name); void writeMetricsToFile(string name); void calculateMetrics(vector<vector<double>> examples, vector<vector<double>> network); int main(int argc, const char * argv[]) { cout << "Please enter the file containing the neural network\n"; //read the file cin >> file1; // file1 = "1neuralNetwork.txt"; // file1 = "2gradesNN.txt"; // file1 = "MINE_1results.txt"; readFromFile1(file1); network.reserve( weightsToHidden.size() + weightsToOutput.size() ); // preallocate memory network.insert( network.end(), weightsToHidden.begin(), weightsToHidden.end() ); network.insert( network.end(), weightsToOutput.begin(), weightsToOutput.end() ); cout << "Please enter the file containing the test set.\n"; cin >> file2; // readFromFile2(file2); // file2 = "1testingExamples.txt"; // file2 = "2gradesTrainingExamples.txt"; // file2 = "MINE_2testExamples.txt"; readFromFile2(file2); examples.reserve( exampleInputs.size() + exampleOutputs.size() ); // preallocate memory examples.insert( examples.end(), exampleInputs.begin(), exampleInputs.end() ); examples.insert( examples.end(), exampleOutputs.begin(), exampleOutputs.end() ); cout << "Where would you like to output the results to?\n"; cin >> file3; // file3 = "1compareToTestResults.txt"; // file3 = "2compareToGradesResults.txt"; // file3 = "MINE_2finalResults.txt"; A.resize(outputNodes); B.resize(outputNodes); C.resize(outputNodes); D.resize(outputNodes); overallAccuracy.resize(outputNodes); precision.resize(outputNodes); recall.resize(outputNodes); f1.resize(outputNodes); calculateMetrics(examples, network); writeMetricsToFile(file3); return 0; } void readFromFile1(string name){ /* 1st line has 3 integers - number of input nodes - number of hidden nodes - number of output nodes Next Nh lines each has Ni + 1 weights entering the 1st hidden node, then 2nd ... until Nh There is a +1 because a bias weight which is always the first weight Weights are doubleing point numbers Next No has Nh + 1 weights */ ifstream myFile; myFile.open(file1); if (myFile.is_open()){ //Put contents of file into array for (int i = 0; i <= 3; i++){ if (i == 0) myFile >> inputNodes; if (i == 1) myFile >> hiddenNodes; if (i == 2){ myFile >> outputNodes; } } weightsToHidden.resize(hiddenNodes); for (int j = 0; j < hiddenNodes; j++){ weightsToHidden[j].resize(inputNodes+1); for (int m = 0; m <= inputNodes; m++){ // cout << "j = " << j << "m = " << m << endl; myFile >> weightsToHidden[j][m]; } } weightsToOutput.resize(outputNodes); for (int k = 0; k < outputNodes; k++){ weightsToOutput[k].resize(hiddenNodes+1); for (int n = 0; n <= hiddenNodes; n++){ myFile >> weightsToOutput[k][n]; } } myFile.close(); } else cout << "Unable to open file.\n"; } //training examples to train void readFromFile2(string name){ /* 1st line has 3 integers - number of training examples - number of input nodes(will match file1) - number of output nodes(will match file1) every other line is an example - Ni doubleing point inputs - No Boolean output(0 or 1) */ ifstream myFile; myFile.open(file2); if (myFile.is_open()){ //Put contents of file into array for (int i = 0; i <= 3; i++){ if (i == 0) myFile >> numTrainingExamples; if (i == 1) myFile >> inputs; if (i == 2){ myFile >> outputs; } } if (inputs != inputNodes || outputs != outputNodes){ cout << "The input and output values do not match the initial neural network."; } else{ int sum = inputs + outputs; exampleInputs.resize(numTrainingExamples); exampleOutputs.resize(numTrainingExamples); //go through each line one at a time, put the stuff in a vector, and do the backprop for (int i = 0; i < numTrainingExamples; i++){ exampleInputs[i].resize(inputs); exampleOutputs[i].resize(outputs); for (int j = 0; j < sum; j++){ if (j < inputs){ myFile >> exampleInputs[i][j]; } else { myFile >> exampleOutputs[i][j-inputs]; } } } myFile.close(); } } else cout << "Unable to open file.\n"; } double applyActivFunct(double x){ double result = 1/(1+exp(-1*x)); return result; } double applyDerivActivFunct(double x){ double result = applyActivFunct(x) * (1 - applyActivFunct(x));; return result; } //given return a neural network and the examples, return a neural network //examples include both input and output examples. same with network. contains first weight from input to hidden node, then hidden node to output void calculateMetrics(vector<vector<double>> examples, vector<vector<double>> network){ //error for both outlayer and hiddenlayer vector<vector<double>> errors; errors.resize(2); errors[0].resize(outputNodes); errors[1].resize(hiddenNodes); //go through each example in examples //you could do numTrainingExamples or you can do the exampleInputs.size() for (int i = 0; i < numTrainingExamples; i++){ //base will contain all the example inputs vector<double> base = examples[i]; //propagate the inputs forward to compute the outputs vector<double> middle; middle.resize(hiddenNodes); //loop through each hidden node for (int j = 0; j < hiddenNodes; j++){ double result = 0; //get contribution from each node from previous layer for (int k = 0; k < inputNodes+1; k++){ //for the first weight, multiply by the fixed input -1 if (k == 0){ result += -1 * network[j][0]; } else { //network has the bias weight at the beginning and is ahead of the example/base result += network[j][k] * base[k-1]; } } middle[j] = result; } //output vector<double> top; top.resize(outputNodes); for (int j = 0; j < outputNodes; j++){ double result = 0; for (int k = 0; k < hiddenNodes+1; k++){ if (k == 0){ result += -1 * network[hiddenNodes+j][0]; } else { result += network[hiddenNodes+j][k] * applyActivFunct(middle[k-1]); } } top[j] = result; } for (int j = 0; j < outputNodes; j++){ //the activation of output nodes should be rounded to 1 or 0 double actualOutput = (applyActivFunct(top[j]) >= 0.5) ? 1 : 0; // cout << "actual: " << actualOutput; //compare the actual output with the expected output from the training set(examples) double expectedOutput = examples[numTrainingExamples+i][j]; // cout << " expected: " << expectedOutput; // if (actualOutput != expectedOutput){ // cout << "not equal"; // } // cout << "\n"; //YOU TAKE THE OUTPUT FROM THE EXAMPLE FILE AND YOU COMPARE WITH THE RESULT YOU GET FROM TAKING THE INPUT AND PROPAGATING IT FORWARD //based on the contingency table if (actualOutput == 1 && expectedOutput == 1){ A[j]++; } else if (actualOutput == 1 && expectedOutput == 0){ B[j]++; } else if (actualOutput == 0 && expectedOutput == 1){ C[j]++; } else if (actualOutput == 0 && expectedOutput == 0){ D[j]++; } } for (int j = 0; j < outputNodes; j++){ overallAccuracy[j] = (A[j]+D[j])/(A[j]+B[j]+C[j]+D[j]); precision[j] = A[j]/(A[j]+B[j]); recall[j] = A[j]/(A[j]+C[j]); f1[j] = (2*precision[j]*recall[j])/(precision[j]+recall[j]); } } //MICRO double totalA, totalB, totalC, totalD; //add up all As/output for (int i = 0; i < outputNodes;i++){ totalA += A[i]; totalB += B[i]; totalC += C[i]; totalD += D[i]; } microAccuracy = (totalA+totalD)/(totalA+totalB+totalC+totalD); microPrecision = totalA/(totalA+totalB); microRecall = totalA/(totalA+totalC); microf1 = (2*microPrecision*microRecall)/(microPrecision+microRecall); //MACRO //add up all the Accuracy/outputNode to get micro for (int i = 0; i < outputNodes; i++){ macroAccuracy += overallAccuracy[i]; macroPrecision += precision[i]; macroRecall += recall[i]; } macroAccuracy /= outputNodes; macroPrecision /= outputNodes; macroRecall /= outputNodes; macrof1 = (2*macroPrecision*macroRecall)/(macroPrecision+macroRecall); //will have a value in between the microPrecision and microRecall, closer to the lower of the two // cout << overallAccuracy << endl; // cout << precision << endl; // cout << recall << endl;; // cout << f1 << endl; } void writeMetricsToFile(string name){ ofstream myfile; myfile.open (name); if (myfile.is_open()) { for (int i = 0; i < outputNodes + 2; i++){ if (i < outputNodes){ //the two ways below work. you can cast the doubles to ints or just use seetprecision to not show the trailing 0s // myfile << (int)A[i] << " " << (int)B[i] << " " << (int)C[i] << " " << (int)D[i] << " "; myfile << fixed << setprecision(0) << A[i] << " " << B[i] << " " << C[i] << " " << D[i] << " "; //metrics from ABCD myfile << fixed << setprecision(3) <<overallAccuracy[i] << " " << precision[i] << " " << recall[i] << " " << f1[i]; } else if (i == outputNodes){ //micro myfile << fixed << setprecision(3) << microAccuracy << " " << microPrecision << " " << microRecall << " " << microf1; } else if (i == outputNodes + 1){ //macro myfile << fixed << setprecision(3) << macroAccuracy << " " << macroPrecision << " " << macroRecall << " " << macrof1; } myfile << "\n"; } myfile.close(); } else cout << "Unable to open file"; }
f3aba3d362b7d33fad910e579e6a11d07257c287
d04b59d89ded86b1f9c7a1a34798cd359fbe7045
/box2d.cc
6bd839f1de5426c2003e6a0a4447dbb25e914076
[ "MIT" ]
permissive
scamara-clgx/php7-mapnik
004ed526bae098ef38fa4c6a822f2869b5a0b39a
14c4d7d3ad4a040967530242c3905472126a62ac
refs/heads/master
2020-04-02T19:31:02.518552
2018-05-15T16:30:42
2018-05-15T16:30:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,154
cc
#include "php.h" #include "exception.h" #include "box2d.h" #include <mapnik/box2d.hpp> zend_class_entry *php_mapnik_box2d_ce; zend_object_handlers php_mapnik_box2d_object_handlers; // PHP object handling void php_mapnik_box2d_free_storage(zend_object *object TSRMLS_DC) { php_mapnik_box2d_object *obj; obj = php_mapnik_box2d_fetch_object(object); delete obj->box2d; zend_object_std_dtor(object TSRMLS_DC); } zend_object * php_mapnik_box2d_new(zend_class_entry *ce TSRMLS_DC) { // Allocate sizeof(custom) + sizeof(properties table requirements) php_mapnik_box2d_object *intern; intern = (php_mapnik_box2d_object*) ecalloc(1, sizeof(php_mapnik_box2d_object) + zend_object_properties_size(ce)); zend_object_std_init(&intern->std, ce TSRMLS_CC); object_properties_init(&intern->std, ce); intern->std.handlers = &php_mapnik_box2d_object_handlers; return &intern->std; } // Class methods PHP_METHOD(Box2D, __construct) { php_mapnik_box2d_object *obj; mapnik::box2d<double> *box2d = NULL; double minX, minY, maxX, maxY; if (ZEND_NUM_ARGS() == 0) { box2d = new mapnik::box2d<double>(); } else if (::zend_parse_parameters_ex( ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "dddd", &minX, &minY, &maxX, &maxY) == SUCCESS ) { box2d = new mapnik::box2d<double>(minX, minY, maxX, maxY); } else { php_mapnik_throw_exception("Wrong arguments passed to \\Mapnik\\Box2D::__construct"); } obj = Z_PHP_MAPNIK_BOX2D_P(getThis()); obj->box2d = box2d; } PHP_METHOD(Box2D, minX) { php_mapnik_box2d_object *obj = Z_PHP_MAPNIK_BOX2D_P(getThis()); RETURN_DOUBLE(obj->box2d->minx()); } PHP_METHOD(Box2D, minY) { php_mapnik_box2d_object *obj = Z_PHP_MAPNIK_BOX2D_P(getThis()); RETURN_DOUBLE(obj->box2d->miny()); } PHP_METHOD(Box2D, maxX) { php_mapnik_box2d_object *obj = Z_PHP_MAPNIK_BOX2D_P(getThis()); RETURN_DOUBLE(obj->box2d->maxx()); } PHP_METHOD(Box2D, maxY) { php_mapnik_box2d_object *obj = Z_PHP_MAPNIK_BOX2D_P(getThis()); RETURN_DOUBLE(obj->box2d->maxy()); } // Register methods zend_function_entry php_mapnik_box2d_methods[] = { PHP_ME(Box2D, __construct, NULL, ZEND_ACC_PUBLIC) PHP_ME(Box2D, minX, NULL, ZEND_ACC_PUBLIC) PHP_ME(Box2D, minY, NULL, ZEND_ACC_PUBLIC) PHP_ME(Box2D, maxX, NULL, ZEND_ACC_PUBLIC) PHP_ME(Box2D, maxY, NULL, ZEND_ACC_PUBLIC) { NULL, NULL, NULL } }; // Extension class startup void php_mapnik_box2d_startup(INIT_FUNC_ARGS) { zend_class_entry ce; INIT_NS_CLASS_ENTRY(ce, "Mapnik", "Box2D", php_mapnik_box2d_methods); php_mapnik_box2d_ce = zend_register_internal_class(&ce TSRMLS_CC); php_mapnik_box2d_ce->create_object = php_mapnik_box2d_new; memcpy(&php_mapnik_box2d_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); php_mapnik_box2d_object_handlers.offset = XtOffsetOf(struct php_mapnik_box2d_object, std); php_mapnik_box2d_object_handlers.free_obj = &php_mapnik_box2d_free_storage; php_mapnik_box2d_object_handlers.clone_obj = NULL; }
32ab584a835d5ac05b969e616941f750234bc47f
df64220046dd199d0c71aca4da3174e7f6f488d7
/themaze/src/3DMath.cpp
8853b8955eff79dc2144eea4e1f71c2198b7085b
[]
no_license
BackupTheBerlios/themaze
307f6ceaf3139c2f0456b18bc3933ec31dc500ea
4f8ed94a22d792db12e511eb5a3da0afcdb19628
refs/heads/master
2020-06-06T13:37:57.116072
2003-12-11T10:25:31
2003-12-11T10:25:31
40,318,228
0
0
null
null
null
null
UTF-8
C++
false
false
24,965
cpp
/*-------------extracted from a DigiBen tutorial -----------------------------*/ //***********************************************************************// // // // - "Talk to me like I'm a 3 year old!" Programming Lessons - // // // // $Author: DigiBen [email protected] // // // // $Program: CameraWorldCollision // // // // $Description: Shows how to check if camera and world collide // // // // $Date: 1/23/02 // // // //***********************************************************************// #include "main.h" #include <math.h> // We include math.h so we can use the sqrt() function #include <float.h> // This is so we can use _isnan() for acos() /////////////////////////////////////// ABSOLUTE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the absolute value of the number passed in ///// /////////////////////////////////////// ABSOLUTE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* float Absolute(float num) { // If num is less than zero, we want to return the absolute value of num. // This is simple, either we times num by -1 or subtract it from 0. if(num < 0) return (0 - num); // Return the original number because it was already positive return num; } /////////////////////////////////////// CROSS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns a perpendicular vector from 2 given vectors by taking the cross product. ///// /////////////////////////////////////// CROSS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* CVector3 Cross(CVector3 vVector1, CVector3 vVector2) { CVector3 vNormal; // The vector to hold the cross product // The X value for the vector is: (V1.y * V2.z) - (V1.z * V2.y) // Get the X value vNormal.x = ((vVector1.y * vVector2.z) - (vVector1.z * vVector2.y)); // The Y value for the vector is: (V1.z * V2.x) - (V1.x * V2.z) vNormal.y = ((vVector1.z * vVector2.x) - (vVector1.x * vVector2.z)); // The Z value for the vector is: (V1.x * V2.y) - (V1.y * V2.x) vNormal.z = ((vVector1.x * vVector2.y) - (vVector1.y * vVector2.x)); return vNormal; // Return the cross product (Direction the polygon is facing - Normal) } /////////////////////////////////////// MAGNITUDE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the magnitude of a normal (or any other vector) ///// /////////////////////////////////////// MAGNITUDE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* float Magnitude(CVector3 vNormal) { // This will give us the magnitude or "Norm" as some say, of our normal. // Here is the equation: magnitude = sqrt(V.x^2 + V.y^2 + V.z^2) Where V is the vector return (float)sqrt( (vNormal.x * vNormal.x) + (vNormal.y * vNormal.y) + (vNormal.z * vNormal.z) ); } /////////////////////////////////////// NORMALIZE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns a normalize vector (A vector exactly of length 1) ///// /////////////////////////////////////// NORMALIZE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* CVector3 Normalize(CVector3 vNormal) { float magnitude = Magnitude(vNormal); // Get the magnitude of our normal // Now that we have the magnitude, we can divide our normal by that magnitude. // That will make our normal a total length of 1. This makes it easier to work with too. vNormal.x /= magnitude; // Divide the X value of our normal by it's magnitude vNormal.y /= magnitude; // Divide the Y value of our normal by it's magnitude vNormal.z /= magnitude; // Divide the Z value of our normal by it's magnitude // Finally, return our normalized normal. return vNormal; // Return the new normal of length 1. } /////////////////////////////////////// NORMAL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the normal of a polygon (The direction the polygon is facing) ///// /////////////////////////////////////// NORMAL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* CVector3 Normal(CVector3 vPolygon[]) { // Get 2 vectors from the polygon (2 sides), Remember the order! CVector3 vVector1 = vPolygon[2] - vPolygon[0]; CVector3 vVector2 = vPolygon[1] - vPolygon[0]; CVector3 vNormal = Cross(vVector1, vVector2); // Take the cross product of our 2 vectors to get a perpendicular vector // Now we have a normal, but it's at a strange length, so let's make it length 1. vNormal = Normalize(vNormal); // Use our function we created to normalize the normal (Makes it a length of one) return vNormal; // Return our normal at our desired length } /////////////////////////////////// DISTANCE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the distance between 2 3D points ///// /////////////////////////////////// DISTANCE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* float Distance(CVector3 vPoint1, CVector3 vPoint2) { // This is the classic formula used in beginning algebra to return the // distance between 2 points. Since it's 3D, we just add the z dimension: // // Distance = sqrt( (P2.x - P1.x)^2 + (P2.y - P1.y)^2 + (P2.z - P1.z)^2 ) // double distance = sqrt( (vPoint2.x - vPoint1.x) * (vPoint2.x - vPoint1.x) + (vPoint2.y - vPoint1.y) * (vPoint2.y - vPoint1.y) + (vPoint2.z - vPoint1.z) * (vPoint2.z - vPoint1.z) ); // Return the distance between the 2 points return (float)distance; } ////////////////////////////// CLOSEST POINT ON LINE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the point on the line vA_vB that is closest to the point vPoint ///// ////////////////////////////// CLOSEST POINT ON LINE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* CVector3 ClosestPointOnLine(CVector3 vA, CVector3 vB, CVector3 vPoint) { // Create the vector from end point vA to our point vPoint. CVector3 vVector1 = vPoint - vA; // Create a normalized direction vector from end point vA to end point vB CVector3 vVector2 = Normalize(vB - vA); // Use the distance formula to find the distance of the line segment (or magnitude) float d = Distance(vA, vB); // Using the dot product, we project the vVector1 onto the vector vVector2. // This essentially gives us the distance from our projected vector from vA. float t = Dot(vVector2, vVector1); // If our projected distance from vA, "t", is less than or equal to 0, it must // be closest to the end point vA. We want to return this end point. if (t <= 0) return vA; // If our projected distance from vA, "t", is greater than or equal to the magnitude // or distance of the line segment, it must be closest to the end point vB. So, return vB. if (t >= d) return vB; // Here we create a vector that is of length t and in the direction of vVector2 CVector3 vVector3 = vVector2 * t; // To find the closest point on the line segment, we just add vVector3 to the original // end point vA. CVector3 vClosestPoint = vA + vVector3; // Return the closest point on the line segment return vClosestPoint; } /////////////////////////////////// PLANE DISTANCE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the distance between a plane and the origin ///// /////////////////////////////////// PLANE DISTANCE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* float PlaneDistance(CVector3 Normal, CVector3 Point) { float distance = 0; // This variable holds the distance from the plane tot he origin // Use the plane equation to find the distance (Ax + By + Cz + D = 0) We want to find D. // So, we come up with D = -(Ax + By + Cz) // Basically, the negated dot product of the normal of the plane and the point. (More about the dot product in another tutorial) distance = - ((Normal.x * Point.x) + (Normal.y * Point.y) + (Normal.z * Point.z)); return distance; // Return the distance } /////////////////////////////////// INTERSECTED PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This checks to see if a line intersects a plane ///// /////////////////////////////////// INTERSECTED PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* bool IntersectedPlane(CVector3 vPoly[], CVector3 vLine[], CVector3 &vNormal, float &originDistance) { float distance1=0, distance2=0; // The distances from the 2 points of the line from the plane vNormal = Normal(vPoly); // We need to get the normal of our plane to go any further // Let's find the distance our plane is from the origin. We can find this value // from the normal to the plane (polygon) and any point that lies on that plane (Any vertex) originDistance = PlaneDistance(vNormal, vPoly[0]); // Get the distance from point1 from the plane using: Ax + By + Cz + D = (The distance from the plane) distance1 = ((vNormal.x * vLine[0].x) + // Ax + (vNormal.y * vLine[0].y) + // Bx + (vNormal.z * vLine[0].z)) + originDistance; // Cz + D // Get the distance from point2 from the plane using Ax + By + Cz + D = (The distance from the plane) distance2 = ((vNormal.x * vLine[1].x) + // Ax + (vNormal.y * vLine[1].y) + // Bx + (vNormal.z * vLine[1].z)) + originDistance; // Cz + D // Now that we have 2 distances from the plane, if we times them together we either // get a positive or negative number. If it's a negative number, that means we collided! // This is because the 2 points must be on either side of the plane (IE. -1 * 1 = -1). if(distance1 * distance2 >= 0) // Check to see if both point's distances are both negative or both positive return false; // Return false if each point has the same sign. -1 and 1 would mean each point is on either side of the plane. -1 -2 or 3 4 wouldn't... return true; // The line intersected the plane, Return TRUE } /////////////////////////////////// DOT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This computers the dot product of 2 vectors ///// /////////////////////////////////// DOT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* float Dot(CVector3 vVector1, CVector3 vVector2) { // The dot product is this equation: V1.V2 = (V1.x * V2.x + V1.y * V2.y + V1.z * V2.z) // In math terms, it looks like this: V1.V2 = ||V1|| ||V2|| cos(theta) // (V1.x * V2.x + V1.y * V2.y + V1.z * V2.z) return ( (vVector1.x * vVector2.x) + (vVector1.y * vVector2.y) + (vVector1.z * vVector2.z) ); } /////////////////////////////////// ANGLE BETWEEN VECTORS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This checks to see if a point is inside the ranges of a polygon ///// /////////////////////////////////// ANGLE BETWEEN VECTORS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* double AngleBetweenVectors(CVector3 Vector1, CVector3 Vector2) { // Get the dot product of the vectors float dotProduct = Dot(Vector1, Vector2); // Get the product of both of the vectors magnitudes float vectorsMagnitude = Magnitude(Vector1) * Magnitude(Vector2) ; // Get the angle in radians between the 2 vectors double angle = acos( dotProduct / vectorsMagnitude ); // Here we make sure that the angle is not a -1.#IND0000000 number, which means indefinate if(_isnan(angle)) return 0; // Return the angle in radians return( angle ); } /////////////////////////////////// INTERSECTION POINT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the intersection point of the line that intersects the plane ///// /////////////////////////////////// INTERSECTION POINT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* CVector3 IntersectionPoint(CVector3 vNormal, CVector3 vLine[], double distance) { CVector3 vPoint, vLineDir; // Variables to hold the point and the line's direction double Numerator = 0.0, Denominator = 0.0, dist = 0.0; // 1) First we need to get the vector of our line, Then normalize it so it's a length of 1 vLineDir = vLine[1] - vLine[0]; // Get the Vector of the line vLineDir = Normalize(vLineDir); // Normalize the lines vector // 2) Use the plane equation (distance = Ax + By + Cz + D) to find the // distance from one of our points to the plane. Numerator = - (vNormal.x * vLine[0].x + // Use the plane equation with the normal and the line vNormal.y * vLine[0].y + vNormal.z * vLine[0].z + distance); // 3) If we take the dot product between our line vector and the normal of the polygon, Denominator = Dot(vNormal, vLineDir); // Get the dot product of the line's vector and the normal of the plane // Since we are using division, we need to make sure we don't get a divide by zero error // If we do get a 0, that means that there are INFINATE points because the the line is // on the plane (the normal is perpendicular to the line - (Normal.Vector = 0)). // In this case, we should just return any point on the line. if( Denominator == 0.0) // Check so we don't divide by zero return vLine[0]; // Return an arbitrary point on the line dist = Numerator / Denominator; // Divide to get the multiplying (percentage) factor // Now, like we said above, we times the dist by the vector, then add our arbitrary point. vPoint.x = (float)(vLine[0].x + (vLineDir.x * dist)); vPoint.y = (float)(vLine[0].y + (vLineDir.y * dist)); vPoint.z = (float)(vLine[0].z + (vLineDir.z * dist)); return vPoint; // Return the intersection point } /////////////////////////////////// INSIDE POLYGON \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This checks to see if a point is inside the ranges of a polygon ///// /////////////////////////////////// INSIDE POLYGON \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* bool InsidePolygon(CVector3 vIntersection, CVector3 Poly[], long verticeCount) { const double MATCH_FACTOR = 0.99; // Used to cover up the error in floating point double Angle = 0.0; // Initialize the angle CVector3 vA, vB; // Create temp vectors for (int i = 0; i < verticeCount; i++) // Go in a circle to each vertex and get the angle between { vA = Poly[i] - vIntersection; // Subtract the intersection point from the current vertex // Subtract the point from the next vertex vB = Poly[(i + 1) % verticeCount] - vIntersection; Angle += AngleBetweenVectors(vA, vB); // Find the angle between the 2 vectors and add them all up as we go along } if(Angle >= (MATCH_FACTOR * (2.0 * PI)) ) // If the angle is greater than 2 PI, (360 degrees) return true; // The point is inside of the polygon return false; // If you get here, it obviously wasn't inside the polygon, so Return FALSE } /////////////////////////////////// INTERSECTED POLYGON \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This checks if a line is intersecting a polygon ///// /////////////////////////////////// INTERSECTED POLYGON \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* bool IntersectedPolygon(CVector3 vPoly[], CVector3 vLine[], int verticeCount) { CVector3 vNormal; float originDistance = 0; // First, make sure our line intersects the plane // Reference // Reference if(!IntersectedPlane(vPoly, vLine, vNormal, originDistance)) return false; // Now that we have our normal and distance passed back from IntersectedPlane(), // we can use it to calculate the intersection point. CVector3 vIntersection = IntersectionPoint(vNormal, vLine, originDistance); // Now that we have the intersection point, we need to test if it's inside the polygon. if(InsidePolygon(vIntersection, vPoly, verticeCount)) return true; // We collided! Return success return false; // There was no collision, so return false } ///////////////////////////////// CLASSIFY SPHERE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This tells if a sphere is BEHIND, in FRONT, or INTERSECTS a plane, also it's distance ///// ///////////////////////////////// CLASSIFY SPHERE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* int ClassifySphere(CVector3 &vCenter, CVector3 &vNormal, CVector3 &vPoint, float radius, float &distance) { // First we need to find the distance our polygon plane is from the origin. float d = (float)PlaneDistance(vNormal, vPoint); // Here we use the famous distance formula to find the distance the center point // of the sphere is from the polygon's plane. distance = (vNormal.x * vCenter.x + vNormal.y * vCenter.y + vNormal.z * vCenter.z + d); // If the absolute value of the distance we just found is less than the radius, // the sphere intersected the plane. if(Absolute(distance) < radius) return INTERSECTS; // Else, if the distance is greater than or equal to the radius, the sphere is // completely in FRONT of the plane. else if(distance >= radius) return FRONT; // If the sphere isn't intersecting or in FRONT of the plane, it must be BEHIND return BEHIND; } ///////////////////////////////// EDGE SPHERE COLLSIION \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns true if the sphere is intersecting any of the edges of the polygon ///// ///////////////////////////////// EDGE SPHERE COLLSIION \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* bool EdgeSphereCollision(CVector3 &vCenter, CVector3 vPolygon[], int vertexCount, float radius) { CVector3 vPoint; // This function takes in the sphere's center, the polygon's vertices, the vertex count // and the radius of the sphere. We will return true from this function if the sphere // is intersecting any of the edges of the polygon. // Go through all of the vertices in the polygon for(int i = 0; i < vertexCount; i++) { // This returns the closest point on the current edge to the center of the sphere. vPoint = ClosestPointOnLine(vPolygon[i], vPolygon[(i + 1) % vertexCount], vCenter); // Now, we want to calculate the distance between the closest point and the center float distance = Distance(vPoint, vCenter); // If the distance is less than the radius, there must be a collision so return true if(distance < radius) return true; } // The was no intersection of the sphere and the edges of the polygon return false; } ////////////////////////////// SPHERE POLYGON COLLISION \\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns true if our sphere collides with the polygon passed in ///// ////////////////////////////// SPHERE POLYGON COLLISION \\\\\\\\\\\\\\\\\\\\\\\\\\\\\* bool SpherePolygonCollision(CVector3 vPolygon[], CVector3 &vCenter, int vertexCount, float radius) { // 1) STEP ONE - Finding the sphere's classification // Let's use our Normal() function to return us the normal to this polygon CVector3 vNormal = Normal(vPolygon); // This will store the distance our sphere is from the plane float distance = 0.0f; // This is where we determine if the sphere is in FRONT, BEHIND, or INTERSECTS the plane int classification = ClassifySphere(vCenter, vNormal, vPolygon[0], radius, distance); // If the sphere intersects the polygon's plane, then we need to check further if(classification == INTERSECTS) { // 2) STEP TWO - Finding the psuedo intersection point on the plane // Now we want to project the sphere's center onto the polygon's plane CVector3 vOffset = vNormal * distance; // Once we have the offset to the plane, we just subtract it from the center // of the sphere. "vPosition" now a point that lies on the plane of the polygon. CVector3 vPosition = vCenter - vOffset; // 3) STEP THREE - Check if the intersection point is inside the polygons perimeter // If the intersection point is inside the perimeter of the polygon, it returns true. // We pass in the intersection point, the list of vertices and vertex count of the poly. if(InsidePolygon(vPosition, vPolygon, 3)) return true; // We collided! else { // 4) STEP FOUR - Check the sphere intersects any of the polygon's edges // If we get here, we didn't find an intersection point in the perimeter. // We now need to check collision against the edges of the polygon. if(EdgeSphereCollision(vCenter, vPolygon, vertexCount, radius)) { return true; // We collided! } } } // If we get here, there is obviously no collision return false; } /////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// * ///////////////////////////////// GET COLLISION OFFSET \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns the offset to move the center of the sphere off the collided polygon ///// ///////////////////////////////// GET COLLISION OFFSET \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* CVector3 GetCollisionOffset(CVector3 &vNormal, float radius, float distance) { CVector3 vOffset = CVector3(0, 0, 0); // Once we find if a collision has taken place, we need make sure the sphere // doesn't move into the wall. In our app, the position will actually move into // the wall, but we check our collision detection before we render the scene, which // eliminates the bounce back effect it would cause. The question is, how do we // know which direction to move the sphere back? In our collision detection, we // account for collisions on both sides of the polygon. Usually, you just need // to worry about the side with the normal vector and positive distance. If // you don't want to back face cull and have 2 sided planes, I check for both sides. // // Let me explain the math that is going on here. First, we have the normal to // the plane, the radius of the sphere, as well as the distance the center of the // sphere is from the plane. In the case of the sphere colliding in the front of // the polygon, we can just subtract the distance from the radius, then multiply // that new distance by the normal of the plane. This projects that leftover // distance along the normal vector. For instance, say we have these values: // // vNormal = (1, 0, 0) radius = 5 distance = 3 // // If we subtract the distance from the radius we get: (5 - 3 = 2) // The number 2 tells us that our sphere is over the plane by a distance of 2. // So basically, we need to move the sphere back 2 units. How do we know which // direction though? This part is easy, we have a normal vector that tells us the // direction of the plane. // If we multiply the normal by the left over distance we get: (2, 0, 0) // This new offset vectors tells us which direction and how much to move back. // We then subtract this offset from the sphere's position, giving is the new // position that is lying right on top of the plane. Ba da bing! // If we are colliding from behind the polygon (not usual), we do the opposite // signs as seen below: // If our distance is greater than zero, we are in front of the polygon if(distance > 0) { // Find the distance that our sphere is overlapping the plane, then // find the direction vector to move our sphere. float distanceOver = radius - distance; vOffset = vNormal * distanceOver; } else // Else colliding from behind the polygon { // Find the distance that our sphere is overlapping the plane, then // find the direction vector to move our sphere. float distanceOver = radius + distance; vOffset = vNormal * -distanceOver; } // There is one problem with check for collisions behind the polygon, and that // is if you are moving really fast and your center goes past the front of the // polygon, it will then assume you were colliding from behind and not let // you back in. Most likely you will take out the if / else check, but I // figured I would show both ways in case someone didn't want to back face cull. // Return the offset we need to move back to not be intersecting the polygon. return vOffset; } /////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// * ///////////////////////////////////////////////////////////////////////////////// // // * QUICK NOTES * // // Nothing really new added to this file since the last collision tutorial. We did // however tweak the EdgePlaneCollision() function to handle the camera collision // better around edges. // // // Ben Humphrey (DigiBen) // Game Programmer // [email protected] // Co-Web Host of www.GameTutorials.com // //
[ "moppa" ]
moppa
94d449eb17812e9df3968d159570df821117c5ba
18a3f93e4b94f4f24ff17280c2820497e019b3db
/geant4/G4QGSPProtonBuilder.hh
5cae973f64bcded19c59951deec997592717aa65
[]
no_license
jjzhang166/BOSS_ExternalLibs
0e381d8420cea17e549d5cae5b04a216fc8a01d7
9b3b30f7874ed00a582aa9526c23ca89678bf796
refs/heads/master
2023-03-15T22:24:21.249109
2020-11-22T15:11:45
2020-11-22T15:11:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,588
hh
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // $Id: G4QGSPProtonBuilder.hh,v 1.5 2009/03/31 11:04:01 vnivanch Exp $ // GEANT4 tag $Name: geant4-09-03-patch-01 $ // //--------------------------------------------------------------------------- // // ClassName: G4QGSPProtonBuilder // // Author: 2002 J.P. Wellisch // // Modified: // 30.03.2009 V.Ivanchenko create cross section by new // //---------------------------------------------------------------------------- // #ifndef G4QGSPProtonBuilder_h #define G4QGSPProtonBuilder_h #include "globals.hh" #include "G4HadronElasticProcess.hh" #include "G4HadronFissionProcess.hh" #include "G4HadronCaptureProcess.hh" #include "G4ProtonInelasticProcess.hh" #include "G4VProtonBuilder.hh" #include "G4NeutronInelasticCrossSection.hh" #include "G4TheoFSGenerator.hh" #include "G4ExcitationHandler.hh" #include "G4PreCompoundModel.hh" #include "G4GeneratorPrecompoundInterface.hh" #include "G4QGSModel.hh" #include "G4QGSParticipants.hh" #include "G4QGSMFragmentation.hh" #include "G4ExcitedStringDecay.hh" #include "G4QuasiElasticChannel.hh" #include "G4ProjectileDiffractiveChannel.hh" #include "G4ProtonInelasticCrossSection.hh" class G4QGSPProtonBuilder : public G4VProtonBuilder { public: G4QGSPProtonBuilder(G4bool quasiElastic=false, G4bool projectileDiffraction=false); virtual ~G4QGSPProtonBuilder(); public: virtual void Build(G4HadronElasticProcess * aP); virtual void Build(G4ProtonInelasticProcess * aP); void SetMinEnergy(G4double aM) {theMin = aM;} private: G4TheoFSGenerator * theModel; G4PreCompoundModel * thePreEquilib; G4GeneratorPrecompoundInterface * theCascade; G4QGSModel< G4QGSParticipants > * theStringModel; G4ExcitedStringDecay * theStringDecay; G4QuasiElasticChannel * theQuasiElastic; G4ProjectileDiffractiveChannel * theProjectileDiffraction; G4double theMin; }; // 2002 by J.P. Wellisch #endif
451b546241f08c77239d489c0a73f13c62b28ed7
4bc01c1011b7cfd18e3dea96d9aca583f491bd7b
/core/engine.cpp
27511a3b86007373bf00f3d9ffe52bdd578f9597
[]
no_license
ameuleman/Harmony
8d369aa4c6885a83e05c3c352c24c3582ec9e93c
4b341f41ae788489816e1bb7ffe44912f13c9113
refs/heads/master
2021-01-19T11:04:18.626410
2017-02-06T12:13:34
2017-02-06T12:13:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
724
cpp
#include "engine.hpp" namespace harmony{ namespace core{ Engine::Engine(const Setting &settings): state(State::initialized) { game.reset(new Game(settings)); } void Engine::operator()() { state = State::running; game->status = Game::Status::ongoing; // TODO remove turn count (temporary end condition) while(state == State::running) { boost::shared_ptr<harmony::core::Turn> turn(new harmony::core::Turn (game)); (*turn)(); executedTurns.push_back(turn); if(game->getStatus() != Game::Status::ongoing) { state = State::ended; } } } const Game &Engine::getGame() const { return *game; } }}
dc17d008f00c3f333f2183a1bf31f9349bc64307
cc9af96765cd952df2bed0053cc0ec05ee97d610
/Dynamic Programming/Padovan_Sequence.cpp
9ff68480df825b7e79b916553e69b016dc8009ce
[]
no_license
avantikasparihar/GeeksForGeeks
2a611f8977a677a66e776b682a0c533a78a8cc8e
497675423fe9996aa12b532db7e00978519dc6ee
refs/heads/master
2023-02-14T22:22:23.726395
2021-01-06T16:50:52
2021-01-06T16:50:52
286,539,458
2
2
null
2020-10-01T13:32:13
2020-08-10T17:33:26
C++
UTF-8
C++
false
false
396
cpp
#include<bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Padovan Sequence int t, n; cin >> t; while (t--) { cin >> n; long long p[n+2]; p[0]=1; p[1]=1; p[2]=1; for(int i=3; i<=n; i++) p[i] = p[i-2] + p[i-3]; cout << p[n]%1000000007 << endl; } return 0; }
ee549f584cf5678fda1c84675eab456e89778c15
5b7b4d3883233e21e7545478664a04d0eaebd423
/projects/vkworld/wrappers/VkwTextureGenerator.cpp
57d52cb5593a74d4e12231cf66b710dc5458a094
[ "MIT" ]
permissive
stefannesic/world
c8dca13c6d46c91c4d2a6e027f5cf413f51ccab0
44c01623ab1777c3224f83f53b74d50b58372fb1
refs/heads/master
2021-03-02T01:02:15.200828
2020-03-07T09:10:26
2020-03-07T09:10:26
245,825,486
0
0
MIT
2020-03-08T14:04:50
2020-03-08T14:04:49
null
UTF-8
C++
false
false
3,655
cpp
#include "VkwTextureGenerator.h" #include "VkwMemoryHelper.h" namespace world { VkwTextureGenerator::VkwTextureGenerator(int width, int height, std::string shaderName) : _width(width), _height(height), _texture(width, height, VkwImageUsage::OFFSCREEN_RENDER, vk::Format::eR32G32B32A32Sfloat), _shaderName(std::move(shaderName)) { _worker = std::make_unique<VkwGraphicsWorker>(); } VkwTextureGenerator::~VkwTextureGenerator() = default; void VkwTextureGenerator::addParameter(int id, DescriptorType type, MemoryUsage memtype, size_t size, void *data) { _layout.addBinding(type, id); auto &ctx = Vulkan::context(); VkwSubBuffer buffer = ctx.allocate(size, type, memtype); buffer.setData(data); _buffers[id] = buffer; } void VkwTextureGenerator::addImageParameter(int id, const VkwImage &image) { _layout.addBinding(DescriptorType::IMAGE, id); _images.emplace(id, image); } Image VkwTextureGenerator::generateTexture() { generateTextureAsync(); return getGeneratedImage(); } void VkwTextureGenerator::generateTextureAsync() { VkwDescriptorSet dset(_layout); for (auto &entry : _buffers) { dset.addDescriptor(entry.first, entry.second); } for (auto &entry : _images) { dset.addDescriptor(entry.first, entry.second); } VkwGraphicsPipeline pipeline(_layout); if (_mesh.empty()) { pipeline.setBuiltinShader(VkwShaderType::VERTEX, "generic-texture.vert"); pipeline.enableVertexBuffer(false); } else { pipeline.setBuiltinShader(VkwShaderType::VERTEX, "generic-2D.vert"); } pipeline.setBuiltinShader(VkwShaderType::FRAGMENT, _shaderName); auto &ctx = Vulkan::context(); VkwRenderPass renderPass(_texture); pipeline.setRenderPass(renderPass); _worker->beginRenderPass(renderPass); _worker->bindCommand(pipeline, dset); // --- Draw if (_mesh.empty()) { _worker->draw(6); } else { // TODO Staging buffers // Setup Vertex buffer std::vector<VkwVertex> vertices; for (u32 i = 0; i < _mesh.getVerticesCount(); ++i) { vertices.emplace_back(_mesh.getVertex(i)); } _verticesBuf = ctx.allocate(vertices.size() * sizeof(VkwVertex), DescriptorType::VERTEX_BUFFER, MemoryUsage::CPU_WRITES); _verticesBuf.setData(&vertices[0]); // Setup Indices buffer std::vector<u32> indices; for (u32 i = 0; i < _mesh.getFaceCount(); ++i) { const Face &face = _mesh.getFace(i); for (u32 j = 0; j < face.vertexCount(); ++j) { indices.push_back(face.getID(j)); } } _indicesBuf = ctx.allocate(indices.size() * sizeof(u32), DescriptorType::INDEX_BUFFER, MemoryUsage::CPU_WRITES); _indicesBuf.setData(&indices[0]); // Draw Indexed _worker->drawIndexed(_indicesBuf, _verticesBuf, indices.size()); } // End renderpass _worker->endRenderPass(); _worker->endCommandRecording(); _worker->run(); } Image VkwTextureGenerator::getGeneratedImage() { Image img(_width, _height, ImageType::RGBA); getGeneratedImage(img); return img; } void VkwTextureGenerator::getGeneratedImage(Image &img) { _worker->waitForCompletion(); VkwMemoryHelper::GPUToImage(_texture, img, 4); } } // namespace world
164131001700b48f01b50f304472e3d62458ef4a
cc13bdb0f445b8acf6bec24946fcfb5e854989b6
/Pods/gRPC-Core/src/core/lib/security/credentials/jwt/json_token.cc
2bb171e790b45ec26c2339899993800a3f8f7367
[ "MIT", "Apache-2.0" ]
permissive
devMEremenko/XcodeBenchmark
59eaf0f7d6cdaead6338511431489d9d2bf0bbb5
3aaaa6aa4400a20513dd4b6fdb372c48b8c9e772
refs/heads/master
2023-09-04T08:37:51.014081
2023-07-25T23:37:37
2023-07-25T23:37:37
288,524,849
2,335
346
MIT
2023-09-08T16:52:16
2020-08-18T17:47:47
Swift
UTF-8
C++
false
false
9,310
cc
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/error.h" #include "src/core/lib/security/credentials/jwt/json_token.h" #include <string.h> #include <grpc/grpc_security.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/time.h> #include "src/core/lib/gpr/string.h" #include "src/core/lib/security/util/json_util.h" #include "src/core/lib/slice/b64.h" extern "C" { #if COCOAPODS==1 #include <openssl_grpc/bio.h> #else #include <openssl/bio.h> #endif #if COCOAPODS==1 #include <openssl_grpc/evp.h> #else #include <openssl/evp.h> #endif #if COCOAPODS==1 #include <openssl_grpc/pem.h> #else #include <openssl/pem.h> #endif } using grpc_core::Json; /* --- Constants. --- */ /* 1 hour max. */ gpr_timespec grpc_max_auth_token_lifetime() { gpr_timespec out; out.tv_sec = 3600; out.tv_nsec = 0; out.clock_type = GPR_TIMESPAN; return out; } #define GRPC_JWT_RSA_SHA256_ALGORITHM "RS256" #define GRPC_JWT_TYPE "JWT" /* --- Override for testing. --- */ static grpc_jwt_encode_and_sign_override g_jwt_encode_and_sign_override = nullptr; /* --- grpc_auth_json_key. --- */ int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key) { return (json_key != nullptr) && strcmp(json_key->type, GRPC_AUTH_JSON_TYPE_INVALID); } grpc_auth_json_key grpc_auth_json_key_create_from_json(const Json& json) { grpc_auth_json_key result; BIO* bio = nullptr; const char* prop_value; int success = 0; grpc_error* error = GRPC_ERROR_NONE; memset(&result, 0, sizeof(grpc_auth_json_key)); result.type = GRPC_AUTH_JSON_TYPE_INVALID; if (json.type() == Json::Type::JSON_NULL) { gpr_log(GPR_ERROR, "Invalid json."); goto end; } prop_value = grpc_json_get_string_property(json, "type", &error); GRPC_LOG_IF_ERROR("JSON key parsing", error); if (prop_value == nullptr || strcmp(prop_value, GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT)) { goto end; } result.type = GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT; if (!grpc_copy_json_string_property(json, "private_key_id", &result.private_key_id) || !grpc_copy_json_string_property(json, "client_id", &result.client_id) || !grpc_copy_json_string_property(json, "client_email", &result.client_email)) { goto end; } prop_value = grpc_json_get_string_property(json, "private_key", &error); GRPC_LOG_IF_ERROR("JSON key parsing", error); if (prop_value == nullptr) { goto end; } bio = BIO_new(BIO_s_mem()); success = BIO_puts(bio, prop_value); if ((success < 0) || (static_cast<size_t>(success) != strlen(prop_value))) { gpr_log(GPR_ERROR, "Could not write into openssl BIO."); goto end; } result.private_key = PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, (void*)""); if (result.private_key == nullptr) { gpr_log(GPR_ERROR, "Could not deserialize private key."); goto end; } success = 1; end: if (bio != nullptr) BIO_free(bio); if (!success) grpc_auth_json_key_destruct(&result); return result; } grpc_auth_json_key grpc_auth_json_key_create_from_string( const char* json_string) { grpc_error* error = GRPC_ERROR_NONE; Json json = Json::Parse(json_string, &error); GRPC_LOG_IF_ERROR("JSON key parsing", error); return grpc_auth_json_key_create_from_json(std::move(json)); } void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key) { if (json_key == nullptr) return; json_key->type = GRPC_AUTH_JSON_TYPE_INVALID; if (json_key->client_id != nullptr) { gpr_free(json_key->client_id); json_key->client_id = nullptr; } if (json_key->private_key_id != nullptr) { gpr_free(json_key->private_key_id); json_key->private_key_id = nullptr; } if (json_key->client_email != nullptr) { gpr_free(json_key->client_email); json_key->client_email = nullptr; } if (json_key->private_key != nullptr) { RSA_free(json_key->private_key); json_key->private_key = nullptr; } } /* --- jwt encoding and signature. --- */ static char* encoded_jwt_header(const char* key_id, const char* algorithm) { Json json = Json::Object{ {"alg", algorithm}, {"typ", GRPC_JWT_TYPE}, {"kid", key_id}, }; std::string json_str = json.Dump(); return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0); } static char* encoded_jwt_claim(const grpc_auth_json_key* json_key, const char* audience, gpr_timespec token_lifetime, const char* scope) { gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); gpr_timespec expiration = gpr_time_add(now, token_lifetime); if (gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()) > 0) { gpr_log(GPR_INFO, "Cropping token lifetime to maximum allowed value."); expiration = gpr_time_add(now, grpc_max_auth_token_lifetime()); } Json::Object object = { {"iss", json_key->client_email}, {"aud", audience}, {"iat", now.tv_sec}, {"exp", expiration.tv_sec}, }; if (scope != nullptr) { object["scope"] = scope; } else { /* Unscoped JWTs need a sub field. */ object["sub"] = json_key->client_email; } Json json(object); std::string json_str = json.Dump(); return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0); } static char* dot_concat_and_free_strings(char* str1, char* str2) { size_t str1_len = strlen(str1); size_t str2_len = strlen(str2); size_t result_len = str1_len + 1 /* dot */ + str2_len; char* result = static_cast<char*>(gpr_malloc(result_len + 1 /* NULL terminated */)); char* current = result; memcpy(current, str1, str1_len); current += str1_len; *(current++) = '.'; memcpy(current, str2, str2_len); current += str2_len; GPR_ASSERT(current >= result); GPR_ASSERT((uintptr_t)(current - result) == result_len); *current = '\0'; gpr_free(str1); gpr_free(str2); return result; } const EVP_MD* openssl_digest_from_algorithm(const char* algorithm) { if (strcmp(algorithm, GRPC_JWT_RSA_SHA256_ALGORITHM) == 0) { return EVP_sha256(); } else { gpr_log(GPR_ERROR, "Unknown algorithm %s.", algorithm); return nullptr; } } char* compute_and_encode_signature(const grpc_auth_json_key* json_key, const char* signature_algorithm, const char* to_sign) { const EVP_MD* md = openssl_digest_from_algorithm(signature_algorithm); EVP_MD_CTX* md_ctx = nullptr; EVP_PKEY* key = EVP_PKEY_new(); size_t sig_len = 0; unsigned char* sig = nullptr; char* result = nullptr; if (md == nullptr) return nullptr; md_ctx = EVP_MD_CTX_create(); if (md_ctx == nullptr) { gpr_log(GPR_ERROR, "Could not create MD_CTX"); goto end; } EVP_PKEY_set1_RSA(key, json_key->private_key); if (EVP_DigestSignInit(md_ctx, nullptr, md, nullptr, key) != 1) { gpr_log(GPR_ERROR, "DigestInit failed."); goto end; } if (EVP_DigestSignUpdate(md_ctx, to_sign, strlen(to_sign)) != 1) { gpr_log(GPR_ERROR, "DigestUpdate failed."); goto end; } if (EVP_DigestSignFinal(md_ctx, nullptr, &sig_len) != 1) { gpr_log(GPR_ERROR, "DigestFinal (get signature length) failed."); goto end; } sig = static_cast<unsigned char*>(gpr_malloc(sig_len)); if (EVP_DigestSignFinal(md_ctx, sig, &sig_len) != 1) { gpr_log(GPR_ERROR, "DigestFinal (signature compute) failed."); goto end; } result = grpc_base64_encode(sig, sig_len, 1, 0); end: if (key != nullptr) EVP_PKEY_free(key); if (md_ctx != nullptr) EVP_MD_CTX_destroy(md_ctx); if (sig != nullptr) gpr_free(sig); return result; } char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key, const char* audience, gpr_timespec token_lifetime, const char* scope) { if (g_jwt_encode_and_sign_override != nullptr) { return g_jwt_encode_and_sign_override(json_key, audience, token_lifetime, scope); } else { const char* sig_algo = GRPC_JWT_RSA_SHA256_ALGORITHM; char* to_sign = dot_concat_and_free_strings( encoded_jwt_header(json_key->private_key_id, sig_algo), encoded_jwt_claim(json_key, audience, token_lifetime, scope)); char* sig = compute_and_encode_signature(json_key, sig_algo, to_sign); if (sig == nullptr) { gpr_free(to_sign); return nullptr; } return dot_concat_and_free_strings(to_sign, sig); } } void grpc_jwt_encode_and_sign_set_override( grpc_jwt_encode_and_sign_override func) { g_jwt_encode_and_sign_override = func; }
1643339f8408db9ebf476bba0ee6a858bef7677b
880da7cfc1193cff18dfbdb4372c4cec7be95f86
/Set-2020/Set-01-(Math)/Sherlock_pairs.cpp
0beb7066d4fb7fb4c5fd88685a69c2e9247c7a14
[]
no_license
chaitanyawho/Summer19
07213c5b4b6a181c6ba43ec086fa0222b474c5c7
9dd18f0e0592d9c93f5fc83c456133088fddd878
refs/heads/master
2021-07-16T10:03:54.235183
2020-10-01T06:15:38
2020-10-01T06:15:38
204,030,598
0
3
null
2020-10-01T06:15:39
2019-08-23T16:03:46
Java
UTF-8
C++
false
false
1,647
cpp
import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Solution { // Complete the solve function below. static long solve(long[] a) { Map<Long, Long> m = new HashMap<Long, Long>(); int n = a.length; for (int i = 0; i < n; i++) { if (!m.containsKey(a[i])) { m.put(a[i], 0L); } m.put(a[i], m.get(a[i]) + 1); } long ans = 0; for (Long an : m.keySet()) { ans += m.get(an) * (m.get(an) - 1); } return ans; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int t = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int tItr = 0; tItr < t; tItr++) { int aCount = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); long[] a = new long[aCount]; String[] aItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int aItr = 0; aItr < aCount; aItr++) { int aItem = Integer.parseInt(aItems[aItr]); a[aItr] = aItem; } long result = solve(a); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); } bufferedWriter.close(); scanner.close(); } }
c8dfd60a1ef1cc880f906f23e0ded475b89b114b
a04974b23601541d4b26bd4d3ec493ff69898580
/DOTD_Epoch.Chernarus/dayz_code/configs/CfgLoot/Groups/Generic.hpp
a9adea8c65021f1671bc6748895395bff22d7a08
[]
no_license
DarrianJCairns/RS_Overpoch
50c153754e69ba708c469f4f4a77abe5c27b5d9a
81e35ffcd53fb5a0d5bf5a37d130ae561762ecfc
refs/heads/master
2020-08-29T00:12:58.933117
2017-07-22T16:57:05
2017-07-22T16:57:05
94,383,226
0
1
null
null
null
null
UTF-8
C++
false
false
1,681
hpp
Generic[] = { {Loot_MAGAZINE, 1, 1Rnd_Arrow_Wood}, {Loot_MAGAZINE, 1, HandRoadFlare}, {Loot_MAGAZINE, 1, HandChemGreen}, {Loot_MAGAZINE, 1, HandChemBlue}, {Loot_MAGAZINE, 1, HandChemRed}, //DZE {Loot_MAGAZINE, 1, 5Rnd_17HMR}, {Loot_MAGAZINE, 2, 10Rnd_303British}, {Loot_MAGAZINE, 2, 15Rnd_W1866_Slug}, {Loot_MAGAZINE, 2, 5Rnd_762x54_Mosin}, {Loot_MAGAZINE, 2, 8Rnd_9x18_Makarov}, {Loot_MAGAZINE, 2, 7Rnd_45ACP_1911}, {Loot_MAGAZINE, 2, 6Rnd_45ACP}, // {Loot_MAGAZINE, 1, ItemBookBible}, {Loot_MAGAZINE, 1, equip_string}, {Loot_MAGAZINE, 1, ItemDocument}, {Loot_MAGAZINE, 1, equip_duct_tape}, {Loot_MAGAZINE, 1, equip_rope}, {Loot_MAGAZINE, 1, equip_herb_box}, // {Loot_MAGAZINE, 1, equip_pvc_box}, {Loot_MAGAZINE, 1, equip_lever}, {Loot_MAGAZINE, 1, equip_rag}, {Loot_MAGAZINE, 1, equip_nails}, {Loot_MAGAZINE, 1, ItemFuelCan}, {Loot_MAGAZINE, 1, PartWoodPile} }; tents[] = { {Loot_MAGAZINE, 0.5, ItemDomeTent}, {Loot_MAGAZINE, 1, ItemTent}, {Loot_MAGAZINE, 0.5, ItemDesertTent} //EPOCH ADDITION }; GenericSmall[] = { {Loot_MAGAZINE, 1, HandRoadFlare}, {Loot_MAGAZINE, 1, HandChemGreen}, {Loot_MAGAZINE, 1, HandChemBlue}, {Loot_MAGAZINE, 1, HandChemRed}, {Loot_MAGAZINE, 1, 5Rnd_17HMR}, {Loot_MAGAZINE, 2, 10Rnd_303British}, {Loot_MAGAZINE, 2, 15Rnd_W1866_Slug}, {Loot_MAGAZINE, 1, 5Rnd_762x54_Mosin}, {Loot_MAGAZINE, 2, 8Rnd_9x18_Makarov}, {Loot_MAGAZINE, 2, 7Rnd_45ACP_1911}, {Loot_MAGAZINE, 1, 6Rnd_45ACP}, {Loot_MAGAZINE, 1, equip_string}, {Loot_MAGAZINE, 1, equip_duct_tape}, {Loot_MAGAZINE, 1, equip_rope}, {Loot_MAGAZINE, 1, equip_nails} };
3af2f14e31bc55b434ec319c83839aad46e897c8
d60c0fca38dcf419a79705a0d176b08ee68ef591
/Bengine/IMainGame.cpp
6281ddc21e33eed62ec5fc353da20a93b88cad9d
[ "MIT" ]
permissive
Alejandro-Casanova/Advanced-C-and-Graphics-VS-
b7dcb1153edb814673321d04e02c869253f84e28
e29bbdbe39b906cdb4cb0dbcbc39bba616e5dcf7
refs/heads/master
2022-12-09T13:40:08.862887
2020-09-11T11:16:18
2020-09-11T11:16:18
294,559,035
0
0
null
null
null
null
UTF-8
C++
false
false
4,168
cpp
#include "pch.h" #include "IMainGame.h" #include "Timing.h" #include "IGameScreen.h" namespace Bengine{ IMainGame::IMainGame(){ m_screenList = std::make_unique<ScreenList>(this); } IMainGame::~IMainGame(){} void IMainGame::run(){ if(!init()) return; FpsLimiter limiter; limiter.init(m_maxFps); ///TimeStep parameters const float DESIRED_fps = 60.0f; const int MAX_PHYSICS_STEPS = 4; //Max steps simulated in one frame. Prevents "spiral of death", where too many steps prevent the program from rendering const float MS_PER_SECOND = 1000.0f; const float DESIRED_FRAME_TIME = MS_PER_SECOND / DESIRED_fps; const float MAX_DELTA_TIME = 1.0f; float prevTicks = SDL_GetTicks(); ///Game loop m_isRunning = true; while(m_isRunning){ limiter.begin(); ///Delta Time Calculation Uint32 newTicks = SDL_GetTicks(); Uint32 frameTime = newTicks - prevTicks; prevTicks = newTicks; float totalDeltaTime = frameTime / DESIRED_FRAME_TIME; m_totalDeltaTime = totalDeltaTime; int i = 0;//Prevents "spiral of death" while( ( totalDeltaTime > 0.0f ) && ( i < MAX_PHYSICS_STEPS ) ){ float deltaTime = std::min(MAX_DELTA_TIME, totalDeltaTime); ///Call custom update and draw methods inputManager.update(); update(deltaTime); i++; totalDeltaTime -= deltaTime; } if(m_isRunning){///< Prevents crash draw(); m_window.swapBuffer(); } m_fps = limiter.end(); } } void IMainGame::exitGame(){ m_currentScreen->onExit(); if(m_screenList){ m_screenList->destroy(); m_screenList.reset(); } m_isRunning = false; } void IMainGame::update(float deltaTime){ if(m_currentScreen){///< Checks m_currentScreen != nullptr switch(m_currentScreen->getScreenState()){ case ScreenState::RUNNING: m_currentScreen->update(deltaTime); break; case ScreenState::CHANGE_NEXT: m_currentScreen->onExit(); m_currentScreen = m_screenList->moveNext(); if(m_currentScreen){ m_currentScreen->setRunning(); m_currentScreen->onEntry(); } break; case ScreenState::CHANGE_PREVIOUS: m_currentScreen->onExit(); m_currentScreen = m_screenList->movePrevious(); if(m_currentScreen){ m_currentScreen->setRunning(); m_currentScreen->onEntry(); } break; case ScreenState::EXIT_APPLICATION: exitGame(); break; default: break; } }else{ exitGame(); } } void IMainGame::draw(){ glViewport(0, 0, m_window.getScreenWidth(), m_window.getScreenHeight()); if(m_currentScreen && (m_currentScreen->getScreenState() == ScreenState::RUNNING)){ m_currentScreen->draw(); } } void IMainGame::onSDLEvent(SDL_Event& evnt){ switch(evnt.type){ case SDL_QUIT: exitGame(); break; case SDL_MOUSEMOTION: inputManager.setMouseCoords(evnt.motion.x, evnt.motion.y); break; case SDL_KEYDOWN: inputManager.pressKey(evnt.key.keysym.sym); break; case SDL_KEYUP: inputManager.releaseKey(evnt.key.keysym.sym); break; case SDL_MOUSEBUTTONDOWN: inputManager.pressKey(evnt.button.button); break; case SDL_MOUSEBUTTONUP: inputManager.releaseKey(evnt.button.button); break; } } bool IMainGame::init(){ Bengine::init(); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); if(!initSystems()) return false; onInit(); addScreens(); m_currentScreen = m_screenList->getCurrent(); m_currentScreen->onEntry(); m_currentScreen->setRunning(); return true; } bool IMainGame::initSystems(){ if(m_window.create("Default", m_screenWidth, m_screenHeight, 0) != 0) return false; return true; } }
693833efde539a9987b4b181776d47a64dedfb43
9dc658ac2439d41254cfba15805184727597a536
/screenrightarroweventhandler.h
a109041c4e8838edf538dc1d40a9f53ccdc29b5a
[]
no_license
tdphong/FrontEnd
cd8c8bff770b65275e1b88e0406a90931e8eea7a
16fc66ab969ba7a541eea9d1d8d1b279e352df0d
refs/heads/master
2021-01-20T12:10:29.246213
2016-06-01T00:48:28
2016-06-01T00:48:28
60,133,214
0
0
null
null
null
null
UTF-8
C++
false
false
1,005
h
// // Created by phtran on 21/05/2016. // #ifndef FRONTEND_SCREENRIGHTARROWEVENTHANDLER_H #define FRONTEND_SCREENRIGHTARROWEVENTHANDLER_H #include "baseeventhandler.h" #include "screen.h" #include "screenfield.h" #include "event.h" namespace UI { class ScreenRightArrowEventHandler : public BaseEventHandler { UI::Screen& screen_; public: ScreenRightArrowEventHandler(Screen& s) : screen_(s) { } virtual void invoke() { if (screen_.focus() == screen_.end()) { return; } if (screen_.focus()->get()->cursorAtLast()) { screen_.notifyEvent(UI::StepFocusForwardEvent()); return; } screen_.focus()->get()->notifyEvent(RightArrowEvent()); } virtual ScreenRightArrowEventHandler* clone() const { return new ScreenRightArrowEventHandler(*this); } }; } #endif //FRONTEND_SCREENRIGHTARROWEVENTHANDLER_H
f2267ce1620232dd603f87d720b44b7ecc4bb0f2
bd2c7d8e4728d04115c772f43b878db562e76638
/stl-program/Program/algorithm/compare.cpp
b1144ddc775fc7a8c5ab492aafd8b15d00cf0a76
[]
no_license
billpwchan/COMP-2012-Programs
c86c92d681cf00d9abca431e3fb915dc7afffaab
726fc3b0695a28187acc548033b452ad4def3f25
refs/heads/main
2023-02-05T02:54:20.869804
2020-12-27T20:44:02
2020-12-27T20:44:02
324,845,396
0
0
null
null
null
null
UTF-8
C++
false
false
85
cpp
int Compare_Integer(int* i, int* j) { return((*i) - (*j)); } /* File: compare.cpp */
309676c8e702b0ddb52e95a8367933d2bf744a80
69625150ef1a2c2893c96f0ab1502efc4b22a033
/src/MFRC522.h
0002335f8aed1e06d6796e085e33577740ce7d0f
[]
no_license
suratkw/mfrc522-mi
94107d58d77ebf988fe77f12b2138e4c34873dec
283b7149c17a7b9eee9fd8ec966667089345f32d
refs/heads/master
2020-03-27T04:47:37.717751
2018-08-24T09:20:46
2018-08-24T09:20:46
145,968,771
0
0
null
null
null
null
UTF-8
C++
false
false
23,784
h
/** * MFRC522.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT. * Based on code Dr.Leong ( WWW.B2CQSHOP.COM ) * Created by Miguel Balboa (circuitito.com), Jan, 2012. * Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013 (Translation to English, refactored, comments, anti collision, cascade levels.) * Extended by Tom Clement with functionality to write to sector 0 of UID changeable Mifare cards. * Released into the public domain. * * Please read this file for an overview and then MFRC522.cpp for comments on the specific functions. * Search for "mf-rc522" on ebay.com to purchase the MF-RC522 board. * * There are three hardware components involved: * 1) The micro controller: An Arduino * 2) The PCD (short for Proximity Coupling Device): NXP MFRC522 Contactless Reader IC * 3) The PICC (short for Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203. * * The microcontroller and card reader uses SPI for communication. * The protocol is described in the MFRC522 datasheet: http://www.nxp.com/documents/data_sheet/MFRC522.pdf * * The card reader and the tags communicate using a 13.56MHz electromagnetic field. * The protocol is defined in ISO/IEC 14443-3 Identification cards -- Contactless integrated circuit cards -- Proximity cards -- Part 3: Initialization and anticollision". * A free version of the final draft can be found at http://wg8.de/wg8n1496_17n3613_Ballot_FCD14443-3.pdf * Details are found in chapter 6, Type A – Initialization and anticollision. * * If only the PICC UID is wanted, the above documents has all the needed information. * To read and write from MIFARE PICCs, the MIFARE protocol is used after the PICC has been selected. * The MIFARE Classic chips and protocol is described in the datasheets: * 1K: http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf * 4K: http://datasheet.octopart.com/MF1S7035DA4,118-NXP-Semiconductors-datasheet-11046188.pdf * Mini: http://www.idcardmarket.com/download/mifare_S20_datasheet.pdf * The MIFARE Ultralight chip and protocol is described in the datasheets: * Ultralight: http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf * Ultralight C: http://www.nxp.com/documents/short_data_sheet/MF0ICU2_SDS.pdf * * MIFARE Classic 1K (MF1S503x): * Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes. * The blocks are numbered 0-63. * Block 3 in each sector is the Sector Trailer. See http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf sections 8.6 and 8.7: * Bytes 0-5: Key A * Bytes 6-8: Access Bits * Bytes 9: User data * Bytes 10-15: Key B (or user data) * Block 0 is read-only manufacturer data. * To access a block, an authentication using a key from the block's sector must be performed first. * Example: To read from block 10, first authenticate using a key from sector 3 (blocks 8-11). * All keys are set to FFFFFFFFFFFFh at chip delivery. * Warning: Please read section 8.7 "Memory Access". It includes this text: if the PICC detects a format violation the whole sector is irreversibly blocked. * To use a block in "value block" mode (for Increment/Decrement operations) you need to change the sector trailer. Use PICC_SetAccessBits() to calculate the bit patterns. * MIFARE Classic 4K (MF1S703x): * Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes. * The blocks are numbered 0-255. * The last block in each sector is the Sector Trailer like above. * MIFARE Classic Mini (MF1 IC S20): * Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes. * The blocks are numbered 0-19. * The last block in each sector is the Sector Trailer like above. * * MIFARE Ultralight (MF0ICU1): * Has 16 pages of 4 bytes = 64 bytes. * Pages 0 + 1 is used for the 7-byte UID. * Page 2 contains the last check digit for the UID, one byte manufacturer internal data, and the lock bytes (see http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf section 8.5.2) * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. * Pages 4-15 are read/write unless blocked by the lock bytes in page 2. * MIFARE Ultralight C (MF0ICU2): * Has 48 pages of 4 bytes = 192 bytes. * Pages 0 + 1 is used for the 7-byte UID. * Page 2 contains the last check digit for the UID, one byte manufacturer internal data, and the lock bytes (see http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf section 8.5.2) * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. * Pages 4-39 are read/write unless blocked by the lock bytes in page 2. * Page 40 Lock bytes * Page 41 16 bit one way counter * Pages 42-43 Authentication configuration * Pages 44-47 Authentication key */ #ifndef MFRC522_h #define MFRC522_h #include "require_cpp11.h" #include "deprecated.h" // Enable integer limits #define __STDC_LIMIT_MACROS #include <stdint.h> #include <cstring> #include <wiringPi.h> #include <wiringPiSPI.h> #define byte uint8_t #define MFRC522_SPICLOCK SPI_CLOCK_DIV4 // MFRC522 accept upto 10MHz // Firmware data for self-test // Reference values based on firmware version // Hint: if needed, you can remove unused self-test data to save flash memory // // Version 0.0 (0x90) // Philips Semiconductors; Preliminary Specification Revision 2.0 - 01 August 2005; 16.1 self-test const byte MFRC522_firmware_referenceV0_0[] = { 0x00, 0x87, 0x98, 0x0f, 0x49, 0xFF, 0x07, 0x19, 0xBF, 0x22, 0x30, 0x49, 0x59, 0x63, 0xAD, 0xCA, 0x7F, 0xE3, 0x4E, 0x03, 0x5C, 0x4E, 0x49, 0x50, 0x47, 0x9A, 0x37, 0x61, 0xE7, 0xE2, 0xC6, 0x2E, 0x75, 0x5A, 0xED, 0x04, 0x3D, 0x02, 0x4B, 0x78, 0x32, 0xFF, 0x58, 0x3B, 0x7C, 0xE9, 0x00, 0x94, 0xB4, 0x4A, 0x59, 0x5B, 0xFD, 0xC9, 0x29, 0xDF, 0x35, 0x96, 0x98, 0x9E, 0x4F, 0x30, 0x32, 0x8D }; // Version 1.0 (0x91) // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 self-test const byte MFRC522_firmware_referenceV1_0[] = { 0x00, 0xC6, 0x37, 0xD5, 0x32, 0xB7, 0x57, 0x5C, 0xC2, 0xD8, 0x7C, 0x4D, 0xD9, 0x70, 0xC7, 0x73, 0x10, 0xE6, 0xD2, 0xAA, 0x5E, 0xA1, 0x3E, 0x5A, 0x14, 0xAF, 0x30, 0x61, 0xC9, 0x70, 0xDB, 0x2E, 0x64, 0x22, 0x72, 0xB5, 0xBD, 0x65, 0xF4, 0xEC, 0x22, 0xBC, 0xD3, 0x72, 0x35, 0xCD, 0xAA, 0x41, 0x1F, 0xA7, 0xF3, 0x53, 0x14, 0xDE, 0x7E, 0x02, 0xD9, 0x0F, 0xB5, 0x5E, 0x25, 0x1D, 0x29, 0x79 }; // Version 2.0 (0x92) // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 self-test const byte MFRC522_firmware_referenceV2_0[] = { 0x00, 0xEB, 0x66, 0xBA, 0x57, 0xBF, 0x23, 0x95, 0xD0, 0xE3, 0x0D, 0x3D, 0x27, 0x89, 0x5C, 0xDE, 0x9D, 0x3B, 0xA7, 0x00, 0x21, 0x5B, 0x89, 0x82, 0x51, 0x3A, 0xEB, 0x02, 0x0C, 0xA5, 0x00, 0x49, 0x7C, 0x84, 0x4D, 0xB3, 0xCC, 0xD2, 0x1B, 0x81, 0x5D, 0x48, 0x76, 0xD5, 0x71, 0x61, 0x21, 0xA9, 0x86, 0x96, 0x83, 0x38, 0xCF, 0x9D, 0x5B, 0x6D, 0xDC, 0x15, 0xBA, 0x3E, 0x7D, 0x95, 0x3B, 0x2F }; // Clone // Fudan Semiconductor FM17522 (0x88) const byte FM17522_firmware_reference[] = { 0x00, 0xD6, 0x78, 0x8C, 0xE2, 0xAA, 0x0C, 0x18, 0x2A, 0xB8, 0x7A, 0x7F, 0xD3, 0x6A, 0xCF, 0x0B, 0xB1, 0x37, 0x63, 0x4B, 0x69, 0xAE, 0x91, 0xC7, 0xC3, 0x97, 0xAE, 0x77, 0xF4, 0x37, 0xD7, 0x9B, 0x7C, 0xF5, 0x3C, 0x11, 0x8F, 0x15, 0xC3, 0xD7, 0xC1, 0x5B, 0x00, 0x2A, 0xD0, 0x75, 0xDE, 0x9E, 0x51, 0x64, 0xAB, 0x3E, 0xE9, 0x15, 0xB5, 0xAB, 0x56, 0x9A, 0x98, 0x82, 0x26, 0xEA, 0x2A, 0x62 }; class MFRC522 { public: // Size of the MFRC522 FIFO static const byte FIFO_SIZE = 64; // The FIFO is 64 bytes. // MFRC522 registers. Described in chapter 9 of the datasheet. // When using SPI all addresses are shifted one bit left in the "SPI address byte" (section 8.1.2.3) enum PCD_Register : byte { // Page 0: Command and status // 0x00 // reserved for future use CommandReg = 0x01 << 1, // starts and stops command execution ComIEnReg = 0x02 << 1, // enable and disable interrupt request control bits DivIEnReg = 0x03 << 1, // enable and disable interrupt request control bits ComIrqReg = 0x04 << 1, // interrupt request bits DivIrqReg = 0x05 << 1, // interrupt request bits ErrorReg = 0x06 << 1, // error bits showing the error status of the last command executed Status1Reg = 0x07 << 1, // communication status bits Status2Reg = 0x08 << 1, // receiver and transmitter status bits FIFODataReg = 0x09 << 1, // input and output of 64 byte FIFO buffer FIFOLevelReg = 0x0A << 1, // number of bytes stored in the FIFO buffer WaterLevelReg = 0x0B << 1, // level for FIFO underflow and overflow warning ControlReg = 0x0C << 1, // miscellaneous control registers BitFramingReg = 0x0D << 1, // adjustments for bit-oriented frames CollReg = 0x0E << 1, // bit position of the first bit-collision detected on the RF interface // 0x0F // reserved for future use // Page 1: Command // 0x10 // reserved for future use ModeReg = 0x11 << 1, // defines general modes for transmitting and receiving TxModeReg = 0x12 << 1, // defines transmission data rate and framing RxModeReg = 0x13 << 1, // defines reception data rate and framing TxControlReg = 0x14 << 1, // controls the logical behavior of the antenna driver pins TX1 and TX2 TxASKReg = 0x15 << 1, // controls the setting of the transmission modulation TxSelReg = 0x16 << 1, // selects the internal sources for the antenna driver RxSelReg = 0x17 << 1, // selects internal receiver settings RxThresholdReg = 0x18 << 1, // selects thresholds for the bit decoder DemodReg = 0x19 << 1, // defines demodulator settings // 0x1A // reserved for future use // 0x1B // reserved for future use MfTxReg = 0x1C << 1, // controls some MIFARE communication transmit parameters MfRxReg = 0x1D << 1, // controls some MIFARE communication receive parameters // 0x1E // reserved for future use SerialSpeedReg = 0x1F << 1, // selects the speed of the serial UART interface // Page 2: Configuration // 0x20 // reserved for future use CRCResultRegH = 0x21 << 1, // shows the MSB and LSB values of the CRC calculation CRCResultRegL = 0x22 << 1, // 0x23 // reserved for future use ModWidthReg = 0x24 << 1, // controls the ModWidth setting? // 0x25 // reserved for future use RFCfgReg = 0x26 << 1, // configures the receiver gain GsNReg = 0x27 << 1, // selects the conductance of the antenna driver pins TX1 and TX2 for modulation CWGsPReg = 0x28 << 1, // defines the conductance of the p-driver output during periods of no modulation ModGsPReg = 0x29 << 1, // defines the conductance of the p-driver output during periods of modulation TModeReg = 0x2A << 1, // defines settings for the internal timer TPrescalerReg = 0x2B << 1, // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg. TReloadRegH = 0x2C << 1, // defines the 16-bit timer reload value TReloadRegL = 0x2D << 1, TCounterValueRegH = 0x2E << 1, // shows the 16-bit timer value TCounterValueRegL = 0x2F << 1, // Page 3: Test Registers // 0x30 // reserved for future use TestSel1Reg = 0x31 << 1, // general test signal configuration TestSel2Reg = 0x32 << 1, // general test signal configuration TestPinEnReg = 0x33 << 1, // enables pin output driver on pins D1 to D7 TestPinValueReg = 0x34 << 1, // defines the values for D1 to D7 when it is used as an I/O bus TestBusReg = 0x35 << 1, // shows the status of the internal test bus AutoTestReg = 0x36 << 1, // controls the digital self-test VersionReg = 0x37 << 1, // shows the software version AnalogTestReg = 0x38 << 1, // controls the pins AUX1 and AUX2 TestDAC1Reg = 0x39 << 1, // defines the test value for TestDAC1 TestDAC2Reg = 0x3A << 1, // defines the test value for TestDAC2 TestADCReg = 0x3B << 1 // shows the value of ADC I and Q channels // 0x3C // reserved for production tests // 0x3D // reserved for production tests // 0x3E // reserved for production tests // 0x3F // reserved for production tests }; // MFRC522 commands. Described in chapter 10 of the datasheet. enum PCD_Command : byte { PCD_Idle = 0x00, // no action, cancels current command execution PCD_Mem = 0x01, // stores 25 bytes into the internal buffer PCD_GenerateRandomID = 0x02, // generates a 10-byte random ID number PCD_CalcCRC = 0x03, // activates the CRC coprocessor or performs a self-test PCD_Transmit = 0x04, // transmits data from the FIFO buffer PCD_NoCmdChange = 0x07, // no command change, can be used to modify the CommandReg register bits without affecting the command, for example, the PowerDown bit PCD_Receive = 0x08, // activates the receiver circuits PCD_Transceive = 0x0C, // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission PCD_MFAuthent = 0x0E, // performs the MIFARE standard authentication as a reader PCD_SoftReset = 0x0F // resets the MFRC522 }; // MFRC522 RxGain[2:0] masks, defines the receiver's signal voltage gain factor (on the PCD). // Described in 9.3.3.6 / table 98 of the datasheet at http://www.nxp.com/documents/data_sheet/MFRC522.pdf enum PCD_RxGain : byte { RxGain_18dB = 0x00 << 4, // 000b - 18 dB, minimum RxGain_23dB = 0x01 << 4, // 001b - 23 dB RxGain_18dB_2 = 0x02 << 4, // 010b - 18 dB, it seems 010b is a duplicate for 000b RxGain_23dB_2 = 0x03 << 4, // 011b - 23 dB, it seems 011b is a duplicate for 001b RxGain_33dB = 0x04 << 4, // 100b - 33 dB, average, and typical default RxGain_38dB = 0x05 << 4, // 101b - 38 dB RxGain_43dB = 0x06 << 4, // 110b - 43 dB RxGain_48dB = 0x07 << 4, // 111b - 48 dB, maximum RxGain_min = 0x00 << 4, // 000b - 18 dB, minimum, convenience for RxGain_18dB RxGain_avg = 0x04 << 4, // 100b - 33 dB, average, convenience for RxGain_33dB RxGain_max = 0x07 << 4 // 111b - 48 dB, maximum, convenience for RxGain_48dB }; // Commands sent to the PICC. enum PICC_Command : byte { // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4) PICC_CMD_REQA = 0x26, // REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame. PICC_CMD_WUPA = 0x52, // Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame. PICC_CMD_CT = 0x88, // Cascade Tag. Not really a command, but used during anti collision. PICC_CMD_SEL_CL1 = 0x93, // Anti collision/Select, Cascade Level 1 PICC_CMD_SEL_CL2 = 0x95, // Anti collision/Select, Cascade Level 2 PICC_CMD_SEL_CL3 = 0x97, // Anti collision/Select, Cascade Level 3 PICC_CMD_HLTA = 0x50, // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT. PICC_CMD_RATS = 0xE0, // Request command for Answer To Reset. // The commands used for MIFARE Classic (from http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf, Section 9) // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on the sector. // The read/write commands can also be used for MIFARE Ultralight. PICC_CMD_MF_AUTH_KEY_A = 0x60, // Perform authentication with Key A PICC_CMD_MF_AUTH_KEY_B = 0x61, // Perform authentication with Key B PICC_CMD_MF_READ = 0x30, // Reads one 16 byte block from the authenticated sector of the PICC. Also used for MIFARE Ultralight. PICC_CMD_MF_WRITE = 0xA0, // Writes one 16 byte block to the authenticated sector of the PICC. Called "COMPATIBILITY WRITE" for MIFARE Ultralight. PICC_CMD_MF_DECREMENT = 0xC0, // Decrements the contents of a block and stores the result in the internal data register. PICC_CMD_MF_INCREMENT = 0xC1, // Increments the contents of a block and stores the result in the internal data register. PICC_CMD_MF_RESTORE = 0xC2, // Reads the contents of a block into the internal data register. PICC_CMD_MF_TRANSFER = 0xB0, // Writes the contents of the internal data register to a block. // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6) // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight. PICC_CMD_UL_WRITE = 0xA2 // Writes one 4 byte page to the PICC. }; // MIFARE constants that does not fit anywhere else enum MIFARE_Misc { MF_ACK = 0xA, // The MIFARE Classic uses a 4 bit ACK/NAK. Any other value than 0xA is NAK. MF_KEY_SIZE = 6 // A Mifare Crypto1 key is 6 bytes. }; // PICC types we can detect. Remember to update PICC_GetTypeName() if you add more. // last value set to 0xff, then compiler uses less ram, it seems some optimisations are triggered enum PICC_Type : byte { PICC_TYPE_UNKNOWN , PICC_TYPE_ISO_14443_4 , // PICC compliant with ISO/IEC 14443-4 PICC_TYPE_ISO_18092 , // PICC compliant with ISO/IEC 18092 (NFC) PICC_TYPE_MIFARE_MINI , // MIFARE Classic protocol, 320 bytes PICC_TYPE_MIFARE_1K , // MIFARE Classic protocol, 1KB PICC_TYPE_MIFARE_4K , // MIFARE Classic protocol, 4KB PICC_TYPE_MIFARE_UL , // MIFARE Ultralight or Ultralight C PICC_TYPE_MIFARE_PLUS , // MIFARE Plus PICC_TYPE_MIFARE_DESFIRE, // MIFARE DESFire PICC_TYPE_TNP3XXX , // Only mentioned in NXP AN 10833 MIFARE Type Identification Procedure PICC_TYPE_NOT_COMPLETE = 0xff // SAK indicates UID is not complete. }; // Return codes from the functions in this class. Remember to update GetStatusCodeName() if you add more. // last value set to 0xff, then compiler uses less ram, it seems some optimisations are triggered enum StatusCode : byte { STATUS_OK , // Success STATUS_ERROR , // Error in communication STATUS_COLLISION , // Collission detected STATUS_TIMEOUT , // Timeout in communication. STATUS_NO_ROOM , // A buffer is not big enough. STATUS_INTERNAL_ERROR , // Internal error in the code. Should not happen ;-) STATUS_INVALID , // Invalid argument. STATUS_CRC_WRONG , // The CRC_A does not match STATUS_MIFARE_NACK = 0xff // A MIFARE PICC responded with NAK. }; // A struct used for passing the UID of a PICC. typedef struct { byte size; // Number of bytes in the UID. 4, 7 or 10. byte uidByte[10]; byte sak; // The SAK (Select acknowledge) byte returned from the PICC after successful selection. } Uid; // A struct used for passing a MIFARE Crypto1 key typedef struct { byte keyByte[MF_KEY_SIZE]; } MIFARE_Key; // Member variables Uid uid; // Used by PICC_ReadCardSerial(). ///////////////////////////////////////////////////////////////////////////////////// // Functions for setting up the Arduino ///////////////////////////////////////////////////////////////////////////////////// MFRC522(); DEPRECATED_MSG("use MFRC522(byte chipSelectPin, byte resetPowerDownPin)") MFRC522(byte resetPowerDownPin); MFRC522(byte chipSelectPin, byte resetPowerDownPin); ///////////////////////////////////////////////////////////////////////////////////// // Basic interface functions for communicating with the MFRC522 ///////////////////////////////////////////////////////////////////////////////////// void PCD_WriteRegister(PCD_Register reg, byte value); void PCD_WriteRegister(PCD_Register reg, byte count, byte *values); byte PCD_ReadRegister(PCD_Register reg); void PCD_ReadRegister(PCD_Register reg, byte count, byte *values, byte rxAlign = 0); void PCD_SetRegisterBitMask(PCD_Register reg, byte mask); void PCD_ClearRegisterBitMask(PCD_Register reg, byte mask); StatusCode PCD_CalculateCRC(byte *data, byte length, byte *result); ///////////////////////////////////////////////////////////////////////////////////// // Functions for manipulating the MFRC522 ///////////////////////////////////////////////////////////////////////////////////// void PCD_Init(); DEPRECATED_MSG("use PCD_Init(byte chipSelectPin, byte resetPowerDownPin)") void PCD_Init(byte resetPowerDownPin); void PCD_Init(byte chipSelectPin, byte resetPowerDownPin); void PCD_Reset(); void PCD_AntennaOn(); void PCD_AntennaOff(); byte PCD_GetAntennaGain(); void PCD_SetAntennaGain(byte mask); ///////////////////////////////////////////////////////////////////////////////////// // Functions for communicating with PICCs ///////////////////////////////////////////////////////////////////////////////////// StatusCode PCD_TransceiveData(byte *sendData, byte sendLen, byte *backData, byte *backLen, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); StatusCode PCD_CommunicateWithPICC(byte command, byte waitIRq, byte *sendData, byte sendLen, byte *backData = NULL, byte *backLen = NULL, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); StatusCode PICC_RequestA(byte *bufferATQA, byte *bufferSize); StatusCode PICC_WakeupA(byte *bufferATQA, byte *bufferSize); StatusCode PICC_REQA_or_WUPA(byte command, byte *bufferATQA, byte *bufferSize); virtual StatusCode PICC_Select(Uid *uid, byte validBits = 0); StatusCode PICC_HaltA(); ///////////////////////////////////////////////////////////////////////////////////// // Functions for communicating with MIFARE PICCs ///////////////////////////////////////////////////////////////////////////////////// StatusCode PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid); void PCD_StopCrypto1(); StatusCode MIFARE_Read(byte blockAddr, byte *buffer, byte *bufferSize); StatusCode MIFARE_Write(byte blockAddr, byte *buffer, byte bufferSize); StatusCode MIFARE_Ultralight_Write(byte page, byte *buffer, byte bufferSize); StatusCode MIFARE_Decrement(byte blockAddr, int32_t delta); StatusCode MIFARE_Increment(byte blockAddr, int32_t delta); StatusCode MIFARE_Restore(byte blockAddr); StatusCode MIFARE_Transfer(byte blockAddr); StatusCode MIFARE_GetValue(byte blockAddr, int32_t *value); StatusCode MIFARE_SetValue(byte blockAddr, int32_t value); StatusCode PCD_NTAG216_AUTH(byte *passWord, byte pACK[]); ///////////////////////////////////////////////////////////////////////////////////// // Support functions ///////////////////////////////////////////////////////////////////////////////////// StatusCode PCD_MIFARE_Transceive(byte *sendData, byte sendLen, bool acceptTimeout = false); // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory //const char *GetStatusCodeName(byte code); static const char *GetStatusCodeName(StatusCode code); static PICC_Type PICC_GetType(byte sak); // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory //const char *PICC_GetTypeName(byte type); static const char *PICC_GetTypeName(PICC_Type type); void PCD_DumpVersionToSerial(); ///////////////////////////////////////////////////////////////////////////////////// // Convenience functions - does not add extra functionality ///////////////////////////////////////////////////////////////////////////////////// virtual bool PICC_IsNewCardPresent(); virtual bool PICC_ReadCardSerial(); protected: int _fd; byte _chipSelectPin; // Arduino pin connected to MFRC522's SPI slave select input (Pin 24, NSS, active low) byte _resetPowerDownPin; // Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low) StatusCode MIFARE_TwoStepHelper(byte command, byte blockAddr, int32_t data); }; #endif
f7eafb8ec475577fc6d885518a74e0e976fb6dc6
b9081b5b1824a7ac34bb39c85ecc0331a5f06d46
/CPP/Testbox/COM-server/stdafx.cpp
421aa3097cb3b7c75587c6a39fa49c549e40bf4a
[]
no_license
mightymamont/Demos
6cee3e6d5bd67ae7da541c97d85ac5d2b5ffd089
c00c4c5b7a6276974f001ed54a693a6e49074097
refs/heads/master
2020-05-17T03:47:15.790834
2013-05-28T17:50:41
2013-05-28T17:50:41
9,468,813
0
1
null
null
null
null
WINDOWS-1251
C++
false
false
380
cpp
// stdafx.cpp: исходный файл, содержащий только стандартные включаемые модули // COM-server.pch будет предкомпилированным заголовком // stdafx.obj будет содержать предварительно откомпилированные сведения о типе #include "stdafx.h"
42b279be42250c5e6669cedc4649d76b60efdf84
0203c18e12531e00ef5154776cb32b731e6688d0
/PBINFO/160-inserareinainte.cpp
8ca685a6df187d26d1bbb4581d4e37e05f1ac21f
[]
no_license
KiraBeleaua/Solved-Problems
a656566e4592f206365a11cff670139baa27c80a
99a2343883faa9e0d61d8a92b8e82f9a0d89c2c2
refs/heads/main
2023-06-20T23:10:18.496603
2021-07-15T22:50:56
2021-07-15T22:50:56
359,094,167
0
0
null
null
null
null
UTF-8
C++
false
false
1,569
cpp
#include <iostream> #include <vector> #include <math.h> #include <algorithm> #include <iomanip> #include <array> using namespace std; void printVector(vector<int64_t> v) { for (auto& el : v) { cout << el << " "; } cout << "\n"; } int maximAdi(vector<int64_t> v) { int64_t maxim = v[0], indice = 0; for (int i = 0; i < v.size() - 1; i++) { if (v[i] < v[i + 1] && maxim < v[i + 1]) { maxim = v[i + 1]; indice = i + 1; } else if (v[i] > v[i + 1] && maxim < v[i]) { maxim = v[i]; indice = i; } } return maxim; } int maxim(vector<int64_t> v) { int64_t m = v[0]; for (auto el : v) { m = max(el, m); } return m; } vector<int64_t> generateRandomVector(int64_t n, int64_t left, int64_t right) { srand(time(NULL)); int64_t space = right - left; vector <int64_t> v; for (int i = 0; i < n; i++) { int64_t el = rand() % space + left; v.push_back(el); } return v; } int64_t maxVector(vector<int64_t> a) { int64_t m = a[0]; for (int i = 1; i < a.size(); i++) { m = max(a[i], m); } return m; } int64_t maximIndiceVector(vector<int64_t> a) { int64_t m = a[0]; int indice = 0; for (int i = 1; i < a.size(); i++) { if (a[i] > m) { m = a[i]; indice = i; } } return indice; } int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } int main() { int64_t n, ceva; cin >> n; vector <int64_t> v; v.resize(n); for (auto& el : v) { cin >> el; } for (int i = 0; i < n; i++) { ceva = sqrt(v[i]); if (ceva * ceva == v[i]) { v.insert(v.begin() + i, sqrt(v[i])); n++; i++; } } printVector(v); }
e5e0090abe302ec69b6d20a98606cbb6675290f5
d7d33966eaedb1f64182a8d39036c60fe068e074
/sources/Renderer/Direct3D11/D3D11CommandQueue.h
a60f4004b1f9c191132ef13df0803b07c4c2da2e
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
beldenfox/LLGL
7aca3d5902bba9f8e09f09d0dd3808756be3088c
3a54125ebfa79bb06fccf8c413d308ff22186b52
refs/heads/master
2023-07-12T09:32:31.348478
2021-08-24T03:41:24
2021-08-26T16:55:47
275,416,529
1
0
NOASSERTION
2020-06-27T17:01:24
2020-06-27T17:01:24
null
UTF-8
C++
false
false
2,219
h
/* * D3D11CommandQueue.h * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #ifndef LLGL_D3D11_COMMAND_QUEUE_H #define LLGL_D3D11_COMMAND_QUEUE_H #include <LLGL/CommandQueue.h> #include <LLGL/ForwardDecls.h> #include "RenderState/D3D11Fence.h" #include "../DXCommon/ComPtr.h" #include <d3d11.h> namespace LLGL { class D3D11QueryHeap; class D3D11CommandQueue final : public CommandQueue { public: D3D11CommandQueue(ID3D11Device* device, ComPtr<ID3D11DeviceContext>& context); /* ----- Command Buffers ----- */ void Submit(CommandBuffer& commandBuffer) override; /* ----- Queries ----- */ bool QueryResult( QueryHeap& queryHeap, std::uint32_t firstQuery, std::uint32_t numQueries, void* data, std::size_t dataSize ) override; /* ----- Fences ----- */ void Submit(Fence& fence) override; bool WaitFence(Fence& fence, std::uint64_t timeout) override; void WaitIdle() override; private: bool QueryResultSingleUInt64( D3D11QueryHeap& queryHeapD3D, std::uint32_t query, std::uint64_t& data ); bool QueryResultUInt32( D3D11QueryHeap& queryHeapD3D, std::uint32_t firstQuery, std::uint32_t numQueries, std::uint32_t* data ); bool QueryResultUInt64( D3D11QueryHeap& queryHeapD3D, std::uint32_t firstQuery, std::uint32_t numQueries, std::uint64_t* data ); bool QueryResultPipelineStatistics( D3D11QueryHeap& queryHeapD3D, std::uint32_t firstQuery, std::uint32_t numQueries, QueryPipelineStatistics* data ); private: ComPtr<ID3D11DeviceContext> context_; D3D11Fence intermediateFence_; }; } // /namespace LLGL #endif // ================================================================================
29f3304abd4224fca2ac1bbffc31d47e70ac9c88
a909df0ba2abf695df4a7d15350312d4c6463c48
/UVa/914.cpp
b00c22dd359d4364f940a10cc666bad9da142689
[]
no_license
SayaUrobuchi/uvachan
1dadd767a96bb02c7e9449c48e463847480e98ec
c213f5f3dcfc72376913a21f9abe72988a8127a1
refs/heads/master
2023-07-23T03:59:50.638063
2023-07-16T04:31:23
2023-07-16T04:31:23
94,064,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
cpp
#include<stdio.h> #include<math.h> int a,b,c,d,e,f,g,h,i,j,k[78498][2],l[115]; int main() { k[0][0]=2; k[0][1]=0; k[1][0]=3; k[1][1]=1; for(a=5,b=1;a<1000001;a+=2) { c=sqrt(a)+1; for(d=0;k[d][0]<c;d++) { if(!(a%k[d][0])) { break; } } if(k[d][0]>c-1) { k[++b][0]=a; k[b][1]=a-k[b-1][0]; } } scanf("%d",&h); for(g=115;h>0;h--) { scanf("%d%d",&a,&b); i=0; j=78497; while(1) { c=i+j; c/=2; if(k[c][0]==a) { break; } else if(a>k[c][0]) { i=c+1; if(i>j) { c++; break; } } else { j=c-1; if(i>j) { break; } } } i=0; j=78497; while(1) { d=i+j; d/=2; if(k[d][0]==b) { break; } else if(b>k[d][0]) { i=d+1; if(i>j) { break; } } else { j=d-1; if(i>j) { d--; break; } } } if(c==d) { printf("No jumping champion\n"); continue; } for(e=1;e<g;e++) { l[e]=0; } for(d++,e=c+1;e<d;e++) { l[k[e][1]]++; } for(e=1,i=0;e<115;e++) { if(l[e]>i) { i=l[e]; f=e; j=0; } else if(l[e]==i) { j=1; } } if(j) { printf("No jumping champion\n"); } else { printf("The jumping champion is %d\n",f); } } return 0; }
f0bce646dc1cfc3935173a6f79173e277f2ef698
32dadc18334247e1523e4a7e64ec3f2746c688e5
/common/Enum.h
d4219b8512827523d15eb54c81994c6a596d72f2
[]
no_license
rdspring1/cs393r
95861c3705119602d82dc53b4740af093f9ed295
150bdd9e759ce32ae222bad92437304171d85d01
refs/heads/master
2021-01-19T00:25:58.218904
2013-12-09T04:15:50
2013-12-09T04:15:50
13,565,545
1
0
null
null
null
null
UTF-8
C++
false
false
2,162
h
#ifndef ENUM_H_D82U9SWU #define ENUM_H_D82U9SWU /* * @file Tools/Enum.h * Defines a macro that declares an enum and provides * a function to access the names of its elements. * * @author Thomas Röfer */ #include <string> #include <vector> /** * @class EnumName * The class converts a single comma-separated string of enum names * into single entries that can be accessed in constant time. * It is the worker class for the templated version below. */ class EnumName { private: std::vector<std::string> names; /**< The vector of enum names. */ /** * A method that trims a string, i.e. removes spaces from its * beginning and end. * @param s The string that is trimmed. * @return The string without spaces at the beginning and at its end. */ static std::string trim(const std::string& s); public: /** * Constructor. * @param enums A string that contains a comma-separated list of enum * elements. It is allowed that an element is initialized * with the value of its predecessor. Any other * initializations are forbidden. * "a, b, numOfLettersBeforeC, c = numOfLettersBeforeC, d" * would be a legal parameter. * @param numOfEnums The number of enums in the string. Reassignments do * not count, i.e. in the example above, this * parameter had to be 4. */ EnumName(const std::string& enums, size_t numOfEnums); /** * The method returns the name of an enum element. * @param index The index of the enum element. * @return Its name. */ const char* getName(size_t e) {return e >= names.size() ? 0 : names[e].c_str();} }; /** * Defining an enum and a function get<Enum>Name(<Enum>) that can return * the name of each enum element. The enum will automatically * contain an element NUM_<Enum>s that reflects the number of * elements defined. */ #define ENUM(Enum, ...) \ enum Enum {__VA_ARGS__, NUM_##Enum##s}; \ inline static const char* getName(Enum e) {static EnumName en(#__VA_ARGS__, (size_t) NUM_##Enum##s); return en.getName((size_t) e);} #endif /* end of include guard: ENUM_H_D82U9SWU */
8fcdb1275358ddb0ed3c2eea73f669db94fe086c
0aa8118cb3dd196832628f238e54c74912b27e83
/firmware/arduino/src/Sensors/BatteryVoltageSensor/BatteryVoltageSensor.cpp
8729ec99638a851bd830754038762b33f646fd02
[]
no_license
carlesm/covid19-ventilator
ffa9e6202de8dee74be026597747b090474cf61a
5a322fdb95b9e0057bf1b54026d13986b3f17aef
refs/heads/master
2022-04-18T20:31:14.442473
2020-04-16T03:11:12
2020-04-16T03:11:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
#include "BatteryVoltageSensor.h" BatteryVoltageSensor::BatteryVoltageSensor(int pin) { _pin = pin; } float BatteryVoltageSensor::read() { float batteryVoltage = (float) analogRead(_pin)*15.974/1024; // from eamon data sheeet return batteryVoltage; } int BatteryVoltageSensor::readPercentage() { // this isnt perfect (far from it as we dont know what the current draw is or the size of battery. this is a guess at best) float batteryVoltage = read(); int batteryPercentage = constrain(map(batteryVoltage, 11.3, 12.8, 0, 100), 0, 100); return batteryPercentage; }
7a52f170ac7ec853012a7f5904ceb8d752658236
a59e0fc4a9c573794bba987548dfc7680a1d04d5
/granary/base/operator.h
80b10afcf712b720bcea39ca7728069b695f105a
[ "MIT" ]
permissive
00mjk/granary2
cc671bf83b02b44e1408e63248dd24c2c14f574b
66f60e0a9d94c9e9bf9df78587871b981c9e3bed
refs/heads/master
2021-09-15T09:28:39.502722
2016-10-22T19:37:07
2016-10-22T19:37:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
/* Copyright 2014 Peter Goodman, all rights reserved. */ #ifndef GRANARY_BASE_OPERATOR_H_ #define GRANARY_BASE_OPERATOR_H_ #include "granary/base/base.h" // For placement new. namespace granary { // Initialize some meta-data. template <typename T> void Construct(void *mem) { new (mem) T; } // Initialize some meta-data. template <typename T> void CopyConstruct(void *mem, const void *that) { new (mem) T(*reinterpret_cast<const T *>(that)); } // Destroy some meta-data. template <typename T> void Destruct(void *mem) { reinterpret_cast<T *>(mem)->~T(); } } // namespace granary #endif // GRANARY_BASE_OPERATOR_H_
06d8815cfa5368ab48e2a68c9dd10e3b6966d277
9ff8e317e7293033e3983c5e6660adc4eff75762
/Gamecore/lists/SGF_AirList.h
5b7eaaf2c49004f1580060dcb27e29bbd948e0be
[]
no_license
rasputtim/SGF
b26fd29487b93c8e67c73f866635830796970116
d8af92216bf4e86aeb452fda841c73932de09b65
refs/heads/master
2020-03-28T21:55:14.668643
2018-11-03T21:15:32
2018-11-03T21:15:32
147,579,544
0
0
null
null
null
null
IBM852
C++
false
false
1,456
h
/* SGF - Super Game Fabric Super Game Fabric Copyright (C) 2010-2011 Rasputtim <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // VorGaenger = Antecessor // Anfang = Comešo // Aktuell = Corrente, Atual // Hinzufuegen = Adicionar // Ende = Final // NachFolger = Sucessor #ifndef AIRLIST_H #define AIRLIST_H #include "../SGF_Config.h" #include "liststructs.h" using namespace std; namespace SGF{ class SGE_API CAirList { public: CAirList(); ~CAirList(); public: AirLinkedList *Corrente; AirLinkedList *Comeco; AirLinkedList *Final; public: void Adicionar(AirLinkedList *AirData); void Next(); void Prev(); void SetStart(){Corrente=Comeco;}; AirLinkedList *GetAirData(){return Corrente;} void CleanUpTheList(); }; } //end SGF #endif
f5c75fc3abc7a41cd5148cc1aecf3c7053f05319
9da42e04bdaebdf0193a78749a80c4e7bf76a6cc
/third_party/gecko-15/win32/include/nsIDOMHTMLTableColElement.h
3805c6d1df35d6ff9cf8d56cb0f7ca385cf72c16
[ "Apache-2.0" ]
permissive
bwp/SeleniumWebDriver
9d49e6069881845e9c23fb5211a7e1b8959e2dcf
58221fbe59fcbbde9d9a033a95d45d576b422747
refs/heads/master
2021-01-22T21:32:50.541163
2012-11-09T16:19:48
2012-11-09T16:19:48
6,602,097
1
0
null
null
null
null
UTF-8
C++
false
false
7,925
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/dom/interfaces/html/nsIDOMHTMLTableColElement.idl */ #ifndef __gen_nsIDOMHTMLTableColElement_h__ #define __gen_nsIDOMHTMLTableColElement_h__ #ifndef __gen_nsIDOMHTMLElement_h__ #include "nsIDOMHTMLElement.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMHTMLTableColElement */ #define NS_IDOMHTMLTABLECOLELEMENT_IID_STR "8f98865c-1600-4282-a553-838d87cc9f1f" #define NS_IDOMHTMLTABLECOLELEMENT_IID \ {0x8f98865c, 0x1600, 0x4282, \ { 0xa5, 0x53, 0x83, 0x8d, 0x87, 0xcc, 0x9f, 0x1f }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMHTMLTableColElement : public nsIDOMHTMLElement { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMHTMLTABLECOLELEMENT_IID) /* attribute DOMString align; */ NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign) = 0; NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign) = 0; /* attribute DOMString ch; */ NS_SCRIPTABLE NS_IMETHOD GetCh(nsAString & aCh) = 0; NS_SCRIPTABLE NS_IMETHOD SetCh(const nsAString & aCh) = 0; /* attribute DOMString chOff; */ NS_SCRIPTABLE NS_IMETHOD GetChOff(nsAString & aChOff) = 0; NS_SCRIPTABLE NS_IMETHOD SetChOff(const nsAString & aChOff) = 0; /* attribute long span; */ NS_SCRIPTABLE NS_IMETHOD GetSpan(PRInt32 *aSpan) = 0; NS_SCRIPTABLE NS_IMETHOD SetSpan(PRInt32 aSpan) = 0; /* attribute DOMString vAlign; */ NS_SCRIPTABLE NS_IMETHOD GetVAlign(nsAString & aVAlign) = 0; NS_SCRIPTABLE NS_IMETHOD SetVAlign(const nsAString & aVAlign) = 0; /* attribute DOMString width; */ NS_SCRIPTABLE NS_IMETHOD GetWidth(nsAString & aWidth) = 0; NS_SCRIPTABLE NS_IMETHOD SetWidth(const nsAString & aWidth) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMHTMLTableColElement, NS_IDOMHTMLTABLECOLELEMENT_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMHTMLTABLECOLELEMENT \ NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign); \ NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign); \ NS_SCRIPTABLE NS_IMETHOD GetCh(nsAString & aCh); \ NS_SCRIPTABLE NS_IMETHOD SetCh(const nsAString & aCh); \ NS_SCRIPTABLE NS_IMETHOD GetChOff(nsAString & aChOff); \ NS_SCRIPTABLE NS_IMETHOD SetChOff(const nsAString & aChOff); \ NS_SCRIPTABLE NS_IMETHOD GetSpan(PRInt32 *aSpan); \ NS_SCRIPTABLE NS_IMETHOD SetSpan(PRInt32 aSpan); \ NS_SCRIPTABLE NS_IMETHOD GetVAlign(nsAString & aVAlign); \ NS_SCRIPTABLE NS_IMETHOD SetVAlign(const nsAString & aVAlign); \ NS_SCRIPTABLE NS_IMETHOD GetWidth(nsAString & aWidth); \ NS_SCRIPTABLE NS_IMETHOD SetWidth(const nsAString & aWidth); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMHTMLTABLECOLELEMENT(_to) \ NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign) { return _to GetAlign(aAlign); } \ NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign) { return _to SetAlign(aAlign); } \ NS_SCRIPTABLE NS_IMETHOD GetCh(nsAString & aCh) { return _to GetCh(aCh); } \ NS_SCRIPTABLE NS_IMETHOD SetCh(const nsAString & aCh) { return _to SetCh(aCh); } \ NS_SCRIPTABLE NS_IMETHOD GetChOff(nsAString & aChOff) { return _to GetChOff(aChOff); } \ NS_SCRIPTABLE NS_IMETHOD SetChOff(const nsAString & aChOff) { return _to SetChOff(aChOff); } \ NS_SCRIPTABLE NS_IMETHOD GetSpan(PRInt32 *aSpan) { return _to GetSpan(aSpan); } \ NS_SCRIPTABLE NS_IMETHOD SetSpan(PRInt32 aSpan) { return _to SetSpan(aSpan); } \ NS_SCRIPTABLE NS_IMETHOD GetVAlign(nsAString & aVAlign) { return _to GetVAlign(aVAlign); } \ NS_SCRIPTABLE NS_IMETHOD SetVAlign(const nsAString & aVAlign) { return _to SetVAlign(aVAlign); } \ NS_SCRIPTABLE NS_IMETHOD GetWidth(nsAString & aWidth) { return _to GetWidth(aWidth); } \ NS_SCRIPTABLE NS_IMETHOD SetWidth(const nsAString & aWidth) { return _to SetWidth(aWidth); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMHTMLTABLECOLELEMENT(_to) \ NS_SCRIPTABLE NS_IMETHOD GetAlign(nsAString & aAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAlign(aAlign); } \ NS_SCRIPTABLE NS_IMETHOD SetAlign(const nsAString & aAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAlign(aAlign); } \ NS_SCRIPTABLE NS_IMETHOD GetCh(nsAString & aCh) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCh(aCh); } \ NS_SCRIPTABLE NS_IMETHOD SetCh(const nsAString & aCh) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCh(aCh); } \ NS_SCRIPTABLE NS_IMETHOD GetChOff(nsAString & aChOff) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetChOff(aChOff); } \ NS_SCRIPTABLE NS_IMETHOD SetChOff(const nsAString & aChOff) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetChOff(aChOff); } \ NS_SCRIPTABLE NS_IMETHOD GetSpan(PRInt32 *aSpan) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSpan(aSpan); } \ NS_SCRIPTABLE NS_IMETHOD SetSpan(PRInt32 aSpan) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetSpan(aSpan); } \ NS_SCRIPTABLE NS_IMETHOD GetVAlign(nsAString & aVAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetVAlign(aVAlign); } \ NS_SCRIPTABLE NS_IMETHOD SetVAlign(const nsAString & aVAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetVAlign(aVAlign); } \ NS_SCRIPTABLE NS_IMETHOD GetWidth(nsAString & aWidth) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetWidth(aWidth); } \ NS_SCRIPTABLE NS_IMETHOD SetWidth(const nsAString & aWidth) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetWidth(aWidth); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMHTMLTableColElement : public nsIDOMHTMLTableColElement { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMHTMLTABLECOLELEMENT nsDOMHTMLTableColElement(); private: ~nsDOMHTMLTableColElement(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMHTMLTableColElement, nsIDOMHTMLTableColElement) nsDOMHTMLTableColElement::nsDOMHTMLTableColElement() { /* member initializers and constructor code */ } nsDOMHTMLTableColElement::~nsDOMHTMLTableColElement() { /* destructor code */ } /* attribute DOMString align; */ NS_IMETHODIMP nsDOMHTMLTableColElement::GetAlign(nsAString & aAlign) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMHTMLTableColElement::SetAlign(const nsAString & aAlign) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute DOMString ch; */ NS_IMETHODIMP nsDOMHTMLTableColElement::GetCh(nsAString & aCh) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMHTMLTableColElement::SetCh(const nsAString & aCh) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute DOMString chOff; */ NS_IMETHODIMP nsDOMHTMLTableColElement::GetChOff(nsAString & aChOff) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMHTMLTableColElement::SetChOff(const nsAString & aChOff) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute long span; */ NS_IMETHODIMP nsDOMHTMLTableColElement::GetSpan(PRInt32 *aSpan) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMHTMLTableColElement::SetSpan(PRInt32 aSpan) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute DOMString vAlign; */ NS_IMETHODIMP nsDOMHTMLTableColElement::GetVAlign(nsAString & aVAlign) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMHTMLTableColElement::SetVAlign(const nsAString & aVAlign) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute DOMString width; */ NS_IMETHODIMP nsDOMHTMLTableColElement::GetWidth(nsAString & aWidth) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMHTMLTableColElement::SetWidth(const nsAString & aWidth) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMHTMLTableColElement_h__ */
60980f21da2a000368dd10a1cd59f776bb2a236f
cd638ac1cd7633ac5bc9a92e77e90f3a53a5cc80
/World CodeSprint 12/Red Knight's Shortest Path.cpp
fa77da8a3a6efea13740ea9309d763123bfced9b
[ "MIT" ]
permissive
Jvillegasd/HackerRank
f756ddcac69fa9c541e635317bee66e8b7a0e793
feef30d9f396ba6f85fef8a5a474d9af8e71c69d
refs/heads/master
2021-08-29T21:33:33.243836
2017-12-15T02:59:13
2017-12-15T02:59:13
114,320,224
1
0
null
null
null
null
UTF-8
C++
false
false
1,917
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <queue> #include <cstring> using namespace std; bool visited[250][250] = {0}; const int rows[] = {-2, -2, 0, 2, 2, 0}, cols[] = {-1, 1, 2, 1, -1, -2}; const string mov[] = {"UL", "UR" , "R", "LR", "LL", "L"}; int n; struct Node{ int row, col, moves; int indices[3000]; void init(int row, int col, int moves){ this->row = row; this->col = col; this->moves = moves; } }; bool validValues(int row, int col){ if(row < 0 || col < 0 || row > n || col > n) return false; return true; } bool BFS(Node in, int rowF, int colF){ queue<Node> cola; cola.push(in); while(!cola.empty()){ Node nodo = cola.front(); cola.pop(); int row2 = nodo.row; int col2 = nodo.col; if(row2 == rowF && col2 == colF){ printf("%d\n", nodo.moves); for(int i = 0; i < nodo.moves; i++){ printf("%s", mov[nodo.indices[i]].c_str()); if(i != nodo.moves - 1) printf(" "); } printf("\n"); return true; } if(visited[row2][col2]) continue; visited[row2][col2] = true; for(int i = 0; i < 6; i++){ int nRow = row2 + rows[i]; int nCol = col2 + cols[i]; if(validValues(nRow, nCol)){ Node nNodo; nNodo.init(nRow, nCol, nodo.moves + 1); nodo.indices[nodo.moves] = i; for(int j = 0; j < nodo.moves + 1; j++) nNodo.indices[j] = nodo.indices[j]; cola.push(nNodo); } } } return false; } int main() { int rowO, colO, row, col; cin >> n; cin >> rowO >> colO >> row >> col; Node in; in.init(rowO, colO, 0); if(!BFS(in, row, col)) printf("Impossible\n"); return 0; }
19acc8bf8761a46ac46e0e500495ea640b25c1fe
16ace91e34501883bfeb8df55ff168189db983e8
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
96175301de570fca85466dd317d0a0c04c99fa05
[]
no_license
minico/Android
4bfa0923b896aed82d2b54610fc68cd72257a628
71bd4bea5466bc7c017bf9baa1aa369f597ce13e
refs/heads/master
2020-12-24T06:08:32.844033
2016-06-27T01:58:03
2016-06-27T01:58:03
61,892,950
0
0
null
null
null
null
UTF-8
C++
false
false
134,610
cpp
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define ATRACE_TAG ATRACE_TAG_GRAPHICS #include <stdint.h> #include <sys/types.h> #include <errno.h> #include <math.h> #include <dlfcn.h> #include <inttypes.h> #include <stdatomic.h> #include <EGL/egl.h> #include <cutils/log.h> #include <cutils/properties.h> #include <binder/IPCThreadState.h> #include <binder/IServiceManager.h> #include <binder/MemoryHeapBase.h> #include <binder/PermissionCache.h> #include <ui/DisplayInfo.h> #include <ui/DisplayStatInfo.h> #include <gui/BitTube.h> #include <gui/BufferQueue.h> #include <gui/GuiConfig.h> #include <gui/IDisplayEventConnection.h> #include <gui/Surface.h> #include <gui/GraphicBufferAlloc.h> #include <ui/GraphicBufferAllocator.h> #include <ui/PixelFormat.h> #include <ui/UiConfig.h> #include <utils/misc.h> #include <utils/String8.h> #include <utils/String16.h> #include <utils/StopWatch.h> #include <utils/Trace.h> #include <private/android_filesystem_config.h> #include <private/gui/SyncFeatures.h> #include "Client.h" #include "clz.h" #include "Colorizer.h" #include "DdmConnection.h" #include "DisplayDevice.h" #include "DispSync.h" #include "EventControlThread.h" #include "EventThread.h" #include "Layer.h" #include "LayerDim.h" #include "SurfaceFlinger.h" #include "DisplayHardware/FramebufferSurface.h" #include "DisplayHardware/HWComposer.h" #include "DisplayHardware/VirtualDisplaySurface.h" #include "Effects/Daltonizer.h" #include "RenderEngine/RenderEngine.h" #include <cutils/compiler.h> #include "DisplayUtils.h" #define DISPLAY_COUNT 1 /* * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all * black pixels. */ #define DEBUG_SCREENSHOTS false EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name); namespace android { // This is the phase offset in nanoseconds of the software vsync event // relative to the vsync event reported by HWComposer. The software vsync // event is when SurfaceFlinger and Choreographer-based applications run each // frame. // // This phase offset allows adjustment of the minimum latency from application // wake-up (by Choregographer) time to the time at which the resulting window // image is displayed. This value may be either positive (after the HW vsync) // or negative (before the HW vsync). Setting it to 0 will result in a // minimum latency of two vsync periods because the app and SurfaceFlinger // will run just after the HW vsync. Setting it to a positive number will // result in the minimum latency being: // // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD)) // // Note that reducing this latency makes it more likely for the applications // to not have their window content image ready in time. When this happens // the latency will end up being an additional vsync period, and animations // will hiccup. Therefore, this latency should be tuned somewhat // conservatively (or at least with awareness of the trade-off being made). static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS; // This is the phase offset at which SurfaceFlinger's composition runs. static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS; // --------------------------------------------------------------------------- const String16 sHardwareTest("android.permission.HARDWARE_TEST"); const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER"); const String16 sDump("android.permission.DUMP"); // --------------------------------------------------------------------------- SurfaceFlinger::SurfaceFlinger() : BnSurfaceComposer(), mTransactionFlags(0), mTransactionPending(false), mAnimTransactionPending(false), mLayersRemoved(false), mRepaintEverything(0), mRenderEngine(NULL), mBootTime(systemTime()), mVisibleRegionsDirty(false), mHwWorkListDirty(false), mAnimCompositionPending(false), mDebugRegion(0), mDebugDDMS(0), mDebugDisableHWC(0), mDebugDisableTransformHint(0), mDebugInSwapBuffers(0), mLastSwapBufferTime(0), mDebugInTransaction(0), mLastTransactionTime(0), mBootFinished(false), mForceFullDamage(false), mPrimaryHWVsyncEnabled(false), mHWVsyncAvailable(false), mDaltonize(false), mHasColorMatrix(false), mHasPoweredOff(false), mFrameBuckets(), mTotalTime(0), mLastSwapTime(0) { ALOGI("SurfaceFlinger is starting"); // debugging stuff... char value[PROPERTY_VALUE_MAX]; property_get("ro.bq.gpu_to_cpu_unsupported", value, "0"); mGpuToCpuSupported = !atoi(value); property_get("debug.sf.drop_missed_frames", value, "0"); mDropMissedFrames = atoi(value); property_get("debug.sf.showupdates", value, "0"); mDebugRegion = atoi(value); property_get("debug.sf.ddms", value, "0"); mDebugDDMS = atoi(value); if (mDebugDDMS) { if (!startDdmConnection()) { // start failed, and DDMS debugging not enabled mDebugDDMS = 0; } } ALOGI_IF(mDebugRegion, "showupdates enabled"); ALOGI_IF(mDebugDDMS, "DDMS debugging enabled"); } void SurfaceFlinger::onFirstRef() { mEventQueue.init(this); } SurfaceFlinger::~SurfaceFlinger() { EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglTerminate(display); } void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */) { // the window manager died on us. prepare its eulogy. // restore initial conditions (default device unblank, etc) initializeDisplays(); // restart the boot-animation startBootAnim(); } sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() { sp<ISurfaceComposerClient> bclient; sp<Client> client(new Client(this)); status_t err = client->initCheck(); if (err == NO_ERROR) { bclient = client; } return bclient; } sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) { class DisplayToken : public BBinder { sp<SurfaceFlinger> flinger; virtual ~DisplayToken() { // no more references, this display must be terminated Mutex::Autolock _l(flinger->mStateLock); flinger->mCurrentState.displays.removeItem(this); flinger->setTransactionFlags(eDisplayTransactionNeeded); } public: DisplayToken(const sp<SurfaceFlinger>& flinger) : flinger(flinger) { } }; sp<BBinder> token = new DisplayToken(this); Mutex::Autolock _l(mStateLock); DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL); info.displayName = displayName; info.isSecure = secure; mCurrentState.displays.add(token, info); return token; } void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) { Mutex::Autolock _l(mStateLock); ssize_t idx = mCurrentState.displays.indexOfKey(display); if (idx < 0) { ALOGW("destroyDisplay: invalid display token"); return; } const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx)); if (!info.isVirtualDisplay()) { ALOGE("destroyDisplay called for non-virtual display"); return; } mCurrentState.displays.removeItemsAt(idx); setTransactionFlags(eDisplayTransactionNeeded); } void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) { ALOGW_IF(mBuiltinDisplays[type], "Overwriting display token for display type %d", type); mBuiltinDisplays[type] = new BBinder(); DisplayDeviceState info(type); // All non-virtual displays are currently considered secure. info.isSecure = true; mCurrentState.displays.add(mBuiltinDisplays[type], info); } sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) { if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id); return NULL; } return mBuiltinDisplays[id]; } sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() { sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); return gba; } void SurfaceFlinger::bootFinished() { const nsecs_t now = systemTime(); const nsecs_t duration = now - mBootTime; ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); mBootFinished = true; // wait patiently for the window manager death const String16 name("window"); sp<IBinder> window(defaultServiceManager()->getService(name)); if (window != 0) { window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this)); } // stop boot animation // formerly we would just kill the process, but we now ask it to exit so it // can choose where to stop the animation. property_set("service.bootanim.exit", "1"); } void SurfaceFlinger::deleteTextureAsync(uint32_t texture) { class MessageDestroyGLTexture : public MessageBase { RenderEngine& engine; uint32_t texture; public: MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture) : engine(engine), texture(texture) { } virtual bool handler() { engine.deleteTextures(1, &texture); return true; } }; postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture)); } class DispSyncSource : public VSyncSource, private DispSync::Callback { public: DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync, const char* label) : mValue(0), mTraceVsync(traceVsync), mVsyncOnLabel(String8::format("VsyncOn-%s", label)), mVsyncEventLabel(String8::format("VSYNC-%s", label)), mDispSync(dispSync), mCallbackMutex(), mCallback(), mVsyncMutex(), mPhaseOffset(phaseOffset), mEnabled(false) {} virtual ~DispSyncSource() {} virtual void setVSyncEnabled(bool enable) { Mutex::Autolock lock(mVsyncMutex); if (enable) { status_t err = mDispSync->addEventListener(mPhaseOffset, static_cast<DispSync::Callback*>(this)); if (err != NO_ERROR) { ALOGE("error registering vsync callback: %s (%d)", strerror(-err), err); } //ATRACE_INT(mVsyncOnLabel.string(), 1); } else { status_t err = mDispSync->removeEventListener( static_cast<DispSync::Callback*>(this)); if (err != NO_ERROR) { ALOGE("error unregistering vsync callback: %s (%d)", strerror(-err), err); } //ATRACE_INT(mVsyncOnLabel.string(), 0); } mEnabled = enable; } virtual void setCallback(const sp<VSyncSource::Callback>& callback) { Mutex::Autolock lock(mCallbackMutex); mCallback = callback; } virtual void setPhaseOffset(nsecs_t phaseOffset) { Mutex::Autolock lock(mVsyncMutex); // Normalize phaseOffset to [0, period) auto period = mDispSync->getPeriod(); phaseOffset %= period; if (phaseOffset < 0) { // If we're here, then phaseOffset is in (-period, 0). After this // operation, it will be in (0, period) phaseOffset += period; } mPhaseOffset = phaseOffset; // If we're not enabled, we don't need to mess with the listeners if (!mEnabled) { return; } // Remove the listener with the old offset status_t err = mDispSync->removeEventListener( static_cast<DispSync::Callback*>(this)); if (err != NO_ERROR) { ALOGE("error unregistering vsync callback: %s (%d)", strerror(-err), err); } // Add a listener with the new offset err = mDispSync->addEventListener(mPhaseOffset, static_cast<DispSync::Callback*>(this)); if (err != NO_ERROR) { ALOGE("error registering vsync callback: %s (%d)", strerror(-err), err); } } private: virtual void onDispSyncEvent(nsecs_t when) { sp<VSyncSource::Callback> callback; { Mutex::Autolock lock(mCallbackMutex); callback = mCallback; if (mTraceVsync) { mValue = (mValue + 1) % 2; ATRACE_INT(mVsyncEventLabel.string(), mValue); } } if (callback != NULL) { callback->onVSyncEvent(when); } } int mValue; const bool mTraceVsync; const String8 mVsyncOnLabel; const String8 mVsyncEventLabel; DispSync* mDispSync; Mutex mCallbackMutex; // Protects the following sp<VSyncSource::Callback> mCallback; Mutex mVsyncMutex; // Protects the following nsecs_t mPhaseOffset; bool mEnabled; }; void SurfaceFlinger::init() { ALOGI( "SurfaceFlinger's main thread ready to run. " "Initializing graphics H/W..."); Mutex::Autolock _l(mStateLock); // initialize EGL for the default display mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(mEGLDisplay, NULL, NULL); // start the EventThread sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync, vsyncPhaseOffsetNs, true, "app"); mEventThread = new EventThread(vsyncSrc); sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync, sfVsyncPhaseOffsetNs, true, "sf"); mSFEventThread = new EventThread(sfVsyncSrc); mEventQueue.setEventThread(mSFEventThread); // Initialize the H/W composer object. There may or may not be an // actual hardware composer underneath. mHwc = DisplayUtils::getInstance()->getHWCInstance(this, *static_cast<HWComposer::EventHandler *>(this)); // get a RenderEngine for the given display / config (can't fail) mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID()); // retrieve the EGL context that was selected/created mEGLContext = mRenderEngine->getEGLContext(); LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT, "couldn't create EGLContext"); // initialize our non-virtual displays for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) { DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i); // set-up the displays that are already connected if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) { // All non-virtual displays are currently considered secure. bool isSecure = true; createBuiltinDisplayLocked(type); wp<IBinder> token = mBuiltinDisplays[i]; sp<IGraphicBufferProducer> producer; sp<IGraphicBufferConsumer> consumer; BufferQueue::createBufferQueue(&producer, &consumer, new GraphicBufferAlloc()); sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i, consumer); int32_t hwcId = allocateHwcDisplayId(type); sp<DisplayDevice> hw = new DisplayDevice(this, type, hwcId, mHwc->getFormat(hwcId), isSecure, token, fbs, producer, mRenderEngine->getEGLConfig()); if (i > DisplayDevice::DISPLAY_PRIMARY) { // FIXME: currently we don't get blank/unblank requests // for displays other than the main display, so we always // assume a connected display is unblanked. ALOGD("marking display %zu as acquired/unblanked", i); hw->setPowerMode(HWC_POWER_MODE_NORMAL); } // When a non-virtual display device is added at boot time, // update the active config by querying HWC otherwise the // default config (config 0) will be used. int activeConfig = mHwc->getActiveConfig(hwcId); if (activeConfig >= 0) { hw->setActiveConfig(activeConfig); } mDisplays.add(token, hw); } } // make the GLContext current so that we can create textures when creating Layers // (which may happens before we render something) getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); mEventControlThread = new EventControlThread(this); mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY); // set a fake vsync period if there is no HWComposer if (mHwc->initCheck() != NO_ERROR) { mPrimaryDispSync.setPeriod(16666667); } // initialize our drawing state mDrawingState = mCurrentState; // set initial conditions (e.g. unblank default device) initializeDisplays(); // start boot animation startBootAnim(); } int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) { return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ? type : mHwc->allocateDisplayId(); } void SurfaceFlinger::startBootAnim() { // start boot animation property_set("service.bootanim.exit", "0"); property_set("ctl.start", "bootanim"); } size_t SurfaceFlinger::getMaxTextureSize() const { return mRenderEngine->getMaxTextureSize(); } size_t SurfaceFlinger::getMaxViewportDims() const { return mRenderEngine->getMaxViewportDims(); } // ---------------------------------------------------------------------------- bool SurfaceFlinger::authenticateSurfaceTexture( const sp<IGraphicBufferProducer>& bufferProducer) const { Mutex::Autolock _l(mStateLock); sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer)); return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0; } status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display, Vector<DisplayInfo>* configs) { if ((configs == NULL) || (display.get() == NULL)) { return BAD_VALUE; } if (!display.get()) return NAME_NOT_FOUND; int32_t type = NAME_NOT_FOUND; for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) { if (display == mBuiltinDisplays[i]) { type = i; break; } } if (type < 0) { return type; } // TODO: Not sure if display density should handled by SF any longer class Density { static int getDensityFromProperty(char const* propName) { char property[PROPERTY_VALUE_MAX]; int density = 0; if (property_get(propName, property, NULL) > 0) { density = atoi(property); } return density; } public: static int getEmuDensity() { return getDensityFromProperty("qemu.sf.lcd_density"); } static int getBuildDensity() { return getDensityFromProperty("ro.sf.lcd_density"); } }; configs->clear(); const Vector<HWComposer::DisplayConfig>& hwConfigs = getHwComposer().getConfigs(type); for (size_t c = 0; c < hwConfigs.size(); ++c) { const HWComposer::DisplayConfig& hwConfig = hwConfigs[c]; DisplayInfo info = DisplayInfo(); float xdpi = hwConfig.xdpi; float ydpi = hwConfig.ydpi; if (type == DisplayDevice::DISPLAY_PRIMARY) { // The density of the device is provided by a build property float density = Density::getBuildDensity() / 160.0f; if (density == 0) { // the build doesn't provide a density -- this is wrong! // use xdpi instead ALOGE("ro.sf.lcd_density must be defined as a build property"); density = xdpi / 160.0f; } if (Density::getEmuDensity()) { // if "qemu.sf.lcd_density" is specified, it overrides everything xdpi = ydpi = density = Density::getEmuDensity(); density /= 160.0f; } info.density = density; // TODO: this needs to go away (currently needed only by webkit) sp<const DisplayDevice> hw(getDefaultDisplayDevice()); info.orientation = hw->getOrientation(); } else { // TODO: where should this value come from? static const int TV_DENSITY = 213; info.density = TV_DENSITY / 160.0f; info.orientation = 0; } info.w = hwConfig.width; info.h = hwConfig.height; info.xdpi = xdpi; info.ydpi = ydpi; info.fps = float(1e9 / hwConfig.refresh); info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS; info.colorTransform = hwConfig.colorTransform; // This is how far in advance a buffer must be queued for // presentation at a given time. If you want a buffer to appear // on the screen at time N, you must submit the buffer before // (N - presentationDeadline). // // Normally it's one full refresh period (to give SF a chance to // latch the buffer), but this can be reduced by configuring a // DispSync offset. Any additional delays introduced by the hardware // composer or panel must be accounted for here. // // We add an additional 1ms to allow for processing time and // differences between the ideal and actual refresh rate. info.presentationDeadline = hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000; // All non-virtual displays are currently considered secure. info.secure = true; configs->push_back(info); } return NO_ERROR; } status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */, DisplayStatInfo* stats) { if (stats == NULL) { return BAD_VALUE; } // FIXME for now we always return stats for the primary display memset(stats, 0, sizeof(*stats)); stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0); stats->vsyncPeriod = mPrimaryDispSync.getPeriod(); return NO_ERROR; } int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) { sp<DisplayDevice> device(getDisplayDevice(display)); if (device != NULL) { return device->getActiveConfig(); } return BAD_VALUE; } void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) { ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(), this); int32_t type = hw->getDisplayType(); int currentMode = hw->getActiveConfig(); if (mode == currentMode) { ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode); return; } if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { ALOGW("Trying to set config for virtual display"); return; } status_t status = getHwComposer().setActiveConfig(type, mode); if (status == NO_ERROR) { hw->setActiveConfig(mode); } } status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) { class MessageSetActiveConfig: public MessageBase { SurfaceFlinger& mFlinger; sp<IBinder> mDisplay; int mMode; public: MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp, int mode) : mFlinger(flinger), mDisplay(disp) { mMode = mode; } virtual bool handler() { Vector<DisplayInfo> configs; mFlinger.getDisplayConfigs(mDisplay, &configs); if (mMode < 0 || mMode >= static_cast<int>(configs.size())) { ALOGE("Attempt to set active config = %d for display with %zu configs", mMode, configs.size()); } sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); if (hw == NULL) { ALOGE("Attempt to set active config = %d for null display %p", mMode, mDisplay.get()); } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { ALOGW("Attempt to set active config = %d for virtual display", mMode); } else { mFlinger.setActiveConfigInternal(hw, mMode); } return true; } }; sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode); postMessageSync(msg); return NO_ERROR; } status_t SurfaceFlinger::clearAnimationFrameStats() { Mutex::Autolock _l(mStateLock); mAnimFrameTracker.clearStats(); return NO_ERROR; } status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const { Mutex::Autolock _l(mStateLock); mAnimFrameTracker.getStats(outStats); return NO_ERROR; } // ---------------------------------------------------------------------------- sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() { return mEventThread->createEventConnection(); } // ---------------------------------------------------------------------------- void SurfaceFlinger::waitForEvent() { mEventQueue.waitMessage(); } void SurfaceFlinger::signalTransaction() { mEventQueue.invalidate(); } void SurfaceFlinger::signalLayerUpdate() { mEventQueue.invalidate(); } void SurfaceFlinger::signalRefresh() { mEventQueue.refresh(); } status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime, uint32_t /* flags */) { return mEventQueue.postMessage(msg, reltime); } status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime, uint32_t /* flags */) { status_t res = mEventQueue.postMessage(msg, reltime); if (res == NO_ERROR) { msg->wait(); } return res; } void SurfaceFlinger::run() { do { waitForEvent(); } while (true); } void SurfaceFlinger::enableHardwareVsync() { Mutex::Autolock _l(mHWVsyncLock); if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) { mPrimaryDispSync.beginResync(); //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true); mEventControlThread->setVsyncEnabled(true); mPrimaryHWVsyncEnabled = true; } } void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) { Mutex::Autolock _l(mHWVsyncLock); if (makeAvailable) { mHWVsyncAvailable = true; } else if (!mHWVsyncAvailable) { ALOGE("resyncToHardwareVsync called when HW vsync unavailable"); return; } const nsecs_t period = getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); mPrimaryDispSync.reset(); mPrimaryDispSync.setPeriod(period); if (!mPrimaryHWVsyncEnabled) { mPrimaryDispSync.beginResync(); //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true); mEventControlThread->setVsyncEnabled(true); mPrimaryHWVsyncEnabled = true; } } void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) { Mutex::Autolock _l(mHWVsyncLock); if (mPrimaryHWVsyncEnabled) { //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false); mEventControlThread->setVsyncEnabled(false); mPrimaryDispSync.endResync(); mPrimaryHWVsyncEnabled = false; } if (makeUnavailable) { mHWVsyncAvailable = false; } } void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) { bool needsHwVsync = false; { // Scope for the lock Mutex::Autolock _l(mHWVsyncLock); if (type == 0 && mPrimaryHWVsyncEnabled) { needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp); } } if (needsHwVsync) { enableHardwareVsync(); } else { disableHardwareVsync(false); } } void SurfaceFlinger::onHotplugReceived(int type, bool connected) { if (mEventThread == NULL) { // This is a temporary workaround for b/7145521. A non-null pointer // does not mean EventThread has finished initializing, so this // is not a correct fix. ALOGW("WARNING: EventThread not started, ignoring hotplug"); return; } if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { Mutex::Autolock _l(mStateLock); if (connected) { createBuiltinDisplayLocked((DisplayDevice::DisplayType)type); } else { mCurrentState.displays.removeItem(mBuiltinDisplays[type]); mBuiltinDisplays[type].clear(); updateVisibleRegionsDirty(); } setTransactionFlags(eDisplayTransactionNeeded); // Defer EventThread notification until SF has updated mDisplays. } } void SurfaceFlinger::eventControl(int disp, int event, int enabled) { ATRACE_CALL(); getHwComposer().eventControl(disp, event, enabled); } void SurfaceFlinger::onMessageReceived(int32_t what) { ATRACE_CALL(); switch (what) { case MessageQueue::TRANSACTION: { handleMessageTransaction(); break; } case MessageQueue::INVALIDATE: { bool refreshNeeded = handleMessageTransaction(); refreshNeeded |= handleMessageInvalidate(); refreshNeeded |= mRepaintEverything; if (refreshNeeded) { // Signal a refresh if a transaction modified the window state, // a new buffer was latched, or if HWC has requested a full // repaint signalRefresh(); } break; } case MessageQueue::REFRESH: { handleMessageRefresh(); break; } } } bool SurfaceFlinger::handleMessageTransaction() { uint32_t transactionFlags = peekTransactionFlags(eTransactionMask); if (transactionFlags) { handleTransaction(transactionFlags); return true; } return false; } bool SurfaceFlinger::handleMessageInvalidate() { ATRACE_CALL(); return handlePageFlip(); } void SurfaceFlinger::handleMessageRefresh() { ATRACE_CALL(); static nsecs_t previousExpectedPresent = 0; nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0); static bool previousFrameMissed = false; bool frameMissed = (expectedPresent == previousExpectedPresent); if (frameMissed != previousFrameMissed) { ATRACE_INT("FrameMissed", static_cast<int>(frameMissed)); } previousFrameMissed = frameMissed; if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) { // Latch buffers, but don't send anything to HWC, then signal another // wakeup for the next vsync preComposition(); repaintEverything(); } else { preComposition(); rebuildLayerStacks(); setUpHWComposer(); doDebugFlashRegions(); doComposition(); postComposition(); } previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0); } void SurfaceFlinger::doDebugFlashRegions() { // is debugging enabled if (CC_LIKELY(!mDebugRegion)) return; const bool repaintEverything = mRepaintEverything; for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { const sp<DisplayDevice>& hw(mDisplays[dpy]); if (hw->isDisplayOn()) { // transform the dirty region into this screen's coordinate space const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); if (!dirtyRegion.isEmpty()) { // redraw the whole screen doComposeSurfaces(hw, Region(hw->bounds())); // and draw the dirty region const int32_t height = hw->getHeight(); RenderEngine& engine(getRenderEngine()); engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1); hw->compositionComplete(); hw->swapBuffers(getHwComposer()); } } } postFramebuffer(); if (mDebugRegion > 1) { usleep(mDebugRegion * 1000); } HWComposer& hwc(getHwComposer()); if (hwc.initCheck() == NO_ERROR) { status_t err = hwc.prepare(); ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); } } void SurfaceFlinger::preComposition() { bool needExtraInvalidate = false; const LayerVector& layers(mDrawingState.layersSortedByZ); const size_t count = layers.size(); for (size_t i=0 ; i<count ; i++) { if (layers[i]->onPreComposition()) { needExtraInvalidate = true; } } if (needExtraInvalidate) { signalLayerUpdate(); } } void SurfaceFlinger::postComposition() { const LayerVector& layers(mDrawingState.layersSortedByZ); const size_t count = layers.size(); for (size_t i=0 ; i<count ; i++) { layers[i]->onPostComposition(); } const HWComposer& hwc = getHwComposer(); sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); if (presentFence->isValid()) { if (mPrimaryDispSync.addPresentFence(presentFence)) { enableHardwareVsync(); } else { disableHardwareVsync(false); } } const sp<const DisplayDevice> hw(getDefaultDisplayDevice()); if (kIgnorePresentFences) { if (hw->isDisplayOn()) { enableHardwareVsync(); } } if (mAnimCompositionPending) { mAnimCompositionPending = false; if (presentFence->isValid()) { mAnimFrameTracker.setActualPresentFence(presentFence); } else { // The HWC doesn't support present fences, so use the refresh // timestamp instead. nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); mAnimFrameTracker.setActualPresentTime(presentTime); } mAnimFrameTracker.advanceFrame(); } if (hw->getPowerMode() == HWC_POWER_MODE_OFF) { return; } nsecs_t currentTime = systemTime(); if (mHasPoweredOff) { mHasPoweredOff = false; } else { nsecs_t period = mPrimaryDispSync.getPeriod(); nsecs_t elapsedTime = currentTime - mLastSwapTime; size_t numPeriods = static_cast<size_t>(elapsedTime / period); if (numPeriods < NUM_BUCKETS - 1) { mFrameBuckets[numPeriods] += elapsedTime; } else { mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime; } mTotalTime += elapsedTime; } mLastSwapTime = currentTime; } void SurfaceFlinger::rebuildLayerStacks() { updateExtendedMode(); // rebuild the visible layer list per screen if (CC_UNLIKELY(mVisibleRegionsDirty)) { ATRACE_CALL(); mVisibleRegionsDirty = false; invalidateHwcGeometry(); const LayerVector& layers(mDrawingState.layersSortedByZ); for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { Region opaqueRegion; Region dirtyRegion; Vector< sp<Layer> > layersSortedByZ; const sp<DisplayDevice>& hw(mDisplays[dpy]); const Transform& tr(hw->getTransform()); const Rect bounds(hw->getBounds()); if (hw->isDisplayOn()) { computeVisibleRegions(hw->getHwcDisplayId(), layers, hw->getLayerStack(), dirtyRegion, opaqueRegion); const size_t count = layers.size(); for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(layers[i]); { Region drawRegion(tr.transform( layer->visibleNonTransparentRegion)); drawRegion.andSelf(bounds); if (!drawRegion.isEmpty()) { layersSortedByZ.add(layer); } } } } hw->setVisibleLayersSortedByZ(layersSortedByZ); hw->undefinedRegion.set(bounds); hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion)); hw->dirtyRegion.orSelf(dirtyRegion); } } } void SurfaceFlinger::setUpHWComposer() { for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty(); bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0; bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers; // If nothing has changed (!dirty), don't recompose. // If something changed, but we don't currently have any visible layers, // and didn't when we last did a composition, then skip it this time. // The second rule does two things: // - When all layers are removed from a display, we'll emit one black // frame, then nothing more until we get new layers. // - When a display is created with a private layer stack, we won't // emit any black frames until a layer is added to the layer stack. bool mustRecompose = dirty && !(empty && wasEmpty); ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL, "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy, mustRecompose ? "doing" : "skipping", dirty ? "+" : "-", empty ? "+" : "-", wasEmpty ? "+" : "-"); mDisplays[dpy]->beginFrame(mustRecompose); if (mustRecompose) { mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty; } } HWComposer& hwc(getHwComposer()); if (hwc.initCheck() == NO_ERROR) { // build the h/w work list if (CC_UNLIKELY(mHwWorkListDirty)) { mHwWorkListDirty = false; for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { sp<const DisplayDevice> hw(mDisplays[dpy]); const int32_t id = hw->getHwcDisplayId(); if (id >= 0) { const Vector< sp<Layer> >& currentLayers( hw->getVisibleLayersSortedByZ()); const size_t count = currentLayers.size(); if (hwc.createWorkList(id, count) == NO_ERROR) { HWComposer::LayerListIterator cur = hwc.begin(id); const HWComposer::LayerListIterator end = hwc.end(id); for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { const sp<Layer>& layer(currentLayers[i]); layer->setGeometry(hw, *cur); if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) { cur->setSkip(true); } } } } } } // set the per-frame data for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { sp<const DisplayDevice> hw(mDisplays[dpy]); const int32_t id = hw->getHwcDisplayId(); if (id >= 0) { bool freezeSurfacePresent = false; isfreezeSurfacePresent(freezeSurfacePresent, hw, id); const Vector< sp<Layer> >& currentLayers( hw->getVisibleLayersSortedByZ()); const size_t count = currentLayers.size(); HWComposer::LayerListIterator cur = hwc.begin(id); const HWComposer::LayerListIterator end = hwc.end(id); for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { /* * update the per-frame h/w composer data for each layer * and build the transparent region of the FB */ const sp<Layer>& layer(currentLayers[i]); layer->setPerFrameData(hw, *cur); setOrientationEventControl(freezeSurfacePresent,id); } } } // If possible, attempt to use the cursor overlay on each display. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { sp<const DisplayDevice> hw(mDisplays[dpy]); const int32_t id = hw->getHwcDisplayId(); if (id >= 0) { const Vector< sp<Layer> >& currentLayers( hw->getVisibleLayersSortedByZ()); const size_t count = currentLayers.size(); HWComposer::LayerListIterator cur = hwc.begin(id); const HWComposer::LayerListIterator end = hwc.end(id); for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { const sp<Layer>& layer(currentLayers[i]); if (layer->isPotentialCursor()) { cur->setIsCursorLayerHint(); break; } } } } status_t err = hwc.prepare(); ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { sp<const DisplayDevice> hw(mDisplays[dpy]); hw->prepareFrame(hwc); } } } void SurfaceFlinger::doComposition() { ATRACE_CALL(); const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { const sp<DisplayDevice>& hw(mDisplays[dpy]); if (hw->isDisplayOn()) { // transform the dirty region into this screen's coordinate space const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); // repaint the framebuffer (if needed) doDisplayComposition(hw, dirtyRegion); hw->dirtyRegion.clear(); hw->flip(hw->swapRegion); hw->swapRegion.clear(); } // inform the h/w that we're done compositing hw->compositionComplete(); } postFramebuffer(); } void SurfaceFlinger::postFramebuffer() { ATRACE_CALL(); const nsecs_t now = systemTime(); mDebugInSwapBuffers = now; HWComposer& hwc(getHwComposer()); if (hwc.initCheck() == NO_ERROR) { if (!hwc.supportsFramebufferTarget()) { // EGL spec says: // "surface must be bound to the calling thread's current context, // for the current rendering API." getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); } hwc.commit(); } // make the default display current because the VirtualDisplayDevice code cannot // deal with dequeueBuffer() being called outside of the composition loop; however // the code below can call glFlush() which is allowed (and does in some case) call // dequeueBuffer(). getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { sp<const DisplayDevice> hw(mDisplays[dpy]); const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ()); hw->onSwapBuffersCompleted(hwc); const size_t count = currentLayers.size(); int32_t id = hw->getHwcDisplayId(); if (id >=0 && hwc.initCheck() == NO_ERROR) { HWComposer::LayerListIterator cur = hwc.begin(id); const HWComposer::LayerListIterator end = hwc.end(id); for (size_t i = 0; cur != end && i < count; ++i, ++cur) { currentLayers[i]->onLayerDisplayed(hw, &*cur); } } else { for (size_t i = 0; i < count; i++) { currentLayers[i]->onLayerDisplayed(hw, NULL); } } } mLastSwapBufferTime = systemTime() - now; mDebugInSwapBuffers = 0; uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount(); if (flipCount % LOG_FRAME_STATS_PERIOD == 0) { logFrameStats(); } } void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) { ATRACE_CALL(); // here we keep a copy of the drawing state (that is the state that's // going to be overwritten by handleTransactionLocked()) outside of // mStateLock so that the side-effects of the State assignment // don't happen with mStateLock held (which can cause deadlocks). State drawingState(mDrawingState); Mutex::Autolock _l(mStateLock); const nsecs_t now = systemTime(); mDebugInTransaction = now; // Here we're guaranteed that some transaction flags are set // so we can call handleTransactionLocked() unconditionally. // We call getTransactionFlags(), which will also clear the flags, // with mStateLock held to guarantee that mCurrentState won't change // until the transaction is committed. transactionFlags = getTransactionFlags(eTransactionMask); handleTransactionLocked(transactionFlags); mLastTransactionTime = systemTime() - now; mDebugInTransaction = 0; invalidateHwcGeometry(); // here the transaction has been committed } void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) { const LayerVector& currentLayers(mCurrentState.layersSortedByZ); const size_t count = currentLayers.size(); /* * Traversal of the children * (perform the transaction for each of them if needed) */ if (transactionFlags & eTraversalNeeded) { for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(currentLayers[i]); uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); if (!trFlags) continue; const uint32_t flags = layer->doTransaction(0); if (flags & Layer::eVisibleRegion) mVisibleRegionsDirty = true; } } /* * Perform display own transactions if needed */ if (transactionFlags & eDisplayTransactionNeeded) { // here we take advantage of Vector's copy-on-write semantics to // improve performance by skipping the transaction entirely when // know that the lists are identical const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); if (!curr.isIdenticalTo(draw)) { mVisibleRegionsDirty = true; const size_t cc = curr.size(); size_t dc = draw.size(); // find the displays that were removed // (ie: in drawing state but not in current state) // also handle displays that changed // (ie: displays that are in both lists) for (size_t i=0 ; i<dc ; i++) { const ssize_t j = curr.indexOfKey(draw.keyAt(i)); if (j < 0) { // in drawing state but not in current state if (!draw[i].isMainDisplay()) { // Call makeCurrent() on the primary display so we can // be sure that nothing associated with this display // is current. const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice()); defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext); sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i))); if (hw != NULL) hw->disconnect(getHwComposer()); if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) mEventThread->onHotplugReceived(draw[i].type, false); mDisplays.removeItem(draw.keyAt(i)); } else { ALOGW("trying to remove the main display"); } } else { // this display is in both lists. see if something changed. const DisplayDeviceState& state(curr[j]); const wp<IBinder>& display(curr.keyAt(j)); const sp<IBinder> state_binder = IInterface::asBinder(state.surface); const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface); if (state_binder != draw_binder) { // changing the surface is like destroying and // recreating the DisplayDevice, so we just remove it // from the drawing state, so that it get re-added // below. sp<DisplayDevice> hw(getDisplayDevice(display)); if (hw != NULL) hw->disconnect(getHwComposer()); mDisplays.removeItem(display); mDrawingState.displays.removeItemsAt(i); dc--; i--; // at this point we must loop to the next item continue; } const sp<DisplayDevice> disp(getDisplayDevice(display)); if (disp != NULL) { if (state.layerStack != draw[i].layerStack) { disp->setLayerStack(state.layerStack); } if ((state.orientation != draw[i].orientation) || (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) { disp->setProjection(state.orientation, state.viewport, state.frame); } if (state.width != draw[i].width || state.height != draw[i].height) { disp->setDisplaySize(state.width, state.height); } } } } // find displays that were added // (ie: in current state but not in drawing state) for (size_t i=0 ; i<cc ; i++) { if (draw.indexOfKey(curr.keyAt(i)) < 0) { const DisplayDeviceState& state(curr[i]); sp<DisplaySurface> dispSurface; sp<IGraphicBufferProducer> producer; sp<IGraphicBufferProducer> bqProducer; sp<IGraphicBufferConsumer> bqConsumer; BufferQueue::createBufferQueue(&bqProducer, &bqConsumer, new GraphicBufferAlloc()); int32_t hwcDisplayId = -1; if (state.isVirtualDisplay()) { // Virtual displays without a surface are dormant: // they have external state (layer stack, projection, // etc.) but no internal state (i.e. a DisplayDevice). if (state.surface != NULL) { int width = 0; DisplayUtils* displayUtils = DisplayUtils::getInstance(); int status = state.surface->query( NATIVE_WINDOW_WIDTH, &width); ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status); int height = 0; status = state.surface->query( NATIVE_WINDOW_HEIGHT, &height); ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status); if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 || (width <= MAX_VIRTUAL_DISPLAY_DIMENSION && height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) { int usage = 0; status = state.surface->query( NATIVE_WINDOW_CONSUMER_USAGE_BITS, &usage); ALOGW_IF(status != NO_ERROR, "Unable to query usage (%d)", status); if ( (status == NO_ERROR) && displayUtils->canAllocateHwcDisplayIdForVDS(usage)) { hwcDisplayId = allocateHwcDisplayId(state.type); } } displayUtils->initVDSInstance(mHwc, hwcDisplayId, state.surface, dispSurface, producer, bqProducer, bqConsumer, state.displayName, state.isSecure, state.type); } } else { ALOGE_IF(state.surface!=NULL, "adding a supported display, but rendering " "surface is provided (%p), ignoring it", state.surface.get()); hwcDisplayId = allocateHwcDisplayId(state.type); // for supported (by hwc) displays we provide our // own rendering surface dispSurface = new FramebufferSurface(*mHwc, state.type, bqConsumer); producer = bqProducer; } const wp<IBinder>& display(curr.keyAt(i)); if (dispSurface != NULL && producer != NULL) { sp<DisplayDevice> hw = new DisplayDevice(this, state.type, hwcDisplayId, mHwc->getFormat(hwcDisplayId), state.isSecure, display, dispSurface, producer, mRenderEngine->getEGLConfig()); hw->setLayerStack(state.layerStack); hw->setProjection(state.orientation, state.viewport, state.frame); hw->setDisplayName(state.displayName); // When a new display device is added update the active // config by querying HWC otherwise the default config // (config 0) will be used. if (hwcDisplayId >= DisplayDevice::DISPLAY_PRIMARY && hwcDisplayId < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { int activeConfig = mHwc->getActiveConfig(hwcDisplayId); if (activeConfig >= 0) { hw->setActiveConfig(activeConfig); } } mDisplays.add(display, hw); if (state.isVirtualDisplay()) { if (hwcDisplayId >= 0) { mHwc->setVirtualDisplayProperties(hwcDisplayId, hw->getWidth(), hw->getHeight(), hw->getFormat()); } } else { mEventThread->onHotplugReceived(state.type, true); } } } } } } if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) { // The transform hint might have changed for some layers // (either because a display has changed, or because a layer // as changed). // // Walk through all the layers in currentLayers, // and update their transform hint. // // If a layer is visible only on a single display, then that // display is used to calculate the hint, otherwise we use the // default display. // // NOTE: we do this here, rather than in rebuildLayerStacks() so that // the hint is set before we acquire a buffer from the surface texture. // // NOTE: layer transactions have taken place already, so we use their // drawing state. However, SurfaceFlinger's own transaction has not // happened yet, so we must use the current state layer list // (soon to become the drawing state list). // sp<const DisplayDevice> disp; uint32_t currentlayerStack = 0; for (size_t i=0; i<count; i++) { // NOTE: we rely on the fact that layers are sorted by // layerStack first (so we don't have to traverse the list // of displays for every layer). const sp<Layer>& layer(currentLayers[i]); uint32_t layerStack = layer->getDrawingState().layerStack; if (i==0 || currentlayerStack != layerStack) { currentlayerStack = layerStack; // figure out if this layerstack is mirrored // (more than one display) if so, pick the default display, // if not, pick the only display it's on. disp.clear(); for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { sp<const DisplayDevice> hw(mDisplays[dpy]); if (hw->getLayerStack() == currentlayerStack) { if (disp == NULL) { disp = hw; } else { disp = NULL; break; } } } } if (disp == NULL) { // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to // redraw after transform hint changes. See bug 8508397. // could be null when this layer is using a layerStack // that is not visible on any display. Also can occur at // screen off/on times. disp = getDefaultDisplayDevice(); } layer->updateTransformHint(disp); } } /* * Perform our own transaction if needed */ const LayerVector& layers(mDrawingState.layersSortedByZ); if (currentLayers.size() > layers.size()) { // layers have been added mVisibleRegionsDirty = true; } // some layers might have been removed, so // we need to update the regions they're exposing. if (mLayersRemoved) { mLayersRemoved = false; mVisibleRegionsDirty = true; const size_t count = layers.size(); for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(layers[i]); if (currentLayers.indexOf(layer) < 0) { // this layer is not visible anymore // TODO: we could traverse the tree from front to back and // compute the actual visible region // TODO: we could cache the transformed region const Layer::State& s(layer->getDrawingState()); Region visibleReg = s.transform.transform( Region(Rect(s.active.w, s.active.h))); invalidateLayerStack(s.layerStack, visibleReg); } } } commitTransaction(); updateCursorAsync(); } void SurfaceFlinger::updateCursorAsync() { HWComposer& hwc(getHwComposer()); for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { sp<const DisplayDevice> hw(mDisplays[dpy]); const int32_t id = hw->getHwcDisplayId(); if (id < 0) { continue; } const Vector< sp<Layer> >& currentLayers( hw->getVisibleLayersSortedByZ()); const size_t count = currentLayers.size(); HWComposer::LayerListIterator cur = hwc.begin(id); const HWComposer::LayerListIterator end = hwc.end(id); for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) { continue; } const sp<Layer>& layer(currentLayers[i]); Rect cursorPos = layer->getPosition(hw); hwc.setCursorPositionAsync(id, cursorPos); break; } } } void SurfaceFlinger::commitTransaction() { if (!mLayersPendingRemoval.isEmpty()) { // Notify removed layers now that they can't be drawn from for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { mLayersPendingRemoval[i]->onRemoved(); } mLayersPendingRemoval.clear(); } // If this transaction is part of a window animation then the next frame // we composite should be considered an animation as well. mAnimCompositionPending = mAnimTransactionPending; mDrawingState = mCurrentState; mTransactionPending = false; mAnimTransactionPending = false; mTransactionCV.broadcast(); } void SurfaceFlinger::computeVisibleRegions(size_t dpy, const LayerVector& currentLayers, uint32_t layerStack, Region& outDirtyRegion, Region& outOpaqueRegion) { ATRACE_CALL(); Region aboveOpaqueLayers; Region aboveCoveredLayers; Region dirty; outDirtyRegion.clear(); bool bIgnoreLayers = false; int indexLOI = -1; getIndexLOI(dpy, currentLayers, bIgnoreLayers, indexLOI); size_t i = currentLayers.size(); while (i--) { const sp<Layer>& layer = currentLayers[i]; // start with the whole surface at its current location const Layer::State& s(layer->getDrawingState()); if(updateLayerVisibleNonTransparentRegion(dpy, layer, bIgnoreLayers, indexLOI, layerStack, i)) continue; /* * opaqueRegion: area of a surface that is fully opaque. */ Region opaqueRegion; /* * visibleRegion: area of a surface that is visible on screen * and not fully transparent. This is essentially the layer's * footprint minus the opaque regions above it. * Areas covered by a translucent surface are considered visible. */ Region visibleRegion; /* * coveredRegion: area of a surface that is covered by all * visible regions above it (which includes the translucent areas). */ Region coveredRegion; /* * transparentRegion: area of a surface that is hinted to be completely * transparent. This is only used to tell when the layer has no visible * non-transparent regions and can be removed from the layer list. It * does not affect the visibleRegion of this layer or any layers * beneath it. The hint may not be correct if apps don't respect the * SurfaceView restrictions (which, sadly, some don't). */ Region transparentRegion; // handle hidden surfaces by setting the visible region to empty if (CC_LIKELY(layer->isVisible())) { const bool translucent = !layer->isOpaque(s); Rect bounds(s.transform.transform(layer->computeBounds())); visibleRegion.set(bounds); if (!visibleRegion.isEmpty()) { // Remove the transparent area from the visible region if (translucent) { const Transform tr(s.transform); if (tr.transformed()) { if (tr.preserveRects()) { // transform the transparent region transparentRegion = tr.transform(s.activeTransparentRegion); } else { // transformation too complex, can't do the // transparent region optimization. transparentRegion.clear(); } } else { transparentRegion = s.activeTransparentRegion; } } // compute the opaque region const int32_t layerOrientation = s.transform.getOrientation(); if (s.alpha==255 && !translucent && ((layerOrientation & Transform::ROT_INVALID) == false)) { // the opaque region is the layer's footprint opaqueRegion = visibleRegion; } } } // Clip the covered region to the visible region coveredRegion = aboveCoveredLayers.intersect(visibleRegion); // Update aboveCoveredLayers for next (lower) layer aboveCoveredLayers.orSelf(visibleRegion); // subtract the opaque region covered by the layers above us visibleRegion.subtractSelf(aboveOpaqueLayers); // compute this layer's dirty region if (layer->contentDirty) { // we need to invalidate the whole region dirty = visibleRegion; // as well, as the old visible region dirty.orSelf(layer->visibleRegion); layer->contentDirty = false; } else { /* compute the exposed region: * the exposed region consists of two components: * 1) what's VISIBLE now and was COVERED before * 2) what's EXPOSED now less what was EXPOSED before * * note that (1) is conservative, we start with the whole * visible region but only keep what used to be covered by * something -- which mean it may have been exposed. * * (2) handles areas that were not covered by anything but got * exposed because of a resize. */ const Region newExposed = visibleRegion - coveredRegion; const Region oldVisibleRegion = layer->visibleRegion; const Region oldCoveredRegion = layer->coveredRegion; const Region oldExposed = oldVisibleRegion - oldCoveredRegion; dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); } dirty.subtractSelf(aboveOpaqueLayers); // accumulate to the screen dirty region outDirtyRegion.orSelf(dirty); // Update aboveOpaqueLayers for next (lower) layer aboveOpaqueLayers.orSelf(opaqueRegion); // Store the visible region in screen space layer->setVisibleRegion(visibleRegion); layer->setCoveredRegion(coveredRegion); layer->setVisibleNonTransparentRegion( visibleRegion.subtract(transparentRegion)); } outOpaqueRegion = aboveOpaqueLayers; } void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, const Region& dirty) { for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { const sp<DisplayDevice>& hw(mDisplays[dpy]); if (hw->getLayerStack() == layerStack) { hw->dirtyRegion.orSelf(dirty); } } } bool SurfaceFlinger::handlePageFlip() { Region dirtyRegion; bool visibleRegions = false; const LayerVector& layers(mDrawingState.layersSortedByZ); bool frameQueued = false; // Store the set of layers that need updates. This set must not change as // buffers are being latched, as this could result in a deadlock. // Example: Two producers share the same command stream and: // 1.) Layer 0 is latched // 2.) Layer 0 gets a new frame // 2.) Layer 1 gets a new frame // 3.) Layer 1 is latched. // Display is now waiting on Layer 1's frame, which is behind layer 0's // second frame. But layer 0's second frame could be waiting on display. Vector<Layer*> layersWithQueuedFrames; for (size_t i = 0, count = layers.size(); i<count ; i++) { const sp<Layer>& layer(layers[i]); if (layer->hasQueuedFrame()) { frameQueued = true; if (layer->shouldPresentNow(mPrimaryDispSync)) { layersWithQueuedFrames.push_back(layer.get()); } else { layer->useEmptyDamage(); } } else { layer->useEmptyDamage(); } } for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) { Layer* layer = layersWithQueuedFrames[i]; const Region dirty(layer->latchBuffer(visibleRegions)); layer->useSurfaceDamage(); const Layer::State& s(layer->getDrawingState()); invalidateLayerStack(s.layerStack, dirty); } mVisibleRegionsDirty |= visibleRegions; // If we will need to wake up at some time in the future to deal with a // queued frame that shouldn't be displayed during this vsync period, wake // up during the next vsync period to check again. if (frameQueued && layersWithQueuedFrames.empty()) { signalLayerUpdate(); } // Only continue with the refresh if there is actually new work to do return !layersWithQueuedFrames.empty(); } void SurfaceFlinger::invalidateHwcGeometry() { mHwWorkListDirty = true; } void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& inDirtyRegion) { // We only need to actually compose the display if: // 1) It is being handled by hardware composer, which may need this to // keep its virtual display state machine in sync, or // 2) There is work to be done (the dirty region isn't empty) bool isHwcDisplay = hw->getHwcDisplayId() >= 0; if (!isHwcDisplay && inDirtyRegion.isEmpty()) { return; } Region dirtyRegion(inDirtyRegion); // compute the invalid region hw->swapRegion.orSelf(dirtyRegion); uint32_t flags = hw->getFlags(); if (flags & DisplayDevice::SWAP_RECTANGLE) { // we can redraw only what's dirty, but since SWAP_RECTANGLE only // takes a rectangle, we must make sure to update that whole // rectangle in that case dirtyRegion.set(hw->swapRegion.bounds()); } else { if (flags & DisplayDevice::PARTIAL_UPDATES) { // We need to redraw the rectangle that will be updated // (pushed to the framebuffer). // This is needed because PARTIAL_UPDATES only takes one // rectangle instead of a region (see DisplayDevice::flip()) dirtyRegion.set(hw->swapRegion.bounds()); } else { // we need to redraw everything (the whole screen) dirtyRegion.set(hw->bounds()); hw->swapRegion = dirtyRegion; } } if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) { if (!doComposeSurfaces(hw, dirtyRegion)) return; } else { RenderEngine& engine(getRenderEngine()); mat4 colorMatrix = mColorMatrix; if (mDaltonize) { colorMatrix = colorMatrix * mDaltonizer(); } mat4 oldMatrix = engine.setupColorTransform(colorMatrix); doComposeSurfaces(hw, dirtyRegion); engine.setupColorTransform(oldMatrix); } // update the swap region and clear the dirty region hw->swapRegion.orSelf(dirtyRegion); // swap buffers (presentation) hw->swapBuffers(getHwComposer()); } bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) { RenderEngine& engine(getRenderEngine()); const int32_t id = hw->getHwcDisplayId(); HWComposer& hwc(getHwComposer()); HWComposer::LayerListIterator cur = hwc.begin(id); const HWComposer::LayerListIterator end = hwc.end(id); bool hasGlesComposition = hwc.hasGlesComposition(id); if (hasGlesComposition) { if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) { ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s", hw->getDisplayName().string()); eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) { ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting."); } return false; } // Never touch the framebuffer if we don't have any framebuffer layers const bool hasHwcComposition = hwc.hasHwcComposition(id); if (hasHwcComposition) { // when using overlays, we assume a fully transparent framebuffer // NOTE: we could reduce how much we need to clear, for instance // remove where there are opaque FB layers. however, on some // GPUs doing a "clean slate" clear might be more efficient. // We'll revisit later if needed. engine.clearWithColor(0, 0, 0, 0); } else { // we start with the whole screen area const Region bounds(hw->getBounds()); // we remove the scissor part // we're left with the letterbox region // (common case is that letterbox ends-up being empty) const Region letterbox(bounds.subtract(hw->getScissor())); // compute the area to clear Region region(hw->undefinedRegion.merge(letterbox)); // but limit it to the dirty region region.andSelf(dirty); // screen is already cleared here if (!region.isEmpty()) { // can happen with SurfaceView drawWormHoleIfRequired(cur, end, hw, region); } } if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) { // just to be on the safe side, we don't set the // scissor on the main display. It should never be needed // anyways (though in theory it could since the API allows it). const Rect& bounds(hw->getBounds()); const Rect& scissor(hw->getScissor()); if (scissor != bounds) { // scissor doesn't match the screen's dimensions, so we // need to clear everything outside of it and enable // the GL scissor so we don't draw anything where we shouldn't // enable scissor for this frame const uint32_t height = hw->getHeight(); engine.setScissor(scissor.left, height - scissor.bottom, scissor.getWidth(), scissor.getHeight()); } } } /* * and then, render the layers targeted at the framebuffer */ const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ()); const size_t count = layers.size(); const Transform& tr = hw->getTransform(); if (cur != end) { // we're using h/w composer for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) { const sp<Layer>& layer(layers[i]); const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); if (!clip.isEmpty()) { switch (cur->getCompositionType()) { case HWC_CURSOR_OVERLAY: case HWC_OVERLAY: { const Layer::State& state(layer->getDrawingState()); if ((cur->getHints() & HWC_HINT_CLEAR_FB) && i && layer->isOpaque(state) && (state.alpha == 0xFF) && hasGlesComposition) { // never clear the very first layer since we're // guaranteed the FB is already cleared layer->clearWithOpenGL(hw, clip); } break; } case HWC_FRAMEBUFFER: { layer->draw(hw, clip); break; } case HWC_FRAMEBUFFER_TARGET: { // this should not happen as the iterator shouldn't // let us get there. ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i); break; } } } layer->setAcquireFence(hw, *cur); } } else { // we're not using h/w composer for (size_t i=0 ; i<count ; ++i) { const sp<Layer>& layer(layers[i]); const Region clip(dirty.intersect( tr.transform(layer->visibleRegion))); if (!clip.isEmpty()) { layer->draw(hw, clip); } } } // disable scissor at the end of the frame engine.disableScissor(); return true; } void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const { const int32_t height = hw->getHeight(); RenderEngine& engine(getRenderEngine()); engine.fillRegionWithColor(region, height, 0, 0, 0, 0); } status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle, const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc) { // add this layer to the current state list { Mutex::Autolock _l(mStateLock); if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) { return NO_MEMORY; } mCurrentState.layersSortedByZ.add(lbc); mGraphicBufferProducerList.add(IInterface::asBinder(gbc)); } // attach this layer to the client client->attachLayer(handle, lbc); return NO_ERROR; } status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) { Mutex::Autolock _l(mStateLock); ssize_t index = mCurrentState.layersSortedByZ.remove(layer); if (index >= 0) { mLayersPendingRemoval.push(layer); mLayersRemoved = true; setTransactionFlags(eTransactionNeeded); return NO_ERROR; } return status_t(index); } uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) { return android_atomic_release_load(&mTransactionFlags); } uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) { return android_atomic_and(~flags, &mTransactionFlags) & flags; } uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) { uint32_t old = android_atomic_or(flags, &mTransactionFlags); if ((old & flags)==0) { // wake the server up signalTransaction(); } return old; } void SurfaceFlinger::setTransactionState( const Vector<ComposerState>& state, const Vector<DisplayState>& displays, uint32_t flags) { ATRACE_CALL(); delayDPTransactionIfNeeded(displays); Mutex::Autolock _l(mStateLock); uint32_t transactionFlags = 0; if (flags & eAnimation) { // For window updates that are part of an animation we must wait for // previous animation "frames" to be handled. while (mAnimTransactionPending) { status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); if (CC_UNLIKELY(err != NO_ERROR)) { // just in case something goes wrong in SF, return to the // caller after a few seconds. ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out " "waiting for previous animation frame"); mAnimTransactionPending = false; break; } } } size_t count = displays.size(); for (size_t i=0 ; i<count ; i++) { const DisplayState& s(displays[i]); transactionFlags |= setDisplayStateLocked(s); } count = state.size(); for (size_t i=0 ; i<count ; i++) { const ComposerState& s(state[i]); // Here we need to check that the interface we're given is indeed // one of our own. A malicious client could give us a NULL // IInterface, or one of its own or even one of our own but a // different type. All these situations would cause us to crash. // // NOTE: it would be better to use RTTI as we could directly check // that we have a Client*. however, RTTI is disabled in Android. if (s.client != NULL) { sp<IBinder> binder = IInterface::asBinder(s.client); if (binder != NULL) { String16 desc(binder->getInterfaceDescriptor()); if (desc == ISurfaceComposerClient::descriptor) { sp<Client> client( static_cast<Client *>(s.client.get()) ); transactionFlags |= setClientStateLocked(client, s.state); } } } } if (transactionFlags) { // this triggers the transaction setTransactionFlags(transactionFlags); // if this is a synchronous transaction, wait for it to take effect // before returning. if (flags & eSynchronous) { mTransactionPending = true; } if (flags & eAnimation) { mAnimTransactionPending = true; } while (mTransactionPending) { status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); if (CC_UNLIKELY(err != NO_ERROR)) { // just in case something goes wrong in SF, return to the // called after a few seconds. ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!"); mTransactionPending = false; break; } } } } uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) { ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token); if (dpyIdx < 0) return 0; uint32_t flags = 0; DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx)); if (disp.isValid()) { const uint32_t what = s.what; if (what & DisplayState::eSurfaceChanged) { if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) { disp.surface = s.surface; flags |= eDisplayTransactionNeeded; } } if (what & DisplayState::eLayerStackChanged) { if (disp.layerStack != s.layerStack) { disp.layerStack = s.layerStack; flags |= eDisplayTransactionNeeded; } } if (what & DisplayState::eDisplayProjectionChanged) { if (disp.orientation != s.orientation) { disp.orientation = s.orientation; flags |= eDisplayTransactionNeeded; } if (disp.frame != s.frame) { disp.frame = s.frame; flags |= eDisplayTransactionNeeded; } if (disp.viewport != s.viewport) { disp.viewport = s.viewport; flags |= eDisplayTransactionNeeded; } } if (what & DisplayState::eDisplaySizeChanged) { if (disp.width != s.width) { disp.width = s.width; flags |= eDisplayTransactionNeeded; } if (disp.height != s.height) { disp.height = s.height; flags |= eDisplayTransactionNeeded; } } } return flags; } uint32_t SurfaceFlinger::setClientStateLocked( const sp<Client>& client, const layer_state_t& s) { uint32_t flags = 0; sp<Layer> layer(client->getLayerUser(s.surface)); if (layer != 0) { const uint32_t what = s.what; if (what & layer_state_t::ePositionChanged) { if (layer->setPosition(s.x, s.y)) flags |= eTraversalNeeded; } if (what & layer_state_t::eLayerChanged) { // NOTE: index needs to be calculated before we update the state ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); if (layer->setLayer(s.z)) { mCurrentState.layersSortedByZ.removeAt(idx); mCurrentState.layersSortedByZ.add(layer); // we need traversal (state changed) // AND transaction (list changed) flags |= eTransactionNeeded|eTraversalNeeded; } } if (what & layer_state_t::eSizeChanged) { if (layer->setSize(s.w, s.h)) { flags |= eTraversalNeeded; } } if (what & layer_state_t::eAlphaChanged) { if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) flags |= eTraversalNeeded; } if (what & layer_state_t::eMatrixChanged) { if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded; } if (what & layer_state_t::eTransparentRegionChanged) { if (layer->setTransparentRegionHint(s.transparentRegion)) flags |= eTraversalNeeded; } if (what & layer_state_t::eFlagsChanged) { if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded; } if (what & layer_state_t::eCropChanged) { if (layer->setCrop(s.crop)) flags |= eTraversalNeeded; } if (what & layer_state_t::eLayerStackChanged) { // NOTE: index needs to be calculated before we update the state ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); if (layer->setLayerStack(s.layerStack)) { mCurrentState.layersSortedByZ.removeAt(idx); mCurrentState.layersSortedByZ.add(layer); // we need traversal (state changed) // AND transaction (list changed) flags |= eTransactionNeeded|eTraversalNeeded; } } } return flags; } status_t SurfaceFlinger::createLayer( const String8& name, const sp<Client>& client, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp) { //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); if (int32_t(w|h) < 0) { ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", int(w), int(h)); return BAD_VALUE; } status_t result = NO_ERROR; sp<Layer> layer; switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { case ISurfaceComposerClient::eFXSurfaceNormal: result = createNormalLayer(client, name, w, h, flags, format, handle, gbp, &layer); break; case ISurfaceComposerClient::eFXSurfaceDim: result = createDimLayer(client, name, w, h, flags, handle, gbp, &layer); break; default: result = BAD_VALUE; break; } if (result != NO_ERROR) { return result; } result = addClientLayer(client, *handle, *gbp, layer); if (result != NO_ERROR) { return result; } setTransactionFlags(eTransactionNeeded); return result; } status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client, const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format, sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) { // initialize the surfaces switch (format) { case PIXEL_FORMAT_TRANSPARENT: case PIXEL_FORMAT_TRANSLUCENT: format = PIXEL_FORMAT_RGBA_8888; break; case PIXEL_FORMAT_OPAQUE: format = PIXEL_FORMAT_RGBX_8888; break; } *outLayer = DisplayUtils::getInstance()->getLayerInstance(this, client, name, w, h, flags); status_t err = (*outLayer)->setBuffers(w, h, format, flags); if (err == NO_ERROR) { *handle = (*outLayer)->getHandle(); *gbp = (*outLayer)->getProducer(); } ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err)); return err; } status_t SurfaceFlinger::createDimLayer(const sp<Client>& client, const String8& name, uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) { *outLayer = new LayerDim(this, client, name, w, h, flags); *handle = (*outLayer)->getHandle(); *gbp = (*outLayer)->getProducer(); return NO_ERROR; } status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle) { // called by the window manager when it wants to remove a Layer status_t err = NO_ERROR; sp<Layer> l(client->getLayerUser(handle)); if (l != NULL) { err = removeLayer(l); ALOGE_IF(err<0 && err != NAME_NOT_FOUND, "error removing layer=%p (%s)", l.get(), strerror(-err)); } return err; } status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer) { // called by ~LayerCleaner() when all references to the IBinder (handle) // are gone status_t err = NO_ERROR; sp<Layer> l(layer.promote()); if (l != NULL) { err = removeLayer(l); ALOGE_IF(err<0 && err != NAME_NOT_FOUND, "error removing layer=%p (%s)", l.get(), strerror(-err)); } return err; } // --------------------------------------------------------------------------- void SurfaceFlinger::onInitializeDisplays() { // reset screen orientation and use primary layer stack Vector<ComposerState> state; Vector<DisplayState> displays; DisplayState d; d.what = DisplayState::eDisplayProjectionChanged | DisplayState::eLayerStackChanged; d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]; d.layerStack = 0; d.orientation = DisplayState::eOrientationDefault; d.frame.makeInvalid(); d.viewport.makeInvalid(); d.width = 0; d.height = 0; displays.add(d); setTransactionState(state, displays, 0); setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL); const nsecs_t period = getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); mAnimFrameTracker.setDisplayRefreshPeriod(period); } void SurfaceFlinger::initializeDisplays() { class MessageScreenInitialized : public MessageBase { SurfaceFlinger* flinger; public: MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { } virtual bool handler() { flinger->onInitializeDisplays(); return true; } }; sp<MessageBase> msg = new MessageScreenInitialized(this); postMessageAsync(msg); // we may be called from main thread, use async message } void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw, int mode) { ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(), this); int32_t type = hw->getDisplayType(); int currentMode = hw->getPowerMode(); if (mode == currentMode) { ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode); return; } hw->setPowerMode(mode); if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { ALOGW("Trying to set power mode for virtual display"); return; } if (currentMode == HWC_POWER_MODE_OFF) { getHwComposer().setPowerMode(type, mode); if (type == DisplayDevice::DISPLAY_PRIMARY) { // FIXME: eventthread only knows about the main display right now mEventThread->onScreenAcquired(); resyncToHardwareVsync(true); } mVisibleRegionsDirty = true; mHasPoweredOff = true; repaintEverything(); } else if (mode == HWC_POWER_MODE_OFF) { if (type == DisplayDevice::DISPLAY_PRIMARY) { disableHardwareVsync(true); // also cancels any in-progress resync // FIXME: eventthread only knows about the main display right now mEventThread->onScreenReleased(); } getHwComposer().setPowerMode(type, mode); mVisibleRegionsDirty = true; // from this point on, SF will stop drawing on this display } else { getHwComposer().setPowerMode(type, mode); } } void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) { class MessageSetPowerMode: public MessageBase { SurfaceFlinger& mFlinger; sp<IBinder> mDisplay; int mMode; public: MessageSetPowerMode(SurfaceFlinger& flinger, const sp<IBinder>& disp, int mode) : mFlinger(flinger), mDisplay(disp) { mMode = mode; } virtual bool handler() { sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); if (hw == NULL) { ALOGE("Attempt to set power mode = %d for null display %p", mMode, mDisplay.get()); } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { ALOGW("Attempt to set power mode = %d for virtual display", mMode); } else { mFlinger.setPowerModeInternal(hw, mMode); } return true; } }; sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode); postMessageSync(msg); } // --------------------------------------------------------------------------- status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) { String8 result; IPCThreadState* ipc = IPCThreadState::self(); const int pid = ipc->getCallingPid(); const int uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) { result.appendFormat("Permission Denial: " "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid); } else { // Try to get the main lock, but give up after one second // (this would indicate SF is stuck, but we want to be able to // print something in dumpsys). status_t err = mStateLock.timedLock(s2ns(1)); bool locked = (err == NO_ERROR); if (!locked) { result.appendFormat( "SurfaceFlinger appears to be unresponsive (%s [%d]), " "dumping anyways (no locks held)\n", strerror(-err), err); } bool dumpAll = true; size_t index = 0; size_t numArgs = args.size(); if (numArgs) { if ((index < numArgs) && (args[index] == String16("--list"))) { index++; listLayersLocked(args, index, result); dumpAll = false; } if ((index < numArgs) && (args[index] == String16("--latency"))) { index++; dumpStatsLocked(args, index, result); dumpAll = false; } if ((index < numArgs) && (args[index] == String16("--latency-clear"))) { index++; clearStatsLocked(args, index, result); dumpAll = false; } if ((index < numArgs) && (args[index] == String16("--dispsync"))) { index++; mPrimaryDispSync.dump(result); dumpAll = false; } if ((index < numArgs) && (args[index] == String16("--static-screen"))) { index++; dumpStaticScreenStats(result); dumpAll = false; } } if (dumpAll) { dumpAllLocked(args, index, result); } if (locked) { mStateLock.unlock(); } } write(fd, result.string(), result.size()); return NO_ERROR; } void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */, String8& result) const { const LayerVector& currentLayers = mCurrentState.layersSortedByZ; const size_t count = currentLayers.size(); for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(currentLayers[i]); result.appendFormat("%s\n", layer->getName().string()); } } void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const { String8 name; if (index < args.size()) { name = String8(args[index]); index++; } const nsecs_t period = getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); result.appendFormat("%" PRId64 "\n", period); if (name.isEmpty()) { mAnimFrameTracker.dumpStats(result); } else { const LayerVector& currentLayers = mCurrentState.layersSortedByZ; const size_t count = currentLayers.size(); for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(currentLayers[i]); if (name == layer->getName()) { layer->dumpFrameStats(result); } } } } void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, String8& /* result */) { String8 name; if (index < args.size()) { name = String8(args[index]); index++; } const LayerVector& currentLayers = mCurrentState.layersSortedByZ; const size_t count = currentLayers.size(); for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(currentLayers[i]); if (name.isEmpty() || (name == layer->getName())) { layer->clearFrameStats(); } } mAnimFrameTracker.clearStats(); } // This should only be called from the main thread. Otherwise it would need // the lock and should use mCurrentState rather than mDrawingState. void SurfaceFlinger::logFrameStats() { const LayerVector& drawingLayers = mDrawingState.layersSortedByZ; const size_t count = drawingLayers.size(); for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(drawingLayers[i]); layer->logFrameStats(); } mAnimFrameTracker.logAndResetStats(String8("<win-anim>")); } /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result) { static const char* config = " [sf" #ifdef HAS_CONTEXT_PRIORITY " HAS_CONTEXT_PRIORITY" #endif #ifdef NEVER_DEFAULT_TO_ASYNC_MODE " NEVER_DEFAULT_TO_ASYNC_MODE" #endif #ifdef TARGET_DISABLE_TRIPLE_BUFFERING " TARGET_DISABLE_TRIPLE_BUFFERING" #endif "]"; result.append(config); } void SurfaceFlinger::dumpStaticScreenStats(String8& result) const { result.appendFormat("Static screen stats:\n"); for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) { float bucketTimeSec = mFrameBuckets[b] / 1e9; float percent = 100.0f * static_cast<float>(mFrameBuckets[b]) / mTotalTime; result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent); } float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9; float percent = 100.0f * static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime; result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n", NUM_BUCKETS - 1, bucketTimeSec, percent); } void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const { bool colorize = false; if (index < args.size() && (args[index] == String16("--color"))) { colorize = true; index++; } Colorizer colorizer(colorize); // figure out if we're stuck somewhere const nsecs_t now = systemTime(); const nsecs_t inSwapBuffers(mDebugInSwapBuffers); const nsecs_t inTransaction(mDebugInTransaction); nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; /* * Dump library configuration. */ colorizer.bold(result); result.append("Build configuration:"); colorizer.reset(result); appendSfConfigString(result); appendUiConfigString(result); appendGuiConfigString(result); result.append("\n"); colorizer.bold(result); result.append("Sync configuration: "); colorizer.reset(result); result.append(SyncFeatures::getInstance().toString()); result.append("\n"); colorizer.bold(result); result.append("DispSync configuration: "); colorizer.reset(result); result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, " "present offset %d ns (refresh %" PRId64 " ns)", vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS, mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY)); result.append("\n"); // Dump static screen stats result.append("\n"); dumpStaticScreenStats(result); result.append("\n"); /* * Dump the visible layer list */ const LayerVector& currentLayers = mCurrentState.layersSortedByZ; const size_t count = currentLayers.size(); colorizer.bold(result); result.appendFormat("Visible layers (count = %zu)\n", count); colorizer.reset(result); for (size_t i=0 ; i<count ; i++) { const sp<Layer>& layer(currentLayers[i]); layer->dump(result, colorizer); } /* * Dump Display state */ colorizer.bold(result); result.appendFormat("Displays (%zu entries)\n", mDisplays.size()); colorizer.reset(result); for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { const sp<const DisplayDevice>& hw(mDisplays[dpy]); hw->dump(result); } /* * Dump SurfaceFlinger global state */ colorizer.bold(result); result.append("SurfaceFlinger global state:\n"); colorizer.reset(result); HWComposer& hwc(getHwComposer()); sp<const DisplayDevice> hw(getDefaultDisplayDevice()); colorizer.bold(result); result.appendFormat("EGL implementation : %s\n", eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION)); colorizer.reset(result); result.appendFormat("%s\n", eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS)); mRenderEngine->dump(result); hw->undefinedRegion.dump(result, "undefinedRegion"); result.appendFormat(" orientation=%d, isDisplayOn=%d\n", hw->getOrientation(), hw->isDisplayOn()); result.appendFormat( " last eglSwapBuffers() time: %f us\n" " last transaction time : %f us\n" " transaction-flags : %08x\n" " refresh-rate : %f fps\n" " x-dpi : %f\n" " y-dpi : %f\n" " gpu_to_cpu_unsupported : %d\n" , mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0, mTransactionFlags, 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY), hwc.getDpiX(HWC_DISPLAY_PRIMARY), hwc.getDpiY(HWC_DISPLAY_PRIMARY), !mGpuToCpuSupported); result.appendFormat(" eglSwapBuffers time: %f us\n", inSwapBuffersDuration/1000.0); result.appendFormat(" transaction time: %f us\n", inTransactionDuration/1000.0); /* * VSYNC state */ mEventThread->dump(result); /* * Dump HWComposer state */ colorizer.bold(result); result.append("h/w composer state:\n"); colorizer.reset(result); result.appendFormat(" h/w composer %s and %s\n", hwc.initCheck()==NO_ERROR ? "present" : "not present", (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) ? "disabled" : "enabled"); hwc.dump(result); /* * Dump gralloc state */ const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); alloc.dump(result); } const Vector< sp<Layer> >& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) { // Note: mStateLock is held here wp<IBinder> dpy; for (size_t i=0 ; i<mDisplays.size() ; i++) { if (mDisplays.valueAt(i)->getHwcDisplayId() == id) { dpy = mDisplays.keyAt(i); break; } } if (dpy == NULL) { ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id); // Just use the primary display so we have something to return dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY); } return getDisplayDevice(dpy)->getVisibleLayersSortedByZ(); } bool SurfaceFlinger::startDdmConnection() { void* libddmconnection_dso = dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW); if (!libddmconnection_dso) { return false; } void (*DdmConnection_start)(const char* name); DdmConnection_start = (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start"); if (!DdmConnection_start) { dlclose(libddmconnection_dso); return false; } (*DdmConnection_start)(getServiceName()); return true; } status_t SurfaceFlinger::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch (code) { case CREATE_CONNECTION: case CREATE_DISPLAY: case SET_TRANSACTION_STATE: case BOOT_FINISHED: case CLEAR_ANIMATION_FRAME_STATS: case GET_ANIMATION_FRAME_STATS: case SET_POWER_MODE: { // codes that require permission check IPCThreadState* ipc = IPCThreadState::self(); const int pid = ipc->getCallingPid(); const int uid = ipc->getCallingUid(); if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) && !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { ALOGE("Permission Denial: " "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); return PERMISSION_DENIED; } break; } case CAPTURE_SCREEN: { // codes that require permission check IPCThreadState* ipc = IPCThreadState::self(); const int pid = ipc->getCallingPid(); const int uid = ipc->getCallingUid(); if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { ALOGE("Permission Denial: " "can't read framebuffer pid=%d, uid=%d", pid, uid); return PERMISSION_DENIED; } break; } } status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { CHECK_INTERFACE(ISurfaceComposer, data, reply); if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { IPCThreadState* ipc = IPCThreadState::self(); const int pid = ipc->getCallingPid(); const int uid = ipc->getCallingUid(); ALOGE("Permission Denial: " "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); return PERMISSION_DENIED; } int n; switch (code) { case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE return NO_ERROR; case 1002: // SHOW_UPDATES n = data.readInt32(); mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); invalidateHwcGeometry(); repaintEverything(); return NO_ERROR; case 1004:{ // repaint everything repaintEverything(); return NO_ERROR; } case 1005:{ // force transaction setTransactionFlags( eTransactionNeeded| eDisplayTransactionNeeded| eTraversalNeeded); return NO_ERROR; } case 1006:{ // send empty update signalRefresh(); return NO_ERROR; } case 1008: // toggle use of hw composer n = data.readInt32(); mDebugDisableHWC = n ? 1 : 0; invalidateHwcGeometry(); repaintEverything(); return NO_ERROR; case 1009: // toggle use of transform hint n = data.readInt32(); mDebugDisableTransformHint = n ? 1 : 0; invalidateHwcGeometry(); repaintEverything(); return NO_ERROR; case 1010: // interrogate. reply->writeInt32(0); reply->writeInt32(0); reply->writeInt32(mDebugRegion); reply->writeInt32(0); reply->writeInt32(mDebugDisableHWC); return NO_ERROR; case 1013: { Mutex::Autolock _l(mStateLock); sp<const DisplayDevice> hw(getDefaultDisplayDevice()); reply->writeInt32(hw->getPageFlipCount()); return NO_ERROR; } case 1014: { // daltonize n = data.readInt32(); switch (n % 10) { case 1: mDaltonizer.setType(Daltonizer::protanomaly); break; case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break; case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break; } if (n >= 10) { mDaltonizer.setMode(Daltonizer::correction); } else { mDaltonizer.setMode(Daltonizer::simulation); } mDaltonize = n > 0; invalidateHwcGeometry(); repaintEverything(); return NO_ERROR; } case 1015: { // apply a color matrix n = data.readInt32(); mHasColorMatrix = n ? 1 : 0; if (n) { // color matrix is sent as mat3 matrix followed by vec3 // offset, then packed into a mat4 where the last row is // the offset and extra values are 0 for (size_t i = 0 ; i < 4; i++) { for (size_t j = 0; j < 4; j++) { mColorMatrix[i][j] = data.readFloat(); } } } else { mColorMatrix = mat4(); } invalidateHwcGeometry(); repaintEverything(); return NO_ERROR; } // This is an experimental interface // Needs to be shifted to proper binder interface when we productize case 1016: { n = data.readInt32(); mPrimaryDispSync.setRefreshSkipCount(n); return NO_ERROR; } case 1017: { n = data.readInt32(); mForceFullDamage = static_cast<bool>(n); return NO_ERROR; } case 1018: { // Modify Choreographer's phase offset n = data.readInt32(); mEventThread->setPhaseOffset(static_cast<nsecs_t>(n)); return NO_ERROR; } case 1019: { // Modify SurfaceFlinger's phase offset n = data.readInt32(); mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n)); return NO_ERROR; } } } return err; } void SurfaceFlinger::repaintEverything() { android_atomic_or(1, &mRepaintEverything); signalTransaction(); } // --------------------------------------------------------------------------- // Capture screen into an IGraphiBufferProducer // --------------------------------------------------------------------------- /* The code below is here to handle b/8734824 * * We create a IGraphicBufferProducer wrapper that forwards all calls * from the surfaceflinger thread to the calling binder thread, where they * are executed. This allows the calling thread in the calling process to be * reused and not depend on having "enough" binder threads to handle the * requests. */ class GraphicProducerWrapper : public BBinder, public MessageHandler { /* Parts of GraphicProducerWrapper are run on two different threads, * communicating by sending messages via Looper but also by shared member * data. Coherence maintenance is subtle and in places implicit (ugh). * * Don't rely on Looper's sendMessage/handleMessage providing * release/acquire semantics for any data not actually in the Message. * Data going from surfaceflinger to binder threads needs to be * synchronized explicitly. * * Barrier open/wait do provide release/acquire semantics. This provides * implicit synchronization for data coming back from binder to * surfaceflinger threads. */ sp<IGraphicBufferProducer> impl; sp<Looper> looper; status_t result; bool exitPending; bool exitRequested; Barrier barrier; uint32_t code; Parcel const* data; Parcel* reply; enum { MSG_API_CALL, MSG_EXIT }; /* * Called on surfaceflinger thread. This is called by our "fake" * BpGraphicBufferProducer. We package the data and reply Parcel and * forward them to the binder thread. */ virtual status_t transact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t /* flags */) { this->code = code; this->data = &data; this->reply = reply; if (exitPending) { // if we've exited, we run the message synchronously right here. // note (JH): as far as I can tell from looking at the code, this // never actually happens. if it does, i'm not sure if it happens // on the surfaceflinger or binder thread. handleMessage(Message(MSG_API_CALL)); } else { barrier.close(); // Prevent stores to this->{code, data, reply} from being // reordered later than the construction of Message. atomic_thread_fence(memory_order_release); looper->sendMessage(this, Message(MSG_API_CALL)); barrier.wait(); } return result; } /* * here we run on the binder thread. All we've got to do is * call the real BpGraphicBufferProducer. */ virtual void handleMessage(const Message& message) { int what = message.what; // Prevent reads below from happening before the read from Message atomic_thread_fence(memory_order_acquire); if (what == MSG_API_CALL) { result = IInterface::asBinder(impl)->transact(code, data[0], reply); barrier.open(); } else if (what == MSG_EXIT) { exitRequested = true; } } public: GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) : impl(impl), looper(new Looper(true)), exitPending(false), exitRequested(false) {} // Binder thread status_t waitForResponse() { do { looper->pollOnce(-1); } while (!exitRequested); return result; } // Client thread void exit(status_t result) { this->result = result; exitPending = true; // Ensure this->result is visible to the binder thread before it // handles the message. atomic_thread_fence(memory_order_release); looper->sendMessage(this, Message(MSG_EXIT)); } }; status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, const sp<IGraphicBufferProducer>& producer, Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ, uint32_t maxLayerZ, bool useIdentityTransform, ISurfaceComposer::Rotation rotation) { if (CC_UNLIKELY(display == 0)) return BAD_VALUE; if (CC_UNLIKELY(producer == 0)) return BAD_VALUE; // if we have secure windows on this display, never allow the screen capture // unless the producer interface is local (i.e.: we can take a screenshot for // ourselves). if (!IInterface::asBinder(producer)->localBinder()) { Mutex::Autolock _l(mStateLock); sp<const DisplayDevice> hw(getDisplayDevice(display)); if (hw->getSecureLayerVisible()) { ALOGW("FB is protected: PERMISSION_DENIED"); return PERMISSION_DENIED; } } // Convert to surfaceflinger's internal rotation type. Transform::orientation_flags rotationFlags; switch (rotation) { case ISurfaceComposer::eRotateNone: rotationFlags = Transform::ROT_0; break; case ISurfaceComposer::eRotate90: rotationFlags = Transform::ROT_90; break; case ISurfaceComposer::eRotate180: rotationFlags = Transform::ROT_180; break; case ISurfaceComposer::eRotate270: rotationFlags = Transform::ROT_270; break; default: rotationFlags = Transform::ROT_0; ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation); break; } class MessageCaptureScreen : public MessageBase { SurfaceFlinger* flinger; sp<IBinder> display; sp<IGraphicBufferProducer> producer; Rect sourceCrop; uint32_t reqWidth, reqHeight; uint32_t minLayerZ,maxLayerZ; bool useIdentityTransform; Transform::orientation_flags rotation; status_t result; public: MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display, const sp<IGraphicBufferProducer>& producer, Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ, uint32_t maxLayerZ, bool useIdentityTransform, Transform::orientation_flags rotation) : flinger(flinger), display(display), producer(producer), sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight), minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), useIdentityTransform(useIdentityTransform), rotation(rotation), result(PERMISSION_DENIED) { } status_t getResult() const { return result; } virtual bool handler() { Mutex::Autolock _l(flinger->mStateLock); sp<const DisplayDevice> hw(flinger->getDisplayDevice(display)); result = flinger->captureScreenImplLocked(hw, producer, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, useIdentityTransform, rotation); static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result); return true; } }; // make sure to process transactions before screenshots -- a transaction // might already be pending but scheduled for VSYNC; this guarantees we // will handle it before the screenshot. When VSYNC finally arrives // the scheduled transaction will be a no-op. If no transactions are // scheduled at this time, this will end-up being a no-op as well. mEventQueue.invalidateTransactionNow(); // this creates a "fake" BBinder which will serve as a "fake" remote // binder to receive the marshaled calls and forward them to the // real remote (a BpGraphicBufferProducer) sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer); // the asInterface() call below creates our "fake" BpGraphicBufferProducer // which does the marshaling work forwards to our "fake remote" above. sp<MessageBase> msg = new MessageCaptureScreen(this, display, IGraphicBufferProducer::asInterface( wrapper ), sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, useIdentityTransform, rotationFlags); status_t res = postMessageAsync(msg); if (res == NO_ERROR) { res = wrapper->waitForResponse(); } return res; } void SurfaceFlinger::renderScreenImplLocked( const sp<const DisplayDevice>& hw, Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ, uint32_t maxLayerZ, bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation) { ATRACE_CALL(); RenderEngine& engine(getRenderEngine()); // get screen geometry const int32_t hw_w = hw->getWidth(); const int32_t hw_h = hw->getHeight(); const bool filtering = static_cast<int32_t>(reqWidth) != hw_w || static_cast<int32_t>(reqHeight) != hw_h; // if a default or invalid sourceCrop is passed in, set reasonable values if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) { sourceCrop.setLeftTop(Point(0, 0)); sourceCrop.setRightBottom(Point(hw_w, hw_h)); } // ensure that sourceCrop is inside screen if (sourceCrop.left < 0) { ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left); } if (sourceCrop.right > hw_w) { ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w); } if (sourceCrop.top < 0) { ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top); } if (sourceCrop.bottom > hw_h) { ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h); } // make sure to clear all GL error flags engine.checkErrors(); if (DisplayDevice::DISPLAY_PRIMARY == hw->getDisplayType() && hw->isPanelInverseMounted()) { rotation = (Transform::orientation_flags) (rotation ^ Transform::ROT_180); } // set-up our viewport engine.setViewportAndProjection( reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation); engine.disableTexturing(); // redraw the screen entirely... engine.clearWithColor(0, 0, 0, 1); const LayerVector& layers( mDrawingState.layersSortedByZ ); const size_t count = layers.size(); for (size_t i=0 ; i<count ; ++i) { const sp<Layer>& layer(layers[i]); const Layer::State& state(layer->getDrawingState()); if (state.layerStack == hw->getLayerStack()) { if (state.z >= minLayerZ && state.z <= maxLayerZ) { if (canDrawLayerinScreenShot(hw,layer)) { if (filtering) layer->setFiltering(true); layer->draw(hw, useIdentityTransform); if (filtering) layer->setFiltering(false); } } } } // compositionComplete is needed for older driver hw->compositionComplete(); hw->setViewportAndProjection(); } status_t SurfaceFlinger::captureScreenImplLocked( const sp<const DisplayDevice>& hw, const sp<IGraphicBufferProducer>& producer, Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ, uint32_t maxLayerZ, bool useIdentityTransform, Transform::orientation_flags rotation) { ATRACE_CALL(); // get screen geometry uint32_t hw_w = hw->getWidth(); uint32_t hw_h = hw->getHeight(); if (rotation & Transform::ROT_90) { std::swap(hw_w, hw_h); } if ((reqWidth > hw_w) || (reqHeight > hw_h)) { ALOGE("size mismatch (%d, %d) > (%d, %d)", reqWidth, reqHeight, hw_w, hw_h); return BAD_VALUE; } reqWidth = (!reqWidth) ? hw_w : reqWidth; reqHeight = (!reqHeight) ? hw_h : reqHeight; // create a surface (because we're a producer, and we need to // dequeue/queue a buffer) sp<Surface> sur = new Surface(producer, false); ANativeWindow* window = sur.get(); status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL); if (result == NO_ERROR) { uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE; int err = 0; err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight); err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW); err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888); err |= native_window_set_usage(window, usage); if (err == NO_ERROR) { ANativeWindowBuffer* buffer; /* TODO: Once we have the sync framework everywhere this can use * server-side waits on the fence that dequeueBuffer returns. */ result = native_window_dequeue_buffer_and_wait(window, &buffer); if (result == NO_ERROR) { int syncFd = -1; // create an EGLImage from the buffer so we can later // turn it into a texture EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, buffer, NULL); if (image != EGL_NO_IMAGE_KHR) { // this binds the given EGLImage as a framebuffer for the // duration of this scope. RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image); if (imageBond.getStatus() == NO_ERROR) { // this will in fact render into our dequeued buffer // via an FBO, which means we didn't have to create // an EGLSurface and therefore we're not // dependent on the context's EGLConfig. renderScreenImplLocked( hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true, useIdentityTransform, rotation); // Attempt to create a sync khr object that can produce a sync point. If that // isn't available, create a non-dupable sync object in the fallback path and // wait on it directly. EGLSyncKHR sync; if (!DEBUG_SCREENSHOTS) { sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL); // native fence fd will not be populated until flush() is done. getRenderEngine().flush(); } else { sync = EGL_NO_SYNC_KHR; } if (sync != EGL_NO_SYNC_KHR) { // get the sync fd syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync); if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) { ALOGW("captureScreen: failed to dup sync khr object"); syncFd = -1; } eglDestroySyncKHR(mEGLDisplay, sync); } else { // fallback path sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL); if (sync != EGL_NO_SYNC_KHR) { EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/); EGLint eglErr = eglGetError(); if (result == EGL_TIMEOUT_EXPIRED_KHR) { ALOGW("captureScreen: fence wait timed out"); } else { ALOGW_IF(eglErr != EGL_SUCCESS, "captureScreen: error waiting on EGL fence: %#x", eglErr); } eglDestroySyncKHR(mEGLDisplay, sync); } else { ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError()); } } if (DEBUG_SCREENSHOTS) { uint32_t* pixels = new uint32_t[reqWidth*reqHeight]; getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels); checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, hw, minLayerZ, maxLayerZ); delete [] pixels; } } else { ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot"); result = INVALID_OPERATION; } // destroy our image eglDestroyImageKHR(mEGLDisplay, image); } else { result = BAD_VALUE; } // queueBuffer takes ownership of syncFd result = window->queueBuffer(window, buffer, syncFd); } } else { result = BAD_VALUE; } native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL); } return result; } void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr, const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) { if (DEBUG_SCREENSHOTS) { for (size_t y=0 ; y<h ; y++) { uint32_t const * p = (uint32_t const *)vaddr + y*s; for (size_t x=0 ; x<w ; x++) { if (p[x] != 0xFF000000) return; } } ALOGE("*** we just took a black screenshot ***\n" "requested minz=%d, maxz=%d, layerStack=%d", minLayerZ, maxLayerZ, hw->getLayerStack()); const LayerVector& layers( mDrawingState.layersSortedByZ ); const size_t count = layers.size(); for (size_t i=0 ; i<count ; ++i) { const sp<Layer>& layer(layers[i]); const Layer::State& state(layer->getDrawingState()); const bool visible = (state.layerStack == hw->getLayerStack()) && (state.z >= minLayerZ && state.z <= maxLayerZ) && (layer->isVisible()); ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x", visible ? '+' : '-', i, layer->getName().string(), state.layerStack, state.z, layer->isVisible(), state.flags, state.alpha); } } } /* ------------------------------------------------------------------------ * Extensions */ bool SurfaceFlinger::updateLayerVisibleNonTransparentRegion(const int& /*dpy*/, const sp<Layer>& layer, bool& /*bIgnoreLayers*/, int& /*indexLOI*/, uint32_t layerStack, const int& /*i*/) { const Layer::State& s(layer->getDrawingState()); // only consider the layers on the given layer stack if (s.layerStack != layerStack) { /* set the visible region as empty since we have removed the * layerstack check in rebuildLayerStack() function */ Region visibleNonTransRegion; visibleNonTransRegion.set(Rect(0,0)); layer->setVisibleNonTransparentRegion(visibleNonTransRegion); return true; } return false; } bool SurfaceFlinger::canDrawLayerinScreenShot( const sp<const DisplayDevice>& /*hw*/, const sp<Layer>& layer) { return layer->isVisible(); } void SurfaceFlinger::drawWormHoleIfRequired(HWComposer::LayerListIterator& /*cur*/, const HWComposer::LayerListIterator& /*end*/, const sp<const DisplayDevice>& hw, const Region& region) { drawWormhole(hw, region); } // --------------------------------------------------------------------------- SurfaceFlinger::LayerVector::LayerVector() { } SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) : SortedVector<sp<Layer> >(rhs) { } int SurfaceFlinger::LayerVector::do_compare(const void* lhs, const void* rhs) const { // sort layers per layer-stack, then by z-order and finally by sequence const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs)); const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs)); uint32_t ls = l->getCurrentState().layerStack; uint32_t rs = r->getCurrentState().layerStack; if (ls != rs) return ls - rs; uint32_t lz = l->getCurrentState().z; uint32_t rz = r->getCurrentState().z; if (lz != rz) return lz - rz; return l->sequence - r->sequence; } // --------------------------------------------------------------------------- SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) { } SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type) : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) { viewport.makeInvalid(); frame.makeInvalid(); } // --------------------------------------------------------------------------- }; // namespace android #if defined(__gl_h_) #error "don't include gl/gl.h in this file" #endif #if defined(__gl2_h_) #error "don't include gl2/gl2.h in this file" #endif
88841590357d21660d9146cbd4eb03406da770c6
2e72a74d760a8c14ca242df077413a9ff9699774
/include/gto_d2_kit/d2_ee_spds_AC.hpp
04c0a4924f3165bcf1ba7d0091a08fbd8c338008
[]
no_license
chemiczny/automateusz_gto_d2
ba3f1bec939a135a3591d512663ee01c4aa10b0c
b4c7e0978424bf53fd4b1f67de8e65ab3373fc10
refs/heads/master
2020-03-21T15:30:46.767378
2019-05-08T14:33:56
2019-05-08T14:33:56
138,716,717
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
hpp
#ifndef D2_EE_SPDS_AC_HPP #define D2_EE_SPDS_AC_HPP void second_derivative_ee_0120_13( const double ae, const double xA, const double yA, const double zA, const double be, const double xB, const double yB, const double zB, const double ce, const double xC, const double yC, const double zC, const double de, const double xD, const double yD, const double zD, const double* const bs, double* const d2eexx, double* const d2eexy, double* const d2eexz, double* const d2eeyx, double* const d2eeyy, double* const d2eeyz, double* const d2eezx, double* const d2eezy, double* const d2eezz); void second_derivative_ee_0120_31( const double ae, const double xA, const double yA, const double zA, const double be, const double xB, const double yB, const double zB, const double ce, const double xC, const double yC, const double zC, const double de, const double xD, const double yD, const double zD, const double* const bs, double* const d2eexx, double* const d2eexy, double* const d2eexz, double* const d2eeyx, double* const d2eeyy, double* const d2eeyz, double* const d2eezx, double* const d2eezy, double* const d2eezz); #endif
81b659b5504278a3b7c42c8af5786526c2f4298a
4ca2b09fb25a1e30ed02f7f471e675e9621c6b5e
/task_7_sensors/Code/libraries/forceSensor_lib/ForceSensor.cpp
158a35e07142078fa75e45faca00d77bdaba37a1
[]
no_license
MRSD2018/minebot
c37ca9631d626e746500f04695710c556282c7f6
10b36904d292a9f067edaf7cd4cc2aa5d0c9f43f
refs/heads/master
2021-01-23T17:09:25.776356
2018-04-02T16:08:02
2018-04-02T16:08:02
102,762,889
2
0
null
null
null
null
UTF-8
C++
false
false
824
cpp
#include "Arduino.h" #include "ForceSensor.h" ForceSensor::ForceSensor(int pin) { pinMode(pin, INPUT); _pin = pin; } int ForceSensor::getRawOutput(){ return analogRead(_pin); } float ForceSensor::getForce(){ // outputs force [grams] float V = (getFilteredOutput()/1023.0)*5.0; return exp((V-0.5975)/0.5459); } float ForceSensor::getFilteredOutput(){ // code from: https://www.arduino.cc/en/Tutorial/Smoothing total = total - readings[readIndex]; readings[readIndex] = getRawOutput(); total = total + readings[readIndex]; readIndex++; if (readIndex >= numReadings) { readIndex = 0; } return total / numReadings; } void ForceSensor::initDataArray(){ // start with an array of zeros for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } }
3fb33875e31d96d0f5f5ef8a289f21106d0d71c8
f8ecaa68b86d3f7f7c7cdd9f9f2c84832ed3bbd4
/BacterieA.h
3dc699179e6206480b9a95470f42d9a67600a39c
[]
no_license
3bim/projet-conte
583d48d6fada96377debc0a325a1af84dc930a0f
af1cf4fd36966686194d34a48ec0bae469963407
refs/heads/master
2020-03-14T11:37:28.351073
2018-06-21T07:50:12
2018-06-21T07:50:12
131,594,213
0
0
null
null
null
null
UTF-8
C++
false
false
371
h
#ifndef BACTERIE_A_H_ #define BACTERIE_A_H_ #include "Bacterie.h" class BacterieA : public Bacterie { public: BacterieA(); BacterieA(map<char,double> phen); virtual ~BacterieA(); void metabolisme(map<char,double>* ext); void set_fitness(); Bacterie* reproduire(); inline char type(); }; inline char BacterieA::type() {return 'A';} #endif
72c8ccf1b40ff2f4b73f427210ee06c3c2adaa58
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/printscan/faxsrv/src/test/src/xxxunusedxxx/corruptimage/corruptprocess.h
19ce03aef97c21e91522fe0e494067785a2d19a5
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
869
h
// CorruptProcess.h: interface for the CCorruptProcess class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_CORRUPTPROCESS_H__C470EDEB_7C79_4B3C_B1F5_190F57609DBE__INCLUDED_) #define AFX_CORRUPTPROCESS_H__C470EDEB_7C79_4B3C_B1F5_190F57609DBE__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "CorruptImageBase.h" class CCorruptProcess : public CCorruptImageBase { public: CCorruptProcess(); virtual ~CCorruptProcess(); static HANDLE CreateProcess(TCHAR *szImageName, TCHAR *szParams); protected: virtual bool CorruptOriginalImageBuffer(PVOID pCorruptionData); virtual HANDLE LoadImage(TCHAR *szImageName, TCHAR *szParams); void CleanupCorrupedImages(); }; #endif // !defined(AFX_CORRUPTPROCESS_H__C470EDEB_7C79_4B3C_B1F5_190F57609DBE__INCLUDED_)
36232df7257dc5b7c176611517eb673f38fddaa2
9ef4d29828d597c3c80e5083be55edf3e02659b4
/hovercraft/msg_gen/cpp/include/hovercraft/Current.h
58b801abb5fe64ae502a73162466ef5149f89af2
[]
no_license
travis-sweetser/HoverboardCSCE439
f48fcd72ef4f587a639ed8e79528b39cddcb2b62
1f11a73c26484ed4bde7b37c0777fa724deeefaf
refs/heads/master
2021-05-29T15:56:11.814455
2013-09-15T22:48:11
2013-09-15T22:48:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,949
h
/* Auto-generated by genmsg_cpp for file /mnt/hgfs/groovy_workspace/sandbox/HoverboardCSCE439/hovercraft/msg/Current.msg */ #ifndef HOVERCRAFT_MESSAGE_CURRENT_H #define HOVERCRAFT_MESSAGE_CURRENT_H #include <string> #include <vector> #include <map> #include <ostream> #include "ros/serialization.h" #include "ros/builtin_message_traits.h" #include "ros/message_operations.h" #include "ros/time.h" #include "ros/macros.h" #include "ros/assert.h" #include "std_msgs/Header.h" namespace hovercraft { template <class ContainerAllocator> struct Current_ { typedef Current_<ContainerAllocator> Type; Current_() : header() , current(0.0) { } Current_(const ContainerAllocator& _alloc) : header(_alloc) , current(0.0) { } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; ::std_msgs::Header_<ContainerAllocator> header; typedef double _current_type; double current; typedef boost::shared_ptr< ::hovercraft::Current_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::hovercraft::Current_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; // struct Current typedef ::hovercraft::Current_<std::allocator<void> > Current; typedef boost::shared_ptr< ::hovercraft::Current> CurrentPtr; typedef boost::shared_ptr< ::hovercraft::Current const> CurrentConstPtr; template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::hovercraft::Current_<ContainerAllocator> & v) { ros::message_operations::Printer< ::hovercraft::Current_<ContainerAllocator> >::stream(s, "", v); return s;} } // namespace hovercraft namespace ros { namespace message_traits { template<class ContainerAllocator> struct IsMessage< ::hovercraft::Current_<ContainerAllocator> > : public TrueType {}; template<class ContainerAllocator> struct IsMessage< ::hovercraft::Current_<ContainerAllocator> const> : public TrueType {}; template<class ContainerAllocator> struct MD5Sum< ::hovercraft::Current_<ContainerAllocator> > { static const char* value() { return "0f12dc28919a92ca29c78429b7b11164"; } static const char* value(const ::hovercraft::Current_<ContainerAllocator> &) { return value(); } static const uint64_t static_value1 = 0x0f12dc28919a92caULL; static const uint64_t static_value2 = 0x29c78429b7b11164ULL; }; template<class ContainerAllocator> struct DataType< ::hovercraft::Current_<ContainerAllocator> > { static const char* value() { return "hovercraft/Current"; } static const char* value(const ::hovercraft::Current_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct Definition< ::hovercraft::Current_<ContainerAllocator> > { static const char* value() { return "Header header\n\ \n\ #The current in Amps\n\ float64 current \n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.secs: seconds (stamp_secs) since epoch\n\ # * stamp.nsecs: nanoseconds since stamp_secs\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ "; } static const char* value(const ::hovercraft::Current_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct HasHeader< ::hovercraft::Current_<ContainerAllocator> > : public TrueType {}; template<class ContainerAllocator> struct HasHeader< const ::hovercraft::Current_<ContainerAllocator> > : public TrueType {}; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::hovercraft::Current_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.current); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct Current_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::hovercraft::Current_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::hovercraft::Current_<ContainerAllocator> & v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "current: "; Printer<double>::stream(s, indent + " ", v.current); } }; } // namespace message_operations } // namespace ros #endif // HOVERCRAFT_MESSAGE_CURRENT_H
e3c11f495e32d6e9977b36d23bd0a0b7b6398227
6b90d0b5db269e09eb367ed7f69a923ebbf88f5a
/app/watch/src/watch.cpp
c392685cd7a2c86a1a5b2dfdc70dc47ddc62b2c7
[]
no_license
github188/HNCSJSNJ_C
6e5e3f5fe1440f2dfabda583950a8f51a6061ba5
4d4bd0d0e68f6d3f333809f6c4e2610fa1ee794d
refs/heads/master
2020-03-07T13:17:09.948911
2016-12-30T15:06:40
2016-12-30T15:06:40
null
0
0
null
null
null
null
GB18030
C++
false
false
13,360
cpp
#include <sys/wait.h> #include <unistd.h> #include <signal.h> #include <time.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include <getopt.h> #include <pthread.h> #include <ctype.h> #include <ftw.h> #include <syslog.h> #include <log.h> #include "SoftDog.hpp" #include "program_watch.hpp" #include "watchdog.hpp" #include "rtc.hpp" #include "version.hpp" #define MAX_FILE_NUM (100) #ifdef MEASURE_CALIBRATION void run_calibrate_program( ); bool IsCalibrateTrue( ); #endif void InitDaemon( void ); void initenv(); enum PROCESS_STATUS { NO_EXIST, RUNNING, SLEEPING, DISK_SLEEP, STOPPED, TRACING_STOP, ZOMBIE, DEAD, OTHER, }; /////////////////////////////////////////////////// // 循环喂看门狗 ////////////////////////////////////////////////////// void * LoopFeedWatchdog( void * ); void usage_print() { printf( "%s\n (%s)\n", version, MAKEDATE ); printf( "\nUsage: watchdog [OPTION]...\n" ); printf( "\nTo init other programs and fresh watchdog devices at intervals.\n" ); printf( "\nOptions:\n" ); printf( "\t-h --help Output this help string\n" ); printf( "\t-v --version Show version\n" ); printf( "\t-f --configfile filename Set program config file\n" ); } char * logfile = (char *)"/data1/watchdog.log"; ////////////////////////////////////////////////////////////////////// // 生成随机的复位时间, // 注意:由于终端(模块)集中在某一时刻复位、重新上线,会给移动网络和主站带来冲击,因此采用在某些时间段随机复位的方式实现。 // 通常在跨日时要做很多工作,必须避开,所以只允许从02:10:00 到 04:50:00这一段时间内复位 /////////////////////////////////////////////////////////////////////// inline int GetRebootSeconds() { float const BEGIN_SECONDS = 2 * 60 * 60 + 10 * 60; // 允许复位时间段起始时刻 2:10:00 float const END_SECONDS = 4 * 60 * 60 + 50 * 60; // 允许复位时间段结束时刻 4:50:00 return (int)( BEGIN_SECONDS + ( END_SECONDS - BEGIN_SECONDS ) * ( rand() / ( RAND_MAX + 1.0 ) )); } /////////////////////////////////////////////////////////// // 功能:根据输入的进程号获取该进程对应的进程状态 //////////////////////////////////////////////////////////// enum PROCESS_STATUS GetPidState( int pid ) { #define BUFLEN 64 #define LINUM 2 char buffer[BUFLEN], state[2] = { 0xff, 0xff }; FILE *proc_fs_p; int coln_count = 1, tmp = 0; if (snprintf(buffer, BUFLEN, "/proc/%d/status", pid) >= BUFLEN) { printf("buffer overflow detected\n"); return NO_EXIST; } proc_fs_p = fopen(buffer , "r"); if (!proc_fs_p) { printf("/proc open failed\n"); return NO_EXIST; } while ( fgets( buffer, BUFLEN, proc_fs_p ) != NULL ) { tmp++; if ( tmp != LINUM ) { continue; } for ( int i = 0; i < BUFLEN; i++ ) { if ( buffer[i] == ':' ) { coln_count--; } else if ( !coln_count && !isblank( buffer[i] ) ) { state[0] = buffer[i]; state[1] = buffer[i + 1]; break; } } break; } fclose( proc_fs_p ); switch ( state[0] ) { case 'R': return RUNNING; case 'W': return OTHER; case 'S': return SLEEPING; case 'T': return TRACING_STOP; case 'Z': return ZOMBIE; case 'D': return DISK_SLEEP; default: printf("unable to determine process state\n"); return OTHER; } return OTHER; // unreachable #undef BUFLEN #undef LINUM } ////////////////////////////////////////////////////////////////// // 功能: 当程序进入“D”状态(disk sleep)或“Z”状态(zombie)后,如果程序不能被杀死,则系统功能部分丧失 // 这时需要复位系统以保证系统功能正常。 // 注意:进程处于"D"或"Z"状态,很可能是由于现场环境干扰造成的,公司内部做EMC性能测试是,有一定概率出现, // 类似于死机现象,需要复位处理 // 判断程序能否杀死 /////////////////////////////////////////////////////////////////// void SaveSystem( int pid, char *name ) { #define MAX_TRIES 3 for ( int i = 0; i < MAX_TRIES; i ++ ) { char cmd[50]; sprintf( cmd, "/usr/bin/killall -9 %s", name ); system( cmd ); syslog( LOG_CONS|LOG_WARNING, "进程%s异常,软看门狗将其复位\n", name ); sleep( 1 ); if ( GetPidState( pid ) != DISK_SLEEP && GetPidState( pid ) != ZOMBIE ) { return; } } syslog( LOG_CONS|LOG_WARNING, "不能杀死进程,系统复位.\n" ); system( "/sbin/reboot" ); sleep( 20 ); system( "/usr/bin/killall -9 watchdog" ); #undef MAX_TRIES } int Watch(const char *file, const struct stat *sb, int flag) { struct process_t process = {0, 1, 0, ""}; if ( flag == FTW_F ) { FILE* fp = fopen(file, "rb"); if(fp==NULL) { return 0; } fread(&process, sizeof(process_t), 1, fp); fclose( fp ); struct sysinfo info ; if ( sysinfo( &info ) < 0 ) { return 0; } if ( process.up_time + process.dead_seconds < info.uptime ) { if( process.pid > 0 ) { if ( GetPidState( process.pid ) == DISK_SLEEP || GetPidState( process.pid ) == ZOMBIE ) { //syslog( LOG_CONS|LOG_WARNING, "进程%s异常,进程处于'D'状态.\n", process.name); SaveSystem( process.pid, process.name ); } else { kill(process.pid, SIGKILL); syslog( LOG_CONS|LOG_WARNING, "进程%s异常,软看门狗将其复位\n", process.name); } } remove(file); } } return 0; } int main( int argc, char *argv[], char *env[] ) { // time_t boottime; int next_option; const char * short_options = "hvf:"; const struct option long_options[] = { { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'v' }, { "configfile", 1, NULL, 'f' }, { NULL, 0, NULL, 0 }, }; char * configfile = NULL; for ( ;; ) { next_option = getopt_long( argc, argv,short_options, long_options, NULL ); if ( next_option == -1 ) { break; } switch( next_option ) { case 'h': usage_print(); exit( 1 ); break; case 'f': if ( optarg != NULL ) { configfile = optarg; } else { usage_print(); exit( -1 ); } break; case 'v': printf( "%s\n Compiled on %s.\n", version, MAKEDATE ); exit( 1 ); break; default: usage_print(); exit( 1 ); break; } } // for ( ;; ) // /* 判断程序启动参数是否正确 */ // if ( argc > 3) { // usage_print(); // return -1; // } // if ( argc == 2 ) { // if ( strcmp( "-v", argv[1] ) != 0 ) { // usage_print(); // return -1; // } // printf( "%s\n (%s) \n", version, MAKEDATE ); // return 0; // } // if ( argc == 3 ) { // if ( strcmp( "-f", argv[1] ) != 0 ) { // usage_print(); // return -1; // } // } //清空软看门狗工作目录 char command [sizeof( SOFT_WATCH_PATH ) + 10]; sprintf( command, "rm -rf %s", SOFT_WATCH_PATH ); system( command ); mkdir(SOFT_WATCH_PATH, S_IRWXU); class ProgramWatch progs; class RTClock rtc; progs.SetConfName( configfile ); // to mask the SIGTERM signal signal( SIGTERM, SIG_IGN ); progs.Init(); InitDaemon(); initenv(); pthread_t thread; if ( pthread_create( &thread, NULL, LoopFeedWatchdog, NULL ) != 0 ) { printf( "can not create thread\n" ); exit(-1); } int i; for( i = 0; i < 6; i ++ ) { if ( !rtc.SyncTime() ) { sleep(1); } else { break; } } if ( i == 3 ) { //Log2File( logfile, "can not sync rtc time!\n" ); } #ifdef MEASURE_CALIBRATION run_calibrate_program( ); #endif progs.Run(); //Log2File( logfile, "system boot succeeded!\n" ); // boottime = time( NULL ); int count = 0; bool isreboot = false; int reboot_seconds = 0; while( 1 ) { sleep(1); progs.Watch(); if ( progs.isreboot ) { // Log2File( logfile, "program crash, system must be reboot!\n" ); // to reboot system for( i = 0; i < 30; i ++ ) { sleep(1); } system( "/sbin/reboot" ); } if ( rebootinterval != 0 ) { if ( isreboot ) { if ( time( NULL ) % ( 24 * 60 * 60 ) > reboot_seconds ) { // to reboot system for( i = 0; i < 30; i ++ ) { sleep(1); } system( "/sbin/reboot" ); } } else { FILE *fp = fopen( "/proc/uptime", "r" ); if ( fp != NULL ) { double boottime; fscanf( fp, "%lf", &boottime ); if ( boottime > rebootinterval ) { // Log2File( logfile, "reboot time reached, system must be reboot!\n" ); reboot_seconds = GetRebootSeconds(); isreboot = true; } fclose( fp ); } } } count ++; if (count >= 60) { rtc.SyncTime(); count = 0; } } // at normal state never reach here return 0; } void InitDaemon (void) { struct sigaction act; int max_fd, i, ret; /*进行第1次fork,为setsid作准备 */ ret = fork (); if (ret < 0) { // Log2File( logfile, "InitDaemon() fork failed!" ); exit (1); } else if (ret != 0) exit (0); /*调用setsid,使得进程旧会话过程分离 */ // sleep( 600 ); ret = setsid (); if (ret < 0) { // Log2File( logfile, "InitDaemon() setsid failed!" ); exit (1); } /*忽略信号SIGHUP */ act.sa_handler = SIG_IGN; sigemptyset (&act.sa_mask); act.sa_flags = 0; sigaction (SIGHUP, &act, 0); /* *进行第2次fork,使进程不再是会话过程的领头进程,因而不能再打开 *终端作为自己的控制终端 */ ret = fork (); if (ret < 0) { // Log2File( logfile, "InitDaemon() fork failed!" ); exit (1); } else if (ret != 0) exit (0); /*修改进程的当前目录 */ chdir ("/"); /*清除进程的文件掩码 */ umask (0); /*使得进程脱离原来的进程组,不再受发往原来进程组的信号的干扰 */ setpgrp (); /*关闭进程所有的文件描述符 */ max_fd = sysconf (_SC_OPEN_MAX); for (i = 0; i < max_fd; i++) close (i); /*打开空设备,使得后续的输出语句不会出问题 */ if ((i = open("/dev/null", O_RDWR)) >= 0) { while (0 <= i && i <= 2) i = dup(i); if (i >= 0) close(i); } /* open ("/dev/null", O_RDWR); */ /* dup (1); */ /* dup (2); */ /*打开日志 */ //openlog(pathname, LOG_PID, facility); return; } void initenv() { setenv( "HOME", "/home/et1000", 1 ); setenv( "LD_LIBRARY_PATH", "/lib:/usr/lib:/home/et1000:/home/et1000/lib", 1 ); setenv( "locale", g_locale_str, 1 ); setenv( "cputype", g_cputype_str, 1 ); setenv( "cssupport", g_cs_str, 1 ); setenv( "area", g_area_str, 1 ); setenv( "baudrate", g_baudrate_str, 1 ); system( "mknod /dev/wfet1000clock c 254 0" ); chdir( "/home/et1000" ); } void * LoopFeedWatchdog( void * ) { printf( "in LoopFeedWatchdog()\n" ); class Watchdog watchdog; watchdog.Open(); watchdog.Feed(); watchdog.Feed(); watchdog.Feed(); int count = 0; while( true ) { printf( "in while() loop \n" ); if(count == 4) { count = 0; } if(count == 0) { //增加软件看门狗判断 ftw(SOFT_WATCH_PATH, Watch, MAX_FILE_NUM); } count++; watchdog.Feed(); usleep( 200000 ); } return NULL; } #ifdef MEASURE_CALIBRATION ///////////////////////////////////////////////////////////////////////////////////////// // for calibration requirement // if the writeable state of measure chip is true( 1 ), // calibration program must be launched, and nother program be launched; // else, just do as normal // 为了校表的需要, 当计量芯片参数存储器可写标志为"可写"时, 芯片参数设置程序必须启动, // 而且不能启动其它程序, // 当计量芯片参数不可写, 则正常启动程序 ///////////////////////////////////////////////////////////////////////////////////////// void run_calibrate_program( ) { if (IsCalibrateTrue( )) { int pid = fork(); if ( pid < 0 ) { perror( " fork() failed " ); exit( 1 ); } else if ( pid == 0 ) { execl( "/home/et1000/Calibrations1000F", "Calibrations1000F", (char *)NULL ); exit( 1 ); } while ( 1 ) { sleep ( 1 ); if (!IsCalibrateTrue( )){ system("killall -9 Calibrations1000F"); return; } } } } bool IsCalibrateTrue( ) { FILE * fp = fopen( "/proc/wfet/tdk6513_state", "r" ); if ( fp == NULL ) { return false; } char state[ 9 ] = { 0 }; fread( &state[ 0 ], sizeof( char ), 9, fp ); fclose( fp ); int i = atoi( state ); return ( i == 1 ); } #endif
4eae2eeae3e1a87efb9bf9b6540a1d5c5a8c33aa
e0915750c0683ae62b56a9cd2c28a62e0136aa3d
/include/iso/iso.cpp
262747b2703b227fdbca9e33501c5c20aa415943
[]
no_license
sealeks/nsdavinci
e2700b7329f8b23a0ab951a28e7c8da5cf6f69c6
a2bb626b96550aee95374e14b3c34f5f93faa4bf
refs/heads/master
2020-04-12T08:05:49.143881
2016-10-14T15:31:26
2016-10-14T15:31:26
41,061,947
0
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
// Copyright 2013 Alexeev Sergey [email protected] // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #include <iso/iso.h> namespace boost { namespace itu { error_code errorcode_by_reason(octet_type val) { switch (val) { case DR_REASON_CONGST: return ER_EAGAIN; case DR_REASON_ADDRESS: return ER_NAADDRESS; case DR_REASON_NORM: return ER_RELEASE; case DR_REASON_RCNGS: return ER_REQBUSY; case DR_REASON_NEGOT: return ER_REQBUSY; default: { } } return ER_PROTOCOL; } } }
991ef676ea8a4292c90c83ea7766978bb4730d28
787b7f8a01876e15637dd6ae9b47bfb2b1fd024f
/src/WorldObject/Effect/EffectFlashBack.cpp
50a673839d84ae2c4e05cb36714b271642ca9ac3
[]
no_license
flat0531/Monta3D
896428837d453b3b6a2c3f27237b0ac3f9b32d3e
11d9995901f3c040e57389cbde7923439b1bf6d0
refs/heads/master
2020-12-30T14:19:56.170855
2017-08-19T03:10:35
2017-08-19T03:10:35
91,307,641
1
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
#include "EffectFlashBack.h" #include"../../Top/DrawManager.h" #include"../../Top/EasingManager.h" #include"../../Top/Top.h" #include"../../Top/TextureManager.h" #include"../../Top/SoundManager.h" #include"../../Top/DataManager.h" using namespace ci; using namespace ci::app; EffectFlashBack::EffectFlashBack() { } EffectFlashBack::EffectFlashBack(const float _time, const ci::ColorA _color) { t = 0.0f; time = _time; color = ColorA(_color.r, _color.g, _color.b, 0.0f); } void EffectFlashBack::update() { EasingManager::tCount(t, time); color.a = EasingReturn(t, 0.f, 1.f); } void EffectFlashBack::draw(const ci::CameraPersp camera) { DrawM.drawBoxEdge(Vec2f(0, 0), Vec2f(WINDOW_WIDTH, WINDOW_HEIGHT), color); } bool EffectFlashBack::deleteThis() { return EasingManager::tCountEnd(t); }
b9d3063ee2c145ae8eb4a662025adea2f96dfc3a
06ada07a3f9e55e72f9c2c655febd142f759c1a7
/main.cpp
c2766660d600df9514145f3fecff2eaa1745b679
[]
no_license
poi2002/QtModbus
a1524df61a06cf2392fc022fa5915106f6e6dd6b
dab9bc3349015309f10cbd18b2f011eb61ba2999
refs/heads/master
2020-05-06T20:29:15.087047
2015-01-01T13:18:53
2015-01-01T13:18:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
168
cpp
#include "qtmodbus.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QtModbus w; w.show(); return a.exec(); }
287d94c48df7092ad50c69f7292bd4dc405595c8
1f9dbb5f9ebc89312496024575de9a203064dd64
/Source/Engine/System/Messagebox.h
dd03a3a4e504bb66f656367dbd9b834cfa6f18e2
[ "MIT" ]
permissive
ricmzn/SomeGame
b0a11c414671e667a4139321f46754783e9aa432
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
refs/heads/master
2021-05-28T22:20:27.416733
2015-05-21T02:59:35
2015-05-21T02:59:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
600
h
#ifndef MESSAGEBOX_H #define MESSAGEBOX_H #include <Engine/System/Macros.h> namespace System { class api_public Messagebox { private: Messagebox(); public: enum class Option { Cancel, Ok, Yes = Ok, No = Cancel }; static Option Error (const char* title, const char* message); static Option Warning (const char* title, const char* message); static Option YesNo (const char* title, const char* message); }; } #endif // MESSAGEBOX_H
6888781c2a2b06485b7a886f17ac003427039609
aca40624f9e03e37766ec5649406c4be28e01246
/Camera.cpp
700bc0eab3704428c24bf75dac141f1cff9bd0a8
[]
no_license
jrjg/CounterEngine
48f95c732fb2b115d409e9ce40d83c6cb5540017
c758d79146fd6bb62c583f2d7156df05930790f4
refs/heads/master
2020-04-15T20:14:39.740603
2016-10-25T11:01:52
2016-10-25T11:01:52
68,045,624
0
0
null
null
null
null
UTF-8
C++
false
false
5,393
cpp
//#include "TopInclude.h" //#include "Engine.h" //#include "ProcessManager.h" //#include "EventManager.h" //#include "windowmgr.h" //#include "Memory.h" // // //#include "Camera.h" // // // //HRESULT Camera_Reset(Camera * pCamera) //{ // pCamera->pitch = 0.0f; // pCamera->yaw = 0.0f; // pCamera->moveBackForward = 0.0f; // pCamera->moveLeftRight = 0.0f; // pCamera->Forward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f); // pCamera->Right = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f); // pCamera->DefaultForward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f); // pCamera->DefaultRight = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f); // pCamera->Target = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); // pCamera->Position = XMVectorSet(0.0f, 1.3f, -4.0f, 0.0f); // pCamera->Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); // pCamera->Projection = XMMatrixPerspectiveFovLH(0.4f*3.14f, Engine_BUFFERWIDTH() / Engine_BUFFERHEIGHT(), 1.0f, 1000.0f); // pCamera->CursorLastPos.x = -1.0f; // pCamera->CursorLastPos.y = -1.0f; // pCamera->mr = false; // pCamera->ml = false; // pCamera->mf = false; // pCamera->mb = false; // CE1_CALL(Camera_Run(NULL)); // return S_OK; //} // //XMMATRIX* Camera_GetCamView(Camera* pCamera) { // return &pCamera->View; //} // //XMMATRIX* Camera_GetCamProjection(Camera* pCamera) { // return &pCamera->Projection; //} // //XMMATRIX* Camera_GetViewTimesProjection(Camera* pCamera) { // return &pCamera->ViewTimesProjection; //} // //HRESULT Camera_CalcViewTimesProjection(Camera* pCamera) { // pCamera->ViewTimesProjection = pCamera->View * pCamera->Projection; // return S_OK; //} // //HRESULT Camera_CalcView(Camera* pCamera,TIME elapsed) { // pCamera->RotationMatrix = XMMatrixRotationRollPitchYaw(pCamera->pitch, pCamera->yaw, 0); // pCamera->Target = XMVector3TransformCoord(pCamera->DefaultForward, pCamera->RotationMatrix); // pCamera->Target = XMVector3Normalize(pCamera->Target); // // XMMATRIX RotateYTempMatrix; // RotateYTempMatrix = XMMatrixRotationY(pCamera->yaw); // // pCamera->Right = XMVector3TransformCoord(pCamera->DefaultRight, RotateYTempMatrix); // pCamera->Up = XMVector3TransformCoord(pCamera->Up, RotateYTempMatrix); // pCamera->Forward = XMVector3TransformCoord(pCamera->DefaultForward, RotateYTempMatrix); // // pCamera->Position += pCamera->moveLeftRight * (pCamera->Right); // pCamera->Position += pCamera->moveBackForward * (pCamera->Forward); // // pCamera->Target = pCamera->Position + pCamera->Target; // pCamera->View = XMMatrixLookAtLH(pCamera->Position, pCamera->Target, pCamera->Up); // return S_OK; //} // // //HRESULT Camera_Run(TIME elapsed) //{ // Camera* pCamera = Engine_GetCamera(); // POINT p; // // GetCursorPos(&p); // pCamera->yaw += (p.x - pCamera->CursorLastPos.x) * 0.001f; // pCamera->pitch += (p.y - pCamera->CursorLastPos.y) * 0.001f; // pCamera->CursorLastPos.x = Engine_BUFFERWIDTH() / 2; // pCamera->CursorLastPos.y = Engine_BUFFERHEIGHT() / 2; // SetCursorPos(pCamera->CursorLastPos.x, pCamera->CursorLastPos.y); // // CE1_CALL(Camera_CalcView(pCamera, elapsed)); // CE1_CALL(Camera_CalcViewTimesProjection(pCamera)); // return S_OK; //} // //HRESULT Camera_MoveLeft(void* pDown) { // Camera* pCamera = Engine_GetCamera(); // if (*(bool*)pDown) { // pCamera->moveLeftRight = -0.02f; // pCamera->ml = true; // } // else { // pCamera->ml = false; // if (!pCamera->mr) { // pCamera->moveLeftRight = 0.0f; // } // else { // pCamera->moveLeftRight = 0.02f; // } // } // return S_OK; //} // //HRESULT Camera_MoveRight(void* pDown) { // Camera* pCamera = Engine_GetCamera(); // if (*(bool*)pDown) { // pCamera->moveLeftRight = 0.02f; // pCamera->mr = true; // } // else { // pCamera->mr = false; // if (!pCamera->ml) { // pCamera->moveLeftRight = 0.0f; // } // else { // pCamera->moveLeftRight = -0.02f; // } // } // return S_OK; //} // //HRESULT Camera_MoveBack(void* pDown) { // Camera* pCamera = Engine_GetCamera(); // if (*(bool*)pDown) { // pCamera->moveBackForward = -0.02f; // pCamera->mb = true; // } // else { // pCamera->mb = false; // if (!pCamera->mf) { // pCamera->moveBackForward = 0.0f; // } // else { // pCamera->moveBackForward = 0.02f; // } // } // return S_OK; //} // //HRESULT Camera_MoveForward(void* pDown) { // Camera* pCamera = Engine_GetCamera(); // if (*(bool*)pDown) { // pCamera->moveBackForward = 0.02f; // pCamera->mf = true; // } // else { // pCamera->mf = false; // if (!pCamera->mb) { // pCamera->moveBackForward = 0.0f; // } // else { // pCamera->moveBackForward = -0.02f; // } // } // return S_OK; //} // //HRESULT Camera_New(Camera** ppCamera) //{ // _NEW(Camera, *ppCamera); // EventManager_RegisterForEvent(EVENT_START, &Camera_Startup); // EventManager_RegisterForEvent(EVENT_END, &Camera_ShutdownAndDelete); // return S_OK; //} // //HRESULT Camera_Startup(void* p0) { // Camera* pCamera = Engine_GetCamera(); // ProcessManager_NewProcess(&Camera_Run, (1000.0f) / (100.0f)); // // EventManager_RegisterForEvent(EVENT_MOVELEFT, &Camera_MoveLeft); // EventManager_RegisterForEvent(EVENT_MOVERIGHT, &Camera_MoveRight); // EventManager_RegisterForEvent(EVENT_MOVEBACK, &Camera_MoveBack); // EventManager_RegisterForEvent(EVENT_MOVEFORWARD, &Camera_MoveForward); // CE1_CALL(Camera_Reset(pCamera)); // return S_OK; //} // //HRESULT Camera_ShutdownAndDelete(void* p0) //{ // Camera* pCamera = Engine_GetCamera(); // if (!pCamera) { return S_OK; } // CE1_DEL(pCamera); // return S_OK; //}
70cc975fcde3262640a7d0a66d04eb7c467a9232
268fdb6b0d39d404124274be1519599bea3b329a
/BattleTank/Source/BattleTank/TankPlayerController.h
58f712242117c3aa7dfaf8249760def857620157
[]
no_license
araujojr82/BattleTank
7c537f44688ca7bbf2b629798b7f901cf8e51cc4
aba17de2463d9d43a0ef1a0f4eead7fa6fde7fbe
refs/heads/master
2021-10-28T03:54:07.660246
2019-04-21T19:24:45
2019-04-21T19:24:45
156,631,146
0
0
null
null
null
null
UTF-8
C++
false
false
1,327
h
// Copyright Euclides Araujo 2018 #pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "TankPlayerController.generated.h" // Must be the last include class UTankAimingComponent; /** * Responsible for helping the player aim. */ UCLASS() class BATTLETANK_API ATankPlayerController : public APlayerController { GENERATED_BODY() public: virtual void BeginPlay() override; virtual void Tick( float DeltaTime ) override; protected: UFUNCTION( BlueprintImplementableEvent, Category = "Setup" ) void FoundAimingComponent( UTankAimingComponent* AimCompRef ); private: virtual void SetPawn( APawn* InPawn ) override; UFUNCTION() void OnTankDeath(); // Start the tank moving the barrel so that the shot would hit where // the crosshair intersects the world void AimTowardsCrosshair(); // Return an OUT parameter, true if hit landscape bool GetSightRayHitLocation( FVector& OutHitLocation ) const; bool GetLookDirection( FVector2D ScreenLocation, FVector& OutHitLocation ) const; bool GetLookVectorHitLocation( FVector LookDirection, FVector& HitLocation ) const; UPROPERTY( EditDefaultsOnly ) float CrossHairXLocation = 0.5; UPROPERTY( EditDefaultsOnly ) float CrossHairYLocation = 0.3333; UPROPERTY( EditDefaultsOnly ) float LineTraceRange = 1000000.0f; };
3918fdd4d38f4eaa053260ad290ffb7407ed2945
346678ce0c5f01a49390057dbcb001d585c06541
/src/common/primitive_iterator.cpp
9edfa3f6ce1b2f1e811a29a37678b02289d91352
[ "Apache-2.0", "Intel" ]
permissive
wuhuikx/mkl-dnn-bk
16e9c394d553c5b09f4e73fb7dcb36be03b3f98c
5481ef7e869d7e80e16c84a665d9a311fce6ed02
refs/heads/master
2021-04-30T01:56:34.708046
2018-03-15T04:57:01
2018-03-15T04:57:01
121,357,885
0
0
null
null
null
null
UTF-8
C++
false
false
5,542
cpp
/******************************************************************************* * Copyright 2016-2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <assert.h> #include "mkldnn.h" #include "c_types_map.hpp" #include "engine.hpp" #include "primitive_desc.hpp" #include "type_helpers.hpp" using namespace mkldnn::impl; using namespace mkldnn::impl::status; struct mkldnn_primitive_desc_iterator: public c_compatible { using pd_create_f = engine_t::primitive_desc_create_f; mkldnn_primitive_desc_iterator(engine_t *engine, const op_desc_t *op_desc, const primitive_attr_t *attr, const primitive_desc_t *hint_fwd_pd) : idx_(-1), engine_(engine), pd_(nullptr), op_desc_(op_desc) , attr_(attr ? *attr : primitive_attr_t()), hint_fwd_pd_(hint_fwd_pd) , impl_list_(engine_->get_implementation_list()), last_idx_(0) { while (impl_list_[last_idx_] != nullptr) ++last_idx_; } ~mkldnn_primitive_desc_iterator() { if (pd_) delete pd_; } bool operator==(const primitive_desc_iterator_t& rhs) const { return idx_ == rhs.idx_ && engine_ == rhs.engine_; } bool operator!=(const primitive_desc_iterator_t& rhs) const { return !operator==(rhs); } primitive_desc_iterator_t end() const { return mkldnn_primitive_desc_iterator(engine_, last_idx_); } primitive_desc_iterator_t &operator++() { if (pd_) { delete pd_; pd_ = nullptr; } while (++idx_ != last_idx_) { auto s = impl_list_[idx_](&pd_, op_desc_, &attr_, engine_, hint_fwd_pd_); if (s == success) { printf("idx = %d\n", idx_); break; } } return *this; } primitive_desc_t *operator*() const { if (*this == end() || pd_ == nullptr) return nullptr; return pd_->clone(); } protected: int idx_; engine_t *engine_; primitive_desc_t *pd_; const op_desc_t *op_desc_; const primitive_attr_t attr_; const primitive_desc_t *hint_fwd_pd_; const pd_create_f *impl_list_; int last_idx_; private: mkldnn_primitive_desc_iterator(engine_t *engine, int last_idx) : idx_(last_idx), engine_(engine), pd_(nullptr) , op_desc_(nullptr), hint_fwd_pd_(nullptr) , impl_list_(nullptr), last_idx_(last_idx) {} }; status_t mkldnn_primitive_desc_iterator_create_v2( primitive_desc_iterator_t **iterator, const_c_op_desc_t c_op_desc, const primitive_attr_t *attr, engine_t *engine, const primitive_desc_t *hint_fwd_pd) { const op_desc_t *op_desc = (const op_desc_t *)c_op_desc; auto it = new primitive_desc_iterator_t(engine, op_desc, attr, hint_fwd_pd); if (it == nullptr) return out_of_memory; ++(*it); if (*it == it->end()) { delete it; return unimplemented; } *iterator = it; return success; } status_t mkldnn_primitive_desc_iterator_create( primitive_desc_iterator_t **iterator, const_c_op_desc_t c_op_desc, engine_t *engine, const primitive_desc_t *hint_fwd_pd) { return mkldnn_primitive_desc_iterator_create_v2(iterator, c_op_desc, nullptr, engine, hint_fwd_pd); } status_t mkldnn_primitive_desc_iterator_next( primitive_desc_iterator_t *iterator) { if (iterator == nullptr) return invalid_arguments; ++(*iterator); return *iterator == iterator->end() ? iterator_ends : success; } primitive_desc_t *mkldnn_primitive_desc_iterator_fetch( const primitive_desc_iterator_t *iterator) { if (iterator == nullptr) return nullptr; return *(*iterator); } status_t mkldnn_primitive_desc_clone(primitive_desc_t **primitive_desc, const primitive_desc_t *existing_primitive_desc) { if (utils::any_null(primitive_desc, existing_primitive_desc)) return invalid_arguments; return safe_ptr_assign<primitive_desc_t>(*primitive_desc, existing_primitive_desc->clone()); } status_t mkldnn_primitive_desc_iterator_destroy( primitive_desc_iterator_t *iterator) { if (iterator != nullptr) delete iterator; return success; } status_t mkldnn_primitive_desc_create_v2(primitive_desc_t **primitive_desc, const_c_op_desc_t c_op_desc, const primitive_attr_t *attr, engine_t *engine, const primitive_desc_t *hint_fwd_pd) { const op_desc_t *op_desc = (const op_desc_t *)c_op_desc; mkldnn_primitive_desc_iterator it(engine, op_desc, attr, hint_fwd_pd); ++it; if (it == it.end()) return unimplemented; return safe_ptr_assign<primitive_desc_t>(*primitive_desc, *it); } status_t mkldnn_primitive_desc_create(primitive_desc_t **primitive_desc, const_c_op_desc_t c_op_desc, engine_t *engine, const primitive_desc_t *hint_fwd_pd) { return mkldnn_primitive_desc_create_v2(primitive_desc, c_op_desc, nullptr, engine, hint_fwd_pd); } // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
77ba9809675c81ee8cfed5df126095663832a64a
f894022957903fb378efae6fae2067bf7c65f828
/baekjoonOnlineJudge/2822/main.cpp
a941669fa168183fa031d0e59e220d082946189e
[ "Apache-2.0" ]
permissive
sdkcoding/baekjoonOnlineJudge
e9f372f314fbadeb02aa2cf6c21d476f3ed8ebc7
ec381847517613475f41157638083b13a75ab9d6
refs/heads/master
2022-11-13T05:57:52.139002
2022-11-06T01:26:17
2022-11-06T01:26:17
177,353,208
0
0
null
null
null
null
UTF-8
C++
false
false
872
cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; class Number { public : int element; int index; Number(int element, int index):element(element),index(index){} }; bool compare1(Number num1, Number num2) { return num1.element < num2.element; } bool compare2(Number num1, Number num2) { return num1.index < num2.index; } int main() { cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false); vector<Number> v; int num; for (int i = 0; i < 8; i++) { cin >> num; v.push_back(Number(num, i + 1)); } sort(v.begin(), v.end(), compare1); int sum = 0; for (int i = 3; i < 8; i++) { sum += v[i].element; } cout << sum << '\n'; int min = v[2].element; sort(v.begin(), v.end(), compare2); for (int i = 0; i < 8; i++) { if (min < v[i].element) { cout << v[i].index << " "; } } cout << '\n'; return 0; }
75c8cbaa99d8b35c6f2aef22d9a95f8cdc414d6a
1f322e4ed509aeefdac7bbe089b526c04f9c583d
/Homestrife/physicsobject.cpp
d19ba6ea564f31142e1334ce9b033a8ef06e5b6e
[]
no_license
Honeybunch/HomestrifeMac
5dc85e79047903f93a6039f4090903575c9a2f42
fdbb1be01d50277869664f9b6e81b3bd87fbdb98
refs/heads/master
2021-01-10T20:07:14.883691
2013-09-26T15:17:33
2013-09-26T15:17:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,457
cpp
#include "physicsobject.h" float gravity = 4; ///////////////////// //PhysicsObjectHold// ///////////////////// PhysicsObjectHold::PhysicsObjectHold() : TerrainObjectHold() { changePhysicsAttributes = false; ignoreGravity = false; } PhysicsObjectHold::~PhysicsObjectHold() { } bool PhysicsObjectHold::IsPhysicsObjectHold() { return true; } ///////////////// //PhysicsObject// ///////////////// PhysicsObject::PhysicsObject() : TerrainObject() { health = 0; curHealth = 0; mass = 0; falls = true; ignoreGravity = false; maxFallSpeed = 100; ignoreJumpThroughTerrain = false; takesTerrainDamage = false; blockability = MID; horizontalDirectionBasedBlock = false; reversedHorizontalBlock = false; damage = 0; hitstun = 0; blockstun = 0; force.x = 0; force.y = 0; trips = false; } PhysicsObject::~PhysicsObject() { } int PhysicsObject::Event(InputStates * inputHistory, int frame) { return 0; } int PhysicsObject::Update() { if(int error = TerrainObject::Update() != 0) { return error; } //there was an error in the base update //apply gravity if(falls && !ignoreGravity) { vel.y += gravity; if(vel.y > maxFallSpeed) { vel.y = maxFallSpeed; } } return 0; } bool PhysicsObject::AdvanceHold(HSObjectHold * hold) { if(TerrainObject::AdvanceHold(hold)) { PhysicsObjectHold * phHold = (PhysicsObjectHold*)curHold; if(phHold->changePhysicsAttributes) { ignoreGravity = phHold->ignoreGravity; } return true; } return false; } bool PhysicsObject::ChangeHold(HSObjectHold * hold) { ignoreGravity = false; return TerrainObject::ChangeHold(hold); } HSObjectHold * PhysicsObject::GetDefaultHold() { ignoreGravity = false; return TerrainObject::GetDefaultHold(); } HSVect2D PhysicsObject::GetLeftHypotenusePoint(HSVect2D * boxPos, HSBox * box) { HSVect2D point; point.x = 0; point.y = 0; if(boxPos == NULL || box == NULL) { return point; } //no position or box given point.x = boxPos->x + box->offset.x; point.y = boxPos->y + box->offset.y; if((!box->rightAlign && !box->bottomAlign) || (box->rightAlign && box->bottomAlign)) { point.y += box->height; } return point; } HSVect2D PhysicsObject::GetRightHypotenusePoint(HSVect2D * boxPos, HSBox * box) { HSVect2D point; point.x = 0; point.y = 0; if(boxPos == NULL || box == NULL) { return point; } //no position or box given point.x = boxPos->x + box->offset.x + box->width; point.y = boxPos->y + box->offset.y; if((!box->rightAlign && box->bottomAlign) || (box->rightAlign && !box->bottomAlign)) { point.y += box->height; } return point; } HSVect2D PhysicsObject::GetRightAnglePoint(HSVect2D * boxPos, HSBox * box) { HSVect2D point; point.x = 0; point.y = 0; if(boxPos == NULL || box == NULL) { return point; } //no position or box given point.x = boxPos->x + box->offset.x; if(box->rightAlign) { point.x += box->width; } point.y = boxPos->y + box->offset.y; if(box->bottomAlign) { point.y += box->height; } return point; } HSVect2D PhysicsObject::GetIntersectionPoint(HSVect2D * lineOnePointA, HSVect2D * lineOnePointB, HSVect2D * lineTwoPointA, HSVect2D * lineTwoPointB) { HSVect2D intersectionPoint = *lineOnePointA; if(lineOnePointA == NULL || lineOnePointB == NULL || lineTwoPointA == NULL || lineTwoPointB == NULL) { return intersectionPoint; } float uDenom = ((lineTwoPointB->y - lineTwoPointA->y) * (lineOnePointB->x - lineOnePointA->x)) - ((lineTwoPointB->x - lineTwoPointA->x) * (lineOnePointB->y - lineOnePointA->y)); if(uDenom == 0) { return intersectionPoint; } //lines are parallel float uA = (((lineTwoPointB->x - lineTwoPointA->x) * (lineOnePointA->y - lineTwoPointA->y)) - ((lineTwoPointB->y - lineTwoPointA->y) * (lineOnePointA->x - lineTwoPointA->x))) / uDenom; //float uB = (((lineOnePointB->x - lineOnePointA->x) * (lineOnePointA->y - lineTwoPointA->y)) - ((lineOnePointB->y - lineOnePointA->y) * (lineOnePointA->x - lineTwoPointA->x))) / uDenom; intersectionPoint.x = lineOnePointA->x + uA * (lineOnePointB->x - lineOnePointA->x); intersectionPoint.y = lineOnePointA->y + uA * (lineOnePointB->y - lineOnePointA->y); return intersectionPoint; } float PhysicsObject::IntervalDifference(float * minA, float * maxA, float * minB, float * maxB) { if(minA == NULL || minB == NULL || maxA == NULL || maxB == NULL) { return 0; } if (*minA < *minB) { return *minB - *maxA; } else { return *minA - *maxB; } } void PhysicsObject::ProjectLineSegmentAgainstLine(HSVect2D * pointA, HSVect2D * pointB, HSVect2D * targetLine, float * min, float * max) { if(pointA == NULL || pointB == NULL || targetLine == NULL || min == NULL || max == NULL) { return; } //get the dot product of the line and the first point float dotProd = (targetLine->x * pointA->x) + (targetLine->y * pointA->y); *min = dotProd; *max = dotProd; //do the same with the second point dotProd = (targetLine->x * pointB->x) + (targetLine->y * pointB->y); if(dotProd < *min) { *min = dotProd; } if(dotProd > *max) { *max = dotProd; } } void PhysicsObject::ProjectBoxAgainstLine(HSVect2D * boxPos, HSBox * box, HSVect2D * targetLine, float * min, float * max) { if(boxPos == NULL || box == NULL || targetLine == NULL || min == NULL || max == NULL) { return; } if(box->isTriangle) { //get the three points HSVect2D rightAng, leftHyp, rightHyp; rightAng = GetRightAnglePoint(boxPos, box); leftHyp = GetLeftHypotenusePoint(boxPos, box); rightHyp = GetRightHypotenusePoint(boxPos, box); //get the dot product of the line and the first point float dotProd = (targetLine->x * rightAng.x) + (targetLine->y * rightAng.y); *min = dotProd; *max = dotProd; //do the same with the second point dotProd = (targetLine->x * leftHyp.x) + (targetLine->y * leftHyp.y); if(dotProd < *min) { *min = dotProd; } if(dotProd > *max) { *max = dotProd; } //do the same with the third point dotProd = (targetLine->x * rightHyp.x) + (targetLine->y * rightHyp.y); if(dotProd < *min) { *min = dotProd; } if(dotProd > *max) { *max = dotProd; } } else { //get the four points HSVect2D pointA, pointB, pointC, pointD; pointA.x = pos.x + box->offset.x; pointA.y = pos.y + box->offset.y; pointB.x = pointA.x + box->width; pointB.y = pointA.y; pointC.x = pointA.x; pointC.y = pointA.y + box->height; pointD.x = pointB.x; pointD.y = pointC.y; //get the dot product of the line and the first point float dotProd = (targetLine->x * pointA.x) + (targetLine->y * pointA.y); *min = dotProd; *max = dotProd; //do the same with the second point dotProd = (targetLine->x * pointB.x) + (targetLine->y * pointB.y); if(dotProd < *min) { *min = dotProd; } if(dotProd > *max) { *max = dotProd; } //do the same with the third point dotProd = (targetLine->x * pointC.x) + (targetLine->y * pointB.y); if(dotProd < *min) { *min = dotProd; } if(dotProd > *max) { *max = dotProd; } //do the same with the fourth point dotProd = (targetLine->x * pointD.x) + (targetLine->y * pointB.y); if(dotProd < *min) { *min = dotProd; } if(dotProd > *max) { *max = dotProd; } } } TerrainCollisionResult PhysicsObject::IsBoxCollidingWithHypotenuse(HSVect2D * ownPos, HSBox * ownBox, TerrainObject * targetObject, HSBox * targetBox, bool movingAway) { TerrainCollisionResult result; result.lastSelfBox = NULL; result.lastTargetBox = NULL; result.lastTargetObject = NULL; result.horizontalImpact = false; result.verticalImpact = false; if(ownPos == NULL || ownBox == NULL || targetObject == NULL || targetBox == NULL) { return result; } //get own box's point that is threatening to collide with the hypotenuse, at both current and previous position HSVect2D ownBoxPoint; HSVect2D ownBoxPrevPoint; HSVect2D ownBoxFurthestPoint; ownBoxPoint.x = ownPos->x + ownBox->offset.x; ownBoxPrevPoint.x = prevPos.x + ownBox->offset.x; ownBoxFurthestPoint.x = pos.x + ownBox->offset.x; if(targetBox->rightAlign) { ownBoxPoint.x += ownBox->width; ownBoxPrevPoint.x += ownBox->width; ownBoxFurthestPoint.x += ownBox->width; } ownBoxPoint.y = ownPos->y + ownBox->offset.y; ownBoxPrevPoint.y = prevPos.y + ownBox->offset.y; ownBoxFurthestPoint.y = pos.y + ownBox->offset.y; if(targetBox->bottomAlign) { ownBoxPoint.y += ownBox->height; ownBoxPrevPoint.y += ownBox->height; ownBoxFurthestPoint.y += ownBox->height; } //get the target box's hypotenuse points HSVect2D leftHyp = GetLeftHypotenusePoint(&(targetObject->pos), targetBox); HSVect2D rightHyp = GetRightHypotenusePoint(&(targetObject->pos), targetBox); ////compare ownBoxPoint to the collision point //float distSqrd = pow(ownBoxPoint.x - collisionPoint.x , 2) + pow(ownBoxPoint.y - collisionPoint.y, 2); //if(distSqrd < pow(MIN_VEL, 2)) { ownBoxPoint = collisionPoint; } //they're practically the same, so make them the same ////compare ownBoxPrevPoint to the collision point //distSqrd = pow(ownBoxPrevPoint.x - collisionPoint.x , 2) + pow(ownBoxPrevPoint.y - collisionPoint.y, 2); //if(distSqrd < pow(MIN_VEL, 2)) { ownBoxPrevPoint = collisionPoint; } //they're practically the same, so make them the same if(movingAway) { float curPointDist; float prevPointDist; curPointDist = ((rightHyp.x - leftHyp.x) * (ownBoxPoint.y - leftHyp.y)) - ((rightHyp.y - leftHyp.y) * (ownBoxPoint.x - leftHyp.x)); prevPointDist = ((rightHyp.x - leftHyp.x) * (ownBoxPrevPoint.y - leftHyp.y)) - ((rightHyp.y - leftHyp.y) * (ownBoxPrevPoint.x - leftHyp.x)); //if a point is very close to the line, just treat it like it's on top of it if(curPointDist < MIN_VEL) { curPointDist = 0; } if(prevPointDist < MIN_VEL) { prevPointDist = 0; } if((targetBox->bottomAlign && (curPointDist > 0 || prevPointDist > 0)) || (!targetBox->bottomAlign && (curPointDist < 0 || prevPointDist < 0))) { //this counts as a collision result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; result.horizontalImpact = true; result.verticalImpact = true; return result; } } else { //get the collision point HSVect2D collisionPoint = GetIntersectionPoint(&ownBoxFurthestPoint, &ownBoxPrevPoint, &leftHyp, &rightHyp); if(collisionPoint.x == ownBoxPoint.x && collisionPoint.y == ownBoxPoint.y) { //collision happened right at an own box point //this doesn't count as a collision return result; } //float curPointDist = ((rightHyp.x - leftHyp.x) * (ownBoxPoint.y - leftHyp.y)) - ((rightHyp.y - leftHyp.y) * (ownBoxPoint.x - leftHyp.x)); if(//((targetBox->bottomAlign && curPointDist > 0) || (!targetBox->bottomAlign && curPointDist < 0)) && (((ownBoxPoint.x <= ownBoxPrevPoint.x && collisionPoint.x >= ownBoxPoint.x && collisionPoint.x <= ownBoxPrevPoint.x) || (ownBoxPoint.x >= ownBoxPrevPoint.x && collisionPoint.x <= ownBoxPoint.x && collisionPoint.x >= ownBoxPrevPoint.x)) && ((ownBoxPoint.y <= ownBoxPrevPoint.y && collisionPoint.y >= ownBoxPoint.y && collisionPoint.y <= ownBoxPrevPoint.y) || (ownBoxPoint.y >= ownBoxPrevPoint.y && collisionPoint.y <= ownBoxPoint.y && collisionPoint.y >= ownBoxPrevPoint.y)))) { //collision point lies somewhere on the line described by own box's two points result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; result.horizontalImpact = true; result.verticalImpact = true; result.hypCollisionPoint = collisionPoint; return result; } } //no valid intersection return result; } TerrainCollisionResult PhysicsObject::AreTerrainBoxesColliding(HSBox * ownBox, TerrainObject * targetObject, HSBox * targetBox, TerrainCollisionResult * prevResult, HSVect2D * ownPos, HSVect2D * ownPrevPos, bool ignoreCurrentlyOverlapping) { TerrainCollisionResult result; result.lastSelfBox = NULL; result.lastTargetBox = NULL; result.lastTargetObject = NULL; result.horizontalImpact = false; result.verticalImpact = false; if(ownBox == NULL || targetBox == NULL || targetBox == NULL) { return result; } //a position or box is not given if(targetObject->canBeJumpedThrough && ignoreJumpThroughTerrain) { //this is jump-through terrain, and this object is currently ignoring it. ignore it return result; } if(prevResult != NULL && ownBox == prevResult->lastSelfBox && targetBox == prevResult->lastTargetBox) { //this collision has already been handled. Skip it } if(ownPos == NULL) { ownPos = &pos; } if(ownPrevPos == NULL) { ownPrevPos = &prevPos; } //get own box's change in position HSVect2D posChange; posChange.x = ownPos->x - ownPrevPos->x; posChange.y = ownPos->y - ownPrevPos->y; //no change in position, so don't even bother /*if(posChange.x == 0 && posChange.y == 0) { return result; }*/ //check if own box at the starting position is overlapping the target box. if so, ignore this collision. //this is mostly for jump-through platforms, but also makes for an "easy out" in the event that another object //gets stuck in terrain somehow. if(ignoreCurrentlyOverlapping && AreRectanglesColliding(&prevPos, ownBox, &(targetObject->pos), targetBox)) { return result; } //get the total bounding box of both positions HSBox totalBox; //get its width and height totalBox.width = ownBox->width + abs(posChange.x); totalBox.height = ownBox->height + abs(posChange.y); //get its offset in relation to the current position if(posChange.x < 0) { totalBox.offset.x = ownBox->offset.x; } else { totalBox.offset.x = ownBox->offset.x - abs(posChange.x); } if(posChange.y < 0) { totalBox.offset.y = ownBox->offset.y; } else { totalBox.offset.y = ownBox->offset.y - abs(posChange.y); } //see if the target box's rectangle falls anywhere in the total bounding box if(!AreRectanglesColliding(ownPos, &totalBox, &(targetObject->pos), targetBox)) { //the target box definitely isn't colliding with the total box at any point return result; } //target box falls within the total bounding box if(posChange.x == 0 || posChange.y == 0) { //ownBox only moved on one axis, so there was a collision between rectangles at some point. if(posChange.x != 0) { //if the box can be jumped through then horizontal collisions don't count if(targetObject->canBeJumpedThrough) { return result; } if(!targetBox->isTriangle || (posChange.x < 0 && targetBox->rightAlign) || (posChange.x > 0 && !targetBox->rightAlign) || (targetBox->bottomAlign && ownPos->y + ownBox->offset.y + ownBox->height > targetObject->pos.y + targetBox->offset.y + targetBox->height) || (!targetBox->bottomAlign && ownPos->y + ownBox->offset.y < targetObject->pos.y + targetBox->offset.y)) { if(targetBox->isTriangle && ((posChange.x < 0 && targetBox->rightAlign) || (posChange.x > 0 && !targetBox->rightAlign))) { //own box could be moving directly away from the hypotenuse. check for this. TerrainCollisionResult testResult = IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox, true); if(!testResult.horizontalImpact) { //box is moving away from the hypotenuse, so ignore it return result; } } //own box is impacting a vertical edge or a hypotenuse point on the target box result.horizontalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } else { //own box is potentially impacting the hypotenuse of the target box. return IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox); } } else if(posChange.y != 0) { //if the target box is jump-through, then upward moving collisions don't count if(targetObject->canBeJumpedThrough && posChange.y <= 0) { return result; } if(!targetBox->isTriangle || (posChange.y < 0 && targetBox->bottomAlign) || (posChange.y > 0 && !targetBox->bottomAlign) || (targetBox->rightAlign && ownPos->x + ownBox->offset.x + ownBox->width > targetObject->pos.x + targetBox->offset.x + targetBox->width) || (!targetBox->rightAlign && ownPos->x + ownBox->offset.x < targetObject->pos.x + targetBox->offset.x)) { if(targetBox->isTriangle && ((posChange.y < 0 && targetBox->bottomAlign) || (posChange.y > 0 && !targetBox->bottomAlign))) { //own box could be moving directly away from the hypotenuse. check for this. TerrainCollisionResult testResult = IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox, true); if(!testResult.horizontalImpact) { //box is moving away from the hypotenuse, so ignore it return result; } } //own box is impacting a horizontal edge or a hypotenuse point on the target box result.verticalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } else { //own box is potentially impacting the hypotenuse of the target box. return IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox); } } else if(posChange.x == 0 && posChange.y == 0) { if(AreRectanglesColliding(&prevPos, ownBox, &(targetObject->pos), targetBox)) { result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } } } //own box moves on both axes. //get the potential collision timeframe HSVect2D tMin, tMax; if(posChange.x < 0) { tMin.x = ((targetObject->pos.x + targetBox->offset.x + targetBox->width) - (ownPos->x + ownBox->offset.x)) / posChange.x; tMax.x = ((targetObject->pos.x + targetBox->offset.x) - (ownPos->x + ownBox->offset.x + ownBox->width)) / posChange.x; } else if(posChange.x > 0) { tMin.x = ((targetObject->pos.x + targetBox->offset.x) - (ownPos->x + ownBox->offset.x + ownBox->width)) / posChange.x; tMax.x = ((targetObject->pos.x + targetBox->offset.x + targetBox->width) - (ownPos->x + ownBox->offset.x)) / posChange.x; } if(posChange.y < 0) { tMin.y = ((targetObject->pos.y + targetBox->offset.y + targetBox->height) - (ownPos->y + ownBox->offset.y)) / posChange.y; tMax.y = ((targetObject->pos.y + targetBox->offset.y) - (ownPos->y + ownBox->offset.y + ownBox->height)) / posChange.y; } else if(posChange.y > 0) { tMin.y = ((targetObject->pos.y + targetBox->offset.y) - (ownPos->y + ownBox->offset.y + ownBox->height)) / posChange.y; tMax.y = ((targetObject->pos.y + targetBox->offset.y + targetBox->height) - (ownPos->y + ownBox->offset.y)) / posChange.y; } //compare the timeframes if(tMax.y < tMin.x || tMax.x < tMin.y) { //no collision return result; } //assume our own box is a rectangle if(targetBox->isTriangle && ((posChange.x < 0 && !targetBox->rightAlign) || (posChange.x > 0 && targetBox->rightAlign) || (posChange.y < 0 && !targetBox->bottomAlign) || (posChange.y > 0 && targetBox->bottomAlign))) { //target box is a triangle and the hypotenuse isn't oriented away from the direction of movement, //so we still need to check against it's hypotenuse. //projections against the axis perpendicular to the movement vector are necessary, so get that axis HSVect2D movePerp; movePerp.x = posChange.y * -1; movePerp.y = posChange.x; float movePerpMag = sqrt(pow(movePerp.x, 2) + pow(movePerp.y, 2)); movePerp.x = movePerp.x / movePerpMag; movePerp.y = movePerp.y / movePerpMag; //get all the necessary points of own box HSVect2D centerPoint, verticalPoint, horizontalPoint, leftHyp, rightHyp; if(posChange.x < 0) { centerPoint.x = ownPos->x + ownBox->offset.x; horizontalPoint.x = centerPoint.x + ownBox->width; if(posChange.y < 0) { centerPoint.y = ownPos->y + ownBox->offset.y; verticalPoint.y = centerPoint.y + ownBox->height; } else if(posChange.y > 0) { centerPoint.y = ownPos->y + ownBox->offset.y + ownBox->height; verticalPoint.y = centerPoint.y - ownBox->height; } } else if(posChange.x > 0) { centerPoint.x = ownPos->x + ownBox->offset.x + ownBox->width; horizontalPoint.x = centerPoint.x - ownBox->width; if(posChange.y < 0) { centerPoint.y = ownPos->y + ownBox->offset.y; verticalPoint.y = centerPoint.y + ownBox->height; } else if(posChange.y > 0) { centerPoint.y = ownPos->y + ownBox->offset.y + ownBox->height; verticalPoint.y = centerPoint.y - ownBox->height; } } verticalPoint.x = centerPoint.x; horizontalPoint.y = centerPoint.y; if(((posChange.x < 0 && !targetBox->rightAlign) || (posChange.x > 0 && targetBox->rightAlign)) && ((posChange.y < 0 && !targetBox->bottomAlign) || (posChange.y > 0 && targetBox->bottomAlign))) { //hypotenuse is oriented directly towards the direction of movement. //project own box's forward edges and the target box's hypotenuse aganst the axis perpendicular to the movement vector. leftHyp = GetLeftHypotenusePoint(&(targetObject->pos), targetBox); rightHyp = GetRightHypotenusePoint(&(targetObject->pos), targetBox); //project the hypotenuse against the axis float hypMin, hypMax; ProjectLineSegmentAgainstLine(&leftHyp, &rightHyp, &movePerp, &hypMin, &hypMax); //project the horizontal line against the axis float ownMin, ownMax; ProjectLineSegmentAgainstLine(&centerPoint, &horizontalPoint, &movePerp, &ownMin, &ownMax); //compare the results if(IntervalDifference(&hypMin, &hypMax, &ownMin, &ownMax) > 0) { //if the box can be jumped through then horizontal collisions don't count if(targetObject->canBeJumpedThrough) { return result; } //horizontal line never hits the hypotenuse, so the vertical line must hit a hypotenuse point result.horizontalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } //project the vertical line against the axis ProjectLineSegmentAgainstLine(&centerPoint, &verticalPoint, &movePerp, &ownMin, &ownMax); //compare the results if(IntervalDifference(&hypMin, &hypMax, &ownMin, &ownMax) >= 0) { //check if the box is jump through if(targetObject->canBeJumpedThrough && posChange.y <= 0) { //the box is jump-through and own box isn't moving downward, so ignore the box return result; } //vertical line never hits the hypotenuse, so the horizontal line hits a hypotenuse point result.verticalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } //there is a potential collision with the hypotenuse. Exit this if/else statment } else { //hypotenuse is facing in a direction perpendicular-ish to the direction of movement. //project own box's forward edges and the target box's hypotenuse and opposing edge aganst the axis perpendicular to the movement vector. //get the points on the triangle HSVect2D rightAng, closeHyp, farHyp; rightAng = GetRightAnglePoint(&(targetObject->pos), targetBox); if(posChange.x < 0) { closeHyp = GetRightHypotenusePoint(&(targetObject->pos), targetBox); farHyp = GetLeftHypotenusePoint(&(targetObject->pos), targetBox); } else if(posChange.x > 0) { closeHyp = GetLeftHypotenusePoint(&(targetObject->pos), targetBox); farHyp = GetRightHypotenusePoint(&(targetObject->pos), targetBox); } //project close edge against the axis float targetMin, targetMax; ProjectLineSegmentAgainstLine(&closeHyp, &rightAng, &movePerp, &targetMin, &targetMax); if(closeHyp.x == rightAng.x) { //target box's straight edge facing own box is vertical. if(tMin.x > tMin.y) { //we already know that the vertical edges might strike. //own box could be moving directly away from the hypotenuse. check for this. TerrainCollisionResult testResult = IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox, true); if(!testResult.horizontalImpact) { //box is moving away from the hypotenuse, so ignore it return result; } //if the box can be jumped through then horizontal collisions don't count if(targetObject->canBeJumpedThrough) { return result; } //vertical edges strike result.horizontalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } //project own box's horizontal edge against the axis float ownMin, ownMax; ProjectLineSegmentAgainstLine(&horizontalPoint, &centerPoint, &movePerp, &ownMin, &ownMax); if(IntervalDifference(&targetMin, &targetMax, &ownMin, &ownMax) <= 0) { //own horizontal edge might strike a hypotenuse point. //own box could be moving directly away from the hypotenuse. check for this. TerrainCollisionResult testResult = IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox, true); if(!testResult.horizontalImpact) { //box is moving away from the hypotenuse, so ignore it return result; } //check if the box is jump through if(targetObject->canBeJumpedThrough && posChange.y <= 0) { //the box is jump-through and own box isn't moving downward, so ignore the box return result; } //hypotenuse point struck result.verticalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } //project the hypotenuse against the axis ProjectLineSegmentAgainstLine(&closeHyp, &farHyp, &movePerp, &targetMin, &targetMax); if(IntervalDifference(&targetMin, &targetMax, &ownMin, &ownMax) >= 0) { //own horizontal edge is not approaching the hypotenuse, so no collision return result; } //there is a potential collision with the hypotenuse. Exit this if/else statment } else if(closeHyp.y == rightAng.y) { //target box's straight edge facing own box is horizontal. if(tMin.x <= tMin.y) { //we already know that the horizontal edge might strike. //own box could be moving directly away from the hypotenuse. check for this. TerrainCollisionResult testResult = IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox, true); if(!testResult.horizontalImpact) { //box is moving away from the hypotenuse, so ignore it return result; } //check if the box is jump through if(targetObject->canBeJumpedThrough && posChange.y <= 0) { //the box is jump-through and own box isn't moving downward, so ignore the box return result; } //horizontal edges strike result.verticalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } //project own box's vertical edge against the axis float ownMin, ownMax; ProjectLineSegmentAgainstLine(&verticalPoint, &centerPoint, &movePerp, &ownMin, &ownMax); if(IntervalDifference(&targetMin, &targetMax, &ownMin, &ownMax) < 0) { //own vertical edge might strike a hypotenuse point. //own box could be moving directly away from the hypotenuse. check for this. TerrainCollisionResult testResult = IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox, true); if(!testResult.horizontalImpact) { //box is moving away from the hypotenuse, so ignore it return result; } //if the box can be jumped through then horizontal collisions don't count if(targetObject->canBeJumpedThrough) { return result; } //hypotenuse point struck result.horizontalImpact = true; result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } //project the hypotenuse against the axis ProjectLineSegmentAgainstLine(&closeHyp, &farHyp, &movePerp, &targetMin, &targetMax); if(IntervalDifference(&targetMin, &targetMax, &ownMin, &ownMax) >= 0) { //own vertical edge is not approaching the hypotenuse, so no collision return result; } //there is a potential collision with the hypotenuse. Exit this if/else statment } //there is a potential collision with the hypotenuse. Exit this if/else statment } //potential impact against the hypotenuse. return IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox); } else { //we know both rectangles collide if(targetBox->isTriangle) { //own box could be moving directly away from the hypotenuse. check for this. TerrainCollisionResult testResult = IsBoxCollidingWithHypotenuse(ownPos, ownBox, targetObject, targetBox, true); if(!testResult.horizontalImpact) { //box is moving away from the hypotenuse, so ignore it return result; } } //figure out the earliest collision point if(tMin.x > tMin.y) { //if the box can be jumped through then horizontal collisions don't count if(targetObject->canBeJumpedThrough) { return result; } //x hit first result.horizontalImpact = true; } else { //check if the box is jump through if(targetObject->canBeJumpedThrough && posChange.y <= 0) { //the box is jump-through and own box isn't moving downward, so ignore the box return result; } //y hit first result.verticalImpact = true; } result.lastSelfBox = ownBox; result.lastTargetBox = targetBox; result.lastTargetObject = targetObject; return result; } } TerrainCollisionResult PhysicsObject::IsCollidingWithObjectTerrain(TerrainObject * targetObject, TerrainCollisionResult * prevResult, HSVect2D * ownPos, HSVect2D * ownPrevPos, bool ignoreCurrentlOverlapping) { //loop through this object's terrain boxes HSBox * selfTerrainBox = firstTerrainBox; HSBox * targetTerrainBox; while(selfTerrainBox != NULL) { //loop through the target's terrain boxes targetTerrainBox = targetObject->firstTerrainBox; while(targetTerrainBox != NULL) { //check for collision TerrainCollisionResult result = AreTerrainBoxesColliding(selfTerrainBox, targetObject, targetTerrainBox, prevResult, ownPos, ownPrevPos, ignoreCurrentlOverlapping); if(result.lastSelfBox != NULL) { return result; } targetTerrainBox = targetTerrainBox->nextBox; } selfTerrainBox = selfTerrainBox->nextBox; } //no collisions TerrainCollisionResult result; result.lastSelfBox = NULL; result.lastTargetBox = NULL; result.lastTargetObject = NULL; result.horizontalImpact = false; result.verticalImpact = false; return result; } TerrainCollisionResult PhysicsObject::IsCollidingWithAnyTerrain(list<HSObject*> * gameObjects, TerrainCollisionResult * prevResult, HSVect2D * ownPos, HSVect2D * ownPrevPos) { list<HSObject*>::iterator objIt; for ( objIt=gameObjects->begin(); objIt != gameObjects->end(); objIt++) { if((*objIt)->id != id && (*objIt)->IsTerrain() && ((TerrainObject*)(*objIt))->firstTerrainBox != NULL) { TerrainCollisionResult result = IsCollidingWithObjectTerrain((TerrainObject*)(*objIt), prevResult, ownPos, ownPrevPos); if(result.lastSelfBox != NULL) { return result; } } } //no collisions TerrainCollisionResult result; result.lastSelfBox = NULL; result.lastTargetBox = NULL; result.lastTargetObject = NULL; result.horizontalImpact = false; result.verticalImpact = false; return result; } void PhysicsObject::MoveOutOfTerrain(list<HSObject*> * gameObjects, HSVect2D * ownPrevPos) { //see if this object is currently colliding with anything TerrainCollisionResult result = IsCollidingWithAnyTerrain(gameObjects, NULL, ownPrevPos, ownPrevPos); //not colliding with anything, so return if(result.lastSelfBox == NULL) { return; } //move own terrain box just outside of the target terrain box } HSVect2D PhysicsObject::CollisionReposition(list<HSObject*> * gameObjects, TerrainCollisionResult * result, HSVect2D * ownPos, HSVect2D * ownPrevPos) { HSVect2D newPos; bool collision = true; if(ownPos == NULL) { ownPos = &pos; } if(ownPrevPos == NULL) { ownPrevPos = &prevPos; } //store the collision position newPos.x = ownPos->x; newPos.y = ownPos->y; //get own box's change in position HSVect2D posChange; posChange.x = ownPos->x - ownPrevPos->x; posChange.y = ownPos->y - ownPrevPos->y; //move this object out of terrain while(collision) { collision = false; if(result->horizontalImpact && result->verticalImpact) { //need to move to the edge of the hypotenuse. //we should already have the point of impact. we just need to use that to find the new position newPos.x = result->hypCollisionPoint.x - result->lastSelfBox->offset.x; if(result->lastTargetBox->rightAlign) { newPos.x -= result->lastSelfBox->width; } newPos.y = result->hypCollisionPoint.y - result->lastSelfBox->offset.y; if(result->lastTargetBox->bottomAlign) { newPos.y -= result->lastSelfBox->height; } } else if(result->horizontalImpact) { //need to move to the edge of a vertical surface. //adjust x based on the target box if(posChange.x < 0) { newPos.x = result->lastTargetObject->pos.x + result->lastTargetBox->offset.x + result->lastTargetBox->width - result->lastSelfBox->offset.x; } else if(posChange.x > 0) { newPos.x = result->lastTargetObject->pos.x + result->lastTargetBox->offset.x - result->lastSelfBox->width - result->lastSelfBox->offset.x; } //adjust y based on x adjustment float xRatio = (newPos.x - ownPrevPos->x) / posChange.x; newPos.y = ownPrevPos->y + (posChange.y * xRatio); } else if(result->verticalImpact) { //need to move to the edge of a horizontal surface. //adjust y based on the target box if(posChange.y < 0) { newPos.y = result->lastTargetObject->pos.y + result->lastTargetBox->offset.y + result->lastTargetBox->height - result->lastSelfBox->offset.y; } else if(posChange.y > 0) { newPos.y = result->lastTargetObject->pos.y + result->lastTargetBox->offset.y - result->lastSelfBox->height - result->lastSelfBox->offset.y; } //adjust x based on y adjustment float yRatio = (newPos.y - ownPrevPos->y) / posChange.y; newPos.x = ownPrevPos->x + (posChange.x * yRatio); } //don't let the object get moved too far back if((posChange.x > 0 && newPos.x < ownPrevPos->x) || (posChange.x < 0 && newPos.x > ownPrevPos->x)) { newPos.x = ownPrevPos->x; } if((posChange.y > 0 && newPos.y < ownPrevPos->y) || (posChange.y < 0 && newPos.y > ownPrevPos->y)) { newPos.y = ownPrevPos->y; } //now, try colliding with all objects again, using the new position TerrainCollisionResult newResult = IsCollidingWithAnyTerrain(gameObjects, result, &newPos); if(newResult.lastSelfBox != NULL) { if(ownPrevPos->x == newPos.x || ownPrevPos->y == newPos.y) { //this object can't be moved any farther and is still stuck in terrain. Move it out a different way MoveOutOfTerrain(gameObjects, ownPrevPos); break; } //there's still a collision, so try again collision = true; *result = newResult; } } return newPos; } void PhysicsObject::CollisionPhysics(HSVect2D * newPos, TerrainCollisionResult * result, HSVect2D * ownPos, HSVect2D * ownPrevPos) { if(ownPos == NULL) { ownPos = &pos; } if(ownPrevPos == NULL) { ownPrevPos = &prevPos; } //handle terrain impact physics HSVect2D newVel; newVel.x = vel.x; newVel.y = vel.y; //scale back the y velocity due to the fact that it actually had less time to accelerate //due to gravity before hitting the terrain if(newPos->y != ownPos->y && ownPrevPos->y != ownPos->y) { newVel.y -= (abs(newPos->y - ownPos->y) / abs(ownPrevPos->y - ownPos->y)) * gravity; } //get the largest bounce factor between the two objects float largestBounce = bounce; if(result->lastTargetObject->bounce > largestBounce) { largestBounce = result->lastTargetObject->bounce; } //get the friction float totalFriction = (1 - friction) * (1 - result->lastTargetObject->friction); //apply bounce and friciton if(result->horizontalImpact && result->verticalImpact) { //a hit on the hypotenuse. gotta do something more complicated //figure out how the impact line is oriented HSVect2D lineA, lineB; if(result->lastTargetBox->bottomAlign) { lineA = GetLeftHypotenusePoint(&result->lastTargetObject->pos, result->lastTargetBox); lineB = GetRightHypotenusePoint(&result->lastTargetObject->pos, result->lastTargetBox); } else { lineA = GetRightHypotenusePoint(&result->lastTargetObject->pos, result->lastTargetBox); lineB = GetLeftHypotenusePoint(&result->lastTargetObject->pos, result->lastTargetBox); } //get the normal of the impact line, pointing away from the triangle HSVect2D normal; normal.x = lineB.y - lineA.y; normal.y = (lineB.x - lineA.x) * -1; //get components of the new velocity float uPart = ((newVel.x * normal.x) + (newVel.y * normal.y)) / (pow(normal.x, 2) + pow(normal.y, 2)); HSVect2D u, w; u.x = normal.x * uPart; u.y = normal.y * uPart; w.x = newVel.x - u.x; w.y = newVel.y - u.y; //get the new velocity, applying bounce and friction newVel.x = (w.x * totalFriction) - (u.x * largestBounce); newVel.y = (w.y * totalFriction) - (u.y * largestBounce); } else if(result->horizontalImpact) { //a hit on the left/right newVel.x = newVel.x * largestBounce * -1; newVel.y = newVel.y * totalFriction; } else if(result->verticalImpact) { //a hit on the top/bottom newVel.x = newVel.x * totalFriction; newVel.y = newVel.y * largestBounce * -1; } //scale back the y velocity once again, in order to reflect the remainder of the frame in //which it is pulling downward on the object and counteracting the upward bounce if(newPos->y != ownPrevPos->y && ownPos->y != ownPrevPos->y) { newVel.y += (abs(newPos->y - ownPos->y) / abs(ownPrevPos->y - ownPos->y)) * gravity; } //now, get the magnitude of the velocity and if it's too small, just set it to zero float velMagSqrd = pow(newVel.x, 2) + pow(newVel.y, 2); if(velMagSqrd < pow(MIN_VEL, 2)) { newVel.x = 0; newVel.y = 0; } //apply the new position and velocity pos.x = newPos->x; pos.y = newPos->y; vel.x = newVel.x; vel.y = newVel.y; } int PhysicsObject::HandleTerrainCollision(list<HSObject*> * gameObjects, TerrainCollisionResult * result, HSVect2D * ownPos, HSVect2D * ownPrevPos) { if(ownPos == NULL) { ownPos = &pos; } if(ownPrevPos == NULL) { ownPrevPos = &prevPos; } //get the new position HSVect2D newPos = CollisionReposition(gameObjects, result, ownPos, ownPrevPos); ////handle terrain impact physics CollisionPhysics(&newPos, result, ownPos, ownPrevPos); if(fragile) { toDelete = true; } return 0; } int PhysicsObject::CollideTerrain(list<HSObject*> * gameObjects) { //check for collisions with terrain, if this object has any terrain boxes. if there is one, handle it if(firstTerrainBox != NULL && (pos.x != prevPos.x || pos.y != prevPos.y)) { TerrainCollisionResult result = IsCollidingWithAnyTerrain(gameObjects); if(result.lastSelfBox != NULL) { HandleTerrainCollision(gameObjects, &result); } } return 0; } bool PhysicsObject::IsTerrain() { return false; } bool PhysicsObject::IsTerrainObject() { return true; } bool PhysicsObject::IsPhysicsObject() { return true; }
b05629c32d7d549a0732a5a7e4f5cc43c2704f4f
b953e3a99f590b00578b769ecf4ed94d634d28c5
/editor2.h
99d68fa6426a570dc3931150ade3f952a05d8e3c
[]
no_license
sefloware/GBR
096f0cd265dfc04088d98cb437decb9d877bb118
6e674d20f13cca5e70dc5d66cb00ec81452e1de2
refs/heads/master
2021-01-10T20:47:58.483762
2014-05-08T07:43:55
2014-05-08T07:43:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,347
h
/** @file editor2.h * @brief the C++ editor2. * @author Runhua Li * @date 2013.6 * @version v1.0 * @note * The file is about the the C++ editor Class inherited * from the Editor1 Class. */ #ifndef EDITOR2_H #define EDITOR2_H #include "editor1.h" #include <QObject> QT_BEGIN_NAMESPACE class QPaintEvent; class QResizeEvent; class QSize; class QWidget; QT_END_NAMESPACE class LineNumberArea; class Editor2 : public Editor1 { Q_OBJECT public: Editor2(QWidget *parent = 0); void lineNumberAreaPaintEvent(QPaintEvent *event); int lineNumberAreaWidth(); protected: void resizeEvent(QResizeEvent *event); private slots: void updateLineNumberAreaWidth(int newBlockCount); void highlightCurrentLine(); void updateLineNumberArea(const QRect &, int); private: LineNumberArea *lineNumberArea; int currentBlockNumber; }; class LineNumberArea : public QWidget { public: LineNumberArea(Editor2 *editor) : QWidget(editor) { this->setObjectName("LineNumberArea"); codeEditor = editor; } QSize sizeHint() const { return QSize(codeEditor->lineNumberAreaWidth(), 0); } protected: void paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); codeEditor->lineNumberAreaPaintEvent(event); } private: Editor2 *codeEditor; }; #endif //EDITOR2_H
32bc855a65e16dab0a7513c594dbec9a55da8c50
7f45fa54386a7e2bb86b4bcfb04ff0a31d63703c
/algorithms/0279/numSquares-dp.cpp
c3a1e2a58b6882dd2a6fc405cb761f9cef80f6dc
[]
no_license
ejunjsh/leetcode
e3ca7e30eea89dd345b286264bd64695e5faaf73
5aa8d70939acd9180c1e8d351a72b2cfcd4ff04f
refs/heads/master
2021-08-31T22:19:20.522206
2021-08-25T07:47:47
2021-08-25T07:47:47
160,124,292
4
1
null
null
null
null
UTF-8
C++
false
false
390
cpp
class Solution { public: int numSquares(int n) { vector<int> dp(n+1,INT_MAX); dp[0] = 0; for(int i = 1; i <= n; ++i) { int _min = INT_MAX; int j = 1; while(i - j*j >= 0) { _min = min(_min, dp[i - j*j] + 1); ++j; } dp[i] = _min; } return dp[n]; } };
90da6f3019acbcc2cb2f0e91bb0bd630b2ee5427
07b3819b6b9d27c9505288b36edefca3d6ca6ffe
/include/lib_a/helloworld.pb.h
dc446f2a6b1576f8a17901b0fdf5686489b473d2
[]
no_license
IllidanSR/modern_cmake_example
42a2a1c2dadef097ee4ee3d79968d5b2fcb47165
66769a320be44b19f78a910d57934a808eee819e
refs/heads/master
2023-03-19T16:20:05.016813
2021-03-01T07:44:09
2021-03-01T07:44:09
343,329,509
1
0
null
null
null
null
UTF-8
C++
false
true
25,087
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: helloworld.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_helloworld_2eproto #define GOOGLE_PROTOBUF_INCLUDED_helloworld_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3011000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3011002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/any.pb.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_helloworld_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_helloworld_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[2] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_helloworld_2eproto; namespace db_package { class StorageAddRequest; class StorageAddRequestDefaultTypeInternal; extern StorageAddRequestDefaultTypeInternal _StorageAddRequest_default_instance_; class StorageAddResponse; class StorageAddResponseDefaultTypeInternal; extern StorageAddResponseDefaultTypeInternal _StorageAddResponse_default_instance_; } // namespace db_package PROTOBUF_NAMESPACE_OPEN template<> ::db_package::StorageAddRequest* Arena::CreateMaybeMessage<::db_package::StorageAddRequest>(Arena*); template<> ::db_package::StorageAddResponse* Arena::CreateMaybeMessage<::db_package::StorageAddResponse>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace db_package { enum Status : int { OK = 0, NOT_OK = 1, Status_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(), Status_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max() }; bool Status_IsValid(int value); constexpr Status Status_MIN = OK; constexpr Status Status_MAX = NOT_OK; constexpr int Status_ARRAYSIZE = Status_MAX + 1; const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Status_descriptor(); template<typename T> inline const std::string& Status_Name(T enum_t_value) { static_assert(::std::is_same<T, Status>::value || ::std::is_integral<T>::value, "Incorrect type passed to function Status_Name."); return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( Status_descriptor(), enum_t_value); } inline bool Status_Parse( const std::string& name, Status* value) { return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<Status>( Status_descriptor(), name, value); } // =================================================================== class StorageAddRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:db_package.StorageAddRequest) */ { public: StorageAddRequest(); virtual ~StorageAddRequest(); StorageAddRequest(const StorageAddRequest& from); StorageAddRequest(StorageAddRequest&& from) noexcept : StorageAddRequest() { *this = ::std::move(from); } inline StorageAddRequest& operator=(const StorageAddRequest& from) { CopyFrom(from); return *this; } inline StorageAddRequest& operator=(StorageAddRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const StorageAddRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StorageAddRequest* internal_default_instance() { return reinterpret_cast<const StorageAddRequest*>( &_StorageAddRequest_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(StorageAddRequest& a, StorageAddRequest& b) { a.Swap(&b); } inline void Swap(StorageAddRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline StorageAddRequest* New() const final { return CreateMaybeMessage<StorageAddRequest>(nullptr); } StorageAddRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<StorageAddRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const StorageAddRequest& from); void MergeFrom(const StorageAddRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StorageAddRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "db_package.StorageAddRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_helloworld_2eproto); return ::descriptor_table_helloworld_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kRequestValueFieldNumber = 2, kMessageIdFieldNumber = 1, kTaskIdFieldNumber = 3, }; // string request_value = 2; void clear_request_value(); const std::string& request_value() const; void set_request_value(const std::string& value); void set_request_value(std::string&& value); void set_request_value(const char* value); void set_request_value(const char* value, size_t size); std::string* mutable_request_value(); std::string* release_request_value(); void set_allocated_request_value(std::string* request_value); private: const std::string& _internal_request_value() const; void _internal_set_request_value(const std::string& value); std::string* _internal_mutable_request_value(); public: // int64 message_id = 1; void clear_message_id(); ::PROTOBUF_NAMESPACE_ID::int64 message_id() const; void set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value); private: ::PROTOBUF_NAMESPACE_ID::int64 _internal_message_id() const; void _internal_set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value); public: // int64 task_id = 3; void clear_task_id(); ::PROTOBUF_NAMESPACE_ID::int64 task_id() const; void set_task_id(::PROTOBUF_NAMESPACE_ID::int64 value); private: ::PROTOBUF_NAMESPACE_ID::int64 _internal_task_id() const; void _internal_set_task_id(::PROTOBUF_NAMESPACE_ID::int64 value); public: // @@protoc_insertion_point(class_scope:db_package.StorageAddRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr request_value_; ::PROTOBUF_NAMESPACE_ID::int64 message_id_; ::PROTOBUF_NAMESPACE_ID::int64 task_id_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_helloworld_2eproto; }; // ------------------------------------------------------------------- class StorageAddResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:db_package.StorageAddResponse) */ { public: StorageAddResponse(); virtual ~StorageAddResponse(); StorageAddResponse(const StorageAddResponse& from); StorageAddResponse(StorageAddResponse&& from) noexcept : StorageAddResponse() { *this = ::std::move(from); } inline StorageAddResponse& operator=(const StorageAddResponse& from) { CopyFrom(from); return *this; } inline StorageAddResponse& operator=(StorageAddResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const StorageAddResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StorageAddResponse* internal_default_instance() { return reinterpret_cast<const StorageAddResponse*>( &_StorageAddResponse_default_instance_); } static constexpr int kIndexInFileMessages = 1; friend void swap(StorageAddResponse& a, StorageAddResponse& b) { a.Swap(&b); } inline void Swap(StorageAddResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline StorageAddResponse* New() const final { return CreateMaybeMessage<StorageAddResponse>(nullptr); } StorageAddResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<StorageAddResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const StorageAddResponse& from); void MergeFrom(const StorageAddResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StorageAddResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "db_package.StorageAddResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_helloworld_2eproto); return ::descriptor_table_helloworld_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kResponseValueFieldNumber = 2, kMessageIdFieldNumber = 1, kTaskStatusFieldNumber = 3, }; // string response_value = 2; void clear_response_value(); const std::string& response_value() const; void set_response_value(const std::string& value); void set_response_value(std::string&& value); void set_response_value(const char* value); void set_response_value(const char* value, size_t size); std::string* mutable_response_value(); std::string* release_response_value(); void set_allocated_response_value(std::string* response_value); private: const std::string& _internal_response_value() const; void _internal_set_response_value(const std::string& value); std::string* _internal_mutable_response_value(); public: // int64 message_id = 1; void clear_message_id(); ::PROTOBUF_NAMESPACE_ID::int64 message_id() const; void set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value); private: ::PROTOBUF_NAMESPACE_ID::int64 _internal_message_id() const; void _internal_set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value); public: // .db_package.Status task_status = 3; void clear_task_status(); ::db_package::Status task_status() const; void set_task_status(::db_package::Status value); private: ::db_package::Status _internal_task_status() const; void _internal_set_task_status(::db_package::Status value); public: // @@protoc_insertion_point(class_scope:db_package.StorageAddResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr response_value_; ::PROTOBUF_NAMESPACE_ID::int64 message_id_; int task_status_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_helloworld_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // StorageAddRequest // int64 message_id = 1; inline void StorageAddRequest::clear_message_id() { message_id_ = PROTOBUF_LONGLONG(0); } inline ::PROTOBUF_NAMESPACE_ID::int64 StorageAddRequest::_internal_message_id() const { return message_id_; } inline ::PROTOBUF_NAMESPACE_ID::int64 StorageAddRequest::message_id() const { // @@protoc_insertion_point(field_get:db_package.StorageAddRequest.message_id) return _internal_message_id(); } inline void StorageAddRequest::_internal_set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value) { message_id_ = value; } inline void StorageAddRequest::set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value) { _internal_set_message_id(value); // @@protoc_insertion_point(field_set:db_package.StorageAddRequest.message_id) } // string request_value = 2; inline void StorageAddRequest::clear_request_value() { request_value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline const std::string& StorageAddRequest::request_value() const { // @@protoc_insertion_point(field_get:db_package.StorageAddRequest.request_value) return _internal_request_value(); } inline void StorageAddRequest::set_request_value(const std::string& value) { _internal_set_request_value(value); // @@protoc_insertion_point(field_set:db_package.StorageAddRequest.request_value) } inline std::string* StorageAddRequest::mutable_request_value() { // @@protoc_insertion_point(field_mutable:db_package.StorageAddRequest.request_value) return _internal_mutable_request_value(); } inline const std::string& StorageAddRequest::_internal_request_value() const { return request_value_.GetNoArena(); } inline void StorageAddRequest::_internal_set_request_value(const std::string& value) { request_value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); } inline void StorageAddRequest::set_request_value(std::string&& value) { request_value_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:db_package.StorageAddRequest.request_value) } inline void StorageAddRequest::set_request_value(const char* value) { GOOGLE_DCHECK(value != nullptr); request_value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:db_package.StorageAddRequest.request_value) } inline void StorageAddRequest::set_request_value(const char* value, size_t size) { request_value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:db_package.StorageAddRequest.request_value) } inline std::string* StorageAddRequest::_internal_mutable_request_value() { return request_value_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* StorageAddRequest::release_request_value() { // @@protoc_insertion_point(field_release:db_package.StorageAddRequest.request_value) return request_value_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void StorageAddRequest::set_allocated_request_value(std::string* request_value) { if (request_value != nullptr) { } else { } request_value_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), request_value); // @@protoc_insertion_point(field_set_allocated:db_package.StorageAddRequest.request_value) } // int64 task_id = 3; inline void StorageAddRequest::clear_task_id() { task_id_ = PROTOBUF_LONGLONG(0); } inline ::PROTOBUF_NAMESPACE_ID::int64 StorageAddRequest::_internal_task_id() const { return task_id_; } inline ::PROTOBUF_NAMESPACE_ID::int64 StorageAddRequest::task_id() const { // @@protoc_insertion_point(field_get:db_package.StorageAddRequest.task_id) return _internal_task_id(); } inline void StorageAddRequest::_internal_set_task_id(::PROTOBUF_NAMESPACE_ID::int64 value) { task_id_ = value; } inline void StorageAddRequest::set_task_id(::PROTOBUF_NAMESPACE_ID::int64 value) { _internal_set_task_id(value); // @@protoc_insertion_point(field_set:db_package.StorageAddRequest.task_id) } // ------------------------------------------------------------------- // StorageAddResponse // int64 message_id = 1; inline void StorageAddResponse::clear_message_id() { message_id_ = PROTOBUF_LONGLONG(0); } inline ::PROTOBUF_NAMESPACE_ID::int64 StorageAddResponse::_internal_message_id() const { return message_id_; } inline ::PROTOBUF_NAMESPACE_ID::int64 StorageAddResponse::message_id() const { // @@protoc_insertion_point(field_get:db_package.StorageAddResponse.message_id) return _internal_message_id(); } inline void StorageAddResponse::_internal_set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value) { message_id_ = value; } inline void StorageAddResponse::set_message_id(::PROTOBUF_NAMESPACE_ID::int64 value) { _internal_set_message_id(value); // @@protoc_insertion_point(field_set:db_package.StorageAddResponse.message_id) } // string response_value = 2; inline void StorageAddResponse::clear_response_value() { response_value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline const std::string& StorageAddResponse::response_value() const { // @@protoc_insertion_point(field_get:db_package.StorageAddResponse.response_value) return _internal_response_value(); } inline void StorageAddResponse::set_response_value(const std::string& value) { _internal_set_response_value(value); // @@protoc_insertion_point(field_set:db_package.StorageAddResponse.response_value) } inline std::string* StorageAddResponse::mutable_response_value() { // @@protoc_insertion_point(field_mutable:db_package.StorageAddResponse.response_value) return _internal_mutable_response_value(); } inline const std::string& StorageAddResponse::_internal_response_value() const { return response_value_.GetNoArena(); } inline void StorageAddResponse::_internal_set_response_value(const std::string& value) { response_value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); } inline void StorageAddResponse::set_response_value(std::string&& value) { response_value_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:db_package.StorageAddResponse.response_value) } inline void StorageAddResponse::set_response_value(const char* value) { GOOGLE_DCHECK(value != nullptr); response_value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:db_package.StorageAddResponse.response_value) } inline void StorageAddResponse::set_response_value(const char* value, size_t size) { response_value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:db_package.StorageAddResponse.response_value) } inline std::string* StorageAddResponse::_internal_mutable_response_value() { return response_value_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* StorageAddResponse::release_response_value() { // @@protoc_insertion_point(field_release:db_package.StorageAddResponse.response_value) return response_value_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void StorageAddResponse::set_allocated_response_value(std::string* response_value) { if (response_value != nullptr) { } else { } response_value_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), response_value); // @@protoc_insertion_point(field_set_allocated:db_package.StorageAddResponse.response_value) } // .db_package.Status task_status = 3; inline void StorageAddResponse::clear_task_status() { task_status_ = 0; } inline ::db_package::Status StorageAddResponse::_internal_task_status() const { return static_cast< ::db_package::Status >(task_status_); } inline ::db_package::Status StorageAddResponse::task_status() const { // @@protoc_insertion_point(field_get:db_package.StorageAddResponse.task_status) return _internal_task_status(); } inline void StorageAddResponse::_internal_set_task_status(::db_package::Status value) { task_status_ = value; } inline void StorageAddResponse::set_task_status(::db_package::Status value) { _internal_set_task_status(value); // @@protoc_insertion_point(field_set:db_package.StorageAddResponse.task_status) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace db_package PROTOBUF_NAMESPACE_OPEN template <> struct is_proto_enum< ::db_package::Status> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::db_package::Status>() { return ::db_package::Status_descriptor(); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_helloworld_2eproto
ff254e737732d74b9200a927f691fac253294900
6b95158bedf856771632fc761812b137e1c784f8
/GUI/AScope/DisplayView.cc
d3bc2251abb61c6a5d14d300dec51c68511a3515
[ "MIT" ]
permissive
hhuangwx/sidecar
dabaa8b87ee7ab1160f60c73bc7ee70f52bcd74e
fe4fa1832410f815a566fbb1934c84e55d153992
refs/heads/master
2021-06-02T08:10:32.349881
2016-08-30T00:39:42
2016-08-30T00:39:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,071
cc
#include "QtCore/QSettings" #include "QtGui/QPainter" #include "QtGui/QResizeEvent" #include "QtGui/QGridLayout" #include "GUI/LogUtils.h" #include "DisplayView.h" #include "ScaleWidget.h" #include "Visualizer.h" using namespace SideCar::GUI::AScope; DisplayView* DisplayView::activeDisplayView_ = 0; Logger::Log& DisplayView::Log() { static Logger::Log& log_ = Logger::Log::Find("ascope.DisplayView"); return log_; } DisplayView::DisplayView(QWidget* parent, AzimuthLatch* azimuthLatch) : QFrame(parent), visualizer_(new Visualizer(this, azimuthLatch)), horizontalScale_(new ScaleWidget(this, Qt::Horizontal)), verticalScale_(new ScaleWidget(this, Qt::Vertical)) { initialize(); } DisplayView::~DisplayView() { static Logger::ProcLog log("~DisplayView", Log()); LOGINFO << this << " + " << visualizer_ << std::endl; if (activeDisplayView_ == this) { activeDisplayView_ = 0; emit activeDisplayViewChanged(0); } } void DisplayView::saveToSettings(QSettings& settings) { Logger::ProcLog log("saveToSettings", Log()); LOGINFO << settings.group() << std::endl; settings.beginGroup("Visualizer"); visualizer_->saveToSettings(settings); settings.endGroup(); LOGINFO << "done" << std::endl; } void DisplayView::restoreFromSettings(QSettings& settings) { Logger::ProcLog log("restoreFromSettings", Log()); LOGINFO << settings.group() << std::endl; settings.beginGroup("Visualizer"); visualizer_->restoreFromSettings(settings); settings.endGroup(); makeBackground(); LOGINFO << "done" << std::endl; } void DisplayView::duplicate(const DisplayView* other) { visualizer_->duplicate(other->visualizer_); } void DisplayView::initialize() { static Logger::ProcLog log("initialize", Log()); LOGINFO << std::endl; setFrameStyle(QFrame::Box | QFrame::Plain); setLineWidth(2); // NOTE: use Qt::QueuedConnection with the transformChanged() signal so that all widget resizing is done // before we do anything with the new transform. Specifically, we need our Scale widgets to adjust before we // use them to update the background pixmap intalled in the Visualizer object. // connect(visualizer_, SIGNAL(transformChanged()), SLOT(visualizerTransformChanged()), Qt::QueuedConnection); connect(visualizer_, SIGNAL(pointerMoved(const QPoint&, const QPointF&)), SLOT(updateCursorPosition(const QPoint&, const QPointF&))); const ViewBounds& viewRect(visualizer_->getCurrentView().getBounds()); horizontalScale_->setStart(viewRect.getXMin()); horizontalScale_->setRange(viewRect.getWidth()); verticalScale_->setStart(viewRect.getYMin()); verticalScale_->setRange(viewRect.getHeight()); QGridLayout* layout = new QGridLayout; layout->setSpacing(0); layout->addWidget(verticalScale_, 0, 0); layout->addWidget(visualizer_, 0, 1); layout->addWidget(horizontalScale_, 1, 1); setLayout(layout); makeBackground(); } void DisplayView::visualizerTransformChanged() { static Logger::ProcLog log("visualizerTransformChanged", Log()); LOGINFO << std::endl; const ViewSettings& viewSettings(visualizer_->getCurrentView()); const ViewBounds& viewRect(viewSettings.getBounds()); horizontalScale_->setStart(viewRect.getXMin()); horizontalScale_->setRange(viewRect.getWidth()); verticalScale_->setStart(viewRect.getYMin()); verticalScale_->setRange(viewRect.getHeight()); makeBackground(); } void DisplayView::makeBackground() { static Logger::ProcLog log("makeBackground", Log()); LOGINFO << std::endl; QImage image(visualizer_->width(), visualizer_->height(), QImage::Format_RGB32); if (! image.isNull()) { QPainter painter(&image); painter.setBackground(Qt::black); painter.eraseRect(image.rect()); if (visualizer_->isShowingGrid()) { horizontalScale_->drawGridLines(painter); verticalScale_->drawGridLines(painter); } painter.end(); visualizer_->setBackground(image); } } void DisplayView::updateCursorPosition(const QPoint& local, const QPointF& world) { horizontalScale_->setCursorPosition(local.x()); verticalScale_->setCursorPosition(local.y()); } void DisplayView::updateActiveDisplayViewIndicator(bool on) { static Logger::ProcLog log("updateActiveDisplayViewIndicator", Log()); LOGINFO << this << " + " << visualizer_ << ' ' << on << std::endl; QPalette p(palette()); p.setColor(QPalette::WindowText, on ? "Green" : "White"); setPalette(p); update(); } void DisplayView::setActiveDisplayView() { static Logger::ProcLog log("setActiveDisplayView", Log()); LOGINFO << this << " + " << visualizer_ << std::endl; if (activeDisplayView_ != this) { if (activeDisplayView_) activeDisplayView_->updateActiveDisplayViewIndicator(false); activeDisplayView_ = this; updateActiveDisplayViewIndicator(true); emit activeDisplayViewChanged(this); } } void DisplayView::resizeEvent(QResizeEvent* evt) { Super::resizeEvent(evt); updateActiveDisplayViewIndicator(activeDisplayView_ == this); } bool DisplayView::isHorizontalScaleVisible() const { return horizontalScale_->isVisible(); } bool DisplayView::isVerticalScaleVisible() const { return verticalScale_->isVisible(); } void DisplayView::setHorizontalScaleVisibility(bool value) { horizontalScale_->setVisible(value); } void DisplayView::setVerticalScaleVisibility(bool value) { verticalScale_->setVisible(value); } void DisplayView::setFrozen(bool state) { visualizer_->setFrozen(state); } void DisplayView::setShowGrid(bool state) { visualizer_->setShowGrid(state); } void DisplayView::setShowPeakBars(bool state) { visualizer_->setShowPeakBars(state); } bool DisplayView::isFrozen() const { return visualizer_->isFrozen(); } bool DisplayView::isShowingGrid() const { return visualizer_->isShowingGrid(); } bool DisplayView::isShowingPeakBars() const { return visualizer_->isShowingPeakBars(); }
54e93a063c7e1a68bc4a36144ea52dca199a17d6
f09b3e399d817bc42547273a522641a74a1cb0d0
/src/ndnph/keychain/digest.hpp
a4a4545ca805b357058e66b54e19be8d05a638ff
[ "ISC" ]
permissive
yoursunny/NDNph
ed0863b64faba16e0e9f5ecdda874619da972044
3480448b1e878da68f58909c0b32bd6cf09e33d7
refs/heads/main
2023-08-08T13:23:53.559530
2022-12-23T19:09:27
2022-12-23T19:09:27
231,204,807
2
2
ISC
2021-04-26T10:06:18
2020-01-01T10:58:36
C++
UTF-8
C++
false
false
1,263
hpp
#ifndef NDNPH_KEYCHAIN_DIGEST_HPP #define NDNPH_KEYCHAIN_DIGEST_HPP #include "../port/timingsafe/port.hpp" #include "helper.hpp" #include "private-key.hpp" #include "public-key.hpp" namespace ndnph { /** @brief DigestSha256 signing and verification. */ class DigestKey : public PrivateKey , public PublicKey { public: static const DigestKey& get() { static DigestKey instance; return instance; } size_t getMaxSigLen() const final { return NDNPH_SHA256_LEN; } void updateSigInfo(SigInfo& sigInfo) const final { sigInfo.sigType = SigType::Sha256; sigInfo.name = Name(); } ssize_t sign(std::initializer_list<tlv::Value> chunks, uint8_t* sig) const final { bool ok = detail::computeDigest(chunks, sig); return ok ? NDNPH_SHA256_LEN : -1; } bool matchSigInfo(const SigInfo& sigInfo) const final { return sigInfo.sigType == SigType::Sha256; } bool verify(std::initializer_list<tlv::Value> chunks, const uint8_t* sig, size_t sigLen) const final { uint8_t digest[NDNPH_SHA256_LEN]; return detail::computeDigest(chunks, digest) && port::TimingSafeEqual()(digest, NDNPH_SHA256_LEN, sig, sigLen); } }; } // namespace ndnph #endif // NDNPH_KEYCHAIN_DIGEST_HPP
73638c8e059bd2902654e71901efb4b5db5b471d
234964c935ee5df3840ff8c5923ff49820dba9b5
/IGC/VectorCompiler/lib/GenXOpts/CMTrans/CMImpParam.cpp
67ef5b5541e7a2a93864b3be829d8da0e26ad26b
[ "MIT" ]
permissive
kala9012/intel-graphics-compiler
3a45498039be4f42760d713ab8ad1d78eb9dc52c
5aa880a0de8eb8f40e921b2c9a855a92be246b8d
refs/heads/master
2022-12-04T02:37:48.611372
2020-08-08T05:09:30
2020-08-08T05:23:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,517
cpp
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation 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. ======================= end_copyright_notice ==================================*/ //===----------------------------------------------------------------------===// // /// CMImpParam /// ---------- /// /// As well as explicit kernel args declared in the CM kernel function, certain /// implicit args are also passed. These fall into two categories: /// /// 1. fields set up in r0 by the hardware, depending on which dispatch method /// is being used (e.g. media walker); /// /// 2. implicit args set up along with the explicit args in CURBE by the CM /// runtime. /// /// The r0 implicit args are represented in LLVM IR by special intrinsics, and the /// GenX backend generates these to special reserved vISA registers. /// /// For the CM runtime implicit args in (2) above, in vISA 3.2 and earlier, these were also /// represented by LLVM special intrinsics and vISA special reserved vISA registers. /// Because they are specific to the CM runtime, and not any other user of vISA, /// vISA 3.3 has removed them, and instead they are handled much like other kernel /// args in the input table. /// /// The *kind* byte in the input table has two fields: /// /// * the *category* field, saying whether the input is general/surface/etc; /// /// * the *provenance* field, saying whether the input is an explicit one from /// the CM source, or an implicit one generated by this pass. This is a /// protocol agreed between the CM compiler (in fact this pass) and the CM /// runtime. /// /// Within the CM compiler, the vISA input table for a kernel is represented by an /// array of kind bytes, each one corresponding to an argument of the kernel function. /// /// Clang codegen still generates special intrinsics for these CM runtime implicit /// args. It is the job of this CMImpParam pass to transform those intrinsics: /// /// * where the intrinsic for a CM runtime implicit arg is used somewhere: /// /// - a global variable is created for it; /// /// - for any kernel that uses the implicit arg (or can reach a subroutine that /// uses it), the implicit arg is added to the input table in the kernel /// metadata and as an extra arg to the definition of the kernel itself, /// and its value is stored into the global variable; /// /// * each use of the intrinsic for a CM runtime implicit arg is transformed into /// a load of the corresponding global variable. /// /// Like any other global variable, the subsequent CMABI pass turns the global /// variable for an implicit arg into local variable(s) passed into subroutines /// if necessary. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "cmimpparam" #include "vc/GenXOpts/GenXOpts.h" #include "vc/GenXOpts/Utils/KernelInfo.h" #include "llvm/ADT/SCCIterator.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/CallGraphSCCPass.h" #include "llvm/GenXIntrinsics/GenXIntrinsics.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Module.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <set> #include <map> using namespace llvm; namespace llvm { void initializeCMImpParamPass(PassRegistry &); } // namespace llvm namespace { class ImplicitUseInfo { public: typedef std::set<unsigned> ImplicitSetTy; explicit ImplicitUseInfo(Function *F) : Fn(F) {} ImplicitUseInfo() : Fn(nullptr) {} Function *getFunction() const { return Fn; } bool empty() const { return Implicits.empty(); } ImplicitSetTy &getImplicits() { return Implicits; } const ImplicitSetTy &getImplicits() const { return Implicits; } // \brief Add an implicit arg intrinsic void addImplicit(unsigned IID) { Implicits.insert(IID); } void merge(const ImplicitUseInfo &IUI) { Implicits.insert(IUI.Implicits.begin(), IUI.Implicits.end()); } void dump() const { print(dbgs()); } void print(raw_ostream &OS, unsigned depth = 0) const { for (auto IID : Implicits) { OS.indent(depth) << GenXIntrinsic::getAnyName(IID, None) << "\n"; } } private: // \brief The function being analyzed Function *Fn; // \brief Implicit arguments used ImplicitSetTy Implicits; }; struct CMImpParam : public ModulePass { static char ID; bool IsCmRT; CMImpParam(bool isCmRT = true) : ModulePass(ID), IsCmRT(isCmRT) { initializeCMImpParamPass(*PassRegistry::getPassRegistry()); } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<CallGraphWrapperPass>(); } virtual StringRef getPassName() const { return "CM Implicit Params"; } virtual bool runOnModule(Module &M); void dump() const { print(dbgs()); } virtual void print(raw_ostream &OS, const Module *M = nullptr) const; private: void replaceWithGlobal(CallInst *CI, unsigned IID); bool AnalyzeImplicitUse(Module &M); void MergeImplicits(ImplicitUseInfo &implicits, Function *F); void PropagateImplicits(Function *F, Module &M, ImplicitUseInfo &implicits); CallGraphNode *ProcessKernel(Function *F); static Value *getValue(Metadata *M) { if (auto VM = dyn_cast<ValueAsMetadata>(M)) return VM->getValue(); return nullptr; } // Convert to implicit thread payload related intrinsics. bool ConvertToOCLPayload(Module &M); uint32_t MapToKind(unsigned IID) { using namespace genx; switch (IID) { default: return KernelMetadata::AK_NORMAL; case GenXIntrinsic::genx_print_buffer: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_OCL_PRINTF_BUFFER; case GenXIntrinsic::genx_local_size: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_LOCAL_SIZE; case GenXIntrinsic::genx_local_id: case GenXIntrinsic::genx_local_id16: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_LOCAL_ID; case GenXIntrinsic::genx_group_count: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_GROUP_COUNT; case GenXIntrinsic::genx_get_scoreboard_deltas: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_SB_DELTAS; case GenXIntrinsic::genx_get_scoreboard_bti: return KernelMetadata::AK_SURFACE | KernelMetadata::IMP_SB_BTI; case GenXIntrinsic::genx_get_scoreboard_depcnt: return KernelMetadata::AK_SURFACE | KernelMetadata::IMP_SB_DEPCNT; case GenXIntrinsic::genx_local_id_x: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_OCL_LOCAL_ID_X; case GenXIntrinsic::genx_local_id_y: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_OCL_LOCAL_ID_Y; case GenXIntrinsic::genx_local_id_z: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_OCL_LOCAL_ID_Z; case GenXIntrinsic::genx_group_or_local_size: return KernelMetadata::AK_NORMAL | KernelMetadata::IMP_OCL_GROUP_OR_LOCAL_SIZE; } return KernelMetadata::AK_NORMAL; } // \brief Returns the implicit use info associated with a function ImplicitUseInfo &getImplicitUseInfo(Function *F) { if (!ImplicitsInfo.count(F)) { ImplicitUseInfo *IUI = new ImplicitUseInfo(F); ImplicitsInfoObjs.push_back(IUI); ImplicitsInfo[F] = IUI; return *IUI; } return *ImplicitsInfo[F]; } // \brief Returns the implict use info associated with a function (kernel) // and also creates a new one that represents the total implicits for the // kernel as a whole (stored in a different object) ImplicitUseInfo &getImplicitUseInfoKernel(Function *F) { assert(Kernels.count(F)); if (KernelsInfo.count(F)) { // Kernel already processed return *KernelsInfo[F]; } ImplicitUseInfo *IUI = new ImplicitUseInfo(F); ImplicitsInfoObjs.push_back(IUI); KernelsInfo[F] = IUI; if (ImplicitsInfo.count(F)) { IUI->merge(*ImplicitsInfo[F]); } return *IUI; } const ImplicitUseInfo *implicitUseInfoKernelExist(Function *F) const { if (KernelsInfo.count(F)) { auto CI = KernelsInfo.find(F); return CI->second; } return nullptr; } void addImplicit(Function *F, unsigned IID) { getImplicitUseInfo(F).addImplicit(IID); } GlobalVariable *getIIDGlobal(Function *F, unsigned IID) { if (GlobalsMap.count(IID)) return GlobalsMap[IID]; Type * Ty = getIntrinRetType(F->getContext(), IID); assert(Ty); GlobalVariable *NewVar = new GlobalVariable( *F->getParent(), Ty, false, GlobalVariable::InternalLinkage, Constant::getNullValue(Ty), "__imparg_" + GenXIntrinsic::getAnyName(IID, None)); GlobalsMap[IID] = NewVar; return NewVar; } Type *getIntrinRetType(LLVMContext &Context, unsigned IID) { switch (IID) { case GenXIntrinsic::genx_print_buffer: return llvm::Type::getInt64Ty(Context); case GenXIntrinsic::genx_local_id: case GenXIntrinsic::genx_local_size: case GenXIntrinsic::genx_group_count: return llvm::VectorType::get(llvm::Type::getInt32Ty(Context), 3); case GenXIntrinsic::genx_local_id16: return llvm::VectorType::get(llvm::Type::getInt16Ty(Context), 3); default: // Should be able to extract the type from the intrinsic // directly as no overloading is required (if it is then // you need to define specific type in a case statement above) FunctionType *FTy = dyn_cast_or_null<FunctionType>( GenXIntrinsic::getAnyType(Context, IID)); if (FTy) return FTy->getReturnType(); } return nullptr; } // This map captures all implicit uses to be transformed SmallDenseMap<Function *, ImplicitUseInfo *> ImplicitsInfo; // This map captures all implicit uses that are required for a kernel // (includes sub function uses) SmallDenseMap<Function *, ImplicitUseInfo *> KernelsInfo; // All kernels (entry points) in module being processed SmallPtrSet<Function *, 8> Kernels; // Already visited functions SmallPtrSet<Function *, 8> AlreadyVisited; // ImplicitUseInfo objects created SmallVector<ImplicitUseInfo *, 8> ImplicitsInfoObjs; // Functions that contain implicit arg intrinsics SmallPtrSet<Function *, 8> ContainImplicit; // GlobalVariables that have been created for an intrinsic SmallDenseMap<unsigned, GlobalVariable *> GlobalsMap; }; } // namespace bool CMImpParam::runOnModule(Module &M) { bool changed = false; // Apply necessary changes if kernels are compiled for OpenCL runtime. changed |= ConvertToOCLPayload(M); // Analyze functions for implicit use intrinsic invocation changed |= AnalyzeImplicitUse(M); // Collect all CM kernels from named metadata and also traverse the call graph // to determine what the total implicit uses are for the top level kernels if (NamedMDNode *Named = M.getNamedMetadata(genx::FunctionMD::GenXKernels)) { for (unsigned I = 0, E = Named->getNumOperands(); I != E; ++I) { MDNode *Node = Named->getOperand(I); if (auto F = dyn_cast_or_null<Function>( getValue(Node->getOperand(genx::KernelMDOp::FunctionRef)))) { Kernels.insert(F); AlreadyVisited.clear(); ImplicitUseInfo &implicits = getImplicitUseInfoKernel(F); PropagateImplicits(F, M, implicits); // for OCL/L0 RT we should unconditionally add // implicit PRIVATE_BASE argument which is not supported on CM RT if (!implicits.empty() || !IsCmRT) { ProcessKernel(F); changed |= true; } } } } for (ImplicitUseInfo *Obj : ImplicitsInfoObjs) delete Obj; return changed; } // Replace the given instruction with a load from a global void CMImpParam::replaceWithGlobal(CallInst *CI, unsigned IID) { GlobalVariable *GV = getIIDGlobal(CI->getParent()->getParent(), IID); LoadInst *Load = new LoadInst(GV, GV->getName() + ".val", CI); CI->replaceAllUsesWith(Load); } // For each function, see if it uses an intrinsic that in turn requires an // implicit kernel argument // (such as llvm.genx.local.size) bool CMImpParam::AnalyzeImplicitUse(Module &M) { bool changed = false; for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { Function *Fn = &*I; LLVM_DEBUG(dbgs() << "AnalyzeImplicitUse visiting " << Fn->getName() << "\n"); bool implicitUse = false; SmallVector<CallInst *, 8> ToErase; // FIXME I think this should scan function declarations to find the implicit // arg intrinsics, then scan their uses, instead of scanning the whole code // to find calls to them. for (inst_iterator II = inst_begin(Fn), IE = inst_end(Fn); II != IE; ++II) { Instruction *Inst = &*II; if (CallInst *CI = dyn_cast<CallInst>(Inst)) { if (Function *Callee = CI->getCalledFunction()) { auto IID = GenXIntrinsic::getAnyIntrinsicID(Callee); if (GenXIntrinsic::isAnyNonTrivialIntrinsic(IID)) { switch (IID) { case GenXIntrinsic::genx_local_size: case GenXIntrinsic::genx_local_id: case GenXIntrinsic::genx_local_id16: case GenXIntrinsic::genx_group_count: case GenXIntrinsic::genx_get_scoreboard_deltas: case GenXIntrinsic::genx_get_scoreboard_bti: case GenXIntrinsic::genx_get_scoreboard_depcnt: case GenXIntrinsic::genx_local_id_x: case GenXIntrinsic::genx_local_id_y: case GenXIntrinsic::genx_local_id_z: case GenXIntrinsic::genx_group_or_local_size: case GenXIntrinsic::genx_print_buffer: LLVM_DEBUG(dbgs() << "AnalyzeImplicitUse found " << GenXIntrinsic::getGenXName((GenXIntrinsic::ID)IID, None)); addImplicit(Fn, IID); implicitUse = true; // Replace the intrinsic with a load of a global at this point replaceWithGlobal(CI, IID); ToErase.push_back(CI); changed = true; break; default: // Ignore (default added to prevent compiler warnings) break; } } } } } for (auto CI : ToErase) CI->eraseFromParent(); // Mark this function as containing an implicit use intrinsic if (implicitUse) ContainImplicit.insert(Fn); } return changed; } // Convert to implicit thread payload related intrinsics. bool CMImpParam::ConvertToOCLPayload(Module &M) { // Check if this kernel is compiled for OpenCL runtime. bool DoConversion = false; if (NamedMDNode *Named = M.getNamedMetadata(genx::FunctionMD::GenXKernels)) { for (unsigned I = 0, E = Named->getNumOperands(); I != E; ++I) { MDNode *Node = Named->getOperand(I); auto F = dyn_cast_or_null<Function>( getValue(Node->getOperand(genx::KernelMDOp::FunctionRef))); if (F && (F->hasFnAttribute(genx::FunctionMD::OCLRuntime) || !IsCmRT)) { DoConversion = true; break; } } } if (!DoConversion) return false; bool Changed = false; auto getFn = [=, &M](unsigned ID, Type *Ty) { return M.getFunction(GenXIntrinsic::getAnyName(ID, Ty)); }; // Convert genx_local_id -> zext(genx_local_id16) Type *Ty32 = VectorType::get(Type::getInt32Ty(M.getContext()), 3); Type *Ty16 = VectorType::get(Type::getInt16Ty(M.getContext()), 3); if (auto LIDFn = getFn(GenXIntrinsic::genx_local_id, Ty32)) { Function *LID16 = GenXIntrinsic::getGenXDeclaration( &M, GenXIntrinsic::genx_local_id16, Ty16); for (auto UI = LIDFn->user_begin(); UI != LIDFn->user_end();) { auto UInst = dyn_cast<Instruction>(*UI++); if (UInst) { IRBuilder<> Builder(UInst); Value *Val = Builder.CreateCall(LID16); Val = Builder.CreateZExt(Val, Ty32); UInst->replaceAllUsesWith(Val); UInst->eraseFromParent(); Changed = true; } } } return Changed; } // Merge implicit uses from the supplied function with implicit set passed in void CMImpParam::MergeImplicits(ImplicitUseInfo &implicits, Function *F) { assert(ImplicitsInfo.count(F) && "Function not found in implicits info map"); auto IInfo = ImplicitsInfo[F]; implicits.merge(*IInfo); } // Determine if the named function uses any functions tagged with implicit use // in the call-graph void CMImpParam::PropagateImplicits(Function *F, Module &M, ImplicitUseInfo &implicits) { // Traverse the call graph from the Kernel to determine what implicits are // used CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); // If this node has already been processed then return immediately if (AlreadyVisited.count(F)) return; // Add this node to the already visited list AlreadyVisited.insert(F); // Start the traversal CallGraphNode *N = CG[F]; // Inspect all children (recursive) for (auto Children : *N) { auto Func = Children.second->getFunction(); // Does this function have implicit arg use? if (ContainImplicit.count(Func)) { // Yes - add the implicits it contains to the set so far MergeImplicits(implicits, Func); } // Also recursively process children of this node PropagateImplicits(Func, M, implicits); } } // Process a kernel - loads from a global (and the globals) have already been // added if required elsewhere (in doInitialization) // We've already determined that this is a kernel and that it requires some // implicit arguments adding CallGraphNode *CMImpParam::ProcessKernel(Function *F) { LLVMContext &Context = F->getContext(); assert(Kernels.count(F) && "ProcessKernel invoked on non-kernel CallGraphNode"); AttributeList AttrVec; const AttributeList &PAL = F->getAttributes(); // Determine the new argument list SmallVector<Type *, 8> ArgTys; // First transfer all the explicit arguments from the old kernel unsigned ArgIndex = 0; for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I, ++ArgIndex) { ArgTys.push_back(I->getType()); AttributeSet attrs = PAL.getParamAttributes(ArgIndex); if (attrs.hasAttributes()) { AttrBuilder B(attrs); AttrVec = AttrVec.addParamAttributes(Context, ArgIndex, B); } } bool UsesImplicits = KernelsInfo.count(F) > 0; // Now add all the implicit arguments if (UsesImplicits) { ImplicitUseInfo *IUI = KernelsInfo[F]; for (unsigned IID : IUI->getImplicits()) { ArgTys.push_back(getIntrinRetType(Context, IID)); // TODO: Might need to also add any attributes from the intrinsic at some // point } } if (!IsCmRT) { // PRIVATE_BASE arg ArgTys.push_back(Type::getInt64Ty(F->getContext())); } FunctionType *NFTy = FunctionType::get(F->getReturnType(), ArgTys, false); assert((NFTy != F->getFunctionType()) && "type out of sync, expect bool arguments)"); // Add any function attributes AttributeSet FnAttrs = PAL.getFnAttributes(); if (FnAttrs.hasAttributes()) { AttrBuilder B(FnAttrs); AttrVec = AttrVec.addAttributes(Context, AttributeList::FunctionIndex, B); } // Create new function body and insert into the module Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName()); NF->setAttributes(AttrVec); LLVM_DEBUG(dbgs() << "CMImpParam: Transforming to: " << *NF << "\n" << "From: " << *F); F->getParent()->getFunctionList().insert(F->getIterator(), NF); NF->takeName(F); NF->setSubprogram(F->getSubprogram()); // tranfer debug-info // Now to splice the body of the old function into the new function NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); // Loop over the argument list, transferring uses of the old arguments to the // new arguments, also tranferring over the names as well Function::arg_iterator I2 = NF->arg_begin(); for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I, ++I2) { I->replaceAllUsesWith(I2); I2->takeName(I); } // Get the insertion point ready for stores to globals Instruction &FirstI = *NF->getEntryBlock().begin(); llvm::SmallVector<uint32_t, 8> ImpKinds; if (UsesImplicits) { ImplicitUseInfo *IUI = KernelsInfo[F]; for (unsigned IID : IUI->getImplicits()) { // We known that for each IID implicit we've already added an arg // Rename the arg to something more meaningful here assert(I2 != NF->arg_end() && "fewer parameters for new function than expected"); I2->setName("__arg_" + GenXIntrinsic::getAnyName(IID, None)); // Also insert a new store at the start of the function to the global // variable used for this implicit argument intrinsic assert(GlobalsMap.count(IID) && "no global associated with this imp arg intrinsic"); new StoreInst(I2, GlobalsMap[IID], &FirstI); // Prepare the kinds that will go into the metadata ImpKinds.push_back(MapToKind(IID)); ++I2; } } if (!IsCmRT) { I2->setName("privBase"); ImpKinds.push_back(genx::KernelMetadata::AK_NORMAL | genx::KernelMetadata::IMP_OCL_PRIVATE_BASE); } CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF); if (F->hasDLLExportStorageClass()) NF->setDLLStorageClass(F->getDLLStorageClass()); // Scan the CM kernel metadata and replace with NF if (NamedMDNode *Named = CG.getModule().getNamedMetadata(genx::FunctionMD::GenXKernels)) { for (unsigned I = 0, E = Named->getNumOperands(); I != E; ++I) { MDNode *Node = Named->getOperand(I); if (auto VM = dyn_cast_or_null<ValueAsMetadata>( Node->getOperand(genx::KernelMDOp::FunctionRef))) { if (F == VM->getValue()) { Node->replaceOperandWith(genx::KernelMDOp::FunctionRef, ValueAsMetadata::get(NF)); llvm::SmallVector<llvm::Metadata *, 8> ArgKinds; // Create a new MDNode of Kinds // First add all the current Kinds for explicit operands MDNode *TypeNode = dyn_cast<MDNode>(Node->getOperand(genx::KernelMDOp::ArgKinds)); assert(TypeNode); for (unsigned i = 0; i < TypeNode->getNumOperands(); ++i) ArgKinds.push_back(TypeNode->getOperand(i)); for (uint32_t Kind : ImpKinds) ArgKinds.push_back(ValueAsMetadata::getConstant( ConstantInt::get(Type::getInt32Ty(Context), Kind))); llvm::MDNode *Kinds = llvm::MDNode::get(Context, ArgKinds); Node->replaceOperandWith(genx::KernelMDOp::ArgKinds, Kinds); } } } } // Now that the old function is dead, delete it. If there is a dangling // reference to the CallGraphNode, just leave the dead function around NF_CGN->stealCalledFunctionsFrom(CG[F]); CallGraphNode *CGN = CG[F]; if (CGN->getNumReferences() == 0) delete CG.removeFunctionFromModule(CGN); else F->setLinkage(Function::ExternalLinkage); return NF_CGN; } void CMImpParam::print(raw_ostream &OS, const Module *M) const { OS << "Kernels : \n"; for (auto Func : Kernels) { OS.indent(4) << Func->getName() << "\n"; const ImplicitUseInfo *IUI = implicitUseInfoKernelExist(Func); if (IUI) IUI->print(OS, 8); } OS << "Functions with implicit arg intrinsics : \n"; for (auto FuncInfoPair : ImplicitsInfo) { OS.indent(4) << FuncInfoPair.first->getName() << "\n"; FuncInfoPair.second->print(OS, 8); } } char CMImpParam::ID = 0; INITIALIZE_PASS_BEGIN(CMImpParam, "cmimpparam", "Transformations required to support implicit arguments", false, false) INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) INITIALIZE_PASS_END(CMImpParam, "cmimpparam", "Transformations required to support implicit arguments", false, false) Pass *llvm::createCMImpParamPass(bool IsCMRT) { return new CMImpParam(IsCMRT); }
2b153e31e26bb12719fe63ed95f704895ef10839
51e75424f83c750683810707d1512ce5dbb197ba
/mdwEditor/mdcodeView.h
1a2b66f1d9ac0c7839c5ef046fdb6ada98165a13
[]
no_license
smile-ttxp/winsundown
4548552074a18d6b52bf4ff69381be11afede6eb
7646e2198fd0938fee1ed81f22776bf4c9394971
refs/heads/master
2021-05-27T23:32:30.967853
2013-08-09T06:41:39
2013-08-09T06:41:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
818
h
#pragma once // CmdcodeView view class CmdcodeView : public CEditView { DECLARE_DYNCREATE(CmdcodeView) CFont m_Font; BOOL m_ctrlQ; void insertMarkdownCode(TCHAR key); void openHelpDialog(); protected: CmdcodeView(); // protected constructor used by dynamic creation virtual ~CmdcodeView(); public: #ifdef _DEBUG virtual void AssertValid() const; #ifndef _WIN32_WCE virtual void Dump(CDumpContext& dc) const; #endif #endif protected: DECLARE_MESSAGE_MAP() public: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); protected: virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView); public: afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); // afx_msg void OnEditHelp(); };
0015af5baba97ff3dd13d40db95afe066d8204cf
c1546c6c202321cff5c6d29c8fef542e5dd27d40
/ParsePigg.cpp
58004c0bf093f13cae85995022d3054a06c437c7
[ "BSD-2-Clause" ]
permissive
toebes/PiggViewer
7c74fe2f30674576a6d747e6a2c89caa254d0b76
662742e5a12497b9862bc07c1166025badc07705
refs/heads/master
2020-05-26T02:25:00.219025
2019-05-22T17:34:59
2019-05-22T17:34:59
188,074,407
0
0
null
null
null
null
UTF-8
C++
false
false
18,507
cpp
// ParsePigg.cpp: implementation of the CParsePigg class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "PiggViewer.h" #include "ParsePigg.h" #include "PiggViewerDoc.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CParsePigg::CParsePigg() { m_mapExtensions[".bin"] = new CFileViewTypeBin(); m_mapExtensions[".ttf"] = new CFileViewTypeTTF(); m_mapExtensions[".TTF"] = new CFileViewTypeTTF(); m_mapExtensions[".ttc"] = new CFileViewTypeTTF(); m_mapExtensions[".geo"] = new CFileViewTypeGeo(); m_mapExtensions[".anim"] = new CFileViewTypeAnim(); m_mapExtensions[".txt"] = new CFileViewTypeTxt(); m_mapExtensions[".ogg"] = new CFileViewTypeOgg(); m_mapExtensions[".texture"] = new CFileViewTypeTexture(); m_mapExtensions[".tga"] = new CFileViewTypeTexture(); m_mapExtensions[".rcp"] = new CFileViewTypeCode(); m_mapExtensions[".vp"] = new CFileViewTypeCode(); m_mapExtensions[".fp"] = new CFileViewTypeCode(); m_mapExtensions[".ms"] = new CFileViewTypeCode(); m_mapExtensions[".tec"] = new CFileViewTypeCode(); m_mapExtensions[".mnu"] = new CFileViewTypeCode(); m_mapExtensions[".def"] = new CFileViewTypeCode(); m_mapExtensions[".types"] = new CFileViewTypeCode(); m_mapExtensions[".old"] = new CFileViewTypeCode(); m_mapExtensions[".ch"] = new CFileViewTypeCode(); m_mapExtensions[".ko"] = new CFileViewTypeCode(); } BOOL CParsePigg::ReadPigg(CArchive& ar) { m_filePigg = ar.GetFile(); CPiggViewerDoc *pDoc = (CPiggViewerDoc *)ar.m_pDocument; ULONGLONG dwSlotTableStart; if (!ReadData(&m_PiggHeader, sizeof(m_PiggHeader))) { return FALSE; } if ((m_PiggHeader.m_dwMarker != MARKER_PIGG_START) || (m_PiggHeader.m_usUnknown2 != UNKNOWN2_VALUE) || (m_PiggHeader.m_usUnknown3 != UNKNOWN3_VALUE) || (m_PiggHeader.m_usUnknown4 != UNKNOWN4_VALUE) || (m_PiggHeader.m_usUnknown5 != UNKNOWN5_VALUE)) { CString strOutput; strOutput.Format("Bad Header: U1=%08lx vs %08lx, U2=%04lx vs %04lx, U3=%04lx vs %04lx, U4=%04lx vs %04lx, U5=%04lx vs %04lx", m_PiggHeader.m_dwMarker, MARKER_PIGG_START, m_PiggHeader.m_usUnknown2, UNKNOWN2_VALUE, m_PiggHeader.m_usUnknown3, UNKNOWN3_VALUE, m_PiggHeader.m_usUnknown4, UNKNOWN4_VALUE, m_PiggHeader.m_usUnknown5, UNKNOWN5_VALUE); ::AfxMessageBox(strOutput, MB_OK); return FALSE; } // // Allocate space for all the directory entries // m_aDirectoryEntries.SetSize(m_PiggHeader.m_dwDirEntCount); // We got a header so now we need to read the data for(unsigned int nDirEnt = 0; nDirEnt < m_PiggHeader.m_dwDirEntCount; nDirEnt++) { PiggDirectoryEntry *pde = &m_aDirectoryEntries[nDirEnt]; if (!ReadData(&m_aDirectoryEntries[nDirEnt], sizeof(PiggDirectoryEntry))) { return FALSE; } } // // Now we need to read in the string table // if (!ReadData(&m_PiggStringTable, sizeof(m_PiggStringTable))) { return FALSE; } if (m_PiggStringTable.m_dwMarker != MARKER_STRING_TABLE) { CString strOutput; strOutput.Format("Bad String Header: %08lx vs %08lx", m_PiggStringTable.m_dwMarker, MARKER_STRING_TABLE); ::AfxMessageBox(strOutput, MB_OK); return FALSE; } m_aStrings.SetSize(m_PiggStringTable.m_dwStringCount); // // Figure out where the SlotTable will start at // dwSlotTableStart = m_filePigg->GetPosition() + m_PiggStringTable.m_dwLength; // // Read in each of the strings // for(unsigned int nStringEnt = 0; nStringEnt < m_PiggStringTable.m_dwStringCount; nStringEnt++) { PiggSlotLength slotLength; LPTSTR lpstrString; if (!ReadData(&slotLength, sizeof(slotLength))) { return FALSE; } lpstrString = m_aStrings[nStringEnt].GetBuffer(slotLength.m_dwEntryLength); if (!ReadData(lpstrString, slotLength.m_dwEntryLength)) { return FALSE; } m_aStrings[nStringEnt].ReleaseBuffer(-1); } // // Seek to the start of the SlotTable // m_filePigg->Seek(dwSlotTableStart, CFile::begin); // // Now we read in the information on the Slot Table // if (!ReadData(&m_PiggSlotTable, sizeof(m_PiggSlotTable))) { return FALSE; } if (m_PiggSlotTable.m_dwMarker != MARKER_SLOT_TABLE) { CString strOutput; strOutput.Format("Bad String Header: %08lx vs %08lx", m_PiggSlotTable.m_dwMarker, MARKER_SLOT_TABLE); ::AfxMessageBox(strOutput, MB_OK); return FALSE; } m_aSlotEntries.SetSize(m_PiggSlotTable.m_dwEntryCount); // // Now read in each entry from the table // for(unsigned int nSlotEnt = 0; nSlotEnt < m_PiggSlotTable.m_dwEntryCount; nSlotEnt++) { PiggSlotLength slotLength; if (!ReadData(&slotLength, sizeof(slotLength))) { return FALSE; } if (slotLength.m_dwEntryLength != 0x74) { // // We need to decompress the data.. but for now we just read the data in // BOOL rc; PiggCompressedSlotEntry *pCompressedSlotSource; PiggCompressedSlotEntry *pCompressedSlotDest; pCompressedSlotSource = (PiggCompressedSlotEntry *)new char[slotLength.m_dwEntryLength]; if (!ReadData(pCompressedSlotSource, slotLength.m_dwEntryLength)) { delete pCompressedSlotSource; return FALSE; } if (slotLength.m_dwEntryLength == pCompressedSlotSource->m_dwLength) { pCompressedSlotDest = (PiggCompressedSlotEntry *)new char[slotLength.m_dwEntryLength + sizeof(PiggCompressedSlotEntry) - sizeof(PiggUnCompressedSlotEntry)]; m_aSlotEntries[nSlotEnt] = (PiggSlotEntry *)pCompressedSlotDest; pCompressedSlotDest->m_dwLength = pCompressedSlotSource->m_dwLength; pCompressedSlotDest->m_dwUncompressedSize = pCompressedSlotSource->m_dwLength; memcpy(pCompressedSlotDest->m_aucData, &pCompressedSlotSource->m_dwUncompressedSize, slotLength.m_dwEntryLength-sizeof(PiggUnCompressedSlotEntry)); } else { pCompressedSlotDest = (PiggCompressedSlotEntry *)new char[sizeof(PiggCompressedSlotEntry) + pCompressedSlotSource->m_dwUncompressedSize]; m_aSlotEntries[nSlotEnt] = (PiggSlotEntry *)pCompressedSlotDest; pCompressedSlotDest->m_dwLength = pCompressedSlotSource->m_dwLength; pCompressedSlotDest->m_dwUncompressedSize = pCompressedSlotSource->m_dwUncompressedSize; rc = pDoc->UnCompress((BYTE *)pCompressedSlotDest->m_aucData, pCompressedSlotDest->m_dwUncompressedSize, pCompressedSlotSource->m_aucData, pCompressedSlotSource->m_dwLength); } delete pCompressedSlotSource; } else { PiggSlotEntry *piggSlotEntry = NULL; piggSlotEntry = (PiggSlotEntry *)new char[slotLength.m_dwEntryLength]; m_aSlotEntries[nSlotEnt] = piggSlotEntry; if (!ReadData(piggSlotEntry, slotLength.m_dwEntryLength)) { return FALSE; } } } return TRUE; } CParsePigg::~CParsePigg() { for(int i = 0; i < m_aSlotEntries.GetSize(); i++) { delete m_aSlotEntries[i]; } // // We need to clean out all of the extensions // CMapStringToOb map; POSITION pos; CString key; CFileViewType* pFileViewType; for( pos = m_mapExtensions.GetStartPosition(); pos != NULL; ) { m_mapExtensions.GetNextAssoc( pos, key, (void*&)pFileViewType ); delete pFileViewType; m_mapExtensions.RemoveKey(key); } } //Using CString::FormatV(), you can write functions like the following: void CParsePigg::WriteOutput(LPCTSTR pstrFormat, ...) { CString strOutput; // format and write the data we were given va_list args; va_start(args, pstrFormat); strOutput.FormatV(pstrFormat, args); m_fileOutput.WriteString(strOutput); } void CParsePigg::DumpPigg(CString strOutfile) { m_fileOutput.Open(strOutfile, CFile::modeCreate |CFile::modeWrite|CFile::typeText); CString strOutput; // // Dump out the header // WriteOutput("%d Directory entries\n", m_PiggHeader.m_dwDirEntCount); for(UINT nDirEntry = 0; nDirEntry < m_PiggHeader.m_dwDirEntCount; nDirEntry++) { CTime timeEntry((time_t)m_aDirectoryEntries[nDirEntry].m_dwDateStamp); WriteOutput("\n %3d: Flags=%08lx Date=%s String=%d Slot=%d Pos=%08lx Length=%08lx\n", nDirEntry, m_aDirectoryEntries[nDirEntry].m_dwFileSize, timeEntry.Format("%d-%b-%Y %I:%M%p"), m_aDirectoryEntries[nDirEntry].m_dwStringNum, m_aDirectoryEntries[nDirEntry].m_dwIndex, m_aDirectoryEntries[nDirEntry].m_dwFileStart, m_aDirectoryEntries[nDirEntry].m_dwCompressedSize); WriteOutput(" Key= %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", m_aDirectoryEntries[nDirEntry].m_ausMD5[ 0], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 1], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 2], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 3], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 4], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 5], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 6], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 7], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 8], m_aDirectoryEntries[nDirEntry].m_ausMD5[ 9], m_aDirectoryEntries[nDirEntry].m_ausMD5[10], m_aDirectoryEntries[nDirEntry].m_ausMD5[11], m_aDirectoryEntries[nDirEntry].m_ausMD5[12], m_aDirectoryEntries[nDirEntry].m_ausMD5[13], m_aDirectoryEntries[nDirEntry].m_ausMD5[14], m_aDirectoryEntries[nDirEntry].m_ausMD5[15]); if (m_aDirectoryEntries[nDirEntry].m_dwStringNum < (DWORD)(m_aStrings.GetSize())) { WriteOutput(" Str:%s\n", m_aStrings[m_aDirectoryEntries[nDirEntry].m_dwStringNum]); } if (m_aDirectoryEntries[nDirEntry].m_dwIndex < (DWORD)(m_aSlotEntries.GetSize())) { PiggSlotEntry *piggSlotEntry = m_aSlotEntries[m_aDirectoryEntries[nDirEntry].m_dwIndex]; WriteOutput(" Slot:%s\n", piggSlotEntry->m_ausTitle); WriteOutput(" Len=%d Ext=%c%c%c%c U8=%08lx U9=%08lx U10=%08lx U11=%08lx U12=%08lx U13=%08lx\n", piggSlotEntry->m_dwLength, (isprint(piggSlotEntry->m_ausExtension[0]) ? piggSlotEntry->m_ausExtension[0] : '.'), (isprint(piggSlotEntry->m_ausExtension[1]) ? piggSlotEntry->m_ausExtension[1] : '.'), (isprint(piggSlotEntry->m_ausExtension[2]) ? piggSlotEntry->m_ausExtension[2] : '.'), (isprint(piggSlotEntry->m_ausExtension[3]) ? piggSlotEntry->m_ausExtension[3] : '.'), piggSlotEntry->m_dwUnknown8, piggSlotEntry->m_dwWidth, piggSlotEntry->m_dwHeight, piggSlotEntry->m_dwUnknown11, piggSlotEntry->m_dwUnknown12, piggSlotEntry->m_dwUnknown13); } } // // Now dump out all the sections // for(nDirEntry = 0; nDirEntry < m_PiggHeader.m_dwDirEntCount; nDirEntry++) { m_filePigg->Seek(m_aDirectoryEntries[nDirEntry].m_dwFileStart, CFile::begin); DWORD dwLength = m_aDirectoryEntries[nDirEntry].m_dwCompressedSize; if (dwLength == 0) { dwLength = m_aDirectoryEntries[nDirEntry].m_dwFileSize; } if (dwLength == 0) { continue; } CString strTitle; if (m_aDirectoryEntries[nDirEntry].m_dwStringNum < (DWORD)(m_aStrings.GetSize())) { strTitle = m_aStrings[m_aDirectoryEntries[nDirEntry].m_dwStringNum]; } WriteOutput("\n====Section %d Start=%08lx Len=%08lx (%d) %s====\n", nDirEntry, m_aDirectoryEntries[nDirEntry].m_dwFileStart, dwLength, dwLength, strTitle); for(UINT dwPos = 0; dwPos < dwLength; dwPos += 16) { int nRemain = dwLength-dwPos; int nSpot = dwPos % 16; char aucData[16]; char aucAscii[16+(16/4)+1]; char aucHex[(3*16)+(16/4)+1]; if (nRemain > 16) { nRemain = 16; } if (!ReadData(aucData, nRemain)) { return; } memset(aucHex,' ', sizeof(aucHex)); aucHex[sizeof(aucHex)-1] = 0; memset(aucAscii,' ', sizeof(aucAscii)); aucAscii[sizeof(aucAscii)-1] = 0; for(int nPos = 0; nPos < nRemain; nPos++) { int nDest = (nPos*3) + (nPos/4); int c = aucData[nPos]; aucAscii[nPos + nPos/4] = isprint(c) ? c : '.'; aucHex[nDest] = "0123456789ABCDEF"[(c>>4)&0xf]; aucHex[nDest+1] = "0123456789ABCDEF"[(c )&0xf]; } WriteOutput(" %08lx: %s |%s|\n", dwPos, aucHex, aucAscii); } } } BOOL CParsePigg::ReadData(void *pvData, UINT nLength) { UINT nReadLength; nReadLength = m_filePigg->Read(pvData, nLength); if (nReadLength < nLength) { CString strOutput; strOutput.Format("Only able to read %d bytes from %d expected", nReadLength, nLength); ::AfxMessageBox(strOutput, MB_OK); return FALSE; } return TRUE; } CString CParsePigg::GetDirectoryName(int nDirectoryEntry) { if ((nDirectoryEntry < 0) || (((DWORD)nDirectoryEntry) >= m_PiggHeader.m_dwDirEntCount)) { return ""; } return m_aStrings[m_aDirectoryEntries[nDirectoryEntry].m_dwStringNum]; } void CParsePigg::GetExternalInfo(ExternalInfo &externalInfo, int nDirectoryEntry) { int nExtPos; CString strExtension; externalInfo.m_strName = ""; externalInfo.m_strTitle = ""; externalInfo.m_dwFileSize = 0; externalInfo.m_dwDateStamp = 0; externalInfo.m_dwFileStart = 0; externalInfo.m_dwUnknown6 = 0; externalInfo.m_dwIndex = 0; memset(externalInfo.m_ausMD5, 0, sizeof(externalInfo.m_ausMD5)); externalInfo.m_dwCompressedSize = 0; externalInfo.m_dwSlotLength = 0; externalInfo.m_dwUnknown8 = 0; externalInfo.m_dwWidth = 0; externalInfo.m_dwHeight = 0; externalInfo.m_dwUnknown11 = 0; externalInfo.m_dwUnknown12 = 0; externalInfo.m_dwUnknown13 = 0; externalInfo.m_dwSecondarySize = 0; externalInfo.m_pszSecondaryData = NULL; externalInfo.m_pFileViewType = &m_FileViewTypeDefault; memset(externalInfo.m_ausExtension, ' ', sizeof(externalInfo.m_ausExtension)); if ((nDirectoryEntry < 0) || (((DWORD)nDirectoryEntry) >= m_PiggHeader.m_dwDirEntCount)) { return; } PiggDirectoryEntry *pde = &m_aDirectoryEntries[nDirectoryEntry]; externalInfo.m_dwCompressedSize = m_aDirectoryEntries[nDirectoryEntry].m_dwCompressedSize; externalInfo.m_strName = m_aStrings[m_aDirectoryEntries[nDirectoryEntry].m_dwStringNum]; externalInfo.m_dwFileSize = m_aDirectoryEntries[nDirectoryEntry].m_dwFileSize; externalInfo.m_dwDateStamp = m_aDirectoryEntries[nDirectoryEntry].m_dwDateStamp; externalInfo.m_dwFileStart = m_aDirectoryEntries[nDirectoryEntry].m_dwFileStart; externalInfo.m_dwUnknown6 = m_aDirectoryEntries[nDirectoryEntry].m_dwUnknown6; externalInfo.m_dwIndex = m_aDirectoryEntries[nDirectoryEntry].m_dwIndex; memcpy(externalInfo.m_ausMD5, m_aDirectoryEntries[nDirectoryEntry].m_ausMD5, sizeof(externalInfo.m_ausMD5)); if (m_aDirectoryEntries[nDirectoryEntry].m_dwIndex < (DWORD)(m_aSlotEntries.GetSize())) { PiggSlotEntry *piggSlotEntry = m_aSlotEntries[m_aDirectoryEntries[nDirectoryEntry].m_dwIndex]; if (piggSlotEntry->m_dwLength == 0x70) { externalInfo.m_dwSlotLength = piggSlotEntry->m_dwLength; externalInfo.m_dwUnknown8 = piggSlotEntry->m_dwUnknown8; externalInfo.m_dwWidth = piggSlotEntry->m_dwWidth; externalInfo.m_dwHeight = piggSlotEntry->m_dwHeight; externalInfo.m_dwUnknown11 = piggSlotEntry->m_dwUnknown11; externalInfo.m_dwUnknown12 = piggSlotEntry->m_dwUnknown12; externalInfo.m_dwUnknown13 = piggSlotEntry->m_dwUnknown13; memcpy(externalInfo.m_ausExtension, piggSlotEntry->m_ausExtension, sizeof(externalInfo.m_ausExtension)); externalInfo.m_strTitle = piggSlotEntry->m_ausTitle; } else { externalInfo.m_dwIndex = 0xffffffff; PiggCompressedSlotEntry *pCompressedSlotEntry = (PiggCompressedSlotEntry *)piggSlotEntry; externalInfo.m_dwSecondarySize = pCompressedSlotEntry->m_dwUncompressedSize; externalInfo.m_pszSecondaryData = (const char *)pCompressedSlotEntry->m_aucData; } } // // Determine the file type based on the extension // nExtPos = externalInfo.m_strName.ReverseFind('.'); if (nExtPos == -1) { strExtension = externalInfo.m_strName; } else { strExtension = externalInfo.m_strName.Mid(nExtPos); } externalInfo.m_pFileViewType = (CFileViewType*)m_mapExtensions[strExtension]; if (externalInfo.m_pFileViewType == NULL) { AfxMessageBox(strExtension, MB_OK); externalInfo.m_pFileViewType = &m_FileViewTypeDefault; } }
1a3fe87e21a435577b5b4a6073e29591fdcb3482
dceff34eaceed8f7a52ea908958645104167e3e1
/src/backup-n3l2.0/20170704/beam/BeamExtractor.cpp
d2fcc0552a94936b71b5ca51795047da764a6746
[]
no_license
zhangmeishan/NNRelationExtraction
a100acc0f6c9d5fd0db7686249b647a21ae908b2
8efd8173b2503bc75274b2238b2392476a86a8e9
refs/heads/master
2021-01-11T19:48:25.552293
2017-07-30T13:23:56
2017-07-30T13:23:56
79,401,948
14
2
null
null
null
null
UTF-8
C++
false
false
18,171
cpp
#include "BeamExtractor.h" #include <set> #include "Argument_helper.h" Extractor::Extractor(size_t memsize) : m_driver(memsize) { srand(0); } Extractor::~Extractor() { } int Extractor::createAlphabet(vector<Instance> &vecInsts) { cout << "Creating Alphabet..." << endl; int totalInstance = vecInsts.size(); unordered_map<string, int> word_stat; unordered_map<string, int> tag_stat; unordered_map<string, int> dep_stat; unordered_map<string, int> ner_stat; unordered_map<string, int> rel_stat; unordered_map<string, int> char_stat; string root = "ROOT"; assert(totalInstance > 0); for (int numInstance = 0; numInstance < vecInsts.size(); numInstance++) { const Instance &instance = vecInsts[numInstance]; for (int idx = 0; idx < instance.words.size(); idx++) { string curWord = normalize_to_lower(instance.words[idx]); m_driver._hyperparams.word_stat[curWord]++; word_stat[curWord]++; tag_stat[instance.tags[idx]]++; dep_stat[instance.labels[idx]]++; if (instance.heads[idx] == -1) root = instance.labels[idx]; string curner = instance.result.ners[idx]; if (is_start_label(curner)) { ner_stat[cleanLabel(curner)]++; } for (int idy = 0; idy < instance.chars[idx].size(); idy++) { char_stat[instance.chars[idx][idy]]++; } } for (int idx = 0; idx < instance.result.relations.size(); idx++) { for (int idy = 0; idy < instance.result.relations[idx].size(); idy++) { if (instance.result.relations[idx][idy] != "noRel") { rel_stat[instance.result.relations[idx][idy]]++; m_driver._hyperparams.rel_dir[instance.result.relations[idx][idy]].insert(instance.result.directions[idx][idy]); } } } } if (m_options.wordEmbFile != "") { m_driver._modelparams.embeded_ext_words.initial(m_options.wordEmbFile); } else { std::cerr << "missing embedding file! \n"; exit(0); } word_stat[unknownkey] = m_options.wordCutOff + 1; m_driver._modelparams.embeded_words.initial(word_stat, m_options.wordCutOff); m_driver._modelparams.embeded_tags.initial(tag_stat, 0); //m_driver._modelparams.embeded_labels.initial(dep_stat, 0); char_stat[unknownkey] = 1; m_driver._modelparams.embeded_chars.initial(char_stat, 0); // TODO: m_driver._hyperparams.ner_labels.clear(); m_driver._hyperparams.ner_labels.from_string("o"); static unordered_map<string, int>::const_iterator iter; for (iter = ner_stat.begin(); iter != ner_stat.end(); iter++) { m_driver._hyperparams.ner_labels.from_string("b-" + iter->first); m_driver._hyperparams.ner_labels.from_string("m-" + iter->first); m_driver._hyperparams.ner_labels.from_string("e-" + iter->first); m_driver._hyperparams.ner_labels.from_string("s-" + iter->first); } m_driver._hyperparams.ner_labels.set_fixed_flag(true); int ner_count = m_driver._hyperparams.ner_labels.size(); m_driver._hyperparams.rel_labels.clear(); m_driver._hyperparams.rel_labels.from_string("noRel"); m_driver._hyperparams.rel_dir["noRel"].insert(1); for (iter = rel_stat.begin(); iter != rel_stat.end(); iter++) { m_driver._hyperparams.rel_labels.from_string(iter->first); } m_driver._hyperparams.rel_labels.set_fixed_flag(true); int rel_count = m_driver._hyperparams.rel_labels.size(); m_driver._hyperparams.action_num = ner_count > 2 * rel_count ? ner_count : 2 * rel_count; unordered_map<string, int> action_stat; vector<CStateItem> state(m_driver._hyperparams.maxlength + 1); CResult output; CAction answer; Metric ner, rel, rel_punc; ner.reset(); rel.reset(); rel_punc.reset(); int stepNum; for (int numInstance = 0; numInstance < totalInstance; numInstance++) { Instance &instance = vecInsts[numInstance]; stepNum = 0; state[stepNum].clear(); state[stepNum].setInput(instance); while (!state[stepNum].IsTerminated()) { state[stepNum].getGoldAction(m_driver._hyperparams, instance.result, answer); // std::cout << answer.str(&(m_driver._hyperparams)) << " "; action_stat[answer.str(&(m_driver._hyperparams))]++; // TODO: state? answer(gold action)? state[stepNum].prepare(&m_driver._hyperparams, NULL, NULL); state[stepNum].move(&(state[stepNum + 1]), answer); stepNum++; } // state[stepNum].getResults(output, m_driver._hyperparams); // std::cout << endl; // std::cout << output.str(); //// instance.evaluate(output, ner, rel); //TODO: 不唯一? //FIXME: if (!ner.bIdentical() || !rel.bIdentical()) { std::cout << "error state conversion!" << std::endl; exit(0); } if ((numInstance + 1) % m_options.verboseIter == 0) { std::cout << numInstance + 1 << " "; if ((numInstance + 1) % (40 * m_options.verboseIter) == 0) std::cout << std::endl; std::cout.flush(); } if (m_options.maxInstance > 0 && numInstance == m_options.maxInstance) break; } action_stat[nullkey] = 1; m_driver._modelparams.embeded_actions.initial(action_stat, 0); return 0; } void Extractor::getGoldActions(vector<Instance>& vecInsts, vector<vector<CAction> >& vecActions) { vecActions.clear(); static vector<CAction> acs; static bool bFindGold; Metric ner, rel, rel_punc; vector<CStateItem> state(m_driver._hyperparams.maxlength + 1); CResult output; CAction answer; ner.reset(); rel.reset(); rel_punc.reset(); static int numInstance, stepNum; vecActions.resize(vecInsts.size()); for (numInstance = 0; numInstance < vecInsts.size(); numInstance++) { Instance &instance = vecInsts[numInstance]; stepNum = 0; state[stepNum].clear(); state[stepNum].setInput(instance); while (!state[stepNum].IsTerminated()) { state[stepNum].getGoldAction(m_driver._hyperparams, instance.result, answer); // std::cout << answer.str(&(m_driver._hyperparams)) << " "; state[stepNum].getCandidateActions(acs, &m_driver._hyperparams, &m_driver._modelparams); bFindGold = false; for (int idz = 0; idz < acs.size(); idz++) { if (acs[idz] == answer) { bFindGold = true; break; } } if (!bFindGold) { state[stepNum].getCandidateActions(acs, &m_driver._hyperparams, &m_driver._modelparams); std::cout << "gold action has been filtered" << std::endl; exit(0); } vecActions[numInstance].push_back(answer); state[stepNum].move(&state[stepNum + 1], answer); stepNum++; } state[stepNum].getResults(output, m_driver._hyperparams); //FIXME: 内存错误 // std::cout << endl; // std::cout << output.str(); instance.evaluate(output, ner, rel); if (!ner.bIdentical() || !rel.bIdentical()) { std::cout << "error state conversion!" << std::endl; exit(0); } if ((numInstance + 1) % m_options.verboseIter == 0) { cout << numInstance + 1 << " "; if ((numInstance + 1) % (40 * m_options.verboseIter) == 0) cout << std::endl; cout.flush(); } if (m_options.maxInstance > 0 && numInstance == m_options.maxInstance) break; } } void Extractor::train(const string &trainFile, const string &devFile, const string &testFile, const string &modelFile, const string &optionFile) { if (optionFile != "") m_options.load(optionFile); m_options.showOptions(); vector<Instance> trainInsts, devInsts, testInsts; m_pipe.readInstances(trainFile, trainInsts, m_options.maxInstance); if (devFile != "") m_pipe.readInstances(devFile, devInsts, m_options.maxInstance); if (testFile != "") m_pipe.readInstances(testFile, testInsts, m_options.maxInstance); vector<vector<Instance> > otherInsts(m_options.testFiles.size()); for (int idx = 0; idx < m_options.testFiles.size(); idx++) { m_pipe.readInstances(m_options.testFiles[idx], otherInsts[idx], m_options.maxInstance); } createAlphabet(trainInsts); m_driver._modelparams.word_ext_table.initial(&m_driver._modelparams.embeded_ext_words, m_options.wordEmbFile, false, m_options.wordEmbNormalize); m_options.wordExtEmbSize = m_driver._modelparams.word_ext_table.nDim; m_driver._modelparams.word_table.initial(&m_driver._modelparams.embeded_words, m_options.wordEmbSize, true); m_driver._modelparams.tag_table.initial(&m_driver._modelparams.embeded_tags, m_options.tagEmbSize, true); m_driver._modelparams.action_table.initial(&m_driver._modelparams.embeded_actions, m_options.actionEmbSize, true); //m_driver._modelparams.label_table.initial(&m_driver._modelparams.embeded_labels, m_options.labelEmbSize, true); m_driver._modelparams.char_table.initial(&m_driver._modelparams.embeded_chars, m_options.charEmbSize, true); m_driver._hyperparams.setRequared(m_options); m_driver.initial(); vector<vector<CAction> > trainInstGoldactions, devInstGoldactions, testInstGoldactions; getGoldActions(trainInsts, trainInstGoldactions); //getGoldActions(devInsts, devInstGoldactions); //getGoldActions(testInsts, testInstGoldactions); double bestFmeasure = -1; int inputSize = trainInsts.size(); std::vector<int> indexes; for (int i = 0; i < inputSize; ++i) indexes.push_back(i); static Metric eval; static Metric dev_ner, dev_rel; static Metric test_ner, test_rel; int maxIter = m_options.maxIter; int oneIterMaxRound = (inputSize + m_options.batchSize - 1) / m_options.batchSize; std::cout << "\nmaxIter = " << maxIter << std::endl; int devNum = devInsts.size(), testNum = testInsts.size(); static vector<CResult > decodeInstResults; static CResult curDecodeInst; static bool bCurIterBetter; static vector<Instance> subInstances; static vector<vector<CAction> > subInstGoldActions; NRVec<bool> decays; decays.resize(maxIter); decays = false; //decays[5] = true; decays[15] = true; decays[25] = true; for (int iter = 0; iter < maxIter; ++iter) { std::cout << "##### Iteration " << iter << std::endl; srand(iter); random_shuffle(indexes.begin(), indexes.end()); std::cout << "random: " << indexes[0] << ", " << indexes[indexes.size() - 1] << std::endl; bool bEvaluate = false; eval.reset(); bEvaluate = true; for (int idy = 0; idy < inputSize; idy++) { subInstances.clear(); subInstGoldActions.clear(); subInstances.push_back(trainInsts[indexes[idy]]); subInstGoldActions.push_back(trainInstGoldactions[indexes[idy]]); double cost = m_driver.train(subInstances, subInstGoldActions, iter < m_options.maxNERIter); eval.overall_label_count += m_driver._eval.overall_label_count; eval.correct_label_count += m_driver._eval.correct_label_count; if ((idy + 1) % (m_options.verboseIter) == 0) { std::cout << "current: " << idy + 1 << ", Cost = " << cost << ", Correct(%) = " << eval.getAccuracy() << std::endl; } if (m_driver._batch >= m_options.batchSize) { m_driver.updateModel(); } } if (m_driver._batch > 0) { m_driver.updateModel(); } if (decays[iter]) { m_options.adaAlpha = 0.5 * m_options.adaAlpha; m_driver.setUpdateParameters(m_options.regParameter, m_options.adaAlpha, m_options.adaEps); } std::cout << "current: " << iter + 1 << ", Correct(%) = " << eval.getAccuracy() << std::endl; if (bEvaluate && devNum > 0) { clock_t time_start = clock(); std::cout << "Dev start." << std::endl; bCurIterBetter = false; if (!m_options.outBest.empty()) decodeInstResults.clear(); dev_ner.reset(); dev_rel.reset(); for (int idx = 0; idx < devInsts.size(); idx++) { predict(devInsts[idx], curDecodeInst); devInsts[idx].evaluate(curDecodeInst, dev_ner, dev_rel); if (!m_options.outBest.empty()) { decodeInstResults.push_back(curDecodeInst); } } std::cout << "Dev finished. Total time taken is: " << double(clock() - time_start) / CLOCKS_PER_SEC << std::endl; std::cout << "dev:" << std::endl; dev_ner.print(); dev_rel.print(); if (!m_options.outBest.empty() && dev_rel.getAccuracy() > bestFmeasure) { m_pipe.outputAllInstances(devFile + m_options.outBest, decodeInstResults); bCurIterBetter = true; } } if (testNum > 0) { clock_t time_start = clock(); std::cout << "Test start." << std::endl; if (!m_options.outBest.empty()) decodeInstResults.clear(); test_ner.reset(); test_rel.reset(); for (int idx = 0; idx < testInsts.size(); idx++) { predict(testInsts[idx], curDecodeInst); testInsts[idx].evaluate(curDecodeInst, test_ner, test_rel); if (bCurIterBetter && !m_options.outBest.empty()) { decodeInstResults.push_back(curDecodeInst); } } std::cout << "Test finished. Total time taken is: " << double(clock() - time_start) / CLOCKS_PER_SEC << std::endl; std::cout << "test:" << std::endl; test_ner.print(); test_rel.print(); if (!m_options.outBest.empty() && bCurIterBetter) { m_pipe.outputAllInstances(testFile + m_options.outBest, decodeInstResults); } } for (int idx = 0; idx < otherInsts.size(); idx++) { std::cout << "processing " << m_options.testFiles[idx] << std::endl; clock_t time_start = clock(); if (!m_options.outBest.empty()) decodeInstResults.clear(); test_ner.reset(); test_rel.reset(); for (int idy = 0; idy < otherInsts[idx].size(); idy++) { predict(otherInsts[idx][idy], curDecodeInst); otherInsts[idx][idy].evaluate(curDecodeInst, test_ner, test_rel); if (bCurIterBetter && !m_options.outBest.empty()) { decodeInstResults.push_back(curDecodeInst); } } std::cout << m_options.testFiles[idx] << " finished. Total time taken is: " << double(clock() - time_start) / CLOCKS_PER_SEC << std::endl; std::cout << "test:" << std::endl; test_ner.print(); test_rel.print(); if (!m_options.outBest.empty() && bCurIterBetter) { m_pipe.outputAllInstances(m_options.testFiles[idx] + m_options.outBest, decodeInstResults); } } if (m_options.saveIntermediate && dev_rel.getAccuracy() > bestFmeasure) { std::cout << "Exceeds best previous DIS of " << bestFmeasure << ". Saving model file.." << std::endl; bestFmeasure = dev_rel.getAccuracy(); writeModelFile(modelFile); } } } void Extractor::predict(Instance &input, CResult &output) { m_driver.decode(input, output); } void Extractor::test(const string &testFile, const string &outputFile, const string &modelFile) { } void Extractor::loadModelFile(const string &inputModelFile) { } void Extractor::writeModelFile(const string &outputModelFile) { } int main(int argc, char *argv[]) { std::string trainFile = "", devFile = "", testFile = "", modelFile = ""; std::string wordEmbFile = "", optionFile = ""; std::string outputFile = ""; bool bTrain = false; dsr::Argument_helper ah; int memsize = 0; ah.new_flag("l", "learn", "train or test", bTrain); ah.new_named_string("train", "trainCorpus", "named_string", "training corpus to train a model, must when training", trainFile); ah.new_named_string("dev", "devCorpus", "named_string", "development corpus to train a model, optional when training", devFile); ah.new_named_string("test", "testCorpus", "named_string", "testing corpus to train a model or input file to test a model, optional when training and must when testing", testFile); ah.new_named_string("model", "modelFile", "named_string", "model file, must when training and testing", modelFile); ah.new_named_string("word", "wordEmbFile", "named_string", "pretrained word embedding file to train a model, optional when training", wordEmbFile); ah.new_named_string("option", "optionFile", "named_string", "option file to train a model, optional when training", optionFile); ah.new_named_string("output", "outputFile", "named_string", "output file to test, must when testing", outputFile); ah.new_named_int("mem", "memsize", "named_int", "memory allocated for tensor nodes", memsize); ah.process(argc, argv); Extractor extractor(memsize); if (bTrain) { extractor.train(trainFile, devFile, testFile, modelFile, optionFile); } else { extractor.test(testFile, outputFile, modelFile); } //test(argv); //ah.write_values(std::cout); }
d1129d72352e09d797e118b6b52f76cad8d0d4fd
922add69f3ad1d6b844214c6185ff9353bbd873c
/muduo/examples/simple/echo/echo.cc
4f688659a82285c24938af51edad0b32498efec8
[]
no_license
NitefullWind/unet
c52dc6b4bad34c9df09f2cfbe291a42e85107ce6
a6f9f0e749e7ae1f99886cdc73f0c32a77ec74de
refs/heads/master
2023-05-12T06:42:47.849147
2019-05-07T11:33:39
2019-05-07T11:33:39
127,446,483
0
0
null
null
null
null
UTF-8
C++
false
false
938
cc
#include "echo.h" #include <muduo/base/Logging.h> #include <boost/bind.hpp> EchoServer::EchoServer(EventLoop* loop, const InetAddress &listenAddr) : server_(loop, listenAddr, "EchoServer") { server_.setConnectionCallback(boost::bind(&EchoServer::onConnection, this, _1)); server_.setMessageCallback(boost::bind(&EchoServer::onMessage, this, _1, _2, _3)); server_.setThreadNum(100); } void EchoServer::start() { server_.start(); } void EchoServer::onConnection(const TcpConnectionPtr &conn) { LOG_INFO << "EchoServer - " << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " is " << (conn->connected() ? "UP" : "DOWN"); } void EchoServer::onMessage(const TcpConnectionPtr &conn, Buffer* buf, Timestamp time) { muduo::string msg(buf->retrieveAllAsString()); LOG_INFO << conn->name() << " echo " << msg.size() << " bytes, " << "data received at " << time.toString(); conn->send(msg); }
bdcedbcffc05980d6aa40505a9fc69acb7070ccb
ca1a19ee719b6f1880706b0cf213134956fc753e
/src/easylink/utils/conditional/EqualityCompare.cpp
49d5343b2f00096139f3ea4cfbba5c01317293d4
[]
no_license
EasyLinks/RDBMSTool
4e959f7bba9804c68b42147698fbced902624627
96d1d9321e9d4ec899b09620ce4bfb25992227a3
refs/heads/master
2021-01-19T00:46:14.106444
2014-05-23T18:54:28
2014-05-23T18:54:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
#include "easylink/utils/conditional/EqualityCompare.h" namespace easylink { namespace utils { namespace conditional { EqualityCompare::EqualityCompare() { //ctor } EqualityCompare::~EqualityCompare() { //dtor } } // namespace conditional } // namespace utils } // namespace easylink
ed15a63ba49ca26e5952bcb88eafd9ca8a20f251
1997462d0233715f5aebb4e43733906a18dd4010
/Semester Project/game.h
09758014f9dbe64e7d3a2d1cbfbe6ed5f868fd4f
[]
no_license
nthoms9/NT-Semester_Project
422cfe0abe6709ee86af7d94383fa7828f1fecb5
1cb93fb9f8d6e2eb4789cc519de98984308d3f9f
refs/heads/master
2021-03-10T08:58:10.689472
2020-05-07T02:25:06
2020-05-07T02:25:06
246,440,881
0
0
null
null
null
null
UTF-8
C++
false
false
3,828
h
// This is the specification file for the game class. #ifndef GAME_H #define GAME_H // All other classes are included in this one. #include"grid.h" #include"block.h" #include"blockType1.h" #include"blockType2.h" #include"blockType3.h" #include"blockType4.h" #include"blockType5.h" #include"blockType6.h" #include"blockType7.h" #include "scoreBoard.h" using namespace std; // This class acts like the body of the game, it contains the game loop, the different boolean checks for movements, and // also ties together all of the game objects. class game { public: game(); // constructor ~game(); // deconstructor // Preconditions: The game object has been created. // Postconditions: The game loop is executed. void runGame(); // Preconditions: The game object has been created and the flow of control has entered the game loop, and the game can continue. // Postconditions: A block object is created and the block loop is executed while the space below the object is clear. // Then the block is deleted. The gameGrid object is updated when the block moves and stores the final position // of the block when the block loop exits. void runBlock(int); // Preconditions: The game object has been created and an block object has been created. // Postconditions: The grid object udpdates the postion of the block object, displays the result then restets the grid coordinates // to default values unless it is the end of the block loop. void updatePos(block* &); // Preconditions: The game object has been created and an block object has been created. // Postconditions: The block is dropped until it reaches the nearest surface. void instaDrop(block* &); // Preconditions: The game object has been created and an block object has been created. // Postconditions: The block is rotated one position in a clockwise direction. void rotate(block* &); // Preconditions: The game object has been created and an block object has been created. // Postconditions: The clearRowCheck is executed and if it returns true the grid method downshift is called and changes are made // to the score board. void clearRow(block*); // Preconditions: The game object has been created. // Postconditions: The grid and the score board are displayed to the screen. void display(); // Preconditions: The game object has been created and an block object has been created. // Postconditions: A bool value is returned true if the check is succesfull otherwise false is returned. bool downCheck(block*); // Preconditions: The game object has been created and an block object has been created. // Postconditions: A bool value is returned true if the check is succesfull otherwise false is returned. bool rightCheck(block*); // Preconditions: The game object has been created and an block object has been created. // Postconditions: A bool value is returned true if the check is succesfull otherwise false is returned. bool leftCheck(block*); // Preconditions: The game object has been created and an block object has been created. // Postconditions: A bool value is returned true if the check is succesfull otherwise false is returned. bool rotateCheck(block*); // Preconditions: The game object has been created and an block object has been created. // Postconditions: A bool value is returned true if the check is succesfull otherwise false is returned. bool fullRowCheck( int y); // Preconditions: The game object has been created and an block object has been created. // Postconditions: A bool value is returned true if the check is succesfull otherwise false is returned. bool endOfGame(int); private: grid gameGrid; //The grid object is created scoreBoard score; //The score board object is created. }; #endif
305f048c077a14b698cdf175d68a3b46389746c2
c26dad4ff553a9bc3e403e274e08ad74387feddc
/TUI.cpp
62e95f265fa34ebd33bb719a2202fabc8d45be6b
[]
no_license
linyunbb/tui
9133770216f77581ed250517aa87dc06210c4edd
511c1d6cce02eab54beff88a8298bc9d241e4192
refs/heads/master
2021-01-20T01:59:00.430584
2017-04-25T11:25:53
2017-04-25T11:25:53
89,352,789
1
0
null
null
null
null
UTF-8
C++
false
false
1,947
cpp
// TUI.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "TUI.h" #include "TUIDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTUIApp BEGIN_MESSAGE_MAP(CTUIApp, CWinApp) //{{AFX_MSG_MAP(CTUIApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTUIApp construction CTUIApp::CTUIApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CTUIApp object CTUIApp theApp; ///////////////////////////////////////////////////////////////////////////// // CTUIApp initialization BOOL CTUIApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif CTUIDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
[ "Yun Lin" ]
Yun Lin
1bccab01d2980fac69ff4af24e89d76a13338852
90d39aa2f36783b89a17e0687980b1139b6c71ce
/SPOJ/MTREE.cpp
e7fe11a739f6e6c299407efac239f0e7458b3820
[]
no_license
nims11/coding
634983b21ad98694ef9badf56ec8dfc950f33539
390d64aff1f0149e740629c64e1d00cd5fb59042
refs/heads/master
2021-03-22T08:15:29.770903
2018-05-28T23:27:37
2018-05-28T23:27:37
247,346,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,607
cpp
/* Nimesh Ghelani (nims11) */ #include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<map> #include<string> #include<vector> #include<queue> #include<cmath> #include<stack> #include<set> #include<utility> #define in_T int t;for(scanf("%d",&t);t--;) #define in_I(a) scanf("%d",&a) #define in_F(a) scanf("%lf",&a) #define in_L(a) scanf("%lld",&a) #define in_S(a) scanf("%s",a) #define newline printf("\n") #define MAX(a,b) a>b?a:b #define MIN(a,b) a<b?a:b #define SWAP(a,b) {int tmp=a;a=b;b=tmp;} #define P_I(a) printf("%d",a) using namespace std; vector<pair<int, int> > neigh[100001]; bool visited[100001]; int mod = 1000000007; pair<int, int> x; // MODULO OP pair<int, int> dfs(int u) { pair<int, int> ret = make_pair(0, 1); int tmp = 1; for(int i=0;i<neigh[u].size();i++) { int v = neigh[u][i].first; if(!visited[v]) { visited[v] = true; x = dfs(v); ret.first = (ret.first + x.first)%mod; x.second = (x.second*1LL*neigh[u][i].second)%mod; ret.first = (ret.first + (1LL*tmp*x.second)%mod)%mod; tmp = (tmp + x.second)%mod; ret.second = (ret.second + x.second)%mod; } } // cout<<u<<" "<<ret.first<<" "<<ret.second<<endl; return ret; } int main() { int n,a,b,c; in_I(n); for(int i=0;i<n-1;i++) { in_I(a);in_I(b);in_I(c); neigh[a].push_back(make_pair(b,c)); neigh[b].push_back(make_pair(a,c)); } visited[1] = true; printf("%d\n", dfs(1).first); }
80c47d4472069e281f256c8b56088041b62e7361
78fbbc80a394ed4128d886a3e2e8b6326a420d6f
/src/caffe/cc/core/cc_utils.cpp
c507fb6588a6d79e74226427ce7da0841dc734b3
[]
no_license
hfen-cn/CC4.0
274dba87994fd98423e5e6e4674b1c38dff6898e
08efcef470100f065d3e1509b09740827333887e
refs/heads/master
2020-03-25T03:09:16.332049
2018-07-24T07:46:01
2018-07-24T07:46:01
143,325,504
1
0
null
2018-08-02T17:27:11
2018-08-02T17:27:11
null
GB18030
C++
false
false
18,422
cpp
#include "caffe/net.hpp" #include "caffe/cc/core/cc_utils.h" #include <map> #include <string> #include <thread> #include <mutex> #include <condition_variable> #include "caffe/util/model_crypt.h" using namespace std; using namespace cc; #define min(a, b) ((a)<(b)?(a):(b)) #define max(a, b) ((a)>(b)?(a):(b)) namespace cc{ #define CLASSIFIER_MODEL_FROM_DATMODEL 0 #define CLASSIFIER_MODEL_FROM_PROTOTXT_CAFFEMODEL 1 CCAPI Classifier* CCCALL loadClassifier(const char* prototxt, const char* caffemodel, float scale, int numMeans, float* meanValue, int gpuID){ return new Classifier(prototxt, caffemodel, scale, numMeans, meanValue, gpuID); } CCAPI Classifier* CCCALL loadClassifier2(const char* datmodel, float scale, int numMeans, float* meanValue, int gpuID){ return new Classifier(datmodel, scale, numMeans, meanValue, gpuID); } CCAPI void CCCALL releaseClassifier(Classifier* clas){ if (clas) delete clas; } Classifier::Classifier(const char* datmodel, float scale, int numMeans, float* meanValue, int gpuID){ this->contextInited_ = false; this->datmodel_ = datmodel; this->scale_ = scale; this->num_mean_ = numMeans; this->gpuID_ = gpuID; this->modelFrom_ = CLASSIFIER_MODEL_FROM_DATMODEL; memset(this->mean_, 0, sizeof(this->mean_)); for (int i = 0; i < min(numMeans, 3); ++i) this->mean_[i] = meanValue[i]; } Classifier::Classifier(const char* prototxt, const char* caffemodel, float scale, int numMeans, float* meanValue, int gpuID){ this->contextInited_ = false; this->prototxt_ = prototxt; this->caffemodel_ = caffemodel; this->scale_ = scale; this->num_mean_ = numMeans; this->gpuID_ = gpuID; this->modelFrom_ = CLASSIFIER_MODEL_FROM_PROTOTXT_CAFFEMODEL; memset(this->mean_, 0, sizeof(this->mean_)); for (int i = 0; i < min(numMeans, 3); ++i) this->mean_[i] = meanValue[i]; } bool Classifier::isInitContext(){ return this->contextInited_; } Blob* Classifier::inputBlob(int index){ return this->net_->input_blob(index); } Blob* Classifier::outputBlob(int index){ return this->net_->output_blob(index); } void Classifier::initContext(){ if (this->contextInited_) return; this->contextInited_ = true; if (this->modelFrom_ == CLASSIFIER_MODEL_FROM_DATMODEL){ PackageDecode decoder; if (!decoder.decode(this->datmodel_)){ throw "无法解析模型文件: " + string(this->datmodel_); } int indDeploy = decoder.find(PART_TYPE_DEPLOY); int indCaffemodel = decoder.find(PART_TYPE_CAFFEMODEL); if (indDeploy == -1){ throw "模型没有有效的deploy数据"; } if (indCaffemodel == -1){ throw "模型没有有效的caffemodel数据"; } uchar* deploy = decoder.data(indDeploy); uchar* caffemodel = decoder.data(indCaffemodel); this->net_ = loadNetFromPrototxtString((char*)deploy, decoder.size(indDeploy), PhaseTest); this->net_->copyTrainedParamFromData(caffemodel, decoder.size(indCaffemodel)); } else if (this->modelFrom_ == CLASSIFIER_MODEL_FROM_PROTOTXT_CAFFEMODEL){ this->net_ = loadNetFromPrototxt(this->prototxt_, PhaseTest); this->net_->copyTrainedParamFromFile(this->caffemodel_); } else{ throw "错误的modelFrom_"; } } void Classifier::reshape(int num, int channels, int height, int width){ Blob* input = net_->input_blob(0); num = num == -1 ? input->num() : num; channels = channels == -1 ? input->channel() : channels; height = height == -1 ? input->height() : height; width = width == -1 ? input->width() : width; input->Reshape(num, channels, height, width); net_->Reshape(); } Classifier::~Classifier(){ } void Classifier::forward(const Mat& im){ forward(1, &im); } void Classifier::getBlob(const char* name, BlobData* data){ if (data){ Blob* blob = getBlob(name); if (blob) data->copyFrom(blob); } } void Classifier::forward(int num, const Mat* ims){ initContext(); Mat fm; Blob* input = net_->input_blob(0); int w = input->width(); int h = input->height(); //fix,如果输入的通道不匹配会报错 if (num != input->num()){ input->Reshape(num, input->channel(), input->height(), input->width()); net_->Reshape(); } for (int i = 0; i < num; ++i){ float* image_ptr = input->mutable_cpu_data() + input->offset(i); CHECK_EQ(ims[i].channels(), input->channel()) << "channels not match"; ims[i].copyTo(fm); if (CV_MAT_TYPE(fm.type()) != CV_32F) fm.convertTo(fm, CV_32F); if (fm.size() != cv::Size(w, h)) cv::resize(fm, fm, cv::Size(w, h)); if (this->num_mean_ > 0) fm -= cv::Scalar(this->mean_[0], this->mean_[1], this->mean_[2]); if (this->scale_ != 1) fm *= this->scale_; Mat ms[3]; float* check = image_ptr; for (int c = 0; c < input->channel(); ++c){ ms[c] = Mat(h, w, CV_32F, image_ptr); image_ptr += w * h; } split(fm, ms); CHECK_EQ((float*)ms[0].data, check) << "data ptr error"; } if (this->gpuID_ != CLASSIFIER_INVALID_DEVICE_ID) setGPU(this->gpuID_); net_->Forward(); } void Classifier::reshape2(int width, int height){ Blob* input = net_->input_blob(0); input->Reshape(input->num(), input->channel(), height, width); net_->Reshape(); } Blob* Classifier::getBlob(const char* name){ return net_->blob(name); } /////////////////////////////////////////////////////////////////////////////////////////////////////// CCAPI void CCCALL releaseBlobData(BlobData* ptr){ if (ptr) delete ptr; } CCAPI BlobData* CCCALL newBlobData(int num, int channels, int height, int width){ BlobData* data = new BlobData(); data->reshape(num, channels, height, width); return data; } CCAPI BlobData* CCCALL newBlobDataFromBlobShape(Blob* blob){ return newBlobData(blob->num(), blob->channel(), blob->height(), blob->width()); } CCAPI void CCCALL copyFromBlob(BlobData* dest, Blob* blob){ dest->reshape(1, blob->channel(), blob->height(), blob->width()); if (blob->count()>0) memcpy(dest->list, blob->cpu_data(), blob->count()*sizeof(float)); } CCAPI void CCCALL copyOneFromBlob(BlobData* dest, Blob* blob, int numIndex){ dest->reshape(1, blob->channel(), blob->height(), blob->width()); int numSize = blob->channel()*blob->height()*blob->width(); if (blob->count()>0) memcpy(dest->list, blob->cpu_data() + numIndex * numSize, numSize*sizeof(float)); } CCAPI void CCCALL releaseObjectDetectList(ObjectDetectList* list){ if (list) delete list; } /////////////////////////////////////////////////////////////////////////////////////////////////////// //任务池定义 struct _TaskPool{ Classifier* model; int count_worker; volatile int* operType; volatile Mat* recImgs; volatile char** blobNames; volatile int* cacheOperType; volatile Mat* cacheImgs; volatile char** cacheBlobNames; volatile int recNum; volatile BlobData** outBlobs; volatile BlobData** cacheOutBlobs; volatile ObjectDetectList** recDetection; volatile int job_cursor; semaphore* semaphoreWait; volatile semaphore** cacheSemaphoreGetResult; volatile semaphore** semaphoreGetResult; semaphore* semaphoreGetResultFinish; criticalsection jobCS; volatile bool flag_run; volatile bool flag_exit; int gpu_id; }; static void swapCache(TaskPool* pool_){ _TaskPool* pool = (_TaskPool*)pool_; pool->recNum = pool->job_cursor; if (pool->recNum > 0){ enterCriticalSection(&pool->jobCS); pool->recNum = pool->job_cursor; std::swap(pool->cacheImgs, pool->recImgs); std::swap(pool->cacheBlobNames, pool->blobNames); std::swap(pool->cacheOperType, pool->operType); std::swap(pool->cacheSemaphoreGetResult, pool->semaphoreGetResult); std::swap(pool->cacheOutBlobs, pool->outBlobs); pool->job_cursor = 0; leaveCriticalSection(&pool->jobCS); releaseSemaphore(pool->semaphoreWait, pool->recNum); } if (pool->recNum == 0) sleep_cc(1); } //从blob数据中,得到检测结果列表, static vector<ObjectDetectList*> detectObjectMulti(BlobData* fr){ vector<ObjectDetectList*> ods; if (!fr || !fr->list) return ods; float* p = fr->list; int num = *p++; ods.resize(num); for (int i = 0; i < num; ++i){ int numobj = *p++; int totalbbox = 0; ods[i] = new ObjectDetectList(); for (int j = 0; j < numobj; ++j){ int numbox = *p++; p += numbox * 7; totalbbox += numbox; } ods[i]->count = totalbbox; if (ods[i]->count > 0) ods[i]->list = new ObjectInfo[ods[i]->count]; else ods[i]->list = 0; } p = fr->list; num = *p++; for (int i = 0; i < num; ++i){ int numobj = *p++; int box_index = 0; for (int j = 0; j < numobj; ++j){ int numbox = *p++; for (int b = 0; b < numbox; ++b){ auto& obj = ods[i]->list[box_index++]; obj.image_id = p[0]; obj.label = p[1]; obj.score = p[2]; obj.xmin = p[3]; obj.ymin = p[4]; obj.xmax = p[5]; obj.ymax = p[6]; p += 7; } } CV_Assert(box_index == ods[i]->count); } return ods; } static void poolThread(void* param){ _TaskPool* pool = (_TaskPool*)param; // GPU是线程上下文相关的 cc::setGPU(pool->gpu_id); pool->model->initContext(); WPtr<BlobData> ssd_cacheBlob = new BlobData(); //vector<Mat> ims; while (pool->flag_run){ swapCache(pool); //printf("recnum = %d\n", pool->recNum); if (pool->recNum > 0){ pool->model->reshape(pool->recNum); pool->model->forward(pool->recNum, (Mat*)pool->recImgs); if (pool->operType[0] == operType_Detection){ for (int i = 0; i < pool->recNum; ++i){ pool->recDetection[i] = 0; } Blob* outblob = pool->model->getBlob((const char*)pool->blobNames[0]); if (outblob){ copyFromBlob(ssd_cacheBlob, outblob); vector<ObjectDetectList*> detectResult = detectObjectMulti(ssd_cacheBlob); if (detectResult.size() != pool->recNum){ printf("detectResult.size()[%d] != recNum[%d]\n", detectResult.size(), pool->recNum); } else{ for (int i = 0; i < pool->recNum; ++i){ pool->recDetection[i] = detectResult[i]; if (pool->recDetection[i]){ int width = ((Mat*)pool->recImgs)->cols; int height = ((Mat*)pool->recImgs)->rows; for (int j = 0; j < pool->recDetection[i]->count; ++j){ pool->recDetection[i]->list[j].xmin *= width; pool->recDetection[i]->list[j].ymin *= height; pool->recDetection[i]->list[j].xmax *= width; pool->recDetection[i]->list[j].ymax *= height; } } } } } else{ printf("没有找到outblob: %s\n", (const char*)pool->blobNames[0]); } } else{ for (int i = 0; i < pool->recNum; ++i){ copyOneFromBlob((BlobData*)pool->outBlobs[i], pool->model->getBlob((const char*)pool->blobNames[i]), i); } } for (int i = 0; i < pool->recNum; ++i) releaseSemaphore((semaphore*)pool->semaphoreGetResult[i], 1); for (int i = 0; i < pool->recNum; ++i) waitSemaphore(pool->semaphoreGetResultFinish); } } pool->flag_run = false; pool->flag_exit = true; } CCAPI TaskPool* CCCALL buildPool(Classifier* model, int gpu_id, int batch_size){ if (model->isInitContext()){ printf("Warning:如果分类器已经被初始化,此时会造成多GPU时CUDNN错误,如果报错,请保证初始化在TaskPool内进行的\n"); } batch_size = batch_size < 1 ? 1 : batch_size; _TaskPool* pool = new _TaskPool(); memset(pool, 0, sizeof(*pool)); pool->model = model; pool->count_worker = batch_size; pool->recImgs = new volatile Mat[batch_size]; pool->blobNames = new volatile char*[batch_size]; pool->operType = new volatile int[batch_size]; pool->cacheImgs = new volatile Mat[batch_size]; pool->cacheBlobNames = new volatile char*[batch_size]; pool->cacheOperType = new volatile int[batch_size]; pool->semaphoreWait = createSemaphore(batch_size, batch_size); pool->outBlobs = new volatile BlobData*[batch_size]; pool->cacheOutBlobs = new volatile BlobData*[batch_size]; pool->recDetection = new volatile ObjectDetectList*[batch_size]; //pool->semaphoreGetResult = CreateSemaphoreA(0, 0, batch_size, 0); pool->semaphoreGetResultFinish = createSemaphore(0, batch_size); pool->gpu_id = gpu_id; pool->flag_exit = false; pool->flag_run = true; pool->semaphoreGetResult = new volatile semaphore*[batch_size]; pool->cacheSemaphoreGetResult = new volatile semaphore*[batch_size]; for (int i = 0; i < batch_size; ++i){ pool->semaphoreGetResult[i] = createSemaphore(0, 1); pool->cacheSemaphoreGetResult[i] = createSemaphore(0, 1); } initializeCriticalSection(&pool->jobCS); thread(poolThread, pool).detach(); return pool; } CCAPI ObjectDetectList* CCCALL forwardSSDByTaskPool(TaskPool* pool_, const Mat& img, const char* blob_name){ _TaskPool* pool = (_TaskPool*)pool_; if (pool == 0) return 0; if (img.empty()) return 0; if (!pool->flag_run) return 0; Mat im; img.copyTo(im); if (im.empty()) return 0; waitSemaphore(pool->semaphoreWait); if (!pool->flag_run) return 0; enterCriticalSection(&pool->jobCS); int cursor = pool->job_cursor; volatile semaphore* semap = pool->cacheSemaphoreGetResult[cursor]; ((Mat*)pool->cacheImgs)[cursor] = im; pool->cacheBlobNames[cursor] = (char*)blob_name; pool->cacheOperType[cursor] = operType_Detection; pool->job_cursor++; leaveCriticalSection(&pool->jobCS); waitSemaphore((semaphore*)semap); volatile ObjectDetectList* result = pool->recDetection[cursor]; releaseSemaphore(pool->semaphoreGetResultFinish, 1); return (ObjectDetectList*)result; } CCAPI bool CCCALL forwardByTaskPool(TaskPool* pool_, const Mat& img, const char* blob_name, BlobData* inplace_blobData){ //CCAPI BlobData* CCCALL forwardByTaskPool(TaskPool* pool_, const Mat& img, const char* blob_name){ _TaskPool* pool = (_TaskPool*)pool_; if (pool == 0) return false; if (img.empty()) return false; if (!pool->flag_run) return false; if (inplace_blobData == 0) return false; Mat im; img.copyTo(im); if (im.empty()) return false; waitSemaphore(pool->semaphoreWait); if (!pool->flag_run) return false; enterCriticalSection(&pool->jobCS); int cursor = pool->job_cursor; volatile semaphore* semap = pool->cacheSemaphoreGetResult[cursor]; ((Mat*)pool->cacheImgs)[cursor] = im; pool->cacheBlobNames[cursor] = (char*)blob_name; pool->cacheOperType[cursor] = operType_Forward; pool->cacheOutBlobs[cursor] = inplace_blobData; pool->job_cursor++; leaveCriticalSection(&pool->jobCS); waitSemaphore((semaphore*)semap); releaseSemaphore(pool->semaphoreGetResultFinish, 1); return true; } CCAPI void CCCALL releaseTaskPool(TaskPool* pool_){ _TaskPool* pool = (_TaskPool*)pool_; if (pool == 0) return; pool->flag_run = false; releaseSemaphore(pool->semaphoreWait, pool->count_worker); releaseSemaphore(pool->semaphoreGetResultFinish, pool->count_worker); while (!pool->flag_exit) sleep_cc(10); deleteSemaphore(&pool->semaphoreWait); for (int i = 0; i < pool->count_worker; ++i){ deleteSemaphore((semaphore**)&pool->semaphoreGetResult[i]); deleteSemaphore((semaphore**)&pool->cacheSemaphoreGetResult[i]); } deleteSemaphore(&pool->semaphoreGetResultFinish); deleteCriticalSection(&pool->jobCS); delete[] pool->recImgs; delete[] pool->operType; delete[] pool->blobNames; delete[] pool->cacheImgs; delete[] pool->cacheOperType; delete[] pool->cacheBlobNames; delete[] pool->recDetection; delete[] pool->semaphoreGetResult; delete[] pool->cacheSemaphoreGetResult; delete[] pool->outBlobs; delete[] pool->cacheOutBlobs; delete pool; } CCAPI void CCCALL initializeCriticalSection(criticalsection* cs){ cs->p = new std::mutex(); } CCAPI void CCCALL enterCriticalSection(criticalsection* cs){ ((std::mutex*)cs->p)->lock(); } CCAPI void CCCALL leaveCriticalSection(criticalsection* cs){ ((std::mutex*)cs->p)->unlock(); } CCAPI void CCCALL deleteCriticalSection(criticalsection* cs){ delete ((std::mutex*)cs->p); cs->p = 0; } CCAPI semaphore* CCCALL createSemaphore(int numInitialize, int maxSemaphore){ semaphore* s = new semaphore(); s->p1 = new std::condition_variable(); s->p2 = new std::mutex(); s->numFree = numInitialize; s->maxSemaphore = maxSemaphore; return s; } CCAPI void CCCALL deleteSemaphore(semaphore** pps){ if (pps){ semaphore* ps = *pps; if (ps){ if (ps->p1) delete ((std::condition_variable*)(ps->p1)); if (ps->p2) delete ((std::mutex*)(ps->p2)); ps->p1 = 0; ps->p2 = 0; } *pps = 0; } } CCAPI void CCCALL waitSemaphore(semaphore* s){ std::unique_lock<std::mutex> lock(*(std::mutex*)(s->p2)); ((std::condition_variable*)(s->p1))->wait(lock, [=]{return s->numFree > 0; }); --s->numFree; } CCAPI void CCCALL releaseSemaphore(semaphore* s, int num){ std::unique_lock<std::mutex> lock(*(std::mutex*)(s->p2)); num = min(s->maxSemaphore - s->numFree, num); for (int i = 0; i < num; ++i){ s->numFree++; ((std::condition_variable*)(s->p1))->notify_one(); } } CCAPI void CCCALL sleep_cc(int milliseconds){ std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); } CCAPI void CCCALL disableLogPrintToConsole(){ static volatile int flag = 0; if (flag) return; flag = 1; google::InitGoogleLogging("cc"); } CCAPI const char* CCCALL getCCVersionString(){ return VersionStr __TIMESTAMP__; } CCAPI int CCCALL getCCVersionInt(){ return VersionInt; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CCAPI int CCCALL argmax(Blob* classification_blob, int numIndex, float* conf_ptr){ if (conf_ptr) *conf_ptr = 0; if (!classification_blob) return -1; int planeSize = classification_blob->height() * classification_blob->width(); return argmax(classification_blob->mutable_cpu_data() + classification_blob->offset(numIndex), classification_blob->channel() * planeSize, conf_ptr); } CCAPI int CCCALL argmax(float* data_ptr, int num_data, float* conf_ptr){ if (conf_ptr) *conf_ptr = 0; if (!data_ptr || num_data < 1) return -1; int label = std::max_element(data_ptr, data_ptr + num_data) - data_ptr; if (conf_ptr) *conf_ptr = data_ptr[label]; return label; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// }
65fc44397122b77c42a2608d29a31d70efb19111
d1411b1c3235fc2f790e871f1b9275b58b5b4549
/source/cpp/testapp/core/SceneNode.h
652c4d1486d8849ecb4511817161e4a7f161b53f
[]
no_license
jancajthaml/sgloi13
9103bb74a04349de562e1ff44c81283a56403bde
55576551861d365ecc8bc299e502c13271171ab1
refs/heads/master
2021-01-01T05:42:19.506286
2013-12-16T12:58:29
2013-12-16T12:58:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,740
h
// // SceneNode.h // libsgl // // Created by Jan Brejcha on 01.11.13. // Copyright (c) 2013 brejchajan. All rights reserved. // #ifndef libsgl_SceneNode_h #define libsgl_SceneNode_h #include <vector> #include "../struct/Matrix.h" #include "../struct/light/Light.h" #include "Model.h" /** Basic SceneGraph Node, other elements except Lights extends this one. */ class SceneNode { protected: ///model that is held by this SceneNode Model * model; ///children nodes of this scene node //FIXME std::vector really slow std::vector< SceneNode* > children; ///model view projection matrix for this scene node public: Matrix MVP; SceneNode() { model = NULL; } virtual ~SceneNode() { if( model!=NULL ) delete model; uint8 i = -1; const uint8 size = children.size(); while( ++i<size ) delete children[i]; } //TODO copy assignment operator, to support RULE OF THREE. /** Constructor of the SceneNode @param _model model that will be held by this SceneNode @param _mvp Model View Projection matrix for this model */ SceneNode( Model* _model, Matrix _mvp ) { this->model = _model; this->MVP = _mvp; } /** Rasterizes this node @param lights lights affecting this node. */ virtual void rasterize( std::vector< Light > lights ) { model->rasterize(lights, this->MVP); for( std::vector< SceneNode* >::iterator iter = children.begin(); iter != children.end(); ++iter ) (*iter)->rasterize(lights); children.clear(); } /** Adds child to children @param child the child to be added */ void addChild(SceneNode * child) { children.push_back(child); } void addVertex(Vertex v) { model->addVertex(v); } Model* getModel() { return model; } }; #endif
060ca5ddcff76c8a8ff5a3200a46a3d29daaf04c
85d32a4608fc62edda7d100e946b2a7e0d59d027
/4. VARIED_VARIABLE_SCOPE/EnumeratedTypes/Source.cpp
2b40ef37a3329f740d1fcd85b6b9b81a41940343
[]
no_license
jongkukpark/FollowStudyCPP
b6a274218fc697a9b87ef511b1559327fe6f5246
d4bffcfe895d8eca357afe89ff0cac1ce3e5a442
refs/heads/master
2020-04-13T00:08:35.883523
2019-02-12T08:44:25
2019-02-12T08:44:25
162,838,685
0
0
null
null
null
null
UHC
C++
false
false
977
cpp
#include <iostream> #include <typeinfo> //int computeDamage(int weapon_id) // 숫자로 쓰면 외우기 힘듦. //{ // if (weapon_id == 0) // sword // { // return 1; // } // if (weapon_id == 1) // hammer // { // return 2; // } //} enum Color // 사용자 정의 자료형, users defined data type { COLOR_BALCK = -3, // 숫자를 담고 있음 COLOR_RED = -1, COLOR_BLUE, COLOR_GREEN, COLOR_SKYBLUE, // BLUE // enum에서 같은 이름으로 정의하면 안됨. }; // 반드시 세미콜론 //enum Feeling //{ // HAPPY, // JOY, // TIRED, // BLUE //}; int main() { using namespace std; Color paint = COLOR_BALCK; Color house(COLOR_BLUE); Color apple{ COLOR_RED }; int color_id = COLOR_RED; // 됨. // Color my_color = color_id; // 안됨. Color my_color = static_cast<Color>(color_id); // 됨. cout << paint << endl; // cin >> my_color; // 안됨. int in_number; cin >> in_number; if (in_number == 0) my_color = COLOR_BALCK; // ... return 0; }
d28af9ba50126e956df895dcef5897ff5496f62f
6d12c71bcb0732bc75906b36ce1fd3556e1560a8
/Cpp/leetCode/217_array_ContainsDuplicateValueRepeatedAtLeastTwice.cpp
4d23e1d51534f11a5acd652e4b609d2f2abeb4de
[]
no_license
surajmitsel/surajmitsel
35b4a6d9f2a6728d9710c3183d3621047b1e0296
06956f694745c8781a8e57ea355208b13c08b3e4
refs/heads/main
2023-08-09T03:44:33.035383
2023-08-07T17:56:38
2023-08-07T17:56:38
372,733,800
0
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
#include <iostream> #include <vector> using namespace std; /* 217. Contains Duplicate Easy Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true */ /* */ // METHOD1: with extra space of L,R bool containsDuplicate(vector<int> &nums) { bool result; return result; } int main() { vector<int> vec{1, 2, 3, 1}; // vector<int> vec{1,1,1,3,3,4,3,2,4,2}; cout << "containsDuplicate:" << containsDuplicate(vec); }
dc3870008f442e410d4406db8da51ac38aee02cd
caf548f3eea8e33cacbd59011fb3bff9c90757f3
/omegaUp/promedio_cal/promedio_cal.cpp
5b91f83b57ff52b1a7a6b911b62eb46cc07e9e57
[]
no_license
bernovie/cpp
01e756b29ab424d221bbcf0d4afbac3df8a107f4
01caccc3e30529ce4ed78a23396878078ff30259
refs/heads/master
2021-06-30T13:59:36.233531
2017-09-17T21:40:10
2017-09-17T21:40:10
103,863,843
0
0
null
null
null
null
UTF-8
C++
false
false
196
cpp
#include <iostream> using namespace std; int main(){ int cals[5]; double total = 0; for(int i = 0; i < 5; i++){ cin>>cals[i]; total += cals[i]; } printf("%.1f\n",total/5); return 0; }
311983a4623ac79d0b79917246f3221633f0814f
f7e8786b1e62222bd1cedcb58383a0576c36a2a2
/src/services/ui/view_manager/view_manager_app.cc
ff5a201b5b58b472eba82faf8d15a9a3b3a8ab70
[ "BSD-3-Clause" ]
permissive
amplab/ray-core
656915553742302915a363e42b7497037985a91e
89a278ec589d98bcbc7e57e0b80d055667cca62f
refs/heads/master
2023-07-07T20:45:40.883095
2016-08-06T23:52:23
2016-08-06T23:52:23
61,343,320
4
5
null
2016-08-06T23:52:24
2016-06-17T03:35:34
C++
UTF-8
C++
false
false
2,123
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/ui/view_manager/view_manager_app.h" #include "base/command_line.h" #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "mojo/common/tracing_impl.h" #include "mojo/public/cpp/application/connect.h" #include "mojo/public/cpp/application/run_application.h" #include "mojo/public/cpp/application/service_provider_impl.h" #include "services/ui/view_manager/view_manager_impl.h" namespace view_manager { ViewManagerApp::ViewManagerApp() {} ViewManagerApp::~ViewManagerApp() {} void ViewManagerApp::OnInitialize() { auto command_line = base::CommandLine::ForCurrentProcess(); command_line->InitFromArgv(args()); logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; logging::InitLogging(settings); tracing_.Initialize(shell(), &args()); // Connect to compositor. mojo::gfx::composition::CompositorPtr compositor; mojo::ConnectToService(shell(), "mojo:compositor_service", GetProxy(&compositor)); compositor.set_connection_error_handler(base::Bind( &ViewManagerApp::OnCompositorConnectionError, base::Unretained(this))); // Create the registry. registry_.reset(new ViewRegistry(compositor.Pass())); } bool ViewManagerApp::OnAcceptConnection( mojo::ServiceProviderImpl* service_provider_impl) { service_provider_impl->AddService<mojo::ui::ViewManager>([this]( const mojo::ConnectionContext& connection_context, mojo::InterfaceRequest<mojo::ui::ViewManager> view_manager_request) { DCHECK(registry_); view_managers_.AddBinding(new ViewManagerImpl(registry_.get()), view_manager_request.Pass()); }); return true; } void ViewManagerApp::OnCompositorConnectionError() { LOG(ERROR) << "Exiting due to compositor connection error."; Shutdown(); } void ViewManagerApp::Shutdown() { mojo::TerminateApplication(MOJO_RESULT_OK); } } // namespace view_manager
a1c34c78276e9cc089c34ec00cb6a739a4815e46
a08758b50f7457e254b8375cabea03fd363bc65e
/TonightClimax_ForD3D/退避用/Wall/Wall.h
26073221d10ccffe2b295fa0ee942402282d56c5
[]
no_license
YuukiReiya/Tonight-also-the-mountains
328043d6ed78483c68d64a056b3f08a8e2c2e212
fcd34f9ae8f5cde9ecfdd6b5b30a20f7cc0104a0
refs/heads/master
2020-04-10T15:23:30.387536
2019-01-24T05:42:47
2019-01-24T05:42:47
161,107,983
0
0
null
null
null
null
UTF-8
C++
false
false
1,891
h
#pragma once #include "../Sprite/Sprite.h" #include "../Texture/Texture.h" #include <DirectXMath.h> #include <memory> #include "../Tile/Tile.h" class UpWall { public: UpWall() {}; ~UpWall() {}; void Init(); void Render(); private: std::unique_ptr<Texture> m_pLWallTex; std::unique_ptr<Texture> m_pRWallTex; std::unique_ptr<Texture> m_pMWallTex; std::unique_ptr<Sprite> m_pSprite; static constexpr DirectX::XMFLOAT2 c_ImageSize = { 48,144 }; static constexpr int c_Num = static_cast<int>(Tile::c_Num.x*(Tile::c_ImageSize.x / c_ImageSize.x)); static constexpr float c_Scale = Tile::c_Scale; DirectX::XMFLOAT2 ConvertPos(int x); }; class LeftWall { public: LeftWall() {}; ~LeftWall() {}; void Init(); void Render(); private: std::unique_ptr<Texture> m_pUWallTex; std::unique_ptr<Texture> m_pMWallTex; std::unique_ptr<Texture> m_pDWallTex; std::unique_ptr<Sprite> m_pSprite; static constexpr DirectX::XMFLOAT2 c_ImageSize = { 48,144 }; static constexpr float c_Scale = Tile::c_Scale; }; class DownWall { public: DownWall() {}; ~DownWall() {}; void Init(); void Render(); private: std::unique_ptr<Texture> m_pLWallTex; std::unique_ptr<Texture> m_pRWallTex; std::unique_ptr<Texture> m_pMWallTex; std::unique_ptr<Sprite> m_pSprite; static constexpr DirectX::XMFLOAT2 c_ImageSize = { 48,48 }; static constexpr int c_Num = static_cast<int>(Tile::c_Num.x*(Tile::c_ImageSize.x / c_ImageSize.x)); static constexpr float c_Scale = Tile::c_Scale; DirectX::XMFLOAT2 ConvertPos(int x); }; class RightWall { public: RightWall() {}; ~RightWall() {}; void Init(); void Render(); private: std::unique_ptr<Texture> m_pUWallTex; std::unique_ptr<Texture> m_pMWallTex; std::unique_ptr<Texture> m_pDWallTex; std::unique_ptr<Sprite> m_pSprite; static constexpr DirectX::XMFLOAT2 c_ImageSize = { 48,144 }; static constexpr float c_Scale = Tile::c_Scale; };
f70f8a011ea4ab378f1e6f1c2d62908e8e759e70
468716b83d837e2944fe6a3c8078b585560d7d1f
/Players/Cocos2d-x_v4/Effekseer/Effekseer/SIMD/Effekseer.SIMD4f_SSE.h
265d10e62ca273481b2657914f98520a1111515c
[ "MIT" ]
permissive
darreney/EffekseerForCocos2d-x
0a1bfea09ec9858081f799cc5b0ce3f42147883a
de9222b28f6f376cfb96f98b7b4dd783a3d66055
refs/heads/master
2020-12-18T20:24:59.103886
2020-06-16T07:21:44
2020-06-16T07:21:44
235,512,027
0
0
MIT
2020-01-22T06:21:45
2020-01-22T06:21:44
null
UTF-8
C++
false
false
10,924
h
 #ifndef __EFFEKSEER_SIMD4F_SSE_H__ #define __EFFEKSEER_SIMD4F_SSE_H__ #if (defined(_M_AMD64) || defined(_M_X64)) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2) || defined(__SSE__) #include <stdint.h> #ifdef _MSC_VER #include <intrin.h> #else #include <x86intrin.h> #endif #include "../Effekseer.Math.h" namespace Effekseer { inline float Sqrt(float x) { _mm_store_ss(&x, _mm_sqrt_ss(_mm_load_ss(&x))); return x; } inline float Rsqrt(float x) { _mm_store_ss(&x, _mm_rsqrt_ss(_mm_load_ss(&x))); return x; } /** @brief simd class for sse */ struct alignas(16) SIMD4f { __m128 s; SIMD4f() = default; SIMD4f(const SIMD4f& rhs) = default; SIMD4f(__m128 rhs) { s = rhs; } SIMD4f(__m128i rhs) { s = _mm_castsi128_ps(rhs); } SIMD4f(float x, float y, float z, float w) { s = _mm_setr_ps(x, y, z, w); } SIMD4f(float i) { s = _mm_set_ps1(i); } float GetX() const { return _mm_cvtss_f32(s); } float GetY() const { return _mm_cvtss_f32(Swizzle<1,1,1,1>(s).s); } float GetZ() const { return _mm_cvtss_f32(Swizzle<2,2,2,2>(s).s); } float GetW() const { return _mm_cvtss_f32(Swizzle<3,3,3,3>(s).s); } void SetX(float i) { s = _mm_move_ss(s, _mm_set_ss(i)); } void SetY(float i) { s = Swizzle<1,0,2,3>(_mm_move_ss(Swizzle<1,0,2,3>(s).s, _mm_set_ss(i))).s; } void SetZ(float i) { s = Swizzle<2,1,0,3>(_mm_move_ss(Swizzle<2,1,0,3>(s).s, _mm_set_ss(i))).s; } void SetW(float i) { s = Swizzle<3,1,2,0>(_mm_move_ss(Swizzle<3,1,2,0>(s).s, _mm_set_ss(i))).s; } SIMD4f& operator+=(const SIMD4f& rhs) { s = _mm_add_ps(s, rhs.s); return *this; } SIMD4f& operator-=(const SIMD4f& rhs) { s = _mm_sub_ps(s, rhs.s); return *this; } SIMD4f& operator*=(const SIMD4f& rhs) { s = _mm_mul_ps(s, rhs.s); return *this; } SIMD4f& operator*=(float rhs) { s = _mm_mul_ps(s, _mm_set1_ps(rhs)); return *this; } SIMD4f& operator/=(const SIMD4f& rhs) { s = _mm_div_ps(s, rhs.s); return *this; } SIMD4f& operator/=(float rhs) { s = _mm_div_ps(s, _mm_set1_ps(rhs)); return *this; } static SIMD4f Load2(const void* mem); static void Store2(void* mem, const SIMD4f& i); static SIMD4f Load3(const void* mem); static void Store3(void* mem, const SIMD4f& i); static SIMD4f Load4(const void* mem); static void Store4(void* mem, const SIMD4f& i); static SIMD4f SetZero(); static SIMD4f SetInt(int32_t x, int32_t y, int32_t z, int32_t w); static SIMD4f SetUInt(uint32_t x, uint32_t y, uint32_t z, uint32_t w); static SIMD4f Sqrt(const SIMD4f& in); static SIMD4f Rsqrt(const SIMD4f& in); static SIMD4f Abs(const SIMD4f& in); static SIMD4f Min(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f Max(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f MulAdd(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c); static SIMD4f MulSub(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c); template<size_t LANE> static SIMD4f MulLane(const SIMD4f& lhs, const SIMD4f& rhs); template<size_t LANE> static SIMD4f MulAddLane(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c); template<size_t LANE> static SIMD4f MulSubLane(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c); template <uint32_t indexX, uint32_t indexY, uint32_t indexZ, uint32_t indexW> static SIMD4f Swizzle(const SIMD4f& v); static SIMD4f Dot3(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f Cross3(const SIMD4f& lhs, const SIMD4f& rhs); template <uint32_t X, uint32_t Y, uint32_t Z, uint32_t W> static SIMD4f Mask(); static uint32_t MoveMask(const SIMD4f& in); static SIMD4f Equal(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f NotEqual(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f LessThan(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f LessEqual(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f GreaterThan(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f GreaterEqual(const SIMD4f& lhs, const SIMD4f& rhs); static SIMD4f NearEqual(const SIMD4f& lhs, const SIMD4f& rhs, float epsilon = DefaultEpsilon); static SIMD4f IsZero(const SIMD4f& in, float epsilon = DefaultEpsilon); static void Transpose(SIMD4f& s0, SIMD4f& s1, SIMD4f& s2, SIMD4f& s3); }; inline SIMD4f operator+(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_add_ps(lhs.s, rhs.s)}; } inline SIMD4f operator-(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_sub_ps(lhs.s, rhs.s)}; } inline SIMD4f operator*(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_mul_ps(lhs.s, rhs.s)}; } inline SIMD4f operator*(const SIMD4f& lhs, float rhs) { return SIMD4f{_mm_mul_ps(lhs.s, _mm_set1_ps(rhs))}; } inline SIMD4f operator/(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_div_ps(lhs.s, rhs.s)}; } inline SIMD4f operator/(const SIMD4f& lhs, float rhs) { return SIMD4f{_mm_div_ps(lhs.s, _mm_set1_ps(rhs))}; } inline SIMD4f operator&(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_and_ps(lhs.s, rhs.s)}; } inline SIMD4f operator|(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_or_ps(lhs.s, rhs.s)}; } inline bool operator==(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f::MoveMask(SIMD4f::Equal(lhs, rhs)) == 0xf; } inline bool operator!=(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f::MoveMask(SIMD4f::Equal(lhs, rhs)) != 0xf; } inline SIMD4f SIMD4f::Load2(const void* mem) { __m128 x = _mm_load_ss((const float*)mem + 0); __m128 y = _mm_load_ss((const float*)mem + 1); return _mm_unpacklo_ps(x, y); } inline void SIMD4f::Store2(void* mem, const SIMD4f& i) { SIMD4f t1 = Swizzle<1,1,1,1>(i.s); _mm_store_ss((float*)mem + 0, i.s); _mm_store_ss((float*)mem + 1, t1.s); } inline SIMD4f SIMD4f::Load3(const void* mem) { __m128 x = _mm_load_ss((const float*)mem + 0); __m128 y = _mm_load_ss((const float*)mem + 1); __m128 z = _mm_load_ss((const float*)mem + 2); __m128 xy = _mm_unpacklo_ps(x, y); return _mm_movelh_ps(xy, z); } inline void SIMD4f::Store3(void* mem, const SIMD4f& i) { SIMD4f t1 = Swizzle<1,1,1,1>(i.s); SIMD4f t2 = Swizzle<2,2,2,2>(i.s); _mm_store_ss((float*)mem + 0, i.s); _mm_store_ss((float*)mem + 1, t1.s); _mm_store_ss((float*)mem + 2, t2.s); } inline SIMD4f SIMD4f::Load4(const void* mem) { return _mm_loadu_ps((const float*)mem); } inline void SIMD4f::Store4(void* mem, const SIMD4f& i) { _mm_storeu_ps((float*)mem, i.s); } inline SIMD4f SIMD4f::SetZero() { return _mm_setzero_ps(); } inline SIMD4f SIMD4f::SetInt(int32_t x, int32_t y, int32_t z, int32_t w) { return SIMD4f{_mm_setr_epi32((int)x, (int)y, (int)z, (int)w)}; } inline SIMD4f SIMD4f::SetUInt(uint32_t x, uint32_t y, uint32_t z, uint32_t w) { return SIMD4f{_mm_setr_epi32((int)x, (int)y, (int)z, (int)w)}; } inline SIMD4f SIMD4f::Sqrt(const SIMD4f& in) { return SIMD4f{_mm_sqrt_ps(in.s)}; } inline SIMD4f SIMD4f::Rsqrt(const SIMD4f& in) { return SIMD4f{_mm_rsqrt_ps(in.s)}; } inline SIMD4f SIMD4f::Abs(const SIMD4f& in) { return _mm_andnot_ps(_mm_set1_ps(-0.0f), in.s); } inline SIMD4f SIMD4f::Min(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_min_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::Max(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_max_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::MulAdd(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c) { #ifdef __AVX2__ return SIMD4f{_mm_fmadd_ps(b.s, c.s, a.s)}; #else return SIMD4f{_mm_add_ps(a.s, _mm_mul_ps(b.s, c.s))}; #endif } inline SIMD4f SIMD4f::MulSub(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c) { #ifdef __AVX2__ return SIMD4f{_mm_fnmadd_ps(b.s, c.s, a.s)}; #else return SIMD4f{_mm_sub_ps(a.s, _mm_mul_ps(b.s, c.s))}; #endif } template<size_t LANE> SIMD4f SIMD4f::MulLane(const SIMD4f& lhs, const SIMD4f& rhs) { static_assert(LANE < 4, "LANE is must be less than 4."); return SIMD4f{_mm_mul_ps(lhs.s, _mm_shuffle_ps(rhs.s, rhs.s, _MM_SHUFFLE(LANE, LANE, LANE, LANE)))}; } template<size_t LANE> SIMD4f SIMD4f::MulAddLane(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c) { static_assert(LANE < 4, "LANE is must be less than 4."); #ifdef __AVX2__ return SIMD4f{_mm_fmadd_ps(b.s, _mm_shuffle_ps(c.s, c.s, _MM_SHUFFLE(LANE, LANE, LANE, LANE)), a.s)}; #else return SIMD4f{_mm_add_ps(a.s, _mm_mul_ps(b.s, _mm_shuffle_ps(c.s, c.s, _MM_SHUFFLE(LANE, LANE, LANE, LANE))))}; #endif } template<size_t LANE> SIMD4f SIMD4f::MulSubLane(const SIMD4f& a, const SIMD4f& b, const SIMD4f& c) { static_assert(LANE < 4, "LANE is must be less than 4."); #ifdef __AVX2__ return SIMD4f{_mm_fnmadd_ps(b.s, _mm_shuffle_ps(c.s, c.s, _MM_SHUFFLE(LANE, LANE, LANE, LANE)), a.s)}; #else return SIMD4f{_mm_sub_ps(a.s, _mm_mul_ps(b.s, _mm_shuffle_ps(c.s, c.s, _MM_SHUFFLE(LANE, LANE, LANE, LANE))))}; #endif } template <uint32_t indexX, uint32_t indexY, uint32_t indexZ, uint32_t indexW> SIMD4f SIMD4f::Swizzle(const SIMD4f& v) { static_assert(indexX < 4, "indexX is must be less than 4."); static_assert(indexY < 4, "indexY is must be less than 4."); static_assert(indexZ < 4, "indexZ is must be less than 4."); static_assert(indexW < 4, "indexW is must be less than 4."); return SIMD4f{_mm_shuffle_ps(v.s, v.s, _MM_SHUFFLE(indexW, indexZ, indexY, indexX))}; } inline SIMD4f SIMD4f::Dot3(const SIMD4f& lhs, const SIMD4f& rhs) { SIMD4f muled = lhs * rhs; return _mm_add_ss(_mm_add_ss(muled.s, SIMD4f::Swizzle<1,1,1,1>(muled).s), SIMD4f::Swizzle<2,2,2,2>(muled).s); } inline SIMD4f SIMD4f::Cross3(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f::Swizzle<1,2,0,3>(lhs) * SIMD4f::Swizzle<2,0,1,3>(rhs) - SIMD4f::Swizzle<2,0,1,3>(lhs) * SIMD4f::Swizzle<1,2,0,3>(rhs); } template <uint32_t X, uint32_t Y, uint32_t Z, uint32_t W> inline SIMD4f SIMD4f::Mask() { return _mm_setr_epi32( (int)(0xffffffff * X), (int)(0xffffffff * Y), (int)(0xffffffff * Z), (int)(0xffffffff * W)); } inline uint32_t SIMD4f::MoveMask(const SIMD4f& in) { return (uint32_t)_mm_movemask_ps(in.s); } inline SIMD4f SIMD4f::Equal(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_cmpeq_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::NotEqual(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_cmpneq_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::LessThan(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_cmplt_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::LessEqual(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_cmple_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::GreaterThan(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_cmpgt_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::GreaterEqual(const SIMD4f& lhs, const SIMD4f& rhs) { return SIMD4f{_mm_cmpge_ps(lhs.s, rhs.s)}; } inline SIMD4f SIMD4f::NearEqual(const SIMD4f& lhs, const SIMD4f& rhs, float epsilon) { return LessEqual(Abs(lhs - rhs), SIMD4f(epsilon)); } inline SIMD4f SIMD4f::IsZero(const SIMD4f& in, float epsilon) { return LessEqual(Abs(in), SIMD4f(epsilon)); } inline void SIMD4f::Transpose(SIMD4f& s0, SIMD4f& s1, SIMD4f& s2, SIMD4f& s3) { _MM_TRANSPOSE4_PS(s0.s, s1.s, s2.s, s3.s); } } // namespace Effekseer #endif #endif // __EFFEKSEER_SIMD4F_SSE_H__
61fded0bb9c5a9c27889c2c5b1d70fd14943f404
9527f2723b97bee3b140ea4298d7ab42d8ea1efa
/Isetta-GameTemplate/GameTemplate/GameTemplate/MyScript.h
dabef87ca2b2e9b43b9d35a9f5d12fe1042bc2f4
[]
no_license
ZiuTinyat/IsettaGameJam
052ed7896d0ea84c8a663df24bcdb1eba79a4c03
f7f6f5081bb233f1792e4febd6beabef045bcebf
refs/heads/master
2020-04-09T03:10:10.315793
2018-12-01T23:42:25
2018-12-01T23:42:25
159,971,900
2
0
null
null
null
null
UTF-8
C++
false
false
1,242
h
#pragma once #include <IsettaEngine.h> using namespace Isetta; DEFINE_COMPONENT(MyScript, Component, false) private: // Private variables of your component U64 handleEscPress; public: // A component MUST have a default constructor MyScript() = default; // Awake is called once, immediately when the component is first created and enabled //void Awake() override; // Start is called once, on the first update frame after the component is created and enabled void Start() override; // OnEnable is called immediately each time the component becomes active, including after creation void OnEnable() override; // OnDisable is called immediately each time the component becomes inactive void OnDisable() override; // Update is called each frame (variable delta time) void Update() override; // GuiUpdate is called each frame (variable delta time), GUI can only be called in GuiUpdate //void GuiUpdate() override; // LateUpdate is called each frame (variable delta time) //void LateUpdate() override; // FixedUpdate is called on fixed time (constant delta time) //void FixedUpdate() override; // OnDestroy is called once when the component is destroyed //void OnDestroy() override; DEFINE_COMPONENT_END(MyScript, Component)
f7d25818005d7de94e6e0169be30265e5af1252e
69005ab4c8cc5d88d7996d47ac8def0b28730b95
/msvc-cluster-realistic-1000/src/dir_1/perf97.cpp
f1b568dfdafa92dd392e6f9b96d7ef31b2180721
[]
no_license
sakerbuild/performance-comparisons
ed603c9ffa0d34983a7da74f7b2b731dc3350d7e
78cd8d7896c4b0255ec77304762471e6cab95411
refs/heads/master
2020-12-02T19:14:57.865537
2020-05-11T14:09:40
2020-05-11T14:09:40
231,092,201
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
#include <Windows.h> #include <vector> #include <inc_7/header_142.h> static_assert(sizeof(GenClass_142) > 0, "failed"); #include <inc_1/header_34.h> static_assert(sizeof(GenClass_34) > 0, "failed"); std::vector<int> perf_func_97() { LoadLibrary("abc.dll"); return {97}; }
2277da00a9a45f8ea97c768987a16bee0e5d58dd
4706a2b946019a20155bd60069f7e2e2ac6b7f03
/Single Cell/Single File/hESC-CM_singlefile.cpp
78d448110a43930981fb0eba1f3aa84f6b24b5eb
[]
no_license
TleeB/hESC
22c15003a56721be8e3e0a4f69168fa53cb67dae
33c1e5ac0034e927170fcbbc27c37fc8523e0dfe
refs/heads/master
2021-01-18T14:11:50.857730
2013-08-15T01:54:44
2013-08-15T01:54:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,300
cpp
#include <cmath> #include <iostream> #include <cstdio> //Note model was converted from V/s to mV/ms by converting: // myShiftK1 *1000 to convert from V to mV // R constant *1000 to convert the reversal potentials in mV // Maximal conductances from S/F to mS/F or nS/pF // Time dependent only parameters // Vleak *(1/1000) to convert 1/s to 1/ms units // arel and crel *(1/1000) to convert mM/s to mM/ms units // Vc and Vsr converted from um^3 to picoliters // To reproduce simulations in paper experiments were run for 350 seconds, // drug block was administered at 300 seconds. #define beats 1000 #define EPI #define INITIALVALS #define EARLY //#define LATE using namespace std; //Variables to measure action potential parameters int counter = 0; int start_output = 0; double vmin[beats]; double tvmin[beats]; double vmax[beats]; double dvdtmax[beats]; //double vdvdtmax[beats]; double apd_start[beats]; double apd30_start[beats]; double apd50_start[beats]; double apd70_start[beats]; double apd90_start[beats]; double APA[beats]; double apd_end[beats]; double ddr[beats]; double top[beats]; double ttop[beats]; double top_slope[beats]; double apd30[beats]; double apd50[beats]; double apd70[beats]; double apd90[beats]; double bcl[beats]; //timestep double DT = 0.001;//ms bool Ikrblock = true; double blocktime = 300000; double E4031 = 1; double tmin = 0.0; double tmax = 350000; double t; char output_file_name[20] = "Ikrblock_early.dat"; #ifdef EARLY int CellTypeFlag= 2; double cardiom_C = 41e-12; //[F] spostata dal file parametri, è il valore approssimato della C del cardiom per le equazioni dei fibro. double EarlySRTypeFlag = 2; double lock_Nai=0; double lock_Ki = 0; double Cap_div=1; double RaINa=0.038; double myCoefTauH =2.8;//3.7; double myCoefTauJ = 1; double RaICaL=0.25; double Vh_dCa=12.5; double kCa=12.5; double ampICaLDinf = 1; double KtaufCa=1433; // [1/mM] Altamirano & Bers 2007 double myVhfCaL = 20; double myKfCaL = 7;//7 double ampICaLFinf = 1;//per accelerare la tauF e far inattivare piu' rapidamente la ICaL double myKtauF = 1; double myTauFShift = 0; double myShiftFCaInf = -0.11e-3; //[mM] per spostare un po' a sx la signmoide di fCa double Vth_ICaL = -60; double RaICaT =0.25; double RaINaCa=1.750e1; double alfa=0.8; double RaINaK=0.7;//0.79; ////////RETICOLO ON double RaIK1=0.05*2.67/3; //// Sartiani 20100412 modificato per prove double myShiftK1 = -0.015*1000; double RaIKr=3;//3;//2.6;//2;//4;//2*2; //// RETICOLO ON double poffi = 0; double mySlope = 1;//0.5; double myShift = 0; double RaIKs=0.1; double RaIto=0.1673*0.4903*0.8; double myShiftItoR = -25;//-20; double mySlopeItoR = 0.3; double myShiftItoS = 0;//-5; double mySlopeItoS = 1; double myConstTauR= 1; double myConstTauS= 1; double RaIup=0.4/3;//0.7/3;//0.3/18;//0.003*2; //0.03*10; ////RETICOLO ON double RaIrel=0.2/18;//0.2/18;//0.005*2;//0.05*10; double RaIleak=0.1/18;//0.4/18;//0.004*2;//0.04*10; double RaIf=0.5389;//0.5389; ////Sartiani double Rax0=1.1061; double Radx=0.6537; double myIfconst = 1; double RaCm=0.22162; double RaICap=1; double RaIKp=0; double RaIback=0.2;//0.2;//0.45; #endif #ifdef LATE int CellTypeFlag= 3; double ryanSR = 1; double cardiom_C = 33e-12;// [F] spostata dal file parametri, è il valore approssimato della C del cardiom per le equazioni dei fibro. double lock_Nai=0; double lock_Ki = 0; double Cap_div=1; double RaINa=1; // Itoh double myCoefTauH = 2.8; double myCoefTauJ = 1; double RaICaL=0.422; double Vh_dCa=16; double kCa=12.8; double ampICaLDinf = 1; double KtaufCa=1433; // [1/mM] Altamirano & Bers 2007 double myVhfCaL = 20; double myKfCaL = 7; double ampICaLFinf = 1; double myKtauF = 1; double myTauFShift = 0; double myShiftFCaInf = -0.12e-3; //[mM] per spostare un po' a sx la signmoide di fCa double Vth_ICaL = 0; double RaICaT =0.05; double RaINaCa=1.824e+01; //////////////////// dai dati Sartiani double alfa=0.38; double RaINaK=0.83; double RaIK1=0.4*0.05*2.67*4; double myShiftK1 = -0.015*1000; double RaIKr=1.4; double poffi = 0; double mySlope = 1; double myShift = 0; double RaIKs=0.1; double RaIto=0.3754*0.4903*0.9; // dai dati Sartiani double myShiftItoR = -25; double mySlopeItoR = 0.3; double myShiftItoS = 0; double mySlopeItoS = 1; double myConstTauR= 1; double myConstTauS= 1; double RaIup=0.33; double RaIrel=0.4; double RaIleak=0.3*1; double RaIf=0.23; // dati Sartiani double Rax0=1.1061; double Radx=0.6537; double RaCm=0.17838; // dati Sartiani double RaICap=1; double RaIKp=0; double RaIback=1; // Itoh #endif //// Constants double R=8314.472; // [J/millimoles/K] Gas constant double F=96485.3415; // [C/mol] Faraday constant double T=310.0; // [K] Temperature //// Buffering double Bufc=0.25; // [mM] total cytoplasmic buffer concentration double Kbufc=0.001; // [mM] Cai half saturation constant double Bufsr=10; // [mM] total sarcoplasmic buffer concentration double Kbufsr=0.3; // [mM] CaSR half saturation constant //// Extracellular Ionic concentrations ////TT //Ko=5.4; // [mM] //Cao=1.8; // [mM] //Nao=140; // [mM] ////Sartiani double Ko=4; // [mM] double Cao=2.7; // [mM] double Nao=150.5; // [mM] double Nao_naca = Nao; //// Intracellular Ionic concentrations // // Pre-dialysis double Ki=140; // [mM] & 140 in TT04 double Nai=7; // [mM] //// Intracellular Volumes double Vc=16.404*RaCm; double Vsr=1.094*RaCm; double capacitance=0.185*1000*RaCm; //// Flag to choose between epi, endo and M cell types int epi=1; int endo=0; int Mcell=0; //// Ionic Currents //// Fast Na+ Current double Vh_h=-73; double k_h=5.6; double Gnamax=14.838*RaINa; // [nS/pF] maximal INa conductance //// If Current double Gf=0.090926*RaIf; double x0=-89.73015*Rax0; double dx=11.7335*Radx; //// L-type Ca2+ Current double GCaL=0.000175*RaICaL; // [m^3/F/s] maximal ICaL conductance //// T-type Ca2+ Current double GICaT = 0.1832*RaICaT; //[S/F] //// Transient Outward Current double GItoepi=0.294*RaIto; // [S/F] maximal ITo conductance double GItoendo=73; // [S/F] maximal ITo conductance double GItoMcell=294; // [S/F] maximal ITo conductance int soepi=1; int soendo=1; //// IKs double GKsepi =0.157*RaIKs; //245; //[S/F] maximal IKs conductance double GKsendo =157; //245;// [S/F] maximal IKs conductance double GKsMcell =40; //62;// [S/F] maximal IKs conductance double pKNa=0.03; // [ ] //// IKr double GKr=0.096*sqrt(Ko/5.4)*RaIKr; //GKr=96 nS/pF maximal IKr conductance double Q=2.3; double L0=0.025; double Kc=0.58e-3; double Ka=2.6e-3; //// Inward Rectifier K+ Current double gK1max=5.405*sqrt(Ko/5.4)*RaIK1; // maximal IK1 conductance //// Na+/Ca2+ Exchanger Current double knaca=1000*RaINaCa; // [pA/pF] maximal INaCa double KmNai=87.5; // [mM] Nai half saturation constant double KmCa=1.38; // [mM] Cai half saturation constant double ksat=0.1; // [dimensionless] saturation factor for INaCa double n=0.35; // [dimensionless] voltage dependence parameter //// Na+/K+ Pump Current double knak=1.362*RaINaK; // [pA/pF] maximal INaK double KmK=1; // [mM] Ko half saturation constant double KmNa=40; // [mM] Nai half saturation constant //// IpCa double GpCa=0.825*RaICap; // [pA/pF] maximal IpCa double kpca=0.0005; // [mM] Cai half saturation constant //// IpK double GpK=0.0146*RaIKp; // [nS/F] maximal IpK conductance //// Background Currents double GbNa=0*0.29*RaIback; // [nS/pF] maximal IbNa conductance double GbCa=0.000592*RaIback; // [nS/pF] maximal IbCa conductance //// Calcium Dynamics //// Ileak double Vleak=0.00008*RaIleak; // [1/ms] maximal Ileak =0.00008/s //// Irel double arel=0.016464; // [mM/ms] maximal CaSR-dependent Irel double brel=0.25; // [mM] CaSR half saturation constant double crel=0.008232; // [mM/ms] maximal CaSR-independent Irel //// Iup double Vmaxup=0.000425*RaIup; //[mM/ms] // 0.000425; // [mM/ms] maximal Iup double Kup=0.00025;//0.00025; // [mM] half saturation constant //APD paramters double dvdt,dvdtold; double vnew; int main(){ FILE *output; int file_output_counter=0; double RTONF, Ek, Ena, Eks, Eca, Ef; double V, Cai, CaSR, alpha_K1, beta_K1, x_K1_inf; double alpha_m, beta_m, tau_m, m_inf, alpha_h, beta_h, tau_h, h_inf, alpha_j, beta_j, tau_j, j_inf, alpha_d, beta_d, gamma_d, tau_d, d_inf, f_inf, tau_f, g_inf, tau_g, constg, f_ca_inf, tau_f_ca, constf_ca, r_inf, tau_r, s_inf, tau_s, alpha_xs, beta_xs, xs_inf, tau_xs, alpha_xr1, beta_xr1, xr1_inf, tau_xr1, alpha_xr2, beta_xr2, xr2_inf, tau_xr2, xf_inf, tau_xf, dCaT_inf, tau_dCaT, fCaT_inf, tau_fCaT; double INa, m, h, j, ICaL, d, df, tempf, f, g, f_ca, Ito, r, s, IKr, xr1, xr2, IKs, xs, IK1, INaCa, INaK, IpCa, IpK, IbNa, IbCa, Istim,If,xf,ICaT,dCaT,fCaT, Itotal; double Ileak, Iup, Irel, CaBuf, CaCSQN, CaCurrent, CaSRCurrent, dCaSR, bjsr, cjsr, dCai, bc, cc; output = fopen( output_file_name , "w" ); //Initial values #ifdef INITIALVALS V= -70; Cai = 0.0002; CaSR = 0.2; m = 0.; h = 0.75; j = 0.75; xr1 = 0.; xr2 = 1.; xs = 0.; r = 0.; s = 1.; d = 0.; f = 1.; f_ca = 1.; g = 1.; //Initialization parameters added for hESC_Cm model xf=0.1; dCaT=0.; fCaT=1.; #endif #ifndef INITIALVALS //Initial Conditions after 250 seconds ~100 beats #ifdef EARLY V = -0.069160; Cai = 0.000027; CaSR = 0.086301; m = 0.041569; h = 0.600505; j = 0.618972; xr1 = 0.001208; xr2 = 0.313321; xs = 0.010087; r = 0.000000; s = 0.999948; d = 0.001452; f = 0.999173; f_ca = 1.002065; g = 1.000000; dCaT = 0.000789; fCaT = 0.797842; xf = 0.014191; #endif #ifdef LATE //Initial Conditions after 100 seconds V = -70.350507; Cai = 0.000072; CaSR = 0.095304; m = 0.033609; h = 0.226380; j = 0.194417; xr1 = 0.034771; xr2 = 0.324050; xs = 0.009288; r = 0.000000; s = 0.999958; d = 0.001174; f = 0.998545; f_ca = 0.995698; g = 0.999920; dCaT = 0.000647; fCaT = 0.828093; xf = 0.010919; #endif #endif RTONF = (R*T)/F; for(counter=0;counter<beats;counter++){ vmin[counter] = 100000.0; vmax[counter] = -10000.0; dvdtmax[counter] = -10000.0; ddr[counter] = -10000.0; APA[counter] = 10000.0; top[counter] = 10000.0; top_slope[counter] = -10000.0; apd30[counter] = -10000.0; apd50[counter] = -10000.0; apd70[counter] = -10000.0; apd90[counter] = -10000.0; bcl[counter] = -10000.0; } printf("Vmin(mV)\tVmax(mV)\tdVdtmax(mV/s)\tAPD30(ms)\tAPD50(ms)\tAPD70(ms)\tAPD90(ms)\tFreq.(bpm)\tDDR(mV/s)\tTOP(mV)\tAPA(mV)\n"); counter =0; start_output = 0; dvdt = 1000.0; dvdtold = 500.0; start_output = 0; t=tmin; for (t = tmin + DT; t<=tmax; t+=DT) { if ((Ikrblock) && (t > (blocktime))){ #ifdef EARLY E4031 = 0.5; #endif #ifdef LATE E4031 = 0.4; #endif } //Reversal potentials Eca = 0.5*(R*T/F)*log(Cao/Cai); Ek = (R*T/F)*log(Ko/Ki); Ena = (R*T/F)*log(Nao/Nai); Eks = (R*T/F)*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); /////////////////////////////////////////////////////////////////////////////////////////////// //INa m gate////////////////////////////////////////////////////////////// alpha_m = 1/(1+exp((-60-V)/5)); beta_m = 0.1/(1+exp((V+35)/5))+0.1/(1+exp((V-50)/200)); tau_m = alpha_m*beta_m; m_inf = 1/((1+exp((-56.86-V)/9.03))*(1+exp((-56.86-V)/9.03))); m = m_inf-(m_inf-m)*exp(-DT/(tau_m)); //INa, h gate ///////////////////////////////////////////////////////////// #ifdef EARLY h_inf = pow((1/(1+exp((V-Vh_h)/k_h))),0.5); #endif #ifdef LATE h_inf = 1/((1+exp((V+71.55)/7.43))*(1+exp((V+71.55)/7.43))); #endif if ( V >= -40. ){ alpha_h = 0.; beta_h = ((0.77/(0.13*(1+exp(-(V+10.66)/11.1))))); } else{ alpha_h = (0.057*exp(-(V+80)/6.8)); beta_h = (2.7*exp(0.079*V)+(3.1e5)*exp(0.3485*V)); } tau_h = 2.8/(alpha_h+beta_h); h = h_inf-(h_inf-h)*exp(-DT/(tau_h)); // dhdt = (h_inf-h)/(myCoefTauH/(beta_h+alpha_h))*1000*slo; //INa j gate/////////////////////////////////////////////////////////////// //j_inf varies depending on the cell type//////////////////////////////// #ifdef EARLY j_inf = pow((1/(1+exp((V-Vh_h)/k_h))),0.5); #endif #ifdef LATE j_inf = 1/((1+exp((V+71.55)/7.43))*(1+exp((V+71.55)/7.43))); #endif if( V >= -40. ){ alpha_j = 0.0; beta_j = ((0.6*exp((0.057)*V)/(1+exp(-0.1*(V+32))))); } else{ alpha_j = (-(25428)*exp(0.2444*V)-(0.000006948)*exp(-0.04391*V))*(V+37.78)/(1+exp(0.311*(V+79.23))); beta_j = ((0.02424*exp(-0.01052*V)/(1+exp(-0.1378*(V+40.14))))); } tau_j = 1.0/(alpha_j+beta_j); j = j_inf-(j_inf-j)*exp(-DT/tau_j); //djdt = (j_inf-j)/(myCoefTauJ/(alpha_j+beta_j))*1000*slo; //ICaL, d gate, and Irel d gate////////////////////////////////////////// alpha_d = 1.4/(1+exp((-35-V)/13))+0.25; beta_d = 1.4/(1+exp((V+5)/5)); gamma_d = 1/(1+exp((50-V)/20)); tau_d = alpha_d*beta_d+gamma_d; d_inf = 1/(1+exp(-(V-Vh_dCa)/kCa)); //dddt = (d_inf-d)/tau_d*1000*slo; d = d_inf-(d_inf-d)*exp(-DT/tau_d); //ICaL, f gate/////////////////////////////////////////////////////////// f_inf = 1/(1+exp((V+myVhfCaL)/myKfCaL)); #ifdef EARLY //Equations for this parameter is a bit confusing must email author tau_f = 100.; #endif #ifdef LATE if(f_inf > f){ tau_f = (1125*exp(-((V-myTauFShift)+27)*((V-myTauFShift)+27)/240)+80+165/(1+exp((25-(V-myTauFShift))/10)))*(1+KtaufCa*(Cai-.5e-4)); } else{ tau_f = (1125*exp(-((V-myTauFShift)+27)*((V-myTauFShift)+27)/240)+80+165/(1+exp((25-(V-myTauFShift))/10))); } #endif f = f_inf-(f_inf-f)*exp(-DT/tau_f); //dfdt = (f_inf-f)/tau_f*1000*slo; //ICaL, fCa gate/////////////////////////////////////////////////////// done #ifdef EARLY f_ca_inf = (1/(1+(pow(((Cai-myShiftFCaInf)/0.000325),8)))+0.1/(1+exp(((Cai-myShiftFCaInf)-0.0005)/0.0001))+0.2/(1+exp(((Cai-myShiftFCaInf)-0.00075)/0.0008))+0.23)/1.46; #endif #ifdef LATE f_ca_inf = (1/(1+(pow((Cai/0.0006),8)))+0.1/(1+exp((Cai-0.0009)/0.0001))+0.3/(1+exp((Cai-0.00075)/0.0008)))/1.3156; #endif tau_f_ca = 2.0;//ms if ( V > -60.0 ){ if ( f_ca_inf > f_ca ){ f_ca = f_ca;//Note the integral of dfCa/dt = 0 is fCa } else{ f_ca = f_ca_inf-(f_ca_inf-f_ca)*exp(-DT/tau_f_ca); } } else{ f_ca = f_ca_inf-(f_ca_inf-f_ca)*exp(-DT/tau_f_ca); } //df_cadt = (f_ca_inf-f_ca)/tau_f_ca*1000*slo*(1-(f_ca_inf>f_ca)*(V>-0.06)); //cout <<"Calculated gates for ICaL"<<endl; //Irel, g gate////////////////////////////////////////////////////////// done tau_g = 2.0;//units in ms if (Cai<=0.00035){ g_inf = (1/(1+pow((Cai/0.00035),6))); } else{ g_inf = (1/(1+pow((Cai/0.00035),16))); } if ( V > -60.0 ){ if ( g_inf > g ){ g = g; } else{ g = g_inf-(g_inf-g)*exp(-DT/tau_g); } } else{ g = g_inf-(g_inf-g)*exp(-DT/tau_g); } //dgdt = (g_inf-g)/tau_g*1000*slo*(1-(g_inf>g)*(V>-0.06)); //Ito, r gate/////////////////////////////////////////////////////// done r_inf = 1/(1+exp((-V+20+myShiftItoR)/(6*mySlopeItoR))); tau_r = myConstTauR*(9.5*exp(-pow((V+40),2)/1800)+0.8); //drdt = (r_inf-r)/tau_r*1000*slo; r = r_inf-(r_inf-r)*exp(-DT/tau_r); //Ito, s gate/////////////////////////////////////////////////////// done s_inf = 1/(1+exp((V+20+myShiftItoS)/(5*mySlopeItoS))); tau_s = myConstTauS*(85*exp(-(V+45)*(V+45)/320)+5/(1+exp((V-20)/5))+3); //dsdt = (s_inf - s)/tau_s *1000*slo; s = s_inf-(s_inf-s)*exp(-DT/tau_s); //cout <<"Calculated gates for Ito"<<endl; //IKs, Xs gate/////////////////////////////////////////////////////// done xs_inf = 1/(1+exp((-5-V)/14)); alpha_xs = 1100/(sqrt(1+exp((-10-V)/6))); beta_xs = 1/(1+exp((V-60)/20)); tau_xs = alpha_xs*beta_xs; //dxsdt = ((xs_inf-xs)/(alpha_xs*beta_xs))*slo*1000; xs = xs_inf-(xs_inf-xs)*exp(-DT/tau_xs); //cout <<"Calculated gates for IKs"<<endl; //IKr, Xr1 gate/////////////////////////////////////////////////////// done //parameter added for rapid delayed rectifier current xr1_inf = 1/(1+exp((((-R*T/F/Q*log(1/pow(((1+Cao*0.001/Kc)/(1+Cao*0.001/Ka)),4)/L0))-26)-(V-myShift))/7)); alpha_xr1 = 450/(1+exp((-45-(V-myShift))/(10))); beta_xr1 = 6/(1+exp(((V-myShift)-(-30))/11.5)); tau_xr1 = alpha_xr1*beta_xr1; //dxr1dt = ((xr1_inf-xr1)/(myRedTauxr1*alpha_xr1*beta_xr1 ))*1000; xr1 = xr1_inf-(xr1_inf-xr1)*exp(-DT/tau_xr1); //IKr, Xr2 gate////////////////////////////////////////////////////// done xr2_inf = 1/(1+exp(((V-myShift)-(-88))/24)); alpha_xr2 = 3/(1+exp((-60-(V-myShift))/20)); beta_xr2 = 1.12/(1+exp(((V-myShift)-60)/20)); tau_xr2 = alpha_xr2*beta_xr2; //dxr2dt = ((xr2_inf-xr2)/(myRedTauxr2*alpha_xr2*beta_xr2))*1000; xr2 = xr2_inf-(xr2_inf-xr2)*exp(-DT/tau_xr2); //If, Xf gate////////////////////////////////////////////////////////done tau_xf = 1900;//ms xf_inf = 1/(1+exp((V-(-102.4))/(7.6))); //xf_inf = 1/(1 + exp((u*1000-x0)/dx)); //dxfdt=(xf_inf-xf)/tauif*1000; xf = xf_inf-(xf_inf-xf)*exp(-DT/tau_xf); //xf = xf + DT*((xf_inf-xf)/tau_xf*1000); //ICaT, dCaT gate//////////////////////////////////////////////////// done dCaT_inf = 1/(1+exp(-(V+26.3)/(6))); tau_dCaT = 1/(1.068*exp((V+26.3)/(30))+1.068*exp(-(V+26.3)/(30))); //ddCaTdt = (dCaT_inf-dCaT)/tau_dCaT*1000*slo; dCaT = dCaT_inf-(dCaT_inf-dCaT)*exp(-DT/tau_dCaT); //dCaT = dCaT + DT *((dCaT_inf - dCaT)/tau_dCaT*1000); //ICaT, fCaT gate//////////////////////////////////////////////////// done fCaT_inf = 1/(1+exp((V+61.7)/(5.6))); tau_fCaT = 1/(0.0153*exp(-(V+61.7)/(83.3))+ 0.015*exp((V+61.7)/(15.38))); //dfCaTdt = (fCaT_inf-fCaT)/tau_fCaT*1000*slo; fCaT = fCaT_inf-(fCaT_inf-fCaT)*exp(-DT/tau_fCaT); //fCaT = fCaT + DT *((fCaT_inf - fCaT)/tau_fCaT*1000); //IK1, alphas and betas////////////////////////////////////////////// done alpha_K1 = 0.1/(1+exp(0.06*((V-myShiftK1)-Ek-200))); beta_K1 = (3*exp(0.0002*((V-myShiftK1)-Ek+100))+exp(0.1*((V-myShiftK1)-Ek-10)))/(1+exp(-0.5*((V-myShiftK1)-Ek))); x_K1_inf = alpha_K1/(alpha_K1+beta_K1); //Na+ current, INa done INa = Gnamax*m*m*m*h*j*(V-Ena); //L-type Ca2+ current, ICaL done ICaL = GCaL*d*f*f_ca*4*V*(F*F)/R/T*(Cai*exp(2*V*F/R/T)-0.341*Cao)/(exp(2*V*F/R/T)-1); //Transient outward current, Ito done Ito = GItoepi*r*s*(V-Ek); //Rapid delayed rectifier K+ current, IKr done IKr = E4031*GKr*xr1*xr2*(V-Ek); //Slow delayed rectifier K+ current, IKs, added a scaling factor (1+0.6/(1+pow((3.8e-5/Cai),1.4)) IKs = GKsepi*(1+.6/pow((1+(3.8e-5/Cai)),1.4))*xs*xs*(V-Eks); //Inward rectifier K+ current, IK1 done IK1=x_K1_inf*gK1max*(V-Ek); //Na+/Ca2+ exchanger current, INaCa, not than n represents lambda done INaCa = knaca*(1/(KmNai*KmNai*KmNai+Nao_naca*Nao_naca*Nao_naca))*(1/(KmCa+Cao))*(1/(1+ksat*exp((n-1)*V*F/(R*T))))*(exp(n*V*F/(R*T))*Nai*Nai*Nai*Cao-exp((n-1)*V*F/(R*T))*Nao_naca*Nao_naca*Nao_naca*Cai*alfa); //Na+/K+ pump current, INaK, note that code uses knak variable for pnak //INaK = knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*(1./(1.+0.1245*exp(-0.1*V*F/(R*T))+0.0353*exp(-V*F/(R*T)))); INaK = (1/(1+0.1245*exp(-0.1*V*F/(R*T))+0.0353*exp(-V*F/(R*T))))*(knak*Ko/(Ko+KmK)*Nai/(Nai+KmNa)); //Calcium pump current, IpCa done IpCa = GpCa*Cai/(kpca+Cai); //Plateau K+ current done IpK = GpK*(V-Ek)*(1/(1+exp((25-V)/5.98))); //Background sodium current done IbNa = GbNa*(V-Ena); //Calcium background current, IbCa done IbCa = GbCa*(V-Eca); //Currents added for the hESC_CM model ////Hyperpolarization activated funny current, If note this is a new current incorporated into the model //not initially in the ten Tusscher model done If = Gf*xf*(V+17); //T-type Ca2+ Current, ICaT, not originally in the tentusscher model done ICaT = dCaT*fCaT*GICaT*(V-Eca); dvdtold = dvdt; Itotal = INa + ICaL + Ito + IKr + IKs + IK1 + INaCa + INaK + IpCa + IbNa + IpK + IbCa + If + ICaT; Ileak = Vleak*(CaSR-Cai); Iup = Vmaxup/(1.+((Kup*Kup)/(Cai*Cai))); //modified by RaIrel Irel = (d*g*(crel+arel*(CaSR*CaSR)/((brel*brel)+(CaSR*CaSR))))*RaIrel; //Analytic solution of calcium dynamics taken from Pete Jordan's version of the original Ten //Tusscher model CaBuf = Bufc*Cai/(Cai+Kbufc); CaCSQN = Bufsr*CaSR/(CaSR+Kbufsr); CaSRCurrent = Iup-Irel-Ileak; //Added ICaT to CaCurrent CaCurrent = -(ICaL+IbCa+ICaT+IpCa-2.0*INaCa)*(1.0/(2.0*Vc*F))*capacitance; dCaSR = DT*(Vc/Vsr)*CaSRCurrent; bjsr = Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr = Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR = (sqrt(bjsr*bjsr+4*cjsr)-bjsr)/2; dCai = DT*(CaCurrent-CaSRCurrent); bc = Bufc-CaBuf-dCai-Cai+Kbufc; cc = Kbufc*(CaBuf+dCai+Cai); Cai = (sqrt(bc*bc+4*cc)-bc)/2; file_output_counter++; dvdt = -Itotal; vnew = V+DT*dvdt; //Method of calculation of parameters taken from Kharche from modelDB if(dvdt>=0.0 && dvdtold<0.0){ vmin[counter] = V; tvmin[counter] = t; start_output = 1; } if(dvdt>dvdtmax[counter]&&start_output>0){ dvdtmax[counter] = dvdt; apd_start[counter] = t; } if(dvdtold>0.0 && dvdt<=0.0){ vmax[counter] = V; APA[counter] = vmax[counter] - vmin[counter]; top_slope[counter] = (vmax[counter]-vmin[counter])/(t - tvmin[counter]); } if((counter>0)&&(dvdtold <= top_slope[counter-1]) && (dvdt>top_slope[counter-1])){ top[counter] = V; ttop[counter] = t; ddr[counter] = (V - vmin[counter])/(t - tvmin[counter]); } if((vnew <= (top[counter] + 0.7*APA[counter])) && (V > (top[counter] + 0.7*APA[counter])) ){ if(apd_start[counter]>0.0) apd30[counter] = t - apd_start[counter]; } if((vnew <= (top[counter] + 0.5*APA[counter])) && (V > (top[counter] + 0.5*APA[counter])) ){ if(apd_start[counter]>0.0) apd50[counter] = t - apd_start[counter]; } if((vnew <= (top[counter] + 0.3*APA[counter])) && (V > (top[counter] + 0.3*APA[counter])) ){ //cout << vnew << " " << (top[counter] + 0.3*APA[counter]) << " "<< V << endl; if(apd_start[counter]>0.0) apd70[counter] = t - apd_start[counter]; } if((vnew <= (0.9*vmin[counter])) && (V > (0.9*vmin[counter]))){//Algorith fails for the case of APD90 if(apd_start[counter]>0.0){ apd_end[counter] = t; apd90[counter] = t - apd_start[counter]; } } if (start_output && (apd_end[counter] > 0.0)){ bcl[counter] = apd_start[counter]-apd_start[counter-1]; printf("%10.5f\t",vmin[counter]); printf("%10.5f\t",vmax[counter]); printf("%10.5f\t",dvdtmax[counter]); printf("%10.5f\t",apd30[counter]); printf("%10.5f\t",apd50[counter]); printf("%10.5f\t",apd70[counter]); printf("%10.5f\t",apd90[counter]); printf("%10.5f\t",(60000/bcl[counter]));//convert cycle length to beats per minute printf("%10.5f\t",ddr[counter]); printf("%10.5f\t",top[counter]);//take off potential printf("%10.5f\t",APA[counter]); printf("\n"); counter++; } V = vnew; if((file_output_counter%1000==0) && (t>200000)) { // if(print_header){ // print_header = false; // } //fprintf( output, "%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\n", time+(number-1)*basic_bcl, V, m, h, j, d, f, g, f_ca, r, s, xs, xr1, xr2 ); //fprintf( output, "%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.105f\t%4.10f\t%4.10f\t%4.10f\n", time+(number-1)*basic_bcl, Ileak, Iup, Irel, CaBuf, CaSR, Cai, Nai, Ki, V ); //fprintf( output, "%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\t%4.10f\n", t, IKr, IKs, IK1, Ito, INa, If, INaK, ICaL, IbCa, INaCa, V, ICaT, Cai, IpCa, Irel, Itotal,dvdt ); fprintf( output, "%4.10f\t%4.10f\t%4.10f\n", t/1000,V/1000, dvdt); } } printf( "\nV = %f;\nCai = %f;\nCaSR = %f;\nm = %f;\nh = %f;\nj = %f;\nxr1 = %f;\nxr2 = %f;\nxs = %f;\nr = %f;\ns = %f;\nd = %f;\nf = %f;\nf_ca = %f;\ng = %f;\ndCaT = %f;\nfCaT = %f;\nxf = %f;\n", V, Cai, CaSR, m, h, j, xr1, xr2, xs, r, s, d, f, f_ca,g, dCaT, fCaT, xf ); fclose( output ); return 0; }
9db98922b7b46e5b8b52aa4c81673408d7f25ba0
eee5fc5e9e1bd9ababc9cf8ccb8add19c9219ca3
/ABC/098/c.cpp
e4837447e5ab5f5a1248a12f529ea6f282de6840
[]
no_license
matatabinoneko/Atcoder
31aa0114bde28ab1cf528feb86d1e70d54622d84
07cc54894b5bcf9bcb43e57a67f2a0cbb2714867
refs/heads/master
2021-11-13T04:39:13.824438
2021-10-31T01:42:52
2021-10-31T01:42:52
196,823,857
0
0
null
null
null
null
UTF-8
C++
false
false
407
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int main(void){ int n; cin >> n; string s; cin >> s; vector<int>l(n),r(n); l[0]=0;r[n-1]=0; for(int i=1;i<n;i++) l[i]=l[i-1]+(s[i-1]=='W'); for(int i=n-2;0<=i;i--) r[i] = r[i+1] + (s[i+1]=='E'); ll ans = n*2; for(int i=0;i<n;i++) if(r[i]+l[i] < ans) ans = r[i]+l[i]; cout << ans << endl; return 0; }