blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
1bcb558f793b038a91e13d3f71f6aa226583bccd
6115b3898bb02e46af87d8b6c6bbf5254b432047
/NOT_REALLY_A_Training_Bot/src/main/include/Commands/LiftDown.h
313dbb4f4bd26e668e7d99d8c644a5c222310091
[]
no_license
cgzog/Programming-Training
5a1bfb35b26ac5f4900e45c236a7c65d1cea5c25
a6c2d155386f9a4be51848c5cf5354494f331bfc
refs/heads/master
2023-04-02T04:33:40.791361
2021-04-08T03:44:42
2021-04-08T03:44:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
738
h
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #pragma once #include <Commands/Command.h> class LiftDown : public frc::Command { public: LiftDown(); void Initialize() override; void Execute() override; bool IsFinished() override; void End() override; void Interrupted() override; };
[ "cyborgs@D-CYB-04.jths.org" ]
cyborgs@D-CYB-04.jths.org
deb8d22b17cc02d6bbdbe6b3dff7efe9aab3eb8b
f08b019f7d49fa6057da59c3c5cf8339263aa945
/chapter03/3_4.cpp
96df9af8be9e644ddc9ff15fc182bcba6da66380
[]
no_license
rocky946/data-structure-course
38be4738703165448354fc632e8d60e0ef7a5568
53b82c53a8db787d9e52c5249b989e7305775e76
refs/heads/master
2023-01-23T11:52:13.318226
2020-11-19T06:49:06
2020-11-19T06:49:06
257,018,601
0
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
#include <stdio.h> #include "sq_stack.h" /** * 判断str是否为对称串 * @param str * @return */ bool Symmetry(ElemType str[]) { SqStack *stack = nullptr; InitStack(stack); int i = 0; while (str[i] != '\0') { Push(stack, str[i]); i++; } int j = 0; ElemType e; while (!StackEmpty(stack)) { Pop(stack, e); if (str[j] != e) { DestroyStack(stack); return false; } j++; } DestroyStack(stack); return true; } int main() { ElemType e[6] = {'2', '2', '3', '2', '1', '\0'}; bool ret = Symmetry(e); printf("ret: %d\n", ret); return 0; }
[ "rocky946@outlook.com" ]
rocky946@outlook.com
d0569a13cf7953744e06eb102c5f19ebd06fa883
ee03435aba4c70ad0464d9d9cc9b78884ff50b28
/src/chainparams.cpp
f13ce468b693f0dd7187a90ff2ed4b7e95d61af5
[ "MIT" ]
permissive
dashero/dsr1
1ed03db021af70dd1aba82d26419d7fa3d4c9a0c
66848fd55f2c6e4c4f65414a2bf16f0fea81ef67
refs/heads/master
2021-09-01T06:03:00.837967
2017-12-25T08:07:10
2017-12-25T08:07:10
115,318,787
0
0
null
null
null
null
UTF-8
C++
false
false
23,239
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. //#include <stdio.h> #include "globals.h" #include "chainparams.h" #include "consensus/merkle.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" #include <assert.h> #include <boost/assign/list_of.hpp> #include "chainparamsseeds.h" static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { CMutableTransaction txNew; txNew.nVersion = 1; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = genesisReward; txNew.vout[0].scriptPubKey = genesisOutputScript; CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(txNew); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = BlockMerkleRoot(genesis); return genesis; } /** * Build the genesis block. Note that the output of its generation * transaction cannot be spent since it did not originally exist in the * database. * */ static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = GENESIS_TIME_STAMP; const CScript genesisOutputScript = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } /** * Main network */ /** * What makes a good checkpoint block? * + Is surrounded by blocks with reasonable timestamps * (no blocks before with a timestamp after, none after with * timestamp before) * + Contains no strange transactions */ class CMainParams : public CChainParams { public: CMainParams() { strNetworkID = "main"; consensus.nSubsidyHalvingInterval = 210240; // Note: actual number of blocks per calendar year with DGW v3 is ~200700 (for example 449750 - 249050) consensus.nMasternodePaymentsStartBlock = 1750; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock consensus.nMasternodePaymentsIncreaseBlock = 1750; // actual historical value consensus.nMasternodePaymentsIncreasePeriod = 576*30; // 17280 - actual historical value consensus.nInstantSendKeepLock = 24; consensus.nBudgetPaymentsStartBlock = 1750; // actual historical value consensus.nBudgetPaymentsCycleBlocks = 16616; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725 consensus.nBudgetPaymentsWindowBlocks = 100; consensus.nBudgetProposalEstablishingTime = 60*60*24; consensus.nSuperblockStartBlock = 1750; // The block at which 12.1 goes live (end of final 12.0 budget cycle) consensus.nSuperblockCycle = 16616; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725 consensus.nGovernanceMinQuorum = 10; consensus.nGovernanceFilterElements = 20000; consensus.nMasternodeMinimumConfirmations = 15; consensus.nMajorityEnforceBlockUpgrade = 750; consensus.nMajorityRejectBlockOutdated = 950; consensus.nMajorityWindow = 1000; consensus.BIP34Height = 227931; consensus.BIP34Hash = uint256S("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"); consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000"); consensus.nPowTargetTimespan = 24 * 60 * 60; // Dash: 1 day consensus.nPowTargetSpacing = 2.5 * 60; // Dash: 2.5 minutes consensus.fPowAllowMinDifficultyBlocks = false; consensus.fPowNoRetargeting = false; consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1486252800; // Feb 5th, 2017 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1517788800; // Feb 5th, 2018 /** * The message start string is designed to be unlikely to occur in normal data. * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 32-bit integer with any alignment. */ pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0x0c; pchMessageStart[2] = 0x6b; pchMessageStart[3] = 0xbd; vAlertPubKey = ParseHex("048240a8748a80a286b270ba126705ced4f2ce5a7847b3610ea3c06513150dade2a8512ed5ea86320824683fc0818f0ac019214973e677acd1244f6d0571fc5103"); nDefaultPort = DEFAULT_PORT; nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin nPruneAfterHeight = 100000; // compute the nNonce /* for(uint32_t ii=1500000;ii<2000000;ii++) { genesis = CreateGenesisBlock(GENESIS_BLOCK_TIME, ii, 0x1e0ffff0, 1, 50 * COIN); consensus.hashGenesisBlock = genesis.GetHash(); LogPrintf("nNonce = %9u, hash = %s, MerkleRoot = %s\n",ii,consensus.hashGenesisBlock.GetHex(),genesis.hashMerkleRoot.GetHex()); if(ii%10000 == 0) printf("%9u\n",ii); } */ // genesis = CreateGenesisBlock(GENESIS_BLOCK_TIME, GENESIS_BLOCK_NONCE, 0x1e0ffff0, 1, 50 * COIN); consensus.hashGenesisBlock = genesis.GetHash(); LogPrintf("nNonce = %9u, hash = %s, MerkleRoot = %s\n",GENESIS_BLOCK_NONCE,consensus.hashGenesisBlock.GetHex(),genesis.hashMerkleRoot.GetHex()); // assert(consensus.hashGenesisBlock == uint256S(GENESIS_BLOCK_HASH)); // assert(genesis.hashMerkleRoot == uint256S(GENESIS_BLOCK_MERKLE)); vSeeds.push_back(CDNSSeedData("23.91.97.27", "23.91.97.27"));//ucloud-hk-ubuntu vSeeds.push_back(CDNSSeedData("106.75.99.86", "106.75.99.86"));//ucloud-bj-ubuntu vSeeds.push_back(CDNSSeedData("seed1.puzcoin.com","seed1.puzcoin.com"));//seed-1-hk vSeeds.push_back(CDNSSeedData("seed2.puzcoin.com","seed2.puzcoin.com"));//seed-2-europe vSeeds.push_back(CDNSSeedData("seed3.puzcoin.com","seed3.puzcoin.com"));//seed-3-america // Dash addresses start with 'R' base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>PREFIXES_PUBKEY_ADDRESS; // Dash script addresses start with '7' base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>PREFIXES_SCRIPT_ADDRESS; // Dash private keys start with '7' or 'V' base58Prefixes[SECRET_KEY] = std::vector<unsigned char>PREFIXES_SECRET_KEY; // Dash BIP32 pubkeys start with 'xpub' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); // Dash BIP32 prvkeys start with 'xprv' (Bitcoin defaults) base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); // Dash BIP44 coin type is '5' base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x05).convert_to_container<std::vector<unsigned char> >(); vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main)); fMiningRequiresPeers = false; fDefaultConsistencyChecks = false; fRequireStandard = true; fMineBlocksOnDemand = false; fTestnetToBeDeprecatedFieldRPC = false; nPoolMaxTransactions = 3; nFulfilledRequestExpireTime = 60*60; // fulfilled requests expire in 1 hour strSporkPubKey = "04549ac134f694c0243f503e8c8a9a986f5de6610049c40b07816809b0d1d06a21b07be27b9bb555931773f62ba6cf35a25fd52f694d4e1106ccd237a7bb899fdd"; strMasternodePaymentsPubKey = "04549ac134f694c0243f503e8c8a9a986f5de6610049c40b07816809b0d1d06a21b07be27b9bb555931773f62ba6cf35a25fd52f694d4e1106ccd237a7bb899fdd"; checkpointData = (CCheckpointData) { boost::assign::map_list_of /* ( 1500, uint256S("0x000000aaf0300f59f49bc3e970bad15c11f961fe2347accffff19d96ec9778e3")) ( 4991, uint256S("0x000000003b01809551952460744d5dbb8fcbd6cbae3c220267bf7fa43f837367")) ( 9918, uint256S("0x00000000213e229f332c0ffbe34defdaa9e74de87f2d8d1f01af8d121c3c170b")) ( 16912, uint256S("0x00000000075c0d10371d55a60634da70f197548dbbfa4123e12abfcbc5738af9")) ( 23912, uint256S("0x0000000000335eac6703f3b1732ec8b2f89c3ba3a7889e5767b090556bb9a276")) ( 35457, uint256S("0x0000000000b0ae211be59b048df14820475ad0dd53b9ff83b010f71a77342d9f")) ( 45479, uint256S("0x000000000063d411655d590590e16960f15ceea4257122ac430c6fbe39fbf02d")) ( 55895, uint256S("0x0000000000ae4c53a43639a4ca027282f69da9c67ba951768a20415b6439a2d7")) ( 68899, uint256S("0x0000000000194ab4d3d9eeb1f2f792f21bb39ff767cb547fe977640f969d77b7")) ( 74619, uint256S("0x000000000011d28f38f05d01650a502cc3f4d0e793fbc26e2a2ca71f07dc3842")) ( 75095, uint256S("0x0000000000193d12f6ad352a9996ee58ef8bdc4946818a5fec5ce99c11b87f0d")) ( 88805, uint256S("0x00000000001392f1652e9bf45cd8bc79dc60fe935277cd11538565b4a94fa85f")) ( 107996, uint256S("0x00000000000a23840ac16115407488267aa3da2b9bc843e301185b7d17e4dc40")) ( 137993, uint256S("0x00000000000cf69ce152b1bffdeddc59188d7a80879210d6e5c9503011929c3c")) ( 167996, uint256S("0x000000000009486020a80f7f2cc065342b0c2fb59af5e090cd813dba68ab0fed")) ( 207992, uint256S("0x00000000000d85c22be098f74576ef00b7aa00c05777e966aff68a270f1e01a5")) ( 312645, uint256S("0x0000000000059dcb71ad35a9e40526c44e7aae6c99169a9e7017b7d84b1c2daf")) ( 407452, uint256S("0x000000000003c6a87e73623b9d70af7cd908ae22fee466063e4ffc20be1d2dbc")) ( 523412, uint256S("0x000000000000e54f036576a10597e0e42cc22a5159ce572f999c33975e121d4d")) */ ( 174, uint256S("0x0000018e50574080306a385a7dd8e1aef8d47d5aeb4868306287b12564f068ad")), 1471809614, // * UNIX timestamp of last checkpoint block 1998064, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 2800 // * estimated number of transactions per day after checkpoint }; } }; static CMainParams mainParams; /** * Testnet (v3) */ class CTestNetParams : public CChainParams { public: CTestNetParams() { strNetworkID = "test"; consensus.nSubsidyHalvingInterval = 210240; consensus.nMasternodePaymentsStartBlock = 10000; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock consensus.nMasternodePaymentsIncreaseBlock = 46000; consensus.nMasternodePaymentsIncreasePeriod = 576; consensus.nInstantSendKeepLock = 6; consensus.nBudgetPaymentsStartBlock = 60000; consensus.nBudgetPaymentsCycleBlocks = 50; consensus.nBudgetPaymentsWindowBlocks = 10; consensus.nBudgetProposalEstablishingTime = 60*20; consensus.nSuperblockStartBlock = 61000; // NOTE: Should satisfy nSuperblockStartBlock > nBudgetPeymentsStartBlock consensus.nSuperblockCycle = 24; // Superblocks can be issued hourly on testnet consensus.nGovernanceMinQuorum = 1; consensus.nGovernanceFilterElements = 500; consensus.nMasternodeMinimumConfirmations = 1; consensus.nMajorityEnforceBlockUpgrade = 51; consensus.nMajorityRejectBlockOutdated = 75; consensus.nMajorityWindow = 100; consensus.BIP34Height = 21111; consensus.BIP34Hash = uint256S("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8"); consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000"); consensus.nPowTargetTimespan = 24 * 60 * 60; // Dash: 1 day consensus.nPowTargetSpacing = 2.5 * 60; // Dash: 2.5 minutes consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = false; consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017 pchMessageStart[0] = 0xce; pchMessageStart[1] = 0xe2; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0xff; vAlertPubKey = ParseHex("04517d8a699cb43d3938d7b24faaff7cda448ca4ea267723ba614784de661949bf632d6304316b244646dea079735b9a6fc4af804efb4752075b9fe2245e14e412"); nDefaultPort = 19999; nMaxTipAge = 0x7fffffff; // allow mining on top of old blocks for testnet nPruneAfterHeight = 1000; genesis = CreateGenesisBlock(1390666206UL, 3861367235UL, 0x1e0ffff0, 1, 50 * COIN); consensus.hashGenesisBlock = genesis.GetHash(); //assert(consensus.hashGenesisBlock == uint256S("0x00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c")); //assert(genesis.hashMerkleRoot == uint256S("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7")); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("dashdot.io", "testnet-seed.dashdot.io")); vSeeds.push_back(CDNSSeedData("masternode.io", "test.dnsseed.masternode.io")); // Testnet Dash addresses start with 'y' base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140); // Testnet Dash script addresses start with '8' or '9' base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); // Testnet Dash BIP32 pubkeys start with 'tpub' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); // Testnet Dash BIP32 prvkeys start with 'tprv' (Bitcoin defaults) base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); // Testnet Dash BIP44 coin type is '1' (All coin's testnet default) base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >(); vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test)); fMiningRequiresPeers = true; fDefaultConsistencyChecks = false; fRequireStandard = false; fMineBlocksOnDemand = false; fTestnetToBeDeprecatedFieldRPC = true; nPoolMaxTransactions = 3; nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes strSporkPubKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e"; strMasternodePaymentsPubKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e"; checkpointData = (CCheckpointData) { boost::assign::map_list_of ( 261, uint256S("0x00000c26026d0815a7e2ce4fa270775f61403c040647ff2c3091f99e894a4618")) ( 1999, uint256S("0x00000052e538d27fa53693efe6fb6892a0c1d26c0235f599171c48a3cce553b1")) ( 2999, uint256S("0x0000024bc3f4f4cb30d29827c13d921ad77d2c6072e586c7f60d83c2722cdcc5")) ( 12907, uint256S("0x00000067de20fd6d276ee0839a3187b203accaa5aad04ca5c17c2997e2730e4c")) ( 15590, uint256S("0x00000009df8f2ee9c230aef9dad257d82bde20ca83378a208ce5d95d29a78852")) ( 65900, uint256S("0x00000063e4e94d75d0dc075e93898444c8ef50655990dfff7c32d92a7efff671")) ( 127618, uint256S("0x0000002104a2c1fc923b0e3b74b1860236fbc2b4479a833c28abaf456ea4e466")), 1483076495, // * UNIX timestamp of last checkpoint block 168590, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 500 // * estimated number of transactions per day after checkpoint }; } }; static CTestNetParams testNetParams; /** * Regression test */ class CRegTestParams : public CChainParams { public: CRegTestParams() { strNetworkID = "regtest"; consensus.nSubsidyHalvingInterval = 150; consensus.nMasternodePaymentsStartBlock = 240; consensus.nMasternodePaymentsIncreaseBlock = 350; consensus.nMasternodePaymentsIncreasePeriod = 10; consensus.nInstantSendKeepLock = 6; consensus.nBudgetPaymentsStartBlock = 1000; consensus.nBudgetPaymentsCycleBlocks = 50; consensus.nBudgetPaymentsWindowBlocks = 10; consensus.nBudgetProposalEstablishingTime = 60*20; consensus.nSuperblockStartBlock = 1500; consensus.nSuperblockCycle = 10; consensus.nGovernanceMinQuorum = 1; consensus.nGovernanceFilterElements = 100; consensus.nMasternodeMinimumConfirmations = 1; consensus.nMajorityEnforceBlockUpgrade = 750; consensus.nMajorityRejectBlockOutdated = 950; consensus.nMajorityWindow = 1000; consensus.BIP34Height = -1; // BIP34 has not necessarily activated on regtest consensus.BIP34Hash = uint256(); consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 24 * 60 * 60; // Dash: 1 day consensus.nPowTargetSpacing = 2.5 * 60; // Dash: 2.5 minutes consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = true; consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016) consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL; pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin nDefaultPort = 19994; nPruneAfterHeight = 1000; genesis = CreateGenesisBlock(1417713337, 1096447, 0x207fffff, 1, 50 * COIN); consensus.hashGenesisBlock = genesis.GetHash(); //assert(consensus.hashGenesisBlock == uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")); //assert(genesis.hashMerkleRoot == uint256S("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7")); vFixedSeeds.clear(); //! Regtest mode doesn't have any fixed seeds. vSeeds.clear(); //! Regtest mode doesn't have any DNS seeds. fMiningRequiresPeers = false; fDefaultConsistencyChecks = true; fRequireStandard = false; fMineBlocksOnDemand = true; fTestnetToBeDeprecatedFieldRPC = false; nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes checkpointData = (CCheckpointData){ boost::assign::map_list_of ( 0, uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")), 0, 0, 0 }; // Regtest Dash addresses start with 'y' base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140); // Regtest Dash script addresses start with '8' or '9' base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19); // Regtest private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); // Regtest Dash BIP32 pubkeys start with 'tpub' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); // Regtest Dash BIP32 prvkeys start with 'tprv' (Bitcoin defaults) base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); // Regtest Dash BIP44 coin type is '1' (All coin's testnet default) base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >(); } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = 0; const CChainParams &Params() { assert(pCurrentParams); return *pCurrentParams; } CChainParams& Params(const std::string& chain) { if (chain == CBaseChainParams::MAIN) return mainParams; else if (chain == CBaseChainParams::TESTNET) return testNetParams; else if (chain == CBaseChainParams::REGTEST) return regTestParams; else throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } void SelectParams(const std::string& network) { SelectBaseParams(network); pCurrentParams = &Params(network); }
[ "akuma@mud.com.cn" ]
akuma@mud.com.cn
de8c13bf8754b1d7ce0ec5c017024a84597d7271
a05981170f4c4d4eb8bf6559990152997647dcd5
/egor_kursach-master/SKursovaya/MD5.cpp
c461134ff5a83077f9923db849d0519d63c8a004
[]
no_license
EgorWK4/OOP-cource-project-
e68fc89fbb017a6adf44d3488a1280fb9a2604d6
feb1b918d89e4c8543f9e113490b508795dfb16d
refs/heads/master
2022-03-31T18:38:04.602472
2020-01-20T04:24:31
2020-01-20T04:24:31
235,017,915
0
0
null
null
null
null
UTF-8
C++
false
false
10,293
cpp
#include"MD5.h" /* system implementation headers */ #include <cstdio> #include <msclr/marshal_cppstd.h> // Constants for MD5Transform routine. #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 /////////////////////////////////////////////// // F, G, H and I are basic MD5 functions. inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { return x & y | ~x & z; } inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { return x & z | y & ~z; } inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { return x ^ y ^ z; } inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { return y ^ (x | ~z); } // rotate_left rotates x left n bits. inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { return (x << n) | (x >> (32 - n)); } // FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. // Rotation is separate from addition to prevent recomputation. inline void MD5::FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { a = rotate_left(a + F(b, c, d) + x + ac, s) + b; } inline void MD5::GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { a = rotate_left(a + G(b, c, d) + x + ac, s) + b; } inline void MD5::HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { a = rotate_left(a + H(b, c, d) + x + ac, s) + b; } inline void MD5::II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { a = rotate_left(a + I(b, c, d) + x + ac, s) + b; } ////////////////////////////////////////////// // default ctor, just initailize MD5::MD5() { init(); } ////////////////////////////////////////////// // nifty shortcut ctor, compute MD5 for string and finalize it right away MD5::MD5(const std::string& text) { init(); update(text.c_str(), text.length()); finalize(); } ////////////////////////////// void MD5::init() { finalized = false; count[0] = 0; count[1] = 0; // load magic initialization constants. state[0] = 0x67452301; state[1] = 0xefcdab89; state[2] = 0x98badcfe; state[3] = 0x10325476; } ////////////////////////////// // decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. void MD5::decode(uint4 output[], const uint1 input[], size_type len) { for (unsigned int i = 0, j = 0; j < len; i++, j += 4) output[i] = ((uint4)input[j]) | (((uint4)input[j + 1]) << 8) | (((uint4)input[j + 2]) << 16) | (((uint4)input[j + 3]) << 24); } ////////////////////////////// // encodes input (uint4) into output (unsigned char). Assumes len is // a multiple of 4. void MD5::encode(uint1 output[], const uint4 input[], size_type len) { for (size_type i = 0, j = 0; j < len; i++, j += 4) { output[j] = input[i] & 0xff; output[j + 1] = (input[i] >> 8) & 0xff; output[j + 2] = (input[i] >> 16) & 0xff; output[j + 3] = (input[i] >> 24) & 0xff; } } ////////////////////////////// // apply MD5 algo on a block void MD5::transform(const uint1 block[blocksize]) { uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; decode(x, block, blocksize); /* Round 1 */ FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; // Zeroize sensitive information. memset(x, 0, sizeof x); } ////////////////////////////// // MD5 block update operation. Continues an MD5 message-digest // operation, processing another message block void MD5::update(const unsigned char input[], size_type length) { // compute number of bytes mod 64 size_type index = count[0] / 8 % blocksize; // Update number of bits if ((count[0] += (length << 3)) < (length << 3)) count[1]++; count[1] += (length >> 29); // number of bytes we need to fill in buffer size_type firstpart = 64 - index; size_type i; // transform as many times as possible. if (length >= firstpart) { // fill buffer first, transform memcpy(&buffer[index], input, firstpart); transform(buffer); // transform chunks of blocksize (64 bytes) for (i = firstpart; i + blocksize <= length; i += blocksize) transform(&input[i]); index = 0; } else i = 0; // buffer remaining input memcpy(&buffer[index], &input[i], length - i); } ////////////////////////////// // for convenience provide a verson with signed char void MD5::update(const char input[], size_type length) { update((const unsigned char*)input, length); } ////////////////////////////// // MD5 finalization. Ends an MD5 message-digest operation, writing the // the message digest and zeroizing the context. MD5& MD5::finalize() { static unsigned char padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; if (!finalized) { // Save number of bits unsigned char bits[8]; encode(bits, count, 8); // pad out to 56 mod 64. size_type index = count[0] / 8 % 64; size_type padLen = (index < 56) ? (56 - index) : (120 - index); update(padding, padLen); // Append length (before padding) update(bits, 8); // Store state in digest encode(digest, state, 16); // Zeroize sensitive information. memset(buffer, 0, sizeof buffer); memset(count, 0, sizeof count); finalized = true; } return *this; } ////////////////////////////// // return hex representation of digest as string std::string MD5::hexdigest() const { if (!finalized) return ""; char buf[33]; for (int i = 0; i < 16; i++) sprintf(buf + i * 2, "%02x", digest[i]); buf[32] = 0; return std::string(buf); } ////////////////////////////// std::ostream& operator<<(std::ostream& out, MD5 md5) { return out << md5.hexdigest(); } ////////////////////////////// std::string md5(const std::string str) { MD5 md5 = MD5(str); return md5.hexdigest(); } bool equals(System::String^ hash, System::String^ pass) { std::string stdHash = msclr::interop::marshal_as<std::string>(hash); std::string str = msclr::interop::marshal_as<std::string>(pass); MD5 md5 = MD5(str); return md5.hexdigest() == stdHash; }
[ "noreply@github.com" ]
EgorWK4.noreply@github.com
c5e66f987709f16058f536d2fd5d1f69f152ad35
de80b91a12b10bd962b59a89b2badbb83a0193da
/ClientProject/Mof/MofLibrary/Include/Common/MofCommonWindows.h
81b234c81efdf7aea65176bc9c478dea68810ddb
[ "MIT" ]
permissive
OIC-Shinchaemin/RatchetNclank-PrivateCopy
8845eea799b3346646c8c93435c0149e842dede8
e2e646e89ef3c29d474a503f5ca80405c4c676c9
refs/heads/main
2023-08-15T06:36:05.244293
2021-10-08T00:34:48
2021-10-08T00:34:48
350,923,064
0
0
MIT
2021-10-06T11:05:03
2021-03-24T02:35:36
C++
SHIFT_JIS
C++
false
false
4,345
h
/*************************************************************************//*! @file MofCommonWindows.h @brief ライブラリの基本定義を行う。 @author CDW @date 2014.05.14 *//**************************************************************************/ //ONCE #ifndef __MOFCOMMONWINDOWS__H__ #define __MOFCOMMONWINDOWS__H__ #ifdef MOFLIB_WINDOWS_DESKTOP #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <mmsystem.h> #include <shellapi.h> #include <shlwapi.h> #include <Commdlg.h> #include <process.h> #include <tchar.h> #include <direct.h> #pragma comment(lib,"shlwapi.lib") #pragma comment(lib,"winmm.lib") #pragma comment(lib,"Comctl32.lib") typedef HWND MofWindowHandle; typedef HINSTANCE MofInstanceHandle; typedef HICON MofIconHandle; typedef HCURSOR MofCursorHandle; typedef LRESULT MofProcResult; typedef WPARAM MofProcParamW; typedef LPARAM MofProcParamL; typedef HANDLE MofThreadID; typedef CRITICAL_SECTION MofLock; typedef HANDLE MofSemaphore; #else #define WIN32_LEAN_AND_MEAN #include <wrl.h> #include <wrl/client.h> #include <roapi.h> #include <Windows.h> #include <process.h> #include <tchar.h> #include <agile.h> #include <ppltasks.h> #include <Collection.h> typedef Windows::UI::Core::CoreWindow^ MofWindowHandle; typedef HINSTANCE MofInstanceHandle; typedef HICON MofIconHandle; typedef HCURSOR MofCursorHandle; typedef LRESULT MofProcResult; typedef WPARAM MofProcParamW; typedef LPARAM MofProcParamL; typedef HANDLE MofThreadID; typedef CRITICAL_SECTION MofLock; typedef HANDLE MofSemaphore; #endif #define MOF_ALIGNED16(a) __declspec(align(16)) a #define MOF_ALIGNED16_CLASS MOF_ALIGNED16(class) MOFLIBRARY_API #define MOF_ALIGNED16_STRUCT struct MOFLIBRARY_API //#define MOF_ALIGNED16_STRUCT MOF_ALIGNED16(struct) MOFLIBRARY_API #if defined(DEBUG) || defined(_DEBUG) #include <crtdbg.h> template <class T> T& PLACEMENT_NEW(T &p) { new (&p) T(); return p; } template <class T1, class T2> T1& PLACEMENT_NEW(T1 &p, const T2 &value) { new (&p) T1(value); return p; } #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define NEW DEBUG_NEW #define ALIGN_NEW(T) new (_mm_malloc(sizeof(T),__alignof(T))) T #define MOF_ALIGNED_NEW_OPERATOR(T) \ FORCE_INLINE void* operator new(size_t sizeInBytes) { return _mm_malloc(sizeInBytes,__alignof(T)); }\ FORCE_INLINE void operator delete(void* ptr) { _mm_free(ptr); } \ FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \ FORCE_INLINE void operator delete(void*, void*) { } \ FORCE_INLINE void* operator new[](size_t sizeInBytes){ return _mm_malloc(sizeInBytes,__alignof(T)); }\ FORCE_INLINE void operator delete[](void* ptr) { _mm_free(ptr); } \ FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \ FORCE_INLINE void operator delete[](void*, void*) { } FORCE_INLINE void MOF_PRINTLOG(const _TCHAR* fmt, ...) { _TCHAR buf[512]; va_list ap; va_start(ap, fmt); _vsntprintf(buf, 511, fmt, ap); OutputDebugString(buf); } #else template <class T> T& PLACEMENT_NEW(T &p) { new (&p) T(); return p; } template <class T1, class T2> T1& PLACEMENT_NEW(T1 &p, const T2 &value) { new (&p) T1(value); return p; } #define DEBUG_NEW new #define NEW new #define ALIGN_NEW(T) new (_mm_malloc(sizeof(T),__alignof(T))) T #define MOF_ALIGNED_NEW_OPERATOR(T) \ FORCE_INLINE void* operator new(size_t sizeInBytes) { return _mm_malloc(sizeInBytes,__alignof(T)); }\ FORCE_INLINE void operator delete(void* ptr) { _mm_free(ptr); } \ FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \ FORCE_INLINE void operator delete(void*, void*) { } \ FORCE_INLINE void* operator new[](size_t sizeInBytes){ return _mm_malloc(sizeInBytes,__alignof(T)); }\ FORCE_INLINE void operator delete[](void* ptr) { _mm_free(ptr); } \ FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \ FORCE_INLINE void operator delete[](void*, void*) { } #define MOF_PRINTLOG(fmt,...) __noop #endif #endif
[ "shin@oic.jp" ]
shin@oic.jp
409af424f384eda64bcadf774b7a1b5a973520b4
7d5b22941862884b36f111f9eddea956275b03b6
/OpenGL/Windows/Native/Fixed_Function_PipeLine/15_Kundali/Kundali_Lines.cpp
4ff377459ad247583d53f14f9c45051b13139cae
[]
no_license
blckopps/RTR_Assignments
df6d9845111a862cca7a7d03a1104acc62359c7d
6a05a2cb9c8dfef1d4313c97c48e26f5035db61e
refs/heads/master
2022-12-10T14:39:07.063238
2020-05-22T19:54:59
2020-05-22T19:54:59
295,221,570
2
0
null
null
null
null
UTF-8
C++
false
false
7,782
cpp
#include<Windows.h> #include<stdio.h> #include<math.h> #include<gl/GL.h> #include<gl/GLU.h> #pragma comment(lib,"openGL32.lib") #pragma comment(lib,"glu32.lib") #define WIN_WIDTH 800 #define WIN_HEIGHT 600 FILE *gpfile = NULL; LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM); //GLOBAL VARIABLES bool bFullScreen=false; DWORD dwstyle; WINDOWPLACEMENT wpPrev={sizeof(WINDOWPLACEMENT)}; HWND ghwnd=NULL; bool gbActiveWindow=false; HDC ghdc=NULL; HGLRC ghrc=NULL; int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmdLine,int iCmdShow) { //FUnction declaration int initialize(void); void display(void); //variable decl int iret=0; bool bdone=false; WNDCLASSEX wndclass; HWND hwnd; MSG msg; TCHAR szAppName[]=TEXT("MYWINDOW "); if(fopen_s(&gpfile, "log.txt","w")!=0) { MessageBox(NULL, TEXT("Cant create log"),TEXT("ERROR!!!"),MB_OK); } else { fprintf(gpfile, "log file created\n"); } wndclass.cbSize=sizeof(WNDCLASSEX); wndclass.style=CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndclass.cbClsExtra=0; wndclass.cbWndExtra=0; wndclass.lpfnWndProc=WndProc; wndclass.hInstance=hInstance; wndclass.hIcon=LoadIcon(NULL,IDI_APPLICATION); wndclass.hCursor=LoadCursor(NULL,IDC_ARROW); wndclass.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH); wndclass.lpszClassName=szAppName; wndclass.lpszMenuName=NULL; wndclass.hIconSm=LoadIcon(NULL,IDI_APPLICATION); RegisterClassEx(&wndclass); //create window hwnd=CreateWindowEx(WS_EX_APPWINDOW, szAppName, TEXT("My APP-SHUBHAM"), WS_OVERLAPPEDWINDOW |WS_CLIPCHILDREN | WS_CLIPCHILDREN |WS_VISIBLE, 100, 100, WIN_WIDTH, WIN_HEIGHT, NULL, NULL, hInstance, NULL); ghwnd=hwnd; iret=initialize(); //handling return values and create log if(iret == -1) { fprintf(gpfile,"CHoice pixel format failed!!\n"); DestroyWindow(hwnd); } else if(iret == -2) { fprintf(gpfile,"SetPixelFormat failed!! \n"); DestroyWindow(hwnd); } else if(iret == -3) { fprintf(gpfile,"create context failed\n"); DestroyWindow(hwnd); } else if(iret == -4) { fprintf(gpfile,"wgl make current failed!!\n"); DestroyWindow(hwnd); } else { fprintf(gpfile,"Initialization Successfull!!\n"); } ShowWindow(hwnd,iCmdShow); SetForegroundWindow(hwnd); SetFocus(hwnd); //call in game loop UpdateWindow(hwnd); while(bdone == false) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message == WM_QUIT) { bdone = true; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { if(gbActiveWindow == true) { //here call update } display(); } } return((int)msg.wParam); } LRESULT CALLBACK WndProc(HWND hwnd,UINT iMsg,WPARAM wParam,LPARAM lParam) { //FUnction Declarations void resize(int ,int); void uninitialize(void); void toogle_screen(void); switch(iMsg) { case WM_KEYDOWN: switch(wParam) { case 0x46: // MessageBox(hwnd,TEXT("P BUTTON PRESSED!!"),TEXT("BUTTON P"),MB_OK); toogle_screen(); break; case VK_ESCAPE: if(bFullScreen == true) //We should exit from fullscreen and then destroy the window. { SetWindowLong(ghwnd, GWL_STYLE, dwstyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(ghwnd,&wpPrev); SetWindowPos(ghwnd, HWND_TOP, 0,0,0,0, SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE| SWP_NOOWNERZORDER); ShowCursor(TRUE); } DestroyWindow(hwnd); break; } break; case WM_SETFOCUS: gbActiveWindow = true; break; case WM_KILLFOCUS: gbActiveWindow = false; break; case WM_SIZE: resize(LOWORD(lParam),HIWORD(lParam)); break; case WM_CLOSE: DestroyWindow(hwnd); break; case WM_ERASEBKGND: return 0; case WM_DESTROY: //MessageBox(hwnd,TEXT("This is WM_DESTROY!!"),TEXT("In Wm_DESTROY"),MB_OK); uninitialize(); PostQuitMessage(0); break; } return(DefWindowProc(hwnd,iMsg,wParam,lParam)); } //User Defined Functions void toogle_screen(void) { //MONITORINFO mi; if(bFullScreen == false) { dwstyle=GetWindowLong(ghwnd, GWL_STYLE); if(dwstyle & WS_OVERLAPPEDWINDOW) { MONITORINFO mi= {sizeof(MONITORINFO)}; if(GetWindowPlacement(ghwnd, &wpPrev) && GetMonitorInfo(MonitorFromWindow(ghwnd,MONITORINFOF_PRIMARY),&mi)) { SetWindowLong(ghwnd, GWL_STYLE,dwstyle&~WS_OVERLAPPEDWINDOW); SetWindowPos(ghwnd, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right-mi.rcMonitor.left, mi.rcMonitor.bottom-mi.rcMonitor.top, SWP_NOZORDER | SWP_FRAMECHANGED ); } } ShowCursor(FALSE); bFullScreen=true; } else { SetWindowLong(ghwnd, GWL_STYLE, dwstyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(ghwnd,&wpPrev); SetWindowPos(ghwnd, HWND_TOP, 0,0,0,0, SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE| SWP_NOOWNERZORDER); ShowCursor(TRUE); bFullScreen=false; } } int initialize(void) { void resize(int,int); PIXELFORMATDESCRIPTOR pfd; int iPixelFormatIndex; //code ZeroMemory(&pfd,sizeof(PPIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cRedBits = 8; pfd.cGreenBits = 8; pfd.cBlueBits = 8; pfd.cAlphaBits = 8; ghdc = GetDC(ghwnd); iPixelFormatIndex = ChoosePixelFormat(ghdc, &pfd); if(iPixelFormatIndex == 0) { return -1; } if(SetPixelFormat(ghdc, iPixelFormatIndex, &pfd) == FALSE) { return -2; } ghrc = wglCreateContext(ghdc); if(ghrc == NULL) { return -3; } if(wglMakeCurrent(ghdc, ghrc) == FALSE) { return -4; } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); resize(WIN_WIDTH, WIN_HEIGHT); return 0; } void resize(int width, int height) { if(height == 0) { height = 1; } glViewport(0, 0, (GLsizei)width,(GLsizei)height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 100.0f); } void display(void) { void outerRectangle(); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, 0.0f, -2.0f); outerRectangle(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, 0.0f, -2.0f); glRotatef(45, 0.0f, 0.0f, 1.0f); glScalef(-0.7f,-0.7f,-0.7f); outerRectangle(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, 0.0f, -2.0f); glBegin(GL_LINES); glVertex2f(0.5f, 0.5f); glVertex2f(-0.5f, -0.5f); glVertex2f(-0.5f, 0.5f); glVertex2f(0.5f, -0.5f); glEnd(); SwapBuffers(ghdc); } void uninitialize(void) { if(bFullScreen == true) { SetWindowLong(ghwnd, GWL_STYLE, dwstyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(ghwnd,&wpPrev); SetWindowPos(ghwnd, HWND_TOP, 0,0,0,0, SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE| SWP_NOOWNERZORDER); ShowCursor(TRUE); } if(wglGetCurrentContext() == ghrc) { wglMakeCurrent(NULL, NULL); } if(ghrc) { wglDeleteContext(ghrc); ghrc = NULL; } if(ghdc) { ReleaseDC(ghwnd, ghdc); ghdc = NULL; } } void outerRectangle() { glBegin(GL_LINES); ////Rectangle Outside glVertex2f(0.5f,0.5f); glVertex2f(-0.5f,0.5f); glVertex2f(-0.5f,0.5f); glVertex2f(-0.5f,-0.5f); glVertex2f(-0.5f, -0.5f); glVertex2f(0.5f, -0.5f); glVertex2f(0.5f,-0.5f); glVertex2f(0.5f,0.5f); /* glVertex2f(0.5f, 0.5f); glVertex2f(-0.5f, -0.5f); glVertex2f(-0.5f, 0.5f); glVertex2f(0.5f, -0.5f); */ glEnd(); }
[ "shubhambendre96@gmail.com" ]
shubhambendre96@gmail.com
bd1fe2f0e2b0479e4b4641a8c85d4ed14254ca75
091afb7001e86146209397ea362da70ffd63a916
/inst/include/boost/simd/include/functions/scalar/all.hpp
e542448e31f9747950f79cf087952355ed8ce698
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
196
hpp
#ifndef BOOST_SIMD_INCLUDE_FUNCTIONS_SCALAR_ALL_HPP_INCLUDED #define BOOST_SIMD_INCLUDE_FUNCTIONS_SCALAR_ALL_HPP_INCLUDED #include <boost/simd/reduction/include/functions/scalar/all.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
be544d9d4cfce18435df13e9c6e368f15cb62557
b71b8bd385c207dffda39d96c7bee5f2ccce946c
/testcases/CWE590_Free_Memory_Not_on_Heap/s02/CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_11.cpp
d7746d8fcdca9cd377a0556cb82de05afc96213f
[]
no_license
Sporknugget/Juliet_prep
e9bda84a30bdc7938bafe338b4ab2e361449eda5
97d8922244d3d79b62496ede4636199837e8b971
refs/heads/master
2023-05-05T14:41:30.243718
2021-05-25T16:18:13
2021-05-25T16:18:13
369,334,230
0
0
null
null
null
null
UTF-8
C++
false
false
3,092
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_11.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml Template File: sources-sink-11.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: alloca Data buffer is allocated on the stack with alloca() * GoodSource: Allocate memory on the heap * Sink: * BadSink : Print then free data * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse()) * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_11 { #ifndef OMITBAD void bad() { char * data; data = NULL; /* Initialize data */ { { /* FLAW: data is allocated on the stack and deallocated in the BadSink */ char * dataBuffer = (char *)ALLOCA(sizeof(char)); *dataBuffer = 'A'; data = dataBuffer; } } printHexCharLine(*data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */ static void goodG2B1() { char * data; data = NULL; /* Initialize data */ { { /* FIX: data is allocated on the heap and deallocated in the BadSink */ char * dataBuffer = new char; *dataBuffer = 'A'; data = dataBuffer; } } printHexCharLine(*data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { char * data; data = NULL; /* Initialize data */ { { /* FIX: data is allocated on the heap and deallocated in the BadSink */ char * dataBuffer = new char; *dataBuffer = 'A'; data = dataBuffer; } } printHexCharLine(*data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_11; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "jaredzap@rams.colostate.edu" ]
jaredzap@rams.colostate.edu
fb8038af8b7229fe9f6c515e0efbc9cbd760918a
fbb232537f30e084a1caaff7d00de08c8abfaeec
/controller-firmware/src/Application.cpp
8cf53fb619251ff3d0f1d12d541645e4625b14fd
[]
no_license
kallaspriit/protocity
92a87b3fe2056277739bd84d5947397db659f762
8a733916beee57bd4e127f57ef46b143ebd9154d
refs/heads/master
2022-12-13T13:56:42.185243
2018-01-23T10:42:26
2018-01-23T10:42:26
71,896,428
2
3
null
2021-08-04T08:47:41
2016-10-25T12:48:57
C++
UTF-8
C++
false
false
19,705
cpp
#include "Application.hpp" #include "Config.hpp" #include "capabilities/DebugCapability.hpp" #include "capabilities/TSL2561Capability.hpp" #include "capabilities/TMP102Capability.hpp" #include "capabilities/MPL3115A2Capability.hpp" #include "capabilities/PN532Capability.hpp" #include "capabilities/TLC5940Capability.hpp" #include "capabilities/Si7021Capability.hpp" #include "capabilities/WeatherStationCapability.hpp" Application::Application(Config *config, Serial *serial) : config(config), serial(serial), port1(1, config->port1Pin), port2(2, config->port2Pin), port3(3, config->port3Pin), port4(4, config->port4Pin), port5(5, config->port5Pin), port6(6, config->port6Pin), port7(7, config->port7Pin), mainLoopLed(config->mainLoopLedPin) { commandBuffer = new char[COMMAND_BUFFER_SIZE]; sendBuffer = new char[SEND_BUFFER_SIZE]; } void Application::run() { setup(); testSetup(); while (true) { loop(); } } void Application::setup() { setupSerial(); setupCommandHandlers(); setupPorts(); setupDebug(); setupEthernetManager(); setupSocketServer(); setupTimer(); initialFreeMemory = Debug::getFreeMemoryBytes(); } void Application::loop() { int deltaUs = timer.read_us(); timer.reset(); consumeQueuedCommands(); sendQueuedMessages(); updateControllers(deltaUs); updateHeartbeat(deltaUs); mainLoopLed = !mainLoopLed; } void Application::setupSerial() { // configure serial serial->attach(callback(this, &Application::handleSerialRx), Serial::RxIrq); } void Application::setupCommandHandlers() { log.info("setting up command handlers"); // register command handlers registerCommandHandler("ping", this, &Application::handlePingCommand); registerCommandHandler("memory", this, &Application::handleMemoryCommand); registerCommandHandler("version", this, &Application::handleVersionCommand); registerCommandHandler("restart", this, &Application::handleRestartCommand); registerCommandHandler("port", this, &Application::handlePortCommand); } void Application::setupPorts() { log.info("setting up ports"); // register the ports in the mapping portNumberToControllerMap[port1.getId()] = &port1; portNumberToControllerMap[port2.getId()] = &port2; portNumberToControllerMap[port3.getId()] = &port3; portNumberToControllerMap[port4.getId()] = &port4; portNumberToControllerMap[port5.getId()] = &port5; portNumberToControllerMap[port6.getId()] = &port6; portNumberToControllerMap[port7.getId()] = &port7; // register port event listeners for (DigitalPortNumberToControllerMap::iterator it = portNumberToControllerMap.begin(); it != portNumberToControllerMap.end(); it++) { setupPort(it->second); } } void Application::setupPort(PortController *portController) { portController->addEventListener(this); portController->addCapability(new DebugCapability(serial, portController, config->sdaPin, config->sclPin)); portController->addCapability(new TSL2561Capability(serial, portController, config->sdaPin, config->sclPin)); portController->addCapability(new TMP102Capability(serial, portController, config->sdaPin, config->sclPin)); portController->addCapability(new MPL3115A2Capability(serial, portController, config->sdaPin, config->sclPin)); portController->addCapability(new Si7021Capability(serial, portController, config->sdaPin, config->sclPin)); portController->addCapability(new PN532Capability(serial, portController, config->nfcMosiPin, config->nfcMisoPin, config->nfcSclkPin)); portController->addCapability(new TLC5940Capability(serial, portController, config->ledMosiPin, config->ledSclkPin, config->ledBlankPin, config->ledErrorPin, config->ledGsclkPin, config->ledChainLength)); portController->addCapability(new WeatherStationCapability(serial, portController, config->sdaPin, config->sclPin, config->lcdTxPin, config->lcdRxPin, config->lcdResetPin)); } void Application::setupDebug() { log.info("setting up debugging"); debug.setLedMode(LED_BREATHE_INDEX, Debug::LedMode::BREATHE); } void Application::setupEthernetManager() { log.info("setting up ethernet manager"); debug.setLedMode(LED_ETHERNET_STATUS_INDEX, Debug::LedMode::BLINK_FAST); bool isConnected = ethernetManager.initialize(); if (isConnected) { debug.setLedMode(LED_ETHERNET_STATUS_INDEX, Debug::LedMode::BLINK_SLOW); } else { debug.setLedMode(LED_ETHERNET_STATUS_INDEX, Debug::LedMode::OFF); log.warn("connecting to ethernet failed, performing reset to try again"); restart(); } } void Application::setupSocketServer() { log.info("setting up socket server"); socketServer.addListener(this); socketServer.start(ethernetManager.getEthernetInterface(), config->socketServerPort); } void Application::setupTimer() { timer.start(); } template<typename T, typename M> void Application::registerCommandHandler(std::string name, T *obj, M method) { registerCommandHandler(name, Callback<CommandManager::Command::Response(CommandManager::Command*)>(obj, method)); } void Application::registerCommandHandler(std::string name, Callback<CommandManager::Command::Response(CommandManager::Command*)> func) { log.info("registering command handler for '%s'", name.c_str()); commandHandlerMap[name].attach(func); } void Application::consumeQueuedCommands() { CommandManager::Command *command = commandManager.getNextCommand(); while (command != NULL) { consumeCommand(command); command = commandManager.getNextCommand(); } } void Application::consumeCommand(CommandManager::Command *command) { CommandHandlerMap::iterator commandIt = commandHandlerMap.find(command->name); std::string responseText; if (commandIt != commandHandlerMap.end()) { /* log.trace("calling command handler for #%d '%s' (source: %d)", command->id, command->name.c_str(), command->sourceId); for (int i = 0; i < command->argumentCount; i++) { log.trace("- argument %d: %s", i, command->arguments[i].c_str()); } */ CommandManager::Command::Response response = commandIt->second.call(command); responseText = response.getResponseText(); } else { log.warn("command handler for #%d '%s' (source: %d) has not been registered", command->id, command->name.c_str(), command->sourceId); for (int i = 0; i < command->argumentCount; i++) { log.debug("- argument %d: %s", i, command->arguments[i].c_str()); } // build response text char responseBuffer[100]; snprintf(responseBuffer, sizeof(responseBuffer), "%d:ERROR:unsupported command requested", command->id); responseText = responseBuffer; } log.debug("> %s", responseText.c_str()); switch (command->sourceId) { case CommandSource::SOCKET: socketServer.sendMessage(responseText + "\n"); break; case CommandSource::SERIAL: break; default: log.error("unexpected command source %d", command->sourceId); } } void Application::sendQueuedMessages() { while (messageQueue.size() > 0) { std::string message = messageQueue.front(); messageQueue.pop(); // last character is a linefeed \n, remove it log.debug("> %s", message.substr(0, message.length() - 1).c_str()); if (socketServer.isClientConnected()) { socketServer.sendMessage(message); } } } void Application::updateControllers(int deltaUs) { for (DigitalPortNumberToControllerMap::iterator it = portNumberToControllerMap.begin(); it != portNumberToControllerMap.end(); it++) { it->second->update(deltaUs); } } void Application::updateHeartbeat(int deltaUs) { timeSinceLastHeartbeatUs += deltaUs; if (timeSinceLastHeartbeatUs > HEATBEAT_INTERVAL_US) { sendHeartbeat(); timeSinceLastHeartbeatUs = 0; } } void Application::sendHeartbeat() { if (!socketServer.isClientConnected()) { return; } int length = snprintf(sendBuffer, SEND_BUFFER_SIZE, "0:HEARTBEAT:%d\n", heartbeatCounter++); socketServer.sendMessage(sendBuffer, length); } bool Application::validateCommandArgumentCount(CommandManager::Command *command, int expectedArgumentCount) { if (command->argumentCount != expectedArgumentCount) { return false; } return true; } void Application::onSocketClientConnected(TCPSocketConnection* client) { debug.setLedMode(LED_ETHERNET_STATUS_INDEX, Debug::LedMode::ON); } void Application::onSocketClientDisconnected(TCPSocketConnection* client) { debug.setLedMode(LED_ETHERNET_STATUS_INDEX, Debug::LedMode::BLINK_SLOW); log.warn("socket client disconnected, performing reset"); restart(); } void Application::onSocketCommandReceived(const char *command, int length) { commandManager.handleCommand(CommandSource::SOCKET, command, length); debug.setLedMode(LED_COMMAND_RECEIVED_INDEX, Debug::LedMode::BLINK_ONCE); } void Application::onPortDigitalValueChange(int id, PortController::DigitalValue value) { snprintf(sendBuffer, SEND_BUFFER_SIZE, "0:INTERRUPT_CHANGE:%d:%s\n", id, value == PortController::DigitalValue::HIGH ? "HIGH" : "LOW"); enqueueMessage(std::string(sendBuffer)); } void Application::onPortAnalogValueChange(int id, float value) { snprintf(sendBuffer, SEND_BUFFER_SIZE, "0:ANALOG_IN:%d:%f\n", id, value); enqueueMessage(std::string(sendBuffer)); } void Application::onPortValueRise(int id) { snprintf(sendBuffer, SEND_BUFFER_SIZE, "0:INTERRUPT_RISE:%d\n", id); enqueueMessage(std::string(sendBuffer)); } void Application::onPortValueFall(int id) { snprintf(sendBuffer, SEND_BUFFER_SIZE, "0:INTERRUPT_FALL:%d\n", id); enqueueMessage(std::string(sendBuffer)); } void Application::onPortCapabilityUpdate(int id, std::string capabilityName, std::string message) { snprintf(sendBuffer, SEND_BUFFER_SIZE, "0:CAPABILITY:%d:%s:%s\n", id, capabilityName.c_str(), message.c_str()); enqueueMessage(std::string(sendBuffer)); } void Application::handleSerialRx() { char receivedChar = serial->getc(); if (receivedChar == '\n') { commandManager.handleCommand(CommandSource::SERIAL, commandBuffer, commandLength); commandBuffer[0] = '\0'; commandLength = 0; debug.setLedMode(LED_COMMAND_RECEIVED_INDEX, Debug::LedMode::BLINK_ONCE); //consumeQueuedCommands(); } else { if (commandLength > MAX_COMMAND_LENGTH - 1) { log.warn("maximum command length is %d characters, stopping at %s", MAX_COMMAND_LENGTH, commandBuffer); } commandBuffer[commandLength++] = receivedChar; commandBuffer[commandLength] = '\0'; } } void Application::enqueueMessage(std::string message) { messageQueue.push(message); } CommandManager::Command::Response Application::handlePingCommand(CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 0)) { return command->createFailureResponse("expected no parameters"); } return command->createSuccessResponse("pong"); } CommandManager::Command::Response Application::handleMemoryCommand(CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 0)) { return command->createFailureResponse("expected no parameters"); } int freeMemoryBytes = Debug::getFreeMemoryBytes(); return command->createSuccessResponse(freeMemoryBytes, initialFreeMemory, Debug::getTotalMemoryBytes()); } CommandManager::Command::Response Application::handleVersionCommand(CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 0)) { return command->createFailureResponse("expected no parameters"); } return command->createSuccessResponse(getVersion()); } CommandManager::Command::Response Application::handleRestartCommand(CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 0)) { return command->createFailureResponse("expected no parameters"); } restart(); return command->createSuccessResponse(); } void Application::restart() { log.info("restarting system.."); Thread::wait(100); NVIC_SystemReset(); } CommandManager::Command::Response Application::handlePortCommand(CommandManager::Command *command) { if (command->argumentCount < 2) { return command->createFailureResponse("expected at least two parameters"); } int portNumber = command->getInt(0); PortController *portController = getPortControllerByPortNumber(portNumber); if (portController == NULL) { return command->createFailureResponse("invalid port number requested"); } std::string action = command->getString(1); if (action == "mode") { return handlePortModeCommand(portController, command); } else if (action == "pull") { return handlePortPullCommand(portController, command); } else if (action == "value") { return handlePortValueCommand(portController, command); } else if (action == "read") { return handlePortReadCommand(portController, command); } else if (action == "listen") { return handlePortListenCommand(portController, command); } else { AbstractCapability *capability = portController->getCapabilityByName(action); if (capability == NULL) { return command->createFailureResponse("invalid action requested"); } return capability->handleCommand(command); } return command->createSuccessResponse(); } CommandManager::Command::Response Application::handlePortModeCommand(PortController *portController, CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 3)) { return command->createFailureResponse("expected three parameters"); } int portNumber = command->getInt(0); std::string modeName = command->getString(2); PortController::PortMode portMode = PortController::getPortModeByName(modeName); if (portMode == PortController::PortMode::INVALID) { return command->createFailureResponse("invalid port mode requested"); } portController->setPortMode(portMode); log.debug("set port %d mode: %s", portNumber, modeName.c_str()); return command->createSuccessResponse(); } CommandManager::Command::Response Application::handlePortPullCommand(PortController *portController, CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 3)) { return command->createFailureResponse("expected three parameters"); } PortController::PortMode portMode = portController->getPortMode(); if (portMode != PortController::PortMode::DIGITAL_IN && portMode != PortController::PortMode::INTERRUPT) { return command->createFailureResponse("setting pull mode is only applicable for DIGITAL_IN and INTERRUPT ports"); } int portNumber = command->getInt(0); std::string modeName = command->getString(2); PinMode pinMode = PinMode::PullNone; if (modeName == "NONE") { pinMode = PinMode::PullNone; } else if (modeName == "UP") { pinMode = PinMode::PullUp; } else if (modeName == "DOWN") { pinMode = PinMode::PullDown; } else { return command->createFailureResponse("invalid pull mode requested"); } portController->setPinMode(pinMode); log.debug("set port %d pull mode: %s", portNumber, modeName.c_str()); return command->createSuccessResponse(); } CommandManager::Command::Response Application::handlePortValueCommand(PortController *portController, CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 3)) { return command->createFailureResponse("expected three parameters"); } int portNumber = command->getInt(0); float value = command->getFloat(2); PortController::PortMode portMode = portController->getPortMode(); switch (portMode) { case PortController::PortMode::DIGITAL_OUT: { PortController::DigitalValue digitalValue = PortController::DigitalValue::LOW; std::string stringValue = command->getString(2); if (stringValue == "HIGH") { digitalValue = PortController::DigitalValue::HIGH; } else if (stringValue == "LOW") { digitalValue = PortController::DigitalValue::LOW; } else { if (value != 0.0f && value != 1.0f) { return command->createFailureResponse("expected either HIGH/LOW or 1/0 as value"); } digitalValue = value == 1.0f ? PortController::DigitalValue::HIGH : PortController::DigitalValue::LOW; } portController->setDigitalValue(digitalValue); log.debug("port set digital value for %d: %d", portNumber, digitalValue); } break; case PortController::PortMode::ANALOG_OUT: { if (value < 0.0f || value > 1.0f) { return command->createFailureResponse("expected value between 0.0 and 1.0"); } float pwmDutyCycle = min(max(value, 0.0f), 1.0f); portController->setAnalogValue(pwmDutyCycle); log.debug("port set pwm duty cycle value for %d: %f", portNumber, pwmDutyCycle); } break; default: return command->createFailureResponse("setting port value is only valid for DIGITAL_OUT or ANALOG_OUT modes"); } return command->createSuccessResponse(); } CommandManager::Command::Response Application::handlePortReadCommand(PortController *portController, CommandManager::Command *command) { if (!validateCommandArgumentCount(command, 2)) { return command->createFailureResponse("expected two parameters"); } PortController::PortMode portMode = portController->getPortMode(); if (portMode == PortController::PortMode::DIGITAL_IN || portMode == PortController::PortMode::INTERRUPT) { PortController::DigitalValue value = portController->getDigitalValue(); return command->createSuccessResponse(value == PortController::DigitalValue::HIGH ? "HIGH" : "LOW"); } else if (portMode == PortController::PortMode::ANALOG_IN) { float value = portController->getAnalogValue(); return command->createSuccessResponse(value); } else { return command->createFailureResponse("reading value is only valid for DIGITAL_IN, INTERRUPT and ANALOG_IN"); } } CommandManager::Command::Response Application::handlePortListenCommand(PortController *portController, CommandManager::Command *command) { if (command->argumentCount < 2 || command->argumentCount > 4) { return command->createFailureResponse("expected at least two and no more than four parameters"); } PortController::PortMode portMode = portController->getPortMode(); if (portMode != PortController::PortMode::ANALOG_IN) { return command->createFailureResponse("listening for port events is only valid for analog inputs"); } int portNumber = command->getInt(0); float changeThreshold = 0.01f; int intervalMs = 0; if (command->argumentCount >= 3) { if (command->getString(2) == "off") { log.info("stopping listening for analog port %d value changes", portNumber); portController->stopAnalogValueListener(); return command->createSuccessResponse(); } changeThreshold = command->getFloat(2); } if (command->argumentCount >= 4) { intervalMs = command->getInt(3); } log.info("listening for analog port %d value changes (threshold: %f, interval: %dms)", portNumber, changeThreshold, intervalMs); portController->listenAnalogValueChange(changeThreshold, intervalMs); return command->createSuccessResponse(); } PortController *Application::getPortControllerByPortNumber(int portNumber) { DigitalPortNumberToControllerMap::iterator findIterator = portNumberToControllerMap.find(portNumber); if (findIterator == portNumberToControllerMap.end()) { return NULL; } return findIterator->second; } void Application::testSetup() { log.info("setting up tests"); testLoopThread.start(callback(this, &Application::testLoop)); } void Application::testLoop() { /* TSL2561 lum(p9, p10, TSL2561_ADDR_FLOAT); if (lum.begin()) { log.debug("TSL2561 Sensor Found"); } else { log.debug("TSL2561 Sensor not Found"); } lum.setGain(TSL2561_GAIN_0X); lum.setTiming(TSL2561_INTEGRATIONTIME_402MS); while (true) { // test TSL2561 // log.info("illuminance: %f lux", lum.lux()); uint16_t x,y,z; x = lum.getLuminosity(TSL2561_VISIBLE); y = lum.getLuminosity(TSL2561_FULLSPECTRUM); z = lum.getLuminosity(TSL2561_INFRARED); log.info("illuminance: %d, %d, %d lux", x, y, z); // update loop testFlipFlop = testFlipFlop == 1 ? 0 : 1; Thread::wait(1000); } */ }
[ "kallaspriit@gmail.com" ]
kallaspriit@gmail.com
e2e4cd5df57410fdb14159491a5e291988494639
5e32f954095784b2d355f7792726f1561dc92ec9
/Lab4/game.cpp
070b572ec3838f64f42c8b589c58bee34b7b187a
[]
no_license
GachiGucciGhoul/Laboratory_works
168a45b88147a991a23c27dff3100236e9d29ed0
bf12b29d17122251b57af91876002f6523bcd054
refs/heads/master
2020-07-29T21:10:43.816105
2020-06-05T09:00:46
2020-06-05T09:00:46
209,960,397
1
4
null
null
null
null
UTF-8
C++
false
false
4,837
cpp
#include <iostream> #include <ctime> #include "game.h" Game initGame(char userChar) { srand(time(NULL)); Game game; game.status = PLAY; game.userChar = userChar; if (userChar == 'x') game.botChar = '0'; else game.botChar = 'x'; for (char i = 0; i < 3; i++) for (char j = 0; j < 3; j++) game.board[i][j] = ' '; if (rand() % 2) { game.isUserTurn = true; } else { game.isUserTurn = false; } return game; } void updateDisplay(const Game game) { system("cls"); std::cout << "\ta\tb\tc\n1\t"<<game.board[0][0]<<"\t" << game.board[0][1] << "\t" << game.board[0][2] << "\n2\t" << game.board[1][0] << "\t" << game.board[1][1] << "\t" << game.board[1][2] << "\n3\t" << game.board[2][0] << "\t" << game.board[2][1] << "\t" << game.board[2][2] << "\n"; return; } void botTurn(Game* game) { short num_X=0, num_Y=0, j2=0; for (short i = 0; i < 3; i++) for (short j = 0; j < 3; j++) if (game->board[i][j] != ' ') j2++; if (j2 == 0) { game->board[1][1] = game->botChar; return; } j2 = 0; for (short i = 0; i < 3; i++) { if (game->board[i][i] == game->userChar) num_X++; if (game->board[i][i] == ' ') { num_Y++; j2 = i; } } if ( (num_X == 2) && (num_Y == 1) ) { game->board[j2][j2] = game->botChar; return; } num_X = 0; num_Y = 0; for (short i = 0; i < 3; i++) { if (game->board[i][2-i] == game->userChar) num_X++; if (game->board[i][2-i] == ' ') { num_Y++; j2 = i; } } if ((num_X == 2) && (num_Y == 1)) { game->board[j2][2-j2] = game->botChar; return; } for (short i = 0; i < 3; i++) { num_X = 0; num_Y = 0; for (short j = 0; j < 3; j++) { j2 = j; if (game->board[i][j] == game->userChar) { num_X++; if (num_X == 2) { j = 2; while (j >= 0) { if (game->board[i][j] == ' ') { game->board[i][j] = game->botChar; return; } j--; } } j = j2; } if (game->board[j][i] == game->userChar) { num_Y++; if (num_Y == 2) { j = 2; while (j >= 0) { if (game->board[j][i] == ' ') { game->board[j][i] = game->botChar; return; } j--; } } j = j2; } } } do { num_X = rand() % 3; num_Y = rand() % 3; if (game->board[num_X][num_Y] == ' ') { game->board[num_X][num_Y] = game->botChar; return; } } while (true); } void userTurn(Game* game) { char a; short b; bool wrong = 1; std::cout << "User turn, pls enter x, y: "; do { std::cin >> a >> b; switch (a) { case 'a': a = 0; break; case 'b': a = 1; break; case 'c': a = 2; break; default: std::cout << "wrong a\n"; break; } switch (b) { case 1: b--; break; case 2: b--; break; case 3: b--; break; default: std::cout << "wrong b\n"; break; } if (game->board[b][a] == ' ') wrong = 0; else std::cout << "wrong place!\n"; } while (wrong); game->board[b][a] = game->userChar; } bool updateGame(Game* game) { for (short i = 0; i < 3; i++) { if (game->board[i][0] == 'x' || game->board[i][0] == '0') { if ( (game->board[i][1] == game->board[i][0]) && (game->board[i][2] == game->board[i][0]) ) { if (game->board[i][0] == game->userChar) game->status = USER_WIN; else game->status = BOT_WIN; return true; } } if (game->board[0][i] == 'x' || game->board[0][i] == '0') { if ((game->board[1][i] == game->board[0][i]) && (game->board[2][i] == game->board[0][i])) { if (game->board[0][i] == game->userChar) game->status = USER_WIN; else game->status = BOT_WIN; return true; } } } if (game->board[0][0] == 'x' || game->board[0][0] == '0') { if ((game->board[1][1] == game->board[0][0]) && (game->board[2][2] == game->board[0][0])) { if (game->board[2][2] == game->userChar) game->status = USER_WIN; else game->status = BOT_WIN; return true; } } if (game->board[2][0] == 'x' || game->board[2][0] == '0') { if ((game->board[1][1] == game->board[0][2]) && (game->board[1][1] == game->board[2][0])) { if (game->board[1][1] == game->userChar) game->status = USER_WIN; else game->status = BOT_WIN; return true; } } bool draw = 1; for (short i = 0; i < 3; i++) { for (short j = 0; j < 3; j++) if (game->board[i][j] == ' ') draw = 0; } if (draw) { game->status = NOT_WIN; return true; } game->isUserTurn = !game->isUserTurn; return false; }
[ "noreply@github.com" ]
GachiGucciGhoul.noreply@github.com
b68f7e8fbdc92aaf7d99e5f83caafc722f0d6bf5
3d8d2e4ebe08730cbbed3edd590c3ffa0b9bb732
/Graph Algorithms/Graph Seaching Algorithms/bfs.cpp
fcfe3f861f438d267ffb68580198050ee640692f
[]
no_license
InnoCentCoder5497/DSA-in-C-plus-plus
762ce2e9ccf30ac98f15f6821c4f3e737bc7ebfa
4afc9afd47c6ea9ca0fe0dad95e767d402a74d4a
refs/heads/master
2022-12-09T06:29:31.930326
2020-09-14T08:30:49
2020-09-14T08:30:49
285,457,864
3
0
null
null
null
null
UTF-8
C++
false
false
2,652
cpp
#include<iostream> #include<vector> #include<queue> #define NIL -1 #define INF 9999 using namespace std; void bfs(vector<int>[], char[], int[], int[], int, int); void print_path(vector<int>[], int, int, int[]); int main() { int num_vertex; int num_edges; int s; int src, dst; cout << "Total Number of Vertices : "; cin >> num_vertex; cout << "total Number of edges : "; cin >> num_edges; char color[num_vertex]; int dist[num_vertex]; int pred[num_vertex]; vector<int> adj[num_vertex]; for(int i = 0; i < num_edges; i++){ cout << "Enter src and dst : "; cin >> src >> dst; adj[src].push_back(dst); adj[dst].push_back(src); } for(int i = 0; i < num_vertex; i++){ cout << "vertex : " << i << " --> "; for(vector<int>::iterator it = adj[i].begin(); it != adj[i].end(); ++it){ cout << *it << " "; } cout << endl; } cout << "Enter src vertex : "; cin >> src; bfs(adj, color, dist, pred, num_vertex, src); for(int i = 0; i < num_vertex; i++){ cout << i << " "; } cout << endl; for(int i = 0; i < num_vertex; i++){ cout << color[i] << " "; } cout << endl; for(int i = 0; i < num_vertex; i++){ cout << dist[i] << " "; } cout << endl; for(int i = 0; i < num_vertex; i++){ cout << pred[i] << " "; } cout << endl; cout << "Enter vertex to which path is to be printed : "; cin >> dst; print_path(adj, src, dst, pred); return 0; } void print_path(vector<int> G[], int src, int dst, int pred[]){ if(dst == src){ cout << src << " "; } else if(pred[dst] == NIL){ cout << "No path exist from " << src << " to " << dst << endl; } else{ print_path(G, src, pred[dst], pred); cout << dst << " "; } } void bfs(vector<int> G[], char color[], int dist[], int pred[], int num_vertex, int src){ int i; int u; queue<int> Q; for(i = 0; i < num_vertex; i++){ if(i != src){ color[i] = 'W'; dist[i] = INF; pred[i] = NIL; } } color[src] = 'G'; dist[src] = 0; pred[src] = NIL; Q.push(src); while(!Q.empty()){ u = Q.front(); Q.pop(); for(vector<int>::iterator it = G[u].begin(); it != G[u].end(); ++it){ if(color[*it] == 'W'){ color[*it] = 'G'; dist[*it] = dist[u] + 1; pred[*it] = u; Q.push(*it); } } color[u] = 'B'; } }
[ "innocentcoder5497@gmail.com" ]
innocentcoder5497@gmail.com
20ade4a4739d847cc176fa8835d74c1b45b52cad
5db5a5a053ef2c572c115f4ac36bfefa00e28379
/Codeforces/CF1169B.cpp
4eca966b6992db46a88e6808923465d768e3ae2c
[]
no_license
CaptainSlowWZY/OI-Code
4491dfa40aae4af148db2dd529556a229a1e76af
be470914186b27d8b24177fb9b5d01d4ac55cd51
refs/heads/master
2020-03-22T08:36:19.753282
2019-12-19T08:22:51
2019-12-19T08:22:51
139,777,376
2
0
null
null
null
null
UTF-8
C++
false
false
632
cpp
#include <cstdio> #include <cstring> const int kMaxn = 3e5 + 5; int n, m; int A[kMaxn], B[kMaxn], cnt[kMaxn]; bool Suppose(int x); int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) scanf("%d%d", A + i, B + i); puts(Suppose(A[0]) || Suppose(B[0]) ? "YES" : "NO"); return 0; } bool Suppose(int x) { static int cnt[kMaxn]; memset(cnt, 0, sizeof cnt); int tot = 0; for (int i = 1; i < m; i++) { if (A[i] == x || B[i] == x) continue; ++tot, ++cnt[A[i]]; if (B[i] != A[i]) ++cnt[B[i]]; } int maxi = 0; for (int i = 1; i <= n; i++) { if (cnt[maxi] < cnt[i]) maxi = i; } return cnt[maxi] == tot; }
[ "CaptainSlowWZY@163.com" ]
CaptainSlowWZY@163.com
5309b2151b3263cabf7fd7962b6e60292834318b
a2dff7d13e1395985c6c402c6567b8ceb51cdc9a
/Class.h
57b958d76cae7f12b33dc8e4b70bcb7531ce996b
[ "WTFPL" ]
permissive
SitanHuang/RJC
864af9fd797b8e95b0e20ada2dc27cf9237ee9c0
a11688054c89a46bb6c1e91fa1f91ed0e7c09ffd
refs/heads/master
2021-01-17T13:10:03.606829
2015-09-13T04:16:23
2015-09-13T04:16:23
42,292,494
1
0
null
null
null
null
UTF-8
C++
false
false
232
h
#pragma once #include "jasminclude.h" #include <map> #include <memory> using namespace std; class Class { public: Class() { } ~Class() { name.clear(); } string name; }; map<string,Class> classes;
[ "978494543.qq54@gmail.com" ]
978494543.qq54@gmail.com
76946d5b5585bbf28c35ccba8d70a1bac95c59fb
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp
91f2cd8c248780c0dcc76322abc385498e6ca61b
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
3,820
cpp
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/workers/WorkerOrWorkletGlobalScope.h" #include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/TaskRunnerHelper.h" #include "core/frame/Deprecation.h" #include "core/inspector/ConsoleMessage.h" #include "core/loader/WorkerFetchContext.h" #include "core/probe/CoreProbes.h" #include "core/workers/WorkerReportingProxy.h" #include "core/workers/WorkerThread.h" #include "platform/CrossThreadFunctional.h" #include "platform/loader/fetch/ResourceFetcher.h" #include "platform/runtime_enabled_features.h" #include "platform/wtf/Functional.h" namespace blink { WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope( v8::Isolate* isolate, WorkerClients* worker_clients, WorkerReportingProxy& reporting_proxy) : worker_clients_(worker_clients), script_controller_( WorkerOrWorkletScriptController::Create(this, isolate)), reporting_proxy_(reporting_proxy), used_features_(static_cast<int>(WebFeature::kNumberOfFeatures)) { if (worker_clients_) worker_clients_->ReattachThread(); } WorkerOrWorkletGlobalScope::~WorkerOrWorkletGlobalScope() = default; void WorkerOrWorkletGlobalScope::CountFeature(WebFeature feature) { DCHECK(IsContextThread()); DCHECK_NE(WebFeature::kOBSOLETE_PageDestruction, feature); DCHECK_GT(WebFeature::kNumberOfFeatures, feature); if (used_features_.QuickGet(static_cast<int>(feature))) return; used_features_.QuickSet(static_cast<int>(feature)); ReportingProxy().CountFeature(feature); } void WorkerOrWorkletGlobalScope::CountDeprecation(WebFeature feature) { DCHECK(IsContextThread()); DCHECK_NE(WebFeature::kOBSOLETE_PageDestruction, feature); DCHECK_GT(WebFeature::kNumberOfFeatures, feature); if (used_features_.QuickGet(static_cast<int>(feature))) return; used_features_.QuickSet(static_cast<int>(feature)); // Adds a deprecation message to the console. DCHECK(!Deprecation::DeprecationMessage(feature).IsEmpty()); AddConsoleMessage( ConsoleMessage::Create(kDeprecationMessageSource, kWarningMessageLevel, Deprecation::DeprecationMessage(feature))); ReportingProxy().CountDeprecation(feature); } ResourceFetcher* WorkerOrWorkletGlobalScope::EnsureFetcher() { DCHECK(RuntimeEnabledFeatures::OffMainThreadFetchEnabled()); DCHECK(!IsMainThreadWorkletGlobalScope()); if (resource_fetcher_) return resource_fetcher_; WorkerFetchContext* fetch_context = WorkerFetchContext::Create(*this); resource_fetcher_ = ResourceFetcher::Create(fetch_context); DCHECK(resource_fetcher_); return resource_fetcher_; } ResourceFetcher* WorkerOrWorkletGlobalScope::Fetcher() const { DCHECK(RuntimeEnabledFeatures::OffMainThreadFetchEnabled()); DCHECK(!IsMainThreadWorkletGlobalScope()); DCHECK(resource_fetcher_); return resource_fetcher_; } bool WorkerOrWorkletGlobalScope::IsJSExecutionForbidden() const { return script_controller_->IsExecutionForbidden(); } void WorkerOrWorkletGlobalScope::DisableEval(const String& error_message) { script_controller_->DisableEval(error_message); } bool WorkerOrWorkletGlobalScope::CanExecuteScripts( ReasonForCallingCanExecuteScripts) { return !IsJSExecutionForbidden(); } void WorkerOrWorkletGlobalScope::Dispose() { DCHECK(script_controller_); script_controller_->Dispose(); script_controller_.Clear(); if (resource_fetcher_) { resource_fetcher_->StopFetching(); resource_fetcher_->ClearContext(); } } DEFINE_TRACE(WorkerOrWorkletGlobalScope) { visitor->Trace(resource_fetcher_); visitor->Trace(script_controller_); ExecutionContext::Trace(visitor); } } // namespace blink
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
52af017d1a9f32663dc85167b27cb4bd820199af
1c1837cd29f317fea252636a7310108f0f6de078
/sources/levelcube.cpp
9bc3e669b94a83c374c4bd13f3d1663e88b183b7
[]
no_license
exoticorn/ld26-minimalism
1e6e0896f6f852e486782668b44bd82966fd23e6
f0553a63e15527793da3dcef9087a5f69638a2e7
refs/heads/master
2016-09-05T09:23:47.729727
2013-05-01T12:12:28
2013-05-01T12:12:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,254
cpp
#include "levelcube.hpp" #include "cuberenderer.hpp" #include <math.h> LevelCube::LevelCube(float x, float y, float sx, CubeType type) { m_type = type; m_posX = x; m_posY = y; m_speedX = sx; m_pPrev = 0; m_pNext = 0; m_size = 1; m_time = 0; } void LevelCube::update(float timeStep, bool isPlayerAttached) { m_posX += m_speedX * timeStep; m_time += timeStep; if(m_type == CubeType_Shrinking && isPlayerAttached) { m_size -= timeStep / 3; if(m_size < 0) m_size = 0; } } void LevelCube::render(CubeRenderer& renderer) { switch(m_type) { case CubeType_Sticky: renderer.render(m_posX, m_posY, m_size, 0.6f, 0.6f, 1); break; case CubeType_Bouncy: renderer.render(m_posX, m_posY, m_size + sinf(m_time * 10) * 0.05f, 0.5f, 1, 0.5f); break; case CubeType_Shrinking: renderer.render(m_posX, m_posY, m_size, 0.8f, 0.3f, 0.2f); break; case CubeType_Harmful: renderer.render(m_posX, m_posY, m_size, 1, 1 - fmodf(m_time, 0.5f), 0.25f); break; } } bool LevelCube::canBeDeleted(float camY) const { if(m_size < 0.3f) return true; if(m_speedX < 0 && m_posX < -10) return true; if(m_speedX > 0 && m_posX > 10) return true; float dy = camY - m_posY; dy = dy < 0 ? -dy : dy; if(dy > 8) return true; return false; }
[ "dennis.ranke@gmail.com" ]
dennis.ranke@gmail.com
7f0f38c6f8372dc89599a4582684cb58926f759b
80d53f81c0fa573cc51f534636623da7520c2d91
/Cpp/RecFunc_string_16/RecFunc_string_16/main.cpp
9a8728f8f2af36f3293902810a2aa432d83c8e6b
[]
no_license
PSKuznetsov/Study
f75e36184019ee7990d24b2d3bf66d1454c9ff8a
e22b09d2dff568cfe4e4aea3e487902fe0e1fc62
refs/heads/master
2021-01-10T16:03:21.099778
2015-12-25T21:44:10
2015-12-25T21:44:10
48,591,279
0
0
null
null
null
null
UTF-8
C++
false
false
981
cpp
// // main.cpp // RecFunc_string_16 // // Created by Paul Kuznetsov on 10/03/15. // Copyright (c) 2015 Paul Kuznetsov. All rights reserved. // #include <iostream> #include <fstream> using namespace std; ifstream in ("/Users/NSCoder/Documents/C plus plus/RecFunc_string_16/RecFunc_string_16/input.txt"); ofstream out ("/Users/NSCoder/Documents/C plus plus/RecFunc_string_16/RecFunc_string_16/output.txt"); void fancyStringFromSymbol(char ansStr[], char str[], char symbol_a, char symbol_b, int index) { ansStr[index] = str[index]; if(str[index] == symbol_a) { ansStr[index + 1] = symbol_b; } if(str[index] != '\0') { fancyStringFromSymbol(ansStr, str, symbol_a, symbol_b, ++index); } } int main() { char string[256]; char ansString[256]; char a; char b; in >> a >> b >> string; fancyStringFromSymbol(ansString, string, a, b, 0); out << ansString << " "; return 0; }
[ "paulrussian@me.com" ]
paulrussian@me.com
06db3707d48b8756cda05e7eaa8ad929c0620335
6219540f3d6f86cca35447d7c7f07348c6724541
/Main/BufferMgr/headers/MyDB_BufferManagerDelegate.h
5e36d9f6e8df21f888d78e65fb7b5684bd58eb69
[]
no_license
wjy920421/MyDB
53ef2483510ca4977304984fbc650b33b406bd21
98f3f3069f325a1842bb64b2643eab4f7ec72cf2
refs/heads/master
2021-01-10T02:21:28.453922
2016-02-22T19:17:13
2016-02-22T19:17:13
50,632,185
0
1
null
null
null
null
UTF-8
C++
false
false
641
h
#ifndef BUFFER_MGR_DELEGATE_H #define BUFFER_MGR_DELEGATE_H #include <functional> using namespace std; class MyDB_Page; typedef function<void(string)> BufferManagerDelegateUnpin; typedef function<void(string)> BufferManagerDelegateRelease; typedef function<void(MyDB_Page *)> BufferManagerDelegateReload; class BufferManagerDelegate { public: // Delegate function to unpin a specified page BufferManagerDelegateUnpin unpin; // Delegate function to lease a specified page BufferManagerDelegateRelease release; // Delegate function to reload an evicted page BufferManagerDelegateReload reload; }; #endif
[ "wjy920421@yahoo.com" ]
wjy920421@yahoo.com
718f113d8d6ff9871ad63c8e5a808d97642c13e0
f16cb8ea52e5fb7c71a5b3ee0c5a8b0b86bd9ca3
/bak/mcSolveMvc/Code/xbApp/CxbRw.cpp
2016554d314a272f537b1c1d3a4375054d719b24
[]
no_license
hbdlyao/HVDC
cd09a9d1540a4f906e066c0144538ba326386d91
b6887933fbbdc8bcef2b7d34047994a01f6598cc
refs/heads/master
2021-01-20T00:20:09.401296
2017-05-24T12:48:41
2017-05-24T12:48:41
89,109,342
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
893
cpp
/////////////////////////////////////////////////////////// // CxbRw.cpp // Implementation of the Class CxbRw // Created on: 06-4ÔÂ-2017 17:56:23 // Original author: Administrator /////////////////////////////////////////////////////////// #include "CxbRw.h" void CxbRw::doLoad(CDevBase * vDevice) { string vFieldName; string vStr; _variant_t vValue; CxbDevBase * vDev; vDev = dynamic_cast<CxbDevBase *>(vDevice); CRwDev::doLoad(vDev); RwAdo->GetFieldValue("PosOrNeg", vValue); if (vValue.vt != VT_NULL) { vDev->SetPosOrNeg(vValue.iVal);//ÕûÐÍ }; } void CxbRw::doSave(CDevBase * vDevice) { string vStr; _variant_t vValue; CxbDevBase * vDev; vDev = dynamic_cast<CxbDevBase *>(vDevice); CRwDev::doSave(vDev); SqlStr = SqlStr + ","; SqlParam = SqlParam + ","; SqlStr = SqlStr + "PosOrNeg "; SqlParam = SqlParam + GetString(vDev->GetPosOrNeg()); }
[ "298598204@qq.com" ]
298598204@qq.com
b634f02a3976bab3975013b820414b33eb1d0d24
5b36c629df399989df0a7e2dd3a055008d57a2f8
/CP - Handbook/longestIncreaseSub.cpp
86294510d7d52878174a503826d83b26370c5371
[]
no_license
VelisariosF/Algorithms
2b3861e75f7d06ffdcbc69228c84e94e571be750
9c73cdcfcbe640fa2feb1d4edc22bba9544aa479
refs/heads/master
2022-12-24T14:48:40.115777
2020-09-26T07:34:38
2020-09-26T07:34:38
298,761,711
0
0
null
2020-09-26T07:30:36
2020-09-26T07:30:36
null
UTF-8
C++
false
false
397
cpp
#include<bits/stdc++.h> using namespace std; int A[] = {6, 2, 5, 1, 7, 4, 8, 3, 9}; int N = 9; const int Nmax = 101; int L[Nmax]; int main(){ for(int i = 0; i < N; i++){ L[i] = 1; for(int j = i - 1; j >= 0; j--){ if(A[j] < A[i]){ L[i] = max(L[i], L[j] + 1); } } } printf("%d\n", *max_element(L, L + N)); return 0; }
[ "shraymist@gmail.com" ]
shraymist@gmail.com
b4e9436c0f837bcac5d36abffab3c3b3d662e70f
7e81e474e7df16e56b60f98a6882ba00c0c53df7
/image_server/include/image_server/KinectServer.h
15a3360b3cabd9490409b220df0861a067910ff2
[]
no_license
hgaiser/roman-technologies
440088391b2a5a3866251e0d269d5e2d8fa0a53c
a47cd6f1704455f04c5ff7bd54fe638de642facc
refs/heads/master
2020-09-24T13:59:22.892232
2012-09-02T21:52:33
2012-09-02T21:52:33
32,988,642
0
0
null
null
null
null
UTF-8
C++
false
false
3,881
h
/* * KinectServer.h * * Created on: 2012-04-18 * Author: hgaiser */ #ifndef KINECTSERVER_H_ #define KINECTSERVER_H_ #include "ros/ros.h" #include "image_transport/image_transport.h" #include "image_server/OpenCVTools.h" #include "sensor_msgs/CompressedImage.h" #include "nero_msgs/SetActive.h" #include "nero_msgs/ColorDepth.h" #include "nero_msgs/QueryCloud.h" #include "image_server/CaptureKinect.h" class KinectServer { protected: ros::NodeHandle mNodeHandle; //ROS node handler image_transport::ImageTransport mImageTransport; image_transport::Publisher mRGBPub; ros::Publisher mPCPub; ros::Publisher mDepthPub; ros::Publisher mLaserPub; ros::Publisher mRGBDepthPub; ros::Publisher mXYZRGBPub; ros::ServiceServer mRGBControl; ros::ServiceServer mCloudControl; ros::ServiceServer mForceKinectControl; ros::ServiceServer mForceDepthControl; ros::ServiceServer mQueryCloud; ros::ServiceServer mProjectPoints; ros::ServiceServer mSendClouds; bool mSendEmptyLaserscan; bool mPublishRGB; bool mPublishDepth; bool mPublishCloud; bool mPublishLaserScan; bool mPublishRGBDepth; bool mPublishXYZRGB; bool mForceKinectOpen; bool mForceDepthOpen; bool mForceSendCloud; double mScale; bool mCloseIdleKinect; CaptureKinect mKinect; public: KinectServer(const char *filePath); ~KinectServer() { mNodeHandle.shutdown(); } void run(); inline ros::NodeHandle* getNodeHandle() { return &mNodeHandle; }; inline bool isDepthGenerating() { return mKinect.isDepthGenerating(); }; inline bool isRGBGenerating() { return mKinect.isRGBGenerating(); }; inline bool isGenerating() { return isDepthGenerating() || isRGBGenerating(); }; private: bool openKinect(); bool queryKinect(bool queryRGB, bool queryDepth); bool grabRGB(cv::Mat &rgb); bool grabDepth(cv::Mat &depth); bool grabCloud(cv::Mat &cloud, cv::Mat depth); inline void startRGB() { if (isRGBGenerating()) return; ROS_INFO("Starting RGB stream ..."); mKinect.startRGB(); ROS_INFO("Started RGB stream."); }; inline void startDepth() { if (isDepthGenerating()) return; ROS_INFO("Starting depth stream ..."); mKinect.startDepth(); ROS_INFO("Started depth stream."); }; inline void resizeMat(cv::Mat &mat, float scale = 1.f) { if (scale == 1.f) return; cv::resize(mat, mat, cv::Size(mat.cols * mScale, mat.rows * scale), 0, 0, cv::INTER_LINEAR); }; inline void publishRGB(cv::Mat rgb) { resizeMat(rgb, mScale); mRGBPub.publish(OpenCVTools::matToImage(rgb)); }; inline void publishDepth(cv::Mat depth) { resizeMat(depth, mScale); mDepthPub.publish(OpenCVTools::matToImage(depth)); }; inline void publishCloud(cv::Mat cloud) { mPCPub.publish(OpenCVTools::matToPointCloud2(cloud)); }; inline void publishRegisteredCloud(cv::Mat cloud, cv::Mat rgb) { mXYZRGBPub.publish(OpenCVTools::matToRegisteredPointCloud2(cloud, rgb)); }; inline void publishLaserScan(cv::Mat cloud) { mLaserPub.publish(OpenCVTools::matToLaserScan(cloud)); }; inline void publishRGBDepth(cv::Mat rgb, cv::Mat depth) { nero_msgs::ColorDepth msg; msg.color = *OpenCVTools::matToImage(rgb); msg.depth = *OpenCVTools::matToImage(depth); mRGBDepthPub.publish(msg); }; bool RGBControl(nero_msgs::SetActive::Request &req, nero_msgs::SetActive::Response &res); bool CloudControl(nero_msgs::SetActive::Request &req, nero_msgs::SetActive::Response &res); bool ForceKinectControl(nero_msgs::SetActive::Request &req, nero_msgs::SetActive::Response &res); bool ForceDepthControl(nero_msgs::SetActive::Request &req, nero_msgs::SetActive::Response &res); bool QueryCloud(nero_msgs::QueryCloud::Request &req, nero_msgs::QueryCloud::Response &res); bool ProjectPoints(nero_msgs::QueryCloud::Request &req, nero_msgs::QueryCloud::Response &res); bool SendClouds(nero_msgs::SetActive::Request &req, nero_msgs::SetActive::Response &res); }; #endif /* KINECTSERVER_H_ */
[ "hansg91@gmail.com@efe3342a-cd92-a411-41d2-ccb54d0c40cb" ]
hansg91@gmail.com@efe3342a-cd92-a411-41d2-ccb54d0c40cb
0913075bc28676723405fa16ea165f514db71aa3
f04f081eed945caa370a268a5f7de11991dff636
/Snake.cpp
6acaea3d8511e7cd9137109234d0a66be359aabe
[]
no_license
Dark90lab/university-projects
0464b67f3ab38cb8499422f416c79c04d7f4de9b
7cb77d08df71cbd7a6ff48b338777a4569c785ef
refs/heads/master
2023-01-07T00:55:50.017930
2020-11-04T12:13:17
2020-11-04T12:13:17
286,094,285
0
0
null
null
null
null
UTF-8
C++
false
false
2,902
cpp
#include <iostream> #include <windows.h> #include <conio.h> #include <stdlib.h> using namespace std; bool gameOver, gameMode; const int width = 20; const int height = 20; int x, y,fruitX,fruitY,score; int tailX[100], tailY[100]; int lenTail; enum eDirection {STOP=0,LEFT,RIGHT,UP,DOWN}; eDirection dir; void Color(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } void Setup() { cout << "Chose game Mode :" << endl << "With walls - [0], Without Wals - [1]"<<endl; cin >> gameMode; gameOver = false; dir = STOP; x = width / 2;// centring the snake; y = height / 2; fruitX = rand() % width; fruitY = rand() % height; score = 0; } void Draw() { system("cls"); Color(13); for (int i = 0; i < width + 2; i++)// top wall cout << "#"; cout << endl; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (j == 0)//side wall cout << "#"; if (i == y && j == x)//printing head cout << "O"; else if (i == fruitY && j == fruitX)//printing fruit cout << "@"; else { bool print = false; for (int k = 0; k < lenTail; k++)//printing tail { if (tailX[k] == j && tailY[k] == i) { cout << "o"; print = true; } } if (!print) cout << " "; } if (j == width - 1) cout << "#"; } cout << endl; } for (int i = 0; i < width + 2; i++)//bottom wall cout << "#"; cout << endl; cout << "Score: " << score << endl; cout << "FX: " << fruitX << " FY: " << fruitY<<endl; cout << "headX: " << x << " headY: " << y<<endl; } void Input() { if (_kbhit()) //check if button is pushed { switch (_getch()) //which button is pushed { case 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': gameOver = true; break; } } } void Logic() { for (int i = lenTail-1; i >0; i--) //generating tail { tailX[i] = tailX[i - 1]; tailY[i] = tailY[i - 1]; } tailX[0] = x;//setting cordinates of head tailY[0] = y; switch (dir) //changing position of head { case LEFT: x--; break; case RIGHT: x++; break; case UP: y--; break; case DOWN: y++; break; default: break; } if (!gameMode)//with walls { if (x > width-1 || x < 0||y>height-1 || y<0) // checkig whether head collides with walls gameOver=true; } else//without walls { if (x >= width) x = 0; else if (x < 0) x = width - 1; if (y >= height) y = 0; else if (y < 0) y = height - 1; } for (int i = 0; i < lenTail; i++) //check if head collides with tail if (tailX[i]==x && tailY[i]==y) gameOver = true; if (x == fruitX && y == fruitY)//generating new fruit { score++; fruitX = rand() % (width-1)+1; fruitY = rand() % (height-2); lenTail++; } } int main() { Setup(); while (!gameOver) { Draw(); Input(); Logic(); Sleep(15); } }
[ "mat.grzelak00@gmail.com" ]
mat.grzelak00@gmail.com
d3714f431b944f859bddd40ae8f8b674e8463c22
93d6631117556809fbb605a9df3d815c19240f76
/z3/Source.cpp
36e2ad1634a3d6d1820b8109538bcfeff1436ac9
[]
no_license
protyom/z1
51c08c1e2c1404ab407fe63be55957322cf5fa68
5742bb26035f0292323198175fae8a0bf54a6410
refs/heads/master
2020-03-19T06:54:27.530375
2018-06-04T18:21:32
2018-06-04T18:21:32
136,065,846
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,675
cpp
/*Пример 1-1. Простейшая программа с главным окном*/ /*Операторы препроцессора*/ #include <windows.h>//Два файла с определениями, макросами #include <windowsx.h>//и прототипами функций Windows /*Прототип используемой в программе функции пользователя*/ LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); /*Главная функция WinMain*/ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int nCmd) { char szClassName[] = "MainWindow";//Имя класса главного окна char szTitle[] = "Программа 1-3";//Заголовок окна MSG msg;//Структура msg для получения сообщений Windows WNDCLASS wc;//Структура wc для задания характеристик окна /*Зарегистрируем класс главного окна*/ ZeroMemory(&wc, sizeof(wc));//Обнуление всех членов wc wc.lpfnWndProc = WndProc;//Определяем оконную процедуру wc.hInstance = hInst;//Дескриптор приложения wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);//Пиктограмма wc.hCursor = LoadCursor(NULL, IDC_ARROW);//Курсор мыши wc.hbrBackground = GetStockBrush(WHITE_BRUSH);//Белый фон wc.lpszClassName = szClassName; wc.style = CS_HREDRAW | CS_VREDRAW; RegisterClass(&wc);//Собственно регистрация класса окна /*Создадим главное окно и сделаем его видимым*/ HWND hwnd = CreateWindow(LPCSTR(szClassName),//Класс окна LPCSTR(szTitle), WS_OVERLAPPEDWINDOW,//Заголовок, стиль окна 10, 10, 500, 300, //Координаты, размеры NULL, NULL,//Родитель, меню hInst, NULL);//Дескриптор приложения, параметры ShowWindow(hwnd, nCmd);//Покажем окно /*Организуем цикл обработки сообщений*/ while (GetMessage(&msg, NULL, 0, 0))//Получить сообщение, { TranslateMessage(&msg);//Перевод сообщения в код символа DispatchMessage(&msg);//вызвать WndProc } return 0;//После выхода из цикла вернуться в Windows }//Конец функции WinMain HPEN hPen; HBRUSH hBrush; /*Оконная функция WndProc главного окна*/ LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { HDC hDC; RECT rect; switch (msg) { case WM_CREATE: hPen = CreatePen(PS_SOLID, 2, RGB(150, 0, 0)); hBrush = CreateSolidBrush(RGB(255, 150, 150)); break; case WM_PAINT: RedrawWindow(hWnd, NULL, NULL, RDW_INVALIDATE); PAINTSTRUCT ps; hDC = BeginPaint(hWnd, &ps); GetClientRect(hWnd, &rect); DrawText(hDC, "Вверху слева", -1, &rect, DT_TOP | DT_LEFT|DT_SINGLELINE); DrawText(hDC, "Вверху справа", -1, &rect, DT_TOP | DT_RIGHT | DT_SINGLELINE); DrawText(hDC, "Вверху слева", -1, &rect, DT_BOTTOM | DT_LEFT | DT_SINGLELINE); DrawText(hDC, "Внизу справа", -1, &rect, DT_BOTTOM | DT_RIGHT | DT_SINGLELINE); DrawText(hDC, "По центру", -1, &rect, DT_CENTER | DT_VCENTER | DT_SINGLELINE); EndPaint(hWnd, &ps); break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: DeleteObject(hPen); DeleteObject(hBrush); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } }//Конец функции WndProc
[ "protyom@gmail.com" ]
protyom@gmail.com
9f47c0c7ac73013e5b7f39065218156761b24464
43ff99dacbf3ce80648664afecdd5218d06043f3
/headers/hardw_info.h
3fed6139daeda36255930cdf06bae6f383a5fc87
[]
no_license
peewster/System_Configuration_Tool
aaa1e252cf869f784ee81cc29b2b78345ec4e60f
bb8fcb1a57622a4365dd5a8b89e2402c8880ffe7
refs/heads/master
2021-01-19T12:31:40.105858
2012-07-26T19:54:54
2012-07-26T19:54:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,899
h
using namespace std; bool IsSpaceOrCR(char ch) { return ::isspace(ch) || ch == '\n'; } //Lists the installed networking cards. void networkcards() { system("cls"); system("color B"); cout << "\n"; cout << "Installed Networking Cards: \n\n"; int sysinf = system("wmic nic get description, Speed | findstr \"Connection Net Gig GIG PCIe GB GBE Speed\""); cout << endl; cout << "\n " + sysinf << endl; system("pause"); } //Show partitions with size void partitions() { string line; system("cls"); system("color B"); int sysinf = system("wmic logicaldisk get Name, Filesystem, Size, VolumeName "); cout << endl; cout << "\n" + sysinf; system("pause"); } //Shows cpu information #pragma comment(lib, "user32.lib") void cpuinfo() { SYSTEM_INFO siSysInfo; // Copy the hardware information to the SYSTEM_INFO structure. GetSystemInfo(&siSysInfo); printf(" Number of processors: %u\n", siSysInfo.dwNumberOfProcessors); system("cls"); string answer; cout << "\n for VM type (V/v), for PC (P/p): "; cin.ignore(256,'\n'); getline(cin, answer); answer.erase(remove_if(answer.begin(), answer.end(), IsSpaceOrCR), answer.end()); if(answer=="V" || answer=="v") { system("cls"); system("color B"); system("wmic cpu get Name"); cout << "\n"; system("wmic cpu get ProcessorId, Revision"); cout << "\n"; GetSystemInfo(&siSysInfo); printf("Number of processor cores: %u\n\n", siSysInfo.dwNumberOfProcessors); system("wmic cpu get Manufacturer, MaxClockSpeed"); cout << endl; system("pause"); } if(answer=="P" || answer=="p") { system("color B"); system("cls"); system("wmic cpu get Name"); cout << "\n"; system("wmic cpu get ProcessorId, Revision"); cout << "\n"; GetSystemInfo(&siSysInfo); printf("Number of processor cores: %u\n", siSysInfo.dwNumberOfProcessors); system("wmic cpu get Status "); int sysinfo2 = system("wmic cpu get Manufacturer, MaxClockSpeed"); cout << "\n"; int sysinfo3 = system("wmic cpu get L2CacheSize, L3Cachesize"); cout << endl; system("pause"); } } //Shows memory information void memory() { #define DIV 1024000; MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); GlobalMemoryStatusEx (&statex); system("cls"); string answer; cout << "\n for VM type (V/v), for PC (P/p): "; cin.ignore(256,'\n'); getline(cin, answer); answer.erase(remove_if(answer.begin(), answer.end(), IsSpaceOrCR), answer.end()); if(answer=="V" || answer=="v") { system("cls"); system("color B"); std::cout << "System Memory usage: \t\t" << statex.dwMemoryLoad << "%\n"; std::cout << "System Available Memory: \t" << statex.ullAvailPhys/DIV; cout << " MB \n"; std::cout << "System Total Memory: \t\t" << statex.ullTotalPhys/DIV; cout << " MB \n"; cout << "\n"; int sysinfo = system("wmic MEMORYCHIP get banklabel, devicelocator, caption, PartNumber, SerialNumber, speed"); cout << "\n" + sysinfo << endl; system("pause"); } if(answer=="P" || answer=="p") { system("cls"); system("color B"); std::cout << "System Memory usage: \t\t" << statex.dwMemoryLoad << "%\n"; std::cout << "System Available Memory: \t" << statex.ullAvailPhys/DIV; cout << " MB \n"; std::cout << "System Total Memory: \t\t" << statex.ullTotalPhys/DIV; cout << " MB \n"; cout << "\n"; int sysinfo = system("wmic MEMORYCHIP get banklabel, devicelocator, caption, PartNumber, speed"); cout << "\n" + sysinfo << endl; system("pause"); } } //Shows disk info void harddrives() { system("cls"); system("color B"); cout << "\n"; int sysinfo = system("wmic diskdrive get Size, Interfacetype"); cout << "\n"; int sysinfo1 = system("wmic diskdrive get MediaType, Model, Status"); cout << "\n"; system("pause"); }
[ "peewster@gmail.com" ]
peewster@gmail.com
101b29d8de50d78a5f352936dfb31eeb9d4c5131
4fd9f29b20e26b7cc80d748abd8f1dcd94fbbfdd
/Software rasterizer/Lukas Hermanns/SoftPixelEngine/sources/RenderSystem/spShaderConfigTypes.hpp
ece5cb74a30f48a3173623ea3bea72e16120714b
[ "Zlib" ]
permissive
Kochise/3dglrtvr
53208109ca50e53d8380bed0ebdcb7682a2e9438
dcc2bf847ca26cd6bbd5644190096c27432b542a
refs/heads/master
2021-12-28T03:24:51.116120
2021-08-02T18:55:21
2021-08-02T18:55:21
77,951,439
8
5
null
null
null
null
UTF-8
C++
false
false
3,845
hpp
/* * Shader configuration types header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_SHADER_CONFIG_TYPES_H__ #define __SP_SHADER_CONFIG_TYPES_H__ #include "Base/spStandard.hpp" #include <boost/function.hpp> namespace sp { namespace scene { class MaterialNode; }; namespace video { /* * Enumerations */ enum EShaderTypes { SHADER_DUMMY, //!< Dummy shader when shaders are not supported. SHADER_VERTEX_PROGRAM, //!< Vertex program since Direct3D 8 and OpenGL 1.3. SHADER_PIXEL_PROGRAM, //!< Pixel program since Direct3D 8 and OpenGL 1.3. SHADER_VERTEX, //!< Vertex shader since Direct3D 9 and OpenGL 2. SHADER_PIXEL, //!< Pixel shader since Direct3D 9 and OpenGL 2. SHADER_GEOMETRY, //!< Geometry shader since Direct3D 10 and OpenGL 3.2. SHADER_HULL, //!< Hull shader (for tessellation) since Direct3D 11 and OpenGL 4. SHADER_DOMAIN, //!< Domain shader (for tessellation) since Direct3D 11 and OpenGL 4. SHADER_COMPUTE, //!< Compute shader since Direct3D 11 and OpenGL 4. }; enum EConstantTypes { CONSTANT_UNKNOWN, //!< Unknown constant type. CONSTANT_BOOL, //!< Single Boolean. CONSTANT_INT, //!< Single Integer. CONSTANT_FLOAT, //!< Single float. CONSTANT_VECTOR2, //!< 2D float vector. CONSTANT_VECTOR3, //!< 3D float vector. CONSTANT_VECTOR4, //!< 4D float vector. CONSTANT_MATRIX2, //!< 2x2 float matrix. CONSTANT_MATRIX3, //!< 3x3 float matrix. CONSTANT_MATRIX4, //!< 4x4 float matrix. }; enum EShaderVersions { DUMMYSHADER_VERSION, GLSL_VERSION_1_20, GLSL_VERSION_1_30, GLSL_VERSION_1_40, GLSL_VERSION_1_50, GLSL_VERSION_3_30_6, GLSL_VERSION_4_00_8, HLSL_VERTEX_1_0, HLSL_VERTEX_2_0, HLSL_VERTEX_2_a, HLSL_VERTEX_3_0, HLSL_VERTEX_4_0, HLSL_VERTEX_4_1, HLSL_VERTEX_5_0, HLSL_PIXEL_1_0, HLSL_PIXEL_1_1, HLSL_PIXEL_1_2, HLSL_PIXEL_1_3, HLSL_PIXEL_1_4, HLSL_PIXEL_2_0, HLSL_PIXEL_2_a, HLSL_PIXEL_2_b, HLSL_PIXEL_3_0, HLSL_PIXEL_4_0, HLSL_PIXEL_4_1, HLSL_PIXEL_5_0, HLSL_GEOMETRY_4_0, HLSL_GEOMETRY_4_1, HLSL_GEOMETRY_5_0, HLSL_COMPUTE_4_0, HLSL_COMPUTE_4_1, HLSL_COMPUTE_5_0, HLSL_HULL_5_0, HLSL_DOMAIN_5_0, CG_VERSION_2_0, }; class Texture; class Shader; class ShaderTable; struct SMaterialStates; struct SMeshSurfaceTexture; /** Construction of the shader object callback function. A shader callback can be used to update the shader constants (or rather variables) before the shader is set and the object rendered. When a ShaderTable is bounded to a Mesh or a Billboard both parameters are always none zero and you do not need to check if they are valid pointers. \param Table: Pointer to a ShaderTable object which is currently used. \param Object: Pointer to a MaterialNode object which is currently used. */ typedef boost::function<void (ShaderTable* Table, const scene::MaterialNode* Object)> ShaderObjectCallback; /** Construction of the shader surface callback. This is similar to "PFNSHADEROBJECTCALLBACKPROC" but in this case the callback will be called for each surface. You can update your shader settings for the individual textures. */ typedef boost::function<void (ShaderTable* Table, const std::vector<SMeshSurfaceTexture>* TextureList)> ShaderSurfaceCallback; } // /namespace video } // /namespace sp #endif // ================================================================================
[ "noreply@github.com" ]
Kochise.noreply@github.com
4eced3402d58f64ffcf0077e443be9d424d9b237
6191a1770ca3c9c4a3fd8e68e949ae2e4d45b7d0
/src/geneserver/GeneServerThread.cpp
67210cbdee19b45eb8a007da6689428ecb55bdb9
[]
no_license
lanlijing/iocp-lua-server
6f08a2efd555c82b53f5f4ee6c3250c31183df18
4a7d3137756ac1af56644c5677e10f00c6c5c257
refs/heads/master
2021-06-26T19:36:49.088375
2021-06-04T13:31:42
2021-06-04T13:31:42
231,350,234
2
0
null
null
null
null
GB18030
C++
false
false
9,354
cpp
#include "stdafx.h" #include "geneserver.h" #include <direct.h> #include "DAppLog.h" #include "DMemoryPool.h" #include "DBuf.h" #include "DNetMsgBase.h" #include "DNetMsg.h" #include "DNetWorkBase.h" #include "geneserverDlg.h" #include "LuaMgr.h" #include "GeneServerThread.h" GeneServerThread::GeneServerThread() { m_pMainDlg = nullptr; m_strCommCaption = ""; m_byType = 0; m_bLuaInit = FALSE; m_bReloadLua = FALSE; m_strLuaFile = ""; m_ushServerPort = 0; m_dwGameServerConn = 0; m_addrGameServer.Init(); m_ullGameServerConnTick = 0; } GeneServerThread::~GeneServerThread() { } GeneServerThread* GeneServerThread::Instance() { static GeneServerThread s_inst; return &s_inst; } string GeneServerThread::GetTypeName() { string strRet; switch (m_byType) { case GeneServerType::eLuaTest: strRet = LUATESTNAME; break; case GeneServerType::eTestClient: strRet = TESTCLIENTNAME; break; case GeneServerType::eGameServer: strRet = GAMESERVERNAME; break; } return strRet; } BOOL GeneServerThread::StartServer(CgeneserverDlg* pMainDlg) { if ((m_byType < GeneServerType::eLuaTest) || (m_byType > GeneServerType::eGameServer)) return FALSE; if (pMainDlg == nullptr) return FALSE; m_pMainDlg = pMainDlg; //读取配置文件 string strConfig = "", strTypeName = GetTypeName(); ChangeCurDir(); GetConfigFileName(strConfig); char szRead[512] = { 0 }, szLogDir[512] = { 0 }; GetPrivateProfileStringA("common", "logdir", "", szLogDir, (sizeof(szLogDir) - 1), strConfig.c_str()); if (strlen(szLogDir) == 0) { AfxMessageBox(_T("读取配置文件出错,读不到日志目录")); return FALSE; } GetPrivateProfileStringA("common", "caption", "", szRead, (sizeof(szRead) - 1), strConfig.c_str()); if (strlen(szRead) == 0) { AfxMessageBox(_T("读取配置文件出错,读不到通用caption")); return FALSE; } m_strCommCaption = szRead; memset(szRead, 0, sizeof(szRead)); GetPrivateProfileStringA(strTypeName.c_str(), "luafile", "", szRead, (sizeof(szRead) - 1), strConfig.c_str()); if (strlen(szRead) == 0) { AfxMessageBox(_T("读取配置文件出错,读不到lua文件路径")); return FALSE; } m_strLuaFile = szRead; if (m_byType == GeneServerType::eTestClient) // 作为临时客户端,需要保存游戏服务端地址 { memset(szRead, 0, sizeof(szRead)); GetPrivateProfileStringA(GAMESERVERNAME, "ip", "", szRead, (sizeof(szRead) - 1), strConfig.c_str()); if (strlen(szRead) == 0) { AfxMessageBox(_T("读取配置文件出错,读不到游戏服务器地址")); return FALSE; } m_addrGameServer.m_strAddr = szRead; m_addrGameServer.m_nFarPort = GetPrivateProfileIntA(GAMESERVERNAME, "port", 0, strConfig.c_str()); if (m_addrGameServer.m_nFarPort == 0) { AfxMessageBox(_T("读取配置文件出错,读不游戏服务器端口")); return FALSE; } } else if (m_byType == GeneServerType::eGameServer) // 作为游戏服务端,需要保存监听端口 { m_ushServerPort = GetPrivateProfileIntA(strTypeName.c_str(), "port", 0, strConfig.c_str()); if (m_ushServerPort == 0) { AfxMessageBox(_T("读取配置文件出错,读不到服务器监听端口")); return FALSE; } } // DAppLog::Instance()->Init(szLogDir, strTypeName.c_str(), m_pMainDlg->GetSafeHwnd()); DMemoryPool::Instance()->StartPool(); if (m_byType == GeneServerType::eGameServer) DNetWorkBase::Instance()->InitNetObjectPool(16, 1600, 160000); //作为服务端,最大linker承载暂定为1600 else DNetWorkBase::Instance()->InitNetObjectPool(16, 16, 1600); // 不作服务端,linker设置较小 DNetWorkBase::Instance()->SocketStart(); //创建IOCP服务器 if (m_byType == GeneServerType::eGameServer) { m_ushServerPort = DNetWorkBase::Instance()->CreateIOCPServer(m_ushServerPort, this); if (m_ushServerPort == 0) { AfxMessageBox(_T("创建服务器监听出错")); return FALSE; } } // 开启消息处理线程 Start(); return TRUE; } void GeneServerThread::StopServer() { Stop(); DNetWorkBase::Instance()->CleanAllServerClient(); DNetWorkBase::Instance()->CleanUpNetObjectPool(); DNetWorkBase::Instance()->SocketCleanup(); DAppLog::Instance()->StopLog(); } void GeneServerThread::AddLog(const char* szLog) { DAppLog::Instance()->Info(TRUE, szLog); } void GeneServerThread::SetCaption(const char* szCaption) { char buf[512] = { 0 }; _snprintf(buf, sizeof(buf) - 1, "%s %s 进程号:%d", m_strCommCaption.c_str(), szCaption, GetCurrentProcessId()); USES_CONVERSION; CString strTemp = A2W(buf); m_pMainDlg->SetWindowText(strTemp); } int GeneServerThread::SendDBufToGameServer(DBuf* pSendDBuf) { if (m_byType != GeneServerType::eTestClient) { DAppLog::Instance()->Info(TRUE, "GeneServerThread::SendDBufToGameServer,类型必须为eTestClient型"); return 1; } return DNetWorkBase::Instance()->SendConnMsg(m_dwGameServerConn, pSendDBuf); } int GeneServerThread::SendDBufToClient(DWORD dwLinkerId, DBuf* pSendDBuf) { if (m_byType != GeneServerType::eGameServer) { DAppLog::Instance()->Info(TRUE, "GeneServerThread::SendDBufToClient,类型必须为eGameServer型"); return 1; } DNetWorkBase::Instance()->SendNetMsg(m_ushServerPort, dwLinkerId, pSendDBuf->GetBuf(), pSendDBuf->GetLength()); return 0; } void GeneServerThread::ProcessMsg(DBuf* pMsgBuf) { // 正式开始处理消息 BYTE byMsgType = pMsgBuf->m_dwBufType; DWORD dwFrom = pMsgBuf->m_dwBufFrom; UINT32 unDBufLen = 0,unUserID = 0, unMsgID = 0; if (byMsgType == DBufType::eAppDispatchMsg) { if (dwFrom != 0) return; pMsgBuf->ReadUint32(unDBufLen); pMsgBuf->ReadUint32(unDBufLen); pMsgBuf->ReadUint32(unUserID); pMsgBuf->ReadUint32(unMsgID); if (unUserID != 0) return; if (unMsgID == NetMsgID::SYSTEM_MSG_LUADEBUG) { string strScript = ""; pMsgBuf->ReadString(strScript); if (strScript.length() == 0) return; LuaMgr::Instance()->DoString(strScript.c_str()); } else if (unMsgID == NetMsgID::SYSTEM_MSG_CLOSE) { LuaFunc::CallLuaOnGameExit(); //给主窗口发退出消息 m_pMainDlg->SendMessage(WM_CLOSE); } } else if (byMsgType == DBufType::eNetClientDisConnected) // 只有TestClient时有 { if ((m_byType == GeneServerType::eTestClient) && (dwFrom == m_dwGameServerConn)) { DNetWorkBase::Instance()->CloseClientConn(m_dwGameServerConn); //显式调用,否则资源泄露 m_dwGameServerConn = 0; LuaFunc::CallLuaOnGameSvrDisConnect(); } } else if (byMsgType == DBufType::eNetClientNormalMsg) // 只有TestClient时有 { if ((m_byType == GeneServerType::eTestClient) && (dwFrom == m_dwGameServerConn)) LuaFunc::CallLuaOnGameSvrMsg(pMsgBuf); } else if (byMsgType == DBufType::eNetServerNormalMsg) // 只有GameServer时有 { if (m_byType == GeneServerType::eGameServer) { LuaFunc::CallLuaOnClientMsg(pMsgBuf, pMsgBuf->m_dwBufFrom); } } else if (byMsgType == DBufType::eNetServerAcceptMsg) // 只有GameServer时有 { if (m_byType == GeneServerType::eGameServer) { LuaFunc::CallLuaOnClientConnect(pMsgBuf->m_dwBufFrom); } } else if (byMsgType == DBufType::eNetServerCloseLinkerMsg) // 只有GameServer时有 { if (m_byType == GeneServerType::eGameServer) { LuaFunc::CallLuaOnClientDisConnect(pMsgBuf->m_dwBufFrom); } } } void GeneServerThread::ProcessLogic() { if (!m_bLuaInit) // 放在此处初始化是为了LUA对象由主线程创建 { LuaMgr::Instance()->DoFile(m_strLuaFile.c_str()); LuaFunc::CallLuaOnGameInit(); m_bLuaInit = TRUE; } // 是否要重新加载LUA脚本 if (m_bReloadLua) { LuaFunc::CallLuaOnGameExit(); if (m_byType == GeneServerType::eTestClient) // 测试客户端会断开与网关服连接 { DNetWorkBase::Instance()->CloseClientConn(m_dwGameServerConn); m_dwGameServerConn = 0; } LuaMgr::Instance()->ReLoadLua(); m_bLuaInit = FALSE; m_bReloadLua = FALSE; } // 和服务器的连接 if (m_byType == GeneServerType::eTestClient) { GameServerReConn(); } if (m_bLuaInit) LuaFunc::CallLuaOnGameFrame(); } void GeneServerThread::GameServerReConn() { if (m_dwGameServerConn != 0) return; ULONGLONG ullNow = GetTickCount64(); if ((ullNow - m_ullGameServerConnTick) < 5000) //5秒重连一次 return; m_dwGameServerConn = DNetWorkBase::Instance()->CreateClientConn(m_addrGameServer.m_strAddr.c_str(), m_addrGameServer.m_nFarPort, this); m_ullGameServerConnTick = GetTickCount64(); if (m_dwGameServerConn == 0) DAppLog::Instance()->Info(TRUE, "连接游戏服失败,正在尝试重连"); else { DAppLog::Instance()->Info(TRUE, "游戏服连接成功"); LuaFunc::CallLuaOnGameSvrConnect(); } } string GeneServerThread::GetConfigFileName(string& strConfig) { strConfig = ""; char szFileName[1024] = { 0 }; GetModuleFileNameA(GetModuleHandleA(NULL), szFileName, (sizeof(szFileName) - 1)); char* szPos = strrchr(szFileName, '\\'); if (szPos == NULL) { AfxMessageBox(_T("获取当前程序路径错误,可能路径包含特殊字符")); return strConfig; } strcpy(szPos + 1, "config.ini"); strConfig = szFileName; return strConfig; } void GeneServerThread::ChangeCurDir() { char szCurrentDir[512] = { 0 }; GetModuleFileNameA(GetModuleHandleA(NULL), szCurrentDir, sizeof(szCurrentDir) - 1); char* szPos = strrchr(szCurrentDir, '\\'); *(szPos + 1) = 0; _chdir(szCurrentDir); }
[ "273428590@qq.com" ]
273428590@qq.com
ccc76c10f709b192d0d1499c7479bdbd87bdf2b3
4151c7b2977085a1beec0f9ea696bc8e42cba038
/opencvWork/findMarker/testCamera/geometryStructs.hpp
f4474b4ea80fe54d5145ec7b0cc2eed6572dc00f
[]
no_license
TBFMX/opencvWork
1afeaf883b1f3dae7fc55cd0133b9ece07146af5
7050f79852325f18c1f1142881b5158ed23e81c9
refs/heads/master
2021-03-12T22:21:22.477765
2014-07-31T23:50:40
2014-07-31T23:50:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,510
hpp
#ifndef geometryStructs_hpp #define geometryStructs_hpp #define EPSILON 1e-12 #define maxObjSize 1596 #include <GL/gl.h> #include <GL/glext.h> #include <opencv/cv.h> struct point3{ float x; float y; float z; }; struct triangle{ point3 p1; point3 p2; point3 p3; }; struct texture{ point3 p1; point3 p2; }; struct face{ triangle f; texture t; triangle n; float d; // distance }; void orthogonalStart(); void orthogonalEnd(); void startArrays(); void endArrays(); void startTexture(GLuint); void endTexture(); void perspectiveGL( float fovY, float aspect, float zNear, float zFar ); void drawFurnish(unsigned int texName, int screenWidth, int screenHeight); void drawBackground(unsigned int texName, int w, int h); void getFurnishTexture(unsigned int); void getBackgroundTextures(); void getObjectTexture(unsigned int, const cv::Mat&); void getCameraOrigin(GLfloat mdl[16], point3 *camera_org); void scaling(float scale, float inVertexes[], float outVertexes[], unsigned vertexesSize); void getFacesNearToCamera(unsigned vertexesSize, point3 cameraOrigin,float inTexcoords[], float inColors[][4], float inVertexes[], float outTexCoords[], float outColors[][4], float outVertexes[], unsigned *finalVertexes); void getAllSortedFaces(unsigned vertexesSize, point3 cameraOrigin,float inTexcoords[], float inVertexes[], float inNormals[], float outTexCoords[], float outVertexes[], float outNormals[], unsigned *finalVertexes); float getDistance(point3 a, point3 b); #endif
[ "root@tbf03.tbf.mx" ]
root@tbf03.tbf.mx
8ea79c2e1e7deea7c0bf1ad31a5607c8fbd0b757
8380b5eb12e24692e97480bfa8939a199d067bce
/Carberp Botnet/source - absource/pro/all source/BlackJoeWhiteJoe/include/necko/nsIEffectiveTLDService.h
3a750be0bceddccf36df9f37368d64b8cafa6682
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
RamadhanAmizudin/malware
788ee745b5bb23b980005c2af08f6cb8763981c2
62d0035db6bc9aa279b7c60250d439825ae65e41
refs/heads/master
2023-02-05T13:37:18.909646
2023-01-26T08:43:18
2023-01-26T08:43:18
53,407,812
873
291
null
2023-01-26T08:43:19
2016-03-08T11:44:21
C++
UTF-8
C++
false
false
10,575
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/netwerk/dns/public/nsIEffectiveTLDService.idl */ #ifndef __gen_nsIEffectiveTLDService_h__ #define __gen_nsIEffectiveTLDService_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIURI; /* forward declaration */ /* starting interface: nsIEffectiveTLDService */ #define NS_IEFFECTIVETLDSERVICE_IID_STR "6852369e-baa9-4c9a-bbcd-5123fc54a297" #define NS_IEFFECTIVETLDSERVICE_IID \ {0x6852369e, 0xbaa9, 0x4c9a, \ { 0xbb, 0xcd, 0x51, 0x23, 0xfc, 0x54, 0xa2, 0x97 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIEffectiveTLDService : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IEFFECTIVETLDSERVICE_IID) /** * Returns the public suffix of a URI. A public suffix is the highest-level domain * under which individual domains may be registered; it may therefore contain one * or more dots. For example, the public suffix for "www.bbc.co.uk" is "co.uk", * because the .uk TLD does not allow the registration of domains at the * second level ("bbc.uk" is forbidden). * * The public suffix will be returned encoded in ASCII/ACE and will be normalized * according to RFC 3454, i.e. the same encoding returned by nsIURI::GetAsciiHost(). * If consumers wish to compare the result of this method against the host from * another nsIURI, the host should be obtained using nsIURI::GetAsciiHost(). * In the case of nested URIs, the innermost URI will be used. * * @param aURI The URI to be analyzed * * @returns the public suffix * * @throws NS_ERROR_UNEXPECTED * or other error returned by nsIIDNService::normalize when * the hostname contains characters disallowed in URIs * @throws NS_ERROR_HOST_IS_IP_ADDRESS * if the host is a numeric IPv4 or IPv6 address (as determined by * the success of a call to PR_StringToNetAddr()). */ /* ACString getPublicSuffix (in nsIURI aURI); */ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffix(nsIURI *aURI, nsACString & _retval NS_OUTPARAM) = 0; /** * Returns the base domain of a URI; that is, the public suffix with a given * number of additional domain name parts. For example, the result of this method * for "www.bbc.co.uk", depending on the value of aAdditionalParts parameter, will * be: * * 0 (default) -> bbc.co.uk * 1 -> www.bbc.co.uk * * Similarly, the public suffix for "www.developer.mozilla.org" is "org", and the base * domain will be: * * 0 (default) -> mozilla.org * 1 -> developer.mozilla.org * 2 -> www.developer.mozilla.org * * The base domain will be returned encoded in ASCII/ACE and will be normalized * according to RFC 3454, i.e. the same encoding returned by nsIURI::GetAsciiHost(). * If consumers wish to compare the result of this method against the host from * another nsIURI, the host should be obtained using nsIURI::GetAsciiHost(). * In the case of nested URIs, the innermost URI will be used. * * @param aURI The URI to be analyzed * @param aAdditionalParts Number of domain name parts to be * returned in addition to the public suffix * * @returns the base domain (public suffix plus the requested number of additional parts) * * @throws NS_ERROR_UNEXPECTED * or other error returned by nsIIDNService::normalize when * the hostname contains characters disallowed in URIs * @throws NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS * when there are insufficient subdomain levels in the hostname to satisfy the * requested aAdditionalParts value. * @throws NS_ERROR_HOST_IS_IP_ADDRESS * if aHost is a numeric IPv4 or IPv6 address (as determined by * the success of a call to PR_StringToNetAddr()). * * @see getPublicSuffix() */ /* ACString getBaseDomain (in nsIURI aURI, [optional] in PRUint32 aAdditionalParts); */ NS_SCRIPTABLE NS_IMETHOD GetBaseDomain(nsIURI *aURI, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) = 0; /** * NOTE: It is strongly recommended to use getPublicSuffix() above if a suitable * nsIURI is available. Only use this method if this is not the case. * * Returns the public suffix of a host string. Otherwise identical to getPublicSuffix(). * * @param aHost The host to be analyzed. Any additional parts (e.g. scheme, * port, or path) will cause this method to throw. ASCII/ACE and * UTF8 encodings are acceptable as input; normalization will * be performed as specified in getBaseDomain(). * * @see getPublicSuffix() */ /* ACString getPublicSuffixFromHost (in AUTF8String aHost); */ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffixFromHost(const nsACString & aHost, nsACString & _retval NS_OUTPARAM) = 0; /** * NOTE: It is strongly recommended to use getBaseDomain() above if a suitable * nsIURI is available. Only use this method if this is not the case. * * Returns the base domain of a host string. Otherwise identical to getBaseDomain(). * * @param aHost The host to be analyzed. Any additional parts (e.g. scheme, * port, or path) will cause this method to throw. ASCII/ACE and * UTF8 encodings are acceptable as input; normalization will * be performed as specified in getBaseDomain(). * * @see getBaseDomain() */ /* ACString getBaseDomainFromHost (in AUTF8String aHost, [optional] in PRUint32 aAdditionalParts); */ NS_SCRIPTABLE NS_IMETHOD GetBaseDomainFromHost(const nsACString & aHost, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIEffectiveTLDService, NS_IEFFECTIVETLDSERVICE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIEFFECTIVETLDSERVICE \ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffix(nsIURI *aURI, nsACString & _retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetBaseDomain(nsIURI *aURI, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffixFromHost(const nsACString & aHost, nsACString & _retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetBaseDomainFromHost(const nsACString & aHost, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIEFFECTIVETLDSERVICE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffix(nsIURI *aURI, nsACString & _retval NS_OUTPARAM) { return _to GetPublicSuffix(aURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetBaseDomain(nsIURI *aURI, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) { return _to GetBaseDomain(aURI, aAdditionalParts, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffixFromHost(const nsACString & aHost, nsACString & _retval NS_OUTPARAM) { return _to GetPublicSuffixFromHost(aHost, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetBaseDomainFromHost(const nsACString & aHost, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) { return _to GetBaseDomainFromHost(aHost, aAdditionalParts, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIEFFECTIVETLDSERVICE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffix(nsIURI *aURI, nsACString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPublicSuffix(aURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetBaseDomain(nsIURI *aURI, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetBaseDomain(aURI, aAdditionalParts, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetPublicSuffixFromHost(const nsACString & aHost, nsACString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPublicSuffixFromHost(aHost, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetBaseDomainFromHost(const nsACString & aHost, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetBaseDomainFromHost(aHost, aAdditionalParts, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsEffectiveTLDService : public nsIEffectiveTLDService { public: NS_DECL_ISUPPORTS NS_DECL_NSIEFFECTIVETLDSERVICE nsEffectiveTLDService(); private: ~nsEffectiveTLDService(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsEffectiveTLDService, nsIEffectiveTLDService) nsEffectiveTLDService::nsEffectiveTLDService() { /* member initializers and constructor code */ } nsEffectiveTLDService::~nsEffectiveTLDService() { /* destructor code */ } /* ACString getPublicSuffix (in nsIURI aURI); */ NS_IMETHODIMP nsEffectiveTLDService::GetPublicSuffix(nsIURI *aURI, nsACString & _retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* ACString getBaseDomain (in nsIURI aURI, [optional] in PRUint32 aAdditionalParts); */ NS_IMETHODIMP nsEffectiveTLDService::GetBaseDomain(nsIURI *aURI, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* ACString getPublicSuffixFromHost (in AUTF8String aHost); */ NS_IMETHODIMP nsEffectiveTLDService::GetPublicSuffixFromHost(const nsACString & aHost, nsACString & _retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* ACString getBaseDomainFromHost (in AUTF8String aHost, [optional] in PRUint32 aAdditionalParts); */ NS_IMETHODIMP nsEffectiveTLDService::GetBaseDomainFromHost(const nsACString & aHost, PRUint32 aAdditionalParts, nsACString & _retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIEffectiveTLDService_h__ */
[ "fdiskyou@users.noreply.github.com" ]
fdiskyou@users.noreply.github.com
3a2f7c3b8c54b5e95fd411221bcd331ba175a719
1d9e0de82d0a507836a152c49d19a0a2dd8b356f
/Extraction/ColorStructureExtraction.cpp
d60f3b8220214730d5a5d65b5886d023611e1200
[]
no_license
fabiofranca92/Imagiology-----College
3aede9151da02def753edcee1cbf319c1f604965
f8b8aaed7f8428855156ce4cf57307e9b7097c5c
refs/heads/master
2016-08-11T06:25:44.995115
2016-01-12T14:52:49
2016-01-12T14:52:49
49,506,764
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
30,233
cpp
//////////////////////////////////////////////////////////////////////// // // ColorStructureExtraction.cpp // // This software module was originally developed by // // Jim Errico, Sharp Laboratories of America, Camas, WA // Peter van Beek, Sharp Laboratories of America, Camas, WA // // // in the course of development of the MPEG-7 standard (ISO/IEC 15938). // This software module is an implementation of a part of one or more // MPEG-7 tools as specified by the MPEG-7 standard (ISO/IEC 15938). // ISO/IEC gives users of the MPEG-7 standard free license to this // software module or modifications thereof for use in hardware or // software products claiming conformance to the MPEG-7 standard. // Those intending to use this software module in hardware or software // products are advised that its use may infringe existing patents. // The original developer of this software module and his/her company, // the subsequent editors and their companies, and ISO/IEC have no // liability for use of this software module or modifications thereof // in an application. No license to this software is granted for non // MPEG-7 conforming products. // Sharp Laboratories of America retains full right to use the software // module for their own purpose, assign or donate the software module // to a third party and to inhibit third parties from using the software // module for non MPEG-7 conforming products. // // Copyright (c) 2000 // // This copyright notice must be included in all copies or derivative // works of this software module. // //////////////////////////////////////////////////////////////////////// #ifndef MAX #define MAX(a,b) ((a) < (b) ? (b) : (a)) #endif #include <cassert> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include "AddressLib/momusys.h" #include "Extraction/ColorStructureExtraction.h" //============================================================================= using namespace XM; // Hard coded ColorQuantization parameters const int ColorStructureExtractionTool:: diffThresh[NUM_COLOR_QUANT_SPACE][MAX_SUB_SPACE+1] = { {0,6,60,110,256,-1}, {0,6,20,60,110,256}, {0,6,20,60,110,256}, {0,6,20,60,110,256}}; const int ColorStructureExtractionTool:: nHueLevels[NUM_COLOR_QUANT_SPACE][MAX_SUB_SPACE] = { {1,4,4,4,0}, {1,4,4,8,8}, {1,4,8,8,8}, {1,4,16,16,16}}; const int ColorStructureExtractionTool:: nSumLevels[NUM_COLOR_QUANT_SPACE][MAX_SUB_SPACE] = { {8,4,1,1,0}, {8,4,4,2,1}, {16,4,4,4,4}, {32,8,4,4,4}}; // The following could be derived implicitly from nHue and nSum // Reverse these to order quantization from inside to outside const int ColorStructureExtractionTool:: nCumLevels[NUM_COLOR_QUANT_SPACE][MAX_SUB_SPACE] = { // {0,8,24,28,0}, // {0,8,24,40,56}, // {0,16,32,64,96}, // {0,32,64,128,192}}; {24,8,4,0,0}, {56,40,24,8,0}, {112,96,64,32,0}, {224,192,128,64,0}}; const double ColorStructureExtractionTool:: amplThresh[] = {0.0, 0.000000000001, 0.037, 0.08, 0.195, 0.32}; const int ColorStructureExtractionTool:: nAmplLevels[] = {1, 25, 20, 35, 35, 140}; unsigned char *ColorStructureExtractionTool:: colorQuantTable[NUM_COLOR_QUANT_SPACE] = {0,0,0,0}; unsigned char cqt256_128[] = { 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 13, 14, 15, 12, 13, 14, 15, 16, 17, 18, 19, 16, 17, 18, 19, 20, 21, 22, 23, 20, 21, 22, 23, 24, 25, 26, 27, 24, 25, 26, 27, 28, 29, 30, 31, 28, 29, 30, 31, 32, 33, 34, 35, 32, 33, 34, 35, 36, 37, 38, 39, 36, 37, 38, 39, 40, 41, 42, 43, 40, 41, 42, 43, 44, 45, 46, 47, 44, 45, 46, 47, 48, 49, 50, 51, 48, 49, 50, 51, 52, 53, 54, 55, 52, 53, 54, 55, 56, 57, 58, 59, 56, 57, 58, 59, 60, 61, 62, 63, 60, 61, 62, 63, 64, 65, 66, 67, 64, 65, 66, 67, 68, 69, 70, 71, 68, 69, 70, 71, 72, 73, 74, 75, 72, 73, 74, 75, 76, 77, 78, 79, 76, 77, 78, 79, 80, 81, 82, 83, 80, 81, 82, 83, 84, 85, 86, 87, 84, 85, 86, 87, 88, 89, 90, 91, 88, 89, 90, 91, 92, 93, 94, 95, 92, 93, 94, 95, 96, 96, 97, 97, 98, 98, 99, 99, 100, 100, 101, 101, 102, 102, 103, 103, 104, 104, 105, 105, 106, 106, 107, 107, 108, 108, 109, 109, 110, 110, 111, 111, 112, 112, 113, 113, 114, 114, 115, 115, 116, 116, 117, 117, 118, 118, 119, 119, 120, 120, 121, 121, 122, 122, 123, 123, 124, 124, 125, 125, 126, 126, 127, 127 }; unsigned char cqt256_064[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 8, 8, 9, 9, 10, 10, 11, 11, 10, 10, 11, 11, 12, 12, 13, 13, 12, 12, 13, 13, 14, 14, 15, 15, 14, 14, 15, 15, 16, 16, 17, 17, 16, 16, 17, 17, 18, 18, 19, 19, 18, 18, 19, 19, 20, 20, 21, 21, 20, 20, 21, 21, 22, 22, 23, 23, 22, 22, 23, 23, 24, 25, 26, 27, 24, 25, 26, 27, 24, 25, 26, 27, 24, 25, 26, 27, 28, 29, 30, 31, 28, 29, 30, 31, 28, 29, 30, 31, 28, 29, 30, 31, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 36, 37, 38, 39, 36, 37, 38, 39, 36, 37, 38, 39, 36, 37, 38, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 56, 56, 57, 57, 57, 57, 58, 58, 58, 58, 59, 59, 59, 59, 60, 60, 60, 60, 61, 61, 61, 61, 62, 62, 62, 62, 63, 63, 63, 63 }; unsigned char cqt256_032[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 16, 17, 18, 19, 16, 17, 18, 19, 16, 17, 18, 19, 16, 17, 18, 19, 20, 21, 22, 23, 20, 21, 22, 23, 20, 21, 22, 23, 20, 21, 22, 23, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31 }; unsigned char cqt128_064[] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 25, 26, 27, 24, 25, 26, 27, 28, 29, 30, 31, 28, 29, 30, 31, 32, 33, 34, 35, 32, 33, 34, 35, 36, 37, 38, 39, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 63 }; unsigned char cqt128_032[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 13, 14, 15, 12, 13, 14, 15, 16, 17, 18, 19, 16, 17, 18, 19, 20, 21, 22, 23, 20, 21, 22, 23, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31 }; unsigned char cqt064_032[] = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; #ifndef REGENERATE_TRANSFORM_TABLE unsigned char *ColorStructureExtractionTool:: colorQuantTransform[NUM_COLOR_QUANT_SPACE][NUM_COLOR_QUANT_SPACE] = {{0, 0, 0, 0}, {cqt064_032, 0, 0, 0}, {cqt128_032, cqt128_064, 0, 0}, {cqt256_032, cqt256_064, cqt256_128, 0}}; #else unsigned char *ColorStructureExtractionTool:: colorQuantTransform[NUM_COLOR_QUANT_SPACE][NUM_COLOR_QUANT_SPACE] = {{0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}}; #endif //============================================================================= ColorStructureExtractionTool::ColorStructureExtractionTool(): m_Descriptor(NULL), srcImage(NULL) { m_Descriptor = new ColorStructureDescriptor(); #ifdef REGENERATE_TRANSFORM_TABLE int iOrig, iNew; for(iOrig = 3; iOrig >= 0; iOrig--) BuildColorQuantTable(iOrig); for(iOrig = 3; iOrig >= 0; iOrig--) for(iNew = iOrig - 1; iNew >= 0; iNew--) BuildTransformTable(iOrig, iNew); #endif } //---------------------------------------------------------------------------- ColorStructureExtractionTool::~ColorStructureExtractionTool() { // release descriptor // commented out - mb - 07.07.2008 // descriptor will be released by the clients //if (m_Descriptor) // m_Descriptor->release(); } // set source image whose descriptor is to be computed int ColorStructureExtractionTool::setSourceImage(MomVop* img) { if( img == NULL ) return -1; srcImage = img; return 0; } //---------------------------------------------------------------------------- ColorStructureDescriptor* ColorStructureExtractionTool::GetDescriptor() { return m_Descriptor; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool:: SetDescriptor( ColorStructureDescriptor* aColorStructureDescriptor) { /* check if new value is different from old value*/ if (m_Descriptor == aColorStructureDescriptor) return 0; if (m_Descriptor) delete m_Descriptor; m_Descriptor = aColorStructureDescriptor; return 0; } //---------------------------------------------------------------------------- // img: input image whose descriptor is to be computed // descriptorSize: final descriptor size unsigned long ColorStructureExtractionTool::extract( MomVop *img, int descriptorSize ) { this->setSourceImage( img ); return this->extract( descriptorSize ); } //---------------------------------------------------------------------------- // img: input image whose descriptor is to be computed // descriptorSize: BASE_QUANT_SPACE = 256 unsigned long ColorStructureExtractionTool::extract( MomVop *img) { this->setSourceImage( img ); return this->extract( BASE_QUANT_SPACE ); } //---------------------------------------------------------------------------- // input image must have been set using SetSourceImage function // descriptorSize: fBASE_QUANT_SPACE = 256 unsigned long ColorStructureExtractionTool::extract( void ) { return this->extract( BASE_QUANT_SPACE ); } //---------------------------------------------------------------------------- // source ýmage: RGB (converted to HMMD within the function) // descriptorSize: final descriptor size unsigned long ColorStructureExtractionTool::extract( int descriptorSize ) { MomVop *ImageMedia; unsigned long *quantImageBuffer; // First check that it's all correctly initialised if (m_Descriptor==NULL) return (unsigned long)-1; //if(strcmp(m_Descriptor->GetName(), // "ColorStructureDescriptionInterface") != 0) return (unsigned long)-1; /////////////////////////////////////////////////// // Initial extraction is always to Base size // /////////////////////////////////////////////////// if (!m_Descriptor->SetSize(BASE_QUANT_SPACE)) // BASE_QUANT_SPACE = 256 { for (int i=0; i < BASE_QUANT_SPACE; i++) m_Descriptor->SetElement(i,0); } // source image if ( srcImage == NULL ) return (unsigned long)-1; ImageMedia = srcImage; // Allocate space for quantized image int imageSize = ImageMedia->width * ImageMedia->height; quantImageBuffer = new unsigned long[imageSize]; if (!quantImageBuffer) { //std::cerr << "Allocation error - CSD:extract()" << std::endl; return (unsigned long)-1; } /////////////////////////////////////////// // Convert color space and quantize // /////////////////////////////////////////// int i; int H, S, D; for (i = 0; i < imageSize; i++) { // rgb is vyu in MomVop RGB2HMMD( ImageMedia->v_chan->data->u[i], ImageMedia->y_chan->data->u[i], ImageMedia->u_chan->data->u[i], H, S, D ); quantImageBuffer[i] = QuantHMMD(H, S, D, BASE_QUANT_SPACE_INDEX); } /////////////////////////////////////////// // Extract histogram of color structure // /////////////////////////////////////////// unsigned long col, row, index; unsigned long Norm; unsigned long modifiedImageWidth, modifiedImageHeight, moduloSlideHeight; unsigned long *slideHist; unsigned long *pAdd, *pDel, *pAddStop; unsigned char *pAddAlpha, *pDelAlpha, *quantImageAlpha = 0; if( ImageMedia->a_chan && ImageMedia->a_chan->data ) quantImageAlpha = ImageMedia->a_chan->data->u; // determine working dimensions //const unsigned long slideWidth = 15, slideHeight = 15, subSample = 1; double logArea = log(ImageMedia->width * ImageMedia->height) / log(2); int scalePower = (int)floor(0.5 * logArea - 8 + 0.5); scalePower = MAX(0, scalePower); unsigned long subSample = 1 << scalePower; unsigned long slideWidth = 8 * subSample; unsigned long slideHeight = 8 * subSample; modifiedImageWidth = ImageMedia->width - (slideWidth - 1); modifiedImageHeight = ImageMedia->height - (slideHeight - 1); //moduloSlideHeight = (int) // ((slideHeight + subSample - 1)/subSample) * subSample; // How many actual rows from the first row of a slideHist // to the first row of the next slideHist // If slideHeight is not a multiple of subSample, and n is on // a subSample, then n+slideHeight won't be on a subSample if(slideHeight % subSample == 0) { moduloSlideHeight = slideHeight; } else { moduloSlideHeight = slideHeight + (subSample - slideHeight % subSample); } //assert( slideWidth & 1); // odd //assert( slideHeight & 1); // odd // allocate local sliding window histogram slideHist = new unsigned long[BASE_QUANT_SPACE]; assert( slideHist ); // loop through columns for( col = 0; col < modifiedImageWidth; col += subSample ) { // reset and fill in the first (top of image) full sliding window histograms memset( (void *) slideHist, 0, BASE_QUANT_SPACE * sizeof(unsigned long) ); for( row = 0; row < slideHeight; row += subSample ) { pAdd = &quantImageBuffer[row * ImageMedia->width + col]; pAddAlpha = &quantImageAlpha[row * ImageMedia->width + col]; // May be illegal pointer pAddStop = pAdd + slideWidth; for( ; pAdd < pAddStop; pAdd += subSample, pAddAlpha += subSample ) if( !quantImageAlpha || *pAddAlpha ) slideHist[*pAdd] ++; } // update histogram from first sliding window histograms for ( index = 0; index < BASE_QUANT_SPACE; index ++) { if( slideHist[ index ] ) m_Descriptor-> SetElement( index, m_Descriptor-> GetElement(index) + 1 ); } // slide the window down the rest of the rows for( row = subSample; row < modifiedImageHeight; row += subSample ) { pDel = &quantImageBuffer[(row - subSample) * ImageMedia->width + col]; pDelAlpha = &quantImageAlpha[(row - subSample) * ImageMedia->width + col]; pAdd = &quantImageBuffer[(row + moduloSlideHeight - subSample) * ImageMedia->width + col]; pAddAlpha = &quantImageAlpha[(row + moduloSlideHeight - subSample) * ImageMedia->width + col]; pAddStop = pAdd + slideWidth; for( ; pAdd < pAddStop; pDel += subSample, pAdd += subSample, pDelAlpha += subSample, pAddAlpha += subSample ) { if( !quantImageAlpha || *pDelAlpha ) slideHist[*pDel] --; if( !quantImageAlpha || *pAddAlpha ) slideHist[*pAdd] ++; } // update histogram from sliding window histogram for ( index = 0; index < BASE_QUANT_SPACE; index ++) { if( slideHist[ index ] ) m_Descriptor-> SetElement( index, m_Descriptor-> GetElement(index) + 1 ); } } } // Free memory delete [] slideHist; delete [] quantImageBuffer; Norm = ((ImageMedia->height - slideHeight)/subSample + 1) * ((ImageMedia->width - slideWidth )/subSample + 1); /////////////////////////////////////////// // Requantize color space to Target size // /////////////////////////////////////////// UnifyBins(Norm, descriptorSize); /////////////////////////////////////////// // Quantize the Bin Amplitude // /////////////////////////////////////////// QuantAmplNonLinear(Norm); return 0; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::DownQuantHMMD(int nNewSize) { int nOrigSize = m_Descriptor->GetSize(); if (nOrigSize == nNewSize) return 0; assert(nOrigSize > nNewSize); // Linearize, Unify, and Nonlinearize; all at 2^20 ConvertAmplLinear ((1 << 20) - 1); UnifyBins ((1 << 20) - 1, nNewSize); QuantAmplNonLinear ((1 << 20) - 1); return 0; } //---------------------------------------------------------------------------- void ColorStructureExtractionTool::RGB2HMMD(int R, int G, int B, int &H, int &S, int &D) { int max, min; float hue; max=R; if(max<G) {max=G;} if(max<B) {max=B;} min=R; if(min>G) {min=G;} if(min>B) {min=B;} if (max == min) // ( R == G == B )//exactly gray hue = -1; //hue is undefined else { //solve Hue if(R==max) hue=((G-B)/(float)(max-min)); else if(G==max) hue=(2.0+(B-R)/(float)(max-min)); else if(B==max) hue=(4.0+(R-G)/(float)(max-min)); hue*=60; if(hue<0.0) hue+=360; } H = (long)(hue + 0.5); //range [0,360] S = (long)((max + min)/2.0 + 0.5); //range [0,255] D = (long)(max - min + 0.5); //range [0,255] return; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::QuantHMMD(int H, int S, int D, int N) { // Test bounds of input assert(H >= 0 && H <= 360); assert(D >= 0 && D < 256); assert(S >= (D+1)>>1 && S < 256 - (D>>1)); if (colorQuantTable[N]) return colorQuantTable[N][(H<<16) + (S<<8) + D]; // Note: lower threshold boundary is inclusive, // i.e. diffThresh[..][m] <= (D of subspace m) < diffThresh[..][m+1] // Quantize the Difference component, find the Subspace int iSub = 0; while( diffThresh[N][iSub + 1] <= D ) iSub ++; // Valid subspace ? assert(diffThresh[N][iSub + 1] >= 0); // Quantize the Hue component int Hindex = (int)((H / 360.0) * nHueLevels[N][iSub]); if ( H == 360 ) Hindex = 0; // Quantize the Sum component // The min value of Sum in a subspace is 0.5*diffThresh (see HMMD slice) int Sindex = (int)floor((S - 0.5*diffThresh[N][iSub]) * nSumLevels[N][iSub] / (255 - diffThresh[N][iSub])); if ( Sindex >= nSumLevels[N][iSub] ) Sindex = nSumLevels[N][iSub] - 1; /* The following quantization of Sum is more uniform and doesn't require the bounds check int Sindex = (int)floor((S - 0.5*diffThresh[N][iSub]) * nSumLevels[N][iSub] / (256 - diffThresh[N][iSub])); */ return nCumLevels[N][iSub] + Hindex*nSumLevels[N][iSub] + Sindex; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::BuildColorQuantTable(int iColorQuantSpace) { const int nSize = 361*256*256; // TODO cut size in half, using triangular properties if (colorQuantTable[iColorQuantSpace]) return 1; unsigned char *tbl = new unsigned char[nSize]; memset(tbl,0,nSize); if (!tbl) { //std::cerr << "Could not allocate " << nSize << " for Color Quant Table!" << std::endl; return 0; } //std::cerr << "Building Color Quant Table (" << (32 << iColorQuantSpace) << ")" << std::endl; int H, S, D; for ( H = 0; H < 361; H++) { for ( D = 0; D < 256; D++ ) { int beginS = (D+1)>>1; int endS = 256 - (D>>1); // Color Space extraction rounds up (i.e. max=255,min=254 => sum=255) for ( S = beginS; S < endS; S++ ) { tbl[(H<<16) + (S<<8) + D] = QuantHMMD(H, S, D, iColorQuantSpace); } } } colorQuantTable[iColorQuantSpace] = tbl; return 1; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::TransformBinIndex(int iOrig, int iOrigColorQuantSpace, int iNewColorQuantSpace) { // ColorQuantSpace enums are in ascending order assert(iOrigColorQuantSpace > iNewColorQuantSpace); // Build transform table if not already present if (!colorQuantTransform[iOrigColorQuantSpace][iNewColorQuantSpace]) BuildTransformTable(iOrigColorQuantSpace, iNewColorQuantSpace); if (!colorQuantTransform[iOrigColorQuantSpace][iNewColorQuantSpace]) { //std::cerr << "Unable to BuildTransformTable" << std::endl; exit(1); } return colorQuantTransform[iOrigColorQuantSpace][iNewColorQuantSpace][iOrig]; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::BuildTransformTable(int iOrigColorQuantSpace, int iNewColorQuantSpace) { const int maxMatchTest = 27; // Allow deviation +/- 1 in 3D int iMatch[maxMatchTest], nMatch[maxMatchTest], nUniqueMatch = 0; int iOrig, iNew; int H, S, D; int iTest; // Allocate unsigned char *tbl = new unsigned char[GetBinSize(iOrigColorQuantSpace)]; if (!tbl) { //std::cerr << "Could not allocate " << GetBinSize(iOrigColorQuantSpace) << // " for Color Space Transform!" << std::endl; return 0; } //std::cerr << "Building Transform Table (" << (32 << iOrigColorQuantSpace) << // " => " << (32 << iNewColorQuantSpace) << ")" << std::endl; // Loop through originating cells for (iOrig = 0; iOrig < GetBinSize(iOrigColorQuantSpace); iOrig++ ) { // Loop through 24 bit HMMD values for (H = 0; H < 361; H++) { for (D = 0; D < 256; D++) { int beginS = (D+1)>>1; int endS = 256 - (D>>1); for (S = beginS; S < endS; S++) { // Check match and get new space if (QuantHMMD(H, S, D, iOrigColorQuantSpace) == iOrig) { iNew = QuantHMMD(H, S, D, iNewColorQuantSpace); // Find result in Match array for (iTest = 0; iTest < nUniqueMatch; iTest++) { if ( iMatch[iTest] == iNew ) break; } // Accumulate stats on best match if (iTest == nUniqueMatch) { assert( nUniqueMatch < maxMatchTest); iMatch[nUniqueMatch] = iNew; nMatch[nUniqueMatch] = 1; nUniqueMatch ++; } else nMatch[iTest] ++; } } } } // Report on inexact matches if (nUniqueMatch > 1) { int nTotal = 0; fprintf(stdout,"%d to %d duplicate mapping: %d => ", GetBinSize(iOrigColorQuantSpace), GetBinSize(iNewColorQuantSpace), iOrig); for(iTest = 0; iTest < nUniqueMatch; iTest++) nTotal += nMatch[iTest]; for(iTest = 0; iTest < nUniqueMatch; iTest++) fprintf(stdout, "%d (%2d%%), ", iMatch[iTest], 100*nMatch[iTest]/nTotal); fprintf(stdout,"\n"); } if (!nUniqueMatch) { fprintf(stderr, "No match found in BuildTransformTable(%d,%d)", iOrigColorQuantSpace,iNewColorQuantSpace); exit(1); } // Select the best match int iBest = -1, nBest = 0; for ( iTest = 0; iTest < nUniqueMatch; iTest ++) { if ( nMatch[iTest] > nBest ) { nBest = nMatch[iTest]; iBest = iMatch[iTest]; } } // Update table and reset stats tbl[iOrig] = iBest; nUniqueMatch = 0; } // Loop through orig indices // Print out transform table (then, hard-code into this module) fprintf(stdout, "Color Space Transform: %d to %d\n", GetBinSize(iOrigColorQuantSpace), GetBinSize(iNewColorQuantSpace)); int nPrec = GetBinSize(iNewColorQuantSpace)>100?3:2; for (iOrig = 0; iOrig < GetBinSize(iOrigColorQuantSpace); iOrig ++) { fprintf(stdout, "%*d", nPrec, tbl[iOrig]); if (iOrig != GetBinSize(iOrigColorQuantSpace)-1) fprintf(stdout, ","); if ((iOrig+1) % 16 == 0) fprintf(stdout, "\n"); else fprintf(stdout, " "); } fflush(stdout); if (colorQuantTransform[iOrigColorQuantSpace][iNewColorQuantSpace]) delete colorQuantTransform[iOrigColorQuantSpace][iNewColorQuantSpace]; colorQuantTransform[iOrigColorQuantSpace][iNewColorQuantSpace] = tbl; return 1; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::QuantAmplNonLinear(unsigned long Norm) { unsigned long iBin, TotalNoOfBins, iQuant; const int nAmplLinearRegions = sizeof(nAmplLevels)/sizeof(nAmplLevels[0]); int nTotalLevels = 0; // Calculate total levels for (iQuant = 0; iQuant < nAmplLinearRegions; iQuant++) nTotalLevels += nAmplLevels[iQuant]; // Get size TotalNoOfBins = m_Descriptor->GetSize(); // Loop through bins for ( iBin = 0; iBin < TotalNoOfBins; iBin ++) { // Get bin amplitude double val = m_Descriptor->GetElement(iBin); // Normalize val /= Norm; assert (val>=0.0); assert (val<= 1.0); // Find quantization boundary and base value int quantValue = 0; for (iQuant = 0; iQuant+1 < nAmplLinearRegions; iQuant++ ) { if (val < amplThresh[iQuant+1]) break; quantValue += nAmplLevels[iQuant]; } // Quantize double nextThresh = (iQuant+1 < nAmplLinearRegions) ? amplThresh[iQuant+1] : 1.0; val = floor(quantValue + (val - amplThresh[iQuant]) * (nAmplLevels[iQuant] / (nextThresh - amplThresh[iQuant]))); // Limit (and alert), one bin contains all of histogram if (val == nTotalLevels) { // Possible (though rare) case // cerr << "Degenerate case, histogram bin " << iBin << " has value " << // GetHistogramDescriptorInterface()->GetElement(iBin) << " of " << Norm << " Norm" << endl; val = nTotalLevels - 1; } assert(val >= 0.0); assert(val < nTotalLevels); // Set value into histogram m_Descriptor->SetElement( iBin, (int)val ); } return 0; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::UnifyBins(unsigned long Norm, int nTargSize) { double *pBin; int iTargBin, iOrigBin; int nOrigSize = m_Descriptor->GetSize(); if (nTargSize == nOrigSize) return 0; // Only down quantize assert ( nTargSize < nOrigSize ); // Grab temp space pBin = new double [nTargSize]; assert(pBin); for (iTargBin = 0; iTargBin < nTargSize; iTargBin++) pBin[iTargBin] = 0.0; int iTargSpace = GetColorQuantSpace(nTargSize); int iOrigSpace = GetColorQuantSpace(nOrigSize); // Unify for (iOrigBin = 0; iOrigBin < nOrigSize; iOrigBin++) { iTargBin = TransformBinIndex(iOrigBin, iOrigSpace, iTargSpace); pBin[iTargBin] += m_Descriptor->GetElement(iOrigBin); } // Resize the descriptor m_Descriptor->SetSize(nTargSize); // Clip and insert for (iTargBin = 0; iTargBin < nTargSize; iTargBin++) { if (pBin[iTargBin] > Norm) pBin[iTargBin] = Norm; m_Descriptor->SetElement(iTargBin, pBin[iTargBin]); } return 0; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::ConvertAmplLinear(unsigned long NewNorm) { unsigned long iBin, TotalNoOfBins; const unsigned long OldNorm = 255; const int nAmplLinearRegions = sizeof(nAmplLevels)/sizeof(nAmplLevels[0]); int iQuant; // Get histogram size TotalNoOfBins = m_Descriptor->GetSize(); #ifdef _DEBUG // Assume that OldNorm is equal to the maximum quant level // Test assumption int cumQuant = 0; for( iQuant = 0; iQuant < nAmplLinearRegions; iQuant++) cumQuant += nAmplLevels[iQuant]; assert(cumQuant == OldNorm + 1); #endif // Loop through bins for ( iBin = 0; iBin < TotalNoOfBins; iBin ++) { // Get bin amplitude double val = m_Descriptor->GetElement(iBin); assert(val <= OldNorm); // Find quantization boundary and base value int quantBdry = 0; for( iQuant = 0; iQuant < nAmplLinearRegions; iQuant++ ) { if (val < quantBdry + nAmplLevels[iQuant]) break; quantBdry += nAmplLevels[iQuant]; } assert(iQuant < nAmplLinearRegions); // UnQuantize, find central point of this quantization level double nextQuantBdry = quantBdry + nAmplLevels[iQuant]; double nextThresh = iQuant+1 < nAmplLinearRegions ? amplThresh[iQuant+1] : 1.0; val = amplThresh[iQuant] + (nextThresh - amplThresh[iQuant]) * (val + 0.5 - quantBdry) / (nextQuantBdry - quantBdry); // UnNormalize (new) assert(val <= 1.0); val = floor(val * NewNorm + 0.5); // Set value into histogram m_Descriptor->SetElement( iBin, (int)val ); } return 0; } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::GetColorQuantSpace(int size) { if (size == 256) return 3; else if (size == 128) return 2; else if (size == 64) return 1; else if (size == 32) return 0; else { assert("Out of bounds GetColorQuantSpace"); return -1; } } //---------------------------------------------------------------------------- int ColorStructureExtractionTool::GetBinSize(int iColorQuantSpace) { if (iColorQuantSpace <= 3 && iColorQuantSpace >= 0) return 32 << iColorQuantSpace; else { assert("Out of bounds GetBinSize"); return 0; } }
[ "fabiofranca@Fabio-Franca-2.home" ]
fabiofranca@Fabio-Franca-2.home
eeb893340e53e5345011ef35a978174c91474f6a
cd3779b42d5e4e5f922d3ede1cbd4373f7c99d85
/Corruption/game/entityLayer/entitySerializer.hpp
200128d8983e4bbdbb50b2dcb247730df12c7dbc
[]
no_license
ianw3214/corruption
87e24de830bf798cbac0fe0add3f938eb4e91234
6d5c7e38453d1b213c49e0a9d00f291c2f74cfdb
refs/heads/master
2020-09-15T17:46:26.403713
2019-12-23T04:16:24
2019-12-23T04:16:24
223,519,748
0
1
null
null
null
null
UTF-8
C++
false
false
760
hpp
#pragma once #include "entity.hpp" #include <unordered_map> #include <fstream> class EntitySerializer { public: static void Init(); static void ExportEntity(Oasis::Reference<Entity> entity, const std::string& filename); static void ExportEntity(Oasis::Reference<Entity> entity, std::ofstream& file); static Entity* ReadEntity(const std::string& filename); static Entity* ReadEntity(std::ifstream& file); private: static std::unordered_map<int, Component*> s_componentMap; ///////////////////////////////////////////////////////////////// template<typename COMPONENT, int index> static void RegisterComponent() { s_componentMap[index] = new COMPONENT(); COMPONENT::s_serializerIndex = index; }; };
[ "ianw3214@gmail.com" ]
ianw3214@gmail.com
f015e9aac3ca8fa6a04f2428272119b77805472f
962b523b62da7ca57872f2ab48b437aad19480d1
/src/raw_02_work2.cpp
8ba9f62ea2938572094a3ed22b010c54a35ac7f4
[]
no_license
HyungjunAn/lang-cpp
bda40646d075660c6f69e437f411e8777f34a53c
24d2a1658eadfbae3f5b73f655d8c9da2b2608cb
refs/heads/main
2023-06-28T16:57:32.550490
2021-08-10T07:18:20
2021-08-10T07:18:20
394,546,795
0
0
null
null
null
null
UHC
C++
false
false
1,124
cpp
#define USING_GUI #include "cppmaster.h" #include <map> using namespace std; // 1일차 thiscall 예제를 참고 하세요 int foo(int hwnd, int msg, int a, int b) { switch (msg) { case WM_KEYDOWN: cout << "keydown" << endl; break; case WM_LBUTTONDOWN: cout << "lbutton" << endl; break; } return 0; } int main() { int h1 = ec_make_window(foo, "A"); int h2 = ec_make_window(foo, "B"); ec_process_message(); } /* // 아래의 Window 클래스를 만드는 것이 과제 입니다 class Window { int hwnd; public: void Create() { // 여기를 구현하세요.. // 메세지 처리 함수도 Window 클래스 안에 추가하세요 } virtual void LButtonDown() {} virtual void KeyDown() {} }; class MyWindow : public Window { public: virtual void LButtonDown() { cout << "MyWindow LButtonDown" << endl; } virtual void KeyDown() { cout << "MyWindow KeyDown" << endl; } }; int main() { MyWindow w; w.Create(); // 이순간 윈도우가 생성되어야합니다. // 왼쪽 버튼을 누르면 MyWindow 의 LButtonDown() 함수가 호출되어야 합니다. ec_process_message(); } */
[ "hyungjun0429@gmail.com" ]
hyungjun0429@gmail.com
abe8a17de3fefb0a45381157adf527e8f0c1d0bb
2a2927294921211d9f0392d0dd201024d489dd36
/ex9/gradesFuncs.cpp
0bdbec7067430d87baedea53cd45558c26d37238
[]
no_license
david-s0/Savitch-Ch6
487139020ddf1af8f2c0f0f04a28162375f8fea6
31e1f995d3a26c15a4c676f9b3ca464bd515d922
refs/heads/master
2021-01-10T20:36:32.354988
2012-12-28T20:47:06
2012-12-28T20:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,229
cpp
#include <fstream> #include <iostream> #include "gradesFuncs.hpp" using namespace std; //START OF FUNCTION DEFINITION FOR void (ifstream&, ofstream&) void produceResult(ifstream& in, ofstream& out) { char next_char; bool space = false; //open the file in.open("grades.txt"); out.open("results.txt"); //make sure the file is OK if (in.fail()) { cerr << "There was a problem opening the file." << endl; } while (!in.eof()) { in.get(next_char); out.put(next_char); if ((next_char == ' ') && space) { totalOfGrades(in, out); space = false; } else if (next_char == ' ') { space = true; } } in.close(); out.close(); } //END OF FUNCTION DEFINITION //START OF FUNCTION DEFINITION FOR int totalOfGrades(ifstream&) void totalOfGrades(ifstream& in, ofstream& out) { char next_char; double curr, tot = 0; double result; while (next_char != '\n') { in.get(next_char); if (next_char == '\n') { out.put(' '); result = tot / 10; out << std::fixed << result; } out.put(next_char); if (next_char != ' ') { curr = static_cast<int>(next_char) - 48; tot += curr; } } } //END OF FUNCTION DEFINITION
[ "ds2412@imperial.ac.uk" ]
ds2412@imperial.ac.uk
6d8f1572895a48121060aa07b40d3955b642eb22
f1a2325795dcd90f940e45a3535ac3a0cb765616
/development/TelecomServices/SignalProtection/SP_ERSIF.h
7aff7ee1be17247c15e5834a15df2766c95d1c30
[]
no_license
MoonStart/Frame
45c15d1e6febd7eb390b74b891bc5c40646db5de
e3a3574e5c243d9282778382509858514585ae03
refs/heads/master
2021-01-01T19:09:58.670794
2015-12-02T07:52:55
2015-12-02T07:52:55
31,520,344
0
0
null
null
null
null
UTF-8
C++
false
false
2,100
h
//Copyright(c) Tellabs Transport Group. All rights reserved #ifndef SP_ERSIF_H #define SP_ERSIF_H #include <CommonTypes/CT_Telecom.h> #include <CommonTypes/CT_SignalProtection.h> #include <SignalProtection/SP_Definitions.h> class SP_TimingRSConfigRegion; //This class defines an abstract interface //for equipment redundancy related operations //Any module that supports equipment redundancy is //expected to provide a concrete implementation of this //interface class SP_ERSIF { public: virtual void AcquireMastership() =0; virtual void ReleaseMastership() =0; virtual bool IsMaster() = 0; virtual bool IsMateMaster() = 0; virtual bool IsMatePresent() = 0; virtual bool IsMateReady() = 0; virtual void SendERSMessage(CT_ControllerMode theMode) = 0; virtual uint32 GetRxMessageCounter() = 0; virtual bool IsModuleOOS() = 0; virtual bool InitOnOOSAllowed() = 0; virtual void SetHeartBeatState(bool theState) = 0; virtual bool GetHeartBeatState() = 0; virtual void SetTxERSMessage(uint32 theMessage) = 0; virtual uint32 GetTxERSMessage() = 0; virtual uint32 GetRxERSMessage() = 0; virtual void ControlActiveLED(bool isActive) = 0; }; //This class provides a base implementation for the above //SP_ERSIF interface class SP_ERSDefaultImp: public SP_ERSIF { public: // Default class constructor SP_ERSDefaultImp(); // Virtual class destructor virtual ~SP_ERSDefaultImp(); virtual void AcquireMastership(); virtual void ReleaseMastership(); virtual bool IsMaster(); virtual bool IsMateMaster(); virtual bool IsMatePresent(); virtual bool IsMateReady(); virtual void SendERSMessage(CT_ControllerMode theMode); virtual uint32 GetRxMessageCounter(); virtual bool IsModuleOOS(); virtual bool InitOnOOSAllowed(); virtual void SetHeartBeatState(bool theState); virtual bool GetHeartBeatState(); virtual void SetTxERSMessage(uint32 theMessage); virtual uint32 GetTxERSMessage(); virtual uint32 GetRxERSMessage(); virtual void ControlActiveLED(bool isActive); private: }; #endif /* SP_ERSIF_H */
[ "lijin303x@163.com" ]
lijin303x@163.com
cb356cd043fa4f2f809e20d5276e4466b7b405f7
68c4bab1f5d5228078d603066b6c6cea87fdbc7a
/lab/frozen/with-some-problems/sinfonia-cpp/src/cpp/includeExt/biblia/io/rede/InterfaceCliente.h
c0d492c09271a8fa98e713c61ed6e6b41829d4de
[]
no_license
felipelalli/micaroni
afab919dab304e21ba916aa6310dca102b1a04a5
741b628754b7c7085d3e68009a621242c2a1534e
refs/heads/master
2023-08-03T06:25:15.405861
2023-07-25T14:44:56
2023-07-25T14:44:56
537,536
2
1
null
null
null
null
ISO-8859-1
C++
false
false
743
h
/* * $RCSfile: InterfaceCliente.h,v $ * $Date: 2003/05/29 21:13:19 $ * $Revision: 1.2 $ * * Implementação da biblioteca Bíblia. * Streamworks, outubro de 2002. ($Name: $ , $Author: felipe $) */ #ifndef INTERFACE_CLIENTE_SW #define INTERFACE_CLIENTE_SW #include "biblia/io/rede/ComunicadorRede.h" using namespace biblia::io::rede; namespace biblia{ namespace io{ namespace rede{ class InterfaceCliente{ private: ComunicadorRede* pRedeCliente; protected: ComunicadorRede* InterfaceCliente::getRede(); public: InterfaceCliente::InterfaceCliente(ComunicadorRede* redeCliente); virtual InterfaceCliente::~InterfaceCliente(); }; } } } #endif
[ "micaroni@gmail.com" ]
micaroni@gmail.com
487cf6988aefbc17ce5858a3ea74491c547edd77
67f988dedfd8ae049d982d1a8213bb83233d90de
/external/chromium/ui/base/ui_base_switches.h
eca1bdd8b9089ff095a4cb80e16e827ad853c970
[ "BSD-3-Clause" ]
permissive
opensourceyouthprogramming/h5vcc
94a668a9384cc3096a365396b5e4d1d3e02aacc4
d55d074539ba4555e69e9b9a41e5deb9b9d26c5b
refs/heads/master
2020-04-20T04:57:47.419922
2019-02-12T00:56:14
2019-02-12T00:56:14
168,643,719
1
1
null
2019-02-12T00:49:49
2019-02-01T04:47:32
C++
UTF-8
C++
false
false
2,079
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Defines all the command-line switches used by ui/base. #ifndef UI_BASE_UI_BASE_SWITCHES_H_ #define UI_BASE_UI_BASE_SWITCHES_H_ #include "base/compiler_specific.h" #include "ui/base/ui_export.h" namespace switches { UI_EXPORT extern const char kDisableTouchAdjustment[]; UI_EXPORT extern const char kEnableBezelTouch[]; UI_EXPORT extern const char kEnableNewDialogStyle[]; UI_EXPORT extern const char kEnableNewMenuStyle[]; UI_EXPORT extern const char kEnableTouchDragDrop[]; UI_EXPORT extern const char kEnableViewsTextfield[]; UI_EXPORT extern const char kForceDeviceScaleFactor[]; UI_EXPORT extern const char kHighlightMissingScaledResources[]; UI_EXPORT extern const char kLang[]; UI_EXPORT extern const char kLocalePak[]; UI_EXPORT extern const char kOldCheckboxStyle[]; UI_EXPORT extern const char kNoMessageBox[]; UI_EXPORT extern const char kTouchEvents[]; UI_EXPORT extern const char kTouchEventsAuto[]; UI_EXPORT extern const char kTouchEventsDisabled[]; UI_EXPORT extern const char kTouchEventsEnabled[]; UI_EXPORT extern const char kTouchOptimizedUI[]; UI_EXPORT extern const char kTouchOptimizedUIAuto[]; UI_EXPORT extern const char kTouchOptimizedUIDisabled[]; UI_EXPORT extern const char kTouchOptimizedUIEnabled[]; #if defined(USE_XI2_MT) UI_EXPORT extern const char kTouchCalibration[]; #endif #if defined(OS_MACOSX) // TODO(kbr): remove this and the associated old code path: // http://crbug.com/105344 // This isn't really the right place for this switch, but is the most // convenient place where it can be shared between // src/webkit/plugins/npapi/ and src/content/plugin/ . UI_EXPORT extern const char kDisableCompositedCoreAnimationPlugins[]; UI_EXPORT extern const char kDisableCoreAnimationPlugins[]; #endif #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) UI_EXPORT extern const char kTouchDevices[]; #endif } // namespace switches #endif // UI_BASE_UI_BASE_SWITCHES_H_
[ "rjogrady@google.com" ]
rjogrady@google.com
2f0a91a454a981c2b0df091034f21b7515ee7e00
c8b037a2161ea136b95dac0f5039a92fa6d686e3
/lab_evidencia 4/evidencia 4.cpp
115e5e7ea5e1cfb48b0ec9866f2c3fca02cf067a
[]
no_license
kaiser4900/Lenguaje-de-programaci-n-1
1967249ec68b6105c01526e4479b0d7a1dcdcc63
50dca7d5715618d6fbf83182b0dca89d448b2e22
refs/heads/master
2020-04-03T00:06:21.993615
2018-12-08T08:59:46
2018-12-08T08:59:46
154,888,727
0
0
null
null
null
null
UTF-8
C++
false
false
1,064
cpp
#include<iostream> using namespace std; int main(){ char* findX(const char* s, const char* x) { int res=0; if (x==0) return s; for (int i = 0; s[i]; ++i) { if (s[i] == x[0]) { for (int j = 1; x[j]; ++j) { if (x[j+1]==0) { res=&s[i]; return res; } if (s[i+j+1]==0) { return res; } } } } return res; } void to_lower(char* s) { int A='A'; int Z='Z'; int a='a'; int dif= A-a; for (int i = 0; s[i]; ++i) { if (s[i]>=A && s[i]<=Z) { s[i] =s[i]+dif; } } } bool find(string p) { bool res=false; Link* r; r=this; while(r) { if(r==p) { res=true; } } return res; } return 0; }
[ "galemanz@ulasalle.edu.pe" ]
galemanz@ulasalle.edu.pe
83cca2927f5fbfe3e85e75f031ce880127c3d6de
11cd65ab418283f31ded8a81304fa9abb70c9c74
/SDK/LibOpenCV/src/modules/dnn/src/int8layers/layers_common.simd_declarations.hpp
8f26176a58f670cf9dcdb168604573926dbd5fdc
[ "Apache-2.0" ]
permissive
sim9108/SDKS
16affd227b21ff40454e7fffd0fcde3ac7ad6844
358ff46d925de151c422ee008e1ddaea6be3d067
refs/heads/main
2023-03-15T22:47:10.973000
2022-05-16T12:50:00
2022-05-16T12:50:00
27,232,062
2
0
null
null
null
null
UTF-8
C++
false
false
377
hpp
#define CV_CPU_SIMD_FILENAME "dnn/src/int8layers/layers_common.simd.hpp" #define CV_CPU_DISPATCH_MODE AVX2 #include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp" #define CV_CPU_DISPATCH_MODE AVX512_SKX #include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp" #define CV_CPU_DISPATCH_MODES_ALL AVX512_SKX, AVX2, BASELINE #undef CV_CPU_SIMD_FILENAME
[ "sim910@naver.com" ]
sim910@naver.com
96f8cd54094802d0c6dd11e8826e44eda59a0c76
f104ab0af3ea46df358751c3aa926cce086d5865
/native/CefBeforeDownloadCallback_N.cpp
00da7295a7450731753b096ebfbcf0fe2ed8c10d
[ "BSD-3-Clause" ]
permissive
YattaSolutions/java-cef
f375eecab2951601ace23dcd75d7cf67b9f6f88e
3dfcb98eea1ddf345e1f5bc47afa90032c5c0325
refs/heads/master
2023-08-31T08:46:00.490232
2021-09-16T12:54:33
2021-09-16T12:54:33
292,809,950
0
0
NOASSERTION
2020-09-04T09:41:50
2020-09-04T09:41:49
null
UTF-8
C++
false
false
1,151
cpp
// Copyright (c) 2014 The Chromium Embedded Framework 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 "CefBeforeDownloadCallback_N.h" #include "include/cef_download_handler.h" #include "jni_scoped_helpers.h" #include "jni_util.h" namespace { CefRefPtr<CefBeforeDownloadCallback> GetSelf(jlong self) { return reinterpret_cast<CefBeforeDownloadCallback*>(self); } void ClearSelf(JNIEnv* env, jobject obj) { // Clear the reference added in DownloadHandler::OnBeforeDownload. SetCefForJNIObject<CefBeforeDownloadCallback>(env, obj, NULL, "CefBeforeDownloadCallback"); } } // namespace JNIEXPORT void JNICALL Java_org_cef_callback_CefBeforeDownloadCallback_1N_N_1Continue( JNIEnv* env, jobject obj, jlong self, jstring jdownloadPath, jboolean jshowDialog) { CefRefPtr<CefBeforeDownloadCallback> callback = GetSelf(self); if (!callback) return; callback->Continue(GetJNIString(env, jdownloadPath), jshowDialog != JNI_FALSE); ClearSelf(env, obj); }
[ "magreenblatt@gmail.com" ]
magreenblatt@gmail.com
c9f5a51c7357937fa709850fa2c05693c772f341
938cb17fa0a1764ee3871f762a723e78335421a5
/Experimental/TFT/ST7735.cpp
1825860bf74058eaaf30af9750d0f0aaab2526e7
[]
no_license
cacycleworks/chipKIT_ST7735
ff3bd7c69ad04ed1cecb586af453907bf13008a2
f875a20919230fa946b75074b5b12e02346f9cbd
refs/heads/master
2021-01-25T08:48:54.071405
2013-10-17T00:04:15
2013-10-17T00:04:15
12,660,477
2
2
null
null
null
null
UTF-8
C++
false
false
14,326
cpp
// ST7735 code to get Adafruit 1.8" TFT shield working with chipKIT uC32 // Note was not able to make it work on my Uno32 with SPI, DSPI with or without delays in ST7735.cpp // This port to chipKIT written by Chris Kelley of ca-cycleworks.com (c) ? Sure, ok same MIT thing, whatever // This code derived from Adafruit_ST7735 library. See bottom of .h file for their full MIT license stuff. //////////////////////////////////////////////////////////////////////////////// #include <TFT.h> #define ST7735_NOP 0x00 #define ST7735_SWRESET 0x01 #define ST7735_RDDID 0x04 #define ST7735_RDDST 0x09 #define ST7735_SLPIN 0x10 #define ST7735_SLPOUT 0x11 #define ST7735_PTLON 0x12 #define ST7735_NORON 0x13 #define ST7735_INVOFF 0x20 #define ST7735_INVON 0x21 #define ST7735_DISPOFF 0x28 #define ST7735_DISPON 0x29 #define ST7735_CASET 0x2A #define ST7735_RASET 0x2B #define ST7735_RAMWR 0x2C #define ST7735_RAMRD 0x2E #define ST7735_PTLAR 0x30 #define ST7735_COLMOD 0x3A #define ST7735_MADCTL 0x36 #define ST7735_FRMCTR1 0xB1 #define ST7735_FRMCTR2 0xB2 #define ST7735_FRMCTR3 0xB3 #define ST7735_INVCTR 0xB4 #define ST7735_DISSET5 0xB6 #define ST7735_PWCTR1 0xC0 #define ST7735_PWCTR2 0xC1 #define ST7735_PWCTR3 0xC2 #define ST7735_PWCTR4 0xC3 #define ST7735_PWCTR5 0xC4 #define ST7735_VMCTR1 0xC5 #define ST7735_RDID1 0xDA #define ST7735_RDID2 0xDB #define ST7735_RDID3 0xDC #define ST7735_RDID4 0xDD #define ST7735_PWCTR6 0xFC #define ST7735_GMCTRP1 0xE0 #define ST7735_GMCTRN1 0xE1 // Rather than a bazillion writecommand() and writedata() calls, screen // initialization commands and arguments are organized in these tables. // The table may look bulky, but that's mostly the formatting -- storage-wise // this is hundreds of bytes more compact than the equivalent code. // Companion function follows. #define DELAY 0x80 static uint8_t Bcmd[] = { // Initialization commands for 7735B screens 18, // 18 commands in list: ST7735_SWRESET, DELAY, // 1: Software reset, no args, w/delay 50, // 50 ms delay ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, no args, w/delay 255, // 255 = 500 ms delay ST7735_COLMOD , 1+DELAY, // 3: Set color mode, 1 arg + delay: 0x05, // 16-bit color 10, // 10 ms delay ST7735_FRMCTR1, 3+DELAY, // 4: Frame rate control, 3 args + delay: 0x00, // fastest refresh 0x06, // 6 lines front porch 0x03, // 3 lines back porch 10, // 10 ms delay ST7735_MADCTL , 1 , // 5: Memory access ctrl (directions), 1 arg: 0x08, // Row addr/col addr, bottom to top refresh ST7735_DISSET5, 2 , // 6: Display settings #5, 2 args, no delay: 0x15, // 1 clk cycle nonoverlap, 2 cycle gate // rise, 3 cycle osc equalize 0x02, // Fix on VTL ST7735_INVCTR , 1 , // 7: Display inversion control, 1 arg: 0x0, // Line inversion ST7735_PWCTR1 , 2+DELAY, // 8: Power control, 2 args + delay: 0x02, // GVDD = 4.7V 0x70, // 1.0uA 10, // 10 ms delay ST7735_PWCTR2 , 1 , // 9: Power control, 1 arg, no delay: 0x05, // VGH = 14.7V, VGL = -7.35V ST7735_PWCTR3 , 2 , // 10: Power control, 2 args, no delay: 0x01, // Opamp current small 0x02, // Boost frequency ST7735_VMCTR1 , 2+DELAY, // 11: Power control, 2 args + delay: 0x3C, // VCOMH = 4V 0x38, // VCOML = -1.1V 10, // 10 ms delay ST7735_PWCTR6 , 2 , // 12: Power control, 2 args, no delay: 0x11, 0x15, ST7735_GMCTRP1,16 , // 13: Magical unicorn dust, 16 args, no delay: 0x09, 0x16, 0x09, 0x20, // (seriously though, not sure what 0x21, 0x1B, 0x13, 0x19, // these config values represent) 0x17, 0x15, 0x1E, 0x2B, 0x04, 0x05, 0x02, 0x0E, ST7735_GMCTRN1,16+DELAY, // 14: Sparkles and rainbows, 16 args + delay: 0x0B, 0x14, 0x08, 0x1E, // (ditto) 0x22, 0x1D, 0x18, 0x1E, 0x1B, 0x1A, 0x24, 0x2B, 0x06, 0x06, 0x02, 0x0F, 10, // 10 ms delay ST7735_CASET , 4 , // 15: Column addr set, 4 args, no delay: 0x00, 0x02, // XSTART = 2 0x00, 0x81, // XEND = 129 ST7735_RASET , 4 , // 16: Row addr set, 4 args, no delay: 0x00, 0x02, // XSTART = 1 0x00, 0x81, // XEND = 160 ST7735_NORON , DELAY, // 17: Normal display on, no args, w/delay 10, // 10 ms delay ST7735_DISPON , DELAY, // 18: Main screen turn on, no args, w/delay 255 }, // 255 = 500 ms delay Rcmd1[] = { // Init for 7735R, part 1 (red or green tab) 15, // 15 commands in list: ST7735_SWRESET, DELAY, // 1: Software reset, 0 args, w/delay 150, // 150 ms delay ST7735_SLPOUT , DELAY, // 2: Out of sleep mode, 0 args, w/delay 255, // 500 ms delay ST7735_FRMCTR1, 3 , // 3: Frame rate ctrl - normal mode, 3 args: 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) ST7735_FRMCTR2, 3 , // 4: Frame rate control - idle mode, 3 args: 0x01, 0x2C, 0x2D, // Rate = fosc/(1x2+40) * (LINE+2C+2D) ST7735_FRMCTR3, 6 , // 5: Frame rate ctrl - partial mode, 6 args: 0x01, 0x2C, 0x2D, // Dot inversion mode 0x01, 0x2C, 0x2D, // Line inversion mode ST7735_INVCTR , 1 , // 6: Display inversion ctrl, 1 arg, no delay: 0x07, // No inversion ST7735_PWCTR1 , 3 , // 7: Power control, 3 args, no delay: 0xA2, 0x02, // -4.6V 0x84, // AUTO mode ST7735_PWCTR2 , 1 , // 8: Power control, 1 arg, no delay: 0xC5, // VGH25 = 2.4C VGSEL = -10 VGH = 3 * AVDD ST7735_PWCTR3 , 2 , // 9: Power control, 2 args, no delay: 0x0A, // Opamp current small 0x00, // Boost frequency ST7735_PWCTR4 , 2 , // 10: Power control, 2 args, no delay: 0x8A, // BCLK/2, Opamp current small & Medium low 0x2A, ST7735_PWCTR5 , 2 , // 11: Power control, 2 args, no delay: 0x8A, 0xEE, ST7735_VMCTR1 , 1 , // 12: Power control, 1 arg, no delay: 0x0E, ST7735_INVOFF , 0 , // 13: Don't invert display, no args, no delay ST7735_MADCTL , 1 , // 14: Memory access control (directions), 1 arg: 0xC8, // row addr/col addr, bottom to top refresh ST7735_COLMOD , 1 , // 15: set color mode, 1 arg, no delay: 0x05 }, // 16-bit color Rcmd2green[] = { // Init for 7735R, part 2 (green tab only) 2, // 2 commands in list: ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: 0x00, 0x02, // XSTART = 0 0x00, 0x7F+0x02, // XEND = 127 ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: 0x00, 0x01, // XSTART = 0 0x00, 0x9F+0x01 }, // XEND = 159 Rcmd2red[] = { // Init for 7735R, part 2 (red tab only) 2, // 2 commands in list: ST7735_CASET , 4 , // 1: Column addr set, 4 args, no delay: 0x00, 0x00, // XSTART = 0 0x00, 0x7F, // XEND = 127 ST7735_RASET , 4 , // 2: Row addr set, 4 args, no delay: 0x00, 0x00, // XSTART = 0 0x00, 0x9F }, // XEND = 159 Rcmd3[] = { // Init for 7735R, part 3 (red or green tab) 4, // 4 commands in list: ST7735_GMCTRP1, 16 , // 1: Magical unicorn dust, 16 args, no delay: 0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2B, 0x39, 0x00, 0x01, 0x03, 0x10, ST7735_GMCTRN1, 16 , // 2: Sparkles and rainbows, 16 args, no delay: 0x03, 0x1d, 0x07, 0x06, 0x2E, 0x2C, 0x29, 0x2D, 0x2E, 0x2E, 0x37, 0x3F, 0x00, 0x00, 0x02, 0x10, ST7735_NORON , DELAY, // 3: Normal display on, no args, w/delay 10, // 10 ms delay ST7735_DISPON , DELAY, // 4: Main screen turn on, no args w/delay 100 }; // 100 ms delay inline uint16_t swapcolor(uint16_t x) { return (x << 11) | (x & 0x07E0) | (x >> 11); } void ST7735::initializeDevice() { _comm->initializeDevice(); colstart = rowstart = 0; _width = ST7735::Width; _height = ST7735::Height; switch (_variant) { case GreenTab: streamCommands(Rcmd1); streamCommands(Rcmd2green); colstart = 2; rowstart = 1; streamCommands(Rcmd3); break; case RedTab: streamCommands(Rcmd1); streamCommands(Rcmd2red); streamCommands(Rcmd3); break; case BlackTab: streamCommands(Rcmd1); streamCommands(Rcmd2red); streamCommands(Rcmd3); break; case TypeB: streamCommands(Bcmd); break; } } void ST7735::streamCommands(uint8_t *cmdlist) { uint8_t numCommands, numArgs; uint16_t ms; numCommands = *cmdlist; cmdlist++; while(numCommands--) { _comm->writeCommand8(*cmdlist); cmdlist++; numArgs = *cmdlist; cmdlist++; ms = numArgs & DELAY; numArgs &= ~DELAY; while(numArgs--) { _comm->writeData8(*cmdlist); cmdlist++; } if(ms) { ms = *cmdlist; #ifndef __PIC32MX__ delay(ms); #endif cmdlist++; } } } void ST7735::setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1) { _comm->writeCommand8(ST7735_CASET); // Column addr set _comm->writeData8(0x00); _comm->writeData8(x0+colstart); // XSTART _comm->writeData8(0x00); _comm->writeData8(x1+colstart); // XEND _comm->writeCommand8(ST7735_RASET); // Row addr set _comm->writeData8(0x00); _comm->writeData8(y0+rowstart); // YSTART _comm->writeData8(0x00); _comm->writeData8(y1+rowstart); // YEND _comm->writeCommand8(ST7735_RAMWR); // write to RAM } void ST7735::setPixel(int16_t x, int16_t y, uint16_t color) { if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; setAddrWindow(x,y,x+1,y+1); if (_variant == BlackTab) color = swapcolor(color); _comm->writeData16(color); } void ST7735::fillScreen(uint16_t color) { fillRectangle(0, 0, _width, _height, color); } void ST7735::fillRectangle(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { if((x >= _width) || (y >= _height)) return; if((x + w - 1) >= _width) w = _width - x; if((y + h - 1) >= _height) h = _height - y; if (_variant == BlackTab) color = swapcolor(color); setAddrWindow(x, y, x+w-1, y+h-1); uint8_t hi = color >> 8, lo = color; _comm->streamStart(); for(y=h; y>0; y--) { for(x=w; x>0; x--) { _comm->streamData16(color); } } _comm->streamEnd(); } void ST7735::drawHorizontalLine(int16_t x, int16_t y, int16_t w, uint16_t color) { // Rudimentary clipping if((x >= _width) || (y >= _height)) return; if((x+w-1) >= _width) w = _width-x; setAddrWindow(x, y, x+w-1, y); if (_variant == BlackTab) color = swapcolor(color); uint8_t hi = color >> 8, lo = color; _comm->streamStart(); while (w--) { _comm->streamData16(color); } _comm->streamEnd(); } void ST7735::drawVerticalLine(int16_t x, int16_t y, int16_t h, uint16_t color) { if((x >= _width) || (y >= _height)) return; if((y+h-1) >= _height) h = _height-y; setAddrWindow(x, y, x, y+h-1); if (_variant == BlackTab) color = swapcolor(color); uint8_t hi = color >> 8, lo = color; _comm->streamStart(); while (h--) { _comm->streamData16(color); } _comm->streamEnd(); } #define MADCTL_MY 0x80 #define MADCTL_MX 0x40 #define MADCTL_MV 0x20 #define MADCTL_ML 0x10 #define MADCTL_RGB 0x08 #define MADCTL_MH 0x04 void ST7735::setRotation(uint8_t m) { _comm->writeCommand8(ST7735_MADCTL); rotation = m % 4; // can't be higher than 3 switch (rotation) { case 0: _comm->writeData8(MADCTL_MX | MADCTL_MY | MADCTL_RGB); _width = ST7735::Width; _height = ST7735::Height; break; case 1: _comm->writeData8(MADCTL_MY | MADCTL_MV | MADCTL_RGB); _width = ST7735::Height; _height = ST7735::Width; break; case 2: _comm->writeData8(MADCTL_RGB); _width = ST7735::Width; _height = ST7735::Height; break; case 3: _comm->writeData8(MADCTL_MX | MADCTL_MV | MADCTL_RGB); _width = ST7735::Height; _height = ST7735::Width; break; } } void ST7735::invertDisplay(boolean i) { _comm->writeCommand8(i ? ST7735_INVON : ST7735_INVOFF); } void ST7735::update(Framebuffer *fb) { setAddrWindow(0, 0, _width, _height); uint32_t pixpair = 0; uint16_t color = 0; _comm->streamStart(); for (int y = 0; y < _height; y++) { uint8_t l = y & 1; for (int x = 0; x < _width; x+=2) { color = fb->colorAt(x, y); if (_variant == ST7735::BlackTab) color = swapcolor(color); pixpair = color << 16; color = fb->colorAt(x+1, y); if (_variant == ST7735::BlackTab) color = swapcolor(color); pixpair |= color; _linebuffer[l][x >> 1] = pixpair; } _comm->blockData(_linebuffer[l], _width>>1); } _comm->streamEnd(); }
[ "matt@majenko.co.uk" ]
matt@majenko.co.uk
cc5e3f6ab3f6df4625ca280cbc8b78a3148222e6
22e52b87c80f4c43ada5d4c721193dd0acf80b1e
/src/AutoRefl/TypeInfoGenerator.h
4017a422b60caf6a13c674f0f6d417d0fe4e362c
[]
no_license
wu-yy/AutoRefl
1eed7f557d51aa666772760d5c241a6d17d62c67
8866f4009529d58461a437c37b2eeb7a0c217e9d
refs/heads/main
2023-02-07T06:04:00.115756
2020-12-27T04:36:55
2020-12-27T04:36:55
324,686,869
0
0
null
null
null
null
UTF-8
C++
false
false
1,252
h
// // Created by wuyongyu02 on 2020/12/27. // #ifndef TEST_DEMO_SRC_AUTOREFL_TYPEINFOGENERATOR_H_ #define TEST_DEMO_SRC_AUTOREFL_TYPEINFOGENERATOR_H_ #pragma once #include "Meta.h" #include <config.h> class TypeInfoGenerator { public: enum class ConstMode { Constepxr, Const, NonConst }; struct Config { bool nonNamespaceNameWithoutQuotation{ false }; bool namespaceNameWithQuotation{ false }; bool isAttrValueToFunction{ false }; std::string_view nameof_namespace = UMeta::nameof_namespace; bool isInitializerAsAttr{ true }; std::string_view nameof_initializer = UMeta::nameof_initializer; std::string_view nameof_constructor = UMeta::nameof_constructor; std::string_view nameof_destructor = UMeta::nameof_destructor; bool generateDefaultFunctions{ true }; std::string_view nameof_default_functions = UMeta::nameof_default_functions; ConstMode attrListConstMode{ ConstMode::Constepxr }; ConstMode fieldListConstMode{ ConstMode::Constepxr }; }; TypeInfoGenerator(Config config = Config{}) : config{ std::move(config) } {} std::string Generate(const std::vector<TypeMeta>& typeMetas); private: Config config; }; #endif //TEST_DEMO_SRC_AUTOREFL_TYPEINFOGENERATOR_H_
[ "wuyongyu02@meituan.com" ]
wuyongyu02@meituan.com
57b1836ed3c92dfa5ddeb9890f61bec18a7a2266
dae9c7efe93bee189e4c89b9599b9b80a7395cd1
/snake/src/SnakeFood.cpp
7a62f758f1ed8d4b9615f4ca87b8c3c4b9febd43
[]
no_license
libesz/FadeCube_cpp
862c830b40af266a732a615cd074fb4343989564
24a724e0b20eaf718350ecc321c481d2bd31cacc
refs/heads/master
2020-04-19T15:26:40.160679
2014-07-31T19:17:27
2014-07-31T19:17:27
19,249,839
0
0
null
null
null
null
UTF-8
C++
false
false
1,059
cpp
/* * SnakeFood.cpp * * Created on: Apr 23, 2014 * Author: libesz */ #include <SnakeFood.h> #include <ctime> #include <iostream> namespace FadeCube { void SnakeFood::createFood() { std::uniform_int_distribution<int> genX(0, cubeProp.getSpaceX()-1); std::uniform_int_distribution<int> genY(0, cubeProp.getSpaceY()-1); std::uniform_int_distribution<int> genZ(0, cubeProp.getSpaceZ()-1); foodPosition.setX(genX(rng)); foodPosition.setY(genY(rng)); foodPosition.setZ(genZ(rng)); } SnakeFood::SnakeFood(CubeProp newCubeProp): cubeProp(newCubeProp), foodPosition(0,0,0,255), invisible(false) { rng.seed(time(0)); createFood(); } SnakeFood::~SnakeFood() { } const std::vector<Point> SnakeFood::render() const { std::vector<Point> result; Point pos = foodPosition; if(invisible) pos.setBr(0); result.push_back(pos); return result; } void SnakeFood::toogleInvisible() { invisible = !invisible; } Point SnakeFood::get() { return foodPosition; } void SnakeFood::tick() { createFood(); } } /* namespace FadeCube */
[ "huszty.gergo@digitaltrip.hu" ]
huszty.gergo@digitaltrip.hu
10c0c2b9918771a482e36ff1f584072647f19a9a
8fd0ed1daddef7f0e5e7b4e3c35b85acba8115a7
/Project 3/Barbarian.hpp
95c012119347dee1d01373ca75a949899665b047
[]
no_license
DylanTrull/CS162
ff3939342991c8b7460e25ff823ec6b4b47d3985
2b361fc134bcbee19c6cf8f1a035354e90a56ead
refs/heads/master
2022-11-08T17:54:38.252011
2020-06-29T21:02:34
2020-06-29T21:02:34
275,924,940
0
0
null
null
null
null
UTF-8
C++
false
false
602
hpp
// // Barbarian.hpp // Project 3 // // Dylan Trull 11/10/19. // // Barbarian header file that extends the character class #ifndef Barbarian_hpp #define Barbarian_hpp #include "Character.hpp" class Barbarian : public Character{ private: int health; int armor; int type; std::string name; public: Barbarian(); virtual int attack(); virtual int defend(); virtual bool isDead(); virtual void takeDamage(int); virtual int getArmor(); virtual int getHealth(); virtual int getType(); virtual std::string getName(); }; #endif /* Barbarian_hpp */
[ "noreply@github.com" ]
DylanTrull.noreply@github.com
dc745d69fb1eac33250dc817ae01d568067cf132
c54b16b05178f5f8155fcb5e7a86cb91925c9801
/Alchemy/Include/DXImageReal.h
3e2dbc48d5e585059a898ad2c70ac3e850ea2050
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SiegeLord/TranscendenceDev
72e9b668da82e89d36dad0d1655b7752dfabad1c
e936d0c0ab7d9202a05f6261c6cd14497947a3ac
refs/heads/master
2021-07-19T09:20:22.178976
2019-01-18T04:24:57
2019-01-18T04:24:57
166,512,940
0
0
NOASSERTION
2019-01-19T06:10:02
2019-01-19T06:10:02
null
UTF-8
C++
false
false
3,633
h
// DXImageReal.h // // Implements floating point images // Copyright (c) 2015 by Kronosaur Productions, LLC. All Rights Reserved. #pragma once class CGRealRGB; class CGRealHSB { public: CGRealHSB (void) { } CGRealHSB (Metric rH, Metric rS, Metric rB, Metric rA = 1.0) : m_rH(rH), m_rS(rS), m_rB(rB), m_rA(rA) { } inline Metric GetAlpha (void) const { return m_rA; } inline Metric GetBrightness (void) const { return m_rB; } inline Metric GetHue (void) const { return m_rH; } inline Metric GetSaturation (void) const { return m_rS; } inline void SetBrightness (Metric rBrightness) { m_rB = Max(0.0, Min(rBrightness, 1.0)); } inline void SetHue (Metric rHue) { m_rH = mathAngleModDegrees(rHue); } inline void SetSaturation (Metric rSaturation) { m_rS = Max(0.0, Min(rSaturation, 1.0)); } static CGRealHSB FromRGB (const CGRealRGB &rgbColor); static CGRealHSB FromRGB (CG32bitPixel rgbColor); private: Metric m_rH; // Hue: 0-360 Metric m_rS; // Saturation: 0-1 Metric m_rB; // Brightness: 0-1 Metric m_rA; // Alpha: 0-1 }; class CGRealRGB { public: CGRealRGB (void) { } CGRealRGB (Metric rR, Metric rG, Metric rB, Metric rA = 1.0) : m_rR(rR), m_rG(rG), m_rB(rB), m_rA(rA) { } CGRealRGB (CG32bitPixel rgbColor); inline Metric GetAlpha (void) const { return m_rA; } inline Metric GetBlue (void) const { return m_rB; } inline Metric GetGreen (void) const { return m_rG; } inline Metric GetRed (void) const { return m_rR; } static CGRealRGB FromHSB (const CGRealHSB &hsbColor); inline static Metric From8bit (BYTE byValue) { return (Metric)byValue / 255.0; } inline static BYTE To8bit (Metric Value) { return (BYTE)(DWORD)(255.0 * Value); } private: Metric m_rR; // Red: 0-1 Metric m_rG; // Green: 0-1 Metric m_rB; // Blue: 0-1 Metric m_rA; // Alpha: 0-1 }; class CGRealChannel : public TImagePlane<CGRealChannel> { public: CGRealChannel (void); CGRealChannel (const CGRealChannel &Src); ~CGRealChannel (void); CGRealChannel &operator= (const CGRealChannel &Src); // Basic Interface void CleanUp (void); bool Create (int cxWidth, int cyHeight, Metric InitialValue = 0); bool Create (const CG8bitImage &Src, int xSrc = 0, int ySrc = 0, int cxSrc = -1, int cySrc = -1); bool CreateChannel (ChannelTypes iChannel, const CG32bitImage &Src, int xSrc = 0, int ySrc = 0, int cxSrc = -1, int cySrc = -1); inline Metric GetPixel (int x, int y) const { return *GetPixelPos(x, y); } inline Metric *GetPixelPos (int x, int y) const { return m_pChannel + (y * m_cxWidth) + x; } inline bool IsEmpty (void) const { return (m_pChannel == NULL); } inline bool IsMarked (void) const { return m_bMarked; } inline Metric *NextRow (Metric *pPos) const { return pPos + m_cxWidth; } inline void SetMarked (bool bMarked = true) { m_bMarked = bMarked; } // Basic Drawing Interface void Fill (int x, int y, int cxWidth, int cyHeight, Metric Value); inline void FillColumn (int x, int y, int cyHeight, Metric Value) { Fill(x, y, 1, cyHeight, Value); } inline void FillLine (int x, int y, int cxWidth, Metric Value) { Fill(x, y, cxWidth, 1, Value); } inline void SetPixel (int x, int y, Metric Value) { if (x >= m_rcClip.left && y >= m_rcClip.top && x < m_rcClip.right && y < m_rcClip.bottom) *GetPixelPos(x, y) = Value; } private: static int CalcBufferSize (int cxWidth, int cyHeight) { return (cxWidth * cyHeight); } void Copy (const CGRealChannel &Src); Metric *m_pChannel; bool m_bMarked; // Mark/sweep flag (for use by caller) };
[ "public@neurohack.com" ]
public@neurohack.com
044b4ec198d88da048e0f9ed06a75d74b71fe42e
17e0b7775f3a1b429225a405a327d137710bec59
/TryoneTry/Intermediate/Build/Android/TryoneTry/Development/AIModule/Module.AIModule.gen.6_of_7.cpp
c1c409123f3d06351c87e43e7abae6878ff38a2b
[]
no_license
JTY1997/Learning-UE4
923d2cbfe95dec25a9dfe6ca2f36bc67e6203bd3
ed5fcedf3aa35887e5bde1fe67fd4be0b1a7ce29
refs/heads/main
2023-01-31T22:32:04.289755
2020-12-17T15:32:55
2020-12-17T15:32:55
303,879,097
0
0
null
null
null
null
UTF-8
C++
false
false
3,097
cpp
// This file is automatically generated at compile-time to include some subset of the user-created cpp files. #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryInstanceBlueprintWrapper.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryItemType.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryItemType_Actor.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryItemType_ActorBase.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryItemType_Direction.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryItemType_Point.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryItemType_VectorBase.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryManager.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryNode.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryOption.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Distance.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Dot.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_GameplayTags.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Overlap.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Pathfinding.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_PathfindingBatch.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Project.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Random.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Trace.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTest_Volume.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EnvQueryTypes.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EQSQueryResultSourceInterface.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EQSRenderingComponent.gen.cpp" #include "E:/Unreal Projects/TryoneTry/Intermediate/Build/Android/TryoneTry/Inc/AIModule/EQSTestingPawn.gen.cpp"
[ "52436054+JTY1997@users.noreply.github.com" ]
52436054+JTY1997@users.noreply.github.com
722664cb62d33ec671eb45958830ab3abaf93841
d79980c2f3091488ab7d71266ac29097309fc7ea
/sql_test/src/sql_test.cpp
7b2758ab3e31a1c9a3913e611eeed69a12a7cedb
[]
no_license
wyrobjar/SqLiteRepository
0ada320e6feece69d27271aba316c6dcadc39f23
edc1571af2609f5bd4cf8f476b29e4818cbd84a8
refs/heads/master
2016-08-05T06:32:54.194860
2013-11-07T11:54:28
2013-11-07T11:54:28
null
0
0
null
null
null
null
IBM852
C++
false
false
4,510
cpp
/* * sql_test.cpp * * Created on: 10 pač 2013 * Author: wyrobjar */ #include <iostream> #include <sqlite3.h> #include <iomanip> #include <ctime> #include <time.h> #include <string> #include <sstream> #include <vector> using namespace std; static char * timer(char *buffer) { time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer,17,"%Y-%m-%d %H:%M",timeinfo); return buffer; } static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; vector <vector <string> > * vv_text = static_cast <vector <vector <string> > *>(NotUsed); //*(int*)NotUsed = 8; vector <string> txt; for(i=0; i<argc; i++) { txt.push_back(azColName[i]); txt.push_back(argv[i]); cout << azColName[i] << " " << argv[i] << endl; } vv_text->push_back(txt); txt.empty(); return 0; } class Database { sqlite3 *database; public: int test; vector <vector <string> > vv_text; Database(const char * db_name); ~Database(); bool open(const char * db_name); bool query(const char * sql_statement); bool create_db(); bool insert_rec(string name, int hala, string address, int value); bool insert(); bool show(); void show_vector(); void close(); }; Database::Database(const char *db_name) { database = NULL; test = 99; open(db_name); } Database::~Database() { } bool Database::open(const char * db_name) { if(SQLITE_OK == sqlite3_open(db_name, &database)) { return true; } else { return false; } } bool Database::query(const char * sql_statement) { char *zErrMsg = 0; if(SQLITE_OK == sqlite3_exec(database, sql_statement, callback, &vv_text, &zErrMsg)) { return true; } else { cerr << "SQL statement error: "<< zErrMsg << endl; sqlite3_free(zErrMsg); return false; } } bool Database::create_db() { char *sql = "CREATE TABLE COMPANY(" \ "ID INTEGER PRIMARY KEY AUTOINCREMENT," \ "NAME TEXT NOT NULL," \ "HALA INT NOT NULL," \ "ADDRESS CHAR(50)," \ "SALARY REAL," \ "DATE TEXT NOT NULL);"; return query(sql); } bool Database::insert() { char * sql = "INSERT INTO COMPANY (NAME,HALA,ADDRESS,SALARY,DATE) " \ "VALUES ('Paul', 32, 'California', 20000.00, '2013-10-01 12:10' ); " \ "INSERT INTO COMPANY (ID,NAME,HALA,ADDRESS,SALARY,DATE) " \ "VALUES ('Allen', 25, 'Texas', 15000.00, '2013-10-02 12:10' ); " \ "INSERT INTO COMPANY (ID,NAME,HALA,ADDRESS,SALARY,DATE)" \ "VALUES ('Teddy', 23, 'Norway', 20000.00, '2013-10-03 12:10' );" \ "INSERT INTO COMPANY (ID,NAME,HALA,ADDRESS,SALARY,DATE)" \ "VALUES ('Mark', 25, 'Rich-Mond ', 65000.00, '2013-10-04 12:10' );"; return query(sql); } bool Database::insert_rec(string name, int hala, string address, int value) { string temp_sql = "INSERT INTO COMPANY (NAME,HALA,ADDRESS,SALARY,DATE) VALUES ('"; //string str_id = static_cast<ostringstream*>( &(ostringstream() << id) )->str(); //temp_sql += str_id+", '"; temp_sql += name+"', "; string str_hala = static_cast<ostringstream*>( &(ostringstream() << hala) )->str(); temp_sql += str_hala+", '"; temp_sql += address+"', "; string str_salary = static_cast<ostringstream*>( &(ostringstream() << value) )->str(); temp_sql += str_salary+", '"; char *data = new char[17]; string temp = timer(data); temp_sql += temp+"' );"; //cout << temp_sql << endl; delete []data; const char * sql = temp_sql.c_str(); return query(sql); } bool Database::show() { char * sql = "SELECT * from COMPANY"; return query(sql); } void Database::show_vector() { vector< vector <string> >::iterator it; for (it = vv_text.begin(); it < vv_text.end(); ++it) { for (vector<string>::iterator col = it->begin() ; col < it->end(); ++col) { cout << *col << " "; *col += "iterator"; } cout << endl; } } void Database::close() { sqlite3_close(database); } int main() { bool rc; Database Test("Database8.sqlite"); /* rc = Test.create_db(); cout << "Create DB return : " << rc << endl; rc = Test.insert_rec("Ania", 10, "NEW YORK", 15); cout << "Insert DB return : " << rc << endl; */ rc = Test.show(); cout << "Show DB return : " << rc << endl; Test.show_vector(); Test.close(); return 0; }
[ "jarek.wyrobek@gmail.com" ]
jarek.wyrobek@gmail.com
68bbe7846a17e3c6d46270572f61a0c1995f2351
9473d98a9c4bcba737ba8a1eaa3a9a852c73c0c4
/codeforces/educ48/a.cpp
48f89599cf0e8eee5d027ca3c3272e3366fc16ce
[]
no_license
joaopedroxavier/Competitive-Programming
e57528e99ddfbc88be67870974a42c5348fcc90c
fb73e2e23d1f904a35898fcdfa977d72a9ff4e8b
refs/heads/master
2018-10-29T04:22:39.267104
2018-09-14T18:25:49
2018-09-14T18:25:49
82,396,740
0
0
null
null
null
null
UTF-8
C++
false
false
960
cpp
// // 내가 나인 게 싫은 날 // 영영 사라지고 싶은 날 // 문을 하나 만들자 너의 맘 속에다 // 그 문을 열고 들어가면 // 이 곳이 기다릴 거야 // 믿어도 괜찮아 널 위로해줄 magic shop // #include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define st first #define nd second typedef long long ll; typedef long double ld; typedef pair<int,int> ii; const ld EPS = 1e-9; const ld PI = acos(-1); const int N = 1e5+5; const int MOD = 1e9+7; const int INF = 0x3f3f3f3f; ll cur, n, m; int main(){ //freopen("in", "r", stdin); //freopen("out", "w", stdout); scanf("%lld %lld", &n, &m); cur = 0; for(int i=0; i<n; i++) { ll a; scanf("%lld", &a); ll ans = 0; if(cur + a >= m) { ans++; a -= (m-cur); ans += a / m; cur = a % m; } else { cur = cur + a; } printf("%lld ", ans); } printf("\n"); return 0; }
[ "joaopedroaxavier@gmail.com" ]
joaopedroaxavier@gmail.com
cdb09022290c1776d4ac97195d429fcb39a7393a
653243de4744ce47719bf29b509e56e417e58d28
/src/ObstacleGenerator.hpp
c7ce55e33400aee222cbcdf2c003c7e5f6a9e88e
[]
no_license
g-suraj/yumper
342375711b3eba3a743735ae46bf4c166d9e2e7d
40a5cc6ee51e8420a0c53fe56a49507784523ca0
refs/heads/master
2021-07-21T22:07:58.838713
2017-10-28T18:49:51
2017-10-28T18:49:51
76,183,100
0
0
null
null
null
null
UTF-8
C++
false
false
483
hpp
#ifndef OBSTACLEGENERATOR_H #define OBSTACLEGENERATOR_H #include <cstdlib> #include <vector> #include <memory> #include "textures/obstacles/spikeTrap/SpikeTrap.hpp" #include "physics/Collision.hpp" class ObstacleGenerator { public: ObstacleGenerator(SDL_Renderer*& m_renderer, std::shared_ptr<Collision>); void run(int score); void clear(); void reset(); private: std::vector<std::shared_ptr<SpikeTrap>> spikes; int nextobstacle = 0; }; #endif /* OBSTACLEGENERATOR_H */
[ "sg6215@ic.ac.uk" ]
sg6215@ic.ac.uk
928834d05a1f1e0a46bb5cc98608f74cffd8e12f
bd0dc21691908d067791303353b112c0a4e29349
/AlgoGen.h
be2a4a733e72fd8a6ad4fbc54ac02ee23135df91
[]
no_license
Rafaeldsb/AlgoGenetico
df4daa549d693557f4c51e8acaca55c4fbe4a66f
0ae336a41676812ff7a70b08ab20f9d5ceabf11b
refs/heads/master
2021-08-08T05:29:23.639855
2017-11-09T17:24:53
2017-11-09T17:24:53
110,125,937
0
0
null
null
null
null
UTF-8
C++
false
false
3,617
h
//#pragma once using namespace std; class AlgoGen { private: int POP; // Tamanho da população int GENERATIONS; // Tamanho máximo de gerações int GENERATIONS_WITHOUT_BETTER; // Generações máximas sem melhorias double per_elitism; int nGene = 0; vector<string> header; // Header do alfabeto vector<vector<double>> Alph; // Alfabeto vector<vector<double>> Population; // População atual vector<double> Score; // Score da população atual vector<short> Pais_pos; // Posições dos pais; public: void Set_input(string header, vector<double> alpha); static vector<double> Set_array(double inicial, double final, double step); void Initializate(void); void Fitness(double (*Fit)(vector<double>)); double Sum(void); void SelectParents(void); void Print(void); bool IsFather(int id); void SetAlgoGen(int pop, int gener, int gener_wb, double elit); AlgoGen(){} ~AlgoGen(); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Setar Alfabeto // void AlgoGen::Set_input(string header, vector<double> alpha) { //std::cout << header << endl; this->header.push_back(header); this->Alph.push_back(alpha); this->nGene++; } vector<double> AlgoGen::Set_array(double inicial, double final, double step) { vector<double> temp; final += step / 2; for (double init = inicial; init <= final; init += step) { temp.push_back(init); } return temp; } double AlgoGen::Sum(void) { double S = 0; for (int i = 0; i < this->POP; ++i) { S += this->Score[i]; } return S; } void AlgoGen::SelectParents(void){ vector<short> temp; for(int i = 0; i < this->POP; ++i){ temp.push_back(i); } this->Pais_pos.clear(); for(int i = 0; i < this->POP * this->per_elitism; ++i){ double S = 0; for(unsigned int i = 0; i < temp.size(); ++i){ S += this->Score[temp[i]]; } double rad = ((double)rand() / RAND_MAX) * S; int pos = -1; do { pos++; rad -= this->Score[temp[pos]]; } while (rad > 0); this->Pais_pos.push_back(temp[pos]); temp.erase(temp.begin() + pos); } } void AlgoGen::Print(void) { cout << "A\n"; double AC = 0; for (int i = 0; i < this->POP; ++i) { cout << "#" << i << ":\t Cromossomo: "; for (int j = 0; j < this->nGene; ++j) { cout << this->Population[i][j] << " "; } AC += this->Score[i]; cout << "\t\tScore: " << this->Score[i] << " \tAcumulado: " << AC; if (IsFather(i)) cout << "\tPai"; cout << endl; } } bool AlgoGen::IsFather(int id){ for(auto i : this->Pais_pos){ if(i == id) return true; } return false; } void AlgoGen::Initializate(void) { srand(time(NULL)); vector<double> temp; for (int i = 0; i < this->POP; ++i) { temp.clear(); //cout << this->nGene; for (int j = 0; j < this->nGene; ++j) { //int a = rand() % this->Alph[j].size(); temp.push_back( this->Alph[j][ rand() % this->Alph[j].size() ] ); } this->Population.push_back(temp); } } void AlgoGen::Fitness(double (*Fit)(vector<double>)){ this->Score.clear(); for(int i = 0; i < this->POP; ++i){ this->Score.push_back((*Fit)(this->Population[i])); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construtores // void AlgoGen::SetAlgoGen(int pop, int gener, int gener_wb, double elit){ this->POP = pop; this->GENERATIONS = gener; this->GENERATIONS_WITHOUT_BETTER = gener_wb; this->per_elitism = elit; } AlgoGen::~AlgoGen(){ }
[ "rafael.dsbernardo@gmail.com" ]
rafael.dsbernardo@gmail.com
5417337536c68400aca1156241898a69955cc8a3
aeaadd3a687024c1bde5915f312eac506bc9354d
/source/models/QubicleBinary.h
15c945197b02b2d6058e1250e4d6d4c4fad47461
[]
no_license
nitzanel/Vox
3ef33211af7034ec02daf8a2e63b242480f4f3e4
3878002adb0acc7e715dc608420f028c24f37b76
refs/heads/master
2020-12-03T05:19:02.365904
2015-10-13T03:12:20
2015-10-13T03:12:20
44,162,071
3
1
null
2015-10-13T08:18:32
2015-10-13T08:18:32
null
UTF-8
C++
false
false
6,376
h
// ****************************************************************************** // // Filename: QubicleBinary.h // Project: Game // Author: Steven Ball // // Purpose: // // Revision History: // Initial Revision - 10/07/14 // // Copyright (c) 2005-2015, Steven Ball // // ****************************************************************************** #pragma once #include "MS3DModel.h" #include "MS3DAnimator.h" class VoxelCharacter; enum MergedSide { MergedSide_None = 0, MergedSide_X_Positive = 1, MergedSide_X_Negative = 2, MergedSide_Y_Positive = 4, MergedSide_Y_Negative = 8, MergedSide_Z_Positive = 16, MergedSide_Z_Negative = 32, }; bool IsMergedXNegative(int *merged, int x, int y, int z, int width, int height); bool IsMergedXPositive(int *merged, int x, int y, int z, int width, int height); bool IsMergedYNegative(int *merged, int x, int y, int z, int width, int height); bool IsMergedYPositive(int *merged, int x, int y, int z, int width, int height); bool IsMergedZNegative(int *merged, int x, int y, int z, int width, int height); bool IsMergedZPositive(int *merged, int x, int y, int z, int width, int height); class QubicleMatrix { public: char m_nameLength; char* m_name; unsigned int m_matrixSizeX; unsigned int m_matrixSizeY; unsigned int m_matrixSizeZ; int m_matrixPosX; int m_matrixPosY; int m_matrixPosZ; unsigned int *m_pColour; int m_boneIndex; Matrix4x4 m_modelMatrix; float m_scale; float m_offsetX; float m_offsetY; float m_offsetZ; bool m_removed; OpenGLTriangleMesh* m_pMesh; void GetColour(int x, int y, int z, float* r, float* g, float* b, float* a) { unsigned colour = m_pColour[x + m_matrixSizeX * (y + m_matrixSizeY * z)]; unsigned int alpha = (colour & 0xFF000000) >> 24; unsigned int blue = (colour & 0x00FF0000) >> 16; unsigned int green = (colour & 0x0000FF00) >> 8; unsigned int red = (colour & 0x000000FF); *r = (float)(red / 255.0f); *g = (float)(green / 255.0f); *b = (float)(blue / 255.0f); *a = 1.0f; } unsigned int GetColourCompact(int x, int y, int z) { return m_pColour[x + m_matrixSizeX * (y + m_matrixSizeY * z)]; } bool GetActive(int x, int y, int z) { unsigned colour = m_pColour[x + m_matrixSizeX * (y + m_matrixSizeY * z)]; unsigned int alpha = (colour & 0xFF000000) >> 24; unsigned int blue = (colour & 0x00FF0000) >> 16; unsigned int green = (colour & 0x0000FF00) >> 8; unsigned int red = (colour & 0x000000FF); if(alpha == 0) { return false; } return true; } }; typedef std::vector<QubicleMatrix*> QubicleMatrixList; class QubicleBinary { public: /* Public methods */ QubicleBinary(Renderer* pRenderer); ~QubicleBinary(); void Unload(); void ClearMatrices(); void Reset(); string GetFileName(); unsigned int GetMaterial(); Matrix4x4 GetModelMatrix(int qubicleMatrixIndex); int GetMatrixIndexForName(const char* matrixName); void GetMatrixPosition(int index, int* aX, int* aY, int* aZ); bool Import(const char* fileName); bool Export(const char* fileName); void GetColour(int matrixIndex, int x, int y, int z, float* r, float* g, float* b, float* a); unsigned int GetColourCompact(int matrixIndex, int x, int y, int z); bool GetSingleMeshColour(float* r, float* g, float* b, float* a); bool GetActive(int matrixIndex, int x, int y, int z); void SetMeshAlpha(float alpha); void SetMeshSingleColour(float r, float g, float b); void SetForceTransparency(bool force); void CreateMesh(); void UpdateMergedSide(int *merged, int matrixIndex, int blockx, int blocky, int blockz, int width, int height, Vector3d *p1, Vector3d *p2, Vector3d *p3, Vector3d *p4, int startX, int startY, int maxX, int maxY, bool positive, bool zFace, bool xFace, bool yFace); int GetNumMatrices(); QubicleMatrix* GetQubicleMatrix(int index); QubicleMatrix* GetQubicleMatrix(const char* matrixName); const char* GetMatrixName(int index); float GetMatrixScale(int index); Vector3d GetMatrixOffset(int index); void SetupMatrixBones(MS3DAnimator* pSkeleton); void SetScaleAndOffsetForMatrix(const char* matrixName, float scale, float xOffset, float yOffset, float zOffset); float GetScale(const char* matrixName); Vector3d GetOffset(const char* matrixName); void SwapMatrix(const char* matrixName, QubicleMatrix* pMatrix, bool copyMatrixParams); void AddQubicleMatrix(QubicleMatrix* pNewMatrix, bool copyMatrixParams); void RemoveQubicleMatrix(const char* matrixName); void SetQubicleMatrixRender(const char* matrixName, bool render); // Sub selection string GetSubSelectionName(int pickingId); // Rendering modes void SetWireFrameRender(bool wireframe); // Update void Update(float dt); // Rendering void Render(bool renderOutline, bool refelction, bool silhouette, Colour OutlineColour); void RenderWithAnimator(MS3DAnimator** pSkeleton, VoxelCharacter* pVoxelCharacter, bool renderOutline, bool refelction, bool silhouette, Colour OutlineColour, bool subSelectionNamePicking); void RenderSingleMatrix(MS3DAnimator** pSkeleton, VoxelCharacter* pVoxelCharacter, string matrixName, bool renderOutline, bool silhouette, Colour OutlineColour); void RenderFace(MS3DAnimator* pSkeleton, VoxelCharacter* pVoxelCharacter, bool transparency, bool useScale = true, bool useTranslate = true); void RenderPaperdoll(MS3DAnimator* pSkeleton, VoxelCharacter* pVoxelCharacter); void RenderPortrait(MS3DAnimator* pSkeleton, VoxelCharacter* pVoxelCharacter, string matrixName); protected: /* Protected methods */ private: /* Private methods */ public: /* Public members */ static const float BLOCK_RENDER_SIZE; static const int SUBSELECTION_NAMEPICKING_OFFSET = 10000000; protected: /* Protected members */ private: /* Private members */ Renderer* m_pRenderer; // Loaded flag bool m_loaded; // Filename string m_fileName; // Qubicle binary file information char m_version[4]; unsigned int m_colourFormat; unsigned int m_zAxisOrientation; unsigned int m_compressed; unsigned int m_visibilityMaskEncoded; unsigned int m_numMatrices; // Matrix data for file QubicleMatrixList m_vpMatrices; // Render modes bool m_renderWireFrame; // Alpha float m_meshAlpha; bool m_shouldForceTransparency; // Single colour bool m_singleMeshColour; float m_meshSingleColourR; float m_meshSingleColourG; float m_meshSingleColourB; // Material unsigned int m_materialID; };
[ "steven.g.ball@gmail.com" ]
steven.g.ball@gmail.com
b087a6dcca4fadda6f99816f5031b0b310272048
3b4fbf828bb05aad7a06e006513d8baf23383639
/IBInclude/EPosixClientSocketPlatform.h
30dabf221090f372188b428a2bf9ec5ab5c733f8
[]
no_license
wrongii/IBConnectivity
2a6b9d1bb2d920b878b96ca86e37492ca689c570
a965e36f769c9ef7633538c8f55d69f71e337cac
refs/heads/master
2020-03-14T08:03:30.004760
2018-04-29T17:54:12
2018-04-29T17:54:12
131,516,777
0
0
null
null
null
null
UTF-8
C++
false
false
2,209
h
#ifndef eposixclientsocketcommon_def #define eposixclientsocketcommon_def #ifdef _WIN32 // Windows // includes #ifdef NEED_WINVER_XP #define WINVER 0x0501 #endif # ifdef HAVE_WS2TCPIP_H #include <ws2tcpip.h> # endif #include <winsock2.h> #include <time.h> /* These errno re-defines are bad because we want to use strerror on them. We would need to rewrite strerror for _WIN32 but currently I just want to finish with that crap quick and dirty. */ #define EISCONN WSAEISCONN #define EWOULDBLOCK WSAEWOULDBLOCK #define ECONNREFUSED WSAECONNREFUSED #define EINPROGRESS WSAEINPROGRESS #define ETIMEDOUT WSAETIMEDOUT #define ENODATA WSANO_DATA namespace IB { // helpers inline bool SocketsInit( void) { WSADATA data; return ( !WSAStartup( MAKEWORD(2, 2), &data)); }; inline bool SocketsDestroy() { return ( !WSACleanup()); }; inline int SocketClose(int sockfd) { return closesocket( sockfd); }; } #else // LINUX // includes #include <arpa/inet.h> #include <errno.h> #include <sys/select.h> #include <netdb.h> #include <fcntl.h> #include <unistd.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #if ! HAVE_DECL_ENODATA #define ENODATA ETIMEDOUT #endif namespace IB { // helpers inline bool SocketsInit() { return true; }; inline bool SocketsDestroy() { return true; }; inline int SocketClose(int sockfd) { return close( sockfd); }; } #endif namespace IB { static inline int set_socket_nonblock(int sockfd) { #if defined _WIN32 unsigned long mode = 1; if( ioctlsocket(sockfd, FIONBIO, &mode) != NO_ERROR ) { return -1; } #else int flags = fcntl( sockfd, F_GETFL, 0 ); if( flags == -1 ) { return -1; } if( fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) == -1 ) { return -1; } #endif return 0; } static inline int socket_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { int rval = connect(sockfd, addr, addrlen ); #if defined _WIN32 /* connect does not set errno on win32 */ if( rval != 0 ) { errno = WSAGetLastError(); if( errno == WSAEWOULDBLOCK ) { errno = EINPROGRESS; } } #endif return rval; } } // namespace IB #endif
[ "38839694+wrongii@users.noreply.github.com" ]
38839694+wrongii@users.noreply.github.com
f420e871c9a1698a1e48976b42f6e7a4f4f14ab8
284f2e73ce5c4a3274167993fafcdfc18d2d0564
/fontsettingtestsuite.h
bd2076a5275c4e63399fbfb57a48af648ffdc63d
[]
no_license
powertab/ptparser
c9b466307e54ca64389749eccdecb79c0c7f2057
66dd75676b938f4f238ced4a7d219669e276f162
refs/heads/master
2022-11-12T15:31:55.742576
2020-06-25T21:35:35
2020-06-25T21:35:35
275,019,279
0
0
null
2020-06-25T21:32:27
2020-06-25T21:32:27
null
UTF-8
C++
false
false
1,336
h
///////////////////////////////////////////////////////////////////////////// // Name: fontsettingtestsuite.h // Purpose: Performs unit testing on the FontSetting class // Author: Brad Larsen // Modified by: // Created: Dec 7, 2004 // RCS-ID: // Copyright: (c) Brad Larsen // License: wxWindows license ///////////////////////////////////////////////////////////////////////////// #ifndef __FONTSETTINGTESTSUITE_H__ #define __FONTSETTINGTESTSUITE_H__ /// Performs unit testing on the FontSetting class class FontSettingTestSuite : public TestSuite { DECLARE_DYNAMIC_CLASS(FontSettingTestSuite) // Constructor/Destructor public: FontSettingTestSuite(); ~FontSettingTestSuite(); // Overrides size_t GetTestCount() const; bool RunTestCases(); // Test Case Functions private: bool TestCaseConstructor(); bool TestCaseCreation(); bool TestCaseOperator(); bool TestCaseSerialize(); bool TestCaseSetFontSetting(); bool TestCaseSetFontSettingFromString(); bool TestCaseFaceName(); bool TestCasePointSize(); bool TestCaseWeight(); bool TestCaseItalic(); bool TestCaseUnderline(); bool TestCaseStrikeOut(); bool TestCaseColor(); }; #endif
[ "powertab2000@d5aff946-bc2e-0410-8690-abe9dfd6c9e2" ]
powertab2000@d5aff946-bc2e-0410-8690-abe9dfd6c9e2
13f0399469d2c9cce202f62bc0409e51c0e16b27
b426edac874bd1a4619975f1e7155cd94d4317f8
/Sources/Shader.h
0479a57004db96d01af5511ec057a73af5abb0ce
[]
no_license
Wadadeo/BloomEffect
cab801cf0d702ee063f947ac586dab3c829b5f3c
f7c8b9c822e6667b815cb88ae476bd9fbe456b59
refs/heads/master
2021-01-11T13:52:57.475482
2017-06-21T03:59:46
2017-06-21T03:59:46
94,872,137
0
1
null
null
null
null
UTF-8
C++
false
false
1,514
h
#pragma once #include <iostream> #include <string> #include <fstream> #include <vector> #include <map> #include "GL/glew.h" #include <GL/gl.h> #include <glm/glm.hpp> #include "glm/mat4x4.hpp" #define MODEL_MATRIX "model" #define VIEW_MATRIX "view" #define PROJECTION_MATRIX "projection" #define NORMAL_MATRIX "NormalMatrix" #define MVP_ATTRIB "MVP" #define TEXTURE_ATTRIB "textureSampler" #define VERTEX_POSITION_ATTRIB "vertexPosition" #define VERTEX_COLOR_ATTRIB "vertexColor" #define VERTEX_NORMAL_ATTRIB "vertexNormal" #define VERTEX_UV_ATTRIB "vertexUV" using namespace std; class Shader { private: GLuint _programID; string _name; const string vertexShader; const string fragShader; public: Shader(); Shader(const GLuint &programId, const string &name, const string &vertShaderPath, const string& fragShaderPath); ~Shader(); void use() const; void disable() const; void deleteProgram() const; void uniform(const char *name, const glm::mat4 &value) const; void uniform(const char *name, const glm::mat3 &value) const; void uniform(const char *name, const glm::vec3 &value) const; void uniform(const char *name, const glm::vec2 &value) const; void uniform(const char *name, const unsigned int &value) const; void uniform(const char *name, const float &value) const; void uniform(const char *name, bool value) const; const GLuint& program() const; const string& name() const; const string& vertShaderPath() const; const string& fragShaderPath() const; };
[ "valentin.peschard@gmail.com" ]
valentin.peschard@gmail.com
7edd1be1a5e825a07a34c555a24fd25b91b84fcd
d4d7f63398c19eaad2b8e043a06bc1b9bfe88e94
/DeclarativeDragDropEvent.h
f488bef3218af24a2268d37b21987da256442241
[]
no_license
DinnerForBreakfast/supermacrobot
3fa5bdf2c7562698148a034f3d094de1eb785e88
52d799377369f095d138e53d1c62a2ed619d91b8
refs/heads/master
2021-01-21T06:48:58.699585
2013-08-15T05:49:22
2013-08-15T05:49:22
91,586,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,228
h
#ifndef DECLARATIVEDRAGDROPEVENT_H #define DECLARATIVEDRAGDROPEVENT_H #include <QObject> #include <QGraphicsSceneDragDropEvent> #include "DeclarativeMimeData.h" class DeclarativeDragDropEvent : public QObject { Q_OBJECT Q_PROPERTY(int x READ x) Q_PROPERTY(int y READ y) Q_PROPERTY(int buttons READ buttons) Q_PROPERTY(int modifiers READ modifiers) Q_PROPERTY(DeclarativeMimeData* data READ data) Q_PROPERTY(Qt::DropActions possibleActions READ possibleActions) Q_PROPERTY(Qt::DropAction proposedAction READ proposedAction) public: DeclarativeDragDropEvent(QGraphicsSceneDragDropEvent* e, QObject* parent = 0); int x() const { return m_x; } int y() const { return m_y; } int buttons() const { return m_buttons; } int modifiers() const { return m_modifiers; } DeclarativeMimeData* data() { return &m_data; } Qt::DropAction proposedAction() const { return m_event->proposedAction(); } Qt::DropActions possibleActions() const { return m_event->possibleActions(); } public slots: void accept(int action); private: int m_x; int m_y; Qt::MouseButtons m_buttons; Qt::KeyboardModifiers m_modifiers; DeclarativeMimeData m_data; QGraphicsSceneDragDropEvent* m_event; }; #endif // DECLARATIVEDRAGDROPEVENT_H
[ "josh@josh-Kubuntu.(none)" ]
josh@josh-Kubuntu.(none)
1d59215e3809e72ce8f6dbaa2d7c269f62306774
98beeffab0570eb7e4bd2785fc195658e18aa6dd
/SRC/common/crandom.swg
afb9f3d1da61db0bbf8e1e9ab36e3af04bbf83f1
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
shkeshavarz/OOF2
27f59bb04775b76ad250ecfd76118b3760647bba
0f69f535d040875354cd34e8bbedeae142ff09a3
refs/heads/master
2021-01-15T15:32:10.713469
2016-01-13T14:44:20
2016-01-13T14:44:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
901
swg
// -*- C++ -*- // $RCSfile: crandom.swg,v $ // $Revision: 1.4 $ // $Author: langer $ // $Date: 2011/10/12 21:15:51 $ /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modified * versions of this software, you first contact the authors at * oof_manager@nist.gov. */ // This is the SWIG file for the "random.[Ch]" files. It has a name // different from random because there's already a Python module // called "random". #ifndef CRANDOM_SWG #define CRANDOM_SWG %module crandom %include "common/typemaps.swg" %{ #include "common/random.h" %} void rndmseed(int); double rndm(); int irndm(); #endif // CRANDOM_SWG
[ "lnz5@rosie.nist.gov" ]
lnz5@rosie.nist.gov
0f298a2eb9789366c144d749b978c0d43efbedcd
e888dce5b039378f707a3395d7e8c5edc45913f9
/PA5/cix-server.cpp
46688612a454915bf418cd0ee2ac1d4fe344cd10
[]
no_license
revrunner/AdvancedProgramming
c982e1d2b4eb8385aa96f69f37886a387f13d88f
3d230ae35927eea5826f885c3ba3c88b91cc5c81
refs/heads/master
2021-01-09T20:56:33.636842
2016-07-06T17:28:54
2016-07-06T17:28:54
62,740,108
0
0
null
null
null
null
UTF-8
C++
false
false
5,528
cpp
//Dara Diba ddiba@ucsc.edu //Nirav Agrawal nkagrawa@ucsc.edu #include <iostream> using namespace std; #include <libgen.h> #include <iostream> #include <fstream> #include "cix_protocol.h" #include "logstream.h" #include "signal_action.h" #include "sockets.h" logstream log (cout); void reply_ls (accepted_socket& client_sock, cix_header& header) { FILE* ls_pipe = popen ("ls -l", "r"); if (ls_pipe == NULL) { log << "ls -l: popen failed: " << strerror (errno) << endl; header.cix_command = CIX_NAK; header.cix_nbytes = errno; send_packet (client_sock, &header, sizeof header); } string ls_output; char buffer[0x1000]; for (;;) { char* rc = fgets (buffer, sizeof buffer, ls_pipe); if (rc == nullptr) break; ls_output.append (buffer); } header.cix_command = CIX_LSOUT; header.cix_nbytes = ls_output.size(); memset (header.cix_filename, 0, CIX_FILENAME_SIZE); log << "header sending" << header << endl; send_packet (client_sock, &header, sizeof header); send_packet (client_sock, ls_output.c_str(), ls_output.size()); log << "sent " << ls_output.size() << " bytes" << endl; } void reply_put(accepted_socket& client_sock, cix_header& header){ char buffer[header.cix_nbytes +1]; recv_packet (client_sock, buffer, sizeof header); log << "header received" << header << endl; ofstream outfile (header.cix_filename); if(outfile){ buffer[header.cix_nbytes] = '\0'; outfile.write(buffer, header.cix_nbytes); outfile.close(); header.cix_command = CIX_ACK; send_packet(client_sock, &header, sizeof header); cout << "here is your new file @ 'new_file.txt'"<<endl; }else{ header.cix_command = CIX_NAK; send_packet(client_sock, &header, sizeof header); } } void reply_get (accepted_socket& client_sock, cix_header& header) { string get_output = ""; ifstream is (header.cix_filename, ifstream::binary); int length = 0; if (is == nullptr) { log << "get : popen failed: " << strerror (errno) << endl; header.cix_command = CIX_NAK; header.cix_nbytes = errno; send_packet (client_sock, &header, sizeof header); cout<<"sent failure"<<endl; }else{ is.seekg(0, is.end); length = is.tellg(); is.seekg (0, is.beg); char* buffer = new char[length]; is.read(buffer,length); if(is){ cout<<"complete transfer"<<endl; } else cout<<"error only: "<<is.gcount()<<"read"<<endl; is.close(); header.cix_command = CIX_ACK; header.cix_nbytes = length; log << "header sending" << header << endl; send_packet (client_sock, &header, sizeof header); send_packet (client_sock, buffer, header.cix_nbytes); log << "sent " << length << " bytes" << endl; delete[] buffer; } } void reply_rm (accepted_socket& client_sock, cix_header& header) { string rm_output = ""; int rc = unlink(header.cix_filename); if (rc <0) { log << "rm : popen failed: " << strerror (rc) << endl; header.cix_command = CIX_NAK; header.cix_nbytes = rc; send_packet (client_sock, &header, sizeof header); cout<<"sent failure"<<endl; } header.cix_command = CIX_ACK; header.cix_nbytes = rm_output.size(); memset (header.cix_filename, 0, CIX_FILENAME_SIZE); log << "header sending" << header << endl; send_packet (client_sock, &header, sizeof header); send_packet (client_sock, rm_output.c_str(), rm_output.size()); log << "sent " << rm_output.size() << " bytes" << endl; } bool SIGINT_throw_cix_exit = false; void signal_handler (int signal) { log << "signal_handler: caught " << strsignal (signal) << endl; switch (signal) { case SIGINT: case SIGTERM: SIGINT_throw_cix_exit = true; break; default: break; } } int main (int argc, char** argv) { log.execname (basename (argv[0])); log << "starting" << endl; vector<string> args (&argv[1], &argv[argc]); signal_action (SIGINT, signal_handler); signal_action (SIGTERM, signal_handler); int client_fd = args.size() == 0 ? -1 : stoi (args[0]); log << "starting client_fd " << client_fd << endl; try { accepted_socket client_sock (client_fd); log << "connected to " << to_string (client_sock) << endl; for (;;) { if (SIGINT_throw_cix_exit) throw cix_exit(); cix_header header; recv_packet (client_sock, &header, sizeof header); log << "received header" << header << endl; switch (header.cix_command) { case CIX_LS: reply_ls (client_sock, header); break; case CIX_GET: reply_get(client_sock, header); break; case CIX_RM: cout<<"SERVER IS AWAKE: RM.."<<endl; reply_rm(client_sock, header); break; case CIX_PUT: reply_put(client_sock, header); break; default: log << "invalid header from client" << endl; log << "cix_nbytes = " << header.cix_nbytes << endl; log << "cix_command = " << header.cix_command << endl; log << "cix_filename = " << header.cix_filename << endl; break; } } }catch (socket_error& error) { log << error.what() << endl; }catch (cix_exit& error) { log << "caught cix_exit" << endl; } log << "finishing" << endl; return 0; }
[ "nka1994@gmail.com" ]
nka1994@gmail.com
b22c1e152876b9216cfc334fe22b3f9211d41919
a6c2feb728f6c5fcdd80c6c5c6414ba7607df409
/src/c++/lib/svgraph/test/SVLocusSetSerializeTest.cpp
98dc90752301bace1c14deb82ef86427694bd494
[ "BSD-3-Clause", "BSL-1.0", "MIT" ]
permissive
arnoldliaoILMN/manta
ec53002619f1e83d44bafa7765dde5b6ef6ec941
2c70342be434e8c028a89cc98e4bdc048dd91e92
refs/heads/master
2021-01-16T00:46:25.101919
2013-09-30T20:42:09
2013-09-30T20:42:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,863
cpp
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Manta // Copyright (c) 2013 Illumina, Inc. // // This software is provided under the terms and conditions of the // Illumina Open Source Software License 1. // // You should have received a copy of the Illumina Open Source // Software License 1 along with this program. If not, see // <https://github.com/sequencing/licenses/> // /// /// \author Chris Saunders /// #include "boost/archive/tmpdir.hpp" #include "boost/test/unit_test.hpp" #include "svgraph/SVLocusSet.hh" #include "SVLocusTestUtil.hh" using namespace boost::archive; BOOST_AUTO_TEST_SUITE( test_SVLocusSetSerialize ) BOOST_AUTO_TEST_CASE( test_SVLocusSetSerialze ) { // construct a simple two-node locus SVLocus locus1; locusAddPair(locus1,1,10,20,2,30,40); SVLocus locus2; locusAddPair(locus2,3,10,20,4,30,40); SVLocusSet set1; set1.merge(locus1); set1.merge(locus2); std::string filename(tmpdir()); filename += "/testfile.bin"; // serialize set1.save(filename.c_str()); SVLocusSet set1_copy; // deserialize set1_copy.load(filename.c_str()); BOOST_REQUIRE_EQUAL(set1.size(),set1_copy.size()); typedef SVLocusSet::const_iterator citer; citer i(set1.begin()); citer i_copy(set1_copy.begin()); const SVLocus& set1_locus1(*i); const SVLocus& set1_copy_locus1(*i_copy); BOOST_REQUIRE_EQUAL(set1_locus1.size(),set1_copy_locus1.size()); } BOOST_AUTO_TEST_CASE( test_SVLocusSetSerialze2 ) { SVLocusSet set1; { SVLocus locus1; locusAddPair(locus1,1,10,20,2,30,40); SVLocus locus2; locusAddPair(locus2,3,10,20,4,30,40); set1.merge(locus1); set1.merge(locus2); } SVLocusSet set2; { SVLocus locus1; locusAddPair(locus1,1,15,25,4,30,40); SVLocus locus2; locusAddPair(locus2,3,30,40,2,30,40); set2.merge(locus1); set2.merge(locus2); } SVLocusSet set1_copy; { std::string filename(tmpdir()); filename += "/testfile.bin"; // serialize set1.save(filename.c_str()); // deserialize set1_copy.load(filename.c_str()); } SVLocusSet set2_copy; { std::string filename(tmpdir()); filename += "/testfile.bin"; // serialize set2.save(filename.c_str()); // deserialize set2_copy.load(filename.c_str()); } set1.merge(set2); set1_copy.merge(set2_copy); BOOST_REQUIRE_EQUAL(set1.size(),set1_copy.size()); typedef SVLocusSet::const_iterator citer; citer i(set1.begin()); citer i_copy(set1_copy.begin()); const SVLocus& set1_locus1(*i); const SVLocus& set1_copy_locus1(*i_copy); BOOST_REQUIRE_EQUAL(set1_locus1.size(),set1_copy_locus1.size()); } BOOST_AUTO_TEST_SUITE_END()
[ "csaunders@illumina.com" ]
csaunders@illumina.com
636c3c6c3b2e63e0ec6df564a6495cdc4d275e93
51c8fabe609cc7de64dc1aa8a0c702d1ae4f61fe
/67.MiniMap/Classes/HelloWorldScene.cpp
75e2405eee7d2186bcdf9cccfd718ddfdb6708f7
[]
no_license
Gasbebe/cocos2d_source
5f7720da904ff71a4951bee470b8744aab51c59d
2376f6bdb93a58ae92c0e9cbd06c0d97cd241d14
refs/heads/master
2021-01-18T22:35:30.357253
2016-05-20T08:10:55
2016-05-20T08:10:55
54,854,003
0
0
null
null
null
null
UTF-8
C++
false
false
2,010
cpp
#include "HelloWorldScene.h" USING_NS_CC; Scene* HelloWorld::createScene() { auto scene = Scene::create(); auto layer = HelloWorld::create(); scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { if ( !LayerColor::initWithColor(Color4B(255,255,255,255)) ) { return false; } ///////////////////////////// Size winSize = Director::getInstance()->getWinSize(); gameLayer = LayerColor::create(Color4B(255, 0, 0, 255), winSize.width, winSize.height); gameLayer->setAnchorPoint(Vec2(0, 0)); gameLayer->setPosition(Vec2(0, 0)); this->addChild(gameLayer); menuLayer = LayerColor::create(Color4B(0, 0, 0, 0), winSize.width, winSize.height); menuLayer->setAnchorPoint(Vec2(0, 0)); menuLayer->setPosition(Vec2(0, 0)); this->addChild(menuLayer); auto pMan = Sprite::create("Images/grossini.png"); pMan->setPosition(Vec2(60, 160)); gameLayer->addChild(pMan); auto myActionForward = MoveBy::create(2, Vec2(380, 0)); auto myActionBack = myActionForward->reverse(); auto myAction = Sequence::create(myActionForward, myActionBack, nullptr); auto rep = RepeatForever::create(myAction); pMan->runAction(rep); auto pBack = Sprite::create("Images/minimap_back.png"); pBack->setPosition(Vec2(400, 260)); pBack->setColor(Color3B::BLACK); menuLayer->addChild(pBack); miniMap = RenderTexture::create(480, 320, Texture2D::PixelFormat::RGBA8888); miniMap->retain(); miniMap->setPosition(400, 260); return true; } void HelloWorld::onEnter() { Layer::onEnter(); miniMap->begin(); gameLayer->visit(); miniMap->end(); Sprite* mms = miniMap->getSprite(); mms->setScale(0.22f); mms->setScaleY(mms->getScaleY() * 1); menuLayer->addChild(miniMap); this->schedule(schedule_selector(HelloWorld::updateMinimap)); } void HelloWorld::updateMinimap(float f) { miniMap->clear(0, 0, 0, 255); miniMap->begin(); gameLayer->visit(); miniMap->end(); }
[ "gasbebe@gmail.com" ]
gasbebe@gmail.com
c21c4c647ff2bb9b4c90672a4c8953dccb9286e3
a1809f8abdb7d0d5bbf847b076df207400e7b08a
/Simpsons Hit&Run/game/libs/sim/simcommon/simstateflexible.hpp
f6d8af4ad328fa05dec4ff6d844e502e975ac513
[]
no_license
RolphWoggom/shr.tar
556cca3ff89fff3ff46a77b32a16bebca85acabf
147796d55e69f490fb001f8cbdb9bf7de9e556ad
refs/heads/master
2023-07-03T19:15:13.649803
2021-08-27T22:24:13
2021-08-27T22:24:13
400,380,551
8
0
null
null
null
null
UTF-8
C++
false
false
2,023
hpp
#ifndef _SIMSTATEFLEXIBLE_HPP_ #define _SIMSTATEFLEXIBLE_HPP_ #include "simcommon/simstate.hpp" #include <raddebug.hpp> namespace sim { class FlexibleObject; class SimStateFlexible : public SimState { public: static SimStateFlexible* CreateSimStateFlexible(tUID inUID, SimStateAttributes inAttrib = SimStateAttribute_Default, tEntityStore* inStore=NULL ); static SimStateFlexible* CreateSimStateFlexible(const char* inName, SimStateAttributes inAttrib = SimStateAttribute_Default, tEntityStore* inStore=NULL ); static SimStateFlexible* CreateManSimStateFlexible(int m, int n, float size, int inType); void GetVelocity(const rmt::Vector& inPosition, rmt::Vector& oVelocity, int inIndex); virtual void SetTransform(const rmt::Matrix& inTransform, float dt = 0); // usimg not support by ps2 //using SimState::GetPosition; // so that it is not hidden by GetPosition(int inIndex) //using SimState::GetTransform; // so that it is not hidden by GetTransform(int inIndex) const rmt::Vector& GetPosition() const { return SimState::GetPosition(); } const rmt::Matrix& GetTransform() const { return SimState::GetTransform(); } virtual const rmt::Matrix& GetTransform(int inIndex) const; virtual const rmt::Vector& GetPosition(int inIndex) const; virtual void SetHasMoved(bool in_hasMoved); virtual void DebugDisplay(int debugIndex = 0); virtual bool RequiresPushTransforForDisplay() const { return false; } FlexibleObject* GetFlexibleObject() { return (FlexibleObject*) mSimulatedObject; } SimStateFlexible(SimControlEnum inControl = simAICtrl); protected: ~SimStateFlexible(); float mSphereRadius; private: SimStateFlexible& operator=(SimStateFlexible& inObj) { rAssert(false); return *this; } SimStateFlexible(const SimStateFlexible& inObj) { rAssert(false); } }; } // sim #endif // _SIMSTATEFLEXIBLE_HPP_
[ "81568815+RolphWoggom@users.noreply.github.com" ]
81568815+RolphWoggom@users.noreply.github.com
c3657d8f08843e250b3faa00890a7c11c8230c1d
44140767d2be68f173ddb2349809b9fcf8442607
/GWToolbox/GWToolbox/Windows/DialogsWindow.h
ebbe5cc50b57cdcd30be7d94de7d810d54704bb7
[]
no_license
kamadan/zhushou
663249e16cce0b15504f2e3c68546b73f6007bc3
0335c40f8800edd9a9caab801f771cb4be6daabd
refs/heads/master
2020-12-01T05:21:48.390494
2019-12-30T02:53:31
2019-12-30T02:53:31
230,566,379
0
0
null
null
null
null
UTF-8
C++
false
false
997
h
#pragma once #include <Windows.h> #include <vector> #include <Defines.h> #include "ToolboxWindow.h" class DialogsWindow : public ToolboxWindow { DialogsWindow() {}; ~DialogsWindow() {}; public: static DialogsWindow& Instance() { static DialogsWindow instance; return instance; } const char* Name() const override { return "令码"; } void Initialize() override; void Draw(IDirect3DDevice9* pDevice) override; void LoadSettings(CSimpleIni* ini) override; void SaveSettings(CSimpleIni* ini) override; void DrawSettingInternal() override; private: inline DWORD QuestAcceptDialog(DWORD quest) { return (quest << 8) | 0x800001; } inline DWORD QuestRewardDialog(DWORD quest) { return (quest << 8) | 0x800007; } DWORD IndexToQuestID(int index); DWORD IndexToDialogID(int index); int fav_count = 0; std::vector<int> fav_index; bool show_common = true; bool show_uwteles = true; bool show_favorites = true; bool show_custom = true; char customdialogbuf[64] = ""; };
[ "huiji-baike@email" ]
huiji-baike@email
65ca72d336e417f2c6ff5399a8f11c998e8c304e
3dae85df94e05bb1f3527bca0d7ad413352e49d0
/ml/nn/runtime/test/generated/models/embedding_lookup_relaxed.model.cpp
1e3953e5b6f86fc170ed8ca50c521601453f5364
[ "Apache-2.0" ]
permissive
Wenzhao-Xiang/webml-wasm
e48f4cde4cb986eaf389edabe78aa32c2e267cb9
0019b062bce220096c248b1fced09b90129b19f9
refs/heads/master
2020-04-08T11:57:07.170110
2018-11-29T07:21:37
2018-11-29T07:21:37
159,327,152
0
0
null
null
null
null
UTF-8
C++
false
false
813
cpp
// clang-format off // Generated file (from: embedding_lookup_relaxed.mod.py). Do not edit void CreateModel(Model *model) { OperandType type0(Type::TENSOR_INT32, {3}); OperandType type1(Type::TENSOR_FLOAT32, {3, 2, 4}); // Phase 1, operands auto index = model->addOperand(&type0); auto value = model->addOperand(&type1); auto output = model->addOperand(&type1); // Phase 2, operations model->addOperation(ANEURALNETWORKS_EMBEDDING_LOOKUP, {index, value}, {output}); // Phase 3, inputs and outputs model->identifyInputsAndOutputs( {index, value}, {output}); // Phase 4: set relaxed execution model->relaxComputationFloat32toFloat16(true); assert(model->isValid()); } inline bool is_ignored(int i) { static std::set<int> ignore = {}; return ignore.find(i) != ignore.end(); }
[ "wenzhao.xiang@intel.com" ]
wenzhao.xiang@intel.com
eeace3977422b3cea28075db88b45e1ae36026fe
b6a4cec0400b016205f86ab68987116ae2bb9427
/ardrone_urbi/include/libport/dlfcn.h
a369226ad50953adfc9025e4087e1e12f2ef7dc0
[]
no_license
pong3489/Projet_ARDrone_Track
5d96133e31ccffedbad7f1be71b48134634deda3
d5544a6cc18b0e355eaed131a3b4e65b97a96887
refs/heads/master
2021-01-18T00:45:17.313010
2014-02-18T20:38:53
2014-02-18T20:38:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,149
h
/* * Copyright (C) 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** Portable dlopen utilities. -*- c++ -*- * * Keep this file header only as it's used in relocatable binaries. */ #ifndef LIBPORT_DLFCN_H # define LIBPORT_DLFCN_H # include <libport/windows.hh> /*---------------------------------. | dlopen and dlsym under windows. | `---------------------------------*/ # ifdef WIN32 # define RTLD_LAZY 0 # define RTLD_NOW 0 # define RTLD_GLOBAL 0 typedef HMODULE RTLD_HANDLE; static inline RTLD_HANDLE dlopen(const char* name, int) { RTLD_HANDLE res = LoadLibrary(name); if (res) { char buf[BUFSIZ]; GetModuleFileName(res, buf, sizeof buf - 1); buf[sizeof buf - 1] = 0; } return res; } static inline void* dlsym(RTLD_HANDLE module, const char* name) { return GetProcAddress(module, name); } static inline const char* dlerror(DWORD err = GetLastError()) { static char buf[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, 0, (LPTSTR)buf, sizeof buf, 0); return buf; } # else # include <dlfcn.h> typedef void* RTLD_HANDLE; # endif /*-----------------------------. | Portable file names chunks. | `-----------------------------*/ namespace libport { /// Extension of executable files, potential dot included. static const std::string ext_exe = "" # ifdef WIN32 ".exe" # endif ; /// Extension of shared modules, potential dot included. static const std::string ext_module = # if defined(WIN32) ".dll" # else ".so" # endif ; /// Extension of shared libraries, potential dot included. static const std::string ext_shlib = # if defined(WIN32) ".dll" # elif defined(__APPLE__) ".dylib" # else ".so" # endif ; /// Potential prefix to prepend to shared libraries names. static const std::string pre_shlib = "" # ifndef WIN32 "lib" # endif ; } #endif
[ "grancherlaura@gmail.com" ]
grancherlaura@gmail.com
cef8e31a6535c0d5016ca693a751ea0e94aa4997
7983da2a6f9096e6c547fb67a2b638302c55809e
/Buildings/mine.cpp
079200264df05fa1fd838136d7965430b0f35304
[]
no_license
KertAles/Osvajalec-Game
ff8a4c4df491550ecc8f3f065f7b0cbd7db7890d
64f6a51f3793918463abbd8dcb71ffe81f93d142
refs/heads/master
2022-11-14T08:41:20.141703
2020-07-05T09:43:26
2020-07-05T09:43:26
277,158,666
1
0
null
null
null
null
UTF-8
C++
false
false
1,789
cpp
#include "mine.h" extern MainWindow* w; Mine::Mine(Player* ownedBy, GridSquare* createPos) { owner = ownedBy; position = createPos; type = 'm'; blocksMovement = false; maxHp = 50; hp = maxHp; defense = 0; los = 2; areaOfInfluence = -1; queueItem = nullptr; this->setPos(position->getX() + 7, position->getY()+SQUARESIZE - (BUILDINGSIZE + 8)); this->init(); buildPix->setPixmap(QPixmap(":/images/Buildings/mine.png")); w->bah->addItem(this); position->setBuilding(this); position->getResource()->exploit(true); owner -> addBuilding(this); owner -> updateIncome(); qDebug() << "Mine created"; } Mine::~Mine() { if(w->bah->selectedBuilding == this) { w->bah->selectedBuilding = nullptr; w->bah->clearButtons(); } if(queueItem) delete queueItem; position->building = nullptr; position -> getResource() -> exploit(false); owner -> removeBuilding(this); owner -> updateIncome(); delete buildPix; delete background; } void Mine::mousePressEvent(QGraphicsSceneMouseEvent *event) { event->accept(); if(event->button() == Qt::LeftButton) { qDebug() << "Mine leftclicked"; w->bah->selectedBuilding = this; w->bah->selectedUnit = nullptr; w->bah->unitOrderType = 'k'; if(this->getOwner() == w->bah->localPlayer) w->bah->buildingButtons(this); else w->bah->enemyBuildingButtons(this); } else if(event->button() == Qt::RightButton) { qDebug() << "Mine rightclicked"; if(w->bah->selectedUnit != nullptr && w->bah->unitOrderType == 'a') { qDebug() << "Mine attacked"; w->bah->selectedUnit->attackBuilding(this); } } }
[ "ales.kert@gmail.com" ]
ales.kert@gmail.com
df8c5c470f5703701a9fd70f0411eb4dae72b7a2
5e087122eae076b02e9d538d7c61a1b4d535776b
/common.cpp
a812964f57e950887034d3ca1a5e6ac3f6e9eec3
[]
no_license
karanjoisher/hot_code_reload
1f22a95cb5a22e643996ed1fa3d13747bf9bd594
0eeea05f729ae9b657f20e1a357a70e9e05481ba
refs/heads/master
2021-06-09T18:50:37.616802
2021-05-13T09:00:48
2021-05-13T09:00:48
164,218,740
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
cpp
void CopyString(char *source, char *destination, int startIndex, int length) { int destinationIndex = 0; for(int sourceIndex = startIndex; sourceIndex < (startIndex + length); sourceIndex++, destinationIndex++) { destination[destinationIndex] = source[sourceIndex]; } } int StringLength(char *str) { int length = 0; while(str[length] != 0) length++; return length; } void Concatenate(char *first, char *second) { int lengthOfFirst = StringLength(first); char *firstEnd = first + lengthOfFirst; CopyString(second, firstEnd, 0, StringLength(second) + 1); } int GetDirectoryNameEndIndex(char *path) { int result = 0; for(int i = 0; path[i] != 0; i++) { if(path[i] == '\\' || path[i] == '/') { result = i - 1; } } return result; } int GetFilenameStartIndex(char *path) { int result = 0; int length = StringLength(path); for(int i = length - 1; i >= 0; i--) { if(path[i] == '\\' || path[i] == '/') { result = i + 1; break; } } return result; }
[ "karanjoisher@gmail.com" ]
karanjoisher@gmail.com
ce54f40cec111b56466ef3af37d5f7de647b8473
e75a7ae1bca2448e6ef84b93c17600bf11113711
/19_09_01/1_시공의_폭풍_속으로.cpp
79af5f8bceeb80a937790d251ee404e0ff352ab7
[]
no_license
sjoon627/weekly_vita_algorithm
9f47b8ee65e1faf8d33c68502685c1aca7f6f902
6bd5b64449d3351829fbcec5a5df8c757e86c276
refs/heads/master
2020-07-07T01:03:18.149931
2020-04-13T14:07:16
2020-04-13T14:07:16
203,194,409
3
0
null
null
null
null
UTF-8
C++
false
false
258
cpp
#include<iostream> using namespace std; int main(){ int arr[100], num, ans; for(int i = 0; i<4; ++i){ scanf("%d", &num); arr[num] = 1; } for(int i = 0; i<5; ++i){ scanf("%d", &num); if(arr[num] == 0) ++ans; } cout << ans; }
[ "48435096+sjoon627@users.noreply.github.com" ]
48435096+sjoon627@users.noreply.github.com
a477e7d0aaac1aac5d5a0c81a49945351ef41ea3
d7b399f9601ae772b1a783385b017a9a41af7498
/ball_chaser/src/process_image.cpp
89bdd81f2973532a135e52fa9a2f39b456ee0bf2
[]
no_license
prashanthreddyd/robotics-project2
e0fc09fa6922b3af2dae1b058e4e30fcb76df188
c24d1fcee2ba080ff722388303a5453b9a2ecf5d
refs/heads/main
2023-03-13T22:22:00.144640
2021-03-03T03:35:17
2021-03-03T03:35:17
343,629,387
0
0
null
null
null
null
UTF-8
C++
false
false
2,494
cpp
#include "ros/ros.h" #include <sensor_msgs/Image.h> #include "ball_chaser/DriveToTarget.h" // Define a global client that can request services ros::ServiceClient client; // This function calls the command_robot service to drive the robot in the specified direction void drive_robot(float lin_x, float ang_z) { ball_chaser::DriveToTarget srv; srv.request.linear_x = lin_x; srv.request.angular_z = ang_z; // Call the command_robot service and pass the requested motor commands if (!client.call(srv)) { ROS_ERROR("Failed to call service command_robot"); } } // This callback function continuously executes and reads the image data void process_image_callback(const sensor_msgs::Image img) { int white_pixel = 255; bool found_ball = false; int row = 0; int step = 0; int i = 0; for (row = 0; row < img.height && found_ball == false; row++) { for (step = 0; step < img.step && found_ball == false; ++step) { i = (row*img.step)+step; if (img.data[i] == white_pixel) { found_ball = true; } } } if (found_ball) { // Then, identify if this pixel falls in the left, mid, or right side of the image int imgThird = img.width/3; int col = step/3; if (col < imgThird) { drive_robot(0.1, 0.1); // Left } else if (col >= imgThird && col < 2*imgThird) { drive_robot(0.5, 0.0); // Mid } else if (col >= 2*imgThird) { drive_robot(0.1, -0.1); //Right } // Depending on the white ball position, call the drive_bot function and pass velocities to it } else { // Request a stop when there's no white ball seen by the camera drive_robot(0.0, 0.0); //Stop } } int main(int argc, char** argv) { // Initialize the process_image node and create a handle to it ros::init(argc, argv, "process_image"); ros::NodeHandle n; // Define a client service capable of requesting services from command_robot client = n.serviceClient<ball_chaser::DriveToTarget>("/ball_chaser/command_robot"); // Subscribe to /camera/rgb/image_raw topic to read the image data inside the process_image_callback function ros::Subscriber sub1 = n.subscribe("/camera/rgb/image_raw", 10, process_image_callback); // Handle ROS communication events ros::spin(); return 0; }
[ "prashanth.dhundra@gmail.com" ]
prashanth.dhundra@gmail.com
c041971acb0f6b16a83709d9d80bef411f320c48
b1d297edf427da52dc93e725154565f4f1ecc29d
/test_templatemode.h
b46567d0f7ccd8db498da61d709ec9ea0a5a2114
[]
no_license
Chenyanglu99/TestTuple
0c3a8ac048dcc4bde10201fa79b952b26a278617
8b8cf44ac3289c253153fb9f2f2da75659857076
refs/heads/master
2023-02-10T00:29:21.628247
2021-01-08T06:42:17
2021-01-08T06:42:17
327,820,604
0
0
null
null
null
null
UTF-8
C++
false
false
2,627
h
#pragma once #include <iostream> #include <typeinfo> //可变模板类 //模板偏特化和递归方式来展开参数包 //前向声明 /** * \brief 展开可变参数包测试 * \tparam Args 可变参数包 */ template <typename... Args> struct sum; //基本定义 template <typename First, typename... Rest> struct sum<First, Rest...> { enum { value = sum<First>::value + sum<Rest...>::value }; }; //递归终止 template <typename Last> struct sum<Last> { enum { value = sizeof(Last) }; }; //继承方式展开参数包 /** * \brief 整数序列的定于 */ template <int...> struct index_seq { }; /** * \brief 继承方式,开始展开参数包 * \tparam N * \tparam Indexes 参数包 */ template <int N, int... Indexes> struct make_indexes : make_indexes<N - 1, N - 1, Indexes...> { }; /** * \brief 模板特化,终止展开参数包的条件 * \tparam Indexes */ template <int... Indexes> struct make_indexes<0, Indexes...> { typedef index_seq<Indexes...> type; }; /** * \brief 测试继承方式解开参数包 */ inline void test_tmp() { using T = make_indexes<3>::type; std::cout << typeid(T).name() << std::endl; } namespace my_namespace { template <typename T> T* Instance() { return new T(); } template <typename T, typename T0> T* Instance(T0 arg0) { return new T(arg0); } template <typename T, typename T0, typename T1> T* Instance(T0 arg0, T1 arg1) { return new T(arg0, arg1); } template <typename T, typename T0, typename T1, typename T2> T* Instance(T0 arg0, T1 arg1, T2 arg2) { return new T(arg0, arg1, arg2); } template <typename T, typename T0, typename T1, typename T2, typename T3> T* Instance(T0 arg0, T1 arg1, T2 arg2, T3 arg3) { return new T(arg0, arg1, arg2, arg3); } template <typename T, typename T0, typename T1, typename T2, typename T3, typename T4> T* Instance(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { return new T(arg0, arg1, arg2, arg3, arg4); } struct A { A(int) { } }; struct B { B(int, double) { } }; void instance(); } namespace my_namespace1 { struct A { A(int) { } }; struct B { B(int, double) { } }; //可变参数模板优化后的工厂函数 template<typename T, typename... Args> T* instance(Args&&... args) { return new T(std::forward<Args>(args)...); } void test_tmp_instance(); }
[ "46991689+Chenyanglu99@users.noreply.github.com" ]
46991689+Chenyanglu99@users.noreply.github.com
0df12f59e9df9b8aad60f6708e142db4a7ac214c
4dbaea97b6b6ba4f94f8996b60734888b163f69a
/TOJ/Super_A+B_Problem.cpp
6c77c3248525f6e05fae3490b111f5a36d35c35d
[]
no_license
Ph0en1xGSeek/ACM
099954dedfccd6e87767acb5d39780d04932fc63
b6730843ab0455ac72b857c0dff1094df0ae40f5
refs/heads/master
2022-10-25T09:15:41.614817
2022-10-04T12:17:11
2022-10-04T12:17:11
63,936,497
2
0
null
null
null
null
UTF-8
C++
false
false
656
cpp
#include <iostream> #include <stdio.h> #include <algorithm> #include <string.h> using namespace std; int arr[30]; int n, m; int sum; bool dfs(int x) { if(sum == m) return true; if(x >= n) return false; sum += arr[x]; if(dfs(x+1)) return true; sum -= arr[x]; if(dfs(x+1)) return true; return false; } int main() { while(~scanf("%d%d", &n, &m) && n != 0) { sum = 0; for(int i = 0; i < n; i++) scanf("%d", &arr[i]); if(dfs(0)) puts("Yes"); else puts("No"); } return 0; }
[ "54panguosheng@gmail.com" ]
54panguosheng@gmail.com
988bae117aab4f248e3190ee4b92c563aa4012f7
966ebdf53c9c7ceabb511f6af56701baf7e6fdfa
/Fraccion.h
3f0c6c95aeb58f6f69b5f4206bf6f04d5b3e89ac
[]
no_license
javierfuentesm/ReductorFracciones
3f96057b56f34e03e7604f15ca3b6052a8a243db
73f43e72027595643ad9f6e896b82150fd532d90
refs/heads/master
2021-01-06T06:54:44.621702
2020-02-18T00:56:07
2020-02-18T00:56:07
241,239,652
0
0
null
null
null
null
UTF-8
C++
false
false
351
h
// // Created by Javier Fuentes Mora on 17/02/20. // #ifndef FRACCION_FRACCION_H #define FRACCION_FRACCION_H class Fraccion { private: int numerador{}; int denominador{}; public: Fraccion(); void inicializar(int num, int denom); double division(); static int reduce(int num, int denom); }; #endif //FRACCION_FRACCION_H
[ "javier.fuentesm@hotmail.com" ]
javier.fuentesm@hotmail.com
4b5f417bb987f9ea9cedef228a3fd3128bd288c3
e3c02d2605b48855ebe2756dd7f055753cbf4e79
/BattleTank/Source/BattleTank/TankMovementComponent.cpp
7250bfac34a4e91e75a9de98dea2e42efc1ab339
[]
no_license
StarwindI/BattleTank
befaf71b1d199903b254fba7f76f171304332eb5
6b2153b9af07fb3bb27f30108eacd247eec8d7c6
refs/heads/master
2021-01-23T08:21:33.148858
2017-07-19T12:10:48
2017-07-19T12:10:48
86,507,082
0
0
null
null
null
null
UTF-8
C++
false
false
2,044
cpp
#include "BattleTank.h" #include "TankTrack.h" #include "TankMovementComponent.h" void UTankMovementComponent::SetTracks(UTankTrack* ALeftTrack, UTankTrack* ARightTrack) { LeftTrack = ALeftTrack; RightTrack = ARightTrack; } void UTankMovementComponent::IntendMoveForward(float Throw) { LeftTrack->SetThrottle(Throw); RightTrack->SetThrottle(Throw); } void UTankMovementComponent::IntendTurnLeft(float Throw) { LeftTrack->SetThrottle(-Throw); RightTrack->SetThrottle(Throw); } void UTankMovementComponent::IntendTurnRight(float Throw) { LeftTrack->SetThrottle(Throw); RightTrack->SetThrottle(-Throw); } void UTankMovementComponent::IntendMove(FVector TargetLocation) { FVector SelfForward = GetOwner()->GetActorForwardVector().GetSafeNormal(); FRotator DeltaRotator = SelfForward.Rotation() - TargetLocation.Rotation(); if (DeltaRotator.Yaw > 180) { DeltaRotator.Yaw -= 360; } if (DeltaRotator.Yaw < -180) { DeltaRotator.Yaw += 360; } LeftTrack->SetThrottle(FMath::Cos(DeltaRotator.Yaw / 180 * 3.1415926) - FMath::Sin(DeltaRotator.Yaw / 180 * 3.1415926)); RightTrack->SetThrottle(FMath::Cos(DeltaRotator.Yaw / 180 * 3.1415926) + FMath::Sin(DeltaRotator.Yaw / 180 * 3.1415926)); } bool UTankMovementComponent::IntendRotate(FVector TargetLocation) { FVector SelfForward = GetOwner()->GetActorForwardVector().GetSafeNormal(); FRotator DeltaRotator = SelfForward.Rotation() - TargetLocation.Rotation(); if (DeltaRotator.Yaw > 180) { DeltaRotator.Yaw -= 360; } if (DeltaRotator.Yaw < -180) { DeltaRotator.Yaw += 360; } LeftTrack->SetThrottle(-FMath::Sin(DeltaRotator.Yaw / 180 * 3.1415926)); RightTrack->SetThrottle(FMath::Sin(DeltaRotator.Yaw / 180 * 3.1415926)); return FMath::Abs(DeltaRotator.Yaw) < 10; } void UTankMovementComponent::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed) { IntendMove(MoveVelocity.GetSafeNormal()); } bool UTankMovementComponent::RequestDirectRotate(const FVector & MoveVelocity, bool bForceMaxSpeed) { return IntendRotate(MoveVelocity.GetSafeNormal()); }
[ "starwind@pisem.net" ]
starwind@pisem.net
86af1513393466d2f2b0a6763b63e3e346a8073b
1f41b828fb652795482cdeaac1a877e2f19c252a
/maya_plugins/_history/sgOpenGlModeler/SGMainWindow.cpp
b87669cdff3a7f9a9dfddb545903ac8dc7fe96d2
[]
no_license
jonntd/mayadev-1
e315efe582ea433dcf18d7f1e900920f5590b293
f76aeecb592df766d05a4e10fa2c2496f0310ca4
refs/heads/master
2021-05-02T07:16:17.941007
2018-02-05T03:55:12
2018-02-05T03:55:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
#include "SGMainWindow.h" #include "SGPrintf\SGPrintf.h" SGMainWindow::SGMainWindow(QWidget* parent) : QMainWindow( parent ) { m_ptrMesh.resize(0); //sgPrintf("window id : %d", winId()); } SGMainWindow::~SGMainWindow(){ m_ptrMesh.clear(); delete m_centralWidget; } void SGMainWindow::closeEvent(QCloseEvent* evt){ this->~SGMainWindow(); } void SGMainWindow::setCentralWidget(QWidget* widget){ QMainWindow::setCentralWidget(widget); m_centralWidget = widget; } void SGMainWindow::appendMesh( SGMesh* mesh ) { m_ptrMesh.push_back(mesh); } void SGMainWindow::setCamera(SGCam* cam) { m_ptrCam = cam; }
[ "kimsung9k@naver.com" ]
kimsung9k@naver.com
96be72025babafd9fe05c740ed907ba01e0774c3
957e65559f1ff4d9027c6ee11700eb9994295e39
/cs439_f20_pb_beastbla/cs439_f20_testFS_yijing/yijing.cc
887223db92e31ef0ea73d8a7da31d872198b9971
[]
no_license
DD-1111/GheithOS-and-journalism-in-ext2
28133c71773551b7ac99af7b9415d8e526d20888
1b38f35ab12195c6aba6f9a2b3cc7382cd4c6663
refs/heads/master
2023-04-06T15:33:37.791249
2021-04-15T12:44:42
2021-04-15T12:44:42
320,808,605
0
1
null
null
null
null
UTF-8
C++
false
false
2,897
cc
#include "ide.h" #include "ext2.h" #include "shared.h" #include "libk.h" /* This is test case use t0's method show(). 1.Checks if we can't find the file in nested directory and prints out file in each level. 2.Check non exist file */ void show(const char* name, Shared<Node> node, bool show) { Debug::printf("*** looking at %s\n",name); if (node == nullptr) { Debug::printf("*** does not exist\n"); return; } if (node->is_dir()) { Debug::printf("*** is a directory\n"); Debug::printf("*** contains %d entries\n",node->entry_count()); Debug::printf("*** has %d links\n",node->n_links()); } else if (node->is_symlink()) { Debug::printf("*** is a symbolic link\n"); auto sz = node->size_in_bytes(); Debug::printf("*** link size is %d\n",sz); auto buffer = new char[sz+1]; buffer[sz] = 0; node->get_symbol(buffer); Debug::printf("*** => %s\n",buffer); } else if (node->is_file()) { // Debug::printf("*** is a file\n"); auto sz = node->size_in_bytes(); // Debug::printf("*** contains %d bytes\n",sz); // Debug::printf("*** has %d links\n",node->n_links()); if (show) { auto buffer = new char[sz+1]; buffer[sz] = 0; auto cnt = node->read_all(0,sz,buffer); CHECK(sz == cnt); CHECK(K::strlen(buffer) == cnt); // can't just print the string because there is a 1000 character limit // on the output string length. for (uint32_t i=0; i<cnt; i++) { Debug::printf("%c",buffer[i]); } delete[] buffer; Debug::printf("\n"); } } else { Debug::printf("*** is of type %d\n",node->get_type()); } } /* Called by one CPU */ void kernelMain(void) { // IDE device #1 auto ide = Shared<Ide>::make(1); // We expect to find an ext2 file system there auto fs = Shared<Ext2>::make(ide); auto root = fs->root; //files in ./yijing.dir show("/file1.txt",fs->find(root,"file1.txt"),true); Debug::printf("\n"); show("/file2.txt",fs->find(root,"file2.txt"),true); Debug::printf("\n"); auto dir1 = fs->find(root, "dir1"); auto dir2 = fs->find(dir1, "dir2"); auto dir3 = fs->find(dir2, "dir3"); auto dir4 = fs->find(dir3, "dir4"); show("/test",fs->find(root,"test"),true); Debug::printf("\n"); show("/dir1/a.txt",fs->find(dir1,"a.txt"),true); Debug::printf("\n"); show("/dir1/dir2/b.txt",fs->find(dir2,"b.txt"),true); Debug::printf("\n"); show("/dir1/dir2/dir3/c.txt",fs->find(dir3,"c.txt"),true); Debug::printf("\n"); show("/dir1/dir2/dir3/dir4/d.txt",fs->find(dir4,"d.txt"),true); Debug::printf("\n"); Debug::printf("*** PASS!\n"); }
[ "56623337+DD-1111@users.noreply.github.com" ]
56623337+DD-1111@users.noreply.github.com
afdd50d20b907157ff1835abd75c33d450a5126a
8a0474e70576f873db35706b3e931c940a9402ec
/sources/projet/src/Mesh.cpp
279247a3ab95ba5a0184e79552059ae65b9d8d8f
[]
no_license
Michmo/pghp
dbbd033042e1bf66223d86f4f629f292c4fb5232
b408fe81155b36e1a9dffaa410819833e2278a21
refs/heads/master
2016-09-05T12:04:10.325027
2012-04-20T14:42:26
2012-04-20T14:42:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,976
cpp
// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr> #include "Mesh.h" #include "Shader.h" #include <iostream> #include <fstream> #include <limits> #include <QCoreApplication> #include <Eigen/Geometry> #include "../ObjFormat/ObjFormat.h" using namespace Eigen; using namespace std; Mesh::Mesh(const std::string& filename) : mIsInitialized(false) { std::string ext = filename.substr(filename.size()-3,3); if(ext=="off" || ext=="OFF") loadOFF(filename); else if(ext=="obj" || ext=="OBJ") loadOBJ(filename); else std::cerr << "Mesh: extension \'" << ext << "\' not supported." << std::endl; } void Mesh::loadOFF(const std::string& filename) { std::ifstream in(filename.c_str(),std::ios::in); if(!in) { std::cerr << "File not found " << filename << std::endl; return; } std::string header; in >> header; // check the header file if(header != "OFF") { std::cerr << "Wrong header = " << header << std::endl; return; } int nofVertices, nofFaces, inull; int nb, id0, id1, id2; Vector3 v; in >> nofVertices >> nofFaces >> inull; for(int i=0 ; i<nofVertices ; ++i) { in >> v.x() >> v.y() >> v.z(); mVertices.push_back(v); } for(int i=0 ; i<nofFaces ; ++i) { in >> nb >> id0 >> id1 >> id2; assert(nb==3); mFaces.push_back(FaceIndex(id0, id1, id2)); } in.close(); } void Mesh::loadOBJ(const std::string& filename) { ObjMesh* pRawObjMesh = ObjMesh::LoadFromFile(filename); if (!pRawObjMesh) { std::cerr << "Mesh::loadObj: error loading file " << filename << "." << std::endl; return; } // Makes sure we have an indexed face set ObjMesh* pObjMesh = pRawObjMesh->createIndexedFaceSet(Obj::Options(Obj::AllAttribs|Obj::Triangulate)); delete pRawObjMesh; pRawObjMesh = 0; // copy vertices mVertices.resize(pObjMesh->positions.size()); for (int i=0 ; i<pObjMesh->positions.size() ; ++i) { mVertices[i] = Vertex(Vector3f(pObjMesh->positions[i])); if(!pObjMesh->texcoords.empty()) { mVertices[i].texcoord = Vector2f(pObjMesh->texcoords[i]); // std::cerr << i << ": " << Vector2f(pObjMesh->texcoords[i]).transpose() << "\n"; } if(!pObjMesh->normals.empty()) { mVertices[i].normal = Vector3f(pObjMesh->normals[i]); //std::cerr << i << ": " << Vector3f(pObjMesh->normals[i]).transpose() << "\n"; } } // copy faces for (int smi=0 ; smi<pObjMesh->getNofSubMeshes() ; ++smi) { const ObjSubMesh* pSrcSubMesh = pObjMesh->getSubMesh(smi); mFaces.reserve(pSrcSubMesh->getNofFaces()); for (uint fid = 0 ; fid<pSrcSubMesh->getNofFaces() ; ++fid) { ObjConstFaceHandle srcFace = pSrcSubMesh->getFace(fid); mFaces.push_back(Vector3i(srcFace.vPositionId(0), srcFace.vPositionId(1), srcFace.vPositionId(2))); } } } Mesh::~Mesh() { if(mIsInitialized) { glDeleteBuffers(1,&mVertexBufferId); glDeleteBuffers(1,&mIndexBufferId); } } void Mesh::makeUnitary() { // computes the lowest and highest coordinates of the axis aligned bounding box, // which are equal to the lowest and highest coordinates of the vertex positions. Eigen::Vector3f lowest, highest; lowest.fill(std::numeric_limits<float>::max()); // "fill" sets all the coefficients of the vector to the same value highest.fill(-std::numeric_limits<float>::max()); for(VertexArray::iterator v_iter = mVertices.begin() ; v_iter!=mVertices.end() ; ++v_iter) { // - v_iter is an iterator over the elements of mVertices, // an iterator behaves likes a pointer, it has to be dereferenced (*v_iter, or v_iter->) to access the referenced element. // - Here the .aray().min(_) and .array().max(_) operators work per component. // lowest = lowest.array().min(v_iter->position.array()); highest = highest.array().max(v_iter->position.array()); } // TODO: appliquer une transformation à tous les sommets de mVertices de telle sorte // que la boite englobante de l'objet soit centrée en (0,0,0) et que sa plus grande dimension soit de 1 Eigen::Vector3f center = (lowest+highest)/2.0; float m = (highest-lowest).maxCoeff(); for(VertexArray::iterator v_iter = mVertices.begin() ; v_iter!=mVertices.end() ; ++v_iter) v_iter->position = (v_iter->position - center) / m + Vector3f::UnitZ() / 2; } void Mesh::drawGeometry(int prg_id) { if(!mIsInitialized) { mIsInitialized = true; // this is the first call to drawGeometry // => create the BufferObjects and copy the related data into them. glGenBuffers(1,&mVertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferId); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*mVertices.size(), mVertices[0].position.data(), GL_DYNAMIC_DRAW); glGenBuffers(1,&mIndexBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(FaceIndex)*mFaces.size(), mFaces[0].data(), GL_DYNAMIC_DRAW); } glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBufferId); int vertex_loc = glGetAttribLocation(prg_id, "vtx_position"); int normal_loc = glGetAttribLocation(prg_id, "vtx_normal"); int texcoord_loc = glGetAttribLocation(prg_id, "vtx_texcoord"); // specify the vertex data if(vertex_loc>=0) { glVertexAttribPointer(vertex_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(vertex_loc); } if(normal_loc>=0) { glVertexAttribPointer(normal_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(Vector3f)); glEnableVertexAttribArray(normal_loc); } if(texcoord_loc>=0) { glVertexAttribPointer(texcoord_loc, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(2*sizeof(Vector3f))); glEnableVertexAttribArray(texcoord_loc); } // send the geometry glDrawElements(GL_TRIANGLES, 3*mFaces.size(), GL_UNSIGNED_INT, (void*)0); // at this point the mesh has been drawn and raserized into the framebuffer! if(vertex_loc>=0) glDisableVertexAttribArray(vertex_loc); if(normal_loc>=0) glDisableVertexAttribArray(normal_loc); if(texcoord_loc>=0) glDisableVertexAttribArray(texcoord_loc); } void Mesh::Initialize() { if(!mIsInitialized) { mIsInitialized = true; // this is the first call to drawGeometry // => create the BufferObjects and copy the related data into them. glGenBuffers(1,&mVertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferId); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*mVertices.size(), mVertices[0].position.data(), GL_DYNAMIC_DRAW); glGenBuffers(1,&mIndexBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(FaceIndex)*mFaces.size(), mFaces[0].data(), GL_DYNAMIC_DRAW); } } void Mesh::drawGeometry(int prg_id) const { glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBufferId); int vertex_loc = glGetAttribLocation(prg_id, "vtx_position"); int normal_loc = glGetAttribLocation(prg_id, "vtx_normal"); int texcoord_loc = glGetAttribLocation(prg_id, "vtx_texcoord"); // specify the vertex data if(vertex_loc>=0) { glVertexAttribPointer(vertex_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(vertex_loc); } if(normal_loc>=0) { glVertexAttribPointer(normal_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(Vector3f)); glEnableVertexAttribArray(normal_loc); } if(texcoord_loc>=0) { glVertexAttribPointer(texcoord_loc, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(2*sizeof(Vector3f))); glEnableVertexAttribArray(texcoord_loc); } // send the geometry glDrawElements(GL_TRIANGLES, 3*mFaces.size(), GL_UNSIGNED_INT, (void*)0); // at this point the mesh has been drawn and raserized into the framebuffer! if(vertex_loc>=0) glDisableVertexAttribArray(vertex_loc); if(normal_loc>=0) glDisableVertexAttribArray(normal_loc); if(texcoord_loc>=0) glDisableVertexAttribArray(texcoord_loc); } void Mesh::computeNormals() { // pass 1: set the normal to 0 for(VertexArray::iterator v_iter = mVertices.begin() ; v_iter!=mVertices.end() ; ++v_iter) v_iter->normal.setZero(); // pass 2: compute face normals and accumulate for(FaceIndexArray::iterator f_iter = mFaces.begin() ; f_iter!=mFaces.end() ; ++f_iter) { Vector3f v0 = mVertices[(*f_iter)(0)].position; Vector3f v1 = mVertices[(*f_iter)(1)].position; Vector3f v2 = mVertices[(*f_iter)(2)].position; Vector3f n = (v1-v0).cross(v2-v0).normalized(); mVertices[(*f_iter)(0)].normal += n; mVertices[(*f_iter)(1)].normal += n; mVertices[(*f_iter)(2)].normal += n; } // pass 3: normalize for(VertexArray::iterator v_iter = mVertices.begin() ; v_iter!=mVertices.end() ; ++v_iter) v_iter->normal.normalize(); } float Mesh::findZ(float x, float y) { int cx, cy, fx, fy; cx = ceil(x); cy = ceil(y); fx = floor(x); fy = floor(y); float z = mVertices[fy+fx*640].position.z(); z += mVertices[fy+cx*640].position.z(); z += mVertices[cy+fx*640].position.z(); z += mVertices[cy+cx*640].position.z(); z /= 4; //cout << "x = " << x << "y = " << y << "z = " << z << endl; return z; } Eigen::Vector3f Mesh::findNormal(float x, float y){ Eigen::Vector3f normal = Eigen::Vector3f::UnitX(); int cx, cy, fx, fy; cx = ceil(x); cy = ceil(y); fx = floor(x); fy = floor(y); normal.x() = mVertices[fy+fx*640].normal.x() + mVertices[fy+cx*640].normal.x() + mVertices[cy+fx*640].normal.x() + mVertices[cy+cx*640].normal.x(); normal.x() = mVertices[fy+fx*640].normal.y() + mVertices[fy+cx*640].normal.y() + mVertices[cy+fx*640].normal.y() + mVertices[cy+cx*640].normal.y(); normal.x() = mVertices[fy+fx*640].normal.z() + mVertices[fy+cx*640].normal.z() + mVertices[cy+fx*640].normal.z() + mVertices[cy+cx*640].normal.z(); return normal; } Eigen::Matrix4f Mesh::orientMesh(const Eigen::Vector3f& position, const Eigen::Vector3f& target, const Eigen::Vector3f& up){ Eigen::Matrix4f tmp; Matrix3f R; Eigen::Vector3f vz = (position - target).normalized(); Eigen::Vector3f vx = (up.cross(vz)).normalized(); Eigen::Vector3f vy = (vz.cross(vx)).normalized(); R.col(2)=vz; R.col(0)=vx; R.col(1)=vy; tmp.block<3,3>(0,0)=R.transpose(); tmp.block<3,1>(0,3)=-(R.transpose()*position); return tmp; }
[ "mmorgan.etu@gmail.com" ]
mmorgan.etu@gmail.com
b4d377e60a74a6fb3feb53895c56cd06cea2af1d
d6739e417fe69a8b8b57767b3edf8102caf9da60
/src/simple_fifo.cpp
f02ae5351b07d013968310b3474751d3d65999aa
[]
no_license
derekdm3/systemc
fdcf54743a11ae19895e41a231fead77c0293841
0d2a74dc64c0552dd83a8606f8b24e4e3b3a1b69
refs/heads/master
2021-01-22T06:49:43.536352
2013-07-15T04:10:03
2013-07-15T04:10:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
679
cpp
//! File: simple_fifo.cpp #include "simple_fifo.hpp" simple_fifo::simple_fifo(sc_core::sc_module_name name) : sc_channel(name) , num_elements(0) , first(0) { // noop } void simple_fifo::write(char c) { if(MAX == num_elements) { wait(read_event); } data[(first + num_elements) % MAX] = c; num_elements++; write_event.notify(); } void simple_fifo::read(char& c) { if(0 == num_elements) { wait(write_event); } c = data[first]; num_elements--; first = (first + 1) % MAX; read_event.notify(); } void simple_fifo::reset() { num_elements = first = 0; } int simple_fifo::num_available() { return num_elements; }
[ "derekdm3@yahoo.com" ]
derekdm3@yahoo.com
e4582b48b0b8d1710d4598f140cee859d4e02544
e96ecf4ba068cf79ad1a7f544b513e7c79d70a42
/ejemplo.cpp
9e88b372b5f87182dcd5be03290b9c7e3c7f2b71
[]
no_license
jogalvisper/Prog3
ad502f2bdc4871aaa27e8847d47f14f4f315f850
23e097cffe54a99f0e86100ad1e012c4cf20a1ba
refs/heads/master
2023-03-12T22:25:52.872469
2021-03-03T23:48:58
2021-03-03T23:48:58
344,297,226
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
// Calcular los números primos entre 1 y 100 // incluir las librerías que vamos a usar #include <iostream> #include <cmath> void print_even(int nmin, int nmax); //declaración int main(void) { const int m = 1; const int n =20; print_even(m, n); print_even(m/2, 2*n); return 0; } void print_even(int nmin, int nmax) //implementación { for(int ii =nmin; ii <= nmax ; ii=ii+1){ if (ii%2 == 0) { std::cout << ii << " "; } } std::cout << "\n"; }
[ "jogalvisp@unal.edu.co" ]
jogalvisp@unal.edu.co
af300f5c3018c304dc09bbefaffa5d8453107e68
a81111ea5d673188bf19e8564b17c5242ad2a782
/test/test_avg_pool.in.cpp
b498294aa77202cbc6b379aa363e6a1cc64c65d2
[ "Apache-2.0" ]
permissive
liuwenbo3/he-transformer
83b98a2ded6f3b862b376db1ef454ca999fc00f4
907419e937f0e9a3276c6c0583f43bd7098286fe
refs/heads/master
2020-05-20T19:16:47.944580
2019-04-18T20:52:26
2019-04-18T20:52:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,766
cpp
//***************************************************************************** // Copyright 2018-2019 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 "he_backend.hpp" #include "ngraph/ngraph.hpp" #include "test_util.hpp" #include "util/all_close.hpp" #include "util/ndarray.hpp" #include "util/test_control.hpp" #include "util/test_tools.hpp" using namespace std; using namespace ngraph; static string s_manifest = "${MANIFEST}"; NGRAPH_TEST(${BACKEND_NAME}, avg_pool_1d_1channel_1image) { auto backend = runtime::Backend::create("${BACKEND_NAME}"); Shape shape_a{1, 1, 14}; Shape window_shape{3}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_r{1, 1, 12}; float denom = 3.0; auto t = make_shared<op::AvgPool>(A, window_shape); auto f = make_shared<Function>(t, ParameterVector{A}); // Create some tensors for input/output auto tensors_list = generate_plain_cipher_tensors({t}, {A}, backend.get(), true); for (auto tensors : tensors_list) { auto results = get<0>(tensors); auto inputs = get<1>(tensors); auto a = inputs[0]; auto result = results[0]; copy_data( a, test::NDArray<float, 3>{{{0, 1, 0, 2, 1, 0, 3, 2, 0, 0, 2, 0, 0, 0}}} .get_vector()); auto handle = backend->compile(f); handle->call_with_validate({result}, {a}); EXPECT_TRUE(all_close(test::NDArray<float, 3>( {{{1 / denom, 3 / denom, 3 / denom, 3 / denom, 4 / denom, 5 / denom, 5 / denom, 2 / denom, 2 / denom, 2 / denom, 2 / denom, 0 / denom}}}) .get_vector(), read_vector<float>(result))); } } NGRAPH_TEST(${BACKEND_NAME}, avg_pool_1d_1channel_2image) { auto backend = runtime::Backend::create("${BACKEND_NAME}"); Shape shape_a{2, 1, 14}; Shape window_shape{3}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_r{2, 1, 12}; float denom = 3.0; auto t = make_shared<op::AvgPool>(A, window_shape); auto f = make_shared<Function>(t, ParameterVector{A}); // Create some tensors for input/output auto tensors_list = generate_plain_cipher_tensors({t}, {A}, backend.get(), true); for (auto tensors : tensors_list) { auto results = get<0>(tensors); auto inputs = get<1>(tensors); auto a = inputs[0]; auto result = results[0]; copy_data(a, test::NDArray<float, 3>( {{{0, 1, 0, 2, 1, 0, 3, 2, 0, 0, 2, 0, 0, 0}}, {{0, 2, 1, 1, 0, 0, 0, 2, 0, 1, 0, 0, 1, 2}}}) .get_vector()); auto handle = backend->compile(f); handle->call_with_validate({result}, {a}); EXPECT_TRUE(all_close(test::NDArray<float, 3>( {{{1 / denom, 3 / denom, 3 / denom, 3 / denom, 4 / denom, 5 / denom, 5 / denom, 2 / denom, 2 / denom, 2 / denom, 2 / denom, 0 / denom}}, {{3 / denom, 4 / denom, 2 / denom, 1 / denom, 0 / denom, 2 / denom, 2 / denom, 3 / denom, 1 / denom, 1 / denom, 1 / denom, 3 / denom}}}) .get_vector(), read_vector<float>(result))); } } NGRAPH_TEST(${BACKEND_NAME}, avg_pool_1d_1channel_2image_batched) { auto backend = runtime::Backend::create("${BACKEND_NAME}"); auto he_backend = static_cast<runtime::he::HEBackend*>(backend.get()); Shape shape_a{2, 1, 14}; Shape window_shape{3}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_r{2, 1, 12}; float denom = 3.0; auto t = make_shared<op::AvgPool>(A, window_shape); auto f = make_shared<Function>(t, ParameterVector{A}); // Create some tensors for input/output auto t_a = he_backend->create_batched_cipher_tensor(element::f32, shape_a); auto t_result = he_backend->create_batched_cipher_tensor(element::f32, shape_r); copy_data(t_a, test::NDArray<float, 3>( {{{0, 1, 0, 2, 1, 0, 3, 2, 0, 0, 2, 0, 0, 0}}, {{0, 2, 1, 1, 0, 0, 0, 2, 0, 1, 0, 0, 1, 2}}}) .get_vector()); auto handle = backend->compile(f); handle->call_with_validate({t_result}, {t_a}); EXPECT_TRUE(all_close( test::NDArray<float, 3>( {{{1 / denom, 3 / denom, 3 / denom, 3 / denom, 4 / denom, 5 / denom, 5 / denom, 2 / denom, 2 / denom, 2 / denom, 2 / denom, 0 / denom}}, {{3 / denom, 4 / denom, 2 / denom, 1 / denom, 0 / denom, 2 / denom, 2 / denom, 3 / denom, 1 / denom, 1 / denom, 1 / denom, 3 / denom}}}) .get_vector(), generalized_read_vector<float>(t_result))); } NGRAPH_TEST(${BACKEND_NAME}, avg_pool_1d_2channel_2image) { auto backend = runtime::Backend::create("${BACKEND_NAME}"); Shape shape_a{2, 2, 14}; Shape window_shape{3}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_r{2, 2, 12}; float denom = 3.0; auto t = make_shared<op::AvgPool>(A, window_shape); auto f = make_shared<Function>(t, ParameterVector{A}); // Create some tensors for input/output auto tensors_list = generate_plain_cipher_tensors({t}, {A}, backend.get(), true); for (auto tensors : tensors_list) { auto results = get<0>(tensors); auto inputs = get<1>(tensors); auto a = inputs[0]; auto result = results[0]; copy_data(a, test::NDArray<float, 3>( {{{0, 1, 0, 2, 1, 0, 3, 2, 0, 0, 2, 0, 0, 0}, {0, 0, 0, 2, 0, 0, 2, 3, 0, 1, 2, 0, 1, 0}}, {{0, 2, 1, 1, 0, 0, 0, 2, 0, 1, 0, 0, 1, 2}, {2, 1, 0, 0, 1, 0, 2, 0, 0, 0, 1, 1, 2, 0}}}) .get_vector()); auto handle = backend->compile(f); handle->call_with_validate({result}, {a}); EXPECT_TRUE(all_close(test::NDArray<float, 3>( {{{1 / denom, 3 / denom, 3 / denom, 3 / denom, 4 / denom, 5 / denom, 5 / denom, 2 / denom, 2 / denom, 2 / denom, 2 / denom, 0 / denom}, {0 / denom, 2 / denom, 2 / denom, 2 / denom, 2 / denom, 5 / denom, 5 / denom, 4 / denom, 3 / denom, 3 / denom, 3 / denom, 1 / denom}}, {{3 / denom, 4 / denom, 2 / denom, 1 / denom, 0 / denom, 2 / denom, 2 / denom, 3 / denom, 1 / denom, 1 / denom, 1 / denom, 3 / denom}, {3 / denom, 1 / denom, 1 / denom, 1 / denom, 3 / denom, 2 / denom, 2 / denom, 0 / denom, 1 / denom, 2 / denom, 4 / denom, 3 / denom}}}) .get_vector(), read_vector<float>(result))); } } NGRAPH_TEST(${BACKEND_NAME}, avg_pool_2d_2channel_2image) { auto backend = runtime::Backend::create("${BACKEND_NAME}"); Shape shape_a{2, 2, 5, 5}; Shape window_shape{2, 3}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_r{2, 2, 4, 3}; float denom = 2 * 3; auto t = make_shared<op::AvgPool>(A, window_shape); auto f = make_shared<Function>(t, ParameterVector{A}); // Create some tensors for input/output auto tensors_list = generate_plain_cipher_tensors({t}, {A}, backend.get(), true); for (auto tensors : tensors_list) { auto results = get<0>(tensors); auto inputs = get<1>(tensors); auto a = inputs[0]; auto result = results[0]; copy_data(a, test::NDArray<float, 4>({{{{0, 1, 0, 2, 1}, // img 0 chan 0 {0, 3, 2, 0, 0}, {2, 0, 0, 0, 1}, {2, 0, 1, 1, 2}, {0, 2, 1, 0, 0}}, {{0, 0, 0, 2, 0}, // img 0 chan 1 {0, 2, 3, 0, 1}, {2, 0, 1, 0, 2}, {3, 1, 0, 0, 0}, {2, 0, 0, 0, 0}}}, {{{0, 2, 1, 1, 0}, // img 1 chan 0 {0, 0, 2, 0, 1}, {0, 0, 1, 2, 3}, {2, 0, 0, 3, 0}, {0, 0, 0, 0, 0}}, {{2, 1, 0, 0, 1}, // img 1 chan 1 {0, 2, 0, 0, 0}, {1, 1, 2, 0, 2}, {1, 1, 1, 0, 1}, {1, 0, 0, 0, 2}}}}) .get_vector()); auto handle = backend->compile(f); handle->call_with_validate({result}, {a}); EXPECT_TRUE( all_close(test::NDArray<float, 4>( {{{{6 / denom, 8 / denom, 5 / denom}, // img 0 chan 0 {7 / denom, 5 / denom, 3 / denom}, {5 / denom, 2 / denom, 5 / denom}, {6 / denom, 5 / denom, 5 / denom}}, {{5 / denom, 7 / denom, 6 / denom}, // img 0 chan 1 {8 / denom, 6 / denom, 7 / denom}, {7 / denom, 2 / denom, 3 / denom}, {6 / denom, 1 / denom, 0 / denom}}}, {{{5 / denom, 6 / denom, 5 / denom}, // img 1 chan 0 {3 / denom, 5 / denom, 9 / denom}, {3 / denom, 6 / denom, 9 / denom}, {2 / denom, 3 / denom, 3 / denom}}, {{5 / denom, 3 / denom, 1 / denom}, // img 1 chan 1 {6 / denom, 5 / denom, 4 / denom}, {7 / denom, 5 / denom, 6 / denom}, {4 / denom, 2 / denom, 4 / denom}}}}) .get_vector(), read_vector<float>(result))); } } NGRAPH_TEST(${BACKEND_NAME}, avg_pool_2d_1channel_1image_strided) { auto backend = runtime::Backend::create("${BACKEND_NAME}"); Shape shape_a{1, 1, 8, 8}; Shape window_shape{2, 3}; auto window_movement_strides = Strides{3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_r{1, 1, 3, 3}; float denom = 2 * 3; auto t = make_shared<op::AvgPool>(A, window_shape, window_movement_strides); auto f = make_shared<Function>(t, ParameterVector{A}); // Create some tensors for input/output auto tensors_list = generate_plain_cipher_tensors({t}, {A}, backend.get(), true); for (auto tensors : tensors_list) { auto results = get<0>(tensors); auto inputs = get<1>(tensors); auto a = inputs[0]; auto result = results[0]; copy_data(a, test::NDArray<float, 4>({{{{0, 1, 0, 2, 1, 2, 0, 0}, {0, 3, 2, 0, 0, 0, 1, 0}, {2, 0, 0, 0, 1, 0, 0, 0}, {2, 0, 1, 1, 2, 2, 3, 0}, {0, 2, 1, 0, 0, 0, 1, 0}, {2, 0, 3, 1, 0, 0, 0, 0}, {1, 2, 0, 0, 0, 1, 2, 0}, {1, 0, 2, 0, 0, 0, 1, 0}}}}) .get_vector()); auto handle = backend->compile(f); handle->call_with_validate({result}, {a}); EXPECT_TRUE(all_close( test::NDArray<float, 4>({{{{6 / denom, 5 / denom, 4 / denom}, {6 / denom, 5 / denom, 8 / denom}, {6 / denom, 2 / denom, 4 / denom}}}}) .get_vector(), read_vector<float>(result))); } }
[ "noreply@github.com" ]
liuwenbo3.noreply@github.com
b30b86fe467dd5fb6bf01483fd57e634bf629dbe
74283f990026f4bd71869c0f708b07bf2f8a0fcf
/makeref.cpp
7ddf65ffb83ed6cb5d75fd30cdae2ff4e29a8cc2
[]
no_license
lllamnyp/MakeREF
5f250d7825f2a0d2b13140aec686bf4414098516
3eff7f63508e4aaf76db6ebe838840119411c83e
refs/heads/master
2021-01-12T11:11:09.779079
2018-09-27T13:17:20
2018-09-27T13:17:20
72,859,326
0
0
null
null
null
null
UTF-8
C++
false
false
5,009
cpp
#include <stdio.h> #include <string.h> const int maxN = 2; // Max No. of experiments double x; // Wavenumber double y[8]; // Intensities int f_idx[maxN][8]; // File index int n = 2; char buffer[256]; int string_trim(char *source) // Trims a trailing backslash; path names must be terminated { // with spaces before closing double quote (implement in OPUS) char *end; size_t len = strlen(source); while ((len > 0) && ((source[len-1] == ' ') || (source[len-1] == '\\'))) len--; source[len] = '\0'; return 0; } double div0(double x, double y) // Handles division by 0.0 and negative intensity values { // Returns 1.0 for x<0 or y<=0 as this is meaningless in reflectivity if (y > 0.0 && x > 0.0) return x/y; else return 1.0; } int main ( int argc, char *argv[] ) { if (argc < 8) { printf("Usage: makeref.exe n Filename \"InputPath \" \"OutputPath \" \"SampleName \" T XPM1 [XPM2]\n"); printf("---\n"); printf("n Number of spectral ranges (1 or 2)\n"); printf("Filename Base name (without extension) of file to be saved\n"); printf("InputPath Path to input files (expected as: 0.dat, 1.dat, ...)\n"); printf("OutputPath Path to output file\n"); printf("SampleName Short description of measured sample\n"); printf("T Temperature\n"); printf("XPM1 Filename for XPM of first spectral range\n"); printf("XPM2 Filename for XPM of second spectral range (optional)\n"); printf("---\n"); printf("Any of the arguments containing spaces should be enclosed in double quotes. Arguments ending\n"); printf("with a backslash \'\\\' should have a trailing space before the closing quote (especially\n"); printf("applicable to InputPath and OutputPath."); return 1; } sscanf(argv[1], "%d", &n); // 1st arg: No. of exps (immediately stored in n) // 2nd arg: filename (stored in argv[2] without modification) string_trim(argv[3]); // 3rd arg: 2-col tables dir, backslash stripped string_trim(argv[4]); // 4th arg: measurement dir, backslash stripped // 5th arg: Sample name (argv[5]) // 6th arg: Temperature (argv[6], stored as string, without modification) // 7th arg: XPM file #1 (argv[7]) // 8th arg: optional, XPM file #2 (argv[8], if present and n=2) // ---------------------------------------------------------------------------------- if ((n != 1) && (n != 2)) return 1; // bullet-proofing (OPUS macro is implemented for n = 1 and n = 2) // ---------------------------------------------------------------------------------- // For loop to populate array of file numbers for (int i = 0; i < n; i++) // This is the spectral range index { for (int j = 0; j < 2; j++) // j=0 -> sample; j=1 -> mirror { for(int k = 0; k < 4; k++) // enumerate pola angles { f_idx[i][k + 4 * j] = k + 4 * i + 4 * j * n; // k for Pola angles; offset by 4i for spectral range; } // offset by 4jn to get to mirror from sample; } } FILE * ifile [n][8 * maxN]; // Declare input FILE array FILE * ofile; // and output file for (int i = 0; i < n; i++) // Loop to open input files { for (int j = 0; j < 8; j++) { sprintf(buffer, "%s\\%d.dat", argv[3],f_idx[i][j]); ifile[i][j] = fopen(buffer, "r"); } } sprintf(buffer, "%s\\%s.ref", argv[4], argv[2]); // Get output filename for writing ofile = fopen(buffer, "w"); // Open it fprintf(ofile, "Sample: %s; Temp = %s K;\nNo. of exps: %d\n", argv[5], argv[6], n); // Write header for (int i = 0; i < n; i++) // Write more header { fprintf(ofile, "Experiment %d: %s\n", i, argv[7 + i]); } for (int i = 0; i < n; i++) // Main loop to read/write (loop over spectral ranges) { fprintf(ofile, "\n\n"); // Precede each datablock with newline while (fscanf(ifile[i][0], "%lf%lf", &x, &y[0]) == 2) // While fscanf successfully obtains two elements from first file { // Exectue the loop for the first datablock for (int j = 1; j < 8; j++) // Already have first file, go through remaining seven { fscanf(ifile[i][j], "%*lf%lf", &y[j]); // Get only intensity value, wn is same for all files } fprintf(ofile, " % 12.2f", x); // Write wavenumber for (int j = 0; j < 8; j++) // Loop to write 8 intensity values { fprintf(ofile, " %+12.5E", y[j]); } for (int j = 0; j < 4; j++) // Loop to write four unnormalized reflectivity values { fprintf(ofile, " %+12.5E", div0(y[j],y[j+4])); } fprintf(ofile, "\n"); // End with newline } } for (int i = 0; i < n; i++) // Loop to close input files { for (int j = 0; j < 8; j++) { sprintf(buffer, "%s\\%d.dat", argv[3], f_idx[i][j]); fclose(ifile[i][j]); } } fclose(ofile); // Close output file return 0; }
[ "noreply@github.com" ]
lllamnyp.noreply@github.com
e5062e85c1e8f5bd0a0bd85910db91ca4abeb26b
861b9569e3f2e5ddd7b60bd0024c5b0c8df744ed
/cods/Stack.hpp
f101a44e4ae2eb025b26372fb91c476f34d414e1
[ "MIT" ]
permissive
hitchico/cods
33d5ce3d35b410f5859b3d8b29f08619f569cd1c
f9c031fde98651f1a4ef7faf62c65404fec731da
refs/heads/master
2021-01-20T04:08:48.445505
2016-03-26T22:39:42
2016-03-26T22:39:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
396
hpp
template <typename T> Stack<T>::Stack() : Stack<T>::Vector() { } template <typename T> void Stack<T>::push(const T &value) { Stack<T>::prepend(value); } template <typename T> T Stack<T>::pop() { return Stack<T>::takeFirst(); } template <typename T> T &Stack<T>::top() { return *Stack<T>::begin(); } template <typename T> const T &Stack<T>::top() const { return *Stack<T>::cbegin(); }
[ "msk@nullpointer.dk" ]
msk@nullpointer.dk
c11d03f7b5038d09119721bef2e17e8f2d820d7c
48b7c50ee5d51b10c5c4839c6c64fac7d1a05fa5
/include/cockpit/packet/protocol/MC_ADMIN_ASSASIN.h
fa69afbc99810d5b22e129e60f5b5dbf36c3130a
[ "MIT" ]
permissive
gogo-dev/GoGo
6b65da6188bdac846115dd5c2deede49ba862113
28ecf16ff7d3e4890bf6f1e0a35dd1cf109c5308
refs/heads/master
2021-01-02T09:31:24.503364
2010-08-20T19:42:04
2010-08-20T19:42:04
752,140
1
0
null
null
null
null
UTF-8
C++
false
false
606
h
/* * NOTICE: Do not manually edit this file. It has been autogenerated by * protocol/parse.py. Any changes should me made there, instead of here. */ #pragma once #include <boost/cstdint.hpp> #include <cockpit/packet/Packet.h> #include <cockpit/packet/Parameters.h> namespace cockpit { namespace packet { namespace protocol { // choose admin as commander class MC_ADMIN_ASSASIN : public Packet { public: enum { packetID = 536 }; MC_ADMIN_ASSASIN(); const char* name() const; const char* doc() const; boost::uint16_t id() const; Buffer serialize() const; ~MC_ADMIN_ASSASIN() { } }; } } }
[ "cg.wowus.cg@gmail.com" ]
cg.wowus.cg@gmail.com
83e11a2523a23b1e0fe67a8d27a11de2ba81b07d
4cc51211ef649d7d2bb9a7777ba3d78d2e405849
/uri/1929.cpp
d189264211bbac9706b68930337ed6993b8fe581
[ "MIT" ]
permissive
Shisir/Online-Judge
0044fe7d52e8c922dbc491fc00abbb2915ce995e
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
refs/heads/master
2021-01-12T14:59:50.878107
2016-11-08T16:22:13
2016-11-08T16:22:13
71,658,699
0
0
null
null
null
null
UTF-8
C++
false
false
236
cpp
#include <bits/stdc++.h> using namespace std; int main() { int a[4]; scanf("%d%d%d%d",&a[0],&a[1],&a[2],&a[3]); sort(a,a+4); if(a[1]+a[2]>a[3] ||a[0]+a[1]>a[2]||a[0]+a[1]>a[3]) return printf("S\n"),0; return printf("N\n"), 0; }
[ "nazmul295iit@gmail.com" ]
nazmul295iit@gmail.com
c45745244f7d4b579bc340db9d2cba067ed108cd
b21b238d066ad46b171c56552fc8e372422c98ab
/leetcode/leetcode_341.cc
26561c90f7c0c220e7c5ec9d957fd6e4fae0804e
[ "MIT" ]
permissive
math715/arts
854a8c8da4035267785571b18d626138d5100b70
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
refs/heads/master
2021-08-07T01:10:31.981914
2021-07-01T13:32:05
2021-07-01T13:32:05
142,163,367
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cc
#include <algorithm> #include <iostream> #include <map> #include <set> #include <string> #include <vector> using namespace std; class NestedInteger { public: // Return true if this NestedInteger holds a single integer, rather than a nested list. bool isInteger() const; // Return the single integer that this NestedInteger holds, if it holds a single integer // The result is undefined if this NestedInteger holds a nested list int getInteger() const; // Return the nested list that this NestedInteger holds, if it holds a nested list // The result is undefined if this NestedInteger holds a single integer const vector<NestedInteger> &getList() const; }; void put(NestedInteger& list, vector<int> &vs) { if (list.isInteger()) { vs.push_back(list.getInteger()); } else { for (auto l : list.getList()) { put(l, vs); } } } class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { for (auto l : nestedList ) { put(l, vs); } it = vs.begin(); } int next() { int a = *it; it++; return a; } bool hasNext() { return it != vs.end(); } private: vector<int> vs; vector<int>::iterator it; }; int main( int argc, char *argv[] ) { return 0; }
[ "wangyanlong@genomics.cn" ]
wangyanlong@genomics.cn
9fd754ff66c3cab2658afb67851210e3a52ff3e0
f71c655ade5851a2877416d1a77115b9bfb1938d
/CPPprimer/ch04/4.10.cc
a29fd225bc8e1ea9b7e918c902f7392f1e10577f
[]
no_license
hzylyq/Book
7b46c293af73f71db963034dc94483e589e1ab16
2f8d5ee59cba11edfb71400b8057811c096155b2
refs/heads/master
2021-06-03T08:33:44.712728
2021-01-09T05:52:44
2021-01-09T05:52:44
126,025,282
0
0
null
null
null
null
UTF-8
C++
false
false
175
cc
#include <iostream> using namespace std; int main(void) { int num = 0; while (cin >> num && num != 42); while (cin >> num){ if (num == 42) break; } return 0; }
[ "164177565@qq.com" ]
164177565@qq.com
4542cc83f82c34e8c4cb295834f2aaeb4d18dea5
e9662948f6e42915cd428760eb515064b0e7e051
/animationjc-master/core/modifierhandler.h
7b8161c17b3bccfaddd78e738c2732d00878084a
[]
no_license
Eignar17/backup-plugins
dd50a129c6c29a00c8a492e188db5a2deec37f98
4173f838e245c8eac5b5cbe83bc2a1f6f037e613
refs/heads/master
2023-02-13T18:01:31.054093
2023-02-11T00:56:05
2023-02-11T00:56:05
133,735,293
2
0
null
null
null
null
UTF-8
C++
false
false
2,939
h
/* * Copyright © 2008 Dennis Kasprzyk * Copyright © 2007 Novell, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without * fee, provided that the above copyright notice appear in all copies * and that both that copyright notice and this permission notice * appear in supporting documentation, and that the name of * Dennis Kasprzyk not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior permission. * Dennis Kasprzyk makes no representations about the suitability of this * software for any purpose. It is provided "as is" without express or * implied warranty. * * DENNIS KASPRZYK DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN * NO EVENT SHALL DENNIS KASPRZYK BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Authors: Dennis Kasprzyk <onestone@compiz-fusion.org> * David Reveman <davidr@novell.com> * Sam Spilsbury <smspillaz@gmail.com> */ #include <core/core.h> /** * Toplevel class which provides access to display * level modifier information */ class ModifierHandler { public: ModifierHandler (); ~ModifierHandler (); typedef enum { Alt = 1, Meta, Super, Hyper, ModeSwitch, NumLock, ScrollLock, ModNum } Modifier; typedef enum { AltMask = (1 << 16), MetaMask = (1 << 17), SuperMask = (1 << 18), HyperMask = (1 << 19), ModeSwitchMask = (1 << 20), NumLockMask = (1 << 21), ScrollLockMask = (1 << 22), NoMask = (1 << 25), } ModMask; public: /** * Takes an X11 Keycode and returns a bitmask * with modifiers that have been pressed */ unsigned int keycodeToModifiers (int keycode); /** * Updates X11 Modifier mappings */ void updateModifierMappings (); /** * Takes a virtual modMask and returns a real modifier mask * by removing unused bits */ unsigned int virtualToRealModMask (unsigned int modMask); /** * Returns a bit modifier mask for a Motifier enum */ unsigned int modMask (Modifier); /** * Returns a const bit modifier mask for what should be ignored */ unsigned int ignoredModMask (); /** * Returns a const XModifierKeymap for compiz */ const XModifierKeymap * modMap (); friend class CompScreenImpl; private: static const unsigned int virtualModMask[7]; static const int maskTable[8]; static const int maskTableSize = 8; ModMask mModMask[ModNum]; unsigned int mIgnoredModMask; XModifierKeymap *mModMap; };
[ "noreply@github.com" ]
Eignar17.noreply@github.com
8b4ea8992ebbadbe79f39841761150d7ed16be88
030c54986e309ea335204af18baac78f9aaadb14
/QClientFramework/Model/http_service_moudle/base64.h
b2b51b14479d221062c0763a21d65a2aade22817
[]
no_license
lxj434368832/ProgramFramework
035fb3e8709f5eede7ad14823937548317d777d7
5d27d887c42f7bb0d7a0f782fc5eb55b655d5382
refs/heads/master
2023-09-02T16:55:23.968901
2023-08-23T12:50:31
2023-08-23T12:50:31
159,472,625
0
0
null
null
null
null
UTF-8
C++
false
false
5,262
h
#pragma once #include <string> const char kBase64Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; class Base64 { public: static bool Encode(const std::string &in, std::string *out) { int i = 0, j = 0; size_t enc_len = 0; unsigned char a3[3]; unsigned char a4[4]; out->resize(EncodedLength(in)); int input_len = in.size(); std::string::const_iterator input = in.begin(); while (input_len--) { a3[i++] = *(input++); if (i == 3) { a3_to_a4(a4, a3); for (i = 0; i < 4; i++) { (*out)[enc_len++] = kBase64Alphabet[a4[i]]; } i = 0; } } if (i) { for (j = i; j < 3; j++) { a3[j] = '\0'; } a3_to_a4(a4, a3); for (j = 0; j < i + 1; j++) { (*out)[enc_len++] = kBase64Alphabet[a4[j]]; } while ((i++ < 3)) { (*out)[enc_len++] = '='; } } return (enc_len == out->size()); } static bool Encode(const char *input, size_t input_length, char *out, size_t out_length) { int i = 0, j = 0; char *out_begin = out; unsigned char a3[3]; unsigned char a4[4]; size_t encoded_length = EncodedLength(input_length); if (out_length < encoded_length) return false; while (input_length--) { a3[i++] = *input++; if (i == 3) { a3_to_a4(a4, a3); for (i = 0; i < 4; i++) { *out++ = kBase64Alphabet[a4[i]]; } i = 0; } } if (i) { for (j = i; j < 3; j++) { a3[j] = '\0'; } a3_to_a4(a4, a3); for (j = 0; j < i + 1; j++) { *out++ = kBase64Alphabet[a4[j]]; } while ((i++ < 3)) { *out++ = '='; } } return (out == (out_begin + encoded_length)); } static bool Decode(const std::string &in, std::string *out) { int i = 0, j = 0; size_t dec_len = 0; unsigned char a3[3]; unsigned char a4[4]; int input_len = in.size(); std::string::const_iterator input = in.begin(); out->resize(DecodedLength(in)); while (input_len--) { if (*input == '=') { break; } a4[i++] = *(input++); if (i == 4) { for (i = 0; i <4; i++) { a4[i] = b64_lookup(a4[i]); } a4_to_a3(a3,a4); for (i = 0; i < 3; i++) { (*out)[dec_len++] = a3[i]; } i = 0; } } if (i) { for (j = i; j < 4; j++) { a4[j] = '\0'; } for (j = 0; j < 4; j++) { a4[j] = b64_lookup(a4[j]); } a4_to_a3(a3,a4); for (j = 0; j < i - 1; j++) { (*out)[dec_len++] = a3[j]; } } return (dec_len == out->size()); } static bool Decode(const char *input, size_t input_length, char *out, size_t out_length) { int i = 0, j = 0; char *out_begin = out; unsigned char a3[3]; unsigned char a4[4]; size_t decoded_length = DecodedLength(input, input_length); if (out_length < decoded_length) return false; while (input_length--) { if (*input == '=') { break; } a4[i++] = *(input++); if (i == 4) { for (i = 0; i <4; i++) { a4[i] = b64_lookup(a4[i]); } a4_to_a3(a3,a4); for (i = 0; i < 3; i++) { *out++ = a3[i]; } i = 0; } } if (i) { for (j = i; j < 4; j++) { a4[j] = '\0'; } for (j = 0; j < 4; j++) { a4[j] = b64_lookup(a4[j]); } a4_to_a3(a3,a4); for (j = 0; j < i - 1; j++) { *out++ = a3[j]; } } return (out == (out_begin + decoded_length)); } static int DecodedLength(const char *in, size_t in_length) { int numEq = 0; const char *in_end = in + in_length; while (*--in_end == '=') ++numEq; return ((6 * in_length) / 8) - numEq; } static int DecodedLength(const std::string &in) { int numEq = 0; int n = in.size(); for (std::string::const_reverse_iterator it = in.rbegin(); *it == '='; ++it) { ++numEq; } return ((6 * n) / 8) - numEq; } inline static int EncodedLength(size_t length) { return (length + 2 - ((length + 2) % 3)) / 3 * 4; } inline static int EncodedLength(const std::string &in) { return EncodedLength(in.length()); } inline static void StripPadding(std::string *in) { while (!in->empty() && *(in->rbegin()) == '=') in->resize(in->size() - 1); } private: static inline void a3_to_a4(unsigned char * a4, unsigned char * a3) { a4[0] = (a3[0] & 0xfc) >> 2; a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4); a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6); a4[3] = (a3[2] & 0x3f); } static inline void a4_to_a3(unsigned char * a3, unsigned char * a4) { a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4); a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2); a3[2] = ((a4[2] & 0x3) << 6) + a4[3]; } static inline unsigned char b64_lookup(unsigned char c) { if(c >='A' && c <='Z') return c - 'A'; if(c >='a' && c <='z') return c - 71; if(c >='0' && c <='9') return c + 4; if(c == '+') return 62; if(c == '/') return 63; return 255; } };
[ "434368832@qq.com" ]
434368832@qq.com
7f291fdec825b8a6919a4849ec629c5785ae82d4
78e4d00de9768f5bc7cfefb599d0747b0b4dfacd
/bitmask.cpp
08aa89db21e851406d26c9891f62fe7f1adb5802
[]
no_license
HabibRaju/Dynamic-Programming
96b85459b4779df7cc8714b20d793426b5077411
77e53f8730aa345dabf92eff9c895ff61cc8311e
refs/heads/main
2023-04-19T16:22:16.939927
2021-04-27T15:41:17
2021-04-27T15:41:17
362,164,584
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#include <bits/stdc++.h> using namespace std; int n=3; bool chk(int mask){ return (bool)(mask & ((1<<10)-1)); } int dp[1000][(1<<10)+2]; int fun(int pos,int mask){ if(pos>=n){ if(chk(mask))return 1; return 0; } if(dp[pos][mask]!=-1)return dp[pos][mask]; int low=0,res=0; if(pos==0)low=1; for(int i=low; i<10; i++){ int val = fun(pos+1, mask | (1<<pos)); res+=val; } return dp[pos][mask] = res; } int main(){ memset(dp,-1,sizeof(dp)); cout<<fun(0,0); }
[ "noreply@github.com" ]
HabibRaju.noreply@github.com
512a1aaeba5cdc712ba522a0e2f03d8b1cdd1223
857fb4bda4cd2c898f265ff08b25876cb505323f
/udaan/set-1/unique-subsequences/gen-small.cpp
b283a9c0644ad14f24924ee04b3fe453a2d0b71b
[]
no_license
raviku9273/sugar-rush
c57729ef8a19706b24874d7599b8ba4025a9f0ef
929210e0e9c06a739104c2146efc6e030f0f725a
refs/heads/master
2022-11-16T05:33:03.754433
2020-07-16T16:48:55
2020-07-16T16:48:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
#include <iostream> #include "testlib.h" using namespace std; /********************* Custom Inputs ***************************/ const int t_low = 1; const int t_high = 1; const int len_low = 1; const int len_high = 1e5; const int rep_low = 1; const int rep_high = 2; /********************* Custom Inputs ***************************/ #define endl '\n' void generate() { string str = ""; for(char c = 'a'; c <= 'z'; c++) { int rep = rnd.next(rep_low, rep_high); for(int i = 0; i < rep; i++) str += c; } cout << str.length() << endl; cout << str << endl; } int main(int argc, char* argv[]) { registerGen(argc, argv, 1); int t = rnd.next(t_low, t_high); cout << t << endl; for(int i = 0; i < t; i++) generate(); return 0; }
[ "just1visitor@gmail.com" ]
just1visitor@gmail.com
2fa80e00f062b353aaa60a5979719ba7245d7251
48dea64e33da0594a8a167b2c75aa8ec7c99bcfa
/mobile_net_hls/solution1/syn/systemc/fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x.h
a3e4330955fc3e6dae152cc834870f0a34f0ff1c
[ "BSD-3-Clause" ]
permissive
myheartisweeping/FPGA-DCNN-Accelerator
f304a6cb390c5cc9a1308af5215f834008460041
3ed02fa47b72c877c76ca8fa961184ea2260dedc
refs/heads/master
2022-01-13T03:28:09.580136
2019-06-11T07:12:57
2019-06-11T07:12:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,920
h
// ============================================================== // File generated on Sun Apr 28 16:10:43 +0800 2019 // Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2018.3 (64-bit) // SW Build 2405991 on Thu Dec 6 23:38:27 MST 2018 // IP Build 2404404 on Fri Dec 7 01:43:56 MST 2018 // Copyright 1986-2018 Xilinx, Inc. All Rights Reserved. // ============================================================== #ifndef fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_HH_ #define fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_HH_ #include <systemc> using namespace std; SC_MODULE(fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x) { static const unsigned int DATA_WIDTH = 32; static const unsigned int ADDR_WIDTH = 2; static const unsigned int fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth = 3; sc_core::sc_in_clk clk; sc_core::sc_in< sc_dt::sc_logic > reset; sc_core::sc_out< sc_dt::sc_logic > if_empty_n; sc_core::sc_in< sc_dt::sc_logic > if_read_ce; sc_core::sc_in< sc_dt::sc_logic > if_read; sc_core::sc_out< sc_dt::sc_lv<DATA_WIDTH> > if_dout; sc_core::sc_out< sc_dt::sc_logic > if_full_n; sc_core::sc_in< sc_dt::sc_logic > if_write_ce; sc_core::sc_in< sc_dt::sc_logic > if_write; sc_core::sc_in< sc_dt::sc_lv<DATA_WIDTH> > if_din; sc_core::sc_signal< sc_dt::sc_logic > internal_empty_n; sc_core::sc_signal< sc_dt::sc_logic > internal_full_n; sc_core::sc_signal< sc_dt::sc_lv<DATA_WIDTH> > mStorage[fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth]; sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mInPtr; sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mOutPtr; sc_core::sc_signal< sc_dt::sc_uint<1> > mFlag_nEF_hint; sc_core::sc_trace_file* mTrace; SC_CTOR(fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x) : mTrace(0) { const char* dump_vcd = std::getenv("AP_WRITE_VCD"); if (dump_vcd && string(dump_vcd) == "1") { std::string tracefn = "sc_trace_" + std::string(name()); mTrace = sc_core::sc_create_vcd_trace_file( tracefn.c_str()); sc_trace(mTrace, clk, "(port)clk"); sc_trace(mTrace, reset, "(port)reset"); sc_trace(mTrace, if_full_n, "(port)if_full_n"); sc_trace(mTrace, if_write_ce, "(port)if_write_ce"); sc_trace(mTrace, if_write, "(port)if_write"); sc_trace(mTrace, if_din, "(port)if_din"); sc_trace(mTrace, if_empty_n, "(port)if_empty_n"); sc_trace(mTrace, if_read_ce, "(port)if_read_ce"); sc_trace(mTrace, if_read, "(port)if_read"); sc_trace(mTrace, if_dout, "(port)if_dout"); sc_trace(mTrace, mInPtr, "mInPtr"); sc_trace(mTrace, mOutPtr, "mOutPtr"); sc_trace(mTrace, mFlag_nEF_hint, "mFlag_nEF_hint"); } mInPtr = 0; mOutPtr = 0; mFlag_nEF_hint = 0; SC_METHOD(proc_read_write); sensitive << clk.pos(); SC_METHOD(proc_dout); sensitive << mOutPtr; for (unsigned i = 0; i < fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth; i++) { sensitive << mStorage[i]; } SC_METHOD(proc_ptr); sensitive << mInPtr << mOutPtr<< mFlag_nEF_hint; SC_METHOD(proc_status); sensitive << internal_empty_n << internal_full_n; } ~fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x() { if (mTrace) sc_core::sc_close_vcd_trace_file(mTrace); } void proc_status() { if_empty_n.write(internal_empty_n.read()); if_full_n.write(internal_full_n.read()); } void proc_read_write() { if (reset.read() == sc_dt::SC_LOGIC_1) { mInPtr.write(0); mOutPtr.write(0); mFlag_nEF_hint.write(0); } else { if (if_read_ce.read() == sc_dt::SC_LOGIC_1 && if_read.read() == sc_dt::SC_LOGIC_1 && internal_empty_n.read() == sc_dt::SC_LOGIC_1) { sc_dt::sc_uint<ADDR_WIDTH> ptr; if (mOutPtr.read().to_uint() == (fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth-1)) { ptr = 0; mFlag_nEF_hint.write(~mFlag_nEF_hint.read()); } else { ptr = mOutPtr.read(); ptr++; } assert(ptr.to_uint() < fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth); mOutPtr.write(ptr); } if (if_write_ce.read() == sc_dt::SC_LOGIC_1 && if_write.read() == sc_dt::SC_LOGIC_1 && internal_full_n.read() == sc_dt::SC_LOGIC_1) { sc_dt::sc_uint<ADDR_WIDTH> ptr; ptr = mInPtr.read(); mStorage[ptr.to_uint()].write(if_din.read()); if (ptr.to_uint() == (fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth-1)) { ptr = 0; mFlag_nEF_hint.write(~mFlag_nEF_hint.read()); } else { ptr++; assert(ptr.to_uint() < fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth); } mInPtr.write(ptr); } } } void proc_dout() { sc_dt::sc_uint<ADDR_WIDTH> ptr = mOutPtr.read(); if (ptr.to_uint() > fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_depth) { if_dout.write(sc_dt::sc_lv<DATA_WIDTH>()); } else { if_dout.write(mStorage[ptr.to_uint()]); } } void proc_ptr() { if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==0) { internal_empty_n.write(sc_dt::SC_LOGIC_0); } else { internal_empty_n.write(sc_dt::SC_LOGIC_1); } if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==1) { internal_full_n.write(sc_dt::SC_LOGIC_0); } else { internal_full_n.write(sc_dt::SC_LOGIC_1); } } }; #endif //fifo_w32_d2_A_x_x_x_x_x_x_x_x_x_x_HH_
[ "1310283407@qq.com" ]
1310283407@qq.com
3531ed32755fde4bae921bfa3be10125ad8d42ab
7ac86228240a5f6f725e986e122f9e5870c0743d
/cds/intrusive/hopscotch_hashset.h
35808d817366ba565a1a182bc81eb80f62c5089c
[ "BSL-1.0" ]
permissive
AndreyFdrv/libcds
ecb33b40ce1a1c8a30105e00d2f7f03a2e8f4443
ed5be9218f51403277db97d6f8303c93c1014e3f
refs/heads/master
2020-04-03T05:55:29.556686
2019-01-20T18:01:59
2019-01-20T18:01:59
155,059,745
1
0
null
2018-10-28T10:40:32
2018-10-28T10:40:32
null
UTF-8
C++
false
false
119,044
h
/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CDSLIB_INTRUSIVE_HOPSCOTCH_HASHSET_H #define CDSLIB_INTRUSIVE_HOPSCOTCH_HASHSET_H #include <memory> #include <type_traits> #include <mutex> #include <functional> // ref #include <cds/intrusive/details/base.h> #include <cds/opt/compare.h> #include <cds/opt/hash.h> #include <cds/sync/lock_array.h> #include <cds/os/thread.h> #include <cds/sync/spinlock.h> namespace cds { namespace intrusive { /// HopscotchHashset-related definitions namespace hopscotch_hashset { /// Option to define probeset type /** The option specifies probeset type for the HopscotchHashset. Available values: - \p cds::intrusive::hopscotch_hashset::list - the probeset is a single-linked list. The node contains pointer to next node in probeset. - \p cds::intrusive::hopscotch_hashset::vector<Capacity> - the probeset is a vector with constant-size \p Capacity where \p Capacity is an <tt>unsigned int</tt> constant. The node does not contain any auxiliary data. */ template <typename Type> struct probeset_type { //@cond template <typename Base> struct pack: public Base { typedef Type probeset_type; }; //@endcond }; /// Option specifying whether to store hash values in the node /** This option reserves additional space in the hook to store the hash value of the object once it's introduced in the container. When this option is used, the unordered container will store the calculated hash value in the hook and rehashing operations won't need to recalculate the hash of the value. This option will improve the performance of unordered containers when rehashing is frequent or hashing the value is a slow operation The \p Count template parameter defines the size of hash array. Remember that hopscotch hashing implies at least two hash values per item. Possible values of \p Count: - 0 - no hash storing in the node - greater that 1 - store hash values. Value 1 is deprecated. */ template <unsigned int Count> struct store_hash { //@cond template <typename Base> struct pack: public Base { static unsigned int const store_hash = Count; }; //@endcond }; //@cond // Probeset type placeholders struct list_probeset_class; struct vector_probeset_class; //@endcond //@cond /// List probeset type struct list; //@endcond /// Vector probeset type template <unsigned int Capacity> struct vector { /// Vector capacity static unsigned int const c_nCapacity = Capacity; }; /// HopscotchHashset node /** Template arguments: - \p ProbesetType - type of probeset. Can be \p cds::intrusive::hopscotch_hashset::list or \p cds::intrusive::hopscotch_hashset::vector<Capacity>. - \p StoreHashCount - constant that defines whether to store node hash values. See hopscotch_hashset::store_hash option for explanation - \p Tag - a \ref cds_intrusive_hook_tag "tag" */ template <typename ProbesetType = hopscotch_hashset::list, unsigned int StoreHashCount = 0, typename Tag = opt::none> struct node #ifdef CDS_DOXYGEN_INVOKED { typedef ProbesetType probeset_type ; ///< Probeset type typedef Tag tag ; ///< Tag static unsigned int const hash_array_size = StoreHashCount ; ///< The size of hash array } #endif ; //@cond template <typename Tag> struct node< hopscotch_hashset::list, 0, Tag> { typedef list_probeset_class probeset_class; typedef hopscotch_hashset::list probeset_type; typedef Tag tag; static unsigned int const hash_array_size = 0; static unsigned int const probeset_size = 0; node * m_pNext; constexpr node() noexcept : m_pNext( nullptr ) {} void store_hash( size_t const* ) {} size_t * get_hash() const { // This node type does not store hash values!!! assert(false); return nullptr; } void clear() { m_pNext = nullptr; } }; template <unsigned int StoreHashCount, typename Tag> struct node< hopscotch_hashset::list, StoreHashCount, Tag> { typedef list_probeset_class probeset_class; typedef hopscotch_hashset::list probeset_type; typedef Tag tag; static unsigned int const hash_array_size = StoreHashCount; static unsigned int const probeset_size = 0; node * m_pNext; size_t m_arrHash[ hash_array_size ]; node() noexcept : m_pNext( nullptr ) { memset( m_arrHash, 0, sizeof(m_arrHash)); } void store_hash( size_t const* pHashes ) { memcpy( m_arrHash, pHashes, sizeof( m_arrHash )); } size_t * get_hash() const { return const_cast<size_t *>( m_arrHash ); } void clear() { m_pNext = nullptr; } }; template <unsigned int VectorSize, typename Tag> struct node< hopscotch_hashset::vector<VectorSize>, 0, Tag> { typedef vector_probeset_class probeset_class; typedef hopscotch_hashset::vector<VectorSize> probeset_type; typedef Tag tag; static unsigned int const hash_array_size = 0; static unsigned int const probeset_size = probeset_type::c_nCapacity; node() noexcept {} void store_hash( size_t const* ) {} size_t * get_hash() const { // This node type does not store hash values!!! assert(false); return nullptr; } void clear() {} }; template <unsigned int VectorSize, unsigned int StoreHashCount, typename Tag> struct node< hopscotch_hashset::vector<VectorSize>, StoreHashCount, Tag> { typedef vector_probeset_class probeset_class; typedef hopscotch_hashset::vector<VectorSize> probeset_type; typedef Tag tag; static unsigned int const hash_array_size = StoreHashCount; static unsigned int const probeset_size = probeset_type::c_nCapacity; size_t m_arrHash[ hash_array_size ]; node() noexcept { memset( m_arrHash, 0, sizeof(m_arrHash)); } void store_hash( size_t const* pHashes ) { memcpy( m_arrHash, pHashes, sizeof( m_arrHash )); } size_t * get_hash() const { return const_cast<size_t *>( m_arrHash ); } void clear() {} }; //@endcond //@cond struct default_hook { typedef hopscotch_hashset::list probeset_type; static unsigned int const store_hash = 0; typedef opt::none tag; }; template < typename HookType, typename... Options> struct hook { typedef typename opt::make_options< default_hook, Options...>::type traits; typedef typename traits::probeset_type probeset_type; typedef typename traits::tag tag; static unsigned int const store_hash = traits::store_hash; typedef node<probeset_type, store_hash, tag> node_type; typedef HookType hook_type; }; //@endcond /// Base hook /** \p Options are: - \p hopscotch_hashset::probeset_type - probeset type. Defaul is \p hopscotch_hashset::list - \p hopscotch_hashset::store_hash - store hash values in the node or not. Default is 0 (no storing) - \p opt::tag - a \ref cds_intrusive_hook_tag "tag" */ template < typename... Options > struct base_hook: public hook< opt::base_hook_tag, Options... > {}; /// Member hook /** \p MemberOffset defines offset in bytes of \ref node member into your structure. Use \p offsetof macro to define \p MemberOffset \p Options are: - \p hopscotch_hashset::probeset_type - probeset type. Defaul is \p hopscotch_hashset::list - \p hopscotch_hashset::store_hash - store hash values in the node or not. Default is 0 (no storing) - \p opt::tag - a \ref cds_intrusive_hook_tag "tag" */ template < size_t MemberOffset, typename... Options > struct member_hook: public hook< opt::member_hook_tag, Options... > { //@cond static const size_t c_nMemberOffset = MemberOffset; //@endcond }; /// Traits hook /** \p NodeTraits defines type traits for node. See \ref node_traits for \p NodeTraits interface description \p Options are: - \p hopscotch_hashset::probeset_type - probeset type. Defaul is \p hopscotch_hashset::list - \p hopscotch_hashset::store_hash - store hash values in the node or not. Default is 0 (no storing) - \p opt::tag - a \ref cds_intrusive_hook_tag "tag" */ template <typename NodeTraits, typename... Options > struct traits_hook: public hook< opt::traits_hook_tag, Options... > { //@cond typedef NodeTraits node_traits; //@endcond }; /// Internal statistics for \ref striping mutex policy struct striping_stat { typedef cds::atomicity::event_counter counter_type; ///< Counter type counter_type m_nCellLockCount ; ///< Count of obtaining cell lock counter_type m_nCellTryLockCount ; ///< Count of cell \p try_lock attempts counter_type m_nFullLockCount ; ///< Count of obtaining full lock counter_type m_nResizeLockCount ; ///< Count of obtaining resize lock counter_type m_nResizeCount ; ///< Count of resize event //@cond void onCellLock() { ++m_nCellLockCount; } void onCellTryLock() { ++m_nCellTryLockCount; } void onFullLock() { ++m_nFullLockCount; } void onResizeLock() { ++m_nResizeLockCount; } void onResize() { ++m_nResizeCount; } //@endcond }; /// Dummy internal statistics for \ref striping mutex policy struct empty_striping_stat { //@cond void onCellLock() const {} void onCellTryLock() const {} void onFullLock() const {} void onResizeLock() const {} void onResize() const {} //@endcond }; /// Lock striping concurrent access policy /** This is one of available opt::mutex_policy option type for HopscotchHashset Lock striping is very simple technique. The hopscotch set consists of the bucket tables and the array of locks. There is single lock array for each bucket table, at least, the count of bucket table is 2. Initially, the capacity of lock array and each bucket table is the same. When set is resized, bucket table capacity will be doubled but lock array will not. The lock \p i protects each bucket \p j, where <tt> j = i mod L </tt>, where \p L - the size of lock array. The policy contains an internal array of \p RecursiveLock locks. Template arguments: - \p RecursiveLock - the type of recursive mutex. The default is \p std::recursive_mutex. The mutex type should be default-constructible. Note that a recursive spin-lock is not suitable for lock striping for performance reason. - \p Arity - unsigned int constant that specifies an arity. The arity is the count of hash functors, i.e., the count of lock arrays. Default value is 2. - \p Alloc - allocator type used for lock array memory allocation. Default is \p CDS_DEFAULT_ALLOCATOR. - \p Stat - internal statistics type. Note that this template argument is automatically selected by \ref HopscotchHashset class according to its \p opt::stat option. */ template < class RecursiveLock = std::recursive_mutex, unsigned int Arity = 2, class Alloc = CDS_DEFAULT_ALLOCATOR, class Stat = empty_striping_stat > class striping { public: typedef RecursiveLock lock_type ; ///< lock type typedef Alloc allocator_type ; ///< allocator type static unsigned int const c_nArity = Arity ; ///< the arity typedef Stat statistics_type ; ///< Internal statistics type (\ref striping_stat or \ref empty_striping_stat) //@cond typedef striping_stat real_stat; typedef empty_striping_stat empty_stat; template <typename Stat2> struct rebind_statistics { typedef striping<lock_type, c_nArity, allocator_type, Stat2> other; }; //@endcond typedef cds::sync::lock_array< lock_type, cds::sync::pow2_select_policy, allocator_type > lock_array_type ; ///< lock array type protected: //@cond class lock_array: public lock_array_type { public: // placeholder ctor lock_array(): lock_array_type( typename lock_array_type::select_cell_policy(2)) {} // real ctor lock_array( size_t nCapacity ): lock_array_type( nCapacity, typename lock_array_type::select_cell_policy(nCapacity)) {} }; class scoped_lock: public std::unique_lock< lock_array_type > { typedef std::unique_lock< lock_array_type > base_class; public: scoped_lock( lock_array& arrLock, size_t nHash ): base_class( arrLock, nHash ) {} }; //@endcond protected: //@cond lock_array m_Locks[c_nArity] ; ///< array of \p lock_array_type statistics_type m_Stat ; ///< internal statistics //@endcond public: //@cond class scoped_cell_lock { lock_type * m_guard[c_nArity]; public: scoped_cell_lock( striping& policy, size_t const* arrHash ) { for ( unsigned int i = 0; i < c_nArity; ++i ) { m_guard[i] = &( policy.m_Locks[i].at( policy.m_Locks[i].lock( arrHash[i] ))); } policy.m_Stat.onCellLock(); } ~scoped_cell_lock() { for ( unsigned int i = 0; i < c_nArity; ++i ) m_guard[i]->unlock(); } }; class scoped_cell_trylock { typedef typename lock_array_type::lock_type lock_type; lock_type * m_guard[c_nArity]; bool m_bLocked; public: scoped_cell_trylock( striping& policy, size_t const* arrHash ) { size_t nCell = policy.m_Locks[0].try_lock( arrHash[0] ); m_bLocked = nCell != lock_array_type::c_nUnspecifiedCell; if ( m_bLocked ) { m_guard[0] = &(policy.m_Locks[0].at(nCell)); for ( unsigned int i = 1; i < c_nArity; ++i ) { m_guard[i] = &( policy.m_Locks[i].at( policy.m_Locks[i].lock( arrHash[i] ))); } } else { std::fill( m_guard, m_guard + c_nArity, nullptr ); } policy.m_Stat.onCellTryLock(); } ~scoped_cell_trylock() { if ( m_bLocked ) { for ( unsigned int i = 0; i < c_nArity; ++i ) m_guard[i]->unlock(); } } bool locked() const { return m_bLocked; } }; class scoped_full_lock { std::unique_lock< lock_array_type > m_guard; public: scoped_full_lock( striping& policy ) : m_guard( policy.m_Locks[0] ) { policy.m_Stat.onFullLock(); } /// Ctor for scoped_resize_lock - no statistics is incremented scoped_full_lock( striping& policy, bool ) : m_guard( policy.m_Locks[0] ) {} }; class scoped_resize_lock: public scoped_full_lock { public: scoped_resize_lock( striping& policy ) : scoped_full_lock( policy, false ) { policy.m_Stat.onResizeLock(); } }; //@endcond public: /// Constructor striping( size_t nLockCount ///< The size of lock array. Must be power of two. ) { // Trick: initialize the array of locks for ( unsigned int i = 0; i < c_nArity; ++i ) { lock_array * pArr = m_Locks + i; pArr->lock_array::~lock_array(); new ( pArr ) lock_array( nLockCount ); } } /// Returns lock array size /** Lock array size is unchanged during \p striping object lifetime */ size_t lock_count() const { return m_Locks[0].size(); } //@cond void resize( size_t ) { m_Stat.onResize(); } //@endcond /// Returns the arity of striping mutex policy constexpr unsigned int arity() const noexcept { return c_nArity; } /// Returns internal statistics statistics_type const& statistics() const { return m_Stat; } }; /// Internal statistics for \ref refinable mutex policy struct refinable_stat { typedef cds::atomicity::event_counter counter_type ; ///< Counter type counter_type m_nCellLockCount ; ///< Count of obtaining cell lock counter_type m_nCellLockWaitResizing ; ///< Count of loop iteration to wait for resizing counter_type m_nCellLockArrayChanged ; ///< Count of event "Lock array has been changed when obtaining cell lock" counter_type m_nCellLockFailed ; ///< Count of event "Cell lock failed because of the array is owned by other thread" counter_type m_nSecondCellLockCount ; ///< Count of obtaining cell lock when another cell is already locked counter_type m_nSecondCellLockFailed ; ///< Count of unsuccess obtaining cell lock when another cell is already locked counter_type m_nFullLockCount ; ///< Count of obtaining full lock counter_type m_nFullLockIter ; ///< Count of unsuccessfull iteration to obtain full lock counter_type m_nResizeLockCount ; ///< Count of obtaining resize lock counter_type m_nResizeLockIter ; ///< Count of unsuccessfull iteration to obtain resize lock counter_type m_nResizeLockArrayChanged; ///< Count of event "Lock array has been changed when obtaining resize lock" counter_type m_nResizeCount ; ///< Count of resize event //@cond void onCellLock() { ++m_nCellLockCount; } void onCellWaitResizing() { ++m_nCellLockWaitResizing; } void onCellArrayChanged() { ++m_nCellLockArrayChanged; } void onCellLockFailed() { ++m_nCellLockFailed; } void onSecondCellLock() { ++m_nSecondCellLockCount; } void onSecondCellLockFailed() { ++m_nSecondCellLockFailed; } void onFullLock() { ++m_nFullLockCount; } void onFullLockIter() { ++m_nFullLockIter; } void onResizeLock() { ++m_nResizeLockCount; } void onResizeLockIter() { ++m_nResizeLockIter; } void onResizeLockArrayChanged() { ++m_nResizeLockArrayChanged; } void onResize() { ++m_nResizeCount; } //@endcond }; /// Dummy internal statistics for \ref refinable mutex policy struct empty_refinable_stat { //@cond void onCellLock() const {} void onCellWaitResizing() const {} void onCellArrayChanged() const {} void onCellLockFailed() const {} void onSecondCellLock() const {} void onSecondCellLockFailed() const {} void onFullLock() const {} void onFullLockIter() const {} void onResizeLock() const {} void onResizeLockIter() const {} void onResizeLockArrayChanged() const {} void onResize() const {} //@endcond }; /// Refinable concurrent access policy /** This is one of available \p opt::mutex_policy option type for \p HopscotchHashset Refining is like a striping technique (see \p hopscotch_hashset::striping) but it allows growing the size of lock array when resizing the hash table. So, the sizes of hash table and lock array are equal. Template arguments: - \p RecursiveLock - the type of mutex. Reentrant (recursive) mutex is required. The default is \p std::recursive_mutex. The mutex type should be default-constructible. - \p Arity - unsigned int constant that specifies an arity. The arity is the count of hash functors, i.e., the count of lock arrays. Default value is 2. - \p BackOff - back-off strategy. Default is \p cds::backoff::Default - \p Alloc - allocator type used for lock array memory allocation. Default is \p CDS_DEFAULT_ALLOCATOR. - \p Stat - internal statistics type. Note that this template argument is automatically selected by \ref HopscotchHashset class according to its \p opt::stat option. */ template < class RecursiveLock = std::recursive_mutex, unsigned int Arity = 2, typename BackOff = cds::backoff::Default, class Alloc = CDS_DEFAULT_ALLOCATOR, class Stat = empty_refinable_stat > class refinable { public: typedef RecursiveLock lock_type ; ///< lock type typedef Alloc allocator_type ; ///< allocator type typedef BackOff back_off ; ///< back-off strategy typedef Stat statistics_type ; ///< internal statistics type static unsigned int const c_nArity = Arity; ///< the arity //@cond typedef refinable_stat real_stat; typedef empty_refinable_stat empty_stat; template <typename Stat2> struct rebind_statistics { typedef refinable< lock_type, c_nArity, back_off, allocator_type, Stat2> other; }; //@endcond protected: //@cond typedef cds::sync::trivial_select_policy lock_selection_policy; class lock_array_type : public cds::sync::lock_array< lock_type, lock_selection_policy, allocator_type > , public std::enable_shared_from_this< lock_array_type > { typedef cds::sync::lock_array< lock_type, lock_selection_policy, allocator_type > lock_array_base; public: lock_array_type( size_t nCapacity ) : lock_array_base( nCapacity ) {} }; typedef std::shared_ptr< lock_array_type > lock_array_ptr; typedef cds::details::Allocator< lock_array_type, allocator_type > lock_array_allocator; typedef unsigned long long owner_t; typedef cds::OS::ThreadId threadId_t; typedef cds::sync::spin spinlock_type; typedef std::unique_lock< spinlock_type > scoped_spinlock; //@endcond protected: //@cond static owner_t const c_nOwnerMask = (((owner_t) 1) << (sizeof(owner_t) * 8 - 1)) - 1; atomics::atomic< owner_t > m_Owner ; ///< owner mark (thread id + boolean flag) atomics::atomic<size_t> m_nCapacity ; ///< lock array capacity lock_array_ptr m_arrLocks[ c_nArity ] ; ///< Lock array. The capacity of array is specified in constructor. spinlock_type m_access ; ///< access to m_arrLocks statistics_type m_Stat ; ///< internal statistics //@endcond protected: //@cond struct lock_array_disposer { void operator()( lock_array_type * pArr ) { // Seems, there is a false positive in std::shared_ptr deallocation in uninstrumented libc++ // see, for example, https://groups.google.com/forum/#!topic/thread-sanitizer/eHu4dE_z7Cc // https://reviews.llvm.org/D21609 CDS_TSAN_ANNOTATE_IGNORE_WRITES_BEGIN; lock_array_allocator().Delete( pArr ); CDS_TSAN_ANNOTATE_IGNORE_WRITES_END; } }; lock_array_ptr create_lock_array( size_t nCapacity ) { return lock_array_ptr( lock_array_allocator().New( nCapacity ), lock_array_disposer()); } void acquire( size_t const * arrHash, lock_array_ptr * pLockArr, lock_type ** parrLock ) { owner_t me = (owner_t) cds::OS::get_current_thread_id(); owner_t who; size_t cur_capacity; back_off bkoff; while ( true ) { { scoped_spinlock sl(m_access); for ( unsigned int i = 0; i < c_nArity; ++i ) pLockArr[i] = m_arrLocks[i]; cur_capacity = m_nCapacity.load( atomics::memory_order_acquire ); } // wait while resizing while ( true ) { who = m_Owner.load( atomics::memory_order_acquire ); if ( !( who & 1 ) || (who >> 1) == (me & c_nOwnerMask)) break; bkoff(); m_Stat.onCellWaitResizing(); } if ( cur_capacity == m_nCapacity.load( atomics::memory_order_acquire )) { size_t const nMask = pLockArr[0]->size() - 1; assert( cds::beans::is_power2( nMask + 1 )); for ( unsigned int i = 0; i < c_nArity; ++i ) { parrLock[i] = &( pLockArr[i]->at( arrHash[i] & nMask )); parrLock[i]->lock(); } who = m_Owner.load( atomics::memory_order_acquire ); if ( ( !(who & 1) || (who >> 1) == (me & c_nOwnerMask)) && cur_capacity == m_nCapacity.load( atomics::memory_order_acquire )) { m_Stat.onCellLock(); return; } for ( unsigned int i = 0; i < c_nArity; ++i ) parrLock[i]->unlock(); m_Stat.onCellLockFailed(); } else m_Stat.onCellArrayChanged(); // clears pLockArr can lead to calling dtor for each item of pLockArr[i] that may be a heavy-weighted operation // (each pLockArr[i] is a shared pointer to array of a ton of mutexes) // It is better to do this before the next loop iteration where we will use spin-locked assignment to pLockArr // However, destructing a lot of mutexes under spin-lock is a bad solution for ( unsigned int i = 0; i < c_nArity; ++i ) pLockArr[i].reset(); } } bool try_second_acquire( size_t const * arrHash, lock_type ** parrLock ) { // It is assumed that the current thread already has a lock // and requires a second lock for other hash size_t const nMask = m_nCapacity.load(atomics::memory_order_acquire) - 1; size_t nCell = m_arrLocks[0]->try_lock( arrHash[0] & nMask); if ( nCell == lock_array_type::c_nUnspecifiedCell ) { m_Stat.onSecondCellLockFailed(); return false; } parrLock[0] = &(m_arrLocks[0]->at(nCell)); for ( unsigned int i = 1; i < c_nArity; ++i ) { parrLock[i] = &( m_arrLocks[i]->at( m_arrLocks[i]->lock( arrHash[i] & nMask))); } m_Stat.onSecondCellLock(); return true; } void acquire_all() { owner_t me = (owner_t) cds::OS::get_current_thread_id(); back_off bkoff; while ( true ) { owner_t ownNull = 0; if ( m_Owner.compare_exchange_strong( ownNull, (me << 1) | 1, atomics::memory_order_acq_rel, atomics::memory_order_relaxed )) { m_arrLocks[0]->lock_all(); m_Stat.onFullLock(); return; } bkoff(); m_Stat.onFullLockIter(); } } void release_all() { m_arrLocks[0]->unlock_all(); m_Owner.store( 0, atomics::memory_order_release ); } void acquire_resize( lock_array_ptr * pOldLocks ) { owner_t me = (owner_t) cds::OS::get_current_thread_id(); size_t cur_capacity; while ( true ) { { scoped_spinlock sl(m_access); for ( unsigned int i = 0; i < c_nArity; ++i ) pOldLocks[i] = m_arrLocks[i]; cur_capacity = m_nCapacity.load( atomics::memory_order_acquire ); } // global lock owner_t ownNull = 0; if ( m_Owner.compare_exchange_strong( ownNull, (me << 1) | 1, atomics::memory_order_acq_rel, atomics::memory_order_relaxed )) { if ( cur_capacity == m_nCapacity.load( atomics::memory_order_acquire )) { pOldLocks[0]->lock_all(); m_Stat.onResizeLock(); return; } m_Owner.store( 0, atomics::memory_order_release ); m_Stat.onResizeLockArrayChanged(); } else m_Stat.onResizeLockIter(); // clears pOldLocks can lead to calling dtor for each item of pOldLocks[i] that may be a heavy-weighted operation // (each pOldLocks[i] is a shared pointer to array of a ton of mutexes) // It is better to do this before the next loop iteration where we will use spin-locked assignment to pOldLocks // However, destructing a lot of mutexes under spin-lock is a bad solution for ( unsigned int i = 0; i < c_nArity; ++i ) pOldLocks[i].reset(); } } void release_resize( lock_array_ptr * pOldLocks ) { m_Owner.store( 0, atomics::memory_order_release ); pOldLocks[0]->unlock_all(); } //@endcond public: //@cond class scoped_cell_lock { lock_type * m_arrLock[ c_nArity ]; lock_array_ptr m_arrLockArr[ c_nArity ]; public: scoped_cell_lock( refinable& policy, size_t const* arrHash ) { policy.acquire( arrHash, m_arrLockArr, m_arrLock ); } ~scoped_cell_lock() { for ( unsigned int i = 0; i < c_nArity; ++i ) m_arrLock[i]->unlock(); } }; class scoped_cell_trylock { lock_type * m_arrLock[ c_nArity ]; bool m_bLocked; public: scoped_cell_trylock( refinable& policy, size_t const* arrHash ) { m_bLocked = policy.try_second_acquire( arrHash, m_arrLock ); } ~scoped_cell_trylock() { if ( m_bLocked ) { for ( unsigned int i = 0; i < c_nArity; ++i ) m_arrLock[i]->unlock(); } } bool locked() const { return m_bLocked; } }; class scoped_full_lock { refinable& m_policy; public: scoped_full_lock( refinable& policy ) : m_policy( policy ) { policy.acquire_all(); } ~scoped_full_lock() { m_policy.release_all(); } }; class scoped_resize_lock { refinable& m_policy; lock_array_ptr m_arrLocks[ c_nArity ]; public: scoped_resize_lock( refinable& policy ) : m_policy(policy) { policy.acquire_resize( m_arrLocks ); } ~scoped_resize_lock() { m_policy.release_resize( m_arrLocks ); } }; //@endcond public: /// Constructor refinable( size_t nLockCount ///< The size of lock array. Must be power of two. ) : m_Owner(0) , m_nCapacity( nLockCount ) { assert( cds::beans::is_power2( nLockCount )); for ( unsigned int i = 0; i < c_nArity; ++i ) m_arrLocks[i] = create_lock_array( nLockCount ); } //@cond void resize( size_t nCapacity ) { lock_array_ptr pNew[ c_nArity ]; for ( unsigned int i = 0; i < c_nArity; ++i ) pNew[i] = create_lock_array( nCapacity ); { scoped_spinlock sl(m_access); m_nCapacity.store( nCapacity, atomics::memory_order_release ); for ( unsigned int i = 0; i < c_nArity; ++i ) m_arrLocks[i] = pNew[i]; } m_Stat.onResize(); } //@endcond /// Returns lock array size /** Lock array size is not a constant for \p refinable policy and can be changed when the set is resized. */ size_t lock_count() const { return m_nCapacity.load(atomics::memory_order_relaxed); } /// Returns the arity of \p refinable mutex policy constexpr unsigned int arity() const noexcept { return c_nArity; } /// Returns internal statistics statistics_type const& statistics() const { return m_Stat; } }; /// \p HopscotchHashset internal statistics struct stat { typedef cds::atomicity::event_counter counter_type ; ///< Counter type counter_type m_nRelocateCallCount ; ///< Count of \p relocate() function call counter_type m_nRelocateRoundCount ; ///< Count of attempts to relocate items counter_type m_nFalseRelocateCount ; ///< Count of unneeded attempts of \p relocate call counter_type m_nSuccessRelocateCount ; ///< Count of successful item relocating counter_type m_nRelocateAboveThresholdCount; ///< Count of item relocating above probeset threshold counter_type m_nFailedRelocateCount ; ///< Count of failed relocation attemp (when all probeset is full) counter_type m_nResizeCallCount ; ///< Count of \p resize() function call counter_type m_nFalseResizeCount ; ///< Count of false \p resize() function call (when other thread has been resized the set) counter_type m_nResizeSuccessNodeMove; ///< Count of successful node moving when resizing counter_type m_nResizeRelocateCall ; ///< Count of \p relocate() function call from \p resize function counter_type m_nInsertSuccess ; ///< Count of successful \p insert() function call counter_type m_nInsertFailed ; ///< Count of failed \p insert() function call counter_type m_nInsertResizeCount ; ///< Count of \p resize() function call from \p insert() counter_type m_nInsertRelocateCount ; ///< Count of \p relocate() function call from \p insert() counter_type m_nInsertRelocateFault ; ///< Count of failed \p relocate() function call from \p insert() counter_type m_nUpdateExistCount ; ///< Count of call \p update() function for existing node counter_type m_nUpdateSuccessCount ; ///< Count of successful \p insert() function call for new node counter_type m_nUpdateResizeCount ; ///< Count of \p resize() function call from \p update() counter_type m_nUpdateRelocateCount ; ///< Count of \p relocate() function call from \p update() counter_type m_nUpdateRelocateFault ; ///< Count of failed \p relocate() function call from \p update() counter_type m_nUnlinkSuccess ; ///< Count of success \p unlink() function call counter_type m_nUnlinkFailed ; ///< Count of failed \p unlink() function call counter_type m_nEraseSuccess ; ///< Count of success \p erase() function call counter_type m_nEraseFailed ; ///< Count of failed \p erase() function call counter_type m_nFindSuccess ; ///< Count of success \p find() function call counter_type m_nFindFailed ; ///< Count of failed \p find() function call counter_type m_nFindEqualSuccess ; ///< Count of success \p find_equal() function call counter_type m_nFindEqualFailed ; ///< Count of failed \p find_equal() function call counter_type m_nFindWithSuccess ; ///< Count of success \p find_with() function call counter_type m_nFindWithFailed ; ///< Count of failed \p find_with() function call //@cond void onRelocateCall() { ++m_nRelocateCallCount; } void onRelocateRound() { ++m_nRelocateRoundCount; } void onFalseRelocateRound() { ++m_nFalseRelocateCount; } void onSuccessRelocateRound(){ ++m_nSuccessRelocateCount; } void onRelocateAboveThresholdRound() { ++m_nRelocateAboveThresholdCount; } void onFailedRelocate() { ++m_nFailedRelocateCount; } void onResizeCall() { ++m_nResizeCallCount; } void onFalseResizeCall() { ++m_nFalseResizeCount; } void onResizeSuccessMove() { ++m_nResizeSuccessNodeMove; } void onResizeRelocateCall() { ++m_nResizeRelocateCall; } void onInsertSuccess() { ++m_nInsertSuccess; } void onInsertFailed() { ++m_nInsertFailed; } void onInsertResize() { ++m_nInsertResizeCount; } void onInsertRelocate() { ++m_nInsertRelocateCount; } void onInsertRelocateFault() { ++m_nInsertRelocateFault; } void onUpdateExist() { ++m_nUpdateExistCount; } void onUpdateSuccess() { ++m_nUpdateSuccessCount; } void onUpdateResize() { ++m_nUpdateResizeCount; } void onUpdateRelocate() { ++m_nUpdateRelocateCount; } void onUpdateRelocateFault() { ++m_nUpdateRelocateFault; } void onUnlinkSuccess() { ++m_nUnlinkSuccess; } void onUnlinkFailed() { ++m_nUnlinkFailed; } void onEraseSuccess() { ++m_nEraseSuccess; } void onEraseFailed() { ++m_nEraseFailed; } void onFindSuccess() { ++m_nFindSuccess; } void onFindFailed() { ++m_nFindFailed; } void onFindWithSuccess() { ++m_nFindWithSuccess; } void onFindWithFailed() { ++m_nFindWithFailed; } //@endcond }; /// HopscotchHashset empty internal statistics struct empty_stat { //@cond void onRelocateCall() const {} void onRelocateRound() const {} void onFalseRelocateRound() const {} void onSuccessRelocateRound()const {} void onRelocateAboveThresholdRound() const {} void onFailedRelocate() const {} void onResizeCall() const {} void onFalseResizeCall() const {} void onResizeSuccessMove() const {} void onResizeRelocateCall() const {} void onInsertSuccess() const {} void onInsertFailed() const {} void onInsertResize() const {} void onInsertRelocate() const {} void onInsertRelocateFault() const {} void onUpdateExist() const {} void onUpdateSuccess() const {} void onUpdateResize() const {} void onUpdateRelocate() const {} void onUpdateRelocateFault() const {} void onUnlinkSuccess() const {} void onUnlinkFailed() const {} void onEraseSuccess() const {} void onEraseFailed() const {} void onFindSuccess() const {} void onFindFailed() const {} void onFindWithSuccess() const {} void onFindWithFailed() const {} //@endcond }; /// Type traits for HopscotchHashset class struct traits { /// Hook used /** Possible values are: hopscotch_hashset::base_hook, hopscotch_hashset::member_hook, hopscotch_hashset::traits_hook. */ typedef base_hook<> hook; /// Hash functors tuple /** This is mandatory type and has no predefined one. At least, two hash functors should be provided. All hash functor should be orthogonal (different): for each <tt> i,j: i != j => h[i](x) != h[j](x) </tt>. The hash functors are defined as <tt> std::tuple< H1, H2, ... Hn > </tt>: \@code cds::opt::hash< std::tuple< h1, h2 > > \@endcode The number of hash functors specifies the number \p k - the count of hash tables in hopscotch hashing. To specify hash tuple in traits you should use \p cds::opt::hash_tuple: \code struct my_traits: public cds::intrusive::hopscotch_hashset::traits { typedef cds::opt::hash_tuple< hash1, hash2 > hash; }; \endcode */ typedef cds::opt::none hash; /// Concurrent access policy /** Available opt::mutex_policy types: - \p hopscotch_hashset::striping - simple, but the lock array is not resizable - \p hopscotch_hashset::refinable - resizable lock array, but more complex access to set data. Default is \p hopscotch_hashset::striping. */ typedef hopscotch_hashset::striping<> mutex_policy; /// Key equality functor /** Default is <tt>std::equal_to<T></tt> */ typedef opt::none equal_to; /// Key comparing functor /** No default functor is provided. If the option is not specified, the \p less is used. */ typedef opt::none compare; /// specifies binary predicate used for key comparison. /** Default is \p std::less<T>. */ typedef opt::none less; /// Item counter /** The type for item counting feature. Default is \p cds::atomicity::item_counter Only atomic item counter type is allowed. */ typedef atomicity::item_counter item_counter; /// Allocator type /** The allocator type for allocating bucket tables. */ typedef CDS_DEFAULT_ALLOCATOR allocator; /// Disposer /** The disposer functor is used in \p HopscotchHashset::clear() member function to free set's node. */ typedef intrusive::opt::v::empty_disposer disposer; /// Internal statistics. Available statistics: \p hopscotch_hashset::stat, \p hopscotch_hashset::empty_stat typedef empty_stat stat; }; /// Metafunction converting option list to \p HopscotchHashset traits /** Template argument list \p Options... are: - \p intrusive::opt::hook - hook used. Possible values are: \p hopscotch_hashset::base_hook, \p hopscotch_hashset::member_hook, \p hopscotch_hashset::traits_hook. If the option is not specified, <tt>%hopscotch_hashset::base_hook<></tt> is used. - \p opt::hash - hash functor tuple, mandatory option. At least, two hash functors should be provided. All hash functor should be orthogonal (different): for each <tt> i,j: i != j => h[i](x) != h[j](x) </tt>. The hash functors are passed as <tt> std::tuple< H1, H2, ... Hn > </tt>. The number of hash functors specifies the number \p k - the count of hash tables in hopscotch hashing. - \p opt::mutex_policy - concurrent access policy. Available policies: \p hopscotch_hashset::striping, \p hopscotch_hashset::refinable. Default is \p %hopscotch_hashset::striping. - \p opt::equal_to - key equality functor like \p std::equal_to. If this functor is defined then the probe-set will be unordered. If \p %opt::compare or \p %opt::less option is specified too, then the probe-set will be ordered and \p %opt::equal_to will be ignored. - \p opt::compare - key comparison functor. No default functor is provided. If the option is not specified, the \p %opt::less is used. If \p %opt::compare or \p %opt::less option is specified, then the probe-set will be ordered. - \p opt::less - specifies binary predicate used for key comparison. Default is \p std::less<T>. If \p %opt::compare or \p %opt::less option is specified, then the probe-set will be ordered. - \p opt::item_counter - the type of item counting feature. Default is \p atomicity::item_counter The item counter should be atomic. - \p opt::allocator - the allocator type using for allocating bucket tables. Default is \ref CDS_DEFAULT_ALLOCATOR - \p intrusive::opt::disposer - the disposer type used in \p clear() member function for freeing nodes. Default is \p intrusive::opt::v::empty_disposer - \p opt::stat - internal statistics. Possibly types: \p hopscotch_hashset::stat, \p hopscotch_hashset::empty_stat. Default is \p %hopscotch_hashset::empty_stat The probe set traits \p hopscotch_hashset::probeset_type and \p hopscotch_hashset::store_hash are taken from \p node type specified by \p opt::hook option. */ template <typename... Options> struct make_traits { typedef typename cds::opt::make_options< typename cds::opt::find_type_traits< hopscotch_hashset::traits, Options... >::type ,Options... >::type type ; ///< Result of metafunction }; //@cond namespace details { template <typename Node, typename Probeset> class bucket_entry; template <typename Node> class bucket_entry<Node, hopscotch_hashset::list> { public: typedef Node node_type; typedef hopscotch_hashset::list_probeset_class probeset_class; typedef hopscotch_hashset::list probeset_type; protected: node_type * pHead; unsigned int nSize; public: class iterator { node_type * pNode; friend class bucket_entry; public: iterator() : pNode( nullptr ) {} iterator( node_type * p ) : pNode( p ) {} iterator( iterator const& it) : pNode( it.pNode ) {} iterator& operator=( iterator const& it ) { pNode = it.pNode; return *this; } iterator& operator=( node_type * p ) { pNode = p; return *this; } node_type * operator->() { return pNode; } node_type& operator*() { assert( pNode != nullptr ); return *pNode; } // preinc iterator& operator ++() { if ( pNode ) pNode = pNode->m_pNext; return *this; } bool operator==(iterator const& it ) const { return pNode == it.pNode; } bool operator!=(iterator const& it ) const { return !( *this == it ); } }; public: bucket_entry() : pHead( nullptr ) , nSize(0) { static_assert(( std::is_same<typename node_type::probeset_type, probeset_type>::value ), "Incompatible node type" ); } iterator begin() { return iterator(pHead); } iterator end() { return iterator(); } void insert_after( iterator it, node_type * p ) { node_type * pPrev = it.pNode; if ( pPrev ) { p->m_pNext = pPrev->m_pNext; pPrev->m_pNext = p; } else { // insert as head p->m_pNext = pHead; pHead = p; } ++nSize; } void remove( iterator itPrev, iterator itWhat ) { node_type * pPrev = itPrev.pNode; node_type * pWhat = itWhat.pNode; assert( (!pPrev && pWhat == pHead) || (pPrev && pPrev->m_pNext == pWhat)); if ( pPrev ) pPrev->m_pNext = pWhat->m_pNext; else { assert( pWhat == pHead ); pHead = pHead->m_pNext; } pWhat->clear(); --nSize; } void clear() { node_type * pNext; for ( node_type * pNode = pHead; pNode; pNode = pNext ) { pNext = pNode->m_pNext; pNode->clear(); } nSize = 0; pHead = nullptr; } template <typename Disposer> void clear( Disposer disp ) { node_type * pNext; for ( node_type * pNode = pHead; pNode; pNode = pNext ) { pNext = pNode->m_pNext; pNode->clear(); disp( pNode ); } nSize = 0; pHead = nullptr; } unsigned int size() const { return nSize; } }; template <typename Node, unsigned int Capacity> class bucket_entry<Node, hopscotch_hashset::vector<Capacity>> { public: typedef Node node_type; typedef hopscotch_hashset::vector_probeset_class probeset_class; typedef hopscotch_hashset::vector<Capacity> probeset_type; static unsigned int const c_nCapacity = probeset_type::c_nCapacity; protected: node_type * m_arrNode[c_nCapacity]; unsigned int m_nSize; void shift_up( unsigned int nFrom ) { assert( m_nSize < c_nCapacity ); if ( nFrom < m_nSize ) std::copy_backward( m_arrNode + nFrom, m_arrNode + m_nSize, m_arrNode + m_nSize + 1 ); } void shift_down( node_type ** pFrom ) { assert( m_arrNode <= pFrom && pFrom < m_arrNode + m_nSize); std::copy( pFrom + 1, m_arrNode + m_nSize, pFrom ); } public: class iterator { node_type ** pArr; friend class bucket_entry; public: iterator() : pArr( nullptr ) {} iterator( node_type ** p ) : pArr(p) {} iterator( iterator const& it) : pArr( it.pArr ) {} iterator& operator=( iterator const& it ) { pArr = it.pArr; return *this; } node_type * operator->() { assert( pArr != nullptr ); return *pArr; } node_type& operator*() { assert( pArr != nullptr ); assert( *pArr != nullptr ); return *(*pArr); } // preinc iterator& operator ++() { ++pArr; return *this; } bool operator==(iterator const& it ) const { return pArr == it.pArr; } bool operator!=(iterator const& it ) const { return !( *this == it ); } }; public: bucket_entry() : m_nSize(0) { memset( m_arrNode, 0, sizeof(m_arrNode)); static_assert(( std::is_same<typename node_type::probeset_type, probeset_type>::value ), "Incompatible node type" ); } iterator begin() { return iterator(m_arrNode); } iterator end() { return iterator(m_arrNode + size()); } void insert_after( iterator it, node_type * p ) { assert( m_nSize < c_nCapacity ); assert( !it.pArr || (m_arrNode <= it.pArr && it.pArr <= m_arrNode + m_nSize)); if ( it.pArr ) { shift_up( static_cast<unsigned int>(it.pArr - m_arrNode) + 1 ); it.pArr[1] = p; } else { shift_up(0); m_arrNode[0] = p; } ++m_nSize; } void remove( iterator /*itPrev*/, iterator itWhat ) { itWhat->clear(); shift_down( itWhat.pArr ); --m_nSize; } void clear() { m_nSize = 0; } template <typename Disposer> void clear( Disposer disp ) { for ( unsigned int i = 0; i < m_nSize; ++i ) { disp( m_arrNode[i] ); } m_nSize = 0; } unsigned int size() const { return m_nSize; } }; template <typename Node, unsigned int ArraySize> struct hash_ops { static void store( Node * pNode, size_t const* pHashes ) { memcpy( pNode->m_arrHash, pHashes, sizeof(pHashes[0]) * ArraySize ); } static bool equal_to( Node& node, unsigned int nTable, size_t nHash ) { return node.m_arrHash[nTable] == nHash; } }; template <typename Node> struct hash_ops<Node, 0> { static void store( Node * /*pNode*/, size_t * /*pHashes*/ ) {} static bool equal_to( Node& /*node*/, unsigned int /*nTable*/, size_t /*nHash*/ ) { return true; } }; template <typename NodeTraits, bool Ordered> struct contains; template <typename NodeTraits> struct contains<NodeTraits, true> { template <typename BucketEntry, typename Position, typename Q, typename Compare> static bool find( BucketEntry& probeset, Position& pos, unsigned int /*nTable*/, size_t /*nHash*/, Q const& val, Compare cmp ) { // Ordered version typedef typename BucketEntry::iterator bucket_iterator; bucket_iterator itPrev; for ( bucket_iterator it = probeset.begin(), itEnd = probeset.end(); it != itEnd; ++it ) { int cmpRes = cmp( *NodeTraits::to_value_ptr(*it), val ); if ( cmpRes >= 0 ) { pos.itFound = it; pos.itPrev = itPrev; return cmpRes == 0; } itPrev = it; } pos.itPrev = itPrev; pos.itFound = probeset.end(); return false; } }; template <typename NodeTraits> struct contains<NodeTraits, false> { template <typename BucketEntry, typename Position, typename Q, typename EqualTo> static bool find( BucketEntry& probeset, Position& pos, unsigned int nTable, size_t nHash, Q const& val, EqualTo eq ) { // Unordered version typedef typename BucketEntry::iterator bucket_iterator; typedef typename BucketEntry::node_type node_type; bucket_iterator itPrev; for ( bucket_iterator it = probeset.begin(), itEnd = probeset.end(); it != itEnd; ++it ) { if ( hash_ops<node_type, node_type::hash_array_size>::equal_to( *it, nTable, nHash ) && eq( *NodeTraits::to_value_ptr(*it), val )) { pos.itFound = it; pos.itPrev = itPrev; return true; } itPrev = it; } pos.itPrev = itPrev; pos.itFound = probeset.end(); return false; } }; } // namespace details //@endcond } // namespace hopscotch_hashset /// Hopscotch hash set /** @ingroup cds_intrusive_map Source - [2007] M.Herlihy, N.Shavit, M.Tzafrir "Concurrent Hopscotch Hashing. Technical report" - [2008] Maurice Herlihy, Nir Shavit "The Art of Multiprocessor Programming" <b>About Hopscotch hashing</b> [From <i>"The Art of Multiprocessor Programming"</i>] <a href="https://en.wikipedia.org/wiki/Hopscotch_hashing">Hopscotch hashing</a> is a hashing algorithm in which a newly added item displaces any earlier item occupying the same slot. For brevity, a table is a k-entry array of items. For a hash set of size N = 2k we use a two-entry array of tables, and two independent hash functions, <tt> h0, h1: KeyRange -> 0,...,k-1</tt> mapping the set of possible keys to entries in he array. To test whether a value \p x is in the set, <tt>find(x)</tt> tests whether either <tt>table[0][h0(x)]</tt> or <tt>table[1][h1(x)]</tt> is equal to \p x. Similarly, <tt>erase(x)</tt>checks whether \p x is in either <tt>table[0][h0(x)]</tt> or <tt>table[1][h1(x)]</tt>, ad removes it if found. The <tt>insert(x)</tt> successively "kicks out" conflicting items until every key has a slot. To add \p x, the method swaps \p x with \p y, the current occupant of <tt>table[0][h0(x)]</tt>. If the prior value was \p nullptr, it is done. Otherwise, it swaps the newly nest-less value \p y for the current occupant of <tt>table[1][h1(y)]</tt> in the same way. As before, if the prior value was \p nullptr, it is done. Otherwise, the method continues swapping entries (alternating tables) until it finds an empty slot. We might not find an empty slot, either because the table is full, or because the sequence of displacement forms a cycle. We therefore need an upper limit on the number of successive displacements we are willing to undertake. When this limit is exceeded, we resize the hash table, choose new hash functions and start over. For concurrent hopscotch hashing, rather than organizing the set as a two-dimensional table of items, we use two-dimensional table of probe sets, where a probe set is a constant-sized set of items with the same hash code. Each probe set holds at most \p PROBE_SIZE items, but the algorithm tries to ensure that when the set is quiescent (i.e no method call in progress) each probe set holds no more than <tt>THRESHOLD < PROBE_SET</tt> items. While method calls are in-flight, a probe set may temporarily hold more than \p THRESHOLD but never more than \p PROBE_SET items. In current implementation, a probe set can be defined either as a (single-linked) list or as a fixed-sized vector, optionally ordered. In description above two-table hopscotch hashing (<tt>k = 2</tt>) has been considered. We can generalize this approach for <tt>k >= 2</tt> when we have \p k hash functions <tt>h[0], ... h[k-1]</tt> and \p k tables <tt>table[0], ... table[k-1]</tt>. The search in probe set is linear, the complexity is <tt> O(PROBE_SET) </tt>. The probe set may be ordered or not. Ordered probe set can be more efficient since the average search complexity is <tt>O(PROBE_SET/2)</tt>. However, the overhead of sorting can eliminate a gain of ordered search. The probe set is ordered if \p compare or \p less is specified in \p Traits template parameter. Otherwise, the probe set is unordered and \p Traits should provide \p equal_to predicate. The \p cds::intrusive::hopscotch_hashset namespace contains \p %HopscotchHashset-related declarations. Template arguments: - \p T - the type stored in the set. The type must be based on \p hopscotch_hashset::node (for \p hopscotch_hashset::base_hook) or it must have a member of type %hopscotch_hashset::node (for \p hopscotch_hashset::member_hook), or it must be convertible to \p %hopscotch_hashset::node (for \p hopscotch_hashset::traits_hook) - \p Traits - type traits, default is \p hopscotch_hashset::traits. It is possible to declare option-based set with \p hopscotch_hashset::make_traits metafunction result as \p Traits template argument. <b>How to use</b> You should incorporate \p hopscotch_hashset::node into your struct \p T and provide appropriate \p hopscotch_hashset::traits::hook in your \p Traits template parameters. Usually, for \p Traits you define a struct based on \p hopscotch_hashset::traits. Example for base hook and list-based probe-set: \code #include <cds/intrusive/hopscotch_hashset.h> // Data stored in hopscotch set // We use list as probe-set container and store hash values in the node // (since we use two hash functions we should store 2 hash values per node) struct my_data: public cds::intrusive::hopscotch_hashset::node< cds::intrusive::hopscotch_hashset::list, 2 > { // key field std::string strKey; // other data // ... }; // Provide equal_to functor for my_data since we will use unordered probe-set struct my_data_equal_to { bool operator()( const my_data& d1, const my_data& d2 ) const { return d1.strKey.compare( d2.strKey ) == 0; } bool operator()( const my_data& d, const std::string& s ) const { return d.strKey.compare(s) == 0; } bool operator()( const std::string& s, const my_data& d ) const { return s.compare( d.strKey ) == 0; } }; // Provide two hash functor for my_data struct hash1 { size_t operator()(std::string const& s) const { return cds::opt::v::hash<std::string>( s ); } size_t operator()( my_data const& d ) const { return (*this)( d.strKey ); } }; struct hash2: private hash1 { size_t operator()(std::string const& s) const { size_t h = ~( hash1::operator()(s)); return ~h + 0x9e3779b9 + (h << 6) + (h >> 2); } size_t operator()( my_data const& d ) const { return (*this)( d.strKey ); } }; // Declare type traits struct my_traits: public cds::intrusive::hopscotch_hashset::traits { typedef cds::intrusive::hopscotch_hashset::base_hook< cds::intrusive::hopscotch_hashset::probeset_type< my_data::probeset_type > ,cds::intrusive::hopscotch_hashset::store_hash< my_data::hash_array_size > > hook; typedef my_data_equa_to equal_to; typedef cds::opt::hash_tuple< hash1, hash2 > hash; }; // Declare HopscotchHashset type typedef cds::intrusive::HopscotchHashset< my_data, my_traits > my_hopscotch_hashset; // Equal option-based declaration typedef cds::intrusive::HopscotchHashset< my_data, cds::intrusive::hopscotch_hashset::make_traits< cds::intrusive::opt::hook< cds::intrusive::hopscotch_hashset::base_hook< cds::intrusive::hopscotch_hashset::probeset_type< my_data::probeset_type > ,cds::intrusive::hopscotch_hashset::store_hash< my_data::hash_array_size > > > ,cds::opt::hash< std::tuple< hash1, hash2 > > ,cds::opt::equal_to< my_data_equal_to > >::type > opt_hopscotch_hashset_set; \endcode If we provide \p compare function instead of \p equal_to for \p my_data we get as a result a hopscotch set with ordered probe set that may improve performance. Example for base hook and ordered vector-based probe-set: \code #include <cds/intrusive/hopscotch_hashset.h> // Data stored in hopscotch set // We use a vector of capacity 4 as probe-set container and store hash values in the node // (since we use two hash functions we should store 2 hash values per node) struct my_data: public cds::intrusive::hopscotch_hashset::node< cds::intrusive::hopscotch_hashset::vector<4>, 2 > { // key field std::string strKey; // other data // ... }; // Provide compare functor for my_data since we want to use ordered probe-set struct my_data_compare { int operator()( const my_data& d1, const my_data& d2 ) const { return d1.strKey.compare( d2.strKey ); } int operator()( const my_data& d, const std::string& s ) const { return d.strKey.compare(s); } int operator()( const std::string& s, const my_data& d ) const { return s.compare( d.strKey ); } }; // Provide two hash functor for my_data struct hash1 { size_t operator()(std::string const& s) const { return cds::opt::v::hash<std::string>( s ); } size_t operator()( my_data const& d ) const { return (*this)( d.strKey ); } }; struct hash2: private hash1 { size_t operator()(std::string const& s) const { size_t h = ~( hash1::operator()(s)); return ~h + 0x9e3779b9 + (h << 6) + (h >> 2); } size_t operator()( my_data const& d ) const { return (*this)( d.strKey ); } }; // Declare type traits struct my_traits: public cds::intrusive::hopscotch_hashset::traits { typedef cds::intrusive::hopscotch_hashset::base_hook< cds::intrusive::hopscotch_hashset::probeset_type< my_data::probeset_type > ,cds::intrusive::hopscotch_hashset::store_hash< my_data::hash_array_size > > hook; typedef my_data_compare compare; typedef cds::opt::hash_tuple< hash1, hash2 > hash; }; // Declare HopscotchHashset type typedef cds::intrusive::HopscotchHashset< my_data, my_traits > my_hopscotch_hashset; // Equal option-based declaration typedef cds::intrusive::HopscotchHashset< my_data, cds::intrusive::hopscotch_hashset::make_traits< cds::intrusive::opt::hook< cds::intrusive::hopscotch_hashset::base_hook< cds::intrusive::hopscotch_hashset::probeset_type< my_data::probeset_type > ,cds::intrusive::hopscotch_hashset::store_hash< my_data::hash_array_size > > > ,cds::opt::hash< std::tuple< hash1, hash2 > > ,cds::opt::compare< my_data_compare > >::type > opt_hopscotch_hashset_set; \endcode */ template <typename T, typename Traits = hopscotch_hashset::traits> class HopscotchHashset { public: typedef T value_type; ///< The value type stored in the set typedef Traits traits; ///< Set traits typedef typename traits::hook hook; ///< hook type typedef typename hook::node_type node_type; ///< node type typedef typename get_node_traits< value_type, node_type, hook>::type node_traits; ///< node traits typedef typename traits::hash hash; ///< hash functor tuple wrapped for internal use typedef typename hash::hash_tuple_type hash_tuple_type; ///< Type of hash tuple typedef typename traits::stat stat; ///< internal statistics type typedef typename traits::mutex_policy original_mutex_policy; ///< Concurrent access policy, see \p hopscotch_hashset::traits::mutex_policy //@cond typedef typename original_mutex_policy::template rebind_statistics< typename std::conditional< std::is_same< stat, hopscotch_hashset::empty_stat >::value ,typename original_mutex_policy::empty_stat ,typename original_mutex_policy::real_stat >::type >::other mutex_policy; //@endcond /// Probe set should be ordered or not /** If \p Traits specifies \p cmpare or \p less functor then the set is ordered. Otherwise, it is unordered and \p Traits should provide \p equal_to functor. */ static bool const c_isSorted = !( std::is_same< typename traits::compare, opt::none >::value && std::is_same< typename traits::less, opt::none >::value ); static size_t const c_nArity = hash::size ; ///< the arity of hopscotch_hashset hashing: the number of hash functors provided; minimum 2. /// Key equality functor; used only for unordered probe-set typedef typename opt::details::make_equal_to< value_type, traits, !c_isSorted>::type key_equal_to; /// key comparing functor based on \p opt::compare and \p opt::less option setter. Used only for ordered probe set typedef typename opt::details::make_comparator< value_type, traits >::type key_comparator; /// allocator type typedef typename traits::allocator allocator; /// item counter type typedef typename traits::item_counter item_counter; /// node disposer typedef typename traits::disposer disposer; protected: //@cond typedef typename node_type::probeset_class probeset_class; typedef typename node_type::probeset_type probeset_type; static unsigned int const c_nNodeHashArraySize = node_type::hash_array_size; typedef typename mutex_policy::scoped_cell_lock scoped_cell_lock; typedef typename mutex_policy::scoped_cell_trylock scoped_cell_trylock; typedef typename mutex_policy::scoped_full_lock scoped_full_lock; typedef typename mutex_policy::scoped_resize_lock scoped_resize_lock; typedef hopscotch_hashset::details::bucket_entry< node_type, probeset_type > bucket_entry; typedef typename bucket_entry::iterator bucket_iterator; typedef cds::details::Allocator< bucket_entry, allocator > bucket_table_allocator; typedef size_t hash_array[c_nArity] ; ///< hash array struct position { bucket_iterator itPrev; bucket_iterator itFound; }; typedef hopscotch_hashset::details::contains< node_traits, c_isSorted > contains_action; template <typename Predicate> struct predicate_wrapper { typedef typename std::conditional< c_isSorted, cds::opt::details::make_comparator_from_less<Predicate>, Predicate>::type type; }; typedef typename std::conditional< c_isSorted, key_comparator, key_equal_to >::type key_predicate; //@endcond public: static unsigned int const c_nDefaultProbesetSize = 4; ///< default probeset size static size_t const c_nDefaultInitialSize = 16; ///< default initial size static unsigned int const c_nRelocateLimit = c_nArity * 2 - 1; ///< Count of attempts to relocate before giving up protected: bucket_entry * m_BucketTable[ c_nArity ] ; ///< Bucket tables atomics::atomic<size_t> m_nBucketMask ; ///< Hash bitmask; bucket table size minus 1. unsigned int const m_nProbesetSize ; ///< Probe set size unsigned int const m_nProbesetThreshold ; ///< Probe set threshold hash m_Hash ; ///< Hash functor tuple mutex_policy m_MutexPolicy ; ///< concurrent access policy item_counter m_ItemCounter ; ///< item counter mutable stat m_Stat ; ///< internal statistics protected: //@cond static void check_common_constraints() { static_assert( (c_nArity == mutex_policy::c_nArity), "The count of hash functors must be equal to mutex_policy arity" ); } void check_probeset_properties() const { assert( m_nProbesetThreshold < m_nProbesetSize ); // if probe set type is hopscotch_hashset::vector<N> then m_nProbesetSize == N assert( node_type::probeset_size == 0 || node_type::probeset_size == m_nProbesetSize ); } template <typename Q> void hashing( size_t * pHashes, Q const& v ) const { m_Hash( pHashes, v ); } void copy_hash( size_t * pHashes, value_type const& v ) const { constexpr_if ( c_nNodeHashArraySize != 0 ) memcpy( pHashes, node_traits::to_node_ptr( v )->get_hash(), sizeof( pHashes[0] ) * c_nNodeHashArraySize ); else hashing( pHashes, v ); } bucket_entry& bucket( unsigned int nTable, size_t nHash ) { assert( nTable < c_nArity ); return m_BucketTable[nTable][nHash & m_nBucketMask.load( atomics::memory_order_relaxed ) ]; } static void store_hash( node_type * pNode, size_t * pHashes ) { hopscotch_hashset::details::hash_ops< node_type, c_nNodeHashArraySize >::store( pNode, pHashes ); } static bool equal_hash( node_type& node, unsigned int nTable, size_t nHash ) { return hopscotch_hashset::details::hash_ops< node_type, c_nNodeHashArraySize >::equal_to( node, nTable, nHash ); } void allocate_bucket_tables( size_t nSize ) { assert( cds::beans::is_power2( nSize )); m_nBucketMask.store( nSize - 1, atomics::memory_order_release ); bucket_table_allocator alloc; for ( unsigned int i = 0; i < c_nArity; ++i ) m_BucketTable[i] = alloc.NewArray( nSize ); } static void free_bucket_tables( bucket_entry ** pTable, size_t nCapacity ) { bucket_table_allocator alloc; for ( unsigned int i = 0; i < c_nArity; ++i ) { alloc.Delete( pTable[i], nCapacity ); pTable[i] = nullptr; } } void free_bucket_tables() { free_bucket_tables( m_BucketTable, m_nBucketMask.load( atomics::memory_order_relaxed ) + 1 ); } static constexpr unsigned int const c_nUndefTable = (unsigned int) -1; template <typename Q, typename Predicate > unsigned int contains( position * arrPos, size_t * arrHash, Q const& val, Predicate pred ) { // Buckets must be locked for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry& probeset = bucket( i, arrHash[i] ); if ( contains_action::find( probeset, arrPos[i], i, arrHash[i], val, pred )) return i; } return c_nUndefTable; } template <typename Q, typename Predicate, typename Func> value_type * erase_( Q const& val, Predicate pred, Func f ) { hash_array arrHash; hashing( arrHash, val ); position arrPos[ c_nArity ]; { scoped_cell_lock guard( m_MutexPolicy, arrHash ); unsigned int nTable = contains( arrPos, arrHash, val, pred ); if ( nTable != c_nUndefTable ) { node_type& node = *arrPos[nTable].itFound; f( *node_traits::to_value_ptr(node)); bucket( nTable, arrHash[nTable]).remove( arrPos[nTable].itPrev, arrPos[nTable].itFound ); --m_ItemCounter; m_Stat.onEraseSuccess(); return node_traits::to_value_ptr( node ); } } m_Stat.onEraseFailed(); return nullptr; } template <typename Q, typename Predicate, typename Func> bool find_( Q& val, Predicate pred, Func f ) { hash_array arrHash; position arrPos[ c_nArity ]; hashing( arrHash, val ); scoped_cell_lock sl( m_MutexPolicy, arrHash ); unsigned int nTable = contains( arrPos, arrHash, val, pred ); if ( nTable != c_nUndefTable ) { f( *node_traits::to_value_ptr( *arrPos[nTable].itFound ), val ); m_Stat.onFindSuccess(); return true; } m_Stat.onFindFailed(); return false; } bool relocate( unsigned int nTable, size_t * arrGoalHash ) { // arrGoalHash contains hash values for relocating element // Relocating element is first one from bucket( nTable, arrGoalHash[nTable] ) probeset m_Stat.onRelocateCall(); hash_array arrHash; value_type * pVal; for ( unsigned int nRound = 0; nRound < c_nRelocateLimit; ++nRound ) { m_Stat.onRelocateRound(); while ( true ) { scoped_cell_lock guard( m_MutexPolicy, arrGoalHash ); bucket_entry& refBucket = bucket( nTable, arrGoalHash[nTable] ); if ( refBucket.size() < m_nProbesetThreshold ) { // probeset is not above the threshold m_Stat.onFalseRelocateRound(); return true; } pVal = node_traits::to_value_ptr( *refBucket.begin()); copy_hash( arrHash, *pVal ); scoped_cell_trylock guard2( m_MutexPolicy, arrHash ); if ( !guard2.locked()) continue ; // try one more time refBucket.remove( typename bucket_entry::iterator(), refBucket.begin()); unsigned int i = (nTable + 1) % c_nArity; // try insert into free probeset while ( i != nTable ) { bucket_entry& bkt = bucket( i, arrHash[i] ); if ( bkt.size() < m_nProbesetThreshold ) { position pos; contains_action::find( bkt, pos, i, arrHash[i], *pVal, key_predicate()) ; // must return false! bkt.insert_after( pos.itPrev, node_traits::to_node_ptr( pVal )); m_Stat.onSuccessRelocateRound(); return true; } i = ( i + 1 ) % c_nArity; } // try insert into partial probeset i = (nTable + 1) % c_nArity; while ( i != nTable ) { bucket_entry& bkt = bucket( i, arrHash[i] ); if ( bkt.size() < m_nProbesetSize ) { position pos; contains_action::find( bkt, pos, i, arrHash[i], *pVal, key_predicate()) ; // must return false! bkt.insert_after( pos.itPrev, node_traits::to_node_ptr( pVal )); nTable = i; memcpy( arrGoalHash, arrHash, sizeof(arrHash)); m_Stat.onRelocateAboveThresholdRound(); goto next_iteration; } i = (i + 1) % c_nArity; } // all probeset is full, relocating fault refBucket.insert_after( typename bucket_entry::iterator(), node_traits::to_node_ptr( pVal )); m_Stat.onFailedRelocate(); return false; } next_iteration:; } return false; } void resize() { m_Stat.onResizeCall(); size_t nOldCapacity = bucket_count( atomics::memory_order_acquire ); bucket_entry* pOldTable[ c_nArity ]; { scoped_resize_lock guard( m_MutexPolicy ); if ( nOldCapacity != bucket_count()) { m_Stat.onFalseResizeCall(); return; } size_t nCapacity = nOldCapacity * 2; m_MutexPolicy.resize( nCapacity ); memcpy( pOldTable, m_BucketTable, sizeof(pOldTable)); allocate_bucket_tables( nCapacity ); hash_array arrHash; position arrPos[ c_nArity ]; for ( unsigned int nTable = 0; nTable < c_nArity; ++nTable ) { bucket_entry * pTable = pOldTable[nTable]; for ( size_t k = 0; k < nOldCapacity; ++k ) { bucket_iterator itNext; for ( bucket_iterator it = pTable[k].begin(), itEnd = pTable[k].end(); it != itEnd; it = itNext ) { itNext = it; ++itNext; value_type& val = *node_traits::to_value_ptr( *it ); copy_hash( arrHash, val ); CDS_VERIFY_EQ( contains( arrPos, arrHash, val, key_predicate()), c_nUndefTable ); for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry& refBucket = bucket( i, arrHash[i] ); if ( refBucket.size() < m_nProbesetThreshold ) { refBucket.insert_after( arrPos[i].itPrev, &*it ); m_Stat.onResizeSuccessMove(); goto do_next; } } for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry& refBucket = bucket( i, arrHash[i] ); if ( refBucket.size() < m_nProbesetSize ) { refBucket.insert_after( arrPos[i].itPrev, &*it ); assert( refBucket.size() > 1 ); copy_hash( arrHash, *node_traits::to_value_ptr( *refBucket.begin())); m_Stat.onResizeRelocateCall(); relocate( i, arrHash ); break; } } do_next:; } } } } free_bucket_tables( pOldTable, nOldCapacity ); } constexpr static unsigned int calc_probeset_size( unsigned int nProbesetSize ) noexcept { return std::is_same< probeset_class, hopscotch_hashset::vector_probeset_class >::value ? node_type::probeset_size : (nProbesetSize ? nProbesetSize : ( node_type::probeset_size ? node_type::probeset_size : c_nDefaultProbesetSize )); } //@endcond public: /// Default constructor /** Initial size = \ref c_nDefaultInitialSize Probe set size: - \p c_nDefaultProbesetSize if \p probeset_type is \p hopscotch_hashset::list - \p Capacity if \p probeset_type is <tt> hopscotch_hashset::vector<Capacity> </tt> Probe set threshold = probe set size - 1 */ HopscotchHashset() : m_nProbesetSize( calc_probeset_size(0)) , m_nProbesetThreshold( m_nProbesetSize - 1 ) , m_MutexPolicy( c_nDefaultInitialSize ) { check_common_constraints(); check_probeset_properties(); allocate_bucket_tables( c_nDefaultInitialSize ); } /// Constructs the set object with given probe set size and threshold /** If probe set type is <tt> hopscotch_hashset::vector<Capacity> </tt> vector then \p nProbesetSize is ignored since it should be equal to vector's \p Capacity. */ HopscotchHashset( size_t nInitialSize ///< Initial set size; if 0 - use default initial size \p c_nDefaultInitialSize , unsigned int nProbesetSize ///< probe set size , unsigned int nProbesetThreshold = 0 ///< probe set threshold, <tt>nProbesetThreshold < nProbesetSize</tt>. If 0, <tt>nProbesetThreshold = nProbesetSize - 1</tt> ) : m_nProbesetSize( calc_probeset_size(nProbesetSize)) , m_nProbesetThreshold( nProbesetThreshold ? nProbesetThreshold : m_nProbesetSize - 1 ) , m_MutexPolicy( cds::beans::ceil2(nInitialSize ? nInitialSize : c_nDefaultInitialSize )) { check_common_constraints(); check_probeset_properties(); allocate_bucket_tables( nInitialSize ? cds::beans::ceil2( nInitialSize ) : c_nDefaultInitialSize ); } /// Constructs the set object with given hash functor tuple /** The probe set size and threshold are set as default, see \p HopscotchHashset() */ HopscotchHashset( hash_tuple_type const& h ///< hash functor tuple of type <tt>std::tuple<H1, H2, ... Hn></tt> where <tt> n == \ref c_nArity </tt> ) : m_nProbesetSize( calc_probeset_size(0)) , m_nProbesetThreshold( m_nProbesetSize -1 ) , m_Hash( h ) , m_MutexPolicy( c_nDefaultInitialSize ) { check_common_constraints(); check_probeset_properties(); allocate_bucket_tables( c_nDefaultInitialSize ); } /// Constructs the set object with given probe set properties and hash functor tuple /** If probe set type is <tt> hopscotch_hashset::vector<Capacity> </tt> vector then \p nProbesetSize should be equal to vector's \p Capacity. */ HopscotchHashset( size_t nInitialSize ///< Initial set size; if 0 - use default initial size \p c_nDefaultInitialSize , unsigned int nProbesetSize ///< probe set size, positive integer , unsigned int nProbesetThreshold ///< probe set threshold, <tt>nProbesetThreshold < nProbesetSize</tt>. If 0, <tt>nProbesetThreshold = nProbesetSize - 1</tt> , hash_tuple_type const& h ///< hash functor tuple of type <tt>std::tuple<H1, H2, ... Hn></tt> where <tt> n == \ref c_nArity </tt> ) : m_nProbesetSize( calc_probeset_size(nProbesetSize)) , m_nProbesetThreshold( nProbesetThreshold ? nProbesetThreshold : m_nProbesetSize - 1) , m_Hash( h ) , m_MutexPolicy( cds::beans::ceil2(nInitialSize ? nInitialSize : c_nDefaultInitialSize )) { check_common_constraints(); check_probeset_properties(); allocate_bucket_tables( nInitialSize ? cds::beans::ceil2( nInitialSize ) : c_nDefaultInitialSize ); } /// Constructs the set object with given hash functor tuple (move semantics) /** The probe set size and threshold are set as default, see \p HopscotchHashset() */ HopscotchHashset( hash_tuple_type&& h ///< hash functor tuple of type <tt>std::tuple<H1, H2, ... Hn></tt> where <tt> n == \ref c_nArity </tt> ) : m_nProbesetSize( calc_probeset_size(0)) , m_nProbesetThreshold( m_nProbesetSize / 2 ) , m_Hash( std::forward<hash_tuple_type>(h)) , m_MutexPolicy( c_nDefaultInitialSize ) { check_common_constraints(); check_probeset_properties(); allocate_bucket_tables( c_nDefaultInitialSize ); } /// Constructs the set object with given probe set properties and hash functor tuple (move semantics) /** If probe set type is <tt> hopscotch_hashset::vector<Capacity> </tt> vector then \p nProbesetSize should be equal to vector's \p Capacity. */ HopscotchHashset( size_t nInitialSize ///< Initial set size; if 0 - use default initial size \p c_nDefaultInitialSize , unsigned int nProbesetSize ///< probe set size, positive integer , unsigned int nProbesetThreshold ///< probe set threshold, <tt>nProbesetThreshold < nProbesetSize</tt>. If 0, <tt>nProbesetThreshold = nProbesetSize - 1</tt> , hash_tuple_type&& h ///< hash functor tuple of type <tt>std::tuple<H1, H2, ... Hn></tt> where <tt> n == \ref c_nArity </tt> ) : m_nProbesetSize( calc_probeset_size(nProbesetSize)) , m_nProbesetThreshold( nProbesetThreshold ? nProbesetThreshold : m_nProbesetSize - 1) , m_Hash( std::forward<hash_tuple_type>(h)) , m_MutexPolicy( cds::beans::ceil2(nInitialSize ? nInitialSize : c_nDefaultInitialSize )) { check_common_constraints(); check_probeset_properties(); allocate_bucket_tables( nInitialSize ? cds::beans::ceil2( nInitialSize ) : c_nDefaultInitialSize ); } /// Destructor ~HopscotchHashset() { free_bucket_tables(); } public: /// Inserts new node /** The function inserts \p val in the set if it does not contain an item with key equal to \p val. Returns \p true if \p val is inserted into the set, \p false otherwise. */ bool insert( value_type& val ) { return insert( val, []( value_type& ) {} ); } /// Inserts new node /** The function allows to split creating of new item into two part: - create item with key only - insert new item into the set - if inserting is success, calls \p f functor to initialize value-field of \p val. The functor signature is: \code void func( value_type& val ); \endcode where \p val is the item inserted. The user-defined functor is called only if the inserting is success. */ template <typename Func> bool insert( value_type& val, Func f ) { hash_array arrHash; position arrPos[ c_nArity ]; unsigned int nGoalTable; hashing( arrHash, val ); node_type * pNode = node_traits::to_node_ptr( val ); store_hash( pNode, arrHash ); while (true) { { scoped_cell_lock guard( m_MutexPolicy, arrHash ); if ( contains( arrPos, arrHash, val, key_predicate()) != c_nUndefTable ) { m_Stat.onInsertFailed(); return false; } for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry& refBucket = bucket( i, arrHash[i] ); if ( refBucket.size() < m_nProbesetThreshold ) { refBucket.insert_after( arrPos[i].itPrev, pNode ); f( val ); ++m_ItemCounter; m_Stat.onInsertSuccess(); return true; } } for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry& refBucket = bucket( i, arrHash[i] ); if ( refBucket.size() < m_nProbesetSize ) { refBucket.insert_after( arrPos[i].itPrev, pNode ); f( val ); ++m_ItemCounter; nGoalTable = i; assert( refBucket.size() > 1 ); copy_hash( arrHash, *node_traits::to_value_ptr( *refBucket.begin())); goto do_relocate; } } } m_Stat.onInsertResize(); resize(); } do_relocate: m_Stat.onInsertRelocate(); if ( !relocate( nGoalTable, arrHash )) { m_Stat.onInsertRelocateFault(); m_Stat.onInsertResize(); resize(); } m_Stat.onInsertSuccess(); return true; } /// Updates the node /** The operation performs inserting or changing data with lock-free manner. If the item \p val is not found in the set, then \p val is inserted into the set iff \p bAllowInsert is \p true. Otherwise, the functor \p func is called with item found. The functor \p func signature is: \code void func( bool bNew, value_type& item, value_type& val ); \endcode with arguments: - \p bNew - \p true if the item has been inserted, \p false otherwise - \p item - item of the set - \p val - argument \p val passed into the \p %update() function If new item has been inserted (i.e. \p bNew is \p true) then \p item and \p val arguments refer to the same thing. The functor may change non-key fields of the \p item. Returns std::pair<bool, bool> where \p first is \p true if operation is successful, i.e. the node has been inserted or updated, \p second is \p true if new item has been added or \p false if the item with \p key already exists. */ template <typename Func> std::pair<bool, bool> update( value_type& val, Func func, bool bAllowInsert = true ) { hash_array arrHash; position arrPos[ c_nArity ]; unsigned int nGoalTable; hashing( arrHash, val ); node_type * pNode = node_traits::to_node_ptr( val ); store_hash( pNode, arrHash ); while (true) { { scoped_cell_lock guard( m_MutexPolicy, arrHash ); unsigned int nTable = contains( arrPos, arrHash, val, key_predicate()); if ( nTable != c_nUndefTable ) { func( false, *node_traits::to_value_ptr( *arrPos[nTable].itFound ), val ); m_Stat.onUpdateExist(); return std::make_pair( true, false ); } if ( !bAllowInsert ) return std::make_pair( false, false ); //node_type * pNode = node_traits::to_node_ptr( val ); //store_hash( pNode, arrHash ); for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry& refBucket = bucket( i, arrHash[i] ); if ( refBucket.size() < m_nProbesetThreshold ) { refBucket.insert_after( arrPos[i].itPrev, pNode ); func( true, val, val ); ++m_ItemCounter; m_Stat.onUpdateSuccess(); return std::make_pair( true, true ); } } for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry& refBucket = bucket( i, arrHash[i] ); if ( refBucket.size() < m_nProbesetSize ) { refBucket.insert_after( arrPos[i].itPrev, pNode ); func( true, val, val ); ++m_ItemCounter; nGoalTable = i; assert( refBucket.size() > 1 ); copy_hash( arrHash, *node_traits::to_value_ptr( *refBucket.begin())); goto do_relocate; } } } m_Stat.onUpdateResize(); resize(); } do_relocate: m_Stat.onUpdateRelocate(); if ( !relocate( nGoalTable, arrHash )) { m_Stat.onUpdateRelocateFault(); m_Stat.onUpdateResize(); resize(); } m_Stat.onUpdateSuccess(); return std::make_pair( true, true ); } //@cond template <typename Func> CDS_DEPRECATED("ensure() is deprecated, use update()") std::pair<bool, bool> ensure( value_type& val, Func func ) { return update( val, func, true ); } //@endcond /// Unlink the item \p val from the set /** The function searches the item \p val in the set and unlink it if it is found and is equal to \p val (here, the equality means that \p val belongs to the set: if \p item is an item found then unlink is successful iif <tt>&val == &item</tt>) The function returns \p true if success and \p false otherwise. */ bool unlink( value_type& val ) { hash_array arrHash; hashing( arrHash, val ); position arrPos[ c_nArity ]; { scoped_cell_lock guard( m_MutexPolicy, arrHash ); unsigned int nTable = contains( arrPos, arrHash, val, key_predicate()); if ( nTable != c_nUndefTable && node_traits::to_value_ptr(*arrPos[nTable].itFound) == &val ) { bucket( nTable, arrHash[nTable]).remove( arrPos[nTable].itPrev, arrPos[nTable].itFound ); --m_ItemCounter; m_Stat.onUnlinkSuccess(); return true; } } m_Stat.onUnlinkFailed(); return false; } /// Deletes the item from the set /** \anchor cds_intrusive_HopscotchHashset_erase The function searches an item with key equal to \p val in the set, unlinks it from the set, and returns a pointer to unlinked item. If the item with key equal to \p val is not found the function return \p nullptr. Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type. */ template <typename Q> value_type * erase( Q const& val ) { return erase( val, [](value_type const&) {} ); } /// Deletes the item from the set using \p pred predicate for searching /** The function is an analog of \ref cds_intrusive_HopscotchHashset_erase "erase(Q const&)" but \p pred is used for key comparing. If hopscotch set is ordered, then \p Predicate should have the interface and semantics like \p std::less. If hopscotch set is unordered, then \p Predicate should have the interface and semantics like \p std::equal_to. \p Predicate must imply the same element order as the comparator used for building the set. */ template <typename Q, typename Predicate> value_type * erase_with( Q const& val, Predicate pred ) { CDS_UNUSED( pred ); return erase_( val, typename predicate_wrapper<Predicate>::type(), [](value_type const&) {} ); } /// Delete the item from the set /** \anchor cds_intrusive_HopscotchHashset_erase_func The function searches an item with key equal to \p val in the set, call \p f functor with item found, unlinks it from the set, and returns a pointer to unlinked item. The \p Func interface is \code struct functor { void operator()( value_type const& item ); }; \endcode If the item with key equal to \p val is not found the function return \p nullptr. Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type. */ template <typename Q, typename Func> value_type * erase( Q const& val, Func f ) { return erase_( val, key_predicate(), f ); } /// Deletes the item from the set using \p pred predicate for searching /** The function is an analog of \ref cds_intrusive_HopscotchHashset_erase_func "erase(Q const&, Func)" but \p pred is used for key comparing. If you use ordered hopscotch set, then \p Predicate should have the interface and semantics like \p std::less. If you use unordered hopscotch set, then \p Predicate should have the interface and semantics like \p std::equal_to. \p Predicate must imply the same element order as the comparator used for building the set. */ template <typename Q, typename Predicate, typename Func> value_type * erase_with( Q const& val, Predicate pred, Func f ) { CDS_UNUSED( pred ); return erase_( val, typename predicate_wrapper<Predicate>::type(), f ); } /// Find the key \p val /** \anchor cds_intrusive_HopscotchHashset_find_func The function searches the item with key equal to \p val and calls the functor \p f for item found. The interface of \p Func functor is: \code struct functor { void operator()( value_type& item, Q& val ); }; \endcode where \p item is the item found, \p val is the <tt>find</tt> function argument. The functor may change non-key fields of \p item. The \p val argument is non-const since it can be used as \p f functor destination i.e., the functor may modify both arguments. Note the hash functor specified for class \p Traits template parameter should accept a parameter of type \p Q that can be not the same as \p value_type. The function returns \p true if \p val is found, \p false otherwise. */ template <typename Q, typename Func> bool find( Q& val, Func f ) { return find_( val, key_predicate(), f ); } //@cond template <typename Q, typename Func> bool find( Q const& val, Func f ) { return find_( val, key_predicate(), f ); } //@endcond /// Find the key \p val using \p pred predicate for comparing /** The function is an analog of \ref cds_intrusive_HopscotchHashset_find_func "find(Q&, Func)" but \p pred is used for key comparison. If you use ordered hopscotch set, then \p Predicate should have the interface and semantics like \p std::less. If you use unordered hopscotch set, then \p Predicate should have the interface and semantics like \p std::equal_to. \p pred must imply the same element order as the comparator used for building the set. */ template <typename Q, typename Predicate, typename Func> bool find_with( Q& val, Predicate pred, Func f ) { CDS_UNUSED( pred ); return find_( val, typename predicate_wrapper<Predicate>::type(), f ); } //@cond template <typename Q, typename Predicate, typename Func> bool find_with( Q const& val, Predicate pred, Func f ) { CDS_UNUSED( pred ); return find_( val, typename predicate_wrapper<Predicate>::type(), f ); } //@endcond /// Checks whether the set contains \p key /** The function searches the item with key equal to \p key and returns \p true if it is found, and \p false otherwise. */ template <typename Q> bool contains( Q const& key ) { return find( key, [](value_type&, Q const& ) {} ); } //@cond template <typename Q> CDS_DEPRECATED("deprecated, use contains()") bool find( Q const& key ) { return contains( key ); } //@endcond /// Checks whether the set contains \p key using \p pred predicate for searching /** The function is similar to <tt>contains( key )</tt> but \p pred is used for key comparing. If the set is unordered, \p Predicate has semantics like \p std::equal_to. For ordered set \p Predicate has \p std::less semantics. In that case \p pred must imply the same element order as the comparator used for building the set. */ template <typename Q, typename Predicate> bool contains( Q const& key, Predicate pred ) { CDS_UNUSED( pred ); return find_with( key, typename predicate_wrapper<Predicate>::type(), [](value_type& , Q const& ) {} ); } //@cond template <typename Q, typename Predicate> CDS_DEPRECATED("deprecated, use contains()") bool find_with( Q const& key, Predicate pred ) { return contains( key, pred ); } //@endcond /// Clears the set /** The function unlinks all items from the set. For any item \p Traits::disposer is called */ void clear() { clear_and_dispose( disposer()); } /// Clears the set and calls \p disposer for each item /** The function unlinks all items from the set calling \p oDisposer for each item. \p Disposer functor interface is: \code struct Disposer{ void operator()( value_type * p ); }; \endcode The \p Traits::disposer is not called. */ template <typename Disposer> void clear_and_dispose( Disposer oDisposer ) { // locks entire array scoped_full_lock sl( m_MutexPolicy ); for ( unsigned int i = 0; i < c_nArity; ++i ) { bucket_entry * pEntry = m_BucketTable[i]; bucket_entry * pEnd = pEntry + m_nBucketMask.load( atomics::memory_order_relaxed ) + 1; for ( ; pEntry != pEnd ; ++pEntry ) { pEntry->clear( [&oDisposer]( node_type * pNode ){ oDisposer( node_traits::to_value_ptr( pNode )) ; } ); } } m_ItemCounter.reset(); } /// Checks if the set is empty /** Emptiness is checked by item counting: if item count is zero then the set is empty. */ bool empty() const { return size() == 0; } /// Returns item count in the set size_t size() const { return m_ItemCounter; } /// Returns the size of hash table /** The hash table size is non-constant and can be increased via resizing. */ size_t bucket_count() const { return m_nBucketMask.load( atomics::memory_order_relaxed ) + 1; } //@cond size_t bucket_count( atomics::memory_order load_mo ) const { return m_nBucketMask.load( load_mo ) + 1; } //@endcond /// Returns lock array size size_t lock_count() const { return m_MutexPolicy.lock_count(); } /// Returns const reference to internal statistics stat const& statistics() const { return m_Stat; } /// Returns const reference to mutex policy internal statistics typename mutex_policy::statistics_type const& mutex_policy_statistics() const { return m_MutexPolicy.statistics(); } }; }} // namespace cds::intrusive #endif // #ifndef CDSLIB_INTRUSIVE_HOPSCOTCH_HASHSET_H
[ "andrei_hedorov@mail.ru" ]
andrei_hedorov@mail.ru
211e1d27e145bc83fb85589613c3100ea30c3149
9be0baa3d53e460fb9088280b2f38d6352a4097e
/src/posemath/matrpy_test.cc
23b546f510296165f45ea14b998cbf3bc1c246fe
[ "LicenseRef-scancode-public-domain" ]
permissive
usnistgov/rcslib
480cd9f97b9abe83c23dcddc1dd4db253084ff13
f26d07fd14e068a1a5bfb97b0dc6ba5afefea0a1
refs/heads/master
2023-04-06T13:35:53.884499
2023-04-03T20:01:08
2023-04-03T20:01:08
32,079,125
35
22
NOASSERTION
2020-10-12T22:03:48
2015-03-12T13:43:52
Java
UTF-8
C++
false
false
2,777
cc
/* The NIST RCS (Real-time Control Systems) library is public domain software, however it is preferred that the following disclaimers be attached. Software Copywrite/Warranty Disclaimer This software was developed at the National Institute of Standards and Technology by employees of the Federal Government in the course of their official duties. Pursuant to title 17 Section 105 of the United States Code this software is not subject to copyright protection and is in the public domain. NIST Real-Time Control System software is an experimental system. NIST assumes no responsibility whatsoever for its use by other parties, and makes no guarantees, expressed or implied, about its quality, reliability, or any other characteristic. We would appreciate acknowledgement if the software is used. This software can be redistributed and/or modified freely provided that any derivative works bear some notice that they are derived from it, and any modified versions bear some notice that they have been modified. */ #include "posemath.h" #include "mathprnt.h" using namespace std; #include <iostream> int main(int argc, const char **argv) { PM_RPY rpy1, rpy2; rpy1 = PM_RPY(-45 * TO_RAD, -90 *TO_RAD, 0); rpy2 = PM_ROTATION_MATRIX( rpy1 ); cout << "rpy1=" << rpy1 << endl; cout << "rpy2=" << rpy2 << endl; } #if 0 /* This is the email that prompted building this file for testing: From Karl Murphy, Will- Brian Womack at GDRS found a bug in _posemath.c in pmMatRpyConvert(). This occurs when pitch is -90 and the roll and yaw are non-zero. To test this run. PM_RPY rpy1, rpy2; rpy1 = PM_RPY(-45 * TO_RAD, -90 *TO_RAD, 0); rpy2 = PM_ROTATION_MATRIX( rpy1 ); rpy2 is (0, -90, 0) when it should be (-45, -90, 0) Note that pitch= +- 90 are singularities and roll and pitch are not uniquely defined. The code sets yaw to zero and roll to the sum (or difference) of the original values. Below is the corrected code. -karl int pmMatRpyConvert(PmRotationMatrix m, PmRpy * rpy) { rpy->p = atan2(-m.x.z, pmSqrt(pmSq(m.x.x) + pmSq(m.x.y))); if (fabs(rpy->p -PM_PI_2) < RPY_P_FUZZ) { rpy->r = atan2(m.y.x, m.y.y); rpy->p =PM_PI_2; /* force it * - / rpy->y = 0.0; } else if (fabs(rpy->p +PM_PI_2) < RPY_P_FUZZ) { /************************************************ bad code. Replace this line... rpy->r = -atan2(m.y.z, m.y.y); with this line... ************************************************* - / rpy->r = -atan2(m.y.x, m.y.y); /* new good code, uses m.y.x * - / rpy->p = -PM_PI_2; /* force it * - / rpy->y = 0.0; } else { rpy->r = atan2(m.y.z, m.z.z); rpy->y = atan2(m.x.y, m.x.x); } return pmErrno = 0; } */ #endif
[ "william.shackleford@nist.gov" ]
william.shackleford@nist.gov
c860ff559173c8ea54be385a79c1d787931e84ea
05b5b0378ae406daade7ec679e59323b82a8b444
/src/qt/sendcoinsentry.cpp
dceb3731694b8a561da697ca931caaf7c27f80b0
[ "MIT" ]
permissive
li003024/frc
ecd722c483fca3badd5834d581226ee00b5c2f3f
7317b2e0f2488c08ad411c8701bd26fb678d1d8d
refs/heads/master
2020-09-22T11:13:38.689484
2016-08-24T03:16:44
2016-08-24T03:16:44
66,419,825
0
0
null
null
null
null
UTF-8
C++
false
false
4,291
cpp
#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a FC address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
[ "mafeiforex@163.com" ]
mafeiforex@163.com
5802409390ce8d4a36cc346a099678f040f03aec
68220572b127c53e169755c1f025c818bfd21252
/exercise_8/germs/main.cpp
d29fc1e774b44fe4c246a20ca1246c80e1dbe51a
[]
no_license
SeboCode/ETHZ-AlgoLab-2020
6579122205cb6e2b2d532c87b267e2f12a2de5e4
9f52ddf5e384fd1c2c8f91020cfebd5fe4f5c030
refs/heads/master
2023-03-06T19:03:00.588563
2021-02-14T20:47:15
2021-02-14T20:47:15
333,606,733
1
0
null
null
null
null
UTF-8
C++
false
false
2,835
cpp
#include <iostream> #include <vector> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Delaunay_triangulation_2<K> Triangulation; typedef Triangulation::Finite_vertices_iterator Vertex_iterator; typedef K::Point_2 Point; double time_to_squared_distance(double time) { double distance = time * time + 0.5; return distance * distance; } double calculate_time(K::FT squaredDistanceFT) { double squaredDistance = CGAL::to_double(squaredDistanceFT); double time = std::ceil(std::sqrt(std::sqrt(squaredDistance) - 0.5)); while (time_to_squared_distance(time) < squaredDistanceFT) { time += 1; } while (time - 1 >= 0 && time_to_squared_distance(time - 1) >= squaredDistanceFT) { time -= 1; } return time; } void testcase(int n) { int l; std::cin >> l; int b; std::cin >> b; int r; std::cin >> r; int t; std::cin >> t; std::vector<Point> bacteriaLocations(n); for (int i = 0; i < n; i++) { int x; std::cin >> x; int y; std::cin >> y; bacteriaLocations[i] = Point(x, y); } Triangulation triangulation; triangulation.insert(bacteriaLocations.begin(), bacteriaLocations.end()); std::vector<K::FT> colisionRadius(n); int i = 0; for (Vertex_iterator v = triangulation.finite_vertices_begin(); v != triangulation.finite_vertices_end(); v++) { Point currentPoint = v->point(); colisionRadius[i] = std::pow(currentPoint.x() - l, 2); colisionRadius[i] = CGAL::min(colisionRadius[i], std::pow(currentPoint.y() - b, 2)); colisionRadius[i] = CGAL::min(colisionRadius[i], std::pow(r - currentPoint.x(), 2)); colisionRadius[i] = CGAL::min(colisionRadius[i], std::pow(t - currentPoint.y(), 2)); Triangulation::Vertex_circulator c = triangulation.incident_vertices(v); // in case we only have one vertex if (c != 0) { do { if (!triangulation.is_infinite(c)) { colisionRadius[i] = CGAL::min(colisionRadius[i], CGAL::squared_distance(c->point(), currentPoint)/4); } } while (++c != triangulation.incident_vertices(v)); } i++; } std::sort(colisionRadius.begin(), colisionRadius.end()); std::cout << calculate_time(colisionRadius[0]) << ' ' << calculate_time(colisionRadius[n/2]) << ' ' << calculate_time(colisionRadius[n-1]) << std::endl; } int main() { std::ios_base::sync_with_stdio(false); while (true) { int n; std::cin >> n; if (n == 0) { break; } testcase(n); } }
[ "mike-marti@outlook.com" ]
mike-marti@outlook.com
cebcca67338e65ea505bb2feb8d00a213fa766dc
0f19ac4a18f8279808a32b002e31135b52adddc4
/cuda/include/nori/enviromentmap.h
2a71dc15ea49069b49e1d7af215e749e9420bb1b
[]
no_license
BlenderCN-Org/cuda-path-tracer
e36aa1b2b0914ac65004fedc20677cbf6cf9141c
2c161a8953bd68b4866be36eb9ebc04b0b73c381
refs/heads/master
2020-05-23T22:53:04.421798
2018-12-10T18:18:44
2018-12-10T18:18:44
186,983,779
1
0
null
2019-05-16T08:17:58
2019-05-16T08:17:58
null
UTF-8
C++
false
false
1,057
h
// // Created by lukas on 18.12.17. // #ifndef NORIGL_ENVIROMENTLIGHT_H #define NORIGL_ENVIROMENTLIGHT_H #include <cmath> #include <nori/emitter.h> #include <nori/warp.h> #include <nori/shape.h> #include <nori/vector.h> #include <iostream> #include <nori/dpdf.h> #include <nori/imagetexture.h> #include <cuda_runtime_api.h> NORI_NAMESPACE_BEGIN class EnviromentMap: public NoriObject{ public: enum envType {ESphere} envType; __host__ virtual size_t getSize() const override {return sizeof(EnviromentMap);}; __host__ virtual EClassType getClassType() const {return EEnvMap;}; //__device__ Color3f eval(const EmitterQueryRecord & lRec) const ; //__device__ Color3f sample(EmitterQueryRecord & lRec, const Point2f & sample) const ; //__device__ float pdf(const EmitterQueryRecord &lRec) const ; protected: }; NORI_NAMESPACE_END #define CallMap(object,function,...) CallCuda1(EnviromentMap,envType,object,function,const,ESphere,SphereMap,__VA_ARGS__); #endif //NORIGL_ENVIROMENTLIGHT_H
[ "wolftho@student.ethz.ch" ]
wolftho@student.ethz.ch
e6e09f15af84143dd1c27e012dd1969b537cc93d
bb7ed686f19d919c0e2a381107637f1c05cb0342
/include/lexy/callback/string.hpp
51564bf9427db42955fcc82d5af7d99115a9bfc7
[ "BSL-1.0" ]
permissive
foonathan/lexy
8945315afd3b1afdbdabaee816570eaabadc0abb
1b31b097fa4fcaf5465f038793fe88cdc2140b71
refs/heads/main
2023-08-17T21:56:02.139707
2023-07-25T20:18:25
2023-07-25T20:18:25
201,454,592
867
59
BSL-1.0
2023-09-01T10:03:35
2019-08-09T11:27:57
C++
UTF-8
C++
false
false
7,383
hpp
// Copyright (C) 2020-2023 Jonathan Müller and lexy contributors // SPDX-License-Identifier: BSL-1.0 #ifndef LEXY_CALLBACK_STRING_HPP_INCLUDED #define LEXY_CALLBACK_STRING_HPP_INCLUDED #include <lexy/_detail/code_point.hpp> #include <lexy/callback/base.hpp> #include <lexy/code_point.hpp> #include <lexy/encoding.hpp> #include <lexy/input/base.hpp> #include <lexy/lexeme.hpp> namespace lexy { struct nullopt; template <typename String> using _string_char_type = LEXY_DECAY_DECLTYPE(LEXY_DECLVAL(String)[0]); template <typename String, typename Encoding, typename CaseFoldingDSL = void> struct _as_string { using return_type = String; using _char_type = _string_char_type<String>; static_assert(lexy::_detail::is_compatible_char_type<Encoding, _char_type>, "invalid character type/encoding combination"); static constexpr String&& _case_folding(String&& str) { if constexpr (std::is_void_v<CaseFoldingDSL>) { return LEXY_MOV(str); } else if constexpr (CaseFoldingDSL::template is_inplace<Encoding>) { // We can change the string in place. auto original_reader = lexy::_range_reader<Encoding>(str.begin(), str.end()); auto reader = typename CaseFoldingDSL::template case_folding<decltype(original_reader)>{ original_reader}; for (auto ptr = str.data(); true; ++ptr) { auto cur = reader.peek(); if (cur == Encoding::eof()) break; reader.bump(); // Once we've bumped it, we're not looking at it again. *ptr = static_cast<_char_type>(cur); } return LEXY_MOV(str); } else { // We store the existing string somewhere else and clear it. // Then we can read the case folded string and append each code unit. auto original = LEXY_MOV(str); str = String(); str.reserve(original.size()); auto original_reader = lexy::_range_reader<Encoding>(original.begin(), original.end()); auto reader = typename CaseFoldingDSL::template case_folding<decltype(original_reader)>{ original_reader}; while (true) { auto cur = reader.peek(); if (cur == Encoding::eof()) break; str.push_back(static_cast<_char_type>(cur)); reader.bump(); } return LEXY_MOV(str); } } template <typename NewCaseFoldingDSL> constexpr auto case_folding(NewCaseFoldingDSL) const { return _as_string<String, Encoding, NewCaseFoldingDSL>{}; } constexpr String operator()(nullopt&&) const { return String(); } constexpr String&& operator()(String&& str) const { return _case_folding(LEXY_MOV(str)); } template <typename Iterator> constexpr auto operator()(Iterator begin, Iterator end) const -> decltype(String(begin, end)) { return _case_folding(String(begin, end)); } template <typename Str = String, typename Iterator> constexpr auto operator()(const typename Str::allocator_type& allocator, Iterator begin, Iterator end) const -> decltype(String(begin, end, allocator)) { return _case_folding(String(begin, end, allocator)); } template <typename Reader> constexpr String operator()(lexeme<Reader> lex) const { static_assert(lexy::char_type_compatible_with_reader<Reader, _char_type>, "cannot convert lexeme to this string type"); using iterator = typename lexeme<Reader>::iterator; if constexpr (std::is_convertible_v<iterator, const _char_type*>) return _case_folding(String(lex.data(), lex.size())); else return _case_folding(String(lex.begin(), lex.end())); } template <typename Str = String, typename Reader> constexpr String operator()(const typename Str::allocator_type& allocator, lexeme<Reader> lex) const { static_assert(lexy::char_type_compatible_with_reader<Reader, _char_type>, "cannot convert lexeme to this string type"); using iterator = typename lexeme<Reader>::iterator; if constexpr (std::is_convertible_v<iterator, const _char_type*>) return _case_folding(String(lex.data(), lex.size(), allocator)); else return _case_folding(String(lex.begin(), lex.end(), allocator)); } constexpr String operator()(code_point cp) const { typename Encoding::char_type buffer[4] = {}; auto size = _detail::encode_code_point<Encoding>(cp.value(), buffer, 4); return _case_folding(String(buffer, buffer + size)); } template <typename Str = String> constexpr String operator()(const typename Str::allocator_type& allocator, code_point cp) const { typename Encoding::char_type buffer[4] = {}; auto size = _detail::encode_code_point<Encoding>(cp.value(), buffer, 4); return _case_folding(String(buffer, buffer + size, allocator)); } struct _sink { String _result; using return_type = String; template <typename CharT, typename = decltype(LEXY_DECLVAL(String).push_back(CharT()))> constexpr void operator()(CharT c) { _result.push_back(c); } constexpr void operator()(String&& str) { _result.append(LEXY_MOV(str)); } template <typename Str = String, typename Iterator> constexpr auto operator()(Iterator begin, Iterator end) -> decltype(void(LEXY_DECLVAL(Str).append(begin, end))) { _result.append(begin, end); } template <typename Reader> constexpr void operator()(lexeme<Reader> lex) { static_assert(lexy::char_type_compatible_with_reader<Reader, _char_type>, "cannot convert lexeme to this string type"); _result.append(lex.begin(), lex.end()); } constexpr void operator()(code_point cp) { typename Encoding::char_type buffer[4] = {}; auto size = _detail::encode_code_point<Encoding>(cp.value(), buffer, 4); _result.append(buffer, buffer + size); } constexpr String&& finish() && { return _case_folding(LEXY_MOV(_result)); } }; constexpr auto sink() const { return _sink{String()}; } template <typename S = String> constexpr auto sink(const typename S::allocator_type& allocator) const { return _sink{String(allocator)}; } }; /// A callback with sink that creates a string (e.g. `std::string`). /// As a callback, it converts a lexeme into the string. /// As a sink, it repeatedly calls `.push_back()` for individual characters, /// or `.append()` for lexemes or other strings. template <typename String, typename Encoding = deduce_encoding<_string_char_type<String>>> constexpr auto as_string = _as_string<String, Encoding>{}; } // namespace lexy #endif // LEXY_CALLBACK_STRING_HPP_INCLUDED
[ "git@foonathan.net" ]
git@foonathan.net
4a41e635a4dbb986620d07d3343c044d4259abfa
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/post90s/d_unico.cpp
ee7866afdcfaf40cb18451d042799a3b532c7f76
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
53,542
cpp
#include "tiles_generic.h" #include "burn_ym3812.h" #include "burn_ym2151.h" #include "msm6295.h" #include "eeprom.h" #include "burn_gun.h" static unsigned char DrvInputPort0[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvInputPort1[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvInputPort2[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvDip[2] = {0, 0}; static unsigned char DrvInput[3] = {0x00, 0x00, 0x00}; static unsigned char DrvReset = 0; static int DrvAnalogPort0 = 0; static int DrvAnalogPort1 = 0; static int DrvAnalogPort2 = 0; static int DrvAnalogPort3 = 0; static unsigned char *Mem = NULL; static unsigned char *MemEnd = NULL; static unsigned char *RamStart = NULL; static unsigned char *RamEnd = NULL; static unsigned char *Drv68KRom = NULL; static unsigned char *Drv68KRam = NULL; static unsigned char *DrvMSM6295ROMSrc = NULL; static unsigned char *DrvVideo0Ram = NULL; static unsigned char *DrvVideo1Ram = NULL; static unsigned char *DrvVideo2Ram = NULL; static unsigned char *DrvSpriteRam = NULL; static unsigned char *DrvPaletteRam = NULL; static unsigned char *DrvScrollRam = NULL; static unsigned char *DrvTiles = NULL; static unsigned char *DrvSprites = NULL; static unsigned char *DrvTempRom = NULL; static unsigned int *DrvPalette = NULL; static int nCyclesDone[1], nCyclesTotal[1]; static int nCyclesSegment; static UINT16 DrvScrollX0; static UINT16 DrvScrollY0; static UINT16 DrvScrollX1; static UINT16 DrvScrollY1; static UINT16 DrvScrollX2; static UINT16 DrvScrollY2; static unsigned char DrvOkiBank; static unsigned int DrvNumTiles; static unsigned int DrvNumSprites; typedef void (*UnicoMakeInputs)(); static UnicoMakeInputs UnicoMakeInputsFunction; static struct BurnInputInfo BurglarxInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort2 + 4, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort2 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort2 + 5, "p2 start" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P1 Fire 3" , BIT_DIGITAL , DrvInputPort0 + 6, "p1 fire 3" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"P2 Fire 3" , BIT_DIGITAL , DrvInputPort1 + 6, "p2 fire 3" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Service" , BIT_DIGITAL , DrvInputPort2 + 2, "service" }, {"Service 2" , BIT_DIGITAL , DrvInputPort2 + 3, "service 2" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Burglarx) #define A(a, b, c, d) {a, b, (unsigned char*)(c), d} static struct BurnInputInfo ZeropntInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort0 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p2 start" }, A("P1 Gun X" , BIT_ANALOG_REL, &DrvAnalogPort0 , "mouse x-axis"), A("P1 Gun Y" , BIT_ANALOG_REL, &DrvAnalogPort1 , "mouse y-axis"), {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 0, "mouse button 1" }, A("P2 Gun X" , BIT_ANALOG_REL, &DrvAnalogPort2 , "p2 x-axis"), A("P2 Gun Y" , BIT_ANALOG_REL, &DrvAnalogPort3 , "p2 y-axis"), {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 fire 1" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Diagnostic" , BIT_DIGITAL , DrvInputPort0 + 2, "diag" }, {"Service" , BIT_DIGITAL , DrvInputPort0 + 7, "service" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Zeropnt) #undef A static inline void BurglarxMakeInputs() { // Reset Inputs DrvInput[0] = DrvInput[1] = DrvInput[2] = 0x00; // Compile Digital Inputs for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvInputPort0[i] & 1) << i; DrvInput[1] |= (DrvInputPort1[i] & 1) << i; DrvInput[2] |= (DrvInputPort2[i] & 1) << i; } // Clear Opposites DrvClearOpposites(&DrvInput[0]); DrvClearOpposites(&DrvInput[1]); } static inline void ZeropntMakeInputs() { // Reset Inputs DrvInput[0] = 0x00; DrvInput[1] = 0xff; // Compile Digital Inputs for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvInputPort0[i] & 1) << i; DrvInput[1] -= (DrvInputPort1[i] & 1) << i; } BurnGunMakeInputs(0, (short)DrvAnalogPort0, (short)DrvAnalogPort1); BurnGunMakeInputs(1, (short)DrvAnalogPort2, (short)DrvAnalogPort3); } static inline void Zeropnt2MakeInputs() { // Reset Inputs DrvInput[0] = 0x00; DrvInput[1] = 0x7f; // Compile Digital Inputs for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvInputPort0[i] & 1) << i; DrvInput[1] -= (DrvInputPort1[i] & 1) << i; } BurnGunMakeInputs(0, (short)DrvAnalogPort0, (short)DrvAnalogPort1); BurnGunMakeInputs(1, (short)DrvAnalogPort2, (short)DrvAnalogPort3); } static struct BurnDIPInfo BurglarxDIPList[]= { // Default Values {0x15, 0xff, 0xff, 0xf7, NULL }, {0x16, 0xff, 0xff, 0xff, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Test Mode" }, {0x15, 0x01, 0x01, 0x01, "Off" }, {0x15, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Free Play" }, {0x15, 0x01, 0x02, 0x02, "Off" }, {0x15, 0x01, 0x02, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x15, 0x01, 0x08, 0x08, "Off" }, {0x15, 0x01, 0x08, 0x00, "On" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x15, 0x01, 0xe0, 0x00, "5 Coins 1 Credit" }, {0x15, 0x01, 0xe0, 0x20, "4 Coins 1 Credit" }, {0x15, 0x01, 0xe0, 0x40, "3 Coins 1 Credit" }, {0x15, 0x01, 0xe0, 0x60, "2 Coins 1 Credit" }, {0x15, 0x01, 0xe0, 0xe0, "1 Coin 1 Credit" }, {0x15, 0x01, 0xe0, 0xc0, "1 Coin 2 Credits" }, {0x15, 0x01, 0xe0, 0xa0, "1 Coin 3 Credits" }, {0x15, 0x01, 0xe0, 0x80, "1 Coin 4 Credits" }, // Dip 2 {0 , 0xfe, 0 , 4 , "Bonus Life" }, {0x16, 0x01, 0x03, 0x02, "None" }, {0x16, 0x01, 0x03, 0x03, "A" }, {0x16, 0x01, 0x03, 0x01, "B" }, {0x16, 0x01, 0x03, 0x00, "C" }, {0 , 0xfe, 0 , 2 , "Starting Energy" }, {0x16, 0x01, 0x80, 0x00, "2" }, {0x16, 0x01, 0x80, 0x80, "3" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x16, 0x01, 0x30, 0x20, "Easy" }, {0x16, 0x01, 0x30, 0x30, "Normal" }, {0x16, 0x01, 0x30, 0x10, "Hard" }, {0x16, 0x01, 0x30, 0x00, "Hardest" }, {0 , 0xfe, 0 , 4 , "Lives" }, {0x16, 0x01, 0xc0, 0x80, "2" }, {0x16, 0x01, 0xc0, 0xc0, "3" }, {0x16, 0x01, 0xc0, 0x40, "4" }, {0x16, 0x01, 0xc0, 0x00, "5" }, }; STDDIPINFO(Burglarx) static struct BurnDIPInfo ZeropntDIPList[]= { // Default Values {0x0d, 0xff, 0xff, 0x08, NULL }, {0x0e, 0xff, 0xff, 0x00, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Free Play" }, {0x0d, 0x01, 0x02, 0x00, "Off" }, {0x0d, 0x01, 0x02, 0x02, "On" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x0d, 0x01, 0x08, 0x00, "Off" }, {0x0d, 0x01, 0x08, 0x08, "On" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x0d, 0x01, 0xe0, 0xe0, "5 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0xc0, "4 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0xa0, "3 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0x80, "2 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0x00, "1 Coin 1 Credit" }, {0x0d, 0x01, 0xe0, 0x20, "1 Coin 2 Credits" }, {0x0d, 0x01, 0xe0, 0x40, "1 Coin 3 Credits" }, {0x0d, 0x01, 0xe0, 0x60, "1 Coin 4 Credits" }, // Dip 2 {0 , 0xfe, 0 , 3 , "Difficulty" }, {0x0e, 0x01, 0x30, 0x10, "Easy" }, {0x0e, 0x01, 0x30, 0x00, "Normal" }, {0x0e, 0x01, 0x30, 0x20, "Hard" }, {0 , 0xfe, 0 , 4 , "Lives" }, {0x0e, 0x01, 0xc0, 0x40, "2" }, {0x0e, 0x01, 0xc0, 0x00, "3" }, {0x0e, 0x01, 0xc0, 0x80, "4" }, {0x0e, 0x01, 0xc0, 0xc0, "5" }, }; STDDIPINFO(Zeropnt) static struct BurnDIPInfo Zeropnt2DIPList[]= { // Default Values {0x0d, 0xff, 0xff, 0xff, NULL }, {0x0e, 0xff, 0xff, 0xfd, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Free Play" }, {0x0d, 0x01, 0x01, 0x01, "Off" }, {0x0d, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Coins to Continue" }, {0x0d, 0x01, 0x02, 0x00, "1" }, {0x0d, 0x01, 0x02, 0x02, "2" }, {0 , 0xfe, 0 , 3 , "Gun Reloading" }, {0x0d, 0x01, 0x0c, 0x08, "No" }, {0x0d, 0x01, 0x0c, 0x04, "Yes" }, {0x0d, 0x01, 0x0c, 0x0c, "Factory Setting" }, {0 , 0xfe, 0 , 2 , "Language" }, {0x0d, 0x01, 0x10, 0x10, "English" }, {0x0d, 0x01, 0x10, 0x00, "Japanese" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x0d, 0x01, 0xe0, 0x00, "5 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0x20, "4 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0x40, "3 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0x60, "2 Coins 1 Credit" }, {0x0d, 0x01, 0xe0, 0xe0, "1 Coin 1 Credit" }, {0x0d, 0x01, 0xe0, 0xc0, "1 Coin 2 Credits" }, {0x0d, 0x01, 0xe0, 0xa0, "1 Coin 3 Credits" }, {0x0d, 0x01, 0xe0, 0x80, "1 Coin 4 Credits" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Korean Language" }, {0x0e, 0x01, 0x01, 0x01, "Off" }, {0x0e, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x0e, 0x01, 0x02, 0x02, "Off" }, {0x0e, 0x01, 0x02, 0x00, "On" }, {0 , 0xfe, 0 , 5 , "Lives" }, {0x0e, 0x01, 0x1c, 0x10, "2" }, {0x0e, 0x01, 0x1c, 0x0c, "3" }, {0x0e, 0x01, 0x1c, 0x1c, "4" }, {0x0e, 0x01, 0x1c, 0x18, "5" }, {0x0e, 0x01, 0x1c, 0x14, "6" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x0e, 0x01, 0xc0, 0x80, "Easy" }, {0x0e, 0x01, 0xc0, 0xc0, "Normal" }, {0x0e, 0x01, 0xc0, 0x40, "Hard" }, {0x0e, 0x01, 0xc0, 0x00, "Hardest" }, }; STDDIPINFO(Zeropnt2) static struct BurnRomInfo BurglarxRomDesc[] = { { "bx-rom2.pgm", 0x80000, 0xf81120c8, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "bx-rom3.pgm", 0x80000, 0x080b4e82, BRF_ESS | BRF_PRG }, // 1 { "bx-rom4", 0x80000, 0xf74ce31f, BRF_GRA }, // 2 Sprites { "bx-rom10", 0x80000, 0x6f56ca23, BRF_GRA }, // 3 { "bx-rom9", 0x80000, 0x33f29d79, BRF_GRA }, // 4 { "bx-rom8", 0x80000, 0x24367092, BRF_GRA }, // 5 { "bx-rom7", 0x80000, 0xaff6bdea, BRF_GRA }, // 6 { "bx-rom6", 0x80000, 0x246afed2, BRF_GRA }, // 7 { "bx-rom11", 0x80000, 0x898d176a, BRF_GRA }, // 8 { "bx-rom5", 0x80000, 0xfdee1423, BRF_GRA }, // 9 { "bx-rom14", 0x80000, 0x30413373, BRF_GRA }, // 10 Layers { "bx-rom18", 0x80000, 0x8e7fc99f, BRF_GRA }, // 11 { "bx-rom19", 0x80000, 0xd40eabcd, BRF_GRA }, // 12 { "bx-rom15", 0x80000, 0x78833c75, BRF_GRA }, // 13 { "bx-rom17", 0x80000, 0xf169633f, BRF_GRA }, // 14 { "bx-rom12", 0x80000, 0x71eb160f, BRF_GRA }, // 15 { "bx-rom13", 0x80000, 0xda34bbb5, BRF_GRA }, // 16 { "bx-rom16", 0x80000, 0x55b28ef9, BRF_GRA }, // 17 { "bx-rom1.snd", 0x80000, 0x8ae67138, BRF_SND }, // 18 Samples }; STD_ROM_PICK(Burglarx) STD_ROM_FN(Burglarx) static struct BurnRomInfo ZeropntRomDesc[] = { { "zero_2.bin", 0x080000, 0x1e599509, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "zero_3.bin", 0x080000, 0x588aeef7, BRF_ESS | BRF_PRG }, // 1 { "zpobjz01.bin", 0x200000, 0x1f2768a3, BRF_GRA }, // 2 Sprites { "zpobjz02.bin", 0x200000, 0xde34f33a, BRF_GRA }, // 3 { "zpobjz03.bin", 0x200000, 0xd7a657f7, BRF_GRA }, // 4 { "zpobjz04.bin", 0x200000, 0x3aec2f8d, BRF_GRA }, // 5 { "zpscrz06.bin", 0x200000, 0xe1e53cf0, BRF_GRA }, // 6 Layers { "zpscrz05.bin", 0x200000, 0x0d7d4850, BRF_GRA }, // 7 { "zpscrz07.bin", 0x200000, 0xbb178f32, BRF_GRA }, // 8 { "zpscrz08.bin", 0x200000, 0x672f02e5, BRF_GRA }, // 9 { "zero_1.bin", 0x080000, 0xfd2384fa, BRF_SND }, // 10 Samples }; STD_ROM_PICK(Zeropnt) STD_ROM_FN(Zeropnt) static struct BurnRomInfo ZeropntaRomDesc[] = { { "zpa2.bin", 0x080000, 0x285fbca3, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "zpa3.bin", 0x080000, 0xad7b3129, BRF_ESS | BRF_PRG }, // 1 { "zpobjz01.bin", 0x200000, 0x1f2768a3, BRF_GRA }, // 2 Sprites { "zpobjz02.bin", 0x200000, 0xde34f33a, BRF_GRA }, // 3 { "zpobjz03.bin", 0x200000, 0xd7a657f7, BRF_GRA }, // 4 { "zpobjz04.bin", 0x200000, 0x3aec2f8d, BRF_GRA }, // 5 { "zpscrz06.bin", 0x200000, 0xe1e53cf0, BRF_GRA }, // 6 Layers { "zpscrz05.bin", 0x200000, 0x0d7d4850, BRF_GRA }, // 7 { "zpscrz07.bin", 0x200000, 0xbb178f32, BRF_GRA }, // 8 { "zpscrz08.bin", 0x200000, 0x672f02e5, BRF_GRA }, // 9 { "zero_1.bin", 0x080000, 0xfd2384fa, BRF_SND }, // 10 Samples }; STD_ROM_PICK(Zeropnta) STD_ROM_FN(Zeropnta) static struct BurnRomInfo Zeropnt2RomDesc[] = { { "d16-d31.4", 0x100000, 0x48314fdb, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "d0-d15.3", 0x100000, 0x5ec4151e, BRF_ESS | BRF_PRG }, // 1 { "db0db1zp.209", 0x400000, 0x474b460c, BRF_GRA }, // 2 Sprites { "db2db3zp.210", 0x400000, 0x0a1d0a88, BRF_GRA }, // 3 { "db4db5zp.211", 0x400000, 0x227169dc, BRF_GRA }, // 4 { "db6db7zp.212", 0x400000, 0xa6306cdb, BRF_GRA }, // 5 { "a0-a1zp.205", 0x400000, 0xf7ca9c0e, BRF_GRA }, // 6 Layers { "a2-a3zp.206", 0x400000, 0x0581c8fe, BRF_GRA }, // 7 { "a4-a5zp.208", 0x400000, 0xddd091ef, BRF_GRA }, // 8 { "a6-a7zp.207", 0x400000, 0x3fd46113, BRF_GRA }, // 9 { "uzp2-1.bin", 0x080000, 0xed0966ed, BRF_SND }, // 10 Samples (Oki 1) { "uzp2-2.bin", 0x040000, 0xdb8cb455, BRF_SND }, // 11 Samples (Oki 2) }; STD_ROM_PICK(Zeropnt2) STD_ROM_FN(Zeropnt2) static int MemIndex() { unsigned char *Next; Next = Mem; Drv68KRom = Next; Next += 0x100000; MSM6295ROM = Next; Next += 0x040000; DrvMSM6295ROMSrc = Next; Next += 0x080000; RamStart = Next; Drv68KRam = Next; Next += 0x014000; DrvVideo0Ram = Next; Next += 0x004000; DrvVideo1Ram = Next; Next += 0x004000; DrvVideo2Ram = Next; Next += 0x004000; DrvSpriteRam = Next; Next += 0x000800; DrvPaletteRam = Next; Next += 0x008000; RamEnd = Next; DrvTiles = Next; Next += DrvNumTiles * 16 * 16; DrvSprites = Next; Next += DrvNumSprites * 16 * 16; DrvPalette = (unsigned int*)Next; Next += 0x02000 * sizeof(unsigned int); MemEnd = Next; return 0; } static int Zeropnt2MemIndex() { unsigned char *Next; Next = Mem; Drv68KRom = Next; Next += 0x200000; MSM6295ROM = Next; Next += 0x140000; DrvMSM6295ROMSrc = Next; Next += 0x080000; RamStart = Next; Drv68KRam = Next; Next += 0x024000; DrvVideo0Ram = Next; Next += 0x004000; DrvVideo1Ram = Next; Next += 0x004000; DrvVideo2Ram = Next; Next += 0x004000; DrvSpriteRam = Next; Next += 0x000800; DrvPaletteRam = Next; Next += 0x008000; DrvScrollRam = Next; Next += 0x000018; RamEnd = Next; DrvTiles = Next; Next += DrvNumTiles * 16 * 16; DrvSprites = Next; Next += DrvNumSprites * 16 * 16; DrvPalette = (unsigned int*)Next; Next += 0x02000 * sizeof(unsigned int); MemEnd = Next; return 0; } static int DrvDoReset() { SekOpen(0); SekReset(); SekClose(); BurnYM3812Reset(); MSM6295Reset(0); DrvScrollX0 = 0; DrvScrollY0 = 0; DrvScrollX1 = 0; DrvScrollY1 = 0; DrvScrollX2 = 0; DrvScrollY2 = 0; DrvOkiBank = 0; return 0; } static int Zeropnt2DoReset() { SekOpen(0); SekReset(); SekClose(); EEPROMReset(); BurnYM2151Reset(); MSM6295Reset(0); MSM6295Reset(1); DrvOkiBank = 0; return 0; } unsigned char __fastcall Burglarx68KReadByte(unsigned int a) { switch (a) { case 0x800000: { return 0xff - DrvInput[1]; } case 0x800001: { return 0xff - DrvInput[0]; } case 0x800019: { return 0xff - DrvInput[2]; } case 0x80001a: { return DrvDip[0]; } case 0x80001c: { return DrvDip[1]; } case 0x800189: { return MSM6295ReadStatus(0); } case 0x80018c: { return BurnYM3812Read(0); } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Read byte => %06X\n"), a); } #endif } return 0; } void __fastcall Burglarx68KWriteByte(unsigned int a, unsigned char d) { switch (a) { case 0x800189: { MSM6295Command(0, d); return; } case 0x80018a: { BurnYM3812Write(1, d); return; } case 0x80018c: { BurnYM3812Write(0, d); return; } case 0x80018e: { DrvOkiBank = d & 1; memcpy(MSM6295ROM + 0x00000, DrvMSM6295ROMSrc + (0x40000 * DrvOkiBank), 0x40000); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Write byte => %06X, %02X\n"), a, d); } #endif } } unsigned short __fastcall Burglarx68KReadWord(unsigned int a) { // switch (a) { // default: { // bprintf(PRINT_NORMAL, _T("68K Read word => %06X\n"), a); // } // } return 0; } void __fastcall Burglarx68KWriteWord(unsigned int a, unsigned short d) { switch (a) { #if 0 case 0x800030: { // NOP??? return; } #endif case 0x80010c: { DrvScrollX0 = d & 0x3ff; return; } case 0x80010e: { DrvScrollY0 = d & 0x3ff; return; } case 0x800110: { DrvScrollY2 = d & 0x3ff; return; } case 0x800114: { DrvScrollX2 = d & 0x3ff; return; } case 0x800116: { DrvScrollX1 = d & 0x3ff; return; } case 0x800120: { DrvScrollY1 = d & 0x3ff; return; } #if 0 case 0x8001e0: { // IRQ Ack??? return; } default: { bprintf(PRINT_NORMAL, _T("68K Write word => %06X, %04X\n"), a, d); } #endif } } unsigned char __fastcall Zeropnt68KReadByte(unsigned int a) { switch (a) { case 0x800018: { return DrvInput[1]; } case 0x800019: { return DrvInput[0]; } case 0x80001a: { return DrvDip[0]; } case 0x80001c: { return DrvDip[1]; } case 0x800170: { int y = BurnGunReturnY(1); y = 0x18 + ((y * 0xe0) / 0xff); return ((y & 0xff) ^ (GetCurrentFrame() & 1)); } case 0x800174: { int x = BurnGunReturnX(1); x = x * 384 / 256; if (x < 0x160) { x = 0x30 + (x * 0xd0 / 0x15f); } else { x = ((x - 0x160) * 0x20) / 0x1f; } return ((x & 0xff) ^ (GetCurrentFrame() & 1)); } case 0x800178: { int y = BurnGunReturnY(0); y = 0x18 + ((y * 0xe0) / 0xff); return ((y & 0xff) ^ (GetCurrentFrame() & 1)); } case 0x80017c: { int x = BurnGunReturnX(0); x = x * 384 / 256; if (x < 0x160) { x = 0x30 + (x * 0xd0 / 0x15f); } else { x = ((x - 0x160) * 0x20) / 0x1f; } return ((x & 0xff) ^ (GetCurrentFrame() & 1)); } case 0x800189: { return MSM6295ReadStatus(0); } case 0x80018c: { return BurnYM3812Read(0); } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Read byte => %06X\n"), a); } #endif } return 0; } void __fastcall Zeropnt68KWriteByte(unsigned int a, unsigned char d) { switch (a) { case 0x800189: { MSM6295Command(0, d); return; } case 0x80018a: { BurnYM3812Write(1, d); return; } case 0x80018c: { BurnYM3812Write(0, d); return; } case 0x80018e: { DrvOkiBank = d & 1; memcpy(MSM6295ROM + 0x20000, DrvMSM6295ROMSrc + 0x20000 + (0x20000 * DrvOkiBank), 0x20000); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Write byte => %06X, %02X\n"), a, d); } #endif } } unsigned short __fastcall Zeropnt68KReadWord(unsigned int a) { // switch (a) { // default: { // bprintf(PRINT_NORMAL, _T("68K Read word => %06X\n"), a); // } // } return 0; } void __fastcall Zeropnt68KWriteWord(unsigned int a, unsigned short d) { switch (a) { #if 0 case 0x800030: { // NOP??? return; } #endif case 0x80010c: { DrvScrollX0 = d & 0x3ff; return; } case 0x80010e: { DrvScrollY0 = d & 0x3ff; return; } case 0x800110: { DrvScrollY2 = d & 0x3ff; return; } case 0x800114: { DrvScrollX2 = d & 0x3ff; return; } case 0x800116: { DrvScrollX1 = d & 0x3ff; return; } case 0x800120: { DrvScrollY1 = d & 0x3ff; return; } #if 0 case 0x8001e0: { // IRQ Ack??? return; } default: { bprintf(PRINT_NORMAL, _T("68K Write word => %06X, %04X\n"), a, d); } #endif } } unsigned char __fastcall Zeropnt268KReadByte(unsigned int a) { switch (a) { case 0x800019: { return DrvInput[0]; } case 0x800025: { return MSM6295ReadStatus(0); } case 0x80002d: { return BurnYM2151ReadStatus(); } case 0x800031: { return MSM6295ReadStatus(1); } case 0x800140: { int y = BurnGunReturnY(1); y = 0x18 + ((y * 0xe0) / 0xff); return ((y & 0xff) ^ (GetCurrentFrame() & 1)) + 0x08; } case 0x800144: { int x = BurnGunReturnX(1); x = x * 384 / 256; if (x < 0x160) { x = 0x30 + (x * 0xd0 / 0x15f); } else { x = ((x - 0x160) * 0x20) / 0x1f; } return ((x & 0xff) ^ (GetCurrentFrame() & 1)) - 0x08; } case 0x800148: { int y = BurnGunReturnY(0); y = 0x18 + ((y * 0xe0) / 0xff); return ((y & 0xff) ^ (GetCurrentFrame() & 1)) + 0x08; } case 0x80014c: { int x = BurnGunReturnX(0); x = x * 384 / 256; if (x < 0x160) { x = 0x30 + (x * 0xd0 / 0x15f); } else { x = ((x - 0x160) * 0x20) / 0x1f; } return ((x & 0xff) ^ (GetCurrentFrame() & 1)) - 0x08; } case 0x800150: { return DrvDip[0]; } case 0x800154: { return DrvDip[1]; } case 0x80015c: { return DrvInput[1] | ((EEPROMRead() & 0x01) << 8); } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Read byte => %06X\n"), a); } #endif } return 0; } void __fastcall Zeropnt268KWriteByte(unsigned int a, unsigned char d) { switch (a) { case 0x800025: { MSM6295Command(0, d); return; } case 0x800029: { BurnYM2151SelectRegister(d); return; } case 0x80002d: { BurnYM2151WriteRegister(d); return; } case 0x800031: { MSM6295Command(1, d); return; } case 0x800034: { DrvOkiBank = (d & 3) % 4; memcpy(MSM6295ROM + 0x20000, DrvMSM6295ROMSrc + 0x20000 + (0x20000 * DrvOkiBank), 0x20000); return; } #if 0 case 0x800039: { // LEDs return; } #endif case 0x8001f0: { EEPROMWrite(d & 0x02, d & 0x01, d & 0x04); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Write byte => %06X, %02X\n"), a, d); } #endif } } unsigned short __fastcall Zeropnt268KReadWord(unsigned int a) { // switch (a) { // default: { // bprintf(PRINT_NORMAL, _T("68K Read word => %06X\n"), a); // } // } return 0; } void __fastcall Zeropnt268KWriteWord(unsigned int a, unsigned short d) { switch (a) { case 0x80010c: { UINT16* ScrollRam = (UINT16*)DrvScrollRam; ScrollRam[0] = swapWord(d); return; } case 0x80010e: { UINT16* ScrollRam = (UINT16*)DrvScrollRam; ScrollRam[1] = swapWord(d); return; } case 0x800110: { UINT16* ScrollRam = (UINT16*)DrvScrollRam; ScrollRam[2] = swapWord(d); return; } case 0x800114: { UINT16* ScrollRam = (UINT16*)DrvScrollRam; ScrollRam[4] = swapWord(d); return; } case 0x800116: { UINT16* ScrollRam = (UINT16*)DrvScrollRam; ScrollRam[5] = swapWord(d); return; } case 0x800120: { UINT16* ScrollRam = (UINT16*)DrvScrollRam; ScrollRam[10] = swapWord(d); return; } #if 0 case 0x8001e0: { // IRQ Ack??? return; } default: { bprintf(PRINT_NORMAL, _T("68K Write word => %06X, %04X\n"), a, d); } #endif } } unsigned int __fastcall Zeropnt268KReadLong(unsigned int a) { // switch (a) { // default: { // bprintf(PRINT_NORMAL, _T("68K Read long => %06X\n"), a); // } // } return 0; } void __fastcall Zeropnt268KWriteLong(unsigned int a, unsigned int d) { // switch (a) { // default: { // bprintf(PRINT_NORMAL, _T("68K Write long => %06X, %08X\n"), a, d); // } // } } static int BurglarxSynchroniseStream(int nSoundRate) { return (long long)SekTotalCycles() * nSoundRate / 16000000; } static int BurglarxTilePlaneOffsets[8] = { 0x1800008, 0x1800000, 0x1000008, 0x1000000, 0x0800008, 0x0800000, 0x0000008, 0x0000000 }; static int ZeropntTilePlaneOffsets[8] = { 0x3000008, 0x3000000, 0x2000008, 0x2000000, 0x1000008, 0x1000000, 0x0000008, 0x0000000 }; static int Zeropnt2TilePlaneOffsets[8] = { 0x6000008, 0x6000000, 0x4000008, 0x4000000, 0x2000008, 0x2000000, 0x0000008, 0x0000000 }; static int TileXOffsets[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 }; static int TileYOffsets[16] = { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 480 }; static int BurglarxInit() { int nRet = 0, nLen; DrvNumTiles = 0x4000; DrvNumSprites = 0x4000; // Allocate and Blank all required memory Mem = NULL; MemIndex(); nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); MemIndex(); DrvTempRom = (unsigned char *)malloc(0x400000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x000001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x000000, 1, 2); if (nRet != 0) return 1; // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 10, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 11, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 12, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100001, 13, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200000, 14, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200001, 15, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300000, 16, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300001, 17, 2); if (nRet != 0) return 1; for (int i = 0; i < 0x400000; i++) { DrvTempRom[i] ^= 0xff; } GfxDecode(0x4000, 8, 16, 16, BurglarxTilePlaneOffsets, TileXOffsets, TileYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x400000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 2, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 3, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100001, 5, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200000, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200001, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300001, 9, 2); if (nRet != 0) return 1; for (int i = 0; i < 0x400000; i++) { DrvTempRom[i] ^= 0xff; } GfxDecode(0x4000, 8, 16, 16, BurglarxTilePlaneOffsets, TileXOffsets, TileYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x00000, 18, 1); if (nRet != 0) return 1; memcpy(MSM6295ROM, DrvMSM6295ROMSrc, 0x40000); free(DrvTempRom); // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x0fffff, SM_ROM); SekMapMemory(DrvVideo1Ram , 0x904000, 0x907fff, SM_RAM); SekMapMemory(DrvVideo2Ram , 0x908000, 0x90bfff, SM_RAM); SekMapMemory(DrvVideo0Ram , 0x90c000, 0x90ffff, SM_RAM); SekMapMemory(Drv68KRam + 0x10000 , 0x920000, 0x923fff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x930000, 0x9307ff, SM_RAM); SekMapMemory(DrvPaletteRam , 0x940000, 0x947fff, SM_RAM); SekMapMemory(Drv68KRam , 0xff0000, 0xffffff, SM_RAM); SekSetReadWordHandler(0, Burglarx68KReadWord); SekSetWriteWordHandler(0, Burglarx68KWriteWord); SekSetReadByteHandler(0, Burglarx68KReadByte); SekSetWriteByteHandler(0, Burglarx68KWriteByte); SekClose(); BurnYM3812Init(3579545, NULL, &BurglarxSynchroniseStream, 0); BurnTimerAttachSekYM3812(16000000); // Setup the OKIM6295 emulation MSM6295Init(0, 1056000 / 132, 100.0, 1); GenericTilesInit(); UnicoMakeInputsFunction = BurglarxMakeInputs; // Reset the driver DrvDoReset(); return 0; } static int ZeropntInit() { int nRet = 0, nLen; DrvNumTiles = 0x8000; DrvNumSprites = 0x8000; // Allocate and Blank all required memory Mem = NULL; MemIndex(); nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); MemIndex(); DrvTempRom = (unsigned char *)malloc(0x800000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x000001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x000000, 1, 2); if (nRet != 0) return 1; // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 6, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200000, 7, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x400000, 8, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x600000, 9, 1); if (nRet != 0) return 1; for (int i = 0; i < 0x800000; i++) { DrvTempRom[i] ^= 0xff; } GfxDecode(0x8000, 8, 16, 16, ZeropntTilePlaneOffsets, TileXOffsets, TileYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x800000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 2, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200000, 3, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x400000, 4, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x600000, 5, 1); if (nRet != 0) return 1; for (int i = 0; i < 0x800000; i++) { DrvTempRom[i] ^= 0xff; } GfxDecode(0x8000, 8, 16, 16, ZeropntTilePlaneOffsets, TileXOffsets, TileYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x00000, 10, 1); if (nRet != 0) return 1; memcpy(MSM6295ROM, DrvMSM6295ROMSrc, 0x40000); free(DrvTempRom); // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x0fffff, SM_ROM); SekMapMemory(DrvVideo1Ram , 0x904000, 0x907fff, SM_RAM); SekMapMemory(DrvVideo2Ram , 0x908000, 0x90bfff, SM_RAM); SekMapMemory(DrvVideo0Ram , 0x90c000, 0x90ffff, SM_RAM); SekMapMemory(Drv68KRam + 0x10000 , 0x920000, 0x923fff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x930000, 0x9307ff, SM_RAM); SekMapMemory(DrvPaletteRam , 0x940000, 0x947fff, SM_RAM); SekMapMemory(Drv68KRam , 0xef0000, 0xefffff, SM_RAM); SekSetReadWordHandler(0, Zeropnt68KReadWord); SekSetWriteWordHandler(0, Zeropnt68KWriteWord); SekSetReadByteHandler(0, Zeropnt68KReadByte); SekSetWriteByteHandler(0, Zeropnt68KWriteByte); SekClose(); BurnYM3812Init(3579545, NULL, &BurglarxSynchroniseStream, 0); BurnTimerAttachSekYM3812(16000000); // Setup the OKIM6295 emulation MSM6295Init(0, 1056000 / 132, 100.0, 1); GenericTilesInit(); BurnGunInit(2, true); UnicoMakeInputsFunction = ZeropntMakeInputs; // Reset the driver DrvDoReset(); return 0; } static const eeprom_interface zeropnt2_eeprom_interface = { 7, // address bits 7 8, // data bits 8 "*110", // read 1 10 aaaaaaa "*101", // write 1 01 aaaaaaa dddddddd "*111", // erase 1 11 aaaaaaa "*10000xxxx", // lock 1 00 00xxxx "*10011xxxx", // unlock 1 00 11xxxx 0, 0 }; static int Zeropnt2Init() { int nRet = 0, nLen; DrvNumTiles = 0x10000; DrvNumSprites = 0x10000; // Allocate and Blank all required memory Mem = NULL; Zeropnt2MemIndex(); nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); Zeropnt2MemIndex(); DrvTempRom = (unsigned char *)malloc(0x1000000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x000000, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x000001, 1, 2); if (nRet != 0) return 1; for (int i = 0; i < 0x200000; i+= 4) { int t = Drv68KRom[i + 1]; Drv68KRom[i + 1] = Drv68KRom[i + 2]; Drv68KRom[i + 2] = t; } // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 6, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x400000, 7, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x800000, 8, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0xc00000, 9, 1); if (nRet != 0) return 1; for (int i = 0; i < 0x1000000; i++) { DrvTempRom[i] ^= 0xff; } GfxDecode(0x10000, 8, 16, 16, Zeropnt2TilePlaneOffsets, TileXOffsets, TileYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x1000000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 2, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x400000, 3, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x800000, 4, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0xc00000, 5, 1); if (nRet != 0) return 1; for (int i = 0; i < 0x1000000; i++) { DrvTempRom[i] ^= 0xff; } GfxDecode(0x10000, 8, 16, 16, Zeropnt2TilePlaneOffsets, TileXOffsets, TileYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x00000, 10, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(MSM6295ROM + 0x100000, 11, 1); if (nRet != 0) return 1; memcpy(MSM6295ROM + 0x000000, DrvMSM6295ROMSrc, 0x40000); free(DrvTempRom); // Setup the 68000 emulation SekInit(0, 0x68EC020); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x1fffff, SM_ROM); SekMapMemory(DrvVideo1Ram , 0x904000, 0x907fff, SM_RAM); SekMapMemory(DrvVideo2Ram , 0x908000, 0x90bfff, SM_RAM); SekMapMemory(DrvVideo0Ram , 0x90c000, 0x90ffff, SM_RAM); SekMapMemory(Drv68KRam + 0x10000 , 0x920000, 0x923fff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x930000, 0x9307ff, SM_RAM); SekMapMemory(DrvPaletteRam , 0x940000, 0x947fff, SM_RAM); SekMapMemory(Drv68KRam , 0xfe0000, 0xffffff, SM_RAM); SekSetReadWordHandler(0, Zeropnt268KReadWord); SekSetWriteWordHandler(0, Zeropnt268KWriteWord); SekSetReadByteHandler(0, Zeropnt268KReadByte); SekSetWriteByteHandler(0, Zeropnt268KWriteByte); SekSetReadLongHandler(0, Zeropnt268KReadLong); SekSetWriteLongHandler(0, Zeropnt268KWriteLong); SekClose(); EEPROMInit(&zeropnt2_eeprom_interface); BurnYM2151Init(3579545, 25.0); MSM6295Init(0, 1056000 / 132, 100.0, 1); MSM6295Init(1, 3960000 / 132, 100.0, 1); GenericTilesInit(); BurnGunInit(2, true); // Reset the driver Zeropnt2DoReset(); return 0; } static int DrvExit() { SekExit(); BurnYM3812Exit(); MSM6295Exit(0); GenericTilesExit(); BurnGunExit(); DrvScrollX0 = 0; DrvScrollY0 = 0; DrvScrollX1 = 0; DrvScrollY1 = 0; DrvScrollX2 = 0; DrvScrollY2 = 0; DrvOkiBank = 0; DrvNumTiles = 0; DrvNumSprites = 0; UnicoMakeInputsFunction = NULL; free(Mem); Mem = NULL; return 0; } static int Zeropnt2Exit() { BurnYM2151Exit(); MSM6295Exit(1); EEPROMExit(); return DrvExit(); } static void DrvRenderSprites(int PriorityDraw) { for (int Offset = 0; Offset < 0x400; Offset += 4) { int x, xStart, xEnd, xInc; UINT16 *SpriteRam = (UINT16*)DrvSpriteRam; int sx = swapWord(SpriteRam[Offset + 0]); int sy = swapWord(SpriteRam[Offset + 1]); int Code = swapWord(SpriteRam[Offset + 2]); int Attr = swapWord(SpriteRam[Offset + 3]); int xFlip = Attr & 0x20; int yFlip = Attr & 0x40; int xDim = ((Attr >> 8) & 0x0f) + 1; int Priority = ((Attr >> 12) & 0x03); if (Priority != PriorityDraw) continue; sx -= 0x3f; sy -= 0x0e; sx = (sx & 0x1ff) - (sx & 0x200); sy = (sy & 0x1ff) - (sy & 0x200); if (xFlip) { xStart = sx + (xDim - 1) * 16; xEnd = sx - 16; xInc = -16; } else { xStart = sx; xEnd = sx + (xDim * 16); xInc = 16; } for (x = xStart; x != xEnd; x += xInc) { if (x > 16 && x < 368 && sy > 16 && sy < 208) { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask_FlipX(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } } else { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask_FlipX_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } } } } } static void Zeropnt2RenderSprites(int PriorityDraw) { for (int Offset = 0; Offset < 0x200; Offset += 2) { int x, xStart, xEnd, xInc; UINT32 *SpriteRam = (UINT32*)DrvSpriteRam; int sx = swapLong(SpriteRam[Offset + 0]) & 0xffff; int sy = swapLong(SpriteRam[Offset + 0]) >> 16; int Code = swapLong(SpriteRam[Offset + 1]) & 0xffff; int Attr = swapLong(SpriteRam[Offset + 1]) >> 16; int xFlip = Attr & 0x20; int yFlip = Attr & 0x40; int xDim = ((Attr >> 8) & 0x0f) + 1; int Priority = ((Attr >> 12) & 0x03); if (Priority != PriorityDraw) continue; sx -= 0x3f; sy -= 0x0e; sx = (sx & 0x1ff) - (sx & 0x200); sy = (sy & 0x1ff) - (sy & 0x200); if (xFlip) { xStart = sx + (xDim - 1) * 16; xEnd = sx - 16; xInc = -16; } else { xStart = sx; xEnd = sx + (xDim * 16); xInc = 16; } for (x = xStart; x != xEnd; x += xInc) { if (x > 16 && x < 368 && sy > 16 && sy < 208) { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask_FlipX(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } } else { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask_FlipX_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code++, x, sy, Attr & 0x1f, 8, 0, 0, DrvSprites); } } } } } } static void DrvRenderLayer(int Layer) { int mx, my, Attr, Code, Colour, x, y, TileIndex = 0, Flip, xFlip, yFlip; UINT16 ScrollX = DrvScrollX0; UINT16 ScrollY = DrvScrollY0; UINT16 *VideoRam = (UINT16*)DrvVideo0Ram; if (Layer == 1) { ScrollX = DrvScrollX1; ScrollY = DrvScrollY1; VideoRam = (UINT16*)DrvVideo1Ram; } if (Layer == 2) { ScrollX = DrvScrollX2; ScrollY = DrvScrollY2; VideoRam = (UINT16*)DrvVideo2Ram; } for (my = 0; my < 64; my++) { for (mx = 0; mx < 64; mx++) { Attr = swapWord(VideoRam[2 * TileIndex + 1]); Code = swapWord(VideoRam[2 * TileIndex + 0]); Colour = Attr & 0x1f; Flip = Attr >> 5; xFlip = (Flip >> 0) & 0x01; yFlip = (Flip >> 1) & 0x01; x = 16 * mx; y = 16 * my; x -= ScrollX; y -= ScrollY; if (x < -16) x += 1024; if (y < -16) y += 1024; y -= 15; if (Layer == 0) x -= 0x32; if (Layer == 1) x -= 0x30; if (Layer == 2) x -= 0x2e; if (x > 16 && x < 368 && y > 16 && y < 208) { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask_FlipX(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } } else { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask_FlipX_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } } TileIndex++; } } } static void Zeropnt2RenderLayer(int Layer) { int mx, my, Attr, Colour, x, y, TileIndex = 0, Flip, xFlip, yFlip; UINT32 Code; UINT32 *VideoRam = (UINT32*)DrvVideo0Ram; UINT32 *ScrollRam = (UINT32*)DrvScrollRam; UINT16 ScrollX = swapLong(ScrollRam[0]) & 0xffff; UINT16 ScrollY = swapLong(ScrollRam[0]) >> 16; if (Layer == 1) { ScrollX = swapLong(ScrollRam[2]) >> 16; ScrollY = swapLong(ScrollRam[5]) & 0xffff; VideoRam = (UINT32*)DrvVideo1Ram; } if (Layer == 2) { ScrollX = swapLong(ScrollRam[2]) & 0xffff; ScrollY = swapLong(ScrollRam[1]) & 0xffff; VideoRam = (UINT32*)DrvVideo2Ram; } ScrollX &= 0x3ff; ScrollY &= 0x3ff; for (my = 0; my < 64; my++) { for (mx = 0; mx < 64; mx++) { Code = swapLong(VideoRam[TileIndex]); Attr = Code >> 16; Code &= 0xffff; Colour = Attr & 0x1f; Flip = Attr >> 5; xFlip = (Flip >> 0) & 0x01; yFlip = (Flip >> 1) & 0x01; x = 16 * mx; y = 16 * my; x -= ScrollX; y -= ScrollY; if (x < -16) x += 1024; if (y < -16) y += 1024; y -= 15; if (Layer == 0) x -= 0x32; if (Layer == 1) x -= 0x30; if (Layer == 2) x -= 0x2e; if (Code) { if (x > 16 && x < 368 && y > 16 && y < 208) { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask_FlipX(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } } else { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask_FlipX_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 0, DrvTiles); } } } } TileIndex++; } } } static void DrvCalcPalette() { UINT16 Data1, Data2; UINT16 *PaletteRam = (UINT16*)DrvPaletteRam; for (int i = 0; i < 0x4000; i += 2) { Data1 = swapWord(PaletteRam[i & ~1]); Data2 = swapWord(PaletteRam[i | 1]); DrvPalette[i >> 1] = BurnHighCol((Data1 >> 8) & 0xfc, (Data1 >> 0) & 0xfc, (Data2 >> 8) & 0xfc, 0); } } static void Zeropnt2CalcPalette() { UINT32 *PaletteRam = (UINT32*)DrvPaletteRam; UINT32 rgb0; for (int i = 0; i < 0x2000; i++) { rgb0 = swapLong(PaletteRam[i]); DrvPalette[i] = BurnHighCol((rgb0 >> 8) & 0xfc, (rgb0 >> 0) & 0xfc, (rgb0 >> 24) & 0xfc, 0); } } static void DrvDraw() { BurnTransferClear(); DrvCalcPalette(); for (int i = 0; i < nScreenHeight * nScreenWidth; i++) { pTransDraw[i] = 0x1f00; } DrvRenderLayer(0); DrvRenderSprites(0); DrvRenderLayer(1); DrvRenderSprites(1); DrvRenderLayer(2); DrvRenderSprites(2); DrvRenderSprites(3); BurnTransferCopy(DrvPalette); for (int i = 0; i < nBurnGunNumPlayers; i++) { BurnGunDrawTarget(i, BurnGunX[i] >> 8, BurnGunY[i] >> 8); } } static void Zeropnt2Draw() { BurnTransferClear(); Zeropnt2CalcPalette(); for (int i = 0; i < nScreenHeight * nScreenWidth; i++) { pTransDraw[i] = 0x1f00; } Zeropnt2RenderSprites(3); Zeropnt2RenderLayer(0); Zeropnt2RenderSprites(2); Zeropnt2RenderLayer(1); Zeropnt2RenderSprites(1); Zeropnt2RenderLayer(2); Zeropnt2RenderSprites(0); BurnTransferCopy(DrvPalette); for (int i = 0; i < nBurnGunNumPlayers; i++) { BurnGunDrawTarget(i, BurnGunX[i] >> 8, BurnGunY[i] >> 8); } } static int DrvFrame() { if (DrvReset) DrvDoReset(); UnicoMakeInputsFunction(); nCyclesTotal[0] = 16000000 / 60; nCyclesDone[0] = 0; SekNewFrame(); SekOpen(0); BurnTimerEndFrameYM3812(nCyclesTotal[0]); SekSetIRQLine(2, SEK_IRQSTATUS_AUTO); BurnYM3812Update(pBurnSoundOut, nBurnSoundLen); MSM6295Render(0, pBurnSoundOut, nBurnSoundLen); SekClose(); if (pBurnDraw) DrvDraw(); return 0; } static int Zeropnt2Frame() { int nInterleave = 10; int nSoundBufferPos = 0; if (DrvReset) Zeropnt2DoReset(); Zeropnt2MakeInputs(); nCyclesTotal[0] = 16000000 / 60; nCyclesDone[0] = 0; SekNewFrame(); for (int i = 0; i < nInterleave; i++) { int nCurrentCPU, nNext; // Run 68000 nCurrentCPU = 0; SekOpen(0); nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave; nCyclesSegment = nNext - nCyclesDone[nCurrentCPU]; nCyclesDone[nCurrentCPU] += SekRun(nCyclesSegment); if (i == 9) SekSetIRQLine(2, SEK_IRQSTATUS_AUTO); SekClose(); if (pBurnSoundOut) { int nSegmentLength = nBurnSoundLen / nInterleave; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); BurnYM2151Render(pSoundBuf, nSegmentLength); MSM6295Render(0, pSoundBuf, nSegmentLength); MSM6295Render(1, pSoundBuf, nSegmentLength); nSoundBufferPos += nSegmentLength; } } if (pBurnSoundOut) { int nSegmentLength = nBurnSoundLen - nSoundBufferPos; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); if (nSegmentLength) { BurnYM2151Render(pSoundBuf, nSegmentLength); MSM6295Render(0, pSoundBuf, nSegmentLength); MSM6295Render(1, pSoundBuf, nSegmentLength); } } if (pBurnDraw) Zeropnt2Draw(); return 0; } static int DrvScan(int nAction, int *pnMin) { struct BurnArea ba; if (pnMin != NULL) { // Return minimum compatible version *pnMin = 0x029691; } if (nAction & ACB_MEMORY_RAM) { memset(&ba, 0, sizeof(ba)); ba.Data = RamStart; ba.nLen = RamEnd-RamStart; ba.szName = "All Ram"; BurnAcb(&ba); } if (nAction & ACB_DRIVER_DATA) { SekScan(nAction); MSM6295Scan(0, nAction); // Scan critical driver variables SCAN_VAR(nCyclesDone); SCAN_VAR(nCyclesSegment); SCAN_VAR(DrvDip); SCAN_VAR(DrvInput); SCAN_VAR(DrvOkiBank); } return 0; } static int BurglarxScan(int nAction, int *pnMin) { DrvScan(nAction, pnMin); if (nAction & ACB_DRIVER_DATA) { BurnYM3812Scan(nAction, pnMin); } if (nAction & ACB_WRITE) { memcpy(MSM6295ROM + 0x00000, DrvMSM6295ROMSrc + (0x40000 * DrvOkiBank), 0x40000); } return 0; } static int ZeropntScan(int nAction, int *pnMin) { DrvScan(nAction, pnMin); if (nAction & ACB_DRIVER_DATA) { BurnYM3812Scan(nAction, pnMin); } if (nAction & ACB_WRITE) { memcpy(MSM6295ROM + 0x20000, DrvMSM6295ROMSrc + 0x20000 + (0x20000 * DrvOkiBank), 0x20000); } return 0; } static int Zeropnt2Scan(int nAction, int *pnMin) { DrvScan(nAction, pnMin); EEPROMScan(nAction, pnMin); if (nAction & ACB_DRIVER_DATA) { BurnYM2151Scan(nAction); MSM6295Scan(1, nAction); } if (nAction & ACB_WRITE) { memcpy(MSM6295ROM + 0x20000, DrvMSM6295ROMSrc + 0x20000 + (0x20000 * DrvOkiBank), 0x20000); } return 0; } struct BurnDriver BurnDrvBurglarx = { "burglarx", NULL, NULL, "1997", "Burglar X\0", NULL, "Unico", "Unico", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, BurglarxRomInfo, BurglarxRomName, BurglarxInputInfo, BurglarxDIPInfo, BurglarxInit, DrvExit, DrvFrame, NULL, BurglarxScan, NULL, 384, 224, 4, 3 }; struct BurnDriver BurnDrvZeropnt = { "zeropnt", NULL, NULL, "1998", "Zero Point (set 1)\0", NULL, "Unico", "Unico", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, ZeropntRomInfo, ZeropntRomName, ZeropntInputInfo, ZeropntDIPInfo, ZeropntInit, DrvExit, DrvFrame, NULL, ZeropntScan, NULL, 384, 224, 4, 3 }; struct BurnDriver BurnDrvZeropnta = { "zeropnta", "zeropnt", NULL, "1998", "Zero Point (set 2)\0", NULL, "Unico", "Unico", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_MISC_MISC, NULL, ZeropntaRomInfo, ZeropntaRomName, ZeropntInputInfo, ZeropntDIPInfo, ZeropntInit, DrvExit, DrvFrame, NULL, ZeropntScan, NULL, 384, 224, 4, 3 }; struct BurnDriver BurnDrvZeropnt2 = { "zeropnt2", NULL, NULL, "1999", "Zero Point 2\0", NULL, "Unico", "Unico", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, Zeropnt2RomInfo, Zeropnt2RomName, ZeropntInputInfo, Zeropnt2DIPInfo, Zeropnt2Init, Zeropnt2Exit, Zeropnt2Frame, NULL, Zeropnt2Scan, NULL, 384, 224, 4, 3 };
[ "twinaphex1@gmail.com" ]
twinaphex1@gmail.com
19bcba9d23ce5c511776ef88310fe3b3494c15b2
1b970fc5bcf2835dd77f7df655162062eaf7e622
/extras/mk_preview.cc
f3def97f6d52af723139f827356d90fd68c621e8
[ "Apache-2.0" ]
permissive
RReverser/libwebp2
ad5878824b998f1b3e72e146b51547e115a05823
c90b5b476004c9a98731ae1c175cebab5de50fbf
refs/heads/master
2023-01-19T17:17:26.443516
2020-10-30T14:09:17
2020-10-30T14:09:42
311,739,302
7
0
null
null
null
null
UTF-8
C++
false
false
13,681
cc
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // ----------------------------------------------------------------------------- // // simple command line tools to create/manipulate/optimize preview bits // // Author: Skal (pascal.massimino@gmail.com) #include <cstdio> #include <cstring> #include <string> #include <vector> #include "extras/extras.h" #include "examples/example_utils.h" #include "imageio/file_format.h" #include "imageio/imageio_util.h" #include "imageio/image_dec.h" #include "imageio/image_enc.h" #include "src/common/preview/preview.h" // TODO(skal): make better include #include "src/enc/preview/preview_enc.h" #include "src/dec/preview/preview_dec.h" #include "src/wp2/encode.h" #define CHECK_OK(COND, STR...) do { \ if (!(COND)) { \ fprintf(stderr, STR); \ return 1; \ } \ } while (false) #define CHECK_STATUS(CALL, STR...) CHECK_OK(((CALL) == WP2_STATUS_OK), STR) static int verbose = 1; static bool check = false; #define VERBOSE(STR...) if (verbose > 0) printf(STR) // NOLINT (string literal) namespace { bool operator==(const WP2::AYCoCg19b& a, const WP2::AYCoCg19b& b) { return (a.y == b.y) && (a.co == b.co) && (a.cg == b.cg) && (a.a == b.a); } bool operator==(const WP2::VertexIndexedColor& a, const WP2::VertexIndexedColor& b) { return (a.x == b.x) && (a.y == b.y) && (a.color_index == b.color_index); } template<typename T> bool SameArray(const T a[], const T b[], size_t size) { for (size_t i = 0; i < size; ++i) { if (!(a[i] == b[i])) return false; } return true; } bool operator==(const WP2::PreviewData& A, const WP2::PreviewData& B) { return (A.grid_width_ == B.grid_width_) && (A.grid_height_ == B.grid_height_) && (A.palette_.size() == B.palette_.size()) && (A.vertices_.size() == B.vertices_.size()) && SameArray(A.corners_, B.corners_, 4) && SameArray(A.palette_.data(), B.palette_.data(), A.palette_.size()) && SameArray(A.vertices_.data(), B.vertices_.data(), A.vertices_.size()); } } // namespace static void Help() { ProgramOptions opt; opt.Add("Usage:"); opt.Add(" preview -convert [-dry] text_files... "); opt.Add(" preview image [bits|text] [options... ]" "[-o output] [-d output]"); opt.Add(""); opt.Add("PreviewConfiguration Options:"); opt.Add(" -m [edge,rand,diff]", "analysis method"); opt.Add(" -n <int>", "starting number of vertices"); opt.Add(" -nc <int>", "starting number of colors"); opt.Add(" -density <float>", "grid density"); opt.Add(" -g <int>", "initial grid size"); opt.Add(" -b <int>", "blur radius"); opt.Add(""); opt.Add("Optimization Options:"); opt.Add(" -s <int>", "target size in bytes"); opt.Add(" -i <int>", "number of optim iterations"); opt.Add(" -l <int>", "size vs quality trade-off. " "0=favor quality, 100=favor size"); opt.Add(" -p none", "reset all proba to 0"); opt.Add(" -p <move> <int>", "change the proba for the given <move>:"); opt.Add(" . vmove: vertex move"); opt.Add(" . vadd: vertex insertion"); opt.Add(" . vsub: vertex removal"); opt.Add(" . cmove: color move"); opt.Add(" . cadd: color insertion"); opt.Add(" . csub: color removal"); opt.Add(" . cidx: color index move"); opt.Add(""); opt.Add("Other Options:"); opt.Add(" -txt", "use Text for preview data"); opt.Add(" -info", "print full preview info"); opt.Add(" -short", "print short preview info"); opt.Add(" -w <int>", "output width for thumbnail"); opt.Add(" -d <file_prefix>", "prefix for reconstructed thumbnail"); opt.Add(" -o <file_prefix>", "prefix for output data"); opt.Add(" -check", "perform round-trip check"); opt.Add(" -noforce", "don't force file over-write"); opt.Add(" -quiet", "reduced verbosity"); opt.Add(" -verbose", "extra verbosity"); opt.Print(); } //------------------------------------------------------------------------------ static int ConvertTextFiles(int argc, const char* argv[]) { // pure txt->bits conversion mode uint32_t total_size = 0; uint32_t nb_files = 0; bool dry_run = false; for (int c = 2; c < argc; ++c) { if (!strcmp(argv[c], "-dry")) { dry_run = true; continue; } else if (!strcmp(argv[c], "-h")) { Help(); return 0; } std::string in; CHECK_STATUS(WP2::IoUtilReadFile(argv[c], &in), "bad input [%s]\n", argv[c]); WP2::PreviewData data; CHECK_STATUS(PreviewFromText(in, &data), "Error in text-to-preview\n"); WP2::ANSEnc enc; CHECK_STATUS(data.Encode(&enc), "Error encoding to binary! SHOULDN'T HAPPEN!!\n"); if (!dry_run) { const std::string out_name = WP2RemoveFileExtension(argv[c]) + ".bits"; CHECK_STATUS(WP2::IoUtilWriteFile(enc.Buffer(), enc.BufferSize(), out_name.c_str()), "Couldn't save compressed bits [%s]!\n", out_name.c_str()); } if (check) { WP2::PreviewData verif; CHECK_STATUS(verif.Decode(enc.Buffer(), enc.BufferSize()), "Round-trip Decode() failed.\n"); CHECK_STATUS(verif == data, "Round-trip verification failed!\n"); } total_size += enc.BufferSize(); ++nb_files; } VERBOSE("%u files, size: %u bytes\n", nb_files, total_size); return 0; } //------------------------------------------------------------------------------ static void ResetProbas(WP2::PreviewConfig* const config) { config->proba_vertex_move = 0; config->proba_vertex_add = 0; config->proba_vertex_sub = 0; config->proba_color_move = 0; config->proba_color_add = 0; config->proba_color_sub = 0; config->proba_color_index_move = 0; } int main(int argc, const char* argv[]) { if (argc < 2) { fprintf(stderr, "missing arguments!\n"); Help(); return 1; } if (argc > 1 && !strcmp(argv[1], "-convert")) { return ConvertTextFiles(argc, argv); } WP2::PreviewConfig config(75.f, 5); const char* img_file = nullptr; const char* bin_file = nullptr; const char* out_file = nullptr; const char* preview_file = nullptr; bool overwrite = true; uint32_t out_w = 256; // width of decoded preview enum { TEXT, INFO, SHORT } out_format = SHORT; for (int c = 1; c < argc; ++c) { bool parse_error = false; if (!strcmp(argv[c], "-h")) { Help(); return 0; } else if (!strcmp(argv[c], "-check")) { check = true; } else if (!strcmp(argv[c], "-noforce")) { overwrite = false; } else if (!strcmp(argv[c], "-quiet")) { verbose = 0; out_format = SHORT; } else if (!strcmp(argv[c], "-verbose")) { verbose = 2; } else if (!strcmp(argv[c], "-txt")) { out_format = TEXT; } else if (!strcmp(argv[c], "-info")) { out_format = INFO; } else if (!strcmp(argv[c], "-short")) { out_format = SHORT; } else if (!strcmp(argv[c], "-w") && c + 1 < argc) { out_w = std::max(ExUtilGetUInt(argv[++c], &parse_error), 32u); } else if (!strcmp(argv[c], "-o") && c + 1 < argc) { out_file = argv[++c]; } else if (!strcmp(argv[c], "-d") && c + 1 < argc) { preview_file = argv[++c]; } else if (!strcmp(argv[c], "-s") && c + 1 < argc) { config.target_num_bytes = ExUtilGetUInt(argv[++c], &parse_error); } else if (!strcmp(argv[c], "-l") && c + 1 < argc) { config.importance_of_size_over_quality = 4.4f * ExUtilGetUInt(argv[++c], &parse_error) / 100.f; } else if (!strcmp(argv[c], "-p") && c + 1 < argc) { if (!strcmp(argv[c + 1], "none")) { ResetProbas(&config); c += 1; } else if (c + 2 < argc) { auto* const dst = !strcmp(argv[c + 1], "vmove") ? &config.proba_vertex_move : !strcmp(argv[c + 1], "vadd") ? &config.proba_vertex_add : !strcmp(argv[c + 1], "vsub") ? &config.proba_vertex_sub : !strcmp(argv[c + 1], "cmove") ? &config.proba_color_move : !strcmp(argv[c + 1], "cadd") ? &config.proba_color_add : !strcmp(argv[c + 1], "csub") ? &config.proba_color_sub : !strcmp(argv[c + 1], "cidx") ? &config.proba_color_index_move : nullptr; CHECK_OK(dst != nullptr, "Invalid -p move '%s'\n", argv[c + 1]); *dst = ExUtilGetUInt(argv[c + 2], &parse_error); c += 2; } } else if (!strcmp(argv[c], "-m") && c + 1 < argc) { ++c; if (!strcmp(argv[c], "edge")) { config.analysis_method = WP2::PreviewConfig::AnalysisMethod::kEdgeSelectionAndRepulsion; } else if (!strcmp(argv[c], "diff")) { config.analysis_method = WP2::PreviewConfig::AnalysisMethod::kColorDiffMaximization; } else if (!strcmp(argv[c], "rand")) { config.analysis_method = WP2::PreviewConfig::AnalysisMethod::kRandomEdgeSelection; } else { CHECK_OK(false, "Unknown analysis method '%s'\n", argv[c]); } } else if (!strcmp(argv[c], "-n") && c + 1 < argc) { config.num_vertices = ExUtilGetUInt(argv[++c], &parse_error); } else if (!strcmp(argv[c], "-nc") && c + 1 < argc) { config.num_colors = ExUtilGetUInt(argv[++c], &parse_error); } else if (!strcmp(argv[c], "-density") && c + 1 < argc) { config.grid_density = ExUtilGetUInt(argv[++c], &parse_error); } else if (!strcmp(argv[c], "-g") && c + 1 < argc) { config.grid_size = ExUtilGetUInt(argv[++c], &parse_error); } else if (!strcmp(argv[c], "-b") && c + 1 < argc) { config.blur_radius = ExUtilGetUInt(argv[++c], &parse_error); } else if (!strcmp(argv[c], "-i") && c + 1 < argc) { config.num_iterations = ExUtilGetUInt(argv[++c], &parse_error); } else if (c < argc && argv[c][0] != '-') { if (img_file == nullptr) { img_file = argv[c]; } else { bin_file = argv[c]; } } else { parse_error = true; } if (parse_error) { Help(); return 1; } } CHECK_OK(img_file != nullptr, "Missing input image"); CHECK_OK(config.IsValid(), "PreviewConfig is invalid.\n"); WP2::ArgbBuffer original; CHECK_STATUS(WP2::ReadImage(img_file, &original), "Can't read image [%s]\n", img_file); WP2::PreviewData data; if (bin_file == nullptr) { WP2::MemoryWriter writer; CHECK_STATUS(WP2::EncodePreview(original, config, &writer), "Error in EncodePreview()\n"); CHECK_STATUS(data.Decode(writer.mem_, writer.size_), "Round-trip error. SHOULDN'T HAPPEN!!'\n"); } else { // Read the starting state const bool as_txt = (WP2GetFileExtension(bin_file) == "txt"); std::string bin; CHECK_STATUS(WP2::IoUtilReadFile(bin_file, &bin), "bad bin file [%s]\n", bin_file); if (as_txt) { CHECK_STATUS(PreviewFromText(bin, &data), "Error in text-to-preview\n"); } else { CHECK_STATUS(data.Decode((const uint8_t*)bin.data(), bin.size()), "Can't decode binary data [%s]", bin_file); } // optimize further CHECK_STATUS(data.Optimize(original, config, /*log=*/true), "Optimize() call failed\n"); } // save binary/text result WP2::ANSEnc enc; CHECK_STATUS(data.Encode(&enc), "Error encoding to binary! SHOULDN'T HAPPEN!!\n"); const uint32_t preview_size = enc.BufferSize(); const uint8_t* const preview_data = enc.Buffer(); VERBOSE("Creating preview for %s. Size:%u\n", img_file, preview_size); if (out_file != nullptr) { const bool as_txt = (WP2GetFileExtension(out_file) == "txt"); if (as_txt) { const std::string s = PreviewToText(data); CHECK_STATUS( WP2::IoUtilWriteFile( (const uint8_t*)s.data(), s.size(), out_file, overwrite), "Couldn't write preview as text [%s]!\n", out_file); } else { // raw output CHECK_STATUS( WP2::IoUtilWriteFile( preview_data, preview_size, out_file, overwrite), "Couldn't write preview as binary [%s]!\n", out_file); } VERBOSE("Saved [%s] as %s\n", out_file, as_txt ? "text" : "binary"); } // save reconstructed preview if (preview_file != nullptr) { const uint32_t out_h = std::max(32u, WP2::DivRound(out_w * original.height, original.width)); WP2::ArgbBuffer thumb; CHECK_STATUS(thumb.Resize(out_w, out_h), "Memory error\n"); CHECK_STATUS(WP2::DecodePreview(preview_data, preview_size, &thumb), "Error in DecodePreview()\n"); CHECK_STATUS(WP2::SaveImage(thumb, preview_file, overwrite), "Couldn't save decoded preview as [%s]!\n", preview_file); VERBOSE("Saved [%s]\n", preview_file); } // print final info std::string infos = "\n"; if (out_format == INFO) { infos = PrintPreview(data, /* reduced= */false); } else if (out_format == SHORT) { infos = PrintPreview(data, /* reduced= */true); } else if (out_format == TEXT) { infos = PreviewToText(data); } VERBOSE("%s", infos.c_str()); return 0; }
[ "yguyon@google.com" ]
yguyon@google.com
b11b9a6a97b86b22b98b085574d2cf507b4df5f4
cad604b38f9257c5410751bfebded37a73b02436
/Userland/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.h
f853f1f08d6b9a1cd64f77c235b439d941d69339
[ "BSD-2-Clause" ]
permissive
govi20/serenity
5f4d7217afbe8b98313aed26ad663d1f56553250
67362b1f8501b19b451c71cc28b540da15171739
refs/heads/master
2023-06-26T21:14:06.461110
2021-07-09T02:57:34
2021-07-09T13:36:50
384,451,039
1
0
BSD-2-Clause
2021-07-09T13:49:20
2021-07-09T13:49:19
null
UTF-8
C++
false
false
2,363
h
/* * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibWasm/AbstractMachine/Configuration.h> #include <LibWasm/AbstractMachine/Interpreter.h> namespace Wasm { struct BytecodeInterpreter : public Interpreter { virtual void interpret(Configuration&) override; virtual ~BytecodeInterpreter() override = default; virtual bool did_trap() const override { return m_trap.has_value(); } virtual String trap_reason() const override { return m_trap.value().reason; } virtual void clear_trap() override { m_trap.clear(); } struct CallFrameHandle { explicit CallFrameHandle(BytecodeInterpreter& interpreter, Configuration& configuration) : m_configuration_handle(configuration) , m_interpreter(interpreter) { } ~CallFrameHandle() = default; Configuration::CallFrameHandle m_configuration_handle; BytecodeInterpreter& m_interpreter; }; protected: virtual void interpret(Configuration&, InstructionPointer&, Instruction const&); void branch_to_label(Configuration&, LabelIndex); template<typename ReadT, typename PushT> void load_and_push(Configuration&, Instruction const&); void store_to_memory(Configuration&, Instruction const&, ReadonlyBytes data); void call_address(Configuration&, FunctionAddress); template<typename V, typename T> MakeUnsigned<T> checked_unsigned_truncate(V); template<typename V, typename T> MakeSigned<T> checked_signed_truncate(V); template<typename T> T read_value(ReadonlyBytes data); Vector<Value> pop_values(Configuration& configuration, size_t count); bool trap_if_not(bool value, StringView reason) { if (!value) m_trap = Trap { reason }; return m_trap.has_value(); } Optional<Trap> m_trap; }; struct DebuggerBytecodeInterpreter : public BytecodeInterpreter { virtual ~DebuggerBytecodeInterpreter() override = default; Function<bool(Configuration&, InstructionPointer&, Instruction const&)> pre_interpret_hook; Function<bool(Configuration&, InstructionPointer&, Instruction const&, Interpreter const&)> post_interpret_hook; private: virtual void interpret(Configuration&, InstructionPointer&, Instruction const&) override; }; }
[ "Ali.mpfard@gmail.com" ]
Ali.mpfard@gmail.com
4880487e5c3309b1eeb244d8c931c908b69a0e53
5b9bc4cddb8246219062551703184740e9c93b03
/HB MED BROKEN CALCULATOR/broken.cpp
263c9a2f248cc5e576008d2b5e93c5e75aa7ae03
[]
no_license
deep-bansal/HACKER-BLOCKS
b182e505c0c7c78e243efc287fe59187cf9d90ab
a102769ca14d06280e1871c1a68a762ec4fa1044
refs/heads/master
2022-11-13T09:26:41.813271
2020-07-08T04:43:02
2020-07-08T04:43:02
274,833,375
1
0
null
null
null
null
UTF-8
C++
false
false
673
cpp
#include <bits/stdc++.h> #include <iostream> using namespace std; void multiply(int* arr, int &n,int no) { int carry = 0; for (int i = 0; i < n; ++i) { int product = arr[i]* no + carry; arr[i] = product%10; carry = product/10; } while(carry) // left out { arr[n] = carry%10; carry = carry/10; n++; } } void big_interger(int num) { int* arr = new int [10000]{0}; arr[0] = 1; int n= 1; for (int i = 2; i <= num; ++i) { multiply(arr,n,i); } for (int i = n-1; i >= 0 ; --i) { cout<<arr[i]; } cout<<endl; } int main(int argc, char const *argv[]) { int n; cin>>n; big_interger(n); return 0; }
[ "noreply@github.com" ]
deep-bansal.noreply@github.com
f6a9d6fbddd33a4386c2096fcda3e1d1f1afa810
99307e632063e7f8fa75fa43f301cb890f109475
/matlab/FlowFilter_mex.cpp
4e7c61bf026f5a63b4693471bb981a9bebef4172
[]
no_license
abeerraj/optical-flow-filter
44806fa414b29b894ad60b78e89598e329a7652c
597197587f8f64eff1bf44d11495fd9c54faab8d
refs/heads/master
2022-04-15T18:02:32.290250
2020-04-11T23:48:28
2020-04-11T23:48:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,213
cpp
/** * \file FlowFilter_mex.cpp * \brief Matlab mex interface to flowfilter::gpu::FlowFilter class. * \copyright 2015, Juan David Adarve, ANU. See AUTHORS for more details * \license 3-clause BSD, see LICENSE for more details */ #include <string> #include <vector> #include "mex.h" #include "classHandle.h" #include "imgutil.h" #include "flowfilter/image.h" #include "flowfilter/gpu/flowfilter.h" using namespace std; using namespace flowfilter; using namespace flowfilter::gpu; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Get the command string char cmd_buffer[64]; if (nrhs < 1 || mxGetString(prhs[0], cmd_buffer, sizeof(cmd_buffer))) { mexErrMsgTxt("First input should be a command string less than 64 characters long"); } string cmd(&cmd_buffer[0]); // mexPrintf("Input command: %s\n", cmd.c_str()); // CONSTRUCTOR if (cmd == "new") { // Check parameters if (nlhs != 1) { mexErrMsgTxt("New: Expecting class handle as output parameter."); } if(nrhs != 3) { mexErrMsgTxt("[height, width] parameters are required to create FlowFilter"); } int height = mxGetScalar(prhs[1]); int width = mxGetScalar(prhs[2]); mexPrintf("FlowFilter.new(): [%d, %d]\n", height, width); // Return a handle to a new C++ instance FlowFilter* filter = new FlowFilter(height, width); plhs[0] = convertPtr2Mat<FlowFilter>(filter); // upon successful creation of object, lock the mex file until the // object is destroyed mexLock(); return; } // Check there is a second input, which should be the class instance handle if (nrhs < 2) { mexErrMsgTxt("Second input should be a class instance handle."); } // DESTRUCTOR if(cmd == "delete") { mexPrintf("FlowFilter.~FlowFilter()\n"); // Destroy the C++ object destroyObject<FlowFilter>(prhs[1]); // Warn if other commands were ignored if (nlhs != 0 || nrhs != 2) { mexWarnMsgTxt("Delete: Unexpected arguments ignored."); } // unlock the mex file. This does not check for errors while destroying the object. mexUnlock(); return; } // Get the class instance pointer from the second input FlowFilter *instance = convertMat2Ptr<FlowFilter>(prhs[1]); // ************************************************************** // // // // CLASS METHODS // // // // * height() // // * width() // // * configure() // // * compute() // // * elapsedTime() // // * loadImage() // // * downloadImage() // // * downloadFlow() // // * setGamma() // // * getGamma() // // * getMaxFlow() // // * setMaxFlow() // // * getSmoothIterations() // // * setSmoothIterations() // // * getPropagationBorder() // // * setPropagationBorder() // // * getPropagationIterations() // // ************************************************************** // // mexPrintf("[nlhs, nrhs]: [%d, %d]", nlhs, nrhs); if(cmd == "loadImage") { if(nlhs != 0) mexErrMsgTxt("FlowFilter.upload(): expecting zero output parameters."); if(nrhs != 3) mexErrMsgTxt("FlowFilter.upload(): expecting 3 input parameters."); const mxArray* img = prhs[2]; image_t img_w = wrapMxImage(img); // printImageWrappedInfo("image parameter", img_w); instance->loadImage(img_w); return; } if(cmd == "compute") { if(nlhs != 0) mexErrMsgTxt("FlowFilter.compute(): expecting zero output parameters."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.compute(): expecting 2 input parameters."); instance->compute(); return; } if(cmd == "elapsedTime") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.elapsedTime(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.elapsedTime(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->elapsedTime()); return; } if(cmd == "downloadFlow") { if(nlhs != 1) mexErrMsgTxt("GPUImage.downloadFlow(): expecting 1 output parameters."); if(nrhs != 2) mexErrMsgTxt("GPUImage.downloadFlow(): expecting 2 input parameters."); // create uint8 image mxArray* flow = createMxArray(instance->height(), instance->width(), 2, mxSINGLE_CLASS); image_t flow_w = wrapMxImage(flow); // set flow as output value plhs[0] = flow; instance->downloadFlow(flow_w); // float* ptr = (float*)mxGetData(flow); // // print first elements // for(unsigned int i = 0; i < 10; i ++) { // mexPrintf("i: %d\t=%f\n", i, ptr[i]); // } return; } if(cmd == "downloadImage") { if(nlhs != 1) mexErrMsgTxt("GPUImage.downloadImage(): expecting 1 output parameters."); if(nrhs != 2) mexErrMsgTxt("GPUImage.downloadImage(): expecting 2 input parameters."); // create uint8 image mxArray* img = createMxArray(instance->height(), instance->width(), mxSINGLE_CLASS); image_t img_w = wrapMxImage(img); // set img as output value plhs[0] = img; instance->downloadImage(img_w); return; } if(cmd == "setGamma") { if(nlhs != 0) mexErrMsgTxt("FlowFilter.setGamma(): expecting zero output parameter."); if(nrhs != 3) mexErrMsgTxt("FlowFilter.setGamma(): expecting 3 input parameters."); instance->setGamma(mxGetScalar(prhs[2])); return; } if(cmd == "getGamma") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.getGamma(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.getGamma(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->getGamma()); return; } if(cmd == "setMaxFlow") { if(nlhs != 0) mexErrMsgTxt("FlowFilter.setMaxFlow(): expecting zero output parameter."); if(nrhs != 3) mexErrMsgTxt("FlowFilter.setMaxFlow(): expecting 3 input parameters."); instance->setMaxFlow(mxGetScalar(prhs[2])); return; } if(cmd == "getMaxFlow") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.getMaxFlow(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.getMaxFlow(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->getMaxFlow()); return; } if(cmd == "setSmoothIterations") { if(nlhs != 0) mexErrMsgTxt("FlowFilter.setSmoothIterations(): expecting zero output parameter."); if(nrhs != 3) mexErrMsgTxt("FlowFilter.setSmoothIterations(): expecting 3 input parameters."); instance->setSmoothIterations((int)mxGetScalar(prhs[2])); return; } if(cmd == "getSmoothIterations") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.getSmoothIterations(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.getSmoothIterations(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->getSmoothIterations()); return; } if(cmd == "setPropagationBorder") { if(nlhs != 0) mexErrMsgTxt("FlowFilter.setPropagationBorder(): expecting zero output parameter."); if(nrhs != 3) mexErrMsgTxt("FlowFilter.setPropagationBorder(): expecting 3 input parameters."); instance->setPropagationBorder((int)mxGetScalar(prhs[2])); return; } if(cmd == "getPropagationBorder") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.getPropagationBorder(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.getPropagationBorder(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->getPropagationBorder()); return; } if(cmd == "getPropagationIterations") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.getPropagationIterations(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.getPropagationIterations(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->getPropagationIterations()); return; } if(cmd == "configure") { if(nlhs != 0) mexErrMsgTxt("FlowFilter.configure(): expecting zero output parameters."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.configure(): expecting 2 input parameters."); instance->configure(); return; } if(cmd == "height") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.height(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.height(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->height()); return; } if(cmd == "width") { if(nlhs != 1) mexErrMsgTxt("FlowFilter.width(): expecting 1 output parameter."); if(nrhs != 2) mexErrMsgTxt("FlowFilter.width(): expecting 2 input parameters."); plhs[0] = mxCreateDoubleScalar(instance->width()); return; } // Got here, so command not recognized mexErrMsgTxt("Command not recognized: "); }
[ "juan.adarve@anu.edu.au" ]
juan.adarve@anu.edu.au
201bd9c193fcb2150af5cd0a54f3d707faf18d7d
cdb79e4ed5246ed423e31973150925b1eb6f6d29
/src/potentials/potentials_name.h
9ec6dc98692f4fd579c98e9daa3f3936b25f3b0a
[]
no_license
jmacdona/pd2_public
6a0906e944878d954be29a245be718d3145c88e6
5b84579fd4a093e3095cd9bf15d2ca9d2b0b9b48
refs/heads/master
2020-03-08T09:27:34.373885
2019-03-25T15:38:21
2019-03-25T15:38:21
128,047,792
1
1
null
2018-04-11T09:42:33
2018-04-04T10:40:10
C++
UTF-8
C++
false
false
2,316
h
// // (c) JAMES T. MACDONALD 2010 // This file is part of the PRODART 2 software // suite and is made available under license. // // For more information please contact by email: j.t.macdonald+prodart@gmail.com // /* * potentials_name.h * * Created on: 17 Mar 2010 * Author: jmacdona */ #ifndef POTENTIALS_NAME_H_ #define POTENTIALS_NAME_H_ #include <string> #include <cctype> #include<boost/algorithm/string.hpp> #include<boost/lexical_cast.hpp> #include<boost/algorithm/string/split.hpp> #include <map> #include <vector> namespace PRODART { namespace POSE { namespace POTENTIALS { const int max_label_size = 20; //! stores potential name which must be less than or equal to 20 characters long class potentials_name { //! comparison using potentials_label[] friend bool operator==( const potentials_name&, const potentials_name& ); //! comparison using potentials_label[] friend bool operator<( const potentials_name&, const potentials_name& ); public: //potentials_name(); potentials_name(const std::string label); potentials_name& operator=(const potentials_name&); std::string get_label() const; private: void set_label(const std::string& label); //! name as read by weights so must be unique and less than 20 chars long. char potentials_label[max_label_size+1]; }; typedef std::map<potentials_name, double> potentials_name_double_map; typedef std::vector<potentials_name> potentials_name_vector; inline potentials_name::potentials_name(const std::string label){ this->set_label(label); } inline potentials_name& potentials_name::operator=(const potentials_name& at){ for (int i = 0; i < max_label_size; i++){ this->potentials_label[i] = at.potentials_label[i]; } return *this; } inline bool operator==( const potentials_name& at1, const potentials_name& at2 ){ for (int i = 0; i < max_label_size; i++){ if (at1.potentials_label[i] != at2.potentials_label[i]){ return false; } } return true; } inline bool operator<( const potentials_name& at1, const potentials_name& at2 ){ for (int i = 0; i < max_label_size; i++){ if (at1.potentials_label[i] < at2.potentials_label[i]){ return true; } else if (at1.potentials_label[i] > at2.potentials_label[i]) { return false; } } return false; } } } } #endif /* POTENTIALS_NAME_H_ */
[ "jtmacdonald@gmail.com" ]
jtmacdonald@gmail.com
7c961708d463994893ea29a5838cf3b39e4d4e5e
243af6f697c16c54af3613988ddaef62a2b29212
/firmware/uvc_controller/mbed-os/drivers/USBMouseKeyboard.h
281f1926eb1156a1b10b446a304146dbcf0790f3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
davewhiiite/uvc
0020fcc99d279a70878baf7cdc5c02c19b08499a
fd45223097eed5a824294db975b3c74aa5f5cc8f
refs/heads/main
2023-05-29T10:18:08.520756
2021-06-12T13:06:40
2021-06-12T13:06:40
376,287,264
1
0
null
null
null
null
UTF-8
C++
false
false
7,541
h
/* * Copyright (c) 2018-2019, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef USBMOUSEKEYBOARD_H #define USBMOUSEKEYBOARD_H #define REPORT_ID_KEYBOARD 1 #define REPORT_ID_MOUSE 2 #define REPORT_ID_VOLUME 3 #include "USBMouse.h" #include "USBKeyboard.h" #include "platform/Stream.h" #include "USBHID.h" #include "PlatformMutex.h" /** * \defgroup drivers_USBMouseKeyboard USBMouseKeyboard class * \ingroup drivers-public-api-usb * @{ */ /** * USBMouseKeyboard example * @code * * #include "mbed.h" * #include "USBMouseKeyboard.h" * * USBMouseKeyboard key_mouse; * * int main(void) * { * while(1) * { * key_mouse.move(20, 0); * key_mouse.printf("Hello From MBED\r\n"); * ThisThread::sleep_for(1000); * } * } * @endcode * * * @code * * #include "mbed.h" * #include "USBMouseKeyboard.h" * * USBMouseKeyboard key_mouse(ABS_MOUSE); * * int main(void) * { * while(1) * { * key_mouse.move(X_MAX_ABS/2, Y_MAX_ABS/2); * key_mouse.printf("Hello from MBED\r\n"); * ThisThread::sleep_for(1000); * } * } * @endcode * * @note Synchronization level: Thread safe */ class USBMouseKeyboard: public USBHID, public mbed::Stream { public: /** * Basic constructor * * Construct this object optionally connecting and blocking until it is ready. * * @note Do not use this constructor in derived classes. * * @param connect_blocking true to perform a blocking connect, false to start in a disconnected state * @param mouse_type Mouse type: ABS_MOUSE (absolute mouse) or REL_MOUSE (relative mouse) (default: REL_MOUSE) * @param vendor_id Your vendor_id (default: 0x1234) * @param product_id Your product_id (default: 0x0001) * @param product_release Your preoduct_release (default: 0x0001) * */ USBMouseKeyboard(bool connect_blocking = true, MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x0021, uint16_t product_id = 0x0011, uint16_t product_release = 0x0001); /** * Fully featured constructor * * Construct this object with the supplied USBPhy and parameters. The user * this object is responsible for calling connect() or init(). * * @note Derived classes must use this constructor and call init() or * connect() themselves. Derived classes should also call deinit() in * their destructor. This ensures that no interrupts can occur when the * object is partially constructed or destroyed. * * @param phy USB phy to use * @param mouse_type Mouse type: ABS_MOUSE (absolute mouse) or REL_MOUSE (relative mouse) (default: REL_MOUSE) * @param vendor_id Your vendor_id (default: 0x1234) * @param product_id Your product_id (default: 0x0001) * @param product_release Your preoduct_release (default: 0x0001) * */ USBMouseKeyboard(USBPhy *phy, MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x0021, uint16_t product_id = 0x0011, uint16_t product_release = 0x0001); /** * Destroy this object * * Any classes which inherit from this class must call deinit * before this destructor runs. */ virtual ~USBMouseKeyboard(); /** * Write a state of the mouse * * @param x x-axis position * @param y y-axis position * @param buttons buttons state (first bit represents MOUSE_LEFT, second bit MOUSE_RIGHT and third bit MOUSE_MIDDLE) * @param z wheel state (>0 to scroll down, <0 to scroll up) * @returns true if there is no error, false otherwise */ bool update(int16_t x, int16_t y, uint8_t buttons, int8_t z); /** * Move the cursor to (x, y) * * @param x x-axis position * @param y y-axis position * @returns true if there is no error, false otherwise */ bool move(int16_t x, int16_t y); /** * Press one or several buttons * * @param button button state (ex: press(MOUSE_LEFT)) * @returns true if there is no error, false otherwise */ bool press(uint8_t button); /** * Release one or several buttons * * @param button button state (ex: release(MOUSE_LEFT)) * @returns true if there is no error, false otherwise */ bool release(uint8_t button); /** * Double click (MOUSE_LEFT) * * @returns true if there is no error, false otherwise */ bool doubleClick(); /** * Click * * @param button state of the buttons ( ex: clic(MOUSE_LEFT)) * @returns true if there is no error, false otherwise */ bool click(uint8_t button); /** * Scrolling * * @param z value of the wheel (>0 to go down, <0 to go up) * @returns true if there is no error, false otherwise */ bool scroll(int8_t z); /** * To send a character defined by a modifier(CTRL, SHIFT, ALT) and the key * * @code * //To send CTRL + s (save) * keyboard.keyCode('s', KEY_CTRL); * @endcode * * @param modifier bit 0: KEY_CTRL, bit 1: KEY_SHIFT, bit 2: KEY_ALT (default: 0) * @param key character to send * @returns true if there is no error, false otherwise */ bool key_code(uint8_t key, uint8_t modifier = 0); /** * Send a character * * @param c character to be sent * @returns true if there is no error, false otherwise */ virtual int _putc(int c); /** * Control media keys * * @param key media key pressed (KEY_NEXT_TRACK, KEY_PREVIOUS_TRACK, KEY_STOP, KEY_PLAY_PAUSE, KEY_MUTE, KEY_VOLUME_UP, KEY_VOLUME_DOWN) * @returns true if there is no error, false otherwise */ bool media_control(MEDIA_KEY key); /** * Read status of lock keys. Useful to switch-on/off LEDs according to key pressed. Only the first three bits of the result is important: * - First bit: NUM_LOCK * - Second bit: CAPS_LOCK * - Third bit: SCROLL_LOCK * * @returns status of lock keys */ uint8_t lock_status(); /* * To define the report descriptor. Warning: this method has to store the length of the report descriptor in reportLength. * * @returns pointer to the report descriptor */ virtual const uint8_t *report_desc(); /* * Called when a data is received on the OUT endpoint. Useful to switch on LED of LOCK keys * * @returns if handle by subclass, return true */ virtual void report_rx(); private: MOUSE_TYPE _mouse_type; uint8_t _button; uint8_t _lock_status; PlatformMutex _mutex; bool _mouse_send(int8_t x, int8_t y, uint8_t buttons, int8_t z); //dummy otherwise it doesn't compile (we must define all methods of an abstract class) virtual int _getc(); }; /** @}*/ #endif
[ "13125501+davewhiiite@users.noreply.github.com" ]
13125501+davewhiiite@users.noreply.github.com
b26b0c3fa3225543d74cbe9f8ff3db7dc52c65e6
993d195bcd2d0c410983954f13fe34356f73cfe8
/workspace/vflib/include/vf2_sub_state.h
68de9896a9d4aaff327144e81c500c0b6d7c698d
[]
no_license
celebro/diploma
e4da6f0f1447e3b27c31474164f55718b744fdf7
a96df9a188ac3cf035f372839cbd6c372aeeeae1
refs/heads/master
2021-03-12T21:42:39.337604
2013-03-28T08:43:52
2013-03-28T08:43:52
8,127,151
2
0
null
null
null
null
UTF-8
C++
false
false
1,775
h
/*------------------------------------------------------------ * vf2_sub_state.h * Interface of vf2_sub_state.cc * Definition of a class representing a state of the matching * process between two ARGs. * See: argraph.h state.h * * Author: P. Foggia *-----------------------------------------------------------------*/ #ifndef VF2_SUB_STATE_H #define VF2_SUB_STATE_H #include "argraph.h" #include "state.h" /*---------------------------------------------------------- * class VF2SubState * A representation of the SSR current state * See vf2_sub_state.cc for more details. ---------------------------------------------------------*/ class VF2SubState: public State { typedef ARGraph_impl Graph; private: int core_len, orig_core_len; int added_node1; int t1both_len, t2both_len, t1in_len, t1out_len, t2in_len, t2out_len; // Core nodes are also counted by these... node_id *core_1; node_id *core_2; node_id *in_1; node_id *in_2; node_id *out_1; node_id *out_2; node_id *order; Graph *g1, *g2; int n1, n2; long *share_count; node_id *hevristicOrder; public: VF2SubState(Graph *g1, Graph *g2, int sortHevristic = 0); VF2SubState(const VF2SubState &state); ~VF2SubState(); Graph *GetGraph1() { return g1; } Graph *GetGraph2() { return g2; } bool NextPair(node_id *pn1, node_id *pn2, node_id prev_n1 = NULL_NODE, node_id prev_n2 = NULL_NODE); bool IsFeasiblePair(node_id n1, node_id n2); void AddPair(node_id n1, node_id n2); bool IsGoal() { return core_len == n1; } ; bool IsDead() { return n1 > n2 || t1both_len > t2both_len || t1out_len > t2out_len || t1in_len > t2in_len; } ; int CoreLen() { return core_len; } void GetCoreSet(node_id c1[], node_id c2[]); State *Clone(); virtual void BackTrack(); }; #endif
[ "nejc.ramovs@gmail.com" ]
nejc.ramovs@gmail.com
1de8baba867709b7f8a90633e0da27f9791d1981
10265de3a7442a82f3a1ec100feeb36a21ece1a6
/Workspace/VP9/Project/anpr_20180224/PlateRecognizationFramework/include/Crop/crop_char_long.h
dc619cf59a28e1e0504cbb2880010b4fede3e676
[]
no_license
zeklewa/Zeklewa_ANPR
77f861ae7f3c60f6d64ecabbc0586ede8af78b3e
bea4ddc172ebca27e6175ca3d43d2256317023b1
refs/heads/master
2020-04-09T20:36:03.912406
2018-03-07T14:13:07
2018-03-07T14:13:07
124,242,757
0
0
null
null
null
null
UTF-8
C++
false
false
255
h
#ifndef CROP_CHAR_LONG #define CROP_CHAR_LONG #include <iostream> #include <vector> #include <chrono> #include <mutex> using namespace cv; using namespace std; std::vector<cv::Rect> getCharacterRect_LongPlate(cv::Mat& img_rgb); #endif
[ "bachngd@gmail.com" ]
bachngd@gmail.com