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
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 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
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0f15557a9db6ed816e38a74ceee775aa107e0cbd | 3,708 | cpp | C++ | src/vulkan-renderer/io/byte_stream.cpp | JoseETeixeira/vulkan-renderer | 982e8004d9269ab1ffb1b7e8da03b351136985c9 | [
"MIT"
] | 443 | 2019-12-26T03:24:17.000Z | 2022-03-29T07:55:01.000Z | src/vulkan-renderer/io/byte_stream.cpp | JoseETeixeira/vulkan-renderer | 982e8004d9269ab1ffb1b7e8da03b351136985c9 | [
"MIT"
] | 384 | 2019-12-12T13:08:02.000Z | 2022-03-28T19:57:11.000Z | src/vulkan-renderer/io/byte_stream.cpp | JoseETeixeira/vulkan-renderer | 982e8004d9269ab1ffb1b7e8da03b351136985c9 | [
"MIT"
] | 36 | 2020-03-31T11:44:28.000Z | 2022-03-12T08:44:25.000Z | #include "inexor/vulkan-renderer/io/byte_stream.hpp"
#include "inexor/vulkan-renderer/world/cube.hpp"
#include <fstream>
namespace inexor::vulkan_renderer::io {
std::vector<std::uint8_t> ByteStream::read_file(const std::filesystem::path &path) {
std::ifstream stream(path, std::ios::in | std::ios::binary);
return {std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()};
}
ByteStream::ByteStream(std::vector<std::uint8_t> buffer) : m_buffer(std::move(buffer)) {}
ByteStream::ByteStream(const std::filesystem::path &path) : ByteStream(read_file(path)) {}
std::size_t ByteStream::size() const {
return m_buffer.size();
}
const std::vector<std::uint8_t> &ByteStream::buffer() const {
return m_buffer;
}
void ByteStreamReader::check_end(const std::size_t size) const {
if (static_cast<std::size_t>(std::distance(m_iter, m_stream.buffer().end())) < size) {
throw std::runtime_error("end would be overrun");
}
}
ByteStreamReader::ByteStreamReader(const ByteStream &stream) : m_stream(stream), m_iter(stream.buffer().begin()) {}
void ByteStreamReader::skip(const std::size_t size) {
const std::size_t skip = std::min(
size, std::size_t(std::distance<std::vector<std::uint8_t>::const_iterator>(m_iter, m_stream.buffer().end())));
std::advance(m_iter, skip);
}
std::size_t ByteStreamReader::remaining() const {
return std::distance<std::vector<std::uint8_t>::const_iterator>(m_iter, m_stream.buffer().end());
}
template <>
std::uint8_t ByteStreamReader::read() {
check_end(1);
return *m_iter++;
}
template <>
std::uint32_t ByteStreamReader::read() {
check_end(4);
return (*m_iter++ << 0u) | (*m_iter++ << 8u) | (*m_iter++ << 16u) | (*m_iter++ << 24u);
}
template <>
std::string ByteStreamReader::read(const std::size_t &size) {
check_end(size);
auto start = m_iter;
std::advance(m_iter, size);
return std::string(start, m_iter);
}
template <>
world::Cube::Type ByteStreamReader::read() {
return static_cast<world::Cube::Type>(read<std::uint8_t>());
}
template <>
std::array<world::Indentation, 12> ByteStreamReader::read() {
check_end(9);
std::array<world::Indentation, 12> indentations;
auto writer = indentations.begin(); // NOLINT
const auto end = m_iter + 9;
while (m_iter != end) {
*writer++ = world::Indentation(*m_iter >> 2u);
*writer++ = world::Indentation(((*m_iter & 0b00000011u) << 4u) | (*(++m_iter) >> 4u));
*writer++ = world::Indentation(((*m_iter & 0b00001111u) << 2u) | (*(++m_iter) >> 6u));
*writer++ = world::Indentation(*m_iter++ & 0b00111111u);
}
return indentations;
}
template <>
void ByteStreamWriter::write(const std::uint8_t &value) {
m_buffer.emplace_back(value);
}
template <>
void ByteStreamWriter::write(const std::uint32_t &value) {
m_buffer.emplace_back(value >> 24u);
m_buffer.emplace_back(value >> 16u);
m_buffer.emplace_back(value >> 8u);
m_buffer.emplace_back(value);
}
template <>
void ByteStreamWriter::write(const std::string &value) {
std::copy(value.begin(), value.end(), std::back_inserter(m_buffer));
}
template <>
void ByteStreamWriter::write(const world::Cube::Type &value) {
write(static_cast<std::uint8_t>(value));
}
template <>
void ByteStreamWriter::write(const std::array<world::Indentation, 12> &value) {
for (auto iter = value.begin(); iter != value.end(); iter++) { // NOLINT
write<std::uint8_t>((iter->uid() << 2u) | ((++iter)->uid() >> 4));
write<std::uint8_t>((iter->uid() << 4u) | ((++iter)->uid() >> 2));
write<std::uint8_t>((iter->uid() << 6u) | ((++iter)->uid()));
}
}
} // namespace inexor::vulkan_renderer::io
| 32.814159 | 118 | 0.657497 | JoseETeixeira |
0f16ed5b02cce189a93288242bb5484e17a0150a | 3,614 | cpp | C++ | test/module/irohad/consensus/yac/yac_synchronization_test.cpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 1 | 2020-05-15T10:02:38.000Z | 2020-05-15T10:02:38.000Z | test/module/irohad/consensus/yac/yac_synchronization_test.cpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 2 | 2020-02-18T11:25:35.000Z | 2020-02-20T04:09:45.000Z | test/module/irohad/consensus/yac/yac_synchronization_test.cpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 1 | 2020-07-25T11:15:16.000Z | 2020-07-25T11:15:16.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "module/irohad/consensus/yac/yac_fixture.hpp"
#include "common/hexutils.hpp"
using namespace iroha::consensus::yac;
using ::testing::_;
using ::testing::Return;
/**
* The class helps to create fake network for unit testing of consensus
*/
class NetworkUtil {
public:
/// creates fake network of number_of_peers size
NetworkUtil(size_t number_of_peers) {
for (size_t i = 0; i < number_of_peers; ++i) {
peers_.push_back(makePeer(std::to_string(i)));
}
order_ = ClusterOrdering::create(peers_);
}
auto createHash(const iroha::consensus::Round &r,
const std::string &block_hash = "default_block",
const std::string &proposal_hash = "default_proposal") const {
return YacHash(r, proposal_hash, block_hash);
}
auto createVote(size_t from, const YacHash &yac_hash) const {
BOOST_ASSERT_MSG(from < peers_.size(), "Requested unknown index of peer");
return iroha::consensus::yac::createVote(
yac_hash,
*iroha::hexstringToBytestring(peers_.at(from)->pubkey().hex()));
}
/// create votes of peers by their number
auto createVotes(
const std::vector<size_t> &peers,
const iroha::consensus::Round &r,
const std::string &block_hash = "default_block",
const std::string &proposal_hash = "default_proposal") const {
std::vector<VoteMessage> result;
for (auto &peer_number : peers) {
result.push_back(
createVote(peer_number, createHash(r, block_hash, proposal_hash)));
}
return result;
}
std::vector<std::shared_ptr<shared_model::interface::Peer>> peers_;
boost::optional<ClusterOrdering> order_;
};
class YacSynchronizationTest : public YacTest {
public:
void SetUp() override {
YacTest::SetUp();
network_util_ = NetworkUtil(7);
initAndCommitState(network_util_);
}
/// inits initial state and commits some rounds
void initAndCommitState(const NetworkUtil &network_util) {
size_t number_of_committed_rounds = 10;
initYac(*network_util.order_);
EXPECT_CALL(*crypto, verify(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*timer, deny()).Times(number_of_committed_rounds);
for (auto i = 0u; i < number_of_committed_rounds; i++) {
iroha::consensus::Round r{i, 0};
yac->vote(network_util.createHash(r), *network_util.order_);
yac->onState(network_util.createVotes({1, 2, 3, 4, 5, 6}, r));
}
EXPECT_CALL(*network, sendState(_, _)).Times(8);
yac->vote(network_util.createHash({10, 0}), *network_util.order_);
}
NetworkUtil network_util_{1};
};
/**
* @given Yac which stores commit
* @when Vote from known peer from old round which was presented in the cache
* @then Yac sends commit for the last round
*/
TEST_F(YacSynchronizationTest, SynchronizationOncommitInTheCahe) {
yac->onState(network_util_.createVotes({0}, iroha::consensus::Round{1, 0}));
}
/**
* @given Yac which stores commit
* @when Vote from known peer from old round which presents in a cache
* @then Yac sends commit for the last round
*/
TEST_F(YacSynchronizationTest, SynchronizationOnCommitOutOfTheCahe) {
yac->onState(network_util_.createVotes({0}, iroha::consensus::Round{9, 0}));
}
/**
* @given Yac received reject
* @when Vote from known peer from old round which doesn't present in the cache
* @then Yac sends last commit
*/
TEST_F(YacSynchronizationTest, SynchronizationRejectOutOfTheCahe) {
yac->onState(network_util_.createVotes({0}, iroha::consensus::Round{5, 5}));
}
| 31.982301 | 80 | 0.697842 | akshatkarani |
0f175b86135b7c86c9c9b68920d17b0884d50c2d | 1,603 | cpp | C++ | BalancedParanthesis.cpp | florayasmin/Hacktoberfest2021-1 | d61db34b1844ae9202af829d9e4632ed0deb3574 | [
"MIT"
] | 1 | 2021-10-16T01:34:12.000Z | 2021-10-16T01:34:12.000Z | BalancedParanthesis.cpp | florayasmin/Hacktoberfest2021-1 | d61db34b1844ae9202af829d9e4632ed0deb3574 | [
"MIT"
] | null | null | null | BalancedParanthesis.cpp | florayasmin/Hacktoberfest2021-1 | d61db34b1844ae9202af829d9e4632ed0deb3574 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool isValid(string s)
{
int n = s.size();
stack<char> st;
bool ans = true;
for (int i = 0; i < n; i++)
{
if (st.empty() and (s[i] == ')' or s[i] == '}' or s[i] == ']'))
{
return false; // if start with closed paranthesis
}
else if (s[i] == '(' or s[i] == '{' or s[i] == '[')
{
st.push(s[i]);
}
else if (s[i] == ')')
{
if (!st.empty() and st.top() == '(')
{
st.pop();
}
else
{
ans = false;
break;
}
}
else if (s[i] == '}')
{
if (!st.empty() and st.top() == '{')
{
st.pop();
}
else
{
ans = false;
break;
}
}
else if (s[i] == ']')
{
if (!st.empty() and st.top() == '[')
{
st.pop();
}
else
{
ans = false;
break;
}
}
}
if (!st.empty())
{
return false;
}
return ans;
}
int main()
{
string s = "{[(((())))]}";
if (isValid(s))
{
cout << "Valid!" << endl;
}
else
{
cout << "Not valid!" << endl;
}
return 0;
}
| 20.0375 | 73 | 0.257018 | florayasmin |
0f17e58322f6b16326f34df77343baeffbafe7b5 | 8,362 | cc | C++ | PYTHIA8/pythia8210dev/examples/main04.cc | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | PYTHIA8/pythia8210dev/examples/main04.cc | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | PYTHIA8/pythia8210dev/examples/main04.cc | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | // main04.cc is a part of the PYTHIA event generator.
// Copyright (C) 2015 Torbjorn Sjostrand.
// PYTHIA is licenced under the GNU GPL version 2, see COPYING for details.
// Please respect the MCnet Guidelines, see GUIDELINES for details.
// This is a simple test program.
// It illustrates how to generate and study "total cross section" processes,
// i.e. elastic, single and double diffractive, and the "minimum-bias" rest.
// All input is specified in the main06.cmnd file.
// Note that the "total" cross section does NOT include
// the Coulomb contribution to elastic scattering, as switched on here.
#include "Pythia8/Pythia.h"
using namespace Pythia8;
//==========================================================================
int main() {
// Generator. Shorthand for the event.
Pythia pythia;
Event& event = pythia.event;
// Read in commands from external file.
pythia.readFile("main04.cmnd");
// Extract settings to be used in the main program.
int nEvent = pythia.mode("Main:numberOfEvents");
int nAbort = pythia.mode("Main:timesAllowErrors");
// Initialize.
pythia.init();
// Book histograms: multiplicities and mean transverse momenta.
Hist yChg("rapidity of charged particles; all", 100, -10., 10.);
Hist nChg("number of charged particles; all", 100, -0.5, 799.5);
Hist nChgSD("number of charged particles; single diffraction",
100, -0.5, 799.5);
Hist nChgDD("number of charged particles, double diffractive",
100, -0.5, 799.5);
Hist nChgCD("number of charged particles, central diffractive",
100, -0.5, 799.5);
Hist nChgND("number of charged particles, non-diffractive",
100, -0.5, 799.5);
Hist pTnChg("<pt>(n_charged) all", 100, -0.5, 799.5);
Hist pTnChgSD("<pt>(n_charged) single diffraction", 100, -0.5, 799.5);
Hist pTnChgDD("<pt>(n_charged) double diffraction", 100, -0.5, 799.5);
Hist pTnChgCD("<pt>(n_charged) central diffraction", 100, -0.5, 799.5);
Hist pTnChgND("<pt>(n_charged) non-diffractive ", 100, -0.5, 799.5);
// Book histograms: ditto as function of separate subsystem mass.
Hist mLogInel("log10(mass), by diffractive system", 100, 0., 5.);
Hist nChgmLog("<n_charged>(log10(mass))", 100, 0., 5.);
Hist pTmLog("<pT>_charged>(log10(mass))", 100, 0., 5.);
// Book histograms: elastic/diffractive.
Hist tSpecEl("elastic |t| spectrum", 100, 0., 1.);
Hist tSpecElLog("elastic log10(|t|) spectrum", 100, -5., 0.);
Hist tSpecSD("single diffractive |t| spectrum", 100, 0., 2.);
Hist tSpecDD("double diffractive |t| spectrum", 100, 0., 5.);
Hist tSpecCD("central diffractive |t| spectrum", 100, 0., 5.);
Hist mSpec("diffractive mass spectrum", 100, 0., 100.);
Hist mLogSpec("log10(diffractive mass spectrum)", 100, 0., 4.);
// Book histograms: inelastic nondiffractive.
double pTmax = 20.;
double bMax = 4.;
Hist pTspec("total pT_hard spectrum", 100, 0., pTmax);
Hist pTspecND("nondiffractive pT_hard spectrum", 100, 0., pTmax);
Hist bSpec("b impact parameter spectrum", 100, 0., bMax);
Hist enhanceSpec("b enhancement spectrum", 100, 0., 10.);
Hist number("number of interactions", 100, -0.5, 99.5);
Hist pTb1("pT spectrum for b < 0.5", 100, 0., pTmax);
Hist pTb2("pT spectrum for 0.5 < b < 1", 100, 0., pTmax);
Hist pTb3("pT spectrum for 1 < b < 1.5", 100, 0., pTmax);
Hist pTb4("pT spectrum for 1.5 < b", 100, 0., pTmax);
Hist bpT1("b spectrum for pT < 2", 100, 0., bMax);
Hist bpT2("b spectrum for 2 < pT < 5", 100, 0., bMax);
Hist bpT3("b spectrum for 5 < pT < 15", 100, 0., bMax);
Hist bpT4("b spectrum for 15 < pT", 100, 0., bMax);
// Begin event loop.
int iAbort = 0;
for (int iEvent = 0; iEvent < nEvent; ++iEvent) {
// Generate events. Quit if too many failures.
if (!pythia.next()) {
if (++iAbort < nAbort) continue;
cout << " Event generation aborted prematurely, owing to error!\n";
break;
}
// Extract event classification.
int code = pythia.info.code();
// Charged multiplicity and mean pT: all and by event class.
int nch = 0;
double pTsum = 0.;
for (int i = 1; i < event.size(); ++i)
if (event[i].isFinal() && event[i].isCharged()) {
yChg.fill( event[i].y() );
++nch;
pTsum += event[i].pT();
}
nChg.fill( nch );
if (nch > 0) pTnChg.fill( nch, pTsum/nch);
if (code == 103 || code == 104) {
nChgSD.fill( nch );
if (nch > 0) pTnChgSD.fill( nch, pTsum/nch);
} else if (code == 105) {
nChgDD.fill( nch );
if (nch > 0) pTnChgDD.fill( nch, pTsum/nch);
} else if (code == 106) {
nChgCD.fill( nch );
if (nch > 0) pTnChgCD.fill( nch, pTsum/nch);
} else if (code == 101) {
nChgND.fill( nch );
if (nch > 0) pTnChgND.fill( nch, pTsum/nch);
double mLog = log10( event[0].m() );
mLogInel.fill( mLog );
nChgmLog.fill( mLog, nch );
if (nch > 0) pTmLog.fill( mLog, pTsum / nch );
}
// Charged multiplicity and mean pT: per diffractive system.
for (int iDiff = 0; iDiff < 3; ++iDiff)
if ( (iDiff == 0 && pythia.info.isDiffractiveA())
|| (iDiff == 1 && pythia.info.isDiffractiveB())
|| (iDiff == 2 && pythia.info.isDiffractiveC()) ) {
int ndiff = 0;
double pTdiff = 0.;
int nDoc = (iDiff < 2) ? 4 : 5;
for (int i = nDoc + 1; i < event.size(); ++i)
if (event[i].isFinal() && event[i].isCharged()) {
// Trace back final particle to see which system it comes from.
int k = i;
do k = event[k].mother1();
while (k > nDoc);
if (k == iDiff + 3) {
++ndiff;
pTdiff += event[i].pT();
}
}
// Study diffractive mass spectrum.
double mDiff = event[iDiff+3].m();
double mLog = log10( mDiff);
mLogInel.fill( mLog );
nChgmLog.fill( mLog, ndiff );
if (ndiff > 0) pTmLog.fill( mLog, pTdiff / ndiff );
mSpec.fill( mDiff );
mLogSpec.fill( mLog );
}
// Study pT spectrum of all hard collisions, no distinction.
double pT = pythia.info.pTHat();
pTspec.fill( pT );
// Study t distribution of elastic/diffractive events.
if (code > 101) {
double tAbs = abs(pythia.info.tHat());
if (code == 102) {
tSpecEl.fill(tAbs);
tSpecElLog.fill(log10(tAbs));
}
else if (code == 103 || code == 104) tSpecSD.fill(tAbs);
else if (code == 105) tSpecDD.fill(tAbs);
else if (code == 106) {
double t1Abs = abs( (event[3].p() - event[1].p()).m2Calc() );
double t2Abs = abs( (event[4].p() - event[2].p()).m2Calc() );
tSpecCD.fill(t1Abs);
tSpecCD.fill(t2Abs);
}
// Study nondiffractive inelastic events in (pT, b) space.
} else {
double b = pythia.info.bMPI();
double enhance = pythia.info.enhanceMPI();
int nMPI = pythia.info.nMPI();
pTspecND.fill( pT );
bSpec.fill( b );
enhanceSpec.fill( enhance );
number.fill( nMPI );
if (b < 0.5) pTb1.fill( pT );
else if (b < 1.0) pTb2.fill( pT );
else if (b < 1.5) pTb3.fill( pT );
else pTb4.fill( pT );
if (pT < 2.) bpT1.fill( b );
else if (pT < 5.) bpT2.fill( b );
else if (pT < 15.) bpT3.fill( b );
else bpT4.fill( b );
}
// End of event loop.
}
// Final statistics and histograms.
pythia.stat();
pTnChg /= nChg;
pTnChgSD /= nChgSD;
pTnChgDD /= nChgDD;
pTnChgCD /= nChgCD;
pTnChgND /= nChgND;
nChgmLog /= mLogInel;
pTmLog /= mLogInel;
cout << yChg << nChg << nChgSD << nChgDD << nChgCD << nChgND
<< pTnChg << pTnChgSD << pTnChgDD << pTnChgCD << pTnChgND
<< mLogInel << nChgmLog << pTmLog
<< tSpecEl << tSpecElLog << tSpecSD << tSpecDD << tSpecCD
<< mSpec << mLogSpec
<< pTspec << pTspecND << bSpec << enhanceSpec << number
<< pTb1 << pTb2 << pTb3 << pTb4 << bpT1 << bpT2 << bpT3 << bpT4;
// Done.
return 0;
}
| 38.534562 | 76 | 0.562066 | AllaMaevskaya |
0f18af9a65fc2312a438866126f15c1c54fcaa3d | 822 | cpp | C++ | src/c++/schemas/Icon.cpp | TestingTravis/modioSDK | b15c4442a8acdb4bf690a846232399eaf9fe18f6 | [
"MIT"
] | null | null | null | src/c++/schemas/Icon.cpp | TestingTravis/modioSDK | b15c4442a8acdb4bf690a846232399eaf9fe18f6 | [
"MIT"
] | null | null | null | src/c++/schemas/Icon.cpp | TestingTravis/modioSDK | b15c4442a8acdb4bf690a846232399eaf9fe18f6 | [
"MIT"
] | null | null | null | #include "c++/schemas/Icon.h"
namespace modio
{
void Icon::initialize(ModioIcon modio_icon)
{
if (modio_icon.filename)
this->filename = modio_icon.filename;
if (modio_icon.original)
this->original = modio_icon.original;
if (modio_icon.thumb_64x64)
this->thumb_64x64 = modio_icon.thumb_64x64;
if (modio_icon.thumb_128x128)
this->thumb_128x128 = modio_icon.thumb_128x128;
if (modio_icon.thumb_256x256)
this->thumb_256x256 = modio_icon.thumb_256x256;
}
nlohmann::json toJson(Icon &icon)
{
nlohmann::json icon_json;
icon_json["filename"] = icon.filename;
icon_json["original"] = icon.original;
icon_json["thumb_64x64"] = icon.thumb_64x64;
icon_json["thumb_128x128"] = icon.thumb_128x128;
icon_json["thumb_256x256"] = icon.thumb_256x256;
return icon_json;
}
} // namespace modio
| 25.6875 | 51 | 0.738443 | TestingTravis |
0f190b1df98f2b587a679dfa30b5edea02b9b9bd | 1,608 | hpp | C++ | Clover-Configs/Dell/Dell Inspiron 7520/CLOVER/kexts/10.12/Lilu.kext/Contents/Resources/Headers/plugin_start.hpp | worldlove521/Hackintosh-Installer-University | f5cff36de17bdef0f437a70fb36d182d3ca3a20f | [
"Intel",
"CC-BY-4.0"
] | 4,033 | 2016-11-06T13:36:19.000Z | 2022-03-28T14:47:26.000Z | Clover-Configs/Dell/Dell Inspiron 7520/CLOVER/kexts/10.12/Lilu.kext/Contents/Resources/Headers/plugin_start.hpp | sakoula/Hackintosh-Installer-University | 03fd71ed3f8ec1e01ee45b71835f561263107edf | [
"Intel",
"CC-BY-4.0"
] | 52 | 2018-04-16T23:28:37.000Z | 2021-07-23T07:17:18.000Z | Clover-Configs/Dell/Dell Inspiron 7520/CLOVER/kexts/10.12/Lilu.kext/Contents/Resources/Headers/plugin_start.hpp | sakoula/Hackintosh-Installer-University | 03fd71ed3f8ec1e01ee45b71835f561263107edf | [
"Intel",
"CC-BY-4.0"
] | 1,200 | 2016-12-17T13:46:50.000Z | 2022-03-23T06:08:11.000Z | //
// kern_start.hpp
// AppleALC
//
// Copyright © 2016 vit9696. All rights reserved.
//
#ifndef kern_start_hpp
#define kern_start_hpp
#include <Headers/kern_util.hpp>
#include <Library/LegacyIOService.h>
#include <sys/types.h>
struct PluginConfiguration {
const char *product; // Product name (e.g. xStringify(PRODUCT_NAME))
size_t version; // Product version (e.g. parseModuleVersion(xStringify(MODULE_VERSION)))
uint32_t runmode; // Product supported environments (e.g. LiluAPI::AllowNormal)
const char **disableArg; // Pointer to disabling boot arguments array
size_t disableArgNum; // Number of disabling boot arguments
const char **debugArg; // Pointer to debug boot arguments array
size_t debugArgNum; // Number of debug boot arguments
const char **betaArg; // Pointer to beta boot arguments array
size_t betaArgNum; // Number of beta boot arguments
KernelVersion minKernel; // Minimal required kernel version
KernelVersion maxKernel; // Maximum supported kernel version
void (*pluginStart)(); // Main function
};
#ifndef LILU_CUSTOM_KMOD_INIT
extern PluginConfiguration ADDPR(config);
extern bool ADDPR(startSuccess);
#endif /* LILU_CUSTOM_KMOD_INIT */
#ifndef LILU_CUSTOM_IOKIT_INIT
class EXPORT PRODUCT_NAME : public IOService {
OSDeclareDefaultStructors(PRODUCT_NAME)
public:
IOService *probe(IOService *provider, SInt32 *score) override;
bool start(IOService *provider) override;
void stop(IOService *provider) override;
};
#endif /* LILU_CUSTOM_IOKIT_INIT */
#endif /* kern_start_hpp */
| 30.923077 | 101 | 0.733831 | worldlove521 |
0f19bde272c98ec1052f100c29945eedfa1a65e2 | 2,130 | cpp | C++ | src/Tools/Arguments/Maps/Argument_map_info.cpp | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 1 | 2022-02-17T08:47:47.000Z | 2022-02-17T08:47:47.000Z | src/Tools/Arguments/Maps/Argument_map_info.cpp | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | null | null | null | src/Tools/Arguments/Maps/Argument_map_info.cpp | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 1 | 2022-02-15T23:32:39.000Z | 2022-02-15T23:32:39.000Z | #include <stdexcept>
#include "Tools/Arguments/Maps/Argument_map_info.hpp"
using namespace aff3ct;
using namespace aff3ct::tools;
Argument_map_info
::Argument_map_info()
{ }
Argument_map_info
::Argument_map_info(const Argument_map_info& other)
{
other.clone(*this);
}
Argument_map_info
::~Argument_map_info()
{
clear();
}
Argument_map_info& Argument_map_info
::operator=(const Argument_map_info& other)
{
other.clone(*this);
return *this;
}
void Argument_map_info
::add(const Argument_tag& tags, Argument_type* arg_t, const std::string& doc, const arg_rank rank,
const std::string key)
{
if (tags.size() == 0)
throw std::invalid_argument("No tag has been given ('tag.size()' == 0).");
if (arg_t == nullptr)
throw std::invalid_argument("No argument type has been given ('arg_t' == 0).");
if (exist(tags))
erase(tags);
(*this)[tags] = new Argument_info(arg_t, doc, rank, key);
}
void Argument_map_info
::add_link(const Argument_tag& tag1, const Argument_tag& tag2, bool (*callback)(const void*, const void*))
{
links.add(tag1, tag2, callback);
}
bool Argument_map_info
::has_link(const Argument_tag& tag) const
{
return links.find(tag) != links.size();
}
const Argument_links& Argument_map_info
::get_links() const
{
return links;
}
void Argument_map_info
::erase(const Argument_tag& tags)
{
auto it = this->find(tags);
if (it != this->end())
{
if (it->second != nullptr)
delete it->second;
mother_t::erase(it);
}
}
void Argument_map_info
::clear()
{
for (auto it = this->begin(); it != this->end(); it++)
if (it->second != nullptr)
delete it->second;
mother_t::clear();
}
Argument_map_info* Argument_map_info
::clone() const
{
auto* other = new Argument_map_info();
for (auto it = this->begin(); it != this->end(); it++)
(*other)[it->first] = it->second->clone();
return other;
}
void Argument_map_info
::clone(Argument_map_info& other) const
{
other.clear();
for (auto it = this->begin(); it != this->end(); it++)
other[it->first] = it->second->clone();
}
bool Argument_map_info
::exist(const Argument_tag &tags)
{
return (this->find(tags) != this->end());
}
| 18.849558 | 106 | 0.687793 | WilliamMajor |
0f19e90462d302b3b58cffd4b6117ca0334b212c | 4,450 | cpp | C++ | chapter26/chapter26_ex05.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 170 | 2018-08-10T19:37:16.000Z | 2022-03-29T02:03:30.000Z | chapter26/chapter26_ex05.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 7 | 2018-08-29T15:43:14.000Z | 2021-09-23T21:56:49.000Z | chapter26/chapter26_ex05.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 105 | 2015-05-28T11:52:19.000Z | 2018-07-17T14:11:25.000Z | // Chapter 26, exercise 5: add test to see if binary_search modifies the
// sequence
#include<iostream>
#include<exception>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
//------------------------------------------------------------------------------
// check if value val is in the ordered sequence [first,last)
template<class Iter, class T>
bool binary_search(Iter first, Iter last, const T& val)
{
if (first == last) // empty sequence
return false;
Iter p = first;
advance(p,distance(first,last)/2);
if (*p == val)
return true;
else if (val < *p)
return binary_search(first,p,val);
else { // *p < val
if (distance(p,last) == 1)
return false; // sequence has only 1 element, smaller than value
return binary_search(p,last,val);
}
}
//------------------------------------------------------------------------------
template<class T>
struct Test {
Test() : label(""), val(T()), seq(vector<T>()), res(false) { }
string label;
T val;
vector<T> seq;
bool res;
};
//------------------------------------------------------------------------------
// read sequence of format { { 1 2 3 4 } } into seq
template<class T>
istream& operator>>(istream& is, vector<T>& seq)
{
char ch1;
char ch2;
char ch3;
char ch4;
is >> ch1 >> ch2;
if (!is) return is;
if (ch1!='{' || ch2!='{') {
is.clear(ios_base::failbit);
return is;
}
T i;
while (is >> i)
seq.push_back(i);
is.clear();
is >> ch3 >> ch4;
if (!is) return is;
if (ch3!='}' || ch4!='}') {
is.clear(ios_base::failbit);
return is;
}
return is;
}
//------------------------------------------------------------------------------
// read label, search value and expected result into t - sequence is added
// afterwards
template<class T>
istream& operator>>(istream& is, Test<T>& t)
{
char ch1;
char ch2;
is >> ch1;
if (!is) return is;
if (ch1 != '{') {
is.clear(ios_base::failbit);
return is;
}
string lab;
is >> lab;
if (!is) return is;
if (lab=="{") { // this is the next series of tests
is.unget();
is.putback(ch1); // put both '{' back into the stream
is.clear(ios_base::failbit);
return is;
}
T val;
bool res;
is >> val >> res >> ch2;
if (!is) return is;
if (ch2 != '}') {
is.clear(ios_base::failbit);
return is;
}
t.label = lab;
t.val = val;
t.res = res;
return is;
}
//------------------------------------------------------------------------------
template<class T>
vector<Test<T>> read_tests(istream& is)
{
vector<Test<T>> tests;
vector<T> seq;
while (true) {
is >> seq;
if (!is) break;
Test<T> t;
while (is >> t) {
t.seq = seq;
tests.push_back(t);
}
is.clear();
seq.clear();
}
return tests;
}
//------------------------------------------------------------------------------
template<class T>
int test_all(istream& is)
{
int error_count = 0;
vector<Test<T>> tests = read_tests<T>(is);
for (int i = 0; i<tests.size(); ++i) {
vector<T> seq_pre = tests[i].seq; // to check if modified
bool r = binary_search(tests[i].seq.begin(),
tests[i].seq.end(),
tests[i].val);
if (r != tests[i].res) {
cout << "failure: test " << tests[i].label << " binary_search: "
<< tests[i].seq.size() << " elements, val==" << tests[i].val
<< " -> " << tests[i].res << '\n';
++error_count;
}
if (seq_pre != tests[i].seq) {
cout << "failure: test " << tests[i].label
<< " had its sequence modified\n";
++error_count;
}
}
return error_count;
}
//------------------------------------------------------------------------------
int main()
try
{
// sequences of integers
string ifname1 = "pics_and_txt/chapter26_ex04_in.txt";
ifstream ifs1(ifname1);
if (!ifs1) throw runtime_error("can't open " + ifname1);
int errors = test_all<int>(ifs1);
cout << "number of errors in " << ifname1 << ": " << errors << '\n';
}
catch (exception& e) {
cerr << "exception: " << e.what() << '\n';
}
catch (...) {
cerr << "exception\n";
}
| 25.141243 | 80 | 0.456854 | TingeOGinge |
0f1fbeef72f98f3cf71e39d12810388ebfa643a4 | 262 | hpp | C++ | include/chopper/detail_bin_prefixes.hpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | include/chopper/detail_bin_prefixes.hpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | include/chopper/detail_bin_prefixes.hpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
constexpr std::string_view hibf_prefix{"HIGH_LEVEL_IBF"};
constexpr std::string_view merged_bin_prefix{"MERGED_BIN"};
constexpr std::string_view split_bin_prefix{"SPLIT_BIN"};
constexpr size_t merged_bin_prefix_length{merged_bin_prefix.size()};
| 26.2 | 68 | 0.824427 | Felix-Droop |
0f22b9fbce5bb8e3ee5680c035854cf382b15802 | 1,043 | cpp | C++ | src/main.cpp | kondrak/quake_bsp_viewer_legacyOpenGL | e64a2a74fbda91fdd26a9027098e087bbd5cd8b3 | [
"MIT"
] | 4 | 2015-11-29T15:38:42.000Z | 2021-09-12T00:19:28.000Z | src/main.cpp | kondrak/quake_bsp_viewer_legacyOpenGL | e64a2a74fbda91fdd26a9027098e087bbd5cd8b3 | [
"MIT"
] | null | null | null | src/main.cpp | kondrak/quake_bsp_viewer_legacyOpenGL | e64a2a74fbda91fdd26a9027098e087bbd5cd8b3 | [
"MIT"
] | null | null | null | #include "Application.hpp"
#include "InputHandlers.hpp"
#include "renderer/RenderContext.hpp"
// keep the render context and application object global
RenderContext g_renderContext;
Application g_application;
int main(int argc, char **argv)
{
// initialize SDL
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) < 0 )
{
return 1;
}
g_renderContext.Init("Quake BSP Viewer", 100, 100, 1024, 768);
g_application.Initialize(g_renderContext.width, g_renderContext.height);
SDL_ShowCursor( SDL_DISABLE );
// initialize Glee
if (!GLeeInit())
{
return 1;
}
g_application.OnStart( argc, argv );
Uint32 last = SDL_GetTicks();
while( g_application.Running() )
{
Uint32 now = SDL_GetTicks();
processEvents();
g_application.OnUpdate(float(now - last) / 1000.f);
g_application.OnRender();
SDL_GL_SwapWindow( g_renderContext.window );
last = now;
}
g_application.OnTerminate();
SDL_Quit();
return 0;
} | 20.057692 | 76 | 0.645254 | kondrak |
0f2a9491a7af6a8948061edc4e6b30a0cbe03bb6 | 2,093 | cpp | C++ | src/CppParser/CppParser.cpp | P-i-N/CppSharp | c36145b29dd5e8ae273557c2a31fd4d8a7a044be | [
"MIT"
] | null | null | null | src/CppParser/CppParser.cpp | P-i-N/CppSharp | c36145b29dd5e8ae273557c2a31fd4d8a7a044be | [
"MIT"
] | null | null | null | src/CppParser/CppParser.cpp | P-i-N/CppSharp | c36145b29dd5e8ae273557c2a31fd4d8a7a044be | [
"MIT"
] | null | null | null | /************************************************************************
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/
#include "CppParser.h"
#include "Parser.h"
#include <clang/Basic/Version.inc>
namespace CppSharp { namespace CppParser {
CppParserOptions::CppParserOptions()
: ASTContext(0)
, toolSetToUse(0)
, noStandardIncludes(false)
, noBuiltinIncludes(false)
, microsoftMode(false)
, verbose(false)
, unityBuild(false)
, skipPrivateDeclarations(true)
, skipLayoutInfo(false)
, skipFunctionBodies(true)
, clangVersion(CLANG_VERSION_STRING)
{
}
CppParserOptions::~CppParserOptions() {}
std::string CppParserOptions::getClangVersion() { return clangVersion; }
DEF_VECTOR_STRING(CppParserOptions, Arguments)
DEF_VECTOR_STRING(CppParserOptions, SourceFiles)
DEF_VECTOR_STRING(CppParserOptions, IncludeDirs)
DEF_VECTOR_STRING(CppParserOptions, SystemIncludeDirs)
DEF_VECTOR_STRING(CppParserOptions, Defines)
DEF_VECTOR_STRING(CppParserOptions, Undefines)
DEF_VECTOR_STRING(CppParserOptions, SupportedStdTypes)
ParserResult::ParserResult()
: targetInfo(0)
{
}
ParserResult::ParserResult(const ParserResult& rhs)
: kind(rhs.kind)
, Diagnostics(rhs.Diagnostics)
, Libraries(rhs.Libraries)
, targetInfo(rhs.targetInfo)
{}
ParserResult::~ParserResult()
{
for (auto Library : Libraries)
{
delete Library;
}
}
DEF_VECTOR(ParserResult, ParserDiagnostic, Diagnostics)
DEF_VECTOR(ParserResult, NativeLibrary*, Libraries)
LinkerOptions::LinkerOptions() {}
LinkerOptions::~LinkerOptions() {}
DEF_VECTOR_STRING(LinkerOptions, Arguments)
DEF_VECTOR_STRING(LinkerOptions, LibraryDirs)
DEF_VECTOR_STRING(LinkerOptions, Libraries)
ParserDiagnostic::ParserDiagnostic() {}
ParserDiagnostic::ParserDiagnostic(const ParserDiagnostic& rhs)
: fileName(rhs.fileName)
, message(rhs.message)
, level(rhs.level)
, lineNumber(rhs.lineNumber)
, columnNumber(rhs.columnNumber)
{}
ParserDiagnostic::~ParserDiagnostic() {}
} } | 25.216867 | 73 | 0.705686 | P-i-N |
0f2e97cbb920c58e4c5b35e8fc5285d493fa007c | 1,477 | cpp | C++ | Starters 14/TUPCOUNT.cpp | Jks08/CodeChef | a8aec8a563c441176a36b8581031764e99f09833 | [
"MIT"
] | 1 | 2021-09-17T13:10:04.000Z | 2021-09-17T13:10:04.000Z | Starters 14/TUPCOUNT.cpp | Jks08/CodeChef | a8aec8a563c441176a36b8581031764e99f09833 | [
"MIT"
] | null | null | null | Starters 14/TUPCOUNT.cpp | Jks08/CodeChef | a8aec8a563c441176a36b8581031764e99f09833 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define PI 3.14159265358979323846
#define ll long long int
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
const int T = 1e6 + 5;
long long phi[T];
gp_hash_table<long long, long long> mp;
int sz, spf[T], prime[T];
void f() {
memset(spf, 0, sizeof spf);
phi[1] = 1; sz = 0;
for (int i = 2; i < T; i++) {
if (spf[i] == 0) phi[i] = i - 1, spf[i] = i, prime[sz++] = i;
for (int j = 0; j < sz && i * prime[j] < T && prime[j] <= spf[i]; j++) {
spf[i * prime[j]] = prime[j];
if (i % prime[j] == 0) phi[i * prime[j]] = phi[i] * prime[j];
else phi[i * prime[j]] = phi[i] * (prime[j] - 1);
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int test = 1;
cin>>test;
f();
while(test--){
ll n;
cin>>n;
ll ans1=0,ans2=0;
for(int i=2;i<=n;i++){
ll temp=n/i;
temp*=(phi[i]);
ans2+=temp;
temp*=(n/i);
ans1+=temp;
}
ans1*=4LL;
ans1+=n;
ans2*=4LL;
ans2+=n;
ll ans=(ans1+ans2)/2;
cout<<ans<<" ";
cout<<"\n";
}
return 0;
}
| 24.616667 | 82 | 0.411645 | Jks08 |
0f31a22df5f7e480bfeabf09840fb4a0026b9aeb | 1,143 | hpp | C++ | src/mbgl/programs/hillshade_prepare_program.hpp | finnpetersen/mapbox-gl-native3 | 1a7ed9a822db3476ff4f6b5d4d4e3151046c7353 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/programs/hillshade_prepare_program.hpp | finnpetersen/mapbox-gl-native3 | 1a7ed9a822db3476ff4f6b5d4d4e3151046c7353 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/programs/hillshade_prepare_program.hpp | finnpetersen/mapbox-gl-native3 | 1a7ed9a822db3476ff4f6b5d4d4e3151046c7353 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #pragma once
#include <mbgl/programs/program.hpp>
#include <mbgl/programs/attributes.hpp>
#include <mbgl/programs/uniforms.hpp>
#include <mbgl/shaders/hillshade_prepare.hpp>
#include <mbgl/util/geometry.hpp>
namespace mbgl {
namespace uniforms {
MBGL_DEFINE_UNIFORM_VECTOR(uint16_t, 2, u_dimension);
} // namespace uniforms
class HillshadePrepareProgram : public Program<
shaders::hillshade_prepare,
gl::Triangle,
gl::Attributes<
attributes::a_pos,
attributes::a_texture_pos>,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_dimension,
uniforms::u_zoom,
uniforms::u_image>,
style::Properties<>> {
public:
using Program::Program;
static LayoutVertex layoutVertex(Point<int16_t> p, Point<uint16_t> t) {
return LayoutVertex {
{{
p.x,
p.y
}},
{{
t.x,
t.y
}}
};
}
};
using HillshadePrepareLayoutVertex = HillshadePrepareProgram::LayoutVertex;
using HillshadePrepareAttributes = HillshadePrepareProgram::Attributes;
} // namespace mbgl
| 23.8125 | 75 | 0.634296 | finnpetersen |
0f33eff2849001dbb9c22a2d4a861efede0505f7 | 7,347 | cpp | C++ | examples/Meters/ExampleUIMeters.cpp | noisecode3/DPF | 86a621bfd86922a49ce593fec2a618a1e0cc6ef3 | [
"0BSD"
] | 372 | 2015-02-09T15:05:16.000Z | 2022-03-30T15:35:17.000Z | examples/Meters/ExampleUIMeters.cpp | noisecode3/DPF | 86a621bfd86922a49ce593fec2a618a1e0cc6ef3 | [
"0BSD"
] | 324 | 2015-10-05T14:30:41.000Z | 2022-03-30T07:06:04.000Z | examples/Meters/ExampleUIMeters.cpp | noisecode3/DPF | 86a621bfd86922a49ce593fec2a618a1e0cc6ef3 | [
"0BSD"
] | 89 | 2015-02-20T11:26:50.000Z | 2022-02-11T00:07:27.000Z | /*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2019 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoUI.hpp"
START_NAMESPACE_DISTRHO
/**
We need the Color class from DGL.
*/
using DGL_NAMESPACE::Color;
/**
Smooth meters a bit.
*/
static const float kSmoothMultiplier = 3.0f;
// -----------------------------------------------------------------------------------------------------------
class ExampleUIMeters : public UI
{
public:
ExampleUIMeters()
: UI(128, 512),
// default color is green
fColor(93, 231, 61),
// which is value 0
fColorValue(0),
// init meter values to 0
fOutLeft(0.0f),
fOutRight(0.0f)
{
setGeometryConstraints(32, 128, false);
}
protected:
/* --------------------------------------------------------------------------------------------------------
* DSP/Plugin Callbacks */
/**
A parameter has changed on the plugin side.
This is called by the host to inform the UI about parameter changes.
*/
void parameterChanged(uint32_t index, float value) override
{
switch (index)
{
case 0: // color
updateColor(std::round(value));
break;
case 1: // out-left
value = (fOutLeft * kSmoothMultiplier + value) / (kSmoothMultiplier + 1.0f);
/**/ if (value < 0.001f) value = 0.0f;
else if (value > 0.999f) value = 1.0f;
if (fOutLeft != value)
{
fOutLeft = value;
repaint();
}
break;
case 2: // out-right
value = (fOutRight * kSmoothMultiplier + value) / (kSmoothMultiplier + 1.0f);
/**/ if (value < 0.001f) value = 0.0f;
else if (value > 0.999f) value = 1.0f;
if (fOutRight != value)
{
fOutRight = value;
repaint();
}
break;
}
}
/**
A state has changed on the plugin side.
This is called by the host to inform the UI about state changes.
*/
void stateChanged(const char*, const char*) override
{
// nothing here
}
/* --------------------------------------------------------------------------------------------------------
* Widget Callbacks */
/**
The NanoVG drawing function.
*/
void onNanoDisplay() override
{
static const Color kColorBlack(0, 0, 0);
static const Color kColorRed(255, 0, 0);
static const Color kColorYellow(255, 255, 0);
// get meter values
const float outLeft(fOutLeft);
const float outRight(fOutRight);
// tell DSP side to reset meter values
setState("reset", "");
// useful vars
const float halfWidth = static_cast<float>(getWidth())/2;
const float redYellowHeight = static_cast<float>(getHeight())*0.2f;
const float yellowBaseHeight = static_cast<float>(getHeight())*0.4f;
const float baseBaseHeight = static_cast<float>(getHeight())*0.6f;
// create gradients
Paint fGradient1 = linearGradient(0.0f, 0.0f, 0.0f, redYellowHeight, kColorRed, kColorYellow);
Paint fGradient2 = linearGradient(0.0f, redYellowHeight, 0.0f, yellowBaseHeight, kColorYellow, fColor);
// paint left meter
beginPath();
rect(0.0f, 0.0f, halfWidth-1.0f, redYellowHeight);
fillPaint(fGradient1);
fill();
closePath();
beginPath();
rect(0.0f, redYellowHeight-0.5f, halfWidth-1.0f, yellowBaseHeight);
fillPaint(fGradient2);
fill();
closePath();
beginPath();
rect(0.0f, redYellowHeight+yellowBaseHeight-1.5f, halfWidth-1.0f, baseBaseHeight);
fillColor(fColor);
fill();
closePath();
// paint left black matching output level
beginPath();
rect(0.0f, 0.0f, halfWidth-1.0f, (1.0f-outLeft)*getHeight());
fillColor(kColorBlack);
fill();
closePath();
// paint right meter
beginPath();
rect(halfWidth+1.0f, 0.0f, halfWidth-2.0f, redYellowHeight);
fillPaint(fGradient1);
fill();
closePath();
beginPath();
rect(halfWidth+1.0f, redYellowHeight-0.5f, halfWidth-2.0f, yellowBaseHeight);
fillPaint(fGradient2);
fill();
closePath();
beginPath();
rect(halfWidth+1.0f, redYellowHeight+yellowBaseHeight-1.5f, halfWidth-2.0f, baseBaseHeight);
fillColor(fColor);
fill();
closePath();
// paint right black matching output level
beginPath();
rect(halfWidth+1.0f, 0.0f, halfWidth-2.0f, (1.0f-outRight)*getHeight());
fillColor(kColorBlack);
fill();
closePath();
}
/**
Mouse press event.
This UI will change color when clicked.
*/
bool onMouse(const MouseEvent& ev) override
{
// Test for left-clicked + pressed first.
if (ev.button != 1 || ! ev.press)
return false;
const int newColor(fColorValue == 0 ? 1 : 0);
updateColor(newColor);
setParameterValue(0, newColor);
return true;
}
// -------------------------------------------------------------------------------------------------------
private:
/**
Color and its matching parameter value.
*/
Color fColor;
int fColorValue;
/**
Meter values.
These are the parameter outputs from the DSP side.
*/
float fOutLeft, fOutRight;
/**
Update color if needed.
*/
void updateColor(const int color)
{
if (fColorValue == color)
return;
fColorValue = color;
switch (color)
{
case METER_COLOR_GREEN:
fColor = Color(93, 231, 61);
break;
case METER_COLOR_BLUE:
fColor = Color(82, 238, 248);
break;
}
repaint();
}
/**
Set our UI class as non-copyable and add a leak detector just in case.
*/
DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ExampleUIMeters)
};
/* ------------------------------------------------------------------------------------------------------------
* UI entry point, called by DPF to create a new UI instance. */
UI* createUI()
{
return new ExampleUIMeters();
}
// -----------------------------------------------------------------------------------------------------------
END_NAMESPACE_DISTRHO
| 28.699219 | 117 | 0.531782 | noisecode3 |
0f38f548e204fdbca419c5fe7608d207710a24f6 | 1,110 | cpp | C++ | ijk/source/ijk-math/common/ijk-real/_cpp/ijkQuaternionSwizzle.cpp | dbuckstein/ijk | 959f7292d6465e9d2c888ea94bc724c8ee03597e | [
"Apache-2.0"
] | 1 | 2020-05-31T21:14:49.000Z | 2020-05-31T21:14:49.000Z | ijk/source/ijk-math/common/ijk-real/_cpp/ijkQuaternionSwizzle.cpp | dbuckstein/ijk | 959f7292d6465e9d2c888ea94bc724c8ee03597e | [
"Apache-2.0"
] | null | null | null | ijk/source/ijk-math/common/ijk-real/_cpp/ijkQuaternionSwizzle.cpp | dbuckstein/ijk | 959f7292d6465e9d2c888ea94bc724c8ee03597e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020-2021 Daniel S. Buckstein
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.
*/
/*
ijk: an open-source, cross-platform, light-weight,
c-based rendering framework
By Daniel S. Buckstein
ijkQuaternionSwizzle.cpp
C++ testing source definitions for quaternion types.
*/
#include "ijk/ijk-math/ijk-real/ijkQuaternion.h"
//-----------------------------------------------------------------------------
extern "C" {
void ijkMathTestQuaternionSwizzle();
}
void ijkMathTestQuaternionSwizzle()
{
typedef f32 base, * basev;
typedef float type;
typedef fquat tquat;
typedef fdualquat tdualquat;
}
| 26.428571 | 79 | 0.704505 | dbuckstein |
0f4221ff72c9047c31af1c3ad9015b1e9f075fd5 | 3,178 | cpp | C++ | source/agent/analytics/videoGstPipeline/GstInternalIn.cpp | andreasunterhuber/owt-server | 128b83714361c0b543ec44fc841c9094f4267633 | [
"Apache-2.0"
] | 2 | 2021-02-05T04:57:58.000Z | 2021-04-11T08:36:19.000Z | source/agent/analytics/videoGstPipeline/GstInternalIn.cpp | andreasunterhuber/owt-server | 128b83714361c0b543ec44fc841c9094f4267633 | [
"Apache-2.0"
] | 3 | 2020-07-09T06:48:40.000Z | 2020-09-17T03:04:30.000Z | source/agent/analytics/videoGstPipeline/GstInternalIn.cpp | andreasunterhuber/owt-server | 128b83714361c0b543ec44fc841c9094f4267633 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) <2019> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#include "GstInternalIn.h"
#include <gst/gst.h>
#include <stdio.h>
DEFINE_LOGGER(GstInternalIn, "GstInternalIn");
GstInternalIn::GstInternalIn(GstAppSrc *data, unsigned int minPort, unsigned int maxPort)
{
m_transport.reset(new owt_base::RawTransport<owt_base::TCP>(this));
if (minPort > 0 && minPort <= maxPort) {
m_transport->listenTo(minPort, maxPort);
} else {
m_transport->listenTo(0);
}
appsrc = data;
m_needKeyFrame = true;
m_start = false;
}
GstInternalIn::~GstInternalIn()
{
m_transport->close();
}
unsigned int GstInternalIn::getListeningPort()
{
return m_transport->getListeningPort();
}
void GstInternalIn::setPushData(bool status){
m_start = status;
}
void GstInternalIn::onFeedback(const owt_base::FeedbackMsg& msg)
{
char sendBuffer[512];
sendBuffer[0] = owt_base::TDT_FEEDBACK_MSG;
memcpy(&sendBuffer[1], reinterpret_cast<char*>(const_cast<owt_base::FeedbackMsg*>(&msg)), sizeof(owt_base::FeedbackMsg));
m_transport->sendData((char*)sendBuffer, sizeof(owt_base::FeedbackMsg) + 1);
}
void GstInternalIn::onTransportData(char* buf, int len)
{
if(!m_start) {
ELOG_INFO("Not start yet, stop pushing data to appsrc\n");
pthread_t tid;
tid = pthread_self();
return;
}
owt_base::Frame* frame = nullptr;
switch (buf[0]) {
case owt_base::TDT_MEDIA_FRAME:{
frame = reinterpret_cast<owt_base::Frame*>(buf + 1);
if(frame->additionalInfo.video.width == 1) {
ELOG_DEBUG("Not a valid video frame\n");
break;
}
frame->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(owt_base::Frame));
size_t payloadLength = frame->length;
size_t headerLength = sizeof(frame);
GstBuffer *buffer;
GstFlowReturn ret;
GstMapInfo map;
if (m_needKeyFrame) {
if (frame->additionalInfo.video.isKeyFrame) {
m_needKeyFrame = false;
} else {
ELOG_DEBUG("Request key frame\n");
owt_base::FeedbackMsg msg {.type = owt_base::VIDEO_FEEDBACK, .cmd = owt_base::REQUEST_KEY_FRAME};
onFeedback(msg);
return;
}
}
/* Create a new empty buffer */
buffer = gst_buffer_new_and_alloc (payloadLength + headerLength);
gst_buffer_map(buffer, &map, GST_MAP_WRITE);
memcpy(map.data, frame, headerLength);
memcpy(map.data + headerLength, frame->payload, payloadLength);
gst_buffer_unmap(buffer, &map);
g_signal_emit_by_name(appsrc, "push-buffer", buffer, &ret);
gst_buffer_unref(buffer);
if (ret != GST_FLOW_OK) {
/* We got some error, stop sending data */
ELOG_DEBUG("Push buffer to appsrc got error\n");
m_start=false;
}
break;
}
default:
break;
}
}
| 29.425926 | 125 | 0.58905 | andreasunterhuber |
0f42bc0e33dc6fa79792373d243d26e951ac609e | 3,658 | cc | C++ | Mu2eUtilities/src/TriggerResultsNavigator.cc | AndrewEdmonds11/Offline | 99d525aa55a477fb3f21826ac817224c25cda040 | [
"Apache-2.0"
] | 1 | 2021-06-25T00:00:12.000Z | 2021-06-25T00:00:12.000Z | Mu2eUtilities/src/TriggerResultsNavigator.cc | shadowbehindthebread/Offline | 57b5055641a4c626a695f3d83237c79758956b6a | [
"Apache-2.0"
] | null | null | null | Mu2eUtilities/src/TriggerResultsNavigator.cc | shadowbehindthebread/Offline | 57b5055641a4c626a695f3d83237c79758956b6a | [
"Apache-2.0"
] | 1 | 2020-05-27T22:33:52.000Z | 2020-05-27T22:33:52.000Z | #include "fhiclcpp/ParameterSet.h"
#include "fhiclcpp/ParameterSetRegistry.h"
#include "Mu2eUtilities/inc/TriggerResultsNavigator.hh"
#include <iostream>
#include <iomanip>
namespace mu2e {
TriggerResultsNavigator::TriggerResultsNavigator(const art::TriggerResults* trigResults):
_trigResults(trigResults){
auto const id = trigResults->parameterSetID();
auto const& pset = fhicl::ParameterSetRegistry::get(id);
//set the vector<string> with the names of the tirgger_paths
_trigPathsNames = pset.get<std::vector<std::string>>("trigger_paths");
//loop over trigResults to fill the map <string, unsigned int)
for (unsigned int i=0; i< _trigPathsNames.size(); ++i){
_trigMap.insert(std::pair<std::string, unsigned int>(_trigPathsNames[i], i));
}
}
size_t
TriggerResultsNavigator::findTrigPath(std::string const& name) const
{
return find(_trigMap, name);
}
size_t
TriggerResultsNavigator::find(std::map<std::string, unsigned int> const& posmap, std::string const& name) const
{
auto const pos = posmap.find(name);
if (pos == posmap.cend()) {
return posmap.size();
} else {
return pos->second;
}
}
// Has ith path accepted the event?
bool
TriggerResultsNavigator::accepted(std::string const& name) const
{
size_t index = findTrigPath(name);
return _trigResults->accept(index);
}
bool
TriggerResultsNavigator::wasrun(std::string const& name) const
{
size_t index = findTrigPath(name);
return _trigResults->wasrun(index);
}
std::vector<std::string>
TriggerResultsNavigator::triggerModules(std::string const& name) const{
std::vector<std::string> modules;
for ( auto const& i : fhicl::ParameterSetRegistry::get() ){
auto const id = i.first;
if (i.second.has_key(name)){
auto const &pset = fhicl::ParameterSetRegistry::get(id);
modules = pset.get<std::vector<std::string>>(name);
break;
}
}
return modules;
}
unsigned
TriggerResultsNavigator::indexLastModule(std::string const& name) const{
size_t index = findTrigPath(name);
return _trigResults->index(index);
}
std::string
TriggerResultsNavigator::nameLastModule (std::string const& name) const{
unsigned indexLast = indexLastModule(name);
std::vector<std::string> modulesVec = triggerModules(name);
if ( modulesVec.size() == 0) {
std::string nn = "PATH "+name+" NOT FOUND";
std::cout << "[TriggerResultsNavigator::nameLastModule] " << nn << std::endl;
return nn;
}else {
return modulesVec[indexLast];
}
}
art::hlt::HLTState
TriggerResultsNavigator::state(std::string const& name) const{
size_t index = findTrigPath(name);
return _trigResults->state(index);
}
void
TriggerResultsNavigator::print() const {
std::cout << "TriggerResultsNaviogator Map" << std::endl;
std::cout << "//------------------------------------------//" << std::endl;
std::cout << "// trig_pathName id accepted //" << std::endl;
std::cout << "//------------------------------------------//" << std::endl;
for (unsigned int i=0; i< _trigPathsNames.size(); ++i){
std::string name = _trigPathsNames[i];
size_t index = findTrigPath(name);
bool good = accepted(name);
std::cout << std::right;
std::cout <<"//"<<std::setw(24) << name << std::setw(2) << index << (good == true ? 1:0) << "//"<< std::endl;
// %24s %2li %i //\n", name.c_str(), index, good == true ? 1:0);
}
}
}
| 32.087719 | 115 | 0.613997 | AndrewEdmonds11 |
0f4464122c8fb96f11f5246107cf80e97a5b8aec | 24,624 | cpp | C++ | clang-tools-extra/clangd/unittests/SelectionTests.cpp | hborla/llvm-project | 6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7 | [
"Apache-2.0"
] | null | null | null | clang-tools-extra/clangd/unittests/SelectionTests.cpp | hborla/llvm-project | 6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7 | [
"Apache-2.0"
] | null | null | null | clang-tools-extra/clangd/unittests/SelectionTests.cpp | hborla/llvm-project | 6590b7ca0bb9c01e9a362bcbc5500d41d21bd6e7 | [
"Apache-2.0"
] | null | null | null | //===-- SelectionTests.cpp - ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Annotations.h"
#include "Selection.h"
#include "SourceCode.h"
#include "TestTU.h"
#include "support/TestTracer.h"
#include "clang/AST/Decl.h"
#include "llvm/Support/Casting.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace clang {
namespace clangd {
namespace {
using ::testing::ElementsAreArray;
using ::testing::UnorderedElementsAreArray;
// Create a selection tree corresponding to a point or pair of points.
// This uses the precisely-defined createRight semantics. The fuzzier
// createEach is tested separately.
SelectionTree makeSelectionTree(const StringRef MarkedCode, ParsedAST &AST) {
Annotations Test(MarkedCode);
switch (Test.points().size()) {
case 1: { // Point selection.
unsigned Offset = cantFail(positionToOffset(Test.code(), Test.point()));
return SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
Offset, Offset);
}
case 2: // Range selection.
return SelectionTree::createRight(
AST.getASTContext(), AST.getTokens(),
cantFail(positionToOffset(Test.code(), Test.points()[0])),
cantFail(positionToOffset(Test.code(), Test.points()[1])));
default:
ADD_FAILURE() << "Expected 1-2 points for selection.\n" << MarkedCode;
return SelectionTree::createRight(AST.getASTContext(), AST.getTokens(), 0u,
0u);
}
}
Range nodeRange(const SelectionTree::Node *N, ParsedAST &AST) {
if (!N)
return Range{};
const SourceManager &SM = AST.getSourceManager();
const LangOptions &LangOpts = AST.getLangOpts();
StringRef Buffer = SM.getBufferData(SM.getMainFileID());
if (llvm::isa_and_nonnull<TranslationUnitDecl>(N->ASTNode.get<Decl>()))
return Range{Position{}, offsetToPosition(Buffer, Buffer.size())};
auto FileRange =
toHalfOpenFileRange(SM, LangOpts, N->ASTNode.getSourceRange());
assert(FileRange && "We should be able to get the File Range");
return Range{
offsetToPosition(Buffer, SM.getFileOffset(FileRange->getBegin())),
offsetToPosition(Buffer, SM.getFileOffset(FileRange->getEnd()))};
}
std::string nodeKind(const SelectionTree::Node *N) {
return N ? N->kind() : "<null>";
}
std::vector<const SelectionTree::Node *> allNodes(const SelectionTree &T) {
std::vector<const SelectionTree::Node *> Result = {&T.root()};
for (unsigned I = 0; I < Result.size(); ++I) {
const SelectionTree::Node *N = Result[I];
Result.insert(Result.end(), N->Children.begin(), N->Children.end());
}
return Result;
}
// Returns true if Common is a descendent of Root.
// Verifies nothing is selected above Common.
bool verifyCommonAncestor(const SelectionTree::Node &Root,
const SelectionTree::Node *Common,
StringRef MarkedCode) {
if (&Root == Common)
return true;
if (Root.Selected)
ADD_FAILURE() << "Selected nodes outside common ancestor\n" << MarkedCode;
bool Seen = false;
for (const SelectionTree::Node *Child : Root.Children)
if (verifyCommonAncestor(*Child, Common, MarkedCode)) {
if (Seen)
ADD_FAILURE() << "Saw common ancestor twice\n" << MarkedCode;
Seen = true;
}
return Seen;
}
TEST(SelectionTest, CommonAncestor) {
struct Case {
// Selection is between ^marks^.
// common ancestor marked with a [[range]].
const char *Code;
const char *CommonAncestorKind;
};
Case Cases[] = {
{
R"cpp(
template <typename T>
int x = [[T::^U::]]ccc();
)cpp",
"NestedNameSpecifierLoc",
},
{
R"cpp(
struct AAA { struct BBB { static int ccc(); };};
int x = AAA::[[B^B^B]]::ccc();
)cpp",
"RecordTypeLoc",
},
{
R"cpp(
struct AAA { struct BBB { static int ccc(); };};
int x = AAA::[[B^BB^]]::ccc();
)cpp",
"RecordTypeLoc",
},
{
R"cpp(
struct AAA { struct BBB { static int ccc(); };};
int x = [[AAA::BBB::c^c^c]]();
)cpp",
"DeclRefExpr",
},
{
R"cpp(
struct AAA { struct BBB { static int ccc(); };};
int x = [[AAA::BBB::cc^c(^)]];
)cpp",
"CallExpr",
},
{
R"cpp(
void foo() { [[if (1^11) { return; } else {^ }]] }
)cpp",
"IfStmt",
},
{
R"cpp(
int x(int);
#define M(foo) x(foo)
int a = 42;
int b = M([[^a]]);
)cpp",
"DeclRefExpr",
},
{
R"cpp(
void foo();
#define CALL_FUNCTION(X) X()
void bar() { CALL_FUNCTION([[f^o^o]]); }
)cpp",
"DeclRefExpr",
},
{
R"cpp(
void foo();
#define CALL_FUNCTION(X) X()
void bar() { [[CALL_FUNC^TION(fo^o)]]; }
)cpp",
"CallExpr",
},
{
R"cpp(
void foo();
#define CALL_FUNCTION(X) X()
void bar() { [[C^ALL_FUNC^TION(foo)]]; }
)cpp",
"CallExpr",
},
{
R"cpp(
void foo();
#^define CALL_FUNCTION(X) X(^)
void bar() { CALL_FUNCTION(foo); }
)cpp",
nullptr,
},
{
R"cpp(
void foo();
#define CALL_FUNCTION(X) X()
void bar() { CALL_FUNCTION(foo^)^; }
)cpp",
nullptr,
},
{
R"cpp(
namespace ns {
#if 0
void fo^o() {}
#endif
}
)cpp",
nullptr,
},
{
R"cpp(
struct S { S(const char*); };
[[S s ^= "foo"]];
)cpp",
// The AST says a CXXConstructExpr covers the = sign in C++14.
// But we consider CXXConstructExpr to only own brackets.
// (It's not the interesting constructor anyway, just S(&&)).
"VarDecl",
},
{
R"cpp(
struct S { S(const char*); };
[[S ^s = "foo"]];
)cpp",
"VarDecl",
},
{
R"cpp(
[[^void]] (*S)(int) = nullptr;
)cpp",
"BuiltinTypeLoc",
},
{
R"cpp(
[[void (*S)^(int)]] = nullptr;
)cpp",
"FunctionProtoTypeLoc",
},
{
R"cpp(
[[void (^*S)(int)]] = nullptr;
)cpp",
"PointerTypeLoc",
},
{
R"cpp(
[[void (*^S)(int) = nullptr]];
)cpp",
"VarDecl",
},
{
R"cpp(
[[void ^(*S)(int)]] = nullptr;
)cpp",
"ParenTypeLoc",
},
{
R"cpp(
struct S {
int foo() const;
int bar() { return [[f^oo]](); }
};
)cpp",
"MemberExpr", // Not implicit CXXThisExpr, or its implicit cast!
},
{
R"cpp(
auto lambda = [](const char*){ return 0; };
int x = lambda([["y^"]]);
)cpp",
"StringLiteral", // Not DeclRefExpr to operator()!
},
{
R"cpp(
struct Foo {};
struct Bar : [[v^ir^tual private Foo]] {};
)cpp",
"CXXBaseSpecifier",
},
{
R"cpp(
struct Foo {};
struct Bar : private [[Fo^o]] {};
)cpp",
"RecordTypeLoc",
},
{
R"cpp(
struct Foo {};
struct Bar : [[Fo^o]] {};
)cpp",
"RecordTypeLoc",
},
// Point selections.
{"void foo() { [[^foo]](); }", "DeclRefExpr"},
{"void foo() { [[f^oo]](); }", "DeclRefExpr"},
{"void foo() { [[fo^o]](); }", "DeclRefExpr"},
{"void foo() { [[foo^()]]; }", "CallExpr"},
{"void foo() { [[foo^]] (); }", "DeclRefExpr"},
{"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
{"int x = [[42]]^;", "IntegerLiteral"},
// Ignores whitespace, comments, and semicolons in the selection.
{"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
// Tricky case: FunctionTypeLoc in FunctionDecl has a hole in it.
{"[[^void]] foo();", "BuiltinTypeLoc"},
{"[[void foo^()]];", "FunctionProtoTypeLoc"},
{"[[^void foo^()]];", "FunctionDecl"},
{"[[void ^foo()]];", "FunctionDecl"},
// Tricky case: two VarDecls share a specifier.
{"[[int ^a]], b;", "VarDecl"},
{"[[int a, ^b]];", "VarDecl"},
// Tricky case: CXXConstructExpr wants to claim the whole init range.
{
R"cpp(
struct X { X(int); };
class Y {
X x;
Y() : [[^x(4)]] {}
};
)cpp",
"CXXCtorInitializer", // Not the CXXConstructExpr!
},
// Tricky case: anonymous struct is a sibling of the VarDecl.
{"[[st^ruct {int x;}]] y;", "CXXRecordDecl"},
{"[[struct {int x;} ^y]];", "VarDecl"},
{"struct {[[int ^x]];} y;", "FieldDecl"},
// Tricky case: nested ArrayTypeLocs have the same token range.
{"const int x = 1, y = 2; int array[^[[x]]][10][y];", "DeclRefExpr"},
{"const int x = 1, y = 2; int array[x][10][^[[y]]];", "DeclRefExpr"},
{"const int x = 1, y = 2; int array[x][^[[10]]][y];", "IntegerLiteral"},
{"const int x = 1, y = 2; [[i^nt]] array[x][10][y];", "BuiltinTypeLoc"},
{"void func(int x) { int v_array[^[[x]]][10]; }", "DeclRefExpr"},
{"int (*getFunc([[do^uble]]))(int);", "BuiltinTypeLoc"},
// FIXME: the AST has no location info for qualifiers.
{"const [[a^uto]] x = 42;", "AutoTypeLoc"},
{"[[co^nst auto x = 42]];", "VarDecl"},
{"^", nullptr},
{"void foo() { [[foo^^]] (); }", "DeclRefExpr"},
// FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
// This doesn't happen now; the RAV doesn't traverse a node containing ;.
{"int x = 42;^", nullptr},
// Common ancestor is logically TUDecl, but we never return that.
{"^int x; int y;^", nullptr},
// Node types that have caused problems in the past.
{"template <typename T> void foo() { [[^T]] t; }",
"TemplateTypeParmTypeLoc"},
// No crash
{
R"cpp(
template <class T> struct Foo {};
template <[[template<class> class /*cursor here*/^U]]>
struct Foo<U<int>*> {};
)cpp",
"TemplateTemplateParmDecl"},
// Foreach has a weird AST, ensure we can select parts of the range init.
// This used to fail, because the DeclStmt for C claimed the whole range.
{
R"cpp(
struct Str {
const char *begin();
const char *end();
};
Str makeStr(const char*);
void loop() {
for (const char C : [[mak^eStr("foo"^)]])
;
}
)cpp",
"CallExpr"},
// User-defined literals are tricky: is 12_i one token or two?
// For now we treat it as one, and the UserDefinedLiteral as a leaf.
{
R"cpp(
struct Foo{};
Foo operator""_ud(unsigned long long);
Foo x = [[^12_ud]];
)cpp",
"UserDefinedLiteral"},
{
R"cpp(
int a;
decltype([[^a]] + a) b;
)cpp",
"DeclRefExpr"},
{"[[decltype^(1)]] b;", "DecltypeTypeLoc"}, // Not the VarDecl.
// decltype(auto) is an AutoTypeLoc!
{"[[de^cltype(a^uto)]] a = 1;", "AutoTypeLoc"},
// Objective-C nullability attributes.
{
R"cpp(
@interface I{}
@property(nullable) [[^I]] *x;
@end
)cpp",
"ObjCInterfaceTypeLoc"},
{
R"cpp(
@interface I{}
- (void)doSomething:(nonnull [[i^d]])argument;
@end
)cpp",
"TypedefTypeLoc"},
// Objective-C OpaqueValueExpr/PseudoObjectExpr has weird ASTs.
// Need to traverse the contents of the OpaqueValueExpr to the POE,
// and ensure we traverse only the syntactic form of the PseudoObjectExpr.
{
R"cpp(
@interface I{}
@property(retain) I*x;
@property(retain) I*y;
@end
void test(I *f) { [[^f]].x.y = 0; }
)cpp",
"DeclRefExpr"},
{
R"cpp(
@interface I{}
@property(retain) I*x;
@property(retain) I*y;
@end
void test(I *f) { [[f.^x]].y = 0; }
)cpp",
"ObjCPropertyRefExpr"},
// Examples with implicit properties.
{
R"cpp(
@interface I{}
-(int)foo;
@end
int test(I *f) { return 42 + [[^f]].foo; }
)cpp",
"DeclRefExpr"},
{
R"cpp(
@interface I{}
-(int)foo;
@end
int test(I *f) { return 42 + [[f.^foo]]; }
)cpp",
"ObjCPropertyRefExpr"},
{"struct foo { [[int has^h<:32:>]]; };", "FieldDecl"},
{"struct foo { [[op^erator int()]]; };", "CXXConversionDecl"},
{"struct foo { [[^~foo()]]; };", "CXXDestructorDecl"},
// FIXME: The following to should be class itself instead.
{"struct foo { [[fo^o(){}]] };", "CXXConstructorDecl"},
{R"cpp(
struct S1 { void f(); };
struct S2 { S1 * operator->(); };
void test(S2 s2) {
s2[[-^>]]f();
}
)cpp",
"DeclRefExpr"}, // DeclRefExpr to the "operator->" method.
// Template template argument.
{R"cpp(
template <typename> class Vector {};
template <template <typename> class Container> class A {};
A<[[V^ector]]> a;
)cpp",
"TemplateArgumentLoc"},
// Attributes
{R"cpp(
void f(int * __attribute__(([[no^nnull]])) );
)cpp",
"NonNullAttr"},
{R"cpp(
// Digraph syntax for attributes to avoid accidental annotations.
class <:[gsl::Owner([[in^t]])]:> X{};
)cpp",
"BuiltinTypeLoc"},
// This case used to crash - AST has a null Attr
{R"cpp(
@interface I
[[@property(retain, nonnull) <:[My^Object2]:> *x]]; // error-ok
@end
)cpp",
"ObjCPropertyDecl"},
{R"cpp(
typedef int Foo;
enum Bar : [[Fo^o]] {};
)cpp",
"TypedefTypeLoc"},
{R"cpp(
typedef int Foo;
enum Bar : [[Fo^o]];
)cpp",
"TypedefTypeLoc"},
};
for (const Case &C : Cases) {
trace::TestTracer Tracer;
Annotations Test(C.Code);
TestTU TU;
TU.Code = std::string(Test.code());
TU.ExtraArgs.push_back("-xobjective-c++");
auto AST = TU.build();
auto T = makeSelectionTree(C.Code, AST);
EXPECT_EQ("TranslationUnitDecl", nodeKind(&T.root())) << C.Code;
if (Test.ranges().empty()) {
// If no [[range]] is marked in the example, there should be no selection.
EXPECT_FALSE(T.commonAncestor()) << C.Code << "\n" << T;
EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
testing::IsEmpty());
} else {
// If there is an expected selection, common ancestor should exist
// with the appropriate node type.
EXPECT_EQ(C.CommonAncestorKind, nodeKind(T.commonAncestor()))
<< C.Code << "\n"
<< T;
// Convert the reported common ancestor to a range and verify it.
EXPECT_EQ(nodeRange(T.commonAncestor(), AST), Test.range())
<< C.Code << "\n"
<< T;
// Check that common ancestor is reachable on exactly one path from root,
// and no nodes outside it are selected.
EXPECT_TRUE(verifyCommonAncestor(T.root(), T.commonAncestor(), C.Code))
<< C.Code;
EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
ElementsAreArray({0}));
}
}
}
// Regression test: this used to match the injected X, not the outer X.
TEST(SelectionTest, InjectedClassName) {
const char *Code = "struct ^X { int x; };";
auto AST = TestTU::withCode(Annotations(Code).code()).build();
auto T = makeSelectionTree(Code, AST);
ASSERT_EQ("CXXRecordDecl", nodeKind(T.commonAncestor())) << T;
auto *D = dyn_cast<CXXRecordDecl>(T.commonAncestor()->ASTNode.get<Decl>());
EXPECT_FALSE(D->isInjectedClassName());
}
TEST(SelectionTree, Metrics) {
const char *Code = R"cpp(
// error-ok: testing behavior on recovery expression
int foo();
int foo(int, int);
int x = fo^o(42);
)cpp";
auto AST = TestTU::withCode(Annotations(Code).code()).build();
trace::TestTracer Tracer;
auto T = makeSelectionTree(Code, AST);
EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
ElementsAreArray({1}));
EXPECT_THAT(Tracer.takeMetric("selection_recovery_type", "C++"),
ElementsAreArray({1}));
}
// FIXME: Doesn't select the binary operator node in
// #define FOO(X) X + 1
// int a, b = [[FOO(a)]];
TEST(SelectionTest, Selected) {
// Selection with ^marks^.
// Partially selected nodes marked with a [[range]].
// Completely selected nodes marked with a $C[[range]].
const char *Cases[] = {
R"cpp( int abc, xyz = [[^ab^c]]; )cpp",
R"cpp( int abc, xyz = [[a^bc^]]; )cpp",
R"cpp( int abc, xyz = $C[[^abc^]]; )cpp",
R"cpp(
void foo() {
[[if ([[1^11]]) $C[[{
$C[[return]];
}]] else [[{^
}]]]]
char z;
}
)cpp",
R"cpp(
template <class T>
struct unique_ptr {};
void foo(^$C[[unique_ptr<$C[[unique_ptr<$C[[int]]>]]>]]^ a) {}
)cpp",
R"cpp(int a = [[5 >^> 1]];)cpp",
R"cpp(
#define ECHO(X) X
ECHO(EC^HO($C[[int]]) EC^HO(a));
)cpp",
R"cpp( $C[[^$C[[int]] a^]]; )cpp",
R"cpp( $C[[^$C[[int]] a = $C[[5]]^]]; )cpp",
};
for (const char *C : Cases) {
Annotations Test(C);
auto AST = TestTU::withCode(Test.code()).build();
auto T = makeSelectionTree(C, AST);
std::vector<Range> Complete, Partial;
for (const SelectionTree::Node *N : allNodes(T))
if (N->Selected == SelectionTree::Complete)
Complete.push_back(nodeRange(N, AST));
else if (N->Selected == SelectionTree::Partial)
Partial.push_back(nodeRange(N, AST));
EXPECT_THAT(Complete, UnorderedElementsAreArray(Test.ranges("C"))) << C;
EXPECT_THAT(Partial, UnorderedElementsAreArray(Test.ranges())) << C;
}
}
TEST(SelectionTest, PathologicalPreprocessor) {
const char *Case = R"cpp(
#define MACRO while(1)
void test() {
#include "Expand.inc"
br^eak;
}
)cpp";
Annotations Test(Case);
auto TU = TestTU::withCode(Test.code());
TU.AdditionalFiles["Expand.inc"] = "MACRO\n";
auto AST = TU.build();
EXPECT_THAT(*AST.getDiagnostics(), ::testing::IsEmpty());
auto T = makeSelectionTree(Case, AST);
EXPECT_EQ("BreakStmt", T.commonAncestor()->kind());
EXPECT_EQ("WhileStmt", T.commonAncestor()->Parent->kind());
}
TEST(SelectionTest, IncludedFile) {
const char *Case = R"cpp(
void test() {
#include "Exp^and.inc"
break;
}
)cpp";
Annotations Test(Case);
auto TU = TestTU::withCode(Test.code());
TU.AdditionalFiles["Expand.inc"] = "while(1)\n";
auto AST = TU.build();
auto T = makeSelectionTree(Case, AST);
EXPECT_EQ(nullptr, T.commonAncestor());
}
TEST(SelectionTest, MacroArgExpansion) {
// If a macro arg is expanded several times, we only consider the first one
// selected.
const char *Case = R"cpp(
int mul(int, int);
#define SQUARE(X) mul(X, X);
int nine = SQUARE(^3);
)cpp";
Annotations Test(Case);
auto AST = TestTU::withCode(Test.code()).build();
auto T = makeSelectionTree(Case, AST);
EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind());
EXPECT_TRUE(T.commonAncestor()->Selected);
// Verify that the common assert() macro doesn't suffer from this.
// (This is because we don't associate the stringified token with the arg).
Case = R"cpp(
void die(const char*);
#define assert(x) (x ? (void)0 : die(#x))
void foo() { assert(^42); }
)cpp";
Test = Annotations(Case);
AST = TestTU::withCode(Test.code()).build();
T = makeSelectionTree(Case, AST);
EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind());
}
TEST(SelectionTest, Implicit) {
const char *Test = R"cpp(
struct S { S(const char*); };
int f(S);
int x = f("^");
)cpp";
auto AST = TestTU::withCode(Annotations(Test).code()).build();
auto T = makeSelectionTree(Test, AST);
const SelectionTree::Node *Str = T.commonAncestor();
EXPECT_EQ("StringLiteral", nodeKind(Str)) << "Implicit selected?";
EXPECT_EQ("ImplicitCastExpr", nodeKind(Str->Parent));
EXPECT_EQ("CXXConstructExpr", nodeKind(Str->Parent->Parent));
EXPECT_EQ(Str, &Str->Parent->Parent->ignoreImplicit())
<< "Didn't unwrap " << nodeKind(&Str->Parent->Parent->ignoreImplicit());
EXPECT_EQ("CXXConstructExpr", nodeKind(&Str->outerImplicit()));
}
TEST(SelectionTest, CreateAll) {
llvm::Annotations Test("int$unique^ a=1$ambiguous^+1; $empty^");
auto AST = TestTU::withCode(Test.code()).build();
unsigned Seen = 0;
SelectionTree::createEach(
AST.getASTContext(), AST.getTokens(), Test.point("ambiguous"),
Test.point("ambiguous"), [&](SelectionTree T) {
// Expect to see the right-biased tree first.
if (Seen == 0) {
EXPECT_EQ("BinaryOperator", nodeKind(T.commonAncestor()));
} else if (Seen == 1) {
EXPECT_EQ("IntegerLiteral", nodeKind(T.commonAncestor()));
}
++Seen;
return false;
});
EXPECT_EQ(2u, Seen);
Seen = 0;
SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
Test.point("ambiguous"), Test.point("ambiguous"),
[&](SelectionTree T) {
++Seen;
return true;
});
EXPECT_EQ(1u, Seen) << "Return true --> stop iterating";
Seen = 0;
SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
Test.point("unique"), Test.point("unique"),
[&](SelectionTree T) {
++Seen;
return false;
});
EXPECT_EQ(1u, Seen) << "no ambiguity --> only one tree";
Seen = 0;
SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
Test.point("empty"), Test.point("empty"),
[&](SelectionTree T) {
EXPECT_FALSE(T.commonAncestor());
++Seen;
return false;
});
EXPECT_EQ(1u, Seen) << "empty tree still created";
Seen = 0;
SelectionTree::createEach(AST.getASTContext(), AST.getTokens(),
Test.point("unique"), Test.point("ambiguous"),
[&](SelectionTree T) {
++Seen;
return false;
});
EXPECT_EQ(1u, Seen) << "one tree for nontrivial selection";
}
TEST(SelectionTest, DeclContextIsLexical) {
llvm::Annotations Test("namespace a { void $1^foo(); } void a::$2^foo();");
auto AST = TestTU::withCode(Test.code()).build();
{
auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
Test.point("1"), Test.point("1"));
EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
}
{
auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
Test.point("2"), Test.point("2"));
EXPECT_TRUE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
}
}
} // namespace
} // namespace clangd
} // namespace clang
| 31.731959 | 80 | 0.515513 | hborla |
0f454bfc8ec10cb942fabe7006a52f259e290b27 | 944 | cpp | C++ | coast/modules/Security/Base64WDRenderer.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/Security/Base64WDRenderer.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/Security/Base64WDRenderer.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "Base64WDRenderer.h"
#include "Tracer.h"
#include "Base64.h"
//---- Base64WDRenderer ---------------------------------------------------------------
RegisterRenderer(Base64WDRenderer);
Base64WDRenderer::Base64WDRenderer(const char *name) : Renderer(name) { }
Base64WDRenderer::~Base64WDRenderer() { }
void Base64WDRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config)
{
StartTrace(Base64WDRenderer.RenderAll);
String clearText, b64EncodedText;
Renderer::RenderOnString(clearText, ctx, config);
Base64(fName).DoEncode(b64EncodedText, clearText);
reply << b64EncodedText;
}
| 32.551724 | 102 | 0.717161 | zer0infinity |
0f46ef60058b018543fd088fcdedae365ee2ad5c | 1,951 | hpp | C++ | src/PlayerManager.hpp | josephl70/OpenFusion | c1200e94c5f933bffb5885b1a83b9dab5ceb1db1 | [
"MIT"
] | 1 | 2020-08-20T17:43:10.000Z | 2020-08-20T17:43:10.000Z | src/PlayerManager.hpp | josephl70/OpenFusion_VS | c1200e94c5f933bffb5885b1a83b9dab5ceb1db1 | [
"MIT"
] | null | null | null | src/PlayerManager.hpp | josephl70/OpenFusion_VS | c1200e94c5f933bffb5885b1a83b9dab5ceb1db1 | [
"MIT"
] | null | null | null | #pragma once
#include "Player.hpp"
#include "CNProtocol.hpp"
#include "CNStructs.hpp"
#include "CNShardServer.hpp"
#include <map>
#include <list>
struct WarpLocation;
struct PlayerView {
std::list<CNSocket*> viewable;
std::list<int32_t> viewableNPCs;
Player *plr;
uint64_t lastHeartbeat;
};
namespace PlayerManager {
extern std::map<CNSocket*, PlayerView> players;
void init();
void addPlayer(CNSocket* key, Player plr);
void removePlayer(CNSocket* key);
void updatePlayerPosition(CNSocket* sock, int X, int Y, int Z);
std::list<CNSocket*> getNearbyPlayers(int X, int Y, int dist);
void enterPlayer(CNSocket* sock, CNPacketData* data);
void loadPlayer(CNSocket* sock, CNPacketData* data);
void movePlayer(CNSocket* sock, CNPacketData* data);
void stopPlayer(CNSocket* sock, CNPacketData* data);
void jumpPlayer(CNSocket* sock, CNPacketData* data);
void jumppadPlayer(CNSocket* sock, CNPacketData* data);
void launchPlayer(CNSocket* sock, CNPacketData* data);
void ziplinePlayer(CNSocket* sock, CNPacketData* data);
void movePlatformPlayer(CNSocket* sock, CNPacketData* data);
void moveSlopePlayer(CNSocket* sock, CNPacketData* data);
void gotoPlayer(CNSocket* sock, CNPacketData* data);
void setSpecialPlayer(CNSocket* sock, CNPacketData* data);
void heartbeatPlayer(CNSocket* sock, CNPacketData* data);
void revivePlayer(CNSocket* sock, CNPacketData* data);
void exitGame(CNSocket* sock, CNPacketData* data);
void setSpecialSwitchPlayer(CNSocket* sock, CNPacketData* data);
void changePlayerGuide(CNSocket *sock, CNPacketData *data);
void enterPlayerVehicle(CNSocket* sock, CNPacketData* data);
void exitPlayerVehicle(CNSocket* sock, CNPacketData* data);
Player *getPlayer(CNSocket* key);
WarpLocation getRespawnPoint(Player *plr);
bool isAccountInUse(int accountId);
void exitDuplicate(int accountId);
}
| 33.067797 | 68 | 0.732445 | josephl70 |
0f50f1363313589315c0ea5ed4cc9c3899526682 | 3,024 | hpp | C++ | CaffeMex_V28/include/caffe/layers/batch_norm_layer.hpp | yyht/OSM_CAA_WeightedContrastiveLoss | a8911b9fc1c951a2caec26a16473a8f5bfb2005f | [
"BSD-3-Clause"
] | 196 | 2018-07-07T14:22:37.000Z | 2022-03-19T06:21:11.000Z | CaffeMex_V28/include/caffe/layers/batch_norm_layer.hpp | yyht/OSM_CAA_WeightedContrastiveLoss | a8911b9fc1c951a2caec26a16473a8f5bfb2005f | [
"BSD-3-Clause"
] | 2 | 2018-07-09T09:19:09.000Z | 2018-07-17T15:08:49.000Z | lib/caffe-action/include/caffe/layers/batch_norm_layer.hpp | ParrtZhang/Optical-Flow-Guided-Feature | 07d4501a29002ee7821c38c1820e4a64c1acf6e8 | [
"MIT"
] | 48 | 2018-07-10T02:11:20.000Z | 2022-02-04T14:26:30.000Z | #ifndef CAFFE_BATCHNORM_LAYER_HPP_
#define CAFFE_BATCHNORM_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Normalizes the input to have 0-mean and/or unit (1) variance across
* the batch.
*
* This layer computes Batch Normalization as described in [1]. For each channel
* in the data (i.e. axis 1), it subtracts the mean and divides by the variance,
* where both statistics are computed across both spatial dimensions and across
* the different examples in the batch.
*
* By default, during training time, the network is computing global
* mean/variance statistics via a running average, which is then used at test
* time to allow deterministic outputs for each input. You can manually toggle
* whether the network is accumulating or using the statistics via the
* use_global_stats option. For reference, these statistics are kept in the
* layer's three blobs: (0) mean, (1) variance, and (2) moving average factor.
*
* Note that the original paper also included a per-channel learned bias and
* scaling factor. To implement this in Caffe, define a `ScaleLayer` configured
* with `bias_term: true` after each `BatchNormLayer` to handle both the bias
* and scaling factor.
*
* [1] S. Ioffe and C. Szegedy, "Batch Normalization: Accelerating Deep Network
* Training by Reducing Internal Covariate Shift." arXiv preprint
* arXiv:1502.03167 (2015).
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class BatchNormLayer : public Layer<Dtype> {
public:
explicit BatchNormLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "BatchNorm"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
Blob<Dtype> mean_, variance_, temp_, x_norm_;
bool use_global_stats_;
Dtype moving_average_fraction_;
int channels_;
Dtype eps_;
// extra temporarary variables is used to carry out sums/broadcasting
// using BLAS
Blob<Dtype> batch_sum_multiplier_;
Blob<Dtype> num_by_chans_;
Blob<Dtype> spatial_sum_multiplier_;
};
} // namespace caffe
#endif // CAFFE_BATCHNORM_LAYER_HPP_ | 38.769231 | 80 | 0.73578 | yyht |
0f546baf0ef75979d68c16736c687bbf207055b7 | 4,819 | cpp | C++ | logos/lib/utility.cpp | LogosNetwork/logos-core | 6b155539a734efefb8f649a761d044b5f267a51a | [
"BSD-2-Clause"
] | 3 | 2020-01-17T18:05:19.000Z | 2021-12-29T04:21:59.000Z | logos/lib/utility.cpp | LogosNetwork/logos-core | 6b155539a734efefb8f649a761d044b5f267a51a | [
"BSD-2-Clause"
] | null | null | null | logos/lib/utility.cpp | LogosNetwork/logos-core | 6b155539a734efefb8f649a761d044b5f267a51a | [
"BSD-2-Clause"
] | 2 | 2020-12-22T05:51:53.000Z | 2021-06-08T00:27:46.000Z | #include <logos/lib/utility.hpp>
#include <sstream>
#include <iomanip>
std::string logos::unicode_to_hex(std::string const & input)
{
static const char* const lut = "0123456789abcdef";
size_t len = input.length();
std::string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i)
{
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
return output;
}
std::string logos::hex_to_unicode(std::string const & input)
{
std::string output;
assert((input.length() % 2) == 0);
size_t cnt = input.length() / 2;
output.reserve(cnt);
for (size_t i = 0; cnt > i; ++i) {
uint32_t s = 0;
std::stringstream ss;
ss << std::hex << input.substr(i * 2, 2);
ss >> s;
output.push_back(static_cast<unsigned char>(s));
}
return output;
}
bool logos::read (logos::stream & stream_a, Rational & value)
{
Rational::int_type n;
Rational::int_type d;
auto do_read = [&stream_a](auto & val)
{
for(auto i = 0; i < (256 / 8); ++i)
{
uint8_t byte;
if(read(stream_a, byte))
{
return true;
}
Rational::int_type word = byte;
word <<= 8 * i;
val |= word;
}
return false;
};
if(do_read(n))
{
return true;
}
if(do_read(d))
{
return true;
}
value.assign(n, d);
return false;
}
uint64_t logos::write (logos::stream & stream_a, const Rational & value)
{
uint64_t bytes = 0;
for(auto val : {value.numerator(), value.denominator()})
{
for(auto i = 0; i < (256 / 8); ++i)
{
auto byte = static_cast<uint8_t> (val & static_cast<uint8_t> (0xff));
val >>= 8;
bytes += write(stream_a, byte);
}
}
return bytes;
}
template<typename U>
static bool ReadUnion(logos::stream & stream_a, U & value)
{
auto amount_read (stream_a.sgetn (value.bytes.data(), value.bytes.size()));
return amount_read != value.bytes.size();
}
template<typename U>
static uint64_t WriteUnion (logos::stream & stream_a, U const & value)
{
auto amount_written (stream_a.sputn (value.bytes.data(), value.bytes.size()));
assert (amount_written == value.bytes.size());
return amount_written;
}
bool logos::read (logos::stream & stream_a, uint128_union & value)
{
return ReadUnion(stream_a, value);
}
uint64_t logos::write (logos::stream & stream_a, uint128_union const & value)
{
return WriteUnion(stream_a, value);
}
bool logos::read (logos::stream & stream_a, uint256_union & value)
{
return ReadUnion(stream_a, value);
}
uint64_t logos::write (logos::stream & stream_a, uint256_union const & value)
{
return WriteUnion(stream_a, value);
}
bool logos::read (logos::stream & stream_a, uint512_union & value)
{
return ReadUnion(stream_a, value);
}
uint64_t logos::write (logos::stream & stream_a, uint512_union const & value)
{
return WriteUnion(stream_a, value);
}
uint16_t bits_to_bytes_ceiling(uint16_t x)
{
return (x + 7) / 8;
}
bool logos::read (logos::stream & stream_a, std::vector<bool> & value)
{
uint16_t n_bits_le = 0;
bool error = logos::read(stream_a, n_bits_le);
if(error)
{
return error;
}
auto n_bits = le16toh(n_bits_le);
auto to_read = bits_to_bytes_ceiling(n_bits);
std::vector<uint8_t> bytes(to_read);
auto amount_read (stream_a.sgetn (bytes.data(), bytes.size()));
if(amount_read != to_read)
{
return true;
}
for( auto b : bytes)
{
//std::cout << (int)b << std::endl;
for(int i = 0; i < 8; ++i)
{
if(n_bits-- == 0)
return false;
uint8_t mask = 1u<<i;
if(mask & b)
value.push_back(true);
else
value.push_back(false);
}
}
return false;
}
uint64_t logos::write (logos::stream & stream_a, const std::vector<bool> & value)
{
uint16_t n_bits = value.size();
auto n_bits_le = htole16(n_bits);
auto amount_written (stream_a.sputn ((uint8_t *)&n_bits_le, sizeof(uint16_t)));
std::vector<uint8_t> buf;
uint8_t one_byte = 0;
int cmp = 0;
for ( auto b : value)
{
one_byte = one_byte | ((b ? 1 : 0) << cmp++);
if(cmp == 8)
{
//std::cout << (int)one_byte << std::endl;
buf.push_back(one_byte);
cmp = 0;
one_byte = 0;
}
}
if(cmp != 0)
{
//std::cout << (int)one_byte << std::endl;
buf.push_back(one_byte);
}
amount_written += stream_a.sputn (buf.data(), buf.size());
return amount_written;
}
| 22.624413 | 83 | 0.566715 | LogosNetwork |
0f5a027569fc7b1c7542d632313e827cdccdebae | 1,230 | cpp | C++ | src/BaseApplication.cpp | DavidAzouz29/AIENetworking | 0ea9eb45cc56f5dc0e4f07bc09a75ef677a4563e | [
"MIT"
] | null | null | null | src/BaseApplication.cpp | DavidAzouz29/AIENetworking | 0ea9eb45cc56f5dc0e4f07bc09a75ef677a4563e | [
"MIT"
] | null | null | null | src/BaseApplication.cpp | DavidAzouz29/AIENetworking | 0ea9eb45cc56f5dc0e4f07bc09a75ef677a4563e | [
"MIT"
] | null | null | null | #include "BaseApplication.h"
//#include "gl_core_4_4.h"
#include <iostream>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
bool BaseApplication::createWindow(const char* title, int width, int height) {
if (glfwInit() == GL_FALSE)
return false;
m_window = glfwCreateWindow(width, height, title, nullptr, nullptr);
if (m_window == nullptr) {
glfwTerminate();
return false;
}
glfwMakeContextCurrent(m_window);
if (ogl_LoadFunctions() == ogl_LOAD_FAILED) {
glfwDestroyWindow(m_window);
glfwTerminate();
return false;
}
glfwSetWindowSizeCallback(m_window, [](GLFWwindow*, int w, int h){ glViewport(0, 0, w, h); });
auto major = ogl_GetMajorVersion();
auto minor = ogl_GetMinorVersion();
std::cout << "GL: " << major << "." << minor << std::endl;
glClearColor(0.25f, 0.25f, 0.25f, 1);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
return true;
}
GLvoid BaseApplication::destroyWindow() {
glfwDestroyWindow(m_window);
glfwTerminate();
}
GLvoid BaseApplication::run() {
double prevTime = glfwGetTime();
double currTime = 0;
while (currTime = glfwGetTime(),
update((float)(currTime - prevTime))) {
glfwPollEvents();
draw();
glfwSwapBuffers(m_window);
prevTime = currTime;
}
} | 20.5 | 95 | 0.695935 | DavidAzouz29 |
0f5af1202f29c98b17f23e9bb3ea911767f7f38c | 699 | cpp | C++ | solution/day2/part2.cpp | Desheen/AdventOfCode-2018 | 4d633f51ba5f906c365bb8ef2512465dea941d24 | [
"BSD-3-Clause"
] | 1 | 2018-12-02T20:17:59.000Z | 2018-12-02T20:17:59.000Z | solution/day2/part2.cpp | Desheen/AdventOfCode-2018 | 4d633f51ba5f906c365bb8ef2512465dea941d24 | [
"BSD-3-Clause"
] | null | null | null | solution/day2/part2.cpp | Desheen/AdventOfCode-2018 | 4d633f51ba5f906c365bb8ef2512465dea941d24 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <fstream>
#include <algorithm>
#include <map>
#include <vector>
#include <unordered_map>
std::vector<short> match( std::string& s1 , std::string& s2) {
std::vector<short> v;
for( int i = 0 ; i < s1.size() ; ++i)
{
if( s1[i] != s2[i] )
{
v.push_back(i);
}
}
return v;
}
int
main( int argc , char**argv )
{
std::ifstream file;
file.open("input",std::ifstream::in);
std::string line;
std::vector<std::string> data;
while(std::getline(file,line))
{
data.push_back(line);
}
for( auto itr1 : data )
{
for( auto itr2 : data)
{
auto c = match(itr1,itr2);
if( c.size() == 1 ) {
std::cout << itr1 << std::endl;
}
}
}
return 0;
} | 15.533333 | 62 | 0.579399 | Desheen |
0f5dd9d7e3504cf34006c04dd41e55bd4660698e | 9,291 | cpp | C++ | game/debug/log.cpp | edwinkepler/chessman | f9ffb902ce91c15726b8716665707d178ac734e1 | [
"MIT"
] | null | null | null | game/debug/log.cpp | edwinkepler/chessman | f9ffb902ce91c15726b8716665707d178ac734e1 | [
"MIT"
] | 14 | 2017-08-28T15:37:20.000Z | 2017-09-20T09:15:43.000Z | game/debug/log.cpp | edwinkepler/chessman | f9ffb902ce91c15726b8716665707d178ac734e1 | [
"MIT"
] | null | null | null | #include "log.hpp"
namespace Debug
{
Log& Log::info(string _s) {
if(f_verbose_stdout) {
cout << _s;
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << _s;
file_log.close();
}
return *this;
}
Log& Log::info(int _i) {
if(f_verbose_stdout) {
cout << _i;
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << _i;
file_log.close();
}
return *this;
}
Log& Log::n() {
if(f_verbose_stdout) {
cout << endl;
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "\n";
file_log.close();
}
return *this;
}
Log& Log::t() {
if(f_verbose_stdout) {
cout << "\t";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "\t";
file_log.close();
}
return *this;
}
Log& Log::t2() {
if(f_verbose_stdout) {
cout << "\t\t";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "\t\t";
file_log.close();
}
return *this;
}
Log& Log::l(int _l) {
if(f_verbose_stdout) {
cout << "[" << _l << "] ";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "[" << _l << "] ";
file_log.close();
}
return *this;
}
Log& Log::func_head(string _f) {
if(f_verbose_stdout) {
cout << "[" << _f << "][START]\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "[" << _f << "][START]\n";
file_log.close();
}
return *this;
}
Log& Log::func_foot(string _f) {
if(f_verbose_stdout) {
cout << "[" << _f << "][DONE]\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "[" << _f << "][DONE]\n";
file_log.close();
}
return *this;
}
Log& Log::func_foot(string _f, int _n) {
if(f_verbose_stdout) {
cout << "[" << _f << "][DONE in " << _n << "ms]\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "[" << _f << "][DONE in " << _n << "ms]\n";
file_log.close();
}
return *this;
}
Log& Log::piece_func_head(string _f, int _t, int _o, const pair<int, int>& _c) {
if(f_verbose_stdout) {
cout << "\t\t[" << _f << "][type: "
<< _t << ", owner: "
<< _o << ", at: ("
<< _c.first << ", " << _c.second << ")]\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "\t\t[" << _f << "][type: "
<< _t << ", owner: "
<< _o << ", at: ("
<< _c.first << ", " << _c.second << ")]\n";
file_log.close();
}
return *this;
}
Log& Log::board_func_head(string _f, const pair<int, int>& _c) {
if(f_verbose_stdout) {
cout << "\t\t[" << _f << "][coords: ("
<< _c.first << ", " << _c.second << ")]\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "\t\t[" << _f << "][coords: ("
<< _c.first << ", " << _c.second << ")]\n";
file_log.close();
}
return *this;
}
Log& Log::board_func_head(string _f,
const pair<int, int>& _c1,
const pair<int, int>& _c2)
{
if(f_verbose_stdout) {
cout << "\t\t[" << _f << "][from: ("
<< _c1.first << ", " << _c1.second << "), to: ("
<< _c2.first << ", " << _c2.second << ")]\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "\t\t[" << _f << "][from: ("
<< _c1.first << ", " << _c1.second << "), to: ("
<< _c2.first << ", " << _c2.second << ")]\n";
file_log.close();
}
return *this;
}
void Log::test_func_head(const string _t) {
if(f_verbose_stdout) {
cout << "<--------- " << _t << " BEGIN ----------\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "<--------- " << _t << " BEGIN ----------\n";
file_log.close();
}
}
void Log::test_func_foot(const string _t) {
if(f_verbose_stdout) {
cout << "---------- " << _t << " END ----------->\n\n";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "---------- " << _t << " END ----------->\n\n";
file_log.close();
}
}
Log& Log::datetime_stamp() {
if(f_verbose_stdout) {
auto t = time(nullptr);
auto tm = *localtime(&t);
cout << "[" << put_time(&tm, "%d-%m-%Y %H:%M:%S") << "]";
}
if(f_verbose_file) {
auto t = time(nullptr);
auto tm = *localtime(&t);
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "[" << put_time(&tm, "%d-%m-%Y %H:%M:%S") << "]";
file_log.close();
}
return *this;
}
Log& Log::coords(const pair<int, int>& _c) {
if(f_verbose_stdout) {
cout << "coords: (" << _c.first << ", " << _c.second << ")";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "coords: (" << _c.first << ", " << _c.second << ")";
file_log.close();
}
return *this;
}
Log& Log::coords(const pair<int, int>& _c1, const pair<int, int>& _c2) {
if(f_verbose_stdout) {
cout << "coords: (" << _c1.first << ", " << _c1.second << "), ("
<< _c2.first << ", " << _c2.second << ")";
}
if(f_verbose_file) {
ofstream file_log;
file_log.open(
s_file_name,
ios::binary |
ios_base::app |
ios_base::out);
file_log << "coords: (" << _c1.first << ", " << _c1.second << "), ("
<< _c2.first << ", " << _c2.second << ")";
file_log.close();
}
return *this;
}
Log& Log::operator<<(string s) {
info(s);
return *this;
}
Log& Log::operator<<(int i) {
info(i);
return *this;
}
void Log::verbose_stdout(bool _f) {
f_verbose_stdout = _f;
}
void Log::verbose_file(bool _f) {
f_verbose_file = _f;
}
}
| 28.069486 | 84 | 0.380691 | edwinkepler |
0f630b337452435d718cd2626aa782ff86420858 | 2,892 | cpp | C++ | sources/Engine/Modules/Graphics/GUI/GUIProgressBar.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 22 | 2017-07-26T17:42:56.000Z | 2022-03-21T22:12:52.000Z | sources/Engine/Modules/Graphics/GUI/GUIProgressBar.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 50 | 2017-08-02T19:37:48.000Z | 2020-07-24T21:10:38.000Z | sources/Engine/Modules/Graphics/GUI/GUIProgressBar.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 4 | 2018-08-20T08:12:48.000Z | 2020-07-19T14:10:05.000Z | #include "precompiled.h"
#pragma hdrstop
#include "GUIProgressBar.h"
#include "GUISystem.h"
GUIProgressBar::GUIProgressBar()
: GUIWidgetRect("progress_bar"),
m_scaleBox(std::make_unique<GUIWidgetRect>("scale"))
{
}
void GUIProgressBar::applyStylesheetRule(const GUIWidgetStylesheetRule& stylesheetRule)
{
GUIWidgetRect::applyStylesheetRule(stylesheetRule);
stylesheetRule.visit([this](auto propertyName, auto property, GUIWidgetVisualState visualState) {
if (propertyName == "border-padding") {
SW_ASSERT(std::holds_alternative<glm::ivec2>(property.getValue()));
SW_ASSERT(visualState == GUIWidgetVisualState::Default &&
"Border padding is supported only for default state");
this->setBorderPadding(std::get<glm::ivec2>(property.getValue()));
}
else if (propertyName == "max-value") {
SW_ASSERT(std::holds_alternative<int>(property.getValue()));
SW_ASSERT(visualState == GUIWidgetVisualState::Default &&
"Max value is supported only for default state");
this->setMaxValue(std::get<int>(property.getValue()));
}
else if (propertyName == "value") {
SW_ASSERT(std::holds_alternative<int>(property.getValue()));
SW_ASSERT(visualState == GUIWidgetVisualState::Default &&
"Value is supported only for default state");
this->setValue(std::get<int>(property.getValue()));
}
else if (propertyName == "background") {
// Do nothing as property should be already processed by GUILayout
}
else {
SW_ASSERT(false);
}
});
}
void GUIProgressBar::applyStylesheetRuleToChildren(
const GUIWidgetStylesheetRule& stylesheetRule,
const std::vector<GUIWidgetStylesheetSelectorPart>& currentPath)
{
GUIWidget::applyStylesheetRuleToChildren(stylesheetRule, currentPath);
m_scaleBox->applyStylesheetRuleWithSelector(stylesheetRule, currentPath);
}
void GUIProgressBar::setMaxValue(int value)
{
m_maxValue = value;
updateScaleSize();
}
int GUIProgressBar::getMaxValue() const
{
return m_maxValue;
}
void GUIProgressBar::setValue(int value)
{
m_currentValue = value;
updateScaleSize();
}
int GUIProgressBar::getValue() const
{
return m_currentValue;
}
void GUIProgressBar::setBorderPadding(const glm::ivec2& padding)
{
m_borderPadding = padding;
updateScaleSize();
}
const glm::ivec2& GUIProgressBar::getBorderPadding() const
{
return m_borderPadding;
}
void GUIProgressBar::updateScaleSize()
{
if (m_scaleBox->getParent() == nullptr) {
addChildWidget(m_scaleBox);
}
m_scaleBox->setOrigin(m_borderPadding);
float scaleWidthFactor = static_cast<float>(m_currentValue) / static_cast<float>(m_maxValue);
int scaleWidth = static_cast<int>(static_cast<float>(getSize().x - m_borderPadding.x * 2) * scaleWidthFactor);
int scaleHeight = getSize().y - m_borderPadding.y * 2;
m_scaleBox->setSize({ scaleWidth, scaleHeight });
}
| 28.07767 | 112 | 0.728562 | n-paukov |
0f638a0f04e30041fd5fe200bbd888be11aa0a43 | 12,219 | cpp | C++ | Main/src/Audio/AudioPlayback.cpp | redline2466/unnamed-sdvx-clone | 8f75329bb07439683fc2ea438e1fdac6831c897f | [
"MIT"
] | null | null | null | Main/src/Audio/AudioPlayback.cpp | redline2466/unnamed-sdvx-clone | 8f75329bb07439683fc2ea438e1fdac6831c897f | [
"MIT"
] | null | null | null | Main/src/Audio/AudioPlayback.cpp | redline2466/unnamed-sdvx-clone | 8f75329bb07439683fc2ea438e1fdac6831c897f | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "AudioPlayback.hpp"
#include <Beatmap/BeatmapPlayback.hpp>
#include <Beatmap/Beatmap.hpp>
#include <Audio/Audio.hpp>
#include <Audio/DSP.hpp>
AudioPlayback::AudioPlayback()
{
}
AudioPlayback::~AudioPlayback()
{
m_CleanupDSP(m_buttonDSPs[0]);
m_CleanupDSP(m_buttonDSPs[1]);
m_CleanupDSP(m_laserDSP);
}
bool AudioPlayback::Init(class BeatmapPlayback& playback, const String& mapRootPath)
{
// Cleanup exising DSP's
m_currentHoldEffects[0] = nullptr;
m_currentHoldEffects[1] = nullptr;
m_CleanupDSP(m_buttonDSPs[0]);
m_CleanupDSP(m_buttonDSPs[1]);
m_CleanupDSP(m_laserDSP);
m_playback = &playback;
m_beatmap = &playback.GetBeatmap();
m_beatmapRootPath = mapRootPath;
assert(m_beatmap != nullptr);
// Set default effect type
SetLaserEffect(EffectType::PeakingFilter);
const BeatmapSettings& mapSettings = m_beatmap->GetMapSettings();
String audioPath = Path::Normalize(m_beatmapRootPath + Path::sep + mapSettings.audioNoFX);
audioPath.TrimBack(' ');
if(!Path::FileExists(audioPath))
{
Logf("Audio file for beatmap does not exists at: \"%s\"", Logger::Severity::Error, audioPath);
return false;
}
m_music = g_audio->CreateStream(audioPath, true);
if(!m_music)
{
Logf("Failed to load any audio for beatmap \"%s\"", Logger::Severity::Error, audioPath);
return false;
}
m_musicVolume = mapSettings.musicVolume;
m_music->SetVolume(m_musicVolume);
// Load FX track
audioPath = Path::Normalize(m_beatmapRootPath + Path::sep + mapSettings.audioFX);
audioPath.TrimBack(' ');
if(!audioPath.empty())
{
if(!Path::FileExists(audioPath) || Path::IsDirectory(audioPath))
{
Logf("FX audio for for beatmap does not exists at: \"%s\" Using real-time effects instead.", Logger::Severity::Warning, audioPath);
}
else
{
m_fxtrack = g_audio->CreateStream(audioPath, true);
if(m_fxtrack)
{
// Initially mute normal track if fx is enabled
m_music->SetVolume(0.0f);
}
}
}
if (m_fxtrack) {
// Prevent loading switchables if fx track is in use.
return true;
}
auto switchablePaths = m_beatmap->GetSwitchablePaths();
// Load switchable audio tracks
for (auto it = switchablePaths.begin(); it != switchablePaths.end(); ++it) {
audioPath = Path::Normalize(m_beatmapRootPath + Path::sep + *it);
audioPath.TrimBack(' ');
SwitchableAudio switchable;
switchable.m_enabled = false;
if (!audioPath.empty()) {
if (!Path::FileExists(audioPath))
{
Logf("Audio for a SwitchAudio effect does not exists at: \"%s\"", Logger::Severity::Warning, audioPath);
}
else
{
switchable.m_audio = g_audio->CreateStream(audioPath, true);
if (switchable.m_audio)
{
// Mute all switchable audio by default
switchable.m_audio->SetVolume(0.0f);
}
}
}
m_switchables.Add(switchable);
}
return true;
}
void AudioPlayback::Tick(float deltaTime)
{
}
void AudioPlayback::Play()
{
m_music->Play();
if(m_fxtrack)
m_fxtrack->Play();
for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it)
if (it->m_audio)
it->m_audio->Play();
m_paused = false;
}
void AudioPlayback::Advance(MapTime ms)
{
SetPosition(GetPosition() + ms);
}
MapTime AudioPlayback::GetPosition() const
{
return m_music->GetPosition();
}
void AudioPlayback::SetPosition(MapTime time)
{
m_music->SetPosition(time);
if(m_fxtrack)
m_fxtrack->SetPosition(time);
for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it)
if (it->m_audio)
it->m_audio->SetPosition(time);
}
void AudioPlayback::TogglePause()
{
if(m_paused) Play();
else Pause();
}
void AudioPlayback::Pause()
{
if (m_paused)
return;
m_music->Pause();
if (m_fxtrack)
m_fxtrack->Pause();
for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it)
if (it->m_audio)
it->m_audio->Pause();
m_paused = true;
}
bool AudioPlayback::HasEnded() const
{
return m_music->HasEnded();
}
void AudioPlayback::SetEffect(uint32 index, HoldObjectState* object, class BeatmapPlayback& playback)
{
// Don't use effects when using an FX track
if(m_fxtrack)
return;
assert(index <= 1);
m_CleanupDSP(m_buttonDSPs[index]);
m_currentHoldEffects[index] = object;
// For Time based effects
const TimingPoint* timingPoint = playback.GetTimingPointAt(object->time);
// Duration of a single bar
double barDelay = timingPoint->numerator * timingPoint->beatDuration;
DSP*& dsp = m_buttonDSPs[index];
m_buttonEffects[index] = m_beatmap->GetEffect(object->effectType);
// Do not create DSP for SwitchAudio effect
if (m_buttonEffects[index].type == EffectType::SwitchAudio)
return;
dsp = m_buttonEffects[index].CreateDSP(m_GetDSPTrack().get(), *this);
Logf("Set effect: %s", Logger::Severity::Debug, dsp->GetName());
if(dsp)
{
m_buttonEffects[index].SetParams(dsp, *this, object);
// Initialize mix value to previous value
dsp->mix = m_effectMix[index];
dsp->startTime = object->time;
dsp->chartOffset = playback.GetBeatmap().GetMapSettings().offset;
dsp->lastTimingPoint = playback.GetCurrentTimingPoint().time;
}
}
void AudioPlayback::SetEffectEnabled(uint32 index, bool enabled)
{
assert(index <= 1);
m_effectMix[index] = enabled ? 1.0f : 0.0f;
if (m_buttonEffects[index].type == EffectType::SwitchAudio) {
SetSwitchableTrackEnabled(m_buttonEffects[index].switchaudio.index.Sample(), enabled);
return;
}
if(m_buttonDSPs[index])
{
m_buttonDSPs[index]->mix = m_effectMix[index];
}
}
void AudioPlayback::ClearEffect(uint32 index, HoldObjectState* object)
{
assert(index <= 1);
if(m_currentHoldEffects[index] == object)
{
m_CleanupDSP(m_buttonDSPs[index]);
m_currentHoldEffects[index] = nullptr;
}
}
void AudioPlayback::SetLaserEffect(EffectType type)
{
if(type != m_laserEffectType)
{
m_CleanupDSP(m_laserDSP);
m_laserEffectType = type;
m_laserEffect = m_beatmap->GetFilter(type);
}
}
void AudioPlayback::SetLaserFilterInput(float input, bool active)
{
if(m_laserEffect.type != EffectType::None && (active || (input != 0.0f)))
{
if (m_laserEffect.type == EffectType::SwitchAudio) {
m_laserSwitchable = m_laserEffect.switchaudio.index.Sample();
SetSwitchableTrackEnabled(m_laserSwitchable, true);
return;
}
// SwitchAudio transition into other filters
if (m_laserSwitchable > 0)
{
SetSwitchableTrackEnabled(m_laserSwitchable, false);
m_laserSwitchable = -1;
}
// Create DSP
if(!m_laserDSP)
{
// Don't use Bitcrush effects over FX track
if(m_fxtrack && m_laserEffectType == EffectType::Bitcrush)
return;
m_laserDSP = m_laserEffect.CreateDSP(m_GetDSPTrack().get(), *this);
if(!m_laserDSP)
{
Logf("Failed to create laser DSP with type %d", Logger::Severity::Warning, m_laserEffect.type);
return;
}
}
// Set params
m_SetLaserEffectParameter(input);
m_laserInput = input;
}
else
{
if (m_laserSwitchable > 0)
SetSwitchableTrackEnabled(m_laserSwitchable, true);
m_laserSwitchable = -1;
m_CleanupDSP(m_laserDSP);
m_laserInput = 0.0f;
}
}
float AudioPlayback::GetLaserFilterInput() const
{
return m_laserInput;
}
void AudioPlayback::SetLaserEffectMix(float mix)
{
m_laserEffectMix = mix;
}
float AudioPlayback::GetLaserEffectMix() const
{
return m_laserEffectMix;
}
Ref<AudioStream> AudioPlayback::m_GetDSPTrack()
{
if(m_fxtrack) return m_fxtrack;
return m_music;
}
void AudioPlayback::SetFXTrackEnabled(bool enabled)
{
if(!m_fxtrack)
return;
if(m_fxtrackEnabled != enabled)
{
if(enabled)
{
m_fxtrack->SetVolume(m_musicVolume);
m_music->SetVolume(0.0f);
}
else
{
m_fxtrack->SetVolume(0.0f);
m_music->SetVolume(m_musicVolume);
}
}
m_fxtrackEnabled = enabled;
}
void AudioPlayback::SetSwitchableTrackEnabled(size_t index, bool enabled)
{
if (m_fxtrack)
return;
assert(index < m_switchables.size());
int32 disableTrack = -1;
int32 enableTrack = -1;
if (!enabled) {
disableTrack = index;
m_enabledSwitchables.Remove(index);
enableTrack = m_enabledSwitchables.size() ? m_enabledSwitchables.back() : -2;
} else {
disableTrack = m_enabledSwitchables.size() ? m_enabledSwitchables.back() : -2;
m_enabledSwitchables.AddUnique(index);
enableTrack = m_enabledSwitchables.size() ? m_enabledSwitchables.back() : -2;
}
if (disableTrack != -1) {
if (disableTrack == -2)
m_music->SetVolume(0.0f);
else if (m_switchables[disableTrack].m_audio)
m_switchables[disableTrack].m_audio->SetVolume(0.0f);
}
if (enableTrack != -1) {
if (enableTrack == -2)
m_music->SetVolume(m_musicVolume);
else if (m_switchables[enableTrack].m_audio)
m_switchables[enableTrack].m_audio->SetVolume(m_musicVolume);
}
}
void AudioPlayback::ResetSwitchableTracks() {
for (size_t i = 0; i < m_switchables.size(); ++i)
{
if (m_switchables[i].m_audio)
m_switchables[i].m_audio->SetVolume(0.0f);
}
m_music->SetVolume(m_musicVolume);
}
BeatmapPlayback& AudioPlayback::GetBeatmapPlayback()
{
return *m_playback;
}
const Beatmap& AudioPlayback::GetBeatmap() const
{
return *m_beatmap;
}
const String& AudioPlayback::GetBeatmapRootPath() const
{
return m_beatmapRootPath;
}
void AudioPlayback::SetPlaybackSpeed(float speed)
{
m_music->PlaybackSpeed = speed;
if (m_fxtrack)
m_fxtrack->PlaybackSpeed = speed;
for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it)
if (it->m_audio)
it->m_audio->PlaybackSpeed = speed;
}
float AudioPlayback::GetPlaybackSpeed() const
{
return m_music->PlaybackSpeed;
}
void AudioPlayback::SetVolume(float volume)
{
m_music->SetVolume(volume);
if (m_fxtrack)
m_fxtrack->SetVolume(volume);
for (auto it = m_switchables.begin(); it != m_switchables.end(); ++it)
if (it->m_audio)
it->m_audio->SetVolume(volume);
}
void AudioPlayback::m_CleanupDSP(DSP*& ptr)
{
if(ptr)
{
m_GetDSPTrack()->RemoveDSP(ptr);
delete ptr;
ptr = nullptr;
}
}
void AudioPlayback::m_SetLaserEffectParameter(float input)
{
if(!m_laserDSP)
return;
assert(input >= 0.0f && input <= 1.0f);
// Mix float biquad filters, these are applied manualy by changing the filter parameters (gain,q,freq,etc.)
float mix = m_laserEffectMix;
double noteDuration = m_playback->GetCurrentTimingPoint().GetWholeNoteLength();
uint32 actualLength = m_laserEffect.duration.Sample(input).Absolute(noteDuration);
if(input < 0.1f)
mix *= input / 0.1f;
switch (m_laserEffect.type)
{
case EffectType::Bitcrush:
{
m_laserDSP->mix = m_laserEffect.mix.Sample(input);
BitCrusherDSP* bcDSP = (BitCrusherDSP*)m_laserDSP;
bcDSP->SetPeriod((float)m_laserEffect.bitcrusher.reduction.Sample(input));
break;
}
case EffectType::Echo:
{
m_laserDSP->mix = m_laserEffect.mix.Sample(input);
EchoDSP* echoDSP = (EchoDSP*)m_laserDSP;
echoDSP->feedback = m_laserEffect.echo.feedback.Sample(input);
break;
}
case EffectType::PeakingFilter:
{
m_laserDSP->mix = m_laserEffectMix;
if (input > 0.8f)
mix *= 1.0f - (input - 0.8f) / 0.2f;
BQFDSP* bqfDSP = (BQFDSP*)m_laserDSP;
bqfDSP->SetPeaking(m_laserEffect.peaking.q.Sample(input), m_laserEffect.peaking.freq.Sample(input), m_laserEffect.peaking.gain.Sample(input) * mix);
break;
}
case EffectType::LowPassFilter:
{
m_laserDSP->mix = m_laserEffectMix;
BQFDSP* bqfDSP = (BQFDSP*)m_laserDSP;
bqfDSP->SetLowPass(m_laserEffect.lpf.q.Sample(input) * mix + 0.1f, m_laserEffect.lpf.freq.Sample(input));
break;
}
case EffectType::HighPassFilter:
{
m_laserDSP->mix = m_laserEffectMix;
BQFDSP* bqfDSP = (BQFDSP*)m_laserDSP;
bqfDSP->SetHighPass(m_laserEffect.hpf.q.Sample(input) * mix + 0.1f, m_laserEffect.hpf.freq.Sample(input));
break;
}
case EffectType::PitchShift:
{
m_laserDSP->mix = m_laserEffect.mix.Sample(input);
PitchShiftDSP* ps = (PitchShiftDSP*)m_laserDSP;
ps->amount = m_laserEffect.pitchshift.amount.Sample(input);
break;
}
case EffectType::Gate:
{
m_laserDSP->mix = m_laserEffect.mix.Sample(input);
GateDSP * gd = (GateDSP*)m_laserDSP;
// gd->SetLength(actualLength);
break;
}
case EffectType::Retrigger:
{
m_laserDSP->mix = m_laserEffect.mix.Sample(input);
RetriggerDSP * rt = (RetriggerDSP*)m_laserDSP;
rt->SetLength(actualLength);
break;
}
default:
break;
}
}
GameAudioEffect::GameAudioEffect(const AudioEffect& other)
{
*((AudioEffect*)this) = other;
}
| 25.350622 | 150 | 0.717407 | redline2466 |
0f63b2342d8a2d1d8564a5400d8d931e62e908ae | 1,230 | cc | C++ | bindings/java/src/main/native/worker.cc | RankoM/ucx | d8269f0141f97764c21d03235c0783f04a9864b7 | [
"BSD-3-Clause"
] | 5 | 2019-05-31T01:47:34.000Z | 2022-01-10T11:59:53.000Z | bindings/java/src/main/native/worker.cc | frontwing/ucx | e1eed19d973844198445ba822239f0b8a5be19a7 | [
"BSD-3-Clause"
] | 1 | 2020-01-28T08:42:44.000Z | 2020-01-28T08:42:44.000Z | bindings/java/src/main/native/worker.cc | frontwing/ucx | e1eed19d973844198445ba822239f0b8a5be19a7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) Mellanox Technologies Ltd. 2001-2017. ALL RIGHTS RESERVED.
* See file LICENSE for terms.
*/
#include "worker.h"
#include <new> // bad_alloc exception
worker::worker(context* ctx, uint32_t cap, ucp_worker_params_t params) :
jucx_context(ctx), ucp_worker(nullptr),
queue_size(cap), event_queue(nullptr) {
ucs_status_t status = jucx_context->ref_context();
if (status != UCS_OK) {
throw std::bad_alloc{};
}
status = ucp_worker_create(jucx_context->get_ucp_context(),
¶ms, &ucp_worker);
if (status != UCS_OK) {
jucx_context->deref_context();
throw std::bad_alloc{};
}
event_queue = new char[queue_size];
}
worker::~worker() {
delete[] event_queue;
ucp_worker_destroy(ucp_worker);
jucx_context->deref_context();
}
ucs_status_t worker::extract_worker_address(ucp_address_t** worker_address,
size_t& address_length) {
return ucp_worker_get_address(ucp_worker, worker_address, &address_length);
}
void worker::release_worker_address(ucp_address_t* worker_address) {
ucp_worker_release_address(ucp_worker, worker_address);
}
| 30.75 | 79 | 0.657724 | RankoM |
0f69f2a44ad7e3a2d8ef555342593f34218ee841 | 804 | cpp | C++ | solutions/218.the-skyline-problem.378841603.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/218.the-skyline-problem.378841603.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/218.the-skyline-problem.378841603.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings) {
int n = buildings.size();
vector<vector<int>> arr;
vector<vector<int>> ans;
if (!n)
return ans;
for (auto b : buildings) {
arr.push_back({b[0], b[2], 1});
arr.push_back({b[1], b[2], -1});
}
sort(arr.begin(), arr.end());
multiset<int> set;
set.insert(0);
for (int i = 0; i < 2 * n; i++) {
int x = arr[i][0];
int h = arr[i][1];
int op = arr[i][2];
if (op == 1)
set.insert(h);
else
set.erase(set.find(h));
if (i != 2 * n - 1 && arr[i + 1][0] == x)
continue;
if (ans.empty() || *set.rbegin() != ans.back()[1])
ans.push_back({x, *set.rbegin()});
}
return ans;
}
};
| 19.142857 | 66 | 0.472637 | satu0king |
0f7206bcf5ca36bc7659f68efd712639a06a541a | 6,336 | cpp | C++ | rocAL/rocAL/source/video_file_source_reader.cpp | Indumathi31/MIVisionX | e58c8b63d51e3f857d5f1c8750433d1ec887d7f0 | [
"MIT"
] | null | null | null | rocAL/rocAL/source/video_file_source_reader.cpp | Indumathi31/MIVisionX | e58c8b63d51e3f857d5f1c8750433d1ec887d7f0 | [
"MIT"
] | 8 | 2021-12-10T14:07:28.000Z | 2022-03-04T02:53:11.000Z | rocAL/rocAL/source/video_file_source_reader.cpp | Indumathi31/MIVisionX | e58c8b63d51e3f857d5f1c8750433d1ec887d7f0 | [
"MIT"
] | 2 | 2021-06-01T09:42:51.000Z | 2021-11-09T14:35:36.000Z | /*
Copyright (c) 2019 - 2022 Advanced Micro Devices, Inc. All rights reserved.
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 <cassert>
#include <algorithm>
#include <commons.h>
#include "video_file_source_reader.h"
#include <boost/filesystem.hpp>
namespace filesys = boost::filesystem;
#ifdef RALI_VIDEO
VideoFileSourceReader::VideoFileSourceReader() : _shuffle_time("shuffle_time", DBG_TIMING)
{
_curr_sequence_idx = 0;
_loop = false;
_sequence_id = 0;
_shuffle = false;
_sequence_count_all_shards = 0;
}
unsigned VideoFileSourceReader::count_items()
{
if (_loop)
return _total_sequences_count;
int ret = (int)(_total_sequences_count - _read_counter);
return ((ret <= 0) ? 0 : ret);
}
VideoReader::Status VideoFileSourceReader::initialize(VideoReaderConfig desc)
{
auto ret = VideoReader::Status::OK;
_sequence_id = 0;
_folder_path = desc.path();
_shard_id = desc.get_shard_id();
_shard_count = desc.get_shard_count();
_shuffle = desc.shuffle();
_loop = desc.loop();
_video_prop = desc.get_video_properties();
_video_count = _video_prop.videos_count;
_video_file_names.resize(_video_count);
_start_end_frame.resize(_video_count);
_video_file_names = _video_prop.video_file_names;
_sequence_length = desc.get_sequence_length();
_step = desc.get_frame_step();
_stride = desc.get_frame_stride();
_video_frame_count = _video_prop.frames_count;
_start_end_frame = _video_prop.start_end_frame_num;
_batch_count = desc.get_batch_size();
_total_sequences_count = 0;
ret = create_sequence_info();
// the following code is required to make every shard the same size:: required for multi-gpu training
if (_shard_count > 1 && _batch_count > 1) {
int _num_batches = _sequences.size()/_batch_count;
int max_batches_per_shard = (_sequence_count_all_shards + _shard_count-1)/_shard_count;
max_batches_per_shard = (max_batches_per_shard + _batch_count-1)/_batch_count;
if (_num_batches < max_batches_per_shard) {
replicate_last_batch_to_pad_partial_shard();
}
}
//shuffle dataset if set
_shuffle_time.start();
if (ret == VideoReader::Status::OK && _shuffle)
std::random_shuffle(_sequences.begin(), _sequences.end());
_shuffle_time.end();
return ret;
}
void VideoFileSourceReader::incremenet_read_ptr()
{
_read_counter ++;
_curr_sequence_idx = (_curr_sequence_idx + 1) % _sequences.size();
}
SequenceInfo VideoFileSourceReader::get_sequence_info()
{
auto current_sequence = _sequences[_curr_sequence_idx];
auto file_path = current_sequence.video_file_name;
_last_id = file_path;
incremenet_read_ptr();
return current_sequence;
}
VideoFileSourceReader::~VideoFileSourceReader()
{
}
void VideoFileSourceReader::reset()
{
if (_shuffle)
std::random_shuffle(_sequences.begin(), _sequences.end());
_read_counter = 0;
_curr_sequence_idx = 0;
}
VideoReader::Status VideoFileSourceReader::create_sequence_info()
{
VideoReader::Status status = VideoReader::Status::OK;
for (size_t i = 0; i < _video_count; i++)
{
unsigned start = std::get<0>(_start_end_frame[i]);
size_t max_sequence_frames = (_sequence_length - 1) * _stride;
for(size_t sequence_start = start; (sequence_start + max_sequence_frames) < (start + _video_frame_count[i]); sequence_start += _step)
{
if(get_sequence_shard_id() != _shard_id)
{
_sequence_count_all_shards++;
incremenet_sequence_id();
continue;
}
_in_batch_read_count++;
_in_batch_read_count = (_in_batch_read_count % _batch_count == 0) ? 0 : _in_batch_read_count;
_sequences.push_back({sequence_start, _video_file_names[i]});
_last_sequence = _sequences.back();
_total_sequences_count ++;
_sequence_count_all_shards++;
incremenet_sequence_id();
}
}
if(_in_batch_read_count > 0 && _in_batch_read_count < _batch_count)
{
replicate_last_sequence_to_fill_last_shard();
LOG("VideoFileSourceReader ShardID [" + TOSTR(_shard_id) + "] Replicated the last sequence " + TOSTR((_batch_count - _in_batch_read_count) ) + " times to fill the last batch")
}
if(_sequences.empty())
WRN("VideoFileSourceReader ShardID ["+ TOSTR(_shard_id)+ "] Did not load any sequences from " + _folder_path)
return status;
}
void VideoFileSourceReader::replicate_last_sequence_to_fill_last_shard()
{
for (size_t i = _in_batch_read_count; i < _batch_count; i++)
{
_sequences.push_back(_last_sequence);
_total_sequences_count ++;
}
}
void VideoFileSourceReader::replicate_last_batch_to_pad_partial_shard()
{
if (_sequences.size() >= _batch_count)
{
for (size_t i = 0; i < _batch_count; i++)
{
_sequences.push_back(_sequences[i - _batch_count]);
_total_sequences_count ++;
}
}
}
size_t VideoFileSourceReader::get_sequence_shard_id()
{
if (_batch_count == 0 || _shard_count == 0)
THROW("Shard (Batch) size cannot be set to 0")
//return (_sequence_id / (_batch_count)) % _shard_count;
return _sequence_id % _shard_count;
}
#endif
| 35.396648 | 183 | 0.705335 | Indumathi31 |
0f79ba02d5a1e1288510a2e12629e6540e50c1c5 | 137 | hxx | C++ | src/Providers/UNIXProviders/IPsecTransportAction/UNIX_IPsecTransportAction_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/IPsecTransportAction/UNIX_IPsecTransportAction_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/IPsecTransportAction/UNIX_IPsecTransportAction_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_DARWIN
#ifndef __UNIX_IPSECTRANSPORTACTION_PRIVATE_H
#define __UNIX_IPSECTRANSPORTACTION_PRIVATE_H
#endif
#endif
| 11.416667 | 45 | 0.861314 | brunolauze |
0f80b62fa4cef88c932d8280a5697722d5a21b7a | 2,090 | cpp | C++ | chatra_emb/EmbeddedLibraries.cpp | chatra-lang/chatra | fdae457fcbd066ac8c0d44d6b763d4a18bf524f7 | [
"Apache-2.0"
] | 3 | 2019-10-14T12:25:23.000Z | 2021-01-06T17:53:17.000Z | chatra_emb/EmbeddedLibraries.cpp | chatra-lang/chatra | fdae457fcbd066ac8c0d44d6b763d4a18bf524f7 | [
"Apache-2.0"
] | 3 | 2019-10-15T14:40:34.000Z | 2020-08-29T14:25:06.000Z | chatra_emb/EmbeddedLibraries.cpp | chatra-lang/chatra | fdae457fcbd066ac8c0d44d6b763d4a18bf524f7 | [
"Apache-2.0"
] | null | null | null | /*
* Programming language 'Chatra' reference implementation
*
* Copyright(C) 2019-2020 Chatra Project Team
*
* 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.
*
* author: Satoshi Hosokawa ([email protected])
*/
#include "chatra.h"
#include <unordered_map>
#include <atomic>
#include <mutex>
namespace chatra {
namespace emb {
namespace sys { cha::PackageInfo packageInfo(); }
namespace format { cha::PackageInfo packageInfo(); }
namespace regex { cha::PackageInfo packageInfo(); }
namespace containers { cha::PackageInfo packageInfo(); }
namespace io { cha::PackageInfo packageInfo(); }
namespace random { cha::PackageInfo packageInfo(); }
namespace math { cha::PackageInfo packageInfo(); }
} // namespace emb
static std::atomic<bool> initialized = {false};
static std::mutex mtInitialize;
static std::unordered_map<std::string, cha::PackageInfo> packages;
static void initialize() {
std::lock_guard<std::mutex> lock(mtInitialize);
if (initialized)
return;
std::vector<cha::PackageInfo> packageList = {
emb::sys::packageInfo(),
emb::format::packageInfo(),
emb::regex::packageInfo(),
emb::containers::packageInfo(),
emb::io::packageInfo(),
emb::random::packageInfo(),
emb::math::packageInfo(),
};
for (auto& pi : packageList)
packages.emplace(pi.scripts[0].name, pi);
initialized = true;
}
PackageInfo queryEmbeddedPackage(const std::string& packageName) {
if (!initialized)
initialize();
auto it = packages.find(packageName);
return it != packages.cend() ? it->second : PackageInfo{{}, {}, nullptr};
}
} // namespace chatra
| 29.43662 | 75 | 0.721053 | chatra-lang |
0f82767dba14d864176d6d612e74d02352ebf845 | 969 | cpp | C++ | exercise_part_1/exercise3/white_space_file_reader.cpp | jamesjallorina/cpp_exercises | 0e18511aad163510143dc66523a8111057694bff | [
"MIT"
] | 1 | 2019-07-08T14:35:57.000Z | 2019-07-08T14:35:57.000Z | exercise_part_1/exercise3/white_space_file_reader.cpp | jamesjallorina/cpp_exercises | 0e18511aad163510143dc66523a8111057694bff | [
"MIT"
] | null | null | null | exercise_part_1/exercise3/white_space_file_reader.cpp | jamesjallorina/cpp_exercises | 0e18511aad163510143dc66523a8111057694bff | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <ctype.h>
int white_space_counter(std::ifstream &fs)
{
std::string buffer = "";
std::string::const_iterator itr;
int number_of_white_space = 0;
while( std::getline( fs, buffer ))
{
for(itr = buffer.begin(); itr != buffer.end(); ++itr)
{
if( iswspace( *itr ) )
number_of_white_space++;
}
}
return number_of_white_space;
}
int main(int argc, char **argv)
{
if(argc < 2)
{
std::cout << "./white_space_file_reader [filename] \n";
return -1;
}
std::cout << "filename [" << argv[1] << "]\n";
std::ifstream filestream(argv[1], std::ifstream::in);
if(filestream.good())
{
std::cout << "file is good \n";
if(!filestream.is_open())
{
std::cout << "file is not okay to open \n";
return -1;
}
std::cout << "file is okay to open \n";
}
std::cout << "total number of white space inside the file: " << white_space_counter(filestream) << "\n";
filestream.close();
return 0;
}
| 20.1875 | 105 | 0.619195 | jamesjallorina |
0f82db5b1c766f6b5711e40a438d42a38c62990b | 2,847 | hpp | C++ | src/cpu/cpu_memory_storage.hpp | igor-byel/mkl-dnn | b03ea18e2c3a7576052c52e6c9aca7baa66d44af | [
"Apache-2.0"
] | null | null | null | src/cpu/cpu_memory_storage.hpp | igor-byel/mkl-dnn | b03ea18e2c3a7576052c52e6c9aca7baa66d44af | [
"Apache-2.0"
] | null | null | null | src/cpu/cpu_memory_storage.hpp | igor-byel/mkl-dnn | b03ea18e2c3a7576052c52e6c9aca7baa66d44af | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef CPU_MEMORY_STORAGE_HPP
#define CPU_MEMORY_STORAGE_HPP
#include <memory>
#include "common/c_types_map.hpp"
#include "common/memory.hpp"
#include "common/memory_storage.hpp"
#include "common/utils.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
class cpu_memory_storage_t : public memory_storage_t {
public:
cpu_memory_storage_t(engine_t *engine)
: memory_storage_t(engine), data_(nullptr, release) {}
status_t init(unsigned flags, size_t size, void *handle) {
// Do not allocate memory if one of these is true:
// 1) size is 0
// 2) handle is nullptr and 'alloc' flag is not set
if (size == 0 || (!handle && !(flags & memory_flags_t::alloc)))
return status::success;
if (flags & memory_flags_t::alloc) {
void *data_ptr = malloc(size, 64);
if (data_ptr == nullptr) return status::out_of_memory;
data_ = decltype(data_)(data_ptr, destroy);
} else if (flags & memory_flags_t::use_runtime_ptr) {
data_ = decltype(data_)(handle, release);
}
return status::success;
}
virtual status_t get_data_handle(void **handle) const override {
*handle = data_.get();
return status::success;
}
virtual status_t set_data_handle(void *handle) override {
data_ = decltype(data_)(handle, release);
return status::success;
}
virtual std::unique_ptr<memory_storage_t> get_sub_storage(
size_t offset, size_t size) const override {
void *sub_ptr = reinterpret_cast<uint8_t *>(data_.get()) + offset;
auto sub_storage = new cpu_memory_storage_t(this->engine());
sub_storage->init(memory_flags_t::use_runtime_ptr, size, sub_ptr);
return std::unique_ptr<memory_storage_t>(sub_storage);
}
private:
std::unique_ptr<void, void (*)(void *)> data_;
DNNL_DISALLOW_COPY_AND_ASSIGN(cpu_memory_storage_t);
static void release(void *ptr) {}
static void destroy(void *ptr) { free(ptr); }
};
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
| 33.892857 | 80 | 0.642079 | igor-byel |
abf08a48fb387ff01feb50583eaa24bfc1992168 | 787 | cpp | C++ | src/allegro_flare/circle.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 25 | 2015-03-30T02:02:43.000Z | 2019-03-04T22:29:12.000Z | src/allegro_flare/circle.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 122 | 2015-04-01T08:15:26.000Z | 2019-10-16T20:31:22.000Z | src/allegro_flare/circle.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 4 | 2016-09-02T12:14:09.000Z | 2018-11-23T20:38:49.000Z |
#include <allegro_flare/circle.h>
#include <AllegroFlare/Color.hpp>
#include <AllegroFlare/Useful.hpp> // for distance
namespace allegro_flare
{
UISurfaceAreaCircle::UISurfaceAreaCircle(float x, float y, float r)
: UISurfaceAreaBase(x, y, r*2, r*2)
{}
bool UISurfaceAreaCircle::collides(float x, float y)
{
placement.transform_coordinates(&x, &y);
return AllegroFlare::distance(placement.size.x/2, placement.size.y/2, x, y) <= placement.size.x/2;
}
void UISurfaceAreaCircle::draw_bounding_area()
{
placement.start_transform();
al_draw_circle(placement.size.x/2, placement.size.y/2, placement.size.x/2, AllegroFlare::color::color(AllegroFlare::color::aliceblue, 0.2), 3.0);
placement.restore_transform();
}
}
| 19.675 | 151 | 0.691233 | MarkOates |
abf465685e459616242659562e0044675609eb29 | 7,435 | hxx | C++ | BeastHttp/include/http/base/impl/cb.hxx | Lyoko-Jeremie/BeastHttp | 6121cba601a115a638c7c56cd2eb87e5e4eec14b | [
"BSD-2-Clause"
] | 2 | 2022-03-18T10:02:17.000Z | 2022-03-18T14:05:35.000Z | BeastHttp/include/http/base/impl/cb.hxx | Lyoko-Jeremie/BeastHttp | 6121cba601a115a638c7c56cd2eb87e5e4eec14b | [
"BSD-2-Clause"
] | null | null | null | BeastHttp/include/http/base/impl/cb.hxx | Lyoko-Jeremie/BeastHttp | 6121cba601a115a638c7c56cd2eb87e5e4eec14b | [
"BSD-2-Clause"
] | 2 | 2022-03-18T10:02:22.000Z | 2022-03-27T01:09:44.000Z | #ifndef BEASTHTTP_BASE_IMPL_CB_HXX
#define BEASTHTTP_BASE_IMPL_CB_HXX
#include <http/base/config.hxx>
#include <functional>
namespace _0xdead4ead {
namespace http {
namespace base {
namespace cb {
namespace detail {
#ifndef BEASTHTTP_CXX17_IF_CONSTEXPR
template<std::size_t value>
using size_type = std::integral_constant<std::size_t, value>;
template <class Begin, class End, typename S, class... Elements>
struct for_each_impl
{
void
operator()(const std::tuple<Elements...>& tpl,
const Begin& begin,
const End& end)
{
const auto& value = std::get<S::value>(tpl);
begin(value);
for_each_impl<Begin, End, size_type<S() + 1>,
Elements...>{}(tpl, begin, end);
}
}; // struct for_each_impl
template <class Begin, class End, class... Elements>
struct for_each_impl<Begin, End,
size_type<std::tuple_size<std::tuple<Elements...>>::value - 1>,
Elements...>
{
void
operator()(const std::tuple<Elements...>& tpl,
const Begin& begin,
const End& end)
{
const auto& value =
std::get<size_type<std::tuple_size<
std::tuple<Elements...>>::value - 1>::value>(tpl);
end(value);
(void)begin;
}
}; // struct for_each_impl
template<std::size_t Index, class Begin, class End, class... Elements>
void
for_each(const std::tuple<Elements...>& tpl,
const Begin& begin,
const End& end)
{
for_each_impl<Begin, End, size_type<Index>, Elements...>{}(tpl, begin, end);
}
#else
template<std::size_t Index, class Begin, class End, class... Elements>
void
for_each(const std::tuple<Elements...>& tpl,
const Begin& begin,
const End& end)
{
const auto& value = std::get<Index>(tpl);
if constexpr (Index + 1 == std::tuple_size<std::tuple<Elements...>>::value)
end(value);
else {
begin(value);
for_each<Index + 1, Begin, End, Elements...>(tpl, begin, end);
}
}
#endif // BEASTHTTP_CXX17_IF_CONSTEXPR
#ifndef BEASTHTTP_CXX14_GENERIC_LAMBDAS
template<class Container>
struct cb_push_cxx11
{
using container_type = Container;
using value_type = typename container_type::value_type;
Container& l_;
cb_push_cxx11(Container& l)
: l_{l}
{
}
template<class F>
void
operator()(const F& value) const
{
l_.push_back(
value_type(
std::bind<void>(
value,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3)));
}
}; // struct cb_push_cxx11
template<class Container>
struct cb_push_fin_cxx11
{
using container_type = Container;
using value_type = typename container_type::value_type;
Container& l_;
cb_push_fin_cxx11(Container& l)
: l_{l}
{
}
template<class F>
void
operator()(const F& value) const
{
l_.push_back(
value_type(
std::bind<void>(
value,
std::placeholders::_1,
std::placeholders::_2)));
}
}; // struct cb_push_fin_cxx11
#endif // BEASTHTTP_CXX14_GENERIC_LAMBDAS
} // namespace detail
template<class Request, class SessionFlesh, class Storage>
void
executor::execute(Request& request,
SessionFlesh& session_flesh,
Storage& storage)
{
storage.begin_exec(request, session_flesh)();
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
const_iterator<Session, Entry, Container>::const_iterator(
const container_type& container, request_type& request,
session_flesh& flesh)
: pos_{0},
cont_begin_iter_{container.begin()},
cont_end_iter_{container.end()},
request_{request},
session_flesh_{flesh},
current_target_{request_.target().to_string()}
{
if (container.size() > 1)
skip_target();
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
typename const_iterator<Session, Entry, Container>::self_type&
const_iterator<Session, Entry, Container>::operator++()
{
cont_begin_iter_++; pos_++;
if (cont_begin_iter_ == cont_end_iter_) {
cont_begin_iter_--; pos_--;
}
skip_target();
return *this;
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
typename const_iterator<Session, Entry, Container>::self_type
const_iterator<Session, Entry, Container>::operator++(int)
{
self_type _tmp{*this};
++(*this);
return _tmp;
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
void
const_iterator<Session, Entry, Container>::operator()() const
{
session_context _ctx{session_flesh_};
(*cont_begin_iter_) (request_, std::move(_ctx), *this);
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
void
const_iterator<Session, Entry, Container>::skip_target()
{
std::size_t pos = current_target_.find('/', 1);
if (pos != std::string::npos) {
auto next_target = current_target_.substr(0, pos);
current_target_ = current_target_.substr(pos);
request_.target(next_target);
}
else
request_.target(current_target_);
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
typename const_iterator<Session, Entry, Container>::size_type
const_iterator<Session, Entry, Container>::pos() const
{
return pos_;
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
template<class F, class... Fn, typename>
storage<Session, Entry, Container>::storage(F&& f, Fn&&... fn)
: container_{prepare(std::forward<F>(f),
std::forward<Fn>(fn)...)}
{
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
template<class... OnRequest>
typename storage<Session, Entry, Container>::container_type
storage<Session, Entry, Container>::prepare(OnRequest&&... on_request)
{
container_type _l;
const auto& tuple_cb = std::make_tuple(
std::forward<OnRequest>(on_request)...);
static_assert(std::tuple_size<typename std::decay<
decltype (tuple_cb) >::type>::value != 0,
"Oops...! tuple is empty.");
#ifndef BEASTHTTP_CXX14_GENERIC_LAMBDAS
detail::for_each<0>(tuple_cb,
detail::cb_push_cxx11<container_type>{_l},
detail::cb_push_fin_cxx11<container_type>{_l});
#else
detail::for_each<0>(tuple_cb,
[&_l](const auto& value){
_l.push_back(
entry_type(
std::bind<void>(
value,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3)));},
[&_l](const auto & value){
_l.push_back(
entry_type(
std::bind<void>(
value,
std::placeholders::_1,
std::placeholders::_2)));});
#endif // BEASTHTTP_CXX14_GENERIC_LAMBDAS
return _l;
}
BEASTHTTP_DECLARE_STORAGE_TEMPLATE
typename storage<Session, Entry, Container>::iterator_type
storage<Session, Entry, Container>::begin_exec(
request_type& request, session_flesh& flesh)
{
return iterator_type(container_, request, flesh);
}
} // namespace cb
} // namespace base
} // namespace http
} // namespace _0xdead4ead
#endif // not defined BEASTHTTP_BASE_IMPL_CB_HXX
| 26.938406 | 80 | 0.609953 | Lyoko-Jeremie |
abf64bc5c06a1773c952e6c7e32a5c44d0c5f2cb | 549 | cpp | C++ | spec/cpp/tests/timing/ClockTests.cpp | NeoResearch/libbft | 6608f7f3cc90d976c06d54d42b72ec9eb5df5a25 | [
"MIT"
] | 21 | 2019-07-24T22:06:33.000Z | 2021-11-29T08:36:58.000Z | spec/cpp/tests/timing/ClockTests.cpp | NeoResearch/libbft | 6608f7f3cc90d976c06d54d42b72ec9eb5df5a25 | [
"MIT"
] | 35 | 2019-09-30T21:18:56.000Z | 2020-03-03T01:50:48.000Z | spec/cpp/tests/timing/ClockTests.cpp | NeoResearch/libbft | 6608f7f3cc90d976c06d54d42b72ec9eb5df5a25 | [
"MIT"
] | 3 | 2019-12-26T02:53:43.000Z | 2021-03-19T03:55:11.000Z | #include <thread>
#include <gtest/gtest.h>
#include "timing/Clock.hpp"
using namespace std;
using namespace libbft;
TEST(TimingClock, ToString) {
unique_ptr<Clock> clock(new Clock("T"));
EXPECT_EQ("Clock {name='T'}", clock->toString());
}
TEST(TimingClock, GetTime) {
unique_ptr<Clock> clock(new Clock("T"));
auto actualTime = clock->getTime();
EXPECT_LT(0, actualTime);
this_thread::sleep_for(chrono::milliseconds(200));
EXPECT_LT(0.19, clock->getTime() - actualTime);
EXPECT_GT(0.8, clock->getTime() - actualTime);
}
| 22.875 | 53 | 0.688525 | NeoResearch |
abfa449d8085c5bbc3a2784041e546a194a16308 | 3,207 | hpp | C++ | gecode/iter/ranges-rangelist.hpp | LeslieW/gecode-clone | ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c | [
"MIT-feh"
] | null | null | null | gecode/iter/ranges-rangelist.hpp | LeslieW/gecode-clone | ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c | [
"MIT-feh"
] | null | null | null | gecode/iter/ranges-rangelist.hpp | LeslieW/gecode-clone | ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c | [
"MIT-feh"
] | null | null | null | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*
* Copyright:
* Guido Tack, 2011
*
* Last modified:
* $Date$ by $Author$
* $Revision$
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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.
*
*/
namespace Gecode { namespace Iter { namespace Ranges {
/**
* \brief %Range iterator for range lists
*
* Allows to iterate the ranges of a RangeList where the
* ranges must be increasing and non-overlapping.
*
* \ingroup FuncIterRanges
*/
class RangeList {
protected:
/// Current range
const Gecode::RangeList* c;
public:
/// \name Constructors and initialization
//@{
/// Default constructor
RangeList(void);
/// Initialize with BndSet \a s
RangeList(const Gecode::RangeList* s);
/// Initialize with BndSet \a s
void init(const Gecode::RangeList* s);
//@}
/// \name Iteration control
//@{
/// Test whether iterator is still at a range or done
bool operator ()(void) const;
/// Move iterator to next range (if possible)
void operator ++(void);
//@}
/// \name Range access
//@{
/// Return smallest value of range
int min(void) const;
/// Return largest value of range
int max(void) const;
/// Return width of range (distance between minimum and maximum)
unsigned int width(void) const;
//@}
};
forceinline
RangeList::RangeList(void) {}
forceinline
RangeList::RangeList(const Gecode::RangeList* s) : c(s) {}
forceinline void
RangeList::init(const Gecode::RangeList* s) { c = s; }
forceinline bool
RangeList::operator ()(void) const { return c != NULL; }
forceinline void
RangeList::operator ++(void) {
c = c->next();
}
forceinline int
RangeList::min(void) const {
return c->min();
}
forceinline int
RangeList::max(void) const {
return c->max();
}
forceinline unsigned int
RangeList::width(void) const {
return c->width();
}
}}}
// STATISTICS: iter-any
| 27.646552 | 74 | 0.664172 | LeslieW |
abfcc2cdffcf23f0d8427cb5d2994f80ff70ef75 | 5,329 | cc | C++ | test/string_view_test.cc | WilliamTambellini/cpu_features | 20fa92a02ae724f4532b7e12691633a43dec7772 | [
"Apache-2.0"
] | 5 | 2020-12-19T06:56:06.000Z | 2022-01-09T01:28:42.000Z | test/string_view_test.cc | WilliamTambellini/cpu_features | 20fa92a02ae724f4532b7e12691633a43dec7772 | [
"Apache-2.0"
] | 1 | 2021-09-27T06:00:40.000Z | 2021-09-27T06:00:40.000Z | test/string_view_test.cc | WilliamTambellini/cpu_features | 20fa92a02ae724f4532b7e12691633a43dec7772 | [
"Apache-2.0"
] | 3 | 2020-12-19T06:56:27.000Z | 2021-09-26T18:50:44.000Z | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "internal/string_view.h"
#include "gtest/gtest.h"
namespace cpu_features {
bool operator==(const StringView& a, const StringView& b) {
return CpuFeatures_StringView_IsEquals(a, b);
}
namespace {
TEST(StringViewTest, Empty) {
EXPECT_EQ(kEmptyStringView.ptr, nullptr);
EXPECT_EQ(kEmptyStringView.size, 0);
}
TEST(StringViewTest, Build) {
const auto view = str("test");
EXPECT_EQ(view.ptr[0], 't');
EXPECT_EQ(view.size, 4);
}
TEST(StringViewTest, CpuFeatures_StringView_IndexOfChar) {
// Found.
EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("test"), 'e'), 1);
// Not found.
EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("test"), 'z'), -1);
// Empty.
EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(kEmptyStringView, 'z'), -1);
}
TEST(StringViewTest, CpuFeatures_StringView_IndexOf) {
// Found.
EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("test"), str("es")), 1);
// Not found.
EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("test"), str("aa")), -1);
// Empty.
EXPECT_EQ(CpuFeatures_StringView_IndexOf(kEmptyStringView, str("aa")), -1);
EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("aa"), kEmptyStringView), -1);
}
TEST(StringViewTest, CpuFeatures_StringView_StartsWith) {
EXPECT_TRUE(CpuFeatures_StringView_StartsWith(str("test"), str("te")));
EXPECT_FALSE(CpuFeatures_StringView_StartsWith(str("test"), str("")));
EXPECT_FALSE(
CpuFeatures_StringView_StartsWith(str("test"), kEmptyStringView));
EXPECT_FALSE(
CpuFeatures_StringView_StartsWith(kEmptyStringView, str("test")));
}
TEST(StringViewTest, CpuFeatures_StringView_IsEquals) {
EXPECT_TRUE(
CpuFeatures_StringView_IsEquals(kEmptyStringView, kEmptyStringView));
EXPECT_TRUE(CpuFeatures_StringView_IsEquals(kEmptyStringView, str("")));
EXPECT_TRUE(CpuFeatures_StringView_IsEquals(str(""), kEmptyStringView));
EXPECT_TRUE(CpuFeatures_StringView_IsEquals(str("a"), str("a")));
EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("a"), str("b")));
EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("a"), kEmptyStringView));
EXPECT_FALSE(CpuFeatures_StringView_IsEquals(kEmptyStringView, str("a")));
}
TEST(StringViewTest, CpuFeatures_StringView_PopFront) {
EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 2), str("st"));
EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 0), str("test"));
EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 4), str(""));
EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 100), str(""));
}
TEST(StringViewTest, CpuFeatures_StringView_ParsePositiveNumber) {
EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("42")), 42);
EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2a")), 42);
EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2A")), 42);
EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("-0x2A")), -1);
EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("abc")), -1);
EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("")), -1);
}
TEST(StringViewTest, CpuFeatures_StringView_CopyString) {
char buf[4];
buf[0] = 'X';
// Empty
CpuFeatures_StringView_CopyString(str(""), buf, sizeof(buf));
EXPECT_STREQ(buf, "");
// Less
CpuFeatures_StringView_CopyString(str("a"), buf, sizeof(buf));
EXPECT_STREQ(buf, "a");
// exact
CpuFeatures_StringView_CopyString(str("abc"), buf, sizeof(buf));
EXPECT_STREQ(buf, "abc");
// More
CpuFeatures_StringView_CopyString(str("abcd"), buf, sizeof(buf));
EXPECT_STREQ(buf, "abc");
}
TEST(StringViewTest, CpuFeatures_StringView_HasWord) {
// Find flags at beginning, middle and end.
EXPECT_TRUE(
CpuFeatures_StringView_HasWord(str("first middle last"), "first"));
EXPECT_TRUE(
CpuFeatures_StringView_HasWord(str("first middle last"), "middle"));
EXPECT_TRUE(CpuFeatures_StringView_HasWord(str("first middle last"), "last"));
// Do not match partial flags
EXPECT_FALSE(
CpuFeatures_StringView_HasWord(str("first middle last"), "irst"));
EXPECT_FALSE(CpuFeatures_StringView_HasWord(str("first middle last"), "mid"));
EXPECT_FALSE(CpuFeatures_StringView_HasWord(str("first middle last"), "las"));
}
TEST(StringViewTest, CpuFeatures_StringView_GetAttributeKeyValue) {
const StringView line = str(" key : first middle last ");
StringView key, value;
EXPECT_TRUE(CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value));
EXPECT_EQ(key, str("key"));
EXPECT_EQ(value, str("first middle last"));
}
TEST(StringViewTest, FailingGetAttributeKeyValue) {
const StringView line = str("key first middle last");
StringView key, value;
EXPECT_FALSE(CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value));
}
} // namespace
} // namespace cpu_features
| 36.751724 | 80 | 0.750422 | WilliamTambellini |
28004a673c9dcf40e10372183a58c071e8dffe64 | 2,625 | cpp | C++ | export/windows/obj/src/resources/__res_27.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/resources/__res_27.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/resources/__res_27.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.4.7
namespace hx {
unsigned char __res_27[] = {
0xff, 0xff, 0xff, 0xff,
137,80,78,71,13,10,26,10,0,0,
0,13,73,72,68,82,0,0,0,24,
0,0,0,32,8,6,0,0,0,8,
94,184,56,0,0,0,25,116,69,88,
116,83,111,102,116,119,97,114,101,0,
65,100,111,98,101,32,73,109,97,103,
101,82,101,97,100,121,113,201,101,60,
0,0,2,100,73,68,65,84,120,218,
180,150,207,107,19,65,20,199,191,59,
217,132,160,38,84,210,74,37,169,86,
250,195,34,168,69,80,130,160,248,39,
136,34,10,158,20,79,226,77,16,188,
164,180,23,143,34,244,226,15,66,162,
101,211,36,133,180,57,85,4,49,55,
65,68,137,57,91,165,173,144,162,82,
108,105,195,166,201,250,102,77,150,221,
52,27,179,233,228,193,219,153,157,89,
190,159,125,51,195,123,35,5,66,193,
8,128,41,116,201,92,251,252,254,119,
212,106,228,185,110,0,228,90,59,201,
31,15,39,167,91,70,242,104,226,158,
99,0,227,15,77,211,116,8,9,68,
68,71,32,209,30,104,149,74,21,140,
73,144,36,137,143,77,216,69,114,255,
246,101,91,161,222,129,144,125,4,186,
105,82,189,39,52,18,3,112,229,234,
117,140,14,143,8,135,24,128,3,62,
63,158,60,158,198,177,193,65,161,16,
102,126,217,40,85,48,159,74,227,232,
192,17,97,16,11,96,187,164,66,99,
30,44,164,211,8,5,131,66,32,172,
113,96,105,185,168,139,103,102,147,56,
220,223,191,103,200,46,192,159,205,45,
252,94,223,208,247,130,67,14,245,245,
25,16,58,138,145,61,3,184,125,93,
41,234,237,240,208,16,50,201,36,2,
129,64,199,144,166,128,226,207,117,108,
110,149,244,254,241,145,81,61,146,131,
61,61,29,65,152,221,196,82,45,10,
110,39,198,198,48,167,40,240,251,124,
142,33,182,128,213,226,47,168,229,29,
227,253,244,201,83,4,73,56,134,216,
2,120,126,250,190,186,102,25,59,51,
62,14,37,30,135,215,235,109,27,194,
90,77,126,251,177,134,74,181,106,25,
11,159,61,135,212,171,153,182,33,45,
1,170,186,163,47,85,163,157,15,135,
49,19,141,194,227,118,195,84,79,34,
142,1,141,155,109,182,75,23,46,34,
254,252,197,127,33,114,43,241,89,37,
134,124,254,19,109,236,126,18,106,254,
41,95,42,181,92,54,67,96,174,241,
182,128,84,226,37,22,230,211,255,62,
146,93,96,46,214,238,209,183,64,154,
2,178,36,156,201,36,193,11,156,44,
203,144,152,228,52,67,24,144,93,128,
215,139,89,36,104,105,24,99,144,221,
46,62,244,150,252,65,135,201,212,99,
1,228,114,111,16,139,62,53,47,201,
34,47,118,84,163,183,59,173,201,6,
224,227,135,247,40,20,242,112,19,179,
86,252,179,228,215,72,92,21,82,112,
190,20,62,211,95,27,55,139,57,17,
226,70,4,46,235,9,225,226,55,155,
137,219,45,131,147,84,161,144,223,16,
241,231,150,139,87,173,31,35,191,195,
243,156,200,155,93,61,130,103,228,183,
68,139,215,111,215,189,212,222,237,214,
245,253,175,0,3,0,153,80,196,12,
205,10,29,203,0,0,0,0,73,69,
78,68,174,66,96,130,0x00 };
}
| 34.090909 | 39 | 0.690667 | seanbashaw |
28038deb08ecca4ac7c17a4b8fa1206392ac153c | 2,541 | cpp | C++ | src/engineDX7/caption.cpp | FreeAllegiance/Allegiance-AZ | 1d8678ddff9e2efc79ed449de6d47544989bc091 | [
"MIT"
] | 1 | 2017-09-11T22:18:19.000Z | 2017-09-11T22:18:19.000Z | src/engineDX7/caption.cpp | FreeAllegiance/Allegiance-AZ | 1d8678ddff9e2efc79ed449de6d47544989bc091 | [
"MIT"
] | 2 | 2017-09-12T18:28:33.000Z | 2017-09-13T06:15:36.000Z | src/engineDX7/caption.cpp | FreeAllegiance/Allegiance-AZ | 1d8678ddff9e2efc79ed449de6d47544989bc091 | [
"MIT"
] | null | null | null | #include "pch.h"
//////////////////////////////////////////////////////////////////////////////
//
//
//
//////////////////////////////////////////////////////////////////////////////
class CaptionImpl :
public ICaption,
public EventTargetContainer<CaptionImpl>
{
private:
TRef<ButtonPane> m_pbuttonClose;
TRef<ButtonPane> m_pbuttonRestore;
TRef<ButtonPane> m_pbuttonMinimize;
TRef<Pane> m_ppane;
TRef<ICaptionSite> m_psite;
void DoCreateButton(
Modeler* pmodeler,
TRef<ButtonPane>& pbuttonPane,
const ZString& str,
const WinPoint& offset,
Pane* ppane
) {
TRef<ButtonFacePane> pface =
CreateButtonFacePane(
pmodeler->LoadSurface(str, false),
ButtonFaceUp | ButtonFaceDown
);
pbuttonPane = CreateButton(pface);
pbuttonPane->SetOffset(offset);
ppane->InsertAtTop(pbuttonPane);
}
public:
CaptionImpl(Modeler* pmodeler, Pane* ppane, ICaptionSite* psite) :
m_ppane(ppane),
m_psite(psite)
{
DoCreateButton(pmodeler, m_pbuttonClose, "btnclosebmp", WinPoint(780, 5), ppane);
DoCreateButton(pmodeler, m_pbuttonRestore, "btnrestorebmp", WinPoint(761, 5), ppane);
DoCreateButton(pmodeler, m_pbuttonMinimize, "btnminimizebmp", WinPoint(744, 5), ppane);
// mdvalley: Three pointers and class names
AddEventTarget(&CaptionImpl::OnClose, m_pbuttonClose->GetEventSource());
AddEventTarget(&CaptionImpl::OnRestore, m_pbuttonRestore->GetEventSource());
AddEventTarget(&CaptionImpl::OnMinimize, m_pbuttonMinimize->GetEventSource());
}
bool OnClose()
{
m_psite->OnCaptionClose();
return true;
}
bool OnMinimize()
{
m_psite->OnCaptionMinimize();
return true;
}
bool OnRestore()
{
m_psite->OnCaptionRestore();
return true;
}
void SetFullscreen(bool bFullscreen)
{
m_pbuttonClose->SetHidden(!bFullscreen);
m_pbuttonRestore->SetHidden(!bFullscreen);
m_pbuttonMinimize->SetHidden(!bFullscreen);
}
};
//////////////////////////////////////////////////////////////////////////////
//
//
//
//////////////////////////////////////////////////////////////////////////////
TRef<ICaption> CreateCaption(Modeler* pmodeler, Pane* ppane, ICaptionSite* psite)
{
return new CaptionImpl(pmodeler, ppane, psite);
}
| 28.550562 | 95 | 0.541913 | FreeAllegiance |
2805ad8a83ec54c69cd93b852397396041a7e2ef | 7,637 | cpp | C++ | lib/small_range.cpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | lib/small_range.cpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | lib/small_range.cpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | #include <crab/domains/small_range.hpp>
#include <crab/support/debug.hpp>
#include <assert.h>
namespace crab {
namespace domains {
small_range::small_range(kind_t v) : m_value(v){};
/*
[0,0] | [0,0] = [0,0]
[0,0] | [1,1] = [0,1]
[0,0] | [0,1] = [0,1]
[0,0] | [0,+oo] = [0,+oo]
[0,0] | [1,+oo] = [0,+oo]
*/
small_range small_range::join_zero_with(const small_range &other) const {
if (other.m_value == ExactlyZero) {
return other;
} else if (other.m_value == ExactlyOne) {
return small_range(ZeroOrOne);
} else if (other.m_value == ZeroOrOne) {
return other;
} else {
return small_range(ZeroOrMore);
}
}
/*
[1,1] | [0,0] = [0,1]
[1,1] | [1,1] = [1,+oo]
[1,1] | [0,1] = [0,+oo]
[1,1] | [0,+oo] = [0,+oo]
[1,1] | [1,+oo] = [1,+oo]
*/
small_range small_range::join_one_with(const small_range &other) const {
if (other.m_value == ExactlyZero) {
return small_range(ZeroOrOne);
} else if (other.m_value == ExactlyOne) {
return small_range(OneOrMore);
} else if (other.m_value == OneOrMore) {
return other;
} else {
return small_range(ZeroOrMore);
}
}
/*
[0,1] | [0,0] = [0,1]
[0,1] | [1,1] = [0,+oo]
[0,1] | [0,1] = [0,+oo]
[0,1] | [0,+oo] = [0,+oo]
[0,1] | [1,+oo] = [0,+oo]
*/
small_range small_range::join_zero_or_one_with(const small_range &other) const {
if (other.m_value == ExactlyZero) {
return small_range(ZeroOrOne);
} else {
return small_range(ZeroOrMore);
}
}
/*
[1,+oo] | [0,0] = [0,+oo]
[1,+oo] | [1,1] = [1,+oo]
[1,+oo] | [0,1] = [0,+oo]
[1,+oo] | [0,+oo] = [0,+oo]
[1,+oo] | [1,+oo] = [1,+oo]
*/
small_range small_range::join_one_or_more_with(const small_range &other) const {
if (other.m_value == ExactlyOne || other.m_value == OneOrMore) {
return small_range(OneOrMore);
} else {
return small_range(ZeroOrMore);
}
}
/*
[0,0] & [0,0] = [0,0]
[0,0] & [1,1] = _|_
[0,0] & [0,1] = [0,0]
[0,0] & [0,+oo] = [0,0]
[0,0] & [1,+oo] = _|_
*/
small_range small_range::meet_zero_with(const small_range &other) const {
assert(is_zero());
if (other.m_value == ExactlyOne || other.m_value == OneOrMore) {
return small_range::bottom();
} else {
return *this;
}
}
/*
[1,1] & [0,0] = _|_
[1,1] & [1,1] = [1,1]
[1,1] & [0,1] = [1,1]
[1,1] & [0,+oo] = [1,1]
[1,1] & [1,+oo] = [1,1]
*/
small_range small_range::meet_one_with(const small_range &other) const {
assert(is_one());
if (other.m_value == ExactlyZero) {
return small_range::bottom();
} else {
return *this;
}
}
/*
[0,1] & [0,0] = [0,0]
[0,1] & [1,1] = [1,1]
[0,1] & [0,1] = [0,1]
[0,1] & [0,+oo] = [0,1]
[0,1] & [1,+oo] = [1,1]
*/
small_range small_range::meet_zero_or_one_with(const small_range &other) const {
assert(m_value == ZeroOrOne);
if (other.is_zero() || other.is_one()) {
return other;
} else if (other.m_value == OneOrMore) {
return one();
} else {
return *this;
}
}
/*
[1,+oo] & [0,0] = _|_
[1,+oo] & [1,1] = [1,1]
[1,+oo] & [0,1] = [1,1]
[1,+oo] & [0,+oo] = [1,+oo]
[1,+oo] & [1,+oo] = [1,+oo]
*/
small_range small_range::meet_one_or_more_with(const small_range &other) const {
if (other.is_zero()) {
return small_range::bottom();
} else if (other.is_one()) {
return other;
} else if (other.m_value == ZeroOrOne) {
return one();
} else {
assert(other.is_top() || other.m_value == OneOrMore);
return *this;
}
}
small_range::small_range() : m_value(ZeroOrMore) {}
small_range small_range::bottom() { return small_range(Bottom); }
small_range small_range::top() { return small_range(ZeroOrMore); }
small_range small_range::zero() { return small_range(ExactlyZero); }
small_range small_range::one() { return small_range(ExactlyOne); }
small_range small_range::oneOrMore() { return small_range(OneOrMore); }
bool small_range::is_bottom() const { return (m_value == Bottom); }
bool small_range::is_top() const { return (m_value == ZeroOrMore); }
bool small_range::is_zero() const { return (m_value == ExactlyZero); }
bool small_range::is_one() const { return (m_value == ExactlyOne); }
/*
[0,+oo]
| \
| \
[0,1] [1,+oo]
/ \ /
0 1
*/
bool small_range::operator<=(small_range other) const {
if (m_value == other.m_value) {
return true;
} else if (m_value == Bottom || other.m_value == ZeroOrMore) {
return true;
} else if (m_value == ExactlyZero) {
return other.m_value != ExactlyOne && other.m_value != OneOrMore;
} else if (m_value == ExactlyOne) {
return other.m_value != ExactlyZero;
} else if (m_value == ZeroOrOne || m_value == OneOrMore) {
return other.m_value == ZeroOrMore;
} else if (m_value == ZeroOrMore) {
assert(other.m_value != ZeroOrMore);
return false;
}
// should be unreachable
return false;
}
bool small_range::operator==(small_range other) const { return m_value == other.m_value; }
small_range small_range::operator|(small_range other) const {
if (is_bottom()) {
return other;
} else if (other.is_bottom()) {
return *this;
} else if (is_zero()) {
return join_zero_with(other);
} else if (other.is_zero()) {
return join_zero_with(*this);
} else if (is_one()) {
return join_one_with(other);
} else if (other.is_one()) {
return join_one_with(*this);
} else if (m_value == ZeroOrOne) {
return join_zero_or_one_with(other);
} else if (other.m_value == ZeroOrOne) {
return join_zero_or_one_with(*this);
} else if (m_value == OneOrMore) {
return join_one_or_more_with(other);
} else if (other.m_value == OneOrMore) {
return join_one_or_more_with(*this);
} else {
return small_range(ZeroOrMore);
}
}
small_range small_range::operator||(small_range other) const { return *this | other; }
small_range small_range::operator&(small_range other) const {
if (is_bottom() || other.is_top()) {
return *this;
} else if (other.is_bottom() || is_top()) {
return other;
}
if (is_zero()) {
return meet_zero_with(other);
} else if (other.is_zero()) {
return other.meet_zero_with(*this);
} else if (is_one()) {
return meet_one_with(other);
} else if (other.is_one()) {
return other.meet_one_with(*this);
} else if (m_value == ZeroOrOne) {
return meet_zero_or_one_with(other);
} else if (other.m_value == ZeroOrOne) {
return other.meet_zero_or_one_with(*this);
} else if (m_value == OneOrMore) {
return meet_one_or_more_with(other);
} else if (other.m_value == OneOrMore) {
return other.meet_one_or_more_with(*this);
} else { // unreachable because top cases handled above
CRAB_ERROR("unexpected small_range::meet operands");
}
}
small_range small_range::operator&&(small_range other) const { return *this & other; }
small_range small_range::increment(void) {
if (!is_bottom()) {
if (m_value == ExactlyZero) {
m_value = ExactlyOne;
} else if (m_value == ExactlyOne || m_value == ZeroOrMore ||
m_value == ZeroOrOne || m_value == OneOrMore) {
m_value = OneOrMore;
} else {
CRAB_ERROR("small_range::increment unreachable");
}
}
return *this;
}
void small_range::write(crab_os &o) const {
switch (m_value) {
case Bottom:
o << "_|_";
break;
case ExactlyZero:
o << "[0,0]";
break;
case ExactlyOne:
o << "[1,1]";
break;
case ZeroOrOne:
o << "[0,1]";
break;
case ZeroOrMore:
o << "[0,+oo]";
break;
case OneOrMore:
o << "[1,+oo]";
break;
default:
CRAB_ERROR("unexpected small_range value");
}
}
} // end namespace domains
} // end namespace crab
| 26.243986 | 90 | 0.603116 | LinerSu |
28071e2199a013b840686fcace33fc8b113b0b63 | 5,531 | cpp | C++ | people_tracking_filter/src/tracker_particle.cpp | jdddog/people | 8a8254a071e966db90d1d077a051f2d2926aa9af | [
"BSD-3-Clause"
] | 2 | 2018-06-10T19:17:41.000Z | 2021-11-09T10:17:23.000Z | people/people_tracking_filter/src/tracker_particle.cpp | procopiostein/leader | c2daa37e1c7071a3536c53c0cc4544f289923170 | [
"BSD-3-Clause"
] | 1 | 2018-05-05T02:48:42.000Z | 2018-05-05T02:48:42.000Z | people_tracking_filter/src/tracker_particle.cpp | jdddog/people | 8a8254a071e966db90d1d077a051f2d2926aa9af | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Wim Meeussen */
#include "people_tracking_filter/tracker_particle.h"
#include "people_tracking_filter/gaussian_pos_vel.h"
using namespace MatrixWrapper;
using namespace BFL;
using namespace tf;
using namespace std;
using namespace ros;
namespace estimation
{
// constructor
TrackerParticle::TrackerParticle(const string& name, unsigned int num_particles, const StatePosVel& sysnoise):
Tracker(name),
prior_(num_particles),
filter_(NULL),
sys_model_(sysnoise),
meas_model_(tf::Vector3(0.1,0.1,0.1)),
tracker_initialized_(false),
num_particles_(num_particles)
{};
// destructor
TrackerParticle::~TrackerParticle(){
if (filter_) delete filter_;
};
// initialize prior density of filter
void TrackerParticle::initialize(const StatePosVel& mu, const StatePosVel& sigma, const double time)
{
cout << "Initializing tracker with " << num_particles_ << " particles, with covariance "
<< sigma << " around " << mu << endl;
GaussianPosVel gauss_pos_vel(mu, sigma);
vector<Sample<StatePosVel> > prior_samples(num_particles_);
gauss_pos_vel.SampleFrom(prior_samples, num_particles_, CHOLESKY, NULL);
prior_.ListOfSamplesSet(prior_samples);
filter_ = new BootstrapFilter<StatePosVel, tf::Vector3>(&prior_, &prior_, 0, num_particles_/4.0);
// tracker initialized
tracker_initialized_ = true;
quality_ = 1;
filter_time_ = time;
init_time_ = time;
}
// update filter prediction
bool TrackerParticle::updatePrediction(const double time)
{
bool res = true;
if (time > filter_time_){
// set dt in sys model
sys_model_.SetDt(time - filter_time_);
filter_time_ = time;
// update filter
res = filter_->Update(&sys_model_);
if (!res) quality_ = 0;
}
return res;
};
// update filter correction
bool TrackerParticle::updateCorrection(const tf::Vector3& meas, const MatrixWrapper::SymmetricMatrix& cov)
{
assert(cov.columns() == 3);
// set covariance
((MeasPdfPos*)(meas_model_.MeasurementPdfGet()))->CovarianceSet(cov);
// update filter
bool res = filter_->Update(&meas_model_, meas);
if (!res) quality_ = 0;
return res;
};
// get evenly spaced particle cloud
void TrackerParticle::getParticleCloud(const tf::Vector3& step, double threshold, sensor_msgs::PointCloud& cloud) const
{
((MCPdfPosVel*)(filter_->PostGet()))->getParticleCloud(step, threshold, cloud);
};
// get most recent filter posterior
void TrackerParticle::getEstimate(StatePosVel& est) const
{
est = ((MCPdfPosVel*)(filter_->PostGet()))->ExpectedValueGet();
};
void TrackerParticle::getEstimate(people_msgs::PositionMeasurement& est) const
{
StatePosVel tmp = filter_->PostGet()->ExpectedValueGet();
est.pos.x = tmp.pos_[0];
est.pos.y = tmp.pos_[1];
est.pos.z = tmp.pos_[2];
est.header.stamp.fromSec( filter_time_ );
est.object_id = getName();
}
/// Get histogram from certain area
Matrix TrackerParticle::getHistogramPos(const tf::Vector3& min, const tf::Vector3& max, const tf::Vector3& step) const
{
return ((MCPdfPosVel*)(filter_->PostGet()))->getHistogramPos(min, max, step);
};
Matrix TrackerParticle::getHistogramVel(const tf::Vector3& min, const tf::Vector3& max, const tf::Vector3& step) const
{
return ((MCPdfPosVel*)(filter_->PostGet()))->getHistogramVel(min, max, step);
};
double TrackerParticle::getLifetime() const
{
if (tracker_initialized_)
return filter_time_ - init_time_;
else
return 0;
}
double TrackerParticle::getTime() const
{
if (tracker_initialized_)
return filter_time_;
else
return 0;
}
}; // namespace
| 29.110526 | 121 | 0.690472 | jdddog |
28090551b66ae9420e16ec1ef61fd2e67de9381a | 1,310 | hpp | C++ | module-apps/application-onboarding/windows/EULALicenseWindow.hpp | SP2FET/MuditaOS-1 | 2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd | [
"BSL-1.0"
] | 1 | 2021-11-11T22:56:43.000Z | 2021-11-11T22:56:43.000Z | module-apps/application-onboarding/windows/EULALicenseWindow.hpp | SP2FET/MuditaOS-1 | 2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd | [
"BSL-1.0"
] | null | null | null | module-apps/application-onboarding/windows/EULALicenseWindow.hpp | SP2FET/MuditaOS-1 | 2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include "AppWindow.hpp"
#include <module-apps/application-onboarding/presenter/EULALicenseWindowPresenter.hpp>
#include <module-gui/gui/widgets/Label.hpp>
#include <module-gui/gui/widgets/text/Text.hpp>
#include <module-gui/gui/input/InputEvent.hpp>
namespace app::onBoarding
{
class EULALicenseWindow : public gui::AppWindow, public EULALicenseWindowContract::View
{
public:
explicit EULALicenseWindow(app::ApplicationCommon *app,
std::unique_ptr<EULALicenseWindowContract::Presenter> &&windowPresenter);
~EULALicenseWindow() noexcept override;
gui::status_bar::Configuration configureStatusBar(gui::status_bar::Configuration appConfiguration) override;
void onBeforeShow(gui::ShowMode mode, gui::SwitchData *data) override;
bool onInput(const gui::InputEvent &inputEvent) override;
void rebuild() override;
void buildInterface() override;
void destroyInterface() override;
private:
std::unique_ptr<EULALicenseWindowContract::Presenter> presenter;
gui::Text *eulaText = nullptr;
};
} // namespace app::onBoarding
| 36.388889 | 116 | 0.712977 | SP2FET |
28094a5b58ef4275742f10f06786e19964f3bc12 | 936 | hpp | C++ | world/tiles/include/DigChances.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | world/tiles/include/DigChances.hpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | world/tiles/include/DigChances.hpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #pragma once
#include "ISerializable.hpp"
#include <string>
#include <vector>
class DigChances : public ISerializable
{
public:
DigChances();
DigChances(const int new_pct_chance_undead, const int new_pct_chance_item, const std::vector<std::string>& new_item_ids);
bool operator==(const DigChances& dc) const;
void set_pct_chance_undead(const int new_pct_chance_undead);
int get_pct_chance_undead() const;
void set_pct_chance_item(const int new_pct_chance_item);
int get_pct_chance_item() const;
void set_item_ids(const std::vector<std::string>& new_item_ids);
std::vector<std::string> get_item_ids() const;
bool serialize(std::ostream& stream) const override;
bool deserialize(std::istream& stream);
protected:
int pct_chance_undead;
int pct_chance_item;
std::vector<std::string> item_ids;
private:
ClassIdentifier internal_class_identifier() const override;
};
| 26.742857 | 125 | 0.74359 | sidav |
280a5199d107c4755551501dec08f770a2e05e2d | 6,855 | cpp | C++ | Vendor/assimp/test/unit/utFindDegenerates.cpp | mallonoce/BaseOpenGLProject | 597a2ee2619cfa666856f32ee95f7943c6ae5223 | [
"MIT"
] | 1 | 2021-01-07T14:33:22.000Z | 2021-01-07T14:33:22.000Z | Vendor/assimp/test/unit/utFindDegenerates.cpp | mallonoce/BaseOpenGLProject | 597a2ee2619cfa666856f32ee95f7943c6ae5223 | [
"MIT"
] | 1 | 2022-03-26T07:18:59.000Z | 2022-03-26T07:18:59.000Z | Vendor/assimp/test/unit/utFindDegenerates.cpp | mallonoce/BaseOpenGLProject | 597a2ee2619cfa666856f32ee95f7943c6ae5223 | [
"MIT"
] | null | null | null | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
#include "UnitTestPCH.h"
#include "../../include/assimp/scene.h"
#include "PostProcessing/FindDegenerates.h"
#include <memory>
using namespace std;
using namespace Assimp;
class FindDegeneratesProcessTest : public ::testing::Test {
public:
FindDegeneratesProcessTest() :
Test(), mMesh(nullptr), mProcess(nullptr) {
// empty
}
protected:
virtual void SetUp();
virtual void TearDown();
protected:
aiMesh *mMesh;
FindDegeneratesProcess *mProcess;
};
void FindDegeneratesProcessTest::SetUp() {
mMesh = new aiMesh();
mProcess = new FindDegeneratesProcess();
mMesh->mNumFaces = 1000;
mMesh->mFaces = new aiFace[1000];
mMesh->mNumVertices = 5000 * 2;
mMesh->mVertices = new aiVector3D[5000 * 2];
for (unsigned int i = 0; i < 5000; ++i) {
mMesh->mVertices[i] = mMesh->mVertices[i + 5000] = aiVector3D((float)i);
}
mMesh->mPrimitiveTypes = aiPrimitiveType_LINE | aiPrimitiveType_POINT |
aiPrimitiveType_POLYGON | aiPrimitiveType_TRIANGLE;
unsigned int numOut = 0, numFaces = 0;
for (unsigned int i = 0; i < 1000; ++i) {
aiFace &f = mMesh->mFaces[i];
f.mNumIndices = (i % 5) + 1; // between 1 and 5
f.mIndices = new unsigned int[f.mNumIndices];
bool had = false;
for (unsigned int n = 0; n < f.mNumIndices; ++n) {
// FIXME
#if 0
// some duplicate indices
if ( n && n == (i / 200)+1) {
f.mIndices[n] = f.mIndices[n-1];
had = true;
}
// and some duplicate vertices
#endif
if (n && i % 2 && 0 == n % 2) {
f.mIndices[n] = f.mIndices[n - 1] + 5000;
had = true;
} else {
f.mIndices[n] = numOut++;
}
}
if (!had)
++numFaces;
}
mMesh->mNumUVComponents[0] = numOut;
mMesh->mNumUVComponents[1] = numFaces;
}
void FindDegeneratesProcessTest::TearDown() {
delete mMesh;
delete mProcess;
}
TEST_F(FindDegeneratesProcessTest, testDegeneratesDetection) {
mProcess->EnableInstantRemoval(false);
mProcess->ExecuteOnMesh(mMesh);
unsigned int out = 0;
for (unsigned int i = 0; i < 1000; ++i) {
aiFace &f = mMesh->mFaces[i];
out += f.mNumIndices;
}
EXPECT_EQ(1000U, mMesh->mNumFaces);
EXPECT_EQ(10000U, mMesh->mNumVertices);
EXPECT_EQ(out, mMesh->mNumUVComponents[0]);
EXPECT_EQ(static_cast<unsigned int>(
aiPrimitiveType_LINE | aiPrimitiveType_POINT |
aiPrimitiveType_POLYGON | aiPrimitiveType_TRIANGLE),
mMesh->mPrimitiveTypes);
}
TEST_F(FindDegeneratesProcessTest, testDegeneratesRemoval) {
mProcess->EnableAreaCheck(false);
mProcess->EnableInstantRemoval(true);
mProcess->ExecuteOnMesh(mMesh);
EXPECT_EQ(mMesh->mNumUVComponents[1], mMesh->mNumFaces);
}
TEST_F(FindDegeneratesProcessTest, testDegeneratesRemovalWithAreaCheck) {
mProcess->EnableAreaCheck(true);
mProcess->EnableInstantRemoval(true);
mProcess->ExecuteOnMesh(mMesh);
EXPECT_EQ(mMesh->mNumUVComponents[1] - 100, mMesh->mNumFaces);
}
namespace
{
std::unique_ptr<aiMesh> getDegenerateMesh()
{
std::unique_ptr<aiMesh> mesh(new aiMesh);
mesh->mNumVertices = 2;
mesh->mVertices = new aiVector3D[2];
mesh->mVertices[0] = aiVector3D{ 0.0f, 0.0f, 0.0f };
mesh->mVertices[1] = aiVector3D{ 1.0f, 0.0f, 0.0f };
mesh->mNumFaces = 1;
mesh->mFaces = new aiFace[1];
mesh->mFaces[0].mNumIndices = 3;
mesh->mFaces[0].mIndices = new unsigned int[3];
mesh->mFaces[0].mIndices[0] = 0;
mesh->mFaces[0].mIndices[1] = 1;
mesh->mFaces[0].mIndices[2] = 0;
return mesh;
}
}
TEST_F(FindDegeneratesProcessTest, meshRemoval) {
mProcess->EnableAreaCheck(true);
mProcess->EnableInstantRemoval(true);
mProcess->ExecuteOnMesh(mMesh);
std::unique_ptr<aiScene> scene(new aiScene);
scene->mNumMeshes = 5;
scene->mMeshes = new aiMesh*[5];
/// Use the mesh which doesn't get completely stripped of faces from the main test.
aiMesh* meshWhichSurvives = mMesh;
mMesh = nullptr;
scene->mMeshes[0] = getDegenerateMesh().release();
scene->mMeshes[1] = getDegenerateMesh().release();
scene->mMeshes[2] = meshWhichSurvives;
scene->mMeshes[3] = getDegenerateMesh().release();
scene->mMeshes[4] = getDegenerateMesh().release();
scene->mRootNode = new aiNode;
scene->mRootNode->mNumMeshes = 5;
scene->mRootNode->mMeshes = new unsigned int[5];
scene->mRootNode->mMeshes[0] = 0;
scene->mRootNode->mMeshes[1] = 1;
scene->mRootNode->mMeshes[2] = 2;
scene->mRootNode->mMeshes[3] = 3;
scene->mRootNode->mMeshes[4] = 4;
mProcess->Execute(scene.get());
EXPECT_EQ(scene->mNumMeshes, 1);
EXPECT_EQ(scene->mMeshes[0], meshWhichSurvives);
EXPECT_EQ(scene->mRootNode->mNumMeshes, 1);
EXPECT_EQ(scene->mRootNode->mMeshes[0], 0);
}
| 32.799043 | 87 | 0.643764 | mallonoce |
28102ee57483a3ce6077ae6b09cc355c93d8b09d | 918 | cpp | C++ | CoreTests/Script/Test_Eval.cpp | azhirnov/GraphicsGenFramework-modular | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | 12 | 2017-12-23T14:24:57.000Z | 2020-10-02T19:52:12.000Z | CoreTests/Script/Test_Eval.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | CoreTests/Script/Test_Eval.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "CoreTests/Script/Common.h"
class Script
{
public:
static ScriptEngine * engine;
int Run (int value)
{
const char script[] = R"#(
int main (int x) {
return 10 + x;
}
)#";
ScriptModulePtr mod = New<ScriptModule>( engine );
mod->Create( "def1" );
int res = 0;
mod->Run( script, "main", OUT res, value );
return res;
}
};
ScriptEngine * Script::engine = null;
static void Test_ScriptInScript (ScriptEngine &se)
{
const char script[] = R"#(
int main ()
{
Script sc;
return sc.Run( 1 );
}
)#";
Script::engine = &se;
ClassBinder<Script> binder{ &se, "Script" };
binder.CreateClassValue();
binder.AddMethod( &Script::Run, "Run" );
int res = 0;
se.Run( script, "main", OUT res );
TEST( res == 11 );
}
extern void Test_Eval ()
{
ScriptEngine se;
Test_ScriptInScript( se );
}
| 14.806452 | 72 | 0.618736 | azhirnov |
2815d744bc1be7abdc029823f1e835c90446b7b7 | 15,932 | cpp | C++ | test/beast/http/read.cpp | bebuch/beast | 2454d671653844d8435f4f066946a7751a758db7 | [
"BSL-1.0"
] | null | null | null | test/beast/http/read.cpp | bebuch/beast | 2454d671653844d8435f4f066946a7751a758db7 | [
"BSL-1.0"
] | null | null | null | test/beast/http/read.cpp | bebuch/beast | 2454d671653844d8435f4f066946a7751a758db7 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//
// Test that header file is self-contained.
#include <boost/beast/http/read.hpp>
#include "test_parser.hpp"
#include <boost/beast/core/ostream.hpp>
#include <boost/beast/core/flat_static_buffer.hpp>
#include <boost/beast/http/fields.hpp>
#include <boost/beast/http/dynamic_body.hpp>
#include <boost/beast/http/parser.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/_experimental/test/stream.hpp>
#include <boost/beast/_experimental/unit_test/suite.hpp>
#include <boost/beast/test/yield_to.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <atomic>
namespace boost {
namespace beast {
namespace http {
class read_test
: public beast::unit_test::suite
, public test::enable_yield_to
{
public:
template<bool isRequest>
void
failMatrix(char const* s, yield_context do_yield)
{
static std::size_t constexpr limit = 100;
std::size_t n;
auto const len = strlen(s);
for(n = 0; n < limit; ++n)
{
multi_buffer b;
b.commit(net::buffer_copy(
b.prepare(len), net::buffer(s, len)));
test::fail_count fc(n);
test::stream ts{ioc_, fc};
test_parser<isRequest> p(fc);
error_code ec = test::error::test_failure;
ts.close_remote();
read(ts, b, p, ec);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
for(n = 0; n < limit; ++n)
{
static std::size_t constexpr pre = 10;
multi_buffer b;
b.commit(net::buffer_copy(
b.prepare(pre), net::buffer(s, pre)));
test::fail_count fc(n);
test::stream ts{ioc_, fc,
std::string(s + pre, len - pre)};
test_parser<isRequest> p(fc);
error_code ec = test::error::test_failure;
ts.close_remote();
read(ts, b, p, ec);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
for(n = 0; n < limit; ++n)
{
multi_buffer b;
b.commit(net::buffer_copy(
b.prepare(len), net::buffer(s, len)));
test::fail_count fc(n);
test::stream ts{ioc_, fc};
test_parser<isRequest> p(fc);
error_code ec = test::error::test_failure;
ts.close_remote();
async_read(ts, b, p, do_yield[ec]);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
for(n = 0; n < limit; ++n)
{
multi_buffer b;
b.commit(net::buffer_copy(
b.prepare(len), net::buffer(s, len)));
test::fail_count fc(n);
test::stream ts{ioc_, fc};
test_parser<isRequest> p(fc);
error_code ec = test::error::test_failure;
ts.close_remote();
async_read_header(ts, b, p, do_yield[ec]);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
for(n = 0; n < limit; ++n)
{
static std::size_t constexpr pre = 10;
multi_buffer b;
b.commit(net::buffer_copy(
b.prepare(pre), net::buffer(s, pre)));
test::fail_count fc(n);
test::stream ts(ioc_, fc,
std::string{s + pre, len - pre});
test_parser<isRequest> p(fc);
error_code ec = test::error::test_failure;
ts.close_remote();
async_read(ts, b, p, do_yield[ec]);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
}
void testThrow()
{
try
{
multi_buffer b;
test::stream c{ioc_, "GET / X"};
c.close_remote();
request_parser<dynamic_body> p;
read(c, b, p);
fail();
}
catch(std::exception const&)
{
pass();
}
}
void
testBufferOverflow()
{
{
test::stream c{ioc_};
ostream(c.buffer()) <<
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"10\r\n"
"****************\r\n"
"0\r\n\r\n";
flat_static_buffer<1024> b;
request<string_body> req;
try
{
read(c, b, req);
pass();
}
catch(std::exception const& e)
{
fail(e.what(), __FILE__, __LINE__);
}
}
{
test::stream c{ioc_};
ostream(c.buffer()) <<
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"10\r\n"
"****************\r\n"
"0\r\n\r\n";
error_code ec = test::error::test_failure;
flat_static_buffer<10> b;
request<string_body> req;
read(c, b, req, ec);
BEAST_EXPECTS(ec == error::buffer_overflow,
ec.message());
}
}
void testFailures(yield_context do_yield)
{
char const* req[] = {
"GET / HTTP/1.0\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Empty:\r\n"
"\r\n"
,
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Content-Length: 2\r\n"
"\r\n"
"**"
,
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"10\r\n"
"****************\r\n"
"0\r\n\r\n"
,
nullptr
};
char const* res[] = {
"HTTP/1.0 200 OK\r\n"
"Server: test\r\n"
"\r\n"
,
"HTTP/1.0 200 OK\r\n"
"Server: test\r\n"
"\r\n"
"***"
,
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Content-Length: 3\r\n"
"\r\n"
"***"
,
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"10\r\n"
"****************\r\n"
"0\r\n\r\n"
,
nullptr
};
for(std::size_t i = 0; req[i]; ++i)
failMatrix<true>(req[i], do_yield);
for(std::size_t i = 0; res[i]; ++i)
failMatrix<false>(res[i], do_yield);
}
void testRead(yield_context do_yield)
{
static std::size_t constexpr limit = 100;
std::size_t n;
for(n = 0; n < limit; ++n)
{
test::fail_count fc{n};
test::stream c{ioc_, fc,
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
request<dynamic_body> m;
try
{
multi_buffer b;
read(c, b, m);
break;
}
catch(std::exception const&)
{
}
}
BEAST_EXPECT(n < limit);
for(n = 0; n < limit; ++n)
{
test::fail_count fc{n};
test::stream ts{ioc_, fc,
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
request<dynamic_body> m;
error_code ec = test::error::test_failure;
multi_buffer b;
read(ts, b, m, ec);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
for(n = 0; n < limit; ++n)
{
test::fail_count fc{n};
test::stream c{ioc_, fc,
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
request<dynamic_body> m;
error_code ec = test::error::test_failure;
multi_buffer b;
async_read(c, b, m, do_yield[ec]);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
for(n = 0; n < limit; ++n)
{
test::fail_count fc{n};
test::stream c{ioc_, fc,
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"User-Agent: test\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
request_parser<dynamic_body> m;
error_code ec = test::error::test_failure;
multi_buffer b;
async_read_some(c, b, m, do_yield[ec]);
if(! ec)
break;
}
BEAST_EXPECT(n < limit);
}
void
testEof(yield_context do_yield)
{
{
multi_buffer b;
test::stream ts{ioc_};
request_parser<dynamic_body> p;
error_code ec;
ts.close_remote();
read(ts, b, p, ec);
BEAST_EXPECT(ec == http::error::end_of_stream);
}
{
multi_buffer b;
test::stream ts{ioc_};
request_parser<dynamic_body> p;
error_code ec;
ts.close_remote();
async_read(ts, b, p, do_yield[ec]);
BEAST_EXPECT(ec == http::error::end_of_stream);
}
}
// Ensure completion handlers are not leaked
struct handler
{
static std::atomic<std::size_t>&
count() { static std::atomic<std::size_t> n; return n; }
handler() { ++count(); }
~handler() { --count(); }
handler(handler const&) { ++count(); }
void operator()(error_code const&, std::size_t) const {}
};
void
testIoService()
{
{
// Make sure handlers are not destroyed
// after calling io_context::stop
net::io_context ioc;
test::stream ts{ioc,
"GET / HTTP/1.1\r\n\r\n"};
BEAST_EXPECT(handler::count() == 0);
multi_buffer b;
request<dynamic_body> m;
async_read(ts, b, m, handler{});
BEAST_EXPECT(handler::count() > 0);
ioc.stop();
BEAST_EXPECT(handler::count() > 0);
ioc.restart();
BEAST_EXPECT(handler::count() > 0);
ioc.run_one();
BEAST_EXPECT(handler::count() == 0);
}
{
// Make sure uninvoked handlers are
// destroyed when calling ~io_context
{
net::io_context ioc;
test::stream ts{ioc,
"GET / HTTP/1.1\r\n\r\n"};
BEAST_EXPECT(handler::count() == 0);
multi_buffer b;
request<dynamic_body> m;
async_read(ts, b, m, handler{});
BEAST_EXPECT(handler::count() > 0);
}
BEAST_EXPECT(handler::count() == 0);
}
}
// https://github.com/boostorg/beast/issues/430
void
testRegression430()
{
test::stream ts{ioc_};
ts.read_size(1);
ostream(ts.buffer()) <<
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n"
"4\r\nabcd\r\n"
"0\r\n\r\n";
error_code ec;
flat_buffer fb;
response_parser<dynamic_body> p;
read(ts, fb, p, ec);
BEAST_EXPECTS(! ec, ec.message());
}
//--------------------------------------------------------------------------
template<class Parser, class Pred>
void
readgrind(string_view s, Pred&& pred)
{
for(std::size_t n = 1; n < s.size() - 1; ++n)
{
Parser p;
error_code ec = test::error::test_failure;
flat_buffer b;
test::stream ts{ioc_};
ostream(ts.buffer()) << s;
ts.read_size(n);
read(ts, b, p, ec);
if(! BEAST_EXPECTS(! ec, ec.message()))
continue;
pred(p);
}
}
void
testReadGrind()
{
readgrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n"
"4\r\nabcd\r\n"
"0\r\n\r\n"
,[&](test_parser<false> const& p)
{
BEAST_EXPECT(p.body == "abcd");
});
readgrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Expect: Expires, MD5-Fingerprint\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\n"
"*****\r\n"
"2;a;b=1;c=\"2\"\r\n"
"--\r\n"
"0;d;e=3;f=\"4\"\r\n"
"Expires: never\r\n"
"MD5-Fingerprint: -\r\n"
"\r\n"
,[&](test_parser<false> const& p)
{
BEAST_EXPECT(p.body == "*****--");
});
}
struct copyable_handler
{
template<class... Args>
void
operator()(Args&&...) const
{
}
};
void
testAsioHandlerInvoke()
{
using strand = net::strand<
net::io_context::executor_type>;
// make sure things compile, also can set a
// breakpoint in asio_handler_invoke to make sure
// it is instantiated.
{
net::io_context ioc;
strand s{ioc.get_executor()};
test::stream ts{ioc};
flat_buffer b;
request_parser<dynamic_body> p;
async_read_some(ts, b, p,
net::bind_executor(
s, copyable_handler{}));
}
{
net::io_context ioc;
strand s{ioc.get_executor()};
test::stream ts{ioc};
flat_buffer b;
request_parser<dynamic_body> p;
async_read(ts, b, p,
net::bind_executor(
s, copyable_handler{}));
}
{
net::io_context ioc;
strand s{ioc.get_executor()};
test::stream ts{ioc};
flat_buffer b;
request<dynamic_body> m;
async_read(ts, b, m,
net::bind_executor(
s, copyable_handler{}));
}
}
void
run() override
{
testThrow();
testBufferOverflow();
yield_to([&](yield_context yield)
{
testFailures(yield);
});
yield_to([&](yield_context yield)
{
testRead(yield);
});
yield_to([&](yield_context yield)
{
testEof(yield);
});
testIoService();
testRegression430();
testReadGrind();
testAsioHandlerInvoke();
}
};
BEAST_DEFINE_TESTSUITE(beast,http,read);
} // http
} // beast
} // boost
| 28.298401 | 80 | 0.442631 | bebuch |
28163ca0fc1be168bcf7718b9a08388996a625ca | 5,916 | cpp | C++ | XmlLib/Src/SaxContentElement.cpp | shortydude/DDOBuilder-learning | e71162c10b81bb4afd0365e61088437353cc4607 | [
"MIT"
] | null | null | null | XmlLib/Src/SaxContentElement.cpp | shortydude/DDOBuilder-learning | e71162c10b81bb4afd0365e61088437353cc4607 | [
"MIT"
] | null | null | null | XmlLib/Src/SaxContentElement.cpp | shortydude/DDOBuilder-learning | e71162c10b81bb4afd0365e61088437353cc4607 | [
"MIT"
] | null | null | null | // SaxContentElement.cpp
//
#include "stdafx.h"
#include "XmlLib\SaxContentElement.h"
using XmlLib::SaxString;
using XmlLib::SaxAttributes;
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// SaxContentElementInterface
using XmlLib::SaxContentElementInterface;
SaxContentElementInterface::SaxContentElementInterface() :
m_readErrorHandler(NULL)
{
}
SaxContentElementInterface::~SaxContentElementInterface()
{
}
SaxContentElementInterface * SaxContentElementInterface::StartElement(
const SaxString & name,
const SaxAttributes & attributes)
{
return NULL;
}
void SaxContentElementInterface::Characters(const SaxString & chars)
{
}
void SaxContentElementInterface::EndElement()
{
}
SaxContentElementInterface * SaxContentElementInterface::SaxReadErrorHandler() const
{
return m_readErrorHandler;
}
void SaxContentElementInterface::SetSaxReadErrorHandler(SaxContentElementInterface * handler)
{
m_readErrorHandler = handler;
}
void SaxContentElementInterface::ClearSaxReadErrorHandler()
{
m_readErrorHandler = NULL;
}
void SaxContentElementInterface::ReportSaxReadError(const std::string & errorDescription)
{
// propagate or die
if (m_readErrorHandler != NULL)
{
m_readErrorHandler->ReportSaxReadError(errorDescription);
}
else
{
throw errorDescription;
}
}
//////////////////////////////////////////////////////////////////////
// SaxSimpleElement<std::string>
XmlLib::SaxSimpleElement<std::string> XmlLib::SaxSimpleElement<std::string>::s_singleton;
XmlLib::SaxSimpleElement<std::string> * XmlLib::SaxSimpleElement<std::string>::Handle(std::string * t)
{
t->erase();
s_singleton.m_t = t;
return &s_singleton;
}
void XmlLib::SaxSimpleElement<std::string>::Characters(const SaxString & chars)
{
// ensure the capacity grows faster than adding it bit by bit as that
// takes a loooooooong time for big strings
if (m_t->capacity() < m_t->size() + chars.size() + 1)
{
m_t->reserve(m_t->capacity() * 2 + chars.size() + 1);
}
*m_t += chars;
}
//////////////////////////////////////////////////////////////////////
// SaxSimpleElement<std::wstring>
XmlLib::SaxSimpleElement<std::wstring> XmlLib::SaxSimpleElement<std::wstring>::s_singleton;
XmlLib::SaxSimpleElement<std::wstring> * XmlLib::SaxSimpleElement<std::wstring>::Handle(std::wstring * t)
{
t->erase();
s_singleton.m_t = t;
return &s_singleton;
}
void XmlLib::SaxSimpleElement<std::wstring>::Characters(const SaxString & chars)
{
*m_t += chars;
}
//////////////////////////////////////////////////////////////////////
// SaxContentElement
using XmlLib::SaxContentElement;
const XmlLib::SaxString f_saxVersionAttributeName = L"version";
SaxContentElement::SaxContentElement(const SaxString & elementName) :
m_elementName(elementName),
m_elementVersion(0),
m_elementHandlingVersion(0),
m_readErrorMode(REM_terminate)
{
}
SaxContentElement::SaxContentElement(const SaxString & elementName, unsigned version) :
m_elementName(elementName),
m_elementVersion(version),
m_elementHandlingVersion(0),
m_readErrorMode(REM_terminate)
{
}
const XmlLib::SaxString & SaxContentElement::ElementName() const
{
return m_elementName;
}
bool SaxContentElement::SaxElementIsSelf(
const SaxString & name,
const SaxAttributes & attributes)
{
bool self = (name == m_elementName);
if (self)
{
SaxSetAttributes(attributes);
}
return self;
}
void SaxContentElement::SaxSetAttributes(const SaxAttributes & attributes)
{
// store the id attribute (if there is one)
if (attributes.HasAttribute(f_saxVersionAttributeName))
{
std::wstringstream wssSax(attributes[f_saxVersionAttributeName]);
wssSax >> m_elementHandlingVersion;
if (wssSax.fail())
{
std::stringstream ss;
ss << "XML element " << m_elementName << " found with invalid version attribute";
ReportSaxReadError(ss.str());
}
}
}
unsigned SaxContentElement::ElementHandlingVersion() const
{
return m_elementHandlingVersion;
}
SaxAttributes SaxContentElement::VersionAttributes() const
{
SaxAttributes attributes;
if (m_elementVersion > 0)
{
std::wstringstream wssSax;
wssSax << m_elementVersion;
attributes[f_saxVersionAttributeName] = SaxString(wssSax.str());
}
return attributes;
}
void SaxContentElement::ReportSaxReadError(const std::string & errorDescription)
{
if (m_readErrorMode == REM_accumulate)
{
// SAX read errors are collected and the owner must check for read errors
m_saxReadErrors.push_back(errorDescription);
}
else
{
SaxContentElementInterface::ReportSaxReadError(errorDescription);
}
}
void SaxContentElement::SetReadErrorMode(SaxContentElement::ReadErrorMode mode)
{
m_readErrorMode = mode;
m_saxReadErrors.clear();
}
SaxContentElement::ReadErrorMode SaxContentElement::GetReadErrorMode() const
{
return m_readErrorMode;
}
bool SaxContentElement::HasReadErrors() const
{
return !m_saxReadErrors.empty();
}
const std::vector<std::string> & SaxContentElement::ReadErrors() const
{
return m_saxReadErrors;
}
const SaxContentElement & SaxContentElement::operator=(const SaxContentElement & copy)
{
// only copy element name if we don't already have one
if (m_elementName.size() == 0)
{
m_elementName = copy.m_elementName;
m_elementVersion = copy.m_elementVersion;
}
m_elementHandlingVersion = copy.m_elementHandlingVersion;
m_readErrorMode = copy.m_readErrorMode;
m_saxReadErrors = copy.m_saxReadErrors;
return *this;
}
//////////////////////////////////////////////////////////////////////
| 25.174468 | 105 | 0.677654 | shortydude |
2817ed4ba0a6f3a90a6d283794581e941a2d2a78 | 57,078 | cc | C++ | src/selectParser.cc | nporsche/fastbit | 91d06c68b9f4a0a0cc39da737d1c880ab21fe947 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/selectParser.cc | nporsche/fastbit | 91d06c68b9f4a0a0cc39da737d1c880ab21fe947 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/selectParser.cc | nporsche/fastbit | 91d06c68b9f4a0a0cc39da737d1c880ab21fe947 | [
"BSD-3-Clause-LBNL"
] | null | null | null | /* A Bison parser, made by GNU Bison 2.7.12-4996. */
/* Skeleton implementation for Bison LALR(1) parsers in C++
Copyright (C) 2002-2013 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* "%code top" blocks. */
/* Line 276 of lalr1.cc */
#line 6 "selectParser.yy"
/** \file Defines the parser for the select clause accepted by FastBit
IBIS. The definitions are processed through bison.
*/
#include <iostream>
/* Line 276 of lalr1.cc */
#line 44 "selectParser.cc"
// Take the name prefix into account.
#define yylex ibislex
/* First part of user declarations. */
/* Line 283 of lalr1.cc */
#line 52 "selectParser.cc"
#include "selectParser.hh"
/* User implementation prologue. */
/* Line 289 of lalr1.cc */
#line 70 "selectParser.yy"
#include "selectLexer.h"
#undef yylex
#define yylex driver.lexer->lex
/* Line 289 of lalr1.cc */
#line 67 "selectParser.cc"
# ifndef YY_NULL
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULL nullptr
# else
# define YY_NULL 0
# endif
# endif
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* FIXME: INFRINGES ON USER NAME SPACE */
# define YY_(msgid) dgettext ("bison-runtime", msgid)
# endif
# endif
# ifndef YY_
# define YY_(msgid) msgid
# endif
#endif
#define YYRHSLOC(Rhs, K) ((Rhs)[K])
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
# ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (N) \
{ \
(Current).begin = YYRHSLOC (Rhs, 1).begin; \
(Current).end = YYRHSLOC (Rhs, N).end; \
} \
else \
{ \
(Current).begin = (Current).end = YYRHSLOC (Rhs, 0).end; \
} \
while (/*CONSTCOND*/ false)
# endif
/* Suppress unused-variable warnings by "using" E. */
#define YYUSE(e) ((void) (e))
/* Enable debugging if requested. */
#if YYDEBUG
/* A pseudo ostream that takes yydebug_ into account. */
# define YYCDEBUG if (yydebug_) (*yycdebug_)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug_) \
{ \
*yycdebug_ << Title << ' '; \
yy_symbol_print_ ((Type), (Value), (Location)); \
*yycdebug_ << std::endl; \
} \
} while (false)
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug_) \
yy_reduce_print_ (Rule); \
} while (false)
# define YY_STACK_PRINT() \
do { \
if (yydebug_) \
yystack_print_ (); \
} while (false)
#else /* !YYDEBUG */
# define YYCDEBUG if (false) std::cerr
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) YYUSE(Type)
# define YY_REDUCE_PRINT(Rule) static_cast<void>(0)
# define YY_STACK_PRINT() static_cast<void>(0)
#endif /* !YYDEBUG */
#define yyerrok (yyerrstatus_ = 0)
#define yyclearin (yychar = yyempty_)
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus_)
namespace ibis {
/* Line 357 of lalr1.cc */
#line 162 "selectParser.cc"
/* Return YYSTR after stripping away unnecessary quotes and
backslashes, so that it's suitable for yyerror. The heuristic is
that double-quoting is unnecessary unless the string contains an
apostrophe, a comma, or backslash (other than backslash-backslash).
YYSTR is taken from yytname. */
std::string
selectParser::yytnamerr_ (const char *yystr)
{
if (*yystr == '"')
{
std::string yyr = "";
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
yyr += *yyp;
break;
case '"':
return yyr;
}
do_not_strip_quotes: ;
}
return yystr;
}
/// Build a parser object.
selectParser::selectParser (class ibis::selectClause& driver_yyarg)
:
#if YYDEBUG
yydebug_ (false),
yycdebug_ (&std::cerr),
#endif
driver (driver_yyarg)
{
}
selectParser::~selectParser ()
{
}
#if YYDEBUG
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
inline void
selectParser::yy_symbol_value_print_ (int yytype,
const semantic_type* yyvaluep, const location_type* yylocationp)
{
YYUSE (yylocationp);
YYUSE (yyvaluep);
std::ostream& yyo = debug_stream ();
std::ostream& yyoutput = yyo;
YYUSE (yyoutput);
YYUSE (yytype);
}
void
selectParser::yy_symbol_print_ (int yytype,
const semantic_type* yyvaluep, const location_type* yylocationp)
{
*yycdebug_ << (yytype < yyntokens_ ? "token" : "nterm")
<< ' ' << yytname_[yytype] << " ("
<< *yylocationp << ": ";
yy_symbol_value_print_ (yytype, yyvaluep, yylocationp);
*yycdebug_ << ')';
}
#endif
void
selectParser::yydestruct_ (const char* yymsg,
int yytype, semantic_type* yyvaluep, location_type* yylocationp)
{
YYUSE (yylocationp);
YYUSE (yymsg);
YYUSE (yyvaluep);
if (yymsg)
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
switch (yytype)
{
case 13: /* "name" */
/* Line 452 of lalr1.cc */
#line 67 "selectParser.yy"
{ delete ((*yyvaluep).stringVal); };
/* Line 452 of lalr1.cc */
#line 265 "selectParser.cc"
break;
case 14: /* "string literal" */
/* Line 452 of lalr1.cc */
#line 66 "selectParser.yy"
{ delete ((*yyvaluep).stringVal); };
/* Line 452 of lalr1.cc */
#line 272 "selectParser.cc"
break;
case 23: /* mathExpr */
/* Line 452 of lalr1.cc */
#line 68 "selectParser.yy"
{ delete ((*yyvaluep).selectNode); };
/* Line 452 of lalr1.cc */
#line 279 "selectParser.cc"
break;
default:
break;
}
}
void
selectParser::yypop_ (unsigned int n)
{
yystate_stack_.pop (n);
yysemantic_stack_.pop (n);
yylocation_stack_.pop (n);
}
#if YYDEBUG
std::ostream&
selectParser::debug_stream () const
{
return *yycdebug_;
}
void
selectParser::set_debug_stream (std::ostream& o)
{
yycdebug_ = &o;
}
selectParser::debug_level_type
selectParser::debug_level () const
{
return yydebug_;
}
void
selectParser::set_debug_level (debug_level_type l)
{
yydebug_ = l;
}
#endif
inline bool
selectParser::yy_pact_value_is_default_ (int yyvalue)
{
return yyvalue == yypact_ninf_;
}
inline bool
selectParser::yy_table_value_is_error_ (int yyvalue)
{
return yyvalue == yytable_ninf_;
}
int
selectParser::parse ()
{
/// Lookahead and lookahead in internal form.
int yychar = yyempty_;
int yytoken = 0;
// State.
int yyn;
int yylen = 0;
int yystate = 0;
// Error handling.
int yynerrs_ = 0;
int yyerrstatus_ = 0;
/// Semantic value of the lookahead.
static semantic_type yyval_default;
semantic_type yylval = yyval_default;
/// Location of the lookahead.
location_type yylloc;
/// The locations where the error started and ended.
location_type yyerror_range[3];
/// $$.
semantic_type yyval;
/// @$.
location_type yyloc;
int yyresult;
// FIXME: This shoud be completely indented. It is not yet to
// avoid gratuitous conflicts when merging into the master branch.
try
{
YYCDEBUG << "Starting parse" << std::endl;
/* User initialization code. */
/* Line 539 of lalr1.cc */
#line 28 "selectParser.yy"
{ // initialize location object
yylloc.begin.filename = yylloc.end.filename = &(driver.clause_);
}
/* Line 539 of lalr1.cc */
#line 379 "selectParser.cc"
/* Initialize the stacks. The initial state will be pushed in
yynewstate, since the latter expects the semantical and the
location values to have been already stored, initialize these
stacks with a primary value. */
yystate_stack_.clear ();
yysemantic_stack_.clear ();
yylocation_stack_.clear ();
yysemantic_stack_.push (yylval);
yylocation_stack_.push (yylloc);
/* New state. */
yynewstate:
yystate_stack_.push (yystate);
YYCDEBUG << "Entering state " << yystate << std::endl;
/* Accept? */
if (yystate == yyfinal_)
goto yyacceptlab;
goto yybackup;
/* Backup. */
yybackup:
/* Try to take a decision without lookahead. */
yyn = yypact_[yystate];
if (yy_pact_value_is_default_ (yyn))
goto yydefault;
/* Read a lookahead token. */
if (yychar == yyempty_)
{
YYCDEBUG << "Reading a token: ";
yychar = yylex (&yylval, &yylloc);
}
/* Convert token to internal form. */
if (yychar <= yyeof_)
{
yychar = yytoken = yyeof_;
YYCDEBUG << "Now at end of input." << std::endl;
}
else
{
yytoken = yytranslate_ (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yytoken)
goto yydefault;
/* Reduce or error. */
yyn = yytable_[yyn];
if (yyn <= 0)
{
if (yy_table_value_is_error_ (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the token being shifted. */
yychar = yyempty_;
yysemantic_stack_.push (yylval);
yylocation_stack_.push (yylloc);
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus_)
--yyerrstatus_;
yystate = yyn;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact_[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
yylen = yyr2_[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
`$$ = $1'. Otherwise, use the top of the stack.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. */
if (yylen)
yyval = yysemantic_stack_[yylen - 1];
else
yyval = yysemantic_stack_[0];
// Compute the default @$.
{
slice<location_type, location_stack_type> slice (yylocation_stack_, yylen);
YYLLOC_DEFAULT (yyloc, slice, yylen);
}
// Perform the reduction.
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 4:
/* Line 664 of lalr1.cc */
#line 79 "selectParser.yy"
{
driver.addTerm((yysemantic_stack_[(2) - (1)].selectNode), 0);
}
break;
case 5:
/* Line 664 of lalr1.cc */
#line 82 "selectParser.yy"
{
driver.addTerm((yysemantic_stack_[(2) - (1)].selectNode), 0);
}
break;
case 6:
/* Line 664 of lalr1.cc */
#line 85 "selectParser.yy"
{
driver.addTerm((yysemantic_stack_[(3) - (1)].selectNode), (yysemantic_stack_[(3) - (2)].stringVal));
delete (yysemantic_stack_[(3) - (2)].stringVal);
}
break;
case 7:
/* Line 664 of lalr1.cc */
#line 89 "selectParser.yy"
{
driver.addTerm((yysemantic_stack_[(3) - (1)].selectNode), (yysemantic_stack_[(3) - (2)].stringVal));
delete (yysemantic_stack_[(3) - (2)].stringVal);
}
break;
case 8:
/* Line 664 of lalr1.cc */
#line 93 "selectParser.yy"
{
driver.addTerm((yysemantic_stack_[(4) - (1)].selectNode), (yysemantic_stack_[(4) - (3)].stringVal));
delete (yysemantic_stack_[(4) - (3)].stringVal);
}
break;
case 9:
/* Line 664 of lalr1.cc */
#line 97 "selectParser.yy"
{
driver.addTerm((yysemantic_stack_[(4) - (1)].selectNode), (yysemantic_stack_[(4) - (3)].stringVal));
delete (yysemantic_stack_[(4) - (3)].stringVal);
}
break;
case 10:
/* Line 664 of lalr1.cc */
#line 104 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " + " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::PLUS);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 11:
/* Line 664 of lalr1.cc */
#line 116 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " - " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::MINUS);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 12:
/* Line 664 of lalr1.cc */
#line 128 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " * " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::MULTIPLY);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 13:
/* Line 664 of lalr1.cc */
#line 140 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " / " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::DIVIDE);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 14:
/* Line 664 of lalr1.cc */
#line 152 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " % " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::REMAINDER);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 15:
/* Line 664 of lalr1.cc */
#line 164 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " ^ " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::POWER);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 16:
/* Line 664 of lalr1.cc */
#line 176 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " & " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::BITAND);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 17:
/* Line 664 of lalr1.cc */
#line 188 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(3) - (1)].selectNode)
<< " | " << *(yysemantic_stack_[(3) - (3)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::BITOR);
opr->setRight((yysemantic_stack_[(3) - (3)].selectNode));
opr->setLeft((yysemantic_stack_[(3) - (1)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 18:
/* Line 664 of lalr1.cc */
#line 200 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(4) - (1)].stringVal) << "(*)";
#endif
ibis::math::term *fun = 0;
if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "count") == 0) { // aggregation count
ibis::math::variable *var = new ibis::math::variable("*");
fun = driver.addAgregado(ibis::selectClause::CNT, var);
}
else {
LOGGER(ibis::gVerbose >= 0)
<< "Warning -- only operator COUNT supports * as the argument, "
"but received " << *(yysemantic_stack_[(4) - (1)].stringVal);
throw "invalid use of (*)";
}
delete (yysemantic_stack_[(4) - (1)].stringVal);
(yyval.selectNode) = fun;
}
break;
case 19:
/* Line 664 of lalr1.cc */
#line 219 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(4) - (1)].stringVal) << "("
<< *(yysemantic_stack_[(4) - (3)].selectNode) << ")";
#endif
ibis::math::term *fun = 0;
if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "count") == 0) { // aggregation count
delete (yysemantic_stack_[(4) - (3)].selectNode); // drop the expression, replace it with "*"
ibis::math::variable *var = new ibis::math::variable("*");
fun = driver.addAgregado(ibis::selectClause::CNT, var);
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "max") == 0) { // aggregation max
fun = driver.addAgregado(ibis::selectClause::MAX, (yysemantic_stack_[(4) - (3)].selectNode));
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "min") == 0) { // aggregation min
fun = driver.addAgregado(ibis::selectClause::MIN, (yysemantic_stack_[(4) - (3)].selectNode));
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "sum") == 0) { // aggregation sum
fun = driver.addAgregado(ibis::selectClause::SUM, (yysemantic_stack_[(4) - (3)].selectNode));
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "median") == 0) { // aggregation median
fun = driver.addAgregado(ibis::selectClause::MEDIAN, (yysemantic_stack_[(4) - (3)].selectNode));
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "countd") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "countdistinct") == 0) {
// count distinct values
fun = driver.addAgregado(ibis::selectClause::DISTINCT, (yysemantic_stack_[(4) - (3)].selectNode));
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "concat") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "group_concat") == 0) {
// concatenate all values as ASCII strings
fun = driver.addAgregado(ibis::selectClause::CONCAT, (yysemantic_stack_[(4) - (3)].selectNode));
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "avg") == 0) { // aggregation avg
ibis::math::term *numer =
driver.addAgregado(ibis::selectClause::SUM, (yysemantic_stack_[(4) - (3)].selectNode));
ibis::math::variable *var = new ibis::math::variable("*");
ibis::math::term *denom =
driver.addAgregado(ibis::selectClause::CNT, var);
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::DIVIDE);
opr->setRight(denom);
opr->setLeft(numer);
fun = opr;
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "varp") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "varpop") == 0) {
// population variance is computed as
// fabs(sum (x^2) / count(*) - (sum (x) / count(*))^2)
ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode);
ibis::math::number *two = new ibis::math::number(2.0);
ibis::math::variable *star = new ibis::math::variable("*");
ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER);
t11->setLeft(x);
t11->setRight(two);
t11 = driver.addAgregado(ibis::selectClause::SUM, t11);
ibis::math::term *t12 =
driver.addAgregado(ibis::selectClause::CNT, star);
ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE);
t13->setLeft(t11);
t13->setRight(t12);
ibis::math::term *t21 =
driver.addAgregado(ibis::selectClause::SUM, x->dup());
ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE);
t23->setLeft(t21);
t23->setRight(t12->dup());
ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER);
t24->setLeft(t23);
t24->setRight(two->dup());
ibis::math::term *t0 = new ibis::math::bediener(ibis::math::MINUS);
t0->setLeft(t13);
t0->setRight(t24);
fun = new ibis::math::stdFunction1("fabs");
fun->setLeft(t0);
//fun = driver.addAgregado(ibis::selectClause::VARPOP, $3);
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "var") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "varsamp") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "variance") == 0) {
// sample variance is computed as
// fabs((sum (x^2) / count(*) - (sum (x) / count(*))^2) * (count(*) / (count(*)-1)))
ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode);
ibis::math::number *two = new ibis::math::number(2.0);
ibis::math::variable *star = new ibis::math::variable("*");
ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER);
t11->setLeft(x);
t11->setRight(two);
t11 = driver.addAgregado(ibis::selectClause::SUM, t11);
ibis::math::term *t12 =
driver.addAgregado(ibis::selectClause::CNT, star);
ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE);
t13->setLeft(t11);
t13->setRight(t12);
ibis::math::term *t21 =
driver.addAgregado(ibis::selectClause::SUM, x->dup());
ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE);
t23->setLeft(t21);
t23->setRight(t12->dup());
ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER);
t24->setLeft(t23);
t24->setRight(two->dup());
ibis::math::term *t31 = new ibis::math::bediener(ibis::math::MINUS);
t31->setLeft(t13);
t31->setRight(t24);
ibis::math::term *t32 = new ibis::math::bediener(ibis::math::MINUS);
ibis::math::number *one = new ibis::math::number(1.0);
t32->setLeft(t12->dup());
t32->setRight(one);
ibis::math::term *t33 = new ibis::math::bediener(ibis::math::DIVIDE);
t33->setLeft(t12->dup());
t33->setRight(t32);
ibis::math::term *t0 = new ibis::math::bediener(ibis::math::MULTIPLY);
t0->setLeft(t31);
t0->setRight(t33);
fun = new ibis::math::stdFunction1("fabs");
fun->setLeft(t0);
//fun = driver.addAgregado(ibis::selectClause::VARSAMP, $3);
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdevp") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdpop") == 0) {
// population standard deviation is computed as
// sqrt(fabs(sum (x^2) / count(*) - (sum (x) / count(*))^2))
ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode);
ibis::math::number *two = new ibis::math::number(2.0);
ibis::math::variable *star = new ibis::math::variable("*");
ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER);
t11->setLeft(x);
t11->setRight(two);
t11 = driver.addAgregado(ibis::selectClause::SUM, t11);
ibis::math::term *t12 =
driver.addAgregado(ibis::selectClause::CNT, star);
ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE);
t13->setLeft(t11);
t13->setRight(t12);
ibis::math::term *t21 =
driver.addAgregado(ibis::selectClause::SUM, x->dup());
ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE);
t23->setLeft(t21);
t23->setRight(t12->dup());
ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER);
t24->setLeft(t23);
t24->setRight(two->dup());
ibis::math::term *t31 = new ibis::math::bediener(ibis::math::MINUS);
t31->setLeft(t13);
t31->setRight(t24);
ibis::math::term *t0 = new ibis::math::stdFunction1("fabs");
t0->setLeft(t31);
fun = new ibis::math::stdFunction1("sqrt");
fun->setLeft(t0);
//fun = driver.addAgregado(ibis::selectClause::STDPOP, $3);
}
else if (stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "std") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdev") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stddev") == 0 ||
stricmp((yysemantic_stack_[(4) - (1)].stringVal)->c_str(), "stdsamp") == 0) {
// sample standard deviation is computed as
// sqrt(fabs(sum (x^2) / count(*) - (sum (x) / count(*))^2) * (count(*) / (count(*)-1))))
ibis::math::term *x = (yysemantic_stack_[(4) - (3)].selectNode);
ibis::math::number *two = new ibis::math::number(2.0);
ibis::math::variable *star = new ibis::math::variable("*");
ibis::math::term *t11 = new ibis::math::bediener(ibis::math::POWER);
t11->setLeft(x);
t11->setRight(two);
t11 = driver.addAgregado(ibis::selectClause::SUM, t11);
ibis::math::term *t12 =
driver.addAgregado(ibis::selectClause::CNT, star);
ibis::math::term *t13 = new ibis::math::bediener(ibis::math::DIVIDE);
t13->setLeft(t11);
t13->setRight(t12);
ibis::math::term *t21 =
driver.addAgregado(ibis::selectClause::SUM, x->dup());
ibis::math::term *t23 = new ibis::math::bediener(ibis::math::DIVIDE);
t23->setLeft(t21);
t23->setRight(t12->dup());
ibis::math::term *t24 = new ibis::math::bediener(ibis::math::POWER);
t24->setLeft(t23);
t24->setRight(two->dup());
ibis::math::term *t31 = new ibis::math::bediener(ibis::math::MINUS);
t31->setLeft(t13);
t31->setRight(t24);
ibis::math::term *t32 = new ibis::math::bediener(ibis::math::MINUS);
ibis::math::number *one = new ibis::math::number(1.0);
t32->setLeft(t12->dup());
t32->setRight(one);
ibis::math::term *t33 = new ibis::math::bediener(ibis::math::DIVIDE);
t33->setLeft(t12->dup());
t33->setRight(t32);
ibis::math::term *t34 = new ibis::math::bediener(ibis::math::MULTIPLY);
t34->setLeft(t31);
t34->setRight(t33);
ibis::math::term *t0 = new ibis::math::stdFunction1("fabs");
t0->setLeft(t34);
fun = new ibis::math::stdFunction1("sqrt");
fun->setLeft(t0);
// fun = driver.addAgregado(ibis::selectClause::STDSAMP, $3);
}
else { // assume it is a standard math function
fun = new ibis::math::stdFunction1((yysemantic_stack_[(4) - (1)].stringVal)->c_str());
fun->setLeft((yysemantic_stack_[(4) - (3)].selectNode));
}
delete (yysemantic_stack_[(4) - (1)].stringVal);
(yyval.selectNode) = fun;
}
break;
case 20:
/* Line 664 of lalr1.cc */
#line 423 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_GMT("
<< *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")";
#endif
ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str(), "GMT");
ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut);
fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode));
(yyval.selectNode) = fun;
delete (yysemantic_stack_[(6) - (5)].stringVal);
}
break;
case 21:
/* Line 664 of lalr1.cc */
#line 435 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_GMT("
<< *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")";
#endif
ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str(), "GMT");
ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut);
fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode));
(yyval.selectNode) = fun;
delete (yysemantic_stack_[(6) - (5)].stringVal);
}
break;
case 22:
/* Line 664 of lalr1.cc */
#line 447 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_LOCAL("
<< *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")";
#endif
ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str());
ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut);
fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode));
(yyval.selectNode) = fun;
delete (yysemantic_stack_[(6) - (5)].stringVal);
}
break;
case 23:
/* Line 664 of lalr1.cc */
#line 459 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- FORMAT_UNIXTIME_LOCAL("
<< *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].stringVal) << ")";
#endif
ibis::math::formatUnixTime fut((yysemantic_stack_[(6) - (5)].stringVal)->c_str());
ibis::math::stringFunction1 *fun = new ibis::math::stringFunction1(fut);
fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode));
(yyval.selectNode) = fun;
delete (yysemantic_stack_[(6) - (5)].stringVal);
}
break;
case 24:
/* Line 664 of lalr1.cc */
#line 471 "selectParser.yy"
{
/* two-arugment math functions */
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- " << *(yysemantic_stack_[(6) - (1)].stringVal) << "("
<< *(yysemantic_stack_[(6) - (3)].selectNode) << ", " << *(yysemantic_stack_[(6) - (5)].selectNode) << ")";
#endif
ibis::math::stdFunction2 *fun =
new ibis::math::stdFunction2((yysemantic_stack_[(6) - (1)].stringVal)->c_str());
fun->setRight((yysemantic_stack_[(6) - (5)].selectNode));
fun->setLeft((yysemantic_stack_[(6) - (3)].selectNode));
(yyval.selectNode) = fun;
delete (yysemantic_stack_[(6) - (1)].stringVal);
}
break;
case 25:
/* Line 664 of lalr1.cc */
#line 485 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " parsing -- - " << *(yysemantic_stack_[(2) - (2)].selectNode);
#endif
ibis::math::bediener *opr =
new ibis::math::bediener(ibis::math::NEGATE);
opr->setRight((yysemantic_stack_[(2) - (2)].selectNode));
(yyval.selectNode) = opr;
}
break;
case 26:
/* Line 664 of lalr1.cc */
#line 495 "selectParser.yy"
{
(yyval.selectNode) = (yysemantic_stack_[(2) - (2)].selectNode);
}
break;
case 27:
/* Line 664 of lalr1.cc */
#line 498 "selectParser.yy"
{
(yyval.selectNode) = (yysemantic_stack_[(3) - (2)].selectNode);
}
break;
case 28:
/* Line 664 of lalr1.cc */
#line 501 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " got a variable name " << *(yysemantic_stack_[(1) - (1)].stringVal);
#endif
(yyval.selectNode) = new ibis::math::variable((yysemantic_stack_[(1) - (1)].stringVal)->c_str());
delete (yysemantic_stack_[(1) - (1)].stringVal);
}
break;
case 29:
/* Line 664 of lalr1.cc */
#line 509 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " got a string literal " << *(yysemantic_stack_[(1) - (1)].stringVal);
#endif
(yyval.selectNode) = new ibis::math::literal((yysemantic_stack_[(1) - (1)].stringVal)->c_str());
delete (yysemantic_stack_[(1) - (1)].stringVal);
}
break;
case 30:
/* Line 664 of lalr1.cc */
#line 517 "selectParser.yy"
{
#if defined(DEBUG) && DEBUG + 0 > 1
LOGGER(ibis::gVerbose >= 0)
<< __FILE__ << ":" << __LINE__ << " got a number " << (yysemantic_stack_[(1) - (1)].doubleVal);
#endif
(yyval.selectNode) = new ibis::math::number((yysemantic_stack_[(1) - (1)].doubleVal));
}
break;
/* Line 664 of lalr1.cc */
#line 1076 "selectParser.cc"
default:
break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action
invokes YYABORT, YYACCEPT, or YYERROR immediately after altering
yychar. In the case of YYABORT or YYACCEPT, an incorrect
destructor might then be invoked immediately. In the case of
YYERROR, subsequent parser actions might lead to an incorrect
destructor call or verbose syntax error message before the
lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1_[yyn], &yyval, &yyloc);
yypop_ (yylen);
yylen = 0;
YY_STACK_PRINT ();
yysemantic_stack_.push (yyval);
yylocation_stack_.push (yyloc);
/* Shift the result of the reduction. */
yyn = yyr1_[yyn];
yystate = yypgoto_[yyn - yyntokens_] + yystate_stack_[0];
if (0 <= yystate && yystate <= yylast_
&& yycheck_[yystate] == yystate_stack_[0])
yystate = yytable_[yystate];
else
yystate = yydefgoto_[yyn - yyntokens_];
goto yynewstate;
/*------------------------------------.
| yyerrlab -- here on detecting error |
`------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yytranslate_ (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus_)
{
++yynerrs_;
if (yychar == yyempty_)
yytoken = yyempty_;
error (yylloc, yysyntax_error_ (yystate, yytoken));
}
yyerror_range[1] = yylloc;
if (yyerrstatus_ == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= yyeof_)
{
/* Return failure if at end of input. */
if (yychar == yyeof_)
YYABORT;
}
else
{
yydestruct_ ("Error: discarding", yytoken, &yylval, &yylloc);
yychar = yyempty_;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (false)
goto yyerrorlab;
yyerror_range[1] = yylocation_stack_[yylen - 1];
/* Do not reclaim the symbols of the rule which action triggered
this YYERROR. */
yypop_ (yylen);
yylen = 0;
yystate = yystate_stack_[0];
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus_ = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact_[yystate];
if (!yy_pact_value_is_default_ (yyn))
{
yyn += yyterror_;
if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_)
{
yyn = yytable_[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yystate_stack_.height () == 1)
YYABORT;
yyerror_range[1] = yylocation_stack_[0];
yydestruct_ ("Error: popping",
yystos_[yystate],
&yysemantic_stack_[0], &yylocation_stack_[0]);
yypop_ ();
yystate = yystate_stack_[0];
YY_STACK_PRINT ();
}
yyerror_range[2] = yylloc;
// Using YYLLOC is tempting, but would change the location of
// the lookahead. YYLOC is available though.
YYLLOC_DEFAULT (yyloc, yyerror_range, 2);
yysemantic_stack_.push (yylval);
yylocation_stack_.push (yyloc);
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos_[yyn],
&yysemantic_stack_[0], &yylocation_stack_[0]);
yystate = yyn;
goto yynewstate;
/* Accept. */
yyacceptlab:
yyresult = 0;
goto yyreturn;
/* Abort. */
yyabortlab:
yyresult = 1;
goto yyreturn;
yyreturn:
if (yychar != yyempty_)
{
/* Make sure we have latest lookahead translation. See comments
at user semantic actions for why this is necessary. */
yytoken = yytranslate_ (yychar);
yydestruct_ ("Cleanup: discarding lookahead", yytoken, &yylval,
&yylloc);
}
/* Do not reclaim the symbols of the rule which action triggered
this YYABORT or YYACCEPT. */
yypop_ (yylen);
while (1 < yystate_stack_.height ())
{
yydestruct_ ("Cleanup: popping",
yystos_[yystate_stack_[0]],
&yysemantic_stack_[0],
&yylocation_stack_[0]);
yypop_ ();
}
return yyresult;
}
catch (...)
{
YYCDEBUG << "Exception caught: cleaning lookahead and stack"
<< std::endl;
// Do not try to display the values of the reclaimed symbols,
// as their printer might throw an exception.
if (yychar != yyempty_)
{
/* Make sure we have latest lookahead translation. See
comments at user semantic actions for why this is
necessary. */
yytoken = yytranslate_ (yychar);
yydestruct_ (YY_NULL, yytoken, &yylval, &yylloc);
}
while (1 < yystate_stack_.height ())
{
yydestruct_ (YY_NULL,
yystos_[yystate_stack_[0]],
&yysemantic_stack_[0],
&yylocation_stack_[0]);
yypop_ ();
}
throw;
}
}
// Generate an error message.
std::string
selectParser::yysyntax_error_ (int yystate, int yytoken)
{
std::string yyres;
// Number of reported tokens (one for the "unexpected", one per
// "expected").
size_t yycount = 0;
// Its maximum.
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
// Arguments of yyformat.
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yytoken) is
if this state is a consistent state with a default action.
Thus, detecting the absence of a lookahead is sufficient to
determine that there is no unexpected or expected token to
report. In that case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is
a consistent state with a default action. There might have
been a previous inconsistent state, consistent state with a
non-default action, or user semantic action that manipulated
yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state
merging (from LALR or IELR) and default reductions corrupt the
expected token list. However, the list is correct for
canonical LR with one exception: it will still contain any
token that will not be accepted due to an error action in a
later state.
*/
if (yytoken != yyempty_)
{
yyarg[yycount++] = yytname_[yytoken];
int yyn = yypact_[yystate];
if (!yy_pact_value_is_default_ (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = yylast_ - yyn + 1;
int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_;
for (int yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck_[yyx + yyn] == yyx && yyx != yyterror_
&& !yy_table_value_is_error_ (yytable_[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
break;
}
else
yyarg[yycount++] = yytname_[yyx];
}
}
}
char const* yyformat = YY_NULL;
switch (yycount)
{
#define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
#undef YYCASE_
}
// Argument number.
size_t yyi = 0;
for (char const* yyp = yyformat; *yyp; ++yyp)
if (yyp[0] == '%' && yyp[1] == 's' && yyi < yycount)
{
yyres += yytnamerr_ (yyarg[yyi++]);
++yyp;
}
else
yyres += *yyp;
return yyres;
}
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
const signed char selectParser::yypact_ninf_ = -13;
const signed char
selectParser::yypact_[] =
{
126, 126, 126, -13, -12, -13, -6, -2, 126, 30,
126, 29, 20, 20, 113, 126, 126, 61, -13, -13,
-13, 28, 126, 126, 126, 126, 126, 126, 126, 126,
2, -13, 24, 45, 93, 107, -13, 3, 68, 83,
0, 0, 20, 20, 20, 20, -13, -13, -13, 126,
-13, -9, 4, -13, -13, 77, 25, 26, 38, 39,
-13, -13, -13, -13, -13
};
/* YYDEFACT[S] -- default reduction number in state S. Performed when
YYTABLE doesn't specify something else to do. Zero means the
default is an error. */
const unsigned char
selectParser::yydefact_[] =
{
0, 0, 0, 30, 28, 29, 0, 0, 0, 0,
2, 0, 26, 25, 0, 0, 0, 0, 1, 3,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 4, 0, 0, 0, 0, 27, 0, 17, 16,
10, 11, 12, 13, 14, 15, 7, 6, 18, 0,
19, 0, 0, 9, 8, 0, 0, 0, 0, 0,
24, 20, 21, 22, 23
};
/* YYPGOTO[NTERM-NUM]. */
const signed char
selectParser::yypgoto_[] =
{
-13, 37, -13, -1
};
/* YYDEFGOTO[NTERM-NUM]. */
const signed char
selectParser::yydefgoto_[] =
{
-1, 9, 10, 11
};
/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule which
number is the opposite. If YYTABLE_NINF_, syntax error. */
const signed char selectParser::yytable_ninf_ = -1;
const unsigned char
selectParser::yytable_[] =
{
12, 13, 46, 53, 56, 57, 14, 17, 26, 27,
28, 29, 15, 33, 34, 35, 16, 58, 59, 47,
54, 38, 39, 40, 41, 42, 43, 44, 45, 20,
18, 29, 21, 22, 23, 24, 25, 26, 27, 28,
29, 37, 30, 48, 61, 62, 31, 19, 55, 22,
23, 24, 25, 26, 27, 28, 29, 63, 64, 0,
0, 0, 49, 0, 50, 22, 23, 24, 25, 26,
27, 28, 29, 23, 24, 25, 26, 27, 28, 29,
36, 22, 23, 24, 25, 26, 27, 28, 29, 24,
25, 26, 27, 28, 29, 0, 60, 22, 23, 24,
25, 26, 27, 28, 29, 0, 0, 0, 0, 0,
51, 22, 23, 24, 25, 26, 27, 28, 29, 1,
2, 32, 0, 0, 52, 3, 4, 5, 6, 7,
0, 8, 1, 2, 0, 0, 0, 0, 3, 4,
5, 6, 7, 0, 8
};
/* YYCHECK. */
const signed char
selectParser::yycheck_[] =
{
1, 2, 0, 0, 13, 14, 18, 8, 8, 9,
10, 11, 18, 14, 15, 16, 18, 13, 14, 17,
17, 22, 23, 24, 25, 26, 27, 28, 29, 0,
0, 11, 3, 4, 5, 6, 7, 8, 9, 10,
11, 13, 13, 19, 19, 19, 17, 10, 49, 4,
5, 6, 7, 8, 9, 10, 11, 19, 19, -1,
-1, -1, 17, -1, 19, 4, 5, 6, 7, 8,
9, 10, 11, 5, 6, 7, 8, 9, 10, 11,
19, 4, 5, 6, 7, 8, 9, 10, 11, 6,
7, 8, 9, 10, 11, -1, 19, 4, 5, 6,
7, 8, 9, 10, 11, -1, -1, -1, -1, -1,
17, 4, 5, 6, 7, 8, 9, 10, 11, 6,
7, 8, -1, -1, 17, 12, 13, 14, 15, 16,
-1, 18, 6, 7, -1, -1, -1, -1, 12, 13,
14, 15, 16, -1, 18
};
/* STOS_[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
const unsigned char
selectParser::yystos_[] =
{
0, 6, 7, 12, 13, 14, 15, 16, 18, 21,
22, 23, 23, 23, 18, 18, 18, 23, 0, 21,
0, 3, 4, 5, 6, 7, 8, 9, 10, 11,
13, 17, 8, 23, 23, 23, 19, 13, 23, 23,
23, 23, 23, 23, 23, 23, 0, 17, 19, 17,
19, 17, 17, 0, 17, 23, 13, 14, 13, 14,
19, 19, 19, 19, 19
};
#if YYDEBUG
/* TOKEN_NUMBER_[YYLEX-NUM] -- Internal symbol number corresponding
to YYLEX-NUM. */
const unsigned short int
selectParser::yytoken_number_[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 44, 40, 41
};
#endif
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
const unsigned char
selectParser::yyr1_[] =
{
0, 20, 21, 21, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23
};
/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
const unsigned char
selectParser::yyr2_[] =
{
0, 2, 1, 2, 2, 2, 3, 3, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 4, 4,
6, 6, 6, 6, 6, 2, 2, 3, 1, 1,
1
};
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at \a yyntokens_, nonterminals. */
const char*
const selectParser::yytname_[] =
{
"\"end of input\"", "error", "$undefined", "\"as\"", "\"|\"", "\"&\"",
"\"+\"", "\"-\"", "\"*\"", "\"/\"", "\"%\"", "\"**\"",
"\"numerical value\"", "\"name\"", "\"string literal\"",
"\"FORMAT_UNIXTIME_GMT\"", "\"FORMAT_UNIXTIME_LOCAL\"", "','", "'('",
"')'", "$accept", "slist", "sterm", "mathExpr", YY_NULL
};
#if YYDEBUG
/* YYRHS -- A `-1'-separated list of the rules' RHS. */
const selectParser::rhs_number_type
selectParser::yyrhs_[] =
{
21, 0, -1, 22, -1, 22, 21, -1, 23, 17,
-1, 23, 0, -1, 23, 13, 17, -1, 23, 13,
0, -1, 23, 3, 13, 17, -1, 23, 3, 13,
0, -1, 23, 6, 23, -1, 23, 7, 23, -1,
23, 8, 23, -1, 23, 9, 23, -1, 23, 10,
23, -1, 23, 11, 23, -1, 23, 5, 23, -1,
23, 4, 23, -1, 13, 18, 8, 19, -1, 13,
18, 23, 19, -1, 15, 18, 23, 17, 13, 19,
-1, 15, 18, 23, 17, 14, 19, -1, 16, 18,
23, 17, 13, 19, -1, 16, 18, 23, 17, 14,
19, -1, 13, 18, 23, 17, 23, 19, -1, 7,
23, -1, 6, 23, -1, 18, 23, 19, -1, 13,
-1, 14, -1, 12, -1
};
/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
YYRHS. */
const unsigned char
selectParser::yyprhs_[] =
{
0, 0, 3, 5, 8, 11, 14, 18, 22, 27,
32, 36, 40, 44, 48, 52, 56, 60, 64, 69,
74, 81, 88, 95, 102, 109, 112, 115, 119, 121,
123
};
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
const unsigned short int
selectParser::yyrline_[] =
{
0, 78, 78, 78, 79, 82, 85, 89, 93, 97,
104, 116, 128, 140, 152, 164, 176, 188, 200, 219,
423, 435, 447, 459, 471, 485, 495, 498, 501, 509,
517
};
// Print the state stack on the debug stream.
void
selectParser::yystack_print_ ()
{
*yycdebug_ << "Stack now";
for (state_stack_type::const_iterator i = yystate_stack_.begin ();
i != yystate_stack_.end (); ++i)
*yycdebug_ << ' ' << *i;
*yycdebug_ << std::endl;
}
// Report on the debug stream that the rule \a yyrule is going to be reduced.
void
selectParser::yy_reduce_print_ (int yyrule)
{
unsigned int yylno = yyrline_[yyrule];
int yynrhs = yyr2_[yyrule];
/* Print the symbols being reduced, and their result. */
*yycdebug_ << "Reducing stack by rule " << yyrule - 1
<< " (line " << yylno << "):" << std::endl;
/* The symbols being reduced. */
for (int yyi = 0; yyi < yynrhs; yyi++)
YY_SYMBOL_PRINT (" $" << yyi + 1 << " =",
yyrhs_[yyprhs_[yyrule] + yyi],
&(yysemantic_stack_[(yynrhs) - (yyi + 1)]),
&(yylocation_stack_[(yynrhs) - (yyi + 1)]));
}
#endif // YYDEBUG
/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
selectParser::token_number_type
selectParser::yytranslate_ (int t)
{
static
const token_number_type
translate_table[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
18, 19, 2, 2, 17, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16
};
if ((unsigned int) t <= yyuser_token_number_max_)
return translate_table[t];
else
return yyundef_token_;
}
const int selectParser::yyeof_ = 0;
const int selectParser::yylast_ = 144;
const int selectParser::yynnts_ = 4;
const int selectParser::yyempty_ = -2;
const int selectParser::yyfinal_ = 18;
const int selectParser::yyterror_ = 1;
const int selectParser::yyerrcode_ = 256;
const int selectParser::yyntokens_ = 20;
const unsigned int selectParser::yyuser_token_number_max_ = 271;
const selectParser::token_number_type selectParser::yyundef_token_ = 2;
} // ibis
/* Line 1135 of lalr1.cc */
#line 1649 "selectParser.cc"
/* Line 1136 of lalr1.cc */
#line 526 "selectParser.yy"
void ibis::selectParser::error(const ibis::selectParser::location_type& l,
const std::string& m) {
LOGGER(ibis::gVerbose >= 0)
<< "Warning -- ibis::selectParser encountered " << m << " at location "
<< l;
}
| 34.425814 | 111 | 0.547987 | nporsche |
281874f0f50215f6ddae0de843f105fd9460a5dc | 906 | hpp | C++ | src/unit/cavalry/knight.hpp | JoiNNewtany/LETI-Game | 51d31a2b0b212f8bbd11c1562af4ef23d34437b6 | [
"Unlicense"
] | 2 | 2021-11-15T19:27:32.000Z | 2021-12-10T20:51:37.000Z | src/unit/cavalry/knight.hpp | JoiNNewtany/LETI-Game | 51d31a2b0b212f8bbd11c1562af4ef23d34437b6 | [
"Unlicense"
] | null | null | null | src/unit/cavalry/knight.hpp | JoiNNewtany/LETI-Game | 51d31a2b0b212f8bbd11c1562af4ef23d34437b6 | [
"Unlicense"
] | null | null | null | #pragma once
#include "unit/unit.hpp"
class Knight : public Unit {
public:
Knight(int hp = 80, int dmg = 15, int df = 5) {
health = hp;
maxHealth = hp;
damage = dmg;
defense = df;
graphics = 'k';
}
~Knight() {}
virtual bool attack(Unit&) override;
virtual Knight* duplicate() override;
virtual void setHealth(int h) override { health = h; }
virtual int getHealth() override { return health; }
virtual void setDefense(int d) override { defense = d; }
virtual int getDefense() override { return defense; }
virtual void setDamage(int d) override { damage = d; }
virtual int getDamage() override { return damage; }
virtual void setGraphics(char g) override { graphics = g; }
virtual char getGraphics() override { return graphics; }
};
| 29.225806 | 67 | 0.572848 | JoiNNewtany |
2819887ad608e023490df95aa9871e8f846b53bd | 151 | cpp | C++ | Src/Kranos/Layer.cpp | KDahir247/KranosLoader | 5e55a0f1a697170020c2601c9b0d04b0da27da93 | [
"MIT"
] | null | null | null | Src/Kranos/Layer.cpp | KDahir247/KranosLoader | 5e55a0f1a697170020c2601c9b0d04b0da27da93 | [
"MIT"
] | null | null | null | Src/Kranos/Layer.cpp | KDahir247/KranosLoader | 5e55a0f1a697170020c2601c9b0d04b0da27da93 | [
"MIT"
] | null | null | null | //
// Created by kdahi on 2020-09-29.
//
#include "Layer.h"
Layer::Layer(std::string name) : m_DebugName(std::move(name)) {
}
Layer::~Layer() {
} | 10.785714 | 63 | 0.609272 | KDahir247 |
281a91c72bf7f47480b2a52e92ab2773f3aac8da | 3,011 | cpp | C++ | simple-dx11-renderer/Systems/DataSystem.cpp | ike-0/simple-dx11-renderer | e6597e30d9675a56be84c8c26f78697cc16a7e25 | [
"MIT"
] | null | null | null | simple-dx11-renderer/Systems/DataSystem.cpp | ike-0/simple-dx11-renderer | e6597e30d9675a56be84c8c26f78697cc16a7e25 | [
"MIT"
] | null | null | null | simple-dx11-renderer/Systems/DataSystem.cpp | ike-0/simple-dx11-renderer | e6597e30d9675a56be84c8c26f78697cc16a7e25 | [
"MIT"
] | null | null | null | #include "DataSystem.h"
DataSystem* DataSystem::Instance = nullptr;
DataSystem::DataSystem()
{
Instance = this;
}
DataSystem::~DataSystem()
{
Instance = nullptr;
RemoveShaders();
}
void DataSystem::LoadShaders()
{
try
{
std::filesystem::path shaderpath = Path::Relative("shaders\\");
for (auto& dir : std::filesystem::recursive_directory_iterator(shaderpath))
{
if (dir.is_directory())
continue;
if (dir.path().extension() == ".hlsl")
{
AddShaderFromPath(dir.path());
}
}
}
catch (const std::filesystem::filesystem_error& e)
{
WARN("Could not load shaders" + e.what());
}
catch (const std::exception& e)
{
WARN("Error" + e.what());
}
}
void DataSystem::LoadModels()
{
std::filesystem::path shaderpath = Path::Relative("meshes\\");
for (auto& dir : std::filesystem::recursive_directory_iterator(shaderpath))
{
if (dir.is_directory())
continue;
if (dir.path().extension() == ".dae" || dir.path().extension() == ".gltf" || dir.path().extension() == ".fbx")
{
AddModel(dir.path(), dir.path().parent_path());
}
}
}
//void DataSystem::ReloadShaders()
//{
// OnShadersReloadedEvent.Invoke();
// RemoveShaders();
// LoadShaders();
// ShadersReloadedEvent.Invoke();
//}
void DataSystem::AddShaderFromPath(const std::filesystem::path& filepath)
{
Microsoft::WRL::ComPtr<ID3DBlob> blob = HLSLCompiler::LoadFromFile(filepath);
std::filesystem::path filename = filepath.filename();
std::string ext = filename.replace_extension().extension().string();
filename.replace_extension();
ext.erase(0, 1);
AddShader(filename.string(), ext, blob);
}
void DataSystem::AddModel(const std::filesystem::path& filepath, const std::filesystem::path& dir)
{
std::shared_ptr<Model> model;
std::shared_ptr<AnimModel> animmodel;
ModelLoader::LoadFromFile(filepath,dir, &model, &animmodel);
if (model)
{
Models[model->name] = model;
}
}
void DataSystem::AddShader(const std::string& name, const std::string& ext, const Microsoft::WRL::ComPtr<ID3DBlob>& blob)
{
if (ext == "vs")
{
VertexShader vs = VertexShader(name, blob);
vs.Compile();
VertexShaders[name] = vs;
}
else if (ext == "hs")
{
HullShader hs = HullShader(name, blob);
hs.Compile();
HullShaders[name] = hs;
}
else if (ext == "ds")
{
DomainShader ds = DomainShader(name, blob);
ds.Compile();
DomainShaders[name] = ds;
}
else if (ext == "gs")
{
GeometryShader gs = GeometryShader(name, blob);
gs.Compile();
GeometryShaders[name] = gs;
}
else if (ext == "ps")
{
PixelShader ps = PixelShader(name, blob);
ps.Compile();
PixelShaders[name] = ps;
}
else if (ext == "cs")
{
ComputeShader cs = ComputeShader(name, blob);
cs.Compile();
ComputeShaders[name] = cs;
}
else
{
WARN("Unrecognized shader extension \"" + ext + "\" for shader \"" + name + "\"");
}
}
void DataSystem::RemoveShaders()
{
VertexShaders.clear();
HullShaders.clear();
DomainShaders.clear();
GeometryShaders.clear();
PixelShaders.clear();
ComputeShaders.clear();
}
| 20.909722 | 121 | 0.663235 | ike-0 |
281c5f3d12b95787c73b64e42ee2bd5cf0a020d3 | 1,376 | cc | C++ | src/ft_ee_ua_size_op.cc | Incont/n-ftdi | fb9ec653b731c9e55d50a668be539b4774950c8b | [
"MIT"
] | 2 | 2019-09-30T09:22:06.000Z | 2019-09-30T14:40:11.000Z | src/ft_ee_ua_size_op.cc | Incont/n-ftdi | fb9ec653b731c9e55d50a668be539b4774950c8b | [
"MIT"
] | 8 | 2019-09-05T05:18:45.000Z | 2021-07-11T11:45:30.000Z | src/ft_ee_ua_size_op.cc | Incont/n-ftdi | fb9ec653b731c9e55d50a668be539b4774950c8b | [
"MIT"
] | 3 | 2020-05-25T09:49:25.000Z | 2020-06-29T18:34:47.000Z | #include "ft_ee_ua_size_op.h"
Napi::Object FtEeUaSize::Init(Napi::Env env, Napi::Object exports)
{
exports.Set("eeUaSizeSync", Napi::Function::New(env, FtEeUaSize::InvokeSync));
exports.Set("eeUaSize", Napi::Function::New(env, FtEeUaSize::Invoke));
return exports;
}
Napi::Object FtEeUaSize::InvokeSync(const Napi::CallbackInfo &info)
{
FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data();
DWORD uaSize;
FT_STATUS ftStatus = FT_EE_UASize(ftHandle, &uaSize);
return CreateResult(info.Env(), ftStatus, uaSize);
}
Napi::Promise FtEeUaSize::Invoke(const Napi::CallbackInfo &info)
{
FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data();
auto *operation = new FtEeUaSize(info.Env(), ftHandle);
operation->Queue();
return operation->Promise();
}
FtEeUaSize::FtEeUaSize(Napi::Env env, FT_HANDLE ftHandle)
: FtBaseOp(env),
ftHandle(ftHandle)
{
}
void FtEeUaSize::Execute()
{
ftStatus = FT_EE_UASize(ftHandle, &uaSize);
}
void FtEeUaSize::OnOK()
{
Napi::HandleScope scope(Env());
deferred.Resolve(CreateResult(Env(), ftStatus, uaSize));
}
Napi::Object FtEeUaSize::CreateResult(Napi::Env env, FT_STATUS ftStatus, DWORD uaSize)
{
Napi::Object result = Napi::Object::New(env);
result.Set("ftStatus", ftStatus);
result.Set("uaSize", uaSize);
return result;
} | 28.081633 | 86 | 0.695494 | Incont |
281cef6cd6f9e35263ab4bd3be968217ab81112d | 5,880 | cpp | C++ | ScriptHookDotNet/ScriptThread.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 3 | 2021-11-14T20:59:58.000Z | 2021-12-16T16:41:31.000Z | ScriptHookDotNet/ScriptThread.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 2 | 2021-11-29T14:41:23.000Z | 2021-11-30T13:13:51.000Z | ScriptHookDotNet/ScriptThread.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 3 | 2021-11-21T12:41:55.000Z | 2021-12-22T16:17:52.000Z | /*
* Copyright (c) 2009-2011 Hazard ([email protected] / twitter.com/HazardX)
*
* 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 "stdafx.h"
#include "NetThread.h"
#include "ScriptThread.h"
#include "RemoteScriptDomain.h"
#include "Script.h"
namespace GTA {
#ifdef USE_NETTHREAD
ScriptThread::ScriptThread(RemoteScriptDomain^ domain, String^ scriptFile, System::Type^ scriptType) {
#else
ScriptThread::ScriptThread(RemoteScriptDomain^ domain, String^ scriptFile, System::Type^ scriptType)
:IngameThread(true) {
#endif
//SetName("CustomFiberThread");
//GTA::NetHook::LoadScripts();
this->domain = domain;
this->scriptFile = scriptFile;
this->scriptType = scriptType;
}
//ScriptThread::~ScriptThread() {
// this->!ScriptThread();
//}
//ScriptThread::!ScriptThread() {
// if isNotNULL(scriptType) {
// LogFin(scriptType->ToString());
// //delete scriptType;
// scriptType = nullptr;
// }
// if isNotNULL(script) {
// //delete script;
// script = nullptr;
// }
//}
[System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions]
bool ScriptThread::LoadScriptNow() {
//if (!Game::isModdingAllowed) {
// GTA::NetHook::Log(String::Concat( "Rejected start of script '", scriptType->FullName, "' in this multiplayer gamemode!" ));
// //GTA::NetHook::DisplayText(String::Concat( "DO NOT USE MODS/SCRIPTS IN RANKED MULTIPLAYER GAMES!" ), 10000 );
// //Abort();
// return false ;
//}
currentlyLoading = this;
if (VERBOSE) GTA::NetHook::Log(String::Concat( "Constructing script '", scriptType->FullName, "'..." ));
try {
if isNULL(scriptType) return false;
// IMPORTANT: Constructor runs here already
System::Object^ o = System::Activator::CreateInstance(scriptType);
if isNULL(o) return false;
script = static_cast<GTA::Script^>(o); //domain->LoadScript(scriptType);
if isNotNULL(script) {
script->Initialize(this);
//if (VERBOSE) GTA::NetHook::Log(String::Concat( " ...successfully constructed script '", script->Name, "'!" ));
return true;
} else {
//bError = true;
return false;
}
} catch (System::InvalidOperationException^) {
//Object::ReferenceEquals(ex,nullptr); // just a dummy to get rid of the warning
//bError = true;
return false;
} catch (System::Reflection::TargetInvocationException^ ex) {
try {
if ( isNULL(ex) || isNULL(ex->InnerException) ) {
throw gcnew Exception();
return false;
}
throw ex->InnerException;
//} catch (System::MissingMethodException^ ex) {
// if (ex->ToString()->Contains("GTA.value.ScriptSettings GTA.Script.get_Settings()")) continue;
} catchErrors ("Error in constructor of script '"+scriptType->FullName+"'", )
return false;
} catchErrors ("Error during construction of script '"+scriptType->FullName+"'", ) //bError = true;
return false;
}
[System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions]
void ScriptThread::OnStartup() {
bool bError = false;
//lock(syncroot) {
bError = !LoadScriptNow();
//bError = isNULL(script);
if (!bError) {
//if (!GTA::NetHook::RunScript(script)) bError = true;
try {
//if (VERBOSE) GTA::NetHook::Log(String::Concat( " ...starting script '", script->Name, "'..." ));
domain->SetCurrentScript(script); // we have to set it here again, because script was still Nothing at startup
script->DoStartup();
domain->AddRunningScript(script);
GTA::NetHook::Log(String::Concat( " ...successfully started script '", script->Name, "'!" ));
} catchScriptErrors (script, "Startup", bError = true; )
}
if (bError) {
GTA::NetHook::DisplayText( String::Concat("Error in script '", scriptType->FullName, "'!"), 5000 );
if isNotNULL(script) script->myThread = nullptr;
Abort();
}
//} unlock(syncroot);
//script = GTA::NetHook::RunScript(scriptType);
//if(script != nullptr) {
// script->myThread = this;
//} else {
// Abort();
//}
}
[System::Runtime::ExceptionServices::HandleProcessCorruptedStateExceptions]
void ScriptThread::OnTick() {
//lock(syncroot) {
if ( isNULL(script) || (!script->isRunning) ) {
//Abort();
return;
}
try {
script->DoTick();
} catch (System::Threading::ThreadAbortException^ taex) {
throw taex;
} catchScriptErrors (script, "Tick", if isNotNULL(script) script->Abort(); )
//} unlock(syncroot);
}
void ScriptThread::OnThreadContinue() {
domain->SetCurrentScript(script);
}
void ScriptThread::OnThreadHalt() {
//RemoteScriptDomain::Instance->RaiseEventInLocalScriptDomain("ThreadHalt",nullptr);
domain->SetCurrentScript(nullptr);
}
void ScriptThread::OnEnd() {
if isNotNULL(script) {
if (VERBOSE) NetHook::Log("Script ended: " + script->Name);
domain->RemoveRunningScript(script);
}
}
} | 31.44385 | 129 | 0.680442 | HazardX |
281fc5b4ad418631e464c9fb6bb424d4a7a74785 | 3,589 | cpp | C++ | doc/6.0.1/MPG/example-search-tracer.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 1 | 2020-10-28T06:11:30.000Z | 2020-10-28T06:11:30.000Z | doc/6.0.1/MPG/example-search-tracer.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 1 | 2019-05-05T11:10:31.000Z | 2019-05-05T11:10:31.000Z | doc/6.0.1/MPG/example-search-tracer.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 4 | 2019-05-03T18:43:19.000Z | 2020-12-17T04:06:59.000Z | /*
* Authors:
* Christian Schulte <[email protected]>
*
* Copyright:
* Christian Schulte, 2008-2018
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this 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 <gecode/search.hh>
using namespace Gecode;
class SimpleSearchTracer : public SearchTracer {
protected:
static const char* t2s(EngineType et) {
switch (et) {
case EngineType::DFS: return "DFS";
case EngineType::BAB: return "BAB";
case EngineType::LDS: return "LDS";
case EngineType::RBS: return "RBS";
case EngineType::PBS: return "PBS";
case EngineType::AOE: return "AOE";
}
}
public:
SimpleSearchTracer(void) {}
// init
virtual void init(void) {
std::cout << "trace<Search>::init()" << std::endl;
for (unsigned int e=0U; e<engines(); e++) {
std::cout << "\t" << e << ": "
<< t2s(engine(e).type());
if (engine(e).meta()) {
// init for meta engines
std::cout << ", engines: {";
for (unsigned int i=engine(e).efst(); i<engine(e).elst(); i++) {
std::cout << i; if (i+1 < engine(e).elst()) std::cout << ",";
}
} else {
// init for engines
std::cout << ", workers: {";
for (unsigned int i=engine(e).wfst(); i<engine(e).wlst(); i++) {
std::cout << i; if (i+1 < engine(e).wlst()) std::cout << ",";
}
}
std::cout << "}" << std::endl;
}
}
// node
virtual void node(const EdgeInfo& ei, const NodeInfo& ni) {
std::cout << "trace<Search>::node(";
switch (ni.type()) {
case NodeType::FAILED:
std::cout << "FAILED";
break;
case NodeType::SOLVED:
std::cout << "SOLVED";
break;
case NodeType::BRANCH:
std::cout << "BRANCH(" << ni.choice().alternatives() << ")";
break;
}
std::cout << ',' << "w:" << ni.wid() << ','
<< "n:" << ni.nid() << ')';
if (ei) {
if (ei.wid() != ni.wid())
std::cout << " [stolen from w:" << ei.wid() << "]";
std::cout << std::endl << '\t' << ei.string()
<< std::endl;
} else {
std::cout << std::endl;
}
}
// round
virtual void round(unsigned int eid) {
std::cout << "trace<Search>::round(e:" << eid << ")" << std::endl;
}
// skip
virtual void skip(const EdgeInfo& ei) {
std::cout << "trace<Search>Search::skip(w:" << ei.wid()
<< ",n:" << ei.nid()
<< ",a:" << ei.alternative() << ")" << std::endl;
}
// done
virtual void done(void) {
std::cout << "trace<Search>::done()" << std::endl;
}
virtual ~SimpleSearchTracer(void) {}
};
| 33.231481 | 77 | 0.574255 | zayenz |
28286fc38f45510bdb7d3e72f057aa401cd1e532 | 8,781 | cpp | C++ | wrap/csllbc/native/src/comm/_Service.cpp | shakeumm/llbc | 5aaf6f83eedafde87d52adf44b7548e85ad4a9d1 | [
"MIT"
] | 5 | 2021-10-31T17:12:45.000Z | 2022-01-10T11:10:27.000Z | wrap/csllbc/native/src/comm/_Service.cpp | shakeumm/llbc | 5aaf6f83eedafde87d52adf44b7548e85ad4a9d1 | [
"MIT"
] | 1 | 2019-09-04T12:23:37.000Z | 2019-09-04T12:23:37.000Z | wrap/csllbc/native/src/comm/_Service.cpp | ericyonng/llbc | a7fd1193db03b8ad34879441b09914adec8a62e6 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<[email protected]>
//
// 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 "csllbc/common/Export.h"
#include "csllbc/comm/csCoder.h"
#include "csllbc/comm/csFacade.h"
#include "csllbc/comm/csService.h"
#include "csllbc/comm/_Service.h"
LLBC_BEGIN_C_DECL
csllbc_Service *csllbc_Service_Create(int svcType,
const char *svcName,
bool fullStack,
csllbc_Delegates::Deleg_Service_EncodePacket encodeDeleg,
csllbc_Delegates::Deleg_Service_DecodePacket decodeDeleg,
csllbc_Delegates::Deleg_Service_PacketHandler handlerDeleg,
csllbc_Delegates::Deleg_Service_PacketPreHandler preHandlerDeleg,
csllbc_Delegates::Deleg_Service_PacketUnifyPreHandler unifyPreHandlerDeleg,
csllbc_Delegates::Deleg_Service_NativeCouldNotFoundDecoderReport notFoundDecoderDeleg)
{
if (svcType != static_cast<int>(LLBC_IService::Raw) &&
svcType != static_cast<int>(LLBC_IService::Normal))
{
LLBC_SetLastError(LLBC_ERROR_ARG);
return NULL;
}
return LLBC_New9(csllbc_Service,
static_cast<csllbc_Service::Type>(svcType),
svcName,
fullStack != 0,
encodeDeleg,
decodeDeleg,
handlerDeleg,
preHandlerDeleg,
unifyPreHandlerDeleg,
notFoundDecoderDeleg);
}
void csllbc_Service_Delete(csllbc_Service *svc)
{
LLBC_XDelete(svc);
}
int csllbc_Service_GetType(csllbc_Service *svc)
{
return static_cast<int>(svc->GetType());
}
int csllbc_Service_GetId(csllbc_Service *svc)
{
return svc->GetId();
}
int csllbc_Service_IsFullStack(csllbc_Service *svc)
{
return svc->IsFullStack() ? 1 : 0;
}
int csllbc_Service_GetDriveMode(csllbc_Service *svc)
{
return static_cast<int>(svc->GetDriveMode());
}
int csllbc_Service_SetDriveMode(csllbc_Service *svc, int driveMode)
{
return svc->SetDriveMode(static_cast<LLBC_IService::DriveMode>(driveMode));
}
int csllbc_Service_Start(csllbc_Service *svc, int pollerCount)
{
return svc->Start(pollerCount);
}
void csllbc_Service_Stop(csllbc_Service *svc)
{
svc->Stop();
}
int csllbc_Service_IsStarted(csllbc_Service *svc)
{
return svc->IsStarted() ? 1 : 0;
}
int csllbc_Service_GetFPS(csllbc_Service *svc)
{
return svc->GetFPS();
}
int csllbc_Service_SetFPS(csllbc_Service *svc, int fps)
{
return svc->SetFPS(fps);
}
int csllbc_Service_GetFrameInterval(csllbc_Service *svc)
{
return svc->GetFrameInterval();
}
int csllbc_Service_Listen(csllbc_Service *svc, const char *ip, int port)
{
return svc->Listen(ip, port);
}
int csllbc_Service_Connect(csllbc_Service *svc, const char *ip, int port)
{
return svc->Connect(ip, port);
}
int csllbc_Service_AsyncConn(csllbc_Service *svc, const char *ip, int port)
{
return svc->AsyncConn(ip, port);
}
int csllbc_Service_RemoveSession(csllbc_Service *svc, int sessionId, const char *reason, int reasonLength)
{
char *nativeReason;
if (reasonLength == 0)
{
nativeReason = NULL;
}
else
{
nativeReason = LLBC_Malloc(char, reasonLength + 1);
memcpy(nativeReason, reason, reasonLength);
nativeReason[reasonLength] = '\0';
}
const int ret = svc->RemoveSession(sessionId, nativeReason);
LLBC_XFree(nativeReason);
return ret;
}
int csllbc_Service_IsSessionValidate(csllbc_Service *svc, int sessionId)
{
return svc->IsSessionValidate(sessionId) ? 1 : 0;
}
int csllbc_Service_SendBytes(csllbc_Service *svc,
int sessionId,
int opcode,
const void *data,
int dataLen,
int status)
{
return svc->Send(sessionId, opcode, data, static_cast<size_t>(dataLen), status);
}
int csllbc_Service_SendPacket(csllbc_Service *svc,
int sessionId,
int opcode,
sint64 packetId,
int status)
{
csllbc_Coder *coder = LLBC_New(csllbc_Coder);
coder->SetEncodeInfo(packetId, svc->GetEncodePacketDeleg());
if (svc->Send(sessionId, opcode, coder, status) != LLBC_OK)
{
LLBC_Delete(coder);
return LLBC_FAILED;
}
return LLBC_OK;
}
int csllbc_Service_Multicast(csllbc_Service *svc,
int *sessionIds,
int sessionIdCount,
int opcode,
const void *data,
int dataLen,
int status)
{
LLBC_SessionIdList sessionIdList(sessionIdCount);
for (int idx = 0; idx < sessionIdCount; ++idx)
sessionIdList.push_back(sessionIds[idx]);
LLBC_XFree(sessionIds);
return svc->Multicast(sessionIdList, opcode, data, static_cast<size_t>(dataLen), status);
}
int csllbc_Service_Broadcast(csllbc_Service *svc,
int opcode,
const void *data,
int dataLen,
int status)
{
return svc->Broadcast(opcode, data, static_cast<size_t>(dataLen), status);
}
int csllbc_Service_RegisterFacade(csllbc_Service *svc,
csllbc_Delegates::Deleg_Facade_OnInit initDeleg,
csllbc_Delegates::Deleg_Facade_OnDestroy destroyDeleg,
csllbc_Delegates::Deleg_Facade_OnStart startDeleg,
csllbc_Delegates::Deleg_Facade_OnStop stopDeleg,
csllbc_Delegates::Deleg_Facade_OnUpdate updateDeleg,
csllbc_Delegates::Deleg_Facade_OnIdle idleDeleg,
csllbc_Delegates::Deleg_Facade_OnSessionCreate sessionCreateDeleg,
csllbc_Delegates::Deleg_Facade_OnSessionDestroy sessionDestroyDeleg,
csllbc_Delegates::Deleg_Facade_OnAsyncConnResult asyncConnResultDeleg,
csllbc_Delegates::Deleg_Facade_OnProtoReport protoReportDeleg,
csllbc_Delegates::Deleg_Facade_OnUnHandledPacket unHandledPacketDeleg)
{
csllbc_Facade *facade = new csllbc_Facade(initDeleg, destroyDeleg,
startDeleg, stopDeleg,
updateDeleg, idleDeleg,
sessionCreateDeleg, sessionDestroyDeleg, asyncConnResultDeleg,
protoReportDeleg, unHandledPacketDeleg);
if (svc->RegisterFacade(facade) != LLBC_OK)
{
LLBC_Delete(facade);
return LLBC_FAILED;
}
return LLBC_OK;
}
int csllbc_Service_RegisterCoder(csllbc_Service *svc, int opcode)
{
return svc->RegisterCoder(opcode);
}
int csllbc_Service_Subscribe(csllbc_Service *svc, int opcode)
{
return svc->Subscribe(opcode);
}
int csllbc_Service_PreSubscribe(csllbc_Service *svc, int opcode)
{
return svc->PreSubscribe(opcode);
}
int csllbc_Service_UnifyPreSubscribe(csllbc_Service *svc)
{
return svc->UnifyPreSubscribe();
}
void csllbc_Service_OnSvc(csllbc_Service *svc, bool fullFrame)
{
svc->OnSvc(fullFrame);
}
LLBC_END_C_DECL
| 32.643123 | 124 | 0.623961 | shakeumm |
282c19a79fdd2e73cbab17a4ac5b4a42ea2f5aaf | 1,511 | cpp | C++ | ABC197/e.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | ABC197/e.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | 3 | 2021-03-31T01:39:25.000Z | 2021-05-04T10:02:35.000Z | ABC197/e.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for (int i = m; i <= n; i++)
#define FORR(i, m, n) for (int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v + n)
#define MAX 100000
#define inf 1000000007
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<ll, ll>;
using Graph = vector<vector<int>>;
int main()
{
// cin高速化
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<vector<int>> ball(n + 1);
// 色名の管理
set<int> ctyp;
int x, c;
REP(i, n)
{
cin >> x >> c;
ball[c].push_back(x);
ctyp.insert(c);
}
// 色iまで回収し終えたあとに左・右端にいるスコアの最小値
// 左端にいる場合のスコア、右端にいる場合のスコア
ll lscore = 0, rscore = 0;
// 0色回収後の色
int lnew = 0, rnew = 0;
for (auto c : ctyp)
{
sort(ball[c].begin(), ball[c].end());
// 次の色の左端、右端の座標
int l = ball[c][0], r = ball[c][ball[c].size() - 1];
// lnew or rnewからrに移動して、rからlへ回収
ll lmi = min(lscore + abs(r - lnew), rscore + abs(r - rnew)) + abs(r - l);
// lnew or rnewからlに移動して、lからrへ回収
ll rmi = min(lscore + abs(l - lnew), rscore + abs(l - rnew)) + abs(r - l);
// 更新後のスコア
lscore = lmi;
rscore = rmi;
// 操作後の座標
lnew = l;
rnew = r;
}
// 原点へ戻る
cout << min(lscore + abs(lnew), rscore + abs(rnew)) << "\n";
return 0;
} | 26.051724 | 82 | 0.512244 | KoukiNAGATA |
283206c28f3ee30b3afe64271cb1a35d04d539d4 | 1,525 | cpp | C++ | src/read_fasta.cpp | danielsundfeld/cuda_sankoff | dd765a2707b14aef24852a7e1d4d6e5df565d38d | [
"MIT"
] | null | null | null | src/read_fasta.cpp | danielsundfeld/cuda_sankoff | dd765a2707b14aef24852a7e1d4d6e5df565d38d | [
"MIT"
] | null | null | null | src/read_fasta.cpp | danielsundfeld/cuda_sankoff | dd765a2707b14aef24852a7e1d4d6e5df565d38d | [
"MIT"
] | null | null | null | /*!
* \author Daniel Sundfeld
* \copyright MIT License
*/
#include "read_fasta.h"
#include <fstream>
#include <iostream>
#include <string>
#include "Sequences.h"
int read_fasta_file_core(const std::string &name)
{
std::ifstream file(name.c_str());
Sequences *sequences = Sequences::get_instance();
if (!file.is_open())
{
std::cout << "Can't open file " << name << std::endl;
return -1;
}
while (!file.eof())
{
std::string seq;
while (!file.eof())
{
std::string buf;
getline(file, buf);
if ((buf.length() <= 0) || (buf.at(0) == '>'))
break;
seq.append(buf);
}
if (!seq.empty())
sequences->set_seq(seq);
}
return 0;
}
/*!
* Read the \a name fasta file, loading it to the Sequences singleton.
* Fail if the number of sequences is non-null and not equal to \a limit
*/
int read_fasta_file(const std::string &name, const int &check)
{
try
{
int ret = read_fasta_file_core(name);
if (ret == 0 && check != 0 && Sequences::get_nseq() != check)
{
std::cerr << "Invalid fasta file: must have " << check << " sequences.\n";
return -1;
}
return ret;
}
catch (std::exception &e)
{
std::cerr << "Reading file fatal error: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown fatal error while reading file!\n";
}
return -1;
}
| 22.761194 | 86 | 0.523934 | danielsundfeld |
28331d1fad394a87a4e92012de0e9b6b0598c39f | 26,831 | cpp | C++ | shared/source/device_binary_format/patchtokens_decoder.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | shared/source/device_binary_format/patchtokens_decoder.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | shared/source/device_binary_format/patchtokens_decoder.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2019-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "patchtokens_decoder.h"
#include "shared/source/debug_settings/debug_settings_manager.h"
#include "shared/source/helpers/debug_helpers.h"
#include "shared/source/helpers/hash.h"
#include "shared/source/helpers/ptr_math.h"
#include <algorithm>
namespace NEO {
namespace PatchTokenBinary {
struct PatchTokensStreamReader {
const ArrayRef<const uint8_t> data;
PatchTokensStreamReader(ArrayRef<const uint8_t> data) : data(data) {}
template <typename DecodePosT>
bool notEnoughDataLeft(DecodePosT *decodePos, size_t requestedSize) {
return getDataSizeLeft(decodePos) < requestedSize;
}
template <typename T, typename DecodePosT>
constexpr bool notEnoughDataLeft(DecodePosT *decodePos) {
return notEnoughDataLeft(decodePos, sizeof(T));
}
template <typename... ArgsT>
bool enoughDataLeft(ArgsT &&...args) {
return false == notEnoughDataLeft(std::forward<ArgsT>(args)...);
}
template <typename T, typename... ArgsT>
bool enoughDataLeft(ArgsT &&...args) {
return false == notEnoughDataLeft<T>(std::forward<ArgsT>(args)...);
}
template <typename DecodePosT>
size_t getDataSizeLeft(DecodePosT *decodePos) {
auto dataConsumed = ptrDiff(decodePos, data.begin());
UNRECOVERABLE_IF(dataConsumed > data.size());
return data.size() - dataConsumed;
}
};
template <typename T>
inline void assignToken(const T *&dst, const SPatchItemHeader *src) {
dst = reinterpret_cast<const T *>(src);
}
inline KernelArgFromPatchtokens &getKernelArg(KernelFromPatchtokens &kernel, size_t argNum, ArgObjectType type = ArgObjectType::None, ArgObjectTypeSpecialized typeSpecialized = ArgObjectTypeSpecialized::None) {
if (kernel.tokens.kernelArgs.size() < argNum + 1) {
kernel.tokens.kernelArgs.resize(argNum + 1);
}
auto &arg = kernel.tokens.kernelArgs[argNum];
if (arg.objectType == ArgObjectType::None) {
arg.objectType = type;
} else if ((arg.objectType != type) && (type != ArgObjectType::None)) {
kernel.decodeStatus = DecodeError::InvalidBinary;
DBG_LOG(LogPatchTokens, "\n Mismatched metadata for kernel arg :", argNum);
DEBUG_BREAK_IF(true);
}
if (arg.objectTypeSpecialized == ArgObjectTypeSpecialized::None) {
arg.objectTypeSpecialized = typeSpecialized;
} else if (typeSpecialized != ArgObjectTypeSpecialized::None) {
UNRECOVERABLE_IF(arg.objectTypeSpecialized != typeSpecialized);
}
return arg;
}
inline void assignArgInfo(KernelFromPatchtokens &kernel, const SPatchItemHeader *src) {
auto argInfoToken = reinterpret_cast<const SPatchKernelArgumentInfo *>(src);
getKernelArg(kernel, argInfoToken->ArgumentNumber, ArgObjectType::None).argInfo = argInfoToken;
}
template <typename T>
inline uint32_t getArgNum(const SPatchItemHeader *argToken) {
return reinterpret_cast<const T *>(argToken)->ArgumentNumber;
}
inline void assignArg(KernelFromPatchtokens &kernel, const SPatchItemHeader *src) {
uint32_t argNum = 0;
ArgObjectType type = ArgObjectType::Buffer;
switch (src->Token) {
default:
UNRECOVERABLE_IF(src->Token != PATCH_TOKEN_SAMPLER_KERNEL_ARGUMENT);
argNum = getArgNum<SPatchSamplerKernelArgument>(src);
type = ArgObjectType::Sampler;
break;
case PATCH_TOKEN_IMAGE_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchImageMemoryObjectKernelArgument>(src);
type = ArgObjectType::Image;
break;
case PATCH_TOKEN_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchGlobalMemoryObjectKernelArgument>(src);
break;
case PATCH_TOKEN_STATELESS_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchStatelessGlobalMemoryObjectKernelArgument>(src);
break;
case PATCH_TOKEN_STATELESS_CONSTANT_MEMORY_OBJECT_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchStatelessConstantMemoryObjectKernelArgument>(src);
break;
case PATCH_TOKEN_STATELESS_DEVICE_QUEUE_KERNEL_ARGUMENT:
argNum = getArgNum<SPatchStatelessDeviceQueueKernelArgument>(src);
break;
}
getKernelArg(kernel, argNum, type).objectArg = src;
}
inline void assignToken(StackVecStrings &stringVec, const SPatchItemHeader *src) {
auto stringToken = reinterpret_cast<const SPatchString *>(src);
if (stringVec.size() < stringToken->Index + 1) {
stringVec.resize(stringToken->Index + 1);
}
stringVec[stringToken->Index] = stringToken;
}
template <size_t S>
inline void assignTokenInArray(const SPatchDataParameterBuffer *(&tokensArray)[S], const SPatchDataParameterBuffer *src, StackVecUnhandledTokens &unhandledTokens) {
auto sourceIndex = src->SourceOffset >> 2;
if (sourceIndex >= S) {
DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled sourceIndex ", sourceIndex);
DEBUG_BREAK_IF(true);
unhandledTokens.push_back(src);
return;
}
assignToken(tokensArray[sourceIndex], src);
}
template <typename PatchT, size_t NumInlineEl>
inline void addTok(StackVec<const PatchT *, NumInlineEl> &tokensVec, const SPatchItemHeader *src) {
tokensVec.push_back(reinterpret_cast<const PatchT *>(src));
}
inline void decodeKernelDataParameterToken(const SPatchDataParameterBuffer *token, KernelFromPatchtokens &out) {
auto &crossthread = out.tokens.crossThreadPayloadArgs;
auto sourceIndex = token->SourceOffset >> 2;
auto argNum = token->ArgumentNumber;
switch (token->Type) {
default:
DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled SPatchDataParameterBuffer ", token->Type);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
break;
case DATA_PARAMETER_KERNEL_ARGUMENT:
getKernelArg(out, argNum, ArgObjectType::None).byValMap.push_back(token);
break;
case DATA_PARAMETER_LOCAL_WORK_SIZE: {
if (sourceIndex >= 3) {
DBG_LOG(LogPatchTokens, "\n .Type", "Unhandled sourceIndex ", sourceIndex);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
return;
}
auto localWorkSizeArray = (crossthread.localWorkSize[sourceIndex] == nullptr)
? crossthread.localWorkSize
: crossthread.localWorkSize2;
localWorkSizeArray[sourceIndex] = token;
break;
}
case DATA_PARAMETER_GLOBAL_WORK_OFFSET:
assignTokenInArray(crossthread.globalWorkOffset, token, out.unhandledTokens);
break;
case DATA_PARAMETER_ENQUEUED_LOCAL_WORK_SIZE:
assignTokenInArray(crossthread.enqueuedLocalWorkSize, token, out.unhandledTokens);
break;
case DATA_PARAMETER_GLOBAL_WORK_SIZE:
assignTokenInArray(crossthread.globalWorkSize, token, out.unhandledTokens);
break;
case DATA_PARAMETER_NUM_WORK_GROUPS:
assignTokenInArray(crossthread.numWorkGroups, token, out.unhandledTokens);
break;
case DATA_PARAMETER_MAX_WORKGROUP_SIZE:
crossthread.maxWorkGroupSize = token;
break;
case DATA_PARAMETER_WORK_DIMENSIONS:
crossthread.workDimensions = token;
break;
case DATA_PARAMETER_SIMD_SIZE:
crossthread.simdSize = token;
break;
case DATA_PARAMETER_PRIVATE_MEMORY_STATELESS_SIZE:
crossthread.privateMemoryStatelessSize = token;
break;
case DATA_PARAMETER_LOCAL_MEMORY_STATELESS_WINDOW_SIZE:
crossthread.localMemoryStatelessWindowSize = token;
break;
case DATA_PARAMETER_LOCAL_MEMORY_STATELESS_WINDOW_START_ADDRESS:
crossthread.localMemoryStatelessWindowStartAddress = token;
break;
case DATA_PARAMETER_OBJECT_ID:
getKernelArg(out, argNum, ArgObjectType::None).objectId = token;
break;
case DATA_PARAMETER_SUM_OF_LOCAL_MEMORY_OBJECT_ARGUMENT_SIZES: {
auto &kernelArg = getKernelArg(out, argNum, ArgObjectType::Slm);
kernelArg.byValMap.push_back(token);
kernelArg.metadata.slm.token = token;
} break;
case DATA_PARAMETER_BUFFER_OFFSET:
getKernelArg(out, argNum, ArgObjectType::Buffer).metadata.buffer.bufferOffset = token;
break;
case DATA_PARAMETER_BUFFER_STATEFUL:
getKernelArg(out, argNum, ArgObjectType::Buffer).metadata.buffer.pureStateful = token;
break;
case DATA_PARAMETER_IMAGE_WIDTH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.width = token;
break;
case DATA_PARAMETER_IMAGE_HEIGHT:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.height = token;
break;
case DATA_PARAMETER_IMAGE_DEPTH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.depth = token;
break;
case DATA_PARAMETER_IMAGE_CHANNEL_DATA_TYPE:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.channelDataType = token;
break;
case DATA_PARAMETER_IMAGE_CHANNEL_ORDER:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.channelOrder = token;
break;
case DATA_PARAMETER_IMAGE_ARRAY_SIZE:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.arraySize = token;
break;
case DATA_PARAMETER_IMAGE_NUM_SAMPLES:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.numSamples = token;
break;
case DATA_PARAMETER_IMAGE_NUM_MIP_LEVELS:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.numMipLevels = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_BASEOFFSET:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatBaseOffset = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_WIDTH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatWidth = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_HEIGHT:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatHeight = token;
break;
case DATA_PARAMETER_FLAT_IMAGE_PITCH:
getKernelArg(out, argNum, ArgObjectType::Image).metadata.image.flatPitch = token;
break;
case DATA_PARAMETER_SAMPLER_COORDINATE_SNAP_WA_REQUIRED:
getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.coordinateSnapWaRequired = token;
break;
case DATA_PARAMETER_SAMPLER_ADDRESS_MODE:
getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.addressMode = token;
break;
case DATA_PARAMETER_SAMPLER_NORMALIZED_COORDS:
getKernelArg(out, argNum, ArgObjectType::Sampler).metadata.sampler.normalizedCoords = token;
break;
case DATA_PARAMETER_VME_MB_BLOCK_TYPE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.mbBlockType = token;
break;
case DATA_PARAMETER_VME_SUBPIXEL_MODE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.subpixelMode = token;
break;
case DATA_PARAMETER_VME_SAD_ADJUST_MODE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.sadAdjustMode = token;
break;
case DATA_PARAMETER_VME_SEARCH_PATH_TYPE:
getKernelArg(out, argNum, ArgObjectType::None, ArgObjectTypeSpecialized::Vme).metadataSpecialized.vme.searchPathType = token;
break;
case DATA_PARAMETER_PARENT_EVENT:
crossthread.parentEvent = token;
break;
case DATA_PARAMETER_PREFERRED_WORKGROUP_MULTIPLE:
crossthread.preferredWorkgroupMultiple = token;
break;
case DATA_PARAMETER_IMPL_ARG_BUFFER:
out.tokens.crossThreadPayloadArgs.implicitArgsBufferOffset = token;
break;
case DATA_PARAMETER_NUM_HARDWARE_THREADS:
case DATA_PARAMETER_PRINTF_SURFACE_SIZE:
case DATA_PARAMETER_IMAGE_SRGB_CHANNEL_ORDER:
case DATA_PARAMETER_STAGE_IN_GRID_ORIGIN:
case DATA_PARAMETER_STAGE_IN_GRID_SIZE:
case DATA_PARAMETER_LOCAL_ID:
case DATA_PARAMETER_EXECUTION_MASK:
case DATA_PARAMETER_VME_IMAGE_TYPE:
case DATA_PARAMETER_VME_MB_SKIP_BLOCK_TYPE:
case DATA_PARAMETER_CHILD_BLOCK_SIMD_SIZE:
// ignored intentionally
break;
}
}
inline bool decodeToken(const SPatchItemHeader *token, KernelFromPatchtokens &out) {
switch (token->Token) {
default: {
PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Unknown kernel-scope Patch Token: %d\n", token->Token);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
break;
}
case PATCH_TOKEN_INTERFACE_DESCRIPTOR_DATA:
PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Ignored kernel-scope Patch Token: %d\n", token->Token);
break;
case PATCH_TOKEN_SAMPLER_STATE_ARRAY:
assignToken(out.tokens.samplerStateArray, token);
break;
case PATCH_TOKEN_BINDING_TABLE_STATE:
assignToken(out.tokens.bindingTableState, token);
break;
case PATCH_TOKEN_ALLOCATE_LOCAL_SURFACE:
assignToken(out.tokens.allocateLocalSurface, token);
break;
case PATCH_TOKEN_MEDIA_VFE_STATE:
assignToken(out.tokens.mediaVfeState[0], token);
break;
case PATCH_TOKEN_MEDIA_VFE_STATE_SLOT1:
assignToken(out.tokens.mediaVfeState[1], token);
break;
case PATCH_TOKEN_MEDIA_INTERFACE_DESCRIPTOR_LOAD:
assignToken(out.tokens.mediaInterfaceDescriptorLoad, token);
break;
case PATCH_TOKEN_THREAD_PAYLOAD:
assignToken(out.tokens.threadPayload, token);
break;
case PATCH_TOKEN_EXECUTION_ENVIRONMENT:
assignToken(out.tokens.executionEnvironment, token);
break;
case PATCH_TOKEN_KERNEL_ATTRIBUTES_INFO:
assignToken(out.tokens.kernelAttributesInfo, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_PRIVATE_MEMORY:
assignToken(out.tokens.allocateStatelessPrivateSurface, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_CONSTANT_MEMORY_SURFACE_WITH_INITIALIZATION:
assignToken(out.tokens.allocateStatelessConstantMemorySurfaceWithInitialization, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_GLOBAL_MEMORY_SURFACE_WITH_INITIALIZATION:
assignToken(out.tokens.allocateStatelessGlobalMemorySurfaceWithInitialization, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_PRINTF_SURFACE:
assignToken(out.tokens.allocateStatelessPrintfSurface, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_EVENT_POOL_SURFACE:
assignToken(out.tokens.allocateStatelessEventPoolSurface, token);
break;
case PATCH_TOKEN_ALLOCATE_STATELESS_DEFAULT_DEVICE_QUEUE_SURFACE:
assignToken(out.tokens.allocateStatelessDefaultDeviceQueueSurface, token);
break;
case PATCH_TOKEN_STRING:
assignToken(out.tokens.strings, token);
break;
case PATCH_TOKEN_INLINE_VME_SAMPLER_INFO:
assignToken(out.tokens.inlineVmeSamplerInfo, token);
break;
case PATCH_TOKEN_GTPIN_FREE_GRF_INFO:
assignToken(out.tokens.gtpinFreeGrfInfo, token);
break;
case PATCH_TOKEN_GTPIN_INFO:
assignToken(out.tokens.gtpinInfo, token);
break;
case PATCH_TOKEN_STATE_SIP:
assignToken(out.tokens.stateSip, token);
break;
case PATCH_TOKEN_ALLOCATE_SIP_SURFACE:
assignToken(out.tokens.allocateSystemThreadSurface, token);
break;
case PATCH_TOKEN_PROGRAM_SYMBOL_TABLE:
assignToken(out.tokens.programSymbolTable, token);
break;
case PATCH_TOKEN_PROGRAM_RELOCATION_TABLE:
assignToken(out.tokens.programRelocationTable, token);
break;
case PATCH_TOKEN_KERNEL_ARGUMENT_INFO:
assignArgInfo(out, token);
break;
case PATCH_TOKEN_SAMPLER_KERNEL_ARGUMENT:
case PATCH_TOKEN_IMAGE_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_STATELESS_GLOBAL_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_STATELESS_CONSTANT_MEMORY_OBJECT_KERNEL_ARGUMENT:
case PATCH_TOKEN_STATELESS_DEVICE_QUEUE_KERNEL_ARGUMENT:
assignArg(out, token);
break;
case PATCH_TOKEN_DATA_PARAMETER_STREAM:
assignToken(out.tokens.dataParameterStream, token);
break;
case PATCH_TOKEN_DATA_PARAMETER_BUFFER: {
auto tokDataP = reinterpret_cast<const SPatchDataParameterBuffer *>(token);
decodeKernelDataParameterToken(tokDataP, out);
} break;
case PATCH_TOKEN_ALLOCATE_SYNC_BUFFER: {
assignToken(out.tokens.allocateSyncBuffer, token);
} break;
}
return out.decodeStatus != DecodeError::InvalidBinary;
}
inline bool decodeToken(const SPatchItemHeader *token, ProgramFromPatchtokens &out) {
auto &progTok = out.programScopeTokens;
switch (token->Token) {
default: {
PRINT_DEBUG_STRING(DebugManager.flags.PrintDebugMessages.get(), stderr, "Unknown program-scope Patch Token: %d\n", token->Token);
DEBUG_BREAK_IF(true);
out.unhandledTokens.push_back(token);
break;
}
case PATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
addTok(progTok.allocateConstantMemorySurface, token);
break;
case PATCH_TOKEN_ALLOCATE_GLOBAL_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
addTok(progTok.allocateGlobalMemorySurface, token);
break;
case PATCH_TOKEN_GLOBAL_POINTER_PROGRAM_BINARY_INFO:
addTok(progTok.globalPointer, token);
break;
case PATCH_TOKEN_CONSTANT_POINTER_PROGRAM_BINARY_INFO:
addTok(progTok.constantPointer, token);
break;
case PATCH_TOKEN_PROGRAM_SYMBOL_TABLE:
assignToken(progTok.symbolTable, token);
break;
case _PATCH_TOKEN_GLOBAL_HOST_ACCESS_TABLE:
assignToken(progTok.hostAccessTable, token);
break;
}
return true;
}
template <typename DecodeContext>
inline size_t getPatchTokenTotalSize(PatchTokensStreamReader stream, const SPatchItemHeader *token);
template <>
inline size_t getPatchTokenTotalSize<KernelFromPatchtokens>(PatchTokensStreamReader stream, const SPatchItemHeader *token) {
return token->Size;
}
template <>
inline size_t getPatchTokenTotalSize<ProgramFromPatchtokens>(PatchTokensStreamReader stream, const SPatchItemHeader *token) {
size_t tokSize = token->Size;
switch (token->Token) {
default:
return tokSize;
case PATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
return stream.enoughDataLeft<SPatchAllocateConstantMemorySurfaceProgramBinaryInfo>(token)
? tokSize + reinterpret_cast<const SPatchAllocateConstantMemorySurfaceProgramBinaryInfo *>(token)->InlineDataSize
: std::numeric_limits<size_t>::max();
case PATCH_TOKEN_ALLOCATE_GLOBAL_MEMORY_SURFACE_PROGRAM_BINARY_INFO:
return stream.enoughDataLeft<SPatchAllocateGlobalMemorySurfaceProgramBinaryInfo>(token)
? tokSize + reinterpret_cast<const SPatchAllocateGlobalMemorySurfaceProgramBinaryInfo *>(token)->InlineDataSize
: std::numeric_limits<size_t>::max();
}
}
template <typename OutT>
inline bool decodePatchList(PatchTokensStreamReader patchListStream, OutT &out) {
auto decodePos = patchListStream.data.begin();
auto decodeEnd = patchListStream.data.end();
bool decodeSuccess = true;
while ((ptrDiff(decodeEnd, decodePos) > sizeof(SPatchItemHeader)) && decodeSuccess) {
auto token = reinterpret_cast<const SPatchItemHeader *>(decodePos);
size_t tokenTotalSize = getPatchTokenTotalSize<OutT>(patchListStream, token);
decodeSuccess = patchListStream.enoughDataLeft(decodePos, tokenTotalSize);
decodeSuccess = decodeSuccess && (tokenTotalSize > 0U);
decodeSuccess = decodeSuccess && decodeToken(token, out);
decodePos = ptrOffset(decodePos, tokenTotalSize);
}
return decodeSuccess;
}
bool decodeKernelFromPatchtokensBlob(ArrayRef<const uint8_t> kernelBlob, KernelFromPatchtokens &out) {
PatchTokensStreamReader stream{kernelBlob};
auto decodePos = stream.data.begin();
out.decodeStatus = DecodeError::Undefined;
if (stream.notEnoughDataLeft<SKernelBinaryHeaderCommon>(decodePos)) {
out.decodeStatus = DecodeError::InvalidBinary;
return false;
}
out.header = reinterpret_cast<const SKernelBinaryHeaderCommon *>(decodePos);
auto kernelInfoBlobSize = sizeof(SKernelBinaryHeaderCommon) + out.header->KernelNameSize + out.header->KernelHeapSize + out.header->GeneralStateHeapSize + out.header->DynamicStateHeapSize + out.header->SurfaceStateHeapSize + out.header->PatchListSize;
if (stream.notEnoughDataLeft(decodePos, kernelInfoBlobSize)) {
out.decodeStatus = DecodeError::InvalidBinary;
return false;
}
out.blobs.kernelInfo = ArrayRef<const uint8_t>(stream.data.begin(), kernelInfoBlobSize);
decodePos = ptrOffset(decodePos, sizeof(SKernelBinaryHeaderCommon));
auto kernelName = reinterpret_cast<const char *>(decodePos);
out.name = ArrayRef<const char>(kernelName, out.header->KernelNameSize);
decodePos = ptrOffset(decodePos, out.name.size());
out.isa = ArrayRef<const uint8_t>(decodePos, out.header->KernelHeapSize);
decodePos = ptrOffset(decodePos, out.isa.size());
out.heaps.generalState = ArrayRef<const uint8_t>(decodePos, out.header->GeneralStateHeapSize);
decodePos = ptrOffset(decodePos, out.heaps.generalState.size());
out.heaps.dynamicState = ArrayRef<const uint8_t>(decodePos, out.header->DynamicStateHeapSize);
decodePos = ptrOffset(decodePos, out.heaps.dynamicState.size());
out.heaps.surfaceState = ArrayRef<const uint8_t>(decodePos, out.header->SurfaceStateHeapSize);
decodePos = ptrOffset(decodePos, out.heaps.surfaceState.size());
out.blobs.patchList = ArrayRef<const uint8_t>(decodePos, out.header->PatchListSize);
if (false == decodePatchList(out.blobs.patchList, out)) {
out.decodeStatus = DecodeError::InvalidBinary;
return false;
}
out.decodeStatus = DecodeError::Success;
return true;
}
inline bool decodeProgramHeader(ProgramFromPatchtokens &decodedProgram) {
auto decodePos = decodedProgram.blobs.programInfo.begin();
PatchTokensStreamReader stream{decodedProgram.blobs.programInfo};
if (stream.notEnoughDataLeft<SProgramBinaryHeader>(decodePos)) {
return false;
}
decodedProgram.header = reinterpret_cast<const SProgramBinaryHeader *>(decodePos);
if (decodedProgram.header->Magic != MAGIC_CL) {
return false;
}
decodePos = ptrOffset(decodePos, sizeof(SProgramBinaryHeader));
if (stream.notEnoughDataLeft(decodePos, decodedProgram.header->PatchListSize)) {
return false;
}
decodedProgram.blobs.patchList = ArrayRef<const uint8_t>(decodePos, decodedProgram.header->PatchListSize);
decodePos = ptrOffset(decodePos, decodedProgram.blobs.patchList.size());
decodedProgram.blobs.kernelsInfo = ArrayRef<const uint8_t>(decodePos, stream.getDataSizeLeft(decodePos));
return true;
}
inline bool decodeKernels(ProgramFromPatchtokens &decodedProgram) {
auto numKernels = decodedProgram.header->NumberOfKernels;
decodedProgram.kernels.reserve(decodedProgram.header->NumberOfKernels);
const uint8_t *decodePos = decodedProgram.blobs.kernelsInfo.begin();
bool decodeSuccess = true;
PatchTokensStreamReader stream{decodedProgram.blobs.kernelsInfo};
for (uint32_t i = 0; (i < numKernels) && decodeSuccess; i++) {
decodedProgram.kernels.resize(decodedProgram.kernels.size() + 1);
auto &currKernelInfo = *decodedProgram.kernels.rbegin();
auto kernelDataLeft = ArrayRef<const uint8_t>(decodePos, stream.getDataSizeLeft(decodePos));
decodeSuccess = decodeKernelFromPatchtokensBlob(kernelDataLeft, currKernelInfo);
decodePos = ptrOffset(decodePos, currKernelInfo.blobs.kernelInfo.size());
}
return decodeSuccess;
}
bool decodeProgramFromPatchtokensBlob(ArrayRef<const uint8_t> programBlob, ProgramFromPatchtokens &out) {
out.blobs.programInfo = programBlob;
bool decodeSuccess = decodeProgramHeader(out);
decodeSuccess = decodeSuccess && decodeKernels(out);
decodeSuccess = decodeSuccess && decodePatchList(out.blobs.patchList, out);
out.decodeStatus = decodeSuccess ? DecodeError::Success : DecodeError::InvalidBinary;
return decodeSuccess;
}
uint32_t calcKernelChecksum(const ArrayRef<const uint8_t> kernelBlob) {
UNRECOVERABLE_IF(kernelBlob.size() <= sizeof(SKernelBinaryHeaderCommon));
auto dataToHash = ArrayRef<const uint8_t>(ptrOffset(kernelBlob.begin(), sizeof(SKernelBinaryHeaderCommon)), kernelBlob.end());
uint64_t hashValue = Hash::hash(reinterpret_cast<const char *>(dataToHash.begin()), dataToHash.size());
uint32_t checksum = hashValue & 0xFFFFFFFF;
return checksum;
}
bool hasInvalidChecksum(const KernelFromPatchtokens &decodedKernel) {
uint32_t decodedChecksum = decodedKernel.header->CheckSum;
uint32_t calculatedChecksum = NEO::PatchTokenBinary::calcKernelChecksum(decodedKernel.blobs.kernelInfo);
return decodedChecksum != calculatedChecksum;
}
const KernelArgAttributesFromPatchtokens getInlineData(const SPatchKernelArgumentInfo *ptr) {
KernelArgAttributesFromPatchtokens ret = {};
UNRECOVERABLE_IF(ptr == nullptr);
auto decodePos = reinterpret_cast<const char *>(ptr + 1);
auto bounds = reinterpret_cast<const char *>(ptr) + ptr->Size;
ret.addressQualifier = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->AddressQualifierSize, bounds));
decodePos += ret.addressQualifier.size();
ret.accessQualifier = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->AccessQualifierSize, bounds));
decodePos += ret.accessQualifier.size();
ret.argName = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->ArgumentNameSize, bounds));
decodePos += ret.argName.size();
ret.typeName = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->TypeNameSize, bounds));
decodePos += ret.typeName.size();
ret.typeQualifiers = ArrayRef<const char>(decodePos, std::min(decodePos + ptr->TypeQualifierSize, bounds));
return ret;
}
const iOpenCL::SProgramBinaryHeader *decodeProgramHeader(const ArrayRef<const uint8_t> programBlob) {
ProgramFromPatchtokens program;
program.blobs.programInfo = programBlob;
if (false == decodeProgramHeader(program)) {
return nullptr;
}
return program.header;
}
} // namespace PatchTokenBinary
} // namespace NEO
| 42.120879 | 255 | 0.735232 | maleadt |
283383cbfb967feccae62aef0f0c14b3dd3a6c3b | 2,502 | cc | C++ | libcef/common/service_manifests/builtin_service_manifests.cc | aslistener/cef | d2bfa62d2df23cec85b6fea236aafb8ceb6f2423 | [
"BSD-3-Clause"
] | null | null | null | libcef/common/service_manifests/builtin_service_manifests.cc | aslistener/cef | d2bfa62d2df23cec85b6fea236aafb8ceb6f2423 | [
"BSD-3-Clause"
] | null | null | null | libcef/common/service_manifests/builtin_service_manifests.cc | aslistener/cef | d2bfa62d2df23cec85b6fea236aafb8ceb6f2423 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 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 "libcef/common/service_manifests/builtin_service_manifests.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/constants.mojom.h"
#include "chrome/services/printing/public/cpp/manifest.h"
#include "components/services/pdf_compositor/public/cpp/manifest.h" // nogncheck
#include "components/spellcheck/common/spellcheck.mojom.h"
#include "components/startup_metric_utils/common/startup_metric.mojom.h"
#include "extensions/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h"
#include "services/service_manager/public/cpp/manifest_builder.h"
#if defined(OS_MACOSX)
#include "components/spellcheck/common/spellcheck_panel.mojom.h"
#endif
namespace {
const service_manager::Manifest& GetCefManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.WithServiceName(chrome::mojom::kServiceName)
.WithDisplayName("CEF")
.WithOptions(
service_manager::ManifestOptionsBuilder()
.WithExecutionMode(
service_manager::Manifest::ExecutionMode::kInProcessBuiltin)
.WithInstanceSharingPolicy(
service_manager::Manifest::InstanceSharingPolicy::
kSharedAcrossGroups)
.CanConnectToInstancesWithAnyId(true)
.CanRegisterOtherServiceInstances(true)
.Build())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
#if defined(OS_MACOSX)
spellcheck::mojom::SpellCheckPanelHost,
#endif
spellcheck::mojom::SpellCheckHost,
startup_metric_utils::mojom::StartupMetricHost>())
.RequireCapability(chrome::mojom::kRendererServiceName, "browser")
.Build()
};
return *manifest;
}
} // namespace
const std::vector<service_manager::Manifest>& GetBuiltinServiceManifests() {
static base::NoDestructor<std::vector<service_manager::Manifest>> manifests{{
GetCefManifest(),
printing::GetPdfCompositorManifest(),
GetChromePrintingManifest(),
}};
return *manifests;
}
| 39.09375 | 81 | 0.698641 | aslistener |
283494667f8cc67ec616bfd5cbb8447c4cc7275e | 4,735 | cpp | C++ | src/ctrl/form/User.cpp | minyor/PocoBlog | 9556c5e70618dd64abd36913cc34c5c373b5673f | [
"BSD-2-Clause"
] | 5 | 2016-01-19T02:12:40.000Z | 2018-01-12T09:20:53.000Z | src/ctrl/form/User.cpp | minyor/PocoBlog | 9556c5e70618dd64abd36913cc34c5c373b5673f | [
"BSD-2-Clause"
] | null | null | null | src/ctrl/form/User.cpp | minyor/PocoBlog | 9556c5e70618dd64abd36913cc34c5c373b5673f | [
"BSD-2-Clause"
] | null | null | null |
#include "Poco/CountingStream.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
#include <ctrl/form/User.h>
using namespace ctrl::form;
static const std::string birthdayFormat = "%Y-%n-%e";
std::string birthdayFromDate(const Poco::DateTime &date)
{
return Poco::DateTimeFormatter::format(date, birthdayFormat);
}
Poco::DateTime birthdayToDate(const std::string &bday)
{
Poco::DateTime date;
int timeZoneDifferential;
if(Poco::DateTimeParser::tryParse(birthdayFormat, bday, date, timeZoneDifferential))
return date;
return Poco::DateTime(Poco::Timestamp(0));
}
User::User()
{
userTable.hideEmptyCollumns(true);
userGroups.prompt = "Set Group";
userGroups.add("Admin", "0");
userGroups.add("User", "2");
userGroups.add("Subscriber", "3");
addEvent(updateUser);
addEvent(removeUser);
addEvent(selectUser);
addEvent(updateGroup);
addEvent(paginate);
}
User::~User()
{
}
std::string User::format(const std::string &in)
{
return core::util::Html::format(in);
}
User::Mode User::mode()
{
if(users)
return MODE_USERS;
else
return MODE_SETTINGS;
}
std::string User::param()
{
std::string ret;
switch(mode())
{
case MODE_USERS: ret += "m=users&"; break;
case MODE_SETTINGS: ret += ""; break;
}
ret += "p=" + std::to_string(paginator.page()) + "&";
ret += "s=" + std::to_string(userTable.sort()) + "&";
return ret;
}
void User::onEnter()
{
val["status"] = "";
/// Fill settings
val["firstName"] = user().firstName();
val["lastName"] = user().lastName();
val["phoneNumber"] = user().phoneNumber();
val["country"] = user().country();
val["state"] = user().state();
val["birthday"] = birthdayFromDate(user().birthday());
}
void User::onLoad()
{
users = NULL;
/// Parameters
auto &mode = val["m"];
std::int64_t sort = 0; std::istringstream(val["s"]) >> sort;
std::int32_t page = INTMAX(32); std::istringstream(val["p"]) >> page;
userTable.sort(sort);
if(page != INTMAX(32)) paginator.page(page);
/// Mode
switch(0)
{ default:
/// Prepare User table
bool modeUsers = mode == "users" && user().group() == user().ADMIN;
if(modeUsers)
{
paginator.doPaging(ctrl().service().getUsersCount());
users = ctrl().service().getUsers(-1, userTable.sort(), paginator.limit(), paginator.offset());
userTable.set(users);
break;
}
userTable.clear();
}
/// Reset parameters
val["m"] = val["s"] = val["p"] = "";
}
void User::updateUser(std::istream *stream)
{
if(!user()) return;
/// Parameters
auto firstName = val["firstName"];
auto lastName = val["lastName"];
auto phoneNumber = val["phoneNumber"];
auto country = val["country"];
auto state = val["state"];
auto birthday = birthdayToDate(val["birthday"]);
val["status"] = "";
/// Validation
if(!birthday.timestamp().raw())
val["status"] = "*Incorrect birthday format!";
if(lastName.empty())
val["status"] = "*Please enter Last Name!";
if(firstName.empty())
val["status"] = "*Please enter First Name!";
if(!val["status"].empty()) return;
model::User user = this->user();
user.firstName(firstName);
user.lastName(lastName);
user.phoneNumber(phoneNumber);
user.country(country);
user.state(state);
user.birthday(birthday);
ctrl().service().updateUser(user);
ctrl().update();
val["status"] = "Updated successfully!";
}
void User::removeUser(std::istream *stream)
{
if(user().group() != user().ADMIN) return;
for(std::uint32_t i=0; i<users->size(); ++i) {
if(!userTable.rows()[i]->checked) continue;
ctrl().service().deleteUser(users()[i]->id());
}
userTable.clear();
}
void User::selectUser(std::istream *stream)
{
if(user().group() != user().ADMIN) return;
/// Parameters
core::DataID rowAll = 0; std::istringstream(val["a"]) >> rowAll;
core::DataID rowInd = core::DataID(-1); std::istringstream(val["r"]) >> rowInd;
val["a"] = val["r"] = "";
if(rowAll) {
userTable.toggleAll();
return;
}
userTable.toggle(rowInd);
}
void User::updateGroup(std::istream *stream)
{
if(user().group() != user().ADMIN) return;
/// Parameters
std::int32_t group = -1; std::istringstream(val["g"]) >> group;
val["g"] = "";
if(group < 0) return;
for(std::uint32_t i=0; i<users->size(); ++i) {
if(!userTable.rows()[i]->checked) continue;
users()[i]->group((model::User::Group)group);
ctrl().service().updateUser(*users()[i]);
}
userTable.clear();
}
void User::paginate(std::istream *stream)
{
/// Parameters
std::int32_t sort = INTMAX(32); std::istringstream(val["s"]) >> sort;
std::int32_t page = INTMAX(32); std::istringstream(val["p"]) >> page;
val["s"] = val["p"] = "";
if(sort != INTMAX(32)) userTable.sort(sort);
else if(page != INTMAX(32)) paginator.page(page);
else paginator.extend();
ctrl().redirect(path() + "?" + param());
} | 22.023256 | 98 | 0.646251 | minyor |
28359254006702bcfe15cb754c96fba7efaae5fb | 397 | hpp | C++ | include/mk2/math/sin.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | include/mk2/math/sin.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | include/mk2/math/sin.hpp | SachiSakurane/libmk2 | e8acf044ee5de160ad8a6f0a3c955beddea8d8c2 | [
"BSL-1.0"
] | null | null | null | //
// sin.hpp
//
//
// Created by Himatya on 2015/12/18.
// Copyright (c) 2015 Himatya. All rights reserved.
//
#pragma once
#include <type_traits>
#include <mk2/math/cos.hpp>
namespace mk2{
namespace math{
template<class T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
inline constexpr T sin(T x){
return cos(x - math::half_pi<T>);
}
}
}
| 17.26087 | 97 | 0.649874 | SachiSakurane |
2837ca8e718fbb7d3c28209ed54b6039e3f1c823 | 17,969 | hxx | C++ | Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/Segmentation/Conversion/include/otbLabelImageRegionMergingFilter.hxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 otbLabelImageRegionMergingFilter_hxx
#define otbLabelImageRegionMergingFilter_hxx
#include "otbLabelImageRegionMergingFilter.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkProgressReporter.h"
namespace otb
{
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::LabelImageRegionMergingFilter()
{
m_RangeBandwidth = 1.0;
m_NumberOfComponentsPerPixel = 0;
this->SetNumberOfRequiredInputs(2);
this->SetNumberOfRequiredOutputs(2);
this->SetNthOutput(0, OutputLabelImageType::New());
this->SetNthOutput(1, OutputClusteredImageType::New());
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::SetInputLabelImage(
const TInputLabelImage* labelImage)
{
// Process object is not const-correct so the const casting is required.
this->SetNthInput(0, const_cast<TInputLabelImage*>(labelImage));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::SetInputSpectralImage(
const TInputSpectralImage* spectralImage)
{
// Process object is not const-correct so the const casting is required.
this->SetNthInput(1, const_cast<TInputSpectralImage*>(spectralImage));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
TInputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetInputLabelImage()
{
return dynamic_cast<TInputLabelImage*>(itk::ProcessObject::GetInput(0));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
TInputSpectralImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetInputSpectralImage()
{
return dynamic_cast<TInputSpectralImage*>(itk::ProcessObject::GetInput(1));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::~LabelImageRegionMergingFilter()
{
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
TOutputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetLabelOutput()
{
if (this->GetNumberOfOutputs() < 1)
{
return nullptr;
}
return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
const TOutputLabelImage* LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetLabelOutput() const
{
if (this->GetNumberOfOutputs() < 1)
{
return 0;
}
return static_cast<OutputLabelImageType*>(this->itk::ProcessObject::GetOutput(0));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::OutputClusteredImageType*
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetClusteredOutput()
{
if (this->GetNumberOfOutputs() < 2)
{
return nullptr;
}
return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
const typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::OutputClusteredImageType*
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GetClusteredOutput() const
{
if (this->GetNumberOfOutputs() < 2)
{
return 0;
}
return static_cast<OutputClusteredImageType*>(this->itk::ProcessObject::GetOutput(1));
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
unsigned int numberOfComponentsPerPixel = this->GetInputSpectralImage()->GetNumberOfComponentsPerPixel();
if (this->GetClusteredOutput())
{
this->GetClusteredOutput()->SetNumberOfComponentsPerPixel(numberOfComponentsPerPixel);
}
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::EnlargeOutputRequestedRegion(
itk::DataObject* itkNotUsed(output))
{
// This filter requires all of the output images in the buffer.
for (unsigned int j = 0; j < this->GetNumberOfOutputs(); j++)
{
if (this->itk::ProcessObject::GetOutput(j))
{
this->itk::ProcessObject::GetOutput(j)->SetRequestedRegionToLargestPossibleRegion();
}
}
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::GenerateData()
{
typename InputSpectralImageType::Pointer spectralImage = this->GetInputSpectralImage();
typename InputLabelImageType::Pointer inputLabelImage = this->GetInputLabelImage();
typename OutputLabelImageType::Pointer outputLabelImage = this->GetLabelOutput();
typename OutputClusteredImageType::Pointer outputClusteredImage = this->GetClusteredOutput();
// Allocate output
outputLabelImage->SetBufferedRegion(outputLabelImage->GetRequestedRegion());
outputLabelImage->Allocate();
outputClusteredImage->SetBufferedRegion(outputClusteredImage->GetRequestedRegion());
outputClusteredImage->Allocate();
m_NumberOfComponentsPerPixel = spectralImage->GetNumberOfComponentsPerPixel();
// std::cout << "Copy input label image to output label image" << std::endl;
// Copy input label image to output label image
typename itk::ImageRegionConstIterator<InputLabelImageType> inputIt(inputLabelImage, outputLabelImage->GetRequestedRegion());
typename itk::ImageRegionIterator<OutputLabelImageType> outputIt(outputLabelImage, outputLabelImage->GetRequestedRegion());
inputIt.GoToBegin();
outputIt.GoToBegin();
while (!inputIt.IsAtEnd())
{
outputIt.Set(inputIt.Get());
++inputIt;
++outputIt;
}
RegionAdjacencyMapType regionAdjacencyMap = LabelImageToRegionAdjacencyMap(outputLabelImage);
unsigned int regionCount = regionAdjacencyMap.size() - 1;
// Initialize arrays for mode information
m_CanonicalLabels.clear();
m_CanonicalLabels.resize(regionCount + 1);
m_Modes.clear();
m_Modes.reserve(regionCount + 1);
for (unsigned int i = 0; i < regionCount + 1; ++i)
{
m_Modes.push_back(SpectralPixelType(m_NumberOfComponentsPerPixel));
}
m_PointCounts.clear();
m_PointCounts.resize(regionCount + 1); // = std::vector<unsigned int>(regionCount+1);
// Associate each label to a spectral value, a canonical label and a point count
typename itk::ImageRegionConstIterator<InputLabelImageType> inputItWithIndex(inputLabelImage, outputLabelImage->GetRequestedRegion());
inputItWithIndex.GoToBegin();
while (!inputItWithIndex.IsAtEnd())
{
LabelType label = inputItWithIndex.Get();
// if label has not been initialized yet ..
if (m_PointCounts[label] == 0)
{
// m_CanonicalLabels[label] = label;
m_Modes[label] = spectralImage->GetPixel(inputItWithIndex.GetIndex());
}
m_PointCounts[label]++;
++inputItWithIndex;
}
// Region Merging
bool finishedMerging = false;
unsigned int mergeIterations = 0;
// std::cout << "Start merging" << std::endl;
// Iterate until no more merge to do
// while(!finishedMerging)
// {
while (!finishedMerging)
{
// Initialize Canonical Labels
for (LabelType curLabel = 1; curLabel <= regionCount; ++curLabel)
m_CanonicalLabels[curLabel] = curLabel;
// Iterate over all regions
for (LabelType curLabel = 1; curLabel <= regionCount; ++curLabel)
{
if (m_PointCounts[curLabel] == 0)
{
// do not process empty regions
continue;
}
// std::cout<<" point in label "<<curLabel<<" "<<m_PointCounts[curLabel]<<std::endl;
const SpectralPixelType& curSpectral = m_Modes[curLabel];
// Iterate over all adjacent regions and check for merge
typename AdjacentLabelsContainerType::const_iterator adjIt = regionAdjacencyMap[curLabel].begin();
while (adjIt != regionAdjacencyMap[curLabel].end())
{
LabelType adjLabel = *adjIt;
assert(adjLabel <= regionCount);
const SpectralPixelType& adjSpectral = m_Modes[adjLabel];
// Check condition to merge regions
bool isSimilar = true;
RealType norm2 = 0;
for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp)
{
RealType e;
e = (curSpectral[comp] - adjSpectral[comp]) / m_RangeBandwidth;
norm2 += e * e;
}
isSimilar = norm2 < 0.25;
if (isSimilar)
{
// Find canonical label for current region
LabelType curCanLabel = curLabel; // m_CanonicalLabels[curLabel];
while (m_CanonicalLabels[curCanLabel] != curCanLabel)
{
curCanLabel = m_CanonicalLabels[curCanLabel];
}
// Find canonical label for adjacent region
LabelType adjCanLabel = adjLabel; // m_CanonicalLabels[curLabel];
while (m_CanonicalLabels[adjCanLabel] != adjCanLabel)
{
adjCanLabel = m_CanonicalLabels[adjCanLabel];
}
// Assign same canonical label to both regions
if (curCanLabel < adjCanLabel)
{
m_CanonicalLabels[adjCanLabel] = curCanLabel;
}
else
{
m_CanonicalLabels[m_CanonicalLabels[curCanLabel]] = adjCanLabel;
m_CanonicalLabels[curCanLabel] = adjCanLabel;
}
}
++adjIt;
} // end of loop over adjacent labels
} // end of loop over labels
// std::cout << "Simplify the table of canonical labels" << std::endl;
/* Simplify the table of canonical labels */
for (LabelType i = 1; i < regionCount + 1; ++i)
{
LabelType can = i;
while (m_CanonicalLabels[can] != can)
{
can = m_CanonicalLabels[can];
}
m_CanonicalLabels[i] = can;
}
// std::cout << "merge regions with same canonical label" << std::endl;
/* Merge regions with same canonical label */
/* - update modes and point counts */
std::vector<SpectralPixelType> newModes;
newModes.reserve(regionCount + 1); //(regionCount+1, SpectralPixelType(m_NumberOfComponentsPerPixel));
for (unsigned int i = 0; i < regionCount + 1; ++i)
{
newModes.push_back(SpectralPixelType(m_NumberOfComponentsPerPixel));
}
std::vector<unsigned int> newPointCounts(regionCount + 1);
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
newModes[i].Fill(0);
newPointCounts[i] = 0;
}
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
LabelType canLabel = m_CanonicalLabels[i];
unsigned int nPoints = m_PointCounts[i];
for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp)
{
newModes[canLabel][comp] += nPoints * m_Modes[i][comp];
}
newPointCounts[canLabel] += nPoints;
}
// std::cout << "re-labeling" << std::endl;
/* re-labeling */
std::vector<LabelType> newLabels(regionCount + 1);
std::vector<bool> newLabelSet(regionCount + 1);
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
newLabelSet[i] = false;
}
LabelType label = 0;
for (unsigned int i = 1; i < regionCount + 1; ++i)
{
LabelType canLabel = m_CanonicalLabels[i];
if (newLabelSet[canLabel] == false)
{
newLabelSet[canLabel] = true;
label++;
newLabels[canLabel] = label;
unsigned int nPoints = newPointCounts[canLabel];
for (unsigned int comp = 0; comp < m_NumberOfComponentsPerPixel; ++comp)
{
m_Modes[label][comp] = newModes[canLabel][comp] / nPoints;
}
m_PointCounts[label] = newPointCounts[canLabel];
}
}
unsigned int oldRegionCount = regionCount;
regionCount = label;
/* reassign labels in label image */
outputIt.GoToBegin();
while (!outputIt.IsAtEnd())
{
LabelType l = outputIt.Get();
LabelType canLabel;
assert(m_CanonicalLabels[l] <= oldRegionCount);
canLabel = newLabels[m_CanonicalLabels[l]];
outputIt.Set(canLabel);
++outputIt;
}
finishedMerging = oldRegionCount == regionCount || mergeIterations >= 10 || regionCount == 1;
// only one iteration for now
if (!finishedMerging)
{
/* Update adjacency table */
regionAdjacencyMap = LabelImageToRegionAdjacencyMap(outputLabelImage);
}
mergeIterations++;
} // end of main iteration loop
// std::cout << "merge iterations: " << mergeIterations << std::endl;
// std::cout << "number of label objects: " << regionCount << std::endl;
// Generate clustered output
itk::ImageRegionIterator<OutputClusteredImageType> outputClusteredIt(outputClusteredImage, outputClusteredImage->GetRequestedRegion());
outputClusteredIt.GoToBegin();
outputIt.GoToBegin();
while (!outputClusteredIt.IsAtEnd())
{
LabelType label = outputIt.Get();
const SpectralPixelType& p = m_Modes[label];
outputClusteredIt.Set(p);
++outputClusteredIt;
++outputIt;
}
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
void LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::PrintSelf(std::ostream& os,
itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Range bandwidth: " << m_RangeBandwidth << std::endl;
}
template <class TInputLabelImage, class TInputSpectralImage, class TOutputLabelImage, class TOutputClusteredImage>
typename LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::RegionAdjacencyMapType
LabelImageRegionMergingFilter<TInputLabelImage, TInputSpectralImage, TOutputLabelImage, TOutputClusteredImage>::LabelImageToRegionAdjacencyMap(
typename OutputLabelImageType::Pointer labelImage)
{
// declare the output map
RegionAdjacencyMapType ram;
// Find the maximum label value
itk::ImageRegionConstIterator<OutputLabelImageType> it(labelImage, labelImage->GetRequestedRegion());
it.GoToBegin();
LabelType maxLabel = 0;
while (!it.IsAtEnd())
{
LabelType label = it.Get();
maxLabel = std::max(maxLabel, label);
++it;
}
// Set the size of the adjacency map
ram.resize(maxLabel + 1);
// set the image region without bottom and right borders so that bottom and
// right neighbors always exist
RegionType regionWithoutBottomRightBorders = labelImage->GetRequestedRegion();
SizeType size = regionWithoutBottomRightBorders.GetSize();
for (unsigned int d = 0; d < ImageDimension; ++d)
size[d] -= 1;
regionWithoutBottomRightBorders.SetSize(size);
itk::ImageRegionConstIteratorWithIndex<OutputLabelImageType> inputIt(labelImage, regionWithoutBottomRightBorders);
inputIt.GoToBegin();
while (!inputIt.IsAtEnd())
{
const InputIndexType& index = inputIt.GetIndex();
LabelType label = inputIt.Get();
// check neighbors
for (unsigned int d = 0; d < ImageDimension; ++d)
{
InputIndexType neighborIndex = index;
neighborIndex[d]++;
LabelType neighborLabel = labelImage->GetPixel(neighborIndex);
// add adjacency if different labels
if (neighborLabel != label)
{
ram[label].insert(neighborLabel);
ram[neighborLabel].insert(label);
}
}
++inputIt;
}
return ram;
}
} // end namespace otb
#endif
| 38.069915 | 159 | 0.718181 | heralex |
28387227adf8dd2d42870d9474af4f96725dc1d4 | 2,120 | cpp | C++ | solved-codeforces/the_redback/contest/749/c/23155481.cpp | Maruf-Tuhin/Online_Judge | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | 1 | 2019-03-31T05:47:30.000Z | 2019-03-31T05:47:30.000Z | solved-codeforces/the_redback/contest/749/c/23155481.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | solved-codeforces/the_redback/contest/749/c/23155481.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | /**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define mem(a,b) memset(a,b,sizeof(a))
#define sf(a) scanf("%lld",&a)
#define ssf(a) scanf("%s",&a)
#define sf2(a,b) scanf("%lld %lld",&a,&b)
#define sf3(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 100010
#ifdef redback
#define bug printf("line=%d\n",__LINE__);
#define debug(args...) {cout<<":: "; dbg,args; cerr<<endl;}
struct debugger{template<typename T>debugger& operator ,(const T& v){cerr<<v<<" ";return *this;}}dbg;
#else
#define bug
#define debug(args...)
#endif //debugging macros
struct node
{
int w;
node(){}
node(int b) {w = b;}
bool operator < ( const node& p ) const { return w > p.w; }
};
priority_queue<node>R,D;
char a[200010];
ll b[200010];
int main()
{
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin);
#endif
ll t=1,tc;
//sf(tc);
ll l,m,n;
while(~sf(n)) {
ll i,j,k;
R=priority_queue<node>();
D=priority_queue<node>();
mem(b,-1);
ssf(a);
for(i=0;i<n;i++)
{
if(a[i]=='D') D.push(node(i));
if(a[i]=='R') R.push(node(i));
}
while(!R.empty() && !D.empty())
{
node rr=R.top();
node dd=D.top();
R.pop();
D.pop();
if(rr.w<dd.w)
{
R.push(node(rr.w+n));
}
else
D.push(node(dd.w+n));
}
if(!R.empty()) puts("R");
else puts("D");
}
return 0;
}
| 22.083333 | 102 | 0.49434 | Maruf-Tuhin |
283a71c9583a82d67aa9059ac89118881af9ce63 | 47,507 | cpp | C++ | src/conformance/conformance_test/test_LayerComposition.cpp | JoeLudwig/OpenXR-CTS | 144c94e8982fe76986019abc9bf2b016740536df | [
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | 1 | 2020-12-11T03:28:32.000Z | 2020-12-11T03:28:32.000Z | src/conformance/conformance_test/test_LayerComposition.cpp | JoeLudwig/OpenXR-CTS | 144c94e8982fe76986019abc9bf2b016740536df | [
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | null | null | null | src/conformance/conformance_test/test_LayerComposition.cpp | JoeLudwig/OpenXR-CTS | 144c94e8982fe76986019abc9bf2b016740536df | [
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | null | null | null | // Copyright (c) 2019-2021, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <array>
#include <thread>
#include <numeric>
#include "utils.h"
#include "report.h"
#include "conformance_utils.h"
#include "conformance_framework.h"
#include "composition_utils.h"
#include <catch2/catch.hpp>
#include <openxr/openxr.h>
#include <xr_linear.h>
using namespace Conformance;
namespace
{
const XrVector3f Up{0, 1, 0};
enum class LayerMode
{
Scene,
Help,
Complete
};
namespace Colors
{
constexpr XrColor4f Red = {1, 0, 0, 1};
constexpr XrColor4f Green = {0, 1, 0, 1};
constexpr XrColor4f Blue = {0, 0, 1, 1};
constexpr XrColor4f Purple = {1, 0, 1, 1};
constexpr XrColor4f Yellow = {1, 1, 0, 1};
constexpr XrColor4f Orange = {1, 0.65f, 0, 1};
constexpr XrColor4f White = {1, 1, 1, 1};
constexpr XrColor4f Transparent = {0, 0, 0, 0};
// Avoid including red which is a "failure color".
constexpr std::array<XrColor4f, 4> UniqueColors{Green, Blue, Yellow, Orange};
} // namespace Colors
namespace Math
{
// Do a linear conversion of a number from one range to another range.
// e.g. 5 in range [0-8] projected into range (-.6 to 0.6) is 0.15.
float LinearMap(int i, int sourceMin, int sourceMax, float targetMin, float targetMax)
{
float percent = (i - sourceMin) / (float)sourceMax;
return targetMin + ((targetMax - targetMin) * percent);
}
constexpr float DegToRad(float degree)
{
return degree / 180 * MATH_PI;
}
} // namespace Math
namespace Quat
{
constexpr XrQuaternionf Identity{0, 0, 0, 1};
XrQuaternionf FromAxisAngle(XrVector3f axis, float radians)
{
XrQuaternionf rowQuat;
XrQuaternionf_CreateFromAxisAngle(&rowQuat, &axis, radians);
return rowQuat;
}
} // namespace Quat
// Appends composition layers for interacting with interactive composition tests.
struct InteractiveLayerManager
{
InteractiveLayerManager(CompositionHelper& compositionHelper, const char* exampleImage, const char* descriptionText)
: m_compositionHelper(compositionHelper)
{
// Set up the input system for toggling between modes and passing/failing.
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy(actionSetInfo.actionSetName, "interaction_test");
strcpy(actionSetInfo.localizedActionSetName, "Interaction Test");
XRC_CHECK_THROW_XRCMD(xrCreateActionSet(compositionHelper.GetInstance(), &actionSetInfo, &m_actionSet));
compositionHelper.GetInteractionManager().AddActionSet(m_actionSet);
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_BOOLEAN_INPUT;
strcpy(actionInfo.actionName, "interaction_manager_select");
strcpy(actionInfo.localizedActionName, "Interaction Manager Select");
XRC_CHECK_THROW_XRCMD(xrCreateAction(m_actionSet, &actionInfo, &m_select));
strcpy(actionInfo.actionName, "interaction_manager_menu");
strcpy(actionInfo.localizedActionName, "Interaction Manager Menu");
XRC_CHECK_THROW_XRCMD(xrCreateAction(m_actionSet, &actionInfo, &m_menu));
XrPath simpleInteractionProfile =
StringToPath(compositionHelper.GetInstance(), "/interaction_profiles/khr/simple_controller");
compositionHelper.GetInteractionManager().AddActionBindings(
simpleInteractionProfile,
{{
{m_select, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/select/click")},
{m_select, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/select/click")},
{m_menu, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/menu/click")},
{m_menu, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/menu/click")},
}});
}
m_viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, XrPosef{{0, 0, 0, 1}, {0, 0, 0}});
// Load example screenshot if available and set up the quad layer for it.
{
XrSwapchain exampleSwapchain;
if (exampleImage) {
exampleSwapchain = compositionHelper.CreateStaticSwapchainImage(RGBAImage::Load(exampleImage), true /* sRGB */);
}
else {
RGBAImage image(256, 256);
image.PutText(XrRect2Di{{0, image.height / 2}, {image.width, image.height}}, "Example Not Available", 64, {1, 0, 0, 1});
exampleSwapchain = compositionHelper.CreateStaticSwapchainImage(image);
}
// Create a quad to the right of the help text.
m_exampleQuad = compositionHelper.CreateQuadLayer(exampleSwapchain, m_viewSpace, 1.25f, {Quat::Identity, {0.5f, 0, -1.5f}});
XrQuaternionf_CreateFromAxisAngle(&m_exampleQuad->pose.orientation, &Up, -15 * MATH_PI / 180);
}
// Set up the quad layer for showing the help text to the left of the example image.
m_descriptionQuad = compositionHelper.CreateQuadLayer(
m_compositionHelper.CreateStaticSwapchainImage(CreateTextImage(768, 768, descriptionText, 48)), m_viewSpace, 0.75f,
{Quat::Identity, {-0.5f, 0, -1.5f}});
m_descriptionQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
XrQuaternionf_CreateFromAxisAngle(&m_descriptionQuad->pose.orientation, &Up, 15 * MATH_PI / 180);
constexpr uint32_t actionsWidth = 768, actionsHeight = 128;
m_sceneActionsSwapchain = compositionHelper.CreateStaticSwapchainImage(
CreateTextImage(actionsWidth, actionsHeight, "Press Select to PASS. Press Menu for description", 48));
m_helpActionsSwapchain =
compositionHelper.CreateStaticSwapchainImage(CreateTextImage(actionsWidth, actionsHeight, "Press select to FAIL", 48));
// Set up the quad layer and swapchain for showing what actions the user can take in the Scene/Help mode.
m_actionsQuad =
compositionHelper.CreateQuadLayer(m_sceneActionsSwapchain, m_viewSpace, 0.75f, {Quat::Identity, {0, -0.4f, -1}});
m_actionsQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
}
template <typename T>
void AddLayer(T* layer)
{
m_sceneLayers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(layer));
}
bool EndFrame(const XrFrameState& frameState, std::vector<XrCompositionLayerBaseHeader*> layers = {})
{
bool keepRunning = AppendLayers(layers);
keepRunning &= m_compositionHelper.PollEvents();
m_compositionHelper.EndFrame(frameState.predictedDisplayTime, std::move(layers));
return keepRunning;
}
private:
bool AppendLayers(std::vector<XrCompositionLayerBaseHeader*>& layers)
{
// Add layer(s) based on the interaction mode.
switch (GetLayerMode()) {
case LayerMode::Scene:
m_actionsQuad->subImage = m_compositionHelper.MakeDefaultSubImage(m_sceneActionsSwapchain);
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_actionsQuad));
for (auto& sceneLayer : m_sceneLayers) {
layers.push_back(sceneLayer);
}
break;
case LayerMode::Help:
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_descriptionQuad));
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_exampleQuad));
m_actionsQuad->subImage = m_compositionHelper.MakeDefaultSubImage(m_helpActionsSwapchain);
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_actionsQuad));
break;
case LayerMode::Complete:
return false; // Interactive test is complete.
}
return true;
}
LayerMode GetLayerMode()
{
m_compositionHelper.GetInteractionManager().SyncActions(XR_NULL_PATH);
XrActionStateBoolean actionState{XR_TYPE_ACTION_STATE_BOOLEAN};
XrActionStateGetInfo getInfo{XR_TYPE_ACTION_STATE_GET_INFO};
LayerMode mode = LayerMode::Scene;
getInfo.action = m_menu;
XRC_CHECK_THROW_XRCMD(xrGetActionStateBoolean(m_compositionHelper.GetSession(), &getInfo, &actionState));
if (actionState.currentState) {
mode = LayerMode::Help;
}
getInfo.action = m_select;
XRC_CHECK_THROW_XRCMD(xrGetActionStateBoolean(m_compositionHelper.GetSession(), &getInfo, &actionState));
if (actionState.changedSinceLastSync && actionState.currentState) {
if (mode != LayerMode::Scene) {
// Select on the non-Scene modes (help description/preview image) means FAIL and move to the next.
FAIL("User failed the interactive test");
}
// Select on scene means PASS and move to next
mode = LayerMode::Complete;
}
return mode;
}
CompositionHelper& m_compositionHelper;
XrActionSet m_actionSet;
XrAction m_select;
XrAction m_menu;
XrSpace m_viewSpace;
XrSwapchain m_sceneActionsSwapchain;
XrSwapchain m_helpActionsSwapchain;
XrCompositionLayerQuad* m_actionsQuad;
XrCompositionLayerQuad* m_descriptionQuad;
XrCompositionLayerQuad* m_exampleQuad;
std::vector<XrCompositionLayerBaseHeader*> m_sceneLayers;
};
} // namespace
namespace Conformance
{
// Purpose: Verify behavior of quad visibility and occlusion with the expectation that:
// 1. Quads render with painters algo.
// 2. Quads which are facing away are not visible.
TEST_CASE("Quad Occlusion", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Occlusion");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "quad_occlusion.png",
"This test includes a blue and green quad at Z=-2 with opposite rotations on Y axis forming X. The green quad should be"
" fully visible due to painter's algorithm. A red quad is facing away and should not be visible.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
const XrSwapchain redSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Red);
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
// Each quad is rotated on Y axis by 45 degrees to form an X.
// Green is added second so it should draw over the blue quad.
const XrQuaternionf blueRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(-45));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(blueSwapchain, viewSpace, 1.0f, XrPosef{blueRot, {0, 0, -2}}));
const XrQuaternionf greenRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(45));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{greenRot, {0, 0, -2}}));
// Red quad is rotated away from the viewer and should not be visible.
const XrQuaternionf redRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(180));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(redSwapchain, viewSpace, 1.0f, XrPosef{redRot, {0, 0, -1}}));
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Verify order of transforms by exercising the two ways poses can be specified:
// 1. A pose offset when creating the space
// 2. A pose offset when adding the layer
// If the poses are applied in an incorrect order, the quads will not rendener in the correct place or orientation.
TEST_CASE("Quad Poses", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Poses");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "quad_poses.png",
"Render pairs of quads using similar poses to validate order of operations. The blue/green quads apply a"
" rotation around the Z axis on an XrSpace and then translate the quad out on the Z axis through the quad"
" layer's pose. The purple/yellow quads apply the same translation on the XrSpace and the rotation on the"
" quad layer's pose.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
const XrSwapchain orangeSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Orange);
const XrSwapchain yellowSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Yellow);
constexpr int RotationCount = 2;
constexpr float MaxRotationDegrees = 30;
// For each rotation there are a pair of quads.
static_assert(RotationCount * 2 <= XR_MIN_COMPOSITION_LAYERS_SUPPORTED, "Too many layers");
for (int i = 0; i < RotationCount; i++) {
const float radians =
Math::LinearMap(i, 0, RotationCount - 1, Math::DegToRad(-MaxRotationDegrees), Math::DegToRad(MaxRotationDegrees));
const XrPosef pose1 = XrPosef{Quat::FromAxisAngle({0, 1, 0}, radians), {0, 0, 0}};
const XrPosef pose2 = XrPosef{Quat::Identity, {0, 0, -1}};
const XrSpace viewSpacePose1 = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, pose1);
const XrSpace viewSpacePose2 = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, pose2);
auto quad1 = compositionHelper.CreateQuadLayer((i % 2) == 0 ? blueSwapchain : greenSwapchain, viewSpacePose1, 0.25f, pose2);
interactiveLayerManager.AddLayer(quad1);
auto quad2 = compositionHelper.CreateQuadLayer((i % 2) == 0 ? orangeSwapchain : yellowSwapchain, viewSpacePose2, 0.25f, pose1);
interactiveLayerManager.AddLayer(quad2);
}
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Validates alpha blending (both premultiplied and unpremultiplied).
TEST_CASE("Source Alpha Blending", "[composition][interactive]")
{
CompositionHelper compositionHelper("Source Alpha Blending");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "source_alpha_blending.png",
"All three squares should have an identical blue-green gradient.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
constexpr float QuadZ = -3; // How far away quads are placed.
// Creates image with correctly combined green and blue gradient (this is the the source of truth).
{
Conformance::RGBAImage blueGradientOverGreen(256, 256);
for (int y = 0; y < 256; y++) {
const float t = y / 255.0f;
const XrColor4f dst = Colors::Green;
const XrColor4f src{0, 0, t, t};
const XrColor4f blended{dst.r * (1 - src.a) + src.r, dst.g * (1 - src.a) + src.g, dst.b * (1 - src.a) + src.b, 1};
blueGradientOverGreen.DrawRect(0, y, blueGradientOverGreen.width, 1, blended);
}
const XrSwapchain answerSwapchain = compositionHelper.CreateStaticSwapchainImage(blueGradientOverGreen);
interactiveLayerManager.AddLayer(
compositionHelper.CreateQuadLayer(answerSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {0, 0, QuadZ}}));
}
auto createGradientTest = [&](bool premultiplied, float x, float y) {
// A solid green quad layer will be composited under a blue gradient.
{
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
interactiveLayerManager.AddLayer(
compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {x, y, QuadZ}}));
}
// Create gradient of blue lines from 0.0 to 1.0.
{
Conformance::RGBAImage blueGradient(256, 256);
for (int row = 0; row < blueGradient.height; row++) {
XrColor4f color{0, 0, 1, row / (float)blueGradient.height};
if (premultiplied) {
color = XrColor4f{color.r * color.a, color.g * color.a, color.b * color.a, color.a};
}
blueGradient.DrawRect(0, row, blueGradient.width, 1, color);
}
const XrSwapchain gradientSwapchain = compositionHelper.CreateStaticSwapchainImage(blueGradient);
XrCompositionLayerQuad* gradientQuad =
compositionHelper.CreateQuadLayer(gradientSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {x, y, QuadZ}});
gradientQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
if (!premultiplied) {
gradientQuad->layerFlags |= XR_COMPOSITION_LAYER_UNPREMULTIPLIED_ALPHA_BIT;
}
interactiveLayerManager.AddLayer(gradientQuad);
}
};
createGradientTest(true, -1.02f, 0); // Test premultiplied (left of center "answer")
createGradientTest(false, 1.02f, 0); // Test unpremultiplied (right of center "answer")
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Validate eye visibility flags.
TEST_CASE("Eye Visibility", "[composition][interactive]")
{
CompositionHelper compositionHelper("Eye Visibility");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "eye_visibility.png",
"A green quad is shown in the left eye and a blue quad is shown in the right eye.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
XrCompositionLayerQuad* quad1 =
compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {-1, 0, -2}});
quad1->eyeVisibility = XR_EYE_VISIBILITY_LEFT;
interactiveLayerManager.AddLayer(quad1);
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
XrCompositionLayerQuad* quad2 =
compositionHelper.CreateQuadLayer(blueSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {1, 0, -2}});
quad2->eyeVisibility = XR_EYE_VISIBILITY_RIGHT;
interactiveLayerManager.AddLayer(quad2);
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
TEST_CASE("Subimage Tests", "[composition][interactive]")
{
CompositionHelper compositionHelper("Subimage Tests");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "subimage.png",
"Creates a 4x2 grid of quad layers testing subImage array index and imageRect. Red should not be visible except minor bleed in.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, XrPosef{Quat::Identity, {0, 0, -1}});
constexpr float QuadZ = -4; // How far away quads are placed.
constexpr int ImageColCount = 4;
constexpr int ImageArrayCount = 2;
constexpr int ImageWidth = 1024;
constexpr int ImageHeight = ImageWidth / ImageColCount;
constexpr int RedZoneBorderSize = 16;
constexpr int CellWidth = (ImageWidth / ImageColCount);
constexpr int CellHeight = CellWidth;
// Create an array swapchain
auto swapchainCreateInfo =
compositionHelper.DefaultColorSwapchainCreateInfo(ImageWidth, ImageHeight, XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT);
swapchainCreateInfo.format = GetGlobalData().graphicsPlugin->GetRGBA8Format(false /* sRGB */);
swapchainCreateInfo.arraySize = ImageArrayCount;
const XrSwapchain swapchain = compositionHelper.CreateSwapchain(swapchainCreateInfo);
// Render a grid of numbers (1,2,3,4) in slice 0 and (5,6,7,8) in slice 1 of the swapchain
// Create a quad layer referencing each number cell.
compositionHelper.AcquireWaitReleaseImage(swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
int number = 1;
for (int arraySlice = 0; arraySlice < ImageArrayCount; arraySlice++) {
Conformance::RGBAImage numberGridImage(ImageWidth, ImageHeight);
// All unused areas are red (should not be seen).
numberGridImage.DrawRect(0, 0, numberGridImage.width, numberGridImage.height, Colors::Red);
for (int x = 0; x < ImageColCount; x++) {
const auto& color = Colors::UniqueColors[number % Colors::UniqueColors.size()];
const XrRect2Di numberRect{{x * CellWidth + RedZoneBorderSize, RedZoneBorderSize},
{CellWidth - RedZoneBorderSize * 2, CellHeight - RedZoneBorderSize * 2}};
numberGridImage.DrawRect(numberRect.offset.x, numberRect.offset.y, numberRect.extent.width, numberRect.extent.height,
Colors::Transparent);
numberGridImage.PutText(numberRect, std::to_string(number).c_str(), CellHeight, color);
numberGridImage.DrawRectBorder(numberRect.offset.x, numberRect.offset.y, numberRect.extent.width,
numberRect.extent.height, 4, color);
number++;
const float quadX = Math::LinearMap(x, 0, ImageColCount - 1, -2.0f, 2.0f);
const float quadY = Math::LinearMap(arraySlice, 0, ImageArrayCount - 1, 0.75f, -0.75f);
XrCompositionLayerQuad* const quad =
compositionHelper.CreateQuadLayer(swapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {quadX, quadY, QuadZ}});
quad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
quad->subImage.imageArrayIndex = arraySlice;
quad->subImage.imageRect = numberRect;
quad->size.height = 1.0f; // Height needs to be corrected since the imageRect is customized.
interactiveLayerManager.AddLayer(quad);
}
GetGlobalData().graphicsPlugin->CopyRGBAImage(swapchainImage, format, arraySlice, numberGridImage);
}
});
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
TEST_CASE("Projection Array Swapchain", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Array Swapchain");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "projection_array.png",
"Uses a single texture array for a projection layer (each view is a different slice and each slice has a unique color).");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
// Because a single swapchain is being used for all views (each view is a slice of the texture array), the maximum dimensions must be used
// since the dimensions of all slices are the same.
const auto maxWidth = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectWidth < r.recommendedImageRectWidth;
})
->recommendedImageRectWidth;
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create swapchain with array type.
auto swapchainCreateInfo = compositionHelper.DefaultColorSwapchainCreateInfo(maxWidth, maxHeight);
swapchainCreateInfo.arraySize = (uint32_t)viewProperties.size() * 3;
const XrSwapchain swapchain = compositionHelper.CreateSwapchain(swapchainCreateInfo);
// Set up the projection layer
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
// Use non-contiguous array indices to ferret out any assumptions that implementations are making
// about array indices. In particular 0 != left and 1 != right, but this should test for other
// assumptions too.
uint32_t arrayIndex = swapchainCreateInfo.arraySize - (j * 2 + 1);
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = compositionHelper.MakeDefaultSubImage(swapchain, arrayIndex);
}
const std::vector<Cube> cubes = {Cube::Make({-1, 0, -2}), Cube::Make({1, 0, -2}), Cube::Make({0, -1, -2}), Cube::Make({0, 1, -2})};
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each slice of the array swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
for (uint32_t slice = 0; slice < (uint32_t)views.size(); slice++) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage,
projLayer->views[slice].subImage.imageArrayIndex, format);
const_cast<XrFovf&>(projLayer->views[slice].fov) = views[slice].fov;
const_cast<XrPosef&>(projLayer->views[slice].pose) = views[slice].pose;
GetGlobalData().graphicsPlugin->RenderView(projLayer->views[slice], swapchainImage, format, cubes);
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Wide Swapchain", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Wide Swapchain");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_wide.png",
"Uses a single wide texture for a projection layer.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
const auto totalWidth =
std::accumulate(viewProperties.begin(), viewProperties.end(), 0,
[](uint32_t l, const XrViewConfigurationView& r) { return l + r.recommendedImageRectWidth; });
// Because a single swapchain is being used for all views the maximum height must be used.
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create wide swapchain.
const XrSwapchain swapchain =
compositionHelper.CreateSwapchain(compositionHelper.DefaultColorSwapchainCreateInfo(totalWidth, maxHeight));
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
int x = 0;
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
XrSwapchainSubImage subImage = compositionHelper.MakeDefaultSubImage(swapchain, 0);
subImage.imageRect.offset = {x, 0};
subImage.imageRect.extent = {(int32_t)viewProperties[j].recommendedImageRectWidth,
(int32_t)viewProperties[j].recommendedImageRectHeight};
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = subImage;
x += subImage.imageRect.extent.width; // Each view is to the left of the previous view.
}
const std::vector<Cube> cubes = {Cube::Make({-1, 0, -2}), Cube::Make({1, 0, -2}), Cube::Make({0, -1, -2}), Cube::Make({0, 1, -2})};
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each view port of the wide swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage, 0, format);
for (size_t view = 0; view < views.size(); view++) {
const_cast<XrFovf&>(projLayer->views[view].fov) = views[view].fov;
const_cast<XrPosef&>(projLayer->views[view].pose) = views[view].pose;
GetGlobalData().graphicsPlugin->RenderView(projLayer->views[view], swapchainImage, format, cubes);
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Separate Swapchains", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Separate Swapchains");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_separate.png",
"Uses separate textures for each projection layer view.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
SimpleProjectionLayerHelper simpleProjectionLayerHelper(compositionHelper);
auto updateLayers = [&](const XrFrameState& frameState) {
simpleProjectionLayerHelper.UpdateProjectionLayer(frameState);
std::vector<XrCompositionLayerBaseHeader*> layers{simpleProjectionLayerHelper.GetProjectionLayer()};
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Quad Hands", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Hands");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "quad_hands.png",
"10x10cm Quads labeled \'L\' and \'R\' should appear 10cm along the grip "
"positive Z in front of the center of 10cm cubes rendered at the controller "
"grip poses. "
"The quads should face you and be upright when the controllers are in "
"a thumbs-up pointing-into-screen pose. "
"Check that the quads are properly backface-culled, "
"that \'R\' is always rendered atop \'L\', "
"and both are atop the cubes when visible.");
const std::vector<XrPath> subactionPaths{StringToPath(compositionHelper.GetInstance(), "/user/hand/left"),
StringToPath(compositionHelper.GetInstance(), "/user/hand/right")};
XrActionSet actionSet;
XrAction gripPoseAction;
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy(actionSetInfo.actionSetName, "quad_hands");
strcpy(actionSetInfo.localizedActionSetName, "Quad Hands");
XRC_CHECK_THROW_XRCMD(xrCreateActionSet(compositionHelper.GetInstance(), &actionSetInfo, &actionSet));
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_POSE_INPUT;
strcpy(actionInfo.actionName, "grip_pose");
strcpy(actionInfo.localizedActionName, "Grip pose");
actionInfo.subactionPaths = subactionPaths.data();
actionInfo.countSubactionPaths = (uint32_t)subactionPaths.size();
XRC_CHECK_THROW_XRCMD(xrCreateAction(actionSet, &actionInfo, &gripPoseAction));
}
compositionHelper.GetInteractionManager().AddActionSet(actionSet);
XrPath simpleInteractionProfile = StringToPath(compositionHelper.GetInstance(), "/interaction_profiles/khr/simple_controller");
compositionHelper.GetInteractionManager().AddActionBindings(
simpleInteractionProfile,
{{
{gripPoseAction, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/grip/pose")},
{gripPoseAction, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/grip/pose")},
}});
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
SimpleProjectionLayerHelper simpleProjectionLayerHelper(compositionHelper);
// Spaces attached to the hand (subaction).
std::vector<XrSpace> gripSpaces;
// Create XrSpaces for each grip pose
for (XrPath subactionPath : subactionPaths) {
XrSpace space;
XrActionSpaceCreateInfo spaceCreateInfo{XR_TYPE_ACTION_SPACE_CREATE_INFO};
spaceCreateInfo.action = gripPoseAction;
spaceCreateInfo.subactionPath = subactionPath;
spaceCreateInfo.poseInActionSpace = {{0, 0, 0, 1}, {0, 0, 0}};
XRC_CHECK_THROW_XRCMD(xrCreateActionSpace(compositionHelper.GetSession(), &spaceCreateInfo, &space));
gripSpaces.push_back(std::move(space));
}
// Create 10x10cm L and R quads
XrCompositionLayerQuad* const leftQuadLayer =
compositionHelper.CreateQuadLayer(compositionHelper.CreateStaticSwapchainImage(CreateTextImage(64, 64, "L", 48)), gripSpaces[0],
0.1f, {Quat::Identity, {0, 0, 0.1f}});
XrCompositionLayerQuad* const rightQuadLayer =
compositionHelper.CreateQuadLayer(compositionHelper.CreateStaticSwapchainImage(CreateTextImage(64, 64, "R", 48)), gripSpaces[1],
0.1f, {Quat::Identity, {0, 0, 0.1f}});
interactiveLayerManager.AddLayer(leftQuadLayer);
interactiveLayerManager.AddLayer(rightQuadLayer);
const XrVector3f cubeSize{0.1f, 0.1f, 0.1f};
auto updateLayers = [&](const XrFrameState& frameState) {
std::vector<Cube> cubes;
for (const auto& space : gripSpaces) {
XrSpaceLocation location{XR_TYPE_SPACE_LOCATION};
if (XR_SUCCEEDED(
xrLocateSpace(space, simpleProjectionLayerHelper.GetLocalSpace(), frameState.predictedDisplayTime, &location))) {
if ((location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) &&
(location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)) {
cubes.emplace_back(Cube{location.pose, cubeSize});
}
}
}
simpleProjectionLayerHelper.UpdateProjectionLayer(frameState, cubes);
std::vector<XrCompositionLayerBaseHeader*> layers{simpleProjectionLayerHelper.GetProjectionLayer()};
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Mutable Field-of-View", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Mutable Field-of-View");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_mutable.png",
"Uses mutable field-of-views for each projection layer view.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
if (!compositionHelper.GetViewConfigurationProperties().fovMutable) {
return;
}
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
const auto totalWidth =
std::accumulate(viewProperties.begin(), viewProperties.end(), 0,
[](uint32_t l, const XrViewConfigurationView& r) { return l + r.recommendedImageRectWidth; });
// Because a single swapchain is being used for all views the maximum height must be used.
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create wide swapchain.
const XrSwapchain swapchain =
compositionHelper.CreateSwapchain(compositionHelper.DefaultColorSwapchainCreateInfo(totalWidth, maxHeight));
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
int x = 0;
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
XrSwapchainSubImage subImage = compositionHelper.MakeDefaultSubImage(swapchain, 0);
subImage.imageRect.offset = {x, 0};
subImage.imageRect.extent = {(int32_t)viewProperties[j].recommendedImageRectWidth,
(int32_t)viewProperties[j].recommendedImageRectHeight};
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = subImage;
x += subImage.imageRect.extent.width; // Each view is to the left of the previous view.
}
const std::vector<Cube> cubes = {Cube::Make({-.2f, -.2f, -2}), Cube::Make({.2f, -.2f, -2}), Cube::Make({0, .1f, -2})};
const XrVector3f Forward{0, 0, 1};
XrQuaternionf roll180;
XrQuaternionf_CreateFromAxisAngle(&roll180, &Forward, MATH_PI);
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each view port of the wide swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage, 0, format);
for (size_t view = 0; view < views.size(); view++) {
// Copy over the provided FOV and pose but use 40% of the suggested FOV.
const_cast<XrFovf&>(projLayer->views[view].fov) = views[view].fov;
const_cast<XrPosef&>(projLayer->views[view].pose) = views[view].pose;
const_cast<float&>(projLayer->views[view].fov.angleUp) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleDown) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleLeft) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleRight) *= 0.4f;
// Render using a 180 degree roll on Z which effectively creates a flip on both the X and Y axis.
XrCompositionLayerProjectionView rolled = projLayer->views[view];
XrQuaternionf_Multiply(&rolled.pose.orientation, &roll180, &views[view].pose.orientation);
GetGlobalData().graphicsPlugin->RenderView(rolled, swapchainImage, format, cubes);
// After rendering, report a flipped FOV on X and Y without the 180 degree roll, which has the same
// effect. This switcheroo is necessary since rendering with flipped FOV will result in an inverted
// winding causing normally hidden triangles to be visible and visible triangles to be hidden.
const_cast<float&>(projLayer->views[view].fov.angleUp) = -projLayer->views[view].fov.angleUp;
const_cast<float&>(projLayer->views[view].fov.angleDown) = -projLayer->views[view].fov.angleDown;
const_cast<float&>(projLayer->views[view].fov.angleLeft) = -projLayer->views[view].fov.angleLeft;
const_cast<float&>(projLayer->views[view].fov.angleRight) = -projLayer->views[view].fov.angleRight;
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
} // namespace Conformance
| 56.088548 | 146 | 0.636832 | JoeLudwig |
283a80924b2defc573734b3ff42e7e7384c9cffb | 9,532 | cpp | C++ | modules/base/rendering/renderablecartesianaxes.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/base/rendering/renderablecartesianaxes.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/base/rendering/renderablecartesianaxes.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* 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 <modules/base/rendering/renderablecartesianaxes.h>
#include <modules/base/basemodule.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>
#include <openspace/documentation/verifier.h>
#include <ghoul/glm.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/opengl/programobject.h>
namespace {
constexpr const char* ProgramName = "CartesianAxesProgram";
const int NVertexIndices = 6;
constexpr openspace::properties::Property::PropertyInfo XColorInfo = {
"XColor",
"X Color",
"This value determines the color of the x axis."
};
constexpr openspace::properties::Property::PropertyInfo YColorInfo = {
"YColor",
"Y Color",
"This value determines the color of the y axis."
};
constexpr openspace::properties::Property::PropertyInfo ZColorInfo = {
"ZColor",
"Z Color",
"This value determines the color of the z axis."
};
} // namespace
namespace openspace {
documentation::Documentation RenderableCartesianAxes::Documentation() {
using namespace documentation;
return {
"CartesianAxesProgram",
"base_renderable_cartesianaxes",
{
{
XColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
XColorInfo.description
},
{
YColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
YColorInfo.description
},
{
ZColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
ZColorInfo.description
}
}
};
}
RenderableCartesianAxes::RenderableCartesianAxes(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _program(nullptr)
, _xColor(
XColorInfo,
glm::vec4(0.f, 0.f, 0.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
, _yColor(
YColorInfo,
glm::vec4(0.f, 1.f, 0.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
, _zColor(
ZColorInfo,
glm::vec4(0.f, 0.f, 1.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableCartesianAxes"
);
if (dictionary.hasKey(XColorInfo.identifier)) {
_xColor = dictionary.value<glm::vec4>(XColorInfo.identifier);
}
_xColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_xColor);
if (dictionary.hasKey(XColorInfo.identifier)) {
_yColor = dictionary.value<glm::vec4>(YColorInfo.identifier);
}
_yColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_yColor);
if (dictionary.hasKey(ZColorInfo.identifier)) {
_zColor = dictionary.value<glm::vec4>(ZColorInfo.identifier);
}
_zColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_zColor);
}
bool RenderableCartesianAxes::isReady() const {
bool ready = true;
ready &= (_program != nullptr);
return ready;
}
void RenderableCartesianAxes::initializeGL() {
_program = BaseModule::ProgramObjectManager.request(
ProgramName,
[]() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
return global::renderEngine.buildRenderProgram(
ProgramName,
absPath("${MODULE_BASE}/shaders/axes_vs.glsl"),
absPath("${MODULE_BASE}/shaders/axes_fs.glsl")
);
}
);
glGenVertexArrays(1, &_vaoId);
glGenBuffers(1, &_vBufferId);
glGenBuffers(1, &_iBufferId);
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
std::vector<Vertex> vertices({
Vertex{0.f, 0.f, 0.f},
Vertex{1.f, 0.f, 0.f},
Vertex{0.f, 1.f, 0.f},
Vertex{0.f, 0.f, 1.f}
});
std::vector<int> indices = {
0, 1,
0, 2,
0, 3
};
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBufferData(
GL_ARRAY_BUFFER,
vertices.size() * sizeof(Vertex),
vertices.data(),
GL_STATIC_DRAW
);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
indices.size() * sizeof(int),
indices.data(),
GL_STATIC_DRAW
);
}
void RenderableCartesianAxes::deinitializeGL() {
glDeleteVertexArrays(1, &_vaoId);
_vaoId = 0;
glDeleteBuffers(1, &_vBufferId);
_vBufferId = 0;
glDeleteBuffers(1, &_iBufferId);
_iBufferId = 0;
BaseModule::ProgramObjectManager.release(
ProgramName,
[](ghoul::opengl::ProgramObject* p) {
global::renderEngine.removeRenderProgram(p);
}
);
_program = nullptr;
}
void RenderableCartesianAxes::render(const RenderData& data, RendererTasks&){
_program->activate();
const glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
glm::dmat4(data.modelTransform.rotation) *
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale));
const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() *
modelTransform;
_program->setUniform("modelViewTransform", glm::mat4(modelViewTransform));
_program->setUniform("projectionTransform", data.camera.projectionMatrix());
_program->setUniform("xColor", _xColor);
_program->setUniform("yColor", _yColor);
_program->setUniform("zColor", _zColor);
// Saves current state:
GLboolean isBlendEnabled = glIsEnabledi(GL_BLEND, 0);
GLboolean isLineSmoothEnabled = glIsEnabled(GL_LINE_SMOOTH);
GLfloat currentLineWidth;
glGetFloatv(GL_LINE_WIDTH, ¤tLineWidth);
GLenum blendEquationRGB, blendEquationAlpha, blendDestAlpha,
blendDestRGB, blendSrcAlpha, blendSrcRGB;
glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha);
glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB);
glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha);
glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB);
// Changes GL state:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnablei(GL_BLEND, 0);
glEnable(GL_LINE_SMOOTH);
glBindVertexArray(_vaoId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glDrawElements(GL_LINES, NVertexIndices, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
_program->deactivate();
// Restores GL State
glLineWidth(currentLineWidth);
glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha);
glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha);
if (!isBlendEnabled) {
glDisablei(GL_BLEND, 0);
}
if (!isLineSmoothEnabled) {
glDisable(GL_LINE_SMOOTH);
}
}
} // namespace openspace
| 34.536232 | 90 | 0.593999 | nbartzokas |
283afec9ab13eba507692de14055621e68232683 | 3,020 | hpp | C++ | QuantExt/qle/instruments/makecds.hpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | 1 | 2021-03-30T17:24:17.000Z | 2021-03-30T17:24:17.000Z | QuantExt/qle/instruments/makecds.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | null | null | null | QuantExt/qle/instruments/makecds.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | 1 | 2022-02-07T02:04:10.000Z | 2022-02-07T02:04:10.000Z | /*
Copyright (C) 2017 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*
Copyright (C) 2014 Jose Aparicio
Copyright (C) 2014 Peter Caspers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<[email protected]>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file makecds.hpp
\brief Helper class to instantiate standard market cds.
\ingroup instruments
*/
#ifndef quantext_makecds_hpp
#define quantext_makecds_hpp
#include <boost/optional.hpp>
#include <qle/instruments/creditdefaultswap.hpp>
namespace QuantExt {
using namespace QuantLib;
//! helper class
/*! This class provides a more comfortable way
to instantiate standard cds.
\bug support last period dc
\ingroup instruments
*/
class MakeCreditDefaultSwap {
public:
MakeCreditDefaultSwap(const Period& tenor, const Real couponRate);
MakeCreditDefaultSwap(const Date& termDate, const Real couponRate);
operator CreditDefaultSwap() const;
operator boost::shared_ptr<CreditDefaultSwap>() const;
MakeCreditDefaultSwap& withUpfrontRate(Real);
MakeCreditDefaultSwap& withSide(Protection::Side);
MakeCreditDefaultSwap& withNominal(Real);
MakeCreditDefaultSwap& withCouponTenor(Period);
MakeCreditDefaultSwap& withDayCounter(DayCounter&);
// MakeCreditDefaultSwap& withLastPeriodDayCounter(DayCounter&);
MakeCreditDefaultSwap& withPricingEngine(const boost::shared_ptr<PricingEngine>&);
private:
Protection::Side side_;
Real nominal_;
boost::optional<Period> tenor_;
boost::optional<Date> termDate_;
Period couponTenor_;
Real couponRate_;
Real upfrontRate_;
DayCounter dayCounter_;
// DayCounter lastPeriodDayCounter_;
boost::shared_ptr<PricingEngine> engine_;
};
} // namespace QuantExt
#endif
| 33.555556 | 86 | 0.76755 | PiotrSiejda |
2841971e0bff9a57c920a04ac25df9ef4a1e9c4d | 5,126 | cpp | C++ | GEvent.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | GEvent.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | GEvent.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | #include "GEvent.h"
GEvent::GEvent() {
}
GEvent::~GEvent() {
//Do nothing
}
void GEvent::OnEvent(SDL_Event* event) {
switch(event->type) {
case SDL_KEYDOWN: {
OnKeyDown(event->key.keysym.sym,event->key.keysym.mod);
break;
}
case SDL_KEYUP: {
OnKeyUp(event->key.keysym.sym,event->key.keysym.mod);
break;
}
case SDL_MOUSEMOTION: {
OnMouseMove(event->motion.x,event->motion.y,event->motion.xrel,event->motion.yrel,(event->motion.state&SDL_BUTTON(SDL_BUTTON_LEFT))!=0,(event->motion.state&SDL_BUTTON(SDL_BUTTON_RIGHT))!=0,(event->motion.state&SDL_BUTTON(SDL_BUTTON_MIDDLE))!=0);
break;
}
case SDL_MOUSEBUTTONDOWN: {
switch(event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonDown(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonDown(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonDown(event->button.x,event->button.y);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP: {
switch(event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonUp(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonUp(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonUp(event->button.x,event->button.y);
break;
}
}
break;
}
case SDL_JOYAXISMOTION: {
OnJoyAxis(event->jaxis.which,event->jaxis.axis,event->jaxis.value);
break;
}
case SDL_JOYBALLMOTION: {
OnJoyBall(event->jball.which,event->jball.ball,event->jball.xrel,event->jball.yrel);
break;
}
case SDL_JOYHATMOTION: {
OnJoyHat(event->jhat.which,event->jhat.hat,event->jhat.value);
break;
}
case SDL_JOYBUTTONDOWN: {
OnJoyButtonDown(event->jbutton.which,event->jbutton.button);
break;
}
case SDL_JOYBUTTONUP: {
OnJoyButtonUp(event->jbutton.which,event->jbutton.button);
break;
}
case SDL_QUIT: {
OnExit();
break;
}
case SDL_SYSWMEVENT: {
//Ignore
break;
}
// case SDL_VIDEORESIZE: {
// OnResize(event->resize.w,event->resize.h);
// break;
// }
// case SDL_VIDEOEXPOSE: {
// OnExpose();
// break;
// }
default: {
OnUser(event->user.type,event->user.code,event->user.data1,event->user.data2);
break;
}
}
}
void GEvent::OnInputFocus() {
//Pure virtual, do nothing
}
void GEvent::OnInputBlur() {
//Pure virtual, do nothing
}
void GEvent::OnKeyDown(SDL_Keycode &sym, Uint16 &mod) {
//Pure virtual, do nothing
}
void GEvent::OnKeyUp(SDL_Keycode &sym, Uint16 &mod) {
//Pure virtual, do nothing
}
void GEvent::OnMouseFocus() {
//Pure virtual, do nothing
}
void GEvent::OnMouseBlur() {
//Pure virtual, do nothing
}
void GEvent::OnMouseMove(int mX, int mY, int relX, int relY, bool Left,bool Right,bool Middle) {
//Pure virtual, do nothing
}
void GEvent::OnMouseWheel(bool Up, bool Down) {
//Pure virtual, do nothing
}
void GEvent::OnLButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnLButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnRButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnRButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnMButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnMButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnJoyAxis(Uint8 which,Uint8 axis,Sint16 value) {
//Pure virtual, do nothing
}
void GEvent::OnJoyButtonDown(Uint8 which,Uint8 button) {
//Pure virtual, do nothing
}
void GEvent::OnJoyButtonUp(Uint8 which,Uint8 button) {
//Pure virtual, do nothing
}
void GEvent::OnJoyHat(Uint8 which,Uint8 hat,Uint8 value) {
//Pure virtual, do nothing
}
void GEvent::OnJoyBall(Uint8 which,Uint8 ball,Sint16 xrel,Sint16 yrel) {
//Pure virtual, do nothing
}
void GEvent::OnMinimize() {
//Pure virtual, do nothing
}
void GEvent::OnRestore() {
//Pure virtual, do nothing
}
void GEvent::OnResize(int w,int h) {
//Pure virtual, do nothing
}
void GEvent::OnExpose() {
//Pure virtual, do nothing
}
void GEvent::OnExit() {
//Pure virtual, do nothing
}
void GEvent::OnUser(Uint8 type, int code, void* data1, void* data2) {
//Pure virtual, do nothing
}
| 23.953271 | 257 | 0.558525 | abishek-sampath |
2842442eca960d8309112fd16fcafecfcf29aab9 | 21,655 | cc | C++ | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/EmilyWindow.cc,v 1.6 1992/09/08 16:40:43 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: EmilyWindow.cc,v $
* Revision 1.6 1992/09/08 16:40:43 lewis
* Renamed NULL -> Nil.
*
* Revision 1.5 1992/09/01 17:25:44 sterling
* Lots of Foundation changes.
*
* Revision 1.13 1992/02/19 17:31:05 sterling
* enabled setclasinfo when in surtomize mode
*
* Revision 1.11 1992/02/18 01:11:37 lewis
* Use new version support.
*
* Revision 1.9 1992/02/04 22:55:26 lewis
* Use GetShell().GetExtent (), not just GetExtent () for wiundows.
* (maybe should be referencing mainview??).
*
* Revision 1.6 1992/01/31 18:21:58 sterling
* Bootstrapped
*
*/
#include <fstream.h>
#include "Debug.hh"
#include "StreamUtils.hh"
#include "Version.hh"
#include "CommandNumbers.hh"
#include "Dialog.hh"
#include "NumberText.hh"
#include "MenuOwner.hh"
#include "Shell.hh"
#include "CheckBox.hh"
#include "DeskTop.hh"
#include "Language.hh"
#include "EmilyApplication.hh"
#include "ItemPallet.hh"
#include "EmilyWindow.hh"
#include "MainGroupItem.hh"
#include "ClassInfo.hh"
#if qMacUI
CommandNumber EmilyWindow::sCurrentGUI = eMacUI;
#elif qMotifUI
CommandNumber EmilyWindow::sCurrentGUI = eMotifUI;
#elif qWindowsGUI
CommandNumber EmilyWindow::sCurrentGUI = eWindowsGUI;
#endif
CommandNumber EmilyWindow::sCurrentLanguage = eEnglish;
Boolean EmilyWindow::sCustomizeOnly = False;
/*
********************************************************************************
*********************************** EmilyWindow ********************************
********************************************************************************
*/
EmilyWindow::EmilyWindow (EmilyDocument& document):
Window (),
Saveable (1),
fDocument (document),
fClassName ("foo"),
fBaseClass ("View"),
fHeaderPrepend (kEmptyString),
fHeaderAppend (kEmptyString),
fSourcePrepend (kEmptyString),
fSourceAppend (kEmptyString),
fDataPrepend (kEmptyString),
fStringCount (1),
fGrid (EmilyApplication::Get ().GetGrid ()),
fGridVisible (EmilyApplication::Get ().GetGridVisible ()),
#if qMacUI
fGUI (eMacUI),
#elif qMotifUI
fGUI (eMotifUI),
#elif qWindowsGUI
fGUI (eWindowsGUI),
#endif
fLanguage (eEnglish)
{
fMainGroup = new MainGroupItem (*this);
SetMainViewAndTargets (fMainGroup, fMainGroup, fMainGroup);
SetWindowController (&fDocument);
fMainGroup->ResetCustomizeOnly ();
}
EmilyWindow::~EmilyWindow ()
{
SetMainViewAndTargets (Nil, Nil, Nil);
}
EmilyDocument& EmilyWindow::GetDocument ()
{
return (fDocument);
}
void EmilyWindow::PrintPage (PageNumber /*pageNumber*/, class Printer& printer)
{
RequireNotNil (GetMainView ());
printer.DrawView (*GetMainView (), kZeroPoint);
}
void EmilyWindow::CalcPages (PageNumber& userStart, PageNumber& userEnd, const Rect& /*pageRect*/)
{
userStart = 1;
userEnd = 1;
}
PageNumber EmilyWindow::CalcAllPages (const Rect& /*pageRect*/)
{
return (1);
}
void EmilyWindow::DoSetupMenus ()
{
Window::DoSetupMenus ();
SetOn (GetGUI (), True);
SetOn (GetLanguage (), True);
SetOn (eCustomizeOnly, sCustomizeOnly);
EnableCommand (eSetClassInfo);
EnableCommand (eCustomizeOnly);
EnableCommand (eArrow);
EnableCommand (eThumb);
if (ItemPallet::GetEditMode () and (not sCustomizeOnly)) {
for (CommandNumber cmd = eFirstBuildItem; cmd <= eLastBuildItem; cmd++) {
EnableCommand (cmd, ItemPallet::ShouldEnable (cmd));
}
}
#if !qUseCustomMenu
if (ItemPallet::GetSelectedItem () != Nil) {
ItemPallet::GetSelectedItem ()->SetOn (Toggle::kOn, Panel::eNoUpdate);
}
#endif
}
class SetClassInfoCommand : public Command {
public:
SetClassInfoCommand (EmilyWindow& window, class ClassInfo& info);
~SetClassInfoCommand ();
override void DoIt ();
override void UnDoIt ();
private:
EmilyWindow& fWindow;
String fNewClassName;
String fOldClassName;
String fNewBaseClassName;
String fOldBaseClassName;
Point fNewSize;
Point fOldSize;
String fNewHelp;
String fOldHelp;
const Font* fNewFont;
const Font* fOldFont;
Boolean fOldAutoSize;
Boolean fNewAutoSize;
};
SetClassInfoCommand::SetClassInfoCommand (EmilyWindow& window, class ClassInfo& info) :
Command (eSetClassInfo, kUndoable),
fWindow (window),
fNewClassName (info.GetClassNameField ().GetText ()),
fOldClassName (window.fClassName),
fNewBaseClassName (info.GetBaseClassNameField ().GetText ()),
fOldBaseClassName (window.fBaseClass),
fNewSize (Point (info.GetSizeVField ().GetValue (), info.GetSizeHField ().GetValue ())),
fOldSize (window.GetMainGroup ().GetScrollSize ()),
fNewHelp (info.GetHelpField ().GetText ()),
fOldHelp (window.GetMainGroup ().GetHelp ()),
fNewFont (info.fFont),
fOldFont (window.GetMainGroup ().GetFont ()),
fOldAutoSize (window.GetMainGroup ().GetAutoSize ()),
fNewAutoSize (info.GetAutoSizeField ().GetOn ())
{
if (fNewFont != Nil) {
fNewFont = new Font (*fNewFont);
}
if (fOldFont != Nil) {
fOldFont = new Font (*fOldFont);
}
}
SetClassInfoCommand::~SetClassInfoCommand ()
{
delete fNewFont;
delete fOldFont;
}
void SetClassInfoCommand::DoIt ()
{
fWindow.fClassName = fNewClassName;
fWindow.fBaseClass = fNewBaseClassName;
fWindow.GetMainGroup ().SetHelp (fNewHelp);
if (fNewSize != fOldSize) {
if (not fNewAutoSize) {
fWindow.GetMainGroup ().SetScrollSize (fNewSize);
}
}
if (fNewFont != fOldFont) {
fWindow.GetMainGroup ().SetFont (fNewFont);
fWindow.GetMainGroup ().Refresh ();
}
fWindow.GetMainGroup ().SetAutoSize (fNewAutoSize);
fWindow.GetMainGroup ().ApplyCurrentParams ();
Command::DoIt ();
}
void SetClassInfoCommand::UnDoIt ()
{
fWindow.fClassName = fOldClassName;
fWindow.fBaseClass = fOldBaseClassName;
fWindow.GetMainGroup ().SetHelp (fOldHelp);
fWindow.GetMainGroup ().SetAutoSize (fOldAutoSize);
if ((fNewSize != fOldSize) or (fNewAutoSize != fOldAutoSize)) {
if (not fOldAutoSize) {
fWindow.GetMainGroup ().SetScrollSize (fOldSize);
}
}
if (fNewFont != fOldFont) {
fWindow.GetMainGroup ().SetFont (fOldFont);
fWindow.GetMainGroup ().Refresh ();
}
fWindow.GetMainGroup ().ApplyCurrentParams ();
Command::UnDoIt ();
}
Boolean EmilyWindow::DoCommand (const CommandSelection& selection)
{
switch (selection.GetCommandNumber ()) {
case eSetClassInfo:
{
ClassInfo info = ClassInfo (GetMainGroup ());
info.GetClassNameField ().SetText (fClassName);
info.GetBaseClassNameField ().SetText (fBaseClass);
info.GetSizeVField ().SetValue (GetMainGroup ().GetScrollSize ().GetV ());
info.GetSizeHField ().SetValue (GetMainGroup ().GetScrollSize ().GetH ());
info.GetHelpField ().SetText (GetMainGroup ().GetHelp ());
info.GetAutoSizeField ().SetOn (GetMainGroup ().GetAutoSize ());
Dialog d = Dialog (&info, &info, AbstractPushButton::kOKLabel, AbstractPushButton::kCancelLabel);
d.SetDefaultButton (d.GetOKButton ());
if (d.Pose ()) {
PostCommand (new SetClassInfoCommand (*this, info));
PostCommand (new DocumentDirtier (GetDocument ()));
}
}
return (True);
case eMacUI:
case eMotifUI:
case eWindowsGUI:
SetGUI (selection.GetCommandNumber ());
return (True);
case eEnglish:
case eFrench:
case eGerman:
case eItalian:
case eSpanish:
case eJapanese:
SetLanguage (selection.GetCommandNumber ());
return (True);
case eCustomizeOnly:
if (sCustomizeOnly) {
SetLanguage (fLanguage);
SetGUI (fGUI);
}
SetCustomizeOnly (not sCustomizeOnly);
return (True);
default:
return (Window::DoCommand (selection));
}
}
MainGroupItem& EmilyWindow::GetMainGroup () const
{
RequireNotNil (fMainGroup);
return (*fMainGroup);
}
static const String kMachineCodeStartString = "// text before here will be retained: Do not remove or modify this line!!!";
static const String kMachineCodeEndString = "// text past here will be retained: Do not remove or modify this line!!!";
void EmilyWindow::DoRead_ (class istream& from)
{
char bigBuf [1000];
fDataPrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fDataPrepend += s;
fDataPrepend += "\n";
}
}
char c;
from >> c;
from.putback (c);
if (c == 'D') {
// read off data file creation tag
from.getline (bigBuf, sizeof (bigBuf));
from.getline (bigBuf, sizeof (bigBuf));
}
Saveable::DoRead_ (from);
Rect extent = kZeroRect;
from >> extent;
WindowShellHints hints = GetShell ().GetWindowShellHints ();
#if 0
if (extent.GetOrigin () < DeskTop::Get ().GetBounds ().GetBounds ().GetOrigin ()) {
hints.SetDesiredOrigin (extent.GetOrigin ());
}
#endif
hints.SetDesiredSize (extent.GetSize ());
GetShell ().SetWindowShellHints (hints);
ReadString (from, fClassName);
ReadString (from, fBaseClass);
sCustomizeOnly = True;
GetMainGroup ().DoRead (from);
sCustomizeOnly = False;
GetMainGroup ().ResetCustomizeOnly ();
}
void EmilyWindow::DoWrite_ (class ostream& to, int tabCount) const
{
if (fDataPrepend != kEmptyString) {
to << fDataPrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline;
String appLongVersion = kApplicationVersion.GetLongVersionString ();
Assert (appLongVersion != kEmptyString);
to << "Data file written by " << appLongVersion << "." << newline;
to << newline << newline;
Saveable::DoWrite_ (to, tabCount);
to << newline;
to << GetShell ().GetExtent () << newline << newline;
WriteString (to, fClassName);
WriteString (to, fBaseClass);
GetMainGroup ().ResetFieldCounter ();
GetMainGroup ().DoWrite (to, tabCount);
to << newline;
}
void EmilyWindow::ReadHeaderFile (class istream& from)
{
char bigBuf [1000];
fHeaderPrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fHeaderPrepend += s;
fHeaderPrepend += "\n";
}
}
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeEndString) {
break;
}
}
}
fHeaderAppend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf), EOF)) {
fHeaderAppend += String (String::eReadOnly, bigBuf, from.gcount ());
}
}
}
void EmilyWindow::WriteHeaderFile (class ostream& to)
{
if (fHeaderPrepend != kEmptyString) {
to << fHeaderPrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline;
String compilationVariable = "__" + fClassName + "__";
if (EmilyApplication::Get ().GetCompileOnce ()) {
to << "#ifndef " << compilationVariable << newline;
to << "#define " << compilationVariable << newline << newline;
}
static const String kViewString = "View";
static const String kGroupViewString = "GroupView";
static const String kLabelGroupString = "LabeledGroup";
Boolean generateBaseClasses = Boolean ((fBaseClass == kViewString) or (fBaseClass == kGroupViewString) or (fBaseClass == kLabelGroupString));
if (generateBaseClasses) {
if (GetMainGroup ().IsButton ()) {
to << "#include " << quote << "Button.hh" << quote << newline;
}
if (GetMainGroup ().IsFocusItem (eAnyGUI)) {
to << "#include " << quote << "FocusItem.hh" << quote << newline;
}
if (GetMainGroup ().IsSlider ()) {
to << "#include " << quote << "Slider.hh" << quote << newline;
}
if (GetMainGroup ().IsText ()) {
to << "#include " << quote << "TextEdit.hh" << quote << newline;
}
to << "#include " << quote << "View.hh" << quote << newline;
to << newline;
}
GetMainGroup ().WriteIncludes (to, 0);
to << newline << newline;
to << "class "<< fClassName << " : public " << fBaseClass;
if (generateBaseClasses) {
if (GetMainGroup ().IsButton ()) {
to << ", public ButtonController";
}
if (GetMainGroup ().IsSlider ()) {
to << ", public SliderController";
}
if (GetMainGroup ().IsFocusItem (eAnyGUI)) {
to << ", public FocusOwner";
}
if (GetMainGroup ().IsText ()) {
to << ", public TextController";
}
}
to << " {" << newline << tab << "public:" << newline;
// declare constructor
to << tab (2) << fClassName << " ();" << newline;
// declare destructor
to << tab (2) << "~" << fClassName << " ();" << newline << newline;
// declare CalcDefaultSize method
to << tab (2) << "override" << tab << "Point" << tab << "CalcDefaultSize_ (const Point& defaultSize) const;" << newline << newline;
// declare layout method
to << tab << "protected:" << newline;
to << tab (2) << "override" << tab << "void" << tab << "Layout ();" << newline << newline;
// declare fields
GetMainGroup ().WriteDeclaration (to, 2);
to << newline << tab << "private:" << newline;
Boolean first = True;
for (CommandNumber gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << "#elif q";
}
to << directive << newline;
to << tab (2) << "nonvirtual void" << tab << "BuildFor" << directive << " ();" << newline;
}
}
Assert (not first); // must have at least one gui
to << "#else" << newline;
// to << tab (2) << "nonvirtual void" << tab << "BuildFor" << GetGUICompilationDirective (GetMainGroup ().GetBaseGUI ()) << " ();" << newline;
to << tab (2) << "nonvirtual void" << tab << "BuildForUnknownGUI ();" << newline;
to << "#endif /* GUI */" << newline << newline;
to << "};" << newline << newline;
if (EmilyApplication::Get ().GetCompileOnce ()) {
to << "#endif /* " << compilationVariable << " */" << newline;
}
to << newline << newline << kMachineCodeEndString << newline;
if (fHeaderAppend != kEmptyString) {
to << fHeaderAppend;
}
}
void EmilyWindow::ReadSourceFile (class istream& from)
{
char bigBuf [1000];
fSourcePrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fSourcePrepend += s;
fSourcePrepend += "\n";
}
}
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeEndString) {
break;
}
}
}
fSourceAppend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf), EOF)) {
fSourceAppend += String (String::eReadOnly, bigBuf, from.gcount ());
}
}
}
void EmilyWindow::WriteSourceFile (class ostream& to)
{
if (fSourcePrepend != kEmptyString) {
to << fSourcePrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline << newline;
to << "#include " << quote << "Language.hh" << quote << newline;
to << "#include " << quote << "Shape.hh" << quote << newline;
to << newline;
to << "#include " << quote << fDocument.GetHeaderFilePathName ().GetFileName () << quote << newline << newline << newline;
// define constructor
to << fClassName << "::" << fClassName << " ()";
// init fields to zero, in case of exception so we do right thing freeing them...
StringStream tempTo; // we use a stringstream to nuke the trailing comma
tempTo << " :" << newline;
GetMainGroup ().WriteBuilder (tempTo, 1);
String initializers = String (tempTo);
if (initializers.GetLength () > 2) {
// still have bad stream bug where zero length returns -1
initializers.SetLength (initializers.GetLength () -2); // one for comma, one for newline
}
else {
initializers.SetLength (0);
}
to << initializers << newline;
to << "{" << newline;
Boolean first = True;
for (CommandNumber gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << "#elif q";
}
to << directive << newline;
to << tab << "BuildFor" << directive << " ();" << newline;
}
}
Assert (not first); // must have at least one gui
to << "#else" << newline;
// to << tab << "BuildFor" << GetGUICompilationDirective (GetMainGroup ().GetBaseGUI ()) << " ();" << newline;
to << tab << "BuildForUnknownGUI ();" << newline;
to << "#endif /* GUI */" << newline << "}" << newline << newline;
// define destructor
to << fClassName << "::~" << fClassName << " ()" << newline;
to << "{" << newline;
GetMainGroup ().WriteDestructor (to, 0, GetMainGroup ().GetBaseGUI ());
to << "}" << newline << newline;
// define GUI builders
first = True;
for (gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << newline;
to << "#elif q";
}
to << directive << newline << newline;
to << "void" << tab << fClassName << "::BuildFor" << directive << " ()" << newline << "{" << newline;
GetMainGroup ().WriteInitializer (to, 0, gui);
to << "}" << newline;
}
}
Assert (not first); // must have at least one gui
to << newline << "#else" << newline << newline;
to << "void" << tab << fClassName << "::BuildForUnknownGUI ();" << newline << "{" << newline;
GetMainGroup ().WriteInitializer (to, 0, GetMainGroup ().GetBaseGUI ());
to << "}" << newline << newline;
to << "#endif /* GUI */" << newline << newline;
// define CalcDefaultSize method
to << "Point" << tab << fClassName << "::CalcDefaultSize_ (const Point& /*defaultSize*/) const" << newline << "{" << newline;
first = True;
for (gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q" << directive << newline;
first = False;
}
else {
to << "#elif q" << directive << newline;
}
Point scrollSize = GetMainGroup ().GetScrollSize (GetMainGroup ().GetBaseLanguage (), gui);
to << tab << "return (Point (" << scrollSize.GetV () << ", " << scrollSize.GetH () << "));" << newline;
}
}
Assert (not first);
to << "#else" << newline;
Point scrollSize = GetMainGroup ().GetScrollSize (GetMainGroup ().GetBaseLanguage (), GetMainGroup ().GetBaseGUI ());
to << tab << "return (Point (" << scrollSize.GetV () << ", " << scrollSize.GetH () << "));" << newline;
to << "#endif /* GUI */" << newline << "}" << newline << newline;
// define layout method
to << "void" << tab << fClassName << "::Layout ()" << newline << "{" << newline;
GetMainGroup ().WriteLayout (to, 1);
to << tab << fBaseClass << "::Layout ();" << newline;
to << "}" << newline;
to << newline << newline << kMachineCodeEndString << newline;
if (fSourceAppend != kEmptyString) {
to << fSourceAppend;
}
}
void EmilyWindow::EditModeChanged (Boolean newEditMode)
{
MenuOwner::SetMenusOutOfDate ();
GetMainGroup ().EditModeChanged (newEditMode);
}
CommandNumber EmilyWindow::GetGUI ()
{
return (sCurrentGUI);
}
void EmilyWindow::SetGUI (CommandNumber gui)
{
if (sCurrentGUI != gui) {
CommandNumber oldGUI = sCurrentGUI;
sCurrentGUI = gui;
MenuOwner::SetMenusOutOfDate ();
if (sCurrentGUI == eMacUI) {
SetBackground (&kWhiteTile);
}
else if (sCurrentGUI == eMotifUI) {
Tile t = PalletManager::Get ().MakeTileFromColor (kGrayColor);
SetBackground (&t);
}
else if (sCurrentGUI == eWindowsGUI) {
SetBackground (&kWhiteTile);
}
GetMainGroup ().GUIChanged (oldGUI, sCurrentGUI);
GetMainGroup ().Refresh ();
SetMainView (fMainGroup); // what a ridiculous hack to get it to resize stuff!!!
GetMainGroup ().Refresh ();
Update ();
}
}
CommandNumber EmilyWindow::GetLanguage ()
{
return (sCurrentLanguage);
}
void EmilyWindow::SetLanguage (CommandNumber language)
{
if (sCurrentLanguage != language) {
CommandNumber oldLanguage = sCurrentLanguage;
sCurrentLanguage = language;
MenuOwner::SetMenusOutOfDate ();
if (sCurrentLanguage != fLanguage) {
SetCustomizeOnly (True);
}
else if (sCurrentGUI == fGUI) {
SetCustomizeOnly (False);
}
GetMainGroup ().LanguageChanged (oldLanguage, sCurrentLanguage);
}
}
Boolean EmilyWindow::GetCustomizeOnly ()
{
return (sCustomizeOnly);
}
Boolean EmilyWindow::GetFullEditing ()
{
return (not sCustomizeOnly);
}
void EmilyWindow::SetCustomizeOnly (Boolean customizeOnly)
{
if (sCustomizeOnly != customizeOnly) {
sCustomizeOnly = customizeOnly;
MenuOwner::SetMenusOutOfDate ();
}
}
String GetGUICompilationDirective (CommandNumber gui)
{
switch (gui) {
case eMacUI:
return ("MacUI");
case eMotifUI:
return ("MotifUI");
case eWindowsGUI:
return ("WindowsGUI");
default:
RequireNotReached ();
}
AssertNotReached (); return (kEmptyString);
}
String GetLanguageCompilationDirective (CommandNumber language)
{
switch (language) {
case eEnglish:
return ("English");
case eFrench:
return ("French");
case eGerman:
return ("German");
case eItalian:
return ("Italian");
case eSpanish:
return ("Spanish");
case eJapanese:
return ("Japanese");
default:
RequireNotReached ();
}
AssertNotReached (); return (kEmptyString);
}
| 27.136591 | 142 | 0.652274 | SophistSolutions |
2845626b754d5b1438c031a49a8a2ce15d1f8187 | 1,098 | cpp | C++ | library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | null | null | null | library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | 41 | 2021-06-25T14:20:29.000Z | 2022-01-16T02:50:50.000Z | library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | null | null | null | /*! \file
\brief A node constraint element.
Copyright (C) 2019-2022 kaoru https://www.tetengo.org/
*/
#include <memory>
#include <utility>
#include <boost/core/noncopyable.hpp>
#include <tetengo/lattice/node.hpp>
#include <tetengo/lattice/node_constraint_element.hpp>
namespace tetengo::lattice
{
class node_constraint_element::impl : private boost::noncopyable
{
public:
// constructors and destructor
explicit impl(node node_) : m_node{ std::move(node_) } {}
// functions
int matches_impl(const node& node_) const
{
return node_ == m_node ? 0 : -1;
}
private:
// variables
const node m_node;
};
node_constraint_element::node_constraint_element(node node_) : m_p_impl{ std::make_unique<impl>(std::move(node_)) }
{}
node_constraint_element::~node_constraint_element() = default;
int node_constraint_element::matches_impl(const node& node_) const
{
return m_p_impl->matches_impl(node_);
}
}
| 20.716981 | 120 | 0.618397 | tetengo |
28530a40e5accd8f31daea09b54aff0474526fb5 | 3,707 | hpp | C++ | src/ui/AboutDialog/AboutDialog.hpp | ATiltedTree/APASSTools | 1702e082ae3b95ec10f3c5c084ef9396de5c3833 | [
"MIT"
] | null | null | null | src/ui/AboutDialog/AboutDialog.hpp | ATiltedTree/APASSTools | 1702e082ae3b95ec10f3c5c084ef9396de5c3833 | [
"MIT"
] | 4 | 2020-02-25T00:21:58.000Z | 2020-07-03T11:12:03.000Z | src/ui/AboutDialog/AboutDialog.hpp | ATiltedTree/APASSTools | 1702e082ae3b95ec10f3c5c084ef9396de5c3833 | [
"MIT"
] | null | null | null | #pragma once
#include "common/Icon.hpp"
#include <QApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QLayout>
#include <config.hpp>
constexpr int ICON_SIZE = 100;
namespace Ui {
class AboutDialog {
public:
QGridLayout *gridLayout;
QLabel *lableTitle;
QLabel *lableIcon;
QLabel *lableDesc;
QDialogButtonBox *buttonBox;
QDialog *parent;
AboutDialog(QDialog *parent)
: gridLayout(new QGridLayout(parent)), lableTitle(new QLabel(parent)),
lableIcon(new QLabel(parent)), lableDesc(new QLabel(parent)),
buttonBox(new QDialogButtonBox(parent)), parent(parent) {}
void setupUi() const {
parent->window()->layout()->setSizeConstraint(
QLayout::SizeConstraint::SetFixedSize);
parent->setWindowFlag(Qt::WindowType::MSWindowsFixedSizeDialogHint, true);
parent->setWindowIcon(getIcon(Icon::HelpAbout));
lableTitle->setText(
QObject::tr("<p><span style=\"font-size: 14pt; "
"font-weight:600;\">%1<span/><p/>"
"<p>Version: %2"
"<br/>Build with: %4 %5, %6"
"<br/>Copyright (c) 2020 Tilmann Meyer<p/>")
.arg(CONFIG_APP_NAME, CONFIG_APP_VERSION, CONFIG_COMPILER,
CONFIG_COMPILER_VERSION, CONFIG_COMPILER_ARCH));
lableDesc->setText(
"Permission is hereby granted, free of charge, to any person "
"obtaining a copy\n"
"of this software and associated documentation files (the "
"\"Software\"), to deal\n"
"in the Software without restriction, including without limitation "
"the rights\n"
"to use, copy, modify, merge, publish, distribute, sublicense, "
"and/or sell\n"
"copies of the Software, and to permit persons to whom the Software "
"is\n"
"furnished to do so, subject to the following conditions:\n"
"\n"
"The above copyright notice and this permission notice shall be "
"included in all\n"
"copies or substantial portions of the Software.\n"
"\n"
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
"EXPRESS OR\n"
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
"MERCHANTABILITY,\n"
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
"SHALL THE\n"
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
"OTHER\n"
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
"ARISING FROM,\n"
"OUT OF OR IN CONNECTION WI"
"TH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n"
"SOFTWARE\n");
lableIcon->setMaximumSize(QSize(ICON_SIZE, ICON_SIZE));
lableIcon->setPixmap(getIcon(Icon::Logo).pixmap(ICON_SIZE));
lableIcon->setScaledContents(true);
buttonBox->setOrientation(Qt::Orientation::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::StandardButton::Ok);
gridLayout->addWidget(buttonBox, 2, 0, 1, 2);
gridLayout->addWidget(lableIcon, 0, 0, 1, 1);
gridLayout->addWidget(lableDesc, 1, 0, 1, 2);
gridLayout->addWidget(lableTitle, 0, 1, 1, 1);
retranslateUi();
}
void retranslateUi() const {
parent->setWindowTitle(
QCoreApplication::translate("AboutDialog", "About", nullptr));
}
};
} // namespace Ui
class AboutDialog : public QDialog {
Q_OBJECT
public:
explicit AboutDialog(QWidget *parent);
private:
Ui::AboutDialog *ui;
};
| 34.64486 | 80 | 0.626113 | ATiltedTree |
2853a4fae21d10d113c59f1e5e720e1c399ab643 | 3,304 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 426 | 2015-04-12T10:00:46.000Z | 2022-03-29T11:03:02.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 124 | 2015-05-15T05:51:00.000Z | 2022-02-09T15:25:12.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 214 | 2015-05-06T07:30:37.000Z | 2022-03-26T16:14:04.000Z | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcActuatorTypeEnum.h"
// TYPE IfcActuatorTypeEnum = ENUMERATION OF (ELECTRICACTUATOR ,HANDOPERATEDACTUATOR ,HYDRAULICACTUATOR ,PNEUMATICACTUATOR ,THERMOSTATICACTUATOR ,USERDEFINED ,NOTDEFINED);
shared_ptr<BuildingObject> IfcActuatorTypeEnum::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcActuatorTypeEnum> copy_self( new IfcActuatorTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcActuatorTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCACTUATORTYPEENUM("; }
switch( m_enum )
{
case ENUM_ELECTRICACTUATOR: stream << ".ELECTRICACTUATOR."; break;
case ENUM_HANDOPERATEDACTUATOR: stream << ".HANDOPERATEDACTUATOR."; break;
case ENUM_HYDRAULICACTUATOR: stream << ".HYDRAULICACTUATOR."; break;
case ENUM_PNEUMATICACTUATOR: stream << ".PNEUMATICACTUATOR."; break;
case ENUM_THERMOSTATICACTUATOR: stream << ".THERMOSTATICACTUATOR."; break;
case ENUM_USERDEFINED: stream << ".USERDEFINED."; break;
case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break;
}
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcActuatorTypeEnum::toString() const
{
switch( m_enum )
{
case ENUM_ELECTRICACTUATOR: return L"ELECTRICACTUATOR";
case ENUM_HANDOPERATEDACTUATOR: return L"HANDOPERATEDACTUATOR";
case ENUM_HYDRAULICACTUATOR: return L"HYDRAULICACTUATOR";
case ENUM_PNEUMATICACTUATOR: return L"PNEUMATICACTUATOR";
case ENUM_THERMOSTATICACTUATOR: return L"THERMOSTATICACTUATOR";
case ENUM_USERDEFINED: return L"USERDEFINED";
case ENUM_NOTDEFINED: return L"NOTDEFINED";
}
return L"";
}
shared_ptr<IfcActuatorTypeEnum> IfcActuatorTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcActuatorTypeEnum>(); }
if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcActuatorTypeEnum>(); }
shared_ptr<IfcActuatorTypeEnum> type_object( new IfcActuatorTypeEnum() );
if( std_iequal( arg, L".ELECTRICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_ELECTRICACTUATOR;
}
else if( std_iequal( arg, L".HANDOPERATEDACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_HANDOPERATEDACTUATOR;
}
else if( std_iequal( arg, L".HYDRAULICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_HYDRAULICACTUATOR;
}
else if( std_iequal( arg, L".PNEUMATICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_PNEUMATICACTUATOR;
}
else if( std_iequal( arg, L".THERMOSTATICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_THERMOSTATICACTUATOR;
}
else if( std_iequal( arg, L".USERDEFINED." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_USERDEFINED;
}
else if( std_iequal( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
| 39.807229 | 172 | 0.740315 | AlexVlk |
2853bc1c7cf0246f945c77713f29bb9cdbda037c | 2,067 | cpp | C++ | GOOGLETEST/AccountTest/main.cpp | Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake | f1a3951c5fb9c29cc3de7deadb34caea5c8829d0 | [
"MIT"
] | null | null | null | GOOGLETEST/AccountTest/main.cpp | Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake | f1a3951c5fb9c29cc3de7deadb34caea5c8829d0 | [
"MIT"
] | null | null | null | GOOGLETEST/AccountTest/main.cpp | Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake | f1a3951c5fb9c29cc3de7deadb34caea5c8829d0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <gtest/gtest.h>
#include <stdexcept>
#include "account.h"
///////////////////////////////////////////////////////////////////
//fixture class for Account
class AccountTestFixtures: public testing::Test
{
public:
AccountTestFixtures();
static void SetUpTestCase();
void SetUp() override;
void TearDown() override;
static void TearDownTestCase();
virtual ~AccountTestFixtures(){
std::cout<<"\n\ndestructor\n\n";
}
protected:
Account accobj;
};
//method implementations
AccountTestFixtures::AccountTestFixtures()
:accobj{"amit", 198}
{
std::cout<<"\n\nconstructor\n\n";
}
void AccountTestFixtures::SetUpTestCase(){
std::cout<<"\n\nsetup test case\n\n";
}
void AccountTestFixtures::SetUp() {
std::cout<<"\n\nsetup\n\n";
accobj.setBalance( 198.0 );
}
void AccountTestFixtures::TearDown() {
std::cout<<"\n\nTearDown\n\n";
}
void AccountTestFixtures::TearDownTestCase(){
std::cout<<"\n\ntear down test case\n\n";
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 1 :: deposit :: normal deposit
TEST_F( AccountTestFixtures, Testdeposit ){
ASSERT_EQ( 188.0, accobj.withdrawl( 10 ));
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 2 :: deposit :: exception check
TEST_F( AccountTestFixtures, TestdepositSmallerThan0 ){
ASSERT_THROW( accobj.withdrawl( -10 ), std::invalid_argument);
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 3 :: deposit :: exception check
TEST_F( AccountTestFixtures, TestdepositNotEnoughBalance ){
ASSERT_THROW( accobj.withdrawl( 2000 ), std::runtime_error);
}
///////////////////////////////////////////////////////////////////
int main( int argc, char* argv[] ){
testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}
| 27.197368 | 67 | 0.507499 | Amit-Khobragade |
2854d4ff3ddbc2c5e17ae5989f6087554f272d9f | 2,183 | hpp | C++ | lib/STL+/containers/matrix.hpp | knela96/Game-Engine | 06659d933c4447bd8d6c8536af292825ce4c2ab1 | [
"Unlicense"
] | 65 | 2021-01-06T12:36:22.000Z | 2021-06-21T10:30:09.000Z | deps/stlplus/containers/matrix.hpp | evpo/libencryptmsg | fa1ea59c014c0a9ce339d7046642db4c80fc8701 | [
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 4 | 2021-12-06T16:00:00.000Z | 2022-03-18T07:40:33.000Z | deps/stlplus/containers/matrix.hpp | evpo/libencryptmsg | fa1ea59c014c0a9ce339d7046642db4c80fc8701 | [
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 11 | 2021-01-07T02:57:02.000Z | 2021-05-31T06:10:56.000Z | #ifndef STLPLUS_MATRIX
#define STLPLUS_MATRIX
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// General-purpose 2D matrix data structure
////////////////////////////////////////////////////////////////////////////////
#include "containers_fixes.hpp"
#include <stdexcept>
namespace stlplus
{
////////////////////////////////////////////////////////////////////////////////
template<typename T> class matrix
{
public:
matrix(unsigned rows = 0, unsigned cols = 0, const T& fill = T()) ;
~matrix(void) ;
matrix(const matrix&) ;
matrix& operator =(const matrix&) ;
void resize(unsigned rows, unsigned cols, const T& fill = T()) ;
unsigned rows(void) const ;
unsigned columns(void) const ;
void erase(const T& fill = T()) ;
// exceptions: std::out_of_range
void erase(unsigned row, unsigned col, const T& fill = T()) ;
// exceptions: std::out_of_range
void insert(unsigned row, unsigned col, const T&) ;
// exceptions: std::out_of_range
const T& item(unsigned row, unsigned col) const ;
// exceptions: std::out_of_range
T& item(unsigned row, unsigned col) ;
// exceptions: std::out_of_range
const T& operator()(unsigned row, unsigned col) const ;
// exceptions: std::out_of_range
T& operator()(unsigned row, unsigned col) ;
void fill(const T& item = T()) ;
// exceptions: std::out_of_range
void fill_column(unsigned col, const T& item = T()) ;
// exceptions: std::out_of_range
void fill_row(unsigned row, const T& item = T()) ;
void fill_leading_diagonal(const T& item = T()) ;
void fill_trailing_diagonal(const T& item = T()) ;
void make_identity(const T& one, const T& zero = T()) ;
void transpose(void) ;
private:
unsigned m_rows;
unsigned m_cols;
T** m_data;
};
////////////////////////////////////////////////////////////////////////////////
} // end namespace stlplus
#include "matrix.tpp"
#endif
| 30.319444 | 82 | 0.55016 | knela96 |
2857e6515c8cc11801506a908c7252d93ba529c1 | 62 | hpp | C++ | modules/jip/functions/JIP/script_component.hpp | Bear-Cave-ArmA/Olsen-Framework-ArmA-3 | 1c1715f0e4ed8f2b655a66999754256fa42ca6bf | [
"MIT"
] | 4 | 2020-05-04T18:03:59.000Z | 2020-05-06T19:40:27.000Z | modules/jip/functions/JIP/script_component.hpp | Bear-Cave-ArmA/Olsen-Framework-ArmA-3 | 1c1715f0e4ed8f2b655a66999754256fa42ca6bf | [
"MIT"
] | 13 | 2020-05-06T19:02:06.000Z | 2020-08-24T08:16:43.000Z | modules/jip/functions/JIP/script_component.hpp | Bear-Cave-ArmA/Olsen-Framework-ArmA-3 | 1c1715f0e4ed8f2b655a66999754256fa42ca6bf | [
"MIT"
] | 5 | 2020-05-04T18:04:05.000Z | 2020-05-14T16:53:13.000Z | #define COMPONENT JIP
#include "..\..\script_component.hpp"
| 20.666667 | 38 | 0.709677 | Bear-Cave-ArmA |
285b157bd91e1f11fa4f4c0c4a349bb4c69b3637 | 1,988 | cpp | C++ | prototypes/misc_tests/cv_test4.cpp | andrewjouffray/HyperAugment | cc7a675a1dac65ce31666e59dfd468c15293024f | [
"MIT"
] | null | null | null | prototypes/misc_tests/cv_test4.cpp | andrewjouffray/HyperAugment | cc7a675a1dac65ce31666e59dfd468c15293024f | [
"MIT"
] | null | null | null | prototypes/misc_tests/cv_test4.cpp | andrewjouffray/HyperAugment | cc7a675a1dac65ce31666e59dfd468c15293024f | [
"MIT"
] | null | null | null | #include <opencv2/opencv.hpp>
#include <iostream>
#include <omp.h>
#include <fstream>
#include <string>
#include <filesystem>
#include <chrono>
namespace fs = std::filesystem;
using namespace std;
// goal load a video file and process it with multithearding
vector<string> getFiles(string path){
//cout << "adding " + path << endl;
// this is it for now
vector<string> files;
for(const auto & entry : fs::directory_iterator(path)){
string it = entry.path();
//cout << it << endl;
files.push_back(it);
}
return files;
}
cv::Mat blackWhite(cv::Mat img){
cv::Mat grey;
cv::cvtColor(img, grey, cv::COLOR_BGR2GRAY);
return grey;
}
uint64_t timeSinceEpochMillisec(){
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main(int argc, const char* argv[]){
string path = "/mnt/0493db9e-eabd-406b-bd32-c5d3c85ebb38/Projects/Video/Weeds2/nenuphare/data1595119927.9510028output.avi";
string save = "/mnt/0493db9e-eabd-406b-bd32-c5d3c85ebb38/Projects/dump/";
int64_t start = timeSinceEpochMillisec();
cout << start << endl;
cv::VideoCapture cap(path);
cv::Mat frame;
while (1){
if (!cap.read(frame)){
cout << "al done" << endl;
break;
}
//cout << "test" << endl;
cv::Mat img = blackWhite(frame);
//cout << "OK" << endl;
//string windowName = "display " + to_string(i);
int64_t current = timeSinceEpochMillisec();
string name = save + to_string(current) + "ok.jpg";
cv::imwrite(name, img);
// this code will be a task that may be executed immediately on a different core or deferred for later execution
} // end of while loop and single region
uint64_t end = timeSinceEpochMillisec();
uint64_t total = end - start;
cout << end << endl;
cout << total << endl;
return 0;
}
| 18.238532 | 131 | 0.622233 | andrewjouffray |
285ba9ea9a30d009e31a5906e49bc6cbc8bb45c0 | 2,203 | cpp | C++ | src/base/ProxyAllocator.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 675 | 2019-05-28T19:00:55.000Z | 2022-03-31T16:44:28.000Z | src/base/ProxyAllocator.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 13 | 2020-03-29T06:46:32.000Z | 2022-01-29T03:19:30.000Z | src/base/ProxyAllocator.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 53 | 2019-06-02T03:04:10.000Z | 2022-03-11T06:17:50.000Z | #include <ncine/common_macros.h>
#include <nctl/ProxyAllocator.h>
namespace nctl {
///////////////////////////////////////////////////////////
// CONSTRUCTORS and DESTRUCTOR
///////////////////////////////////////////////////////////
ProxyAllocator::ProxyAllocator(const char *name, IAllocator &allocator)
: IAllocator(name, allocateImpl, reallocateImpl, deallocateImpl, 0, nullptr),
allocator_(allocator)
{
}
ProxyAllocator::~ProxyAllocator()
{
FATAL_ASSERT(usedMemory_ == 0 && numAllocations_ == 0);
}
///////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS
///////////////////////////////////////////////////////////
void *ProxyAllocator::allocateImpl(IAllocator *allocator, size_t bytes, uint8_t alignment)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *ptr = subject.allocateFunc_(&subject, bytes, alignment);
if (ptr)
{
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
allocatorImpl->numAllocations_++;
}
return ptr;
}
void *ProxyAllocator::reallocateImpl(IAllocator *allocator, void *ptr, size_t bytes, uint8_t alignment, size_t &oldSize)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *newPtr = subject.reallocateFunc_(&subject, ptr, bytes, alignment, oldSize);
if (newPtr)
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
return newPtr;
}
void ProxyAllocator::deallocateImpl(IAllocator *allocator, void *ptr)
{
if (ptr == nullptr)
return;
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
subject.deallocateFunc_(&subject, ptr);
allocatorImpl->usedMemory_ -= memoryUsedBefore - subject.usedMemory();
FATAL_ASSERT(allocatorImpl->numAllocations_ > 0);
allocatorImpl->numAllocations_--;
}
}
| 29.77027 | 120 | 0.684521 | bigplayszn |
286048f8b0629f4e1171e3411031b2ca73a38f01 | 1,784 | cc | C++ | experiments/efficiency/runtime_test.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 16 | 2018-08-30T19:55:43.000Z | 2022-02-16T16:38:06.000Z | experiments/efficiency/runtime_test.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 151 | 2018-05-27T13:01:50.000Z | 2021-08-04T14:50:50.000Z | experiments/efficiency/runtime_test.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 20 | 2018-11-13T13:46:38.000Z | 2022-02-18T17:33:52.000Z | /** @file runtime_test.cc
* @brief Some tests for runtime behavior of certain C++ constructs
*/
#include <iostream>
#include "lf/base/base.h"
static const int N = 10;
static double stat_tmp[N]; // NOLINT
std::vector<double> getData_VEC(double offset) {
std::vector<double> tmp(10);
for (int j = 0; j < N; j++) {
tmp[j] = 1.0 / (j + offset);
}
return tmp;
}
// NOLINTNEXTLINE
void getData_REF(double offset, std::vector<double> &res) {
for (int j = 0; j < N; j++) {
res[j] = 1.0 / (j + offset);
}
}
nonstd::span<const double> getData_SPAN(double offset) {
for (int j = 0; j < N; j++) {
stat_tmp[j] = 1.0 / (j + offset);
}
return {static_cast<double *>(stat_tmp), (stat_tmp + N)};
}
int main(int /*argc*/, const char * /*unused*/[]) {
std::cout << "Runtime test for range access" << std::endl;
const long int reps = 100000000L;
std::cout << "I. Returning std::vector's" << std::endl;
{
lf::base::AutoTimer t;
for (long int i = 0; i < reps; i++) {
auto res = getData_VEC(static_cast<double>(i));
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
std::cout << "II. Returning result through reference" << std::endl;
{
lf::base::AutoTimer t;
std::vector<double> res(N);
for (long int i = 0; i < reps; i++) {
getData_REF(static_cast<double>(i), res);
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
std::cout << "III. Returning result through span" << std::endl;
{
lf::base::AutoTimer t;
for (long int i = 0; i < reps; i++) {
auto res = getData_SPAN(static_cast<double>(i));
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
return 0;
}
| 22.582278 | 69 | 0.538677 | Fytch |
28617c6019b7bdfdb91bc6e8d63550ad8afaac6a | 4,390 | hpp | C++ | include/xwidgets/xvideo.hpp | SylvainCorlay/xwidgets | f21198f5934c90b034afee9b36c47b0e7b456c6b | [
"BSD-3-Clause"
] | 1 | 2020-01-10T04:13:44.000Z | 2020-01-10T04:13:44.000Z | include/xwidgets/xvideo.hpp | SylvainCorlay/xwidgets | f21198f5934c90b034afee9b36c47b0e7b456c6b | [
"BSD-3-Clause"
] | null | null | null | include/xwidgets/xvideo.hpp | SylvainCorlay/xwidgets | f21198f5934c90b034afee9b36c47b0e7b456c6b | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XWIDGETS_VIDEO_HPP
#define XWIDGETS_VIDEO_HPP
#include <cstddef>
#include <string>
#include <vector>
#include "xmaterialize.hpp"
#include "xmedia.hpp"
namespace xw
{
/*********************
* video declaration *
*********************/
template <class D>
class xvideo : public xmedia<D>
{
public:
using base_type = xmedia<D>;
using derived_type = D;
void serialize_state(nl::json& state, xeus::buffer_sequence&) const;
void apply_patch(const nl::json&, const xeus::buffer_sequence&);
XPROPERTY(std::string, derived_type, format, "mp4");
XPROPERTY(std::string, derived_type, width, "");
XPROPERTY(std::string, derived_type, height, "");
XPROPERTY(bool, derived_type, autoplay, true);
XPROPERTY(bool, derived_type, loop, true);
XPROPERTY(bool, derived_type, controls, true);
protected:
xvideo();
using base_type::base_type;
private:
void set_defaults();
};
using video = xmaterialize<xvideo>;
/*************************
* xvideo implementation *
*************************/
template <class D>
inline void xvideo<D>::serialize_state(nl::json& state, xeus::buffer_sequence& buffers) const
{
base_type::serialize_state(state, buffers);
xwidgets_serialize(format(), state["format"], buffers);
xwidgets_serialize(width(), state["width"], buffers);
xwidgets_serialize(height(), state["height"], buffers);
xwidgets_serialize(autoplay(), state["autoplay"], buffers);
xwidgets_serialize(loop(), state["loop"], buffers);
xwidgets_serialize(controls(), state["controls"], buffers);
}
template <class D>
inline void xvideo<D>::apply_patch(const nl::json& patch, const xeus::buffer_sequence& buffers)
{
base_type::apply_patch(patch, buffers);
set_property_from_patch(format, patch, buffers);
set_property_from_patch(width, patch, buffers);
set_property_from_patch(height, patch, buffers);
set_property_from_patch(autoplay, patch, buffers);
set_property_from_patch(loop, patch, buffers);
set_property_from_patch(controls, patch, buffers);
}
template <class D>
inline xvideo<D>::xvideo()
: base_type()
{
set_defaults();
}
template <class D>
inline void xvideo<D>::set_defaults()
{
this->_model_name() = "VideoModel";
this->_view_name() = "VideoView";
}
/**********************
* custom serializers *
**********************/
inline void set_property_from_patch(decltype(video::value)& property,
const nl::json& patch,
const xeus::buffer_sequence& buffers)
{
auto it = patch.find(property.name());
if (it != patch.end())
{
using value_type = typename decltype(video::value)::value_type;
std::size_t index = buffer_index(patch[property.name()].template get<std::string>());
const auto& value_buffer = buffers[index];
const char* value_buf = value_buffer.data<const char>();
property = value_type(value_buf, value_buf + value_buffer.size());
}
}
inline auto video_from_file(const std::string& filename)
{
return video::initialize().value(read_file(filename));
}
inline auto video_from_url(const std::string& url)
{
std::vector<char> value(url.cbegin(), url.cend());
return video::initialize().value(value).format("url");
}
/*********************
* precompiled types *
*********************/
extern template class xmaterialize<xvideo>;
extern template class xtransport<xmaterialize<xvideo>>;
}
#endif
| 32.043796 | 99 | 0.550797 | SylvainCorlay |
286930b7251bfb77d9c4612c785b52db98fecc5d | 506 | cpp | C++ | test/test_runner.cpp | jmalkin/hll-cpp | 0522f03473352fe50afb85e823e395253ea80532 | [
"Apache-2.0"
] | null | null | null | test/test_runner.cpp | jmalkin/hll-cpp | 0522f03473352fe50afb85e823e395253ea80532 | [
"Apache-2.0"
] | null | null | null | test/test_runner.cpp | jmalkin/hll-cpp | 0522f03473352fe50afb85e823e395253ea80532 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018, Oath Inc. Licensed under the terms of the
* Apache License 2.0. See LICENSE file at the project root for terms.
*/
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
int main(int argc, char **argv) {
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest() );
bool wasSuccessful = runner.run("", false);
return !wasSuccessful;
}
| 31.625 | 87 | 0.741107 | jmalkin |
286c5ecf38d03a1dd8d219ba69cecda5722795ee | 1,415 | cpp | C++ | 1.Top Interview Questions/C++/2.Strings/ReverseString.cpp | HanumantappaBudihal/LeetCode-Solutions | d46ad49f59e14798ff1716f1259a3e04c7aa3d17 | [
"MIT"
] | null | null | null | 1.Top Interview Questions/C++/2.Strings/ReverseString.cpp | HanumantappaBudihal/LeetCode-Solutions | d46ad49f59e14798ff1716f1259a3e04c7aa3d17 | [
"MIT"
] | null | null | null | 1.Top Interview Questions/C++/2.Strings/ReverseString.cpp | HanumantappaBudihal/LeetCode-Solutions | d46ad49f59e14798ff1716f1259a3e04c7aa3d17 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <cstring>
#include <bits/stdc++.h>
using namespace std;
/************************************************************************************************************
* Problem statement : https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/
*
* //Solution :
* //Time complexity :
* //Space complexity :
*
************************************************************************************************************/
//Normal Approach : using the library methods
class Solution1
{
public:
vector<int> reverseString(vector<int> inputString)
{
reverse(inputString.begin(), inputString.end());
}
};
//Without library
class Solution
{
public:
void reverseString(vector<char> inputString)
{
for (int i = 0, j = inputString.size() - 1; i < j; i++, j--)
{
char temp = inputString[i];
inputString[i] = inputString[j];
inputString[j] = temp;
}
}
};
int main()
{
char inputString[5] = {'h', 'e', 'l', 'l', 'o'};
int numberOfElement = sizeof(inputString) / sizeof(inputString[0]);
std::vector<char> string(numberOfElement);
memcpy(&string[0], &inputString[0], numberOfElement * sizeof(int));
Solution solution;
solution.reverseString(string);
}
| 26.203704 | 114 | 0.497527 | HanumantappaBudihal |
286cb47acae02dcb7f8fce48320957ed50ad5f44 | 16,597 | cpp | C++ | wwivconfig/wwivconfig.cpp | k5jat/wwiv | b390e476c75f68e0f4f28c66d4a2eecd74753b7c | [
"Apache-2.0"
] | null | null | null | wwivconfig/wwivconfig.cpp | k5jat/wwiv | b390e476c75f68e0f4f28c66d4a2eecd74753b7c | [
"Apache-2.0"
] | null | null | null | wwivconfig/wwivconfig.cpp | k5jat/wwiv | b390e476c75f68e0f4f28c66d4a2eecd74753b7c | [
"Apache-2.0"
] | null | null | null | /**************************************************************************/
/* */
/* WWIV Initialization Utility Version 5 */
/* Copyright (C)1998-2017, WWIV Software Services */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, */
/* software distributed under the License is distributed on an */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */
/* either express or implied. See the License for the specific */
/* language governing permissions and limitations under the License. */
/* */
/**************************************************************************/
#define _DEFINE_GLOBALS_
#include <cctype>
#include <cerrno>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <memory>
#ifdef _WIN32
#include <direct.h>
#include <io.h>
#endif
#include <locale.h>
#include <sys/stat.h>
#include "local_io/wconstants.h"
#include "core/command_line.h"
#include "core/datafile.h"
#include "core/file.h"
#include "core/inifile.h"
#include "core/log.h"
#include "core/os.h"
#include "core/strings.h"
#include "core/version.cpp"
#include "core/wwivport.h"
#include "wwivconfig/archivers.h"
#include "wwivconfig/autoval.h"
#include "wwivconfig/convert.h"
#include "wwivconfig/editors.h"
#include "wwivconfig/languages.h"
#include "wwivconfig/levels.h"
#include "wwivconfig/menus.h"
#include "wwivconfig/networks.h"
#include "wwivconfig/newinit.h"
#include "wwivconfig/paths.h"
#include "wwivconfig/protocols.h"
#include "wwivconfig/regcode.h"
#include "wwivconfig/subsdirs.h"
#include "wwivconfig/sysop_account.h"
#include "wwivconfig/system_info.h"
#include "wwivconfig/user_editor.h"
#include "wwivconfig/utility.h"
#include "wwivconfig/wwivconfig.h"
#include "wwivconfig/wwivd_ui.h"
#include "sdk/vardec.h"
#include "localui/curses_io.h"
#include "localui/curses_win.h"
#include "localui/input.h"
#include "localui/listbox.h"
#include "localui/stdio_win.h"
#include "localui/ui_win.h"
#include "localui/wwiv_curses.h"
#include "sdk/config.h"
#include "sdk/filenames.h"
#include "sdk/usermanager.h"
using std::string;
using std::vector;
using namespace wwiv::core;
using namespace wwiv::sdk;
using namespace wwiv::strings;
static bool CreateConfigOvr(const string& bbsdir) {
IniFile oini(WWIV_INI, {"WWIV"});
int num_instances = oini.value("NUM_INSTANCES", 4);
std::vector<legacy_configovrrec_424_t> config_ovr_data;
for (int i = 1; i <= num_instances; i++) {
string instance_tag = StringPrintf("WWIV-%u", i);
IniFile ini("wwiv.ini", {instance_tag, "WWIV"});
string temp_directory = ini.value<string>("TEMP_DIRECTORY");
if (temp_directory.empty()) {
LOG(ERROR) << "TEMP_DIRECTORY is not set! Unable to create CONFIG.OVR";
return false;
}
// TEMP_DIRECTORY is defined in wwiv.ini, therefore use it over config.ovr, also
// default the batch_directory to TEMP_DIRECTORY if BATCH_DIRECTORY does not exist.
string batch_directory(ini.value<string>("BATCH_DIRECTORY", temp_directory));
// Replace %n with instance number value.
const auto instance_num_string = std::to_string(i);
StringReplace(&temp_directory, "%n", instance_num_string);
StringReplace(&batch_directory, "%n", instance_num_string);
File::absolute(bbsdir, &temp_directory);
File::absolute(bbsdir, &batch_directory);
File::EnsureTrailingSlash(&temp_directory);
File::EnsureTrailingSlash(&batch_directory);
legacy_configovrrec_424_t r = {};
r.primaryport = 1;
to_char_array(r.batchdir, batch_directory);
to_char_array(r.tempdir, temp_directory);
config_ovr_data.emplace_back(r);
}
DataFile<legacy_configovrrec_424_t> file(CONFIG_OVR, File::modeBinary | File::modeReadWrite |
File::modeCreateFile |
File::modeTruncate);
if (!file) {
LOG(ERROR) << "Unable to open CONFIG.OVR for writing.";
return false;
}
if (!file.WriteVector(config_ovr_data)) {
LOG(ERROR) << "Unable to write to CONFIG.OVR.";
return false;
}
return true;
}
WInitApp::WInitApp() {}
WInitApp::~WInitApp() {
// Don't leak the localIO (also fix the color when the app exits)
delete out;
out = nullptr;
}
int main(int argc, char* argv[]) {
try {
wwiv::core::Logger::Init(argc, argv);
std::unique_ptr<WInitApp> app(new WInitApp());
return app->main(argc, argv);
} catch (const std::exception& e) {
LOG(INFO) << "Fatal exception launching wwivconfig: " << e.what();
}
}
static bool IsUserDeleted(const User& user) { return user.data.inact & inact_deleted; }
static bool CreateSysopAccountIfNeeded(const std::string& bbsdir) {
Config config(bbsdir);
{
UserManager usermanager(config);
auto num_users = usermanager.num_user_records();
for (int n = 1; n <= num_users; n++) {
User u{};
usermanager.readuser(&u, n);
if (!IsUserDeleted(u)) {
return true;
}
}
}
out->Cls(ACS_CKBOARD);
if (!dialog_yn(out->window(), "Would you like to create a sysop account now?")) {
messagebox(out->window(), "You will need to log in locally and manually create one");
return true;
}
create_sysop_account(config);
return true;
}
enum class ShouldContinue { CONTINUE, EXIT };
static ShouldContinue
read_configdat_and_upgrade_datafiles_if_needed(UIWindow* window, const wwiv::sdk::Config& config) {
// Convert 4.2X to 4.3 format if needed.
configrec cfg;
File file(config.config_filename());
if (file.length() != sizeof(configrec)) {
// TODO(rushfan): make a subwindow here but until this clear the altcharset background.
if (!dialog_yn(out->window(), "Upgrade config.dat from 4.x format?")) {
return ShouldContinue::EXIT;
}
window->Bkgd(' ');
convert_config_424_to_430(window, config);
}
if (file.Open(File::modeBinary | File::modeReadOnly)) {
file.Read(&cfg, sizeof(configrec));
}
file.Close();
// Check for 5.2 config
{
static const std::string expected_sig = "WWIV";
if (expected_sig != cfg.header.header.signature) {
// We don't have a 5.2 header, let's convert.
if (!dialog_yn(out->window(), "Upgrade config.dat to 5.2 format?")) {
return ShouldContinue::EXIT;
}
convert_config_to_52(window, config);
{
if (file.Open(File::modeBinary | File::modeReadOnly)) {
file.Read(&cfg, sizeof(configrec));
}
file.Close();
}
}
ensure_latest_5x_config(window, config, cfg);
}
ensure_offsets_are_updated(window, config);
return ShouldContinue::CONTINUE;
}
static void ShowHelp(CommandLine& cmdline) {
std::cout << cmdline.GetHelp() << std::endl;
exit(1);
}
static bool config_offsets_matches_actual(const Config& config) {
File file(config.config_filename());
if (!file.Open(File::modeBinary | File::modeReadWrite)) {
return false;
}
configrec x{};
file.Read(&x, sizeof(configrec));
// update user info data
int16_t userreclen = static_cast<int16_t>(sizeof(userrec));
int16_t waitingoffset = offsetof(userrec, waiting);
int16_t inactoffset = offsetof(userrec, inact);
int16_t sysstatusoffset = offsetof(userrec, sysstatus);
int16_t fuoffset = offsetof(userrec, forwardusr);
int16_t fsoffset = offsetof(userrec, forwardsys);
int16_t fnoffset = offsetof(userrec, net_num);
if (userreclen != x.userreclen || waitingoffset != x.waitingoffset ||
inactoffset != x.inactoffset || sysstatusoffset != x.sysstatusoffset ||
fuoffset != x.fuoffset || fsoffset != x.fsoffset || fnoffset != x.fnoffset) {
return false;
}
return true;
}
bool legacy_4xx_menu(const Config& config, UIWindow* window) {
bool done = false;
int selected = -1;
do {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
vector<ListBoxItem> items = {{"N. Network Configuration", 'N'},
{"U. User Editor", 'U'},
{"W. wwivd Configuration", 'W'},
{"Q. Quit", 'Q'}};
int selected_hotkey = -1;
{
ListBox list(window, "Main Menu", items);
list.selection_returns_hotkey(true);
list.set_additional_hotkeys("$");
list.set_selected(selected);
ListBoxResult result = list.Run();
selected = list.selected();
if (result.type == ListBoxResultType::HOTKEY) {
selected_hotkey = result.hotkey;
} else if (result.type == ListBoxResultType::NO_SELECTION) {
done = true;
}
}
out->footer()->SetDefaultFooter();
// It's easier to use the hotkey for this case statement so it's simple to know
// which case statement matches which item.
switch (selected_hotkey) {
case 'Q':
done = true;
break;
case 'N':
networks(config);
break;
case 'U':
user_editor(config);
break;
case 'W':
wwivd_ui(config);
break;
case '$': {
vector<string> lines;
std::ostringstream ss;
ss << "WWIV " << wwiv_version << beta_version << " wwivconfig compiled " << wwiv_date;
lines.push_back(ss.str());
lines.push_back(StrCat("QSCan Lenth: ", config.qscn_len()));
messagebox(window, lines);
} break;
}
out->SetIndicatorMode(IndicatorMode::NONE);
} while (!done);
return true;
}
int WInitApp::main(int argc, char** argv) {
setlocale(LC_ALL, "");
CommandLine cmdline(argc, argv, "net");
cmdline.AddStandardArgs();
cmdline.set_no_args_allowed(true);
cmdline.add_argument(BooleanCommandLineArgument(
"initialize", "Initialize the datafiles for the 1st time and exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("user_editor", 'U', "Run the user editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("menu_editor", 'M', "Run the menu editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("network_editor", 'N', "Run the network editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("4xx", '4', "Only run editors that work on WWIV 4.xx.", false));
cmdline.add_argument({"menu_dir", "Override the menu directory when using --menu_editor.", ""});
if (!cmdline.Parse() || cmdline.help_requested()) {
ShowHelp(cmdline);
return 0;
}
auto bbsdir = File::EnsureTrailingSlash(cmdline.bbsdir());
const bool forced_initialize = cmdline.barg("initialize");
UIWindow* window;
if (forced_initialize) {
window = new StdioWindow(nullptr, new ColorScheme());
} else {
CursesIO::Init(StringPrintf("WWIV %s%s Configuration Program.", wwiv_version, beta_version));
window = out->window();
out->Cls(ACS_CKBOARD);
window->SetColor(SchemeId::NORMAL);
}
if (forced_initialize && File::Exists(CONFIG_DAT)) {
messagebox(window, "Unable to use --initialize when CONFIG.DAT exists.");
return 1;
}
bool need_to_initialize = !File::Exists(CONFIG_DAT) || forced_initialize;
if (need_to_initialize) {
window->Bkgd(' ');
if (!new_init(window, bbsdir, need_to_initialize)) {
return 2;
}
}
Config config(bbsdir);
bool legacy_4xx_mode = false;
if (cmdline.barg("menu_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
auto menu_dir = config.menudir();
auto menu_dir_arg = cmdline.sarg("menu_dir");
if (!menu_dir_arg.empty()) {
menu_dir = menu_dir_arg;
}
menus(menu_dir);
return 0;
} else if (cmdline.barg("user_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
user_editor(config);
return 0;
} else if (cmdline.barg("network_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
if (!config_offsets_matches_actual(config)) {
return 1;
}
networks(config);
return 0;
} else if (cmdline.barg("4xx")) {
if (!config_offsets_matches_actual(config)) {
return 1;
}
legacy_4xx_mode = true;
}
if (!legacy_4xx_mode &&
read_configdat_and_upgrade_datafiles_if_needed(window, config) ==
ShouldContinue::EXIT) {
legacy_4xx_mode = true;
}
if (legacy_4xx_mode) {
legacy_4xx_menu(config, window);
return 0;
}
CreateConfigOvr(bbsdir);
{
File archiverfile(FilePath(config.datadir(), ARCHIVER_DAT));
if (!archiverfile.Open(File::modeBinary | File::modeReadOnly)) {
create_arcs(window, config.datadir());
}
}
if (forced_initialize) {
return 0;
}
// GP - We can move this up to after "read_status" if the
// wwivconfig --initialize flow should query the user to make an account.
CreateSysopAccountIfNeeded(bbsdir);
bool done = false;
int selected = -1;
do {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
vector<ListBoxItem> items = {{"G. General System Configuration", 'G'},
{"P. System Paths", 'P'},
{"T. External Transfer Protocol Configuration", 'T'},
{"E. External Editor Configuration", 'E'},
{"S. Security Level Configuration", 'S'},
{"V. Auto-Validation Level Configuration", 'V'},
{"A. Archiver Configuration", 'A'},
{"L. Language Configuration", 'L'},
{"M. Menu Editor", 'M'},
{"N. Network Configuration", 'N'},
{"R. Registration Information", 'R'},
{"U. User Editor", 'U'},
{"X. Update Sub/Directory Maximums", 'X'},
{"W. wwivd Configuration", 'W'},
{"Q. Quit", 'Q'}};
int selected_hotkey = -1;
{
ListBox list(window, "Main Menu", items);
list.selection_returns_hotkey(true);
list.set_additional_hotkeys("$");
list.set_selected(selected);
ListBoxResult result = list.Run();
selected = list.selected();
if (result.type == ListBoxResultType::HOTKEY) {
selected_hotkey = result.hotkey;
} else if (result.type == ListBoxResultType::NO_SELECTION) {
done = true;
}
}
out->footer()->SetDefaultFooter();
// It's easier to use the hotkey for this case statement so it's simple to know
// which case statement matches which item.
switch (selected_hotkey) {
case 'Q':
done = true;
break;
case 'G':
sysinfo1(config);
break;
case 'P':
setpaths(config);
break;
case 'T':
extrn_prots(config.datadir());
break;
case 'E':
extrn_editors(config);
break;
case 'S':
sec_levs(config);
break;
case 'V':
autoval_levs(config);
break;
case 'A':
edit_archivers(config);
break;
case 'L':
edit_languages(config);
break;
case 'N':
networks(config);
break;
case 'M':
menus(config.menudir());
break;
case 'R':
edit_registration_code(config);
break;
case 'U':
user_editor(config);
break;
case 'W':
wwivd_ui(config);
break;
case 'X':
up_subs_dirs(config);
break;
case '$': {
vector<string> lines;
std::ostringstream ss;
ss << "WWIV " << wwiv_version << beta_version << " wwivconfig compiled " << wwiv_date;
lines.push_back(ss.str());
lines.push_back(StrCat("QSCan Lenth: ", config.qscn_len()));
messagebox(window, lines);
} break;
}
out->SetIndicatorMode(IndicatorMode::NONE);
} while (!done);
config.Save();
return 0;
}
| 31.433712 | 105 | 0.607519 | k5jat |
287383cba67d98a84142fed9f734d6bae19a47fa | 2,432 | hpp | C++ | android-28/android/os/storage/StorageManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/os/storage/StorageManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-28/android/os/storage/StorageManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../../JObject.hpp"
namespace android::os
{
class Handler;
}
namespace android::os
{
class ParcelFileDescriptor;
}
namespace android::os
{
class ProxyFileDescriptorCallback;
}
namespace android::os::storage
{
class OnObbStateChangeListener;
}
namespace android::os::storage
{
class StorageVolume;
}
namespace java::io
{
class File;
}
namespace java::io
{
class FileDescriptor;
}
class JString;
namespace java::util
{
class UUID;
}
namespace android::os::storage
{
class StorageManager : public JObject
{
public:
// Fields
static JString ACTION_MANAGE_STORAGE();
static JString EXTRA_REQUESTED_BYTES();
static JString EXTRA_UUID();
static java::util::UUID UUID_DEFAULT();
// QJniObject forward
template<typename ...Ts> explicit StorageManager(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
StorageManager(QJniObject obj);
// Constructors
// Methods
void allocateBytes(java::io::FileDescriptor arg0, jlong arg1) const;
void allocateBytes(java::util::UUID arg0, jlong arg1) const;
jlong getAllocatableBytes(java::util::UUID arg0) const;
jlong getCacheQuotaBytes(java::util::UUID arg0) const;
jlong getCacheSizeBytes(java::util::UUID arg0) const;
JString getMountedObbPath(JString arg0) const;
android::os::storage::StorageVolume getPrimaryStorageVolume() const;
android::os::storage::StorageVolume getStorageVolume(java::io::File arg0) const;
JObject getStorageVolumes() const;
java::util::UUID getUuidForPath(java::io::File arg0) const;
jboolean isAllocationSupported(java::io::FileDescriptor arg0) const;
jboolean isCacheBehaviorGroup(java::io::File arg0) const;
jboolean isCacheBehaviorTombstone(java::io::File arg0) const;
jboolean isEncrypted(java::io::File arg0) const;
jboolean isObbMounted(JString arg0) const;
jboolean mountObb(JString arg0, JString arg1, android::os::storage::OnObbStateChangeListener arg2) const;
android::os::ParcelFileDescriptor openProxyFileDescriptor(jint arg0, android::os::ProxyFileDescriptorCallback arg1, android::os::Handler arg2) const;
void setCacheBehaviorGroup(java::io::File arg0, jboolean arg1) const;
void setCacheBehaviorTombstone(java::io::File arg0, jboolean arg1) const;
jboolean unmountObb(JString arg0, jboolean arg1, android::os::storage::OnObbStateChangeListener arg2) const;
};
} // namespace android::os::storage
| 30.4 | 155 | 0.759457 | YJBeetle |
287a82b966168a85726b83082e51688a7df03935 | 6,669 | cpp | C++ | EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | 1 | 2021-03-30T06:28:32.000Z | 2021-03-30T06:28:32.000Z | EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////////
// Copyright(c) 2016, Lin Koon Wing Macgyver, [email protected] //
// //
// Author : Mac Lin //
// Module : Magnum Engine v1.0.0 //
// Date : 14/Jun/2016 //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "Audio.h"
#include "AudioSourceBase.h"
#include "fmod.hpp"
#include "fmod_errors.h"
using namespace Magnum;
AudioSourceBase::AudioSourceBase(Component::Owner &owner_)
: AudioComponent(owner_)
, channelHandle(0)
, paused(false)
, muteEnabled(false)
, bypassEffectsEnabled(false)
, loopEnabled(false)
, priority(128)
, volume(1)
, pitch(1)
, dopplerLevel(1)
, volumeDecayMode(LogorithmRollOff)
, minDistance(1)
, panLevel(1)
, spread(0)
, maxDistance(500)
{
Audio::Manager::instance().audioSources.push() = this;
}
AudioSourceBase::~AudioSourceBase()
{
int idx = Audio::Manager::instance().audioSources.search(this);
if(idx>=0)
{
Audio::Manager::instance().audioSources.remove(idx);
}
}
void AudioSourceBase::stop()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
if(channel)
{
FMOD_RESULT result;
result = channel->stop();
channel = 0;
}
}
void AudioSourceBase::pause()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
paused = true;
if(channel)
channel->setPaused(true);
}
void AudioSourceBase::resume()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
paused = false;
if(channel)
channel->setPaused(false);
}
void AudioSourceBase::setMuteEnable(bool muteEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
muteEnabled = muteEnable_;
if(channel)
{
channel->setMute(muteEnabled);
}
}
void AudioSourceBase::setBypassEffectsEnable(bool bypassEffectsEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
bypassEffectsEnabled = bypassEffectsEnable_;
if(channel)
{
assert(0);
}
}
void AudioSourceBase::setLoopEnable(bool loopEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
loopEnabled = loopEnable_;
if(channel)
{
if(loopEnable_)
{
//result = channel->setMode(FMOD_LOOP_NORMAL);
result = channel->setLoopCount(-1);
}
else
{
//result = channel->setMode(FMOD_LOOP_OFF);
result = channel->setLoopCount(0);
}
}
}
void AudioSourceBase::setPriority(int priority_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
priority = priority_;
if(channel)
{
channel->setPriority(priority);
}
}
void AudioSourceBase::setVolume(float volume_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
volume = volume_;
if(channel)
{
channel->setVolume(volume);
}
}
void AudioSourceBase::setPitch(float pitch_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
pitch = pitch_;
if(channel)
{
FMOD::Sound *sound;
result = channel->getCurrentSound(&sound);
if(sound)
{
float frequency;
sound->getDefaults(&frequency, 0, 0, 0);
channel->setFrequency(frequency * pitch);
}
}
}
void AudioSourceBase::set3DDopplerLevel(float dopplerLevel_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
dopplerLevel = dopplerLevel_;
if(channel)
{
channel->set3DDopplerLevel(dopplerLevel_);
}
}
void AudioSourceBase::set3DVolumeDecayMode(AudioSourceBase::DecayMode volumeDecayMode_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
volumeDecayMode = volumeDecayMode_;
if(channel)
{
assert(0);
}
}
void AudioSourceBase::set3DMinDistance(float minDistance_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
minDistance = minDistance_;
if(channel)
{
channel->set3DMinMaxDistance(minDistance, maxDistance);
}
}
void AudioSourceBase::set3DPanLevel(float panLevel_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
panLevel = panLevel_;
if(channel)
{
channel->set3DPanLevel(panLevel);
}
}
void AudioSourceBase::set3DSpread(float spread_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
spread = spread_;
if(channel)
{
channel->set3DSpread(spread);
}
}
void AudioSourceBase::set3DMaxDistance(float maxDistance_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
maxDistance = maxDistance_;
if(channel)
{
channel->set3DMinMaxDistance(minDistance, maxDistance);
}
}
bool AudioSourceBase::isPaused() const
{
return paused;
}
bool AudioSourceBase::isMuteEnabled() const
{
return muteEnabled;
}
bool AudioSourceBase::isBypassEffectsEnabled() const
{
return bypassEffectsEnabled;
}
bool AudioSourceBase::isLoopEnabled() const
{
return loopEnabled;
}
int AudioSourceBase::getPriority() const
{
return priority;
}
float AudioSourceBase::getVolume() const
{
return volume;
}
float AudioSourceBase::getPitch() const
{
return pitch;
}
float AudioSourceBase::get3DDopplerLevel() const
{
return dopplerLevel;
}
AudioSourceBase::DecayMode AudioSourceBase::get3DVolumeDecayMode() const
{
return volumeDecayMode;
}
float AudioSourceBase::get3DMinDistance() const
{
return minDistance;
}
float AudioSourceBase::get3DPanLevel() const
{
return panLevel;
}
float AudioSourceBase::get3DSpread() const
{
return spread;
}
float AudioSourceBase::get3DMaxDistance() const
{
return maxDistance;
}
void *AudioSourceBase::getChannelHandle()
{
return channelHandle;
} | 20.027027 | 87 | 0.690508 | MacgyverLin |
287b22e519dd780eb231663c37e9b63ca68a8796 | 753 | cpp | C++ | src/scene/light.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/scene/light.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/scene/light.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | #include "light.hpp"
#include "../util/nm_math.hpp"
#include "../system/renderer.hpp"
Light::Light(
Scene *scene, Renderer *renderer, glm::vec3 position, glm::vec3 color
) :
SceneObject(scene, renderer, position), color(color)
{}
void Light::render(bool debug_mode)
{
SceneObject::render(debug_mode);
renderer->render_default(
PRIMITIVE_SPHERE,
color,
glm::scale(
glm::translate(
glm::identity<glm::mat4>(),
position),
glm::vec3(1.f / SCALE)));
}
bool Light::hit(float *t, glm::vec3 origin, glm::vec3 direction)
{
return nm_math::ray_sphere(t, origin, direction, position, 1.f / SCALE);
} | 25.965517 | 77 | 0.564409 | nolmoonen |
287d5513210df00735b4bdf41df40e8f8c8b77b1 | 1,399 | cpp | C++ | algorithm/SSSP-on-unweight-graph.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | algorithm/SSSP-on-unweight-graph.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | algorithm/SSSP-on-unweight-graph.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | #include "iostream"
#include "stdio.h"
#include "string"
#include "string.h"
#include "algorithm"
#include "math.h"
#include "vector"
#include "map"
#include "queue"
#include "stack"
#include "deque"
#include "set"
using namespace std;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int inf = 1e9;
#define DFS_WHITE -1 // UNVISITED
#define DFS_BLACK 1 // EXPLORED
#define DFS_GRAY 2 // VISTED BUT NOT EXPLORED
vector<vii> AdjList;
int V, E, u, v, s;
void graphUndirected(){
scanf("%d %d", &V, &E);
AdjList.assign(V + 4, vii());
for (int i = 0; i < E; i++) {
scanf("%d %d", &u, &v);
AdjList[u].push_back(ii(v, 0));
AdjList[v].push_back(ii(u, 0));
}
}
vi p;
void printPath(int u) {
if (u == s) { printf("%d", u); return; }
printPath(p[u]);
printf(" %d", u);
}
void bfs(int s){
vi d(V + 4, inf); d[s] = 0;
queue<int> q; q.push(s);
p.assign(V + 4, -1);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int j = 0; j < (int)AdjList[u].size(); j++) {
ii v = AdjList[u][j];
if (d[v.first] == inf) {
d[v.first] = d[u] + 1;
p[v.first] = u;
q.push(v.first);
}
}
}
}
int main(){
graphUndirected();
s = 5, bfs(s);
printPath(7);
printf("\n");
return 0;
}
| 20.573529 | 58 | 0.50965 | AREA44 |
287f40965278d62cc02152fb361085318976bba3 | 26,955 | hpp | C++ | include/barry/barray-meat.hpp | USCbiostats/barry | 79c363b9f31d9ee03b3ae199e98c688ffc2abdd0 | [
"MIT"
] | 8 | 2020-07-21T01:30:35.000Z | 2022-03-09T15:51:14.000Z | include/barry/barray-meat.hpp | USCbiostats/barry | 79c363b9f31d9ee03b3ae199e98c688ffc2abdd0 | [
"MIT"
] | 2 | 2022-01-24T20:51:46.000Z | 2022-03-16T23:08:40.000Z | include/barry/barray-meat.hpp | USCbiostats/barry | 79c363b9f31d9ee03b3ae199e98c688ffc2abdd0 | [
"MIT"
] | null | null | null | // #include <stdexcept>
#include "barray-bones.hpp"
#ifndef BARRY_BARRAY_MEAT_HPP
#define BARRY_BARRAY_MEAT_HPP
#define BARRAY_TYPE() BArray<Cell_Type, Data_Type>
#define BARRAY_TEMPLATE_ARGS() <typename Cell_Type, typename Data_Type>
#define BARRAY_TEMPLATE(a,b) \
template BARRAY_TEMPLATE_ARGS() inline a BARRAY_TYPE()::b
#define ROW(a) this->el_ij[a]
#define COL(a) this->el_ji[a]
template<typename Cell_Type, typename Data_Type>
Cell<Cell_Type> BArray<Cell_Type,Data_Type>::Cell_default = Cell<Cell_Type>();
// Edgelist with data
BARRAY_TEMPLATE(,BArray) (
uint N_, uint M_,
const std::vector< uint > & source,
const std::vector< uint > & target,
const std::vector< Cell_Type > & value,
bool add
) {
if (source.size() != target.size())
throw std::length_error("-source- and -target- don't match on length.");
if (source.size() != value.size())
throw std::length_error("-sorce- and -value- don't match on length.");
// Initializing
N = N_;
M = M_;
el_ij.resize(N);
el_ji.resize(M);
// Writing the data
for (uint i = 0u; i < source.size(); ++i) {
// Checking range
bool empty = this->is_empty(source[i], target[i], true);
if (add && !empty) {
ROW(source[i])[target[i]].add(value[i]);
continue;
}
if (!empty)
throw std::logic_error("The value already exists. Use 'add = true'.");
this->insert_cell(source[i], target[i], value[i], false, false);
}
return;
}
// Edgelist with data
BARRAY_TEMPLATE(,BArray) (
uint N_, uint M_,
const std::vector< uint > & source,
const std::vector< uint > & target,
bool add
) {
std::vector< Cell_Type > value(source.size(), (Cell_Type) 1.0);
if (source.size() != target.size())
throw std::length_error("-source- and -target- don't match on length.");
if (source.size() != value.size())
throw std::length_error("-sorce- and -value- don't match on length.");
// Initializing
N = N_;
M = M_;
el_ij.resize(N);
el_ji.resize(M);
// Writing the data
for (uint i = 0u; i < source.size(); ++i) {
// Checking range
if ((source[i] >= N_) | (target[i] >= M_))
throw std::range_error("Either source or target point to an element outside of the range by (N,M).");
// Checking if it exists
auto search = ROW(source[i]).find(target[i]);
if (search != ROW(source[i]).end()) {
if (!add)
throw std::logic_error("The value already exists. Use 'add = true'.");
// Increasing the value (this will automatically update the
// other value)
ROW(source[i])[target[i]].add(value[i]);
continue;
}
// Adding the value and creating a pointer to it
ROW(source[i]).emplace(
std::pair<uint, Cell< Cell_Type> >(
target[i],
Cell< Cell_Type >(value[i], visited)
)
);
COL(target[i]).emplace(
source[i],
&ROW(source[i])[target[i]]
);
NCells++;
}
return;
}
BARRAY_TEMPLATE(,BArray) (
const BArray<Cell_Type,Data_Type> & Array_,
bool copy_data
) : N(Array_.N), M(Array_.M)
{
// Dimensions
// el_ij.resize(N);
// el_ji.resize(M);
std::copy(Array_.el_ij.begin(), Array_.el_ij.end(), std::back_inserter(el_ij));
std::copy(Array_.el_ji.begin(), Array_.el_ji.end(), std::back_inserter(el_ji));
// Taking care of the pointers
for (uint i = 0u; i < N; ++i)
{
for (auto& r: row(i, false))
COL(r.first)[i] = &ROW(i)[r.first];
}
this->NCells = Array_.NCells;
this->visited = Array_.visited;
// Data
if (Array_.data != nullptr)
{
if (copy_data)
{
data = new Data_Type(* Array_.data );
delete_data = true;
} else {
data = Array_.data;
delete_data = false;
}
}
return;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator=) (
const BArray<Cell_Type,Data_Type> & Array_
) {
// Clearing
if (this != &Array_)
{
this->clear(true);
this->resize(Array_.N, Array_.M);
// Entries
for (uint i = 0u; i < N; ++i)
{
if (Array_.nnozero() == nnozero())
break;
for (auto& r : Array_.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Data
if (data != nullptr)
{
if (delete_data)
delete data;
data = nullptr;
delete_data = false;
}
if (Array_.data != nullptr)
{
data = new Data_Type(*Array_.data);
delete_data = true;
}
}
return *this;
}
BARRAY_TEMPLATE(,BArray) (
BARRAY_TYPE() && x
) noexcept :
N(0u), M(0u), NCells(0u),
data(nullptr),
delete_data(x.delete_data)
{
this->clear(true);
this->resize(x.N, x.M);
// Entries
for (uint i = 0u; i < N; ++i) {
if (x.nnozero() == nnozero())
break;
for (auto& r : x.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Managing data
if (x.data != nullptr)
{
if (x.delete_data)
{
data = new Data_Type(*x.data);
delete_data = true;
} else {
data = x.data;
delete_data = false;
}
}
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator=) (
BARRAY_TYPE() && x
) noexcept {
// Clearing
if (this != &x) {
this->clear(true);
this->resize(x.N, x.M);
// Entries
for (uint i = 0u; i < N; ++i) {
if (x.nnozero() == nnozero())
break;
for (auto& r : x.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Data
if (data != nullptr)
{
if (delete_data)
delete data;
data = nullptr;
delete_data = false;
}
if (x.data != nullptr)
{
data = new Data_Type( *x.data );
delete_data = true;
}
// x.data = nullptr;
// x.delete_data = false;
}
return *this;
}
BARRAY_TEMPLATE(bool, operator==) (
const BARRAY_TYPE() & Array_
) {
// Dimension and number of cells used
if ((N != Array_.nrow()) | (M != Array_.ncol()) | (NCells != Array_.nnozero()))
return false;
// One holds, and the other doesn't.
if ((!data & Array_.data) | (data & !Array_.data))
return false;
if (this->el_ij != Array_.el_ij)
return false;
return true;
}
BARRAY_TEMPLATE(,~BArray) () {
if (delete_data && (data != nullptr))
delete data;
return;
}
BARRAY_TEMPLATE(void, set_data) (
Data_Type * data_, bool delete_data_
) {
if ((data != nullptr) && delete_data)
delete data;
data = data_;
delete_data = delete_data_;
return;
}
BARRAY_TEMPLATE(Data_Type *, D) ()
{
return this->data;
}
template<typename Cell_Type, typename Data_Type>
inline const Data_Type * BArray<Cell_Type,Data_Type>::D() const
{
return this->data;
}
template<typename Cell_Type, typename Data_Type>
inline void BArray<Cell_Type,Data_Type>::flush_data()
{
if (delete_data)
{
delete data;
delete_data = false;
}
data = nullptr;
return;
}
BARRAY_TEMPLATE(void, out_of_range) (
uint i,
uint j
) const {
if (i >= N)
throw std::range_error("The row is out of range.");
else if (j >= M)
throw std::range_error("The column is out of range.");
return;
}
BARRAY_TEMPLATE(Cell_Type, get_cell) (
uint i,
uint j,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i,j);
if (ROW(i).size() == 0u)
return (Cell_Type) 0.0;
// If it is not empty, then find and return
auto search = ROW(i).find(j);
if (search != ROW(i).end())
return search->second.value;
// This is if it is empty
return (Cell_Type) 0.0;
}
BARRAY_TEMPLATE(std::vector< Cell_Type >, get_row_vec) (
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i, 0u);
std::vector< Cell_Type > ans(ncol(), (Cell_Type) false);
for (const auto & iter : row(i, false))
ans[iter.first] = iter.second.value; //this->get_cell(i, iter->first, false);
return ans;
}
BARRAY_TEMPLATE(void, get_row_vec) (
std::vector< Cell_Type > * x,
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i, 0u);
for (const auto & iter : row(i, false))
x->at(iter.first) = iter.second.value; // this->get_cell(i, iter->first, false);
}
BARRAY_TEMPLATE(std::vector< Cell_Type >, get_col_vec) (
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(0u, i);
std::vector< Cell_Type > ans(nrow(), (Cell_Type) false);
for (const auto iter : col(i, false))
ans[iter.first] = iter.second->value;//this->get_cell(iter->first, i, false);
return ans;
}
BARRAY_TEMPLATE(void, get_col_vec) (
std::vector<Cell_Type> * x,
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(0u, i);
for (const auto & iter : col(i, false))
x->at(iter.first) = iter.second->value;//this->get_cell(iter->first, i, false);
}
BARRAY_TEMPLATE(const Row_type< Cell_Type > &, row) (
uint i,
bool check_bounds
) const {
if (check_bounds)
out_of_range(i, 0u);
return this->el_ij[i];
}
BARRAY_TEMPLATE(const Col_type< Cell_Type > &, col) (
uint i,
bool check_bounds
) const {
if (check_bounds)
out_of_range(0u, i);
return this->el_ji[i];
}
BARRAY_TEMPLATE(Entries< Cell_Type >, get_entries) () const {
Entries<Cell_Type> res(NCells);
for (uint i = 0u; i < N; ++i) {
if (ROW(i).size() == 0u)
continue;
for (auto col = ROW(i).begin(); col != ROW(i).end(); ++col) {
res.source.push_back(i),
res.target.push_back(col->first),
res.val.push_back(col->second.value);
}
}
return res;
}
BARRAY_TEMPLATE(bool, is_empty) (
uint i,
uint j,
bool check_bounds
) const {
if (check_bounds)
out_of_range(i, j);
if (ROW(i).size() == 0u)
return true;
else if (COL(j).size() == 0u)
return true;
if (ROW(i).find(j) == ROW(i).end())
return true;
return false;
}
BARRAY_TEMPLATE(unsigned int, nrow) () const noexcept {
return N;
}
BARRAY_TEMPLATE(unsigned int, ncol) () const noexcept {
return M;
}
BARRAY_TEMPLATE(unsigned int, nnozero) () const noexcept {
return NCells;
}
BARRAY_TEMPLATE(Cell< Cell_Type >, default_val) () const {
return this->Cell_default;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator+=) (
const std::pair<uint,uint> & coords
) {
this->insert_cell(
coords.first,
coords.second,
this->Cell_default,
true, true
);
return *this;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator-=) (
const std::pair<uint,uint> & coords
) {
this->rm_cell(
coords.first,
coords.second,
true, true
);
return *this;
}
template BARRAY_TEMPLATE_ARGS()
inline BArrayCell<Cell_Type,Data_Type> BARRAY_TYPE()::operator()(
uint i,
uint j,
bool check_bounds
) {
return BArrayCell<Cell_Type,Data_Type>(this, i, j, check_bounds);
}
template BARRAY_TEMPLATE_ARGS()
inline const BArrayCell_const<Cell_Type,Data_Type> BARRAY_TYPE()::operator() (
uint i,
uint j,
bool check_bounds
) const {
return BArrayCell_const<Cell_Type,Data_Type>(this, i, j, check_bounds);
}
BARRAY_TEMPLATE(void, rm_cell) (
uint i,
uint j,
bool check_bounds,
bool check_exists
) {
// Checking the boundaries
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Nothing to do
if (ROW(i).size() == 0u)
return;
// Checking the counter part
if (COL(j).size() == 0u)
return;
// Hard work, need to remove it from both, if it exist
if (ROW(i).find(j) == ROW(i).end())
return;
}
// Remove the pointer first (so it wont point to empty)
COL(j).erase(i);
ROW(i).erase(j);
NCells--;
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
const Cell< Cell_Type> & v,
bool check_bounds,
bool check_exists
) {
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Checking if nothing here, then we move along
if (ROW(i).size() == 0u) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
return;
}
// In this case, the row exists, but we are checking that the value is empty
if (ROW(i).find(j) == ROW(i).end()) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
} else {
throw std::logic_error("The cell already exists.");
}
} else {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
}
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
Cell< Cell_Type> && v,
bool check_bounds,
bool check_exists
) {
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Checking if nothing here, then we move along
if (ROW(i).size() == 0u) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
return;
}
// In this case, the row exists, but we are checking that the value is empty
if (ROW(i).find(j) == ROW(i).end()) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
} else {
throw std::logic_error("The cell already exists.");
}
} else {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
}
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
Cell_Type v,
bool check_bounds,
bool check_exists
) {
return insert_cell(i, j, Cell<Cell_Type>(v, visited), check_bounds, check_exists);
}
BARRAY_TEMPLATE(void, swap_cells) (
uint i0, uint j0,
uint i1, uint j1,
bool check_bounds,
int check_exists,
int * report
) {
if (check_bounds) {
out_of_range(i0,j0);
out_of_range(i1,j1);
}
// Simplest case, we know both exists, so we don't need to check anything
if (check_exists == CHECK::NONE)
{
// Just in case, if this was passed
if (report != nullptr)
(*report) = EXISTS::BOTH;
// If source and target coincide, we do nothing
if ((i0 == i1) && (j0 == j1))
return;
// Using the initializing by move, after this, the cell becomes
// invalid. We use pointers instead as this way we access the Heap memory,
// which should be faster to access.
Cell<Cell_Type> c0(std::move(ROW(i0)[j0]));
rm_cell(i0, j0, false, false);
Cell<Cell_Type> c1(std::move(ROW(i1)[j1]));
rm_cell(i1, j1, false, false);
// Inserting the cells by reference, these will be deleted afterwards
insert_cell(i0, j0, c1, false, false);
insert_cell(i1, j1, c0, false, false);
return;
}
bool check0, check1;
if (check_exists == CHECK::BOTH)
{
check0 = !is_empty(i0, j0, false);
check1 = !is_empty(i1, j1, false);
} else if (check_exists == CHECK::ONE) {
check0 = !is_empty(i0, j0, false);
check1 = true;
} else if (check_exists == CHECK::TWO) {
check0 = true;
check1 = !is_empty(i1, j1, false);
}
if (report != nullptr)
(*report) = EXISTS::NONE;
// If both cells exists
if (check0 & check1)
{
if (report != nullptr)
(*report) = EXISTS::BOTH;
// If source and target coincide, we do nothing
if ((i0 == i1) && (j0 == j1))
return;
Cell<Cell_Type> c0(std::move(ROW(i0)[j0]));
rm_cell(i0, j0, false, false);
Cell<Cell_Type> c1(std::move(ROW(i1)[j1]));
rm_cell(i1, j1, false, false);
insert_cell(i0, j0, c1, false, false);
insert_cell(i1, j1, c0, false, false);
} else if (!check0 & check1) { // If only the second exists
if (report != nullptr)
(*report) = EXISTS::TWO;
insert_cell(i0, j0, ROW(i1)[j1], false, false);
rm_cell(i1, j1, false, false);
} else if (check0 & !check1) {
if (report != nullptr)
(*report) = EXISTS::ONE;
insert_cell(i1, j1, ROW(i0)[j0], false, false);
rm_cell(i0, j0, false, false);
}
return;
}
BARRAY_TEMPLATE(void, toggle_cell) (
uint i,
uint j,
bool check_bounds,
int check_exists
) {
if (check_bounds)
out_of_range(i, j);
if (check_exists == EXISTS::UKNOWN) {
if (is_empty(i, j, false)) {
insert_cell(i, j, BArray<Cell_Type, Data_Type>::Cell_default, false, false);
ROW(i)[j].visited = visited;
} else
rm_cell(i, j, false, false);
} else if (check_exists == EXISTS::AS_ONE) {
rm_cell(i, j, false, false);
} else if (check_exists == EXISTS::AS_ZERO) {
insert_cell(i, j, BArray<Cell_Type,Data_Type>::Cell_default, false, false);
ROW(i)[j].visited = visited;
}
return;
}
BARRAY_TEMPLATE(void, swap_rows) (
uint i0,
uint i1,
bool check_bounds
) {
if (check_bounds) {
out_of_range(i0,0u);
out_of_range(i1,0u);
}
bool move0=true, move1=true;
if (ROW(i0).size() == 0u) move0 = false;
if (ROW(i1).size() == 0u) move1 = false;
if (!move0 && !move1)
return;
// Swapping happens naturally, need to take care of the pointers
// though
ROW(i0).swap(ROW(i1));
// Delete the thing
if (move0)
for (auto& i: row(i1, false))
COL(i.first).erase(i0);
if (move1)
for (auto& i: row(i0, false))
COL(i.first).erase(i1);
// Now, point to the thing, if it has something to point at. Recall that
// the indices swapped.
if (move1)
for (auto& i: row(i0, false))
COL(i.first)[i0] = &ROW(i0)[i.first];
if (move0)
for (auto& i: row(i1, false))
COL(i.first)[i1] = &ROW(i1)[i.first];
return;
}
// This swapping is more expensive overall
BARRAY_TEMPLATE(void, swap_cols) (
uint j0,
uint j1,
bool check_bounds
) {
if (check_bounds) {
out_of_range(0u, j0);
out_of_range(0u, j1);
}
// Which ones need to be checked
bool check0 = true, check1 = true;
if (COL(j0).size() == 0u) check0 = false;
if (COL(j1).size() == 0u) check1 = false;
if (check0 && check1) {
// Just swapping one at a time
int status;
Col_type<Cell_Type> col_tmp = COL(j1);
Col_type<Cell_Type> col1 = COL(j0);
for (auto iter = col1.begin(); iter != col1.end(); ++iter) {
// Swapping values (col-wise)
swap_cells(iter->first, j0, iter->first, j1, false, CHECK::TWO, &status);
// Need to remove it, so we don't swap that as well
if (status == EXISTS::BOTH)
col_tmp.erase(iter->first);
}
// If there's anything left to move, we start moving it, otherwise, we just
// skip it
if (col_tmp.size() != 0u) {
for (auto iter = col_tmp.begin(); iter != col_tmp.end(); ++iter) {
insert_cell(iter->first, j0, *iter->second, false, false);
rm_cell(iter->first, j1);
}
}
} else if (check0 && !check1) {
// 1 is empty, so we just add new cells and remove the other ones
for (auto iter = COL(j0).begin(); iter != COL(j0).begin(); ++iter)
insert_cell(iter->first, j1, *iter->second, false, false);
// Setting the column to be zero
COL(j0).empty();
} else if (!check0 && check1) {
// 1 is empty, so we just add new cells and remove the other ones
for (auto iter = COL(j1).begin(); iter != COL(j1).begin(); ++iter) {
// Swapping values (col-wise)
insert_cell(iter->first, j0, *iter->second, false, false);
}
// Setting the column to be zero
COL(j1).empty();
}
return;
}
BARRAY_TEMPLATE(void, zero_row) (
uint i,
bool check_bounds
) {
if (check_bounds)
out_of_range(i, 0u);
// Nothing to do
if (ROW(i).size() == 0u)
return;
// Else, remove all elements
auto row0 = ROW(i);
for (auto row = row0.begin(); row != row0.end(); ++row)
rm_cell(i, row->first, false, false);
return;
}
BARRAY_TEMPLATE(void, zero_col) (
uint j,
bool check_bounds
) {
if (check_bounds)
out_of_range(0u, j);
// Nothing to do
if (COL(j).size() == 0u)
return;
// Else, remove all elements
auto col0 = COL(j);
for (auto col = col0.begin(); col != col0.end(); ++col)
rm_cell(col->first, j, false, false);
return;
}
BARRAY_TEMPLATE(void, transpose) () {
// Start by flipping the switch
visited = !visited;
// Do we need to resize (increase) either?
if (N > M) el_ji.resize(N);
else if (N < M) el_ij.resize(M);
// uint N0 = N, M0 = M;
int status;
for (uint i = 0u; i < N; ++i)
{
// Do we need to move anything?
if (ROW(i).size() == 0u)
continue;
// We now iterate changing rows
Row_type<Cell_Type> row = ROW(i);
for (auto col = row.begin(); col != row.end(); ++col)
{
// Skip if in the diagoal
if (i == col->first)
{
ROW(i)[i].visited = visited;
continue;
}
// We have not visited this yet, we need to change that
if (ROW(i)[col->first].visited != visited)
{
// First, swap the contents
swap_cells(i, col->first, col->first, i, false, CHECK::TWO, &status);
// Changing the switch
if (status == EXISTS::BOTH)
ROW(i)[col->first].visited = visited;
ROW(col->first)[i].visited = visited;
}
}
}
// Shreding. Note that no information should have been lost since, hence, no
// change in NCells.
if (N > M) el_ij.resize(M);
else if (N < M) el_ji.resize(N);
// Swapping the values
std::swap(N, M);
return;
}
BARRAY_TEMPLATE(void, clear) (
bool hard
) {
if (hard)
{
el_ji.clear();
el_ij.clear();
el_ij.resize(N);
el_ji.resize(M);
NCells = 0u;
} else {
for (unsigned int i = 0u; i < N; ++i)
zero_row(i, false);
}
return;
}
BARRAY_TEMPLATE(void, resize) (
uint N_,
uint M_
) {
// Removing rows
if (N_ < N)
for (uint i = N_; i < N; ++i)
zero_row(i, false);
// Removing cols
if (M_ < M)
for (uint j = M_; j < M; ++j)
zero_col(j, false);
// Resizing will invalidate pointers and values out of range
if (M_ != M) {
el_ji.resize(M_);
M = M_;
}
if (N_ != N) {
el_ij.resize(N_);
N = N_;
}
return;
}
BARRAY_TEMPLATE(void, reserve) () {
#ifdef BARRAY_USE_UNORDERED_MAP
for (uint i = 0u; i < N; i++)
ROW(i).reserve(M);
for (uint i = 0u; i < M; i++)
COL(i).reserve(N);
#endif
return;
}
BARRAY_TEMPLATE(void, print) (
const char * fmt,
...
) const {
std::va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
for (uint i = 0u; i < N; ++i)
{
#ifdef BARRY_DEBUG_LEVEL
#if BARRY_DEBUG_LEVEL > 1
printf_barry("%s [%3i,]", BARRY_DEBUG_HEADER, i);
#endif
#else
printf_barry("[%3i,] ", i);
#endif
for (uint j = 0u; j < M; ++j) {
if (this->is_empty(i, j, false))
printf_barry(" . ");
else
printf_barry(" %.2f ", static_cast<double>(this->get_cell(i, j, false)));
}
printf_barry("\n");
}
return;
}
#undef ROW
#undef COL
#undef BARRAY_TYPE
#undef BARRAY_TEMPLATE_ARGS
#undef BARRAY_TEMPLATE
#endif
| 21.968215 | 113 | 0.506733 | USCbiostats |
287f86cc257f7c6803d7226c36014d060a9e76fb | 4,800 | hxx | C++ | src/bp/Config.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | 1 | 2022-03-15T22:54:39.000Z | 2022-03-15T22:54:39.000Z | src/bp/Config.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | null | null | null | src/bp/Config.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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.
*/
#pragma once
#include "access_log/Config.hxx"
#include "ssl/Config.hxx"
#include "net/SocketConfig.hxx"
#include "spawn/Config.hxx"
#include <forward_list>
#include <chrono>
#include <stddef.h>
struct StringView;
/**
* Configuration.
*/
struct BpConfig {
struct Listener : SocketConfig {
std::string tag;
#ifdef HAVE_AVAHI
std::string zeroconf_service;
std::string zeroconf_interface;
#endif
/**
* If non-empty, then this listener has its own
* translation server(s) and doesn't use the global
* server.
*/
std::forward_list<AllocatedSocketAddress> translation_sockets;
enum class Handler {
TRANSLATION,
PROMETHEUS_EXPORTER,
} handler = Handler::TRANSLATION;
bool auth_alt_host = false;
bool ssl = false;
SslConfig ssl_config;
Listener() {
listen = 64;
tcp_defer_accept = 10;
}
explicit Listener(SocketAddress _address) noexcept
:SocketConfig(_address)
{
listen = 64;
tcp_defer_accept = 10;
}
#ifdef HAVE_AVAHI
/**
* @return the name of the interface where the
* Zeroconf service shall be published
*/
[[gnu::pure]]
const char *GetZeroconfInterface() const noexcept {
if (!zeroconf_interface.empty())
return zeroconf_interface.c_str();
if (!interface.empty())
return interface.c_str();
return nullptr;
}
#endif
};
std::forward_list<Listener> listen;
AccessLogConfig access_log;
AccessLogConfig child_error_log;
std::string session_cookie = "beng_proxy_session";
std::chrono::seconds session_idle_timeout = std::chrono::minutes(30);
std::string session_save_path;
struct ControlListener : SocketConfig {
ControlListener() {
pass_cred = true;
}
explicit ControlListener(SocketAddress _bind_address)
:SocketConfig(_bind_address) {
pass_cred = true;
}
};
std::forward_list<ControlListener> control_listen;
std::forward_list<AllocatedSocketAddress> translation_sockets;
/** maximum number of simultaneous connections */
unsigned max_connections = 32768;
size_t http_cache_size = 512 * 1024 * 1024;
size_t filter_cache_size = 128 * 1024 * 1024;
size_t nfs_cache_size = 256 * 1024 * 1024;
unsigned translate_cache_size = 131072;
unsigned translate_stock_limit = 32;
unsigned tcp_stock_limit = 0;
unsigned lhttp_stock_limit = 0, lhttp_stock_max_idle = 8;
unsigned fcgi_stock_limit = 0, fcgi_stock_max_idle = 8;
unsigned was_stock_limit = 0, was_stock_max_idle = 16;
unsigned multi_was_stock_limit = 0, multi_was_stock_max_idle = 16;
unsigned remote_was_stock_limit = 0, remote_was_stock_max_idle = 16;
unsigned cluster_size = 0, cluster_node = 0;
enum class SessionCookieSameSite : uint8_t {
NONE,
STRICT,
LAX,
} session_cookie_same_site;
bool dynamic_session_cookie = false;
bool verbose_response = false;
bool emulate_mod_auth_easy = false;
bool http_cache_obey_no_cache = true;
SpawnConfig spawn;
SslClientConfig ssl_client;
BpConfig() {
#ifdef HAVE_LIBSYSTEMD
spawn.systemd_scope = "bp-spawn.scope";
spawn.systemd_scope_description = "The cm4all-beng-proxy child process spawner";
spawn.systemd_slice = "system-cm4all.slice";
#endif
}
void HandleSet(StringView name, const char *value);
void Finish(unsigned default_port);
};
/**
* Load and parse the specified configuration file. Throws an
* exception on error.
*/
void
LoadConfigFile(BpConfig &config, const char *path);
| 24.742268 | 82 | 0.74375 | nn6n |
288511bf23e83f6efbf7f5bcf6be5bee633d6b90 | 8,823 | cpp | C++ | sources/Platform/Linux/LinuxWindow.cpp | NoFr1ends/LLGL | 837fa70f151e2caeb1bd4122fcd4eb672080efa5 | [
"BSD-3-Clause"
] | null | null | null | sources/Platform/Linux/LinuxWindow.cpp | NoFr1ends/LLGL | 837fa70f151e2caeb1bd4122fcd4eb672080efa5 | [
"BSD-3-Clause"
] | null | null | null | sources/Platform/Linux/LinuxWindow.cpp | NoFr1ends/LLGL | 837fa70f151e2caeb1bd4122fcd4eb672080efa5 | [
"BSD-3-Clause"
] | null | null | null | /*
* LinuxWindow.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <LLGL/Platform/NativeHandle.h>
#include <LLGL/Display.h>
#include "LinuxWindow.h"
#include "MapKey.h"
#include <exception>
namespace LLGL
{
static Offset2D GetScreenCenteredPosition(const Extent2D& size)
{
if (auto display = Display::InstantiatePrimary())
{
const auto resolution = display->GetDisplayMode().resolution;
return
{
static_cast<int>((resolution.width - size.width )/2),
static_cast<int>((resolution.height - size.height)/2),
};
}
return {};
}
std::unique_ptr<Window> Window::Create(const WindowDescriptor& desc)
{
return std::unique_ptr<Window>(new LinuxWindow(desc));
}
LinuxWindow::LinuxWindow(const WindowDescriptor& desc) :
desc_ { desc }
{
OpenWindow();
}
LinuxWindow::~LinuxWindow()
{
XDestroyWindow(display_, wnd_);
XCloseDisplay(display_);
}
void LinuxWindow::GetNativeHandle(void* nativeHandle) const
{
auto& handle = *reinterpret_cast<NativeHandle*>(nativeHandle);
handle.display = display_;
handle.window = wnd_;
handle.visual = visual_;
}
void LinuxWindow::ResetPixelFormat()
{
// dummy
}
Extent2D LinuxWindow::GetContentSize() const
{
/* Return the size of the client area */
return GetSize(true);
}
void LinuxWindow::SetPosition(const Offset2D& position)
{
/* Move window and store new position */
XMoveWindow(display_, wnd_, position.x, position.y);
desc_.position = position;
}
Offset2D LinuxWindow::GetPosition() const
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
return { attribs.x, attribs.y };
}
void LinuxWindow::SetSize(const Extent2D& size, bool useClientArea)
{
XResizeWindow(display_, wnd_, size.width, size.height);
}
Extent2D LinuxWindow::GetSize(bool useClientArea) const
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
return Extent2D
{
static_cast<std::uint32_t>(attribs.width),
static_cast<std::uint32_t>(attribs.height)
};
}
void LinuxWindow::SetTitle(const std::wstring& title)
{
/* Convert UTF16 to UTF8 string (X11 limitation) and set window title */
std::string s(title.begin(), title.end());
XStoreName(display_, wnd_, s.c_str());
}
std::wstring LinuxWindow::GetTitle() const
{
return std::wstring();
}
void LinuxWindow::Show(bool show)
{
if (show)
{
/* Map window and reset window position */
XMapWindow(display_, wnd_);
XMoveWindow(display_, wnd_, desc_.position.x, desc_.position.y);
}
else
XUnmapWindow(display_, wnd_);
if (desc_.borderless)
XSetInputFocus(display_, (show ? wnd_ : None), RevertToParent, CurrentTime);
}
bool LinuxWindow::IsShown() const
{
return false;
}
void LinuxWindow::SetDesc(const WindowDescriptor& desc)
{
//todo...
}
WindowDescriptor LinuxWindow::GetDesc() const
{
return desc_; //todo...
}
void LinuxWindow::OnProcessEvents()
{
XEvent event;
XPending(display_);
while (XQLength(display_))
{
XNextEvent(display_, &event);
switch (event.type)
{
case KeyPress:
ProcessKeyEvent(event.xkey, true);
break;
case KeyRelease:
ProcessKeyEvent(event.xkey, false);
break;
case ButtonPress:
ProcessMouseKeyEvent(event.xbutton, true);
break;
case ButtonRelease:
ProcessMouseKeyEvent(event.xbutton, false);
break;
case Expose:
ProcessExposeEvent();
break;
case MotionNotify:
ProcessMotionEvent(event.xmotion);
break;
case DestroyNotify:
PostQuit();
break;
case ClientMessage:
ProcessClientMessage(event.xclient);
break;
}
}
XFlush(display_);
}
/*
* ======= Private: =======
*/
void LinuxWindow::OpenWindow()
{
/* Get native context handle */
auto nativeHandle = reinterpret_cast<const NativeContextHandle*>(desc_.windowContext);
if (nativeHandle)
{
/* Get X11 display from context handle */
display_ = nativeHandle->display;
visual_ = nativeHandle->visual;
}
else
{
/* Open X11 display */
display_ = XOpenDisplay(nullptr);
visual_ = nullptr;
}
if (!display_)
throw std::runtime_error("failed to open X11 display");
/* Setup common parameters for window creation */
::Window rootWnd = (nativeHandle != nullptr ? nativeHandle->parentWindow : DefaultRootWindow(display_));
int screen = (nativeHandle != nullptr ? nativeHandle->screen : DefaultScreen(display_));
::Visual* visual = (nativeHandle != nullptr ? nativeHandle->visual->visual : DefaultVisual(display_, screen));
int depth = (nativeHandle != nullptr ? nativeHandle->visual->depth : DefaultDepth(display_, screen));
int borderSize = 0;
/* Setup window attributes */
XSetWindowAttributes attribs;
attribs.background_pixel = WhitePixel(display_, screen);
attribs.border_pixel = 0;
attribs.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask);
unsigned long valueMask = CWEventMask | CWBorderPixel;//(CWColormap | CWEventMask | CWOverrideRedirect)
if (nativeHandle)
{
valueMask |= CWColormap;
attribs.colormap = nativeHandle->colorMap;
}
else
valueMask |= CWBackPixel;
if (desc_.borderless) //WARNING -> input no longer works
{
valueMask |= CWOverrideRedirect;
attribs.override_redirect = true;
}
/* Get final window position */
if (desc_.centered)
desc_.position = GetScreenCenteredPosition(desc_.size);
/* Create X11 window */
wnd_ = XCreateWindow(
display_,
rootWnd,
desc_.position.x,
desc_.position.y,
desc_.size.width,
desc_.size.height,
borderSize,
depth,
InputOutput,
visual,
valueMask,
(&attribs)
);
/* Set title and show window (if enabled) */
SetTitle(desc_.title);
/* Show window */
if (desc_.visible)
Show();
/* Prepare borderless window */
if (desc_.borderless)
{
XGrabKeyboard(display_, wnd_, True, GrabModeAsync, GrabModeAsync, CurrentTime);
XGrabPointer(display_, wnd_, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, wnd_, None, CurrentTime);
}
/* Enable WM_DELETE_WINDOW protocol */
closeWndAtom_ = XInternAtom(display_, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display_, wnd_, &closeWndAtom_, 1);
}
void LinuxWindow::ProcessKeyEvent(XKeyEvent& event, bool down)
{
auto key = MapKey(event);
if (down)
PostKeyDown(key);
else
PostKeyUp(key);
}
void LinuxWindow::ProcessMouseKeyEvent(XButtonEvent& event, bool down)
{
switch (event.button)
{
case Button1:
PostMouseKeyEvent(Key::LButton, down);
break;
case Button2:
PostMouseKeyEvent(Key::MButton, down);
break;
case Button3:
PostMouseKeyEvent(Key::RButton, down);
break;
case Button4:
PostWheelMotion(1);
break;
case Button5:
PostWheelMotion(-1);
break;
}
}
void LinuxWindow::ProcessExposeEvent()
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
const Extent2D size
{
static_cast<std::uint32_t>(attribs.width),
static_cast<std::uint32_t>(attribs.height)
};
PostResize(size);
}
void LinuxWindow::ProcessClientMessage(XClientMessageEvent& event)
{
Atom atom = static_cast<Atom>(event.data.l[0]);
if (atom == closeWndAtom_)
PostQuit();
}
void LinuxWindow::ProcessMotionEvent(XMotionEvent& event)
{
const Offset2D mousePos { event.x, event.y };
PostLocalMotion(mousePos);
PostGlobalMotion({ mousePos.x - prevMousePos_.x, mousePos.y - prevMousePos_.y });
prevMousePos_ = mousePos;
}
void LinuxWindow::PostMouseKeyEvent(Key key, bool down)
{
if (down)
PostKeyDown(key);
else
PostKeyUp(key);
}
} // /namespace LLGL
// ================================================================================
| 24.714286 | 139 | 0.613737 | NoFr1ends |
28860ae214f32e95d2218a6f6437461182ed6b67 | 872 | cxx | C++ | painty/core/test/src/KubelkaMunkTest.cxx | lindemeier/painty | 792cac6655b3707805ffc68d902f0e675a7770b8 | [
"MIT"
] | 15 | 2020-04-22T15:18:28.000Z | 2022-03-24T07:48:28.000Z | painty/core/test/src/KubelkaMunkTest.cxx | lindemeier/painty | 792cac6655b3707805ffc68d902f0e675a7770b8 | [
"MIT"
] | 25 | 2020-04-18T18:55:50.000Z | 2021-05-30T21:26:39.000Z | painty/core/test/src/KubelkaMunkTest.cxx | lindemeier/painty | 792cac6655b3707805ffc68d902f0e675a7770b8 | [
"MIT"
] | 2 | 2020-09-16T05:55:54.000Z | 2021-01-09T12:09:43.000Z | /**
* @file KubelkaMunkTest.cxx
* @author thomas lindemeier
*
* @brief
*
* @date 2020-05-14
*
*/
#include "gtest/gtest.h"
#include "painty/core/KubelkaMunk.hxx"
TEST(KubelkaMunk, Reflectance) {
constexpr auto Eps = 0.00001;
const auto d = 0.5;
const painty::vec<double, 3U> k = {0.2, 0.1, 0.22};
const painty::vec<double, 3U> s = {0.124, 0.658, 0.123};
const painty::vec<double, 3U> r0 = {0.65, 0.2, 0.2146};
const auto r1 = painty::ComputeReflectance(k, s, r0, d);
EXPECT_NEAR(r1[0], 0.541596, Eps);
EXPECT_NEAR(r1[1], 0.343822, Eps);
EXPECT_NEAR(r1[2], 0.206651, Eps);
EXPECT_NEAR(painty::ComputeReflectance(k, s, r0, 0.0)[0], r0[0], Eps);
const painty::vec<double, 3U> s2 = {0.0, 0.0, 0.0};
EXPECT_NEAR(painty::ComputeReflectance(k, s2, r0, d)[0], 0.53217499727638173,
Eps);
}
| 27.25 | 79 | 0.598624 | lindemeier |
2887edc208ada4e07f89e8459df6bc8b4032330b | 6,198 | cpp | C++ | test/json2sql/enum_record_set.cpp | slotix/json2sql | bed76cad843a11dcee6d96b58ee6b4a84f4f67a3 | [
"BSD-3-Clause"
] | 8 | 2018-03-05T04:14:44.000Z | 2021-12-22T03:18:16.000Z | test/json2sql/enum_record_set.cpp | slotix/json2sql | bed76cad843a11dcee6d96b58ee6b4a84f4f67a3 | [
"BSD-3-Clause"
] | 10 | 2018-02-23T22:09:07.000Z | 2019-06-06T17:29:26.000Z | test/json2sql/enum_record_set.cpp | slotix/json2sql | bed76cad843a11dcee6d96b58ee6b4a84f4f67a3 | [
"BSD-3-Clause"
] | 7 | 2018-04-06T00:16:43.000Z | 2020-06-26T13:32:47.000Z | //
// Created by sn0w1eo on 26.02.18.
//
#include <gtest/gtest.h>
#include <hash_table.hpp>
#include <enum_table.hpp>
#include "enum_record_set.hpp"
namespace {
using rapidjson::Value;
using namespace DBConvert::Structures;
class EnumRecordSetTest : public ::testing::Test {
protected:
void SetUp() {
any_value_ptr = new Value;
any_value_ptr->SetString("Any Value");
any_value_ptr2 = new Value;
any_value_ptr2->SetDouble(42.42);
parent_title = new Value;
parent_title->SetString("Parent Table");
child_title = new Value;
child_title->SetString("Child Table");
parent_table = new EnumTable(1, parent_title, 0, nullptr);
child_table = new EnumTable(2, child_title, 0, parent_table);
parent_rs = parent_table->get_record_set();
child_rs = child_table->get_record_set();
}
void TearDown() {
parent_rs = nullptr;
child_rs = nullptr;
delete parent_table;
delete child_table;
delete parent_title;
delete child_title;
delete any_value_ptr;
delete any_value_ptr2;
}
Value * parent_title;
Value * child_title;
Table * parent_table;
Table * child_table;
RecordSet * parent_rs;
RecordSet * child_rs;
Value * any_value_ptr;
Value * any_value_ptr2;
};
TEST_F(EnumRecordSetTest, CtorOwnerTableNullException) {
try {
EnumRecordSet ers(nullptr);
FAIL();
} catch (const ERROR_CODES & err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_Ctor_OwnerTableUndefined);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackIdFieldInCtorAsFirstElement) {
EnumRecordSet ers(parent_table);
EXPECT_TRUE( strcmp(ers.get_fields()->at(0)->get_title(), COLUMN_TITLES::PRIMARY_KEY_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackRefIdFieldAsSecondElementIfParentExists) { ;
EnumRecordSet ers(child_table);
EXPECT_TRUE( strcmp(ers.get_fields()->at(1)->get_title(), COLUMN_TITLES::REFERENCE_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackEnumFieldAsThirdElementIfParentExists) {
EnumRecordSet child_rs(child_table);
EXPECT_TRUE( strcmp(child_rs.get_fields()->at(2)->get_title(), COLUMN_TITLES::ENUM_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackEnumFieldAsSecondElementIfNoParent) {
EnumRecordSet parent_rs(parent_table);
EXPECT_TRUE( strcmp(parent_rs.get_fields()->at(1)->get_title(), COLUMN_TITLES::ENUM_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, AddRecordNullValuePtrException) {
try {
parent_rs->add_record(nullptr);
FAIL();
} catch (const ERROR_CODES err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_AddRecord_ValueUndefined);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, AddRecordIncreaseCurrentIdEachTime) {
parent_rs->add_record(any_value_ptr);
EXPECT_EQ(parent_rs->get_current_id(), 1);
parent_rs->add_record(any_value_ptr2);
EXPECT_EQ(parent_rs->get_current_id(), 2);
EXPECT_EQ(parent_rs->get_records()->size(), 2);
}
TEST_F(EnumRecordSetTest, AddRecordAddsNewRecordWithIdAndValueInEnumField) {
Field * id_field = parent_rs->get_fields()->at(0);
Field * enum_field = parent_rs->get_fields()->at(1); // if ParentTable exists enum_field will be ->at(2) otherwise ->at(1)
parent_rs->add_record(any_value_ptr);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(id_field)->GetInt64(), 1);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(enum_field), any_value_ptr);
parent_rs->add_record(any_value_ptr2);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(id_field)->GetInt64(), 2);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(enum_field), any_value_ptr2);
}
TEST_F(EnumRecordSetTest, AddRecordAddsNewRecordWithIdRefIfParentTableExists) {
parent_rs->add_record(any_value_ptr);
child_rs->add_record(any_value_ptr2);
Field * child_ref_id_field = child_rs->get_fields()->at(1);
uint64_t parent_current_id = parent_rs->get_current_id();
uint64_t child_ref_id = child_rs->get_records()->back()->get_value(child_ref_id_field)->GetUint64();
EXPECT_EQ(child_ref_id, parent_current_id);
}
TEST_F(EnumRecordSetTest, AddRecordExceptionIfParentExistsButParentCurrentIdRecordIsZero) {
try{
child_rs->add_record(any_value_ptr);
FAIL();
} catch(const ERROR_CODES & err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_AddRecord_ParentTableCurrentIdRecordIsZero);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, AddRecordUpdatesEnumField) {
Field * enum_field = parent_rs->get_fields()->at(1); // 1 if parent table, 2 child if child table
EXPECT_EQ(enum_field->get_length(), 0);
Value v1; v1.SetInt(12); // length is sizeof(uint32_t)
parent_rs->add_record(&v1);
EXPECT_EQ(enum_field->get_length(), sizeof(uint32_t));
Value v2; v2.SetString("123456789"); // length is 9
parent_rs->add_record(&v2);
EXPECT_EQ(enum_field->get_length(), strlen(v2.GetString()));
}
TEST_F(EnumRecordSetTest, AddNullRecordAddsValueSetNullToRecords) {
Field * enum_field = parent_rs->get_fields()->at(1); // 1 if parent table, 2 child if child table
parent_rs->add_null_record();
Record * added_record = parent_rs->get_records()->back();
EXPECT_TRUE( added_record->get_value(enum_field)->IsNull() );
parent_rs->add_null_record();
added_record = parent_rs->get_records()->back();
EXPECT_TRUE( added_record->get_value(enum_field)->IsNull() );
EXPECT_EQ( parent_rs->get_records()->size(), 2);
}
} | 38.496894 | 132 | 0.647306 | slotix |
288bc24fb2022d139bf8d20be6b86508c0df0c25 | 12,073 | cc | C++ | src/rm/RequestManagerVirtualRouter.cc | vidister/one | 3baad262f81694eb182f9accb5dd576f5596f3b0 | [
"Apache-2.0"
] | 1 | 2019-11-21T09:33:40.000Z | 2019-11-21T09:33:40.000Z | src/rm/RequestManagerVirtualRouter.cc | vidister/one | 3baad262f81694eb182f9accb5dd576f5596f3b0 | [
"Apache-2.0"
] | null | null | null | src/rm/RequestManagerVirtualRouter.cc | vidister/one | 3baad262f81694eb182f9accb5dd576f5596f3b0 | [
"Apache-2.0"
] | 2 | 2020-03-09T09:11:41.000Z | 2020-04-01T13:38:20.000Z | /* -------------------------------------------------------------------------- */
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "RequestManagerVirtualRouter.h"
#include "RequestManagerVMTemplate.h"
#include "RequestManagerVirtualMachine.h"
#include "PoolObjectAuth.h"
#include "Nebula.h"
#include "DispatchManager.h"
#include "VirtualRouterPool.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
RequestManagerVirtualRouter::RequestManagerVirtualRouter(const string& method_name,
const string& help,
const string& params)
: Request(method_name, params, help)
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
auth_op = AuthRequest::MANAGE;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterInstantiate::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
int n_vms = xmlrpc_c::value_int(paramList.getInt(2));
int tmpl_id = xmlrpc_c::value_int(paramList.getInt(3));
string name = xmlrpc_c::value_string(paramList.getString(4));
bool on_hold = xmlrpc_c::value_boolean(paramList.getBoolean(5));
string str_uattrs = xmlrpc_c::value_string(paramList.getString(6));
Nebula& nd = Nebula::instance();
VirtualRouterPool* vrpool = nd.get_vrouterpool();
VirtualRouter * vr;
DispatchManager* dm = nd.get_dm();
VMTemplatePool* tpool = nd.get_tpool();
PoolObjectAuth vr_perms;
Template* extra_attrs;
string error;
string vr_name, tmp_name;
ostringstream oss;
vector<int> vms;
vector<int>::iterator vmid;
int vid;
/* ---------------------------------------------------------------------- */
/* Get the Virtual Router NICs */
/* ---------------------------------------------------------------------- */
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
extra_attrs = vr->get_vm_template();
vr_name = vr->get_name();
if (tmpl_id == -1)
{
tmpl_id = vr->get_template_id();
}
vr->unlock();
if (tmpl_id == -1)
{
att.resp_msg = "A template ID was not provided, and the virtual router "
"does not have a default one";
failure_response(ACTION, att);
return;
}
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
VMTemplate * tmpl = tpool->get_ro(tmpl_id);
if ( tmpl == 0 )
{
att.resp_id = tmpl_id;
att.resp_obj = PoolObjectSQL::TEMPLATE;
failure_response(NO_EXISTS, att);
return;
}
bool is_vrouter = tmpl->is_vrouter();
tmpl->unlock();
if (!is_vrouter)
{
att.resp_msg = "Only virtual router templates are allowed";
failure_response(ACTION, att);
return;
}
if (name.empty())
{
name = "vr-" + vr_name + "-%i";
}
VMTemplateInstantiate tmpl_instantiate;
for (int i=0; i<n_vms; oss.str(""), i++)
{
oss << i;
tmp_name = one_util::gsub(name, "%i", oss.str());
ErrorCode ec = tmpl_instantiate.request_execute(tmpl_id, tmp_name,
true, str_uattrs, extra_attrs, vid, att);
if (ec != SUCCESS)
{
failure_response(ec, att);
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
dm->delete_vm(*vmid, att, att.resp_msg);
}
return;
}
vms.push_back(vid);
}
vr = vrpool->get(vrid);
if (vr != 0)
{
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
vr->add_vmid(*vmid);
}
vr->set_template_id(tmpl_id);
vrpool->update(vr);
vr->unlock();
}
// VMs are created on hold to wait for all of them to be created
// successfully, to avoid the rollback dm->finalize call on prolog
if (!on_hold)
{
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
dm->release(*vmid, att, att.resp_msg);
}
}
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterAttachNic::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
VirtualRouterPool* vrpool = static_cast<VirtualRouterPool*>(pool);
VirtualRouter * vr;
VectorAttribute* nic;
VectorAttribute* nic_bck;
VirtualMachineTemplate tmpl;
PoolObjectAuth vr_perms;
int rc;
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
string str_tmpl = xmlrpc_c::value_string(paramList.getString(2));
// -------------------------------------------------------------------------
// Parse NIC template
// -------------------------------------------------------------------------
rc = tmpl.parse_str_or_xml(str_tmpl, att.resp_msg);
if ( rc != 0 )
{
failure_response(INTERNAL, att);
return;
}
// -------------------------------------------------------------------------
// Authorize the operation & check quotas
// -------------------------------------------------------------------------
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
vr->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
VirtualRouter::set_auth_request(att.uid, ar, &tmpl, true); // USE VNET
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
RequestAttributes att_quota(vr_perms.uid, vr_perms.gid, att);
if ( quota_authorization(&tmpl, Quotas::VIRTUALROUTER, att_quota) == false )
{
return;
}
// -------------------------------------------------------------------------
// Attach NIC to the Virtual Router
// -------------------------------------------------------------------------
vr = vrpool->get(vrid);
if (vr == 0)
{
quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
nic = vr->attach_nic(&tmpl, att.resp_msg);
if ( nic != 0 )
{
nic_bck = nic->clone();
}
set<int> vms = vr->get_vms();
vrpool->update(vr);
vr->unlock();
if (nic == 0)
{
quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);
failure_response(ACTION, att);
return;
}
// -------------------------------------------------------------------------
// Attach NIC to each VM
// -------------------------------------------------------------------------
VirtualMachineAttachNic vm_attach_nic;
for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
{
VirtualMachineTemplate tmpl;
tmpl.set(nic_bck->clone());
ErrorCode ec = vm_attach_nic.request_execute(*vmid, tmpl, att);
if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
{
delete nic_bck;
failure_response(ACTION, att);
return;
}
}
delete nic_bck;
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterDetachNic::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
VirtualRouterPool* vrpool = static_cast<VirtualRouterPool*>(pool);
VirtualRouter * vr;
PoolObjectAuth vr_perms;
int rc;
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
int nic_id = xmlrpc_c::value_int(paramList.getInt(2));
// -------------------------------------------------------------------------
// Authorize the operation
// -------------------------------------------------------------------------
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
vr->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
// -------------------------------------------------------------------------
// Detach the NIC from the Virtual Router
// -------------------------------------------------------------------------
vr = vrpool->get(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
rc = vr->detach_nic(nic_id);
set<int> vms = vr->get_vms();
vrpool->update(vr);
vr->unlock();
if (rc != 0)
{
ostringstream oss;
oss << "NIC with NIC_ID " << nic_id << " does not exist.";
att.resp_msg = oss.str();
failure_response(Request::ACTION, att);
return;
}
// -------------------------------------------------------------------------
// Detach NIC from each VM
// -------------------------------------------------------------------------
VirtualMachineDetachNic vm_detach_nic;
for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
{
ErrorCode ec = vm_detach_nic.request_execute(*vmid, nic_id, att);
if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
{
failure_response(Request::ACTION, att);
return;
}
}
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
| 28.745238 | 83 | 0.455562 | vidister |
288cfffdcaf3e3d50d5fe581c917ddd589663956 | 2,955 | cpp | C++ | Engine/databaseadmincsvformat.cpp | vadkasevas/BAS | 657f62794451c564c77d6f92b2afa9f5daf2f517 | [
"MIT"
] | 302 | 2016-05-20T12:55:23.000Z | 2022-03-29T02:26:14.000Z | Engine/databaseadmincsvformat.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 9 | 2016-07-21T09:04:50.000Z | 2021-05-16T07:34:42.000Z | Engine/databaseadmincsvformat.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 113 | 2016-05-18T07:48:37.000Z | 2022-02-26T12:59:39.000Z | #include "databaseadmincsvformat.h"
#include "ui_databaseadmincsvformat.h"
#include <QDir>
#include <QFileDialog>
#include <QDebug>
DatabaseAdminCsvFormat::DatabaseAdminCsvFormat(QWidget *parent) :
QDialog(parent),
ui(new Ui::DatabaseAdminCsvFormat)
{
ui->setupUi(this);
connect(ui->DragSectionCombo,SIGNAL(ChangedDragSection()),this,SLOT(ChangedDragSection()));
IsExport = true;
ui->LabelValidation->setVisible(false);
IsCsv = true;
}
QString DatabaseAdminCsvFormat::GetExtension()
{
return (IsCsv)?".csv":".xls";
}
void DatabaseAdminCsvFormat::SetXls()
{
IsCsv = false;
setWindowTitle("Xls");
}
QString DatabaseAdminCsvFormat::GetFileName()
{
return ui->FileName->text();
}
void DatabaseAdminCsvFormat::SetIsExport(bool IsExport)
{
this->IsExport = IsExport;
if(IsExport)
{
QString randomString;
{
QString possibleCharacters("abcdefghijklmnopqrstuvwxyz");
int randomStringLength = 10;
for(int i=0; i<randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
}
ui->FileName->setText(QDir::cleanPath(QDir::currentPath() + QDir::separator() + randomString + GetExtension()));
}
}
void DatabaseAdminCsvFormat::ChangedDragSection()
{
QStringList res;
foreach(int i, ui->DragSectionCombo->SelectedItems())
{
res.append(Columns[i].Name);
}
ui->FormatResult->setText(res.join(":"));
}
void DatabaseAdminCsvFormat::SetDatabaseColumns(QList<DatabaseColumn> Columns)
{
this->Columns = Columns;
QStringList List;
QList<int> Items;
int index = 0;
foreach(DatabaseColumn Column, Columns)
{
List.append(Column.Description);
Items.append(index);
index++;
}
ui->DragSectionCombo->SetData(List,Items);
ChangedDragSection();
}
QList<int> DatabaseAdminCsvFormat::GetColumnIds()
{
QList<int> res;
foreach(int i, ui->DragSectionCombo->SelectedItems())
{
res.append(Columns[i].Id);
}
return res;
}
DatabaseAdminCsvFormat::~DatabaseAdminCsvFormat()
{
delete ui;
}
void DatabaseAdminCsvFormat::on_OpenFileButton_clicked()
{
QString fileName;
if(IsExport)
fileName = QFileDialog::getSaveFileName(this, tr("Save"), "", tr("Csv Files (*.csv);;All Files (*.*)"));
else
fileName = QFileDialog::getOpenFileName(this, tr("Save"), "", tr("All Files (*.*);;Csv Files (*.csv)"));
if(fileName.length()>0)
{
ui->FileName->setText(fileName);
}
}
void DatabaseAdminCsvFormat::on_Ok_clicked()
{
if (IsExport || QFile::exists(GetFileName()))
{
accept();
} else
{
ui->LabelValidation->setVisible(true);
}
}
void DatabaseAdminCsvFormat::on_Cancel_clicked()
{
reject();
}
| 21.727941 | 120 | 0.643316 | vadkasevas |
288dbd960d6e8f1e0ae0e8e9da6520c15f44affb | 11,530 | cpp | C++ | src/VS/vlib/Hand.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | null | null | null | src/VS/vlib/Hand.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | 1 | 2015-11-15T08:20:33.000Z | 2018-03-04T09:48:23.000Z | src/VS/vlib/Hand.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | null | null | null | /*
Valet, a generalized Butler scorer for bridge.
Copyright (C) 2015 by Soren Hein.
See LICENSE and README.
*/
#include "stdafx.h"
#include <assert.h>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "valet.h"
#include "Pairs.h"
#include "Hand.h"
#include "scoring.h"
extern OptionsType options;
extern Pairs pairs;
typedef int (*fptrType)(int rawScore);
fptrType fptr;
//////////////////////////////////////////////////
// //
// General functions for all types of scoring //
// //
//////////////////////////////////////////////////
Hand::Hand()
{
Hand::Reset();
}
Hand::~Hand()
{
}
void Hand::Reset()
{
boardNo = 0;
numEntries = 0;
results.resize(HAND_CHUNK_SIZE);
length = HAND_CHUNK_SIZE;
}
int Hand::SetBoardNumber(
const unsigned n)
{
if (boardNo > 0 && n != boardNo)
return RETURN_BOARD_NUMBER_CHANGE;
boardNo = n;
GetVul(boardNo, vulNS, vulEW);
return RETURN_NO_FAULT;
}
unsigned Hand::GetBoardNumber()
{
return boardNo;
}
unsigned Hand::GetNumEntries()
{
return numEntries;
}
void Hand::AddResult(
const ResultType& res)
{
assert(boardNo > 0);
if (numEntries == length)
{
length += 8;
results.resize(length);
}
results[numEntries++] = res;
}
void Hand::ResetValetEntry(
ValetEntryType& entry)
{
entry.pairNo = 0;
entry.oppNo = 0;
entry.declFlag[0] = false;
entry.declFlag[1] = false;
entry.defFlag = false;
entry.leadFlag[0] = false;
entry.leadFlag[1] = false;
entry.overall = 0.;
entry.bidScore = 0.;
entry.playScore[0] = 0.;
entry.playScore[1] = 0.;
entry.leadScore[0] = 0.;
entry.leadScore[1] = 0.;
entry.defScore = 0.;
}
const unsigned Hswap[2][2] = { {0, 1}, {1, 0} };
void Hand::SetPairSwaps(
const ResultType& res,
ValetEntryType& entry,
unsigned& decl,
unsigned& leader)
{
// This function takes care of assigning the scores to the right
// players within a pair. pairNo is negative if the players are
// internally stored in the opposite order to the one that happens
// to be at the table.
unsigned swapNS, swapEW;
int pairNoNS = pairs.GetPairNumber(res.north, res.south);
assert(pairNoNS != 0);
if (pairNoNS < 0)
{
entry.pairNo = static_cast<unsigned>(-pairNoNS);
swapNS = 1;
}
else
{
entry.pairNo = static_cast<unsigned>(pairNoNS);
swapNS = 0;
}
int pairNoEW = pairs.GetPairNumber(res.east, res.west);
assert(pairNoEW != 0);
if (pairNoEW < 0)
{
entry.oppNo = static_cast<unsigned>(-pairNoEW);
swapEW = 1;
}
else
{
entry.oppNo = static_cast<unsigned>(pairNoEW);
swapEW = 0;
}
if (res.declarer == VALET_NORTH || res.declarer == VALET_SOUTH)
{
decl = Hswap[swapNS][res.declarer == VALET_SOUTH];
leader = Hswap[swapEW][res.declarer == VALET_SOUTH];
}
else if (res.declarer == VALET_EAST || res.declarer == VALET_WEST)
{
decl = Hswap[swapEW][res.declarer == VALET_WEST];
leader = Hswap[swapNS][res.declarer == VALET_EAST];
}
else
{
decl = 0;
leader = 0;
assert(false);
}
}
void Hand::SetPassout(
const ResultType& res,
const float totalIMPs,
ValetEntryType& entry)
{
// Pass-out.
int pairNoNS = pairs.GetPairNumber(res.north, res.south);
assert(pairNoNS != 0);
if (pairNoNS < 0)
pairNoNS = -pairNoNS; // Doesn't matter for pass-out
int pairNoEW = pairs.GetPairNumber(res.east, res.west);
assert(pairNoEW != 0);
if (pairNoEW < 0)
pairNoEW = -pairNoEW; // Doesn't matter for pass-out
entry.pairNo = static_cast<unsigned>(pairNoNS);
entry.oppNo = static_cast<unsigned>(pairNoEW);
entry.overall = totalIMPs;
entry.bidScore = totalIMPs;
}
void Hand::SetPlayResult(
const ResultType& res,
const float totalIMPs,
const float bidIMPs,
const float leadIMPs,
ValetEntryType& entry)
{
unsigned decl, leader;
Hand::SetPairSwaps(res, entry, decl, leader);
// All IMPs are seen from NS's side up to here.
float sign = 1.f;
if (res.declarer == VALET_EAST || res.declarer == VALET_WEST)
{
sign = -1.f;
unsigned tmp = entry.pairNo;
entry.pairNo = entry.oppNo;
entry.oppNo = tmp;
}
entry.declFlag[decl] = true;
entry.defFlag = true;
entry.leadFlag[leader] = true;
entry.overall = sign * totalIMPs;
entry.bidScore = sign * bidIMPs;
entry.playScore[decl] = sign * (totalIMPs - bidIMPs);
if (options.leadFlag && res.leadRank > 0)
{
entry.leadScore[leader] = - sign * leadIMPs;
entry.defScore = sign * (bidIMPs - totalIMPs + leadIMPs);
}
else
entry.defScore = sign * (bidIMPs - totalIMPs);
}
//////////////////////////////////////////////////
// //
// Functions only for datum scoring (Butler) //
// //
//////////////////////////////////////////////////
int Hand::GetDatum(
const vector<int>& rawScore)
{
// Datum score (average), rounded to nearest 10.
// This is used for Butler scoring.
int datum = 0;
int dmin = 9999, dmax = -9999;
for (unsigned i = 0; i < numEntries; i++)
{
if (rawScore[i] < dmin)
dmin = rawScore[i];
if (rawScore[i] > dmax)
dmax = rawScore[i];
datum += rawScore[i];
}
if (options.datumFilter && numEntries > 2)
datum = (datum-dmin-dmax) / static_cast<int>(numEntries-2);
else
datum = datum / static_cast<int>(numEntries);
return datum;
}
float Hand::GetDatumBidding(
const ResultType& res,
const unsigned vul,
const unsigned resMatrix[5][14],
const int datum)
{
// This is used for Butler scoring.
// We calculate the IMPs (across-the-field style) for our own
// contract if we get an average declarer of our denomination
// (playing from our side), and we compare this to the datum.
// This gives us the bidding performance, in a way.
float bidIMPs = 0.;
unsigned count = 0;
unsigned d = res.denom;
for (unsigned t = 0; t <= 13; t++)
{
if (resMatrix[d][t] == 0)
continue;
int artifScore = CalculateRawScore(res, vul, t);
bidIMPs += resMatrix[d][t] *
static_cast<float>(CalculateIMPs(artifScore - datum));
count += resMatrix[d][t];
}
assert(count > 0);
return (bidIMPs / count);
}
//////////////////////////////////////////////////
// //
// Functions only for IAF scoring and MPs //
// //
//////////////////////////////////////////////////
float Hand::GetOverallScore(
const vector<int> rawScore,
const int score)
{
// For a given score, we calculate the average number of IMPs/MPs
// against all the other pairs. If we've seen the score before,
// we use a cached value.
map<int, float>::iterator it = scoreLookup.find(score);
if (it != scoreLookup.end())
return it->second;
float result = 0;
unsigned count = 0;
bool seenSelfFlag = false;
for (unsigned i = 0; i < numEntries; i++)
{
// Skip own score.
if (! seenSelfFlag && rawScore[i] == score)
{
seenSelfFlag = true;
continue;
}
result += static_cast<float>((*fptr)(score - rawScore[i]));
count++;
}
assert(count > 0);
return (scoreLookup[score] = result / count);
}
float Hand::GetBiddingScore(
const vector<int> rawScore,
const unsigned no,
const unsigned vul,
const unsigned resMatrix[5][14],
const float overallResult)
{
// This is analogous to GetDatumBidding for Butler scoring.
// We compare to all other scores, not to the datum.
float bidResult = 0.;
unsigned count = 0;
ResultType resArtif = results[no];
unsigned d = resArtif.denom;
for (unsigned t = 0; t <= 13; t++)
{
if (resMatrix[d][t] == 0)
continue;
// Make a synthetic result of our contract with different
// declarers (including ourselves, but that scores 0).
resArtif.tricks = t;
int artifScore = CalculateRawScore(resArtif, vul, t);
bidResult +=
resMatrix[d][t] * Hand::GetOverallScore(rawScore, artifScore);
count += resMatrix[d][t];
}
// Special case: If we're the only ones to play in a denomination,
// we somewhat arbitrarily assign the full score to the bidding.
if (count == 0)
return overallResult;
else
return bidResult / count;
}
//////////////////////////////////////////////////
// //
// General scoring function, uses above //
// //
//////////////////////////////////////////////////
vector<ValetEntryType> Hand::CalculateScores()
{
vector<int> rawScore(numEntries);
vector<unsigned> vulList(numEntries);
unsigned resDeclMatrix[4][5][14] = {0};
unsigned resDeclLeadMatrix[4][4][5][14] = {0};
for (unsigned i = 0; i < numEntries; i++)
{
unsigned decl = results[i].declarer;
unsigned denom = results[i].denom;
unsigned tricks = results[i].tricks;
vulList[i] = (decl == VALET_NORTH ||
decl == VALET_SOUTH ? vulNS : vulEW);
rawScore[i] = CalculateRawScore(results[i], vulList[i]);
resDeclMatrix[decl][denom][tricks]++;
if (options.leadFlag && results[i].leadRank > 0)
{
unsigned lead = results[i].leadDenom;
resDeclLeadMatrix[decl][lead][denom][tricks]++;
}
}
vector<ValetEntryType> entries(numEntries);
if (numEntries == 0)
return entries;
if (options.valet == VALET_IMPS)
{
int datum = Hand::GetDatum(rawScore);
float bidIMPs, bidLeadIMPs, leadIMPs = 0.f;
for (unsigned i = 0; i < numEntries; i++)
{
ValetEntryType& entry = entries[i];
Hand::ResetValetEntry(entry);
const ResultType& res = results[i];
float butlerIMPs = static_cast<float>(
CalculateIMPs(rawScore[i] - datum));
if (res.level == 0)
Hand::SetPassout(res, butlerIMPs, entry);
else
{
bidIMPs = GetDatumBidding(res, vulList[i],
resDeclMatrix[res.declarer], datum);
if (options.leadFlag && res.leadRank > 0)
{
bidLeadIMPs = GetDatumBidding(res, vulList[i],
resDeclLeadMatrix[res.declarer][res.leadDenom], datum);
leadIMPs = bidLeadIMPs - bidIMPs;
}
else
leadIMPs = 0.f;
Hand::SetPlayResult(res, butlerIMPs, bidIMPs, leadIMPs, entry);
}
}
}
else
{
if (options.valet == VALET_IMPS_ACROSS_FIELD)
fptr = &CalculateIMPs;
else if (options.valet == VALET_MATCHPOINTS)
fptr = &CalculateMPs;
else
assert(false);
scoreLookup.clear();
float bidIAF, bidLeadIAF, leadIAF = 0.f;
for (unsigned i = 0; i < numEntries; i++)
{
ValetEntryType& entry = entries[i];
Hand::ResetValetEntry(entry);
const ResultType& res = results[i];
float IAFs = Hand::GetOverallScore(rawScore, rawScore[i]);
if (res.level == 0)
Hand::SetPassout(res, IAFs, entry);
else
{
bidIAF = GetBiddingScore(rawScore, i, vulList[i],
resDeclMatrix[res.declarer], IAFs);
if (options.leadFlag && res.leadRank > 0)
{
bidLeadIAF = GetBiddingScore(rawScore, i, vulList[i],
resDeclLeadMatrix[res.declarer][res.leadDenom], IAFs);
leadIAF = bidLeadIAF - bidIAF;
}
else
leadIAF = 0.f;
Hand::SetPlayResult(res, IAFs, bidIAF, leadIAF, entry);
}
}
}
return entries;
}
| 23.06 | 71 | 0.590286 | valet-bridge |
2890a085007d30e34ab174ff9d044ef698241adf | 2,340 | hpp | C++ | include/range/v3/algorithm/copy.hpp | morinmorin/range-v3 | d911614f40dcbc05062cd3a398007270c86b2d65 | [
"MIT"
] | null | null | null | include/range/v3/algorithm/copy.hpp | morinmorin/range-v3 | d911614f40dcbc05062cd3a398007270c86b2d65 | [
"MIT"
] | null | null | null | include/range/v3/algorithm/copy.hpp | morinmorin/range-v3 | d911614f40dcbc05062cd3a398007270c86b2d65 | [
"MIT"
] | null | null | null | /// \file
// Range v3 library
//
// Copyright Eric Niebler 2013-present
//
// Use, modification and distribution is subject to 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)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_ALGORITHM_COPY_HPP
#define RANGES_V3_ALGORITHM_COPY_HPP
#include <functional>
#include <utility>
#include <range/v3/range_fwd.hpp>
#include <range/v3/algorithm/result_types.hpp>
#include <range/v3/iterator/concepts.hpp>
#include <range/v3/iterator/traits.hpp>
#include <range/v3/range/access.hpp>
#include <range/v3/range/concepts.hpp>
#include <range/v3/range/dangling.hpp>
#include <range/v3/range/traits.hpp>
#include <range/v3/utility/copy.hpp>
#include <range/v3/utility/static_const.hpp>
namespace ranges
{
/// \addtogroup group-algorithms
/// @{
template<typename I, typename O>
using copy_result = detail::in_out_result<I, O>;
struct cpp20_copy_fn
{
template<typename I, typename S, typename O>
constexpr auto operator()(I begin, S end, O out) const
-> CPP_ret(copy_result<I, O>)( //
requires input_iterator<I> && sentinel_for<S, I> && weakly_incrementable<O> &&
indirectly_copyable<I, O>)
{
for(; begin != end; ++begin, ++out)
*out = *begin;
return {begin, out};
}
template<typename Rng, typename O>
constexpr auto operator()(Rng && rng, O out) const
-> CPP_ret(copy_result<safe_iterator_t<Rng>, O>)( //
requires input_range<Rng> && weakly_incrementable<O> &&
indirectly_copyable<iterator_t<Rng>, O>)
{
return (*this)(begin(rng), end(rng), std::move(out));
}
};
struct RANGES_EMPTY_BASES copy_fn
: aux::copy_fn
, cpp20_copy_fn
{
using aux::copy_fn::operator();
using cpp20_copy_fn::operator();
};
/// \sa `copy_fn`
/// \ingroup group-algorithms
RANGES_INLINE_VARIABLE(copy_fn, copy)
namespace cpp20
{
using ranges::copy_result;
RANGES_INLINE_VARIABLE(cpp20_copy_fn, copy)
} // namespace cpp20
/// @}
} // namespace ranges
#endif // include guard
| 28.536585 | 94 | 0.631624 | morinmorin |
2891692a139096ff3c00c7d928507f9dadc410ae | 1,338 | cpp | C++ | obs-studio/plugins/win-dshow/dshow-plugin.cpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | obs-studio/plugins/win-dshow/dshow-plugin.cpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | obs-studio/plugins/win-dshow/dshow-plugin.cpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | #include <obs-module.h>
#include <strsafe.h>
#include <strmif.h>
#include "virtualcam-guid.h"
OBS_DECLARE_MODULE()
OBS_MODULE_USE_DEFAULT_LOCALE("win-dshow", "en-US")
MODULE_EXPORT const char *obs_module_description(void)
{
return "Windows DirectShow source/encoder";
}
extern void RegisterDShowSource();
extern void RegisterDShowEncoders();
#ifdef VIRTUALCAM_ENABLED
extern "C" struct obs_output_info virtualcam_info;
static bool vcam_installed(bool b64)
{
wchar_t cls_str[CHARS_IN_GUID];
wchar_t temp[MAX_PATH];
HKEY key = nullptr;
StringFromGUID2(CLSID_OBS_VirtualVideo, cls_str, CHARS_IN_GUID);
StringCbPrintf(temp, sizeof(temp), L"CLSID\\%s", cls_str);
DWORD flags = KEY_READ;
flags |= b64 ? KEY_WOW64_64KEY : KEY_WOW64_32KEY;
LSTATUS status = RegOpenKeyExW(HKEY_CLASSES_ROOT, temp, 0, flags, &key);
if (status != ERROR_SUCCESS) {
return false;
}
RegCloseKey(key);
return true;
}
#endif
bool obs_module_load(void)
{
RegisterDShowSource();
RegisterDShowEncoders();
#ifdef VIRTUALCAM_ENABLED
obs_register_output(&virtualcam_info);
bool installed = vcam_installed(false);
#else
bool installed = false;
#endif
obs_data_t *obs_settings = obs_data_create();
obs_data_set_bool(obs_settings, "vcamEnabled", installed);
obs_apply_private_data(obs_settings);
obs_data_release(obs_settings);
return true;
}
| 22.3 | 73 | 0.775037 | noelemahcz |
28937011bddc59ba74593117e770a2f406a5a089 | 13,827 | cpp | C++ | src/MIP_deamon.cpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | 1 | 2018-07-29T17:53:50.000Z | 2018-07-29T17:53:50.000Z | src/MIP_deamon.cpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | null | null | null | src/MIP_deamon.cpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | null | null | null | //MIP_deamon.cpp
//Author: Sivert Andresen Cubedo
//C++
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include <queue>
//LINUX
#include <signal.h>
//Local
#include "../include/LinuxException.hpp"
#include "../include/EventPoll.hpp"
#include "../include/RawSock.hpp"
#include "../include/AddressTypes.hpp"
#include "../include/MIPFrame.hpp"
#include "../include/CrossIPC.hpp"
#include "../include/CrossForkExec.hpp"
#include "../include/TimerWrapper.hpp"
enum update_sock_option
{
LOCAL_MIP = 1,
ARP_DISCOVERY = 2,
ARP_LOSTCONNECTION = 3,
ADVERTISEMENT = 4
};
struct ARPPair
{
bool reply; //if true then pair is not lost
MIPAddress mip; //dest mip
MACAddress mac; //dest mac
RawSock::MIPRawSock* sock; //socket to reach dest
};
/*
Globals
*/
std::vector<RawSock::MIPRawSock> raw_sock_vec; //(must keep order intact so not to invalidate ARPPairs)
std::vector<ARPPair> arp_pair_vec; //(can't have duplicates)
ChildProcess routing_deamon;
EventPoll epoll;
AnonymousSocketPacket transport_sock;
AnonymousSocket update_sock;
AnonymousSocket lookup_sock;
std::queue<std::pair<bool, MIPFrame>> lookup_queue; //pair <true if source mip is set, frame>
const int ARP_TIMEOUT = 2000; //in ms
/*
Send local mip discovery to update_sock.
Parameters:
mip local mip discovered
Return:
void
Global:
update_sock
*/
void sendLocalMip(MIPAddress mip)
{
std::uint8_t option = update_sock_option::LOCAL_MIP;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Send arp discovery with update_sock.
Parameters:
mip discovered address
Return:
void
Glboal:
update_sock
*/
void sendArpDiscovery(MIPAddress mip)
{
std::uint8_t option = update_sock_option::ARP_DISCOVERY;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Send arp lost connection with update_sock.
Parameters:
mip lost address
Return:
void
Global:
update_sock
*/
void sendArpLostConnection(MIPAddress mip)
{
std::uint8_t option = update_sock_option::ARP_LOSTCONNECTION;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Print arp_pair_vec.
Parameters:
Return:
void
Global:
arp_pair_vec
*/
void printARPTable()
{
std::printf("%s: %4s:\n", "MIP", "MAC");
for (auto & p : arp_pair_vec) {
std::printf("%d: %4x:%x:%x:%x:%x:%x\n", (int)p.mip, p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5]);
}
}
/*
Add pair to arp_pair_vec.
Parameters:
sock ref to sock that Node was discovered on
mip mip
mac mac
Return:
void
Global:
arp_pair_vec
*/
void addARPPair(RawSock::MIPRawSock & sock, MIPAddress mip, MACAddress mac)
{
ARPPair pair;
pair.reply = true;
pair.mip = mip;
pair.mac = mac;
pair.sock = &sock;
arp_pair_vec.push_back(pair);
printARPTable(); //debug
}
/*
Send response frame to pair.
Parameters:
pair ref to pair
Return:
void
*/
void sendResponseFrame(ARPPair & pair)
{
static MIPFrame mip_frame;
mip_frame.setMipTRA(MIPFrame::ZERO);
mip_frame.setMipDest(pair.mip);
mip_frame.setMipSource(pair.sock->getMip());
mip_frame.setMsgSize(0);
mip_frame.setMipTTL(0xff);
MACAddress dest = pair.mac;
MACAddress source = pair.sock->getMac();
mip_frame.setEthDest(dest);
mip_frame.setEthSource(source);
mip_frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
mip_frame.setMsg(mip_frame.getData(), mip_frame.getSize());
pair.sock->sendMipFrame(mip_frame);
}
/*
Send broadcast frame on sock.
Parameters:
sock ref to sock
Return:
void
*/
void sendBroadcastFrame(RawSock::MIPRawSock & sock)
{
static MIPFrame mip_frame;
mip_frame.setMipTRA(MIPFrame::A);
mip_frame.setMipDest(0xff);
mip_frame.setMipSource(sock.getMip());
mip_frame.setMsgSize(0);
mip_frame.setMipTTL(0xff);
static MACAddress dest{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
MACAddress source = sock.getMac();
mip_frame.setEthDest(dest);
mip_frame.setEthSource(source);
mip_frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
mip_frame.setMsg(mip_frame.getData(), mip_frame.getSize());
sock.sendMipFrame(mip_frame);
}
/*
Receive on transport_sock.
Parameters:
Return:
void
Global:
transport_sock
lookup_queue
raw_sock_vec
*/
void receiveTransportSock()
{
static MIPFrame frame;
if (frame.getMsgSize() != MIPFrame::MSG_MAX_SIZE) {
frame.setMsgSize(MIPFrame::MSG_MAX_SIZE);
}
MIPAddress dest;
std::size_t msg_size;
AnonymousSocketPacket::IovecWrapper<3> iov;
iov.setIndex(0, dest);
iov.setIndex(1, msg_size);
iov.setIndex(2, frame.getMsg(), frame.getMsgSize());
transport_sock.recviovec(iov);
if (frame.getMsgSize() != msg_size) {
frame.setMsgSize(msg_size);
}
//check if dest address is local, if so then send back to transport_deamon
if (std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s) { return s.getMip() == dest; }) != raw_sock_vec.end()) {
transport_sock.sendiovec(iov);
}
else {
frame.setMipTRA(MIPFrame::T);
frame.setMipDest(dest);
frame.setMipTTL(0xff);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
lookup_queue.emplace(false, frame);
lookup_sock.write(reinterpret_cast<char*>(&dest), sizeof(dest));
}
}
/*
Receive on lookup_sock.
Parameters:
Return:
void
Global:
lookup_sock
*/
void receiveLookupSock()
{
bool success;
lookup_sock.read(reinterpret_cast<char*>(&success), sizeof(success));
if (success) {
MIPAddress via;
lookup_sock.read(reinterpret_cast<char*>(&via), sizeof(via));
//check outgoing sockets
auto pair_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == via; });
if (pair_it != arp_pair_vec.end()) {
ARPPair pair = (*pair_it);
MIPFrame & frame = lookup_queue.front().second;
if (!lookup_queue.front().first) {
frame.setMipSource(pair.sock->getMip());
}
MACAddress eth_dest = pair.mac;
MACAddress eth_source = pair.sock->getMac();
frame.setEthDest(eth_dest);
frame.setEthSource(eth_source);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
pair.sock->sendMipFrame(frame);
}
//check if via is target is local
lookup_queue.pop();
}
else {
lookup_queue.pop();
}
}
/*
Receive on update_sock.
Parameters:
Return:
void
Global:
update_sock
arp_pair_vec
*/
void receiveUpdateSock()
{
//receive:
// to
// ad size
// ad
static MIPFrame frame;
MIPAddress dest_mip;
std::size_t ad_size;
update_sock.read(reinterpret_cast<char*>(&dest_mip), sizeof(dest_mip));
update_sock.read(reinterpret_cast<char*>(&ad_size), sizeof(ad_size));
frame.setMsgSize(ad_size);
update_sock.read(frame.getMsg(), ad_size);
auto pair_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == dest_mip; });
if (pair_it != arp_pair_vec.end()) {
ARPPair & pair = (*pair_it);
frame.setMipTRA(MIPFrame::R);
frame.setMipDest(pair.mip);
frame.setMipSource(pair.sock->getMip());
frame.setMipTTL(0xff);
MACAddress eth_dest = pair.mac;
MACAddress eth_source = pair.sock->getMac();
frame.setEthDest(eth_dest);
frame.setEthSource(eth_source);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
pair.sock->sendMipFrame(frame);
}
}
/*
Receive on raw sock.
Parameters:
sock ref to sock
Return:
void
Global:
update_sock
*/
void receiveRawSock(RawSock::MIPRawSock & sock)
{
static MIPFrame mip_frame;
sock.recvMipFrame(mip_frame);
int tra = mip_frame.getMipTRA();
MIPAddress source_mip = mip_frame.getMipSource();
MIPAddress dest_mip = mip_frame.getMipDest();
std::uint8_t option;
std::size_t msg_size = mip_frame.getMsgSize();
std::vector<ARPPair>::iterator arp_it;
switch (tra)
{
case MIPFrame::A:
arp_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == source_mip; });
if (arp_it == arp_pair_vec.end()) {
addARPPair(sock, mip_frame.getMipSource(), mip_frame.getEthSource());
sendArpDiscovery(source_mip);
sendResponseFrame(arp_pair_vec.back());
}
else {
arp_it->reply = true;
sendResponseFrame((*arp_it));
}
break;
case MIPFrame::ZERO:
arp_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == source_mip; });
if (arp_it == arp_pair_vec.end()) {
addARPPair(sock, mip_frame.getMipSource(), mip_frame.getEthSource());
sendArpDiscovery(source_mip);
}
else {
arp_it->reply = true;
}
break;
case MIPFrame::R:
//send ad to routing_deamon
//send:
// from
// ad size
// ad
option = update_sock_option::ADVERTISEMENT;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(std::uint8_t));
update_sock.write(reinterpret_cast<char*>(&source_mip), sizeof(source_mip));
update_sock.write(reinterpret_cast<char*>(&msg_size), sizeof(msg_size));
update_sock.write(mip_frame.getMsg(), msg_size);
break;
case MIPFrame::T:
//cache frame in lookup_queue
//send:
// mip
if (std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s) { return s.getMip() == dest_mip; }) == raw_sock_vec.end()) {
int ttl = mip_frame.getMipTTL();
if (ttl <= 0) {
//drop frame
std::cout << "ttl 0, dropping frame\n";
}
else {
mip_frame.setMipTTL(ttl - 1);
lookup_queue.emplace(true, mip_frame);
lookup_sock.write(reinterpret_cast<char*>(&dest_mip), sizeof(dest_mip));
}
}
else {
//send to transport deamon
AnonymousSocketPacket::IovecWrapper<3> iov;
iov.setIndex(0, source_mip);
iov.setIndex(1, msg_size);
iov.setIndex(2, mip_frame.getMsg(), msg_size);
transport_sock.sendiovec(iov);
}
break;
default:
throw std::runtime_error("Invalid TRA");
break;
}
}
/*
Init raw_sock_vec.
Parameters:
mip_vec ref to vec containing mip
Return:
void
*/
void initRawSock(const std::vector<MIPAddress> & mip_vec)
{
auto inter_names = RawSock::getInterfaceNames(std::vector<int>{ AF_PACKET });
for (auto & mip : mip_vec) {
if (inter_names.empty()) {
//debug
std::cout << raw_sock_vec.size() << " interfaces detected.\n";
return;
}
std::string & name = inter_names.back();
if (name == "lo") {
continue;
}
raw_sock_vec.push_back(RawSock::MIPRawSock(name, mip));
//debug
std::cout << raw_sock_vec.back().toString() << "\n";
inter_names.pop_back();
}
//debug
std::cout << raw_sock_vec.size() << " interfaces detected.\n";
}
/*
Signal function.
*/
void sigintHandler(int signum)
{
epoll.closeResources();
}
/*
args: ./MIP_deamon <transport connection> [mip addresses ...]
*/
int main(int argc, char** argv)
{
//parse args
if (argc < 3) {
std::cerr << "Too few args\n";
return EXIT_FAILURE;
}
//signal
struct sigaction sa;
sa.sa_handler = &sigintHandler;
if (sigaction(SIGINT, &sa, NULL) == -1) {
throw LinuxException::Error("sigaction()");
}
//Connect transport_deamon
transport_sock = AnonymousSocketPacket(argv[1]);
//Connect routing_deamon
{
auto pair1 = AnonymousSocket::createPair();
auto pair2 = AnonymousSocket::createPair();
std::vector<std::string> args(2);
args[0] = pair1.second.toString();
args[1] = pair2.second.toString();
routing_deamon = ChildProcess::forkExec("./routing_deamon", args);
update_sock = pair1.first;
lookup_sock = pair2.first;
pair1.second.closeResources();
pair2.second.closeResources();
}
//Make MIPRawSock
{
std::vector<MIPAddress> mip_vec;
for (int i = 2; i < argc; ++i) {
mip_vec.push_back(std::atoi(argv[i]));
}
initRawSock(mip_vec);
}
//epoll
epoll = EventPoll(100);
for (auto & sock : raw_sock_vec) {
epoll.addFriend<RawSock::MIPRawSock>(sock);
}
epoll.addFriend<AnonymousSocketPacket>(transport_sock);
epoll.addFriend<AnonymousSocket>(update_sock);
epoll.addFriend<AnonymousSocket>(lookup_sock);
//send local mip addresses to routing_deamon
for (auto & s : raw_sock_vec) {
sendLocalMip(s.getMip());
}
//Send first broadcast frames
for (auto & s : raw_sock_vec) {
sendBroadcastFrame(s);
}
//timer
TimerWrapper timeout_timer;
timeout_timer.setExpirationFromNow(ARP_TIMEOUT);
epoll.addFriend(timeout_timer);
while (!epoll.isClosed()) {
try {
auto & event_vec = epoll.wait(20); //<- epoll exceptions will happen here
for (auto & ev : event_vec) {
int in_fd = ev.data.fd;
//check
if (in_fd == timeout_timer.getFd()) {
//std::cout << "Expired: " << timeout_timer.readExpiredTime() << "\n";
for (auto it = arp_pair_vec.begin(); it != arp_pair_vec.end(); ) {
if (!it->reply) {
sendArpLostConnection(it->mip);
arp_pair_vec.erase(it);
}
else {
it->reply = false;
++it;
}
}
for (RawSock::MIPRawSock & sock : raw_sock_vec) {
sendBroadcastFrame(sock);
}
timeout_timer.setExpirationFromNow(ARP_TIMEOUT);
}
else if (in_fd == transport_sock.getFd()) {
receiveTransportSock();
}
else if (in_fd == update_sock.getFd()) {
receiveUpdateSock();
}
else if (in_fd == lookup_sock.getFd()) {
receiveLookupSock();
}
else {
//check raw
auto raw_it = std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s){ return s.getFd() == in_fd; });
if (raw_it != raw_sock_vec.end()) {
receiveRawSock((*raw_it));
}
}
}
}
catch (LinuxException::InterruptedException & e) {
//if this then interrupted
std::cout << "MIP_deamon: epoll interrupted\n";
}
}
update_sock.closeResources();
lookup_sock.closeResources();
std::cout << "MIP_deamon: joining routing_deamon\n";
routing_deamon.join();
std::cout << "MIP_deamon: terminating\n";
return EXIT_SUCCESS;
}
| 24.300527 | 150 | 0.697621 | SaivNator |
28944b8ff24d177b9155a38b7480e3264003a45e | 1,571 | hpp | C++ | src/libs/server_common/include/keto/server_common/EventUtils.hpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | 1 | 2020-03-04T10:38:00.000Z | 2020-03-04T10:38:00.000Z | src/libs/server_common/include/keto/server_common/EventUtils.hpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | null | null | null | src/libs/server_common/include/keto/server_common/EventUtils.hpp | burntjam/keto | dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8 | [
"MIT"
] | 1 | 2020-03-04T10:38:01.000Z | 2020-03-04T10:38:01.000Z | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: EventUtils.hpp
* Author: ubuntu
*
* Created on February 17, 2018, 10:33 AM
*/
#ifndef EVENTUTILS_HPP
#define EVENTUTILS_HPP
#include <string>
#include <vector>
#include "keto/event/Event.hpp"
#include "keto/server_common/VectorUtils.hpp"
#include "keto/server_common/Exception.hpp"
namespace keto {
namespace server_common {
template<class PbType>
keto::event::Event toEvent(PbType& type) {
std::string pbValue;
if (!type.SerializeToString(&pbValue)) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffSerializationException());
}
return keto::event::Event(VectorUtils().copyStringToVector(pbValue));
}
template<class PbType>
keto::event::Event toEvent(const std::string& event, PbType& type) {
std::string pbValue;
if (!type.SerializeToString(&pbValue)) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffSerializationException());
}
return keto::event::Event(event,VectorUtils().copyStringToVector(pbValue));
}
template<class PbType>
PbType fromEvent(const keto::event::Event& event) {
PbType pbValue;
keto::event::Event copyEvent = event;
if (!pbValue.ParseFromString(VectorUtils().copyVectorToString(copyEvent.getMessage()))) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffDeserializationException());
}
return pbValue;
}
}
}
#endif /* EVENTUTILS_HPP */
| 25.754098 | 93 | 0.721833 | burntjam |
28978548b1829e7a11224ceb2e8f5153185fe842 | 1,972 | cpp | C++ | Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | #include "Texture2DComponentWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
namespace editor::impl {
Texture2DComponentWidget::Texture2DComponentWidget(QWidget* parent)
: QWidget(parent)
, m_Entity(nullptr)
, m_Texture2D(nullptr)
, m_Color(nullptr)
, m_Texture2DLineEdit(nullptr)
, m_Texture2DLabel(nullptr) {
QVBoxLayout* layout = new QVBoxLayout(this);
QHBoxLayout* textureLayout = new QHBoxLayout();
m_Color = new Double3Widget("Color", glm::vec3(0.0f), this);
m_Color->SetMinMax(0.0, 1.0);
m_Texture2DLineEdit = new QLineEdit(this);
m_Texture2DLabel = new QLabel("Texture2D", this);
m_Texture2DLabel->setMinimumWidth(80);
textureLayout->addWidget(m_Texture2DLabel);
textureLayout->addWidget(m_Texture2DLineEdit);
layout->addWidget(m_Color);
layout->addLayout(textureLayout);
setLayout(layout);
InitConnections();
}
void Texture2DComponentWidget::OnColorChanged(glm::vec3 value) {
if (m_Texture2D) {
m_Texture2D->Color = value;
}
}
void Texture2DComponentWidget::SetEntity(pawn::engine::GameEntity* entity) {
m_Entity = entity;
}
void Texture2DComponentWidget::SetTexture2D(pawn::engine::Texture2DComponent* texture2D) {
m_Texture2D = texture2D;
m_Texture2DLineEdit->setText(texture2D->TextureName.c_str());
m_Color->SetValue(texture2D->Color);
}
void Texture2DComponentWidget::OnLineEditPress() {
QString& text{ m_Texture2DLineEdit->text() };
std::string& textureName{ m_Texture2D->TextureName };
textureName = text.toLocal8Bit().constData();
emit Texture2DModified(*m_Entity);
m_Texture2DLineEdit->clearFocus();
}
void Texture2DComponentWidget::InitConnections() {
connect(
m_Color,
SIGNAL(ValueChanged(glm::vec3)),
this,
SLOT(OnColorChanged(glm::vec3))
);
connect(
m_Texture2DLineEdit,
SIGNAL(returnPressed()),
this,
SLOT(OnLineEditPress())
);
}
}
| 24.04878 | 92 | 0.704868 | obivan43 |
Subsets and Splits