hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1651082bd716f0a2a479444b9518d6853ee92edd | 1,030 | cpp | C++ | ycitoj/week1/a.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | 3 | 2022-03-30T14:14:57.000Z | 2022-03-31T04:30:32.000Z | ycitoj/week1/a.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | ycitoj/week1/a.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#define ll int64_t
#define endl "\n"
using namespace std;
void solve(){
int n;
cin >> n;
vector<int> vec1, vec2;
for (int i = 0; i < n; i++){
string str;
cin >> str;
vec1.push_back(str[str.size() - 1] - '0');
}
for (int i = 0; i < n; i++){
string str;
cin >> str;
vec2.push_back(str[str.size() - 1] - '0');
}
if (vec1[n - 1] == 1 || vec1[n - 1] == 2){
cout << "NO" << endl;
return;
}
for (int i = 0; i < n; i++){
if ((vec1[i] == 1 || vec1[i] == 2) && (vec2[i] == 3 || vec2[i] == 4))
continue;
else if ((vec2[i] == 1 || vec2[i] == 2) && (vec1[i] == 3 || vec1[i] == 4))
continue;
else{
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
//IO
int t;
cin >> t;
while (t--){
solve();
}
return 0;
}
| 19.433962 | 82 | 0.405825 | Zilanlann |
16516fc0b786ded2ab5ebcc4de3c9cd866b2eadf | 1,617 | hpp | C++ | Applications/Topper/plugins/Topper.Workbench/src/RootEntity.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | 2 | 2018-02-07T01:19:37.000Z | 2018-02-09T14:27:48.000Z | Applications/Topper/plugins/Topper.Workbench/src/RootEntity.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | Applications/Topper/plugins/Topper.Workbench/src/RootEntity.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Topper Trading Workbench
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
// @author Matthew Alan Gray - <mgray@hatboysoftware.com>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once
#include "Entity.hpp"
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Topper {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class RootEntity
: public Entity
{
/// @name Types
/// @{
public:
/// @}
/// @name I_Cleanable implementation
/// @{
public:
void setDirty() const override;
/// @}
/// @name Entity implementation
/// @{
public:
const std::string& getType() const override;
const I_Entity& getRoot() const;
const Helmet::Workbench::I_Model& getParentModel() const override;
bool isVisible() override;
/// @}
/// @name RootEntity implementation
/// @{
public:
/// @}
/// @name 'Structors
/// @{
public:
RootEntity(Helmet::Workbench::I_Model& _parent,
const std::string& _name,
const std::string& _entityInfo);
virtual ~RootEntity();
/// @}
/// @name Member Variables
/// @{
private:
static const std::string sm_type;
Helmet::Workbench::I_Model& m_parent;
/// @}
}; // class RootEntity
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Topper
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| 24.876923 | 80 | 0.413729 | hatboysoftware |
1653357bb6b8dac9a58649f9020b6b74bbca2582 | 1,250 | cpp | C++ | test/result_type_test.cpp | ToruNiina/Boost.toml | 0d29d33834d29f476f2d1a0d9e2758660d3e8eb3 | [
"BSL-1.0"
] | 29 | 2018-06-01T14:40:07.000Z | 2022-01-24T12:57:09.000Z | test/result_type_test.cpp | ToruNiina/Boost.toml | 0d29d33834d29f476f2d1a0d9e2758660d3e8eb3 | [
"BSL-1.0"
] | 1 | 2019-12-07T22:33:37.000Z | 2019-12-09T19:49:50.000Z | test/result_type_test.cpp | ToruNiina/Boost.toml | 0d29d33834d29f476f2d1a0d9e2758660d3e8eb3 | [
"BSL-1.0"
] | 1 | 2020-07-13T20:57:48.000Z | 2020-07-13T20:57:48.000Z | #define BOOST_TEST_MODULE "result_type_test"
#include <boost/test/included/unit_test.hpp>
#include <toml/result.hpp>
#include <iostream>
#include <iomanip>
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_construction)
{
{
result<int, double> r(ok(42));
BOOST_CHECK(r);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(!r.is_err());
}
{
result<int, double> r(err(3.14));
BOOST_CHECK(!r);
BOOST_CHECK(!r.is_ok());
BOOST_CHECK(r.is_err());
}
{
result<int, double> r = ok(42);
BOOST_CHECK(r);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(!r.is_err());
}
{
result<int, double> r = err(3.14);
BOOST_CHECK(!r);
BOOST_CHECK(!r.is_ok());
BOOST_CHECK(r.is_err());
}
}
BOOST_AUTO_TEST_CASE(test_unwrap)
{
{
result<int, double> r(ok(42));
BOOST_CHECK_EQUAL(r.unwrap(), 42);
BOOST_CHECK_EQUAL(r.ok_or(54), 42);
BOOST_CHECK_EQUAL(r.err_or(2.71), 2.71);
}
{
result<int, double> r(err(3.14));
BOOST_CHECK_EQUAL(r.unwrap_err(), 3.14);
BOOST_CHECK_EQUAL(r.ok_or(54), 54);
BOOST_CHECK_EQUAL(r.err_or(2.71), 3.14);
}
}
| 23.584906 | 48 | 0.572 | ToruNiina |
16541366bc006d93360704a60bc16f74e2fbeb30 | 3,432 | cpp | C++ | frontend/main.cpp | shahakash28/mPSI-TableOPPRF | 58a5b71e6af952b3df9bfc6a8eabc3762af9dde1 | [
"Unlicense"
] | 1 | 2021-12-26T09:37:34.000Z | 2021-12-26T09:37:34.000Z | frontend/main.cpp | shahakash28/mPSI-TableOPPRF | 58a5b71e6af952b3df9bfc6a8eabc3762af9dde1 | [
"Unlicense"
] | 2 | 2021-12-20T11:27:45.000Z | 2021-12-22T11:19:12.000Z | frontend/main.cpp | shahakash28/mPSI-TableOPPRF | 58a5b71e6af952b3df9bfc6a8eabc3762af9dde1 | [
"Unlicense"
] | null | null | null | //Modified by Nishka Dasgupta, Akash Shah
#include <iostream>
#include "Network/BtChannel.h"
#include "Network/BtEndpoint.h"
//#include "../MPCHonestMajority/MPSI_Party.h"
using namespace std;
#include "Common/Defines.h"
using namespace osuCrypto;
#include "OtBinMain.h"
#include "bitPosition.h"
#include <numeric>
#include "Common/Log.h"
//int miraclTestMain();
void usage(const char* argv0)
{
std::cout << "Error! Please use:" << std::endl;
std::cout << "\t 1. For unit test: " << argv0 << " -u" << std::endl;
std::cout << "\t 2. For simulation (5 parties <=> 5 terminals): " << std::endl;;
std::cout << "\t\t each terminal: " << argv0 << " -n 5 -t 2 -m 12 -p [pIdx]" << std::endl;
}
int main(int argc, char** argv)
{
/*char **circuitArgv;
std::vector<uint64_t> bins;
MPSI_Party<ZpMersenneLongElement> mpsi(1, circuitArgv, bins, 4096);
mpsi.readMPSIInputs(bins, 4096);
mpsi.runMPSI();*/
//myCuckooTest_stash();
//Table_Based_Random_Test();
//OPPRF2_EmptrySet_Test_Main();
//OPPRFn_EmptrySet_Test_Main();
//Transpose_Test();
//OPPRF3_EmptrySet_Test_Main();
//OPPRFnt_EmptrySet_Test_Main();
//OPPRFnt_EmptrySet_Test_Main();
//OPPRFn_Aug_EmptrySet_Test_Impl();
//OPPRFnt_EmptrySet_Test_Main();
//OPPRF2_EmptrySet_Test_Main();
//return 0;
u64 trials = 1;
u64 pSetSize = 5, psiSecParam = 40, bitSize = 128;
u64 nParties, tParties, opt_basedOPPRF, setSize, isAug;
u64 roundOPPRF;
char * timingsfile = "runtime.txt";
switch (argc) {
case 2: //unit test
if (argv[1][0] == '-' && argv[1][1] == 'u')
OPPRFnt_EmptrySet_Test_Main();
break;
case 7: //2PSI
if (argv[1][0] == '-' && argv[1][1] == 'n')
nParties = atoi(argv[2]);
else
{
usage(argv[0]);
return 0;
}
if (argv[3][0] == '-' && argv[3][1] == 'm')
setSize = 1 << atoi(argv[4]);
else
{
usage(argv[0]);
return 0;
}
if (argv[5][0] == '-' && argv[5][1] == 'p') {
u64 pIdx = atoi(argv[6]);
if (nParties == 2)
party2(pIdx, setSize);
else
{
usage(argv[0]);
return 0;
}
}
else
{
usage(argv[0]);
return 0;
}
break;
case 11: //nPSI or optimized 3PSI
cout << "11\n";
if (argv[1][0] == '-' && argv[1][1] == 'n')
nParties = atoi(argv[2]);
else
{
usage(argv[0]);
return 0;
}
if (argv[3][0] == '-' && argv[3][1] == 'r' && nParties == 3)
{
roundOPPRF = atoi(argv[4]);
tParties = 2;
}
else if (argv[3][0] == '-' && argv[3][1] == 't')
tParties = atoi(argv[4]);
else if (argv[3][0] == '-' && argv[3][1] == 'a')
opt_basedOPPRF = atoi(argv[4]);
else
{
usage(argv[0]);
return 0;
}
if (argv[5][0] == '-' && argv[5][1] == 'm')
setSize = 1 << atoi(argv[6]);
else
{
usage(argv[0]);
return 0;
}
if (argv[7][0] == '-' && argv[7][1] == 'p') {
u64 pIdx = atoi(argv[8]);
if (roundOPPRF == 1 && nParties == 3)
{
//cout << nParties << " " << roundOPPRF << " " << setSize << " " << pIdx << "\n";
party3(pIdx, setSize, trials);
}
else if (argv[3][1] == 't')
{
//cout << nParties << " " << tParties << " " << setSize << " " << pIdx << "\n";
if (argv[9][0] == '-' && argv[9][1] == 'F') {
timingsfile = argv[10];
}
tparty(pIdx, nParties, tParties, setSize, trials, timingsfile);
}
else if (argv[3][1] == 'a')
{
aug_party(pIdx, nParties, setSize, opt_basedOPPRF, trials);
}
}
else
{
usage(argv[0]);
return 0;
}
break;
}
return 0;
}
| 21.185185 | 91 | 0.559149 | shahakash28 |
1656afae5dae168349052cbd3ecc196efe8ca034 | 15,007 | cpp | C++ | src/tests/add-ons/kernel/file_systems/bfs/r5/Journal.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2017-06-17T22:03:56.000Z | 2019-01-25T10:51:55.000Z | src/tests/add-ons/kernel/file_systems/bfs/r5/Journal.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/tests/add-ons/kernel/file_systems/bfs/r5/Journal.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | /*
* Copyright 2001-2008, Axel Dörfler, axeld@pinc-software.de
* This file may be used under the terms of the MIT License.
*/
//! Transaction and logging
#include "Journal.h"
#include "Inode.h"
#include <Drivers.h>
#include <util/kernel_cpp.h>
struct run_array {
int32 count;
int32 max_runs;
block_run runs[0];
int32 CountRuns() const { return BFS_ENDIAN_TO_HOST_INT32(count); }
int32 MaxRuns() const { return BFS_ENDIAN_TO_HOST_INT32(max_runs); }
const block_run &RunAt(int32 i) const { return runs[i]; }
static int32 MaxRuns(int32 blockSize)
{ return (blockSize - sizeof(run_array)) / sizeof(block_run); }
};
class LogEntry : public DoublyLinkedListLinkImpl<LogEntry> {
public:
LogEntry(Journal *journal, uint32 logStart);
~LogEntry();
status_t InitCheck() const { return fArray != NULL ? B_OK : B_NO_MEMORY; }
uint32 Start() const { return fStart; }
uint32 Length() const { return fLength; }
Journal *GetJournal() { return fJournal; }
bool InsertBlock(off_t blockNumber);
bool NotifyBlocks(int32 count);
run_array *Array() const { return fArray; }
int32 CountRuns() const { return fArray->CountRuns(); }
int32 MaxRuns() const { return fArray->MaxRuns() - 1; }
// the -1 is an off-by-one error in Be's BFS implementation
const block_run &RunAt(int32 i) const { return fArray->RunAt(i); }
private:
Journal *fJournal;
uint32 fStart;
uint32 fLength;
uint32 fCachedBlocks;
run_array *fArray;
};
// #pragma mark -
LogEntry::LogEntry(Journal *journal, uint32 start)
:
fJournal(journal),
fStart(start),
fLength(1),
fCachedBlocks(0)
{
int32 blockSize = fJournal->GetVolume()->BlockSize();
fArray = (run_array *)malloc(blockSize);
if (fArray == NULL)
return;
memset(fArray, 0, blockSize);
fArray->max_runs = HOST_ENDIAN_TO_BFS_INT32(run_array::MaxRuns(blockSize));
}
LogEntry::~LogEntry()
{
free(fArray);
}
/** Adds the specified block into the array.
*/
bool
LogEntry::InsertBlock(off_t blockNumber)
{
// Be's BFS log replay routine can only deal with block_runs of size 1
// A pity, isn't it? Too sad we have to be compatible.
if (CountRuns() >= MaxRuns())
return false;
block_run run = fJournal->GetVolume()->ToBlockRun(blockNumber);
fArray->runs[CountRuns()] = run;
fArray->count = HOST_ENDIAN_TO_BFS_INT32(CountRuns() + 1);
fLength++;
fCachedBlocks++;
return true;
}
bool
LogEntry::NotifyBlocks(int32 count)
{
fCachedBlocks -= count;
return fCachedBlocks == 0;
}
// #pragma mark -
Journal::Journal(Volume *volume)
:
fVolume(volume),
fLock("bfs journal"),
fOwner(NULL),
fArray(volume->BlockSize()),
fLogSize(volume->Log().Length()),
fMaxTransactionSize(fLogSize / 4 - 5),
fUsed(0),
fTransactionsInEntry(0)
{
if (fMaxTransactionSize > fLogSize / 2)
fMaxTransactionSize = fLogSize / 2 - 5;
}
Journal::~Journal()
{
FlushLogAndBlocks();
}
status_t
Journal::InitCheck()
{
if (fVolume->LogStart() != fVolume->LogEnd()) {
if (fVolume->SuperBlock().flags != SUPER_BLOCK_DISK_DIRTY)
FATAL(("log_start and log_end differ, but disk is marked clean - trying to replay log...\n"));
return ReplayLog();
}
return B_OK;
}
status_t
Journal::_CheckRunArray(const run_array *array)
{
int32 maxRuns = run_array::MaxRuns(fVolume->BlockSize());
if (array->MaxRuns() != maxRuns
|| array->CountRuns() > maxRuns
|| array->CountRuns() <= 0) {
FATAL(("Log entry has broken header!\n"));
return B_ERROR;
}
for (int32 i = 0; i < array->CountRuns(); i++) {
if (fVolume->ValidateBlockRun(array->RunAt(i)) != B_OK)
return B_ERROR;
}
PRINT(("Log entry has %ld entries (%Ld)\n", array->CountRuns()));
return B_OK;
}
/** Replays an entry in the log.
* \a _start points to the entry in the log, and will be bumped to the next
* one if replaying succeeded.
*/
status_t
Journal::_ReplayRunArray(int32 *_start)
{
PRINT(("ReplayRunArray(start = %ld)\n", *_start));
off_t logOffset = fVolume->ToBlock(fVolume->Log());
off_t blockNumber = *_start % fLogSize;
int32 blockSize = fVolume->BlockSize();
int32 count = 1;
CachedBlock cachedArray(fVolume);
const run_array *array = (const run_array *)cachedArray.SetTo(logOffset + blockNumber);
if (array == NULL)
return B_IO_ERROR;
if (_CheckRunArray(array) < B_OK)
return B_BAD_DATA;
blockNumber = (blockNumber + 1) % fLogSize;
CachedBlock cached(fVolume);
for (int32 index = 0; index < array->CountRuns(); index++) {
const block_run &run = array->RunAt(index);
PRINT(("replay block run %lu:%u:%u in log at %Ld!\n", run.AllocationGroup(),
run.Start(), run.Length(), blockNumber));
off_t offset = fVolume->ToOffset(run);
for (int32 i = 0; i < run.Length(); i++) {
const uint8 *data = cached.SetTo(logOffset + blockNumber);
if (data == NULL)
RETURN_ERROR(B_IO_ERROR);
ssize_t written = write_pos(fVolume->Device(),
offset + (i * blockSize), data, blockSize);
if (written != blockSize)
RETURN_ERROR(B_IO_ERROR);
blockNumber = (blockNumber + 1) % fLogSize;
count++;
}
}
*_start += count;
return B_OK;
}
/** Replays all log entries - this will put the disk into a
* consistent and clean state, if it was not correctly unmounted
* before.
* This method is called by Journal::InitCheck() if the log start
* and end pointer don't match.
*/
status_t
Journal::ReplayLog()
{
INFORM(("Replay log, disk was not correctly unmounted...\n"));
int32 start = fVolume->LogStart();
int32 lastStart = -1;
while (true) {
// stop if the log is completely flushed
if (start == fVolume->LogEnd())
break;
if (start == lastStart) {
// strange, flushing the log hasn't changed the log_start pointer
return B_ERROR;
}
lastStart = start;
status_t status = _ReplayRunArray(&start);
if (status < B_OK) {
FATAL(("replaying log entry from %ld failed: %s\n", start, strerror(status)));
return B_ERROR;
}
start = start % fLogSize;
}
PRINT(("replaying worked fine!\n"));
fVolume->SuperBlock().log_start = HOST_ENDIAN_TO_BFS_INT64(fVolume->LogEnd());
fVolume->LogStart() = fVolume->LogEnd();
fVolume->SuperBlock().flags = HOST_ENDIAN_TO_BFS_INT32(SUPER_BLOCK_DISK_CLEAN);
return fVolume->WriteSuperBlock();
}
/** This is a callback function that is called by the cache, whenever
* a block is flushed to disk that was updated as part of a transaction.
* This is necessary to keep track of completed transactions, to be
* able to update the log start pointer.
*/
void
Journal::blockNotify(off_t blockNumber, size_t numBlocks, void *arg)
{
LogEntry *logEntry = (LogEntry *)arg;
if (!logEntry->NotifyBlocks(numBlocks)) {
// nothing to do yet...
return;
}
Journal *journal = logEntry->GetJournal();
disk_super_block &superBlock = journal->fVolume->SuperBlock();
bool update = false;
// Set log_start pointer if possible...
journal->fEntriesLock.Lock();
if (logEntry == journal->fEntries.First()) {
LogEntry *next = journal->fEntries.GetNext(logEntry);
if (next != NULL) {
int32 length = next->Start() - logEntry->Start();
superBlock.log_start = HOST_ENDIAN_TO_BFS_INT64((superBlock.LogStart() + length) % journal->fLogSize);
} else
superBlock.log_start = HOST_ENDIAN_TO_BFS_INT64(journal->fVolume->LogEnd());
update = true;
}
journal->fUsed -= logEntry->Length();
journal->fEntries.Remove(logEntry);
journal->fEntriesLock.Unlock();
free(logEntry);
// update the superblock, and change the disk's state, if necessary
if (update) {
journal->fVolume->LogStart() = superBlock.log_start;
if (superBlock.log_start == superBlock.log_end)
superBlock.flags = SUPER_BLOCK_DISK_CLEAN;
status_t status = journal->fVolume->WriteSuperBlock();
if (status != B_OK)
FATAL(("blockNotify: could not write back superblock: %s\n", strerror(status)));
}
}
status_t
Journal::WriteLogEntry()
{
fTransactionsInEntry = 0;
fHasChangedBlocks = false;
sorted_array *array = fArray.Array();
if (array == NULL || array->count == 0)
return B_OK;
// Make sure there is enough space in the log.
// If that fails for whatever reason, panic!
force_cache_flush(fVolume->Device(), false);
int32 tries = fLogSize / 2 + 1;
while (TransactionSize() > FreeLogBlocks() && tries-- > 0)
force_cache_flush(fVolume->Device(), true);
if (tries <= 0) {
fVolume->Panic();
return B_BAD_DATA;
}
int32 blockShift = fVolume->BlockShift();
off_t logOffset = fVolume->ToBlock(fVolume->Log()) << blockShift;
off_t logStart = fVolume->LogEnd();
off_t logPosition = logStart % fLogSize;
// Create log entries for the transaction
LogEntry *logEntry = NULL, *firstEntry = NULL, *lastAdded = NULL;
for (int32 i = 0; i < array->CountItems(); i++) {
retry:
if (logEntry == NULL) {
logEntry = new LogEntry(this, logStart);
if (logEntry == NULL)
return B_NO_MEMORY;
if (logEntry->InitCheck() != B_OK) {
delete logEntry;
return B_NO_MEMORY;
}
if (firstEntry == NULL)
firstEntry = logEntry;
logStart++;
}
if (!logEntry->InsertBlock(array->ValueAt(i))) {
// log entry is full - start a new one
fEntriesLock.Lock();
fEntries.Add(logEntry);
fEntriesLock.Unlock();
lastAdded = logEntry;
logEntry = NULL;
goto retry;
}
logStart++;
}
if (firstEntry == NULL)
return B_OK;
if (logEntry != lastAdded) {
fEntriesLock.Lock();
fEntries.Add(logEntry);
fEntriesLock.Unlock();
}
// Write log entries to disk
CachedBlock cached(fVolume);
fEntriesLock.Lock();
for (logEntry = firstEntry; logEntry != NULL; logEntry = fEntries.GetNext(logEntry)) {
// first write the log entry array
write_pos(fVolume->Device(), logOffset + (logPosition << blockShift),
logEntry->Array(), fVolume->BlockSize());
logPosition = (logPosition + 1) % fLogSize;
for (int32 i = 0; i < logEntry->CountRuns(); i++) {
uint8 *block = cached.SetTo(logEntry->RunAt(i));
if (block == NULL)
return B_IO_ERROR;
// write blocks
write_pos(fVolume->Device(), logOffset + (logPosition << blockShift),
block, fVolume->BlockSize());
logPosition = (logPosition + 1) % fLogSize;
}
}
fEntriesLock.Unlock();
fUsed += array->CountItems();
// Update the log end pointer in the superblock
fVolume->SuperBlock().flags = HOST_ENDIAN_TO_BFS_INT32(SUPER_BLOCK_DISK_DIRTY);
fVolume->SuperBlock().log_end = HOST_ENDIAN_TO_BFS_INT64(logPosition);
fVolume->LogEnd() = logPosition;
status_t status = fVolume->WriteSuperBlock();
// We need to flush the drives own cache here to ensure
// disk consistency.
// If that call fails, we can't do anything about it anyway
ioctl(fVolume->Device(), B_FLUSH_DRIVE_CACHE);
fEntriesLock.Lock();
logStart = firstEntry->Start();
for (logEntry = firstEntry; logEntry != NULL; logEntry = fEntries.GetNext(logEntry)) {
// Note: this only works this way as we only have block_runs of length 1
// We're reusing the fArray array, as we don't need it anymore, and
// it's guaranteed to be large enough for us, too
for (int32 i = 0; i < logEntry->CountRuns(); i++) {
array->values[i] = fVolume->ToBlock(logEntry->RunAt(i));
}
set_blocks_info(fVolume->Device(), &array->values[0],
logEntry->CountRuns(), blockNotify, logEntry);
}
fEntriesLock.Unlock();
fArray.MakeEmpty();
// If the log goes to the next round (the log is written as a
// circular buffer), all blocks will be flushed out which is
// possible because we don't have any locked blocks at this
// point.
if (logPosition < logStart)
fVolume->FlushDevice();
return status;
}
status_t
Journal::FlushLogAndBlocks()
{
status_t status = Lock((Transaction *)this);
if (status != B_OK)
return status;
// write the current log entry to disk
if (TransactionSize() != 0) {
status = WriteLogEntry();
if (status < B_OK)
FATAL(("writing current log entry failed: %s\n", strerror(status)));
}
status = fVolume->FlushDevice();
Unlock((Transaction *)this, true);
return status;
}
status_t
Journal::Lock(Transaction *owner)
{
if (owner == fOwner)
return B_OK;
status_t status = fLock.Lock();
if (status == B_OK)
fOwner = owner;
// if the last transaction is older than 2 secs, start a new one
if (fTransactionsInEntry != 0 && system_time() - fTimestamp > 2000000L)
WriteLogEntry();
return B_OK;
}
void
Journal::Unlock(Transaction *owner, bool success)
{
if (owner != fOwner)
return;
TransactionDone(success);
fTimestamp = system_time();
fOwner = NULL;
fLock.Unlock();
}
/** If there is a current transaction that the current thread has
* started, this function will give you access to it.
*/
Transaction *
Journal::CurrentTransaction()
{
if (fLock.LockWithTimeout(0) != B_OK)
return NULL;
Transaction *owner = fOwner;
fLock.Unlock();
return owner;
}
status_t
Journal::TransactionDone(bool success)
{
if (!success && fTransactionsInEntry == 0) {
// we can safely abort the transaction
sorted_array *array = fArray.Array();
if (array != NULL) {
// release the lock for all blocks in the array (we don't need
// to be notified when they are actually written to disk)
for (int32 i = 0; i < array->CountItems(); i++)
release_block(fVolume->Device(), array->ValueAt(i));
}
return B_OK;
}
// Up to a maximum size, we will just batch several
// transactions together to improve speed
if (TransactionSize() < fMaxTransactionSize) {
fTransactionsInEntry++;
fHasChangedBlocks = false;
return B_OK;
}
return WriteLogEntry();
}
status_t
Journal::LogBlocks(off_t blockNumber, const uint8 *buffer, size_t numBlocks)
{
// ToDo: that's for now - we should change the log file size here
if (TransactionSize() + numBlocks + 1 > fLogSize)
return B_DEVICE_FULL;
fHasChangedBlocks = true;
int32 blockSize = fVolume->BlockSize();
for (;numBlocks-- > 0; blockNumber++, buffer += blockSize) {
if (fArray.Find(blockNumber) >= 0) {
// The block is already in the log, so just update its data
// Note, this is only necessary if this method is called with a buffer
// different from the cached block buffer - which is unlikely but
// we'll make sure this way (costs one cache lookup, though).
status_t status = cached_write(fVolume->Device(), blockNumber, buffer, 1, blockSize);
if (status < B_OK)
return status;
continue;
}
// Insert the block into the transaction's array, and write the changes
// back into the locked cache buffer
fArray.Insert(blockNumber);
status_t status = cached_write_locked(fVolume->Device(), blockNumber, buffer, 1, blockSize);
if (status < B_OK)
return status;
}
// If necessary, flush the log, so that we have enough space for this transaction
if (TransactionSize() > FreeLogBlocks())
force_cache_flush(fVolume->Device(), true);
return B_OK;
}
// #pragma mark -
status_t
Transaction::Start(Volume *volume, off_t refBlock)
{
// has it already been started?
if (fJournal != NULL)
return B_OK;
fJournal = volume->GetJournal(refBlock);
if (fJournal != NULL && fJournal->Lock(this) == B_OK)
return B_OK;
fJournal = NULL;
return B_ERROR;
}
| 24.12701 | 105 | 0.690078 | axeld |
165b49d4c77dc5232759996289928184e64b5dd0 | 6,553 | cpp | C++ | src/TransportUtilities.cpp | tamara-schmitz/audacity | df42c72ecfa663cab028f7932c4063c79aee6b9d | [
"CC-BY-3.0"
] | 2 | 2022-01-17T08:27:47.000Z | 2022-02-08T15:54:42.000Z | src/TransportUtilities.cpp | tamara-schmitz/audacity | df42c72ecfa663cab028f7932c4063c79aee6b9d | [
"CC-BY-3.0"
] | 70 | 2021-07-18T18:11:53.000Z | 2021-12-05T20:22:15.000Z | src/TransportUtilities.cpp | tamara-schmitz/audacity | df42c72ecfa663cab028f7932c4063c79aee6b9d | [
"CC-BY-3.0"
] | 2 | 2021-09-08T18:12:22.000Z | 2021-12-24T16:39:47.000Z | /**********************************************************************
Audacity: A Digital Audio Editor
@file TransportUtilities.cpp
@brief implements some UI related to starting and stopping play and record
Paul Licameli split from TransportMenus.cpp
**********************************************************************/
#include "TransportUtilities.h"
#include <thread>
#include "AudioIO.h"
#include "commands/CommandContext.h"
#include "Project.h"
#include "ProjectAudioIO.h"
#include "ProjectAudioManager.h"
#include "ViewInfo.h"
#include "toolbars/ControlToolBar.h"
#include "widgets/ProgressDialog.h"
void TransportUtilities::PlayCurrentRegionAndWait(
const CommandContext &context,
bool newDefault,
bool cutpreview)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
const auto &playRegion = ViewInfo::Get(project).playRegion;
double t0 = playRegion.GetStart();
double t1 = playRegion.GetEnd();
projectAudioManager.PlayCurrentRegion(newDefault, cutpreview);
if (project.mBatchMode > 0 && t0 != t1 && !newDefault) {
wxYieldIfNeeded();
/* i18n-hint: This title appears on a dialog that indicates the progress
in doing something.*/
ProgressDialog progress(XO("Progress"), XO("Playing"), pdlgHideCancelButton);
auto gAudioIO = AudioIO::Get();
while (projectAudioManager.Playing()) {
ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0);
if (result != ProgressResult::Success) {
projectAudioManager.Stop();
if (result != ProgressResult::Stopped) {
context.Error(wxT("Playing interrupted"));
}
break;
}
using namespace std::chrono;
std::this_thread::sleep_for(100ms);
wxYieldIfNeeded();
}
projectAudioManager.Stop();
wxYieldIfNeeded();
}
}
void TransportUtilities::PlayPlayRegionAndWait(
const CommandContext &context,
const SelectedRegion &selectedRegion,
const AudioIOStartStreamOptions &options,
PlayMode mode)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
double t0 = selectedRegion.t0();
double t1 = selectedRegion.t1();
projectAudioManager.PlayPlayRegion(selectedRegion, options, mode);
if (project.mBatchMode > 0) {
wxYieldIfNeeded();
/* i18n-hint: This title appears on a dialog that indicates the progress
in doing something.*/
ProgressDialog progress(XO("Progress"), XO("Playing"), pdlgHideCancelButton);
auto gAudioIO = AudioIO::Get();
while (projectAudioManager.Playing()) {
ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0);
if (result != ProgressResult::Success) {
projectAudioManager.Stop();
if (result != ProgressResult::Stopped) {
context.Error(wxT("Playing interrupted"));
}
break;
}
using namespace std::chrono;
std::this_thread::sleep_for(100ms);
wxYieldIfNeeded();
}
projectAudioManager.Stop();
wxYieldIfNeeded();
}
}
void TransportUtilities::RecordAndWait(
const CommandContext &context, bool altAppearance)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
const auto &selectedRegion = ViewInfo::Get(project).selectedRegion;
double t0 = selectedRegion.t0();
double t1 = selectedRegion.t1();
projectAudioManager.OnRecord(altAppearance);
if (project.mBatchMode > 0 && t1 != t0) {
wxYieldIfNeeded();
/* i18n-hint: This title appears on a dialog that indicates the progress
in doing something.*/
ProgressDialog progress(XO("Progress"), XO("Recording"), pdlgHideCancelButton);
auto gAudioIO = AudioIO::Get();
while (projectAudioManager.Recording()) {
ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0);
if (result != ProgressResult::Success) {
projectAudioManager.Stop();
if (result != ProgressResult::Stopped) {
context.Error(wxT("Recording interrupted"));
}
break;
}
using namespace std::chrono;
std::this_thread::sleep_for(100ms);
wxYieldIfNeeded();
}
projectAudioManager.Stop();
wxYieldIfNeeded();
}
}
// Returns true if this project was stopped, otherwise false.
// (it may though have stopped another project playing)
bool TransportUtilities::DoStopPlaying(const CommandContext &context)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
auto gAudioIO = AudioIOBase::Get();
auto &toolbar = ControlToolBar::Get(project);
auto token = ProjectAudioIO::Get(project).GetAudioIOToken();
//If this project is playing, stop playing, make sure everything is unpaused.
if (gAudioIO->IsStreamActive(token)) {
toolbar.SetStop(); //Pushes stop down
projectAudioManager.Stop();
// Playing project was stopped. All done.
return true;
}
// This project isn't playing.
// If some other project is playing, stop playing it
if (gAudioIO->IsStreamActive()) {
//find out which project we need;
auto start = AllProjects{}.begin(), finish = AllProjects{}.end(),
iter = std::find_if(start, finish,
[&](const AllProjects::value_type &ptr) {
return gAudioIO->IsStreamActive(
ProjectAudioIO::Get(*ptr).GetAudioIOToken()); });
//stop playing the other project
if (iter != finish) {
auto otherProject = *iter;
auto &otherToolbar = ControlToolBar::Get(*otherProject);
auto &otherProjectAudioManager =
ProjectAudioManager::Get(*otherProject);
otherToolbar.SetStop(); //Pushes stop down
otherProjectAudioManager.Stop();
}
}
return false;
}
void TransportUtilities::DoStartPlaying(
const CommandContext &context, bool newDefault)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
auto gAudioIO = AudioIOBase::Get();
//play the front project
if (!gAudioIO->IsBusy()) {
//Otherwise, start playing (assuming audio I/O isn't busy)
// Will automatically set mLastPlayMode
PlayCurrentRegionAndWait(context, newDefault);
}
}
| 32.122549 | 90 | 0.647184 | tamara-schmitz |
165b62def89fd734df69b9cf20d42487fe28b944 | 1,367 | hpp | C++ | libraries/CMakeServerConnector/include/Messages/CodeModelResponse.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | null | null | null | libraries/CMakeServerConnector/include/Messages/CodeModelResponse.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | null | null | null | libraries/CMakeServerConnector/include/Messages/CodeModelResponse.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | 1 | 2020-03-12T04:39:14.000Z | 2020-03-12T04:39:14.000Z | #pragma once
#include <Messages/BasicMessage.hpp>
struct CodeModelResponse : public BasicMessage
{
struct IncludePath
{
std::string path;
};
struct FileGroup
{
std::string compileFlags;
std::vector<std::string> defines;
std::vector<IncludePath> includePaths;
bool isGenerated;
std::string language;
std::vector<std::string> sources;
};
struct Target
{
std::vector<std::string> artifacts;
std::string buildDirectory;
std::vector<FileGroup> fileGroups;
std::string fullName;
std::string linkerLanguage;
std::string name;
std::string sourceDirectory;
std::string type;
};
struct Project
{
std::string buildDirectory;
std::string name;
std::string sourceDirectory;
std::vector<Target> targets;
};
struct Configuration
{
std::string name;
std::vector<Project> projects;
};
std::vector<Configuration> configurations;
static void deserialize(const nlohmann::json& json, BasicMessage& msg);
};
namespace
{
Messages::Registrator<ComputeResponse> CodeModelResponseRegistrator(
"reply",
"codemodel",
Messages::Type::CodeModelResponse,
nullptr,
&CodeModelResponse::deserialize
);
}
| 20.402985 | 75 | 0.610095 | Megaxela |
165e0a4d0ffe0adac7992ab8bba190cfdaa4928d | 1,027 | cc | C++ | chrome/common/metrics_constants_util_win.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | chrome/common/metrics_constants_util_win.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/common/metrics_constants_util_win.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // 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 "chrome/common/metrics_constants_util_win.h"
#include "chrome/installer/util/browser_distribution.h"
namespace {
// Returns the registry path for this product with |suffix| appended to it.
// |suffix| is expected to provide the separator.
base::string16 GetSuffixedRegistryPath(const wchar_t* suffix) {
BrowserDistribution* chrome_distribution =
BrowserDistribution::GetDistribution();
DCHECK(chrome_distribution);
DCHECK_EQ(BrowserDistribution::CHROME_BROWSER,
chrome_distribution->GetType());
DCHECK_EQ(L'\\', *suffix);
DCHECK_NE(L'\\', chrome_distribution->GetRegistryPath().back());
return chrome_distribution->GetRegistryPath() + suffix;
}
} // namespace
namespace chrome {
base::string16 GetBrowserExitCodesRegistryPath() {
return GetSuffixedRegistryPath(L"\\BrowserExitCodes");
}
} // namespace chrome
| 29.342857 | 75 | 0.757546 | xzhan96 |
1660a0319b91c38cbbe2376308e98f031ed515e7 | 1,789 | hpp | C++ | include/mummer/sparseSA_imp.hpp | bredelings/mummer | e084d9b32613ebb1841c60e47a11ff6b1928450a | [
"Artistic-2.0"
] | 284 | 2017-06-12T18:44:09.000Z | 2022-03-29T13:22:00.000Z | ext/mummer/sparseSA_imp.hpp | AT-CG/ChainX | 2b4c902a8981eceda17e72dc7409f744ad3a0bc3 | [
"Apache-2.0"
] | 167 | 2017-06-09T12:33:21.000Z | 2022-03-29T15:45:19.000Z | ext/mummer/sparseSA_imp.hpp | AT-CG/ChainX | 2b4c902a8981eceda17e72dc7409f744ad3a0bc3 | [
"Apache-2.0"
] | 114 | 2017-07-03T07:39:33.000Z | 2022-02-23T06:27:26.000Z | #ifndef __SPARSESA_IMP_H__
#define __SPARSESA_IMP_H__
#undef _OPENMP
#ifdef _OPENMP
#include <omp.h>
#endif
// Implementation of some sparseSA functions
namespace mummer {
namespace sparseSA_imp {
#ifndef _OPENMP
template<typename Map, typename Seq, typename Vec>
void computeLCP(Map& LCP, const Seq& S, const Vec& SA, const Vec& ISA, const long N, const long K) {
long h = 0;
for(long i = 0; i < N / K; ++i) {
const long m = ISA[i];
if(m > 0) {
const long bj = SA[m-1];
const long bi = i * K;
while(bi + h < N && bj + h < N && S[bi + h] == S[bj + h]) ++h;
LCP.set(m, h); //LCP[m] = h;
} else {
LCP.set(m, 0); // LCP[m]=0;
}
h = std::max(0L, h - K);
}
LCP.init();
}
#else // _OPENMP
template<typename Map, typename Seq, typename Vec>
void computeLCP(Map& LCP, const Seq& S, const Vec& SA, const Vec& ISA, const long N, const long K) {
// const long chunk = std::min((long)10000000, (long)(N / omp_get_num_threads()));
std::vector<typename Map::item_vector> Ms;
#pragma omp parallel
{
long h = 0;
typename Map::item_vector tM; // M array for this thread
#pragma omp for schedule(static)
for(long i = 0; i < N / K; ++i) {
const long m = ISA[i];
if(m > 0) {
const long bj = SA[m-1];
const long bi = i * K;
while(bi + h < N && bj + h < N && S[bi + h] == S[bj + h]) ++h;
LCP.set(m, h, tM); //LCP[m] = h;
} else {
LCP.set(m, 0); // LCP[m]=0;
}
h = std::max(0L, h - K);
}
std::sort(tM.begin(), tM.end(), Map::first_comp);
#pragma omp critical
Ms.push_back(std::move(tM));
}
LCP.init_merge(Ms);
}
#endif // _OPENMP
} // namespace sparseSA_imp
} // namespace mummer
#endif /* __SPARSESA_IMP_H__ */
| 24.847222 | 100 | 0.560089 | bredelings |
1668b73bf6e38ce25c4bf0a8301ae61cf44234a7 | 256 | cc | C++ | src/libc/libintl/dcgettext_test.cc | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 298 | 2015-03-04T13:36:51.000Z | 2021-12-19T05:11:58.000Z | src/libc/libintl/dcgettext_test.cc | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 31 | 2015-07-27T14:51:55.000Z | 2020-09-14T15:59:57.000Z | src/libc/libintl/dcgettext_test.cc | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 18 | 2016-03-27T13:49:22.000Z | 2021-09-21T19:02:04.000Z | // Copyright (c) 2016 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <libintl.h>
#include <locale.h>
#include "gtest/gtest.h"
TEST(dcgettext, example) {
ASSERT_STREQ("Hello", dcgettext("appname", "Hello", LC_MESSAGES));
}
| 19.692308 | 68 | 0.6875 | NuxiNL |
1669cb08793b5e4dc5f056e2d1af06ab54b73b3b | 658 | hpp | C++ | src/version.hpp | brandonbraun653/DroneController | b20b8eefa1e03ffc72a3959b567d2cb0b2278b47 | [
"MIT"
] | null | null | null | src/version.hpp | brandonbraun653/DroneController | b20b8eefa1e03ffc72a3959b567d2cb0b2278b47 | [
"MIT"
] | 1 | 2021-10-16T21:56:19.000Z | 2021-10-16T21:56:19.000Z | src/version.hpp | brandonbraun653/DroneController | b20b8eefa1e03ffc72a3959b567d2cb0b2278b47 | [
"MIT"
] | null | null | null | /********************************************************************************
* File Name:
* version.hpp
*
* Description:
* Drone Controller Version
*
* 2021 | Brandon Braun | brandonbraun653@gmail.com
*******************************************************************************/
#pragma once
#ifndef DC_VERSION_HPP
#define DC_VERSION_HPP
/* STL Includes */
#include <string_view>
namespace DC
{
/**
* CHANGELOG;
*
* v0.1.0: Initial version
* v0.2.0: Core hardware working, including basic networking.
*/
static constexpr std::string_view version = "0.2.0";
} // namespace DC
#endif /* !DC_VERSION_HPP */
| 21.225806 | 81 | 0.490881 | brandonbraun653 |
166d54483c158095277be0fbb7105dfafc46ca94 | 2,577 | hpp | C++ | src/xercesc/sax2/SAX2XMLFilter.hpp | gajgeospatial/xerces-c-3.2.2 | 8396d30350e6523313766f9c18e07c4f708be9cb | [
"Apache-2.0"
] | 218 | 2015-07-17T19:18:07.000Z | 2022-03-03T18:00:08.000Z | src/xercesc/sax2/SAX2XMLFilter.hpp | rsn8887/xerces-c | eafbd0b1755fe55550e10aaaf3b15c587d900f39 | [
"Apache-2.0"
] | 88 | 2015-07-08T15:35:46.000Z | 2020-08-13T13:03:09.000Z | src/xercesc/sax2/SAX2XMLFilter.hpp | rsn8887/xerces-c | eafbd0b1755fe55550e10aaaf3b15c587d900f39 | [
"Apache-2.0"
] | 56 | 2015-09-17T21:22:32.000Z | 2021-04-01T20:19:32.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: SAX2XMLFilter.hpp 527149 2007-04-10 14:56:39Z amassari $
*/
#if !defined(XERCESC_INCLUDE_GUARD_SAX2XMLFILTER_HPP)
#define XERCESC_INCLUDE_GUARD_SAX2XMLFILTER_HPP
#include <xercesc/sax2/SAX2XMLReader.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class SAX2_EXPORT SAX2XMLFilter : public SAX2XMLReader
{
public:
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
/** @name Constructors and Destructor */
//@{
/** The default constructor */
SAX2XMLFilter()
{
}
/** The destructor */
virtual ~SAX2XMLFilter()
{
}
//@}
//-----------------------------------------------------------------------
// The XMLFilter interface
//-----------------------------------------------------------------------
/** @name Implementation of SAX 2.0 XMLFilter interface's. */
//@{
/**
* This method returns the parent XMLReader object.
*
* @return A pointer to the parent XMLReader object.
*/
virtual SAX2XMLReader* getParent() const = 0 ;
/**
* Sets the parent XMLReader object; parse requests will be forwarded to this
* object, and callback notifications coming from it will be postprocessed
*
* @param parent The new XMLReader parent.
* @see SAX2XMLReader#SAX2XMLReader
*/
virtual void setParent(SAX2XMLReader* parent) = 0;
//@}
private :
/* The copy constructor, you cannot call this directly */
SAX2XMLFilter(const SAX2XMLFilter&);
/* The assignment operator, you cannot call this directly */
SAX2XMLFilter& operator=(const SAX2XMLFilter&);
};
XERCES_CPP_NAMESPACE_END
#endif
| 31.048193 | 82 | 0.613892 | gajgeospatial |
166e3174a74b9263cd87f863a89338c5b1432abc | 1,750 | cpp | C++ | test/fixture/fixture_string.cpp | engineer-legion/json | 7ef33477720e7c801e5636fae6f34d7fbf55bcf0 | [
"BSL-1.0"
] | null | null | null | test/fixture/fixture_string.cpp | engineer-legion/json | 7ef33477720e7c801e5636fae6f34d7fbf55bcf0 | [
"BSL-1.0"
] | null | null | null | test/fixture/fixture_string.cpp | engineer-legion/json | 7ef33477720e7c801e5636fae6f34d7fbf55bcf0 | [
"BSL-1.0"
] | null | null | null | /*
* fixture_string.cpp
*
* Created on: 01.02.2015
* Author: mike_gresens
*/
#include "fixture_string.hpp"
namespace json {
namespace fixture {
const fixture_base::entry_t
fixture_string::_empty =
{
string_t(),
"\"\""
};
const fixture_base::entry_t
fixture_string::_simple =
{
string_t("foo"),
"\"foo\""
};
const fixture_base::entry_t
fixture_string::_space =
{
string_t(" foo bar "),
"\" foo bar \""
};
const fixture_base::entry_t
fixture_string::_quote =
{
string_t("\"foo\"bar\""),
"\"\\\"foo\\\"bar\\\"\""
};
const fixture_base::entry_t
fixture_string::_backslash =
{
string_t("\\foo\\bar\\"),
"\"\\\\foo\\\\bar\\\\\""
};
const fixture_base::entry_t
fixture_string::_slash =
{
string_t("/foo/bar/"),
"\"\\/foo\\/bar\\/\""
};
const fixture_base::entry_t
fixture_string::_backspace =
{
string_t("\bfoo\bbar\b"),
"\"\\bfoo\\bbar\\b\""
};
const fixture_base::entry_t
fixture_string::_formfeed =
{
string_t("\ffoo\fbar\f"),
"\"\\ffoo\\fbar\\f\""
};
const fixture_base::entry_t
fixture_string::_newline =
{
string_t("\nfoo\nbar\n"),
"\"\\nfoo\\nbar\\n\""
};
const fixture_base::entry_t
fixture_string::_return =
{
string_t("\rfoo\rbar\r"),
"\"\\rfoo\\rbar\\r\""
};
const fixture_base::entry_t
fixture_string::_tab =
{
string_t("\tfoo\tbar\t"),
"\"\\tfoo\\tbar\\t\""
};
const fixture_base::entry_t
fixture_string::_unicode =
{
string_t("\u1234foo\u5555bar\u9876"),
"\"\\u1234foo\\u5555bar\\u9876\""
};
const string_t
fixture_string::_invalid1 =
{
"\"\\ufoo\""
};
const string_t
fixture_string::_invalid2 =
{
"\"\\u12\""
};
const string_t
fixture_string::_invalid3 =
{
"\"\n\""
};
const string_t
fixture_string::_invalid4 =
{
"\\"
};
const string_t
fixture_string::_invalid5 =
{
"\"foo"
};
}
}
| 13.565891 | 38 | 0.640571 | engineer-legion |
166e730bf761817bcbfa36419c4cd8ab3d433dd7 | 1,954 | cpp | C++ | graph-source-code/131-D/897677.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/131-D/897677.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/131-D/897677.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <bitset>
#include <algorithm>
#include <map>
#include <fstream>
#define pb push_back
#define MP make_pair
#define FOR(a,b) for((a)=0 ; (a)<(b) ; (a)++)
typedef long long ll;
using namespace std;
vector<int> table[3001];
vector<int> V;
int N;
bool used[3001];
bool cycle[3001];
int dis[3001];
int cur[3001];
void dfs(int from , int s, int depth){
int i,j;
for(i=0;i<table[s].size();i++){
int to = table[s][i];
if(to == from)continue;
if(used[to]){
for(j=0;j<depth;j++){
if(cur[j]==to){
for(;j<depth;j++)
cycle[cur[j]]=1;
break;
}
}
}else{
used[to] = 1;
cur[depth] = to;
dfs(s,to,depth+1);
}
}
}
void bfs(){
int i,j,k;
queue< pair<int,int> > Q;
for(i=1;i<=N;i++){
if(cycle[i])Q.push(MP(i,0));
}
while(!Q.empty()){
int s= Q.front().first;
int d = Q.front().second;
if(dis[s]==0)d = 0;
for(i=0;i<table[s].size();i++){
int to =table[s][i];
if(dis[to] > d + 1){
dis[to] = d+1;
Q.push(MP(to,d+1));
}
}
Q.pop();
}
return ;
}
int main(){
int i,j,k,M,P,l,m,n;
cin >> N;
int t1,t2;
for(i=0;i<N;i++){
cin >> t1>>t2;
table[t1].pb(t2);
table[t2].pb(t1);
}
cur[0] = 1;
used[1] = 1;
dfs(0,1,1);
for(i=1;i<=N;i++)
if(cycle[i]){
V.pb(i);
dis[i] = 0;
}else dis[i]=100000;
bfs();
for(i=1;i<N;i++){
cout<<dis[i]<<" ";
}
cout<<dis[N]<<endl;
}
| 20.568421 | 46 | 0.413511 | AmrARaouf |
166ec313684fcb5bcc2a8c021ddbaac8b1913b8f | 1,227 | hpp | C++ | source/quantum-script-extension-shell-version.hpp | g-stefan/quantum-script-extension-shell | 27e7885c6b74e518697f40536fa736c637d51981 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-shell-version.hpp | g-stefan/quantum-script-extension-shell | 27e7885c6b74e518697f40536fa736c637d51981 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-shell-version.hpp | g-stefan/quantum-script-extension-shell | 27e7885c6b74e518697f40536fa736c637d51981 | [
"MIT",
"Unlicense"
] | null | null | null | //
// Quantum Script Extension Shell
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#ifndef QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_HPP
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_HPP
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_ABCD 2,1,0,19
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR "2.1.0"
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR_BUILD "19"
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR_DATETIME "2021-08-09 17:38:06"
#ifndef XYO_RC
#ifndef QUANTUM_SCRIPT_EXTENSION_SHELL__EXPORT_HPP
#include "quantum-script-extension-shell--export.hpp"
#endif
namespace Quantum {
namespace Script {
namespace Extension {
namespace Shell {
namespace Version {
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *version();
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *build();
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *versionWithBuild();
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *datetime();
};
};
};
};
};
#endif
#endif
| 29.214286 | 89 | 0.731866 | g-stefan |
166fd21b52feec1d2890a106f0751cd052d0dc1f | 6,252 | cc | C++ | components/tflite/tensorflow/lite/experimental/microfrontend/lib/window_test.cc | HuakeZhBo/bl_mcu_sdk | a6a7f077e5dd535419d1741e4c2f5215eebb699d | [
"Apache-2.0"
] | 93 | 2021-04-27T07:34:49.000Z | 2022-03-22T08:43:44.000Z | components/tflite/tensorflow/lite/experimental/microfrontend/lib/window_test.cc | zeroherolin/bl_mcu_sdk | 97760e3633d7ce0f435be1d98e7c9e8c46bfaca7 | [
"Apache-2.0"
] | 18 | 2021-05-23T14:10:12.000Z | 2022-03-30T09:18:39.000Z | components/tflite/tensorflow/lite/experimental/microfrontend/lib/window_test.cc | zeroherolin/bl_mcu_sdk | 97760e3633d7ce0f435be1d98e7c9e8c46bfaca7 | [
"Apache-2.0"
] | 33 | 2021-04-27T07:46:50.000Z | 2022-02-27T05:45:19.000Z | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/experimental/microfrontend/lib/window.h"
#include "tensorflow/lite/experimental/microfrontend/lib/window_util.h"
#include "tensorflow/lite/micro/testing/micro_test.h"
namespace {
const int kSampleRate = 1000;
const int kWindowSamples = 25;
const int kStepSamples = 10;
const int16_t kFakeAudioData[] = {
0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768,
0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768,
0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768
};
// Test window function behaviors using default config values.
class WindowTestConfig {
public:
WindowTestConfig()
{
config_.size_ms = 25;
config_.step_size_ms = 10;
}
struct WindowConfig config_;
};
} // namespace
TF_LITE_MICRO_TESTS_BEGIN
TF_LITE_MICRO_TEST(WindowState_CheckCoefficients)
{
WindowTestConfig config;
struct WindowState state;
TF_LITE_MICRO_EXPECT(
WindowPopulateState(&config.config_, &state, kSampleRate));
const int16_t expected[] = { 16, 144, 391, 743, 1176, 1664, 2177,
2681, 3145, 3541, 3843, 4032, 4096, 4032,
3843, 3541, 3145, 2681, 2177, 1664, 1176,
743, 391, 144, 16 };
TF_LITE_MICRO_EXPECT_EQ(state.size, sizeof(expected) / sizeof(expected[0]));
int i;
for (i = 0; i < state.size; ++i) {
TF_LITE_MICRO_EXPECT_EQ(state.coefficients[i], expected[i]);
}
WindowFreeStateContents(&state);
}
TF_LITE_MICRO_TEST(WindowState_CheckResidualInput)
{
WindowTestConfig config;
struct WindowState state;
TF_LITE_MICRO_EXPECT(
WindowPopulateState(&config.config_, &state, kSampleRate));
size_t num_samples_read;
TF_LITE_MICRO_EXPECT(WindowProcessSamples(
&state, kFakeAudioData,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read));
int i;
for (i = kStepSamples; i < kWindowSamples; ++i) {
TF_LITE_MICRO_EXPECT_EQ(state.input[i - kStepSamples], kFakeAudioData[i]);
}
WindowFreeStateContents(&state);
}
TF_LITE_MICRO_TEST(WindowState_CheckOutputValues)
{
WindowTestConfig config;
struct WindowState state;
TF_LITE_MICRO_EXPECT(
WindowPopulateState(&config.config_, &state, kSampleRate));
size_t num_samples_read;
TF_LITE_MICRO_EXPECT(WindowProcessSamples(
&state, kFakeAudioData,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read));
const int16_t expected[] = {
0, 1151, 0, -5944, 0, 13311, 0, -21448, 0, 28327, 0, -32256, 0, 32255,
0, -28328, 0, 21447, 0, -13312, 0, 5943, 0, -1152, 0
};
TF_LITE_MICRO_EXPECT_EQ(state.size, sizeof(expected) / sizeof(expected[0]));
int i;
for (i = 0; i < state.size; ++i) {
TF_LITE_MICRO_EXPECT_EQ(state.output[i], expected[i]);
}
WindowFreeStateContents(&state);
}
TF_LITE_MICRO_TEST(WindowState_CheckMaxAbsValue)
{
WindowTestConfig config;
struct WindowState state;
TF_LITE_MICRO_EXPECT(
WindowPopulateState(&config.config_, &state, kSampleRate));
size_t num_samples_read;
TF_LITE_MICRO_EXPECT(WindowProcessSamples(
&state, kFakeAudioData,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read));
TF_LITE_MICRO_EXPECT_EQ(state.max_abs_output_value, 32256);
WindowFreeStateContents(&state);
}
TF_LITE_MICRO_TEST(WindowState_CheckConsecutiveWindow)
{
WindowTestConfig config;
struct WindowState state;
TF_LITE_MICRO_EXPECT(
WindowPopulateState(&config.config_, &state, kSampleRate));
size_t num_samples_read;
TF_LITE_MICRO_EXPECT(WindowProcessSamples(
&state, kFakeAudioData,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read));
TF_LITE_MICRO_EXPECT(WindowProcessSamples(
&state, kFakeAudioData + kWindowSamples,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) - kWindowSamples,
&num_samples_read));
const int16_t expected[] = {
0, -1152, 0, 5943, 0, -13312, 0, 21447, 0, -28328, 0, 32255, 0, -32256,
0, 28327, 0, -21448, 0, 13311, 0, -5944, 0, 1151, 0
};
TF_LITE_MICRO_EXPECT_EQ(state.size, sizeof(expected) / sizeof(expected[0]));
int i;
for (i = 0; i < state.size; ++i) {
TF_LITE_MICRO_EXPECT_EQ(state.output[i], expected[i]);
}
WindowFreeStateContents(&state);
}
TF_LITE_MICRO_TEST(WindowState_CheckNotEnoughSamples)
{
WindowTestConfig config;
struct WindowState state;
TF_LITE_MICRO_EXPECT(
WindowPopulateState(&config.config_, &state, kSampleRate));
size_t num_samples_read;
TF_LITE_MICRO_EXPECT(WindowProcessSamples(
&state, kFakeAudioData,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read));
TF_LITE_MICRO_EXPECT(WindowProcessSamples(
&state, kFakeAudioData + kWindowSamples,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) - kWindowSamples,
&num_samples_read));
TF_LITE_MICRO_EXPECT_EQ(
false, WindowProcessSamples(
&state, kFakeAudioData + kWindowSamples + kStepSamples,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) -
kWindowSamples - kStepSamples,
&num_samples_read));
TF_LITE_MICRO_EXPECT_EQ(
state.input_used,
sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) - 2 * kStepSamples);
WindowFreeStateContents(&state);
}
TF_LITE_MICRO_TESTS_END
| 33.255319 | 82 | 0.679463 | HuakeZhBo |
1673532033720107537b9e6c1e585a7bf75f89e5 | 2,046 | cpp | C++ | chp4_exercises.cpp | toddbrentlinger/Beginning-Cpp-Through-Game-Programming-Third-Edition | 16a53f70869920cec7230f4d2f3e2a0d1dcd43f4 | [
"MIT"
] | 10 | 2018-03-22T19:30:55.000Z | 2021-12-09T14:02:07.000Z | chp4_exercises.cpp | spellberry/Beginning-Cpp-Through-Game-Programming-Third-Edition | 16a53f70869920cec7230f4d2f3e2a0d1dcd43f4 | [
"MIT"
] | null | null | null | chp4_exercises.cpp | spellberry/Beginning-Cpp-Through-Game-Programming-Third-Edition | 16a53f70869920cec7230f4d2f3e2a0d1dcd43f4 | [
"MIT"
] | 8 | 2018-03-22T19:34:31.000Z | 2021-12-09T14:02:13.000Z | // Chapter 4 Exercises
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
cout << "\tChapter43 Exercises\n\n";
// Question 1
vector<string> gameList;
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
cout << "Question 1\n";
cout << "Favorite Games List:\n\n";
cout << "Action Options:\n";
cout << "'List' - list all game titles\n";
cout << "'Add' - add a game title\n";
cout << "'Remove' - remove a game title\n";
cout << "'Quit' - quit the program\n";
string action;
string gameTitle;
// main loop
while (action != "QUIT")
{
cout << "\nAction: ";
cin >> action;
if (action == "LIST")
{
cout << "\nFavorite Game:\n";
for (iter = gameList.begin(); iter != gameList.end(); ++iter)
{
cout << *iter << endl;
}
}
else if (action == "ADD")
{
cout << "\nAdd Game: ";
cin >> gameTitle;
gameList.push_back(gameTitle);
cout << "\nFavorite Game:\n";
for (iter = gameList.begin(); iter < gameList.end(); ++iter)
{
cout << *iter << endl;
}
}
else if (action == "REMOVE")
{
cout << "\nRemove Game: ";
cin >> gameTitle;
myIterator = find(gameList.begin(), gameList.end(), gameTitle);
if (myIterator != gameList.end())
{
gameList.erase(myIterator);
cout << "\nFavorite Game:\n";
for (iter = gameList.begin(); iter < gameList.end(); ++iter)
{
cout << *iter << endl;
}
}
else
{
cout << "\nGame title not found. Try Again.";
}
}
}
// Question 2
cout << "Question 2\n\n";
vector<int> scores(5,0);
vector<int>::iterator myIter2;
vector<int>::const_iterator iter2;
// increment each score
for (myIter2 = scores.begin(); myIter2 != scores.end(); ++myIter2)
{
(*myIter2)++;
}
cout << "Scores:\n";
for (iter2 = scores.begin(); iter2 != scores.end(); ++iter2)
{
cout << *iter2 << endl;
}
return 0;
}
| 21.092784 | 68 | 0.554252 | toddbrentlinger |
1674e284ae9d25a4d3ef335a493869c732606527 | 602 | cpp | C++ | maki_core/src/renderer/vertex_array.cpp | christopher-besch/open_gl_test | 45323817461cbe69a9b99e50ffebbceb7fca823e | [
"MIT"
] | 24 | 2021-12-20T08:12:19.000Z | 2022-01-19T16:15:44.000Z | maki_core/src/renderer/vertex_array.cpp | christopher-besch/open_gl_test | 45323817461cbe69a9b99e50ffebbceb7fca823e | [
"MIT"
] | 23 | 2021-12-25T07:46:29.000Z | 2022-02-05T18:28:20.000Z | maki_core/src/renderer/vertex_array.cpp | christopher-besch/open_gl_test | 45323817461cbe69a9b99e50ffebbceb7fca823e | [
"MIT"
] | null | null | null | #include "pch.h"
#include "buffer.h"
#include "renderer/opengl/opengl_vertex_array.h"
#include "renderer/renderer.h"
namespace Maki {
VertexArray* VertexArray::create()
{
switch(Renderer::get_renderer_impl()) {
case Renderer::Implementation::none:
MAKI_RAISE_CRITICAL("Renderer::Implementation::none is not supported.");
return nullptr;
case Renderer::Implementation::opengl:
return new OpenGLVertexArray();
default:
MAKI_RAISE_CRITICAL("The requested renderer implementation is not supported.");
return nullptr;
}
}
} // namespace Maki
| 24.08 | 87 | 0.700997 | christopher-besch |
16789454c84225a65d9c0b85cb45774fd255768e | 653 | cpp | C++ | cpp/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | mvshmakov/junk | d67b31d918772018f78c3b1ff43d2bfd72bc57c9 | [
"WTFPL"
] | null | null | null | cpp/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | mvshmakov/junk | d67b31d918772018f78c3b1ff43d2bfd72bc57c9 | [
"WTFPL"
] | 1 | 2022-03-02T09:56:38.000Z | 2022-03-02T09:56:38.000Z | cpp/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | mvshmakov/junk | d67b31d918772018f78c3b1ff43d2bfd72bc57c9 | [
"WTFPL"
] | null | null | null | // Массивы.cpp: главный файл проекта.
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
float a[10];
float proiz = 1.0;
int i, n, k = 0;
cout << "Vvedite elementi massiva cherez enter:" << endl;
for (i = 0; i < 10; i++)
{
cin >> a[i];
}
for (i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << "\nVvedite chislo N:" << endl;
cin >> n;
for (i = 0; i < 10; i++)
{
if (a[i] > n) { k++; proiz *= a[i]; };
}
cout << "Proizvedenie elementov massiva = " << proiz << endl;
cout << "Kol-vo elementov bolshih chisla = " << k << endl;
getch();
return 0;
}
| 19.205882 | 63 | 0.503828 | mvshmakov |
1678d5bf6b8dfeca56cc5d8eeb5bc7befdd5564c | 6,038 | cpp | C++ | src/prod/src/data/tstore/StoreTransaction.Test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/data/tstore/StoreTransaction.Test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/data/tstore/StoreTransaction.Test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#include "TStoreTestBase.h"
#define ALLOC_TAG 'ssTP'
namespace TStoreTests
{
class StoreTransactionTest : public TStoreTestBase<LONG64, KBuffer::SPtr, LongComparer, TestStateSerializer<LONG64>, KBufferSerializer>
{
public:
StoreTransactionTest()
{
Setup(1);
Store->EnableSweep = false;
}
~StoreTransactionTest()
{
Cleanup();
}
KBuffer::SPtr CreateBuffer(__in LONG64 size, __in byte fillValue=0xb6)
{
CODING_ERROR_ASSERT(size >= 0);
KBuffer::SPtr bufferSPtr = nullptr;
NTSTATUS status = KBuffer::Create(static_cast<ULONG>(size), bufferSPtr, GetAllocator());
CODING_ERROR_ASSERT(NT_SUCCESS(status));
byte* buffer = static_cast<byte *>(bufferSPtr->GetBuffer());
memset(buffer, fillValue, static_cast<ULONG>(size));
return bufferSPtr;
}
ktl::Awaitable<void> AbortTxnInBackground(WriteTransaction<LONG64, KBuffer::SPtr> & txn)
{
co_await CorHelper::ThreadPoolThread(GetAllocator().GetKtlSystem().DefaultSystemThreadPool());
txn.StoreTransactionSPtr->Unlock();
}
ktl::Awaitable<void> VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition()
{
long key1 = 17;
long key2 = 18;
KBuffer::SPtr value = CreateBuffer(4);
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, key2, value, DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
auto txn1 = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn1->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None);
auto abortTask = AbortTxnInBackground(*txn1);
try
{
co_await Store->ConditionalUpdateAsync(*txn1->StoreTransactionSPtr, key2, value, DefaultTimeout, CancellationToken::None);
}
catch (ktl::Exception const & e)
{
CODING_ERROR_ASSERT(e.GetStatus() == SF_STATUS_TRANSACTION_ABORTED);
}
co_await abortTask;
// Dispose txn
txn1 = nullptr;
// If the abort of txn above does not do a proper cleanup, get on lock key2 will see a timeout exception
{
KeyValuePair<LONG64, KBuffer::SPtr> kvp;
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::ReadRepeatable;
co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, key1, DefaultTimeout, kvp, CancellationToken::None);
co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, key2, DefaultTimeout, kvp, CancellationToken::None);
co_await txn->CommitAsync();
}
}
ktl::Awaitable<void> VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition()
{
long key1 = 17;
long key2 = 18;
KBuffer::SPtr value = CreateBuffer(4);
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, key2, value, DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
auto txn1 = CreateWriteTransaction();
auto updateTask = Store->ConditionalUpdateAsync(*txn1->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None);
auto abortTask = AbortTxnInBackground(*txn1);
try
{
await updateTask;
}
catch (ktl::Exception const & e)
{
CODING_ERROR_ASSERT(e.GetStatus() == SF_STATUS_TRANSACTION_ABORTED);
}
await abortTask;
// Dispose txn
txn1 = nullptr;
// If the abort of txn above does not do a proper cleanup, prime lock will timeout
co_await Store->LockManagerSPtr->AcquirePrimeLockAsync(LockMode::Exclusive, Common::TimeSpan::FromSeconds(1));
Store->LockManagerSPtr->ReleasePrimeLock(LockMode::Exclusive);
}
#pragma region test functions
public:
ktl::Awaitable<void> VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test()
{
co_await VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition();
co_return;
}
ktl::Awaitable<void> VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test()
{
co_await VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition();
co_return;
}
#pragma endregion
};
BOOST_FIXTURE_TEST_SUITE(StoreTransactionTestSuite, StoreTransactionTest)
BOOST_AUTO_TEST_CASE(VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion)
{
SyncAwait(VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test());
}
BOOST_AUTO_TEST_CASE(VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion)
{
SyncAwait(VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test());
}
BOOST_AUTO_TEST_SUITE_END()
}
| 37.271605 | 143 | 0.621398 | gridgentoo |
16793ab16a9274150bf008ff2a693be584f17520 | 5,215 | hpp | C++ | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/transforms/DisplayTransformation.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 12 | 2020-06-25T13:10:17.000Z | 2022-01-27T01:48:26.000Z | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/transforms/DisplayTransformation.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 2 | 2021-05-23T05:02:48.000Z | 2021-05-24T11:15:56.000Z | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/transforms/DisplayTransformation.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 7 | 2020-08-27T08:23:49.000Z | 2021-09-19T12:54:30.000Z | /**
******************************************************************************
* This file is part of the TouchGFX 4.13.0 distribution.
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef DISPLAYTRANSFORMATION_HPP
#define DISPLAYTRANSFORMATION_HPP
#include <touchgfx/hal/Types.hpp>
namespace touchgfx
{
/**
* @class DisplayTransformation DisplayTransformation.hpp touchgfx/transforms/DisplayTransformation.hpp
*
* @brief Defines transformations from display space to frame buffer space.
*
* Defines transformations from display space to frame buffer space. The display might
* be (considered) in portrait mode from 0,0 to 272,480, while the actual frame buffer
* is from 0,0 to 480,272. This class handles the transformations.
*/
class DisplayTransformation
{
public:
/**
* @fn static void DisplayTransformation::transformDisplayToFrameBuffer(int16_t& x, int16_t& y);
*
* @brief Transform x,y from display to frame buffer coordinates.
*
* Transform x,y from display to frame buffer coordinates.
*
* @param [in,out] x the x part to translate.
* @param [in,out] y the y part to translate.
*/
static void transformDisplayToFrameBuffer(int16_t& x, int16_t& y);
/**
* @fn static void DisplayTransformation::transformDisplayToFrameBuffer(float& x, float& y);
*
* @brief Transform x,y from display to frame buffer coordinates.
*
* Transform x,y from display to frame buffer coordinates.
*
* @param [in,out] x the x part to translate.
* @param [in,out] y the y part to translate.
*/
static void transformDisplayToFrameBuffer(float& x, float& y);
/**
* @fn static void DisplayTransformation::transformFrameBufferToDisplay(int16_t& x, int16_t& y);
*
* @brief Transform x,y from frame buffer to display coordinates.
*
* Transform x,y from frame buffer to display coordinates.
*
* @param [in,out] x the x part to translate.
* @param [in,out] y the y part to translate.
*/
static void transformFrameBufferToDisplay(int16_t& x, int16_t& y);
/**
* @fn static void DisplayTransformation::transformDisplayToFrameBuffer(int16_t& x, int16_t& y, const Rect& in);
*
* @brief Transform x,y from coordinates relative to the in rect to frame buffer coordinates.
*
* Transform x,y from coordinates relative to the in rect to frame buffer
* coordinates.
*
* @param [in,out] x the x part to translate.
* @param [in,out] y the y part to translate.
* @param in the rectangle defining the coordinate space.
*/
static void transformDisplayToFrameBuffer(int16_t& x, int16_t& y, const Rect& in);
/**
* @fn static void DisplayTransformation::transformDisplayToFrameBuffer(float& x, float& y, const Rect& in);
*
* @brief Transform x,y from coordinates relative to the in rect to frame buffer coordinates.
*
* Transform x,y from coordinates relative to the in rect to frame buffer
* coordinates.
*
* @param [in,out] x the x part to translate.
* @param [in,out] y the y part to translate.
* @param in the rectangle defining the coordinate space.
*/
static void transformDisplayToFrameBuffer(float& x, float& y, const Rect& in);
/**
* @fn static void DisplayTransformation::transformDisplayToFrameBuffer(Rect& r);
*
* @brief Transform rectangle from display to frame buffer coordinates.
*
* Transform rectangle from display to frame buffer coordinates.
*
* @param [in,out] r the rectangle to translate.
*/
static void transformDisplayToFrameBuffer(Rect& r);
/**
* @fn static void DisplayTransformation::transformFrameBufferToDisplay(Rect& r);
*
* @brief Transform rectangle from frame buffer to display coordinates.
*
* Transform rectangle from frame buffer to display coordinates.
*
* @param [in,out] r the rectangle to translate.
*/
static void transformFrameBufferToDisplay(Rect& r);
/**
* @fn static void DisplayTransformation::transformDisplayToFrameBuffer(Rect& r, const Rect& in);
*
* @brief Transform rectangle r from coordinates relative to the in rect to frame buffer
* coordinates.
*
* Transform rectangle r from coordinates relative to the in rect to frame buffer
* coordinates.
*
* @param [in,out] r the rectangle to translate.
* @param in the rectangle defining the coordinate space.
*/
static void transformDisplayToFrameBuffer(Rect& r, const Rect& in);
};
} // namespace touchgfx
#endif // DISPLAYTRANSFORMATION_HPP
| 37.789855 | 116 | 0.643337 | koson |
167c048ba3a7c1d7f245d8f97f304003c2dbad88 | 3,919 | hpp | C++ | include/zipper_iterator.hpp | aurelien-boch/cpp-ecs | cc3ac80a18909dfcc476d7cfe1f3c7cd67b19e57 | [
"MIT"
] | 5 | 2021-11-22T18:49:49.000Z | 2022-01-14T14:49:09.000Z | include/zipper_iterator.hpp | aurelien-boch/cpp-ecs | cc3ac80a18909dfcc476d7cfe1f3c7cd67b19e57 | [
"MIT"
] | null | null | null | include/zipper_iterator.hpp | aurelien-boch/cpp-ecs | cc3ac80a18909dfcc476d7cfe1f3c7cd67b19e57 | [
"MIT"
] | 1 | 2021-12-05T15:33:05.000Z | 2021-12-05T15:33:05.000Z | #ifndef ZIPPER_ITERATOR_HPP
#define ZIPPER_ITERATOR_HPP
#include <tuple>
#include <optional>
namespace ecs::containers
{
template<class ...T>
class zipper;
}
namespace ecs::iterators
{
/**
* @brief This class defines an iterator instantiated by the zipper class. it's intended to be used in a range based
* loop or a simple for.
* @tparam Containers This variadic template refers to the types to bind the iterator.
*/
template<class ...Containers>
class zipper_iterator
{
template<class Container>
using iterator_t = typename Container::iterator;
template<class Container>
using it_reference_t = decltype(std::declval<typename iterator_t<Container>::reference>().value());
public:
using value_type = std::tuple<it_reference_t<Containers>...>;
using reference = value_type &;
using pointer = void;
using difference_type = std::size_t;
using iterator_category = std::input_iterator_tag;
using iterator_tuple = std::tuple<iterator_t<Containers>...>;
friend ecs::containers::zipper<Containers ...>;
zipper_iterator(zipper_iterator const &z) noexcept :
_max(z._max),
_idx(z._idx),
_current(z._current)
{}
const zipper_iterator &operator++() //TODO fix this magic
{
if (_max == 0)
return (*this);
if (_idx == _max - 1) {
_incrAll(_seq);
_idx++;
}
else if (_idx < _max - 1)
do {
_incrAll(_seq);
_idx += 1;
} while (!_allSet(_seq) && _idx < _max - 1);
if (_idx == _max - 1 && !_allSet(_seq)) {
_incrAll(_seq);
_idx++;
}
return (*this);
}
zipper_iterator operator++(int)
{
zipper_iterator<Containers...> old = *this;
operator++();
return (old);
}
value_type operator*()
{
return (_toValue(_seq));
}
value_type operator->()
{
return (_toValue(_seq));
}
friend inline bool operator==(zipper_iterator const &lhs, zipper_iterator const &rhs)
{
return ((lhs._max - lhs._idx) == (rhs._max - rhs._idx));
}
friend inline bool operator!=(zipper_iterator const &lhs, zipper_iterator const &rhs)
{
return ((lhs._max - lhs._idx) != (rhs._max - rhs._idx));
}
private:
iterator_tuple _current;
std::size_t _max;
std::size_t _idx{};
static constexpr std::index_sequence_for<Containers ...> _seq{};
template<size_t ... Is>
void _incrAll(std::index_sequence<Is ...>)
{
((++std::get<Is>(_current)), ...);
}
template<size_t ... Is>
[[nodiscard]] bool _allSet(std::index_sequence<Is ...>)
{
return (((*std::get<Is>(_current)) != std::nullopt) && ...);
}
template<size_t ... Is>
[[nodiscard]] value_type _toValue(std::index_sequence<Is ...>)
{
return std::tie(std::get<Is>(_current)->value()...);
}
zipper_iterator(iterator_tuple const &it_tuple, std::size_t max) :
_current(it_tuple),
_max(max)
{
if (_max > 0 && !_allSet(_seq))
this->operator++();
}
};
}
#endif //ZIPPER_ITERATOR_HPP
| 29.916031 | 120 | 0.48048 | aurelien-boch |
16804ff4a1bbaea54549335eb42abc5fef457057 | 1,989 | cpp | C++ | src/simulate_bayer_mosaic.cpp | ericpko/computer-graphics-raster-images | 384e1961c84a36ce8822d3ddb9ac7670143da14d | [
"MIT"
] | null | null | null | src/simulate_bayer_mosaic.cpp | ericpko/computer-graphics-raster-images | 384e1961c84a36ce8822d3ddb9ac7670143da14d | [
"MIT"
] | null | null | null | src/simulate_bayer_mosaic.cpp | ericpko/computer-graphics-raster-images | 384e1961c84a36ce8822d3ddb9ac7670143da14d | [
"MIT"
] | null | null | null | #include "simulate_bayer_mosaic.h"
void simulate_bayer_mosaic(
const std::vector<unsigned char> & rgb,
const int & width,
const int & height,
std::vector<unsigned char> & bayer)
{
bayer.resize(width*height);
////////////////////////////////////////////////////////////////////////////
// Add your code here
if (width == 0 || height == 0) {
throw("Image must have proper dimentions");
}
/**
* Idea: Start in the upper left corner (green) and since it is an alternating
* square pattern, we can use even/odd indices to determine the color
*/
int green_blue, red_green;
int pxl_idx = 0;
for (int row = 0; row < height; row++) {
if (row % 2 == 0) {
// Then we are on an even row, so we alternate g, b, g, b, ...
green_blue = 0;
for (int col = 0; col < width; col++) {
if (green_blue++ % 2 == 0) {
// Then we are on a green square
bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 1];
} else {
// Then we are on a blue square
bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 2];
}
}
} else {
// Then we are on an odd row, so we alternate r, g, r, g, ...
red_green = 0;
for (int col = 0; col < width; col++) {
if (red_green++ % 2 == 0) {
// Then we are on a red square
bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 0];
} else {
// Then we are on a green square
bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 1];
}
}
}
}
/**
* NOTE: When we are indexing a pixel here (i.e. green = rgb[(row * width + col) * 3 + 1];)
* (row * width + col) is the index of the pixel we want, then we multiply by
* 3 since we know we are indexing a 3-channel pixel, then we add 1 to get the
* green subpixel in this case. This is different than the way we indexed
* in rgb_to_gray.cpp
*/
////////////////////////////////////////////////////////////////////////////
}
| 34.293103 | 93 | 0.507793 | ericpko |
1683c2842b9b795900eeae61538c906b57befea5 | 8,556 | hh | C++ | subprojects/libostd/ostd/vecmath.hh | Croydon/libcubescript | a6d80a33f40f2c959c8ac881d8f8056d3460b1f3 | [
"Zlib"
] | 1 | 2022-02-02T19:24:35.000Z | 2022-02-02T19:24:35.000Z | subprojects/libostd/ostd/vecmath.hh | Croydon/libcubescript | a6d80a33f40f2c959c8ac881d8f8056d3460b1f3 | [
"Zlib"
] | null | null | null | subprojects/libostd/ostd/vecmath.hh | Croydon/libcubescript | a6d80a33f40f2c959c8ac881d8f8056d3460b1f3 | [
"Zlib"
] | 1 | 2022-02-02T22:39:12.000Z | 2022-02-02T22:39:12.000Z | /* Vector math for libostd.
*
* This file is part of libostd. See COPYING.md for futher information.
*/
#ifndef OSTD_VECMATH_HH
#define OSTD_VECMATH_HH
#include <cstddef>
namespace ostd {
template<typename T>
struct vec2 {
union {
struct { T x, y; };
T value[2];
};
vec2(): x(0), y(0) {}
vec2(vec2 const &v): x(v.x), y(v.y) {}
vec2(T v): x(v), y(v) {}
vec2(T x, T y): x(x), y(y) {}
T &operator[](std::size_t idx) { return value[idx]; }
T operator[](std::size_t idx) const { return value[idx]; }
vec2 &add(T v) {
x += v; y += v;
return *this;
}
vec2 &add(vec2 const &o) {
x += o.x; y += o.y;
return *this;
}
vec2 &sub(T v) {
x -= v; y -= v;
return *this;
}
vec2 &sub(vec2 const &o) {
x -= o.x; y -= o.y;
return *this;
}
vec2 &mul(T v) {
x *= v; y *= v;
return *this;
}
vec2 &mul(vec2 const &o) {
x *= o.x; y *= o.y;
return *this;
}
vec2 &div(T v) {
x /= v; y /= v;
return *this;
}
vec2 &div(vec2 const &o) {
x /= o.x; y /= o.y;
return *this;
}
vec2 &neg() {
x = -x; y = -y;
return *this;
}
bool is_zero() const {
return (x == 0) && (y == 0);
}
T dot(vec2<T> const &o) const {
return (x * o.x) + (y * o.y);
}
};
template<typename T>
inline bool operator==(vec2<T> const &a, vec2<T> const &b) {
return (a.x == b.x) && (a.y == b.y);
}
template<typename T>
inline bool operator!=(vec2<T> const &a, vec2<T> const &b) {
return (a.x != b.x) || (a.y != b.y);
}
template<typename T>
inline vec2<T> operator+(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).add(b);
}
template<typename T>
inline vec2<T> operator+(vec2<T> const &a, T b) {
return vec2<T>(a).add(b);
}
template<typename T>
inline vec2<T> operator-(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).sub(b);
}
template<typename T>
inline vec2<T> operator-(vec2<T> const &a, T b) {
return vec2<T>(a).sub(b);
}
template<typename T>
inline vec2<T> operator*(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).mul(b);
}
template<typename T>
inline vec2<T> operator*(vec2<T> const &a, T b) {
return vec2<T>(a).mul(b);
}
template<typename T>
inline vec2<T> operator/(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).div(b);
}
template<typename T>
inline vec2<T> operator/(vec2<T> const &a, T b) {
return vec2<T>(a).div(b);
}
template<typename T>
inline vec2<T> operator-(vec2<T> const &a) {
return vec2<T>(a).neg();
}
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec2b = vec2<unsigned char>;
using vec2i = vec2<int>;
template<typename T>
struct vec3 {
union {
struct { T x, y, z; };
struct { T r, g, b; };
T value[3];
};
vec3(): x(0), y(0), z(0) {}
vec3(vec3 const &v): x(v.x), y(v.y), z(v.z) {}
vec3(T v): x(v), y(v), z(v) {}
vec3(T x, T y, T z): x(x), y(y), z(z) {}
T &operator[](std::size_t idx) { return value[idx]; }
T operator[](std::size_t idx) const { return value[idx]; }
vec3 &add(T v) {
x += v; y += v; z += v;
return *this;
}
vec3 &add(vec3 const &o) {
x += o.x; y += o.y; z += o.z;
return *this;
}
vec3 &sub(T v) {
x -= v; y -= v; z -= v;
return *this;
}
vec3 &sub(vec3 const &o) {
x -= o.x; y -= o.y; z -= o.z;
return *this;
}
vec3 &mul(T v) {
x *= v; y *= v; z *= v;
return *this;
}
vec3 &mul(vec3 const &o) {
x *= o.x; y *= o.y; z *= o.z;
return *this;
}
vec3 &div(T v) {
x /= v; y /= v; z /= v;
return *this;
}
vec3 &div(vec3 const &o) {
x /= o.x; y /= o.y; z /= o.z;
return *this;
}
vec3 &neg() {
x = -x; y = -y; z = -z;
return *this;
}
bool is_zero() const {
return (x == 0) && (y == 0) && (z == 0);
}
T dot(vec3<T> const &o) const {
return (x * o.x) + (y * o.y) + (z * o.z);
}
};
template<typename T>
inline bool operator==(vec3<T> const &a, vec3<T> const &b) {
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z);
}
template<typename T>
inline bool operator!=(vec3<T> const &a, vec3<T> const &b) {
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z);
}
template<typename T>
inline vec3<T> operator+(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).add(b);
}
template<typename T>
inline vec3<T> operator+(vec3<T> const &a, T b) {
return vec3<T>(a).add(b);
}
template<typename T>
inline vec3<T> operator-(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).sub(b);
}
template<typename T>
inline vec3<T> operator-(vec3<T> const &a, T b) {
return vec3<T>(a).sub(b);
}
template<typename T>
inline vec3<T> operator*(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).mul(b);
}
template<typename T>
inline vec3<T> operator*(vec3<T> const &a, T b) {
return vec3<T>(a).mul(b);
}
template<typename T>
inline vec3<T> operator/(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).div(b);
}
template<typename T>
inline vec3<T> operator/(vec3<T> const &a, T b) {
return vec3<T>(a).div(b);
}
template<typename T>
inline vec3<T> operator-(vec3<T> const &a) {
return vec3<T>(a).neg();
}
using vec3f = vec3<float>;
using vec3d = vec3<double>;
using vec3b = vec3<unsigned char>;
using vec3i = vec3<int>;
template<typename T>
struct vec4 {
union {
struct { T x, y, z, w; };
struct { T r, g, b, a; };
T value[4];
};
vec4(): x(0), y(0), z(0), w(0) {}
vec4(vec4 const &v): x(v.x), y(v.y), z(v.z), w(v.w) {}
vec4(T v): x(v), y(v), z(v), w(v) {}
vec4(T x, T y, T z, T w): x(x), y(y), z(z), w(w) {}
T &operator[](std::size_t idx) { return value[idx]; }
T operator[](std::size_t idx) const { return value[idx]; }
vec4 &add(T v) {
x += v; y += v; z += v; w += v;
return *this;
}
vec4 &add(vec4 const &o) {
x += o.x; y += o.y; z += o.z; w += o.w;
return *this;
}
vec4 &sub(T v) {
x -= v; y -= v; z -= v; w -= v;
return *this;
}
vec4 &sub(vec4 const &o) {
x -= o.x; y -= o.y; z -= o.z; w -= o.w;
return *this;
}
vec4 &mul(T v) {
x *= v; y *= v; z *= v; w *= v;
return *this;
}
vec4 &mul(vec4 const &o) {
x *= o.x; y *= o.y; z *= o.z; w *= o.w;
return *this;
}
vec4 &div(T v) {
x /= v; y /= v; z /= v; w /= v;
return *this;
}
vec4 &div(vec4 const &o) {
x /= o.x; y /= o.y; z /= o.z; w /= o.w;
return *this;
}
vec4 &neg() {
x = -x; y = -y; z = -z; w = -w;
return *this;
}
bool is_zero() const {
return (x == 0) && (y == 0) && (z == 0) && (w == 0);
}
T dot(vec4<T> const &o) const {
return (x * o.x) + (y * o.y) + (z * o.z) + (w * o.w);
}
};
template<typename T>
inline bool operator==(vec4<T> const &a, vec4<T> const &b) {
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w);
}
template<typename T>
inline bool operator!=(vec4<T> const &a, vec4<T> const &b) {
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z) || (a.w != b.w);
}
template<typename T>
inline vec4<T> operator+(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).add(b);
}
template<typename T>
inline vec4<T> operator+(vec4<T> const &a, T b) {
return vec4<T>(a).add(b);
}
template<typename T>
inline vec4<T> operator-(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).sub(b);
}
template<typename T>
inline vec4<T> operator-(vec4<T> const &a, T b) {
return vec4<T>(a).sub(b);
}
template<typename T>
inline vec4<T> operator*(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).mul(b);
}
template<typename T>
inline vec4<T> operator*(vec4<T> const &a, T b) {
return vec4<T>(a).mul(b);
}
template<typename T>
inline vec4<T> operator/(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).div(b);
}
template<typename T>
inline vec4<T> operator/(vec4<T> const &a, T b) {
return vec4<T>(a).div(b);
}
template<typename T>
inline vec4<T> operator-(vec4<T> const &a) {
return vec4<T>(a).neg();
}
using vec4f = vec4<float>;
using vec4d = vec4<double>;
using vec4b = vec4<unsigned char>;
using vec4i = vec4<int>;
} /* namespace ostd */
#endif
| 21.770992 | 72 | 0.5 | Croydon |
1685e0a12d3375087aa27131a3d12d232e9e0e54 | 3,080 | hpp | C++ | include/gdrive/request.hpp | allenbo/libgdrive | a7838bcf55fbbc6cfb66209bb2db1fbe82758924 | [
"MIT"
] | 16 | 2015-05-04T01:05:12.000Z | 2022-03-13T05:25:34.000Z | include/gdrive/request.hpp | allenbo/libgdrive | a7838bcf55fbbc6cfb66209bb2db1fbe82758924 | [
"MIT"
] | 1 | 2019-07-28T19:28:49.000Z | 2021-05-14T14:08:57.000Z | include/gdrive/request.hpp | allenbo/libgdrive | a7838bcf55fbbc6cfb66209bb2db1fbe82758924 | [
"MIT"
] | 3 | 2019-12-06T17:48:44.000Z | 2021-12-07T02:07:29.000Z | #ifndef __GDRIVE_REQUEST_HPP__
#define __GDRIVE_REQUEST_HPP__
#include "gdrive/config.hpp"
#include "common/all.hpp"
#include <string>
#include <map>
#include <vector>
#include <curl/curl.h>
namespace GDRIVE {
enum RequestMethod {
RM_GET,
RM_POST,
RM_PUT,
RM_DELETE,
RM_PATCH
};
enum EncodeMethod {
EM_URL,
EM_JSON,
};
typedef std::map<std::string, std::string> RequestHeader;
typedef std::map<std::string, std::string> RequestQuery;
typedef size_t (*ReadFunction) (void*, size_t, size_t, void*);
class HttpResponse;
class HttpRequest;
class MemoryString {
public:
MemoryString(const char* str, int size)
:_str(str), _size(size), _pos(0) {}
static size_t read(void* ptr, size_t size, size_t nmemb, void* userp) {
MemoryString* self = (MemoryString*)userp;
if (self->_size - self->_pos == 0) return 0;
int length = self->_size - self->_pos > size * nmemb ? size * nmemb : self->_size - self->_pos;
memcpy(ptr, self->_str + self->_pos, length);
self->_pos += length;
return length;
}
private:
const char* _str;
int _size;
int _pos;
};
class HttpResponse {
CLASS_MAKE_LOGGER
public:
HttpResponse() { _header_map.clear(); }
static size_t curl_write_callback(void* content, size_t size, size_t nmemb, void* userp);
inline std::string content() const { return _content; };
inline std::string header() const { return _header; };
inline void clear() { _content = ""; _header = ""; _header_map.clear(); }
inline int status() const { return _status; }
inline void set_status(int status) { _status = status;}
std::string get_header(std::string field);
void _parse_header();
private:
std::string _content;
std::string _header;
int _status;
std::map<std::string, std::string> _header_map;
friend class HttpRequest;
};
class HttpRequest {
CLASS_MAKE_LOGGER
public:
HttpRequest(std::string uri, RequestMethod method);
HttpRequest(std::string uri, RequestMethod method, RequestHeader& header, std::string body);
void add_header(RequestHeader &header);
void add_header(std::string key, std::string value);
void add_query(RequestQuery& query);
void add_query(std::string key, std::string value);
inline void clear_header() { _header.clear();}
inline void clear_query() { _query.clear(); }
void clear();
void set_uri(std::string uri);
HttpResponse& request();
inline HttpResponse& response() { return _resp;}
~HttpRequest();
protected:
std::string _uri;
RequestMethod _method;
RequestHeader _header;
RequestQuery _query;
std::string _body;
HttpResponse _resp;
CURL *_handle;
ReadFunction _read_hook;
void* _read_context;
void _init_curl_handle();
curl_slist* _build_header();
};
}
#endif
| 28.785047 | 107 | 0.624026 | allenbo |
168bba7bb92894891013ab6d88d9da75e02f4bf7 | 2,579 | cpp | C++ | modelo/source/RelacionesFecha.cpp | miglesias91/visualizador-de-contextos | ec1be5533ccef1b5881ce67b8f0d0ab0280b8d3a | [
"Apache-2.0"
] | null | null | null | modelo/source/RelacionesFecha.cpp | miglesias91/visualizador-de-contextos | ec1be5533ccef1b5881ce67b8f0d0ab0280b8d3a | [
"Apache-2.0"
] | 18 | 2018-02-15T19:02:14.000Z | 2018-06-03T00:33:08.000Z | modelo/source/RelacionesFecha.cpp | miglesias91/visualizador-de-contextos | ec1be5533ccef1b5881ce67b8f0d0ab0280b8d3a | [
"Apache-2.0"
] | null | null | null | #include <modelo/include/RelacionesFecha.h>
using namespace visualizador::modelo::relaciones;
using namespace visualizador::modelo;
using namespace visualizador;
RelacionesFecha::RelacionesFecha(herramientas::utiles::ID* id_fecha) :
IRelaciones(id_fecha, aplicacion::ConfiguracionAplicacion::prefijoRelacionesFecha()),
IRelacionConPeriodos(new RelacionConGrupo())
{
}
RelacionesFecha::~RelacionesFecha()
{
}
// GETTERS
// getters de IAlmacenable
std::string RelacionesFecha::getValorAlmacenable()
{
this->armarJson();
return this->getJson()->jsonString();
}
// SETTERS
// METODOS
// metodos de IAlmacenable
void RelacionesFecha::parsearValorAlmacenable(std::string valor_almacenable)
{
herramientas::utiles::Json * json_almacenable = new herramientas::utiles::Json(valor_almacenable);
this->setJson(json_almacenable);
this->parsearJson();
}
std::string RelacionesFecha::prefijoGrupo()
{
return aplicacion::ConfiguracionAplicacion::prefijoRelacionesFecha();
}
unsigned long long int RelacionesFecha::hashcode()
{
return this->getRelacionConPeriodos()->hashcode();
}
// metodos de IContieneJson
bool RelacionesFecha::armarJson()
{
herramientas::utiles::Json * relaciones_fecha = new herramientas::utiles::Json();
relaciones_fecha->agregarAtributoArray("ids_periodos", this->getRelacionConPeriodos()->getIdsGrupoComoUint());
this->getJson()->reset();
this->getJson()->agregarAtributoJson("relaciones_fecha", relaciones_fecha);
delete relaciones_fecha;
return true;
}
bool RelacionesFecha::parsearJson()
{
herramientas::utiles::Json * json_relaciones_fecha = this->getJson()->getAtributoValorJson("relaciones_fecha");
std::vector<unsigned long long int> ids_periodos = json_relaciones_fecha->getAtributoArrayUint("ids_periodos");
for (std::vector<unsigned long long int>::iterator it = ids_periodos.begin(); it != ids_periodos.end(); it++)
{
this->getRelacionConPeriodos()->agregarRelacion(*it);
}
delete json_relaciones_fecha;
return true;
}
IRelaciones * RelacionesFecha::clonar()
{
RelacionesFecha * clon = new RelacionesFecha(this->getId()->copia());
std::vector<herramientas::utiles::ID*> ids_periodos = this->getRelacionConPeriodos()->getIdsGrupo();
for (std::vector<herramientas::utiles::ID*>::iterator it = ids_periodos.begin(); it != ids_periodos.end(); it++)
{
clon->agregarRelacionConPeriodo(*it);
}
return clon;
}
| 26.587629 | 117 | 0.704924 | miglesias91 |
168f32aa163f3cb0144239a0773b3b4f4907215e | 467 | hpp | C++ | include/tadsf/utils.hpp | KanHarI/TADSF | 62b68fd07fa98964125198173e589aa7322541c2 | [
"MIT"
] | 1 | 2019-07-15T06:03:13.000Z | 2019-07-15T06:03:13.000Z | include/tadsf/utils.hpp | KanHarI/CTAD | 62b68fd07fa98964125198173e589aa7322541c2 | [
"MIT"
] | null | null | null | include/tadsf/utils.hpp | KanHarI/CTAD | 62b68fd07fa98964125198173e589aa7322541c2 | [
"MIT"
] | null | null | null | #ifndef GCD_HPP
#define GCD_HPP
namespace TADSF {
constexpr int gcd(int a, int b) {
if (a > b) {
a ^= b ^= a ^= b; // constexpr alternative to std::swap(a, b)
}
while (b%a) {
b %= a;
a ^= b ^= a ^= b;
}
return a;
}
constexpr int ctpow(int base, int exp) {
int acc = 1;
while(exp) {
if (exp%2) {
acc *= base;
}
exp >>= 1;
base <<= 1;
}
return acc;
}
}
#endif
| 14.59375 | 69 | 0.43469 | KanHarI |
1690be2a77320ca8a7bafcc0096038155d72d2da | 285 | hpp | C++ | modules/ui/include/glpp/ui/elements.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | 16 | 2019-12-10T19:44:17.000Z | 2022-01-04T03:16:19.000Z | modules/ui/include/glpp/ui/elements.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | null | null | null | modules/ui/include/glpp/ui/elements.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | 3 | 2021-06-04T21:56:55.000Z | 2022-03-03T06:47:56.000Z | #pragma once
#include "element/box.hpp"
#include "element/button.hpp"
#include "element/flow.hpp"
#include "element/frame.hpp"
#include "element/image.hpp"
#include "element/label.hpp"
#include "element/mouse_action.hpp"
#include "element/multiplex.hpp"
#include "element/widget.hpp"
| 23.75 | 35 | 0.764912 | lenamueller |
16928a8584e121e7bda41f661b7c227f299e8d38 | 1,016 | hpp | C++ | include/metal/map/erase_key.hpp | dpacbach/metal | 9cbc6472aad3a2eb20c24709c3f142df87d9c5d0 | [
"MIT"
] | null | null | null | include/metal/map/erase_key.hpp | dpacbach/metal | 9cbc6472aad3a2eb20c24709c3f142df87d9c5d0 | [
"MIT"
] | null | null | null | include/metal/map/erase_key.hpp | dpacbach/metal | 9cbc6472aad3a2eb20c24709c3f142df87d9c5d0 | [
"MIT"
] | null | null | null | #ifndef METAL_MAP_ERASE_KEY_HPP
#define METAL_MAP_ERASE_KEY_HPP
#include "../config.hpp"
#include "../list/erase.hpp"
#include "../map/order.hpp"
namespace metal {
/// \ingroup map
///
/// ### Description
/// Removes the entry associated with some key in a \map.
///
/// ### Usage
/// For any \map `m` and \value `k`
/// \code
/// using result = metal::erase_key<m, k>;
/// \endcode
///
/// \returns: \map
/// \semantics:
/// If `m` associates keys `k_1, ..., k, ..., k_n` to values
/// `v_1, ..., v, ..., v_n`, then
/// \code
/// using result = metal::map<
/// metal::pair<k_1, v_1>, ..., metal::pair<k_n, v_n>
/// >;
/// \endcode
///
/// ### Example
/// \snippet map.cpp erase_key
///
/// ### See Also
/// \see map, has_key, at_key, insert_key
template<typename seq, typename key>
using erase_key = metal::erase<seq, metal::order<seq, key>>;
}
#endif
| 25.4 | 69 | 0.50689 | dpacbach |
16998b1dd0d4a9fbbd934eb113ef6755e7658bba | 35,300 | cpp | C++ | data-server/src/range/watch_funcs.cpp | gengdaomi/sharkstore | 1b490176846d2da98ceca07a69b6c35646567a28 | [
"Apache-2.0"
] | 1 | 2021-08-11T02:31:52.000Z | 2021-08-11T02:31:52.000Z | data-server/src/range/watch_funcs.cpp | gengdaomi/sharkstore | 1b490176846d2da98ceca07a69b6c35646567a28 | [
"Apache-2.0"
] | null | null | null | data-server/src/range/watch_funcs.cpp | gengdaomi/sharkstore | 1b490176846d2da98ceca07a69b6c35646567a28 | [
"Apache-2.0"
] | null | null | null | #include "range.h"
#include "server/range_server.h"
#include "watch.h"
#include "monitor/statistics.h"
namespace sharkstore {
namespace dataserver {
namespace range {
Status Range::GetAndResp( watch::WatcherPtr pWatcher, const watchpb::WatchCreateRequest& req, const std::string &dbKey, const bool &prefix,
int64_t &version, watchpb::DsWatchResponse *dsResp) {
version = 0;
Status ret;
if(prefix) {
//use iterator
std::string dbKeyEnd{""};
dbKeyEnd.assign(dbKey);
if (0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
FLOG_ERROR("GetAndResp:NextComparableBytes error.");
return Status(Status::kUnknown);
}
std::string hashKey("");
WatchUtil::GetHashKey(pWatcher, prefix, meta_.GetTableID(), &hashKey);
auto watcherServer = context_->WatchServer();
auto ws = watcherServer->GetWatcherSet_(hashKey);
auto result = ws->loadFromDb(store_.get(), watchpb::PUT, dbKey, dbKeyEnd, version, meta_.GetTableID(), dsResp);
if (result.first <= 0) {
delete dsResp;
dsResp = nullptr;
}
} else {
auto resp = dsResp->mutable_resp();
resp->set_watchid(pWatcher->GetWatcherId());
resp->set_code(static_cast<int>(ret.code()));
auto evt = resp->add_events();
std::string dbValue("");
ret = store_->Get(dbKey, &dbValue);
if (ret.ok()) {
evt->set_type(watchpb::PUT);
int64_t dbVersion(0);
std::string userValue("");
std::string ext("");
watch::Watcher::DecodeValue(&dbVersion, &userValue, &ext, dbValue);
auto userKv = new watchpb::WatchKeyValue;
for(auto userKey : req.kv().key()) {
userKv->add_key(userKey);
}
userKv->set_value(userValue);
userKv->set_version(dbVersion);
userKv->set_tableid(meta_.GetTableID());
version = dbVersion;
RANGE_LOG_INFO("GetAndResp ok, db_version: [%"
PRIu64
"]", dbVersion);
} else {
evt->set_type(watchpb::DELETE);
RANGE_LOG_INFO("GetAndResp code_: %s key:%s",
ret.ToString().c_str(), EncodeToHexString(dbKey).c_str());
}
}
return ret;
}
void Range::WatchGet(common::ProtoMessage *msg, watchpb::DsWatchRequest &req) {
errorpb::Error *err = nullptr;
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
auto ds_resp = new watchpb::DsWatchResponse;
auto header = ds_resp->mutable_header();
std::string dbKey{""};
std::string dbValue{""};
int64_t dbVersion{0};
auto prefix = req.req().prefix();
auto tmpKv = req.req().kv();
RANGE_LOG_DEBUG("WatchGet begin msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
do {
if (!VerifyLeader(err)) {
break;
}
if( Status::kOk != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchGet, meta_.Get(), tmpKv, dbKey, dbValue, err) ) {
break;
}
FLOG_DEBUG("range[%" PRIu64 " %s-%s] WatchGet key:%s", id_, EncodeToHexString(meta_.GetStartKey()).c_str(),
EncodeToHexString(meta_.GetEndKey()).c_str(), EncodeToHexString(dbKey).c_str());
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
break;
}
}
} while (false);
//int16_t watchFlag{0};
if (err != nullptr) {
RANGE_LOG_WARN("WatchGet error: %s", err->message().c_str());
common::SetResponseHeader(req.header(), header, err);
context_->SocketSession()->Send(msg, ds_resp);
return;
}
//add watch if client version is not equal to ds side
auto clientVersion = req.req().startversion();
//to do add watch
auto watch_server = context_->WatchServer();
std::vector<watch::WatcherKey*> keys;
for (auto i = 0; i < tmpKv.key_size(); i++) {
keys.push_back(new watch::WatcherKey(tmpKv.key(i)));
}
watch::WatchType watchType = watch::WATCH_KEY;
if(prefix) {
watchType = watch::WATCH_PREFIX;
}
//int64_t expireTime = (req.req().longpull() > 0)?getticks() + req.req().longpull():msg->expire_time;
int64_t expireTime = (req.req().longpull() > 0)?get_micro_second() + req.req().longpull()*1000:msg->expire_time*1000;
auto w_ptr = std::make_shared<watch::Watcher>(watchType, meta_.GetTableID(), keys, clientVersion, expireTime, msg);
watch::WatchCode wcode;
if(prefix) {
//to do load data from memory
//std::string dbKeyEnd("");
//dbKeyEnd.assign(dbKey);
// if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
// //to do set error message
// FLOG_ERROR("NextComparableBytes error.");
// return;
// }
auto hashKey = w_ptr->GetKeys();
std::string encode_key("");
w_ptr->EncodeKey(&encode_key, w_ptr->GetTableId(), w_ptr->GetKeys());
std::vector<watch::CEventBufferValue> vecUpdKeys;
auto retPair = eventBuffer->loadFromBuffer(encode_key, clientVersion, vecUpdKeys);
int32_t memCnt(retPair.first);
auto verScope = retPair.second;
RANGE_LOG_DEBUG("loadFromBuffer key:%s hit count[%" PRId32 "] version scope:%" PRId32 "---%" PRId32 " client_version:%" PRId64 ,
EncodeToHexString(encode_key).c_str(), memCnt, verScope.first, verScope.second, clientVersion);
if(memCnt > 0) {
auto resp = ds_resp->mutable_resp();
resp->set_code(Status::kOk);
resp->set_scope(watchpb::RESPONSE_PART);
for (auto j = 0; j < memCnt; j++) {
auto evt = resp->add_events();
for (decltype(vecUpdKeys[j].key().size()) k = 0; k < vecUpdKeys[j].key().size(); k++) {
evt->mutable_kv()->add_key(vecUpdKeys[j].key(k));
}
evt->mutable_kv()->set_value(vecUpdKeys[j].value());
evt->mutable_kv()->set_version(vecUpdKeys[j].version());
evt->set_type(vecUpdKeys[j].type());
}
w_ptr->Send(ds_resp);
return;
} else {
w_ptr->setBufferFlag(memCnt);
wcode = watch_server->AddPrefixWatcher(w_ptr, store_.get());
}
} else {
wcode = watch_server->AddKeyWatcher(w_ptr, store_.get());
}
if(watch::WATCH_OK == wcode) {
return;
} else if(watch::WATCH_WATCHER_NOT_NEED == wcode) {
auto btime = get_micro_second();
//to do get from db again
GetAndResp(w_ptr, req.req(), dbKey, prefix, dbVersion, ds_resp);
context_->Statistics()->PushTime(monitor::HistogramType::kQWait,
get_micro_second() - btime);
w_ptr->Send(ds_resp);
} else {
RANGE_LOG_ERROR("add watcher exception(%d).", static_cast<int>(wcode));
return;
}
return;
}
void Range::PureGet(common::ProtoMessage *msg, watchpb::DsKvWatchGetMultiRequest &req) {
errorpb::Error *err = nullptr;
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
auto ds_resp = new watchpb::DsKvWatchGetMultiResponse;
auto header = ds_resp->mutable_header();
//encode key and value
std::string dbKey{""};
std::string dbKeyEnd{""};
std::string dbValue("");
//int64_t version{0};
int64_t minVersion(0);
int64_t maxVersion(0);
auto prefix = req.prefix();
RANGE_LOG_DEBUG("PureGet beginmsgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
do {
if (!VerifyLeader(err)) {
break;
}
auto &key = req.kv().key();
if (key.empty()) {
RANGE_LOG_WARN("PureGet error: key empty");
err = KeyNotInRange("EmptyKey");
break;
}
//encode key
if( 0 != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchGet, meta_.Get(), req.kv(), dbKey, dbValue, err)) {
break;
}
RANGE_LOG_INFO("PureGet key before:%s after:%s", key[0].c_str(), EncodeToHexString(dbKey).c_str());
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
break;
}
}
auto resp = ds_resp;
auto btime = get_micro_second();
storage::Iterator *it = nullptr;
Status::Code code = Status::kOk;
if (prefix) {
dbKeyEnd.assign(dbKey);
if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
break;
}
RANGE_LOG_DEBUG("PureGet key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str());
//need to encode and decode
std::shared_ptr<storage::Iterator> iterator(store_->NewIterator(dbKey, dbKeyEnd));
uint32_t count{0};
for (int i = 0; iterator->Valid() ; ++i) {
count++;
auto kv = resp->add_kvs();
auto tmpDbKey = iterator.get()->key();
auto tmpDbValue = iterator.get()->value();
if(Status::kOk != WatchEncodeAndDecode::DecodeKv(funcpb::kFuncPureGet, meta_.GetTableID(), kv, tmpDbKey, tmpDbValue, err)) {
//break;
continue;
}
//to judge version after decoding value and spliting version from value
if (minVersion > kv->version()) {
minVersion = kv->version();
}
if(maxVersion < kv->version()) {
maxVersion = kv->version();
}
iterator->Next();
}
RANGE_LOG_DEBUG("PureGet ok:%d ", count);
code = Status::kOk;
} else {
auto ret = store_->Get(dbKey, &dbValue);
if(ret.ok()) {
//to do decode value version
RANGE_LOG_DEBUG("PureGet: dbKey:%s dbValue:%s ", EncodeToHexString(dbKey).c_str(),
EncodeToHexString(dbValue).c_str());
auto kv = resp->add_kvs();
/*
int64_t dbVersion(0);
std::string userValue("");
std::string extend("");
watch::Watcher::DecodeValue(&dbVersion, &userValue, &extend, dbValue);
*/
if (Status::kOk != WatchEncodeAndDecode::DecodeKv(funcpb::kFuncPureGet, meta_.GetTableID(), kv, dbKey, dbValue, err)) {
RANGE_LOG_WARN("DecodeKv fail. dbvalue:%s err:%s", EncodeToHexString(dbValue).c_str(),
err->message().c_str());
//break;
}
}
RANGE_LOG_DEBUG("PureGet code:%d msg:%s ", ret.code(), ret.ToString().data());
code = ret.code();
}
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, get_micro_second() - btime);
resp->set_code(static_cast<int32_t>(code));
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("PureGet error: %s", err->message().c_str());
}
common::SetResponseHeader(req.header(), header, err);
context_->SocketSession()->Send(msg, ds_resp);
}
void Range::WatchPut(common::ProtoMessage *msg, watchpb::DsKvWatchPutRequest &req) {
errorpb::Error *err = nullptr;
std::string dbKey{""};
//auto dbValue{std::make_shared<std::string>("")};
//auto extPtr{std::make_shared<std::string>("")};
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
RANGE_LOG_DEBUG("WatchPut begin msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
if (!CheckWriteable()) {
auto resp = new watchpb::DsKvWatchPutResponse;
resp->mutable_resp()->set_code(Status::kNoLeftSpace);
return SendError(msg, req.header(), resp, nullptr);
}
do {
if (!VerifyLeader(err)) {
break;
}
auto kv = req.mutable_req()->mutable_kv();
if (kv->key().empty()) {
RANGE_LOG_WARN("WatchPut error: key empty");
err = KeyNotInRange("-");
break;
}
RANGE_LOG_DEBUG("WatchPut key:%s value:%s", kv->key(0).c_str(), kv->value().c_str());
/*
//to do move to apply encode key
if( 0 != version_seq_->nextId(&version)) {
if (err == nullptr) {
err = new errorpb::Error;
}
err->set_message(version_seq_->getErrMsg());
break;
}
kv->set_version(version);
FLOG_DEBUG("range[%" PRIu64 "] WatchPut key-version[%" PRIu64 "]", meta_.id(), version);
if( Status::kOk != WatchCode::EncodeKv(funcpb::kFuncWatchPut, meta_, *kv, *dbKey, *dbValue, err) ) {
break;
}*/
std::vector<std::string*> vecUserKeys;
for ( auto i = 0 ; i < kv->key_size(); i++) {
vecUserKeys.emplace_back(kv->mutable_key(i));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), vecUserKeys);
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
} else {
err = StaleEpochError(epoch);
}
break;
}
/*
//increase key version
kv->set_version(version);
kv->clear_key();
kv->add_key(*dbKey);
kv->set_value(*dbValue);
*/
//raft propagate at first, propagate KV after encodding
if (!WatchPutSubmit(msg, req)) {
err = RaftFailError();
}
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("WatchPut error: %s", err->message().c_str());
auto resp = new watchpb::DsKvWatchPutResponse;
return SendError(msg, req.header(), resp, err);
}
}
void Range::WatchDel(common::ProtoMessage *msg, watchpb::DsKvWatchDeleteRequest &req) {
errorpb::Error *err = nullptr;
std::string dbKey{""};
//auto dbValue = std::make_shared<std::string>();
//auto extPtr = std::make_shared<std::string>();
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
RANGE_LOG_DEBUG("WatchDel begin, msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
if (!CheckWriteable()) {
auto resp = new watchpb::DsKvWatchDeleteResponse;
resp->mutable_resp()->set_code(Status::kNoLeftSpace);
return SendError(msg, req.header(), resp, nullptr);
}
do {
if (!VerifyLeader(err)) {
break;
}
auto kv = req.mutable_req()->mutable_kv();
if (kv->key_size() < 1) {
RANGE_LOG_WARN("WatchDel error due to key is empty");
err = KeyNotInRange("EmptyKey");
break;
}
/*
if(Status::kOk != WatchCode::EncodeKv(funcpb::kFuncWatchDel, meta_, *kv, *dbKey, *dbValue, err)) {
break;
}*/
/*std::vector<std::string*> vecUserKeys;
for(auto itKey : kv->key()) {
vecUserKeys.emplace_back(&itKey);
}*/
std::vector<std::string*> vecUserKeys;
for ( auto i = 0 ; i < kv->key_size(); i++) {
vecUserKeys.emplace_back(kv->mutable_key(i));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), vecUserKeys);
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
} else {
err = StaleEpochError(epoch);
}
break;
}
/*
//set encoding value to request
kv->clear_key();
kv->add_key(*dbKey);
kv->set_value(*dbValue);
*/
/*to do move to apply
//to do consume version and will reply to client
int64_t version{0};
if( 0 != version_seq_->nextId(&version)) {
if (err == nullptr) {
err = new errorpb::Error;
}
err->set_message(version_seq_->getErrMsg());
break;
}
kv->set_version(version);
*/
if (!WatchDeleteSubmit(msg, req)) {
err = RaftFailError();
}
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("WatchDel error: %s", err->message().c_str());
auto resp = new watchpb::DsKvWatchDeleteResponse;
return SendError(msg, req.header(), resp, err);
}
}
bool Range::WatchPutSubmit(common::ProtoMessage *msg, watchpb::DsKvWatchPutRequest &req) {
auto &kv = req.req().kv();
if (is_leader_ && kv.key_size() > 0 ) {
auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) {
cmd.set_cmd_type(raft_cmdpb::CmdType::KvWatchPut);
cmd.set_allocated_kv_watch_put_req(req.release_req());
});
return ret.ok() ? true : false;
}
return false;
}
bool Range::WatchDeleteSubmit(common::ProtoMessage *msg,
watchpb::DsKvWatchDeleteRequest &req) {
auto &kv = req.req().kv();
if (is_leader_ && kv.key_size() > 0 ) {
auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) {
cmd.set_cmd_type(raft_cmdpb::CmdType::KvWatchDel);
cmd.set_allocated_kv_watch_del_req(req.release_req());
});
return ret.ok() ? true : false;
}
return false;
}
Status Range::ApplyWatchPut(const raft_cmdpb::Command &cmd, uint64_t raftIdx) {
Status ret;
errorpb::Error *err = nullptr;
//RANGE_LOG_DEBUG("ApplyWatchPut begin");
auto &req = cmd.kv_watch_put_req();
auto btime = get_micro_second();
watchpb::WatchKeyValue notifyKv;
notifyKv.CopyFrom(req.kv());
static int64_t version{0};
version = raftIdx;
//for test
if (0) {
static std::atomic<int64_t> test_version = {0};
test_version += 1;
////////////////////////////////////////////////////////////
version = test_version;
apply_index_=version;
///////////////////////////////////////////////////////////
}
notifyKv.set_version(version);
RANGE_LOG_DEBUG("ApplyWatchPut new version[%" PRIu64 "]", version);
int64_t beginTime(getticks());
std::string dbKey{""};
std::string dbValue{""};
if( Status::kOk != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchPut, meta_.Get(), notifyKv, dbKey, dbValue, err) ) {
//to do
// SendError()
FLOG_WARN("EncodeKv failed, key:%s ", notifyKv.key(0).c_str());
;
}
notifyKv.clear_key();
notifyKv.add_key(dbKey);
notifyKv.set_value(dbValue);
RANGE_LOG_DEBUG("ApplyWatchPut dbkey:%s dbvalue:%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbValue).c_str());
do {
if (!KeyInRange(dbKey, err)) {
FLOG_WARN("Apply WatchPut failed, key:%s not in range.", dbKey.data());
ret = std::move(Status(Status::kInvalidArgument, "key not in range", ""));
break;
}
//save to db
auto btime = get_micro_second();
ret = store_->Put(dbKey, dbValue);
context_->Statistics()->PushTime(monitor::HistogramType::kQWait,
get_micro_second() - btime);
if (!ret.ok()) {
FLOG_ERROR("ApplyWatchPut failed, code:%d, msg:%s", ret.code(),
ret.ToString().data());
break;
}
/*if(req.kv().key_size() > 1) {
//to do decode group key,ignore single key
auto value = std::make_shared<watch::CEventBufferValue>(notifyKv, watchpb::PUT);
if(value->key_size()) {
FLOG_DEBUG(">>>key is valid.");
}
if (!eventBuffer->enQueue(dbKey, value.get())) {
FLOG_ERROR("load delete event kv to buffer error.");
}
}
*/
if (cmd.cmd_id().node_id() == node_id_) {
auto len = static_cast<uint64_t>(req.kv().ByteSizeLong());
CheckSplit(len);
}
} while (false);
if (cmd.cmd_id().node_id() == node_id_) {
auto resp = new watchpb::DsKvWatchPutResponse;
resp->mutable_resp()->set_code(ret.code());
ReplySubmit(cmd, resp, err, btime);
//notify watcher
std::string errMsg("");
int32_t retCnt = WatchNotify(watchpb::PUT, req.kv(), version, errMsg);
if (retCnt < 0) {
FLOG_ERROR("WatchNotify-put failed, ret:%d, msg:%s", retCnt, errMsg.c_str());
} else {
FLOG_DEBUG("WatchNotify-put success, count:%d, msg:%s", retCnt, errMsg.c_str());
}
} else if (err != nullptr) {
delete err;
return ret;
}
int64_t endTime(getticks());
FLOG_DEBUG("ApplyWatchPut key[%s], take time:%" PRId64 " ms", EncodeToHexString(dbKey).c_str(), endTime - beginTime);
return ret;
}
Status Range::ApplyWatchDel(const raft_cmdpb::Command &cmd, uint64_t raftIdx) {
Status ret;
errorpb::Error *err = nullptr;
// RANGE_LOG_DEBUG("ApplyWatchDel begin");
auto &req = cmd.kv_watch_del_req();
auto btime = get_micro_second();
watchpb::WatchKeyValue notifyKv;
notifyKv.CopyFrom(req.kv());
auto prefix = req.prefix();
uint64_t version{0};
//version = getNextVersion(err);
version = raftIdx;
//for test
if (0) {
static std::atomic<int64_t> test_version = {1};
test_version += 1;
////////////////////////////////////////////////////////////
version = test_version;
apply_index_=version;
///////////////////////////////////////////////////////////
}
notifyKv.set_version(version);
RANGE_LOG_DEBUG("ApplyWatchDel new-version[%" PRIu64 "]", version);
std::string dbKey{""};
std::string dbValue{""};
std::vector<std::string*> userKeys;
for(auto i = 0; i < req.kv().key_size(); i++) {
userKeys.push_back(std::move(new std::string(req.kv().key(i))));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), userKeys);
for(auto it:userKeys) {
delete it;
}
if(!req.kv().value().empty()) {
std::string extend("");
watch::Watcher::EncodeValue(&dbValue, version, &req.kv().value(), &extend);
}
std::vector<std::string> delKeys;
if (!KeyInRange(dbKey, err)) {
FLOG_WARN("ApplyWatchDel failed, key:%s not in range.", dbKey.data());
}
if (err != nullptr) {
delete err;
return ret;
}
if(prefix) {
std::string dbKeyEnd(dbKey);
if (0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
FLOG_ERROR("NextComparableBytes error, skip key:%s", EncodeToHexString(dbKey).c_str());
return Status(Status::kUnknown);
}
RANGE_LOG_DEBUG("ApplyWatchDel key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str());
std::shared_ptr<storage::Iterator> iterator(store_->NewIterator(dbKey, dbKeyEnd));
for (int i = 0; iterator->Valid(); ++i) {
delKeys.push_back(std::move(iterator->key()));
iterator->Next();
}
std::string first_key("");
std::string last_key("");
int64_t keySize = delKeys.size();
if (delKeys.size() > 0) {
first_key = delKeys[0];
last_key = delKeys[delKeys.size() - 1];
}
RANGE_LOG_DEBUG("BatchDelete afftected_keys:%" PRId64 " first_key:%s last_key:%s",
keySize, EncodeToHexString(first_key).c_str(), EncodeToHexString(last_key).c_str());
} else {
delKeys.push_back(dbKey);
}
// ret = store_->BatchDelete(delKeys);
// if (!ret.ok()) {
// FLOG_ERROR("BatchDelete failed, code:%d, msg:%s , key:%s", ret.code(),
// ret.ToString().c_str(), EncodeToHexString(dbKey).c_str());
// break;
// }
auto keySize(delKeys.size());
int64_t idx(0);
std::vector<std::string*> vecKeys;
for(auto it : delKeys) {
idx++;
FLOG_DEBUG("execute delte...[%" PRId64 "/%" PRIu64 "]", idx, keySize);
auto btime = get_micro_second();
ret = store_->Delete(it);
context_->Statistics()->PushTime(monitor::HistogramType::kQWait,
get_micro_second() - btime);
if (cmd.cmd_id().node_id() == node_id_ && delKeys[keySize-1] == it) {
//FLOG_DEBUG("Delete:%s del key:%s---last key:%s", ret.ToString().c_str(), EncodeToHexString(it).c_str(), EncodeToHexString(delKeys[keySize-1]).c_str());
auto resp = new watchpb::DsKvWatchDeleteResponse;
resp->mutable_resp()->set_code(ret.code());
ReplySubmit(cmd, resp, err, btime);
} else if (err != nullptr) {
delete err;
continue;
}
if (!ret.ok()) {
FLOG_ERROR("ApplyWatchDel failed, code:%d, msg:%s , key:%s", ret.code(),
ret.ToString().c_str(), EncodeToHexString(dbKey).c_str());
continue;
}
FLOG_DEBUG("store->Delete->ret.code:%s", ret.ToString().c_str());
if (cmd.cmd_id().node_id() == node_id_) {
notifyKv.clear_key();
vecKeys.clear();
watch::Watcher::DecodeKey(vecKeys, it);
for (auto key:vecKeys) {
notifyKv.add_key(*key);
}
for (auto key:vecKeys) {
delete key;
}
//notify watcher
int32_t retCnt(0);
std::string errMsg("");
retCnt = WatchNotify(watchpb::DELETE, notifyKv, version, errMsg, prefix);
if (retCnt < 0) {
FLOG_ERROR("WatchNotify-del failed, ret:%d, msg:%s", retCnt, errMsg.c_str());
} else {
FLOG_DEBUG("WatchNotify-del success, watch_count:%d, msg:%s", retCnt, errMsg.c_str());
}
}
}
if(prefix && cmd.cmd_id().node_id() == node_id_ && keySize == 0) {
auto resp = new watchpb::DsKvWatchDeleteResponse;
//Delete没有失败,统一返回ok
ret = Status(Status::kOk);
resp->mutable_resp()->set_code(ret.code());
ReplySubmit(cmd, resp, err, btime);
}
return ret;
}
int32_t Range::WatchNotify(const watchpb::EventType evtType, const watchpb::WatchKeyValue& kv, const int64_t &version, std::string &errMsg, bool prefix) {
if(kv.key_size() == 0) {
errMsg.assign("WatchNotify--key is empty.");
return -1;
}
std::vector<watch::WatcherPtr> vecNotifyWatcher;
std::vector<watch::WatcherPtr> vecPrefixNotifyWatcher;
//continue to get prefix key
std::vector<std::string *> decodeKeys;
std::string hashKey("");
std::string dbKey("");
bool hasPrefix(prefix);
if(!hasPrefix && kv.key_size() > 1) {
hasPrefix = true;
}
for(auto it : kv.key()) {
decodeKeys.emplace_back(std::move(new std::string(it)));
//only push the first key
break;
}
watch::Watcher::EncodeKey(&hashKey, meta_.GetTableID(), decodeKeys);
if(hasPrefix) {
int16_t tmpCnt{0};
for(auto it : kv.key()) {
++tmpCnt;
if(tmpCnt == 1) continue;
//to do skip the first element
decodeKeys.emplace_back(std::move(new std::string(it)));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), decodeKeys);
} else {
dbKey = hashKey;
}
for(auto it : decodeKeys) {
delete it;
}
FLOG_DEBUG("WatchNotify haskkey:%s key:%s version:%" PRId64, EncodeToHexString(hashKey).c_str(), EncodeToHexString(dbKey).c_str(), version);
if(hasPrefix) {
auto value = std::make_shared<watch::CEventBufferValue>(kv, evtType, version);
if (!eventBuffer->enQueue(hashKey, value.get())) {
FLOG_ERROR("load delete event kv to buffer error.");
}
}
auto dbValue = kv.value();
int64_t currDbVersion{version};
auto watch_server = context_->WatchServer();
watch_server->GetKeyWatchers(evtType, vecNotifyWatcher, hashKey, dbKey, currDbVersion);
//start to send user kv to client
int32_t watchCnt = vecNotifyWatcher.size();
FLOG_DEBUG("single key notify:%" PRId32 " key:%s", watchCnt, EncodeToHexString(dbKey).c_str());
for(auto i = 0; i < watchCnt; i++) {
auto dsResp = new watchpb::DsWatchResponse;
auto resp = dsResp->mutable_resp();
auto evt = resp->add_events();
evt->set_allocated_kv(new watchpb::WatchKeyValue(kv));
evt->mutable_kv()->set_version(currDbVersion);
evt->set_type(evtType);
SendNotify(vecNotifyWatcher[i], dsResp);
}
if(hasPrefix) {
//watch_server->GetPrefixWatchers(evtType, vecPrefixNotifyWatcher, hashKey, dbKey, currDbVersion);
watch_server->GetPrefixWatchers(evtType, vecPrefixNotifyWatcher, hashKey, hashKey, currDbVersion);
watchCnt = vecPrefixNotifyWatcher.size();
FLOG_DEBUG("prefix key notify:%" PRId32 " key:%s", watchCnt, EncodeToHexString(dbKey).c_str());
for( auto i = 0; i < watchCnt; i++) {
int64_t startVersion(vecPrefixNotifyWatcher[i]->getKeyVersion());
auto dsResp = new watchpb::DsWatchResponse;
std::vector<watch::CEventBufferValue> vecUpdKeys;
vecUpdKeys.clear();
auto retPair = eventBuffer->loadFromBuffer(hashKey, startVersion, vecUpdKeys);
int32_t memCnt(retPair.first);
auto verScope = retPair.second;
RANGE_LOG_DEBUG("loadFromBuffer key:%s hit count[%" PRId32 "] version scope:%" PRId32 "---%" PRId32 " client_version:%" PRId64 ,
EncodeToHexString(hashKey).c_str(), memCnt, verScope.first, verScope.second, startVersion);
if (0 == memCnt) {
FLOG_ERROR("doudbt no changing, notify %d/%"
PRId32
" key:%s", i+1, watchCnt, EncodeToHexString(dbKey).c_str());
delete dsResp;
dsResp = nullptr;
} else if (memCnt > 0) {
FLOG_DEBUG("notify %d/%"
PRId32
" loadFromBuffer key:%s hit count:%"
PRId32, i+1, watchCnt, EncodeToHexString(dbKey).c_str(), memCnt);
auto resp = dsResp->mutable_resp();
resp->set_code(Status::kOk);
resp->set_scope(watchpb::RESPONSE_PART);
for (auto j = 0; j < memCnt; j++) {
auto evt = resp->add_events();
for (decltype(vecUpdKeys[j].key().size()) k = 0; k < vecUpdKeys[j].key().size(); k++) {
evt->mutable_kv()->add_key(vecUpdKeys[j].key(k));
}
evt->mutable_kv()->set_value(vecUpdKeys[j].value());
evt->mutable_kv()->set_version(vecUpdKeys[j].version());
evt->set_type(vecUpdKeys[j].type());
}
} else {
//get all from db
FLOG_INFO("overlimit version in memory,get from db now. notify %d/%"
PRId32
" key:%s version:%"
PRId64,
i+1, watchCnt, EncodeToHexString(dbKey).c_str(), startVersion);
//use iterator
std::string dbKeyEnd{""};
dbKeyEnd.assign(dbKey);
if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
FLOG_ERROR("NextComparableBytes error.");
return -1;
}
//RANGE_LOG_DEBUG("WatchNotify key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str());
auto watcherServer = context_->WatchServer();
auto ws = watcherServer->GetWatcherSet_(hashKey);
auto result = ws->loadFromDb(store_.get(), evtType, dbKey, dbKeyEnd, startVersion, meta_.GetTableID(), dsResp);
if(result.first <= 0) {
delete dsResp;
dsResp = nullptr;
}
//scopeFlag = 1;
FLOG_DEBUG("notify %d/%" PRId32 " load from db, db-count:%" PRId32 " key:%s ", i+1, watchCnt, result.first, EncodeToHexString(dbKey).c_str());
}
if (hasPrefix && watchCnt > 0 && dsResp != nullptr) {
SendNotify(vecPrefixNotifyWatcher[i], dsResp, true);
}
}
}
return watchCnt;
}
int32_t Range::SendNotify( watch::WatcherPtr w, watchpb::DsWatchResponse *ds_resp, bool prefix)
{
auto watch_server = context_->WatchServer();
auto resp = ds_resp->mutable_resp();
auto w_id = w->GetWatcherId();
resp->set_watchid(w_id);
w->Send(ds_resp);
//delete watch
watch::WatchCode del_ret = watch::WATCH_OK;
if (!prefix && w->GetType() == watch::WATCH_KEY) {
del_ret = watch_server->DelKeyWatcher(w);
if (del_ret) {
RANGE_LOG_WARN(" DelKeyWatcher error, watch_id[%" PRId64 "]", w_id);
} else {
RANGE_LOG_WARN(" DelKeyWatcher execute end. watch_id:%" PRIu64, w_id);
}
}
if (prefix && w->GetType() == watch::WATCH_KEY) {
del_ret = watch_server->DelPrefixWatcher(w);
if (del_ret) {
RANGE_LOG_WARN(" DelPrefixWatcher error, watch_id[%" PRId64 "]", w_id);
} else {
RANGE_LOG_WARN(" DelPrefixWatcher execute end. watch_id:%" PRIu64, w_id);
}
}
return del_ret;
}
} // namespace range
} // namespace dataserver
} // namespace sharkstore
| 33.844679 | 165 | 0.552691 | gengdaomi |
1699a05aa718d3c678e9643c681309cc1b610ad2 | 11,993 | hpp | C++ | sycl-info/impl_matchers.hpp | codeplaysoftware/sycl-info | b47d498ee2d6b77ec21972de5882e8e12efecd6c | [
"BSL-1.0"
] | 9 | 2019-11-19T20:48:11.000Z | 2021-09-30T13:26:47.000Z | sycl-info/impl_matchers.hpp | codeplaysoftware/sycl-info | b47d498ee2d6b77ec21972de5882e8e12efecd6c | [
"BSL-1.0"
] | null | null | null | sycl-info/impl_matchers.hpp | codeplaysoftware/sycl-info | b47d498ee2d6b77ec21972de5882e8e12efecd6c | [
"BSL-1.0"
] | 2 | 2019-11-18T18:09:21.000Z | 2020-01-24T11:52:17.000Z | ////////////////////////////////////////////////////////////////////////////////
// impl-matchers.h
//
// Copyright (C) Codeplay Software Limited.
//
// 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 IMPL_MATCHERS_H
#define IMPL_MATCHERS_H
#include <CL/opencl.h>
#include <iostream>
#include <nlohmann/json.hpp>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
// This macro expands to the boilerplate of all the comparison operators
// The operator< must be defined first by the programmer. Any other
// operators are defined relatively to the operator<
#define SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS(type) \
friend inline bool operator>(const type& lhs, const type& rhs) { \
return rhs < lhs; \
} \
friend inline bool operator==(const type& lhs, const type& rhs) { \
return !(lhs < rhs) && !(rhs < lhs); \
} \
friend inline bool operator!=(const type& lhs, const type& rhs) { \
return !(lhs == rhs); \
} \
friend inline bool operator<=(const type& lhs, const type& rhs) { \
return !(rhs < lhs); \
} \
friend inline bool operator>=(const type& lhs, const type& rhs) { \
return !(lhs < rhs); \
}
namespace sycl_info {
struct using_target_matcher {
// The layout we want to model/print
//--------------------------------------
// Platform name: name
// Platform vendor: vendor
// device1:
// device_name: name
// device_vendor: vendor
// supported_drivers: 1.2, 1.3, etc
// device2:
// device_name: name
// device_vendor: vendor
// supported_drivers: 1.2, 1.3, etc
// ...
// ...
// deviceN:
// Platform Name: nameN
// ...
//--------------------------------------
/// @brief A device consists of a name, a vendor and
/// a vector of the supported drivers
///
struct device {
std::string name;
std::string vendor;
/// @brief This is necessarry as this struct will be stored in
/// an std::set. Marking this mutable is important, because
/// it allows us to modify this field without rebalancing
/// the tree. Essentially, this field is ignored in the
/// comparison function used by the data structure
///
mutable std::vector<std::string> drivers;
/// @brief The container of this is an std::set which requires
/// strict weak ordering
/// @see Strict weak ordering https://en.wikipedia.org/wiki/Weak_ordering
/// @see std::set container requirements
/// https://en.cppreference.com/w/cpp/container/set
///
friend inline bool operator<(const device& lhs, const device& rhs) {
return std::tie(lhs.name, lhs.vendor) < std::tie(rhs.name, rhs.vendor);
}
/// define the rest of the comparisson operators
SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS(device)
};
/// @brief A platform consists of a name, a vendor and
/// a set of supported devices. Name and vendor,
///
struct platform {
std::string name;
std::string vendor;
/// @brief This is necessarry as this struct will be stored in
/// an std::set. Marking this mutable is important, because
/// it allows us to modify this field without rebalancing
/// the tree. Essentially, this field is ignored in the
/// comparison function used by the data structure
///
mutable std::set<device> devices;
/// @brief The container of this is an std::set which requires
/// strict weak ordering
/// @see Strict weak ordering https://en.wikipedia.org/wiki/Weak_ordering
/// @see std::set container requirements
/// https://en.cppreference.com/w/cpp/container/set
///
friend inline bool operator<(const platform& lhs, const platform& rhs) {
return std::tie(lhs.name, lhs.vendor) < std::tie(rhs.name, rhs.vendor);
}
/// define the rest of the comparisson operators
SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS(platform);
};
/// The type that we print
using print_type = std::set<platform>;
/// @brief Helper function the converts a json file to the internal
/// representation print_type
/// @param syclinfo json
/// @return a print_type from the nlohmann::json
///
static print_type from_json(const nlohmann::json& syclImp);
/// @brief Finds the common platforms/devices between a sycl
/// implementation and the system's available platforms/devices
/// @param A syclinfo file, the current available hardware,
/// that is, the systems platforms and devices retrieved
/// with the target_selector
/// @return a print_type with the matched results
///
static print_type match(const nlohmann::json& syclImpJson,
const print_type& currentHardware);
};
/// @brief Helper function that converts a vector of platform ids and
/// and device ids into their respective string names
///
using_target_matcher::print_type to_print_type(
const std::vector<std::pair<cl_platform_id, cl_device_id>>& devices);
/// @brief Pretty print function for the --using command line option
/// @param A result of type print_type retrieved by the match()
/// function and an ostream to print to
///
void dump_picked_impl(const using_target_matcher::print_type& devices,
std::ostream& out) noexcept;
/// @brief Retrieves the implementation index for a given input string
/// @param The user input string and the available implementations
/// @return A pair of bool and int, representing whether an implementation was
/// found, and if so the index of that implemetnation
///
std::pair<bool, int> retrieve_index_for_impl(
const std::string& chosenImpl,
const std::vector<nlohmann::json>& impls) noexcept;
/// @brief Matches the --impl index with the available implementations
/// @param The --impl index, a vector of the syclinfo implementations
/// to match
///
using_target_matcher::print_type match_picked_impl(
const unsigned int index, const std::vector<nlohmann::json>& impls,
const bool displayAll);
/// @brief Picks a sycl-info implementation and displays it
/// @param The --using-target index, a vector of the syclinfo
/// implementations and an ostream to print to
///
void print_picked_impl(const unsigned int index,
const std::vector<nlohmann::json>& impls,
const bool displayAll, std::ostream& out);
/// @brief Structure for platform/device pair to represent the --config option
///
struct config {
std::string platform;
std::string device;
};
/// @brief Gets the config from an implementation and an index
/// @return The config specified by the index
///
config get_config(const unsigned int index,
const std::vector<nlohmann::json>& impls,
const std::pair<int, int> configIndex, const bool displayAll);
/// @brief prints the config
///
void print_config(const unsigned int index,
const std::vector<nlohmann::json>& impls,
const std::pair<int, int> configIndex,
const std::string& target, const bool displayAll,
std::ostream& out);
/// @brief Checks if the user specified option config_ is a valid index
/// @return True if config_ is a valid index, false otherwise
bool is_config_index_valid(const using_target_matcher::print_type& impls,
const std::pair<int, int> configIndex) noexcept;
/// @brief Structure for platform/device pair to represent the backend
/// information of a specified --impl
struct backend_info {
std::string backend;
std::string deviceFlags;
};
/// @brief Returns the backend specified by the option --target
/// @param An iterator to the syclinfo file and the value of --target option
///
backend_info get_backend_from_target(
nlohmann::json::const_iterator foundElement, const std::string& target);
/// @brief Returns the default backend for a target (first in the list by
/// default)
/// @param An iterator to the syclinfo file
///
backend_info get_default_backend(
const nlohmann::json::const_iterator foundElement);
/// @brief Helper function that matches an implementation file with the
/// --config. Optinally, it filters by --target.
/// @return The backend specified by config filtered by the optional target
///
backend_info match_config_with_impls(const config& conf,
const nlohmann::json& impl,
const std::string& target);
/// @brief Dumps the backend information specified by --config to a stream
//
void dump_config(const backend_info& info, std::ostream& out) noexcept;
/// @brief Enum that represents the name of a field in the json file.
///
enum class selections {
supported_configurations,
plat_name,
plat_vendor,
dev_name,
dev_flags,
dev_vendor,
supported_backend_targets,
backend,
supported_drivers
};
/// @brief Generic template that will be fully specialized for each value in
/// in the enum selections. The unspecialized base template is left undefined.
/// All in all, a field in the enum selections maps to a string value
/// representing the name of the respective field in the json file.
///
template <selections T>
struct select;
/// @brief Specialization for selections::supported_configurations
///
template <>
struct select<selections::supported_configurations> {
static constexpr const char* value = "supported_configurations";
};
/// @brief Specialization for selections::plat_name
///
template <>
struct select<selections::plat_name> {
static constexpr const char* value = "platform_name";
};
/// @brief Specialization for selections::plat_vendor
///
template <>
struct select<selections::plat_vendor> {
static constexpr const char* value = "platform_vendor";
};
/// @brief Specialization for selections::device_name
///
template <>
struct select<selections::dev_name> {
static constexpr const char* value = "device_name";
};
/// @brief Specialization for selections::device_flags
///
template <>
struct select<selections::dev_flags> {
static constexpr const char* value = "device_flags";
};
/// @brief Specialization for selections::device_vendor
///
template <>
struct select<selections::dev_vendor> {
static constexpr const char* value = "device_vendor";
};
/// @brief Specialization for selections::supported_backend_targets
///
template <>
struct select<selections::supported_backend_targets> {
static constexpr const char* value = "supported_backend_targets";
};
/// @brief Specialization for selections::backend_target
///
template <>
struct select<selections::backend> {
static constexpr const char* value = "backend_target";
};
/// @brief Specialization for selections::supported_drivers
///
template <>
struct select<selections::supported_drivers> {
static constexpr const char* value = "supported_drivers";
};
} // namespace sycl_info
#undef SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS
#endif
| 36.015015 | 80 | 0.658384 | codeplaysoftware |
169b99a6b5b80ca3f8b9d46b90c72b352720699a | 5,747 | cpp | C++ | src/trafficsim/Map.cpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | 12 | 2019-12-28T21:45:23.000Z | 2022-03-28T12:40:44.000Z | src/trafficsim/Map.cpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | null | null | null | src/trafficsim/Map.cpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | 1 | 2021-05-31T10:22:41.000Z | 2021-05-31T10:22:41.000Z | #include "Map.hpp"
#include <fstream>
#include <cfloat> // FLT_MAX
#include <iostream> // FLT_MAX
#include <memory>
#include "Rando.hpp"
#include "RoadTile.hpp"
namespace ts
{
Map::Map()
: grid_(120)
{
}
void Map::clearMap()
{
cars_.clear();
light_networks_.clear();
building_handlers_.clear();
current_network_id_ = 0;
current_building_id_ = 0;
grid_.init();
}
void Map::initDay()
{
for(unsigned int i = 0; i < grid_.getTotalTileCount(); ++i)
{
if(grid_.getTile(i)->getCategory() == TileCategory::RoadCategory)
{
grid_.getTile(i)->getNode()->resetCounter();
}
}
for (auto it = building_handlers_.begin(); it != building_handlers_.end(); ++it)
{
it->second->initDay();
}
}
void Map::update(const sf::Time &game_time, float delta_time)
{
// Move cars, and other things which are dependent on time
//cars, humans, trafficlights
if (!simulating_)
return;
for (auto ita = building_handlers_.begin(); ita != building_handlers_.end(); ++ita)
{
if (ita->second->update(game_time))
{
Rando r(building_handlers_.size());
int index = r.uniroll() - 1;
int i = 0;
const Tile *dest_tile;
for (auto itb = building_handlers_.begin(); itb != building_handlers_.end(); ++itb)
{
if (index == i)
{
dest_tile = itb->second->getClosestRoad();
break;
}
i++;
}
auto spawn_tile = ita->second->getClosestRoad();
if(dest_tile && spawn_tile)
addCar(spawn_tile, dest_tile);
}
}
for (auto &car : cars_)
car->update(game_time, delta_time, cars_, light_networks_);
removeFinishedCars();
for (auto ita = light_networks_.begin(); ita != light_networks_.end(); ++ita)
ita->second->update(delta_time);
}
void Map::addCar(const Tile *spawn_pos, const Tile *dest)
{
cars_.push_back(std::make_unique<Car>(Car(spawn_pos->getNode(), dest->getNode(), sf::Vector2f(50, 100))));
}
unsigned int Map::addBuilding(BuildingTile *building)
{
auto closest_road_node = closestRoadNode(building->getCenter());
if (closest_road_node)
building_handlers_.insert({current_building_id_, std::make_unique<BuildingHandler>(building, grid_.getTile(closest_road_node->getPos()), current_building_id_)});
else
building_handlers_.insert({current_building_id_, std::make_unique<BuildingHandler>(building, nullptr, current_building_id_)});
current_building_id_++;
return current_building_id_ - 1;
}
void Map::updateClosestRoads()
{
for (auto it = building_handlers_.begin(); it != building_handlers_.end(); ++it)
{
auto closest_road_node = closestRoadNode(it->second->getBuildingTile()->getCenter());
if(closest_road_node)
it->second->setClosestRoad(grid_.getTile(closest_road_node->getPos()));
}
}
void Map::addLight(TrafficLight *light, unsigned int handler_id)
{
if (light_networks_.find(handler_id) == light_networks_.end())
{
if (handler_id < UINT_MAX)
{
light_networks_.insert({handler_id, std::make_unique<TrafficLightNetwork>(handler_id)});
}
else
light_networks_.insert({0, std::make_unique<TrafficLightNetwork>(0)});
}
if (light_networks_.find(handler_id) != light_networks_.end())
light_networks_.at(handler_id)->addLight(light);
else
light_networks_.at(current_network_id_)->addLight(light);
}
void Map::newLightNetwork(TrafficLight *light)
{
current_network_id_++;
light_networks_.insert({current_network_id_, std::make_unique<TrafficLightNetwork>(current_network_id_)});
if (light)
{
light_networks_.at(light->getHandlerId())->removeLight(light, light->getPos());
light->setHandlerId(current_network_id_);
light_networks_.at(current_network_id_)->addLight(light);
}
}
void Map::removeBuilding(unsigned int id)
{
building_handlers_.erase(id);
}
void Map::removeLight(TrafficLight *light)
{
light_networks_.at(light->getHandlerId())->removeLight(light, light->getPos());
}
void Map::removeFinishedCars()
{
cars_.erase(std::remove_if(cars_.begin(), cars_.end(), [](const auto &car) -> bool { return car->isFinished(); }), cars_.end());
}
std::shared_ptr<Node> Map::closestRoadNode(const sf::Vector2f &pos)
{
std::shared_ptr<Node> closest = nullptr;
float closest_distance = FLT_MAX;
for (unsigned int i = 0; i < grid_.getTotalTileCount(); ++i)
{
if (grid_.getTile(i)->getCategory() == TileCategory::RoadCategory)
{
auto road_tile = static_cast<RoadTile *>(grid_.getTile(i));
if (road_tile->getType() == RoadType::StraightRoadType)
{
float dist = VectorMath::Distance(pos, grid_.getTile(i)->getCenter());
if (closest_distance > dist)
{
closest_distance = dist;
closest = grid_.getTile(i)->getNode();
}
}
}
}
return closest;
}
void Map::setSimulating(bool val)
{
if (simulating_ == val)
return;
simulating_ = val;
cars_.clear();
}
void Map::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(grid_, states);
if (simulating_)
{
for (const auto &car : cars_)
target.draw(*car, states);
}
else
{
for (auto ita = light_networks_.begin(); ita != light_networks_.end(); ++ita)
target.draw(*ita->second, states);
}
}
} // namespace ts | 28.735 | 169 | 0.616844 | lutrarutra |
169dbf68a9d6144dc779b92ed295d8bfb87b4b92 | 12,371 | cpp | C++ | NativeCode/Plugin_Multiband.cpp | PStewart95/Unity | f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331 | [
"MIT"
] | null | null | null | NativeCode/Plugin_Multiband.cpp | PStewart95/Unity | f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331 | [
"MIT"
] | null | null | null | NativeCode/Plugin_Multiband.cpp | PStewart95/Unity | f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331 | [
"MIT"
] | null | null | null | #include "AudioPluginUtil.h"
namespace Multiband
{
enum Param
{
P_MasterGain,
P_LowFreq, P_HighFreq,
P_LowGain, P_MidGain, P_HighGain,
P_LowAttack, P_MidAttack, P_HighAttack,
P_LowRelease, P_MidRelease, P_HighRelease,
P_LowThreshold, P_MidThreshold, P_HighThreshold,
P_LowRatio, P_MidRatio, P_HighRatio,
P_LowKnee, P_MidKnee, P_HighKnee,
P_FilterOrder,
P_UseLogScale,
P_ShowSpectrum,
P_SpectrumDecay,
P_NUM
};
struct CompressorChannel
{
float env;
float atk;
float rel;
float thr;
float ratio;
float knee;
float reduction;
float exp1;
float exp2;
float GetTimeConstant(float accuracy, float numSamples)
{
/*
Derivation of time constant from transition length specified as numSamples and desired accuracy within which target is reached:
y(n) = y(n-1) + [x(n) - y(n-1)] * alpha
y(0) = 1, x(n) = 0 =>
y(1) = 1 + [0 - 1] * alpha = 1-alpha
y(2) = 1-alpha + [0 - (1-alpha)] * alpha = (1-alpha)*(1-alpha) = (1-alpha)^2
y(3) = (1-alpha)^2 + [0 - (1-alpha)^2] * alpha = (1-alpha) * (1-alpha)^2 = (1-alpha)^3
...
y(n) = (1-alpha)^n = 1-accuracy =>
1-alpha = (1-accuracy)^(1/n)
alpha = 1 - (1-accuracy)^(1/n)
*/
if (numSamples <= 0.0f)
return 1.0f;
return 1.0f - powf(1.0f - accuracy, 1.0f / numSamples);
}
void Setup(float _atk, float _rel, float _thr, float _ratio, float _knee)
{
thr = _thr;
ratio = _ratio;
knee = _knee;
float g = 0.05f * ((1.0f / ratio) - 1.0f);
exp1 = powf(10.0f, g * 0.25f / ((knee > 0.0f) ? knee : 1.0f));
exp2 = powf(10.0f, g);
atk = GetTimeConstant(0.99f, atk);
rel = GetTimeConstant(0.99f, rel);
}
inline float Process(float input)
{
float g = 1.0f;
float s = FastClip(input * input, 1.0e-11f, 100.0f);
float timeConst = (s > env) ? atk : rel;
env += (s - env) * timeConst + 1.0e-16f; // add small constant to always positive number to avoid denormal numbers
float sideChainLevel = 10.0f * log10f(env); // multiply by 10 (not 20) because duckEnvelope is RMS
float t = sideChainLevel - thr;
if (fabsf(t) < knee)
{
t += knee;
g = powf(exp1, t * t);
}
else if (t > 0.0f)
g = powf(exp2, t);
reduction = g;
return input * g;
}
};
const int MAXORDER = 4;
struct EffectData
{
struct Data
{
float p[P_NUM];
BiquadFilter bandsplit[8][MAXORDER][4];
BiquadFilter previewBandsplit[4];
CompressorChannel band[3][8];
Random random;
FFTAnalyzer analyzer;
};
union
{
Data data;
unsigned char pad[(sizeof(Data) + 15) & ~15]; // This entire structure must be a multiple of 16 bytes (and and instance 16 byte aligned) for PS3 SPU DMA requirements
};
};
int InternalRegisterEffectDefinition(UnityAudioEffectDefinition& definition)
{
static const char* bandname[] = { "Low", "Mid", "High" };
int numparams = P_NUM;
definition.paramdefs = new UnityAudioParameterDefinition[numparams];
RegisterParameter(definition, "MasterGain", "dB", -100.0f, 100.0f, 0.0f, 1.0f, 1.0f, P_MasterGain, "Overall gain");
RegisterParameter(definition, "LowFreq", "Hz", 0.01f, 24000.0f, 800.0f, 1.0f, 3.0f, P_LowFreq, "Low/Mid cross-over frequency");
RegisterParameter(definition, "HighFreq", "Hz", 0.01f, 24000.0f, 5000.0f, 1.0f, 3.0f, P_HighFreq, "Mid/High cross-over frequency");
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sGain", bandname[i]), "dB", -100.0f, 100.0f, 0.0f, 1.0f, 1.0f, P_LowGain + i, tmpstr(1, "%s band gain in dB", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sAttackTime", bandname[i]), "ms", 0.0f, 10.0f, 0.1f, 1000.0f, 4.0f, P_LowAttack + i, tmpstr(1, "%s band attack time in seconds", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sReleaseTime", bandname[i]), "ms", 0.0f, 10.0f, 0.5f, 1000.0f, 4.0f, P_LowRelease + i, tmpstr(1, "%s band release time in seconds", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sThreshold", bandname[i]), "dB", -50.0f, 0.0f, -10.0f, 1.0f, 1.0f, P_LowThreshold + i, tmpstr(1, "%s band compression level threshold time in dB", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sRatio", bandname[i]), "%", 1.0f, 30.0f, 1.0f, 100.0f, 1.0f, P_LowRatio + i, tmpstr(1, "%s band compression ratio time in percent", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sKnee", bandname[i]), "dB", 0.0f, 40.0f, 10.0f, 1.0f, 1.0f, P_LowKnee + i, tmpstr(1, "%s band compression curve knee range in dB", bandname[i]));
RegisterParameter(definition, "FilterOrder", "", 1.0f, (float)MAXORDER, 1.0f, 1.0f, 1.0f, P_FilterOrder, "Filter order of cross-over filters");
RegisterParameter(definition, "UseLogScale", "", 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, P_UseLogScale, "Use logarithmic scale for plotting the filter curve frequency response and input/output spectra");
RegisterParameter(definition, "ShowSpectrum", "", 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, P_ShowSpectrum, "Overlay input spectrum (green) and output spectrum (red)");
RegisterParameter(definition, "SpectrumDecay", "dB/s", -50.0f, 0.0f, -10.0f, 1.0f, 1.0f, P_SpectrumDecay, "Hold time for overlaid spectra");
return numparams;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK CreateCallback(UnityAudioEffectState* state)
{
EffectData* effectdata = new EffectData;
memset(effectdata, 0, sizeof(EffectData));
effectdata->data.analyzer.spectrumSize = 4096;
InitParametersFromDefinitions(InternalRegisterEffectDefinition, effectdata->data.p);
state->effectdata = effectdata;
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ReleaseCallback(UnityAudioEffectState* state)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
data->analyzer.Cleanup();
delete data;
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK SetFloatParameterCallback(UnityAudioEffectState* state, int index, float value)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
if (index >= P_NUM)
return UNITY_AUDIODSP_ERR_UNSUPPORTED;
data->p[index] = value;
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK GetFloatParameterCallback(UnityAudioEffectState* state, int index, float* value, char *valuestr)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
if (value != NULL)
*value = data->p[index];
if (valuestr != NULL)
valuestr[0] = 0;
return UNITY_AUDIODSP_OK;
}
static void SetupFilterCoeffs(EffectData::Data* data, int samplerate, BiquadFilter* filter0, BiquadFilter* filter1, BiquadFilter* filter2, BiquadFilter* filter3)
{
const float qfactor = 0.707f;
filter0->SetupLowpass(data->p[P_LowFreq], samplerate, qfactor);
filter1->SetupHighpass(data->p[P_LowFreq], samplerate, qfactor);
filter2->SetupLowpass(data->p[P_HighFreq], samplerate, qfactor);
filter3->SetupHighpass(data->p[P_HighFreq], samplerate, qfactor);
}
int UNITY_AUDIODSP_CALLBACK GetFloatBufferCallback(UnityAudioEffectState* state, const char* name, float* buffer, int numsamples)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
if (strcmp(name, "InputSpec") == 0)
data->analyzer.ReadBuffer(buffer, numsamples, true);
else if (strcmp(name, "OutputSpec") == 0)
data->analyzer.ReadBuffer(buffer, numsamples, false);
else if (strcmp(name, "LiveData") == 0)
{
buffer[0] = data->band[0][0].reduction;
buffer[1] = data->band[1][0].reduction;
buffer[2] = data->band[2][0].reduction;
buffer[3] = data->band[0][0].env;
buffer[4] = data->band[1][0].env;
buffer[5] = data->band[2][0].env;
}
else if (strcmp(name, "Coeffs") == 0)
{
SetupFilterCoeffs(data, state->samplerate, &data->previewBandsplit[0], &data->previewBandsplit[1], &data->previewBandsplit[2], &data->previewBandsplit[3]);
data->previewBandsplit[0].StoreCoeffs(buffer);
data->previewBandsplit[1].StoreCoeffs(buffer);
data->previewBandsplit[2].StoreCoeffs(buffer);
data->previewBandsplit[3].StoreCoeffs(buffer);
}
else
memset(buffer, 0, sizeof(float) * numsamples);
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ProcessCallback(UnityAudioEffectState* state, float* inbuffer, float* outbuffer, unsigned int length, int inchannels, int outchannels)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
const float sr = (float)state->samplerate;
float specDecay = powf(10.0f, 0.05f * data->p[P_SpectrumDecay] * length / sr);
bool calcSpectrum = (data->p[P_ShowSpectrum] >= 0.5f);
if (calcSpectrum)
data->analyzer.AnalyzeInput(inbuffer, inchannels, length, specDecay);
for (int i = 0; i < inchannels; i++)
{
data->band[0][i].Setup(data->p[P_LowAttack] * sr, data->p[P_LowRelease] * sr, data->p[P_LowThreshold], data->p[P_LowRatio], data->p[P_LowKnee]);
data->band[1][i].Setup(data->p[P_MidAttack] * sr, data->p[P_MidRelease] * sr, data->p[P_MidThreshold], data->p[P_MidRatio], data->p[P_MidKnee]);
data->band[2][i].Setup(data->p[P_HighAttack], data->p[P_HighRelease], data->p[P_HighThreshold], data->p[P_HighRatio], data->p[P_HighKnee]);
for (int k = 0; k < MAXORDER; k++)
SetupFilterCoeffs(data, state->samplerate, &data->bandsplit[i][k][0], &data->bandsplit[i][k][1], &data->bandsplit[i][k][2], &data->bandsplit[i][k][3]);
}
const float lowGainLin = powf(10.0f, (data->p[P_LowGain] + data->p[P_MasterGain]) * 0.05f);
const float midGainLin = powf(10.0f, (data->p[P_MidGain] + data->p[P_MasterGain]) * 0.05f);
const float highGainLin = powf(10.0f, (data->p[P_HighGain] + data->p[P_MasterGain]) * 0.05f);
const int order = (int)data->p[P_FilterOrder];
for (unsigned int n = 0; n < length; n++)
{
for (int i = 0; i < outchannels; i++)
{
float killdenormal = (float)(data->random.Get() & 255) * 1.0e-9f;
float input = inbuffer[n * inchannels + i] + killdenormal;
float lpf = input, bpf = input, hpf = input;
for (int k = 0; k < order; k++)
{
lpf = data->bandsplit[i][k][0].Process(lpf);
bpf = data->bandsplit[i][k][1].Process(bpf);
}
for (int k = 0; k < order; k++)
{
bpf = data->bandsplit[i][k][2].Process(bpf);
hpf = data->bandsplit[i][k][3].Process(hpf);
}
outbuffer[n * outchannels + i] =
data->band[0]->Process(lpf) * lowGainLin +
data->band[1]->Process(bpf) * midGainLin +
data->band[2]->Process(hpf) * highGainLin;
}
}
if (calcSpectrum)
data->analyzer.AnalyzeOutput(outbuffer, outchannels, length, specDecay);
return UNITY_AUDIODSP_OK;
}
}
| 47.217557 | 215 | 0.580955 | PStewart95 |
16a2cccb2154ef1e951a16cebc467407c7e64620 | 1,409 | cpp | C++ | PlayerLinkedList.cpp | nickcuenca/UNO-An-SFML-Experience | d43beb5ba659958f1fa596a47814379d612f86b7 | [
"MIT"
] | null | null | null | PlayerLinkedList.cpp | nickcuenca/UNO-An-SFML-Experience | d43beb5ba659958f1fa596a47814379d612f86b7 | [
"MIT"
] | null | null | null | PlayerLinkedList.cpp | nickcuenca/UNO-An-SFML-Experience | d43beb5ba659958f1fa596a47814379d612f86b7 | [
"MIT"
] | null | null | null | //
// Created by Nicolas Cuenca on 11/25/2020.
//
#include "PlayerLinkedList.h"
#include <iostream>
PlayerLinkedList::PlayerLinkedList(Player *first) {
this->first = first;
this->currentPlayer = first;
}
Player *PlayerLinkedList::getFirst() const {
return first;
}
Player *PlayerLinkedList::getCurrentPlayer() const {
return currentPlayer;
}
void PlayerLinkedList::setCurrentPlayer(Player *currentPlayer) {
PlayerLinkedList::currentPlayer = currentPlayer;
}
void PlayerLinkedList::reverseList() {
Player *prev = first;
Player *temp;
Player *curr = first->getNextPlayer();
bool visited = false;
while(!visited || prev != first){
temp = curr->getNextPlayer();
curr->setNextPlayer(prev);
prev = curr;
curr = temp;
visited = true;
}
}
void PlayerLinkedList::deletePlayers() {
Player *curr = first;
Player *next;
int count = 0;
bool visited = false;
while(curr != first || !visited ){
count++;
curr = curr->getNextPlayer();
visited = true;
}
int delete_until = 0;
while(delete_until < count){
std::cout << curr->getId() << std::endl;
next = curr->getNextPlayer();
delete curr;
curr = next;
delete_until++;
}
first = nullptr;
currentPlayer = nullptr;
}
| 22.725806 | 65 | 0.58907 | nickcuenca |
16a43f94ec50c6a149c18417a565413ec29c20b8 | 5,894 | cc | C++ | mindspore/lite/src/runtime/kernel/arm/nnacl/fp32/deconv.cc | i4oolish/mindspore | dac3be31d0f2c0a3516200f47af30980e566601b | [
"Apache-2.0"
] | 1 | 2020-08-10T12:06:22.000Z | 2020-08-10T12:06:22.000Z | mindspore/lite/src/runtime/kernel/arm/nnacl/fp32/deconv.cc | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/nnacl/fp32/deconv.cc | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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 "src/runtime/kernel/arm/nnacl/fp32/deconv.h"
void PackDeConvWeightFp32(const float *weight, float *dst, int input_channel, int output_channel, int plane) {
/* ichwoc(nhwc) -> oc4 * h * w * incUP4 * 4 */
int ic_up4 = UP_ROUND(input_channel, C4NUM);
for (int oc = 0; oc < output_channel; oc++) {
int oc4div = oc / C4NUM;
int oc4mod = oc % C4NUM;
for (int ic = 0; ic < input_channel; ic++) {
for (int hw = 0; hw < plane; hw++) {
int src_index = ic * plane * output_channel + hw * output_channel + oc;
int dst_index = oc4div * ic_up4 * plane * C4NUM + hw * ic_up4 * C4NUM + ic * C4NUM + oc4mod;
dst[dst_index] = weight[src_index];
}
}
}
return;
}
int DeConvFp32(const float *input, const float *weight, float *output, float *tmp_buffer,
StrassenMatMulParameter matmul_param) {
return StrassenMatmul(input, weight, output, &matmul_param, FP32_STRASSEN_MAX_RECURSION, 0, tmp_buffer);
}
int DeConvPostFp32C8x8(const float *src, float *tmp, const float *bias, float *dst, int output_channel,
ConvParameter *conv_param) {
/* row8x8-major(ih*iw x oc*kh*kw) -> row8-major(oh*ow x oc) */
size_t input_plane = conv_param->input_w_ * conv_param->input_h_;
size_t kernel_plane = conv_param->kernel_w_ * conv_param->kernel_h_;
size_t output_plane = conv_param->output_w_ * conv_param->output_h_;
int oc8 = UP_DIV(output_channel, C8NUM);
int in_plane8 = UP_ROUND(input_plane, C8NUM);
for (int c = 0; c < oc8; c++) {
float *dst_ptr = tmp + c * output_plane * C8NUM;
const float *src_ptr = src + c * in_plane8 * kernel_plane * C8NUM;
memset(dst_ptr, 0, output_plane * C8NUM * sizeof(int32_t));
for (int ih = 0; ih < conv_param->input_h_; ih++) {
for (int iw = 0; iw < conv_param->input_w_; iw++) {
int oh = ih * conv_param->stride_h_ - conv_param->pad_h_;
int ow = iw * conv_param->stride_w_ - conv_param->pad_w_;
int kh_start = MSMAX(0, UP_DIV(-oh, conv_param->dilation_h_));
int kh_end = MSMIN(conv_param->kernel_h_, UP_DIV(conv_param->output_h_ - oh, conv_param->dilation_h_));
int kw_start = MSMAX(0, UP_DIV(-ow, conv_param->dilation_w_));
int kw_end = MSMIN(conv_param->kernel_w_, UP_DIV(conv_param->output_w_ - ow, conv_param->dilation_w_));
for (int kh = kh_start; kh < kh_end; kh++) {
for (int kw = kw_start; kw < kw_end; kw++) {
int src_index = ih * conv_param->input_w_ * C8NUM + iw * C8NUM +
kh * in_plane8 * conv_param->kernel_w_ * C8NUM + kw * in_plane8 * C8NUM;
int dst_index = oh * conv_param->output_w_ * C8NUM + ow * C8NUM +
kh * conv_param->dilation_h_ * conv_param->output_w_ * C8NUM +
kw * conv_param->dilation_w_ * C8NUM;
for (int i = 0; i < C8NUM; i++) {
dst_ptr[dst_index + i] += src_ptr[src_index + i];
}
} /*kw*/
} /*kh*/
} /*iw*/
} /*ih*/
} /*oc8*/
PostConvFuncFp32C8(tmp, dst, bias, output_channel, output_plane, conv_param->output_channel_, conv_param->is_relu_,
conv_param->is_relu6_);
return NNACL_OK;
}
int DeConvPostFp32C4(const float *src, float *tmp_c4, float *dst, const float *bias, int output_channel,
int input_plane, int kernel_plane, int output_plane, ConvParameter *conv_param) {
int oc4 = UP_DIV(output_channel, C4NUM);
for (int c = 0; c < oc4; c++) {
float *dst_ptr = tmp_c4 + c * output_plane * C4NUM;
const float *src_ptr = src + c * input_plane * kernel_plane * C4NUM;
memset(dst_ptr, 0, output_plane * C4NUM * sizeof(float));
for (int ih = 0; ih < conv_param->input_h_; ih++) {
for (int iw = 0; iw < conv_param->input_w_; iw++) {
int oh = ih * conv_param->stride_h_ - conv_param->pad_h_;
int ow = iw * conv_param->stride_w_ - conv_param->pad_w_;
int kh_start = MSMAX(0, UP_DIV(-oh, conv_param->dilation_h_));
int kh_end = MSMIN(conv_param->kernel_h_, UP_DIV(conv_param->output_h_ - oh, conv_param->dilation_h_));
int kw_start = MSMAX(0, UP_DIV(-ow, conv_param->dilation_w_));
int kw_end = MSMIN(conv_param->kernel_w_, UP_DIV(conv_param->output_w_ - ow, conv_param->dilation_w_));
for (int kh = kh_start; kh < kh_end; kh++) {
for (int kw = kw_start; kw < kw_end; kw++) {
int src_index = ih * conv_param->input_w_ * C4NUM + iw * C4NUM +
kh * input_plane * conv_param->kernel_w_ * C4NUM + kw * input_plane * C4NUM;
int dst_index = oh * conv_param->output_w_ * C4NUM + ow * C4NUM +
kh * conv_param->dilation_h_ * conv_param->output_w_ * C4NUM +
kw * conv_param->dilation_w_ * C4NUM;
for (int i = 0; i < C4NUM; i++) {
dst_ptr[dst_index + i] += src_ptr[src_index + i];
}
} /*kw*/
} /*kh*/
} /*iw*/
} /*ih*/
} /*oc4*/
PostConvFuncFp32C4(tmp_c4, dst, bias, output_channel, output_plane, conv_param->output_channel_, conv_param->is_relu_,
conv_param->is_relu6_);
return NNACL_OK;
}
| 48.311475 | 120 | 0.61605 | i4oolish |
16a95ae692172148c372031305b66ca4fd3251d9 | 851 | cpp | C++ | Universal-Physics-mod/src/simulation/elements/RFGL.cpp | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | 1 | 2022-03-26T20:01:13.000Z | 2022-03-26T20:01:13.000Z | Universal-Physics-mod/src/simulation/elements/RFGL.cpp | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | null | null | null | Universal-Physics-mod/src/simulation/elements/RFGL.cpp | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | 1 | 2022-03-26T19:59:13.000Z | 2022-03-26T19:59:13.000Z | #include "simulation/ElementCommon.h"
int Element_RFRG_update(UPDATE_FUNC_ARGS);
void Element::Element_RFGL()
{
Identifier = "DEFAULT_PT_RFGL";
Name = "RFGL";
Colour = PIXPACK(0x84C2CF);
MenuVisible = 0;
MenuSection = SC_LIQUID;
Enabled = 1;
Advection = 0.6f;
AirDrag = 0.01f * CFDS;
AirLoss = 0.98f;
Loss = 0.95f;
Collision = 0.0f;
Gravity = 0.1f;
Diffusion = 0.00f;
HotAir = 0.000f * CFDS;
Falldown = 2;
Flammable = 0;
Explosive = 0;
Meltable = 0;
Hardness = 20;
Weight = 10;
HeatConduct = 3;
Description = "Liquid refrigerant.";
Properties = TYPE_LIQUID|PROP_DEADLY;
LowPressure = 2;
LowPressureTransition = PT_RFRG;
HighPressure = IPH;
HighPressureTransition = NT;
LowTemperature = ITL;
LowTemperatureTransition = NT;
HighTemperature = ITH;
HighTemperatureTransition = NT;
Update = &Element_RFRG_update;
}
| 18.106383 | 42 | 0.707403 | AllSafeCyberSecur1ty |
16aa775c41f98abf6ae1c8c2653456c5deddf82f | 1,312 | hpp | C++ | AIR-ARR/Wizualizacja Danych Sensorycznych/Qt/prj/inc/DaneSymulacji.hpp | superdyzio/PWR-Stuff | 942dfd72e4fa987f80b0de185c4a3086d98b4e3f | [
"MIT"
] | null | null | null | AIR-ARR/Wizualizacja Danych Sensorycznych/Qt/prj/inc/DaneSymulacji.hpp | superdyzio/PWR-Stuff | 942dfd72e4fa987f80b0de185c4a3086d98b4e3f | [
"MIT"
] | null | null | null | AIR-ARR/Wizualizacja Danych Sensorycznych/Qt/prj/inc/DaneSymulacji.hpp | superdyzio/PWR-Stuff | 942dfd72e4fa987f80b0de185c4a3086d98b4e3f | [
"MIT"
] | null | null | null | /*!
* \file
* \brief Plik nagłówkowy klasy DaneSymulacji.
*/
#ifndef DANE_HH
#define DANE_HH
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <QVector>
#include <QString>
#include <QDebug>
#include <QFile>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/*!
* \brief Klasa odpowiedzialna za kontrolę trybu symulacji.
*
* Klasa DaneSymulacji przechowuje informacje konieczne do poprawnego działania trybu symulacyjnego.
*/
class DaneSymulacji {
public:
/*!
* \brief Konstruktor klasy DaneSymulacji.
*/
DaneSymulacji();
/*!
* \brief Pole typu double przechowujące aktualny czas symulacji.
*/
double _aktualnyCzas;
/*!
* \brief Wektor typu double przechowujący wartości symulacji.
*/
vector<double> _wartosci;
/*!
* \brief Wektor typu double przechowujący czasy odpowiadające wartościom.
*/
vector<double> _czas;
/*!
* \brief Metoda wczytująca dane do symulacji z pliku.
* \param[in] plik - łańcuch określający nazwę pliku z danymi
* \return Nic nie jest zwracane.
*
* Metoda pobiera jako argument samą nazwę pliku i szuka go w folderze data wewnątrz katalogu projektu.
*/
void wczytajDane(string plik);
/*!
* \brief Pole typu string przechowujące kompletną ścieżkę do pliku z danymi.
*/
string _plikSymulacji;
};
#endif
| 21.508197 | 103 | 0.740091 | superdyzio |
16b14d897675e03f2c39adc7e4d30e12f7b2c69c | 25,018 | hpp | C++ | xfinal/websokcet.hpp | maxbad/xfinal | 3e8ba689fc40b896bb2555aebf903672335b8b7b | [
"MIT"
] | 57 | 2019-05-14T09:55:14.000Z | 2022-03-17T07:08:55.000Z | xfinal/websokcet.hpp | maxbad/xfinal | 3e8ba689fc40b896bb2555aebf903672335b8b7b | [
"MIT"
] | 12 | 2019-05-18T02:34:48.000Z | 2021-06-29T15:30:41.000Z | xfinal/websokcet.hpp | maxbad/xfinal | 3e8ba689fc40b896bb2555aebf903672335b8b7b | [
"MIT"
] | 22 | 2019-06-15T10:09:33.000Z | 2022-01-18T09:24:25.000Z | #pragma once
#include <asio.hpp>
#include "http_handler.hpp"
#include <memory>
#include <functional>
#include <string>
#include "uuid.hpp"
#include <unordered_map>
#include "string_view.hpp"
#include "utils.hpp"
#include <memory>
#include "md5.hpp"
#include <queue>
#include <random>
#include <list>
#include "message_handler.hpp"
#include "any.hpp"
namespace xfinal {
struct frame_info {
frame_info() = default;
bool eof;
int opcode;
int mask;
std::uint64_t payload_length;
unsigned char mask_key[4];
};
class websockets;
class websocket;
template<typename T>
void close_ws(websocket& ws);
inline void close_ws_with_notification(websocket& ws);
class websocket_event final {
friend class websockets;
public:
websocket_event() = default;
public:
template<typename Function, typename...Args>
websocket_event& on(std::string const& event_name, Function&& function, Args&& ...args) {
event_call_back_.insert(std::make_pair(event_name, on_help<(sizeof...(Args))>(0, std::forward<Function>(function), std::forward<Args>(args)...)));
return *this;
}
void trigger(std::string const& event_name, websocket& ws) {
auto it = event_call_back_.find(event_name);
if (it != event_call_back_.end()) {
(it->second)(ws);
}
}
private:
template<std::size_t N, typename Function, typename...Args, typename U = typename std::enable_if<std::is_same<number_content<N>, number_content<0>>::value>::type>
auto on_help(int, Function && function, Args && ...args)->decltype(std::bind(std::forward<Function>(function), std::placeholders::_1)) {
return std::bind(std::forward<Function>(function), std::placeholders::_1);
}
template<std::size_t N, typename Function, typename...Args, typename U = typename std::enable_if<!std::is_same<number_content<N>, number_content<0>>::value>::type>
auto on_help(long, Function && function, Args && ...args)->decltype(std::bind(std::forward<Function>(function), std::forward<Args>(args)..., std::placeholders::_1)) {
return std::bind(std::forward<Function>(function), std::forward<Args>(args)..., std::placeholders::_1);
}
private:
std::unordered_map<std::string, std::function<void(websocket&)>> event_call_back_;
};
class websocket_event_map {
friend class websockets;
friend class websocket;
public:
void trigger(const std::string& url, std::string const& event_name, websocket& ws) {//只是读 多线程没有问题
auto it = events_.find(url);
if (it != events_.end()) {
it->second.trigger(event_name, ws);
}
else {
close_ws<void>(ws);
}
}
void add(nonstd::string_view uuid,std::weak_ptr<websocket> weak) {
std::unique_lock<std::mutex> lock(map_mutex_);
websockets_.insert(std::make_pair(uuid, weak.lock()));
}
void remove(nonstd::string_view uuid) {
std::unique_lock<std::mutex> lock(map_mutex_);
auto it = websockets_.find(uuid);
if (it != websockets_.end()) {
websockets_.erase(it);
}
}
~websocket_event_map() {
map_mutex_.lock();
auto copy_sockets = websockets_;
map_mutex_.unlock();
for (auto&& wsocket : copy_sockets) {
close_ws_with_notification(*wsocket.second);
}
}
private:
std::mutex map_mutex_;
std::unordered_map<std::string, websocket_event> events_;
std::unordered_map<nonstd::string_view, std::shared_ptr<websocket>> websockets_;
};
struct send_message {
std::shared_ptr<websocket> websocket_;
std::shared_ptr<std::queue<std::shared_ptr<std::string>>> message_queue;
std::shared_ptr<std::function<void(bool, std::error_code)>> write_callback;
};
inline void send_to_hub(send_message const&);
class websocket final :public std::enable_shared_from_this<websocket> {
friend class websocket_hub;
friend class connection;
template<typename T>
friend void close_ws(websocket& ws);
public:
websocket(websocket_event_map& web, std::string const& url) :websocket_event_manager(web), socket_uid_(uuids::uuid_system_generator{}().to_short_str()), url_(url){
}
public:
std::string const& uuid() {
return socket_uid_;
}
bool is_open() {
return socket_is_open_;
}
asio::ip::tcp::socket& socket() {
return *socket_;
}
std::map<std::string, std::string> key_params () const noexcept {
return decode_url_params_;
}
private:
void move_socket(std::unique_ptr<asio::ip::tcp::socket>&& socket) {
socket_ = std::move(socket);
socket = nullptr;
socket_is_open_ = true;
auto& io = static_cast<asio::io_service&>(socket_->get_executor().context());
wait_read_timer_ = std::move(std::unique_ptr<asio::steady_timer>(new asio::steady_timer(io)));
wait_write_timer_ = std::move(std::unique_ptr<asio::steady_timer>(new asio::steady_timer(io)));
websocket_event_manager.trigger(url_, "open", *this);
start_read();
}
private:
void start_read() {
read_pos_ = 0;
std::memset(frame, 0, sizeof(frame));
std::memset(&frame_info_, 0, sizeof(frame_info_));
auto handler = this->shared_from_this();
start_read_timeout(); //开始开启空连接超时 从当前时间算起
socket_->async_read_some(asio::buffer(&frame[read_pos_], 2), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->frame_parser();
});
}
public:
nonstd::string_view messages() const {
return message_;
}
unsigned char message_code() const {
return message_opcode;
}
public:
//void write(std::string const& message, unsigned char opcode) {
// auto message_size = message.size();
// auto offset = 0;
// if (message_size < 126) {
// unsigned char frame_head = 128;
// frame_head = frame_head | opcode;
// unsigned char c2 = 0;
// c2 = c2 | ((unsigned char)message_size);
// std::string a_frame;
// a_frame.push_back(frame_head);
// a_frame.push_back(c2);
// a_frame.append(message);
// write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));
// }
// else if (message_size >= 126) {
// auto counts = message_size / frame_data_size_;
// if ((message_size % frame_data_size_) != 0) {
// counts++;
// }
// std::size_t read_pos = 0;
// for (std::size_t i = 0; i < counts; ++i) {
// std::int64_t left_size = std::int64_t(message_size) - std::int64_t(frame_data_size_);
// unsigned short write_data_size = (unsigned short)frame_data_size_;
// unsigned char frame_head = 0;
// std::string a_frame;
// if (left_size <= 0) {
// frame_head = 128;
// write_data_size = (unsigned short)message_size;
// //frame_head = frame_head | opcode;
// }
// if (i == 0) {
// frame_head = frame_head | opcode;
// }
// a_frame.push_back(frame_head);
// unsigned char c2 = 0;
// if (write_data_size >= 126) {
// unsigned char tmp_c = 126;
// c2 = c2 | tmp_c;
// a_frame.push_back(c2);
// auto data_length = l_to_netendian(write_data_size);
// a_frame.append(data_length);
// }
// else if (write_data_size < 126) {
// unsigned char tmp_c = (unsigned char)write_data_size;
// c2 = c2 | tmp_c;
// a_frame.push_back(c2);
// }
// a_frame.append(std::string(&message[read_pos], write_data_size));
// read_pos += write_data_size;
// message_size = (std::size_t)left_size;
// write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));
// }
// }
// write_frame();
//}
void write(std::string const& message, unsigned char opcode, std::function<void(bool, std::error_code)> const& call_back) {
auto message_size = message.size();
if (message_size == 0) {
return;
}
auto offset = 0;
//std::shared_ptr<std::string> write_data(new std::string());
std::shared_ptr<std::queue<std::shared_ptr<std::string>>> write_queue{ new std::queue<std::shared_ptr<std::string>> {} };
if (message_size < 126) {
unsigned char frame_head = 128;
frame_head = frame_head | opcode;
unsigned char c2 = 0;
c2 = c2 | ((unsigned char)message_size);
std::shared_ptr<std::string> a_frame{new std::string()};
a_frame->push_back(frame_head);
a_frame->push_back(c2);
a_frame->append(message);
write_queue->emplace(a_frame);
//write_data->append(a_frame);
/*write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));*/
}
else if (message_size >= 126) {
auto counts = message_size / frame_data_size_;
if ((message_size % frame_data_size_) != 0) {
counts++;
}
std::size_t read_pos = 0;
for (std::size_t i = 0; i < counts; ++i) {
std::int64_t left_size = std::int64_t(message_size) - std::int64_t(frame_data_size_);
unsigned short write_data_size = (unsigned short)frame_data_size_;
unsigned char frame_head = 0;
std::shared_ptr<std::string> a_frame{ new std::string() };
if (left_size <= 0) {
frame_head = 128;
write_data_size = (unsigned short)message_size;
//frame_head = frame_head | opcode;
}
if (i == 0) {
frame_head = frame_head | opcode;
}
a_frame->push_back(frame_head);
unsigned char c2 = 0;
if (write_data_size >= 126) {
unsigned char tmp_c = 126;
c2 = c2 | tmp_c;
a_frame->push_back(c2);
auto data_length = l_to_netendian(write_data_size);
a_frame->append(data_length);
}
else if (write_data_size < 126) {
unsigned char tmp_c = (unsigned char)write_data_size;
c2 = c2 | tmp_c;
a_frame->push_back(c2);
}
a_frame->append(std::string(&message[read_pos], write_data_size));
read_pos += write_data_size;
message_size = (std::size_t)left_size;
write_queue->emplace(a_frame);
//write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));
//write_data->append(a_frame);
}
}
/*write_frame();*/
send_message send_msg = { this->shared_from_this() ,write_queue,std::shared_ptr<std::function<void(bool,std::error_code)>>(new std::function<void(bool,std::error_code)>{call_back}) };
send_to_hub(send_msg);
}
public:
void write_string(std::string const& message,std::function<void(bool,std::error_code)> const& call_back = nullptr) {
write(message, 1, call_back);
}
void write_binary(std::string const& message, std::function<void(bool, std::error_code)> const& call_back = nullptr) {
write(message, 2, call_back);
}
template<typename T>
void set_user_data(std::string const& key,std::shared_ptr<T> const& value){
user_data_.emplace(key, value);
}
template<typename T>
T get_user_data(std::string const& key) {
auto it = user_data_.find(key);
if (it != user_data_.end()) {
return nonstd::any_cast<T>(it->second);
}
return nullptr;//error
}
private:
//void write_frame() {
// if (write_frame_queue_.empty()) {
// return;
// }
// while (!write_frame_queue_.empty()) {
// reset_time();
// auto frame = std::move(write_frame_queue_.front());
// write_frame_queue_.pop();
// asio::const_buffer buffers(frame->data(), frame->size());
// std::error_code ingore_ec;
// asio::write(*socket_, buffers, ingore_ec);
// if (ingore_ec) {
// auto clear = std::queue<std::unique_ptr<std::string>>{};
// write_frame_queue_.swap(clear);
// break;
// }
// }
// // asio::async_write(*socket_,buffers, [frame = std::move(frame),handler = this->shared_from_this()](std::error_code const& ec,std::size_t size) {
// // if (ec) {
// // return;
// // }
// // handler->write_frame();
// // });
//}
public:
void start_read_timeout() {
wait_read_timer_->expires_from_now(std::chrono::seconds(wait_read_time_));
auto handler = this->shared_from_this();
wait_read_timer_->async_wait([handler,this](std::error_code const& ec) {
if (ec) {
return;
}
std::stringstream ss;
ss << "websocket id: "<< socket_uid_<< " read no data during " << wait_read_time_ << " seconds";
utils::messageCenter::get().trigger_message(ss.str());
handler->close();
});
}
void cancel_read_time() {
std::error_code ignore;
wait_read_timer_->cancel(ignore);
}
void start_write_timeout() {
wait_write_timer_->expires_from_now(std::chrono::seconds(wait_write_time_));
auto handler = this->shared_from_this();
wait_write_timer_->async_wait([handler,this](std::error_code const& ec) {
if (ec) {
return;
}
std::stringstream ss;
ss << "websocket id: " << socket_uid_ << " couldn't write data during " << wait_write_time_ << " seconds";
utils::messageCenter::get().trigger_message(ss.str());
handler->close();
});
}
void cancel_write_time() {
std::error_code ignore;
wait_write_timer_->cancel(ignore);
}
void ping() {
//ping_pong_timer_->expires_from_now(std::chrono::seconds(ping_pong_time_));
//ping_pong_timer_->async_wait([handler = this->shared_from_this()](std::error_code const& ec) {
// if (ec) {
// return;
// }
// handler->write("", 9);
// handler->reset_time();
// handler->ping();
//});
}
private:
void frame_parser() {
read_pos_ += 2;
unsigned char c = frame[0];
frame_info_.eof = c >> 7;
frame_info_.opcode = c & 15;
if (frame_info_.opcode) {
message_opcode = (unsigned char)frame_info_.opcode;
}
if (frame_info_.opcode == 8) { //关闭连接
close();
return;
}
if (frame_info_.opcode == 9) { //ping
write("", 10,nullptr); //回应客户端心跳
return;
}
if (frame_info_.opcode == 10) { //pong
cancel_read_time();
return;
}
unsigned char c2 = frame[1];
frame_info_.mask = c2 >> 7;
if (frame_info_.mask != 1) { //mask 必须是1
close();
return;
}
c2 = c2 & 127;
if (c2 < 126) { //数据的长度为当前值
frame_info_.payload_length = c2;
handle_payload_length(0);
}
else if (c2 == 126) { //后续2个字节 unsigned
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&frame[read_pos_], 2), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->handle_payload_length(2);
});
}
else if (c2 == 127) { //后续8个字节 unsigned
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&frame[read_pos_], 8), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->handle_payload_length(8);
});
}
}
void handle_payload_length(std::size_t read_size) { //if length >126
if (read_size == 2) {
unsigned short tmp = 0;
netendian_to_l(tmp, &(frame[read_pos_]));
frame_info_.payload_length = tmp;
}
else if (read_size == 8) {
std::uint64_t tmp = 0;
netendian_to_l(tmp, &(frame[read_pos_]));
frame_info_.payload_length = tmp;
}
if (frame_info_.mask == 1) { //应该必须等于1
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&frame_info_.mask_key[0], 4), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->read_data();
});
}
}
void read_data() {
if (frame_info_.payload_length == 0) { //没有数据需要读取
if (frame_info_.eof) {
message_ = std::string();
buffers_.resize(0);
data_current_pos_ = 0;
//数据帧都处理完整 回调
websocket_event_manager.trigger(url_, "message", *this);
}
start_read();
return;
}
expand_buffer(frame_info_.payload_length);
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&buffers_[data_current_pos_], (std::size_t)frame_info_.payload_length), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->set_current_pos(read_size);
handler->decode_data(read_size);
});
}
void decode_data(std::size_t use_size) {
unsigned char* iter = &(buffers_[data_current_pos_ - use_size]);
for (std::size_t i = 0; i < use_size; ++i) {
auto j = i % 4;
auto mask_key = frame_info_.mask_key[j];
*iter = (*iter) ^ mask_key;
++iter;
}
if (frame_info_.eof) {
message_ = std::string(buffers_.begin(), buffers_.begin() + data_current_pos_);
buffers_.resize(0);
data_current_pos_ = 0;
//数据帧都处理完整 回调
websocket_event_manager.trigger(url_, "message", *this);
}
start_read();
}
void set_current_pos(std::size_t size) {
data_current_pos_ += size;
}
std::size_t left_buffer_size() {
return buffers_.size() - data_current_pos_;
}
void expand_buffer(std::uint64_t need_size) {
auto left_size = left_buffer_size();
if (need_size > left_buffer_size()) {
auto total_size = buffers_.size() + (need_size - left_size);
buffers_.resize((std::size_t)total_size);
}
}
public:
void set_check_alive_time(std::time_t seconds) {
wait_read_time_ = seconds;
}
void set_frame_data_size(std::size_t size) {
frame_data_size_ = size;
}
void set_check_write_alive_time(std::time_t seconds) {
wait_write_time_ = seconds;
}
public:
void close() {
if (socket_is_open_) {
std::error_code ec;
socket_->shutdown(asio::ip::tcp::socket::shutdown_both, ec);
std::error_code ec0;
socket_->close(ec0);
socket_is_open_ = false;
is_writing_ = false;
cancel_read_time();
cancel_write_time();
//ping_pong_timer_->cancel();
websocket_event_manager.trigger(url_, "close", *this); //关闭事件
websocket_event_manager.remove(nonstd::string_view(socket_uid_.data(), socket_uid_.size()));
}
}
void shutdown() {
null_close();
}
private:
void null_close() { //无路由的空连接需要关闭
std::error_code ec;
socket_->shutdown(asio::ip::tcp::socket::shutdown_both, ec);
std::error_code ec0;
socket_->close(ec0);
socket_is_open_ = false;
is_writing_ = false;
cancel_read_time();
cancel_write_time();
//ping_pong_timer_->cancel();
websocket_event_manager.remove(nonstd::string_view(socket_uid_.data(), socket_uid_.size()));
}
private:
std::unique_ptr<asio::ip::tcp::socket> socket_;
websocket_event_map& websocket_event_manager;
std::string socket_uid_;
std::vector<unsigned char> buffers_;
unsigned char frame[10] = {0};
frame_info frame_info_;
std::size_t read_pos_ = 0;
std::size_t data_current_pos_ = 0;
std::string message_;
std::string const url_;
//std::queue<std::unique_ptr<std::string>> write_frame_queue_;
std::size_t frame_data_size_ = 65535;//256
//std::time_t ping_pong_time_ = 30 * 60 * 60;
std::time_t wait_read_time_ = 30 * 60;
std::time_t wait_write_time_ = 30 * 60;
std::unique_ptr<asio::steady_timer> wait_read_timer_;
std::unique_ptr<asio::steady_timer> wait_write_timer_;
//std::unique_ptr<asio::steady_timer> ping_pong_timer_;
unsigned char message_opcode = 0;
std::atomic_bool socket_is_open_{ false };
std::atomic_bool is_writing_{ false };
std::map<std::string, nonstd::any> user_data_;
std::map<std::string, std::string> decode_url_params_;
};
class websocket_hub {
friend class http_router;
public:
static websocket_hub& get() {
static websocket_hub instance;
return instance;
}
public:
void add(send_message const& message) {
std::unique_lock<std::mutex> lock(list_mutex_);
message_list_.emplace_back(message);
lock.unlock();
condtion_.notify_all();
}
private:
void write_ok(std::shared_ptr<websocket> const& websocket) const {
websocket->is_writing_ = false;
}
void close_socket(std::shared_ptr<websocket> const& websocket) const {
websocket->close();
}
private:
void write_frame(std::shared_ptr<websocket> const& websocket, std::shared_ptr<std::queue<std::shared_ptr<std::string>>> const& frame_queue, std::shared_ptr<std::function<void(bool, std::error_code)>> const& call_back) const {
if (frame_queue->empty() || !websocket->is_open()) {
write_ok(websocket);
if (call_back != nullptr && *call_back != nullptr) {
(*call_back)(true, std::error_code{});
}
return;
}
auto a_frame = frame_queue->front();
frame_queue->pop();
auto buff = asio::buffer(a_frame->data(), a_frame->size());
websocket->start_write_timeout();
asio::async_write(*websocket->socket_, buff, [websocket, a_frame, frame_queue, this, call_back](std::error_code const& ec, std::size_t size) {
websocket->cancel_write_time();
if (ec) {
close_socket(websocket);
if (call_back != nullptr && *call_back != nullptr) {
(*call_back)(false, ec);
}
return;
}
write_frame(websocket, frame_queue, call_back);
});
}
private:
void send() {
while (true) {
std::unique_lock<std::mutex> lock(list_mutex_);
condtion_.wait(lock, [this]() {
return message_list_.empty() == false;
});
if (end_thread_ == true) {
return;
}
auto one = message_list_.front();
message_list_.pop_front();
auto websocket = one.websocket_;
auto message = one.message_queue;
auto write_callback = one.write_callback;
if (websocket->socket_is_open_ == true && websocket->is_writing_ == false) {
websocket->is_writing_ = true;
write_frame(websocket, message, write_callback);
}
else if (websocket->socket_is_open_ == true && websocket->is_writing_ == true) {
message_list_.push_back(one);
}
}
}
private:
websocket_hub() = default;
private:
std::mutex list_mutex_;
std::condition_variable condtion_;
std::list<send_message> message_list_;
std::atomic_bool end_thread_{ false };
};
inline void send_to_hub(send_message const& message) {
websocket_hub::get().add(message);
}
template<typename T>
void close_ws(websocket& ws)
{
ws.null_close();
}
void close_ws_with_notification(websocket& ws) {
ws.close();
}
class websockets final :private nocopyable
{
friend class connection;
public:
using event_reg_func = std::function<void(websocket&)>;
public:
std::shared_ptr<websocket> start_webscoket(std::string const& url) { //有多线程竞争
auto ws = std::make_shared<websocket>(websocket_event_map_, url);
ws->set_check_alive_time(websocket_check_read_alive_time_);
ws->set_check_write_alive_time(websocket_check_write_time_);
ws->set_frame_data_size(frame_data_size_);
auto& uuid = ws->uuid();
websocket_event_map_.add(nonstd::string_view{ uuid.data(),uuid.size() }, ws);
return ws;
}
void add_event(std::string const& url, websocket_event const& websocket_event_) {//注册事件 没有多线程竞争
websocket_event_map_.events_.insert(std::make_pair(url, websocket_event_));
}
public:
void set_check_read_alive_time(std::time_t seconds) {
if (seconds <= 0) {
return;
}
websocket_check_read_alive_time_ = seconds;
}
std::time_t get_check_read_alive_time() {
return websocket_check_read_alive_time_;
}
void set_check_write_alive_time(std::time_t seconds) {
if (seconds <= 0) {
return;
}
websocket_check_write_time_ = seconds;
}
std::time_t get_check_write_alive_time() {
return websocket_check_write_time_;
}
void set_frame_data_size(std::size_t size) {
if (size <= 0) {
return;
}
frame_data_size_ = size;
}
std::size_t get_frame_data_size() {
return frame_data_size_;
}
private:
bool is_websocket(request& req) {
using namespace nonstd::string_view_literals;
if (req.method() != "GET"_sv) {
return false;
}
auto connection = req.header("connection");
if (connection.empty() && to_lower(view2str(connection)) != "upgrade") {
return false;
}
auto upgrade = req.header("upgrade");
if (upgrade.empty() && to_lower(view2str(upgrade)) != "websocket") {
return false;
}
auto sec_webSocket_key = req.header("Sec-WebSocket-Key");
if (sec_webSocket_key.empty()) {
return false;
}
auto sec_websocket_version = req.header("Sec-WebSocket-Version");
if (sec_websocket_version.empty()) {
return false;
}
sec_webSocket_key_ = sec_webSocket_key;
sec_websocket_version_ = sec_websocket_version;
return true;
}
void update_to_websocket(response& res) {
res.add_header("Connection", "Upgrade");
res.add_header("Upgrade", "websocket");
auto str = view2str(sec_webSocket_key_) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
auto result = to_base64(to_sha1(str));
res.add_header("Sec-WebSocket-Accept", result);
res.add_header("Sec-WebSocket-Version", view2str(sec_websocket_version_));
res.write_state(http_status::switching_protocols);
}
private:
nonstd::string_view sec_webSocket_key_;
nonstd::string_view sec_websocket_version_;
websocket_event_map websocket_event_map_;
std::time_t websocket_check_read_alive_time_ = 30*60;
std::time_t websocket_check_write_time_ = 30 * 60;
std::size_t frame_data_size_ = 65535;
};
}
| 32.448768 | 227 | 0.668159 | maxbad |
16b1833fa1a5d42acbcb2c846a8534b955b81048 | 8,990 | cpp | C++ | test/webrtc/DslSoupServerMgrUnitTest.cpp | canamex-tech/on-target | 1767bd19aaea7ece75e72626038cd7382a103aba | [
"MIT"
] | 74 | 2021-03-02T07:52:34.000Z | 2022-03-28T04:29:19.000Z | test/webrtc/DslSoupServerMgrUnitTest.cpp | canamex-tech/on-target | 1767bd19aaea7ece75e72626038cd7382a103aba | [
"MIT"
] | 188 | 2021-02-24T19:48:32.000Z | 2022-03-23T22:58:33.000Z | test/webrtc/DslSoupServerMgrUnitTest.cpp | canamex-tech/on-target | 1767bd19aaea7ece75e72626038cd7382a103aba | [
"MIT"
] | 12 | 2021-03-03T00:05:18.000Z | 2022-03-16T06:13:06.000Z | /*
The MIT License
Copyright (c) 2021, Prominence AI, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in-
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "catch.hpp"
#include "Dsl.h"
#include <glib/gstdio.h>
#include <gtypes.h>
#include "DslSoupServerMgr.h"
using namespace DSL;
SCENARIO( "A Signaling Transceiver is created correctly", "[SoupServerMgr]" )
{
GIVEN( "Attribute for a new Client Reciever" )
{
WHEN( "The Signaling Transceiver is created" )
{
std::unique_ptr<SignalingTransceiver> pSignalingTransceiver=
std::unique_ptr<SignalingTransceiver>(new SignalingTransceiver());
THEN( "All attributes are setup correctly" )
{
REQUIRE( pSignalingTransceiver->GetConnection() == NULL);
}
}
}
}
SCENARIO( "A Soup Server Manager can listen on and disconnect from a specific port number", "[SoupServerMgr]" )
{
GIVEN( "A the Soup Server manager" )
{
uint initialPortNumber(99);
REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false );
REQUIRE( initialPortNumber == 0 );
WHEN( "The Soup Server Manager starts listening on a specified port" )
{
uint newPortNumber(DSL_WEBSOCKET_SERVER_DEFAULT_WEBSOCKET_PORT);
uint retPortNumber(0);
REQUIRE( SoupServerMgr::GetMgr()->StartListening(newPortNumber) == true );
REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&retPortNumber) == true );
REQUIRE( retPortNumber == newPortNumber );
// Second call to start when already listening must fail
REQUIRE( SoupServerMgr::GetMgr()->StartListening(newPortNumber) == false );
THEN( "The Soup Server Manager can stop listening successfully." )
{
REQUIRE( SoupServerMgr::GetMgr()->StopListening() == true );
// Second call with the same Signaling Transceiver must fail
REQUIRE( SoupServerMgr::GetMgr()->StopListening() == false );
REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false );
REQUIRE( initialPortNumber == 0 );
}
}
}
}
SCENARIO( "A Soup Server Manager can add and listen for a new URI", "[SoupServerMgr]" )
{
GIVEN( "A the Soup Server manager" )
{
uint initialPortNumber(99);
REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false );
REQUIRE( initialPortNumber == 0 );
WHEN( "A new URI is added to the Soup Server Manager" )
{
std::string newPath("/ws/new_path");
REQUIRE( SoupServerMgr::GetMgr()->AddPath(newPath.c_str()) == true );
THEN( "The Soup Server Manager starts and stops listening correctly." )
{
uint newPortNumber(DSL_WEBSOCKET_SERVER_DEFAULT_WEBSOCKET_PORT);
uint retPortNumber(0);
REQUIRE( SoupServerMgr::GetMgr()->StartListening(newPortNumber) == true );
REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&retPortNumber) == true );
REQUIRE( retPortNumber == newPortNumber );
REQUIRE( SoupServerMgr::GetMgr()->StopListening() == true );
REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false );
REQUIRE( initialPortNumber == 0 );
}
}
}
}
SCENARIO( "A Signaling Transceiver can be added and removed ", "[SoupServerMgr]" )
{
GIVEN( "A new Client Reciever" )
{
std::unique_ptr<SignalingTransceiver> pSignalingTransceiver=
std::unique_ptr<SignalingTransceiver>(new SignalingTransceiver());
WHEN( "The Signaling Transceiver is added the Soup Server Manager" )
{
// First call initializes the singlton, if not called already
REQUIRE( SoupServerMgr::GetMgr()->AddSignalingTransceiver(pSignalingTransceiver.get()) == true);
// Second call with the same Signaling Transceiver must fail
REQUIRE( SoupServerMgr::GetMgr()->AddSignalingTransceiver(pSignalingTransceiver.get()) == false);
THEN( "The same Signaling Transceiver can be removed" )
{
REQUIRE( SoupServerMgr::GetMgr()->RemoveSignalingTransceiver(pSignalingTransceiver.get()) == true);
// Second call with the same Signaling Transceiver must fail
REQUIRE( SoupServerMgr::GetMgr()->RemoveSignalingTransceiver(pSignalingTransceiver.get()) == false);
}
}
}
}
SCENARIO( "A Connection event after removing the only client is handled correctly", "[SoupServerMgr]" )
{
GIVEN( "A new Client Reciever" )
{
std::unique_ptr<SignalingTransceiver> pSignalingTransceiver=
std::unique_ptr<SignalingTransceiver>(new SignalingTransceiver());
std::string pathString("ws");
WHEN( "The Signaling Transceiver is added the Soup Server Manager" )
{
// First call initializes the singlton
REQUIRE( SoupServerMgr::GetMgr()->AddSignalingTransceiver(pSignalingTransceiver.get()) == true);
// Remove the client reciever leaving the Soup Server without a client.
REQUIRE( SoupServerMgr::GetMgr()->RemoveSignalingTransceiver(pSignalingTransceiver.get()) == true);
THEN( "When a new connection is simulated" )
{
SoupWebsocketConnection connection;
SoupServerMgr::GetMgr()->HandleOpen(&connection, pathString.c_str());
}
}
}
}
static void websocket_server_client_listener_1(const wchar_t* path,
void* client_data)
{
std::cout << "Websocket client listener 1\n";
}
static void websocket_server_client_listener_2(const wchar_t* path,
void* client_data)
{
std::cout << "Websocket client listener 2\n";
}
SCENARIO( "A Websocket client listener can be added and removed from the Soup Server Manger", "[SoupServerMgr]" )
{
GIVEN( "The Soup Server Manger" )
{
WHEN( "The client listener is added to the Soup Server Manager" )
{
// First call initializes the singlton, if not called previously by other test cases.
REQUIRE( SoupServerMgr::GetMgr()->AddClientListener(
websocket_server_client_listener_1, NULL) == true );
// Second call with the same Signaling Transceiver must fail
REQUIRE( SoupServerMgr::GetMgr()->AddClientListener(
websocket_server_client_listener_1, NULL) == false );
THEN( "The same Signaling Transceiver can be removed" )
{
REQUIRE( SoupServerMgr::GetMgr()->RemoveClientListener(
websocket_server_client_listener_1) == true );
// Second call with the same Signaling Transceiver must fail
REQUIRE( SoupServerMgr::GetMgr()->RemoveClientListener(
websocket_server_client_listener_1) == false );
}
}
}
}
SCENARIO( "A Connection event results in the Soup Server client listener to be called", "[SoupServerMgr]" )
{
GIVEN( "A new Client Reciever" )
{
std::string pathString("ws");
// First call initializes the singlton, if not called previously by other test cases.
REQUIRE( SoupServerMgr::GetMgr()->AddClientListener(
websocket_server_client_listener_1, NULL) == true );
REQUIRE( SoupServerMgr::GetMgr()->AddClientListener(
websocket_server_client_listener_2, NULL) == true );
WHEN( "When a new socket open event occurrs" )
{
SoupWebsocketConnection connection;
SoupServerMgr::GetMgr()->HandleOpen(&connection, pathString.c_str());
THEN( "Both client listners are called " )
{
// Note: requires visual confirmation of console statements
}
}
}
}
| 39.429825 | 116 | 0.646385 | canamex-tech |
16b1e4f65ab640f5853a1f2350b8fc4edc13ca4c | 11,145 | cpp | C++ | data/602.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/602.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/602.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | int iN, aW, N/*hA*/
,AK8,
Vi0 ,
QCmew, bs,iio1,El
, A3
, bZV
,
BTJ61W
,cAgH2,uL
,
VWN,lsQZ/*K4*/ , nKtYm,/*7R9d*/
HRZ
,tBMY,
ohG
,
cgGKP,xbFv, BBi
, gR ,//j9l
Ek, OD1 ,S6A//Ma
, tvG,Gy, b , tylWc
,/*g*/ wby,gUK,BMc ,
r3,zHKSm ,jL ,Jivf ,
Zcr ,ehp
,LG,
Ue,fly;void f_f0()//vtg
{int n5kter ; volatile int
UuR , fc4IA, vSA
,
HGn ,
//
dTr ,
IQ5, taB ;{volatile int J,FPq, Q
, b9qB
,
OC
, Bu/*a*/;if
/*A*/(
true )
fly=
Bu
+ J
+ FPq/*Yyad*/+
Q +
b9qB+OC
;else
{
int D3//N8i
; volatile int dBTo//
,Xf0
,SaN
,
Dw;return ;//W
{ {{} {
}
}} {volatile int I, Ry; {}
iN =
Ry + I
;/*c*/}for (int /*y*/
i=1;
i< 1 ;++i
){volatile int
CP2
, BX,Zpg,VgFCPuF, eT //Udf
,XJNti; /*eR6*/aW=XJNti //G
+
CP2 +BX
;for(int i=1
;
i<2 ;++i )N =
Zpg+
VgFCPuF
+eT
;
} D3= Dw + dBTo + Xf0 +SaN;/*5*/{{ return ; }}}; if /*iAd*/(true){
volatile int Xs ,T,
P9la
,O ;if(
true) for(int
i=1
;
i< 3;++i)/*t*/{int PAi;volatile int
QHf6,P5x,
qF;PAi= qF+//
QHf6+
P5x
//J
;{volatile int cUVO,qM;
AK8=/*N0P*/ qM +
cUVO ;}for (int i=1;i<4;++i) return ;
{ } }
else{
volatile int fjlLC /*pI*/, TX ; Vi0=TX +fjlLC//DAUF
;
}; {{ }}QCmew
=O
+Xs
+
T +P9la;}else
{int s;
volatile int df,
V
,
Lwiv
,CBu ;
s=CBu
+ df + V
+Lwiv ;for
(int i=1
; //YZ
i< 5;++i)/*1*/return//YK
;{int o7 ; volatile int K //Kg
, jX;; o7 = /*RGu*/jX + K ; } }
}n5kter=taB
+UuR
+fc4IA +
vSA
+HGn+dTr+IQ5 ; return
; for (int
i=1;
i<6
;++i )for (int i=1;i< //ci
7 ;++i
){ volatile int
JO1f,IXqn6, Lu ,oRMf, BYJG;; if//Q4G
( true
)return ;
else bs =BYJG+
JO1f//cw
+
IXqn6+
Lu+oRMf ;
{ { { {
}{}}};//231S
} return
;{
for
(int i=1 ;i<
8
;++i) return ;
{
{//GS
;
} }
{return ;;
{ {
}}} {/**/;return/*x*/ ;
} }{int i8O;volatile int CCFF,ft6S9,fDzsV//x
,uaPIH; return//ZA
;
return ; i8O =uaPIH
+CCFF + ft6S9//j
//Xq
+fDzsV ; } } /*0aG*/
return ;}void f_f1 (){volatile int
Wzx
,
erI5J ,bCD
,
LX/*J*/ ,C , u, Mu ; { { volatile int
/*n*/ U8GU ,
gj
,
h,uC ;
;iio1= uC+ U8GU+gj+
h ; {
{ };for (int
i=1;i<9
;++i )
{ }
} } ; return ;} for(int i=1 /*dwW76*/;i< 10 ;++i
)
{ int/*Y*/ D7
;//29P
volatile int Do ,
DVd ,
TB,/*fBpR*///
/*VF*/ VJB,
cxtax ,deh , VT//M3
,B
,
Qq80
; if(
true)
if(true
)
D7 =Qq80
+ Do +
DVd +TB + VJB ; else{volatile int hBr,
Ry2 ,
hmC3
,M ;/*X*/{return ;}El=M
+
hBr+/*h7pI*/Ry2 +
hmC3;
//5jxQ
{{{}}for(int i=1 ; i<11 ;++i
){
{ }}
} ;
}else A3 /*S*/= cxtax+ deh+ VT/**//*Ao*/+
B
;
{ { return ;
{
;}{
{ };{//Csa
} }} { ;//j
}
}return/**/ ;/*Hzi*/ if
( true) /*4O*/return ; else
{
return ; return ;{{
{
}/**/}{/*8bX*/for(int
i=1/*K1*/ ;i<
12;++i) for (int
i=1
; i<13 ;++i)return ;
} { }
}return ;}}
for(int i=1 ; i<
14 ;++i ) { int tL ; volatile int//Yys
NvW
,a/**/ ,
iIPf , VY
,p ,//dkiH
Oc ;/*FZRx*/ {
volatile int/*1L*/ IhM
,
wcEy ,A3a
, gjjl
; ; bZV
= gjjl+
IhM+
wcEy +
A3a ; {
int xeolf;volatile int Y ,DdPJDs,cfl//w
,PvoQG/*yU*/;
{};return ;xeolf=
PvoQG+
Y+
DdPJDs
//D8P
+ cfl ;
}
} tL/*U*/=Oc
/*tR*/+NvW +a
+ iIPf+
//6y16
VY+p;if/*N5CI*/(/*s2gki*/true )
{ int
rS ;
volatile int
fi4,RGBPw8, re18
, cxD
;rS =
cxD + fi4
+ RGBPw8+ re18;{
return//xlF
;}} else{ /*iBU4HzeB*/{for
(int i=1;/*r5j*/i<
15 ;++i) {}{}}for(int i=1; i<16 ;++i//NFzwR
)
{ {volatile int cr
;
for (int i=1;
i< 17 ;++i )//qfW
/*2I*/{
} BTJ61W=cr
; }
;{ { }
} }{ { /*xTS*/{
}if(
true );else{ //rjg
} }} }{
volatile int lI,iRj
,Qr ,/*8D*/ VctV ;{int
IE1IB ; volatile int
eurp,j,
gx3,
u5O7B ;/*e*/
for(int i=1 ;i<
18 ;++i )if(
true) cAgH2= u5O7B+ eurp; else//7
{ }//Jo
if(
true //h2tyM
)IE1IB=
j+gx3 ;else if (true/*9*/)for
(int i=1
; i< 19;++i )
{
}/*UYP*/ else{ { //aU
}for
(int i=1 ; i<20;++i
) ;
} {/*g*/{//Hh
}}} for(int
i=1
;i<21 ;++i)/*ao*/if (true/*SN*/
)uL = VctV/*UaJc*/
+ lI
+iRj+Qr ;else{ { { for (int i=1 ;/*T*//*i*/i<22
;++i )
;}}
}//T
}}
{;{{{ {
}} }
;
} { int ln123 ;volatile int//q
oaq0
,KX
,ORYNf,W ;
for(int
i=1; i<
23 /*qW7*/;++i )
{int vo ;volatile int n ,FIFGT2;for //Amt
(int
i=1; i<24
;++i){}//RYo
vo
= FIFGT2//h
+n ;}ln123
=W+ oaq0+//w7
KX+
ORYNf
;} {return ;
;//q
}{/*wzy6*/ {int TU;
volatile int g2,//Lf1q
BE ,//H
qiH,j4,je8n ;for
(int i=1;//BUy
i< 25 ;++i
//GT
)
{ }//
TU= je8n+
g2
+
BE +qiH + /*PrLU*/ j4
; }return
;{{
volatile int/*qR1*/
DK
;VWN =
DK; }}
if( true){
{ for
(int i=1 ; i<26
;++i
)
{ volatile int kO ;lsQZ=kO
;return ;} }} else{if(
true
)
{ }else//Yh
{
}//WN2u
{}}//g
;
} }
nKtYm=Mu +Wzx+erI5J +bCD +LX+C+u ;{int WGbb;
volatile int VRFK,WS ,//t
xc
,GFx, Dtcq ;WGbb//YIz
//fZ
=//B
Dtcq
+VRFK//
+WS//Qh
+ xc+GFx ;
return ;/*E3t*/
return ; { volatile int RrX,//iQt
LIqLnz, Yf
;
for(int i=1;
i< 27 ;++i)HRZ =Yf+ RrX +LIqLnz ;;if( true)for(int i=1 ;
i<
28;++i)
{
return ; return ; }else ;}
{ /*uj5*/ { return ;} {volatile int A
, c5/*m*/;if(
true) if
( true
){
{}} else tBMY=c5 +
A /*E*/
;else{ }for
(int
i=1 ; i<
29;++i/*vk*/)
;/*r*/
;};
}{ int
Pd;
volatile int
//JZ
M5bGt ,kDR18U, /*fGp*/
kVH , /*Vl*/ TG
, yla, eAZ;{ { ;} {
int
g38
;volatile int mLYH
,z9B
;
;for(int i=1;
i<30;++i ) if(
true//ID
)/*f4Wr*/if ( true)
{} else
for (int
i=1;i<31 ;++i
)
g38= z9B//6
//
+ mLYH/*5n*/
;
else//
{
}}{ {}{} }}if
(true
) Pd=eAZ+ M5bGt+ kDR18U
;
else
ohG
=kVH +
TG + yla ;} } return ; return ;
}void f_f2() {int
ggsq ;//IPv
volatile int iW8 ,
fC ,
lF9 ,//HZ
ZgT ,ACJ
,
lt3lf//
,id , spd,
BaV4
, Gk ,//62eyaw
gOp, U,
ibD
;
/*0cC*/if (true
/*U7*/) ; else
;cgGKP
=ibD
+
iW8 + fC+ lF9+ZgT + ACJ;ggsq =
lt3lf+//kF
id + spd /*W*/+
BaV4 + Gk +gOp
+U ;;
{{int wV3A
;
volatile int v
,tw
,
Qv1Gj,N6u0
,//p4prhZ
WyD/*g*//*XYc*/; wV3A=WyD +v
+tw +//BAux2
Qv1Gj + N6u0 ;{volatile int IxZX , JPtW,/**/mo
; xbFv
=
mo +IxZX+
JPtW
;
for
(int
i=1
;
//Y24
i<32
;++i
)
{ }if(true)
return ; else for(int i=1;i< 33
;++i) {}} {
{}}
} { ;
{/*GQR*/ return
;
/*E8qy*/ } }{ volatile int /**/ Xq /*6gq7*/
,cG,S ,
tHty;
BBi=/*bxDQ*///rRPPt
tHty
+Xq+
cG
+S ;;for//Rg2nZ
(int
i=1;i<34;++i ){ ;
{
}
{
{}
}}} }return/*MXq*/ ;
} int main() { {volatile int uI , eC
,Up,K0R2
,//UWUM
EPCm//u8p
;{
volatile int WThA
,
bBC ,X21
;for (int //ec
i=1 ;
i<
35 ;++i )/*Q8b*//*c*/if
(true) {/*dv*/int CFl;volatile int Hl
,/**/ wDq ;
CFl//XK5
= wDq/*n*/ +
Hl; }else{ {
} {
int
Njh ;volatile int l3W
;
for(int i=1 ; i<36/*dSj*/;++i ) if(true
){
{}for
(int i=1 ;
i< 37 ;++i
)/*rV*/{
}}//N
else for (int i=1 ;
i<
//wG
38
;++i ){}Njh= l3W
;return 1459539307; }} if (true)//zd
{ {{ }{ ; }}} else
gR
= X21 + WThA+bBC ;
;
}if ( true/**/) { return 450129796
; { int iJGW4
;volatile int EIi
,
CELl ,
cH3t, ebh ,mHL,//S
lgbJF ; for
(int
i=1 ;
i<39 ;++i)Ek= lgbJF +/*qD*/EIi+ CELl;
iJGW4 =cH3t
+ebh +mHL/**/;}{ volatile int Ekwc
, q;
{{} return//WUCIv
77365647;
//fCo
} OD1=q+//8
Ekwc; }{/*IGp*/{
; }} if //ROoq
(/*7*/ true )for (int i=1 ;//2
i<
40//6cY
;++i
)
return 966886858
;
else return 61553154 ;{{{
}{
return 254619342
;}}}for(int
i=1; i< 41/*PK1Hs*/;++i
) ;} else{
int
h5di/*Ti*/;volatile int ka//FF
,Zc8R /*68PHtN*/,XGro; {volatile int
GJ2,tbnaB//Bf
;
S6A= tbnaB+
/*gVNJv*/GJ2
;//Ko
if(true/*pGa6*//*W*/
); else{return 1301871030
;
}
} /*ZVe*/for (int
/*7O*/i=1;i<
42 ;++i//v
)if(true/*CKR*/ )
if(true )h5di=XGro
+/*o*/ka
+Zc8R
;
else return 501854691 ;else /*BaNt*/{for //
(int /*S*/i=1;i<
43;++i ){if ( true) return //cq
834040775/*94OMC*/; else{
{}} { { if(
true){} else {
}} }/*dTu*/ } { ; ;
}//F
}; /*X*/}
tvG =EPCm+ uI+ eC +Up +
/*Q*/K0R2;; }return 493153421
;
{ { {/*oIE*/{
if(true){ } else //pmx
{
}/*OfV*/ //2W
}{ ; } }
//t
for//Pfe
(int i=1
;i<44/*M*/;++i
) { volatile int qC2 ,X7, jYR
, sm ,F9VH/*Tp*/
;Gy
= F9VH+qC2
; { {
}
;
}
b =
X7+jYR+ sm/*YqhC*/;/*qV*/}
{
{
{}
}
{ }} ;
} /*Im*/{{volatile int tws, Uf,PrHRv;{{}/*g*/}
;
tylWc=PrHRv + tws
+/*Gycm*/Uf; } {
;
if(true )//D48
{ int
QB;//Aw
volatile int eL3,
Xp;
return 1486057255;
{//
} { }
return
724636532 ; QB =Xp
+ eL3; } else
{
volatile int dp/*LW*/ , GjQWFe/*Qp*/
;wby=
GjQWFe+dp
; }}return 1870620381 ;
}
if (true){ for
(int i=1 ;i<45
;++i
) //h
;{
{/*TD*/ {return 307491052 ;/*SoA*/} } {
} } for
(int
i=1
;i<46;++i
)
{
{
}
{ volatile int d
,FW ;
gUK
=FW
+
d ;
{
int OJD;
volatile int
c
;
; if (true
){} else for(int i=1 ; i<
47
;++i//cAs
)
OJD =c
;}}}if(true)if (
true )
{int keT ;volatile int uJ,
//9e
hw,x,xm ;
{{} } { ;//JwS
{{}; } }for(int //L
i=1 ; i<48
;++i)/*S*/keT=xm+/*jt*/ uJ+hw
+x
;
{volatile int Czf//9CtW
,
//J
PQJ
;
BMc=PQJ
+ Czf
; }}else {
volatile int nC5 ,
l
,UXFnU ;
if
(true) {int xNS;volatile int q3 , tlG,
DRX;xNS
= DRX
+q3 +tlG/*2V*/
;
}
else {;
}r3
//dL
= UXFnU +nC5+ l ;
}else
for (int i=1 ;i< 49 ;++i ){{ }
{volatile int vDrLW,Ag//T
, Lmf ;zHKSm=Lmf +vDrLW +Ag
;
}}}//6A
else { for /*3r8*/(int i=1/*d*/;i< 50;++i )
{ for
(int i=1
; i< 51 ;++i );} return 26605759
;{if/**/
(
true
){ int D6S ;volatile int s2J, Nd; D6S =
Nd+ s2J ;/*eRQ4*/} else {
{}} {}
/*QSFr*/{/*pf*/{
}//OSkg
/*V3H*/}}} } {int irM6
; volatile int
QO
,
vLi3 ,TwH,
w, dMZ7o/*mN0*/;
{ {//KvK
int//
WL ;
volatile int
tAl,cT, bTy;
{{} return 1839056157;}
{ /**/}WL = bTy
+tAl +cT ;}for(int i=1
; i<52 ;++i ) { {} //eI
{for(int
i=1 ;
i< 53 ;++i){ for(int
/*D*/i=1
; i<
54
;++i)
{}
} for
(int /*bR*/i=1 ; i<55;++i //9y
/**/)
{}
}} {
//N3j
if( true) {}/*JT*/ else{ }
return 699596162
;{ volatile int //Ot
qTjy/**/,S9v ,FsT , lh;
jL
= lh
+qTjy ; if
(true){/*vZ*/}
else for (int i=1 ;
i<
56;++i
) Jivf//g3qjW
=S9v + FsT
;
}{
{}{
}} }}; irM6
= dMZ7o +
QO+ vLi3+TwH+ w
; }
{int R ;/*63*/volatile int Z ,/*z8*/
b9G,wR0
, kV, Gg9O
;
/**/if(
/*UaN*/ true) {volatile int jpR /**/ ,CqK,
PMxc,/*ncX*/ Ow ;
{ { {for (int
i=1;
i<
57 ;++i){ } }} {
if( true)
{}
else {}
}}
Zcr=Ow
+
jpR +
CqK + PMxc
; } else for (int i=1;i<58;++i )R //a
= Gg9O +Z
+
b9G +
wR0
//ZYO
+kV ; {{ ;} //c0
for(int i=1;i<
59
;++i )
{ for
(int /*DS*/i=1 ;
i<
//m
60 ;++i
);
;//MM
}}//
for(int i=1 ;i< 61/**/;++i
);
{ if (
true)for//G6
(int i=1;
i<
62;++i
/*Vt*/) {{int aP7
;volatile int yXuqh ,fg3;
{ }
; {
{} }aP7
= fg3+yXuqh; }{if/*cddz*/ (
true); else for //M6vE
(int
i=1 ;i<
63;++i
){{ }}
} }else //I
{ volatile int upr
,vx,
n7w
/*PfXG*/ ,
eve,r ;if(true
)if
( //V
true
) {{} }
else ehp=
r+
upr +
vx ; else LG
=
n7w+eve ;{}}
if ( true)/*2mtV*/{ {
return
1669666163 ;
//ZSt
} } else
{ volatile int ZO,
SLUs ;/*asJ*/
//
if
( true
)Ue
//vB
=SLUs+ ZO; else if (true//uI
);
else ;}};if (true) {for(int
i=1 ;i< 64 ;++i) {return
231352685 //2
;//rj0sm
}//q
{
{/*4*/
}
}}else return 1008721898 ; }
} | 11.012846 | 74 | 0.468282 | TianyiChen |
16b3d3d98a1f5b073b4cd0a5b35557da2e9886d3 | 3,054 | cxx | C++ | Modules/Filtering/ImageGrid/test/itkCropImageFilterTest.cxx | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2020-10-09T18:12:53.000Z | 2020-10-09T18:12:53.000Z | Modules/Filtering/ImageGrid/test/itkCropImageFilterTest.cxx | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2018-10-18T18:49:19.000Z | 2018-10-18T18:49:19.000Z | Modules/Filtering/ImageGrid/test/itkCropImageFilterTest.cxx | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2017-08-18T19:07:39.000Z | 2017-08-18T19:07:39.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkCropImageFilter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkTestingMacros.h"
int itkCropImageFilterTest( int, char* [] )
{
// Define the dimension of the images
constexpr unsigned int ImageDimension = 2;
// Declare the pixel types of the images
using PixelType = short;
// Declare the types of the images
using ImageType = itk::Image< PixelType, ImageDimension >;
ImageType::Pointer inputImage = ImageType::New();
// Fill in the image
ImageType::IndexType index = {{0, 0}};
ImageType::SizeType size = {{8, 12}};
ImageType::RegionType region;
region.SetSize( size );
region.SetIndex( index );
inputImage->SetLargestPossibleRegion( region );
inputImage->SetBufferedRegion( region );
inputImage->Allocate();
itk::ImageRegionIterator< ImageType > iterator( inputImage, region );
short i = 0;
for(; !iterator.IsAtEnd(); ++iterator, ++i)
{
iterator.Set( i );
}
// Create the filter
itk::CropImageFilter< ImageType, ImageType >::Pointer cropFilter =
itk::CropImageFilter< ImageType, ImageType >::New();
EXERCISE_BASIC_OBJECT_METHODS( cropFilter, CropImageFilter,
ExtractImageFilter );
itk::SimpleFilterWatcher watcher( cropFilter );
cropFilter->SetInput( inputImage );
ImageType::RegionType requestedRegion;
ImageType::SizeType extractSize = {{8, 12}};
extractSize[0] = 1;
extractSize[1] = 1;
cropFilter->SetBoundaryCropSize( extractSize );
cropFilter->SetUpperBoundaryCropSize( extractSize );
TEST_SET_GET_VALUE( extractSize, cropFilter->GetUpperBoundaryCropSize() );
cropFilter->SetLowerBoundaryCropSize( extractSize );
TEST_SET_GET_VALUE( extractSize, cropFilter->GetLowerBoundaryCropSize() );
cropFilter->UpdateLargestPossibleRegion();
requestedRegion = cropFilter->GetOutput()->GetRequestedRegion();
if( cropFilter->GetOutput()->GetLargestPossibleRegion().GetSize()[0] != 6
|| cropFilter->GetOutput()->GetLargestPossibleRegion().GetSize()[1] != 10 )
{
return EXIT_FAILURE;
}
if( cropFilter->GetOutput()->GetLargestPossibleRegion().GetIndex()[0] != 1
|| cropFilter->GetOutput()->GetLargestPossibleRegion().GetIndex()[1] != 1 )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 30.54 | 81 | 0.6778 | floryst |
16b3de198f420eac4de10003a2c8175f56163923 | 6,897 | cpp | C++ | src/Cello/control_refresh.cpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 26 | 2019-02-12T19:39:13.000Z | 2022-03-31T01:52:29.000Z | src/Cello/control_refresh.cpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 128 | 2019-02-13T20:22:30.000Z | 2022-03-29T20:21:00.000Z | src/Cello/control_refresh.cpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 29 | 2019-02-12T19:37:51.000Z | 2022-03-14T14:02:45.000Z | // See LICENSE_CELLO file for license and copyright information
/// @file control_refresh.cpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2013-04-26
/// @brief Charm-related functions associated with refreshing ghost zones
/// @ingroup Control
#include "simulation.hpp"
#include "mesh.hpp"
#include "control.hpp"
#include "charm_simulation.hpp"
#include "charm_mesh.hpp"
// #define DEBUG_REFRESH
#ifdef DEBUG_REFRESH
# define TRACE_REFRESH(msg,REFRESH) \
printf ("%d %s:%d %s TRACE_REFRESH %s type %d\n",CkMyPe(), \
__FILE__,__LINE__,name().c_str(),msg,REFRESH->sync_type()); \
fflush(stdout);
#else
# define TRACE_REFRESH(msg,REFRESH) /* NOTHING */
#endif
//----------------------------------------------------------------------
void Block::refresh_begin_()
{
Refresh * refresh = this->refresh();
TRACE_REFRESH("refresh_begin_()",refresh);
check_leaf_();
check_delete_();
cello::simulation()->set_phase(phase_refresh);
ERROR("refresh_begin_()",
"refresh_begin_ called with NEW_REFRESH");
}
//----------------------------------------------------------------------
void Block::refresh_continue()
{
// Refresh if Refresh object exists and have data
Refresh * refresh = this->refresh();
TRACE_REFRESH("refresh_continue_()",refresh);
if ( refresh && refresh->is_active() ) {
// count self
int count = 1;
// send Field face data
if (refresh->any_fields()) {
count += refresh_load_field_faces_ (refresh);
}
// send Particle face data
if (refresh->any_particles()){
count += refresh_load_particle_faces_ (refresh);
}
// wait for all messages to arrive (including this one)
// before continuing to p_refresh_exit()
ERROR("refresh_continue_()",
"refresh_continue_ called with NEW_REFRESH");
} else {
refresh_exit_();
}
}
//----------------------------------------------------------------------
void Block::p_refresh_store (MsgRefresh * msg)
{
performance_start_(perf_refresh_store);
msg->update(data());
delete msg;
Refresh * refresh = this->refresh();
TRACE_REFRESH("p_refresh_store()",refresh);
ERROR("p_refresh_store()",
"p_refresh_store() called with NEW_REFRESH");
performance_stop_(perf_refresh_store);
performance_start_(perf_refresh_store_sync);
}
//----------------------------------------------------------------------
int Block::refresh_load_field_faces_ (Refresh *refresh)
{
int count = 0;
const int min_face_rank = refresh->min_face_rank();
const int neighbor_type = refresh->neighbor_type();
if (neighbor_type == neighbor_leaf ||
neighbor_type == neighbor_tree) {
// Loop over neighbor leaf Blocks (not necessarily same level)
const int min_level = cello::config()->mesh_min_level;
ItNeighbor it_neighbor =
this->it_neighbor(min_face_rank,index_,
neighbor_type,min_level,refresh->root_level());
int if3[3];
while (it_neighbor.next(if3)) {
Index index_neighbor = it_neighbor.index();
int ic3[3];
it_neighbor.child(ic3);
const int level = this->level();
const int level_face = it_neighbor.face_level();
const int refresh_type =
(level_face == level - 1) ? refresh_coarse :
(level_face == level) ? refresh_same :
(level_face == level + 1) ? refresh_fine : refresh_unknown;
refresh_load_field_face_ (refresh_type,index_neighbor,if3,ic3);
++count;
}
} else if (neighbor_type == neighbor_level) {
// Loop over neighbor Blocks in same level (not necessarily leaves)
ItFace it_face = this->it_face(min_face_rank,index_);
int if3[3];
while (it_face.next(if3)) {
// count all faces if not a leaf, else don't count if face level
// is less than this block's level
if ( ! is_leaf() || face_level(if3) >= level()) {
Index index_face = it_face.index();
int ic3[3] = {0,0,0};
refresh_load_field_face_ (refresh_same,index_face,if3,ic3);
++count;
}
}
}
return count;
}
//----------------------------------------------------------------------
void Block::refresh_load_field_face_
( int refresh_type,
Index index_neighbor,
int if3[3],
int ic3[3])
{
// TRACE_REFRESH("refresh_load_field_face()");
// REFRESH FIELDS
// ... coarse neighbor requires child index of self in parent
if (refresh_type == refresh_coarse) {
index_.child(index_.level(),ic3,ic3+1,ic3+2);
}
// ... copy field ghosts to array using FieldFace object
bool lg3[3] = {false,false,false};
Refresh * refresh = this->refresh();
FieldFace * field_face = create_face
(if3, ic3, lg3, refresh_type, refresh,false);
#ifdef DEBUG_FIELD_FACE
CkPrintf ("%d %s:%d DEBUG_FIELD_FACE creating %p\n",CkMyPe(),__FILE__,__LINE__,field_face);
#endif
DataMsg * data_msg = new DataMsg;
data_msg -> set_field_face (field_face,true);
data_msg -> set_field_data (data()->field_data(),false);
MsgRefresh * msg = new MsgRefresh;
msg->set_data_msg (data_msg);
thisProxy[index_neighbor].p_refresh_store (msg);
}
//----------------------------------------------------------------------
int Block::refresh_load_particle_faces_ (Refresh * refresh)
{
// TRACE_REFRESH("refresh_load_particle_faces()");
const int rank = cello::rank();
const int npa = (rank == 1) ? 4 : ((rank == 2) ? 4*4 : 4*4*4);
ParticleData ** particle_array = new ParticleData *[npa];
ParticleData ** particle_list = new ParticleData *[npa];
std::fill_n(particle_array,npa,nullptr);
std::fill_n(particle_list ,npa,nullptr);
Index * index_list = new Index[npa];
// Sort particles that have left the Block into 4x4x4 array
// corresponding to neighbors
int nl = particle_load_faces_
(npa,particle_list,particle_array, index_list, refresh);
// Send particle data to neighbors
particle_send_(nl,index_list,particle_list);
delete [] particle_array;
delete [] particle_list;
delete [] index_list;
return nl;
}
//----------------------------------------------------------------------
void Block::particle_send_
(int nl,Index index_list[], ParticleData * particle_list[])
{
ParticleDescr * p_descr = cello::particle_descr();
for (int il=0; il<nl; il++) {
Index index = index_list[il];
ParticleData * p_data = particle_list[il];
Particle particle_send (p_descr,p_data);
if (p_data && p_data->num_particles(p_descr)>0) {
DataMsg * data_msg = new DataMsg;
data_msg ->set_particle_data(p_data,true);
MsgRefresh * msg = new MsgRefresh;
msg->set_data_msg (data_msg);
thisProxy[index].p_refresh_store (msg);
} else if (p_data) {
MsgRefresh * msg = new MsgRefresh;
thisProxy[index].p_refresh_store (msg);
// assert ParticleData object exits but has no particles
delete p_data;
}
}
}
| 23.782759 | 93 | 0.623894 | aoife-flood |
16b526a272b533c56ee5bb4e8e746cfc3309cf86 | 28,056 | cpp | C++ | ycsb/YcsbMain.cpp | shenweihai1/veribetrkv-linear | 0e63dc1cc2a24f0ab460e8a905924560e5991644 | [
"MIT"
] | null | null | null | ycsb/YcsbMain.cpp | shenweihai1/veribetrkv-linear | 0e63dc1cc2a24f0ab460e8a905924560e5991644 | [
"MIT"
] | null | null | null | ycsb/YcsbMain.cpp | shenweihai1/veribetrkv-linear | 0e63dc1cc2a24f0ab460e8a905924560e5991644 | [
"MIT"
] | null | null | null | #include <cstdlib>
#ifdef _YCSB_VERIBETRFS
#include "Application.h"
#endif
#include "core_workload.h"
#include "ycsbwrappers.h"
#include "leakfinder.h"
#include "MallocAccounting.h"
#include "hdrhist.hpp"
#ifdef _YCSB_ROCKS
#include "rocksdb/db.h"
#include "rocksdb/table.h"
#include "rocksdb/filter_policy.h"
#endif
#ifdef _YCSB_KYOTO
#include <kchashdb.h>
#endif
#ifdef _YCSB_BERKELEYDB
#include <db_cxx.h>
#include <dbstl_map.h>
#endif
#include <chrono>
#include <iostream>
using namespace std;
using namespace chrono;
template< class C, class D1, class D2 >
void record_duration(HDRHist &hist,
const time_point<C,D1> &begin,
const time_point<C,D2> &end)
{
auto duration = duration_cast<nanoseconds>(end - begin);
hist.add_value(duration.count());
}
void print_summary(HDRHistQuantiles& summary, const string workload_name, const string op) {
if (summary.samples() != 0) {
cout << "--" << "\tlatency_ccdf\top\t" << "quantile" << "\t" << "upper_bound(ns)" << endl;
for (auto summary_el = summary.next();
summary_el.has_value();
summary_el = summary.next()) {
cout << workload_name << "\tlatency_summary\t" << op << "\t"
<< summary_el->quantile << "\t" << summary_el->upper_bound << endl;
}
}
}
void print_ccdf(HDRHistCcdf &ccdf, const string workload_name, const string op) {
optional<CcdfElement> cur = ccdf.next();
while (cur.has_value()) {
cout << workload_name << " latency_ccdf " << op << " "
<< cur->value << " " << cur->fraction << " " << cur->count << endl;
cur = ccdf.next();
}
}
static const vector<pair<ycsbc::Operation, string>> YcsbOperations =
{
make_pair(ycsbc::READ, "read"),
make_pair(ycsbc::UPDATE, "update"),
make_pair(ycsbc::INSERT, "insert"),
make_pair(ycsbc::SCAN, "scan"),
make_pair(ycsbc::READMODIFYWRITE, "readmodifywrite"),
};
template< class DB >
class YcsbExecution {
// Benchmark definition
DB db;
string name;
ycsbc::CoreWorkload& workload;
bool verbose;
int record_count;
int num_ops;
milliseconds max_sync_interval;
int max_sync_interval_ops;
milliseconds progress_report_interval;
// Benchmark results
map<ycsbc::Operation, unique_ptr<HDRHist>> latency_hist;
HDRHist load_insert_latency_hist; // for inserts during load phase
HDRHist sync_latency_hist; // does not include sync at end of load phase
milliseconds load_duration_ms; // includes time to sync at end
milliseconds run_duration_ms; // includes time to sync at end
public:
YcsbExecution(DB db,
string name,
ycsbc::CoreWorkload& workload,
int record_count,
int num_ops,
bool verbose,
int max_sync_interval_ms = 0,
int max_sync_interval_ops = 0,
int progress_report_interval_ms = 1000)
: db(db), name(name), workload(workload),
record_count(record_count), num_ops(num_ops),
verbose(verbose),
max_sync_interval(max_sync_interval_ms),
max_sync_interval_ops(max_sync_interval_ops),
progress_report_interval(progress_report_interval_ms)
{
for (auto op : YcsbOperations) {
latency_hist[op.first] = move(make_unique<HDRHist>());
}
}
inline void performRead() {
malloc_accounting_set_scope("performRead setup");
ycsbcwrappers::TxRead txread = ycsbcwrappers::TransactionRead(workload);
if (!workload.read_all_fields()) {
cerr << db.name << " error: not reading all fields unsupported" << endl;
exit(-1);
}
if (verbose) {
cerr << db.name << " [op] READ " << txread.table << " " << txread.key << " { all fields }" << endl;
}
malloc_accounting_default_scope();
// TODO use the table name?
db.query(txread.key);
}
inline void performInsert(bool load) {
malloc_accounting_set_scope("performInsert setup");
ycsbcwrappers::TxInsert txinsert = ycsbcwrappers::TransactionInsert(workload, load);
if (txinsert.values->size() != 1) {
cerr << db.name << " error: only fieldcount=1 is supported" << endl;
exit(-1);
}
const string& value = (*txinsert.values)[0].second;
if (verbose) {
cerr << db.name << " [op] INSERT " << txinsert.table << " " << txinsert.key << " " << value << endl;
}
malloc_accounting_default_scope();
// TODO use the table name?
db.insert(txinsert.key, value);
}
inline void performUpdate() {
malloc_accounting_set_scope("performUpdate setup");
ycsbcwrappers::TxUpdate txupdate = ycsbcwrappers::TransactionUpdate(workload);
if (!workload.write_all_fields()) {
cerr << db.name << " error: not writing all fields unsupported" << endl;
exit(-1);
}
if (txupdate.values->size() != 1) {
cerr << db.name << " error: only fieldcount=1 is supported" << endl;
exit(-1);
}
const string& value = (*txupdate.values)[0].second;
if (verbose) {
cerr << db.name << " [op] UPDATE " << txupdate.table << " " << txupdate.key << " " << value << endl;
}
malloc_accounting_default_scope();
// TODO use the table name?
db.update(txupdate.key, value);
}
inline void performReadModifyWrite() {
malloc_accounting_set_scope("performReadModifyWrite setup");
ycsbcwrappers::TxUpdate txupdate = ycsbcwrappers::TransactionUpdate(workload);
if (!workload.write_all_fields()) {
cerr << db.name << " error: not writing all fields unsupported" << endl;
exit(-1);
}
if (txupdate.values->size() != 1) {
cerr << db.name << " error: only fieldcount=1 is supported" << endl;
exit(-1);
}
const string& value = (*txupdate.values)[0].second;
if (verbose) {
cerr << db.name << " [op] READMODIFYWRITE " << txupdate.table << " " << txupdate.key << " " << value << endl;
}
malloc_accounting_default_scope();
// TODO use the table name?
db.readmodifywrite(txupdate.key, value);
}
inline void performScan() {
malloc_accounting_set_scope("performScan setup");
ycsbcwrappers::TxScan txscan = ycsbcwrappers::TransactionScan(workload);
if (!workload.write_all_fields()) {
cerr << db.name << " error: not writing all fields unsupported" << endl;
exit(-1);
}
if (verbose) {
cerr << db.name << " [op] SCAN " << txscan.table << " " << txscan.key << " " << txscan.scan_length << endl;
}
malloc_accounting_default_scope();
// TODO use the table name?
db.scan(txscan.key, txscan.scan_length);
}
void Load() {
cout << "[step] " << name << " load start (num ops: " << record_count << ")" << endl;
auto clock_start = steady_clock::now();
auto clock_next_report = clock_start + progress_report_interval;
auto clock_op_started = clock_start;
auto clock_op_completed = clock_start;
for (int i = 0; i < record_count; ++i) {
clock_op_started = steady_clock::now();
performInsert(true /* load */);
clock_op_completed = steady_clock::now();
record_duration(load_insert_latency_hist, clock_op_started, clock_op_completed);
if (clock_next_report < clock_op_completed) {
auto duration_ms = duration_cast<milliseconds>(
clock_op_completed - clock_start).count();
cout << "[step] " << name << " load progress " << duration_ms << " ms " << i << " ops" << endl;
malloc_accounting_status();
clock_next_report = clock_op_completed + progress_report_interval;
}
}
auto duration_ms = duration_cast<milliseconds>(clock_op_completed - clock_start);
cout << "[step] " << name << " load sync " << duration_ms.count() << " ms" << endl;
db.sync(true);
auto clock_end = steady_clock::now();
load_duration_ms = duration_cast<milliseconds>(clock_end - clock_start);
cout << "[step] " << name << " load end " << load_duration_ms.count() << " ms" << endl;
auto load_duration_ns = duration_cast<nanoseconds>(clock_end - clock_start);
assert(load_duration_ns.count() != 0);
double load_duration_s = duration_cast<nanoseconds>(clock_end - clock_start).count() / 1000000000.0;
double throughput = record_count / load_duration_s;
cout << "[step] " << name << " load throughput " << throughput << " ops/sec" << endl;
auto load_insert_summary = load_insert_latency_hist.summary();
auto load_insert_ccdf = load_insert_latency_hist.ccdf();
print_summary(load_insert_summary, name, "load");
print_ccdf(load_insert_ccdf, name, "load");
}
void Run() {
malloc_accounting_set_scope("ycsbRun.setup");
malloc_accounting_default_scope();
auto clock_start = steady_clock::now();
auto next_sync = clock_start + max_sync_interval;
auto next_display = clock_start + progress_report_interval;
int next_sync_ops = 0 < max_sync_interval_ops ? max_sync_interval_ops : num_ops+1;
bool have_done_insert_since_last_sync = false;
#define HACK_EVICT_PERIODIC 0
#if HACK_EVICT_PERIODIC
// An experiment that demonstrated that the heap was filling with small
// junk ("heap Kessler syndrome"?): by evicting periodically, we freed
// most of the small junk and kept the heap waste down. TODO okay to clean up.
int evict_interval_ms = 100000;
int next_evict_ms = evict_interval_ms;
#endif // HACK_EVICT_PERIODIC
#define HACK_PROBE_PERIODIC 1
#if HACK_PROBE_PERIODIC
// An experiment to periodically study how the kv allocations are distributed
int probe_interval_ms = 50000;
int next_probe_ms = probe_interval_ms;
#endif // HACK_PROBE_PERIODIC
cout << "[step] " << name << " run start (num ops: " << num_ops << ", sync interval " <<
max_sync_interval.count() << " ms, sync ops " << max_sync_interval_ops << ")" << endl;
for (int i = 0; i < num_ops; ++i) {
auto next_operation = workload.NextOperation();
auto clock_op_started = steady_clock::now();
switch (next_operation) {
case ycsbc::READ:
performRead();
break;
case ycsbc::UPDATE:
performUpdate();
have_done_insert_since_last_sync = true;
break;
case ycsbc::INSERT:
performInsert(false /* not load */);
have_done_insert_since_last_sync = true;
break;
case ycsbc::SCAN:
performScan();
break;
case ycsbc::READMODIFYWRITE:
performReadModifyWrite();
have_done_insert_since_last_sync = true;
break;
default:
cerr << "error: invalid NextOperation" << endl;
exit(-1);
}
auto clock_op_completed = steady_clock::now();
record_duration(*latency_hist[next_operation], clock_op_started, clock_op_completed);
if (next_display <= clock_op_completed) {
malloc_accounting_display("periodic");
auto elapsed_ms = duration_cast<milliseconds>(clock_op_completed - clock_start);
cout << "[step] " << name << " run progress " << elapsed_ms.count() << " ms " << i << " ops" << endl;
next_display += progress_report_interval;
}
if (have_done_insert_since_last_sync &&
((0 < max_sync_interval.count() && next_sync < clock_op_completed)
|| next_sync_ops <= i)) {
auto sync_started = steady_clock::now();
milliseconds elapsed_ms = duration_cast<milliseconds>(sync_started - clock_start);
cout << "[step] " << name << " run sync start " << elapsed_ms.count() << " ms " << i << " ops" << endl;
db.sync(false);
auto sync_completed = steady_clock::now();
elapsed_ms = duration_cast<milliseconds>(sync_completed - clock_start);
cout << "[step] " << name << " run sync end " << elapsed_ms.count() << " ms " << i << " ops" << endl;
record_duration(sync_latency_hist, sync_started, sync_completed);
have_done_insert_since_last_sync = false;
next_sync = sync_completed + max_sync_interval;
next_sync_ops = i + max_sync_interval_ops;
malloc_accounting_status();
#ifdef _YCSB_VERIBETRFS
#ifdef LOG_QUERY_STATS
cout << "=========================================" << endl;
benchmark_dump();
benchmark_clear();
cout << "=========================================" << endl;
#endif
#endif
fflush(stdout);
}
}
if (have_done_insert_since_last_sync) {
auto sync_started = steady_clock::now();
milliseconds elapsed_ms = duration_cast<milliseconds>(sync_started - clock_start);
cout << "[step] " << name << " sync start " << elapsed_ms.count() << " ms " << num_ops << " ops" << endl;
db.sync(true);
auto sync_completed = steady_clock::now();
elapsed_ms = duration_cast<milliseconds>(sync_completed - clock_start);
cout << "[step] " << name << " sync end " << elapsed_ms.count() << " ms " << num_ops << " ops" << endl;
record_duration(sync_latency_hist, sync_started, sync_completed);
have_done_insert_since_last_sync = false;
next_sync = sync_completed + max_sync_interval;
next_sync_ops = num_ops + max_sync_interval_ops;
}
auto clock_end = steady_clock::now();
run_duration_ms = duration_cast<milliseconds>(clock_end - clock_start);
double run_duration_s = duration_cast<nanoseconds>(clock_end - clock_start).count() / 1000000000.0;
double throughput = num_ops / run_duration_s;
cout << "[step] " << name << " run throughput " << throughput << " ops/sec" << endl;
malloc_accounting_set_scope("ycsbRun.summary");
{
for (auto op : YcsbOperations) {
auto op_summary = latency_hist[op.first]->summary();
auto op_ccdf = latency_hist[op.first]->ccdf();
print_summary(op_summary, name, op.second);
print_ccdf(op_ccdf, name, op.second);
}
auto sync_summary = sync_latency_hist.summary();
auto sync_ccdf = sync_latency_hist.ccdf();
print_summary(sync_summary, name, "sync");
print_ccdf(sync_ccdf, name, "sync");
}
malloc_accounting_default_scope();
}
void LoadAndRun() {
Load();
Run();
malloc_accounting_display("after experiment before teardown");
}
};
#ifdef _YCSB_VERIBETRFS
class VeribetrkvFacade {
protected:
Application& app;
public:
static const string name;
VeribetrkvFacade(Application& app) : app(app) { }
inline void query(const string& key) {
app.Query(key);
}
inline void insert(const string& key, const string& value) {
app.Insert(key, value);
}
inline void update(const string& key, const string& value) {
app.Insert(key, value);
}
inline void readmodifywrite(const string& key, const string& value) {
update(key, value);
}
inline void scan(const string &key, int len) {
app.Succ(ByteString(key), true, len);
}
inline void sync(bool fullSync) {
app.Sync(fullSync);
}
inline void evictEverything() {
app.EvictEverything();
}
inline void CountAmassAllocations() {
app.CountAmassAllocations();
printf("debug-accumulator finish\n");
}
inline void cacheDebug() {
//app.CacheDebug();
}
};
const string VeribetrkvFacade::name = string("veribetrkv");
#endif
#ifdef _YCSB_ROCKS
class RocksdbFacade {
protected:
rocksdb::DB& db;
public:
static const string name;
RocksdbFacade(rocksdb::DB& db) : db(db) { }
inline void query(const string& key) {
static struct rocksdb::ReadOptions roptions = rocksdb::ReadOptions();
string value;
rocksdb::Status status = db.Get(roptions, rocksdb::Slice(key), &value);
assert(status.ok() || status.IsNotFound()); // TODO is it expected we're querying non-existing keys?
}
inline void insert(const string& key, const string& value) {
static struct rocksdb::WriteOptions woptions = rocksdb::WriteOptions();
woptions.disableWAL = true;
rocksdb::Status status = db.Put(woptions, rocksdb::Slice(key), rocksdb::Slice(value));
assert(status.ok());
}
inline void update(const string& key, const string& value) {
static struct rocksdb::WriteOptions woptions = rocksdb::WriteOptions();
woptions.disableWAL = true;
rocksdb::Status status = db.Put(woptions, rocksdb::Slice(key), rocksdb::Slice(value));
assert(status.ok());
}
inline void readmodifywrite(const string& key, const string& value) {
update(key, value);
}
inline void scan(const string &key, int len) {
rocksdb::Iterator* it = db.NewIterator(rocksdb::ReadOptions());
int i = 0;
for (it->Seek(key); i < len && it->Valid(); it->Next()) {
i++;
}
delete it;
}
inline void sync(bool /*fullSync*/) {
static struct rocksdb::FlushOptions foptions = rocksdb::FlushOptions();
rocksdb::Status status = db.Flush(foptions);
assert(status.ok());
}
inline void evictEverything() {
}
inline void CountAmassAllocations() {
}
};
const string RocksdbFacade::name = string("rocksdb");
#endif
#ifdef _YCSB_KYOTO
class KyotoFacade {
protected:
kyotocabinet::TreeDB &db;
public:
static const string name;
KyotoFacade(kyotocabinet::TreeDB &db) : db(db) { }
inline void query(const string& key) {
string result;
db.get(key, &result);
}
inline void insert(const string& key, const string& value) {
if (!db.set(key, value)) {
cout << "Insert failed" << endl;
abort();
}
}
inline void update(const string& key, const string& value) {
if (!db.set(key, value)) {
cout << "Update failed" << endl;
abort();
}
}
inline void readmodifywrite(const string& key, const string& value) {
query(key);
update(key, value);
}
inline void scan(const string &key, int len) {
kyotocabinet::DB::Cursor *cursor = db.cursor();
assert(cursor);
assert(cursor->jump(key));
int i = 0;
while (i < len && cursor->step())
i++;
delete cursor;
}
inline void sync(bool /*fullSync*/) {
db.synchronize();
}
inline void evictEverything() {
}
inline void CountAmassAllocations() {
}
};
const string KyotoFacade::name = string("kyotodb");
#endif
#ifdef _YCSB_BERKELEYDB
class BerkeleyDBFacade {
protected:
//DbEnv *env;
Db* pdb;
dbstl::db_map<string, string> *huge_map;
public:
static const string name;
BerkeleyDBFacade(Db *_pdb) : pdb(_pdb) {
huge_map = new dbstl::db_map<string, string>(pdb, NULL);
}
inline void query(const string& key) {
string result;
try {
const auto &t = *huge_map; // Get a const reference so operator[] doesn't insert key if it doesn't exist.
result = t[key];
} catch (DbException& e) {
cerr << "DbException: " << e.what() << endl;
abort();
} catch (std::exception& e) {
cerr << e.what() << endl;
abort();
}
}
inline void insert(const string& key, const string& value) {
try {
(*huge_map)[key] = value;
} catch (DbException& e) {
cerr << "DbException: " << e.what() << endl;
abort();
} catch (std::exception& e) {
cerr << e.what() << endl;
abort();
}
}
inline void update(const string& key, const string& value) {
insert(key, value);
}
inline void readmodifywrite(const string& key, const string& value) {
query(key);
update(key, value);
}
inline void scan(const string &key, int len) {
int i = 0;
auto iter = huge_map->begin(); // lower_bound() seems to be broken in berkeleydb
while(i < len && iter != huge_map->end()) {
++iter;
i++;
}
}
inline void sync(bool /*fullSync*/) {
pdb->sync(0);
}
inline void evictEverything() {
}
inline void CountAmassAllocations() {
}
};
const string BerkeleyDBFacade::name = string("berkeleydb");
#endif
class NopFacade {
public:
static const string name;
NopFacade() { }
inline void query(const string& key) {
asm volatile ("nop");
}
inline void insert(const string& key, const string& value) {
asm volatile ("nop");
}
inline void update(const string& key, const string& value) {
asm volatile ("nop");
}
inline void readmodifywrite(const string& key, const string& value) {
}
inline void scan(const string &key, int len) {
}
inline void sync(bool /*fullSync*/) {
asm volatile ("nop");
}
inline void evictEverything() {
asm volatile ("nop");
}
inline void CountAmassAllocations() {
asm volatile ("nop");
}
inline void cacheDebug() {
asm volatile ("nop");
}
};
const string NopFacade::name = string("nop");
void dump_metadata(const char* workload_filename, const char* database_filename) {
FILE* fp;
char space[1000];
char* line;
// This could output wrong info if we are not actually running in
// the cgroup.
//
// fp = fopen("/sys/fs/cgroup/memory/VeribetrfsExp/memory.limit_in_bytes", "r");
// if (fp) {
// line = fgets(space, sizeof(space), fp);
// fclose(fp);
// printf("metadata cgroups-memory.limit_in_bytes %s", line);
// }
printf("metadata workload_filename %s", workload_filename);
fp = fopen(workload_filename, "r");
while (true) {
char* line = fgets(space, sizeof(space), fp);
if (line==NULL) {
break;
}
printf("metadata workload %s", line);
}
fclose(fp);
printf("metadata database_filename %s", database_filename);
fflush(stdout);
char cmdbuf[1000];
// yes, this is a security hole. In the measurement framework,
// not the actual system. You can take the man out of K&R, as they say...
snprintf(cmdbuf, sizeof(cmdbuf), "df --output=source %s | tail -1", database_filename);
system(cmdbuf);
fflush(stdout);
}
template< class DbFacade >
void runOneWorkload(DbFacade db, string workload_filename, string database_filename,
ycsbc::CoreWorkload &workload,
bool load, bool do_nop, bool verbose)
{
utils::Properties props = ycsbcwrappers::props_from(workload_filename);
auto properties_map = props.properties();
workload.Init(props, !load);
int record_count = stoi(props[ycsbc::CoreWorkload::RECORD_COUNT_PROPERTY]);
int num_ops = stoi(props[ycsbc::CoreWorkload::OPERATION_COUNT_PROPERTY]);
int sync_interval_ms = 0;
int sync_interval_ops = 0;
string workload_name;
if (properties_map.find("syncintervalms") != properties_map.end()) {
sync_interval_ms= stoi(props["syncintervalms"]);
}
if (properties_map.find("syncintervalops") != properties_map.end()) {
sync_interval_ops = stoi(props["syncintervalops"]);
}
if (properties_map.find("workloadname") != properties_map.end()) {
workload_name = props["workloadname"];
} else {
workload_name = workload_filename;
}
dump_metadata(workload_filename.c_str(), database_filename.c_str());
if (do_nop) {
NopFacade nopdb;
YcsbExecution ycsbExecution(nopdb, workload_name, workload, record_count, num_ops, verbose,
sync_interval_ms, sync_interval_ops);
if (load)
ycsbExecution.Load();
else
ycsbExecution.Run();
} else {
YcsbExecution ycsbExecution(db, workload_name, workload, record_count, num_ops, verbose,
sync_interval_ms, sync_interval_ops);
if (load)
ycsbExecution.Load();
else
ycsbExecution.Run();
}
}
void pretendToDoLoadPhase(const string &workload_filename, ycsbc::CoreWorkload &workload)
{
utils::Properties props = ycsbcwrappers::props_from(workload_filename);
auto properties_map = props.properties();
workload.Init(props, false);
workload.AdvanceToEndOfLoad();
}
void usage(int argc, char **argv)
{
cerr << "Usage: " << argv[0] << " ";
#ifdef _YCSB_VERIBETRFS
cout << "<veribetrkv.img> ";
#endif
#ifdef _YCSB_ROCKS
cout << "<rocksdb-directory> ";
#endif
#ifdef _YCSB_BERKELEYDB
cout << "<berkeley.db> ";
#endif
#ifdef _YCSB_KYOTO
cout << "<kyoto.cbt> ";
#endif
cout << "[--nop] [--verbose] [--preloaded] ";
#ifdef _YCSB_ROCKS
cout << "[--filters] ";
#endif
cout << "<load-workload.spec> [run-workload1.spec...]" << endl;
cout << " --nop: use a no-op database" << endl;
cout << " --preloaded: don't format database. Database must have been loaded " << endl;
cout << " with the given load workload." << endl;
#ifdef _YCSB_ROCKS
cout << " --filters: enable filters" << endl;
#endif
exit(-1);
}
int main(int argc, char* argv[]) {
if (argc < 3)
usage(argc, argv);
bool do_nop = false;
bool verbose = false;
bool preloaded = false;
#ifdef _YCSB_ROCKS
bool use_filters = false;
#endif
std::string database_filename(argv[1]);
int first_workload_filename;
int i;
for (i = 2; i < argc; i++) {
if (string(argv[i]) == "--nop") {
do_nop = true;
} else if (string(argv[i]) == "--verbose") {
verbose = true;
} else if (string(argv[i]) == "--preloaded") {
preloaded = true;
#ifdef _YCSB_ROCKS
} else if (string(argv[i]) == "--filters") {
use_filters = true;
#endif
} else {
break;
}
}
first_workload_filename = i;
// == veribetrkv ==
#ifdef _YCSB_VERIBETRFS
if (!preloaded)
Mkfs(database_filename);
Application app(database_filename);
VeribetrkvFacade db(app);
#endif
// == rocksdb ==
#ifdef _YCSB_ROCKS
rocksdb::DB* rocks_db;
rocksdb::Options options;
if (!preloaded)
options.create_if_missing = true;
//options.error_if_exists = true;
// FIXME this is probably not fair, especially when we implement off-thread compaction
// disables background compaction _and_ flushing
// https://github.com/facebook/rocksdb/blob/master/include/rocksdb/options.h#L531-L536
options.max_background_jobs = 0;
// disabled - we let rocks use the page cache
// options.use_direct_reads = true;
// options.use_direct_io_for_flush_and_compaction = true;
if (use_filters) {
rocksdb::BlockBasedTableOptions table_options;
table_options.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false));
options.table_factory.reset(rocksdb::NewBlockBasedTableFactory(table_options));
}
rocksdb::Status status = rocksdb::DB::Open(options, database_filename, &rocks_db);
assert(status.ok());
RocksdbFacade db(*rocks_db);
#endif
// == kyotodb ==
#ifdef _YCSB_KYOTO
kyotocabinet::TreeDB tdb;
bool success = tdb.open(database_filename,
kyotocabinet::TreeDB::OWRITER
| (preloaded ? 0 : kyotocabinet::TreeDB::OCREATE)
| kyotocabinet::TreeDB::ONOLOCK);
if (!success)
abort();
KyotoFacade db(tdb);
#endif
// == berkeleydb ==
#ifdef _YCSB_BERKELEYDB
Db* pdb;
pdb = new Db(NULL, DB_CXX_NO_EXCEPTIONS);
assert(pdb);
if (pdb->open(NULL, database_filename.c_str(), NULL, DB_BTREE, preloaded ? 0 : DB_CREATE, 0)) {
cerr << "Failed to open database " << database_filename << endl;
abort();
}
BerkeleyDBFacade db(pdb);
#endif
ycsbc::CoreWorkload workload_template;
for (i = first_workload_filename; i < argc; i++) {
if (preloaded && i == first_workload_filename)
pretendToDoLoadPhase(argv[i], workload_template);
else
runOneWorkload(db, argv[i], database_filename, workload_template,
i == first_workload_filename, do_nop, verbose);
}
#ifdef _YCSB_VERIBETRFS
// No shutdown needed
#endif
#ifdef _YCSB_ROCKS
// No shutdown needed
#endif
#ifdef _YCSB_KYOTO
if (!tdb.close()) {
cout << "Failed to close " << database_filename;
abort();
}
#endif
#ifdef _YCSB_BERKELEYDB
if (pdb != NULL) {
if (pdb->close(0)) {
cerr << "Failed to close database" << endl;
abort();
}
delete pdb;
}
#endif
return 0;
}
| 30.429501 | 115 | 0.634445 | shenweihai1 |
16b7676c3309cf0f94512757c43a7410621b5238 | 14,960 | cpp | C++ | net/tapi/skywalker/mspbase/dtevntsk.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/tapi/skywalker/mspbase/dtevntsk.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/tapi/skywalker/mspbase/dtevntsk.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1998-1999 Microsoft Corporation
Module Name:
DTEvntSk.cpp
Abstract:
This module contains implementation of CPTEventSink.
Author:
vlade Nov 1999
--*/
#include "precomp.h"
#pragma hdrstop
//
// a helper function that releases the resources allocated inside event info
//
HRESULT FreeEventInfo( MSP_EVENT_INFO * pEvent )
{
LOG((MSP_TRACE, "FreeEventInfo - enter"));
switch ( pEvent->Event )
{
case ME_ADDRESS_EVENT:
if (NULL != pEvent->MSP_ADDRESS_EVENT_INFO.pTerminal)
{
(pEvent->MSP_ADDRESS_EVENT_INFO.pTerminal)->Release();
}
break;
case ME_CALL_EVENT:
if (NULL != pEvent->MSP_CALL_EVENT_INFO.pTerminal)
{
(pEvent->MSP_CALL_EVENT_INFO.pTerminal)->Release();
}
if (NULL != pEvent->MSP_CALL_EVENT_INFO.pStream)
{
(pEvent->MSP_CALL_EVENT_INFO.pStream)->Release();
}
break;
case ME_TSP_DATA:
break;
case ME_PRIVATE_EVENT:
if ( NULL != pEvent->MSP_PRIVATE_EVENT_INFO.pEvent )
{
(pEvent->MSP_PRIVATE_EVENT_INFO.pEvent)->Release();
}
break;
case ME_FILE_TERMINAL_EVENT:
if( NULL != pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal)
{
(pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal)->Release();
pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal = NULL;
}
if( NULL != pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack )
{
(pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack)->Release();
pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack = NULL;
}
break;
case ME_ASR_TERMINAL_EVENT:
if( NULL != pEvent->MSP_ASR_TERMINAL_EVENT_INFO.pASRTerminal)
{
(pEvent->MSP_ASR_TERMINAL_EVENT_INFO.pASRTerminal)->Release();
}
break;
case ME_TTS_TERMINAL_EVENT:
if( NULL != pEvent->MSP_TTS_TERMINAL_EVENT_INFO.pTTSTerminal)
{
(pEvent->MSP_TTS_TERMINAL_EVENT_INFO.pTTSTerminal)->Release();
}
break;
case ME_TONE_TERMINAL_EVENT:
if( NULL != pEvent->MSP_TONE_TERMINAL_EVENT_INFO.pToneTerminal)
{
(pEvent->MSP_TONE_TERMINAL_EVENT_INFO.pToneTerminal)->Release();
}
break;
default:
break;
}
LOG((MSP_TRACE, "FreeEventInfo - finished"));
return S_OK;
}
CPTEventSink::CPTEventSink() :
m_pMSPStream(NULL)
{
LOG((MSP_TRACE, "CPTEventSink::CPTEventSink enter"));
LOG((MSP_TRACE, "CPTEventSink::CPTEventSink exit"));
}
CPTEventSink::~CPTEventSink()
{
LOG((MSP_TRACE, "CPTEventSink::~CPTEventSink enter"));
LOG((MSP_TRACE, "CPTEventSink::~CPTEventSink exit"));
};
// --- ITPluggableTerminalEventSnk ---
/*++
FireEvent
Parameters:
IN MSPEVENTITEM * pEventItem pointer to the structure that describes the
event. all the pointers contained in the structure must be addreffed by
the caller, and then released by the caller if FireEvent fails
FireEvent makes a (shallow) copy of the structure, so the caller can
delete the structure when the function returns
Returns:
S_OK - every thing was OK
E_FAIL & other - something was wrong
Description:
This method is called by the dynamic terminals to
signal a new event
--*/
STDMETHODIMP CPTEventSink::FireEvent(
IN const MSP_EVENT_INFO * pEventInfo
)
{
LOG((MSP_TRACE, "CPTEventSink::FireEvent enter"));
//
// make sure we got a good mspeventitem structure
//
if( MSPB_IsBadWritePtr( (void*)pEventInfo, sizeof( MSP_EVENT_INFO )))
{
LOG((MSP_ERROR, "CPTEventSink::FireEvent -"
"pEventItem is bad, returns E_POINTER"));
return E_POINTER;
}
//
// Create an MSPEVENTITEM
//
MSPEVENTITEM *pEventItem = AllocateEventItem();
if (NULL == pEventItem)
{
LOG((MSP_ERROR, "CPTEventSink::FireEvent -"
"failed to create MSPEVENTITEM. returning E_OUTOFMEMORY "));
return E_OUTOFMEMORY;
}
//
// make a shallow copy of the structure
//
pEventItem->MSPEventInfo = *pEventInfo;
Lock();
HRESULT hr = E_FAIL;
if (NULL != m_pMSPStream)
{
//
// nicely ask stream to process our event
//
LOG((MSP_TRACE, "CPTEventSink::FireEvent - passing event [%p] to the stream", pEventItem));
AsyncEventStruct *pAsyncEvent = new AsyncEventStruct;
if (NULL == pAsyncEvent)
{
LOG((MSP_ERROR,
"CPTEventSink::FireEvent - failed to allocate memory for AsyncEventStruct"));
hr = E_OUTOFMEMORY;
}
else
{
//
// stuff the structure with the addref'fed stream on which the
// event will be fired and the actual event to fire
//
ULONG ulRC = m_pMSPStream->AddRef();
if (1 == ulRC)
{
//
// this is a workaround for a timing window: the stream could
// be in its desctructor while we are doing the addref. this
// condition is very-vary rare, as the timing window is very
// narrow.
//
// the good thing is that stream destructor will not finish
// while we are here, because it will try to get event sink's
// critical section in its call to SetSinkStream() to set our
// stream pointer to NULL.
//
// so if we detect that the refcount after our addref is 1,
// that would mean that the stream is in (or is about to start
// executing its desctructor). in which case we should do
// nothing.
//
// cleanup and return a failure.
//
Unlock();
LOG((MSP_ERROR,
"CPTEventSink::FireEvent - stream is going away"));
delete pAsyncEvent;
pAsyncEvent = NULL;
FreeEventItem(pEventItem);
pEventItem = NULL;
return TAPI_E_INVALIDSTREAM;
}
pAsyncEvent->pMSPStream = m_pMSPStream;
pAsyncEvent->pEventItem = pEventItem;
//
// now use thread pool api to schedule the event for future async
// processing
//
BOOL bQueueSuccess = QueueUserWorkItem(
CPTEventSink::FireEventCallBack,
(void *)pAsyncEvent,
WT_EXECUTEDEFAULT);
if (!bQueueSuccess)
{
DWORD dwLastError = GetLastError();
LOG((MSP_ERROR,
"CPTEventSink::FireEvent - QueueUserWorkItem failed. LastError = %ld", dwLastError));
//
// undo the addref we did on the stream object. the event will
// be freed later
//
m_pMSPStream->Release();
//
// the event was not enqueued. delete now.
//
delete pAsyncEvent;
pAsyncEvent = NULL;
//
// map the code and bail out
//
hr = HRESULT_FROM_WIN32(dwLastError);
}
else
{
//
// log the event we have submitted, so we can match submission
// with processing from the log
//
LOG((MSP_TRACE,
"CPTEventSink::FireEvent - submitted event [%p]", pAsyncEvent));
hr = S_OK;
} // async event structure submitted
} // async event structure allocated
} // msp stream exists
else
{
hr = TAPI_E_INVALIDSTREAM;
LOG((MSP_ERROR,
"CPTEventSink::FireEvent - stream pointer is NULL"));
}
Unlock();
//
// if we don't have a stream, or if the stream refused to process the
// event, cleanup and return an error
//
if (FAILED(hr))
{
LOG((MSP_ERROR, "CPTEventSink::FireEvent - call to HandleStreamEvent failed. hr = 0x%08x", hr));
FreeEventItem(pEventItem);
return hr;
}
LOG((MSP_TRACE, "CPTEventSink::FireEvent - exit"));
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
// CPTEventSink::FireEventCallBack
//
// the callback function that is called by thread pool api to asyncronously to
// process events fired by the terminals.
//
// the argument should point to the structure that contains the pointer to the
// stream on which to fire the event and the pointer to the event to fire.
//
// the dll is guaranteed to not go away, since the structure passed in holds a
// reference to the stream object on which to process the event
//
// static
DWORD WINAPI CPTEventSink::FireEventCallBack(LPVOID lpParameter)
{
LOG((MSP_TRACE, "CPTEventSink::FireEventCallBack - enter. Argument [%p]",
lpParameter));
AsyncEventStruct *pEventStruct = (AsyncEventStruct *)lpParameter;
//
// make sure the structure is valid
//
if (IsBadReadPtr(pEventStruct, sizeof(AsyncEventStruct)))
{
//
// complain and exit. should not happen, unless there is a problem in
// thread pool api or memory corruption
//
LOG((MSP_ERROR,
"CPTEventSink::FireEventCallBack - Argument does not point to a valid AsyncEventStruct"));
return FALSE;
}
BOOL bBadDataPassedIn = FALSE;
//
// the structure contains an addref'fed stream pointer. extract it and
// make sure it is still valid
//
CMSPStream *pMSPStream = pEventStruct->pMSPStream;
if (IsBadReadPtr(pMSPStream, sizeof(CMSPStream)))
{
//
// should not happen, unless there is a problem in thread pool api or
// memory corruption, or someone is over-releasing the stream object
//
LOG((MSP_ERROR,
"CPTEventSink::FireEventCallBack - stream pointer is bad"));
pMSPStream = NULL;
bBadDataPassedIn = TRUE;
}
//
// the structure contains the event that we are tryint to fire.
// make sure the event we are about to fire is good.
//
MSPEVENTITEM *pEventItem = pEventStruct->pEventItem;
if (IsBadReadPtr(pEventItem, sizeof(MSPEVENTITEM)))
{
//
// should not happen, unless there is a problem in thread pool api or
// memory corruption, or we didn't check success of allocation when we
// created the event (which we did!)
//
LOG((MSP_ERROR,
"CPTEventSink::FireEventCallBack - event is bad"));
pEventItem = NULL;
bBadDataPassedIn = TRUE;
}
//
// bad stream or event structure?
//
if (bBadDataPassedIn)
{
//
// release the event if it was good.
//
if ( NULL != pEventItem)
{
FreeEventItem(pEventItem);
pEventItem = NULL;
}
//
// release the stream if it was good.
//
if (NULL != pMSPStream)
{
pMSPStream->Release();
pMSPStream = NULL;
}
//
// no need to keep the event structure itself, delete it
//
delete pEventStruct;
pEventStruct = NULL;
return FALSE;
}
//
// we have both the stream and the event, fire the event on the stream
//
HRESULT hr = pMSPStream->HandleSinkEvent(pEventItem);
//
// if HandleSinkEvent succeeded, pEventItem will be released by whoever
// will handle the event, otherwise we need to release eventitem here
//
if (FAILED(hr))
{
LOG((MSP_ERROR,
"CPTEventSink::FireEventCallBack - HandleSinkEvent not called or failed. hr = %lx",
hr));
//
// need to free all the resources held by event info
//
FreeEventInfo(&(pEventItem->MSPEventInfo));
FreeEventItem(pEventItem);
pEventItem = NULL;
}
//
// release the stream pointer that is a part of the structure --
// we don't want any reference leaks.
//
//
// note that the dll may go away at this point (if we are holding the last
// reference to the last object from the dll)
//
pMSPStream->Release();
pMSPStream = NULL;
//
// at this point we release the stream pointer and either submitted the
// event or freed it. we no longer need the event structure.
//
delete pEventStruct;
pEventStruct = NULL;
LOG((MSP_(hr), "CPTEventSink::FireEventCallBack - exit. hr = %lx", hr));
return SUCCEEDED(hr);
}
/*++
SetSinkStream
Parameters:
CMSPStream *pStream
the stream that will be processing our events, or NULL when no stream is
available to process our events
Returns:
S_OK -
Description:
this method is called by the stream that is going to process our events
when the stream is going away and is no longer available to process our
messages, it will call SetSinkStream with NULL.
--*/
HRESULT CPTEventSink::SetSinkStream( CMSPStream *pStream )
{
LOG((MSP_TRACE, "CPTEventSink::SetSinkStream - enter"));
Lock();
LOG((MSP_TRACE,
"CPTEventSink::SetSinkStream - replacing sink stream [%p] with [%p]",
m_pMSPStream, pStream));
//
// we don't keep a reference to the stream -- the stream keeps a reference
// to us. when the stream goes away, it will let us know.
//
m_pMSPStream = pStream;
Unlock();
LOG((MSP_TRACE, "CPTEventSink::SetSinkStream - exit"));
return S_OK;
}
| 24.246353 | 106 | 0.542848 | npocmaka |
16b83efb2217c6758e897c4b4134f9086c017c12 | 1,180 | cpp | C++ | test/bitset.cpp | walker-zheng/code | 2959e4227e168aab4d5420bc836768730f2bffdd | [
"MIT"
] | 4 | 2018-05-18T10:58:41.000Z | 2021-12-29T16:17:53.000Z | test/bitset.cpp | walker-zheng/code | 2959e4227e168aab4d5420bc836768730f2bffdd | [
"MIT"
] | 4 | 2017-10-09T09:42:09.000Z | 2019-02-21T01:31:09.000Z | test/bitset.cpp | walker-zheng/code | 2959e4227e168aab4d5420bc836768730f2bffdd | [
"MIT"
] | 1 | 2021-04-09T00:58:19.000Z | 2021-04-09T00:58:19.000Z | // bitset::test
#include <iostream> // std::cout
#include <string> // std::string
#include <cstddef> // std::size_t
#include <bitset> // std::bitset
int main ()
{
std::bitset<16> shit;
std::bitset<16> bar (0xfa2);
std::bitset<16> foo (std::string("0101111001"));
std::cout << "shit: \t" << shit << '\n';
std::cout << "bar: \t" << bar << '\n';
std::cout << "f: \t" << foo << '\n';
std::cout << "flip f:\t" << foo.flip() << '\n';
std::cout << "test f:\t";
for (std::size_t i=0; i<foo.size(); ++i)
std::cout << foo.test(foo.size() - 1 - i) << ' ';
std::cout << std::endl;
std::cout << "to_str:\t" << foo.to_string() << std::endl;
std::cout << "to_ul:\t" << foo.to_ulong() << std::endl;
std::cout << "to_ull:\t" << foo.to_ullong() << std::endl;
std::cout << std::boolalpha;
std::cout << "all: \t" << foo.all() << '\n';
std::cout << "any: \t" << foo.any() << '\n';
std::cout << "none: \t" << foo.none() << '\n';
std::cout << "ones: \t" << foo.count() << '\n';
std::cout << "zeros: \t" << (foo.size()-foo.count()) << '\n';
std::cout << "set: \t" << foo.set() << '\n';
std::cout << "reset: \t" << foo.reset() << '\n';
return 0;
}
| 32.777778 | 62 | 0.492373 | walker-zheng |
16be2152cdfa7abcabc12b5ec3e507c6d0cd22ec | 15 | cpp | C++ | engine/src/id.cpp | unyankee/OutterSpace | a0746dd8d32b33be36f6972ace53f7b71f09d470 | [
"MIT"
] | null | null | null | engine/src/id.cpp | unyankee/OutterSpace | a0746dd8d32b33be36f6972ace53f7b71f09d470 | [
"MIT"
] | null | null | null | engine/src/id.cpp | unyankee/OutterSpace | a0746dd8d32b33be36f6972ace53f7b71f09d470 | [
"MIT"
] | null | null | null | #include <id.h> | 15 | 15 | 0.666667 | unyankee |
16bf11743144e64c08f049815176ed52f37aa485 | 2,801 | cc | C++ | code/render/graphics/globallightentity.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/graphics/globallightentity.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/graphics/globallightentity.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// globallightentity.cc
// (C) 2007 Radon Labs GmbH
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "graphics/globallightentity.h"
#include "lighting/shadowserver.h"
#include "lighting/lightserver.h"
namespace Graphics
{
__ImplementClass(Graphics::GlobalLightEntity, 'GLBE', Graphics::AbstractLightEntity);
using namespace Math;
using namespace Messaging;
using namespace Lighting;
//------------------------------------------------------------------------------
/**
*/
GlobalLightEntity::GlobalLightEntity() :
backLightColor(0.0f, 0.0f, 0.0f, 0.0f),
ambientLightColor(0.0f, 0.0f, 0.0f, 0.0f),
lightDir(0.0f, 0.0f, -1.0f),
backLightOffset(0.3)
{
this->SetLightType(LightType::Global);
this->SetAlwaysVisible(true);
}
//------------------------------------------------------------------------------
/**
*/
ClipStatus::Type
GlobalLightEntity::ComputeClipStatus(const Math::bbox& box)
{
// since we are essentially a directional light, everything is visible,
// we depend on the visibility detection code in the Cell class to
// only create light links for objects that are actually visible
return ClipStatus::Inside;
}
//------------------------------------------------------------------------------
/**
*/
void
GlobalLightEntity::OnTransformChanged()
{
AbstractLightEntity::OnTransformChanged();
// if the light transforms then all shadows must be updated
this->castShadowsThisFrame = this->castShadows;
// extract the light's direction from the transformation matrix
this->lightDir = float4::normalize(this->transform.getrow2());
// calculate shadow transform by doing a simple lookat
this->shadowTransform = matrix44::lookatrh(point(0,0,0), this->lightDir, vector::upvec());
// extend shadow casting frustum so that the global light resolves everything within the shadow casting range
this->transform.set_xaxis(float4::normalize(this->transform.get_xaxis()) * 1000000.0f);
this->transform.set_yaxis(float4::normalize(this->transform.get_yaxis()) * 1000000.0f);
this->transform.set_zaxis(float4::normalize(this->transform.get_zaxis()) * 1000000.0f);
}
//------------------------------------------------------------------------------
/**
*/
void
GlobalLightEntity::OnRenderDebug()
{
// TODO: render shadow frustum?
}
//------------------------------------------------------------------------------
/**
Handle a message, override this method accordingly in subclasses!
*/
void
GlobalLightEntity::HandleMessage(const Ptr<Message>& msg)
{
__Dispatch(GlobalLightEntity, this, msg);
}
} // namespace Graphics
| 31.829545 | 113 | 0.586219 | gscept |
16bfe033e69ed0ed010d0295a66779979ccf8ca1 | 12,795 | cpp | C++ | Chikara/Main.cpp | Chrono-byte/Chikara | 14801ff7de5f40201c542153f1021be9968074ff | [
"Apache-2.0"
] | 11 | 2020-05-25T06:03:57.000Z | 2021-08-12T16:34:11.000Z | Chikara/Main.cpp | Chrono-byte/Chikara | 14801ff7de5f40201c542153f1021be9968074ff | [
"Apache-2.0"
] | 6 | 2020-08-04T04:06:21.000Z | 2022-02-07T02:46:13.000Z | Chikara/Main.cpp | Chrono-byte/Chikara | 14801ff7de5f40201c542153f1021be9968074ff | [
"Apache-2.0"
] | 1 | 2020-09-22T19:16:59.000Z | 2020-09-22T19:16:59.000Z | #include "Main.h"
#include "KDMAPI.h"
#include "OmniMIDI.h"
#include "Config.h"
#include "Utils.h"
#include "Platform.h"
#include <inttypes.h>
#include <fmt/locale.h>
#include <fmt/format.h>
// msvc complains about narrowing conversion with bin2c
#pragma warning(push)
#pragma warning(disable : 4838)
#pragma warning(disable : 4309)
#include "Shaders/notes_f.h"
#include "Shaders/notes_v.h"
#include "Shaders/notes_g.h"
#pragma warning(pop)
Renderer r;
GlobalTime* gtime;
Midi* midi;
MidiTrack* trk;
Vertex instanced_quad[]
{
{ {0,1}, {0,1} },
{ {1,1}, {1,1} },
{ {1,0}, {1,0} },
{ {0,0}, {0,0} },
};
uint32_t instanced_quad_indis[] = {
0, 1, 2,
2, 3, 0,
};
void Main::run(int argc, wchar_t** argv)
{
std::wstring filename;
if(argc < 2) {
filename = Platform::OpenMIDIFileDialog();
if(filename.empty())
return;
}
else {
filename = argv[1];
}
auto config_path = Config::GetConfigPath();
Config::GetConfig().Load(config_path);
InitializeKDMAPIStream();
SetConsoleOutputCP(65001); // utf-8
fmt::print("Loading {}\n", Utils::wstringToUtf8(Utils::GetFileName(filename)));
#ifdef RELEASE
try
{
std::cout << "RPC Enabled: " << Config::GetConfig().discord_rpc << std::endl;
if(Config::GetConfig().discord_rpc) Utils::InitDiscord();
}
catch(const std::exception& e)
{
std::cout << "RPC Enabled: 0 (Discord Not Installed)" << std::endl;
Config::GetConfig().discord_rpc = false;
}
#else
std::cout << "RPC Enabled: 0 (Chikara is compiled as debug)" << std::endl;
#endif
try
{
if(Config::GetConfig().loader_buffer < 0)
{
Config::GetConfig().loader_buffer = 0;
Config::GetConfig().Save();
}
}
catch(const std::exception& e)
{
//Config didn't exist, expecting it to just be 10;
}
wchar_t* filename_temp = _wcsdup(filename.c_str());
midi = new Midi(filename_temp);
r.note_event_buffer = midi->note_event_buffer;
r.midi_renderer_time = &midi->renderer_time;
r.note_stacks.resize(midi->track_count * 16);
r.note_count = &midi->note_count;
r.notes_played = &midi->notes_played;
r.song_len = midi->song_len;
r.marker = &midi->marker;
r.colors = midi->colors;
r.createColors();
midi->colors.clear(); //free up the colors array in color since we no longer need it
// playback thread spawned in mainLoop to ensure it's synced with render
//printf(file_name);
midi->SpawnLoaderThread();
initWindow(filename); //Setup everything for the window
initVulkan(); //Setup everything for Vulkan
gt = new GlobalTime(Config::GetConfig().start_delay, midi->note_count, filename);
gtime = gt;
mainLoop(filename); //The main loop for the application
cleanup(); //Cleanup everything because we closed the application
free(filename_temp);
}
std::wstring midi_file_name;
long long start_time;
long long end_time;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
exit(1);
if(key == GLFW_KEY_SPACE && action == GLFW_PRESS)
{
r.paused = !r.paused;
r.paused ? gtime->pause() : gtime->resume();
}
if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS && mods != GLFW_MOD_SHIFT)
gtime->skipForward(1);
if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS && mods == GLFW_MOD_SHIFT)
gtime->skipForward(5);
}
void Main::initWindow(std::wstring midi)
{
midi_file_name = midi;
glfwInit(); //Init glfw
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); //Set the glfw api to GLFW_NO_API because we are using Vulkan
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); //Change the ability to resize the window
if(Config::GetConfig().transparent)
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE); //Window Transparancy
auto filename = Utils::wstringToUtf8(Utils::GetFileName(midi));
int count;
int monitorX, monitorY;
GLFWmonitor** monitors = glfwGetMonitors(&count);
glfwGetMonitorPos(monitors[0], &monitorX, &monitorY);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
if(Config::GetConfig().fullscreen)
{
r.window = glfwCreateWindow(mode->width, mode->height, std::string("Chikara | " + filename).c_str(), glfwGetPrimaryMonitor(), nullptr); //Now we create the window
r.window_width = mode->width;
r.window_height = mode->height;
}
else {
r.window = glfwCreateWindow(default_width, default_height, std::string("Chikara | " + filename).c_str(), nullptr, nullptr); //Now we create the window
glfwSetWindowPos(r.window, monitorX + (mode->width - default_width) / 2, monitorY + (mode->height - default_height) / 2);
}
glfwSetWindowUserPointer(r.window, &r);
glfwSetFramebufferSizeCallback(r.window, r.framebufferResizeCallback);
glfwSetKeyCallback(r.window, key_callback);
}
void Main::initVulkan()
{
r.createInstance(); //Create the Vulkan Instance
r.setupDebugMessenger();
r.createSurface();
r.setupDevice(); //Pick the physical device
r.createLogicalDevice(); //Create the logical device to use
r.createSwapChain();
r.createImageViews();
r.createRenderPass(&r.note_render_pass, true, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
r.createRenderPass(&r.additional_note_render_pass, true, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
r.createDescriptorSetLayout();
r.createGraphicsPipeline(notes_v, notes_v_length, notes_f, notes_f_length, notes_g, notes_g_length, r.note_render_pass, &r.note_pipeline_layout, &r.note_pipeline);
r.createRenderPass(&r.imgui_render_pass, false, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
r.createPipelineCache();
r.createCommandPool(&r.cmd_pool, 0);
r.createCommandPool(&r.imgui_cmd_pool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
r.createDepthResources();
r.createFramebuffers();
r.createImGuiFramebuffers();
//r.createTextureImage();
//r.createTextureImageView();
//r.createTextureSampler();
//r.createVertexBuffer(instanced_quad, 4, r.note_vertex_buffer, r.note_vertex_buffer_mem);
//r.createInstanceBuffer(sizeof(InstanceData) * MAX_NOTES, r.note_instance_buffer, r.note_instance_buffer_mem);
//r.createIndexBuffer(instanced_quad_indis, 6, r.note_index_buffer, r.note_index_buffer_mem);
r.createNoteDataBuffer(sizeof(NoteData) * MAX_NOTES, r.note_buffer, r.note_buffer_mem);
r.createUniformBuffers(r.uniform_buffers, r.uniform_buffers_mem);
r.createDescriptorPool();
r.createImGuiDescriptorPool();
r.createDescriptorSets();
r.createCommandBuffers();
r.createImGuiCommandBuffers();
r.createSyncObjects();
r.initImGui();
r.PrepareKeyboard();
}
auto timer = std::chrono::steady_clock();
auto last_time = timer.now();
uint64_t frame_counter = 0;
uint64_t fps = 0;
void Main::mainLoop(std::wstring midi_name)
{
midi->SpawnPlaybackThread(gt, Config::GetConfig().start_delay);
/*
char buffer[256];
sprintf(buffer, "Note Count: %s", fmt::format(std::locale(""), "{:n}", midi->note_count));
*/
#ifdef RELEASE
if(Config::GetConfig().discord_rpc && midi) {
auto rpc_text = fmt::format(std::locale(""), "Note Count: {:n}", midi->note_count);
Utils::UpdatePresence(rpc_text.c_str(), "Playing: ", Utils::wstringToUtf8(Utils::GetFileName(midi_name)));
}
#endif
while(!glfwWindowShouldClose(r.window))
{
r.pre_time = Config::GetConfig().note_speed;
//float time;
//auto current_time = std::chrono::high_resolution_clock::now();
//time = std::chrono::duration<float, std::chrono::seconds::period>(current_time - start_time).count();
r.midi_renderer_time->store(gt->getTime() + r.pre_time);
glfwPollEvents();
r.drawFrame(gt);
}
vkDeviceWaitIdle(r.device);
TerminateKDMAPIStream();
}
#pragma region Recreating the swap chain
void Main::cleanupSwapChain()
{
vkDestroyImageView(r.device, r.depth_img_view, nullptr);
vkDestroyImage(r.device, r.depth_img, nullptr);
vkFreeMemory(r.device, r.depth_img_mem, nullptr);
for(size_t i = 0; i < r.swap_chain_framebuffers.size(); i++)
vkDestroyFramebuffer(r.device, r.swap_chain_framebuffers[i], nullptr);
for(size_t i = 0; i < r.imgui_swap_chain_framebuffers.size(); i++)
vkDestroyFramebuffer(r.device, r.imgui_swap_chain_framebuffers[i], nullptr);
vkFreeCommandBuffers(r.device, r.cmd_pool, static_cast<uint32_t>(r.cmd_buffers.size()), r.cmd_buffers.data());
vkFreeCommandBuffers(r.device, r.imgui_cmd_pool, static_cast<uint32_t>(r.imgui_cmd_buffers.size()), r.imgui_cmd_buffers.data());
vkDestroyPipeline(r.device, r.note_pipeline, nullptr);
vkDestroyPipelineLayout(r.device, r.note_pipeline_layout, nullptr);
vkDestroyRenderPass(r.device, r.note_render_pass, nullptr);
vkDestroyRenderPass(r.device, r.additional_note_render_pass, nullptr);
vkDestroyRenderPass(r.device, r.imgui_render_pass, nullptr);
for(size_t i = 0; i < r.swap_chain_img_views.size(); i++)
{
vkDestroyImageView(r.device, r.swap_chain_img_views[i], nullptr);
}
vkDestroySwapchainKHR(r.device, r.swap_chain, nullptr);
for(size_t i = 0; i < r.swap_chain_imgs.size(); i++)
{
vkDestroyBuffer(r.device, r.uniform_buffers[i], nullptr);
vkFreeMemory(r.device, r.uniform_buffers_mem[i], nullptr);
}
vkDestroyDescriptorPool(r.device, r.descriptor_pool, nullptr);
vkDestroyDescriptorPool(r.device, r.imgui_descriptor_pool, nullptr);
}
void Main::recreateSwapChain()
{
int width = 0, height = 0;
glfwGetFramebufferSize(r.window, &width, &height);
while(width == 0 || height == 0)
{
glfwGetFramebufferSize(r.window, &width, &height);
glfwWaitEvents();
}
r.window_width = width;
r.window_height = height;
vkDeviceWaitIdle(r.device);
r.destroyImGui();
cleanupSwapChain();
r.createSwapChain();
r.createImageViews();
r.createRenderPass(&r.note_render_pass, true, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
r.createRenderPass(&r.additional_note_render_pass, true, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
r.createGraphicsPipeline(notes_v, notes_v_length, notes_f, notes_f_length, notes_g, notes_g_length, r.note_render_pass, &r.note_pipeline_layout, &r.note_pipeline);
r.createRenderPass(&r.imgui_render_pass, false, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
r.createDepthResources();
r.createFramebuffers();
r.createImGuiFramebuffers();
r.createUniformBuffers(r.uniform_buffers, r.uniform_buffers_mem);
r.createDescriptorPool();
r.createImGuiDescriptorPool();
r.createDescriptorSets();
r.createCommandBuffers();
r.createImGuiCommandBuffers();
r.initImGui();
r.PrepareKeyboard();
}
#pragma endregion
#pragma region Cleanup
void Main::cleanup()
{
if(enable_validation_layers)
{
r.DestroyDebugUtilsMessengerEXT(r.inst, r.debug_msg, nullptr);
}
r.destroyImGui();
cleanupSwapChain();
//vkDestroySampler(r.device, r.tex_sampler, nullptr);
vkDestroyImageView(r.device, r.tex_img_view, nullptr);
vkDestroyImage(r.device, r.tex_img, nullptr);
vkFreeMemory(r.device, r.tex_img_mem, nullptr);
vkDestroyDescriptorSetLayout(r.device, r.descriptor_set_layout, nullptr);
vkDestroyBuffer(r.device, r.note_buffer, nullptr);
vkFreeMemory(r.device, r.note_buffer_mem, nullptr);
for(size_t i = 0; i < max_frames_in_flight; i++)
{
vkDestroySemaphore(r.device, r.render_fin_semaphore[i], nullptr);
vkDestroySemaphore(r.device, r.img_available_semaphore[i], nullptr);
vkDestroyFence(r.device, r.in_flight_fences[i], nullptr);
}
vkDestroyCommandPool(r.device, r.cmd_pool, nullptr);
vkDestroyCommandPool(r.device, r.imgui_cmd_pool, nullptr);
vkDestroyPipelineCache(r.device, r.pipeline_cache, nullptr);
vkDestroyDevice(r.device, nullptr);
vkDestroySurfaceKHR(r.inst, r.surface, nullptr);
vkDestroyInstance(r.inst, nullptr);
glfwDestroyWindow(r.window);
glfwTerminate(); //Now we terminate
#ifdef RELEASE
Utils::DestroyDiscord();
#endif
}
#pragma endregion
int wmain(int argc, wchar_t** argv)
{
Main app; //Get the main class and call it app
try
{
app.run(argc, argv); //Startup the application
}
catch(const std::exception& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE; //Something broke...
}
return EXIT_SUCCESS;
} | 33.849206 | 170 | 0.733255 | Chrono-byte |
16cacb7673707af23c92c9853e93c16ce0e93ddd | 5,874 | cpp | C++ | src/Htfe/HtfeFile.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | src/Htfe/HtfeFile.cpp | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | src/Htfe/HtfeFile.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | /* Copyright (c) 2015 Convey Computer Corporation
*
* This file is part of the OpenHT toolset located at:
*
* https://github.com/TonyBrewer/OpenHT
*
* Use and distribution licensed under the BSD 3-clause license.
* See the LICENSE file for the complete license text.
*/
// HtFile.cpp: implementation of the CHtFile class.
//
//////////////////////////////////////////////////////////////////////
#include "Htfe.h"
#include "HtfeErrorMsg.h"
#include "HtfeFile.h"
#ifndef _MSC_VER
#include <sys/types.h>
#include <unistd.h>
#define _lseek lseek
#define _read read
#define _unlink unlink
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHtFile::CHtFile()
{
m_indentLevel = 0;
m_bNewLine = false;
m_bDoNotSplitLine = false;
m_dstFp = 0;
m_lineCol = 0;
m_lineNum = 1;
m_maxLineCol = 70;
m_bLineBuffering = false;
m_lineListIdx = 0;
m_bVarInit = false;
m_bInTask = false;
}
bool
CHtFile::Open(const string &outputFileName, char *pMode)
{
m_fileName = outputFileName;
m_dstFp = fopen(outputFileName.c_str(), pMode);
int lastSlash = outputFileName.find_last_of("/\\");
if (lastSlash > 0)
m_folder = outputFileName.substr(0,lastSlash);
else
m_folder = ".";
return m_dstFp != 0;
}
void CHtFile::Close() {
Assert(m_dstFp);
fclose(m_dstFp);
m_dstFp = 0;
}
void CHtFile::Delete() {
if (m_dstFp) {
fclose(m_dstFp);
_unlink(m_fileName.c_str());
}
m_dstFp = 0;
}
void
CHtFile::Dup(int srcFd, int startOffset, int endOffset)
{
int origOffset = _lseek(srcFd, 0, SEEK_CUR);
_lseek(srcFd, startOffset, SEEK_SET);
char buffer[4096];
for (int offset = startOffset; offset < endOffset; ) {
int readSize = endOffset - offset;
if (readSize > 4096)
readSize = 4096;
int readBytes = _read(srcFd, buffer, readSize);
if (readBytes <= 0)
break;
fwrite(buffer, 1, readBytes, m_dstFp);
offset += readBytes;
}
_lseek(srcFd, origOffset, SEEK_SET);
}
void CHtFile::PrintVarInit(const char *format, ...)
{
int savedIndentLevel = GetIndentLevel();
SetIndentLevel(m_varInitIndentLevel);
m_bVarInit = true;
va_list marker;
va_start(marker, format); /* Initialize variable arguments. */
Print_(format, marker);
m_bVarInit = false;
SetIndentLevel(savedIndentLevel);
}
int CHtFile::Print(const char *format, ...)
{
va_list marker;
va_start(marker, format); /* Initialize variable arguments. */
return Print_(format, marker);
}
int CHtFile::Print_(const char *format, va_list marker)
{
if (m_indentLevel == -1) {
int r = vfprintf(m_dstFp, format, marker);
for (const char *pCh = format; *pCh; pCh += 1)
if (*pCh == '\n')
m_lineNum += 1;
return r;
} else {
char buf[4096];
int r = vsprintf(buf, format, marker);
// a newline in the input forces a new line in the output
// the formated string can be split where a space exists or at the boundary
bool bEol = false;
char *pStrStart = buf;
for (;;) {
if (m_bNewLine) {
int level = m_indentLevel;
for (int i = 0; i < level; i += 1)
Putc(' ');
m_lineCol = m_indentLevel;
m_bNewLine = false;
}
// find next string terminated by a ' ', '\t', '\n' or '\0'
char *pStrEnd = pStrStart;
if (pStrStart[0] == '/' && pStrStart[1] == '/') {
// comments must be handled together to avoid wrapping to a newline
while (*pStrEnd != '\n' && *pStrEnd != '\r' && *pStrEnd != '\0')
pStrEnd++;
} else {
while (*pStrEnd != ' ' && *pStrEnd != '\t' && *pStrEnd != '\n' && *pStrEnd != '\r' && *pStrEnd != '\0')
pStrEnd++;
}
m_bNewLine = *pStrEnd == '\n' || *pStrEnd == '\r';
bEol = *pStrEnd == '\0';
bool bSpace = *pStrEnd == ' ';
bool bTab = *pStrEnd == '\t';
*pStrEnd = '\0';
// check if string can fit in current line
int strLen = strlen(pStrStart);
if (!m_bDoNotSplitLine && m_indentLevel < m_lineCol && m_lineCol + strLen > m_maxLineCol) {
// string does not fit, start new line
Putc('\n');
m_lineNum += 1;
for (int i = 0; i < m_indentLevel+1; i += 1)
Putc(' ');
m_lineCol = m_indentLevel+1;
}
if (strLen > 0)
Puts(pStrStart);
m_lineCol += strLen;
if (!m_bNewLine && bSpace) Putc(' ');
if (!m_bNewLine && bTab) Putc('\t');
pStrStart = pStrEnd+1;
if (m_bNewLine) {
Putc('\n');
m_lineNum += 1;
}
while (!bEol && *pStrStart == '\n') {
pStrStart += 1;
Putc('\n');
m_lineNum += 1;
}
if (bEol || *pStrStart == '\0') {
m_bDoNotSplitLine = false;
return r;
}
}
}
}
void CHtFile::Putc(char ch)
{
if (m_bVarInit) {
m_varInitBuffer += ch;
if (ch == '\n') {
m_varInitLineList.push_back(m_varInitBuffer);
m_varInitBuffer.clear();
}
} else if (m_bLineBuffering) {
m_lineBuffer += ch;
if (ch == '\n') {
m_lineList[m_lineListIdx].push_back(m_lineBuffer);
m_lineBuffer.clear();
}
} else
fputc(ch, m_dstFp);
}
void CHtFile::Puts(char * pStr)
{
if (m_bVarInit)
m_varInitBuffer += pStr;
else if (m_bLineBuffering)
m_lineBuffer += pStr;
else
fputs(pStr, m_dstFp);
}
void CHtFile::FlushLineBuffer()
{
for (size_t i = 0; i < m_lineList[m_lineListIdx].size(); i += 1)
fputs(m_lineList[m_lineListIdx][i].c_str(), m_dstFp);
m_lineList[m_lineListIdx].clear();
}
void CHtFile::VarInitClose()
{
if (m_bInTask) {
// first insert task's temp var declarations
m_lineList[m_varInitListIdx].insert(m_lineList[m_varInitListIdx].begin() + m_varInitLineIdx,
m_lineList[2].begin(), m_lineList[2].end());
m_varInitLineIdx += m_lineList[2].size();
m_lineList[2].clear();
// SetLineBuffer(0);
}
m_lineList[m_varInitListIdx].insert(m_lineList[m_varInitListIdx].begin() + m_varInitLineIdx,
m_varInitLineList.begin(), m_varInitLineList.end());
m_varInitLineList.clear();
}
| 23.217391 | 107 | 0.617637 | TonyBrewer |
16cc18d3f91a15da1a0a85da670a20ce14f8fb68 | 2,668 | cpp | C++ | speedcc/stage/SCBehaviorSystem.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 7 | 2018-03-10T02:01:49.000Z | 2021-09-14T15:42:10.000Z | speedcc/stage/SCBehaviorSystem.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | null | null | null | speedcc/stage/SCBehaviorSystem.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 1 | 2018-03-10T02:01:58.000Z | 2018-03-10T02:01:58.000Z | /****************************************************************************
Copyright (c) 2017-2020 Kevin Wu (Wu Feng)
github: http://github.com/kevinwu1024
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "SCBehaviorSystem.h"
#include "../cocos/SCViewController.h"
#include "../system/SCSystem.h"
NAMESPACE_SPEEDCC_BEGIN
///--------- SCBehaviorPurchase
SCBehaviorPurchase::SCBehaviorPurchase(const int nFeatureID,SCStore::ResultFunc_t resultFunc)
:_nFeatureID(nFeatureID)
{
this->setResultFunc(resultFunc);
}
SCBehaviorPurchase::~SCBehaviorPurchase()
{
SCStore::getInstance()->setPurchaseResultFunc(nullptr);
}
void SCBehaviorPurchase::setResultFunc(const SCStore::ResultFunc_t& func)
{
_resultFunc = [func](int nFeatureID,SCStore::EResultType result,void* pInfo)
{
auto ptrCtrl = SCViewNav()->getCurrentController();
ptrCtrl->showBlackMask(false);
ptrCtrl->setTouchAcceptable(true);
if(func!=nullptr)
{
func(nFeatureID,result,pInfo);
}
};
}
void SCBehaviorPurchase::execute(const SCDictionary& par)
{
auto ptrCtrl = SCViewNav()->getCurrentController();
ptrCtrl->showBlackMask(true);
ptrCtrl->setTouchAcceptable(false);
SCStore::getInstance()->purchaseFeature(_nFeatureID,_resultFunc);
}
///---------- SCBehaviorRequestProduct
SCBehaviorRequestProduct::~SCBehaviorRequestProduct()
{
SCStore::getInstance()->setRequestProductResultFunc(nullptr);
}
void SCBehaviorRequestProduct::execute(const SCDictionary& par)
{
SCStore::getInstance()->requestProductInfo(_resultFunc);
}
///----------- SCBehaviorRestorePurchased
SCBehaviorRestorePurchased::~SCBehaviorRestorePurchased()
{
SCStore::getInstance()->setRestoreResultFunc(nullptr);
}
void SCBehaviorRestorePurchased::execute(const SCDictionary& par)
{
SCStore::getInstance()->restorePurchased(_resultFunc);
}
NAMESPACE_SPEEDCC_END
| 30.318182 | 93 | 0.687781 | kevinwu1024 |
16cdf32d98a37fa69ba5632fad2824d1ca1bda5f | 846 | cpp | C++ | Blake2/Blake2/ParallelUtils.cpp | Steppenwolfe65/Blake2 | 9444e194323f98bb797816bc774d202276d17243 | [
"Intel",
"MIT"
] | 1 | 2016-11-09T05:34:58.000Z | 2016-11-09T05:34:58.000Z | Blake2/Blake2/ParallelUtils.cpp | Steppenwolfe65/Blake2 | 9444e194323f98bb797816bc774d202276d17243 | [
"Intel",
"MIT"
] | null | null | null | Blake2/Blake2/ParallelUtils.cpp | Steppenwolfe65/Blake2 | 9444e194323f98bb797816bc774d202276d17243 | [
"Intel",
"MIT"
] | null | null | null | #include "ParallelUtils.h"
#include <functional>
#if defined(_OPENMP)
# include <omp.h>
#else
# include <future>
#endif
NAMESPACE_UTILITY
size_t ParallelUtils::ProcessorCount()
{
#if defined(_OPENMP)
return static_cast<size_t>(omp_get_num_procs());
#else
return static_cast<size_t>(std::thread::hardware_concurrency());
#endif
}
void ParallelUtils::ParallelFor(size_t From, size_t To, const std::function<void(size_t)> &F)
{
#if defined(_OPENMP)
#pragma omp parallel num_threads((int)To)
{
size_t i = (size_t)omp_get_thread_num();
F(i);
}
#else
std::vector<std::future<void>> futures;
for (size_t i = From; i < To; ++i)
{
auto fut = std::async([i, F]()
{
F(i);
});
futures.push_back(std::move(fut));
}
for (size_t i = 0; i < futures.size(); ++i)
futures[i].wait();
futures.clear();
#endif
}
NAMESPACE_UTILITYEND | 17.625 | 93 | 0.683215 | Steppenwolfe65 |
16ce70f858ab74f14d5245986c839d7d47b858b2 | 1,483 | cc | C++ | userFiles/simu/analysis/fitness/specific_fitness/min_dist/MinDistFitness.cc | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/simu/analysis/fitness/specific_fitness/min_dist/MinDistFitness.cc | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/simu/analysis/fitness/specific_fitness/min_dist/MinDistFitness.cc | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null |
#include "MinDistFitness.hh"
#define THRESHOLD_WAIST 0.45
/*! \brief constructor
*
* \param[in] mbs_data Robotran structure
* \param[in] sens_info info from the sensor
*/
MinDistFitness::MinDistFitness(MbsData *mbs_data, SensorsInfo *sens_info): FitnessStage(mbs_data)
{
max_x_before_fall = 0.0;
tf = mbs_data->tf;
lim_x_travel = 0.75 * tf;
max_fitness = 300.0;
this->sens_info = sens_info;
}
/*! \brief destructor
*/
MinDistFitness::~MinDistFitness()
{
}
/*! \brief compute variables at each time step
*/
void MinDistFitness::compute()
{
double x_before_fall;
// threshold_waist prevents from counting positive travelled distance if the robot is falling
if (sens_info->get_waist_to_feet() > THRESHOLD_WAIST)
{
// no interest if going backward
x_before_fall = fmin(fmin(sens_info->get_S_MidWaist_P(0),sens_info->get_S_RFoots_P(0)),sens_info->get_S_LFoots_P(0));
if (x_before_fall < 0.0)
{
x_before_fall = 0.0;
}
// to consider only the max positive value
if (x_before_fall > max_x_before_fall)
{
max_x_before_fall = x_before_fall;
}
}
}
/*! \brief get fitness
*
* \return fitness
*/
double MinDistFitness::get_fitness()
{
return (max_x_before_fall > lim_x_travel) ? max_fitness : max_x_before_fall * (max_fitness/lim_x_travel);
}
/*! \brief detect if next stage is unlocked
*
* \return 1 if next stage unlocked, 0 otherwise
*/
int MinDistFitness::next_stage_unlocked()
{
return 1.0;
}
| 20.315068 | 119 | 0.703978 | mharding01 |
16cebae08ea0694173885374f370c1441893269d | 481 | cpp | C++ | UESTC/2501.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | UESTC/2501.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | UESTC/2501.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include <bits/stdc++.h>
using namespace std;
const long long M=1e9+7;
int k,cnt=-1;
long long x,n=1;
inline long long fpow(long long a,long long b)
{
long long r=1;
for (;b;b>>=1,(a*=a)%=M) if (b&1) (r*=a)%=M;
return r;
}
int main()
{
scanf("%d",&k);
for (int i=1;i<=k;i++)
{
scanf("%lld",&x);
if (!(x&1)) cnt=1;
x%=(M-1);(n*=x)%=(M-1);
}
n=(n+M-2)%(M-1);
long long p=fpow(2,n),q;q=p;
p=(p+cnt+M)%M;(p*=333333336LL)%=M;
printf("%lld/%lld\n",p,q);
return 0;
} | 16.033333 | 46 | 0.528067 | HeRaNO |
16cf20038e00882772a14e9a2dd81ee4ae1c0b1a | 4,746 | cpp | C++ | Dicom/dicom/data/AS.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | Dicom/dicom/data/AS.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | Dicom/dicom/data/AS.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | #include "dicom_pch.h"
#include "dicom/data/AS.h"
#include <sstream>
#include <iomanip>
#include "dicom/data/detail/atoi.h"
namespace {
using namespace dicom::data;
[[nodiscard]] AS::UnitType char_to_units(char c) {
switch (c) {
case 'D': return AS::Days;
case 'W': return AS::Weeks;
case 'M': return AS::Months;
case 'Y': return AS::Years;
default: return AS::UnitType(-1);
}
}
[[nodiscard]] char units_to_char(AS::UnitType units) {
switch (units) {
case AS::Days: return 'D';
case AS::Weeks: return 'W';
case AS::Months: return 'M';
case AS::Years: return 'Y';
default: return 'X'; // Something purposefully invalid
}
}
}
namespace dicom::data {
AS::AS()
: AS(std::string())
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(const char* value)
: AS(std::string(value))
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(const std::string_view& value)
: AS(std::string(value))
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(std::string&& value)
: VR(VRType::AS),
m_value(std::forward<std::string>(value))
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(int32_t age, UnitType units)
: VR(VRType::AS)
{
std::ostringstream ss;
ss << std::setw(3) << std::setfill('0') << age
<< std::setw(0) << units_to_char(units);
m_value = ss.str();
}
//--------------------------------------------------------------------------------------------------------
AS::AS(const AS& other) = default;
AS::AS(AS&& other) = default;
AS& AS::operator = (const AS& other) = default;
AS& AS::operator = (AS&& other) = default;
//--------------------------------------------------------------------------------------------------------
AS::~AS() = default;
//--------------------------------------------------------------------------------------------------------
ValidityType AS::Validate() const {
/*** Essential checks ***/
// Value is always 4 characters long
if (m_value.size() != 4) { return ValidityType::Invalid; }
// Value must have numeric digits for the first three characters
if (!std::all_of(m_value.begin(), m_value.begin() + 3, isdigit)) { return ValidityType::Invalid; }
// Value must have a unit character at the end
if (char_to_units(m_value[3]) == -1) { return ValidityType::Invalid; }
return ValidityType::Valid;
}
//--------------------------------------------------------------------------------------------------------
int32_t AS::Age() const {
AssertValidated();
return detail::unchecked_atoi<int32_t>(m_value.c_str());
}
//--------------------------------------------------------------------------------------------------------
AS::UnitType AS::Units() const {
AssertValidated();
return char_to_units(m_value[3]);
}
//--------------------------------------------------------------------------------------------------------
int32_t AS::Compare(const VR* other) const {
auto result = VR::Compare(other);
if (result) { return result; }
auto typed = static_cast<const AS*>(other);
if (Validity() == ValidityType::Invalid || typed->Validity() == ValidityType::Invalid) {
return m_value.compare(typed->m_value);
}
int32_t diff = Units() - typed->Units();
if (diff != 0) { return diff; }
diff = Age() - typed->Age();
return diff;
}
//--------------------------------------------------------------------------------------------------------
bool AS::operator == (const VR* other) const {
if (VR::Compare(other) != 0) { return false; }
auto typed = static_cast<const AS*>(other);
return (m_value == typed->m_value);
}
//--------------------------------------------------------------------------------------------------------
bool AS::operator != (const VR* other) const {
if (VR::Compare(other) != 0) { return true; }
auto typed = static_cast<const AS*>(other);
return (m_value != typed->m_value);
}
} | 32.067568 | 111 | 0.379899 | drleq |
16cffce2300c7c7bebdb06a8b07fc4f1e2e2a3ea | 4,977 | cpp | C++ | src/EspNowSerialBase.cpp | 3110/m5stack-esp-now-serial | fdca469a855c0754b5f1e5d816fc70b6415b2e34 | [
"MIT"
] | null | null | null | src/EspNowSerialBase.cpp | 3110/m5stack-esp-now-serial | fdca469a855c0754b5f1e5d816fc70b6415b2e34 | [
"MIT"
] | null | null | null | src/EspNowSerialBase.cpp | 3110/m5stack-esp-now-serial | fdca469a855c0754b5f1e5d816fc70b6415b2e34 | [
"MIT"
] | null | null | null |
#include "EspNowSerialBase.h"
const char* EspNowSerialBase::NEWLINE = "\r\n";
const uint8_t EspNowSerialBase::BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
EspNowSerialBase::EspNowSerialBase(void)
: _serial(nullptr), _channel(0), _address{0}, _buf{0} {
uint8_t addr[ESP_NOW_ETH_ALEN] = {0};
esp_read_mac(addr, ESP_MAC_WIFI_STA);
memcpy(this->_address, addr, ESP_NOW_ETH_ALEN);
}
EspNowSerialBase::~EspNowSerialBase(void) {
}
const uint8_t* const EspNowSerialBase::getAddress(void) const {
return this->_address;
}
bool EspNowSerialBase::begin(HardwareSerial& serial) {
this->_serial = &serial;
if (!WiFi.mode(WIFI_STA)) {
return false;
}
if (!WiFi.disconnect()) {
return false;
}
initEspNow();
return true;
}
bool EspNowSerialBase::setChannel(const uint8_t channel) {
this->_channel = channel;
return true;
}
size_t EspNowSerialBase::write(const char* data, size_t len) {
this->_serial->write(data, len);
#if defined(ESPNOW_INITIATOR)
len = send(data, len);
#endif
return len;
}
size_t EspNowSerialBase::printf(const char* format, ...) {
va_list args;
va_start(args, format);
va_list args_copy;
va_copy(args_copy, args);
char* loc = this->_buf;
int len = vsnprintf(loc, sizeof(this->_buf), format, args_copy);
va_end(args_copy);
if (len < 0) {
return 0;
}
if (len >= sizeof(this->_buf)) {
loc = (char*)malloc(len + 1);
if (loc == nullptr) {
return 0;
}
len = vsnprintf(loc, len + 1, format, args);
}
write(loc, len);
if (loc != this->_buf) {
free(loc);
}
return len;
}
size_t EspNowSerialBase::print(const char* str) {
return printf("%s", str);
}
size_t EspNowSerialBase::println(const char* str) {
return printf("%s%s", str, NEWLINE);
}
size_t EspNowSerialBase::println(void) {
return printf("%s", NEWLINE);
}
void EspNowSerialBase::printMacAddress(const uint8_t* macAddr) {
static char macStr[ESP_NOW_ETH_ALEN * 3 + 1] = {0};
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4],
macAddr[5]);
print(macStr);
}
void EspNowSerialBase::dump(const uint8_t* data, size_t len, uint8_t indent,
uint8_t width) {
println();
printf("Dump Length: %d", len);
println();
size_t p = 0;
for (; p < len; ++p) {
if (p % width == 0) {
if (p != 0) {
print(" |");
for (size_t cp = p - width; cp < p; ++cp) {
printf("%c", isPrintable(data[cp]) ? data[cp] : '.');
}
print("|");
println();
}
for (size_t i = 0; i < indent; ++i) {
print(" ");
}
}
printf("%02x ", data[p]);
}
if (len % width != 0) {
uint8_t remain = width - len % width;
for (size_t cp = 0; cp < remain; ++cp) {
print(" ");
}
print(" |");
for (size_t cp = len - len % width; cp < len; ++cp) {
printf("%c", isPrintable(data[cp]) ? data[cp] : '.');
}
print("|");
println();
}
}
void EspNowSerialBase::initEspNow(void) {
if (esp_now_init() != ESP_OK) {
ESP.restart();
}
}
void EspNowSerialBase::initPeer(const uint8_t* addr,
esp_now_peer_info_t& peer) {
memset(&peer, 0, sizeof(peer));
memcpy(&(peer.peer_addr), addr, ESP_NOW_ETH_ALEN);
peer.channel = this->_channel;
peer.encrypt = 0;
}
bool EspNowSerialBase::setRecvCallback(esp_now_recv_cb_t cb) {
esp_err_t e = esp_now_register_recv_cb(cb);
return e == ESP_OK;
}
bool EspNowSerialBase::setSendCallback(esp_now_send_cb_t cb) {
esp_err_t e = esp_now_register_send_cb(cb);
return e == ESP_OK;
}
bool EspNowSerialBase::registerPeer(const uint8_t* addr) {
esp_now_peer_info_t peerInfo;
initPeer(addr, peerInfo);
esp_err_t e = esp_now_add_peer(&peerInfo);
return e == ESP_OK;
}
bool EspNowSerialBase::unregisterPeer(const uint8_t* addr) {
esp_err_t e = esp_now_del_peer(addr);
return e == ESP_OK;
}
size_t EspNowSerialBase::send(const char* data, size_t len) {
esp_err_t e = ESP_OK;
esp_now_peer_info_t peer;
size_t n = 0;
for (size_t i = 0; i < len; i += n) {
n = min(sizeof(this->_buf), len - i);
memcpy(this->_buf, data + i, n);
e = esp_now_fetch_peer(true, &peer);
if (e == ESP_ERR_ESPNOW_NOT_FOUND) { // Broadcast
esp_now_send(BROADCAST_ADDRESS, (uint8_t*)this->_buf, n);
} else {
while (e == ESP_OK) {
esp_now_send(peer.peer_addr, (uint8_t*)this->_buf, n);
e = esp_now_fetch_peer(false, &peer);
}
}
}
return len;
}
| 27.196721 | 76 | 0.573639 | 3110 |
16d11e28f268c65b7aef8efe1f731e87f602a2d0 | 806 | cpp | C++ | codeforces/gym/2016 ACM Amman Collegiate Programming Contest/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/gym/2016 ACM Amman Collegiate Programming Contest/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/gym/2016 ACM Amman Collegiate Programming Contest/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
vi pali = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
map<int, int> ipal;
ipal[2] = 1;
ipal[3] = 7;
ipal[4] = 4;
ipal[5] = 5;
ipal[6] = 9;
ipal[7] = 8;
while(t--){
int n;
cin >> n;
string num;
cin >> num;
int pals = 0;
for(char c:num)
pals += pali[c-'0'];
for(int i=0; i<n; ++i){
int l = (n-i-1)*2, r = (n-i-1)*7;
for(int d=9; d>=0; --d){
int aft = pals - pali[d];
if(aft >= l and aft <= r){
pals -= pali[d];
cout << d;
break;
}
}
}
cout << endl;
}
return 0;
}
| 21.210526 | 45 | 0.331266 | tysm |
16d181156d44bc665a51ff39e88aaa8fde5ce08b | 15,633 | cpp | C++ | src/common/pl/plpython/plpy_main.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 360 | 2020-06-30T14:47:34.000Z | 2022-03-31T15:21:53.000Z | src/common/pl/plpython/plpy_main.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 4 | 2020-06-30T15:09:16.000Z | 2020-07-14T06:20:03.000Z | src/common/pl/plpython/plpy_main.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 133 | 2020-06-30T14:47:36.000Z | 2022-03-25T15:29:00.000Z | /*
* PL/Python main entry points
*
* src/common/pl/plpython/plpy_main.c
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "pgaudit.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/rel_gs.h"
#include "utils/syscache.h"
#include "plpython.h"
#include "plpy_main.h"
#include "plpy_elog.h"
#include "plpy_exec.h"
#include "plpy_plpymodule.h"
#include "plpy_procedure.h"
const int PGAUDIT_MAXLENGTH = 1024;
/* exported functions */
#if PY_MAJOR_VERSION >= 3
/* Use separate names to avoid clash in pg_pltemplate */
#define plpython_validator plpython3_validator
#define plpython_call_handler plpython3_call_handler
#define plpython_inline_handler plpython3_inline_handler
#endif
extern "C" void _PG_init(void);
extern "C" Datum plpython_validator(PG_FUNCTION_ARGS);
extern "C" Datum plpython_call_handler(PG_FUNCTION_ARGS);
extern "C" Datum plpython_inline_handler(PG_FUNCTION_ARGS);
#if PY_MAJOR_VERSION < 3
/* Define aliases plpython2_call_handler etc */
extern "C" Datum plpython2_validator(PG_FUNCTION_ARGS);
extern "C" Datum plpython2_call_handler(PG_FUNCTION_ARGS);
extern "C" Datum plpython2_inline_handler(PG_FUNCTION_ARGS);
#endif
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(plpython_validator);
PG_FUNCTION_INFO_V1(plpython_call_handler);
PG_FUNCTION_INFO_V1(plpython_inline_handler);
#if PY_MAJOR_VERSION < 3
PG_FUNCTION_INFO_V1(plpython2_validator);
PG_FUNCTION_INFO_V1(plpython2_call_handler);
PG_FUNCTION_INFO_V1(plpython2_inline_handler);
#endif
static bool PLy_procedure_is_trigger(Form_pg_proc procStruct);
static void plpython_error_callback(void* arg);
static void plpython_inline_error_callback(void* arg);
static void PLy_init_interp(void);
static PLyExecutionContext* PLy_push_execution_context(void);
static void PLy_pop_execution_context(void);
static void AuditPlpythonFunction(Oid funcoid, const char* funcname, AuditResult result);
static const int plpython_python_version = PY_MAJOR_VERSION;
/* this doesn't need to be global; use PLy_current_execution_context() */
static THR_LOCAL PLyExecutionContext* PLy_execution_contexts = NULL;
THR_LOCAL plpy_t_context_struct g_plpy_t_context = {0};
pthread_mutex_t g_plyLocaleMutex = PTHREAD_MUTEX_INITIALIZER;
void PG_init(void)
{
/* Be sure we do initialization only once (should be redundant now) */
const int** version_ptr;
if (g_plpy_t_context.inited) {
return;
}
/* Be sure we don't run Python 2 and 3 in the same session (might crash) */
version_ptr = (const int**)find_rendezvous_variable("plpython_python_version");
if (!(*version_ptr)) {
*version_ptr = &plpython_python_version;
} else {
if (**version_ptr != plpython_python_version) {
ereport(FATAL,
(errmsg("Python major version mismatch in session"),
errdetail("This session has previously used Python major version %d, and it is now attempting to "
"use Python major version %d.",
**version_ptr,
plpython_python_version),
errhint("Start a new session to use a different Python major version.")));
}
}
pg_bindtextdomain(TEXTDOMAIN);
#if PY_MAJOR_VERSION >= 3
PyImport_AppendInittab("plpy", PyInit_plpy);
#endif
#if PY_MAJOR_VERSION < 3
if (!PyEval_ThreadsInitialized()) {
PyEval_InitThreads();
}
#endif
Py_Initialize();
#if PY_MAJOR_VERSION >= 3
PyImport_ImportModule("plpy");
#endif
#if PY_MAJOR_VERSION >= 3
if (!PyEval_ThreadsInitialized()) {
PyEval_InitThreads();
PyEval_SaveThread();
}
#endif
PLy_init_interp();
PLy_init_plpy();
if (PyErr_Occurred()) {
PLy_elog(FATAL, "untrapped error in initialization");
}
init_procedure_caches();
g_plpy_t_context.explicit_subtransactions = NIL;
PLy_execution_contexts = NULL;
g_plpy_t_context.inited = true;
}
void _PG_init(void)
{
PG_init();
}
/*
* This should only be called once from _PG_init. Initialize the Python
* interpreter and global data.
*/
void PLy_init_interp(void)
{
static PyObject* PLy_interp_safe_globals = NULL;
PyObject* mainmod = NULL;
mainmod = PyImport_AddModule("__main__");
if (mainmod == NULL || PyErr_Occurred()) {
PLy_elog(ERROR, "could not import \"__main__\" module");
}
Py_INCREF(mainmod);
g_plpy_t_context.PLy_interp_globals = PyModule_GetDict(mainmod);
PLy_interp_safe_globals = PyDict_New();
if (PLy_interp_safe_globals == NULL) {
PLy_elog(ERROR, "could not create globals");
}
PyDict_SetItemString(g_plpy_t_context.PLy_interp_globals, "GD", PLy_interp_safe_globals);
Py_DECREF(mainmod);
if (g_plpy_t_context.PLy_interp_globals == NULL || PyErr_Occurred()) {
PLy_elog(ERROR, "could not initialize globals");
}
}
Datum plpython_validator(PG_FUNCTION_ARGS)
{
Oid funcoid = PG_GETARG_OID(0);
HeapTuple tuple;
Form_pg_proc procStruct;
bool is_trigger = false;
if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid)) {
PG_RETURN_VOID();
}
if (!u_sess->attr.attr_sql.check_function_bodies) {
PG_RETURN_VOID();
}
AutoMutexLock plpythonLock(&g_plyLocaleMutex);
if (g_plpy_t_context.Ply_LockLevel == 0) {
plpythonLock.lock();
}
PyLock pyLock(&(g_plpy_t_context.Ply_LockLevel));
PG_TRY();
{
PG_init();
/* Get the new function's pg_proc entry */
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
if (!HeapTupleIsValid(tuple)) {
elog(ERROR, "cache lookup failed for function %u", funcoid);
}
procStruct = (Form_pg_proc)GETSTRUCT(tuple);
is_trigger = PLy_procedure_is_trigger(procStruct);
if (is_trigger) {
elog(ERROR, "PL/Python does not support trigger");
}
ReleaseSysCache(tuple);
/* We can't validate triggers against any particular table ... */
PLy_procedure_get(funcoid, InvalidOid, is_trigger);
}
PG_CATCH();
{
pyLock.Reset();
plpythonLock.unLock();
PG_RE_THROW();
}
PG_END_TRY();
PG_RETURN_VOID();
}
#if PY_MAJOR_VERSION < 3
Datum plpython2_validator(PG_FUNCTION_ARGS)
{
return plpython_validator(fcinfo);
}
#endif /* PY_MAJOR_VERSION < 3 */
Datum plpython_call_handler(PG_FUNCTION_ARGS)
{
AutoMutexLock plpythonLock(&g_plyLocaleMutex);
if (g_plpy_t_context.Ply_LockLevel == 0) {
plpythonLock.lock();
}
Datum retval;
PLyExecutionContext* exec_ctx = NULL;
ErrorContextCallback plerrcontext;
PyLock pyLock(&(g_plpy_t_context.Ply_LockLevel));
PG_TRY();
{
PG_init();
/* Note: SPI_finish() happens in plpy_exec.cpp, which is dubious design */
if (SPI_connect() != SPI_OK_CONNECT) {
elog(ERROR, "SPI_connect failed");
}
/*
* Push execution context onto stack. It is important that this get
* popped again, so avoid putting anything that could throw error between
* here and the PG_TRY.
*/
exec_ctx = PLy_push_execution_context();
/*
* Setup error traceback support for ereport()
*/
plerrcontext.callback = plpython_error_callback;
plerrcontext.previous = t_thrd.log_cxt.error_context_stack;
t_thrd.log_cxt.error_context_stack = &plerrcontext;
}
PG_CATCH();
{
pyLock.Reset();
plpythonLock.unLock();
PG_RE_THROW();
}
PG_END_TRY();
Oid funcoid = fcinfo->flinfo->fn_oid;
PLyProcedure* proc = NULL;
PG_TRY();
{
if (CALLED_AS_TRIGGER(fcinfo)) {
elog(ERROR, "PL/Python does not support trigger");
Relation tgrel = ((TriggerData*)fcinfo->context)->tg_relation;
HeapTuple trv;
proc = PLy_procedure_get(funcoid, RelationGetRelid(tgrel), true);
exec_ctx->curr_proc = proc;
trv = PLy_exec_trigger(fcinfo, proc);
retval = PointerGetDatum(trv);
} else {
proc = PLy_procedure_get(funcoid, InvalidOid, false);
exec_ctx->curr_proc = proc;
retval = PLy_exec_function(fcinfo, proc);
if (AUDIT_EXEC_ENABLED) {
AuditPlpythonFunction(funcoid, proc->proname, AUDIT_OK);
}
}
}
PG_CATCH();
{
if (AUDIT_EXEC_ENABLED) {
AuditPlpythonFunction(funcoid, proc->proname, AUDIT_FAILED);
}
PLy_pop_execution_context();
PyErr_Clear();
pyLock.Reset();
plpythonLock.unLock();
PG_RE_THROW();
}
PG_END_TRY();
PG_TRY();
{
/* Pop the error context stack */
t_thrd.log_cxt.error_context_stack = plerrcontext.previous;
/* ... and then the execution context */
PLy_pop_execution_context();
}
PG_CATCH();
{
pyLock.Reset();
plpythonLock.unLock();
PG_RE_THROW();
}
PG_END_TRY();
return retval;
}
#if PY_MAJOR_VERSION < 3
Datum plpython2_call_handler(PG_FUNCTION_ARGS)
{
return plpython_call_handler(fcinfo);
}
#endif /* PY_MAJOR_VERSION < 3 */
Datum plpython_inline_handler(PG_FUNCTION_ARGS)
{
AutoMutexLock plpythonLock(&g_plyLocaleMutex);
if (g_plpy_t_context.Ply_LockLevel == 0) {
plpythonLock.lock();
}
PyLock pyLock(&(g_plpy_t_context.Ply_LockLevel));
InlineCodeBlock* codeblock = (InlineCodeBlock*)DatumGetPointer(PG_GETARG_DATUM(0));
FunctionCallInfoData fake_fcinfo;
FmgrInfo flinfo;
PLyProcedure proc;
PLyExecutionContext* exec_ctx = NULL;
ErrorContextCallback plerrcontext;
errno_t rc = EOK;
PG_TRY();
{
PG_init();
/* Note: SPI_finish() happens in plpy_exec.c, which is dubious design */
if (SPI_connect() != SPI_OK_CONNECT) {
elog(ERROR, "SPI_connect failed");
}
rc = memset_s(&fake_fcinfo, sizeof(fake_fcinfo), 0, sizeof(fake_fcinfo));
securec_check(rc, "\0", "\0");
rc = memset_s(&flinfo, sizeof(flinfo), 0, sizeof(flinfo));
securec_check(rc, "\0", "\0");
fake_fcinfo.flinfo = &flinfo;
flinfo.fn_oid = InvalidOid;
flinfo.fn_mcxt = CurrentMemoryContext;
rc = memset_s(&proc, sizeof(PLyProcedure), 0, sizeof(PLyProcedure));
securec_check(rc, "\0", "\0");
proc.pyname = PLy_strdup("__plpython_inline_block");
proc.result.out.d.typoid = VOIDOID;
/*
* Push execution context onto stack. It is important that this get
* popped again, so avoid putting anything that could throw error between
* here and the PG_TRY. (plpython_inline_error_callback doesn't currently
* need the stack entry, but for consistency with plpython_call_handler we
* do it in this order.)
*/
exec_ctx = PLy_push_execution_context();
/*
* Setup error traceback support for ereport()
*/
plerrcontext.callback = plpython_inline_error_callback;
plerrcontext.previous = t_thrd.log_cxt.error_context_stack;
t_thrd.log_cxt.error_context_stack = &plerrcontext;
}
PG_CATCH();
{
plpythonLock.unLock();
pyLock.Reset();
PG_RE_THROW();
}
PG_END_TRY();
PG_TRY();
{
PLy_procedure_compile(&proc, codeblock->source_text);
exec_ctx->curr_proc = &proc;
PLy_exec_function(&fake_fcinfo, &proc);
if (AUDIT_EXEC_ENABLED) {
AuditPlpythonFunction(InvalidOid, proc.pyname, AUDIT_OK);
}
}
PG_CATCH();
{
if (AUDIT_EXEC_ENABLED) {
AuditPlpythonFunction(InvalidOid, proc.pyname, AUDIT_FAILED);
}
PLy_pop_execution_context();
PLy_procedure_delete(&proc);
PyErr_Clear();
plpythonLock.unLock();
pyLock.Reset();
PG_RE_THROW();
}
PG_END_TRY();
PG_TRY();
{
/* Pop the error context stack */
t_thrd.log_cxt.error_context_stack = plerrcontext.previous;
/* ... and then the execution context */
PLy_pop_execution_context();
/* Now clean up the transient procedure we made */
PLy_procedure_delete(&proc);
}
PG_CATCH();
{
plpythonLock.unLock();
pyLock.Reset();
PG_RE_THROW();
}
PG_END_TRY();
PG_RETURN_VOID();
}
#if PY_MAJOR_VERSION < 3
Datum plpython2_inline_handler(PG_FUNCTION_ARGS)
{
return plpython_inline_handler(fcinfo);
}
#endif /* PY_MAJOR_VERSION < 3 */
static bool PLy_procedure_is_trigger(Form_pg_proc procStruct)
{
return (procStruct->prorettype == TRIGGEROID || (procStruct->prorettype == OPAQUEOID && procStruct->pronargs == 0));
}
static void plpython_error_callback(void* arg)
{
PLyExecutionContext* exec_ctx = PLy_current_execution_context();
if (AUDIT_EXEC_ENABLED) {
AuditPlpythonFunction(InvalidOid, PLy_procedure_name(exec_ctx->curr_proc), AUDIT_FAILED);
}
if (exec_ctx->curr_proc != NULL) {
errcontext("PL/Python function \"%s\"", PLy_procedure_name(exec_ctx->curr_proc));
}
}
static void plpython_inline_error_callback(void* arg)
{
if (AUDIT_EXEC_ENABLED) {
AuditPlpythonFunction(InvalidOid, "__plpython_inline_block", AUDIT_FAILED);
}
errcontext("PL/Python anonymous code block");
}
PLyExecutionContext* PLy_current_execution_context(void)
{
if (PLy_execution_contexts == NULL) {
elog(ERROR, "no Python function is currently executing");
}
return PLy_execution_contexts;
}
static PLyExecutionContext* PLy_push_execution_context(void)
{
PLyExecutionContext* context = (PLyExecutionContext*)PLy_malloc(sizeof(PLyExecutionContext));
context->curr_proc = NULL;
context->scratch_ctx = AllocSetContextCreate(u_sess->top_transaction_mem_cxt,
"PL/Python scratch context",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
context->next = PLy_execution_contexts;
PLy_execution_contexts = context;
return context;
}
static void PLy_pop_execution_context(void)
{
PLyExecutionContext* context = PLy_execution_contexts;
if (context == NULL) {
elog(ERROR, "no Python function is currently executing");
}
PLy_execution_contexts = context->next;
MemoryContextDelete(context->scratch_ctx);
PLy_free(context);
}
static void AuditPlpythonFunction(Oid funcoid, const char* funcname, AuditResult result)
{
char details[PGAUDIT_MAXLENGTH];
errno_t rc = EOK;
if (result == AUDIT_OK) {
if (funcoid == InvalidOid) {
// for AnonymousBlock
rc = snprintf_s(details, PGAUDIT_MAXLENGTH, PGAUDIT_MAXLENGTH - 1,
"Execute Plpython anonymous code block(oid = %u). ", funcoid);
} else {
// for normal function
rc = snprintf_s(details, PGAUDIT_MAXLENGTH, PGAUDIT_MAXLENGTH - 1,
"Execute PLpython function(oid = %u). ", funcoid);
}
} else {
// for abnormal function
rc = snprintf_s(details, PGAUDIT_MAXLENGTH, PGAUDIT_MAXLENGTH - 1,
"Execute PLpython function(%s). ", funcname);
}
securec_check_ss(rc, "", "");
audit_report(AUDIT_FUNCTION_EXEC, result, funcname, details);
}
| 28.372051 | 120 | 0.665004 | opengauss-mirror |
16d1e27ce68b98c221d0b8cec84b21c8674c94ac | 1,568 | cpp | C++ | src/kv/File.cpp | kushview/decibels | db7298fe4c1ca25a5eb0ddf5b5e481a52fa67aff | [
"0BSD"
] | 3 | 2020-11-14T05:51:35.000Z | 2021-01-18T03:47:55.000Z | src/kv/File.cpp | kushview/lua-rt | db7298fe4c1ca25a5eb0ddf5b5e481a52fa67aff | [
"0BSD"
] | 2 | 2021-02-24T16:44:03.000Z | 2021-02-24T17:28:58.000Z | src/kv/File.cpp | kushview/lua-kv | db7298fe4c1ca25a5eb0ddf5b5e481a52fa67aff | [
"0BSD"
] | null | null | null | /// A file or directory on your system.
// @classmod kv.File
// @pragma nostrip
#include "lua-kv.hpp"
#include LKV_JUCE_HEADER
#define LKV_TYPE_NAME_FILE "File"
using namespace juce;
LKV_EXPORT
int luaopen_kv_File (lua_State* L) {
sol::state_view lua (L);
auto t = lua.create_table();
t.new_usertype<File> (LKV_TYPE_NAME_FILE, sol::no_constructor,
sol::call_constructor, sol::factories (
/// Non-existent file
// @function File.__call
// @within Metamethods
[]() { return File(); },
/// File from absolute path
// @string abspath Absolute file path.
// @function File.__call
// @within Metamethods
// @usage
// local f = kv.File ("/path/to/file/or/dir")
// -- do something with file
[](const char* path) { return File (String::fromUTF8 (path)); }
),
/// File name with extension (string)(readonly).
// @class field
// @name File.name
// @within Attributes
"name", sol::readonly_property ([](File& self) {
return self.getFileName().toStdString();
}),
/// Absolute file path (string)(readonly).
// @class field
// @name File.path
// @within Attributes
"path", sol::readonly_property ([](File& self) {
return self.getFullPathName().toStdString();
})
);
auto M = t.get<sol::table> (LKV_TYPE_NAME_FILE);
t.clear();
sol::stack::push (L, M);
return 1;
}
| 29.037037 | 75 | 0.552934 | kushview |
16d21cfa513614ef99c27e015c5d3c98e305788b | 5,565 | cc | C++ | dcmdata/tests/tvrdatim.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 10 | 2016-07-03T12:16:58.000Z | 2021-12-18T06:15:50.000Z | dcmdata/tests/tvrdatim.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 1 | 2020-04-30T07:55:55.000Z | 2020-04-30T07:55:55.000Z | dcmdata/tests/tvrdatim.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 9 | 2017-02-09T02:16:39.000Z | 2021-01-06T02:49:24.000Z | /*
*
* Copyright (C) 2002-2013, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Joerg Riesmeier
*
* Purpose: test program for classes DcmDate, DcmTime and DcmDateTime
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/ofstd/oftest.h"
#include "dcmtk/dcmdata/dcvrda.h"
#include "dcmtk/dcmdata/dcvrtm.h"
#include "dcmtk/dcmdata/dcvrdt.h"
#include "dcmtk/dcmdata/dcdeftag.h"
#define CHECK_EQUAL(string) do { \
strstream << OFStringStream_ends; \
OFSTRINGSTREAM_GETOFSTRING(strstream, res); \
OFCHECK_EQUAL(res, string); \
strstream.clear(); \
strstream.str(""); \
} while (0)
#define CHECK_STREAM_EQUAL(val, string) do { \
strstream << val; \
CHECK_EQUAL(string); \
strstream.clear(); \
strstream.str(""); \
} while(0)
OFTEST(dcmdata_dateTime)
{
double timeZone;
OFDate dateVal;
OFTime timeVal;
OFDateTime dateTime;
OFString string;
DcmDate dcmDate(DCM_StudyDate);
DcmTime dcmTime(DCM_StudyTime);
DcmDateTime dcmDateTime(DCM_DateTime);
OFOStringStream strstream;
// Determine the local time zone, needed because setOFTime loses the timezone
timeVal.setCurrentTime();
const double localTimeZone = timeVal.getTimeZone();
OFDate curDateVal(2011, 5, 9);
OFTime curTimeVal(10, 35, 20, localTimeZone);
OFDateTime curDateTimeVal(curDateVal, curTimeVal);
dcmDate.setOFDate(curDateVal);
dcmDate.print(strstream);
CHECK_EQUAL("(0008,0020) DA [20110509] # 8, 1 StudyDate\n");
OFCHECK(dcmDate.getOFDate(dateVal).good());
OFCHECK_EQUAL(dateVal, curDateVal);
dcmTime.setOFTime(curTimeVal);
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [103520] # 6, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
OFCHECK_EQUAL(timeVal, curTimeVal);
dcmDateTime.setOFDateTime(curDateTimeVal);
dcmDateTime.print(strstream);
CHECK_EQUAL("(0040,a120) DT [20110509103520] # 14, 1 DateTime\n");
OFCHECK(dcmDateTime.getOFDateTime(dateTime).good());
OFCHECK_EQUAL(dateTime, curDateTimeVal);
OFCHECK(dateTime.getISOFormattedDateTime(string, OFTrue /*seconds*/, OFTrue /*fraction*/, OFFalse /*timeZone*/, OFFalse /*delimiter*/));
OFCHECK_EQUAL(string, "20110509103520.000000");
dcmTime.putString("12");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [12] # 2, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:00:00");
dcmTime.putString("1203");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [1203] # 4, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:00");
dcmTime.putString("120315");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [120315] # 6, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:15");
dcmTime.putString("120301.99");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [120301.99] # 10, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
timeVal.getISOFormattedTime(string, OFTrue /*seconds*/, OFTrue /*fraction*/, OFFalse /*timeZone*/);
OFCHECK_EQUAL(string, "12:03:01.990000");
dcmTime.putString("12:03");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [12:03] # 6, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:00");
dcmTime.putString("12:03:15");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [12:03:15] # 8, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:15");
OFCHECK(DcmTime::getTimeZoneFromString("+0030", timeZone).good());
OFCHECK_EQUAL(timeZone, 0.5);
OFCHECK(DcmTime::getTimeZoneFromString("+1130", timeZone).good());
OFCHECK_EQUAL(timeZone, 11.5);
OFCHECK(DcmTime::getTimeZoneFromString("-0100", timeZone).good());
OFCHECK_EQUAL(timeZone, -1);
OFCHECK(DcmTime::getTimeZoneFromString("-0530", timeZone).good());
OFCHECK_EQUAL(timeZone, -5.5);
OFCHECK(DcmTime::getTimeZoneFromString("01130", timeZone).bad());
OFCHECK(DcmTime::getTimeZoneFromString("+100", timeZone).bad());
OFCHECK(DcmTime::getTimeZoneFromString("UTC+1", timeZone).bad());
dcmDateTime.putString("200204101203+0500");
dcmDateTime.print(strstream);
CHECK_EQUAL("(0040,a120) DT [200204101203+0500] # 18, 1 DateTime\n");
OFCHECK(dcmDateTime.getOFDateTime(dateTime).good());
CHECK_STREAM_EQUAL(dateTime, "2002-04-10 12:03:00");
dcmDateTime.putString("20020410");
dcmDateTime.print(strstream);
CHECK_EQUAL("(0040,a120) DT [20020410] # 8, 1 DateTime\n");
OFCHECK(dcmDateTime.getOFDateTime(dateTime).good());
dateTime.getISOFormattedDateTime(string, OFTrue /*seconds*/, OFFalse /*fraction*/, OFFalse /*timeZone*/);
OFCHECK_EQUAL(string, "2002-04-10 00:00:00");
}
| 38.37931 | 140 | 0.647978 | trice-imaging |
16d3368bb7c27f39a0da056372a016210b6ccbe8 | 1,225 | cpp | C++ | DigitalTriangle/DigitalTriangle11.cpp | nananjy/DynamicPlanning | 03c96c6dca92f5b3c82fceb5e061e93c1d22edfd | [
"Apache-2.0"
] | 1 | 2017-12-28T13:46:35.000Z | 2017-12-28T13:46:35.000Z | DigitalTriangle/DigitalTriangle11.cpp | nananjy/DynamicPlanning | 03c96c6dca92f5b3c82fceb5e061e93c1d22edfd | [
"Apache-2.0"
] | null | null | null | DigitalTriangle/DigitalTriangle11.cpp | nananjy/DynamicPlanning | 03c96c6dca92f5b3c82fceb5e061e93c1d22edfd | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
/**
* 利用动态规划思想求解数字三角形(POJ 1163), 题目来源IOI 1994
* 将一个问题分解为子问题递归求解,并且将中间结果保存以避免重复计算的办法
* 1.问题具有最优子结构性质(问题的最优解所包含的子问题的解也是最优的)
* 2.无后效性(当前若干个状态值一旦确定,此后过程的演变就只和这若干个状态值有关,与之前采取哪种方式演变到若干个状态无关)
* 问题描述:求出累加和最大的最佳路径上的数字之和,
* 路径上每一步只能从一个数走到下一层和它最近的左边的数或右边的数。
* @author 作者名
*/
#define MAX_NUM 100
int d[MAX_NUM + 10][MAX_NUM + 10];//存放待计算的数字三角形
int N;//存放行数
int maxSum[MAX_NUM + 10][MAX_NUM + 10];//存放当前数字到底边的最佳路径之和
/**
* 计算路径和
* @r 数字三角形的行
* @j 数字三角形的列
* @return 从第i行第j列的数字到底边的最佳路径和
*/
int MaxSum(int r, int j)
{
if(r == N)
return d[r][j];//底边数字的路径和即为数字本身
if(maxSum[r+1][j] == -1)//如果MaxSum(r+1, j)没有计算过
maxSum[r+1][j] = MaxSum(r+1, j);
if(maxSum[r+1][j+1] == -1)//如果MaxSum(r+1, j+1)没有计算过
maxSum[r+1][j+1] = MaxSum(r+1, j+1);
if(maxSum[r+1][j] > maxSum[r+1][j+1])
return maxSum[r+1][j] + d[r][j];
return maxSum[r+1][j+1] + d[r][j];//返回当前数字到底边的最佳路径和
}
/**
* 输入数字三角形
*/
int main()
{
scanf("%d", &N);//输入行数
//将maxSum全部置成-1, 表示开始所有的MaxSum(r, j)都没有计算过
memset(maxSum, -1, sizeof(maxSum));
for(int i = 1; i <= N; i++)
for(int j = 1; j <= i; j++)
scanf("%d", &d[i][j]);//输入数字三角形
printf("%d", MaxSum(1, 1));//输出最佳路径和
return 0;
}
| 23.113208 | 63 | 0.64 | nananjy |
16d43efb37d4ed9a4328173e3ada098bdfc0373b | 2,383 | cpp | C++ | Competitive Programing Problem Solutions/UVA/11800 - Determine the Shape.cpp | BIJOY-SUST/ACM---ICPC | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | 1 | 2022-02-27T12:07:59.000Z | 2022-02-27T12:07:59.000Z | Competitive Programing Problem Solutions/UVA/11800 - Determine the Shape.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | Competitive Programing Problem Solutions/UVA/11800 - Determine the Shape.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
//#define mx 100010
//#define mod 1000000007
#define pi 2*acos(0.0)
//#define ll long long int
//#define pp pair<int,int>
//#define ull unsigned long long int
//#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c
//#define mem(arr,val) memset(arr,val,sizeof(arr))
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};
//int biton(int p,int pos){return p=p|(1<<pos);}
//int bitoff(int p,int pos){return p=p&~(1<<pos);}
//bool bitcheck(int p,int pos){return (bool)(p&(1<<pos));}
//ll POW(ll b,ll p) {ll Ans=1; while(p){if(p&1)Ans=(Ans*b);b=(b*b);p>>=1;}return Ans;}
//ll BigMod(ll b,ll p,ll Mod) {ll Ans=1; while(p){if(p&1)Ans=(Ans*b)%Mod;b=(b*b)%Mod;p>>=1;}return Ans;}
//ll ModInverse(ll p,ll Mod) {return BigMod(p,Mod-2,Mod);}
using namespace std;
double dis(double x1,double y1,double x2,double y2){
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
int main(){
// freopen("Input.txt","r",stdin); freopen("Output.txt","w",stdout);
// ios_base::sync_with_stdio(false); cin.tie(NULL);
int t;
scanf("%d",&t);
for(int cs=1;cs<=t;cs++){
double x1,y1,x2,y2,x3,y3,x4,y4;
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4);
double a=dis(x1,y1,x2,y2);
double b=dis(x2,y2,x3,y3);
double c=dis(x3,y3,x4,y4);
double d=dis(x4,y4,x1,y1);
double ac=dis(x4,y4,x2,y2);
double bd=dis(x1,y1,x3,y3);
// double angle_da=(180.0/(1.0*pi))*acos((a*a+d*d-ac*ac)/(2.0*a*d));
// double angle_ab=(180.0/(1.0*pi))*acos((a*a+b*b-bd*bd)/(2.0*a*b));
// double angle_bc=(180.0/(1.0*pi))*acos((b*b+c*c-ac*ac)/(2.0*b*c));
// double angle_cd=(180.0/(1.0*pi))*acos((c*c+d*d-bd*bd)/(2.0*c*d));
// cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
// cout<<setprecision(5)<<angle_da<<" "<<angle_ab<<" "<<angle_bc<<" "<<angle_cd<<endl;
if(a==b&&b==c&&c==d){
printf("Case %d: Square\n",cs);
}
}
return 0;
}
/**
Input:
6
0 0
2 0
2 2
0 2
0 0
3 0
3 2
0 2
0 0
8 4
5 0
3 4
0 0
2 0
3 2
1 2
0 0
5 0
4 3
1 3
0 0
5 0
4 3
1 4
Output:
Case 1: Square
Case 2: Rectangle
Case 3: Rhombus
Case 4: Parallelogram
Case 5: Trapezium
Case 6: Ordinary Quadrilateral
**/
| 28.710843 | 105 | 0.524549 | BIJOY-SUST |
16d9aead6539584257b48eb97868cfc4e78e693e | 4,416 | cc | C++ | verity/verity_main.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | verity/verity_main.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | verity/verity_main.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by the GPL v2 license that can
// be found in the LICENSE file.
//
// Driver program for creating verity hash images.
#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <base/files/file.h>
#include <base/logging.h>
#include <brillo/syslog_logging.h>
#include "verity/file_hasher.h"
namespace {
void print_usage(const char* name) {
// We used to advertise more algorithms, but they've never been implemented:
// sha512 sha384 sha mdc2 ripemd160 md4 md2
fprintf(
stderr,
"Usage:\n"
" %s <arg>=<value>...\n"
"Options:\n"
" mode One of 'create' or 'verify'\n"
" alg Hash algorithm to use. Only sha256 for now\n"
" payload Path to the image to hash\n"
" payload_blocks Size of the image, in blocks (4096 bytes)\n"
" hashtree Path to a hash tree to create or read from\n"
" root_hexdigest Digest of the root node (in hex) for verification\n"
" salt Salt (in hex)\n"
"\n",
name);
}
typedef enum { VERITY_NONE = 0, VERITY_CREATE, VERITY_VERIFY } verity_mode_t;
static unsigned int parse_blocks(const char* block_s) {
return (unsigned int)strtoul(block_s, NULL, 0);
}
} // namespace
static int verity_create(const char* alg,
const char* image_path,
unsigned int image_blocks,
const char* hash_path,
const char* salt);
void splitarg(char* arg, char** key, char** val) {
char* sp = NULL;
*key = strtok_r(arg, "=", &sp);
*val = strtok_r(NULL, "=", &sp);
}
int main(int argc, char** argv) {
verity_mode_t mode = VERITY_CREATE;
const char* alg = NULL;
const char* payload = NULL;
const char* hashtree = NULL;
const char* salt = NULL;
unsigned int payload_blocks = 0;
int i;
char *key, *val;
for (i = 1; i < argc; i++) {
splitarg(argv[i], &key, &val);
if (!key)
continue;
if (!val) {
fprintf(stderr, "missing value: %s\n", key);
print_usage(argv[0]);
return -1;
}
if (!strcmp(key, "alg")) {
alg = val;
} else if (!strcmp(key, "payload")) {
payload = val;
} else if (!strcmp(key, "payload_blocks")) {
payload_blocks = parse_blocks(val);
} else if (!strcmp(key, "hashtree")) {
hashtree = val;
} else if (!strcmp(key, "root_hexdigest")) {
// Silently drop root_hexdigest for now...
} else if (!strcmp(key, "mode")) {
// Silently drop the mode for now...
} else if (!strcmp(key, "salt")) {
salt = val;
} else {
fprintf(stderr, "bogus key: '%s'\n", key);
print_usage(argv[0]);
return -1;
}
}
if (!alg || !payload || !hashtree) {
fprintf(stderr, "missing data: %s%s%s\n", alg ? "" : "alg ",
payload ? "" : "payload ", hashtree ? "" : "hashtree");
print_usage(argv[0]);
return -1;
}
if (mode == VERITY_CREATE) {
return verity_create(alg, payload, payload_blocks, hashtree, salt);
} else {
LOG(FATAL) << "Verification not done yet";
}
return -1;
}
static int verity_create(const char* alg,
const char* image_path,
unsigned int image_blocks,
const char* hash_path,
const char* salt) {
auto source = std::make_unique<base::File>(
base::FilePath(image_path),
base::File::FLAG_OPEN | base::File::FLAG_READ);
LOG_IF(FATAL, source && !source->IsValid())
<< "Failed to open the source file: " << image_path;
auto destination = std::make_unique<base::File>(
base::FilePath(hash_path),
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
LOG_IF(FATAL, destination && !destination->IsValid())
<< "Failed to open destination file: " << hash_path;
// Create the actual worker and create the hash image.
verity::FileHasher hasher(std::move(source), std::move(destination),
image_blocks, alg);
LOG_IF(FATAL, !hasher.Initialize()) << "Failed to initialize hasher";
if (salt)
hasher.set_salt(salt);
LOG_IF(FATAL, !hasher.Hash()) << "Failed to hash hasher";
LOG_IF(FATAL, !hasher.Store()) << "Failed to store hasher";
hasher.PrintTable(true);
return 0;
}
| 31.769784 | 79 | 0.588995 | Toromino |
16dca7140d3fc2d455f4652f94d73f73ec3f922f | 20,346 | hpp | C++ | src/SingleLayerOptics/src/MaterialDescription.hpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 15 | 2018-04-20T19:16:50.000Z | 2022-02-11T04:11:41.000Z | src/SingleLayerOptics/src/MaterialDescription.hpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 31 | 2016-04-05T20:56:28.000Z | 2022-03-31T22:02:46.000Z | src/SingleLayerOptics/src/MaterialDescription.hpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 6 | 2018-04-20T19:38:58.000Z | 2020-04-06T00:30:47.000Z | #ifndef MATERIALDESCRIPTION_H
#define MATERIALDESCRIPTION_H
#include <memory>
#include <vector>
#include <map>
#include <functional>
#include <WCESpectralAveraging.hpp>
#include "BeamDirection.hpp" // Need to include rather than forward declare to default incoming and outgoing directions to CBeamDirection()
#include "BSDFDirections.hpp" // Needed to have CBSDFHemisphere as a member of the BSDF materials. Could forward declare if BSDF material was changed to hide members using the pimpl ideom.
namespace FenestrationCommon
{
enum class Side;
enum class Property;
enum class MaterialType;
enum class WavelengthRange;
class CSeries;
} // namespace FenestrationCommon
namespace SpectralAveraging
{
// enum class SampleProperty;
class CSpectralSample;
class CPhotovoltaicSample;
class CAngularSpectralSample;
class CSingleAngularMeasurement;
class CAngularMeasurements;
} // namespace SpectralAveraging
namespace SingleLayerOptics
{
class CSurface;
struct RMaterialProperties
{
public:
RMaterialProperties(double aTf, double aTb, double aRf, double aRb);
double getProperty(FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side) const;
private:
std::map<FenestrationCommon::Side, std::shared_ptr<CSurface>> m_Surface;
};
static double NIRRatio = 0.49;
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterial
//////////////////////////////////////////////////////////////////////////////////////////
//! \breif Base virtual class for any material definition.
//!
//! It represents material properties over the certain wavelength range. It also defines
//! interface for angular dependency of material properties.
class CMaterial
{
public:
CMaterial(double minLambda, double maxLambda);
explicit CMaterial(FenestrationCommon::WavelengthRange t_Range);
virtual void setSourceData(FenestrationCommon::CSeries &);
virtual void setDetectorData(FenestrationCommon::CSeries & t_DetectorData);
// Get certain material property over the entire range
virtual double
getProperty(FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const = 0;
// Get properties for every band defined in the material
virtual std::vector<double> getBandProperties(
FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const = 0;
std::vector<RMaterialProperties> getBandProperties();
std::shared_ptr<SpectralAveraging::CSpectralSample> getSpectralSample();
std::vector<double> getBandWavelengths();
virtual void setBandWavelengths(const std::vector<double> & wavelengths);
size_t getBandSize();
// Return index of wavelength range for passed value. Returns -1 if index is out of range
int getBandIndex(double t_Wavelength);
double getMinLambda() const;
double getMaxLambda() const;
virtual void Flipped(bool flipped);
[[nodiscard]] bool isWavelengthInRange(double wavelength) const;
protected:
double m_MinLambda;
double m_MaxLambda;
std::vector<double> trimWavelengthToRange(const std::vector<double> & wavelengths) const;
// Set state in order not to calculate wavelengths every time
virtual std::vector<double> calculateBandWavelengths() = 0;
bool m_WavelengthsCalculated;
std::vector<double> m_Wavelengths;
};
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterialSingleBand
//////////////////////////////////////////////////////////////////////////////////////////
//! \brief Simple material with no angular dependence on reflection or transmittance.
//!
//! This is mainly used for shading device materials
class CMaterialSingleBand : public CMaterial
{
public:
CMaterialSingleBand(
double t_Tf, double t_Tb, double t_Rf, double t_Rb, double minLambda, double maxLambda);
CMaterialSingleBand(double t_Tf,
double t_Tb,
double t_Rf,
double t_Rb,
FenestrationCommon::WavelengthRange t_Range);
double
getProperty(FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
std::vector<double> getBandProperties(
FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
private:
std::vector<double> calculateBandWavelengths() override;
protected:
std::map<FenestrationCommon::Side, std::shared_ptr<CSurface>> m_Property;
};
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterialSingleBandBSDF
//////////////////////////////////////////////////////////////////////////////////////////
//! \brief Simple material with angular dependence on reflection or transmittance.
//!
//! This is mainly used for shading device materials
class CMaterialSingleBandBSDF : public CMaterial
{
public:
CMaterialSingleBandBSDF(std::vector<std::vector<double>> const & t_Tf,
std::vector<std::vector<double>> const & t_Tb,
std::vector<std::vector<double>> const & t_Rf,
std::vector<std::vector<double>> const & t_Rb,
CBSDFHemisphere const & t_Hemisphere,
double minLambda,
double maxLambda);
CMaterialSingleBandBSDF(std::vector<std::vector<double>> const & t_Tf,
std::vector<std::vector<double>> const & t_Tb,
std::vector<std::vector<double>> const & t_Rf,
std::vector<std::vector<double>> const & t_Rb,
CBSDFHemisphere const & t_Hemisphere,
FenestrationCommon::WavelengthRange t_Range);
double
getProperty(FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
std::vector<double> getBandProperties(
FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
std::vector<std::vector<double>> const &
getBSDFMatrix(FenestrationCommon::Property const & t_Property,
FenestrationCommon::Side const & t_Side) const;
CBSDFHemisphere getHemisphere() const;
private:
std::vector<double> calculateBandWavelengths() override;
// Checks to make sure a matrix has the same number of values as the BSDF hemisphere
// has directions. Assumption: All the inner vectors have the same number of values
// This should probably be somewhere more general, just putting it here for now
void validateMatrix(std::vector<std::vector<double>> const & matrix,
CBSDFHemisphere const & m_Hemisphere) const;
protected:
std::map<std::pair<FenestrationCommon::Property, FenestrationCommon::Side>,
std::vector<std::vector<double>>>
m_Property;
CBSDFHemisphere m_Hemisphere;
};
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterialDualBand
//////////////////////////////////////////////////////////////////////////////////////////
//! \brief Material that for given solar and partial range (visible, uv) will calculate
//! equivalent optical properties for the entire range
class IMaterialDualBand : public CMaterial
{
public:
// ratio is calculated outside of the class and can be provided here.
// TODO: Need to confirm with the team if we actually need this approach
// (ratio should be calculated and not quessed)
IMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange,
const std::shared_ptr<CMaterial> & t_FullRange,
double t_Ratio = NIRRatio);
// ratio is calculated based on provided solar radiation values
IMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange,
const std::shared_ptr<CMaterial> & t_FullRange,
const FenestrationCommon::CSeries & t_SolarRadiation);
void setSourceData(FenestrationCommon::CSeries & t_SourceData) override;
void setDetectorData(FenestrationCommon::CSeries & t_DetectorData) override;
double
getProperty(FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
std::vector<double> getBandProperties(
FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
protected:
std::vector<double> calculateBandWavelengths() override;
// Checks if material is within valid range. Otherwise, algorithm is not valid.
void checkIfMaterialWithingSolarRange(const CMaterial & t_Material) const;
void createUVRange();
// Creates after UV range and stores data into m_Materials
virtual void createNIRRange(const std::shared_ptr<CMaterial> & t_PartialRange,
const std::shared_ptr<CMaterial> & t_SolarRange,
double t_Fraction) = 0;
// Creates all of the required ranges in m_Materials from a ratio
void createRangesFromRatio(double t_Ratio);
// Creates all of the required ranges in m_Materials from solar radiation
void createRangesFromSolarRadiation(const FenestrationCommon::CSeries & t_SolarRadiation);
std::vector<double> getWavelengthsFromMaterials() const;
// Properties over the rest of range will depend on partial range as well.
// We do want to keep correct properties of partial range, but will want to update
// properties for other partial ranges that are not provided by the user.
// double getModifiedProperty(double t_Range, double t_Solar, double t_Fraction) const;
std::shared_ptr<CMaterial> getMaterialFromWavelegth(double wavelength) const;
std::shared_ptr<CMaterial> m_MaterialFullRange;
std::shared_ptr<CMaterial> m_MaterialPartialRange;
std::function<void(void)> m_RangeCreator;
std::vector<std::shared_ptr<CMaterial>> m_Materials;
};
class CMaterialDualBand : public IMaterialDualBand
{
public:
// ratio is calculated outside of the class and can be provided here.
// TODO: Need to confirm with the team if we actually need this approach
// (ratio should be calculated and not quessed)
CMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange,
const std::shared_ptr<CMaterial> & t_FullRange,
double t_Ratio = NIRRatio);
// ratio is calculated based on provided solar radiation values
CMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange,
const std::shared_ptr<CMaterial> & t_FullRange,
const FenestrationCommon::CSeries & t_SolarRadiation);
private:
// Creates after UV range and stores data into m_Materials
virtual void createNIRRange(const std::shared_ptr<CMaterial> & t_PartialRange,
const std::shared_ptr<CMaterial> & t_FullRange,
double t_Fraction) override;
};
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterialDualBandBSDF
//////////////////////////////////////////////////////////////////////////////////////////
//! \brief Material that for given solar and partial range (visible, uv) will calculate
//! equivalent optical properties for the entire range. Uses BSDF matrices and results are
//! therefore angular dependent.
class CMaterialDualBandBSDF : public IMaterialDualBand
{
public:
// ratio is calculated outside of the class and can be provided here.
// TODO: Need to confirm with the team if we actually need this approach
// (ratio should be calculated and not quessed)
CMaterialDualBandBSDF(const std::shared_ptr<CMaterialSingleBandBSDF> & t_PartialRange,
const std::shared_ptr<CMaterialSingleBandBSDF> & t_FullRange,
double t_Ratio = NIRRatio);
// ratio is calculated based on provided solar radiation values
CMaterialDualBandBSDF(const std::shared_ptr<CMaterialSingleBandBSDF> & t_PartialRange,
const std::shared_ptr<CMaterialSingleBandBSDF> & t_FullRange,
const FenestrationCommon::CSeries & t_SolarRadiation);
protected:
// Creates after UV range and stores data into m_Materials
void createNIRRange(const std::shared_ptr<CMaterial> & t_PartialRange,
const std::shared_ptr<CMaterial> & t_SolarRange,
double t_Fraction) override;
};
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterialSample
//////////////////////////////////////////////////////////////////////////////////////////
//! /brief Material that contains data measured over the range of wavelengths.
//!
//! It also provides material properties at certain angle. Assumes that material properties
//! at certain angle can be calculated by using coated and uncoated algorithms
class CMaterialSample : public CMaterial
{
public:
CMaterialSample(
const std::shared_ptr<SpectralAveraging::CSpectralSample> & t_SpectralSample,
double t_Thickness,
FenestrationCommon::MaterialType t_Type,
double minLambda,
double maxLambda);
CMaterialSample(
const std::shared_ptr<SpectralAveraging::CSpectralSample> & t_SpectralSample,
double t_Thickness,
FenestrationCommon::MaterialType t_Type,
FenestrationCommon::WavelengthRange t_Range);
void setSourceData(FenestrationCommon::CSeries & t_SourceData) override;
void setDetectorData(FenestrationCommon::CSeries & t_DetectorData) override;
// In this case sample property is taken. Standard spectral data file contains T, Rf, Rb
// that is measured at certain wavelengths.
double
getProperty(FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
// Get properties at each wavelength and at given incident angle
std::vector<double> getBandProperties(
FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
void setBandWavelengths(const std::vector<double> & wavelengths) override;
void Flipped(bool flipped) override;
protected:
std::vector<double> calculateBandWavelengths() override;
std::shared_ptr<SpectralAveraging::CAngularSpectralSample> m_AngularSample;
};
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterialPhotovoltaic
//////////////////////////////////////////////////////////////////////////////////////////
class CMaterialPhotovoltaic : public CMaterialSample
{
public:
CMaterialPhotovoltaic(
const std::shared_ptr<SpectralAveraging::CPhotovoltaicSample> & t_SpectralSample,
double t_Thickness,
FenestrationCommon::MaterialType t_Type,
double minLambda,
double maxLambda);
CMaterialPhotovoltaic(
const std::shared_ptr<SpectralAveraging::CPhotovoltaicSample> & t_SpectralSample,
double t_Thickness,
FenestrationCommon::MaterialType t_Type,
FenestrationCommon::WavelengthRange t_Range);
[[nodiscard]] FenestrationCommon::CSeries jscPrime(FenestrationCommon::Side t_Side) const;
private:
std::shared_ptr<SpectralAveraging::CPhotovoltaicSample> m_PVSample;
};
//////////////////////////////////////////////////////////////////////////////////////////
/// CMaterialMeasured
//////////////////////////////////////////////////////////////////////////////////////////
// Material that contains data measured over the range of wavelengths. It also provides material
// properties at certain angle. Assumes that material properties at certain angle can be
// calculated by using coated and uncoated algorithms
class CMaterialMeasured : public CMaterial
{
public:
CMaterialMeasured(
const std::shared_ptr<SpectralAveraging::CAngularMeasurements> & t_Measurements,
double minLambda,
double maxLambda);
CMaterialMeasured(
const std::shared_ptr<SpectralAveraging::CAngularMeasurements> & t_Measurements,
FenestrationCommon::WavelengthRange t_Range);
void setSourceData(FenestrationCommon::CSeries & t_SourceData) override;
// In this case sample property is taken. Standard spectral data file contains T, Rf, Rb
// that is measured at certain wavelengths.
double
getProperty(FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
// Get properties at each wavelength and at given incident angle
std::vector<double> getBandProperties(
FenestrationCommon::Property t_Property,
FenestrationCommon::Side t_Side,
const CBeamDirection & t_IncomingDirection = CBeamDirection(),
const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override;
private:
std::vector<double> calculateBandWavelengths() override;
std::shared_ptr<SpectralAveraging::CAngularMeasurements> m_AngularMeasurements;
};
} // namespace SingleLayerOptics
#endif
| 45.415179 | 192 | 0.613978 | LBNL-ETA |
16e177a8e343d2d71049506dbc4124d2301bdff0 | 882 | cpp | C++ | jianzhioffer/33verifyPostorder.cpp | wanghengg/LeetCode | 4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79 | [
"Apache-2.0"
] | null | null | null | jianzhioffer/33verifyPostorder.cpp | wanghengg/LeetCode | 4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79 | [
"Apache-2.0"
] | null | null | null | jianzhioffer/33verifyPostorder.cpp | wanghengg/LeetCode | 4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool verify(vector<int>& postorder, int left, int right) {
if (left >= right) return true;
int root = postorder[right];
int index = right-1;
while (index >= 0 && postorder[index] > root) {
--index;
}
int mid = index;
while (index >= 0) {
if (postorder[index] > root) {
return false;
} else {
--index;
}
}
return verify(postorder, left, mid) && verify(postorder, mid + 1, right - 1);
}
bool verifyPostorder(vector<int>& postorder) {
return verify(postorder, 0, postorder.size()-1);
}
};
int main() {
vector<int> postorder{5,4,3,2,1};
Solution solution;
cout << solution.verifyPostorder(postorder) << endl;
return 0;
} | 25.941176 | 85 | 0.528345 | wanghengg |
16e2ac8bd50e36687a24da8a1e931ab99745b161 | 596 | cc | C++ | aircrafting/Game.cc | SametSisartenep/game-dev | 8779ea5845784e1ab1cea5bc5c29e46463aef731 | [
"MIT"
] | 1 | 2015-11-08T11:17:50.000Z | 2015-11-08T11:17:50.000Z | aircrafting/Game.cc | SametSisartenep/game-dev | 8779ea5845784e1ab1cea5bc5c29e46463aef731 | [
"MIT"
] | null | null | null | aircrafting/Game.cc | SametSisartenep/game-dev | 8779ea5845784e1ab1cea5bc5c29e46463aef731 | [
"MIT"
] | null | null | null | #include "Game.h"
Game::Game()
: mWindow(sf::VideoMode(640, 480), "SFML Application")
, mPlayer()
{
mPlayer.setRadius(40.f);
mPlayer.setPosition(100.f, 100.f);
mPlayer.setFillColor(sf::Color::Cyan);
}
void Game::run() {
while (mWindow.isOpen()) {
processEvents();
update();
render();
}
}
void Game::processEvents() {
sf::Event event;
while (mWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
mWindow.close();
}
}
}
void Game::update() {
}
void Game::render() {
mWindow.clear();
mWindow.draw(mPlayer);
mWindow.display();
}
| 15.684211 | 56 | 0.607383 | SametSisartenep |
16e44e887c301125aa6e1f42d03c160a38362d48 | 8,965 | cpp | C++ | src/cluster.cpp | n1ckfg/triplclust | d8c5dbb3803c431f3bfb3ed7af8a8b42b5641471 | [
"BSD-2-Clause"
] | null | null | null | src/cluster.cpp | n1ckfg/triplclust | d8c5dbb3803c431f3bfb3ed7af8a8b42b5641471 | [
"BSD-2-Clause"
] | null | null | null | src/cluster.cpp | n1ckfg/triplclust | d8c5dbb3803c431f3bfb3ed7af8a8b42b5641471 | [
"BSD-2-Clause"
] | null | null | null | //
// cluster.cpp
// Functions for triplet clustering and for propagating
// the triplet cluster labels to points
//
// Author: Jens Wilberg, Lukas Aymans, Christoph Dalitz
// Date: 2019-04-02
// License: see ../LICENSE
//
#include <algorithm>
#include <cmath>
#include <fstream>
#include "cluster.h"
#include "hclust/fastcluster.h"
// compute mean of *a* with size *m*
double mean(const double *a, size_t m) {
double sum = 0;
for (size_t i = 0; i < m; ++i) {
sum += a[i];
}
return sum / m;
}
// compute standard deviation of *a* with size *m*
double sd(const double *a, size_t m) {
double sum = 0, result;
double mean_val = mean(a, m);
for (size_t k = 0; k < m; ++k) {
double tmp = mean_val - a[k];
sum += (tmp * tmp);
}
result = (1.0 / (m - 1.0)) * sum;
return std::sqrt(result);
}
//-------------------------------------------------------------------
// computation of condensed distance matrix.
// The distance matrix is computed from the triplets in *triplets*
// and saved in *result*. *triplet_metric* is used as distance metric.
//-------------------------------------------------------------------
void calculate_distance_matrix(const std::vector<triplet> &triplets,
const PointCloud &cloud, double *result,
ScaleTripletMetric &triplet_metric) {
size_t const triplet_size = triplets.size();
size_t k = 0;
for (size_t i = 0; i < triplet_size; ++i) {
for (size_t j = i + 1; j < triplet_size; j++) {
result[k++] = triplet_metric(triplets[i], triplets[j]);
}
}
}
//-------------------------------------------------------------------
// Computation of the clustering.
// The triplets in *triplets* are clustered by the fastcluster algorithm
// and the result is returned as cluster_group. *t* is the cut distance
// and *triplet_metric* is the distance metric for the triplets.
// *opt_verbose* is the verbosity level for debug outputs. the clustering
// is returned in *result*.
//-------------------------------------------------------------------
void compute_hc(const PointCloud &cloud, cluster_group &result,
const std::vector<triplet> &triplets, double s, double t,
bool tauto, double dmax, bool is_dmax, Linkage method,
int opt_verbose) {
const size_t triplet_size = triplets.size();
size_t k, cluster_size;
hclust_fast_methods link;
if (!triplet_size) {
// if no triplets are generated
return;
}
// choose linkage method
switch (method) {
case SINGLE:
link = HCLUST_METHOD_SINGLE;
break;
case COMPLETE:
link = HCLUST_METHOD_COMPLETE;
break;
case AVERAGE:
link = HCLUST_METHOD_AVERAGE;
break;
}
double *distance_matrix = new double[(triplet_size * (triplet_size - 1)) / 2];
double *cdists = new double[triplet_size - 1];
int *merge = new int[2 * (triplet_size - 1)], *labels = new int[triplet_size];
ScaleTripletMetric metric(s);
calculate_distance_matrix(triplets, cloud, distance_matrix, metric);
hclust_fast(triplet_size, distance_matrix, link, merge, cdists);
// splitting the dendrogram into clusters
if (tauto) {
// automatic stopping criterion where cdist is unexpected large
for (k = (triplet_size - 1) / 2; k < (triplet_size - 1); ++k) {
if ((cdists[k - 1] > 0.0 || cdists[k] > 1.0e-8) &&
(cdists[k] > cdists[k - 1] + 2 * sd(cdists, k + 1))) {
break;
}
}
if (opt_verbose) {
double automatic_t;
double prev_cdist = (k > 0) ? cdists[k - 1] : 0.0;
if (k < (triplet_size - 1)) {
automatic_t = (prev_cdist + cdists[k]) / 2.0;
} else {
automatic_t = cdists[k - 1];
}
std::cout << "[Info] optimal cdist threshold: " << automatic_t
<< std::endl;
}
} else {
// fixed threshold t
for (k = 0; k < (triplet_size - 1); ++k) {
if (cdists[k] >= t) {
break;
}
}
}
cluster_size = triplet_size - k;
cutree_k(triplet_size, merge, cluster_size, labels);
// generate clusters
for (size_t i = 0; i < cluster_size; ++i) {
cluster_t new_cluster;
result.push_back(new_cluster);
}
for (size_t i = 0; i < triplet_size; ++i) {
result[labels[i]].push_back(i);
}
if (opt_verbose > 1) {
// write debug file
const char *fname = "debug_cdist.csv";
std::ofstream of(fname);
of << std::fixed; // set float style
if (of.is_open()) {
for (size_t i = 0; i < (triplet_size - 1); ++i) {
of << cdists[i] << std::endl;
}
} else {
std::cerr << "[Error] could not write file '" << fname << "'\n";
}
of.close();
}
// cleanup
delete[] distance_matrix;
delete[] cdists;
delete[] merge;
delete[] labels;
}
//-------------------------------------------------------------------
// Remove all clusters in *cl_group* which contains less then *m*
// triplets. *cl_group* will be modified.
//-------------------------------------------------------------------
void cleanup_cluster_group(cluster_group &cl_group, size_t m, int opt_verbose) {
size_t old_size = cl_group.size();
cluster_group::iterator it = cl_group.begin();
while (it != cl_group.end()) {
if (it->size() < m) {
it = cl_group.erase(it);
} else {
++it;
}
}
if (opt_verbose > 0) {
std::cout << "[Info] in pruning removed clusters: "
<< old_size - cl_group.size() << std::endl;
}
}
//-------------------------------------------------------------------
// Convert the triplet indices ind *cl_group* to point indices.
// *triplets* contains all triplets and *cl_group* will be modified.
//-------------------------------------------------------------------
void cluster_triplets_to_points(const std::vector<triplet> &triplets,
cluster_group &cl_group) {
for (size_t i = 0; i < cl_group.size(); ++i) {
cluster_t point_indices, ¤t_cluster = cl_group[i];
for (std::vector<size_t>::const_iterator triplet_index =
current_cluster.begin();
triplet_index < current_cluster.end(); ++triplet_index) {
const triplet ¤t_triplet = triplets[*triplet_index];
point_indices.push_back(current_triplet.point_index_a);
point_indices.push_back(current_triplet.point_index_b);
point_indices.push_back(current_triplet.point_index_c);
}
// sort point-indices and remove duplicates
std::sort(point_indices.begin(), point_indices.end());
std::vector<size_t>::iterator new_end =
std::unique(point_indices.begin(), point_indices.end());
point_indices.resize(std::distance(point_indices.begin(), new_end));
// replace triplet cluster with point cluster
current_cluster = point_indices;
}
}
//-------------------------------------------------------------------
// Adds the cluster ids to the points in *cloud*
// *cl_group* contains the clusters with the point indices. For every
// point the corresponding cluster id is saved. For gnuplot the points
// which overlap between multiple clusteres are saved in seperate
// clusters in *cl_group*
//-------------------------------------------------------------------
void add_clusters(PointCloud &cloud, cluster_group &cl_group, bool gnuplot) {
for (size_t i = 0; i < cl_group.size(); ++i) {
const std::vector<size_t> ¤t_cluster = cl_group[i];
for (std::vector<size_t>::const_iterator point_index =
current_cluster.begin();
point_index != current_cluster.end(); ++point_index) {
cloud[*point_index].cluster_ids.insert(i);
}
}
// add point indices to the corresponding cluster/vertex vector. this is for
// the gnuplot output
if (gnuplot) {
std::vector<cluster_t> verticies;
for (size_t i = 0; i < cloud.size(); ++i) {
const Point &p = cloud[i];
if (p.cluster_ids.size() > 1) {
// if the point is in multiple clusters add it to the corresponding
// vertex or create one if none exists
bool found = false;
for (std::vector<cluster_t>::iterator v = verticies.begin();
v != verticies.end(); ++v) {
if (cloud[v->at(0)].cluster_ids == p.cluster_ids) {
v->push_back(i);
found = true;
}
}
if (!found) {
cluster_t v;
v.push_back(i);
verticies.push_back(v);
}
// remove the point from all other clusters
for (std::set<size_t>::iterator it = p.cluster_ids.begin();
it != p.cluster_ids.end(); ++it) {
cluster_t &cluster = cl_group[*it];
cluster.erase(std::remove(cluster.begin(), cluster.end(), i),
cluster.end());
}
}
}
// extend clusters with verticies
cl_group.reserve(cl_group.size() + verticies.size());
cl_group.insert(cl_group.end(), verticies.begin(), verticies.end());
}
}
| 34.480769 | 80 | 0.570329 | n1ckfg |
16e922742d90d8d2f191cbb16da1ad360e15706e | 2,416 | cpp | C++ | Demos/UnitTests/src/Sort.cpp | gammaker/Intra | aed1647cd2cf1781ab0976c2809533d0f347e87e | [
"MIT"
] | 8 | 2017-05-22T12:55:40.000Z | 2018-11-11T22:36:56.000Z | Demos/UnitTests/src/Sort.cpp | gammaker/Intra | aed1647cd2cf1781ab0976c2809533d0f347e87e | [
"MIT"
] | 1 | 2020-03-14T11:26:17.000Z | 2020-03-14T12:31:11.000Z | Demos/UnitTests/src/Sort.cpp | devoln/Intra | aed1647cd2cf1781ab0976c2809533d0f347e87e | [
"MIT"
] | 1 | 2017-10-12T10:03:56.000Z | 2017-10-12T10:03:56.000Z | #include "Cpp/Warnings.h"
INTRA_PUSH_DISABLE_REDUNDANT_WARNINGS
#include "Sort.h"
#include "Range/Sort.hh"
#include "Container/Sequential/Array.h"
#include "IO/FormattedWriter.h"
#include "Utils/Debug.h"
INTRA_PUSH_DISABLE_ALL_WARNINGS
#include <algorithm>
INTRA_WARNING_POP
using namespace Intra;
static const short arrayForSortTesting[] = {
2, 4234, -9788, 23, 5, 245, 2, 24, 5, -9890,
2, 5, 4552, 54, 3, -932, 123, 342, 24321, -234
};
void TestSort(IO::FormattedWriter& output)
{
Array<short> arrUnsorted = arrayForSortTesting;
output.PrintLine("Not sorted array: ", arrUnsorted);
Array<short> arrStdSort = arrUnsorted;
std::sort(arrStdSort.begin(), arrStdSort.end());
output.PrintLine("std::sort'ed array: ", arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrStdSort), arrStdSort);
Array<short> arrInsertion = arrUnsorted;
Range::InsertionSort(arrInsertion);
output.PrintLine("InsertionSort'ed array: ", arrInsertion);
INTRA_ASSERT_EQUALS(arrInsertion, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrInsertion), arrInsertion);
Array<short> arrShell = arrUnsorted;
Range::ShellSort(arrShell);
output.PrintLine("ShellSort'ed array: ", arrShell);
INTRA_ASSERT_EQUALS(arrShell, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrShell), arrShell);
Array<short> arrQuick = arrUnsorted;
Range::QuickSort(arrQuick);
output.PrintLine("QuickSort'ed array: ", arrQuick);
INTRA_ASSERT_EQUALS(arrQuick, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrQuick), arrQuick);
Array<short> arrRadix = arrUnsorted;
Range::RadixSort(arrRadix.AsRange());
output.PrintLine("RadixSort'ed array: ", arrRadix);
INTRA_ASSERT_EQUALS(arrRadix, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrRadix), arrRadix);
Array<short> arrMerge = arrUnsorted;
Range::MergeSort(arrMerge);
output.PrintLine("MergeSort'ed array: ", arrMerge);
INTRA_ASSERT_EQUALS(arrMerge, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrMerge), arrMerge);
Array<short> arrHeap = arrUnsorted;
Range::HeapSort(arrHeap);
output.PrintLine("HeapSort'ed array: ", arrHeap);
INTRA_ASSERT_EQUALS(arrHeap, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrHeap), arrHeap);
Array<short> arrSelection = arrUnsorted;
Range::SelectionSort(arrSelection);
output.PrintLine("SelectionSort'ed array: ", arrSelection);
INTRA_ASSERT_EQUALS(arrSelection, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrSelection), arrSelection);
}
INTRA_WARNING_POP
| 31.376623 | 60 | 0.768626 | gammaker |
16eb73148836c6c033158610a65de3b2daf19c4b | 1,148 | hpp | C++ | src/wavefile.hpp | ushitora-anqou/cables | edafc749bfd010e367838c193183b80953f60000 | [
"MIT"
] | 2 | 2021-02-15T08:11:00.000Z | 2021-11-14T17:09:37.000Z | src/wavefile.hpp | ushitora-anqou/cables | edafc749bfd010e367838c193183b80953f60000 | [
"MIT"
] | null | null | null | src/wavefile.hpp | ushitora-anqou/cables | edafc749bfd010e367838c193183b80953f60000 | [
"MIT"
] | null | null | null | #pragma once
#ifndef ___WAVEFILE_HPP___
#define ___WAVEFILE_HPP___
#include "pcmwave.hpp"
#include <cstdint>
#include <fstream>
#include <string>
// リニアPCM専用
struct PCMWaveFileHeader
{
std::uint8_t riffID[4];
std::uint32_t size;
std::uint8_t waveID[4];
std::uint8_t fmtID[4];
std::uint32_t fmtSize;
std::uint16_t format;
std::uint16_t channel;
std::uint32_t sampleRate;
std::uint32_t bytePerSec;
std::uint16_t blockSize;
std::uint16_t bitPerSample;
std::uint8_t dataID[4];
std::uint32_t dataSize;
PCMWaveFileHeader(){}
PCMWaveFileHeader(int) :
riffID{'R', 'I', 'F', 'F'},
waveID{'W', 'A', 'V', 'E'},
fmtID{'f', 'm', 't', ' '},
fmtSize(16), format(1),
dataID{'d', 'a', 't', 'a'}
{}
};
class WaveInFile
{
private:
std::ifstream ifs_;
public:
WaveInFile(const std::string& filename);
~WaveInFile(){}
bool isEOF() const;
PCMWave read();
};
class WaveOutFile
{
private:
std::ofstream ofs_;
public:
WaveOutFile(const std::string& filename);
~WaveOutFile();
void write(const PCMWave& wave);
};
#endif
| 17.9375 | 45 | 0.614111 | ushitora-anqou |
16ec96b7b56a3862a4bc1131d8646d4625a21025 | 2,653 | cc | C++ | src/core/ext/filters/client_channel/server_address.cc | inteos/grpc | fb8e4556c250bbcc523b55e6ebe69cb2b3d95998 | [
"Apache-2.0"
] | 4 | 2020-08-11T10:00:16.000Z | 2021-10-08T15:17:25.000Z | src/core/ext/filters/client_channel/server_address.cc | inteos/grpc | fb8e4556c250bbcc523b55e6ebe69cb2b3d95998 | [
"Apache-2.0"
] | 1 | 2020-05-12T16:17:30.000Z | 2020-05-12T16:17:30.000Z | src/core/ext/filters/client_channel/server_address.cc | inteos/grpc | fb8e4556c250bbcc523b55e6ebe69cb2b3d95998 | [
"Apache-2.0"
] | 3 | 2020-08-16T12:11:56.000Z | 2021-11-06T02:45:04.000Z | /*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/server_address.h"
namespace grpc_core {
//
// ServerAddress
//
ServerAddress::ServerAddress(
const grpc_resolved_address& address, grpc_channel_args* args,
std::map<const char*, std::unique_ptr<AttributeInterface>> attributes)
: address_(address), args_(args), attributes_(std::move(attributes)) {}
ServerAddress::ServerAddress(
const void* address, size_t address_len, grpc_channel_args* args,
std::map<const char*, std::unique_ptr<AttributeInterface>> attributes)
: args_(args), attributes_(std::move(attributes)) {
memcpy(address_.addr, address, address_len);
address_.len = static_cast<socklen_t>(address_len);
}
namespace {
int CompareAttributes(
const std::map<const char*,
std::unique_ptr<ServerAddress::AttributeInterface>>&
attributes1,
const std::map<const char*,
std::unique_ptr<ServerAddress::AttributeInterface>>&
attributes2) {
auto it2 = attributes2.begin();
for (auto it1 = attributes1.begin(); it1 != attributes1.end(); ++it1) {
// attributes2 has fewer elements than attributes1
if (it2 == attributes2.end()) return -1;
// compare keys
int retval = strcmp(it1->first, it2->first);
if (retval != 0) return retval;
// compare values
retval = it1->second->Cmp(it2->second.get());
if (retval != 0) return retval;
++it2;
}
// attributes1 has fewer elements than attributes2
if (it2 != attributes2.end()) return 1;
// equal
return 0;
}
} // namespace
int ServerAddress::Cmp(const ServerAddress& other) const {
if (address_.len > other.address_.len) return 1;
if (address_.len < other.address_.len) return -1;
int retval = memcmp(address_.addr, other.address_.addr, address_.len);
if (retval != 0) return retval;
retval = grpc_channel_args_compare(args_, other.args_);
if (retval != 0) return retval;
return CompareAttributes(attributes_, other.attributes_);
}
} // namespace grpc_core
| 32.353659 | 75 | 0.701093 | inteos |
16ef5617204523102bd98f68ff37ffc01c208f77 | 1,091 | cpp | C++ | D.cpp | ebaty/Typical-DP-Contest | eae2f3547df020dbdb66e3314dbae44c9c51fe89 | [
"MIT"
] | null | null | null | D.cpp | ebaty/Typical-DP-Contest | eae2f3547df020dbdb66e3314dbae44c9c51fe89 | [
"MIT"
] | null | null | null | D.cpp | ebaty/Typical-DP-Contest | eae2f3547df020dbdb66e3314dbae44c9c51fe89 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <sstream>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
using namespace std;
typedef long long ll;
double dp[101][70][40][30];
int main() {
ll N, D;
cin >> N >> D;
int I = 0, J = 0, K = 0;
memset(dp, 0.0, sizeof(dp));
while ( D % 2 == 0 ) {
I++;
D /= 2;
}
while ( D % 3 == 0 ) {
J++;
D /= 3;
}
while ( D % 5 == 0 ) {
K++;
D /= 5;
}
if ( D != 1 ) {
cout << "0.0" << endl;
return 0;
}
dp[0][0][0][0] = 1.0;
REP(n, N) REP(i, I+1) REP(j, J+1) REP(k, K+1) {
double p = dp[n][i][j][k] / 6.0;
int i1 = min(i+1, I);
int i2 = min(i+2, I);
int j1 = min(j+1, J);
int k1 = min(k+1, K);
dp[n+1][i][j][k] += p;
dp[n+1][i1][j][k] += p;
dp[n+1][i][j1][k] += p;
dp[n+1][i2][j][k] += p;
dp[n+1][i][j][k1] += p;
dp[n+1][i1][j1][k] += p;
}
printf("%0.6lf\n", dp[N][I][J][K]);
return 0;
}
| 17.046875 | 49 | 0.447296 | ebaty |
16f12e57f172efe12626bf5e5860754845bed1d9 | 666 | cpp | C++ | answers/ArghyaDas21112001/Day 19/Question 2.cpp | justshivam/30-DaysOfCode-March-2021 | 64d434c07b9ec875384dee681a3eecefab3ddef0 | [
"MIT"
] | 22 | 2021-03-16T14:07:47.000Z | 2021-08-13T08:52:50.000Z | answers/ArghyaDas21112001/Day 19/Question 2.cpp | justshivam/30-DaysOfCode-March-2021 | 64d434c07b9ec875384dee681a3eecefab3ddef0 | [
"MIT"
] | 174 | 2021-03-16T21:16:40.000Z | 2021-06-12T05:19:51.000Z | answers/ArghyaDas21112001/Day 19/Question 2.cpp | justshivam/30-DaysOfCode-March-2021 | 64d434c07b9ec875384dee681a3eecefab3ddef0 | [
"MIT"
] | 135 | 2021-03-16T16:47:12.000Z | 2021-06-27T14:22:38.000Z | #include <iostream>
using namespace std;
int main()
{
int i,j,k;
int n;
cout<<"Enter the size of the array: ";
cin>>n;
int arr[n];
cout<<"Enter the elements of the array: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
int sum;
cout<<"Enter the Sum: ";
cin>>sum;
int ans=0;
for(i=0;i<n - 2;i++)
{
for (int j = i+1; j < n-1; j++)
{
for (int k = j+1; k < n; k++)
{
if (arr[i] + arr[j] + arr[k] < sum)
{
ans++;
}
}
}
}
cout<<"The number of such pairs is :"<<ans;
return 0;
}
| 17.526316 | 50 | 0.382883 | justshivam |
a8480fced0de3740bbe0f324752916d5f212e78c | 1,057 | hpp | C++ | include/Menu.hpp | Kiloris/Complot_Game | 81247c6c13d7921a9cc01b765ab3a4a5924c2391 | [
"MIT"
] | null | null | null | include/Menu.hpp | Kiloris/Complot_Game | 81247c6c13d7921a9cc01b765ab3a4a5924c2391 | [
"MIT"
] | null | null | null | include/Menu.hpp | Kiloris/Complot_Game | 81247c6c13d7921a9cc01b765ab3a4a5924c2391 | [
"MIT"
] | null | null | null | /*
** COMPLOT PROJECT
** AUTHOR:
** Zacharie ABIDAT
*/
#ifndef MENU_HPP_
#define MENU_HPP_
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Graphics/Font.hpp>
#include "Button.hpp"
#include "Square.hpp"
#include <iostream>
#include <cstdlib>
class Menu {
public:
Menu(sf::RenderWindow *);
~Menu();
void draw();
void event_clicked();
void event_pressed();
void clicked_settings();
void clicked_menu();
void pressed_settings();
void pressed_menu();
bool get_verif();
void set_verif(bool);
protected:
private:
sf::RenderWindow *app;
sf::Texture bg_texture;
sf::Sprite bg_sprite;
Button *play_button;
Button *multi_button;
Button *settings_button;
Button *exit_button;
Button *low_sound_button;
Button *high_sound_button;
Button *menu_button;
std::vector<Square *> list_square;
bool settings;
bool verif;
};
#endif /* !MENU_HPP_ */
| 21.571429 | 42 | 0.603595 | Kiloris |
a8495da44209d7d618d0294d61afbbf6915e786f | 14,009 | hpp | C++ | api-cpp/include/dfx/api/MeasurementStreamAPI.hpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | api-cpp/include/dfx/api/MeasurementStreamAPI.hpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | api-cpp/include/dfx/api/MeasurementStreamAPI.hpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | // Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license.
// See LICENSE.txt in the project root for license information.
#pragma once
#ifndef DFX_API_CLOUD_MEASUREMENT_STREAM_API_H
#define DFX_API_CLOUD_MEASUREMENT_STREAM_API_H
#include "dfx/api/CloudAPI_Export.hpp"
#include "dfx/api/CloudConfig.hpp"
#include "dfx/api/CloudStatus.hpp"
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <map>
#include <mutex>
#include <string>
#include <vector>
namespace dfx::api
{
class CloudAPI;
/**
* @brief MeasurementResult is the message type of result data from the server.
*/
struct DFXCLOUD_EXPORT MeasurementResult
{
uint64_t chunkOrder; ///< The Chunk Order
std::string faceID; ///< The Face ID
std::map<std::string, std::vector<float>> signalData;
int64_t frameEndTimestampMS;
int64_t timestampMS;
};
struct DFXCLOUD_EXPORT MeasurementMetric
{
float uploadRate;
};
struct DFXCLOUD_EXPORT MeasurementWarning
{
int warningCode;
std::string warningMessage;
int64_t timestampMS;
};
/**
* @brief Asynchronous callback signature to receive a Measurement ID.
*
* Provides the Measurement ID being used from this Measurement instance.
*/
typedef std::function<void(const std::string& measurementID)> MeasurementIDCallback;
/**
* @brief Asynchronous callback signature to receive Measurement results.
*
* Provides the actual measurement results from the server for individual
* signals like heart rate, or signal-to-noise ratio.
*/
typedef std::function<void(const MeasurementResult& result)> MeasurementResultCallback;
/**
* @brief Asynchronous callback signature to receive Measurement metrics.
*
* Provides diagnostic information on the connection speed.
*/
typedef std::function<void(const MeasurementMetric& result)> MeasurementMetricCallback;
/**
* @brief Asynchronous callback signature to receive Measurement warnings.
*
* The warning Callback is used on gRPC streams to provide warning notifications when
* a signal can't be provided because a criteria has not been met. The connection has not been
* terminated and the server will continue to attempt to process but it is advice that would
* improve the signals being provided.
*/
typedef std::function<void(const MeasurementWarning& warning)> MeasurementWarningCallback;
/**
* @brief Measurement is used to send payload chunks to the DFX Server and get back results.
*
* The sendChunk operation is used to provide the server with payload chunks which the
* server will process and reply with result data. Because of the latency involved in
* the network communication, uploading, processing and result return this class has
* been designed to work on a background thread and offers two forms of use.
*
* If you prefer asynchronous results, you can register callbacks of the message
* types you are interested in and you will be called immediately when there are
* results. The callback itself needs to be thread-safe. If there are any queued
* messages, those will be delivered the instant a callback is registered and the
* queue will be cleared.
*
* If you prefer synchronous results, you can poll the Measurement for results
* using the getResult (and associated signatures) with an optional timeout. If
* you provide no timeout, it will wait until a response is received which might
* be when the underlying connection itself dies.
*/
class DFXCLOUD_EXPORT MeasurementStreamAPI
{
public:
enum class CreateProperty
{
UserProfileID,
DeviceVersion,
Notes,
Mode, ///< For streaming set Mode="STREAMING"
PartnerID,
Resolution ///< Resolution=0 averages results (default), Resolution=100 is non-averaged
};
/**
* @brief MeasurementStreamAPI constructor.
*/
MeasurementStreamAPI();
/**
* @brief Measurement destructor.
*/
virtual ~MeasurementStreamAPI();
/**
* @brief Setup the stream.
*
* @param config
* @param studyID
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setupStream(const CloudConfig& config,
const std::string& studyID,
const std::map<CreateProperty, std::string>& createProperties = {});
/**
* @brief Asynchronously send a payload chunk to the server for processing.
*
* @param config the connection configuration to use when sending the chunk.
* @param chunk the payload chunk of bytes obtained from DFX SDK.
* @param isLastChunk flag indicating if this is the last chunk for proper measurement completion.
* @return status of the measurement connection, CLOUD_OK on SUCCESS
*/
virtual CloudStatus sendChunk(const CloudConfig& config, const std::vector<uint8_t>& chunk, bool isLastChunk);
/**
* @brief Waits for the measurement connection to close ensuring that all results
* have been properly received.
*
* In order for the server to properly close the connection when it has completed
* processing all the chunks, the last chunk needs to be flagged on the sendChunk
* call or this wait for completion may wait a very long time.
*
* @param config the connection configuration to use when waiting.
* @param timeoutMillis the amount of time to wait for completion, zero is wait forever.
* @return status of the measurement connection at close, CLOUD_OK on SUCCESS
*/
virtual CloudStatus waitForCompletion(const CloudConfig& config, int32_t timeoutMillis = 0);
/**
* @brief cancel will inform the server that the Measurement should be terminated.
*
* This will notify the server of the intent to cancel but leave all internal
* state setup to receive any final messages the server might wish to deliver.
*
* @param config the connection configuration to use when cancelling.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus cancel(const CloudConfig& config);
/**
* @brief Resets this measurement back so another stream can be setup.
*
* The current measurement will be cancelled and the state immediately cleared
* so any undelivered messages would be lost, but the instance will be
* able to perform another setupStream() without having to be entirely
* recreated.
*
* @param config the connection configuration to use when cancelling.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus reset(const CloudConfig& config);
/**
* @brief Register an asynchronous callback for receiving the Measurement ID.
*
* @param callback the callback to invoke when a Measurement ID is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setMeasurementIDCallback(const MeasurementIDCallback& callback);
/**
* @brief Register an asynchronous callback for receiving results.
*
* @param callback the callback to invoke when a result is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setResultCallback(const MeasurementResultCallback& callback);
/**
* @brief Register an asynchronous callback for receiving metrics.
*
* @param callback the callback to invoke when a metric is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setMetricCallback(const MeasurementMetricCallback& callback);
/**
* @brief Register an asynchronous callback for receiving warnings.
*
* @param callback the callback to invoke when a warning message is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setWarningCallback(const MeasurementWarningCallback& callback);
/**
* @brief Synchronously poll for a Measurement ID until timeout expires or connection
* dies.
*
* @param measurementID the measurement ID if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getMeasurementID(std::string& measurementID, int32_t timeoutMillis = 0);
/**
* @brief Synchronously poll for a Measurement Result until timeout expires or
* connection dies.
*
* @param result a measurement result if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getResult(MeasurementResult& result, int32_t timeoutMillis = 0);
/**
* @brief Synchronously poll for a Measurement Metric until timeout expires or
* connection dies.
*
* @param result a measurement metric if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getMetric(MeasurementMetric& metric, int32_t timeoutMillis = 0);
/**
* @brief Synchronously poll for a Measurement Warning until timeout expires or
* connection dies.
*
* @param result a measurement warning if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getWarning(MeasurementWarning& warning, int32_t timeoutMillis = 0);
protected:
/**
* @brief handleMeasurementID is called by derived implementations when they
* receive a measurement ID.
*
* @param measurementID the measurementID received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleMeasurementID(const std::string& measurementID);
/**
* @brief handleResult is called by derived implementations when they
* receive a measurement result.
*
* @param result the measurement result received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleResult(const MeasurementResult& result);
/**
* @brief handleMetric is called by derived implementations when they
* receive a measurement metric.
*
* @param metric the measurement metric received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleMetric(const MeasurementMetric& metric);
/**
* @brief handleWarning is called by derived implementations when they
* receive a measurement warning.
*
* @param warning the measurement warning received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleWarning(const MeasurementWarning& warning);
/**
* @brief isMeasurementClosed is called by derived implementations when
* they are interested if the measurement has been closed.
*
* @param status of the closed connection, if it is closed.
* @return true if the connection has been closed, false if it still active.
*/
bool isMeasurementClosed(CloudStatus& status);
/**
* @brief closeMeasurement is called by derived implementations when
* they need to ensure the measurement is closed, either the connection
* has died or the measurement has processed it's last chunk.
*
* @param status of the closed connection that the derived implementation would like to use.
* @return status of the closed connection that was used.
*/
CloudStatus closeMeasurement(const CloudStatus& status);
private:
std::shared_ptr<CloudAPI> cloudAPI;
/**
* @brief waitForQueuedData is an internal method which holds the implementation for how
* all the various message types are handled when a get request is performed.
*
* @tparam T the message type.
* @param condition the condition variable protecting the message type.
* @param timeoutMillis the number of milliseconds, or zero for infinite that should be waited.
* @param queue the queue for message type holding any queued values.
* @param result the value obtained after waiting.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error if connection
* has been closed.
*/
template <typename T>
CloudStatus
waitForQueuedData(std::condition_variable& condition, int32_t timeoutMillis, std::deque<T>& queue, T& result);
template <typename T, typename F>
CloudStatus setCallbackVariable(F& variableCallback, std::deque<T>& queue, const F& callback);
template <typename T, typename F>
CloudStatus handle(std::condition_variable& condition, std::deque<T>& queue, const F& callback, const T& result);
std::mutex measurementMutex;
std::condition_variable cvWaitForCompletion;
bool measurementClosed;
CloudStatus measurementStatus;
MeasurementIDCallback measurementIDCallback;
std::condition_variable cvWaitForMeasurementID;
std::deque<std::string> measurementIDs;
MeasurementResultCallback resultCallback;
std::condition_variable cvWaitForResults;
std::deque<MeasurementResult> measurementResults;
MeasurementMetricCallback metricCallback;
std::condition_variable cvWaitForMetrics;
std::deque<MeasurementMetric> measurementMetrics;
MeasurementWarningCallback warningCallback;
std::condition_variable cvWaitForWarnings;
std::deque<MeasurementWarning> measurementWarnings;
};
} // namespace dfx::api
#endif // DFX_API_CLOUD_MEASUREMENT_STREAM_API_H
| 38.486264 | 117 | 0.721964 | nuralogix |
a84f2912ec22baefc073957b9f3873639de6dac9 | 639 | cpp | C++ | Scripts/BossBehaviourScript/BossStateIdle.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 10 | 2019-02-25T11:36:23.000Z | 2021-11-03T22:51:30.000Z | Scripts/BossBehaviourScript/BossStateIdle.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 146 | 2019-02-05T13:57:33.000Z | 2019-11-07T16:21:31.000Z | Scripts/BossBehaviourScript/BossStateIdle.cpp | FractalPuppy/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 3 | 2019-11-17T20:49:12.000Z | 2020-04-19T17:28:28.000Z | #include "BossStateIdle.h"
#include "BossBehaviourScript.h"
#include "EnemyControllerScript/EnemyControllerScript.h"
#include "ComponentAnimation.h"
BossStateIdle::BossStateIdle(BossBehaviourScript* AIBoss)
{
boss = AIBoss;
trigger = "Idle";
}
BossStateIdle::~BossStateIdle()
{
}
void BossStateIdle::HandleIA()
{
if (timer > (duration + baseDuration))
{
boss->currentState = (BossState*)boss->precast;
}
}
void BossStateIdle::Update()
{
boss->enemyController->LookAt2D(boss->playerPosition);
}
void BossStateIdle::Enter()
{
duration = (std::rand() % 100) / 100.f;
boss->anim->SendTriggerToStateMachine(trigger.c_str());
}
| 17.75 | 57 | 0.730829 | solidajenjo |
a850704010729c2f191254bdf87149b994e49e75 | 205 | cpp | C++ | 02Fundamental Data Types/04staticCast.cpp | CedarChennn/myC | b4de17f332788e3e578d304f2a690d2c9a07c004 | [
"Apache-2.0"
] | 2 | 2021-01-13T08:55:41.000Z | 2021-04-23T15:14:05.000Z | 02Fundamental Data Types/04staticCast.cpp | CedarChennn/myC | b4de17f332788e3e578d304f2a690d2c9a07c004 | [
"Apache-2.0"
] | null | null | null | 02Fundamental Data Types/04staticCast.cpp | CedarChennn/myC | b4de17f332788e3e578d304f2a690d2c9a07c004 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
int main()
{
char ch{'a'};
std::cout<<ch<<'\n';
std::cout<<static_cast<int>(ch)<<'\n';
std::cout<<ch<<'\n';
std::cout<<static_cast<int>(45)<<'\n';
return 0;
} | 18.636364 | 43 | 0.507317 | CedarChennn |
a85394441ace427372373be4380ababe41b36f9f | 1,313 | cpp | C++ | src/Restaurant/Rest/Order.cpp | aashrafh/Tayara | 4d59115ad52a8fed60dc1098d37b0aa33427a126 | [
"MIT"
] | null | null | null | src/Restaurant/Rest/Order.cpp | aashrafh/Tayara | 4d59115ad52a8fed60dc1098d37b0aa33427a126 | [
"MIT"
] | null | null | null | src/Restaurant/Rest/Order.cpp | aashrafh/Tayara | 4d59115ad52a8fed60dc1098d37b0aa33427a126 | [
"MIT"
] | 1 | 2019-05-02T02:57:00.000Z | 2019-05-02T02:57:00.000Z | #include "Order.h"
Order::Order(int id, ORD_TYPE r_Type, REGION r_region, int DST, double MON, int ArrT)
{
ID = (id > 0 && id < 1000) ? id : 0; //1<ID<999
type = r_Type;
Region = r_region;
//should we check for the validaity of the distance? and what we will do if it's invalid?!
Distance = DST;
totalMoney = MON;
ArrTime = ArrT;
}
Order::~Order()
{
}
int Order::GetID()
{
return ID;
}
ORD_TYPE Order::GetType() const
{
return type;
}
REGION Order::GetRegion() const
{
return Region;
}
void Order::SetDistance(int d)
{
Distance = d>0?d:0;
}
int Order::GetDistance() const
{
return Distance;
}
void Order::SetWaitingTime(int timestep)
{
WaitingTime = timestep - ArrTime;
}
int Order::getWaitingTime() const
{
return WaitingTime;
}
int Order::getPriority() const
{
return (ArrTime*Distance/totalMoney);
}
int Order::getFinishTime() const
{
return FinishTime;
}
int Order::getServiceTime() const
{
return ServTime;
}
int Order::getArrivalTime() const
{
return ArrTime;
}
int Order::CalcTime(int timeStep, int Speed)
{
ServTime = Distance / Speed;
WaitingTime = timeStep - ArrTime;
FinishTime = ArrTime + WaitingTime + ServTime;
return FinishTime + ServTime;
}
bool Order::IsWaiting(int TS)
{
return (TS <= WaitingTime + ArrTime);
}
double Order::GetMoney()
{
return totalMoney;
}
| 15.819277 | 91 | 0.693069 | aashrafh |
a8575b98f518033b6731753bc63e967aef4ef02f | 6,434 | hpp | C++ | include/RSG/Tuple.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/RSG/Tuple.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/RSG/Tuple.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: RSG
namespace RSG {
// Forward declaring type: Tuple`2<T1, T2>
template<typename T1, typename T2>
class Tuple_2;
// Forward declaring type: Tuple`3<T1, T2, T3>
template<typename T1, typename T2, typename T3>
class Tuple_3;
// Forward declaring type: Tuple`4<T1, T2, T3, T4>
template<typename T1, typename T2, typename T3, typename T4>
class Tuple_4;
}
// Completed forward declares
// Type namespace: RSG
namespace RSG {
// Forward declaring type: Tuple
class Tuple;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::RSG::Tuple);
DEFINE_IL2CPP_ARG_TYPE(::RSG::Tuple*, "RSG", "Tuple");
// Type namespace: RSG
namespace RSG {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: RSG.Tuple
// [TokenAttribute] Offset: FFFFFFFF
class Tuple : public ::Il2CppObject {
public:
// public System.Void .ctor()
// Offset: 0xA2E734
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static Tuple* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<Tuple*, creationType>()));
}
// static public RSG.Tuple`2<T1,T2> Create(T1 item1, T2 item2)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2>
static ::RSG::Tuple_2<T1, T2>* Create(T1 item1, T2 item2) {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("RSG", "Tuple", "Create", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item1), ::il2cpp_utils::ExtractType(item2)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::RSG::Tuple_2<T1, T2>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, item1, item2);
}
// static public RSG.Tuple`3<T1,T2,T3> Create(T1 item1, T2 item2, T3 item3)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2, class T3>
static ::RSG::Tuple_3<T1, T2, T3>* Create(T1 item1, T2 item2, T3 item3) {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("RSG", "Tuple", "Create", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item1), ::il2cpp_utils::ExtractType(item2), ::il2cpp_utils::ExtractType(item3)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::RSG::Tuple_3<T1, T2, T3>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, item1, item2, item3);
}
// static public RSG.Tuple`4<T1,T2,T3,T4> Create(T1 item1, T2 item2, T3 item3, T4 item4)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2, class T3, class T4>
static ::RSG::Tuple_4<T1, T2, T3, T4>* Create(T1 item1, T2 item2, T3 item3, T4 item4) {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("RSG", "Tuple", "Create", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T4>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item1), ::il2cpp_utils::ExtractType(item2), ::il2cpp_utils::ExtractType(item3), ::il2cpp_utils::ExtractType(item4)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T4>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::RSG::Tuple_4<T1, T2, T3, T4>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, item1, item2, item3, item4);
}
}; // RSG.Tuple
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RSG::Tuple::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: RSG::Tuple::Create
// Il2CppName: Create
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: RSG::Tuple::Create
// Il2CppName: Create
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: RSG::Tuple::Create
// Il2CppName: Create
// Cannot write MetadataGetter for generic methods!
| 68.446809 | 583 | 0.727541 | v0idp |
a857926d1990db6a4478b7d1508a558a9b5e8134 | 2,016 | cpp | C++ | Genesis3D/v120/OpenSource/Tools/mkactor/AStudio/StdAfx.cpp | dumpinfo/WinMasterGame | 59d300ec77c46fec2a821b4cfa095af0c21e434c | [
"Unlicense"
] | null | null | null | Genesis3D/v120/OpenSource/Tools/mkactor/AStudio/StdAfx.cpp | dumpinfo/WinMasterGame | 59d300ec77c46fec2a821b4cfa095af0c21e434c | [
"Unlicense"
] | null | null | null | Genesis3D/v120/OpenSource/Tools/mkactor/AStudio/StdAfx.cpp | dumpinfo/WinMasterGame | 59d300ec77c46fec2a821b4cfa095af0c21e434c | [
"Unlicense"
] | null | null | null | /****************************************************************************************/
/* STDAFX.CPP */
/* */
/* Author: Jim Mischel */
/* Description: Standard MFC includes. */
/* */
/* The contents of this file are subject to the Genesis3D Public License */
/* Version 1.01 (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.genesis3d.com */
/* */
/* Software distributed under the License is distributed on an "AS IS" */
/* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See */
/* the License for the specific language governing rights and limitations */
/* under the License. */
/* */
/* The Original Code is Genesis3D, released March 25, 1999. */
/*Genesis3D Version 1.1 released November 15, 1999 */
/* Copyright (C) 1999 WildTangent, Inc. All Rights Reserved */
/* */
/****************************************************************************************/
// stdafx.cpp : source file that includes just the standard includes
// AStudio.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| 72 | 91 | 0.34871 | dumpinfo |
a85a9f40340d7abe6ff59b27922e0a85144e3d32 | 1,942 | cpp | C++ | descartes_trajectory/src/axial_symmetric_pt.cpp | shaun-edwards/descartes | 75baae4ceccf328ec2315d7fdbc247006949251c | [
"Apache-2.0"
] | null | null | null | descartes_trajectory/src/axial_symmetric_pt.cpp | shaun-edwards/descartes | 75baae4ceccf328ec2315d7fdbc247006949251c | [
"Apache-2.0"
] | 1 | 2016-11-03T18:42:03.000Z | 2016-11-03T18:47:20.000Z | descartes_trajectory/src/axial_symmetric_pt.cpp | shaun-edwards/descartes | 75baae4ceccf328ec2315d7fdbc247006949251c | [
"Apache-2.0"
] | null | null | null | #include "descartes_trajectory/axial_symmetric_pt.h"
using descartes_trajectory::TolerancedFrame;
using descartes_trajectory::AxialSymmetricPt;
using namespace descartes_core::utils;
static TolerancedFrame makeRotationalAxis(AxialSymmetricPt::FreeAxis axis)
{
using namespace descartes_trajectory;
Eigen::Affine3d rot = Eigen::Affine3d::Identity();
PositionTolerance pos_tol = ToleranceBase::zeroTolerance<PositionTolerance>(0,0,0);
OrientationTolerance orient_tol = ToleranceBase::createSymmetric<OrientationTolerance>(0.0, 0.0, 0.0,
((axis == AxialSymmetricPt::X_AXIS) ? 2*M_PI : 0.0),
((axis == AxialSymmetricPt::Y_AXIS) ? 2*M_PI : 0.0),
((axis == AxialSymmetricPt::Z_AXIS) ? 2*M_PI : 0.0));
return TolerancedFrame(rot, pos_tol, orient_tol);
}
namespace descartes_trajectory
{
AxialSymmetricPt::AxialSymmetricPt(double x, double y, double z, double rx, double ry, double rz,
double orient_increment, FreeAxis axis) :
CartTrajectoryPt(toFrame(x, y, z, rx, ry, rz, EulerConventions::XYZ),
makeRotationalAxis(axis),
Eigen::Affine3d::Identity(),
Eigen::Affine3d::Identity(),
0.0, // The position discretization
orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}
AxialSymmetricPt::AxialSymmetricPt(const Eigen::Affine3d& pose, double orient_increment, FreeAxis axis) :
CartTrajectoryPt(pose,
makeRotationalAxis(axis),
Eigen::Affine3d::Identity(),
Eigen::Affine3d::Identity(),
0.0, // The position discretization
orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}
} // end of namespace descartes_trajectory
| 41.319149 | 105 | 0.642122 | shaun-edwards |
a85d331d28dd0db9296751972ce0424c91ec1c51 | 1,498 | cxx | C++ | cgv/reflect/reflect_enum.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | cgv/reflect/reflect_enum.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | cgv/reflect/reflect_enum.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #include "reflect_enum.h"
#include <cgv/utils/convert.h>
#include <cgv/utils/scan_enum.h>
namespace cgv {
namespace reflect {
void abst_enum_reflection_traits::parse_declarations()
{
cgv::utils::parse_enum_declarations(declarations(), ref_names(), ref_values());
}
bool abst_enum_reflection_traits::has_string_conversions() const
{
return true;
}
bool abst_enum_reflection_traits::set_from_string(void* member_ptr, const std::string& str_val)
{
unsigned i = cgv::utils::find_enum_index(str_val, ref_names());
if (i == -1)
return false;
*static_cast<int*>(member_ptr) = ref_values()[i];
return true;
}
void abst_enum_reflection_traits::get_to_string(const void* member_ptr, std::string& str_val)
{
unsigned i = cgv::utils::find_enum_index(*static_cast<const int*>(member_ptr), ref_values());
if (i != -1)
str_val = to_string(ref_names()[i]);
else
str_val = "UNDEF";
}
bool abst_enum_reflection_traits::has_enum_interface() const
{
return true;
}
unsigned abst_enum_reflection_traits::get_nr_enum_items() const
{
return (unsigned) const_cast<abst_enum_reflection_traits*>(this)->ref_values().size();
}
std::string abst_enum_reflection_traits::get_enum_name(unsigned i) const
{
return to_string(const_cast<abst_enum_reflection_traits*>(this)->ref_names()[i]);
}
int abst_enum_reflection_traits::get_enum_value(unsigned i) const
{
return const_cast<abst_enum_reflection_traits*>(this)->ref_values()[i];
}
}
}
| 26.75 | 97 | 0.730975 | MarioHenze |
a85dc5bf5b4cb76bf77a0750e0662cb67b65b4ff | 7,478 | cpp | C++ | worker/src/Channel/ChannelSocket.cpp | kcking/mediasoup | f385349d0f06fe14a4e38d50f0212b48d588fa32 | [
"ISC"
] | 29 | 2020-09-27T12:14:18.000Z | 2022-02-28T15:58:03.000Z | worker/src/Channel/ChannelSocket.cpp | kcking/mediasoup | f385349d0f06fe14a4e38d50f0212b48d588fa32 | [
"ISC"
] | 10 | 2021-10-10T14:04:01.000Z | 2022-03-21T09:39:14.000Z | worker/src/Channel/ChannelSocket.cpp | kcking/mediasoup | f385349d0f06fe14a4e38d50f0212b48d588fa32 | [
"ISC"
] | 7 | 2021-01-12T03:07:14.000Z | 2021-08-23T14:43:32.000Z | #define MS_CLASS "Channel::ChannelSocket"
// #define MS_LOG_DEV_LEVEL 3
#include "Channel/ChannelSocket.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include <cmath> // std::ceil()
#include <cstdio> // sprintf()
#include <cstring> // std::memcpy(), std::memmove()
namespace Channel
{
/* Static methods for UV callbacks. */
inline static void onAsync(uv_handle_t* handle)
{
while (static_cast<ChannelSocket*>(handle->data)->CallbackRead())
{
// Read while there are new messages.
}
}
inline static void onClose(uv_handle_t* handle)
{
delete handle;
}
// Binary length for a 4194304 bytes payload.
static constexpr size_t MessageMaxLen{ 4194308 };
static constexpr size_t PayloadMaxLen{ 4194304 };
/* Instance methods. */
ChannelSocket::ChannelSocket(int consumerFd, int producerFd)
: consumerSocket(new ConsumerSocket(consumerFd, MessageMaxLen, this)),
producerSocket(new ProducerSocket(producerFd, MessageMaxLen)),
writeBuffer(static_cast<uint8_t*>(std::malloc(MessageMaxLen)))
{
MS_TRACE_STD();
}
ChannelSocket::ChannelSocket(
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx)
: channelReadFn(channelReadFn), channelReadCtx(channelReadCtx), channelWriteFn(channelWriteFn),
channelWriteCtx(channelWriteCtx)
{
MS_TRACE_STD();
int err;
this->uvReadHandle = new uv_async_t;
this->uvReadHandle->data = static_cast<void*>(this);
err =
uv_async_init(DepLibUV::GetLoop(), this->uvReadHandle, reinterpret_cast<uv_async_cb>(onAsync));
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR_STD("uv_async_init() failed: %s", uv_strerror(err));
}
err = uv_async_send(this->uvReadHandle);
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR_STD("uv_async_send() failed: %s", uv_strerror(err));
}
}
ChannelSocket::~ChannelSocket()
{
MS_TRACE_STD();
std::free(this->writeBuffer);
if (!this->closed)
Close();
delete this->consumerSocket;
delete this->producerSocket;
}
void ChannelSocket::Close()
{
MS_TRACE_STD();
if (this->closed)
return;
this->closed = true;
if (this->uvReadHandle)
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvReadHandle), static_cast<uv_close_cb>(onClose));
}
if (this->consumerSocket)
{
this->consumerSocket->Close();
}
if (this->producerSocket)
{
this->producerSocket->Close();
}
}
void ChannelSocket::SetListener(Listener* listener)
{
MS_TRACE_STD();
this->listener = listener;
}
void ChannelSocket::Send(json& jsonMessage)
{
MS_TRACE_STD();
if (this->closed)
return;
std::string message = jsonMessage.dump();
if (message.length() > PayloadMaxLen)
{
MS_ERROR_STD("message too big");
return;
}
SendImpl(
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
}
void ChannelSocket::SendLog(const char* message, uint32_t messageLen)
{
MS_TRACE_STD();
if (this->closed)
return;
if (messageLen > PayloadMaxLen)
{
MS_ERROR_STD("message too big");
return;
}
SendImpl(reinterpret_cast<const uint8_t*>(message), messageLen);
}
bool ChannelSocket::CallbackRead()
{
MS_TRACE_STD();
if (this->closed)
return false;
uint8_t* message{ nullptr };
uint32_t messageLen;
size_t messageCtx;
auto free = this->channelReadFn(
&message, &messageLen, &messageCtx, this->uvReadHandle, this->channelReadCtx);
if (free)
{
try
{
json jsonMessage = json::parse(message, message + static_cast<size_t>(messageLen));
auto* request = new Channel::ChannelRequest(this, jsonMessage);
// Notify the listener.
try
{
this->listener->OnChannelRequest(this, request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR_STD("discarding wrong Channel request");
}
free(message, messageLen, messageCtx);
}
return free != nullptr;
}
inline void ChannelSocket::SendImpl(const uint8_t* payload, uint32_t payloadLen)
{
MS_TRACE_STD();
// Write using function call if provided.
if (this->channelWriteFn)
{
this->channelWriteFn(payload, payloadLen, this->channelWriteCtx);
}
else
{
std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (payloadLen != 0)
{
std::memcpy(this->writeBuffer + sizeof(uint32_t), payload, payloadLen);
}
size_t len = sizeof(uint32_t) + payloadLen;
this->producerSocket->Write(this->writeBuffer, len);
}
}
void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen)
{
MS_TRACE_STD();
try
{
json jsonMessage = json::parse(msg, msg + msgLen);
auto* request = new Channel::ChannelRequest(this, jsonMessage);
// Notify the listener.
try
{
this->listener->OnChannelRequest(this, request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR_STD("discarding wrong Channel request");
}
}
void ChannelSocket::OnConsumerSocketClosed(ConsumerSocket* /*consumerSocket*/)
{
MS_TRACE_STD();
this->listener->OnChannelClosed(this);
}
ConsumerSocket::ConsumerSocket(int fd, size_t bufferSize, Listener* listener)
: ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::CONSUMER), listener(listener)
{
MS_TRACE_STD();
}
void ConsumerSocket::UserOnUnixStreamRead()
{
MS_TRACE_STD();
size_t msgStart{ 0 };
// Be ready to parse more than a single message in a single chunk.
while (true)
{
if (IsClosed())
return;
size_t readLen = this->bufferDataLen - msgStart;
if (readLen < sizeof(uint32_t))
{
// Incomplete data.
break;
}
uint32_t msgLen;
// Read message length.
std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
if (readLen < sizeof(uint32_t) + static_cast<size_t>(msgLen))
{
// Incomplete data.
break;
}
this->listener->OnConsumerSocketMessage(
this,
reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
static_cast<size_t>(msgLen));
msgStart += sizeof(uint32_t) + static_cast<size_t>(msgLen);
}
if (msgStart != 0)
{
this->bufferDataLen = this->bufferDataLen - msgStart;
if (this->bufferDataLen != 0)
{
std::memmove(this->buffer, this->buffer + msgStart, this->bufferDataLen);
}
}
}
void ConsumerSocket::UserOnUnixStreamSocketClosed()
{
MS_TRACE_STD();
// Notify the listener.
this->listener->OnConsumerSocketClosed(this);
}
ProducerSocket::ProducerSocket(int fd, size_t bufferSize)
: ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::PRODUCER)
{
MS_TRACE_STD();
}
} // namespace Channel
| 21.426934 | 106 | 0.681733 | kcking |
a8634c0220e2b4ba4d6cd9458efbeef840cd96e3 | 3,171 | cpp | C++ | code/cheonsa/cheonsa__types_vector32x3.cpp | Olaedaria/cheonsa | cf366a5869a4bf0872a0d8dc6a01a68118cfc92e | [
"Unlicense"
] | null | null | null | code/cheonsa/cheonsa__types_vector32x3.cpp | Olaedaria/cheonsa | cf366a5869a4bf0872a0d8dc6a01a68118cfc92e | [
"Unlicense"
] | null | null | null | code/cheonsa/cheonsa__types_vector32x3.cpp | Olaedaria/cheonsa | cf366a5869a4bf0872a0d8dc6a01a68118cfc92e | [
"Unlicense"
] | null | null | null | #include "cheonsa__types_vector32x3.h"
#include "cheonsa__types_vector64x3.h"
#include <cassert>
namespace cheonsa
{
vector32x3_c::vector32x3_c()
: a( 0.0f )
, b( 0.0f )
, c( 0.0f )
{
}
vector32x3_c::vector32x3_c( float32_c const a, float32_c const b, float32_c const c )
: a( a )
, b( b )
, c( c )
{
}
vector32x3_c::vector32x3_c( float32_c const * values )
: a( values[ 0 ] )
, b( values[ 1 ] )
, c( values[ 2 ] )
{
}
vector32x3_c::vector32x3_c( vector64x3_c const & other )
: a( static_cast< float32_c >( other.a ) )
, b( static_cast< float32_c >( other.b ) )
, c( static_cast< float32_c >( other.c ) )
{
}
float32_c & vector32x3_c::get_element_at_index( sint32_c index )
{
assert( index >= 0 && index < 3 );
return reinterpret_cast< float32_c * >( this )[ index ];
}
float32_c const & vector32x3_c::get_element_at_index( sint32_c index ) const
{
assert( index >= 0 && index < 3 );
return reinterpret_cast< float32_c const * >( this )[ index ];
}
float32_c vector32x3_c::get_largest_element() const
{
float32_c result = a > b ? a : b;
result = c > result ? c : result;
return result;
}
vector32x3_c & vector32x3_c::operator *= ( float32_c b )
{
this->a *= b;
this->b *= b;
this->c *= b;
return * this;
}
vector32x3_c & vector32x3_c::operator /= ( float32_c b )
{
this->a /= b;
this->b /= b;
this->c /= b;
return * this;
}
vector32x3_c & vector32x3_c::operator += ( vector32x3_c const & b )
{
this->a += b.a;
this->b += b.b;
this->c += b.c;
return * this;
}
vector32x3_c & vector32x3_c::operator -= ( vector32x3_c const & b )
{
this->a -= b.a;
this->b -= b.b;
this->c -= b.c;
return * this;
}
vector32x3_c & vector32x3_c::operator *= ( vector32x3_c const & b )
{
this->a *= b.a;
this->b *= b.b;
this->c *= b.c;
return * this;
}
vector32x3_c & vector32x3_c::operator /= ( vector32x3_c const & b )
{
this->a /= b.a;
this->b /= b.b;
this->c /= b.c;
return * this;
}
boolean_c operator == ( vector32x3_c const & a, vector32x3_c const & b )
{
return ( a.a == b.a ) && ( a.b == b.b ) && ( a.c == b.c );
}
boolean_c operator != ( vector32x3_c const & a, vector32x3_c const & b )
{
return ( a.a != b.a ) || ( a.b != b.b ) || ( a.c != b.c );
}
vector32x3_c operator - ( vector32x3_c const & a )
{
return vector32x3_c( -a.a, -a.b, -a.c );
}
vector32x3_c operator * ( vector32x3_c a, float32_c b )
{
return a *= b;
}
vector32x3_c operator / ( vector32x3_c a, float32_c b )
{
return a /= b;
}
vector32x3_c operator + ( vector32x3_c a, vector32x3_c const & b )
{
return a += b;
}
vector32x3_c operator - ( vector32x3_c a, vector32x3_c const & b )
{
return a -= b;
}
vector32x3_c operator * ( vector32x3_c a, vector32x3_c const & b )
{
return a *= b;
}
vector32x3_c operator / ( vector32x3_c a, vector32x3_c const & b )
{
return a /= b;
}
vector64x3_c operator * ( vector32x3_c a, float64_c b )
{
return vector64x3_c( a.a * b, a.b * b, a.c * b );
}
vector64x3_c operator * ( vector32x3_c a, vector64x3_c const & b )
{
return vector64x3_c( a.a * b.a, a.b * b.b, a.c * b.c );
}
}
| 19.943396 | 86 | 0.597288 | Olaedaria |
a863ed98d0ee2dd3567f2c52b3b18ed0d8fdab81 | 857 | hpp | C++ | libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/nth_element.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/nth_element.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/nth_element.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file nth_element.hpp
*
* @brief nth_element の実装
*
* @author myoukaku
*/
#ifndef BKSGE_FND_ALGORITHM_DETAIL_NTH_ELEMENT_HPP
#define BKSGE_FND_ALGORITHM_DETAIL_NTH_ELEMENT_HPP
#include <bksge/fnd/algorithm/detail/introselect.hpp>
#include <bksge/fnd/algorithm/detail/lg.hpp>
#include <bksge/fnd/config.hpp>
namespace bksge
{
namespace detail
{
template <typename RandomAccessIterator, typename Compare>
inline BKSGE_CXX14_CONSTEXPR void
nth_element(
RandomAccessIterator first,
RandomAccessIterator nth,
RandomAccessIterator last,
Compare comp)
{
if (first == last || nth == last)
{
return;
}
bksge::detail::introselect(
first, nth, last, bksge::detail::lg(last - first) * 2, comp);
}
} // namespace detail
} // namespace bksge
#endif // BKSGE_FND_ALGORITHM_DETAIL_NTH_ELEMENT_HPP
| 19.477273 | 64 | 0.718786 | myoukaku |
a865f27a20daf4e5f2d44d68a329738578fdeb54 | 4,959 | cpp | C++ | examples/tlm/at_ooo/src/at_ooo_top.cpp | veeYceeY/systemc | 1bd5598ed1a8cf677ebb750accd5af485bc1085a | [
"Apache-2.0"
] | 194 | 2019-07-25T21:27:23.000Z | 2022-03-22T00:08:06.000Z | examples/tlm/at_ooo/src/at_ooo_top.cpp | veeYceeY/systemc | 1bd5598ed1a8cf677ebb750accd5af485bc1085a | [
"Apache-2.0"
] | 24 | 2019-12-03T18:26:07.000Z | 2022-02-17T09:38:25.000Z | examples/tlm/at_ooo/src/at_ooo_top.cpp | veeYceeY/systemc | 1bd5598ed1a8cf677ebb750accd5af485bc1085a | [
"Apache-2.0"
] | 64 | 2019-08-02T19:28:25.000Z | 2022-03-30T10:21:22.000Z | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*=============================================================================
@file example_system_top.cpp
@brief This class instantiates components that compose a TLM2 example system
that demonstrates Out Of Order transaction processing
=============================================================================*/
/*****************************************************************************
Original Authors:
Bill Bunton, ESLX
Anna Keist, ESLX
*****************************************************************************/
#include "at_ooo_top.h" // example system top header
#include "at_target_2_phase.h" // memory target
#include "at_target_ooo_2_phase.h" // memory target
#include "initiator_top.h" // initiator
#include "tlm.h" // TLM header
/*=============================================================================
@fn example_system_top::example_system_top
@brief example_system_top constructor
@details
This class instantiates the example system components and call
the modules bind methods to logically connect the model components.
@param name module name
@retval void
=============================================================================*/
example_system_top::example_system_top ///< constructor
( sc_core::sc_module_name name ///< module name
)
: sc_core::sc_module ///< SC base
( name ///< module name
)
, m_bus ///< bus
( "m_bus" ///< module name
)
, m_at_target_2_phase_1 ///< at_test_target
( "m_at_target_2_phase_1" ///< module name
, 201
, "memory_socket_1" ///< socket name
, 4*1024 ///< memory size (bytes)
, 4 ///< memory width (bytes)
, sc_core::sc_time(10, sc_core::SC_NS) ///< accept delay
, sc_core::sc_time(50, sc_core::SC_NS) ///< read response delay
, sc_core::sc_time(30, sc_core::SC_NS) ///< write response delay
)
, m_at_target_ooo_2_phase_1 ///< at_test_target
( "m_at_target_ooo_2_phase_1" ///< module name
, 202
, "memory_socket_1" ///< socket name
, 4*1024 ///< memory size (bytes)
, 4 ///< memory width (bytes)
// force additional out of order execution by making on
// target longer than the other
, sc_core::sc_time(20, sc_core::SC_NS) ///< accept delay
, sc_core::sc_time(100, sc_core::SC_NS) ///< read response delay
, sc_core::sc_time(60, sc_core::SC_NS) ///< write response delay
)
, m_initiator_1 ///< initiator 1
( "m_initiator_1" ///< module name
, 101 ///< initiator ID
, 0x0000000000000100 ///< fitst base address
, 0x0000000010000100 ///< second base address
, 2 // active transactions
)
, m_initiator_2 ///< initiator 2
( "m_initiator_2" ///< module name
, 102 ///< initiator ID
, 0x0000000000000200 ///< fitst base address
, 0x0000000010000200 ///< second base address
, 2 // active transactions
)
{
// bind TLM2 initiator to TLM2 target
m_initiator_1.initiator_socket(m_bus.target_socket[0]);
m_initiator_2.initiator_socket(m_bus.target_socket[1]);
m_bus.initiator_socket[0](m_at_target_2_phase_1.m_memory_socket);
m_bus.initiator_socket[1](m_at_target_ooo_2_phase_1.m_memory_socket);
}
| 43.5 | 80 | 0.497076 | veeYceeY |
a86623195137bb99ea71ffcb7029404dda1ec14a | 6,306 | hpp | C++ | src/3rd party/boost/boost/multi_array/concept_checks.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/boost/boost/multi_array/concept_checks.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/3rd party/boost/boost/multi_array/concept_checks.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | // Copyright (C) 2002 Ronald Garcia
//
// Permission to copy, use, sell and distribute this software is granted
// provided this copyright notice appears in all copies.
// Permission to modify the code and to distribute modified code is granted
// provided this copyright notice appears in all copies, and a notice
// that the code was modified is included with the copyright notice.
//
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
//
#ifndef BOOST_MULTI_ARRAY_CONCEPT_CHECKS_RG110101_HPP
#define BOOST_MULTI_ARRAY_CONCEPT_CHECKS_RG110101_HPP
//
// concept-checks.hpp - Checks out Const MultiArray and MultiArray
// concepts
//
#include "boost/concept_check.hpp"
namespace boost {
namespace detail {
namespace multi_array {
//
// idgen_helper -
// This is a helper for generating index_gen instantiations with
// the right type in order to test the call to
// operator[](index_gen). Since one would normally write:
// A[ indices[range1][range2] ]; // or
// B[ indices[index1][index2][range1] ];
// idgen helper allows us to generate the "indices" type by
// creating it through recursive calls.
template <std::size_t N>
struct idgen_helper {
template <typename Array, typename IdxGen, typename Call_Type>
static void call(Array& a, const IdxGen& idgen, Call_Type c) {
typedef typename Array::index_range index_range;
typedef typename Array::index index;
idgen_helper<N-1>::call(a,idgen[c],c);
}
};
template <>
struct idgen_helper<0> {
template <typename Array, typename IdxGen, typename Call_Type>
static void call(Array& a, const IdxGen& idgen, Call_Type) {
typedef typename Array::index_range index_range;
typedef typename Array::index index;
a[ idgen ];
}
};
template <typename Array, std::size_t NumDims >
struct ConstMultiArrayConcept
{
void constraints() {
// function_requires< CopyConstructibleConcept<Array> >();
// RG - a( CollectionArchetype) when available...
a[ id ];
// Test slicing, keeping only the first dimension, losing the rest
idgen_helper<NumDims-1>::call(a,idgen[range],id);
// Test slicing, keeping all dimensions.
idgen_helper<NumDims-1>::call(a,idgen[range],range);
st = a.size();
st = a.num_dimensions();
st = a.num_elements();
stp = a.shape();
idp = a.strides();
idp = a.index_bases();
cit = a.begin();
cit = a.end();
crit = a.rbegin();
crit = a.rend();
eltp = a.origin();
}
typedef typename Array::value_type value_type;
typedef typename Array::reference reference;
typedef typename Array::const_reference const_reference;
typedef typename Array::size_type size_type;
typedef typename Array::difference_type difference_type;
typedef typename Array::iterator iterator;
typedef typename Array::const_iterator const_iterator;
typedef typename Array::reverse_iterator reverse_iterator;
typedef typename Array::const_reverse_iterator const_reverse_iterator;
typedef typename Array::element element;
typedef typename Array::index index;
typedef typename Array::index_gen index_gen;
typedef typename Array::index_range index_range;
typedef typename Array::extent_gen extent_gen;
typedef typename Array::extent_range extent_range;
Array a;
size_type st;
const size_type* stp;
index id;
const index* idp;
const_iterator cit;
const_reverse_iterator crit;
const element* eltp;
index_gen idgen;
index_range range;
};
template <typename Array, std::size_t NumDims >
struct MutableMultiArrayConcept
{
void constraints() {
// function_requires< CopyConstructibleConcept<Array> >();
// RG - a( CollectionArchetype) when available...
value_type vt = a[ id ];
// Test slicing, keeping only the first dimension, losing the rest
idgen_helper<NumDims-1>::call(a,idgen[range],id);
// Test slicing, keeping all dimensions.
idgen_helper<NumDims-1>::call(a,idgen[range],range);
st = a.size();
st = a.num_dimensions();
st = a.num_elements();
stp = a.shape();
idp = a.strides();
idp = a.index_bases();
it = a.begin();
it = a.end();
rit = a.rbegin();
rit = a.rend();
eltp = a.origin();
const_constraints(a);
}
void const_constraints(const Array& a) {
// value_type vt = a[ id ];
// Test slicing, keeping only the first dimension, losing the rest
idgen_helper<NumDims-1>::call(a,idgen[range],id);
// Test slicing, keeping all dimensions.
idgen_helper<NumDims-1>::call(a,idgen[range],range);
st = a.size();
st = a.num_dimensions();
st = a.num_elements();
stp = a.shape();
idp = a.strides();
idp = a.index_bases();
cit = a.begin();
cit = a.end();
crit = a.rbegin();
crit = a.rend();
eltp = a.origin();
}
typedef typename Array::value_type value_type;
typedef typename Array::reference reference;
typedef typename Array::const_reference const_reference;
typedef typename Array::size_type size_type;
typedef typename Array::difference_type difference_type;
typedef typename Array::iterator iterator;
typedef typename Array::const_iterator const_iterator;
typedef typename Array::reverse_iterator reverse_iterator;
typedef typename Array::const_reverse_iterator const_reverse_iterator;
typedef typename Array::element element;
typedef typename Array::index index;
typedef typename Array::index_gen index_gen;
typedef typename Array::index_range index_range;
typedef typename Array::extent_gen extent_gen;
typedef typename Array::extent_range extent_range;
Array a;
size_type st;
const size_type* stp;
index id;
const index* idp;
iterator it;
const_iterator cit;
reverse_iterator rit;
const_reverse_iterator crit;
const element* eltp;
index_gen idgen;
index_range range;
};
} // namespace multi_array
} // namespace detail
} // namespace boost
#endif // BOOST_MULTI_ARRAY_CONCEPT_CHECKS_RG110101_HPP
| 30.911765 | 75 | 0.679987 | OLR-xray |
a869c1e901534815ec197af8198353bb6bf335fe | 22,306 | cpp | C++ | learnSipros/Sipros/src/Scores/MVH.cpp | xyz1396/Projects | 943ddb37039c13e2878a1d39a2d4d97c937f183a | [
"MIT"
] | null | null | null | learnSipros/Sipros/src/Scores/MVH.cpp | xyz1396/Projects | 943ddb37039c13e2878a1d39a2d4d97c937f183a | [
"MIT"
] | null | null | null | learnSipros/Sipros/src/Scores/MVH.cpp | xyz1396/Projects | 943ddb37039c13e2878a1d39a2d4d97c937f183a | [
"MIT"
] | null | null | null | /*
* MVH.cpp
*
* Created on: May 23, 2016
* Author: xgo
*/
#include "../Scores/MVH.h"
bool MVH::bUseSmartPlusThreeModel = true;
lnFactorialTable * MVH::lnTable = NULL;
bitset<FragmentTypes_Size> MVH::fragmentTypes(string("0010010"));
double MVH::ProbabilityCutOff = 0.25;
MVH::MVH() {
// TODO Auto-generated constructor stub
}
MVH::~MVH() {
// TODO Auto-generated destructor stub
}
double round(double f, int precision) {
if (f == 0.0f)
return +0.0f;
double multiplier = pow(10.0, (double) precision); // moves f over <precision> decimal places
f *= multiplier;
f = floor(f + 0.5f);
return f / multiplier;
}
/**
* variables needed from MS2Scan
* vdMZ
* vdIntensity
* dParentNeutralMass
* dParentMZ
*/
bool MVH::Preprocess(MS2Scan * Spectrum, multimap<double, double> * IntenSortedPeakPreData) {
vector<double> *vdMZ = &(Spectrum->vdMZ);
vector<double> *vdIntensity = &(Spectrum->vdIntensity);
if (((int) vdMZ->size()) < ProNovoConfig::minIntensityClassCount) {
Spectrum->bSkip = true;
return true;
}
// Spectrum->mzLowerBound = vdMZ->front();
// Spectrum->mzUpperBound = vdMZ->back();
Spectrum->mzLowerBound = ProNovoConfig::minObservedMz;
Spectrum->mzUpperBound = ProNovoConfig::maxObservedMz;
double totalPeakSpace = Spectrum->mzUpperBound - Spectrum->mzLowerBound;
double totalIonCurrent = 0;
if (IntenSortedPeakPreData == NULL) {
cerr << "Error 61" << endl;
exit(1);
return true;
}
IntenSortedPeakPreData->clear();
multimap<double, double>::iterator ite;
for (int i = 0; i < (int) vdMZ->size(); i++) {
if (vdMZ->at(i) <= Spectrum->dParentNeutralMass) {
ite = IntenSortedPeakPreData->insert(make_pair(vdIntensity->at(i), vdMZ->at(i)));
totalIonCurrent += ite->first;
}
}
// FilterByTIC
// Filters out the peaks with the lowest intensities until only <ticCutoffPercentage> of the total ion current remains
if (IntenSortedPeakPreData->empty()) {
Spectrum->bSkip = true;
cerr << "error MVH::Preprocess 1" << endl;
return true;
}
multimap<double, double>::reverse_iterator rite;
double relativeIntensity = 0.0;
for (rite = IntenSortedPeakPreData->rbegin(); relativeIntensity < ProNovoConfig::ticCutoffPercentage && rite != IntenSortedPeakPreData->rend(); ++rite) {
relativeIntensity += (rite->first / totalIonCurrent);
}
if (rite == IntenSortedPeakPreData->rend()) {
--rite;
}
ite = IntenSortedPeakPreData->lower_bound(rite->first);
if (ite != IntenSortedPeakPreData->begin()) {
IntenSortedPeakPreData->erase(IntenSortedPeakPreData->begin(), ite);
}
//FilterByPeakCount
if (!IntenSortedPeakPreData->empty()) {
if (((int) IntenSortedPeakPreData->size()) > ProNovoConfig::MaxPeakCount) {
int peakCount = IntenSortedPeakPreData->size();
ite = IntenSortedPeakPreData->begin();
while (peakCount > ProNovoConfig::MaxPeakCount) {
++ite;
peakCount--;
}
IntenSortedPeakPreData->erase(IntenSortedPeakPreData->begin(), ite);
}
}
//Water Loss
double dMinOneWater = Spectrum->dParentMZ - WATER_MONO / Spectrum->iParentChargeState - ProNovoConfig::getMassAccuracyParentIon();
double dMinTwoWater = Spectrum->dParentMZ - 2 * WATER_MONO / Spectrum->iParentChargeState - ProNovoConfig::getMassAccuracyParentIon();
double dMaxOneWater = Spectrum->dParentMZ - WATER_MONO / Spectrum->iParentChargeState + ProNovoConfig::getMassAccuracyParentIon();
double dMaxTwoWater = Spectrum->dParentMZ - 2 * WATER_MONO / Spectrum->iParentChargeState + ProNovoConfig::getMassAccuracyParentIon();
double maxIntenOneWater = 0;
double dTargeMassOneWater = 0;
double maxIntenTwoWater = 0;
double dTargeMassTwoWater = 0;
for (ite = IntenSortedPeakPreData->begin(); ite != IntenSortedPeakPreData->end(); ++ite) {
if (ite->second > dMinOneWater && ite->second < dMaxOneWater) {
if (maxIntenOneWater < ite->first) {
maxIntenOneWater = ite->first;
dTargeMassOneWater = ite->second;
}
} else if (ite->second > dMinTwoWater && ite->second < dMaxTwoWater) {
if (maxIntenTwoWater < ite->first) {
maxIntenTwoWater = ite->first;
dTargeMassTwoWater = ite->second;
}
}
}
if (dTargeMassOneWater > 0) {
pair<multimap<double, double>::iterator, multimap<double, double>::iterator> iterpair = IntenSortedPeakPreData->equal_range(maxIntenOneWater);
for (ite = iterpair.first; ite != iterpair.second; ++ite) {
if (ite->second == dTargeMassOneWater) {
IntenSortedPeakPreData->erase(ite);
break;
}
}
}
if (dTargeMassTwoWater > 0) {
pair<multimap<double, double>::iterator, multimap<double, double>::iterator> iterpair = IntenSortedPeakPreData->equal_range(maxIntenTwoWater);
for (ite = iterpair.first; ite != iterpair.second; ite++) {
if (ite->second == dTargeMassTwoWater) {
IntenSortedPeakPreData->erase(ite);
break;
}
}
}
//ClassifyPeakIntensities for mvh
map<double, char> * peakData = Spectrum->peakData;
rite = IntenSortedPeakPreData->rbegin();
for (int i = 0; i < ProNovoConfig::NumIntensityClasses; ++i) {
int numFragments = (int) round(
(double) (pow((double) ProNovoConfig::ClassSizeMultiplier, i) * IntenSortedPeakPreData->size())
/ (double) ProNovoConfig::minIntensityClassCount, 0);
for (int j = 0; rite != IntenSortedPeakPreData->rend() && j < numFragments; ++j, ++rite) {
(*peakData)[rite->second] = i + 1;
}
}
vector<int> * intenClassCounts = Spectrum->intenClassCounts;
intenClassCounts->clear();
intenClassCounts->resize(ProNovoConfig::NumIntensityClasses + 1, 0);
map<double, char>::iterator itr;
for (itr = peakData->begin(); itr != peakData->end(); itr++) {
if (itr->second > 0) {
++(intenClassCounts->at(itr->second - 1));
}
}
double fragMassError = ProNovoConfig::getMassAccuracyFragmentIon();
int totalPeakBins = (int) round(totalPeakSpace / (fragMassError * 2.0f), 0);
int peakCount = (int) peakData->size();
intenClassCounts->at(ProNovoConfig::NumIntensityClasses) = totalPeakBins - peakCount;
Spectrum->totalPeakBins = totalPeakBins;
Spectrum->bSkip = false;
IntenSortedPeakPreData->clear();
return true;
}
bool MVH::CalculateSequenceIons(string & sSequence, int maxIonCharge, bool useSmartPlusThreeModel, vector<double>* sequenceIonMasses,
vector<double> * _pdAAforward, vector<double> * _pdAAreverse, vector<char> * seq) {
sequenceIonMasses->clear();
_pdAAforward->clear();
_pdAAreverse->clear();
seq->clear();
int i = 0, j = 0, k = 0, iPeptideLength, iPos;
k = ((int) sSequence.length()) - 1;
char currentPTM = 0;
iPeptideLength = 0;
iPos = 0;
double iterResidueMonoMass;
for (i = 0; i <= k; ++i) {
if (isalpha(sSequence.at(i))) {
iPeptideLength = iPeptideLength + 1;
seq->push_back(sSequence.at(i));
}
}
int iLenMinus1 = iPeptideLength - 1;
if (iPeptideLength < ProNovoConfig::getMinPeptideLength()) {
cerr << "ERROR MVH 1: Peptide sequence is too short " << sSequence << endl;
exit(1);
return false;
}
j = 0;
if (sSequence.at(j) != '[') {
cerr << "ERROR: First character in a peptide sequence must be [." << sSequence << endl;
return false;
}
double dBion = 0;
double dYion = ProNovoConfig::precalcMasses.dCtermOH2;
j++;
if (!isalpha(sSequence.at(j))) {
currentPTM = sSequence.at(j);
iterResidueMonoMass = ProNovoConfig::pdAAMassFragment.find(currentPTM);
if (iterResidueMonoMass == ProNovoConfig::pdAAMassFragment.end()) {
cerr << "ERROR: cannot find this PTM in the config file " << currentPTM << endl;
return false;
}
dBion += iterResidueMonoMass;
j++;
}
if (sSequence.at(k) == ']') {
k--;
} else {
currentPTM = sSequence.at(k);
iterResidueMonoMass = ProNovoConfig::pdAAMassFragment.find(currentPTM);
if (iterResidueMonoMass == ProNovoConfig::pdAAMassFragment.end()) {
cerr << "ERROR: cannot find this PTM in the config file " << currentPTM << endl;
return false;
}
dYion += iterResidueMonoMass;
k--;
if (sSequence.at(k) != ']') {
cerr << "ERROR: (second) Last character in a peptide sequence must be ]." << endl;
return false;
}
k--;
}
//
for (i = 0; i <= iLenMinus1; i++) {
//First forward
if (!isalpha(sSequence.at(j))) {
cerr << "ERROR: One residue can only have one PTM (Up to only one symbol after an amino acid)" << endl;
exit(1);
return false;
}
currentPTM = sSequence.at(j);
iterResidueMonoMass = ProNovoConfig::pdAAMassFragment.find(currentPTM);
if (iterResidueMonoMass == ProNovoConfig::pdAAMassFragment.end()) {
cerr << "ERROR: One residue can only have one PTM (Up to only one symbol after an amino acid)" << endl;
exit(1);
return false;
}
dBion += iterResidueMonoMass;
j++;
if (j < (int) sSequence.length() && !isalpha(sSequence.at(j)) && sSequence.at(j) != ']') {
currentPTM = sSequence.at(j);
iterResidueMonoMass = ProNovoConfig::pdAAMassFragment.find(currentPTM);
if (iterResidueMonoMass == ProNovoConfig::pdAAMassFragment.end()) {
cerr << "ERROR: cannot find this PTM in the config file " << currentPTM << endl;
return false;
}
dBion += iterResidueMonoMass;
j++;
}
_pdAAforward->push_back(dBion);
// now reverse
if (!isalpha(sSequence.at(k))) {
currentPTM = sSequence.at(k);
iterResidueMonoMass = ProNovoConfig::pdAAMassFragment.find(currentPTM);
if (iterResidueMonoMass == ProNovoConfig::pdAAMassFragment.end()) {
cerr << "ERROR: cannot find this PTM in the config file " << currentPTM << endl;
exit(1);
return false;
}
dYion += iterResidueMonoMass;
k--;
}
if (!isalpha(sSequence.at(k))) {
cerr << "ERROR: One residue can only have one PTM (Up to only one symbol after an amino acid)" << endl;
exit(1);
return false;
}
currentPTM = sSequence.at(k);
iterResidueMonoMass = ProNovoConfig::pdAAMassFragment.find(currentPTM);
if (iterResidueMonoMass == ProNovoConfig::pdAAMassFragment.end()) {
cerr << "ERROR: cannot find this PTM in the config file" << currentPTM << endl;
exit(1);
return false;
}
dYion += iterResidueMonoMass;
k--;
_pdAAreverse->push_back(dYion);
iPos++;
}
// calculate y ion MZs
if (maxIonCharge > 2) {
if (useSmartPlusThreeModel) {
int totalStrongBasicCount = 0, totalWeakBasicCount = 0;
for (i = 0; i < iPeptideLength; i++) {
if (seq->at(i) == 'R' || seq->at(i) == 'K' || seq->at(i) == 'H') {
++totalStrongBasicCount;
} else if (seq->at(i) == 'Q' || seq->at(i) == 'N') {
++totalWeakBasicCount;
}
}
int totalBasicity = totalStrongBasicCount * 4 + totalWeakBasicCount * 2 + iPeptideLength - 2;
map<double, int> basicityThresholds;
basicityThresholds.clear();
basicityThresholds[0.0] = 1;
for (int z = 1; z < maxIonCharge - 1; ++z) {
basicityThresholds[(double) z / (double) (maxIonCharge - 1)] = z + 1;
}
for (int c = 0; c <= iPeptideLength; ++c) {
int bStrongBasicCount = 0, bWeakBasicCount = 0;
for (i = 0; i < c; ++i) {
if (seq->at(i) == 'R' || seq->at(i) == 'K' || seq->at(i) == 'H') {
++bStrongBasicCount;
} else if (seq->at(i) == 'Q' || seq->at(i) == 'N') {
++bWeakBasicCount;
}
}
int bScore = bStrongBasicCount * 4 + bWeakBasicCount * 2 + c;
double basicityRatio = (double) bScore / (double) totalBasicity;
map<double, int>::iterator itr = basicityThresholds.upper_bound(basicityRatio);
if (itr == basicityThresholds.begin()) {
cerr << "error 83" << endl;
}
--itr;
int bZ = itr->second;
int yZ = maxIonCharge - bZ;
if (c > 0) {
if (fragmentTypes[FragmentType_B]) {
sequenceIonMasses->push_back((_pdAAforward->at(c - 1) + (Proton * bZ)) / bZ);
}
}
if (c < iPeptideLength) {
if (fragmentTypes[FragmentType_Y]) {
sequenceIonMasses->push_back((_pdAAreverse->at(iLenMinus1 - c) + (Proton * yZ)) / yZ);
}
}
}
} else { // no Smart Plus Three Model
for (int z = 1; z < maxIonCharge; ++z) {
for (int c = 0; c <= iLenMinus1; ++c) {
if (c > 0) {
if (fragmentTypes[FragmentType_B]) {
sequenceIonMasses->push_back((_pdAAforward->at(c - 1) + (Proton * z)) / z);
}
}
if (fragmentTypes[FragmentType_Y]) {
sequenceIonMasses->push_back((_pdAAreverse->at(c) + (Proton * z)) / z);
}
}
}
}
} else {
for (int c = 0; c < iLenMinus1; ++c) {
if (fragmentTypes[FragmentType_B]) {
sequenceIonMasses->push_back((_pdAAforward->at(c) + Proton));
}
if (fragmentTypes[FragmentType_Y]) {
sequenceIonMasses->push_back((_pdAAreverse->at(c) + Proton));
}
}
if (fragmentTypes[FragmentType_Y]) {
sequenceIonMasses->push_back((_pdAAreverse->at(iLenMinus1) + Proton));
}
}
return true;
}
bool MVH::CalculateSequenceIonsSIP(string & sSequence, int maxIonCharge, bool useSmartPlusThreeModel, vector<double>* sequenceIonMasses,
vector<vector<double> > & vvdYionMass, vector<vector<double> > & vvdYionProb, vector<vector<double> > & vvdBionMass,
vector<vector<double> > & vvdBionProb, vector<char> * seq) {
sequenceIonMasses->clear();
seq->clear();
int k = 0, iPeptideLength = 0;
k = ((int) sSequence.length()) - 1;
for (int i = 0; i <= k; ++i) {
if (isalpha(sSequence.at(i))) {
iPeptideLength = iPeptideLength + 1;
seq->push_back(sSequence.at(i));
}
}
int iIonMassSize = 0, iIsotopicDistSize = 0;
double dFragmentIonMassZ = 0;
int iLenMinus1 = iPeptideLength - 1;
if (((int)vvdYionMass.size()) != iLenMinus1 || ((int)vvdBionMass.size()) != iLenMinus1) {
cout << "check 111" << endl;
}
// calculate y ion MZs
if (maxIonCharge > 2) {
if (useSmartPlusThreeModel) {
int totalStrongBasicCount = 0, totalWeakBasicCount = 0;
for (int i = 0; i < iPeptideLength; i++) {
if (seq->at(i) == 'R' || seq->at(i) == 'K' || seq->at(i) == 'H') {
++totalStrongBasicCount;
} else if (seq->at(i) == 'Q' || seq->at(i) == 'N') {
++totalWeakBasicCount;
}
}
int totalBasicity = totalStrongBasicCount * 4 + totalWeakBasicCount * 2 + iPeptideLength - 2;
map<double, int> basicityThresholds;
basicityThresholds.clear();
basicityThresholds[0.0] = 1;
for (int z = 1; z < maxIonCharge - 1; ++z) {
basicityThresholds[(double) z / (double) (maxIonCharge - 1)] = z + 1;
}
for (int c = 1; c < iPeptideLength; ++c) {
int bStrongBasicCount = 0, bWeakBasicCount = 0;
for (int i = 0; i < c; ++i) {
if (seq->at(i) == 'R' || seq->at(i) == 'K' || seq->at(i) == 'H') {
++bStrongBasicCount;
} else if (seq->at(i) == 'Q' || seq->at(i) == 'N') {
++bWeakBasicCount;
}
}
int bScore = bStrongBasicCount * 4 + bWeakBasicCount * 2 + c;
double basicityRatio = (double) bScore / (double) totalBasicity;
map<double, int>::iterator itr = basicityThresholds.upper_bound(basicityRatio);
if (itr == basicityThresholds.begin()) {
cerr << "error 83" << endl;
}
--itr;
int bZ = itr->second;
int yZ = maxIonCharge - bZ;
if (fragmentTypes[FragmentType_B]) {
iIsotopicDistSize = vvdBionMass.at(c - 1).size();
for (int j = 0; j < iIsotopicDistSize; ++j) {
if (vvdBionProb.at(c - 1).at(j) < ProbabilityCutOff) {
continue;
}
dFragmentIonMassZ = (vvdBionMass.at(c - 1).at(j) / bZ + Proton);
sequenceIonMasses->push_back(dFragmentIonMassZ);
}
}
if (fragmentTypes[FragmentType_Y]) {
iIsotopicDistSize = vvdYionMass.at(iLenMinus1 - c).size();
for (int j = 0; j < iIsotopicDistSize; ++j) {
if (vvdYionProb.at(iLenMinus1 - c).at(j) < ProbabilityCutOff) {
continue;
}
dFragmentIonMassZ = (vvdYionMass.at(iLenMinus1 - c).at(j) / yZ + Proton);
sequenceIonMasses->push_back(dFragmentIonMassZ);
}
}
}
} else { // no Smart Plus Three Model
for (int z = 1; z < maxIonCharge; ++z) {
// b-ion
if (fragmentTypes[FragmentType_B]) {
iIonMassSize = vvdBionMass.size();
for (int i = 0; i < iIonMassSize; ++i) {
iIsotopicDistSize = vvdBionMass.at(i).size();
for (int j = 0; j < iIsotopicDistSize; ++j) {
if (vvdBionProb.at(i).at(j) < ProbabilityCutOff) {
continue;
}
dFragmentIonMassZ = (vvdBionMass.at(i).at(j) / z + Proton);
sequenceIonMasses->push_back(dFragmentIonMassZ);
}
}
}
// y-ion
if (fragmentTypes[FragmentType_Y]) {
iIonMassSize = vvdYionMass.size();
for (int i = 0; i < iIonMassSize; ++i) {
iIsotopicDistSize = vvdYionMass.at(i).size();
for (int j = 0; j < iIsotopicDistSize; ++j) {
if (vvdYionProb.at(i).at(j) < ProbabilityCutOff) {
continue;
}
dFragmentIonMassZ = (vvdYionMass.at(i).at(j) / z + Proton);
sequenceIonMasses->push_back(dFragmentIonMassZ);
}
}
}
}
}
} else {
// b-ion
if (fragmentTypes[FragmentType_B]) {
iIonMassSize = vvdBionMass.size();
for (int i = 0; i < iIonMassSize; ++i) {
iIsotopicDistSize = vvdBionMass.at(i).size();
for (int j = 0; j < iIsotopicDistSize; ++j) {
if (vvdBionProb.at(i).at(j) < ProbabilityCutOff) {
continue;
}
dFragmentIonMassZ = (vvdBionMass.at(i).at(j) + Proton);
sequenceIonMasses->push_back(dFragmentIonMassZ);
}
}
}
// y-ion
if (fragmentTypes[FragmentType_Y]) {
iIonMassSize = vvdYionMass.size();
for (int i = 0; i < iIonMassSize; ++i) {
iIsotopicDistSize = vvdYionMass.at(i).size();
for (int j = 0; j < iIsotopicDistSize; ++j) {
if (vvdYionProb.at(i).at(j) < ProbabilityCutOff) {
continue;
}
dFragmentIonMassZ = (vvdYionMass.at(i).at(j) + Proton);
sequenceIonMasses->push_back(dFragmentIonMassZ);
}
}
}
}
return true;
}
bool MVH::destroyLnTable() {
if (MVH::lnTable != NULL) {
delete MVH::lnTable;
MVH::lnTable = NULL;
}
return true;
}
multimap<double, char>::iterator MVH::findNear(map<double, char> * peakData, double mz, double tolerance) {
multimap<double, char>::iterator cur, min, max, best;
min = peakData->lower_bound(mz - tolerance);
max = peakData->upper_bound(mz + tolerance);
if (min == max) {
return peakData->end();
}
best = min;
double minDiff = fabs(mz - best->first);
for (cur = min; cur != max; ++cur) {
double curDiff = fabs(mz - cur->first);
if (curDiff < minDiff) {
minDiff = curDiff;
best = cur;
}
}
return best;
}
bool MVH::initialLnTable(int maxPeakBins) {
if (MVH::lnTable != NULL) {
delete MVH::lnTable;
MVH::lnTable = NULL;
}
MVH::lnTable = new lnFactorialTable();
MVH::lnTable->resize(maxPeakBins);
return true;
}
double MVH::lnCombin(int n, int k) {
if (n < 0 || k < 0 || n < k)
return -1;
try {
return (*lnTable)[n] - (*lnTable)[n - k] - (*lnTable)[k];
} catch (std::exception& e) {
cerr << "lnCombin(): caught exception with n=" << n << " and k=" << k << endl;
throw e;
}
}
bool MVH::ScoreSequenceVsSpectrum(string & currentPeptide, MS2Scan * Spectrum, vector<double>* seqIons, vector<double> * _pdAAforward,
vector<double> * _pdAAreverse, double & dMvh, vector<char> * seq) {
if (!CalculateSequenceIons(currentPeptide, Spectrum->iParentChargeState, bUseSmartPlusThreeModel, seqIons, _pdAAforward, _pdAAreverse, seq)) {
return false;
}
int totalPeaks = (int) seqIons->size();
char peakItr;
PeakList * pPeakList = Spectrum->pPeakList;
vector<int> mvhKey;
mvhKey.clear();
mvhKey.resize(ProNovoConfig::NumIntensityClasses + 1, 0);
for (int j = 0; j < (int) seqIons->size(); ++j) {
if (seqIons->at(j) < Spectrum->mzLowerBound || seqIons->at(j) > Spectrum->mzUpperBound) {
--totalPeaks;
continue;
}
peakItr = pPeakList->findNear(seqIons->at(j), ProNovoConfig::getMassAccuracyFragmentIon());
if (peakItr != pPeakList->end() && peakItr > 0) {
++(mvhKey.at(peakItr - 1));
} else {
++(mvhKey.at(ProNovoConfig::NumIntensityClasses));
}
}
double mvh = 0.0;
int fragmentsUnmatched = mvhKey.back();
if (fragmentsUnmatched != totalPeaks) {
int fragmentsPredicted = accumulate(mvhKey.begin(), mvhKey.end(), 0);
int fragmentsMatched = fragmentsPredicted - fragmentsUnmatched;
if (fragmentsMatched >= ProNovoConfig::MinMatchedFragments) {
int numVoids = Spectrum->intenClassCounts->back();
int totalPeakBins = numVoids + pPeakList->size();
for (int i = 0; i < (int) Spectrum->intenClassCounts->size(); ++i) {
mvh += lnCombin(Spectrum->intenClassCounts->at(i), mvhKey.at(i));
}
mvh -= lnCombin(totalPeakBins, fragmentsPredicted);
dMvh = -mvh;
} else {
return false;
}
} else {
return false;
}
/* if (currentPeptide == "[QITNQDSDARTLIVNNTNGNK]" && Spectrum->iScanId == 120) {
cout << "check" << endl;
}*/
return true;
}
bool MVH::ScoreSequenceVsSpectrumSIP(string & currentPeptide, MS2Scan * Spectrum, vector<double>* seqIons, vector<vector<double> > & vvdYionMass,
vector<vector<double> > & vvdYionProb, vector<vector<double> > & vvdBionMass, vector<vector<double> > & vvdBionProb, double & dMvh,
vector<char> * seq) {
if (!CalculateSequenceIonsSIP(currentPeptide, Spectrum->iParentChargeState, bUseSmartPlusThreeModel, seqIons, vvdYionMass, vvdYionProb, vvdBionMass,
vvdBionProb, seq)) {
return false;
}
int totalPeaks = (int) seqIons->size();
char peakItr;
PeakList * pPeakList = Spectrum->pPeakList;
vector<int> mvhKey;
mvhKey.clear();
mvhKey.resize(ProNovoConfig::NumIntensityClasses + 1, 0);
for (int j = 0; j < (int) seqIons->size(); ++j) {
if (seqIons->at(j) < Spectrum->mzLowerBound || seqIons->at(j) > Spectrum->mzUpperBound) {
--totalPeaks;
continue;
}
peakItr = pPeakList->findNear(seqIons->at(j), ProNovoConfig::getMassAccuracyFragmentIon());
if (peakItr != pPeakList->end() && peakItr > 0) {
++(mvhKey.at(peakItr - 1));
} else {
++(mvhKey.at(ProNovoConfig::NumIntensityClasses));
}
}
double mvh = 0.0;
int fragmentsUnmatched = mvhKey.back();
if (fragmentsUnmatched != totalPeaks) {
int fragmentsPredicted = accumulate(mvhKey.begin(), mvhKey.end(), 0);
int fragmentsMatched = fragmentsPredicted - fragmentsUnmatched;
if (fragmentsMatched >= ProNovoConfig::MinMatchedFragments) {
int numVoids = Spectrum->intenClassCounts->back();
int totalPeakBins = numVoids + pPeakList->size();
for (int i = 0; i < (int) Spectrum->intenClassCounts->size(); ++i) {
mvh += lnCombin(Spectrum->intenClassCounts->at(i), mvhKey.at(i));
}
mvh -= lnCombin(totalPeakBins, fragmentsPredicted);
dMvh = -mvh;
} else {
return false;
}
} else {
return false;
}
return true;
}
| 33.848255 | 154 | 0.654577 | xyz1396 |
a86a357c163bc7e81e00664a6ed39905f5d40611 | 15,313 | cc | C++ | source/geometry/divisions/pyG4ParameterisationCons.cc | yu22mal/geant4_pybind | ff7efc322fe53f39c7ae7ed140861052a92479fd | [
"Unlicense"
] | 6 | 2021-08-08T08:40:13.000Z | 2022-03-23T03:05:15.000Z | source/geometry/divisions/pyG4ParameterisationCons.cc | yu22mal/geant4_pybind | ff7efc322fe53f39c7ae7ed140861052a92479fd | [
"Unlicense"
] | 3 | 2021-12-01T14:38:06.000Z | 2022-02-10T11:28:28.000Z | source/geometry/divisions/pyG4ParameterisationCons.cc | yu22mal/geant4_pybind | ff7efc322fe53f39c7ae7ed140861052a92479fd | [
"Unlicense"
] | 3 | 2021-07-16T13:57:34.000Z | 2022-02-07T11:17:19.000Z | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <G4ParameterisationCons.hh>
#include <G4Material.hh>
#include <G4VPhysicalVolume.hh>
#include <G4VTouchable.hh>
#include <G4VSolid.hh>
#include <G4Box.hh>
#include <G4Tubs.hh>
#include <G4Trd.hh>
#include <G4Trap.hh>
#include <G4Cons.hh>
#include <G4Sphere.hh>
#include <G4Orb.hh>
#include <G4Ellipsoid.hh>
#include <G4Torus.hh>
#include <G4Para.hh>
#include <G4Polycone.hh>
#include <G4Polyhedra.hh>
#include <G4Hype.hh>
#include "typecast.hh"
#include "opaques.hh"
namespace py = pybind11;
class PyG4VParameterisationCons : public G4VParameterisationCons, public py::trampoline_self_life_support {
public:
using G4VParameterisationCons::G4VParameterisationCons;
void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override
{
PYBIND11_OVERRIDE_PURE(void, G4VParameterisationCons, ComputeTransformation, copyNo, physVol);
}
G4double GetMaxParameter() const override
{
PYBIND11_OVERRIDE_PURE(G4double, G4VParameterisationCons, GetMaxParameter, );
}
G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override
{
PYBIND11_OVERRIDE(G4VSolid *, G4VParameterisationCons, ComputeSolid, arg0, arg1);
}
void CheckParametersValidity() override
{
PYBIND11_OVERRIDE(void, G4VParameterisationCons, CheckParametersValidity, );
}
G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol,
const G4VTouchable *parentTouch) override
{
PYBIND11_OVERRIDE(G4Material *, G4VParameterisationCons, ComputeMaterial, repNo, currentVol, parentTouch);
}
G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4VParameterisationCons, IsNested, ); }
G4VVolumeMaterialScanner *GetMaterialScanner() override
{
PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4VParameterisationCons, GetMaterialScanner, );
}
void ComputeDimensions(G4Box &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Tubs &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Trd &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Trap &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Cons &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Sphere &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Orb &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Ellipsoid &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Torus &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Para &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Polycone &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Polyhedra &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
void ComputeDimensions(G4Hype &arg0, const G4int arg1, const G4VPhysicalVolume *arg2) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4VParameterisationCons, "ComputeDimensions", std::addressof(arg0), arg1, arg2);
return G4VParameterisationCons::ComputeDimensions(arg0, arg1, arg2);
}
};
class PyG4ParameterisationConsRho : public G4ParameterisationConsRho, public py::trampoline_self_life_support {
public:
using G4ParameterisationConsRho::G4ParameterisationConsRho;
G4double GetMaxParameter() const override
{
PYBIND11_OVERRIDE(G4double, G4ParameterisationConsRho, GetMaxParameter, );
}
void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override
{
PYBIND11_OVERRIDE(void, G4ParameterisationConsRho, ComputeTransformation, copyNo, physVol);
}
void ComputeDimensions(G4Cons &tubs, const G4int copyNo, const G4VPhysicalVolume *physVol) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4ParameterisationConsRho, "ComputeDimensions", std::addressof(tubs), copyNo,
physVol);
G4ParameterisationConsRho::ComputeDimensions(tubs, copyNo, physVol);
}
G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override
{
PYBIND11_OVERRIDE(G4VSolid *, G4ParameterisationConsRho, ComputeSolid, arg0, arg1);
}
void CheckParametersValidity() override
{
PYBIND11_OVERRIDE(void, G4ParameterisationConsRho, CheckParametersValidity, );
}
G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol,
const G4VTouchable *parentTouch) override
{
PYBIND11_OVERRIDE(G4Material *, G4ParameterisationConsRho, ComputeMaterial, repNo, currentVol, parentTouch);
}
G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4ParameterisationConsRho, IsNested, ); }
G4VVolumeMaterialScanner *GetMaterialScanner() override
{
PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4ParameterisationConsRho, GetMaterialScanner, );
}
};
class PyG4ParameterisationConsPhi : public G4ParameterisationConsPhi, public py::trampoline_self_life_support {
public:
using G4ParameterisationConsPhi::G4ParameterisationConsPhi;
G4double GetMaxParameter() const override
{
PYBIND11_OVERRIDE(G4double, G4ParameterisationConsPhi, GetMaxParameter, );
}
void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override
{
PYBIND11_OVERRIDE(void, G4ParameterisationConsPhi, ComputeTransformation, copyNo, physVol);
}
void ComputeDimensions(G4Cons &tubs, const G4int copyNo, const G4VPhysicalVolume *physVol) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4ParameterisationConsPhi, "ComputeDimensions", std::addressof(tubs), copyNo,
physVol);
G4ParameterisationConsPhi::ComputeDimensions(tubs, copyNo, physVol);
}
G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override
{
PYBIND11_OVERRIDE(G4VSolid *, G4ParameterisationConsPhi, ComputeSolid, arg0, arg1);
}
void CheckParametersValidity() override
{
PYBIND11_OVERRIDE(void, G4ParameterisationConsPhi, CheckParametersValidity, );
}
G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol,
const G4VTouchable *parentTouch) override
{
PYBIND11_OVERRIDE(G4Material *, G4ParameterisationConsPhi, ComputeMaterial, repNo, currentVol, parentTouch);
}
G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4ParameterisationConsPhi, IsNested, ); }
G4VVolumeMaterialScanner *GetMaterialScanner() override
{
PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4ParameterisationConsPhi, GetMaterialScanner, );
}
};
class PyG4ParameterisationConsZ : public G4ParameterisationConsZ, public py::trampoline_self_life_support {
public:
using G4ParameterisationConsZ::G4ParameterisationConsZ;
G4double GetMaxParameter() const override
{
PYBIND11_OVERRIDE(G4double, G4ParameterisationConsZ, GetMaxParameter, );
}
void ComputeTransformation(const G4int copyNo, G4VPhysicalVolume *physVol) const override
{
PYBIND11_OVERRIDE(void, G4ParameterisationConsZ, ComputeTransformation, copyNo, physVol);
}
void ComputeDimensions(G4Cons &tubs, const G4int copyNo, const G4VPhysicalVolume *physVol) const override
{
PYBIND11_OVERRIDE_IMPL(void, G4ParameterisationConsZ, "ComputeDimensions", std::addressof(tubs), copyNo, physVol);
G4ParameterisationConsZ::ComputeDimensions(tubs, copyNo, physVol);
}
G4VSolid *ComputeSolid(const G4int arg0, G4VPhysicalVolume *arg1) override
{
PYBIND11_OVERRIDE(G4VSolid *, G4ParameterisationConsZ, ComputeSolid, arg0, arg1);
}
void CheckParametersValidity() override
{
PYBIND11_OVERRIDE(void, G4ParameterisationConsZ, CheckParametersValidity, );
}
G4Material *ComputeMaterial(const G4int repNo, G4VPhysicalVolume *currentVol,
const G4VTouchable *parentTouch) override
{
PYBIND11_OVERRIDE(G4Material *, G4ParameterisationConsZ, ComputeMaterial, repNo, currentVol, parentTouch);
}
G4bool IsNested() const override { PYBIND11_OVERRIDE(G4bool, G4ParameterisationConsZ, IsNested, ); }
G4VVolumeMaterialScanner *GetMaterialScanner() override
{
PYBIND11_OVERRIDE(G4VVolumeMaterialScanner *, G4ParameterisationConsZ, GetMaterialScanner, );
}
};
void export_G4ParameterisationCons(py::module &m)
{
py::class_<G4VParameterisationCons, PyG4VParameterisationCons, G4VDivisionParameterisation>(
m, "G4VParameterisationCons")
.def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"),
py::arg("offset"), py::arg("step"), py::arg("msolid"), py::arg("divType"))
.def("__copy__", [](const PyG4VParameterisationCons &self) { return PyG4VParameterisationCons(self); })
.def("__deepcopy__",
[](const PyG4VParameterisationCons &self, py::dict) { return PyG4VParameterisationCons(self); });
py::class_<G4ParameterisationConsRho, PyG4ParameterisationConsRho, G4VParameterisationCons>(
m, "G4ParameterisationConsRho")
.def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"),
py::arg("offset"), py::arg("step"), py::arg("motherSolid"), py::arg("divType"))
.def("__copy__", [](const PyG4ParameterisationConsRho &self) { return PyG4ParameterisationConsRho(self); })
.def("__deepcopy__",
[](const PyG4ParameterisationConsRho &self, py::dict) { return PyG4ParameterisationConsRho(self); })
.def("GetMaxParameter", &G4ParameterisationConsRho::GetMaxParameter)
.def("ComputeTransformation", &G4ParameterisationConsRho::ComputeTransformation, py::arg("copyNo"),
py::arg("physVol"))
.def("ComputeDimensions",
py::overload_cast<G4Cons &, const G4int, const G4VPhysicalVolume *>(
&G4ParameterisationConsRho::ComputeDimensions, py::const_),
py::arg("tubs"), py::arg("copyNo"), py::arg("physVol"));
py::class_<G4ParameterisationConsPhi, PyG4ParameterisationConsPhi, G4VParameterisationCons>(
m, "G4ParameterisationConsPhi")
.def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"),
py::arg("offset"), py::arg("step"), py::arg("motherSolid"), py::arg("divType"))
.def("__copy__", [](const PyG4ParameterisationConsPhi &self) { return PyG4ParameterisationConsPhi(self); })
.def("__deepcopy__",
[](const PyG4ParameterisationConsPhi &self, py::dict) { return PyG4ParameterisationConsPhi(self); })
.def("GetMaxParameter", &G4ParameterisationConsPhi::GetMaxParameter)
.def("ComputeTransformation", &G4ParameterisationConsPhi::ComputeTransformation, py::arg("copyNo"),
py::arg("physVol"))
.def("ComputeDimensions",
py::overload_cast<G4Cons &, const G4int, const G4VPhysicalVolume *>(
&G4ParameterisationConsPhi::ComputeDimensions, py::const_),
py::arg("tubs"), py::arg("copyNo"), py::arg("physVol"));
py::class_<G4ParameterisationConsZ, PyG4ParameterisationConsZ, G4VParameterisationCons>(m, "G4ParameterisationConsZ")
.def(py::init<EAxis, G4int, G4double, G4double, G4VSolid *, DivisionType>(), py::arg("axis"), py::arg("nCopies"),
py::arg("offset"), py::arg("step"), py::arg("motherSolid"), py::arg("divType"))
.def("__copy__", [](const PyG4ParameterisationConsZ &self) { return PyG4ParameterisationConsZ(self); })
.def("__deepcopy__",
[](const PyG4ParameterisationConsZ &self, py::dict) { return PyG4ParameterisationConsZ(self); })
.def("GetMaxParameter", &G4ParameterisationConsZ::GetMaxParameter)
.def("ComputeTransformation", &G4ParameterisationConsZ::ComputeTransformation, py::arg("copyNo"),
py::arg("physVol"))
.def("ComputeDimensions",
py::overload_cast<G4Cons &, const G4int, const G4VPhysicalVolume *>(
&G4ParameterisationConsZ::ComputeDimensions, py::const_),
py::arg("tubs"), py::arg("copyNo"), py::arg("physVol"));
}
| 43.751429 | 121 | 0.717691 | yu22mal |
a86bfed67420dbda88c73252b3245f626081fd86 | 7,007 | hxx | C++ | ComputeLBMBoundaries/LBMNoseSphere.hxx | PediatricAirways/CrossSectionMeasurementTools | 059909d16f0b3033b7b604a2174c7c239dc63dcb | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-11-11T16:57:59.000Z | 2018-03-13T09:28:10.000Z | ComputeLBMBoundaries/LBMNoseSphere.hxx | PediatricAirways/CrossSectionMeasurementTools | 059909d16f0b3033b7b604a2174c7c239dc63dcb | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | ComputeLBMBoundaries/LBMNoseSphere.hxx | PediatricAirways/CrossSectionMeasurementTools | 059909d16f0b3033b7b604a2174c7c239dc63dcb | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #ifndef LBMNoseSphere_hxx_included
#define LBMNoseSphere_hxx_included
#include <queue>
#include <itkImage.h>
#include "LBMNoseSphere.h"
namespace {
template< class TBinaryImage >
bool
InsideSphere( typename TBinaryImage::IndexType index,
TBinaryImage * binaryImage,
typename TBinaryImage::PointType sphereCenter,
double sphereRadius )
{
// Compute distance from voxel to sphere center
typename TBinaryImage::PointType voxelPosition;
binaryImage->TransformIndexToPhysicalPoint( index, voxelPosition );
typename TBinaryImage::PointType::VectorType voxelOffset = voxelPosition - sphereCenter;
double distance2 = voxelOffset[0]*voxelOffset[0] +
voxelOffset[1]*voxelOffset[1] +
voxelOffset[2]*voxelOffset[2];
return ( distance2 <= sphereRadius*sphereRadius );
}
template< class TBinaryImage >
bool
OnSphereEdge( typename TBinaryImage::IndexType index,
TBinaryImage * binaryImage,
typename TBinaryImage::PointType sphereCenter,
double sphereRadius )
{
// Make sure this voxel is inside the sphere
if ( !InsideSphere( index, binaryImage, sphereCenter, sphereRadius ) )
return false;
bool neighborOutside = false;
typename TBinaryImage::IndexType nbrIndex;
typename TBinaryImage::RegionType region = binaryImage->GetLargestPossibleRegion();
for ( int k = index[2] - 1; k <= index[2] + 1; ++k ) {
nbrIndex[2] = k;
for ( int j = index[1] - 1; j <= index[1] + 1; ++j ) {
nbrIndex[1] = j;
for ( int i = index[0] - 1; i <= index[0] + 1; ++i ) {
nbrIndex[0] = i;
// Check that we're in the image
if ( region.IsInside( nbrIndex ) ) {
if ( !InsideSphere( nbrIndex, binaryImage,
sphereCenter, sphereRadius ) ) {
neighborOutside = true;
break;
}
}
}
}
}
return neighborOutside;
}
template< class TBinaryImage >
typename TBinaryImage::RegionType
GetNoseSphereRegion( typename TBinaryImage::PointType sphereCenter,
double sphereRadius,
const TBinaryImage * binaryImage )
{
// Find region bounding the sphere
typename TBinaryImage::PointType sphereMin( sphereCenter );
sphereMin -= sphereRadius;
typename TBinaryImage::IndexType sphereMinIndex;
binaryImage->TransformPhysicalPointToIndex( sphereMin, sphereMinIndex );
typename TBinaryImage::PointType sphereMax( sphereCenter );
sphereMax += sphereRadius;
typename TBinaryImage::IndexType sphereMaxIndex;
binaryImage->TransformPhysicalPointToIndex( sphereMax, sphereMaxIndex );
// Pad min and max index by 1
for ( int i = 0; i < TBinaryImage::ImageDimension; ++i ) {
sphereMinIndex[i] -= 1;
sphereMaxIndex[i] += 1;
}
typename TBinaryImage::RegionType sphereRegion;
sphereRegion.SetIndex( sphereMinIndex );
sphereRegion.SetUpperIndex( sphereMaxIndex );
return sphereRegion;
}
template< class TBinaryImage, class TOriginalImage >
void AddNoseSphere( typename TBinaryImage::PointType sphereCenter,
double sphereRadius,
TBinaryImage * binaryImage,
TOriginalImage * originalImage,
double airThreshold,
typename TBinaryImage::PixelType interiorValue,
typename TBinaryImage::PixelType exteriorValue,
typename TBinaryImage::PixelType inflowValue )
{
// Get region of binary image
typename TBinaryImage::RegionType imageRegion =
binaryImage->GetLargestPossibleRegion();
typename TBinaryImage::RegionType sphereRegion =
GetNoseSphereRegion( sphereCenter, sphereRadius, binaryImage );
// Crop the sphere region by the image region
sphereRegion.Crop( imageRegion );
// Allocate an image to track where we've visited
const short NOT_VISITED = 0;
const short SCHEDULED_FOR_VISIT = 1;
const short VISITED = 2;
typedef itk::Image< short, 3 > VisitedImageType;
VisitedImageType::Pointer visitedImage = VisitedImageType::New();
visitedImage->SetRegions( sphereRegion );
visitedImage->Allocate();
visitedImage->FillBuffer( NOT_VISITED );
// Convert seed point to index in binary image
typename TBinaryImage::IndexType seedIndex;
binaryImage->TransformPhysicalPointToIndex( sphereCenter, seedIndex );
// Push seed index onto stack
std::queue< typename TBinaryImage::IndexType > queue;
queue.push( seedIndex );
visitedImage->SetPixel( seedIndex, SCHEDULED_FOR_VISIT );
// Process queue elements until queue is empty
while ( !queue.empty() ) {
typename TBinaryImage::IndexType index = queue.front();
queue.pop();
if ( !imageRegion.IsInside( index ) ) continue;
typename TBinaryImage::PixelType binaryValue =
binaryImage->GetPixel( index );
typename TOriginalImage::PixelType pixelValue =
originalImage->GetPixel( index );
typename VisitedImageType::PixelType visited =
visitedImage->GetPixel( index );
if ( visited != SCHEDULED_FOR_VISIT ) {
std::cout << "Voxel " << index << " wasn't scheduled for visit!" << std::endl;
}
// If already visited, skip this voxel
if ( visited == VISITED ) {
continue;
}
// Mark the voxel as visited
visitedImage->SetPixel( index, VISITED );
// Compute distance from voxel to sphere center
bool insideSphere = InsideSphere( index, binaryImage,
sphereCenter, sphereRadius );
if ( pixelValue <= airThreshold &&
insideSphere ) {
// Mark as being in the segmentation
if ( OnSphereEdge( index, binaryImage, sphereCenter, sphereRadius ) &&
binaryValue == exteriorValue ) {
binaryImage->SetPixel( index, inflowValue );
} else {
binaryImage->SetPixel( index, interiorValue );
}
// Add neighboring pixels to queue if they aren't in the binary
// image already
for ( int z = index[2]-1; z <= index[2]+1; ++z ) {
for ( int y = index[1]-1; y <= index[1]+1; ++y ) {
for ( int x = index[0]-1; x <= index[0]+1; ++x ) {
typename TBinaryImage::IndexType nbrIndex = {{ x, y, z }};
if ( !sphereRegion.IsInside( nbrIndex ) ) continue;
// Don't add voxels that are already not part of the background
short visitedStatus = visitedImage->GetPixel( nbrIndex );
if ( visitedStatus == VISITED ||
visitedStatus == SCHEDULED_FOR_VISIT ) continue;
insideSphere = InsideSphere( nbrIndex, binaryImage,
sphereCenter, sphereRadius );
// Add only voxels that are within the sphere radius
if ( insideSphere ) {
visitedImage->SetPixel( nbrIndex, SCHEDULED_FOR_VISIT );
queue.push( nbrIndex );
}
}
}
}
}
}
}
} // end anonymous namespace
#endif
| 33.051887 | 90 | 0.649493 | PediatricAirways |
a86d654f31b46bd834a81acc20772f64da3ee653 | 22,484 | hpp | C++ | src/Enzo/enzo_EnzoRiemannLUT.hpp | buketbenek/enzo-e | 329a398ce4b11b03a1b2f1aef9e46d04560fe894 | [
"BSD-3-Clause"
] | null | null | null | src/Enzo/enzo_EnzoRiemannLUT.hpp | buketbenek/enzo-e | 329a398ce4b11b03a1b2f1aef9e46d04560fe894 | [
"BSD-3-Clause"
] | null | null | null | src/Enzo/enzo_EnzoRiemannLUT.hpp | buketbenek/enzo-e | 329a398ce4b11b03a1b2f1aef9e46d04560fe894 | [
"BSD-3-Clause"
] | null | null | null | // See LICENSE_CELLO file for license and copyright information
/// @file enzo_EnzoRiemannUtils.hpp
/// @author Matthew Abruzzo (matthewabruzzo@gmail.com)
/// @date Thurs May 15 2020
/// @brief [\ref Enzo] Implementation of EnzoRiemannLUTWrapper
#ifndef ENZO_ENZO_RIEMANN_LUT_WRAPPER_HPP
#define ENZO_ENZO_RIEMANN_LUT_WRAPPER_HPP
//----------------------------------------------------------------------
/// @typedef lutarray
/// @brief Specialization of std::array to be used to hold enzo_floats
/// associated with lookup tables (used with Riemann solvers)
template<class LUT>
using lutarray = std::array<enzo_float, LUT::num_entries>;
//----------------------------------------------------------------------
// Yields a combined token
#define COMBINE(prefix, suffix) prefix##suffix
#define COMBINE3(first, second, third) first##second##third
// Yields a stringized version of the combined token
#define STRINGIZE_COMBINE(prefix,suffix) STR_C_1(COMBINE(prefix,suffix))
#define STR_C_1(s) STR_C_2(s)
#define STR_C_2(s) #s
//----------------------------------------------------------------------
/// @def CREATE_ENUM_VALUE_FORWARDER
/// @brief Given an argument, {name}, this macro defines a struct called
/// forward_{name} that retrieves the value of the enum member
/// called {name} from a given struct/class. If the member is not
/// present, indicates a value of minus 1. This implementation is
/// loosely inspired by https://stackoverflow.com/a/16000226
#define CREATE_ENUM_VALUE_FORWARDER(name) \
/* Default case: target template doesn't have a member named {name}. */ \
template <typename T, typename = int> \
struct COMBINE(forward_, name) \
{static constexpr int value = -1; }; \
\
/* Specialized case: */ \
template <typename T> \
struct COMBINE(forward_, name) <T, decltype((void) T::name, 0)> \
{ static constexpr int value = T::name; }
// omit trailing semicolon to avoid -Wpedantic warning
//----------------------------------------------------------------------
/// @def LUT_INDEX_FORWARDER_T_SCALAR
/// @brief Part of the LUT_INDEX_FORWARDER group of macros that define
/// structs for forwarding the values of enum members of a target
/// struct/class named for actively advected quantities from
/// FIELD_TABLE
#define LUT_INDEX_FORWARDER_T_SCALAR(name) CREATE_ENUM_VALUE_FORWARDER(name);
#define LUT_INDEX_FORWARDER_T_VECTOR(name) \
CREATE_ENUM_VALUE_FORWARDER(COMBINE(name, _i)); \
CREATE_ENUM_VALUE_FORWARDER(COMBINE(name, _j)); \
CREATE_ENUM_VALUE_FORWARDER(COMBINE(name, _k));
#define LUT_INDEX_FORWARDER_F_SCALAR(name) /* ... */
#define LUT_INDEX_FORWARDER_F_VECTOR(name) /* ... */
namespace LUTIndexForward_ {
#define ENTRY(name, math_type, category, if_advection) \
LUT_INDEX_FORWARDER_##if_advection ## _ ## math_type (name)
FIELD_TABLE
#undef ENTRY
// forward number of equations
CREATE_ENUM_VALUE_FORWARDER(num_entries);
// forward the first index holding specific quantities
CREATE_ENUM_VALUE_FORWARDER(specific_start);
}
//----------------------------------------------------------------------
/// @def WRAPPED_LUT_INDEX_VALUE_T_SCALAR
/// @brief Part of the WRAPPED_LUT_INDEX_VALUE group of macros that define
/// is used for defining that values of enum members in
/// `EnzoRiemannLUTWrapper` by forwarding the enum member values from
/// a separate LUT for each of the actively advected quantities from
/// FIELD_TABLE
#define WRAPPED_LUT_INDEX_VALUE_T_SCALAR(name, LUT) \
name = LUTIndexForward_::COMBINE(forward_, name)<LUT>::value,
#define WRAPPED_LUT_INDEX_VALUE_T_VECTOR(name, LUT) \
COMBINE(name,_i) = LUTIndexForward_::COMBINE3(forward_,name,_i)<LUT>::value,\
COMBINE(name,_j) = LUTIndexForward_::COMBINE3(forward_,name,_j)<LUT>::value,\
COMBINE(name,_k) = LUTIndexForward_::COMBINE3(forward_,name,_k)<LUT>::value,
#define WRAPPED_LUT_INDEX_VALUE_F_SCALAR(name, LUT) /* ... */
#define WRAPPED_LUT_INDEX_VALUE_F_VECTOR(name, LUT) /* ... */
//----------------------------------------------------------------------
template <typename InputLUT>
struct EnzoRiemannLUT{
/// @class EnzoRiemannLUT
/// @ingroup Enzo
/// @brief [\ref Enzo] Provides a compile-time lookup table that maps the
/// components of a subset of the actively advected integration
/// quantities from FIELD_TABLE to unique indices
///
/// This is a template class that provides the following features at compile
/// time:
/// - a lookup table (LUT) that maps the names of components of a subset
/// of the actively advected integration quantities defined in
/// FIELD_TABLE to unique, contiguous indices.
/// - the number of quantity components included in the table
/// - a way to iterate over just the conserved or specific integration
/// quantities values that are stored in an array using these mapping
/// - a way to query which of the actively advected integration quantities
/// in FIELD_TABLE are not included in the LUT
///
/// These feature are provided via the definition of publicly accessible
/// integer constants in every specialization of the template class. All
/// specializations have:
/// - a constant called `num_entries` equal to the number of integration
/// quantity components included in the lookup table
/// - a constant called `specific_start` equal to the number of components
/// of conserved integration quantities included in the lookup table
/// - `qkey` constants, which include constants named for the components
/// of ALL actively advected integration quantities in FIELD_TABLE. A
/// constant associated with a SCALAR quantity, `{qname}`, is simply
/// called `{qname}` while constants associated with a vector quantity,
/// `{qname}`, are called `{qname}_i`, `{qname}_j`, and `{qname}_k`.
///
/// The `qkey` constants serve as both the keys of the lookup table and a
/// way to check whether a component of an actively advected quantity is
/// included in the table. Their values satisfy the following conditions:
/// - All constants named for values corresponding to quantities NOT
/// included in the lookup table have values of `-1`
/// - All constants named for conserved integration quantities have unique
/// integer values in the internal `[0,specific_start)`
/// - All constants named for specific integration quantities have unique
/// integer values in the interval `[specific_start, num_entries)`
///
/// The lookup table is always expected to include density and the 3 velocity
/// components. Although it may not be strictly enforced (yet), the lookup
/// table is also expected to include either all 3 components of a vector
/// quantity or None of them. Additionally, the kth component of a vector
/// quantity is expected to have a value that is 1 larger than that of the
/// jth component and 2 larger than the ith component,
///
/// This template class also provides a handful of helpful static methods to
/// programmatically probe the table's contents at runtime and validate that
/// the above requirements are specified.
///
/// @tparam InputLUT Type that defines the `num_entries` constant, the
/// `specific_start` constant, and the `qkey` constants that correspond
/// to the actively advected integration quantities that are actually
/// included in the lookup table. All of the constant values will be
/// directly reused by the resulting template specialization and
/// therefore must meet the criteria defined above. Any undefined `qkey`
/// constants are assumed to not be included in the lookup table and will
/// be defined within the template specialization to have values of `-1`.
/// This type can be implemented with either an unscoped enum OR a class
/// that includes some combination of publicly accessible unscoped enums
/// and static constant member variables.
///
/// @par Examples
/// For the sake of the example, let's assume we have a type `MyInputLUT`
/// that's defined as:
/// @code
/// struct MyIntLUT {
/// enum vals { density=0, velocity_i, velocity_j, velocity_k,
/// total_energy, num_entries, specific_start = 1};
/// };
/// @endcode
/// To access the index associated with density or the jth component of
/// velocity, one would evaluate:
/// @code
/// int density_index = EnzoRiemannLUT<MyInLUT>::density; //=0
/// int vj_index = EnzoRiemannLUT<MyInLUT>::velocity_j; //=2
/// @endcode
///
/// @par
/// It makes more sense to talk about the use of this template class when we
/// have a companion array. For convenience, the alias template
/// `lutarray<LUT>` type is defined. The type,
/// `lutarray<EnzoRiemannLUT<InputLUT>>` is an alias of the type
/// `std::array<enzo_float, EnzoRiemannLUT<InputLUT>::num_entries>;`.
///
/// @par
/// As an example, imagine that the total kinetic energy density needs to be
/// computed at a single location from the values stored in an array, `integ`,
/// of type `lutarray<EnzoRiemannLUT<MyIntLUT>>`. The resulting code to
/// do that might look something like:
/// @code
/// using LUT = EnzoRiemannLUT<MyIntLUT>;
/// enzo_float v2 = (integ[LUT::velocity_i] * integ[LUT::velocity_i] +
/// integ[LUT::velocity_j] * integ[LUT::velocity_j] +
/// integ[LUT::velocity_k] * integ[LUT::velocity_k]);
/// enzo_float kinetic = 0.5 * integ[LUT::density] * v2;
/// @endcode
///
/// @par
/// This template class makes it very easy to write generic code that can be
/// reused for multiple different lookup table by making the lookup table
/// itself into a template argument. Consider the case where a single
/// template function is desired to compute the total non-thermal energy
/// density at a single location for an arbitrary lookup table. To do this,
/// one might write the following code:
/// @code
/// template <class LUT>
/// enzo_float calc_nonthermal_edens(lutarray<LUT> prim)
/// {
/// enzo_float v2 = (prim[LUT::velocity_i] * prim[LUT::velocity_i] +
/// prim[LUT::velocity_j] * prim[LUT::velocity_j] +
/// prim[LUT::velocity_k] * prim[LUT::velocity_k]);
///
/// enzo_float bi = (LUT::bfield_i >= 0) ? prim[LUT::bfield_i] : 0;
/// enzo_float bj = (LUT::bfield_j >= 0) ? prim[LUT::bfield_j] : 0;
/// enzo_float bk = (LUT::bfield_k >= 0) ? prim[LUT::bfield_k] : 0;
/// enzo_float b2 = bi*bi + bj*bj + bk*bk;
///
/// return 0.5(v2*prim[LUT::density] + b2);
/// }
/// @endcode
///
/// @par
/// This final example will show the value of grouping the conserved and
/// specific integration quantities. To implement some Riemann solvers, it is
/// useful to have a generic, reusable function that constructs an array of
/// all quantities that are in the lookup table in their conserved form. The
/// following function was used to accomplish this at one point
/// @code
/// template <class LUT>
/// lutarray<LUT> compute_conserved(const lutarray<LUT> integr) noexcept
/// {
/// lutarray<LUT> cons;
/// for (std::size_t i = 0; i < LUT::specific_start; i++) {
/// cons[i] = integr[i];
/// }
/// for (std::size_t i=LUT::specific_start; i<LUT::num_entries; i++){
/// cons[i] = integr[i] * integr[LUT::density];
/// }
/// return cons;
/// }
/// @endcode
public:
/// initialize the lookup table entries for ever actively advected scalar
/// quantity and component of a vector quantity in FIELD_TABLE by forwarding
/// values from InputLUT (entries not included in InputLUT default to -1)
enum qkey {
#define ENTRY(name, math_type, category, if_advection) \
WRAPPED_LUT_INDEX_VALUE_##if_advection##_##math_type (name, InputLUT)
FIELD_TABLE
#undef ENTRY
};
/// The entry with the minimum (non-negative) index corresponding to a
/// specific integration quantity. All conserved integration quantity entries
/// must have smaller indices (defaults to -1 if not explicitly specified in
/// InputLUT)
static constexpr std::size_t specific_start =
LUTIndexForward_::forward_specific_start<InputLUT>::value;
/// The total number of entries in the InputLUT (with non-negative indices).
/// (defaults to -1 if not explicitly set in InputLUT)
static constexpr std::size_t num_entries =
LUTIndexForward_::forward_num_entries<InputLUT>::value;
// perform some sanity checks:
static_assert(qkey::density >= 0,
"InputLUT must have an entry corresponding to density");
static_assert((qkey::velocity_i >= 0 &&
qkey::velocity_j >= 0 &&
qkey::velocity_k >= 0),
"InputLUT must have entries for each velocity component.");
static_assert(specific_start > 0,
"InputLUT::specific_start was not set to a positive value");
static_assert(specific_start < num_entries,
"InputLUT::num_entries was not set to a value exceeding "
"InputLUT::specific_start");
private:
/// This is not meant to be constructed.
///
/// if it becomes necessary in the future to construct it in the future,
/// there is no harm in doing so
EnzoRiemannLUT() {}
public: //associated static functions
/// returns whether the LUT has any bfields
static constexpr bool has_bfields(){
return (qkey::bfield_i>=0) || (qkey::bfield_j>=0) || (qkey::bfield_k>=0);
}
/// for each actively advected scalar integration quantity and component of
/// an actively advected vector integration quantity in FIELD_TABLE, this
/// passes the associated name and index from the wrapped InputLUT to the
/// function `fn`
///
/// The function should expect (std::string name, int index). In cases where
/// quantites in FIELD_TABLE do not appear in the wrapped InputLUT, an index
/// of -1 is passed.
template<class Function>
static void for_each_entry(Function fn) noexcept;
/// a function that performs a check to make sure that the InputLUT satisfies
/// all assumptions. If it doesn't, the program aborts (with an Error message)
static void validate() noexcept;
};
//----------------------------------------------------------------------
/// @def LUT_UNARY_FUNC_T_SCALAR
/// @brief Part of the LUT_UNARY_FUNC group of macros that apply a
/// unary function to the entries of named for advection related
/// quantities in FIELD_TABLE
#define LUT_UNARY_FUNC_T_SCALAR(func, LUT, name) func(#name, LUT::name)
#define LUT_UNARY_FUNC_T_VECTOR(func, LUT, name) \
func(STRINGIZE_COMBINE(name,_i), LUT::COMBINE(name,_i)); \
func(STRINGIZE_COMBINE(name,_j), LUT::COMBINE(name,_j)); \
func(STRINGIZE_COMBINE(name,_k), LUT::COMBINE(name,_k))
#define LUT_UNARY_FUNC_F_SCALAR(func, LUT, name) /* ... */
#define LUT_UNARY_FUNC_F_VECTOR(func, LUT, name) /* ... */
//----------------------------------------------------------------------
/// template helper function that applies unary function on the enum members of
/// a lookup table that have been named for advection related quantities in
/// FIELD_TABLE
/// @param fn Unary function or that accepts the name of the member and the
/// value of the member as arguments
template<class LUT>
template<class Function>
void EnzoRiemannLUT<LUT>::for_each_entry(Function fn) noexcept{
#define ENTRY(name, math_type, category, if_advection) \
LUT_UNARY_FUNC_##if_advection##_##math_type (fn, \
EnzoRiemannLUT<LUT>, \
name);
FIELD_TABLE
#undef ENTRY
}
//----------------------------------------------------------------------
template <class InputLUT>
void EnzoRiemannLUT<InputLUT>::validate()
noexcept
{
// the elements in the array are default-initialized (they are each "")
std::array<std::string, EnzoRiemannLUT<InputLUT>::num_entries> entry_names;
// define a lambda function to execute for every member of lut
auto fn = [&](std::string name, int index)
{
if ((index >= 0) && (index >= EnzoRiemannLUT<InputLUT>::num_entries)) {
ERROR3("EnzoRiemannLUT<InputLUT>::validate",
("The value of %s, %d, is greater than or equal to "
"InputLUT::num_entries, %d"),
name.c_str(), index, EnzoRiemannLUT<InputLUT>::num_entries);
} else if (index >= 0) {
if (entry_names[index] != ""){
ERROR3("EnzoRiemannLUT<InputLUT>::validate",
"%s and %s both have values of %d",
name.c_str(), entry_names[index], index);
}
entry_names[index] = name;
}
};
EnzoRiemannLUT<InputLUT>::for_each_entry(fn);
std::size_t max_conserved = 0;
std::size_t min_specific = EnzoRiemannLUT<InputLUT>::num_entries;
for (std::size_t i = 0; i < entry_names.size(); i++){
std::string name = entry_names[i];
if (name == ""){
ERROR2("EnzoRiemannLUT<InputLUT>::validate",
"The value of num_entries, %d, is wrong. There is no entry for "
"index %d",
(int)EnzoRiemannLUT<InputLUT>::num_entries, (int)i);
}
std::string quantity =
EnzoCenteredFieldRegistry::get_actively_advected_quantity_name(name,
true);
if (quantity == ""){
ERROR2("EnzoRiemannLUT<InputLUT>::validate",
"\"%s\" (at index %d) isn't an actively advected scalar quantity"
"or a component of an actively advected vector quantity",
name.c_str(), (int)i);
}
FieldCat category;
EnzoCenteredFieldRegistry::quantity_properties(quantity, NULL, &category,
NULL);
if ((i == 0) && (category != FieldCat::conserved)) {
ERROR("EnzoRiemannLUT<InputLUT>::validate",
("the lookup table's entry for index 0 should correspond to a "
"conserved quantity"));
} else if (((i+1) == entry_names.size()) &&
(category != FieldCat::specific)) {
ERROR("EnzoRiemannLUT<InputLUT>::validate",
("the lookup table's entry for the index InputLUT::num_entries-1 "
"should correspond to a specific quantity"));
}
switch(category){
case FieldCat::conserved : { max_conserved = std::max(max_conserved, i);
break;
}
case FieldCat::specific : { min_specific = std::min(min_specific, i);
break;
}
case FieldCat::other : {
ERROR1("EnzoRiemannLUT<InputLUT>::validate",
("%s corresponds to a quantity with FieldCat::other. Quantities "
"of this category should not be included in a lookup table."),
name.c_str());
}
}
}
// The assumption is that all LUTs contain at least 1 conserved quantity
// (nominally density) and at least 1 specific quantity (nominally velocity)
if ((max_conserved+1) != min_specific){
ERROR("EnzoRiemannLUT<InputLUT>::validate",
("InputLUT's entries corresponding to conserved quantities are not "
"all grouped together at indices smaller than those corresponding "
"to specific quantities"));
} else if (min_specific != EnzoRiemannLUT<InputLUT>::specific_start) {
ERROR2("EnzoRiemannLUT<InputLUT>::validate",
"InputLUT's specfic_start value should be set to %d, not %d.",
(int)min_specific, (int)EnzoRiemannLUT<InputLUT>::specific_start);
}
// (It would be faster to include this within the above loop, but this is]
// more readable)
// verify for actively advected vector quantity, qname, that has components
// associated with non-negative values that:
// - if InputLUT::{qname}_j >= 0, then it's equal to 1 + InputLUT::{qname}_i
// and greater than 0
// - if InputLUT::{qname}_k >= 0, then it's equal to 1 + InputLUT::{qname}_j
// and greater than 1
char prev_entry_vector_ax = '\0';
std::string prev_quantity = "";
for (const auto& name : entry_names){
char component;
const std::string cur_quantity =
EnzoCenteredFieldRegistry::get_actively_advected_quantity_name
(name, true, &component);
if (component == '\0'){ // name isn't a component of a vector
prev_entry_vector_ax = '\0';
prev_quantity = ""; // we intentionally use an empty string
} else {
if ( (component == 'j') && ((cur_quantity != prev_quantity) ||
(prev_entry_vector_ax != 'i')) ){
ERROR2("EnzoRiemannLUT<InputLUT>::validate",
"\"%s_j\" is expected to have an index that is 1 greater than "
"the index of \"%s_i\".",
cur_quantity.c_str(), cur_quantity.c_str());
} else if ( (component == 'k') && ((cur_quantity != prev_quantity) ||
(prev_entry_vector_ax != 'j')) ){
ERROR2("EnzoRiemannLUT<InputLUT>::validate",
"\"%s_k\" is expected to have an index that is 1 greater than "
"the index of \"%s_j\".",
cur_quantity.c_str(), cur_quantity.c_str());
}
prev_entry_vector_ax = component;
prev_quantity = cur_quantity;
}
}
}
#endif /* ENZO_ENZO_RIEMANN_LUT_WRAPPER_HPP */
| 46.939457 | 80 | 0.618262 | buketbenek |
a86e86e5c4401366713810ee099c099e47b96948 | 3,007 | cpp | C++ | examples/stackedfm.cpp | vlazzarini/aurora | 4990d81a6873beace4a39d6584cc77afbda82cf4 | [
"BSD-3-Clause"
] | 11 | 2021-11-26T16:23:40.000Z | 2022-01-19T21:36:35.000Z | examples/stackedfm.cpp | vlazzarini/aurora | 4990d81a6873beace4a39d6584cc77afbda82cf4 | [
"BSD-3-Clause"
] | null | null | null | examples/stackedfm.cpp | vlazzarini/aurora | 4990d81a6873beace4a39d6584cc77afbda82cf4 | [
"BSD-3-Clause"
] | null | null | null | // stackedfm.cpp:
// Stacked FM example
//
// (c) V Lazzarini, 2021
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE
#include "Osc.h"
#include <cstdlib>
#include <iostream>
namespace Aurora {
inline double scl(double a, double b) { return a * b; }
inline double mix(double a, double b) { return a + b; }
template <typename S> class StackedFM {
Osc<S> mod0;
Osc<S> mod1;
Osc<S> car;
BinOp<S, scl> amp;
BinOp<S, mix> add;
public:
StackedFM(S fs = (S)def_sr, std::size_t vsize = def_vsize)
: mod0(fs, vsize), mod1(fs, vsize), car(fs, vsize), amp(vsize),
add(vsize){};
std::size_t vsize() { return car.vsize(); }
S fs() { return car.fs(); }
const std::vector<S> &operator()(S a, S fc, S fm0, S fm1, S z0, S z1,
std::size_t vsiz = 0) {
if (vsiz)
mod0.vsize(vsiz);
auto &s0 = add(fm1, mod0(z0 * fm0, fm0));
auto &s1 = add(fc, mod1(amp(z1, s0), s0));
return car(a, s1);
}
};
} // namespace Aurora
int main(int argc, const char *argv[]) {
if (argc > 3) {
double sr = argc > 4 ? std::atof(argv[4]) : Aurora::def_sr;
auto dur = std::atof(argv[1]);
auto amp = std::atof(argv[2]);
auto fr = std::atof(argv[3]);
Aurora::StackedFM<double> fm(sr);
for (int n = 0; n < fm.fs() * dur; n += fm.vsize()) {
const std::vector<double> &out = fm(amp, fr, fr, fr, 3, 2);
for (auto s : out)
std::cout << s << std::endl;
}
} else
std::cout << "usage: " << argv[0] << " dur(s) amp freq(Hz) [sr]"
<< std::endl;
return 0;
}
| 37.123457 | 80 | 0.663785 | vlazzarini |
a870b58f24e926981982fe06011b886bee7bf558 | 9,897 | cpp | C++ | mps/src/v20190612/model/MediaVideoStreamItem.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | mps/src/v20190612/model/MediaVideoStreamItem.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | mps/src/v20190612/model/MediaVideoStreamItem.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/mps/v20190612/model/MediaVideoStreamItem.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Mps::V20190612::Model;
using namespace std;
MediaVideoStreamItem::MediaVideoStreamItem() :
m_bitrateHasBeenSet(false),
m_heightHasBeenSet(false),
m_widthHasBeenSet(false),
m_codecHasBeenSet(false),
m_fpsHasBeenSet(false),
m_colorPrimariesHasBeenSet(false),
m_colorSpaceHasBeenSet(false),
m_colorTransferHasBeenSet(false),
m_hdrTypeHasBeenSet(false)
{
}
CoreInternalOutcome MediaVideoStreamItem::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Bitrate") && !value["Bitrate"].IsNull())
{
if (!value["Bitrate"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Bitrate` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_bitrate = value["Bitrate"].GetInt64();
m_bitrateHasBeenSet = true;
}
if (value.HasMember("Height") && !value["Height"].IsNull())
{
if (!value["Height"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Height` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_height = value["Height"].GetInt64();
m_heightHasBeenSet = true;
}
if (value.HasMember("Width") && !value["Width"].IsNull())
{
if (!value["Width"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Width` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_width = value["Width"].GetInt64();
m_widthHasBeenSet = true;
}
if (value.HasMember("Codec") && !value["Codec"].IsNull())
{
if (!value["Codec"].IsString())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Codec` IsString=false incorrectly").SetRequestId(requestId));
}
m_codec = string(value["Codec"].GetString());
m_codecHasBeenSet = true;
}
if (value.HasMember("Fps") && !value["Fps"].IsNull())
{
if (!value["Fps"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.Fps` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_fps = value["Fps"].GetInt64();
m_fpsHasBeenSet = true;
}
if (value.HasMember("ColorPrimaries") && !value["ColorPrimaries"].IsNull())
{
if (!value["ColorPrimaries"].IsString())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.ColorPrimaries` IsString=false incorrectly").SetRequestId(requestId));
}
m_colorPrimaries = string(value["ColorPrimaries"].GetString());
m_colorPrimariesHasBeenSet = true;
}
if (value.HasMember("ColorSpace") && !value["ColorSpace"].IsNull())
{
if (!value["ColorSpace"].IsString())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.ColorSpace` IsString=false incorrectly").SetRequestId(requestId));
}
m_colorSpace = string(value["ColorSpace"].GetString());
m_colorSpaceHasBeenSet = true;
}
if (value.HasMember("ColorTransfer") && !value["ColorTransfer"].IsNull())
{
if (!value["ColorTransfer"].IsString())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.ColorTransfer` IsString=false incorrectly").SetRequestId(requestId));
}
m_colorTransfer = string(value["ColorTransfer"].GetString());
m_colorTransferHasBeenSet = true;
}
if (value.HasMember("HdrType") && !value["HdrType"].IsNull())
{
if (!value["HdrType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `MediaVideoStreamItem.HdrType` IsString=false incorrectly").SetRequestId(requestId));
}
m_hdrType = string(value["HdrType"].GetString());
m_hdrTypeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void MediaVideoStreamItem::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_bitrateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Bitrate";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_bitrate, allocator);
}
if (m_heightHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Height";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_height, allocator);
}
if (m_widthHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Width";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_width, allocator);
}
if (m_codecHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Codec";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_codec.c_str(), allocator).Move(), allocator);
}
if (m_fpsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Fps";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_fps, allocator);
}
if (m_colorPrimariesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ColorPrimaries";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_colorPrimaries.c_str(), allocator).Move(), allocator);
}
if (m_colorSpaceHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ColorSpace";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_colorSpace.c_str(), allocator).Move(), allocator);
}
if (m_colorTransferHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ColorTransfer";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_colorTransfer.c_str(), allocator).Move(), allocator);
}
if (m_hdrTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HdrType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_hdrType.c_str(), allocator).Move(), allocator);
}
}
int64_t MediaVideoStreamItem::GetBitrate() const
{
return m_bitrate;
}
void MediaVideoStreamItem::SetBitrate(const int64_t& _bitrate)
{
m_bitrate = _bitrate;
m_bitrateHasBeenSet = true;
}
bool MediaVideoStreamItem::BitrateHasBeenSet() const
{
return m_bitrateHasBeenSet;
}
int64_t MediaVideoStreamItem::GetHeight() const
{
return m_height;
}
void MediaVideoStreamItem::SetHeight(const int64_t& _height)
{
m_height = _height;
m_heightHasBeenSet = true;
}
bool MediaVideoStreamItem::HeightHasBeenSet() const
{
return m_heightHasBeenSet;
}
int64_t MediaVideoStreamItem::GetWidth() const
{
return m_width;
}
void MediaVideoStreamItem::SetWidth(const int64_t& _width)
{
m_width = _width;
m_widthHasBeenSet = true;
}
bool MediaVideoStreamItem::WidthHasBeenSet() const
{
return m_widthHasBeenSet;
}
string MediaVideoStreamItem::GetCodec() const
{
return m_codec;
}
void MediaVideoStreamItem::SetCodec(const string& _codec)
{
m_codec = _codec;
m_codecHasBeenSet = true;
}
bool MediaVideoStreamItem::CodecHasBeenSet() const
{
return m_codecHasBeenSet;
}
int64_t MediaVideoStreamItem::GetFps() const
{
return m_fps;
}
void MediaVideoStreamItem::SetFps(const int64_t& _fps)
{
m_fps = _fps;
m_fpsHasBeenSet = true;
}
bool MediaVideoStreamItem::FpsHasBeenSet() const
{
return m_fpsHasBeenSet;
}
string MediaVideoStreamItem::GetColorPrimaries() const
{
return m_colorPrimaries;
}
void MediaVideoStreamItem::SetColorPrimaries(const string& _colorPrimaries)
{
m_colorPrimaries = _colorPrimaries;
m_colorPrimariesHasBeenSet = true;
}
bool MediaVideoStreamItem::ColorPrimariesHasBeenSet() const
{
return m_colorPrimariesHasBeenSet;
}
string MediaVideoStreamItem::GetColorSpace() const
{
return m_colorSpace;
}
void MediaVideoStreamItem::SetColorSpace(const string& _colorSpace)
{
m_colorSpace = _colorSpace;
m_colorSpaceHasBeenSet = true;
}
bool MediaVideoStreamItem::ColorSpaceHasBeenSet() const
{
return m_colorSpaceHasBeenSet;
}
string MediaVideoStreamItem::GetColorTransfer() const
{
return m_colorTransfer;
}
void MediaVideoStreamItem::SetColorTransfer(const string& _colorTransfer)
{
m_colorTransfer = _colorTransfer;
m_colorTransferHasBeenSet = true;
}
bool MediaVideoStreamItem::ColorTransferHasBeenSet() const
{
return m_colorTransferHasBeenSet;
}
string MediaVideoStreamItem::GetHdrType() const
{
return m_hdrType;
}
void MediaVideoStreamItem::SetHdrType(const string& _hdrType)
{
m_hdrType = _hdrType;
m_hdrTypeHasBeenSet = true;
}
bool MediaVideoStreamItem::HdrTypeHasBeenSet() const
{
return m_hdrTypeHasBeenSet;
}
| 27.722689 | 153 | 0.682025 | suluner |
a8764ec99f69dcf8e96cdfb694ae72a5c9e31b59 | 1,107 | cpp | C++ | Source/Services/TitleStorage/title_storage_blob_result.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | 2 | 2021-07-17T13:34:20.000Z | 2022-01-09T00:55:51.000Z | Source/Services/TitleStorage/title_storage_blob_result.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | null | null | null | Source/Services/TitleStorage/title_storage_blob_result.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | 1 | 2018-11-18T08:32:40.000Z | 2018-11-18T08:32:40.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "xsapi/title_storage.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_TITLE_STORAGE_CPP_BEGIN
title_storage_blob_result::title_storage_blob_result()
{
}
title_storage_blob_result::title_storage_blob_result(
_In_ std::shared_ptr<std::vector<unsigned char>> blobBuffer,
_In_ title_storage_blob_metadata blobMetadata
) :
m_blobBuffer(blobBuffer),
m_blobMetadata(std::move(blobMetadata))
{
}
std::shared_ptr<std::vector<unsigned char>> const
title_storage_blob_result::blob_buffer() const
{
return m_blobBuffer;
}
const title_storage_blob_metadata&
title_storage_blob_result::blob_metadata() const
{
return m_blobMetadata;
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_TITLE_STORAGE_CPP_END | 27.675 | 64 | 0.707317 | blgrossMS |
a8765ae4d540befbf7c1096cfb148836f0d8972e | 2,430 | cpp | C++ | src/generate_dijkstra_rank_test_queries.cpp | TheMarex/RoutingKit | 92ad3dd90a82b687a8a9a7468054f2449ff7c67f | [
"BSD-2-Clause"
] | 1 | 2021-04-13T05:54:28.000Z | 2021-04-13T05:54:28.000Z | src/generate_dijkstra_rank_test_queries.cpp | TheMarex/RoutingKit | 92ad3dd90a82b687a8a9a7468054f2449ff7c67f | [
"BSD-2-Clause"
] | null | null | null | src/generate_dijkstra_rank_test_queries.cpp | TheMarex/RoutingKit | 92ad3dd90a82b687a8a9a7468054f2449ff7c67f | [
"BSD-2-Clause"
] | null | null | null | #include <routingkit/vector_io.h>
#include "dijkstra.h"
#include "verify.h"
#include <iostream>
#include <stdexcept>
#include <vector>
#include <random>
using namespace RoutingKit;
using namespace std;
int main(int argc, char*argv[]){
try{
unsigned source_node_count;
unsigned random_seed;
string source_file;
string target_file;
string rank_file;
string distance_file;
vector<unsigned>first_out;
vector<unsigned>head;
vector<unsigned>weight;
if(argc != 10){
cerr << argv[0] << " first_out head weight source_node_count random_seed source_file target_file rank_file distance_file" << endl;
cerr << "source_node_count can be a number or a uint32 vector of which the size is taken." << endl;
return 1;
}else{
first_out = load_vector<unsigned>(argv[1]);
head = load_vector<unsigned>(argv[2]);
weight = load_vector<unsigned>(argv[3]);
try{
source_node_count = stoul(argv[4]);
}catch(...){
source_node_count = load_vector<unsigned>(argv[4]).size();
}
random_seed = stoul(argv[5]);
source_file = argv[6];
target_file = argv[7];
rank_file = argv[8];
distance_file = argv[9];
}
cout << "Validity tests ... " << flush;
check_if_graph_is_valid(first_out, head);
cout << "done" << endl;
unsigned node_count = first_out.size()-1;
vector<unsigned>source;
vector<unsigned>target;
vector<unsigned>rank;
vector<unsigned>distance;
cout << "Generating test queries ... " << flush;
std::default_random_engine gen(random_seed);
std::uniform_int_distribution<int> dist(0, node_count-1);
auto dij = make_dijkstra(first_out, head, weight);
for(unsigned i=0; i<source_node_count; ++i){
unsigned source_node = dist(gen);
unsigned r = 0;
unsigned n = 0;
dij.clear();
dij.add_source_node(source_node);
while(!dij.is_finished()){
auto x = dij.settle();
++n;
if(n == (1u << r)){
if(r > 5){
source.push_back(source_node);
target.push_back(x.id);
rank.push_back(r);
distance.push_back(x.key);
}
++r;
}
}
}
cout << "done" << endl;
cout << "Saving test queries ... " << flush;
save_vector(source_file, source);
save_vector(target_file, target);
save_vector(rank_file, rank);
save_vector(distance_file, distance);
cout << "done" << endl;
}catch(exception&err){
cerr << "Stopped on exception : " << err.what() << endl;
}
}
| 22.293578 | 133 | 0.654733 | TheMarex |
a876a08fce293a9494a6d59244c2965672fe3bcf | 761 | hpp | C++ | robo_trace/include/robo_trace/modes/replay/util.hpp | tu-darmstadt-ros-pkg/robo_trace | 60ce64d60110597a0c077aa31199481c20d164b2 | [
"BSD-3-Clause"
] | null | null | null | robo_trace/include/robo_trace/modes/replay/util.hpp | tu-darmstadt-ros-pkg/robo_trace | 60ce64d60110597a0c077aa31199481c20d164b2 | [
"BSD-3-Clause"
] | null | null | null | robo_trace/include/robo_trace/modes/replay/util.hpp | tu-darmstadt-ros-pkg/robo_trace | 60ce64d60110597a0c077aa31199481c20d164b2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2022 Fachgebiet Simulation, Systemoptimierung und Robotik, TU Darmstadt.
*
* This file is part of RoboTrace
* (see https://github.com/tu-darmstadt-ros-pkg/robo_trace)
* and is governed by a BSD-style license
* that can be found in the LICENSE file.
*/
#pragma once
// Std
#include <memory>
#include <optional>
// MongoDB
#include "robo_trace/config.h"
#include <mongo/client/dbclient.h>
#include <mongo/client/dbclientinterface.h>
// Project
#include "robo_trace/storage/options.hpp"
namespace robo_trace:: {
class ReplayUtil {
public:
/**
*
*/
static std::optional<double> getRecordStartTime(const ConnectionOptions::Ptr connection_options, const std::shared_ptr<mongo::DBClientConnection> connection);
};
} | 22.382353 | 162 | 0.726675 | tu-darmstadt-ros-pkg |
a87bf448fc7f780e890e98f209331501ff975ee4 | 1,776 | hpp | C++ | armadillo/include/armadillo_bits/fn_diagmat.hpp | cornell-cup/cs-r2kart-demo | c7224515bf6d4a1bd6b57d1f7186e999564eabc3 | [
"MIT"
] | 13 | 2016-01-05T13:45:19.000Z | 2020-10-22T05:32:19.000Z | armadillo/include/armadillo_bits/fn_diagmat.hpp | cornell-cup/cs-r2kart-demo | c7224515bf6d4a1bd6b57d1f7186e999564eabc3 | [
"MIT"
] | 1 | 2020-06-26T07:08:25.000Z | 2020-06-26T07:08:25.000Z | armadillo/include/armadillo_bits/fn_diagmat.hpp | cornell-cup/cs-r2kart-demo | c7224515bf6d4a1bd6b57d1f7186e999564eabc3 | [
"MIT"
] | 5 | 2016-01-09T10:05:17.000Z | 2019-03-30T10:58:35.000Z | // Copyright (C) 2008-2015 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au
//! \addtogroup fn_diagmat
//! @{
//! interpret a matrix or a vector as a diagonal matrix (i.e. off-diagonal entries are zero)
template<typename T1>
arma_inline
typename
enable_if2
<
is_arma_type<T1>::value,
const Op<T1, op_diagmat>
>::result
diagmat(const T1& X)
{
arma_extra_debug_sigprint();
return Op<T1, op_diagmat>(X);
}
//! create a matrix with the k-th diagonal set to the given vector
template<typename T1>
arma_inline
typename
enable_if2
<
is_arma_type<T1>::value,
const Op<T1, op_diagmat2>
>::result
diagmat(const T1& X, const sword k)
{
arma_extra_debug_sigprint();
const uword row_offset = (k < 0) ? uword(-k) : uword(0);
const uword col_offset = (k > 0) ? uword( k) : uword(0);
return Op<T1, op_diagmat2>(X, row_offset, col_offset);
}
template<typename T1>
inline
const SpOp<T1, spop_diagmat>
diagmat(const SpBase<typename T1::elem_type,T1>& X)
{
arma_extra_debug_sigprint();
return SpOp<T1, spop_diagmat>(X.get_ref());
}
template<typename T1>
inline
const SpOp<T1, spop_diagmat2>
diagmat(const SpBase<typename T1::elem_type,T1>& X, const sword k)
{
arma_extra_debug_sigprint();
const uword row_offset = (k < 0) ? uword(-k) : uword(0);
const uword col_offset = (k > 0) ? uword( k) : uword(0);
return SpOp<T1, spop_diagmat2>(X.get_ref(), row_offset, col_offset);
}
//! @}
| 21.658537 | 92 | 0.657658 | cornell-cup |
a87c3784001508ab174db2c836a7b2647d2e98b0 | 1,212 | ipp | C++ | ThirdParty/oglplus-develop/implement/oglplus/enums/ext/compat_client_attrib_group_range.ipp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | 24 | 2015-01-31T15:30:49.000Z | 2022-01-29T08:36:42.000Z | ThirdParty/oglplus-develop/implement/oglplus/enums/ext/compat_client_attrib_group_range.ipp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | 4 | 2015-08-21T02:29:15.000Z | 2020-05-02T13:50:36.000Z | ThirdParty/oglplus-develop/implement/oglplus/enums/ext/compat_client_attrib_group_range.ipp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | 9 | 2015-06-08T22:04:15.000Z | 2021-08-16T03:52:11.000Z | /*
* .file oglplus/enums/ext/compat_client_attrib_group_range.ipp
*
* Automatically generated header file. DO NOT modify manually,
* edit 'source/enums/oglplus/ext/compat_client_attrib_group.txt' instead.
*
* Copyright 2010-2013 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
namespace enums {
OGLPLUS_LIB_FUNC aux::CastIterRange<
const GLbitfield*,
CompatibilityClientAttributeGroup
> ValueRange_(CompatibilityClientAttributeGroup*)
#if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \
!defined(OGLPLUS_IMPL_EVR_COMPATIBILITYCLIENTATTRIBUTEGROUP)
#define OGLPLUS_IMPL_EVR_COMPATIBILITYCLIENTATTRIBUTEGROUP
{
static const GLbitfield _values[] = {
#if defined GL_CLIENT_VERTEX_ARRAY_BIT
GL_CLIENT_VERTEX_ARRAY_BIT,
#endif
#if defined GL_CLIENT_PIXEL_STORE_BIT
GL_CLIENT_PIXEL_STORE_BIT,
#endif
#if defined GL_CLIENT_ALL_ATTRIB_BITS
GL_CLIENT_ALL_ATTRIB_BITS,
#endif
0
};
return aux::CastIterRange<
const GLbitfield*,
CompatibilityClientAttributeGroup
>(_values, _values+sizeof(_values)/sizeof(_values[0])-1);
}
#else
;
#endif
} // namespace enums
| 28.186047 | 75 | 0.808581 | vif |
a87fa565177c7141a8787087d6bb689f8880cd6f | 2,415 | cpp | C++ | wznmcmbd/WznmCtpWrsrv/WznmCtpWrsrv_blks.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | wznmcmbd/WznmCtpWrsrv/WznmCtpWrsrv_blks.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | wznmcmbd/WznmCtpWrsrv/WznmCtpWrsrv_blks.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file WznmCtpWrsrv_blks.cpp
* invocation / return data blocks for operation pack WznmCtpWrsrv (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
#include "WznmCtpWrsrv_blks.h"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class DpchInvWznmCtpWrsrv
******************************************************************************/
DpchInvWznmCtpWrsrv::DpchInvWznmCtpWrsrv(
const ubigint oref
, const string& srefKCustop
, const ubigint jref
, const ubigint refWznmMCapability
, const string& Prjshort
, const string& folder
) :
DpchInvWznm(VecWznmVDpch::DPCHINVWZNMCTPWRSRV, oref, jref)
{
this->srefKCustop = srefKCustop;
this->refWznmMCapability = refWznmMCapability;
this->Prjshort = Prjshort;
this->folder = folder;
};
void DpchInvWznmCtpWrsrv::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchInvWznmCtpWrsrv");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrOref", "", scrOref)) add(SCROREF);
if (extractStringUclc(docctx, basexpath, "srefKCustop", "", srefKCustop)) add(SREFKCUSTOP);
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF);
if (extractUbigintUclc(docctx, basexpath, "refWznmMCapability", "", refWznmMCapability)) add(REFWZNMMCAPABILITY);
if (extractStringUclc(docctx, basexpath, "Prjshort", "", Prjshort)) add(PRJSHORT);
if (extractStringUclc(docctx, basexpath, "folder", "", folder)) add(FOLDER);
};
};
void DpchInvWznmCtpWrsrv::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchInvWznmCtpWrsrv");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
writeString(wr, "scrOref", Scr::scramble(oref));
writeString(wr, "srefKCustop", srefKCustop);
writeString(wr, "scrJref", Scr::scramble(jref));
writeUbigint(wr, "refWznmMCapability", refWznmMCapability);
writeString(wr, "Prjshort", Prjshort);
writeString(wr, "folder", folder);
xmlTextWriterEndElement(wr);
};
// IP cust --- INSERT
| 32.2 | 115 | 0.686542 | mpsitech |
a880e6c33081304e5af2743506785dcbeb227880 | 1,423 | cpp | C++ | src/isPaADescendantOfPb.cpp | buaazhouxingyu/topoana | 50a235614efe48cc17d9691c3cc150564e6e60f7 | [
"MIT"
] | 15 | 2020-01-13T01:30:14.000Z | 2022-01-17T03:22:34.000Z | src/isPaADescendantOfPb.cpp | buaazhouxingyu/topoana | 50a235614efe48cc17d9691c3cc150564e6e60f7 | [
"MIT"
] | 5 | 2019-06-01T13:38:44.000Z | 2021-06-19T09:26:12.000Z | src/isPaADescendantOfPb.cpp | buaazhouxingyu/topoana | 50a235614efe48cc17d9691c3cc150564e6e60f7 | [
"MIT"
] | 9 | 2019-06-01T10:19:25.000Z | 2022-01-10T15:00:21.000Z | #include "../include/topoana.h"
#include <iostream>
#include <cstdlib>
bool topoana::isPaADescendantOfPb(vector<int> vMidx, int idxA, int idxB)
{
if(idxA<0||((unsigned int) idxA)>=vMidx.size())
{
cerr<<"Error: The integer \"idxA\" is not a reasonable index for the vector \"vMidx\"!"<<endl;
cerr<<"Infor: The integer \"idxA\" is "<<idxA<<"."<<endl;
cerr<<"Infor: The size of the vector \"vMidx\" is "<<vMidx.size()<<"."<<endl;
cerr<<"Infor: Please check them."<<endl;
exit(-1);
}
if(idxB<0||((unsigned int) idxB)>=vMidx.size())
{
cerr<<"Error: The integer \"idxB\" is not a reasonable index for the vector \"vMidx\"!"<<endl;
cerr<<"Infor: The integer \"idxB\" is "<<idxB<<"."<<endl;
cerr<<"Infor: The size of the vector \"vMidx\" is "<<vMidx.size()<<"."<<endl;
cerr<<"Infor: Please check them."<<endl;
exit(-1);
}
if(idxA<idxB)
{
cerr<<"Error: The integer \"idxA\" is less than the integer \"idxB\"!"<<endl;
cerr<<"Infor: The integer \"idxA\" is "<<idxA<<"."<<endl;
cerr<<"Infor: The integer \"idxB\" is "<<idxB<<"."<<endl;
cerr<<"Infor: The integer \"idxA\" should be greater than the integer \"idxB\"!"<<endl;
cerr<<"Infor: Please check them."<<endl;
exit(-1);
}
while(vMidx[idxA]!=idxA)
{
if(vMidx[idxA]==idxB) return true;
else idxA=vMidx[idxA];
}
return false;
}
| 33.093023 | 100 | 0.574842 | buaazhouxingyu |
a884d2b4c71c5a7cb5e86514912a47e433a6aea0 | 3,479 | cpp | C++ | sycl/test/on-device/xocc/simple_tests/integration_header_check.cpp | gogo2/sycl | df17dc0819c53a73c4ea171bb1a8cd16e8b5011a | [
"Apache-2.0"
] | null | null | null | sycl/test/on-device/xocc/simple_tests/integration_header_check.cpp | gogo2/sycl | df17dc0819c53a73c4ea171bb1a8cd16e8b5011a | [
"Apache-2.0"
] | null | null | null | sycl/test/on-device/xocc/simple_tests/integration_header_check.cpp | gogo2/sycl | df17dc0819c53a73c4ea171bb1a8cd16e8b5011a | [
"Apache-2.0"
] | null | null | null | // REQUIRES: xocc
// RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %s -o %t.out
// RUN: %ACC_RUN_PLACEHOLDER %t.out
/*
The main point of the test is to check if you can name SYCL kernels in
certain ways without the compiler or run-time breaking due to an
incorrectly generated integration header.
This test is similar to sycl/test/regression/kernel_name_class.cpp
But started as an executable variation of integration_header.cpp from the
CodeGenSYCL tests.
*/
#include <CL/sycl.hpp>
#include "../utilities/device_selectors.hpp"
using namespace cl::sycl;
class kernel_1;
namespace second_namespace {
template <typename T = int>
class second_kernel;
}
template <int a, typename T1, typename T2>
class third_kernel;
struct x {};
template <typename T>
struct point {};
namespace template_arg_ns {
template <int DimX>
struct namespaced_arg {};
}
template <typename ...Ts>
class fourth_kernel;
namespace nm1 {
namespace nm2 {
template <int X> class fifth_kernel {};
} // namespace nm2
template <typename... Ts> class sixth_kernel;
}
int main() {
selector_defines::CompiledForDeviceSelector selector;
queue q {selector};
buffer<int> ob(range<1>{1});
q.submit([&](handler &cgh) {
auto wb = ob.get_access<access::mode::write>(cgh);
cgh.single_task<kernel_1>([=]() {
wb[0] = 1;
});
});
{
auto rb = ob.get_access<access::mode::read>();
assert(rb[0] == 1 && "kernel execution or assignment error");
printf("%d \n", rb[0]);
}
q.submit([&](handler &cgh) {
auto wb = ob.get_access<access::mode::write>(cgh);
cgh.single_task<class kernel_2>([=]() {
wb[0] += 2;
});
});
{
auto rb = ob.get_access<access::mode::read>();
assert(rb[0] == 3 && "kernel execution or assignment error");
printf("%d \n", rb[0]);
}
q.submit([&](handler &cgh) {
auto wb = ob.get_access<access::mode::write>(cgh);
cgh.single_task<second_namespace::second_kernel<char>>([=]() {
wb[0] += 3;
});
});
{
auto rb = ob.get_access<access::mode::read>();
assert(rb[0] == 6 && "kernel execution or assignment error");
printf("%d \n", rb[0]);
}
q.submit([&](handler &cgh) {
auto wb = ob.get_access<access::mode::write>(cgh);
// note: in the integration header specialization of this kernel it removes
// the keyword struct from the struct X declaration, it works as it by
// default re-declares it at the beginning of the header, is this ideal
// behavior though?
cgh.single_task<third_kernel<1, int,point<struct X>>>([=]() {
wb[0] += 4;
});
});
{
auto rb = ob.get_access<access::mode::read>();
assert(rb[0] == 10 && "kernel execution or assignment error");
printf("%d \n", rb[0]);
}
q.submit([&](handler &cgh) {
auto wb = ob.get_access<access::mode::write>(cgh);
cgh.single_task<fourth_kernel<template_arg_ns::namespaced_arg<1>>>([=]() {
wb[0] += 5;
});
});
{
auto rb = ob.get_access<access::mode::read>();
assert(rb[0] == 15 && "kernel execution or assignment error");
printf("%d \n", rb[0]);
}
q.submit([&](handler &cgh) {
auto wb = ob.get_access<access::mode::write>(cgh);
cgh.single_task<nm1::sixth_kernel<nm1::nm2::fifth_kernel<10>>>([=]() {
wb[0] += 6;
});
});
{
auto rb = ob.get_access<access::mode::read>();
assert(rb[0] == 21 && "kernel execution or assignment error");
printf("%d \n", rb[0]);
}
return 0;
}
| 23.193333 | 79 | 0.62288 | gogo2 |
a889ce15bbd534798d7e8f6acffc69114c2b928e | 39,822 | hpp | C++ | dev/Code/CryEngine/RenderDll/XRenderD3D9/DX12/Device/CCryDX12DeviceContext.hpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DX12/Device/CCryDX12DeviceContext.hpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/CryEngine/RenderDll/XRenderD3D9/DX12/Device/CCryDX12DeviceContext.hpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#pragma once
#ifndef __CCRYDX12DEVICECONTEXT__
#define __CCRYDX12DEVICECONTEXT__
#include "DX12/CCryDX12Object.hpp"
#include "DX12/Misc/SCryDX11PipelineState.hpp"
#include "DX12/API/DX12Base.hpp"
#include "DX12/API/DX12CommandList.hpp"
#include <pix.h>
class CCryDX12Device;
class CCryDX12DeviceContext
: public CCryDX12Object<ID3D11DeviceContext1>
{
friend class CDeviceManager;
friend class CDeviceObjectFactory;
public:
DX12_OBJECT(CCryDX12DeviceContext, CCryDX12Object<ID3D11DeviceContext1>);
static CCryDX12DeviceContext* Create(CCryDX12Device* pDevice);
CCryDX12DeviceContext(CCryDX12Device* pDevice);
virtual ~CCryDX12DeviceContext();
ILINE void CeaseCoreCommandList(uint32 nPoolId)
{
if (nPoolId == CMDQUEUE_GRAPHICS)
{
CeaseDirectCommandQueue(false);
}
else if (nPoolId == CMDQUEUE_COPY)
{
CeaseCopyCommandQueue(false);
}
}
ILINE void ResumeCoreCommandList(uint32 nPoolId)
{
if (nPoolId == CMDQUEUE_GRAPHICS)
{
ResumeDirectCommandQueue();
}
else if (nPoolId == CMDQUEUE_COPY)
{
ResumeCopyCommandQueue();
}
}
ILINE DX12::CommandListPool& GetCoreCommandListPool(int nPoolId)
{
if (nPoolId == CMDQUEUE_GRAPHICS)
{
return m_DirectListPool;
}
else if (nPoolId == CMDQUEUE_COPY)
{
return m_CopyListPool;
}
__debugbreak();
abort();
}
ILINE DX12::CommandListPool& GetCoreGraphicsCommandListPool()
{
return m_DirectListPool;
}
ILINE DX12::CommandList* GetCoreGraphicsCommandList() const
{
return m_DirectCommandList;
}
ILINE CCryDX12Device* GetDevice() const
{
return m_pDevice;
}
ILINE ID3D12Device* GetD3D12Device() const
{
return m_pDevice->GetD3D12Device();
}
void Finish(DX12::SwapChain* pDX12SwapChain);
#pragma region /* ID3D11DeviceChild implementation */
virtual void STDMETHODCALLTYPE GetDevice(
_Out_ ID3D11Device** ppDevice) final;
virtual HRESULT STDMETHODCALLTYPE GetPrivateData(
_In_ REFGUID guid,
_Inout_ UINT* pDataSize,
_Out_writes_bytes_opt_(*pDataSize) void* pData) final;
virtual HRESULT STDMETHODCALLTYPE SetPrivateData(
_In_ REFGUID guid,
_In_ UINT DataSize,
_In_reads_bytes_opt_(DataSize) const void* pData) final;
virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(
_In_ REFGUID guid,
_In_opt_ const IUnknown* pData) final;
#pragma endregion
#pragma region /* ID3D11DeviceContext implementation */
virtual void STDMETHODCALLTYPE VSSetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE PSSetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_In_reads_opt_(NumViews) ID3D11ShaderResourceView * const* ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE PSSetShader(
_In_opt_ ID3D11PixelShader * pPixelShader,
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance * const* ppClassInstances,
UINT NumClassInstances) final;
virtual void STDMETHODCALLTYPE PSSetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_In_reads_opt_(NumSamplers) ID3D11SamplerState * const* ppSamplers) final;
virtual void STDMETHODCALLTYPE VSSetShader(
_In_opt_ ID3D11VertexShader * pVertexShader,
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance * const* ppClassInstances,
UINT NumClassInstances) final;
virtual void STDMETHODCALLTYPE DrawIndexed(
_In_ UINT IndexCount,
_In_ UINT StartIndexLocation,
_In_ INT BaseVertexLocation) final;
virtual void STDMETHODCALLTYPE Draw(
_In_ UINT VertexCount,
_In_ UINT StartVertexLocation) final;
virtual HRESULT STDMETHODCALLTYPE Map(
_In_ ID3D11Resource* pResource,
_In_ UINT Subresource,
_In_ D3D11_MAP MapType,
_In_ UINT MapFlags,
_Out_ D3D11_MAPPED_SUBRESOURCE* pMappedResource) final;
virtual void STDMETHODCALLTYPE Unmap(
_In_ ID3D11Resource* pResource,
_In_ UINT Subresource) final;
virtual void STDMETHODCALLTYPE PSSetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE IASetInputLayout(
_In_opt_ ID3D11InputLayout* pInputLayout) final;
virtual void STDMETHODCALLTYPE IASetVertexBuffers(
_In_range_(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppVertexBuffers,
_In_reads_opt_(NumBuffers) const UINT * pStrides,
_In_reads_opt_(NumBuffers) const UINT * pOffsets) final;
virtual void STDMETHODCALLTYPE IASetIndexBuffer(
_In_opt_ ID3D11Buffer* pIndexBuffer,
_In_ DXGI_FORMAT Format,
_In_ UINT Offset) final;
virtual void STDMETHODCALLTYPE DrawIndexedInstanced(
_In_ UINT IndexCountPerInstance,
_In_ UINT InstanceCount,
_In_ UINT StartIndexLocation,
_In_ INT BaseVertexLocation,
_In_ UINT StartInstanceLocation) final;
virtual void STDMETHODCALLTYPE DrawInstanced(
_In_ UINT VertexCountPerInstance,
_In_ UINT InstanceCount,
_In_ UINT StartVertexLocation,
_In_ UINT StartInstanceLocation) final;
virtual void STDMETHODCALLTYPE GSSetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE GSSetShader(
_In_opt_ ID3D11GeometryShader * pShader,
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance * const* ppClassInstances,
UINT NumClassInstances) final;
virtual void STDMETHODCALLTYPE IASetPrimitiveTopology(
_In_ D3D11_PRIMITIVE_TOPOLOGY Topology) final;
virtual void STDMETHODCALLTYPE VSSetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_In_reads_opt_(NumViews) ID3D11ShaderResourceView * const* ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE VSSetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_In_reads_opt_(NumSamplers) ID3D11SamplerState * const* ppSamplers) final;
virtual void STDMETHODCALLTYPE Begin(
_In_ ID3D11Asynchronous* pAsync) final;
virtual void STDMETHODCALLTYPE End(
_In_ ID3D11Asynchronous* pAsync) final;
virtual HRESULT STDMETHODCALLTYPE GetData(
_In_ ID3D11Asynchronous * pAsync,
_Out_writes_bytes_opt_(DataSize) void* pData,
_In_ UINT DataSize,
_In_ UINT GetDataFlags) final;
virtual void STDMETHODCALLTYPE SetPredication(
_In_opt_ ID3D11Predicate* pPredicate,
_In_ BOOL PredicateValue) final;
virtual void STDMETHODCALLTYPE GSSetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_In_reads_opt_(NumViews) ID3D11ShaderResourceView * const* ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE GSSetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_In_reads_opt_(NumSamplers) ID3D11SamplerState * const* ppSamplers) final;
virtual void STDMETHODCALLTYPE OMSetRenderTargets(
_In_range_(0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT) UINT NumViews,
_In_reads_opt_(NumViews) ID3D11RenderTargetView * const* ppRenderTargetViews,
_In_opt_ ID3D11DepthStencilView * pDepthStencilView) final;
virtual void STDMETHODCALLTYPE OMSetRenderTargetsAndUnorderedAccessViews(
_In_ UINT NumRTVs,
_In_reads_opt_(NumRTVs) ID3D11RenderTargetView * const* ppRenderTargetViews,
_In_opt_ ID3D11DepthStencilView * pDepthStencilView,
_In_range_(0, D3D11_1_UAV_SLOT_COUNT - 1) UINT UAVStartSlot,
_In_ UINT NumUAVs,
_In_reads_opt_(NumUAVs) ID3D11UnorderedAccessView * const* ppUnorderedAccessViews,
_In_reads_opt_(NumUAVs) const UINT * pUAVInitialCounts) final;
virtual void STDMETHODCALLTYPE OMSetBlendState(
_In_opt_ ID3D11BlendState* pBlendState,
_In_opt_ const FLOAT BlendFactor[4],
_In_ UINT SampleMask) final;
virtual void STDMETHODCALLTYPE OMSetDepthStencilState(
_In_opt_ ID3D11DepthStencilState* pDepthStencilState,
_In_ UINT StencilRef) final;
virtual void STDMETHODCALLTYPE SOSetTargets(
_In_range_(0, D3D11_SO_BUFFER_SLOT_COUNT) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppSOTargets,
_In_reads_opt_(NumBuffers) const UINT * pOffsets) final;
virtual void STDMETHODCALLTYPE DrawAuto() final;
virtual void STDMETHODCALLTYPE DrawIndexedInstancedIndirect(
_In_ ID3D11Buffer* pBufferForArgs,
_In_ UINT AlignedByteOffsetForArgs) final;
virtual void STDMETHODCALLTYPE DrawInstancedIndirect(
_In_ ID3D11Buffer* pBufferForArgs,
_In_ UINT AlignedByteOffsetForArgs) final;
virtual void STDMETHODCALLTYPE Dispatch(
_In_ UINT ThreadGroupCountX,
_In_ UINT ThreadGroupCountY,
_In_ UINT ThreadGroupCountZ) final;
virtual void STDMETHODCALLTYPE DispatchIndirect(
_In_ ID3D11Buffer* pBufferForArgs,
_In_ UINT AlignedByteOffsetForArgs) final;
virtual void STDMETHODCALLTYPE RSSetState(
_In_opt_ ID3D11RasterizerState* pRasterizerState) final;
virtual void STDMETHODCALLTYPE RSSetViewports(
_In_range_(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumViewports,
_In_reads_opt_(NumViewports) const D3D11_VIEWPORT * pViewports) final;
virtual void STDMETHODCALLTYPE RSSetScissorRects(
_In_range_(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumRects,
_In_reads_opt_(NumRects) const D3D11_RECT * pRects) final;
virtual void STDMETHODCALLTYPE CopySubresourceRegion(
_In_ ID3D11Resource* pDstResource,
_In_ UINT DstSubresource,
_In_ UINT DstX,
_In_ UINT DstY,
_In_ UINT DstZ,
_In_ ID3D11Resource* pSrcResource,
_In_ UINT SrcSubresource,
_In_opt_ const D3D11_BOX* pSrcBox) final;
virtual void STDMETHODCALLTYPE CopyResource(
_In_ ID3D11Resource* pDstResource,
_In_ ID3D11Resource* pSrcResource) final;
virtual void STDMETHODCALLTYPE UpdateSubresource(
_In_ ID3D11Resource* pDstResource,
_In_ UINT DstSubresource,
_In_opt_ const D3D11_BOX* pDstBox,
_In_ const void* pSrcData,
_In_ UINT SrcRowPitch,
_In_ UINT SrcDepthPitch) final;
virtual void STDMETHODCALLTYPE CopyStructureCount(
_In_ ID3D11Buffer* pDstBuffer,
_In_ UINT DstAlignedByteOffset,
_In_ ID3D11UnorderedAccessView* pSrcView) final;
virtual void STDMETHODCALLTYPE ClearRenderTargetView(
_In_ ID3D11RenderTargetView* pRenderTargetView,
_In_ const FLOAT ColorRGBA[4]) final;
virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewUint(
_In_ ID3D11UnorderedAccessView* pUnorderedAccessView,
_In_ const UINT Values[4]) final;
virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewFloat(
_In_ ID3D11UnorderedAccessView* pUnorderedAccessView,
_In_ const FLOAT Values[4]) final;
virtual void STDMETHODCALLTYPE ClearDepthStencilView(
_In_ ID3D11DepthStencilView* pDepthStencilView,
_In_ UINT ClearFlags,
_In_ FLOAT Depth,
_In_ UINT8 Stencil) final;
virtual void STDMETHODCALLTYPE GenerateMips(
_In_ ID3D11ShaderResourceView* pShaderResourceView) final;
virtual void STDMETHODCALLTYPE SetResourceMinLOD(
_In_ ID3D11Resource* pResource,
FLOAT MinLOD) final;
virtual FLOAT STDMETHODCALLTYPE GetResourceMinLOD(
_In_ ID3D11Resource* pResource) final;
virtual void STDMETHODCALLTYPE ResolveSubresource(
_In_ ID3D11Resource* pDstResource,
_In_ UINT DstSubresource,
_In_ ID3D11Resource* pSrcResource,
_In_ UINT SrcSubresource,
_In_ DXGI_FORMAT Format) final;
virtual void STDMETHODCALLTYPE HSSetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_In_reads_opt_(NumViews) ID3D11ShaderResourceView * const* ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE HSSetShader(
_In_opt_ ID3D11HullShader * pHullShader,
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance * const* ppClassInstances,
UINT NumClassInstances) final;
virtual void STDMETHODCALLTYPE HSSetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_In_reads_opt_(NumSamplers) ID3D11SamplerState * const* ppSamplers) final;
virtual void STDMETHODCALLTYPE HSSetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE DSSetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_In_reads_opt_(NumViews) ID3D11ShaderResourceView * const* ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE DSSetShader(
_In_opt_ ID3D11DomainShader * pDomainShader,
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance * const* ppClassInstances,
UINT NumClassInstances) final;
virtual void STDMETHODCALLTYPE DSSetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_In_reads_opt_(NumSamplers) ID3D11SamplerState * const* ppSamplers) final;
virtual void STDMETHODCALLTYPE DSSetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE CSSetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_In_reads_opt_(NumViews) ID3D11ShaderResourceView * const* ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE CSSetUnorderedAccessViews(
_In_range_(0, D3D11_1_UAV_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_1_UAV_SLOT_COUNT - StartSlot) UINT NumUAVs,
_In_reads_opt_(NumUAVs) ID3D11UnorderedAccessView * const* ppUnorderedAccessViews,
_In_reads_opt_(NumUAVs) const UINT * pUAVInitialCounts) final;
virtual void STDMETHODCALLTYPE CSSetShader(
_In_opt_ ID3D11ComputeShader * pComputeShader,
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance * const* ppClassInstances,
UINT NumClassInstances) final;
virtual void STDMETHODCALLTYPE CSSetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_In_reads_opt_(NumSamplers) ID3D11SamplerState * const* ppSamplers) final;
virtual void STDMETHODCALLTYPE CSSetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_In_reads_opt_(NumBuffers) ID3D11Buffer * const* ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE VSGetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE PSGetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView * *ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE PSGetShader(
_Out_ ID3D11PixelShader** ppPixelShader,
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance** ppClassInstances,
_Inout_opt_ UINT* pNumClassInstances) final;
virtual void STDMETHODCALLTYPE PSGetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_Out_writes_opt_(NumSamplers) ID3D11SamplerState * *ppSamplers) final;
virtual void STDMETHODCALLTYPE VSGetShader(
_Out_ ID3D11VertexShader** ppVertexShader,
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance** ppClassInstances,
_Inout_opt_ UINT* pNumClassInstances) final;
virtual void STDMETHODCALLTYPE PSGetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE IAGetInputLayout(
_Out_ ID3D11InputLayout** ppInputLayout) final;
virtual void STDMETHODCALLTYPE IAGetVertexBuffers(
_In_range_(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppVertexBuffers,
_Out_writes_opt_(NumBuffers) UINT * pStrides,
_Out_writes_opt_(NumBuffers) UINT * pOffsets) final;
virtual void STDMETHODCALLTYPE IAGetIndexBuffer(
_Out_opt_ ID3D11Buffer** pIndexBuffer,
_Out_opt_ DXGI_FORMAT* Format,
_Out_opt_ UINT* Offset) final;
virtual void STDMETHODCALLTYPE GSGetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE GSGetShader(
_Out_ ID3D11GeometryShader** ppGeometryShader,
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance** ppClassInstances,
_Inout_opt_ UINT* pNumClassInstances) final;
virtual void STDMETHODCALLTYPE IAGetPrimitiveTopology(
_Out_ D3D11_PRIMITIVE_TOPOLOGY* pTopology) final;
virtual void STDMETHODCALLTYPE VSGetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView * *ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE VSGetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_Out_writes_opt_(NumSamplers) ID3D11SamplerState * *ppSamplers) final;
virtual void STDMETHODCALLTYPE GetPredication(
_Out_opt_ ID3D11Predicate** ppPredicate,
_Out_opt_ BOOL* pPredicateValue) final;
virtual void STDMETHODCALLTYPE GSGetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView * *ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE GSGetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_Out_writes_opt_(NumSamplers) ID3D11SamplerState * *ppSamplers) final;
virtual void STDMETHODCALLTYPE OMGetRenderTargets(
_In_range_(0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT) UINT NumViews,
_Out_writes_opt_(NumViews) ID3D11RenderTargetView * *ppRenderTargetViews,
_Out_opt_ ID3D11DepthStencilView * *ppDepthStencilView) final;
virtual void STDMETHODCALLTYPE OMGetRenderTargetsAndUnorderedAccessViews(
_In_range_(0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT) UINT NumRTVs,
_Out_writes_opt_(NumRTVs) ID3D11RenderTargetView * *ppRenderTargetViews,
_Out_opt_ ID3D11DepthStencilView * *ppDepthStencilView,
_In_range_(0, D3D11_PS_CS_UAV_REGISTER_COUNT - 1) UINT UAVStartSlot,
_In_range_(0, D3D11_PS_CS_UAV_REGISTER_COUNT - UAVStartSlot) UINT NumUAVs,
_Out_writes_opt_(NumUAVs) ID3D11UnorderedAccessView * *ppUnorderedAccessViews) final;
virtual void STDMETHODCALLTYPE OMGetBlendState(
_Out_opt_ ID3D11BlendState * *ppBlendState,
_Out_opt_ FLOAT BlendFactor[4],
_Out_opt_ UINT * pSampleMask) final;
virtual void STDMETHODCALLTYPE OMGetDepthStencilState(
_Out_opt_ ID3D11DepthStencilState** ppDepthStencilState,
_Out_opt_ UINT* pStencilRef) final;
virtual void STDMETHODCALLTYPE SOGetTargets(
_In_range_(0, D3D11_SO_BUFFER_SLOT_COUNT) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppSOTargets) final;
virtual void STDMETHODCALLTYPE RSGetState(
_Out_ ID3D11RasterizerState** ppRasterizerState) final;
virtual void STDMETHODCALLTYPE RSGetViewports(
_Inout_ UINT* pNumViewports,
_Out_writes_opt_(*pNumViewports) D3D11_VIEWPORT* pViewports) final;
virtual void STDMETHODCALLTYPE RSGetScissorRects(
_Inout_ UINT* pNumRects,
_Out_writes_opt_(*pNumRects) D3D11_RECT* pRects) final;
virtual void STDMETHODCALLTYPE HSGetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView * *ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE HSGetShader(
_Out_ ID3D11HullShader** ppHullShader,
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance** ppClassInstances,
_Inout_opt_ UINT* pNumClassInstances) final;
virtual void STDMETHODCALLTYPE HSGetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_Out_writes_opt_(NumSamplers) ID3D11SamplerState * *ppSamplers) final;
virtual void STDMETHODCALLTYPE HSGetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE DSGetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView * *ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE DSGetShader(
_Out_ ID3D11DomainShader** ppDomainShader,
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance** ppClassInstances,
_Inout_opt_ UINT* pNumClassInstances) final;
virtual void STDMETHODCALLTYPE DSGetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_Out_writes_opt_(NumSamplers) ID3D11SamplerState * *ppSamplers) final;
virtual void STDMETHODCALLTYPE DSGetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE CSGetShaderResources(
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot) UINT NumViews,
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView * *ppShaderResourceViews) final;
virtual void STDMETHODCALLTYPE CSGetUnorderedAccessViews(
_In_range_(0, D3D11_PS_CS_UAV_REGISTER_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_PS_CS_UAV_REGISTER_COUNT - StartSlot) UINT NumUAVs,
_Out_writes_opt_(NumUAVs) ID3D11UnorderedAccessView * *ppUnorderedAccessViews) final;
virtual void STDMETHODCALLTYPE CSGetShader(
_Out_ ID3D11ComputeShader** ppComputeShader,
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance** ppClassInstances,
_Inout_opt_ UINT* pNumClassInstances) final;
virtual void STDMETHODCALLTYPE CSGetSamplers(
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot) UINT NumSamplers,
_Out_writes_opt_(NumSamplers) ID3D11SamplerState * *ppSamplers) final;
virtual void STDMETHODCALLTYPE CSGetConstantBuffers(
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1) UINT StartSlot,
_In_range_(0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot) UINT NumBuffers,
_Out_writes_opt_(NumBuffers) ID3D11Buffer * *ppConstantBuffers) final;
virtual void STDMETHODCALLTYPE ClearState() final;
virtual void STDMETHODCALLTYPE Flush() final;
virtual D3D11_DEVICE_CONTEXT_TYPE STDMETHODCALLTYPE GetType() final;
virtual UINT STDMETHODCALLTYPE GetContextFlags() final;
virtual void STDMETHODCALLTYPE ExecuteCommandList(
_In_ ID3D11CommandList* pCommandList,
BOOL RestoreContextState) final;
virtual HRESULT STDMETHODCALLTYPE FinishCommandList(
_In_ BOOL RestoreDeferredContextState,
_Out_opt_ ID3D11CommandList** ppCommandList) final;
#pragma endregion
#pragma region /* D3D 11.1 specific functions */
virtual void STDMETHODCALLTYPE CopySubresourceRegion1(ID3D11Resource* pDstResource, UINT DstSubresource, UINT DstX, UINT DstY, UINT DstZ, ID3D11Resource* pSrcResource, UINT SrcSubresource, const D3D11_BOX* pSrcBox, UINT CopyFlags) final;
virtual void STDMETHODCALLTYPE CopyResource1(ID3D11Resource* pDstResource, ID3D11Resource* pSrcResource, UINT CopyFlags) final;
virtual void STDMETHODCALLTYPE UpdateSubresource1(ID3D11Resource* pDstResource, UINT DstSubresource, const D3D11_BOX* pDstBox, const void* pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch, UINT CopyFlags) final;
virtual void STDMETHODCALLTYPE DiscardResource(ID3D11Resource* pResource) final;
virtual void STDMETHODCALLTYPE DiscardView(ID3D11View* pResourceView) final;
virtual void STDMETHODCALLTYPE VSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers, const UINT* pFirstConstant, const UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE HSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers, const UINT* pFirstConstant, const UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE DSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers, const UINT* pFirstConstant, const UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE GSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers, const UINT* pFirstConstant, const UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE PSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers, const UINT* pFirstConstant, const UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE CSSetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers, const UINT* pFirstConstant, const UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE VSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer** ppConstantBuffers, UINT* pFirstConstant, UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE HSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer** ppConstantBuffers, UINT* pFirstConstant, UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE DSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer** ppConstantBuffers, UINT* pFirstConstant, UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE GSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer** ppConstantBuffers, UINT* pFirstConstant, UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE PSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer** ppConstantBuffers, UINT* pFirstConstant, UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE CSGetConstantBuffers1(UINT StartSlot, UINT NumBuffers, ID3D11Buffer** ppConstantBuffers, UINT* pFirstConstant, UINT* pNumConstants) final;
virtual void STDMETHODCALLTYPE SwapDeviceContextState(ID3DDeviceContextState* pState, ID3DDeviceContextState** ppPreviousState) final;
virtual void STDMETHODCALLTYPE ClearView(ID3D11View* pView, const FLOAT Color[4], const D3D11_RECT* pRect, UINT NumRects) final;
virtual void STDMETHODCALLTYPE DiscardView1(ID3D11View* pResourceView, const D3D11_RECT* pRects, UINT NumRects) final;
#pragma endregion
virtual void STDMETHODCALLTYPE ClearRectsRenderTargetView(
_In_ ID3D11RenderTargetView * pRenderTargetView,
_In_ const FLOAT ColorRGBA[4],
_In_ UINT NumRects,
_In_reads_opt_(NumRects) const D3D11_RECT * pRects);
virtual void STDMETHODCALLTYPE ClearRectsUnorderedAccessViewUint(
_In_ ID3D11UnorderedAccessView * pUnorderedAccessView,
_In_ const UINT Values[4],
_In_ UINT NumRects,
_In_reads_opt_(NumRects) const D3D11_RECT * pRects);
virtual void STDMETHODCALLTYPE ClearRectsUnorderedAccessViewFloat(
_In_ ID3D11UnorderedAccessView * pUnorderedAccessView,
_In_ const FLOAT Values[4],
_In_ UINT NumRects,
_In_reads_opt_(NumRects) const D3D11_RECT * pRects);
virtual void STDMETHODCALLTYPE ClearRectsDepthStencilView(
_In_ ID3D11DepthStencilView * pDepthStencilView,
_In_ UINT ClearFlags,
_In_ FLOAT Depth,
_In_ UINT8 Stencil,
_In_ UINT NumRects,
_In_reads_opt_(NumRects) const D3D11_RECT * pRects);
HRESULT STDMETHODCALLTYPE CopyStagingResource(
_In_ ID3D11Resource* pStagingResource,
_In_ ID3D11Resource* pSourceResource,
_In_ UINT SubResource,
_In_ BOOL Upload);
HRESULT STDMETHODCALLTYPE TestStagingResource(
_In_ ID3D11Resource* pStagingResource);
HRESULT STDMETHODCALLTYPE WaitStagingResource(
_In_ ID3D11Resource* pStagingResource);
HRESULT STDMETHODCALLTYPE MapStagingResource(
_In_ ID3D11Resource* pTextureResource,
_In_ ID3D11Resource* pStagingResource,
_In_ UINT SubResource,
_In_ BOOL Upload,
_Out_ void** ppStagingMemory,
_Out_ uint32* pRowPitch);
void STDMETHODCALLTYPE UnmapStagingResource(
_In_ ID3D11Resource* pStagingResource,
_In_ BOOL Upload);
void STDMETHODCALLTYPE UploadResource(
_In_ ICryDX12Resource* pDstResource,
_In_ const D3D11_SUBRESOURCE_DATA* pInitialData,
_In_ size_t numInitialData);
void STDMETHODCALLTYPE UploadResource(
_In_ DX12::Resource* pDstResource,
_In_ const DX12::Resource::InitialData* pSrcData);
ILINE UINT64 InsertFence()
{
return m_CmdFenceSet.GetCurrentValue(CMDQUEUE_GRAPHICS) - !m_DirectCommandList->IsUtilized();
}
ILINE HRESULT FlushToFence(UINT64 fenceValue)
{
m_DirectListPool.GetAsyncCommandQueue().Flush(fenceValue);
return S_OK;
}
ILINE HRESULT TestForFence(UINT64 fenceValue)
{
return m_CmdFenceSet.IsCompleted(fenceValue, CMDQUEUE_GRAPHICS) ? S_OK : S_FALSE;
}
ILINE HRESULT WaitForFence(UINT64 fenceValue)
{
m_CmdFenceSet.WaitForFence(fenceValue, CMDQUEUE_GRAPHICS);
return S_OK;
}
void WaitForIdle();
void ResetCachedState();
void PushMarker(const char* name)
{
PIXBeginEvent(m_DirectCommandList->GetD3D12CommandList(), 0, name);
}
void PopMarker()
{
PIXEndEvent(m_DirectCommandList->GetD3D12CommandList());
}
UINT64 MakeCpuTimestamp(UINT64 gpuTimestamp) const;
UINT64 MakeCpuTimestampMicroseconds(UINT64 gpuTimestamp) const;
void BeginCopyRegion()
{
m_bInCopyRegion = true;
}
void EndCopyRegion()
{
m_bInCopyRegion = false;
}
void SubmitAllCommands(bool wait);
UINT TimestampIndex(DX12::CommandList* pCmdList);
ID3D12Resource* QueryTimestamp(DX12::CommandList* pCmdList, UINT index);
void ResolveTimestamp(DX12::CommandList* pCmdList, UINT index, void* mem);
UINT OcclusionIndex(DX12::CommandList* pCmdList, bool counter);
ID3D12Resource* QueryOcclusion(DX12::CommandList* pCmdList, UINT index, bool counter);
void ResolveOcclusion(DX12::CommandList* pCmdList, UINT index, void* mem);
// This is a somewhat arbitrary number that affects stack usage for methods that get subresource descriptors.
static constexpr int MAX_SUBRESOURCES = 64;
private:
bool PreparePSO(DX12::CommandMode commandMode);
void PrepareGraphicsFF();
bool PrepareGraphicsState();
bool PrepareComputeState();
void CeaseDirectCommandQueue(bool wait);
void ResumeDirectCommandQueue();
void CeaseCopyCommandQueue(bool wait);
void ResumeCopyCommandQueue();
void CeaseAllCommandQueues(bool wait);
void ResumeAllCommandQueues();
void SubmitDirectCommands(bool wait);
void SubmitDirectCommands(bool wait, const UINT64 fenceValue);
void SubmitCopyCommands(bool wait);
void SubmitCopyCommands(bool wait, const UINT64 fenceValue);
void SubmitAllCommands(bool wait, const UINT64(&fenceValues)[CMDQUEUE_NUM]);
void SubmitAllCommands(bool wait, const UINT64(&fenceValues)[CMDQUEUE_NUM], int fenceId);
void SubmitAllCommands(bool wait, const std::atomic<AZ::u64>(&fenceValues)[CMDQUEUE_NUM]);
void SubmitAllCommands(bool wait, const std::atomic<AZ::u64>(&fenceValues)[CMDQUEUE_NUM], int fenceId);
void BindResources(DX12::CommandMode commandMode);
void BindOutputViews();
void DebugPrintResources(DX12::CommandMode commandMode);
void SetConstantBuffers1(
DX12::EShaderStage shaderStage,
UINT StartSlot,
UINT NumBuffers,
ID3D11Buffer* const* ppConstantBuffers,
const UINT* pFirstConstant,
const UINT* pNumConstants,
DX12::CommandMode commandMode);
bool m_bInCopyRegion;
CCryDX12Device* m_pDevice;
DX12::Device* m_pDX12Device;
DX12::CommandListFenceSet m_CmdFenceSet;
DX12::CommandListPool m_DirectListPool;
DX12::CommandListPool m_CopyListPool;
DX12::SmartPtr<DX12::CommandList> m_DirectCommandList;
DX12::SmartPtr<DX12::CommandList> m_CopyCommandList;
const DX12::PipelineState* m_CurrentPSO;
const DX12::RootSignature* m_CurrentRootSignature[DX12::CommandModeCount];
SCryDX11PipelineState m_PipelineState[DX12::CommandModeCount];
UINT m_OutstandingQueries;
ID3D12Resource* m_TimestampDownloadBuffer;
ID3D12Resource* m_OcclusionDownloadBuffer;
UINT m_TimestampIndex;
UINT m_OcclusionIndex;
void* m_TimestampMemory;
void* m_OcclusionMemory;
bool m_TimestampMapValid;
bool m_OcclusionMapValid;
DX12::DescriptorHeap* m_pResourceHeap;
DX12::DescriptorHeap* m_pSamplerHeap;
bool m_bCurrentNative;
int m_nResDynOffset;
int m_nFrame;
uint32 m_nStencilRef;
DX12::QueryHeap m_TimestampHeap;
DX12::QueryHeap m_OcclusionHeap;
DX12::QueryHeap m_PipelineHeap;
#ifdef DX12_STATS
size_t m_NumMapDiscardSkips;
size_t m_NumMapDiscards;
size_t m_NumCommandListOverflows;
size_t m_NumCommandListSplits;
size_t m_NumPSOs;
size_t m_NumRootSignatures;
size_t m_NumberSettingOutputViews;
#endif // DX12_STATS
};
#endif // __CCRYDX12DEVICECONTEXT__
| 45.40707 | 241 | 0.753378 | jeikabu |