hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cdf2513eb6d1d6709030665d463bc5d7e35d2829 | 3,304 | cpp | C++ | CS682/Challenge01/challenge_01_missionaries_cannibals_bfs.cpp | T-R0D/Past-Courses | 0edc83a7bf09515f0d01d23a26df2ff90c0f458a | [
"MIT"
] | 7 | 2017-03-13T17:32:26.000Z | 2021-09-27T16:51:22.000Z | CS682/Challenge01/challenge_01_missionaries_cannibals_bfs.cpp | T-R0D/Past-Courses | 0edc83a7bf09515f0d01d23a26df2ff90c0f458a | [
"MIT"
] | 1 | 2021-05-29T19:54:02.000Z | 2021-05-29T19:54:52.000Z | CS682/Challenge01/challenge_01_missionaries_cannibals_bfs.cpp | T-R0D/Past-Courses | 0edc83a7bf09515f0d01d23a26df2ff90c0f458a | [
"MIT"
] | 25 | 2016-10-18T03:31:44.000Z | 2020-12-29T13:23:10.000Z | // hacky for now, to be cleaned later
#include <vector>
#include <string>
#include <cstdio>
#include <set>
#include <queue>
std::vector< std::vector<int> > gActions = {
{2, 0, 1},
{1, 0, 1},
{1, 1, 1},
{0, 1, 1},
{0, 2, 1}
};
class ProblemState {
public:
ProblemState() : mState{{3, 3, 1}} {
}
ProblemState(const ProblemState& pThat) {
*this = pThat;
}
ProblemState& operator=(const ProblemState& pThat) {
if (this != &pThat) {
mState = pThat.mState;
mActions = pThat.mActions;
}
return *this;
}
ProblemState applyAction(const std::vector<int>& pAction) {
std::vector<int> action = pAction;
if (mState[2] == 1) {
for (int i = 0; i < 3; i++) {
action[i] *= -1;
}
}
ProblemState newState(*this);
for (int i = 0; i < 3; i++) {
newState.mState[i] += action[i];
}
newState.mActions.push_back(actionToString(pAction));
return newState;
}
bool isValid() const {
return validVector(mState) && validVector(complementVector(mState));
}
bool validVector(const std::vector<int>& pState) const {
return (
(pState[0] == 0 || (pState[0] >= pState[1])) &&
pState[0] >= 0 &&
pState[1] >= 0 &&
pState[0] <= 3 &&
pState[1] <= 3
);
}
bool isSuccess() const {
bool success = true;
for (auto count : mState) {
if (count != 0) {
success = false;
}
}
return success;
}
std::string toString() const {
std::string ret;
for (auto count : mState) {
ret += ((char) count + '0');
}
return ret;
}
std::vector<int> complementVector(const std::vector<int>& pVector) const {
std::vector<int> complement;
for (auto count : pVector) {
complement.push_back(3 - count);
}
complement[2] = 1 - pVector[2];
return complement;
}
std::string actionToString(const std::vector<int>& pAction) const {
std::string ret("");
ret += (char(pAction[0]) + '0');
ret += " missionaries ";
ret += (char(pAction[1]) + '0');
ret += " cannibals";
return ret;
}
std::vector<int> mState;
std::vector<std::string> mActions;
};
ProblemState bfs(const ProblemState& pInitialState) {
ProblemState currentState;
std::set<std::string> encounteredStates;
std::queue<ProblemState> statesToBeProcessed;
encounteredStates.insert(pInitialState.toString());
statesToBeProcessed.push(pInitialState);
while (!statesToBeProcessed.empty()) {
currentState = statesToBeProcessed.front();
statesToBeProcessed.pop();
if (currentState.isSuccess()) {
return currentState;
} else {
for (auto operation : gActions) {
ProblemState newState = currentState.applyAction(operation);
if (newState.isValid()) {
if (encounteredStates.find(newState.toString()) == std::end(encounteredStates)) {
encounteredStates.insert(newState.toString());
statesToBeProcessed.push(newState);
}
}
}
}
}
throw 666;
}
int main(int argc, char**argv) {
ProblemState initialState;
try {
ProblemState solution = bfs(initialState);
puts("solution");
int i;
for (i = 0; i < solution.mActions.size() - 1; i += 2) {
printf("Move %s across\n", solution.mActions[i].c_str());
printf("Move %s back\n", solution.mActions[i + 1].c_str());
}
printf("Move %s across\n", solution.mActions[i].c_str());
} catch (int e) {
puts("no solution...");
}
return 0;
} | 20.146341 | 86 | 0.626211 | T-R0D |
cdf64bd5c4140abbca7115cd5c61bb30311be649 | 8,415 | cpp | C++ | test/test_add_torrent.cpp | aldenml/libtorrent | f484a0eff66c1d8932d694e1785da204ac1a2769 | [
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2020-07-20T17:01:46.000Z | 2020-07-20T17:01:46.000Z | test/test_add_torrent.cpp | aldenml/libtorrent | f484a0eff66c1d8932d694e1785da204ac1a2769 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | test/test_add_torrent.cpp | aldenml/libtorrent | f484a0eff66c1d8932d694e1785da204ac1a2769 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2021, Arvid Norberg
All rights reserved.
You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/
#include "test.hpp"
#include "setup_transfer.hpp" // for load_file
#include "libtorrent/flags.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/add_torrent_params.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/aux_/path.hpp"
#include <iostream>
namespace {
using add_torrent_test_flag_t = lt::flags::bitfield_flag<std::uint32_t, struct add_torrent_test_tag>;
using lt::operator""_bit;
#if TORRENT_ABI_VERSION < 3
add_torrent_test_flag_t const set_info_hash = 0_bit;
#endif
add_torrent_test_flag_t const set_info_hashes_v1 = 1_bit;
add_torrent_test_flag_t const set_info_hashes_v2 = 2_bit;
add_torrent_test_flag_t const async_add = 3_bit;
add_torrent_test_flag_t const ec_add = 4_bit;
add_torrent_test_flag_t const magnet_link = 5_bit;
#if TORRENT_ABI_VERSION < 3
add_torrent_test_flag_t const set_invalid_info_hash = 6_bit;
#endif
add_torrent_test_flag_t const set_invalid_info_hash_v1 = 7_bit;
add_torrent_test_flag_t const set_invalid_info_hash_v2 = 8_bit;
lt::error_code test_add_torrent(std::string file, add_torrent_test_flag_t const flags)
{
std::string const root_dir = lt::parent_path(lt::current_working_directory());
std::string const filename = lt::combine_path(lt::combine_path(root_dir, "test_torrents"), file);
lt::error_code ec;
std::vector<char> data;
TEST_CHECK(load_file(filename, data, ec) == 0);
auto ti = std::make_shared<lt::torrent_info>(data, ec, lt::from_span);
TEST_CHECK(!ec);
if (ec) std::printf(" loading(\"%s\") -> failed %s\n", filename.c_str()
, ec.message().c_str());
lt::add_torrent_params atp;
atp.ti = ti;
atp.save_path = ".";
#if TORRENT_ABI_VERSION < 3
if (flags & set_info_hash) atp.info_hash = atp.ti->info_hash();
#endif
if (flags & set_info_hashes_v1) atp.info_hashes.v1 = atp.ti->info_hashes().v1;
if (flags & set_info_hashes_v2) atp.info_hashes.v2 = atp.ti->info_hashes().v2;
#if TORRENT_ABI_VERSION < 3
if (flags & set_invalid_info_hash) atp.info_hash = lt::sha1_hash("abababababababababab");
#endif
if (flags & set_invalid_info_hash_v1) atp.info_hashes.v1 = lt::sha1_hash("abababababababababab");
if (flags & set_invalid_info_hash_v2) atp.info_hashes.v2 = lt::sha256_hash("abababababababababababababababab");
std::vector<char> info_section;
if (flags & magnet_link)
{
auto const is = atp.ti->info_section();
info_section.assign(is.begin(), is.end());
atp.ti.reset();
}
lt::session_params p;
p.settings.set_int(lt::settings_pack::alert_mask, lt::alert_category::error | lt::alert_category::status);
p.settings.set_str(lt::settings_pack::listen_interfaces, "127.0.0.1:6881");
lt::session ses(p);
try
{
if (flags & ec_add)
{
ses.add_torrent(atp, ec);
if (ec) return ec;
}
else if (flags & async_add)
{
ses.async_add_torrent(atp);
}
else
{
ses.add_torrent(atp);
}
}
catch (lt::system_error const& e)
{
return e.code();
}
std::vector<lt::alert*> alerts;
auto const start_time = lt::clock_type::now();
while (lt::clock_type::now() - start_time < lt::seconds(3))
{
ses.wait_for_alert(lt::seconds(1));
alerts.clear();
ses.pop_alerts(&alerts);
for (auto const* a : alerts)
{
std::cout << a->message() << '\n';
if (auto const* te = lt::alert_cast<lt::torrent_error_alert>(a))
{
return te->error;
}
if (auto const* mf = lt::alert_cast<lt::metadata_failed_alert>(a))
{
return mf->error;
}
if (auto const* ta = lt::alert_cast<lt::add_torrent_alert>(a))
{
if (ta->error) return ta->error;
if (flags & magnet_link)
{
// if this fails, we'll pick up the metadata_failed_alert
TEST_CHECK(ta->handle.is_valid());
ta->handle.set_metadata(info_section);
}
else
{
// success!
return lt::error_code();
}
}
if (lt::alert_cast<lt::metadata_received_alert>(a))
{
// success!
return lt::error_code();
}
}
}
return lt::error_code();
}
struct test_case_t
{
char const* filename;
add_torrent_test_flag_t flags;
lt::error_code expected_error;
};
auto const v2 = "v2.torrent";
auto const hybrid = "v2_hybrid.torrent";
auto const v1 = "base.torrent";
test_case_t const add_torrent_test_cases[] = {
{v2, {}, {}},
{v2, set_info_hashes_v1, {}},
{v2, set_info_hashes_v2, {}},
{v2, set_info_hashes_v1 | set_info_hashes_v2, {}},
#if TORRENT_ABI_VERSION < 3
{v2, set_info_hash, {}},
// the info_hash field is ignored when we have an actual torrent_info object
{v2, set_invalid_info_hash, {}},
#endif
{v2, set_invalid_info_hash_v1, lt::errors::mismatching_info_hash},
{v2, set_invalid_info_hash_v2, lt::errors::mismatching_info_hash},
{hybrid, {}, {}},
{hybrid, set_info_hashes_v1, {}},
{hybrid, set_info_hashes_v2, {}},
{hybrid, set_info_hashes_v1 | set_info_hashes_v2, {}},
#if TORRENT_ABI_VERSION < 3
{hybrid, set_info_hash, {}},
// the info_hash field is ignored when we have an actual torrent_info object
{hybrid, set_invalid_info_hash, {}},
#endif
{hybrid, set_invalid_info_hash_v1, lt::errors::mismatching_info_hash},
{hybrid, set_invalid_info_hash_v2, lt::errors::mismatching_info_hash},
{v1, {}, {}},
{v1, set_info_hashes_v1, {}},
#if TORRENT_ABI_VERSION < 3
{v1, set_info_hash, {}},
// the info_hash field is ignored when we have an actual torrent_info object
{v1, set_invalid_info_hash, {}},
#endif
// magnet links
{v2, magnet_link, lt::errors::missing_info_hash_in_uri},
{v2, magnet_link | set_info_hashes_v1, {}},
{v2, magnet_link | set_info_hashes_v2, {}},
#if TORRENT_ABI_VERSION < 3
// a v2-only magnet link supports magnet links with a truncated hash
{v2, magnet_link | set_info_hash, {}},
{v2, magnet_link | set_invalid_info_hash, lt::errors::mismatching_info_hash},
#endif
{v2, magnet_link | set_info_hashes_v1 | set_info_hashes_v2, {}},
{v2, magnet_link | set_invalid_info_hash_v1, lt::errors::mismatching_info_hash},
{v2, magnet_link | set_invalid_info_hash_v2, lt::errors::mismatching_info_hash},
{hybrid, magnet_link, lt::errors::missing_info_hash_in_uri},
{hybrid, magnet_link | set_info_hashes_v1, {}},
{hybrid, magnet_link | set_info_hashes_v2, {}},
#if TORRENT_ABI_VERSION < 3
{hybrid, magnet_link | set_info_hash, {}},
{hybrid, magnet_link | set_invalid_info_hash, lt::errors::mismatching_info_hash},
#endif
{hybrid, magnet_link | set_info_hashes_v1 | set_info_hashes_v2, {}},
{hybrid, magnet_link | set_invalid_info_hash_v1, lt::errors::mismatching_info_hash},
{hybrid, magnet_link | set_invalid_info_hash_v2, lt::errors::mismatching_info_hash},
{v1, magnet_link, lt::errors::missing_info_hash_in_uri},
#if TORRENT_ABI_VERSION < 3
{v1, magnet_link | set_info_hash, {}},
{v1, magnet_link | set_invalid_info_hash, lt::errors::mismatching_info_hash},
#endif
{v1, magnet_link | set_info_hashes_v1, {}},
{v1, magnet_link | set_invalid_info_hash_v1, lt::errors::mismatching_info_hash},
{v1, magnet_link | set_invalid_info_hash_v2, lt::errors::mismatching_info_hash},
};
}
TORRENT_TEST(invalid_file_root)
{
TEST_CHECK(test_add_torrent("v2_invalid_root_hash.torrent", {}) == lt::error_code(lt::errors::torrent_invalid_piece_layer));
}
TORRENT_TEST(add_torrent)
{
int i = 0;
for (auto const& test_case : add_torrent_test_cases)
{
std::cerr << "idx: " << i << '\n';
auto const e = test_add_torrent(test_case.filename, test_case.flags);
if (e != test_case.expected_error)
{
std::cerr << test_case.filename << '\n';
TEST_ERROR(e.message() + " != " + test_case.expected_error.message());
}
++i;
}
}
TORRENT_TEST(async_add_torrent)
{
int i = 0;
for (auto const& test_case : add_torrent_test_cases)
{
auto const e = test_add_torrent(test_case.filename, test_case.flags | async_add);
if (e != test_case.expected_error)
{
std::cerr << "idx: " << i << " " << test_case.filename << '\n';
TEST_ERROR(e.message() + " != " + test_case.expected_error.message());
}
++i;
}
}
TORRENT_TEST(ec_add_torrent)
{
int i = 0;
for (auto const& test_case : add_torrent_test_cases)
{
auto const e = test_add_torrent(test_case.filename, test_case.flags | ec_add);
if (e != test_case.expected_error)
{
std::cerr << "idx: " << i << " " << test_case.filename << '\n';
TEST_ERROR(e.message() + " != " + test_case.expected_error.message());
}
++i;
}
}
| 29.734982 | 125 | 0.714082 | aldenml |
cdf8e1ec2ab4e87781ea86b0f9819b0ad2658c27 | 900 | cpp | C++ | src/core/panels/Profiler.cpp | indigames/igeCreator | 05e6eb39f34f2571275717fbc8ed4404757ed5e3 | [
"MIT"
] | null | null | null | src/core/panels/Profiler.cpp | indigames/igeCreator | 05e6eb39f34f2571275717fbc8ed4404757ed5e3 | [
"MIT"
] | 153 | 2021-05-04T08:26:09.000Z | 2022-01-27T03:48:29.000Z | src/core/panels/Profiler.cpp | indigames/igeCreator | 05e6eb39f34f2571275717fbc8ed4404757ed5e3 | [
"MIT"
] | null | null | null | #include <imgui.h>
#include "core/panels/Profiler.h"
namespace ige::creator
{
Profiler::Profiler(const std::string& name, const Panel::Settings& settings)
: Panel(name, settings)
{
}
Profiler::~Profiler()
{
clear();
}
void Profiler::initialize()
{
clear();
m_timeWidget = createWidget<Label>("Time");
m_fpsWidget = createWidget<Label>("FPS");
}
void Profiler::_drawImpl()
{
// Show FPS
m_timeWidget->setLabel("Time: " + std::to_string(static_cast<int>(1000.0f / ImGui::GetIO().Framerate)) + " ms");
m_fpsWidget->setLabel("FPS: " + std::to_string(static_cast<int>(ImGui::GetIO().Framerate)) + " fps");
Panel::_drawImpl();
}
void Profiler::clear()
{
m_timeWidget = nullptr;
m_fpsWidget = nullptr;
removeAllWidgets();
}
}
| 21.428571 | 120 | 0.562222 | indigames |
cdfb2c79202848b9c6a4be9888a670a2a76643f8 | 4,478 | cpp | C++ | src/modern/gui/trivium.cpp | AntonC9018/uni_crypto | 689e6ffa4a264950a1382280105cee55cad8f1ac | [
"MIT"
] | 1 | 2021-02-15T16:46:49.000Z | 2021-02-15T16:46:49.000Z | src/modern/gui/trivium.cpp | AntonC9018/uni_crypto | 689e6ffa4a264950a1382280105cee55cad8f1ac | [
"MIT"
] | null | null | null | src/modern/gui/trivium.cpp | AntonC9018/uni_crypto | 689e6ffa4a264950a1382280105cee55cad8f1ac | [
"MIT"
] | 1 | 2021-04-12T09:32:40.000Z | 2021-04-12T09:32:40.000Z | #include "trivium.h"
#include "../algos/trivium.h"
TriviumBox::TriviumBox()
: Gtk::Box(Gtk::ORIENTATION_VERTICAL)
{
pack_start(m_KeyGrid);
m_KeyGrid.set_halign(Gtk::ALIGN_CENTER);
m_KeyGrid.attach(m_KeyHeader, 1, 1, 2);
m_KeyGrid.attach(m_KeywordLabel, 1, 2);
m_KeyGrid.attach(m_KeywordEntry, 2, 2);
m_KeyGrid.attach(m_InitializationVectorLabel, 1, 3);
m_KeyGrid.attach(m_InitializationVectorEntry, 2, 3);
pack_start(m_UsageGrid);
m_UsageGrid.set_halign(Gtk::ALIGN_CENTER);
m_UsageGrid.attach(m_UsageHeader, 1, 1, 2);
m_UsageGrid.attach(m_PlainTextLabel, 1, 2, 2);
m_UsageGrid.attach(m_PlainTextView, 1, 3, 2);
m_UsageGrid.attach(m_EncryptedTextLabel, 1, 4, 2);
m_UsageGrid.attach(m_EncryptedTextView, 1, 5, 2);
m_KeyHeader.set_markup("<u><b>Key</b></u>");
m_KeyHeader.set_margin_top(10);
m_KeyHeader.set_margin_bottom(10);
m_KeywordLabel.set_text("Keyword ");
m_refKeywordBuffer = m_KeywordEntry.get_buffer();
m_KeywordEntry.set_text("1234567890");
m_KeywordEntry.signal_changed().connect(
sigc::mem_fun(*this, TriviumBox::changed_keyword_text)
);
m_InitializationVectorLabel.set_text("Initialization Vector ");
m_refInitializationVectorBuffer = m_InitializationVectorEntry.get_buffer();
m_InitializationVectorEntry.set_text("1234567890");
m_InitializationVectorEntry.signal_changed().connect(
sigc::mem_fun(*this, TriviumBox::changed_ivector_text)
);
m_PlainTextLabel.set_text("Plain Message (in base64)");
m_refPlainTextBuffer = Gtk::TextBuffer::create();
m_refPlainTextBuffer->set_text("AAAAAAAAAAAA");
m_refPlainTextBuffer->signal_changed().connect(
sigc::mem_fun(*this, TriviumBox::changed_message_text)
);
m_PlainTextView.set_buffer(m_refPlainTextBuffer);
m_PlainTextView.set_wrap_mode(Gtk::WRAP_WORD_CHAR);
m_EncryptedTextLabel.set_text("Encrypted Message (in base64)");
m_refEncryptedTextBuffer = Gtk::TextBuffer::create();
m_refEncryptedTextBuffer->signal_changed().connect(
sigc::mem_fun(*this, TriviumBox::changed_encrypted_text)
);
m_EncryptedTextView.set_buffer(m_refEncryptedTextBuffer);
m_EncryptedTextView.set_wrap_mode(Gtk::WRAP_WORD_CHAR);
changed_message_text();
logger_attach(&logger, this);
}
void TriviumBox::changed_message_text()
{
if (!m_ignoreTextInput)
{
m_ignoreTextInput = true;
if (!logger.has_errors)
encrypt();
m_ignoreTextInput = false;
}
}
void TriviumBox::changed_encrypted_text()
{
if (!m_ignoreTextInput)
{
m_ignoreTextInput = true;
if (!logger.has_errors)
decrypt();
m_ignoreTextInput = false;
}
}
void TriviumBox::changed_ivector_text()
{
changed_keyword_text();
}
void TriviumBox::changed_keyword_text()
{
if (!m_ignoreTextInput)
{
m_ignoreTextInput = true;
validate();
if (!logger.has_errors)
encrypt();
m_ignoreTextInput = false;
}
}
Glib::ustring TriviumBox::crypt(const Glib::ustring& buffer)
{
auto key_string = m_refKeywordBuffer->get_text();
auto ivector = m_refInitializationVectorBuffer->get_text();
auto base64_decoded = Glib::Base64::decode(buffer);
auto num_bytes = base64_decoded.size();
trivium_crypt(
(u8*)key_string.data(),
(u8*)ivector.data(),
(u8*)base64_decoded.data(),
num_bytes);
return Glib::Base64::encode(base64_decoded);
}
void TriviumBox::encrypt()
{
auto buffer = m_refPlainTextBuffer->get_text();
m_refEncryptedTextBuffer->set_text(crypt(buffer));
}
void TriviumBox::decrypt()
{
auto buffer = m_refEncryptedTextBuffer->get_text();
m_refPlainTextBuffer->set_text(crypt(buffer));
}
void TriviumBox::validate()
{
logger_clear(&logger);
int num_ivector_bytes = m_refInitializationVectorBuffer->get_bytes();
if (num_ivector_bytes < 10)
{
logger_format_error(&logger,
"Not enough bytes in the initialization vector (%i). Must be at least 10.\n", num_ivector_bytes);
}
int num_keyword_bytes = m_refKeywordBuffer->get_bytes();
if (num_keyword_bytes < 10)
{
logger_format_error(&logger,
"Not enough bytes in the keyword (%i). Must be at least 10.\n",
num_keyword_bytes);
}
}
// Salsa20Box::~Salsa20Box() {}
| 26.034884 | 109 | 0.682224 | AntonC9018 |
cdfe2209868063639d2d513a2b54807c5630e9bc | 1,572 | cpp | C++ | src/cppcalllua_lib/jass_luastate.cpp | uniqss/uconfig | 85bd9e429d0d6df4b6a4d6100a0a7c968160c565 | [
"MIT"
] | 1 | 2020-12-30T08:06:51.000Z | 2020-12-30T08:06:51.000Z | projects/uconfiglua/src/jass_luastate.cpp | uniqss/uniqsconfiggenerator | 00fcf2b89d43d86c5eb210e8e517cff9a6303b91 | [
"MIT"
] | 3 | 2021-04-12T03:32:39.000Z | 2021-04-12T03:38:36.000Z | projects/uconfiglua/src/jass_luastate.cpp | uniqss/uniqsconfiggenerator | 00fcf2b89d43d86c5eb210e8e517cff9a6303b91 | [
"MIT"
] | null | null | null | #include "jass_luastate.h"
// Use raw function of form "int(lua_State*)"
// -- this is called a "raw C function",
// and matches the type for lua_CFunction
int LoadFileRequire(lua_State* L) {
// use sol2 stack API to pull
// "first argument"
std::string path = sol::stack::get<std::string>(L, 1);
if (path == "a") {
std::string script = R"(
print("Hello from module land!")
test = 123
return "bananas"
)";
// load "module", but don't run it
luaL_loadbuffer(
L, script.data(), script.size(), path.c_str());
// returning 1 object left on Lua stack:
// a function that, when called, executes the script
// (this is what lua_loadX/luaL_loadX functions return
return 1;
}
sol::stack::push(
L, "This is not the module you're looking for!");
return 1;
}
void jass_luastate::init(const std::string& scriptsPath)
{
luastate.open_libraries(
sol::lib::base
, sol::lib::package
, sol::lib::os
, sol::lib::string
, sol::lib::math
, sol::lib::io
);
// https://github.com/ThePhD/sol2/issues/90
/*
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::package);
const std::string package_path = lua["package"]["path"];
lua["package"]["path"]
= package_path + (!package_path.empty() ? ";" : "") + test::scripts_path("proc/valid/") + "?.lua";
*/
//luastate.clear_package_loaders();
//luastate.add_package_loader(LoadFileRequire);
const std::string package_path = luastate["package"]["path"];
luastate["package"]["path"] = package_path + (!package_path.empty() ? ";" : "") + "./?.lua;" + scriptsPath +"?.lua";
}
| 27.578947 | 117 | 0.648219 | uniqss |
cdfe727e50183d351378c025acc4ad66291ef842 | 8,826 | cc | C++ | runtime/ti/agent.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 20 | 2021-06-24T16:38:42.000Z | 2022-01-20T16:15:57.000Z | runtime/ti/agent.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | null | null | null | runtime/ti/agent.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 4 | 2021-11-03T06:01:12.000Z | 2022-02-24T02:57:31.000Z | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "agent.h"
#include "android-base/stringprintf.h"
#include "nativehelper/scoped_local_ref.h"
#include "nativeloader/native_loader.h"
#include "base/logging.h"
#include "base/strlcpy.h"
#include "jni/java_vm_ext.h"
#include "runtime.h"
#include "thread-current-inl.h"
#include "scoped_thread_state_change-inl.h"
namespace art {
namespace ti {
using android::base::StringPrintf;
const char* AGENT_ON_LOAD_FUNCTION_NAME = "Agent_OnLoad";
const char* AGENT_ON_ATTACH_FUNCTION_NAME = "Agent_OnAttach";
const char* AGENT_ON_UNLOAD_FUNCTION_NAME = "Agent_OnUnload";
AgentSpec::AgentSpec(const std::string& arg) {
size_t eq = arg.find_first_of('=');
if (eq == std::string::npos) {
name_ = arg;
} else {
name_ = arg.substr(0, eq);
args_ = arg.substr(eq + 1, arg.length());
}
}
std::unique_ptr<Agent> AgentSpec::Load(/*out*/jint* call_res,
/*out*/LoadError* error,
/*out*/std::string* error_msg) {
VLOG(agents) << "Loading agent: " << name_ << " " << args_;
return DoLoadHelper(nullptr, false, nullptr, call_res, error, error_msg);
}
// Tries to attach the agent using its OnAttach method. Returns true on success.
std::unique_ptr<Agent> AgentSpec::Attach(JNIEnv* env,
jobject class_loader,
/*out*/jint* call_res,
/*out*/LoadError* error,
/*out*/std::string* error_msg) {
VLOG(agents) << "Attaching agent: " << name_ << " " << args_;
return DoLoadHelper(env, true, class_loader, call_res, error, error_msg);
}
// TODO We need to acquire some locks probably.
std::unique_ptr<Agent> AgentSpec::DoLoadHelper(JNIEnv* env,
bool attaching,
jobject class_loader,
/*out*/jint* call_res,
/*out*/LoadError* error,
/*out*/std::string* error_msg) {
ScopedThreadStateChange stsc(Thread::Current(), ThreadState::kNative);
DCHECK(call_res != nullptr);
DCHECK(error_msg != nullptr);
std::unique_ptr<Agent> agent = DoDlOpen(env, class_loader, error, error_msg);
if (agent == nullptr) {
VLOG(agents) << "err: " << *error_msg;
return nullptr;
}
AgentOnLoadFunction callback = attaching ? agent->onattach_ : agent->onload_;
if (callback == nullptr) {
*error_msg = StringPrintf("Unable to start agent %s: No %s callback found",
(attaching ? "attach" : "load"),
name_.c_str());
VLOG(agents) << "err: " << *error_msg;
*error = kLoadingError;
return nullptr;
}
// Need to let the function fiddle with the array.
std::unique_ptr<char[]> copied_args(new char[args_.size() + 1]);
strlcpy(copied_args.get(), args_.c_str(), args_.size() + 1);
// TODO Need to do some checks that we are at a good spot etc.
*call_res = callback(Runtime::Current()->GetJavaVM(),
copied_args.get(),
nullptr);
if (*call_res != 0) {
*error_msg = StringPrintf("Initialization of %s returned non-zero value of %d",
name_.c_str(), *call_res);
VLOG(agents) << "err: " << *error_msg;
*error = kInitializationError;
return nullptr;
}
return agent;
}
std::unique_ptr<Agent> AgentSpec::DoDlOpen(JNIEnv* env,
jobject class_loader,
/*out*/LoadError* error,
/*out*/std::string* error_msg) {
DCHECK(error_msg != nullptr);
ScopedLocalRef<jstring> library_path(env,
class_loader == nullptr
? nullptr
: JavaVMExt::GetLibrarySearchPath(env, class_loader));
bool needs_native_bridge = false;
char* nativeloader_error_msg = nullptr;
void* dlopen_handle = android::OpenNativeLibrary(env,
Runtime::Current()->GetTargetSdkVersion(),
name_.c_str(),
class_loader,
nullptr,
library_path.get(),
&needs_native_bridge,
&nativeloader_error_msg);
if (dlopen_handle == nullptr) {
*error_msg = StringPrintf("Unable to dlopen %s: %s",
name_.c_str(),
nativeloader_error_msg);
android::NativeLoaderFreeErrorMessage(nativeloader_error_msg);
*error = kLoadingError;
return nullptr;
}
if (needs_native_bridge) {
// TODO: Consider support?
// The result of this call and error_msg is ignored because the most
// relevant error is that native bridge is unsupported.
android::CloseNativeLibrary(dlopen_handle, needs_native_bridge, &nativeloader_error_msg);
android::NativeLoaderFreeErrorMessage(nativeloader_error_msg);
*error_msg = StringPrintf("Native-bridge agents unsupported: %s", name_.c_str());
*error = kLoadingError;
return nullptr;
}
std::unique_ptr<Agent> agent(new Agent(name_, dlopen_handle));
agent->PopulateFunctions();
*error = kNoError;
return agent;
}
std::ostream& operator<<(std::ostream &os, AgentSpec const& m) {
return os << "AgentSpec { name=\"" << m.name_ << "\", args=\"" << m.args_ << "\" }";
}
void* Agent::FindSymbol(const std::string& name) const {
CHECK(dlopen_handle_ != nullptr) << "Cannot find symbols in an unloaded agent library " << this;
return dlsym(dlopen_handle_, name.c_str());
}
// TODO Lock some stuff probably.
void Agent::Unload() {
if (dlopen_handle_ != nullptr) {
if (onunload_ != nullptr) {
onunload_(Runtime::Current()->GetJavaVM());
}
// Don't actually android::CloseNativeLibrary since some agents assume they will never get
// unloaded. Since this only happens when the runtime is shutting down anyway this isn't a big
// deal.
dlopen_handle_ = nullptr;
onload_ = nullptr;
onattach_ = nullptr;
onunload_ = nullptr;
} else {
VLOG(agents) << this << " is not currently loaded!";
}
}
Agent::Agent(Agent&& other) noexcept
: dlopen_handle_(nullptr),
onload_(nullptr),
onattach_(nullptr),
onunload_(nullptr) {
*this = std::move(other);
}
Agent& Agent::operator=(Agent&& other) noexcept {
if (this != &other) {
if (dlopen_handle_ != nullptr) {
Unload();
}
name_ = std::move(other.name_);
dlopen_handle_ = other.dlopen_handle_;
onload_ = other.onload_;
onattach_ = other.onattach_;
onunload_ = other.onunload_;
other.dlopen_handle_ = nullptr;
other.onload_ = nullptr;
other.onattach_ = nullptr;
other.onunload_ = nullptr;
}
return *this;
}
void Agent::PopulateFunctions() {
onload_ = reinterpret_cast<AgentOnLoadFunction>(FindSymbol(AGENT_ON_LOAD_FUNCTION_NAME));
if (onload_ == nullptr) {
VLOG(agents) << "Unable to find 'Agent_OnLoad' symbol in " << this;
}
onattach_ = reinterpret_cast<AgentOnLoadFunction>(FindSymbol(AGENT_ON_ATTACH_FUNCTION_NAME));
if (onattach_ == nullptr) {
VLOG(agents) << "Unable to find 'Agent_OnAttach' symbol in " << this;
}
onunload_ = reinterpret_cast<AgentOnUnloadFunction>(FindSymbol(AGENT_ON_UNLOAD_FUNCTION_NAME));
if (onunload_ == nullptr) {
VLOG(agents) << "Unable to find 'Agent_OnUnload' symbol in " << this;
}
}
Agent::~Agent() {
if (dlopen_handle_ != nullptr) {
Unload();
}
}
std::ostream& operator<<(std::ostream &os, const Agent* m) {
return os << *m;
}
std::ostream& operator<<(std::ostream &os, Agent const& m) {
return os << "Agent { name=\"" << m.name_ << "\", handle=" << m.dlopen_handle_ << " }";
}
} // namespace ti
} // namespace art
| 36.775 | 98 | 0.592567 | Paschalis |
cdff7ff2070b66edde68e62e8ece8465b1e07a29 | 3,476 | cpp | C++ | src/Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.cpp | 540522905/ClickHouse | 299445ec7da10bd2ef62d8e333a95b7ab12bf5f2 | [
"Apache-2.0"
] | 2 | 2022-03-15T16:35:11.000Z | 2022-03-18T12:39:52.000Z | src/Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.cpp | 540522905/ClickHouse | 299445ec7da10bd2ef62d8e333a95b7ab12bf5f2 | [
"Apache-2.0"
] | null | null | null | src/Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.cpp | 540522905/ClickHouse | 299445ec7da10bd2ef62d8e333a95b7ab12bf5f2 | [
"Apache-2.0"
] | null | null | null | #include <IO/WriteHelpers.h>
#include <IO/WriteBufferValidUTF8.h>
#include <Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.h>
#include <Formats/FormatFactory.h>
#include <Formats/registerWithNamesAndTypes.h>
namespace DB
{
JSONCompactEachRowRowOutputFormat::JSONCompactEachRowRowOutputFormat(WriteBuffer & out_,
const Block & header_,
const RowOutputFormatParams & params_,
const FormatSettings & settings_,
bool with_names_,
bool with_types_,
bool yield_strings_)
: IRowOutputFormat(header_, out_, params_), settings(settings_), with_names(with_names_), with_types(with_types_), yield_strings(yield_strings_)
{
}
void JSONCompactEachRowRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num)
{
if (yield_strings)
{
WriteBufferFromOwnString buf;
serialization.serializeText(column, row_num, buf, settings);
writeJSONString(buf.str(), out, settings);
}
else
serialization.serializeTextJSON(column, row_num, out, settings);
}
void JSONCompactEachRowRowOutputFormat::writeFieldDelimiter()
{
writeCString(", ", out);
}
void JSONCompactEachRowRowOutputFormat::writeRowStartDelimiter()
{
writeChar('[', out);
}
void JSONCompactEachRowRowOutputFormat::writeRowEndDelimiter()
{
writeCString("]\n", out);
}
void JSONCompactEachRowRowOutputFormat::writeTotals(const Columns & columns, size_t row_num)
{
writeChar('\n', out);
size_t num_columns = columns.size();
writeRowStartDelimiter();
for (size_t i = 0; i < num_columns; ++i)
{
if (i != 0)
writeFieldDelimiter();
writeField(*columns[i], *serializations[i], row_num);
}
writeRowEndDelimiter();
}
void JSONCompactEachRowRowOutputFormat::writeLine(const std::vector<String> & values)
{
writeRowStartDelimiter();
for (size_t i = 0; i < values.size(); ++i)
{
writeChar('\"', out);
writeString(values[i], out);
writeChar('\"', out);
if (i != values.size() - 1)
writeFieldDelimiter();
}
writeRowEndDelimiter();
}
void JSONCompactEachRowRowOutputFormat::doWritePrefix()
{
const auto & header = getPort(PortKind::Main).getHeader();
if (with_names)
writeLine(header.getNames());
if (with_types)
writeLine(header.getDataTypeNames());
}
void JSONCompactEachRowRowOutputFormat::consumeTotals(DB::Chunk chunk)
{
if (with_names)
IRowOutputFormat::consumeTotals(std::move(chunk));
}
void registerOutputFormatJSONCompactEachRow(FormatFactory & factory)
{
for (bool yield_strings : {false, true})
{
auto register_func = [&](const String & format_name, bool with_names, bool with_types)
{
factory.registerOutputFormat(format_name, [yield_strings, with_names, with_types](
WriteBuffer & buf,
const Block & sample,
const RowOutputFormatParams & params,
const FormatSettings & format_settings)
{
return std::make_shared<JSONCompactEachRowRowOutputFormat>(buf, sample, params, format_settings, with_names, with_types, yield_strings);
});
factory.markOutputFormatSupportsParallelFormatting(format_name);
};
registerWithNamesAndTypes(yield_strings ? "JSONCompactStringsEachRow" : "JSONCompactEachRow", register_func);
}
}
}
| 27.808 | 152 | 0.682681 | 540522905 |
a8057a68a9b2951cfab34cb04e3a82cd1f6e045c | 26,344 | cpp | C++ | src/lp_data/HighsModelUtils.cpp | ERGO-Code/HiGHS | 5196737298b23cbf1b8d300ca3e1bf3898041801 | [
"MIT"
] | 241 | 2018-03-27T15:04:14.000Z | 2022-03-31T14:44:18.000Z | src/lp_data/HighsModelUtils.cpp | ERGO-Code/HiGHS | 5196737298b23cbf1b8d300ca3e1bf3898041801 | [
"MIT"
] | 384 | 2018-03-28T10:34:36.000Z | 2022-03-31T20:19:37.000Z | src/lp_data/HighsModelUtils.cpp | ERGO-Code/HiGHS | 5196737298b23cbf1b8d300ca3e1bf3898041801 | [
"MIT"
] | 54 | 2018-04-28T22:43:19.000Z | 2022-03-31T14:44:22.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the HiGHS linear optimization suite */
/* */
/* Written and engineered 2008-2021 at the University of Edinburgh */
/* */
/* Available as open-source under the MIT License */
/* */
/* Authors: Julian Hall, Ivet Galabova, Qi Huangfu, Leona Gottwald */
/* and Michael Feldmeier */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file lp_data/HighsUtils.cpp
* @brief Class-independent utilities for HiGHS
*/
#include "lp_data/HighsModelUtils.h"
#include <algorithm>
#include <vector>
#include "HConfig.h"
#include "io/HighsIO.h"
#include "lp_data/HConst.h"
#include "util/HighsUtils.h"
HighsStatus assessMatrixDimensions(const HighsLogOptions& log_options,
const std::string matrix_name,
const HighsInt num_vec,
const vector<HighsInt>& matrix_start,
const vector<HighsInt>& matrix_index,
const vector<double>& matrix_value) {
HighsStatus return_status = HighsStatus::kOk;
// Use error_found to track whether an error has been found in multiple tests
bool error_found = false;
// Assess main dimensions
bool legal_num_vec = num_vec >= 0;
if (!legal_num_vec) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal number of vectors = %" HIGHSINT_FORMAT
"\n",
matrix_name.c_str(), num_vec);
error_found = true;
}
HighsInt matrix_start_size = matrix_start.size();
bool legal_matrix_start_size = false;
// Don't expect the matrix_start_size to be legal if there are no vectors
if (num_vec > 0) {
legal_matrix_start_size = matrix_start_size >= num_vec + 1;
if (!legal_matrix_start_size) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal start vector size = %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), matrix_start_size, num_vec + 1);
error_found = true;
}
}
if (matrix_start_size > 0) {
// Check whether the first start is zero
if (matrix_start[0]) {
highsLogUser(log_options, HighsLogType::kWarning,
"%s matrix start vector begins with %" HIGHSINT_FORMAT
" rather than 0\n",
matrix_name.c_str(), matrix_start[0]);
error_found = true;
}
}
// Possibly check the sizes of the index and value vectors. Can only
// do this with the number of nonzeros, and this is only known if
// the start vector has a legal size. Setting num_nz = 0 otherwise
// means that all tests pass, as they just check that the sizes of
// the index and value vectors are non-negative.
HighsInt num_nz = 0;
if (legal_matrix_start_size) num_nz = matrix_start[num_vec];
bool legal_num_nz = num_nz >= 0;
if (!legal_num_nz) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal number of nonzeros = %" HIGHSINT_FORMAT
"\n",
matrix_name.c_str(), num_nz);
error_found = true;
} else {
HighsInt matrix_index_size = matrix_index.size();
HighsInt matrix_value_size = matrix_value.size();
bool legal_matrix_index_size = matrix_index_size >= num_nz;
bool legal_matrix_value_size = matrix_value_size >= num_nz;
if (!legal_matrix_index_size) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal index vector size = %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), matrix_index_size, num_nz);
error_found = true;
}
if (!legal_matrix_value_size) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal value vector size = %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), matrix_value_size, num_nz);
error_found = true;
}
}
if (error_found)
return_status = HighsStatus::kError;
else
return_status = HighsStatus::kOk;
return return_status;
}
HighsStatus assessMatrix(const HighsLogOptions& log_options,
const std::string matrix_name, const HighsInt vec_dim,
const HighsInt num_vec, vector<HighsInt>& matrix_start,
vector<HighsInt>& matrix_index,
vector<double>& matrix_value,
const double small_matrix_value,
const double large_matrix_value) {
if (assessMatrixDimensions(log_options, matrix_name, num_vec, matrix_start,
matrix_index, matrix_value) == HighsStatus::kError)
return HighsStatus::kError;
const HighsInt num_nz = matrix_start[num_vec];
if (num_vec <= 0) return HighsStatus::kOk;
if (num_nz <= 0) return HighsStatus::kOk;
HighsStatus return_status = HighsStatus::kOk;
bool error_found = false;
bool warning_found = false;
// Assess the starts
// Set up previous_start for a fictitious previous empty packed vector
HighsInt previous_start = matrix_start[0];
for (HighsInt ix = 0; ix < num_vec; ix++) {
HighsInt this_start = matrix_start[ix];
bool this_start_too_small = this_start < previous_start;
if (this_start_too_small) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
" has illegal start of %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT
" = "
"previous start\n",
matrix_name.c_str(), ix, this_start, previous_start);
return HighsStatus::kError;
}
bool this_start_too_big = this_start > num_nz;
if (this_start_too_big) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
" has illegal start of %" HIGHSINT_FORMAT
" > %" HIGHSINT_FORMAT
" = "
"number of nonzeros\n",
matrix_name.c_str(), ix, this_start, num_nz);
return HighsStatus::kError;
}
}
// Assess the indices and values
// Count the number of acceptable indices/values
HighsInt num_new_nz = 0;
HighsInt num_small_values = 0;
double max_small_value = 0;
double min_small_value = kHighsInf;
// Set up a zeroed vector to detect duplicate indices
vector<HighsInt> check_vector;
if (vec_dim > 0) check_vector.assign(vec_dim, 0);
for (HighsInt ix = 0; ix < num_vec; ix++) {
HighsInt from_el = matrix_start[ix];
HighsInt to_el = matrix_start[ix + 1];
// Account for any index-value pairs removed so far
matrix_start[ix] = num_new_nz;
for (HighsInt el = from_el; el < to_el; el++) {
// Check the index
HighsInt component = matrix_index[el];
// Check that the index is non-negative
bool legal_component = component >= 0;
if (!legal_component) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT
", is illegal index %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), ix, el, component);
return HighsStatus::kError;
}
// Check that the index does not exceed the vector dimension
legal_component = component < vec_dim;
if (!legal_component) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT
", is illegal index "
"%12" HIGHSINT_FORMAT " >= %" HIGHSINT_FORMAT
" = vector dimension\n",
matrix_name.c_str(), ix, el, component, vec_dim);
return HighsStatus::kError;
}
// Check that the index has not already ocurred
legal_component = check_vector[component] == 0;
if (!legal_component) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT
", is duplicate index %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), ix, el, component);
return HighsStatus::kError;
}
// Indicate that the index has occurred
check_vector[component] = 1;
// Check the value
double abs_value = fabs(matrix_value[el]);
/*
// Check that the value is not zero
bool zero_value = abs_value == 0;
if (zero_value) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT ", entry %"
HIGHSINT_FORMAT ", is zero\n", matrix_name.c_str(), ix, el); return
HighsStatus::kError;
}
*/
// Check that the value is not too large
bool large_value = abs_value > large_matrix_value;
if (large_value) {
highsLogUser(
log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT ", is large value |%g| >= %g\n",
matrix_name.c_str(), ix, el, abs_value, large_matrix_value);
return HighsStatus::kError;
}
bool ok_value = abs_value > small_matrix_value;
if (!ok_value) {
if (max_small_value < abs_value) max_small_value = abs_value;
if (min_small_value > abs_value) min_small_value = abs_value;
num_small_values++;
}
if (ok_value) {
// Shift the index and value of the OK entry to the new
// position in the index and value vectors, and increment
// the new number of nonzeros
matrix_index[num_new_nz] = matrix_index[el];
matrix_value[num_new_nz] = matrix_value[el];
num_new_nz++;
} else {
// Zero the check_vector entry since the small value
// _hasn't_ occurred
check_vector[component] = 0;
}
}
// Zero check_vector
for (HighsInt el = matrix_start[ix]; el < num_new_nz; el++)
check_vector[matrix_index[el]] = 0;
#ifdef HiGHSDEV
// NB This is very expensive so shouldn't be true
const bool check_check_vector = false;
if (check_check_vector) {
// Check zeroing of check vector
for (HighsInt component = 0; component < vec_dim; component++) {
if (check_vector[component]) error_found = true;
}
if (error_found)
highsLogUser(log_options, HighsLogType::kError,
"assessMatrix: check_vector not zeroed\n");
}
#endif
}
if (num_small_values) {
highsLogUser(log_options, HighsLogType::kWarning,
"%s matrix packed vector contains %" HIGHSINT_FORMAT
" |values| in [%g, %g] "
"less than %g: ignored\n",
matrix_name.c_str(), num_small_values, min_small_value,
max_small_value, small_matrix_value);
warning_found = true;
}
matrix_start[num_vec] = num_new_nz;
if (error_found)
return_status = HighsStatus::kError;
else if (warning_found)
return_status = HighsStatus::kWarning;
else
return_status = HighsStatus::kOk;
return return_status;
}
void analyseModelBounds(const HighsLogOptions& log_options, const char* message,
HighsInt numBd, const std::vector<double>& lower,
const std::vector<double>& upper) {
if (numBd == 0) return;
HighsInt numFr = 0;
HighsInt numLb = 0;
HighsInt numUb = 0;
HighsInt numBx = 0;
HighsInt numFx = 0;
for (HighsInt ix = 0; ix < numBd; ix++) {
if (highs_isInfinity(-lower[ix])) {
// Infinite lower bound
if (highs_isInfinity(upper[ix])) {
// Infinite lower bound and infinite upper bound: Fr
numFr++;
} else {
// Infinite lower bound and finite upper bound: Ub
numUb++;
}
} else {
// Finite lower bound
if (highs_isInfinity(upper[ix])) {
// Finite lower bound and infinite upper bound: Lb
numLb++;
} else {
// Finite lower bound and finite upper bound:
if (lower[ix] < upper[ix]) {
// Distinct finite bounds: Bx
numBx++;
} else {
// Equal finite bounds: Fx
numFx++;
}
}
}
}
highsLogDev(log_options, HighsLogType::kInfo,
"Analysing %" HIGHSINT_FORMAT " %s bounds\n", numBd, message);
if (numFr > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" Free: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numFr, (100 * numFr) / numBd);
if (numLb > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" LB: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numLb, (100 * numLb) / numBd);
if (numUb > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" UB: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numUb, (100 * numUb) / numBd);
if (numBx > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" Boxed: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numBx, (100 * numBx) / numBd);
if (numFx > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" Fixed: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numFx, (100 * numFx) / numBd);
highsLogDev(log_options, HighsLogType::kInfo,
"grep_CharMl,%s,Free,LB,UB,Boxed,Fixed\n", message);
highsLogDev(log_options, HighsLogType::kInfo,
"grep_CharMl,%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT
",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT
",%" HIGHSINT_FORMAT "\n",
numBd, numFr, numLb, numUb, numBx, numFx);
}
std::string statusToString(const HighsBasisStatus status, const double lower,
const double upper) {
switch (status) {
case HighsBasisStatus::kLower:
if (lower == upper) {
return "FX";
} else {
return "LB";
}
break;
case HighsBasisStatus::kBasic:
return "BS";
break;
case HighsBasisStatus::kUpper:
return "UB";
break;
case HighsBasisStatus::kZero:
return "FR";
break;
case HighsBasisStatus::kNonbasic:
return "NB";
break;
}
return "";
}
void writeModelBoundSolution(FILE* file, const bool columns, const HighsInt dim,
const std::vector<double>& lower,
const std::vector<double>& upper,
const std::vector<std::string>& names,
const std::vector<double>& primal,
const std::vector<double>& dual,
const std::vector<HighsBasisStatus>& status) {
const bool have_names = names.size() > 0;
const bool have_primal = primal.size() > 0;
const bool have_dual = dual.size() > 0;
const bool have_basis = status.size() > 0;
if (have_names) assert((int)names.size() >= dim);
if (have_primal) assert((int)primal.size() >= dim);
if (have_dual) assert((int)dual.size() >= dim);
if (have_basis) assert((int)status.size() >= dim);
std::string var_status_string;
if (columns) {
fprintf(file, "Columns\n");
} else {
fprintf(file, "Rows\n");
}
fprintf(
file,
" Index Status Lower Upper Primal Dual");
if (have_names) {
fprintf(file, " Name\n");
} else {
fprintf(file, "\n");
}
for (HighsInt ix = 0; ix < dim; ix++) {
if (have_basis) {
var_status_string = statusToString(status[ix], lower[ix], upper[ix]);
} else {
var_status_string = "";
}
fprintf(file, "%9" HIGHSINT_FORMAT " %4s %12g %12g", ix,
var_status_string.c_str(), lower[ix], upper[ix]);
if (have_primal) {
fprintf(file, " %12g", primal[ix]);
} else {
fprintf(file, " ");
}
if (have_dual) {
fprintf(file, " %12g", dual[ix]);
} else {
fprintf(file, " ");
}
if (have_names) {
fprintf(file, " %-s\n", names[ix].c_str());
} else {
fprintf(file, "\n");
}
}
}
void writeModelSolution(FILE* file, const HighsOptions& options,
double solutionObjective, const HighsInt dim,
const std::vector<std::string>& names,
const std::vector<double>& primal,
const std::vector<HighsVarType>& integrality) {
const bool have_names = names.size() > 0;
const bool have_primal = primal.size() > 0;
const bool have_integrality = integrality.size() > 0;
if (!have_names || !have_primal) return;
if (have_names) assert((int)names.size() >= dim);
if (have_primal) assert((int)primal.size() >= dim);
if (have_integrality) assert((int)integrality.size() >= dim);
std::array<char, 32> objStr = highsDoubleToString(solutionObjective, 1e-13);
fprintf(file, "=obj= %s\n", objStr.data());
for (HighsInt ix = 0; ix < dim; ix++) {
std::array<char, 32> valStr = highsDoubleToString(primal[ix], 1e-13);
fprintf(file, "%-s %s\n", names[ix].c_str(), valStr.data());
}
}
bool namesWithSpaces(const HighsInt num_name,
const std::vector<std::string>& names, const bool report) {
bool names_with_spaces = false;
for (HighsInt ix = 0; ix < num_name; ix++) {
HighsInt space_pos = names[ix].find(" ");
if (space_pos >= 0) {
if (report)
printf(
"Name |%s| contains a space character in position %" HIGHSINT_FORMAT
"\n",
names[ix].c_str(), space_pos);
names_with_spaces = true;
}
}
return names_with_spaces;
}
HighsInt maxNameLength(const HighsInt num_name,
const std::vector<std::string>& names) {
HighsInt max_name_length = 0;
for (HighsInt ix = 0; ix < num_name; ix++)
max_name_length = std::max((HighsInt)names[ix].length(), max_name_length);
return max_name_length;
}
HighsStatus normaliseNames(const HighsLogOptions& log_options,
const std::string name_type, const HighsInt num_name,
std::vector<std::string>& names,
HighsInt& max_name_length) {
// Record the desired maximum name length
HighsInt desired_max_name_length = max_name_length;
// First look for empty names
HighsInt num_empty_name = 0;
std::string name_prefix = name_type.substr(0, 1);
bool names_with_spaces = false;
for (HighsInt ix = 0; ix < num_name; ix++) {
if ((HighsInt)names[ix].length() == 0) num_empty_name++;
}
// If there are no empty names - in which case they will all be
// replaced - find the maximum name length
if (!num_empty_name) max_name_length = maxNameLength(num_name, names);
bool construct_names =
num_empty_name || max_name_length > desired_max_name_length;
if (construct_names) {
// Construct names, either because they are empty names, or
// because the existing names are too long
highsLogUser(log_options, HighsLogType::kWarning,
"There are empty or excessively-long %s names: using "
"constructed names with prefix %s\n",
name_type.c_str(), name_prefix.c_str());
for (HighsInt ix = 0; ix < num_name; ix++)
names[ix] = name_prefix + std::to_string(ix);
} else {
// Using original names, so look to see whether there are names with spaces
names_with_spaces = namesWithSpaces(num_name, names);
}
// Find the final maximum name length
max_name_length = maxNameLength(num_name, names);
// Can't have names with spaces and more than 8 characters
if (max_name_length > 8 && names_with_spaces) return HighsStatus::kError;
if (construct_names) return HighsStatus::kWarning;
return HighsStatus::kOk;
}
HighsBasisStatus checkedVarHighsNonbasicStatus(
const HighsBasisStatus ideal_status, const double lower,
const double upper) {
HighsBasisStatus checked_status;
if (ideal_status == HighsBasisStatus::kLower ||
ideal_status == HighsBasisStatus::kZero) {
// Looking to give status LOWER or ZERO
if (highs_isInfinity(-lower)) {
// Lower bound is infinite
if (highs_isInfinity(upper)) {
// Upper bound is infinite
checked_status = HighsBasisStatus::kZero;
} else {
// Upper bound is finite
checked_status = HighsBasisStatus::kUpper;
}
} else {
checked_status = HighsBasisStatus::kLower;
}
} else {
// Looking to give status UPPER
if (highs_isInfinity(upper)) {
// Upper bound is infinite
if (highs_isInfinity(-lower)) {
// Lower bound is infinite
checked_status = HighsBasisStatus::kZero;
} else {
// Upper bound is finite
checked_status = HighsBasisStatus::kLower;
}
} else {
checked_status = HighsBasisStatus::kUpper;
}
}
return checked_status;
}
// Return a string representation of SolutionStatus
std::string utilSolutionStatusToString(const HighsInt solution_status) {
switch (solution_status) {
case kSolutionStatusNone:
return "None";
break;
case kSolutionStatusInfeasible:
return "Infeasible";
break;
case kSolutionStatusFeasible:
return "Feasible";
break;
default:
assert(1 == 0);
return "Unrecognised solution status";
}
}
// Return a string representation of HighsBasisStatus
std::string utilBasisStatusToString(const HighsBasisStatus basis_status) {
switch (basis_status) {
case HighsBasisStatus::kLower:
return "At lower/fixed bound";
break;
case HighsBasisStatus::kBasic:
return "Basic";
break;
case HighsBasisStatus::kUpper:
return "At upper bound";
break;
case HighsBasisStatus::kZero:
return "Free at zero";
break;
case HighsBasisStatus::kNonbasic:
return "Nonbasic";
break;
default:
assert(1 == 0);
return "Unrecognised solution status";
}
}
// Return a string representation of basis validity
std::string utilBasisValidityToString(const HighsInt basis_validity) {
if (basis_validity) {
return "Valid";
} else {
return "Not valid";
}
}
// Return a string representation of HighsModelStatus.
std::string utilModelStatusToString(const HighsModelStatus model_status) {
switch (model_status) {
case HighsModelStatus::kNotset:
return "Not Set";
break;
case HighsModelStatus::kLoadError:
return "Load error";
break;
case HighsModelStatus::kModelError:
return "Model error";
break;
case HighsModelStatus::kPresolveError:
return "Presolve error";
break;
case HighsModelStatus::kSolveError:
return "Solve error";
break;
case HighsModelStatus::kPostsolveError:
return "Postsolve error";
break;
case HighsModelStatus::kModelEmpty:
return "Model empty";
break;
case HighsModelStatus::kOptimal:
return "Optimal";
break;
case HighsModelStatus::kInfeasible:
return "Infeasible";
break;
case HighsModelStatus::kUnboundedOrInfeasible:
return "Primal infeasible or unbounded";
break;
case HighsModelStatus::kUnbounded:
return "Unbounded";
break;
case HighsModelStatus::kObjectiveBound:
return "Reached objective bound";
break;
case HighsModelStatus::kObjectiveTarget:
return "Reached objective target";
break;
case HighsModelStatus::kTimeLimit:
return "Reached time limit";
break;
case HighsModelStatus::kIterationLimit:
return "Reached iteration limit";
break;
case HighsModelStatus::kUnknown:
return "Unknown";
break;
default:
assert(1 == 0);
return "Unrecognised HiGHS model status";
}
}
void zeroHighsIterationCounts(HighsIterationCounts& iteration_counts) {
iteration_counts.simplex = 0;
iteration_counts.ipm = 0;
iteration_counts.crossover = 0;
iteration_counts.qp = 0;
}
// Deduce the HighsStatus value corresponding to a HighsModelStatus value.
HighsStatus highsStatusFromHighsModelStatus(HighsModelStatus model_status) {
switch (model_status) {
case HighsModelStatus::kNotset:
return HighsStatus::kError;
case HighsModelStatus::kLoadError:
return HighsStatus::kError;
case HighsModelStatus::kModelError:
return HighsStatus::kError;
case HighsModelStatus::kPresolveError:
return HighsStatus::kError;
case HighsModelStatus::kSolveError:
return HighsStatus::kError;
case HighsModelStatus::kPostsolveError:
return HighsStatus::kError;
case HighsModelStatus::kModelEmpty:
return HighsStatus::kOk;
case HighsModelStatus::kOptimal:
return HighsStatus::kOk;
case HighsModelStatus::kInfeasible:
return HighsStatus::kOk;
case HighsModelStatus::kUnboundedOrInfeasible:
return HighsStatus::kOk;
case HighsModelStatus::kUnbounded:
return HighsStatus::kOk;
case HighsModelStatus::kObjectiveBound:
return HighsStatus::kOk;
case HighsModelStatus::kObjectiveTarget:
return HighsStatus::kOk;
case HighsModelStatus::kTimeLimit:
return HighsStatus::kWarning;
case HighsModelStatus::kIterationLimit:
return HighsStatus::kWarning;
case HighsModelStatus::kUnknown:
return HighsStatus::kWarning;
default:
return HighsStatus::kError;
}
}
| 37.052039 | 80 | 0.605641 | ERGO-Code |
a805cf5a88e2c33b7877e17769b40ac702621243 | 178 | hpp | C++ | dev/test/so_5_extra/disp/asio_one_thread/multifile_hello/a.hpp | Stiffstream/so5extra | 20f4c83ecde1509fbaf337dcf40f2f49dcf2690d | [
"BSD-3-Clause"
] | 12 | 2020-01-02T01:32:50.000Z | 2022-02-07T17:55:54.000Z | dev/test/so_5_extra/disp/asio_one_thread/multifile_hello/a.hpp | Stiffstream/so5extra | 20f4c83ecde1509fbaf337dcf40f2f49dcf2690d | [
"BSD-3-Clause"
] | 1 | 2019-09-04T12:33:35.000Z | 2020-01-15T15:22:20.000Z | dev/test/so_5_extra/disp/asio_one_thread/multifile_hello/a.hpp | Stiffstream/so5extra | 20f4c83ecde1509fbaf337dcf40f2f49dcf2690d | [
"BSD-3-Clause"
] | 3 | 2019-08-30T09:55:26.000Z | 2022-03-19T12:29:04.000Z | #pragma once
#include <so_5_extra/disp/asio_one_thread/pub.hpp>
void make_coop_a(
so_5::environment_t & env,
so_5::extra::disp::asio_one_thread::dispatcher_handle_t disp );
| 19.777778 | 64 | 0.775281 | Stiffstream |
a806c246312aa0a08440446a82ca16f46c0addeb | 2,314 | hpp | C++ | thirdparty/liblsdj/lsdj_wavetable_import/wavetable_importer.hpp | fossabot/RetroPlug | 5a39379bd10d2e2c0b13a0850380db4d5a58cdd3 | [
"MIT"
] | 186 | 2019-05-14T15:15:33.000Z | 2022-03-21T22:27:10.000Z | thirdparty/liblsdj/lsdj_wavetable_import/wavetable_importer.hpp | fossabot/RetroPlug | 5a39379bd10d2e2c0b13a0850380db4d5a58cdd3 | [
"MIT"
] | 70 | 2018-05-14T15:44:17.000Z | 2020-04-18T14:34:02.000Z | thirdparty/liblsdj/lsdj_wavetable_import/wavetable_importer.hpp | fossabot/RetroPlug | 5a39379bd10d2e2c0b13a0850380db4d5a58cdd3 | [
"MIT"
] | 9 | 2019-05-17T08:24:42.000Z | 2021-11-14T12:00:11.000Z | /*
This file is a part of liblsdj, a C library for managing everything
that has to do with LSDJ, software for writing music (chiptune) with
your gameboy. For more information, see:
* https://github.com/stijnfrishert/liblsdj
* http://www.littlesounddj.com
--------------------------------------------------------------------------------
MIT License
Copyright (c) 2018 - 2020 Stijn Frishert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef LSDJ_WAVETABLE_IMPORTER_HPP
#define LSDJ_WAVETABLE_IMPORTER_HPP
#include <ghc/filesystem.hpp>
#include <string>
#include <vector>
#include <lsdj/error.h>
#include <lsdj/song.h>
namespace lsdj
{
class WavetableImporter
{
public:
bool import(const std::string& projectName, const std::string& wavetableName);
public:
std::string outputName;
uint8_t wavetableIndex = 0;
bool zero = false;
bool force = false;
bool verbose = false;
private:
bool importToSav(const ghc::filesystem::path& path, const std::string& wavetableName);
bool importToLsdsng(const ghc::filesystem::path& path, const std::string& wavetableName);
std::pair<bool, unsigned int> importToSong(lsdj_song_t* song, const std::string& wavetableName);
};
}
#endif
| 33.536232 | 104 | 0.705272 | fossabot |
a8071346a47469afe16a2d445684590247dd14ad | 1,728 | cc | C++ | src/environments/OptimisticTask.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/environments/OptimisticTask.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/environments/OptimisticTask.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | #include "OptimisticTask.h"
/// In the optimistic task, you get reward epsilon in the normal
/// state, reward 1 in the good state.
OptimisticTask::OptimisticTask(real epsilon_, real delta_)
: Environment<int, int>(3, 2), epsilon(epsilon_), delta(delta_) {
Reset();
}
void OptimisticTask::Reset() {
state = 0;
reward = 0;
}
bool OptimisticTask::Act(const int& action) {
// get next state
switch (state) {
case 0:
if (action == 0) {
state = 0;
} else {
state = 1;
}
break;
case 1:
if (urandom() < delta) {
if (action == 0) {
state = 0;
} else {
state = 2;
}
}
break;
case 2:
if (action == 1) {
state = 2;
} else {
state = 1;
}
break;
}
// get next reward
switch (state) {
case 0:
case 2:
reward = epsilon;
break;
case 1:
reward = 0;
break;
}
return true;
}
DiscreteMDP* OptimisticTask::getMDP() const {
DiscreteMDP* mdp = new DiscreteMDP(n_states, n_actions);
// get next state
mdp->setTransitionProbability(0, 0, 0, 1);
mdp->setTransitionProbability(0, 1, 1, 1);
mdp->setTransitionProbability(2, 0, 1, 1);
mdp->setTransitionProbability(2, 1, 2, 1);
mdp->setTransitionProbability(1, 0, 0, delta);
mdp->setTransitionProbability(1, 0, 1, 1 - delta);
mdp->setTransitionProbability(1, 1, 2, delta);
mdp->setTransitionProbability(1, 1, 1, 1 - delta);
mdp->addFixedReward(0, 0, epsilon);
mdp->addFixedReward(0, 1, epsilon);
mdp->addFixedReward(1, 0, 0.0);
mdp->addFixedReward(1, 1, 0.0);
mdp->addFixedReward(2, 0, epsilon);
mdp->addFixedReward(2, 1, epsilon);
return mdp;
}
| 20.819277 | 69 | 0.58044 | litlpoet |
a807666b3ef265ddfe2d781cef95f4c8c5a67a31 | 1,150 | cc | C++ | poj/2/2914.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/2/2914.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/2/2914.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
int g[501][501];
int stoer_wagner(int N)
{
vector<int> v(N);
for (int i = 0; i < N; i++) {
v[i] = i;
}
int cut = numeric_limits<int>::max();
for (int m = N; m > 1; m--) {
//vector<int> ws(m, 0);
int ws[501];
fill(ws, ws + m, 0);
int s, t = 0;
int w;
for (int k = 0; k < m; k++) {
s = t;
t = distance(ws, max_element(ws, ws + m));
w = ws[t];
ws[t] = -1;
for (int i = 0; i < m; i++) {
if (ws[i] >= 0) {
ws[i] += g[v[t]][v[i]];
}
}
}
for (int i = 0; i < m; i++) {
g[v[i]][v[s]] += g[v[i]][v[t]];
g[v[s]][v[i]] += g[v[t]][v[i]];
}
v.erase(v.begin() + t);
cut = min(cut, w);
}
return cut;
}
int main()
{
int N, M;
while (scanf("%d %d", &N, &M) != EOF) {
for (int i = 0; i < N; i++) {
fill(g[i], g[i] + N, 0);
}
for (int i = 0; i < M; i++) {
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
g[u][v] += w;
g[v][u] += w;
}
printf("%d\n", stoer_wagner(N));
}
return 0;
} | 19.166667 | 48 | 0.394783 | eagletmt |
a808027f3270dece78545009ed5d51eda359a988 | 17,912 | cc | C++ | extensions/browser/api/bluetooth/bluetooth_apitest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-01-25T09:58:49.000Z | 2020-01-25T09:58:49.000Z | extensions/browser/api/bluetooth/bluetooth_apitest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | extensions/browser/api/bluetooth/bluetooth_apitest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/ui_test_utils.h"
#include "device/bluetooth/bluetooth_adapter.h"
#include "device/bluetooth/bluetooth_uuid.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
#include "device/bluetooth/test/mock_bluetooth_device.h"
#include "device/bluetooth/test/mock_bluetooth_discovery_session.h"
#include "extensions/browser/api/bluetooth/bluetooth_api.h"
#include "extensions/browser/api/bluetooth/bluetooth_event_router.h"
#include "extensions/common/test_util.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "testing/gmock/include/gmock/gmock.h"
using device::BluetoothAdapter;
using device::BluetoothDevice;
using device::BluetoothDiscoverySession;
using device::BluetoothUUID;
using device::MockBluetoothAdapter;
using device::MockBluetoothDevice;
using device::MockBluetoothDiscoverySession;
using extensions::Extension;
using extensions::ResultCatcher;
namespace utils = extension_function_test_utils;
namespace api = extensions::core_api;
namespace {
static const char* kAdapterAddress = "A1:A2:A3:A4:A5:A6";
static const char* kName = "whatsinaname";
class BluetoothApiTest : public ExtensionApiTest {
public:
BluetoothApiTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
ExtensionApiTest::SetUpOnMainThread();
empty_extension_ = extensions::test_util::CreateEmptyExtension();
SetUpMockAdapter();
}
virtual void TearDownOnMainThread() OVERRIDE {
EXPECT_CALL(*mock_adapter_, RemoveObserver(testing::_));
}
void SetUpMockAdapter() {
// The browser will clean this up when it is torn down
mock_adapter_ = new testing::StrictMock<MockBluetoothAdapter>();
event_router()->SetAdapterForTest(mock_adapter_);
device1_.reset(new testing::NiceMock<MockBluetoothDevice>(
mock_adapter_, 0, "d1", "11:12:13:14:15:16",
true /* paired */, true /* connected */));
device2_.reset(new testing::NiceMock<MockBluetoothDevice>(
mock_adapter_, 0, "d2", "21:22:23:24:25:26",
false /* paired */, false /* connected */));
device3_.reset(new testing::NiceMock<MockBluetoothDevice>(
mock_adapter_, 0, "d3", "31:32:33:34:35:36",
false /* paired */, false /* connected */));
}
void DiscoverySessionCallback(
const BluetoothAdapter::DiscoverySessionCallback& callback,
const BluetoothAdapter::ErrorCallback& error_callback) {
if (mock_session_.get()) {
callback.Run(
scoped_ptr<BluetoothDiscoverySession>(mock_session_.release()));
return;
}
error_callback.Run();
}
template <class T>
T* setupFunction(T* function) {
function->set_extension(empty_extension_.get());
function->set_has_callback(true);
return function;
}
protected:
testing::StrictMock<MockBluetoothAdapter>* mock_adapter_;
scoped_ptr<testing::NiceMock<MockBluetoothDiscoverySession> > mock_session_;
scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device1_;
scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device2_;
scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device3_;
extensions::BluetoothEventRouter* event_router() {
return bluetooth_api()->event_router();
}
extensions::BluetoothAPI* bluetooth_api() {
return extensions::BluetoothAPI::Get(browser()->profile());
}
private:
scoped_refptr<Extension> empty_extension_;
};
static void StopDiscoverySessionCallback(const base::Closure& callback,
const base::Closure& error_callback) {
callback.Run();
}
} // namespace
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetAdapterState) {
EXPECT_CALL(*mock_adapter_, GetAddress())
.WillOnce(testing::Return(kAdapterAddress));
EXPECT_CALL(*mock_adapter_, GetName())
.WillOnce(testing::Return(kName));
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(false));
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, IsDiscovering())
.WillOnce(testing::Return(false));
scoped_refptr<api::BluetoothGetAdapterStateFunction> get_adapter_state;
get_adapter_state = setupFunction(new api::BluetoothGetAdapterStateFunction);
scoped_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult(
get_adapter_state.get(), "[]", browser()));
ASSERT_TRUE(result.get() != NULL);
api::bluetooth::AdapterState state;
ASSERT_TRUE(api::bluetooth::AdapterState::Populate(*result, &state));
EXPECT_FALSE(state.available);
EXPECT_TRUE(state.powered);
EXPECT_FALSE(state.discovering);
EXPECT_EQ(kName, state.name);
EXPECT_EQ(kAdapterAddress, state.address);
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DeviceEvents) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("bluetooth/device_events")));
ExtensionTestMessageListener events_received("ready", true);
event_router()->DeviceAdded(mock_adapter_, device1_.get());
event_router()->DeviceAdded(mock_adapter_, device2_.get());
EXPECT_CALL(*device2_.get(), GetDeviceName())
.WillRepeatedly(testing::Return("the real d2"));
EXPECT_CALL(*device2_.get(), GetName())
.WillRepeatedly(testing::Return(base::UTF8ToUTF16("the real d2")));
event_router()->DeviceChanged(mock_adapter_, device2_.get());
event_router()->DeviceAdded(mock_adapter_, device3_.get());
event_router()->DeviceRemoved(mock_adapter_, device1_.get());
EXPECT_TRUE(events_received.WaitUntilSatisfied());
events_received.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Discovery) {
// Try with a failure to start. This will return an error as we haven't
// initialied a session object.
EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_))
.WillOnce(
testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback));
// StartDiscovery failure will not reference the adapter.
scoped_refptr<api::BluetoothStartDiscoveryFunction> start_function;
start_function = setupFunction(new api::BluetoothStartDiscoveryFunction);
std::string error(
utils::RunFunctionAndReturnError(start_function.get(), "[]", browser()));
ASSERT_FALSE(error.empty());
// Reset the adapter and initiate a discovery session. The ownership of the
// mock session will be passed to the event router.
ASSERT_FALSE(mock_session_.get());
SetUpMockAdapter();
// Create a mock session to be returned as a result. Get a handle to it as
// its ownership will be passed and |mock_session_| will be reset.
mock_session_.reset(new testing::NiceMock<MockBluetoothDiscoverySession>());
MockBluetoothDiscoverySession* session = mock_session_.get();
EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_))
.WillOnce(
testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback));
start_function = setupFunction(new api::BluetoothStartDiscoveryFunction);
(void)
utils::RunFunctionAndReturnError(start_function.get(), "[]", browser());
// End the discovery session. The StopDiscovery function should succeed.
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(true));
EXPECT_CALL(*session, Stop(testing::_, testing::_))
.WillOnce(testing::Invoke(StopDiscoverySessionCallback));
// StopDiscovery success will remove the session object, unreferencing the
// adapter.
scoped_refptr<api::BluetoothStopDiscoveryFunction> stop_function;
stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction);
(void) utils::RunFunctionAndReturnSingleResult(
stop_function.get(), "[]", browser());
// Reset the adapter. Simulate failure for stop discovery. The event router
// still owns the session. Make it appear inactive.
SetUpMockAdapter();
EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(false));
stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction);
error =
utils::RunFunctionAndReturnError(stop_function.get(), "[]", browser());
ASSERT_FALSE(error.empty());
SetUpMockAdapter();
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryCallback) {
mock_session_.reset(new testing::NiceMock<MockBluetoothDiscoverySession>());
MockBluetoothDiscoverySession* session = mock_session_.get();
EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_))
.WillOnce(
testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback));
EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(true));
EXPECT_CALL(*session, Stop(testing::_, testing::_))
.WillOnce(testing::Invoke(StopDiscoverySessionCallback));
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
ExtensionTestMessageListener discovery_started("ready", true);
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("bluetooth/discovery_callback")));
EXPECT_TRUE(discovery_started.WaitUntilSatisfied());
event_router()->DeviceAdded(mock_adapter_, device1_.get());
discovery_started.Reply("go");
ExtensionTestMessageListener discovery_stopped("ready", true);
EXPECT_CALL(*mock_adapter_, RemoveObserver(testing::_));
EXPECT_TRUE(discovery_stopped.WaitUntilSatisfied());
SetUpMockAdapter();
event_router()->DeviceAdded(mock_adapter_, device2_.get());
discovery_stopped.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryInProgress) {
EXPECT_CALL(*mock_adapter_, GetAddress())
.WillOnce(testing::Return(kAdapterAddress));
EXPECT_CALL(*mock_adapter_, GetName())
.WillOnce(testing::Return(kName));
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(true));
// Fake that the adapter is discovering
EXPECT_CALL(*mock_adapter_, IsDiscovering())
.WillOnce(testing::Return(true));
event_router()->AdapterDiscoveringChanged(mock_adapter_, true);
// Cache a device before the extension starts discovering
event_router()->DeviceAdded(mock_adapter_, device1_.get());
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
mock_session_.reset(new testing::NiceMock<MockBluetoothDiscoverySession>());
MockBluetoothDiscoverySession* session = mock_session_.get();
EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_))
.WillOnce(
testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback));
EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(true));
EXPECT_CALL(*session, Stop(testing::_, testing::_))
.WillOnce(testing::Invoke(StopDiscoverySessionCallback));
ExtensionTestMessageListener discovery_started("ready", true);
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("bluetooth/discovery_in_progress")));
EXPECT_TRUE(discovery_started.WaitUntilSatisfied());
// Only this should be received. No additional notification should be sent for
// devices discovered before the discovery session started.
event_router()->DeviceAdded(mock_adapter_, device2_.get());
discovery_started.Reply("go");
ExtensionTestMessageListener discovery_stopped("ready", true);
EXPECT_CALL(*mock_adapter_, RemoveObserver(testing::_));
EXPECT_TRUE(discovery_stopped.WaitUntilSatisfied());
SetUpMockAdapter();
// This should never be received.
event_router()->DeviceAdded(mock_adapter_, device2_.get());
discovery_stopped.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, OnAdapterStateChanged) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
// Load and wait for setup
ExtensionTestMessageListener listener("ready", true);
ASSERT_TRUE(
LoadExtension(
test_data_dir_.AppendASCII("bluetooth/on_adapter_state_changed")));
EXPECT_TRUE(listener.WaitUntilSatisfied());
EXPECT_CALL(*mock_adapter_, GetAddress())
.WillOnce(testing::Return(kAdapterAddress));
EXPECT_CALL(*mock_adapter_, GetName())
.WillOnce(testing::Return(kName));
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(false));
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(false));
EXPECT_CALL(*mock_adapter_, IsDiscovering())
.WillOnce(testing::Return(false));
event_router()->AdapterPoweredChanged(mock_adapter_, false);
EXPECT_CALL(*mock_adapter_, GetAddress())
.WillOnce(testing::Return(kAdapterAddress));
EXPECT_CALL(*mock_adapter_, GetName())
.WillOnce(testing::Return(kName));
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, IsDiscovering())
.WillOnce(testing::Return(true));
event_router()->AdapterPresentChanged(mock_adapter_, true);
EXPECT_CALL(*mock_adapter_, GetAddress())
.WillOnce(testing::Return(kAdapterAddress));
EXPECT_CALL(*mock_adapter_, GetName())
.WillOnce(testing::Return(kName));
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, IsDiscovering())
.WillOnce(testing::Return(true));
event_router()->AdapterDiscoveringChanged(mock_adapter_, true);
listener.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevices) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
BluetoothAdapter::ConstDeviceList devices;
devices.push_back(device1_.get());
devices.push_back(device2_.get());
EXPECT_CALL(*mock_adapter_, GetDevices())
.Times(1)
.WillRepeatedly(testing::Return(devices));
// Load and wait for setup
ExtensionTestMessageListener listener("ready", true);
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("bluetooth/get_devices")));
EXPECT_TRUE(listener.WaitUntilSatisfied());
listener.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevice) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
EXPECT_CALL(*mock_adapter_, GetDevice(device1_->GetAddress()))
.WillOnce(testing::Return(device1_.get()));
EXPECT_CALL(*mock_adapter_, GetDevice(device2_->GetAddress()))
.Times(1)
.WillRepeatedly(testing::Return(static_cast<BluetoothDevice*>(NULL)));
// Load and wait for setup
ExtensionTestMessageListener listener("ready", true);
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("bluetooth/get_device")));
EXPECT_TRUE(listener.WaitUntilSatisfied());
listener.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DeviceInfo) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
// Set up the first device object to reflect a real-world device.
BluetoothAdapter::ConstDeviceList devices;
EXPECT_CALL(*device1_.get(), GetAddress())
.WillRepeatedly(testing::Return("A4:17:31:00:00:00"));
EXPECT_CALL(*device1_.get(), GetDeviceName())
.WillRepeatedly(testing::Return("Chromebook Pixel"));
EXPECT_CALL(*device1_.get(), GetName())
.WillRepeatedly(testing::Return(base::UTF8ToUTF16("Chromebook Pixel")));
EXPECT_CALL(*device1_.get(), GetBluetoothClass())
.WillRepeatedly(testing::Return(0x080104));
EXPECT_CALL(*device1_.get(), GetDeviceType())
.WillRepeatedly(testing::Return(BluetoothDevice::DEVICE_COMPUTER));
EXPECT_CALL(*device1_.get(), GetVendorIDSource())
.WillRepeatedly(testing::Return(BluetoothDevice::VENDOR_ID_BLUETOOTH));
EXPECT_CALL(*device1_.get(), GetVendorID())
.WillRepeatedly(testing::Return(0x00E0));
EXPECT_CALL(*device1_.get(), GetProductID())
.WillRepeatedly(testing::Return(0x240A));
EXPECT_CALL(*device1_.get(), GetDeviceID())
.WillRepeatedly(testing::Return(0x0400));
EXPECT_CALL(*device1_, GetRSSI()).WillRepeatedly(testing::Return(-42));
EXPECT_CALL(*device1_, GetCurrentHostTransmitPower())
.WillRepeatedly(testing::Return(-16));
EXPECT_CALL(*device1_, GetMaximumHostTransmitPower())
.WillRepeatedly(testing::Return(10));
BluetoothDevice::UUIDList uuids;
uuids.push_back(BluetoothUUID("1105"));
uuids.push_back(BluetoothUUID("1106"));
EXPECT_CALL(*device1_.get(), GetUUIDs())
.WillOnce(testing::Return(uuids));
devices.push_back(device1_.get());
// Leave the second largely empty so we can check a device without
// available information.
devices.push_back(device2_.get());
EXPECT_CALL(*mock_adapter_, GetDevices())
.Times(1)
.WillRepeatedly(testing::Return(devices));
// Load and wait for setup
ExtensionTestMessageListener listener("ready", true);
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("bluetooth/device_info")));
EXPECT_TRUE(listener.WaitUntilSatisfied());
listener.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
| 38.686825 | 80 | 0.749107 | Fusion-Rom |
a808fe8a5a392d42a9a9dd76074627d98b9a06f9 | 2,799 | cpp | C++ | src/config.cpp | manjogsingh/ComputerNetworks2020 | 37e061fcc0f988d9eb720cc8df54b9d1b627ce3f | [
"MIT"
] | null | null | null | src/config.cpp | manjogsingh/ComputerNetworks2020 | 37e061fcc0f988d9eb720cc8df54b9d1b627ce3f | [
"MIT"
] | null | null | null | src/config.cpp | manjogsingh/ComputerNetworks2020 | 37e061fcc0f988d9eb720cc8df54b9d1b627ce3f | [
"MIT"
] | 1 | 2020-11-03T00:11:43.000Z | 2020-11-03T00:11:43.000Z | #include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <sstream>
using namespace std;
struct configpeer{
int peerId;
string hostname;
int listport;
bool havefile;
} confp;
struct configcommon{
int noprfnbrs;
int unchokint;
int optunchokint;
string filename;
long filesize;
int piecesize;
} conf;
vector<string> split (string s, string delimiter) {
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
string token;
vector<string> res;
while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
token = s.substr (pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back (token);
}
res.push_back (s.substr (pos_start));
return res;
}
int main()
{
//Parsing Peer Info Config file
std::ifstream pFile ("samplePeerInfo.cfg");
if(pFile.is_open())
{
string delimiter=" ";
size_t pos = 0;
while(pFile.good()){
string line;
getline(pFile,line);
vector<string> v = split(line, delimiter);
confp.peerId=stoi(v[0]);
confp.hostname=v[1];
confp.listport=stoi(v[2]);
int hfile=stoi(v[3]);
(hfile==1) ? confp.havefile=true : confp.havefile=false;
}
}
else
{
std::cerr << "Couldn't open config file for reading.\n";
}
//Parsing Common Config file
std::ifstream cFile ("sampleCommon.cfg");
if (cFile.is_open())
{
string delimiter=" ";
size_t pos = 0;
string token1,token2;
while(cFile.good()){
string line;
getline(cFile,line);
pos=line.find(delimiter);
token1=line.substr(0,pos);
token2=line.substr(pos+1,line.length());
if(token1.compare("NumberOfPreferredNeighbors")==0){
conf.noprfnbrs=stoi(token2);
}
else if(token1.compare("UnchokingInterval")==0)
{
conf.unchokint=stoi(token2);
}
else if(token1.compare("OptimisticUnchokingInterval")==0)
{
conf.optunchokint=stoi(token2);
}
else if(token1.compare("FileName")==0)
{
conf.filename=token2;
}
else if(token1.compare("FileSize")==0)
{
conf.filesize=stoi(token2);
}
else{
conf.piecesize=stoi(token2);
}
}
}
else
{
std::cerr << "Couldn't open config file for reading.\n";
}
}
| 25.445455 | 73 | 0.518042 | manjogsingh |
a80ad36a5094a9d8084e3949d43e7a0c3bdbbb16 | 3,601 | cpp | C++ | week5_spanning_trees/1_connecting_points/connecting_points.cpp | cdlavila/Algorithms-on-Graphs | 7bbb9937ede317b0080932c73664748bc5a9f0d0 | [
"MIT"
] | null | null | null | week5_spanning_trees/1_connecting_points/connecting_points.cpp | cdlavila/Algorithms-on-Graphs | 7bbb9937ede317b0080932c73664748bc5a9f0d0 | [
"MIT"
] | null | null | null | week5_spanning_trees/1_connecting_points/connecting_points.cpp | cdlavila/Algorithms-on-Graphs | 7bbb9937ede317b0080932c73664748bc5a9f0d0 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
using namespace std;
// Disjoint set implementation
class disjoint_set {
private:
int *rank, *parent;
unsigned int n;
public:
// default constructor
disjoint_set() = default;
// Constructor to create and initialize sets of n items
disjoint_set(unsigned int n) {
rank = new int[n];
parent = new int[n];
this->n = n;
makeSet();
}
// Creates n single item sets
void makeSet() {
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
// Finds set of given item x
int find(int x) {
// Finds the representative of the set that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself Then x is not the representative of his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent and move I's node directly under the representative of this set
}
return parent[x];
}
// Do union of two sets represented by x and y.
void Union(int x, int y) {
// Find current sets of x and y
int xSet = find(x);
int ySet = find(y);
// If they are already in same set
if (xSet == ySet)
return;
// Put smaller ranked item under bigger ranked item if ranks are different
if (rank[xSet] < rank[ySet]) {
parent[xSet] = ySet;
} else if (rank[xSet] > rank[ySet]) {
parent[ySet] = xSet;
} else { // If ranks are same, then increment rank.
parent[ySet] = xSet;
rank[xSet]++;
}
}
};
// Undirected weighted edge implementation
class edge{
public:
int u, v;
double weight;
// default constructor
edge() = default;
// Constructor
edge(int u, int v, double weight) {
this->u = u;
this->v = v;
this->weight = weight;
}
};
// Sorting function by weight
bool sorting_by_weight(edge a, edge b) {
return a.weight < b.weight;
}
// Kruskal's algorithm implementation
pair<vector<edge>, double> kruskal(vector<edge> &edges) {
double total_cost = 0;
// for all u ∈ V : MakeSet(v)
disjoint_set ds(edges.size());
// X ← empty set
vector<edge> X(0);
// sort the edges E by weight
sort(edges.begin(), edges.end(), sorting_by_weight);
// for all {u, v} ∈ E in non-decreasing weight order:
for(edge e: edges) {
int u = e.u;
int v = e.v;
// if Find(u) ̸= Find(v):
if (ds.find(u) != ds.find(v)) {
// add {u, v} to X
X.push_back(e);
// Union(u, v)
ds.Union(u, v);
total_cost += e.weight;
}
}
return make_pair(X, total_cost);
}
// Distance between two points function
double distance_between_two_points(int x1, int y1, int x2, int y2) {
return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
}
// Minimum distance (problem solution)
double minimum_distance(vector<int> x, vector<int> y) {
// Constructing the edges list
unsigned int v = x.size();
vector<edge> edges(v);
for (int i = 0; i < v; i++) {
for (int j = i; j < v; j++) {
if (j != i) {
double weight = distance_between_two_points(x[i], y[i], x[j], y[j]);
edge e(i, j, weight);
edges.push_back(e);
}
}
}
// Running Kruskal's algorithm in our graph
pair<vector<edge>, double> result = kruskal(edges);
return result.second;
}
int main() {
size_t n;
cin >> n;
vector<int> x(n), y(n);
for (size_t i = 0; i < n; i++) {
cin >> x[i] >> y[i];
}
cout << fixed << setprecision(10) << minimum_distance(x, y) << "\n";
} | 24.834483 | 116 | 0.579006 | cdlavila |
a80cdb2f7df6c5b4846bdfbc1d92f136ae9c68df | 3,948 | cpp | C++ | Workbench/src/QtDwpViewer/DwpMediaRefContextMenu.cpp | magic-lantern-studio/mle-studio | e962ecf8bc64a854fcd997196be1857d078a2781 | [
"MIT"
] | null | null | null | Workbench/src/QtDwpViewer/DwpMediaRefContextMenu.cpp | magic-lantern-studio/mle-studio | e962ecf8bc64a854fcd997196be1857d078a2781 | [
"MIT"
] | 28 | 2020-06-24T16:47:07.000Z | 2020-08-06T05:15:59.000Z | Workbench/src/QtDwpViewer/DwpMediaRefContextMenu.cpp | magic-lantern-studio/mle-studio | e962ecf8bc64a854fcd997196be1857d078a2781 | [
"MIT"
] | null | null | null | // COPYRIGHT_BEGIN
//
// The MIT License (MIT)
//
// Copyright (c) 2020-2021 Wizzer Works
//
// 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.
//
// COPYRIGHT_END
#include <QDebug>
#include "DwpMediaRefContextMenu.h"
DwpMediaRefContextMenu::DwpMediaRefContextMenu(QObject *parent)
: DwpContextMenu(parent),
addPackageAction(nullptr),
addMediaRefSourceAction(nullptr),
addMediaRefTargetActionAction(nullptr)
{
// Do nothing extra.
}
DwpMediaRefContextMenu::~DwpMediaRefContextMenu()
{
if (addPackageAction != nullptr) delete addPackageAction;
if (addMediaRefSourceAction != nullptr) delete addMediaRefSourceAction;
if (addMediaRefTargetActionAction != nullptr) delete addMediaRefTargetActionAction;
}
void
DwpMediaRefContextMenu::init(QtDwpAttribute *attr)
{
// Call super class method.
DwpContextMenu::init(attr);
// Add menu actions.
if (mUseJava) {
// Support for Java and Android Digital Workprints.
addPackageAction = new QAction(tr("Add DWP Package Item"), this);
//addPackageAction->setShortcuts(QKeySequence::New);
addPackageAction->setStatusTip(tr("Create a new Package item"));
connect(addPackageAction, &QAction::triggered, this, &DwpMediaRefContextMenu::addPackage);
mMenu->addAction(addPackageAction);
//mMenu->addAction("Add DWP Package Item");
}
addMediaRefSourceAction = new QAction(tr("Add DWP MediaRefSource Item"), this);
//addMediaRefSourceAction->setShortcuts(QKeySequence::New);
addMediaRefSourceAction->setStatusTip(tr("Create a new MediaRefSource item"));
connect(addMediaRefSourceAction, &QAction::triggered, this, &DwpMediaRefContextMenu::addPackage);
mMenu->addAction(addMediaRefSourceAction);
//mMenu->addAction("Add DWP MediaRefSource Item");
addMediaRefTargetActionAction = new QAction(tr("Add DWP MediaRefTarget Item"), this);
//addMediaRefTargetActionAction->setShortcuts(QKeySequence::New);
addMediaRefTargetActionAction->setStatusTip(tr("Create a new Package item"));
connect(addMediaRefTargetActionAction, &QAction::triggered, this, &DwpMediaRefContextMenu::addPackage);
mMenu->addAction(addMediaRefTargetActionAction);
//mMenu->addAction("Add DWP MediaRefTarget Item");
}
void
DwpMediaRefContextMenu::addPackage()
{
qDebug() << "DwpMediaRefContextMenu: Adding DWP Package item";
emit DwpContextMenu::insertAttribute(QtDwpAttribute::DWP_ATTRIBUTE_PACKAGE, mAttr);
}
void
DwpMediaRefContextMenu::addMediaRefSource()
{
qDebug() << "DwpMediaRefContextMenu: Adding DWP MediaRefSource item";
emit DwpContextMenu::insertAttribute(QtDwpAttribute::DWP_ATTRIBUTE_MEDIAREFSOURCE, mAttr);
}
void
DwpMediaRefContextMenu::addMediaRefTarget()
{
qDebug() << "DwpMediaRefContextMenu: Adding DWP MediaRefTarget item";
emit DwpContextMenu::insertAttribute(QtDwpAttribute::DWP_ATTRIBUTE_MEDIAREFTARGET, mAttr);
}
| 39.48 | 107 | 0.756586 | magic-lantern-studio |
a8124c23f90671b0462603947b47d696e7d1d032 | 1,619 | hpp | C++ | modules/exponential/include/nt2/toolbox/exponential/function/simd/common/impl/expo/expo_base.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | 1 | 2022-03-24T03:35:10.000Z | 2022-03-24T03:35:10.000Z | modules/exponential/include/nt2/toolbox/exponential/function/simd/common/impl/expo/expo_base.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | null | null | null | modules/exponential/include/nt2/toolbox/exponential/function/simd/common/impl/expo/expo_base.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_EXPONENTIAL_FUNCTION_SIMD_COMMON_IMPL_EXPO_EXPO_BASE_HPP_INCLUDED
#define NT2_TOOLBOX_EXPONENTIAL_FUNCTION_SIMD_COMMON_IMPL_EXPO_EXPO_BASE_HPP_INCLUDED
#include <nt2/include/functions/select.hpp>
namespace nt2
{
namespace details
{
namespace internal
{
template < class A0, class Tag, class Speed_Tag >
struct exponential < A0, Tag, tag::simd_type, Speed_Tag>
{
typedef exp_reduction<A0,Tag> reduc_t;
typedef exp_finalization<A0,Tag,Speed_Tag> finalize_t;
// compute exp(ax)
static inline A0 expa(const A0& a0)
{
A0 hi, lo, x;
A0 k = reduc_t::reduce(a0, hi, lo, x);
A0 c = reduc_t::approx(x);
A0 ge = reduc_t::isgemaxlog(a0);
A0 le = reduc_t::isleminlog(a0);
return sel(ge, Inf<A0>(),
sel(le, Zero<A0>(),
finalize_t::finalize(a0, x, c, k, hi, lo)
)
);
}
};
}
}
}
#endif
// /////////////////////////////////////////////////////////////////////////////
// End of expo_base.hpp
// /////////////////////////////////////////////////////////////////////////////
| 33.040816 | 85 | 0.515133 | brycelelbach |
a813227e81753b00849810d67580f4564b45f55f | 968 | hpp | C++ | include/sharpen/AsyncReadWriteLock.hpp | iceBear67/Sharpen | 4f00fb13a2b3e7dc26cdb34596d58f958eb341f8 | [
"MIT"
] | 13 | 2020-10-25T04:02:07.000Z | 2022-03-29T13:21:30.000Z | include/sharpen/AsyncReadWriteLock.hpp | iceBear67/Sharpen | 4f00fb13a2b3e7dc26cdb34596d58f958eb341f8 | [
"MIT"
] | 18 | 2020-10-09T04:51:03.000Z | 2022-03-01T06:24:23.000Z | include/sharpen/AsyncReadWriteLock.hpp | iceBear67/Sharpen | 4f00fb13a2b3e7dc26cdb34596d58f958eb341f8 | [
"MIT"
] | 7 | 2020-10-23T04:25:28.000Z | 2022-03-23T06:52:39.000Z | #pragma once
#ifndef _SHARPEN_ASYNCREADWRITELOCK_HPP
#define _SHARPEN_ASYNCREADWRITELOCK_HPP
#include <list>
#include "AwaitableFuture.hpp"
namespace sharpen
{
enum class ReadWriteLockState
{
Free,
SharedReading,
UniquedWriting
};
class AsyncReadWriteLock:public sharpen::Noncopyable,public sharpen::Nonmovable
{
private:
using MyFuture = sharpen::AwaitableFuture<void>;
using MyFuturePtr = MyFuture*;
using List = std::list<MyFuturePtr>;
sharpen::ReadWriteLockState state_;
List readWaiters_;
List writeWaiters_;
sharpen::SpinLock lock_;
sharpen::Uint32 readers_;
void WriteUnlock() noexcept;
void ReadUnlock() noexcept;
public:
AsyncReadWriteLock();
void LockReadAsync();
void LockWriteAsync();
void Unlock() noexcept;
~AsyncReadWriteLock() noexcept = default;
};
}
#endif
| 19.755102 | 83 | 0.646694 | iceBear67 |
a813e0cbb9fa0a0e0053a8a103fd78a6322be976 | 1,396 | hpp | C++ | ext/src/java/util/Properties_XmlSupport.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/util/Properties_XmlSupport.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/util/Properties_XmlSupport.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <java/io/fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/util/fwd-POI.hpp>
#include <sun/util/spi/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class java::util::Properties_XmlSupport
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
static ::sun::util::spi::XmlPropertiesProvider* PROVIDER_;
/*void ctor(); (private) */
public: /* package */
static void load(Properties* props, ::java::io::InputStream* in);
/*static ::sun::util::spi::XmlPropertiesProvider* loadProvider(); (private) */
/*static ::sun::util::spi::XmlPropertiesProvider* loadProviderAsService(::java::lang::ClassLoader* cl); (private) */
/*static ::sun::util::spi::XmlPropertiesProvider* loadProviderFromProperty(::java::lang::ClassLoader* cl); (private) */
static void save(Properties* props, ::java::io::OutputStream* os, ::java::lang::String* comment, ::java::lang::String* encoding);
// Generated
public:
Properties_XmlSupport();
protected:
Properties_XmlSupport(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
static ::sun::util::spi::XmlPropertiesProvider*& PROVIDER();
virtual ::java::lang::Class* getClass0();
};
| 29.702128 | 133 | 0.698424 | pebble2015 |
a813ff369b15329f575fac851fe8a334b23785cd | 6,424 | cpp | C++ | examples/06_duino/main/SSD1306UiDemo.cpp | graealex/qemu_esp32 | d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e | [
"Apache-2.0"
] | 335 | 2016-10-12T06:59:33.000Z | 2022-03-29T14:26:04.000Z | examples/06_duino/main/SSD1306UiDemo.cpp | graealex/qemu_esp32 | d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e | [
"Apache-2.0"
] | 30 | 2016-10-30T11:23:59.000Z | 2021-11-12T10:51:20.000Z | examples/06_duino/main/SSD1306UiDemo.cpp | graealex/qemu_esp32 | d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e | [
"Apache-2.0"
] | 48 | 2016-10-30T08:41:13.000Z | 2022-02-15T22:15:09.000Z | /**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* 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 the correct display library
// For a connection via I2C using Wire include
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"`
// or #include "SH1106.h" alis for `#include "SH1106Wire.h"`
// For a connection via I2C using brzo_i2c (must be installed) include
// #include <brzo_i2c.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Brzo.h"
// #include "SH1106Brzo.h"
// For a connection via SPI include
// #include <SPI.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Spi.h"
// #include "SH1106SPi.h"
// Include the UI lib
#include "OLEDDisplayUi.h"
// Include custom images
#include "images.h"
// Use the corresponding display class:
// Initialize the OLED display using SPI
// D5 -> CLK
// D7 -> MOSI (DOUT)
// D0 -> RES
// D2 -> DC
// D8 -> CS
// SSD1306Spi display(D0, D2, D8);
// or
// SH1106Spi display(D0, D2);
// Initialize the OLED display using brzo_i2c
// D3 -> SDA
// D5 -> SCL
// SSD1306Brzo display(0x3c, D3, D5);
// or
// SH1106Brzo display(0x3c, D3, D5);
// Initialize the OLED display using Wire library
///SSD1306 display(0x3c, 5, 4);
// SH1106 display(0x3c, D3, D5);
extern SSD1306 display;
OLEDDisplayUi ui ( &display );
void msOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {
display->setTextAlignment(TEXT_ALIGN_RIGHT);
display->setFont(ArialMT_Plain_10);
display->drawString(128, 0, String(millis()));
}
void drawFrame1(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// draw an xbm image.
// Please note that everything that should be transitioned
// needs to be drawn relative to x and y
display->drawXbm(x + 34, y + 14, WiFi_Logo_width, WiFi_Logo_height, WiFi_Logo_bits);
}
void drawFrame2(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// Demonstrates the 3 included default sizes. The fonts come from SSD1306Fonts.h file
// Besides the default fonts there will be a program to convert TrueType fonts into this format
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(ArialMT_Plain_10);
display->drawString(0 + x, 10 + y, "Arial 10");
display->setFont(ArialMT_Plain_16);
display->drawString(0 + x, 20 + y, "Arial 16");
display->setFont(ArialMT_Plain_24);
display->drawString(0 + x, 34 + y, "Arial 24");
}
void drawFrame3(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// Text alignment demo
display->setFont(ArialMT_Plain_10);
// The coordinates define the left starting point of the text
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->drawString(0 + x, 11 + y, "Left aligned (0,10)");
// The coordinates define the center of the text
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->drawString(64 + x, 22 + y, "Center aligned (64,22)");
// The coordinates define the right end of the text
display->setTextAlignment(TEXT_ALIGN_RIGHT);
display->drawString(128 + x, 33 + y, "Right aligned (128,33)");
}
void drawFrame4(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// Demo for drawStringMaxWidth:
// with the third parameter you can define the width after which words will be wrapped.
// Currently only spaces and "-" are allowed for wrapping
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(ArialMT_Plain_10);
display->drawStringMaxWidth(0 + x, 10 + y, 128, "Lorem ipsum\n dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore.");
}
void drawFrame5(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
}
// This array keeps function pointers to all frames
// frames are the single views that slide in
FrameCallback frames[] = { drawFrame1, drawFrame2, drawFrame3, drawFrame4, drawFrame5 };
// how many frames are there?
int frameCount = 5;
// Overlays are statically drawn on top of a frame eg. a clock
OverlayCallback overlays[] = { msOverlay };
int overlaysCount = 1;
void ui_setup() {
//Serial.begin(115200);
//Serial.println();
//Serial.println();
// The ESP is capable of rendering 60fps in 80Mhz mode
// but that won't give you much time for anything else
// run it in 160Mhz mode or just set it to 30 fps
ui.setTargetFPS(60);
// Customize the active and inactive symbol
ui.setActiveSymbol(activeSymbol);
ui.setInactiveSymbol(inactiveSymbol);
// You can change this to
// TOP, LEFT, BOTTOM, RIGHT
ui.setIndicatorPosition(BOTTOM);
// Defines where the first frame is located in the bar.
ui.setIndicatorDirection(LEFT_RIGHT);
// You can change the transition that is used
// SLIDE_LEFT, SLIDE_RIGHT, SLIDE_UP, SLIDE_DOWN
ui.setFrameAnimation(SLIDE_LEFT);
// Add frames
ui.setFrames(frames, frameCount);
// Add overlays
ui.setOverlays(overlays, overlaysCount);
// Initialising the UI will init the display too.
ui.init();
display.flipScreenVertically();
}
void ui_loop() {
int remainingTimeBudget = ui.update();
if (remainingTimeBudget > 0) {
// You can do some work here
// Don't do stuff if you are below your
// time budget.
delay(remainingTimeBudget);
}
}
| 33.458333 | 162 | 0.721669 | graealex |
a8158f70edf508827735441949467ca7905ad0dd | 261 | cpp | C++ | examples/vector/Main.cpp | huguanghui/cplusplus | 07bfb65f2a781f79f14e27197263762519bc87d0 | [
"MIT"
] | null | null | null | examples/vector/Main.cpp | huguanghui/cplusplus | 07bfb65f2a781f79f14e27197263762519bc87d0 | [
"MIT"
] | null | null | null | examples/vector/Main.cpp | huguanghui/cplusplus | 07bfb65f2a781f79f14e27197263762519bc87d0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
int main()
{
// create a vector containing int
std::vector<int> v = {1, 2, 3, 4};
v.push_back(6);
v.push_back(7);
for (int n:v) {
std::cout << n << '\n';
}
return 0;
} | 15.352941 | 39 | 0.475096 | huguanghui |
a815da353d8718acf96a823176d5ad259b1a8276 | 595 | cc | C++ | codes/raulcr-p3973-Accepted-s1213081.cc | raulcr98/coj-solutions | b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca | [
"MIT"
] | 1 | 2020-03-17T01:44:21.000Z | 2020-03-17T01:44:21.000Z | codes/raulcr-p3973-Accepted-s1213081.cc | raulcr98/coj-solutions | b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca | [
"MIT"
] | null | null | null | codes/raulcr-p3973-Accepted-s1213081.cc | raulcr98/coj-solutions | b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
map<string, pii> mk;
int sol = 0;
int main()
{
string a;
cin >> a;
for(int i = 0 ; i < a.size() ; i++)
for(int j = i ; j < a.size() ; j++){
string c = a.substr(i, j - i + 1);
if(mk.find(c) == mk.end()){
mk[c] = (pii(i, j));
}
else{
pii a = mk[c];
// if(a.second <= i)
sol = max(sol, j - i + 1);
}
}
cout << sol;
return 0;
}
| 19.833333 | 47 | 0.351261 | raulcr98 |
a817f9fce19855f74166f763d9935078583b831b | 1,803 | cpp | C++ | kernel/tr/xqp/ast/ASTCreateIndex.cpp | TonnyRed/sedna | 06ff5a13a16f2d820d3cf0ce579df23f03a59eda | [
"ECL-2.0",
"Apache-2.0"
] | 14 | 2015-09-06T10:17:02.000Z | 2021-12-14T22:39:25.000Z | kernel/tr/xqp/ast/ASTCreateIndex.cpp | TonnyRed/sedna | 06ff5a13a16f2d820d3cf0ce579df23f03a59eda | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-02-15T22:02:14.000Z | 2020-02-17T10:30:14.000Z | kernel/tr/xqp/ast/ASTCreateIndex.cpp | TonnyRed/sedna | 06ff5a13a16f2d820d3cf0ce579df23f03a59eda | [
"ECL-2.0",
"Apache-2.0"
] | 8 | 2015-07-23T05:48:20.000Z | 2021-04-11T05:01:39.000Z | /*
* File: ASTCreateIndex.cpp
* Copyright (C) 2009 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "tr/xqp/serial/deser.h"
#include "tr/xqp/visitor/ASTVisitor.h"
#include "ASTCreateIndex.h"
ASTCreateIndex::~ASTCreateIndex()
{
delete name;
delete on_path;
delete by_path;
delete type;
delete tree_type;
}
void ASTCreateIndex::accept(ASTVisitor &v)
{
v.addToPath(this);
v.visit(*this);
v.removeFromPath(this);
}
ASTNode *ASTCreateIndex::dup()
{
return new ASTCreateIndex(cd, name->dup(), on_path->dup(), by_path->dup(), type->dup(), new std::string(*tree_type) );
}
ASTNode *ASTCreateIndex::createNode(scheme_list &sl)
{
ASTNodeCommonData cd;
ASTNode *name = NULL, *on_path = NULL, *by_path = NULL, *type = NULL;
std::string *tree_type;
U_ASSERT(sl[1].type == SCM_LIST && sl[2].type == SCM_LIST && sl[3].type == SCM_LIST && sl[4].type == SCM_LIST && sl[5].type == SCM_LIST && sl[6].type == SCM_STRING);
cd = dsGetASTCommonFromSList(*sl[1].internal.list);
name = dsGetASTFromSchemeList(*sl[2].internal.list);
on_path = dsGetASTFromSchemeList(*sl[3].internal.list);
by_path = dsGetASTFromSchemeList(*sl[4].internal.list);
type = dsGetASTFromSchemeList(*sl[5].internal.list);
tree_type = new std::string(sl[6].internal.str);
return new ASTCreateIndex(cd, name, on_path, by_path, type, tree_type);
}
void ASTCreateIndex::modifyChild(const ASTNode *oldc, ASTNode *newc)
{
if (name == oldc)
{
name = newc;
return;
}
if (on_path == oldc)
{
on_path = newc;
return;
}
if (by_path == oldc)
{
by_path = newc;
return;
}
if (type == oldc)
{
type = newc;
return;
}
}
| 24.69863 | 169 | 0.63228 | TonnyRed |
a8184158890cf2d536689d788186c10fa5f48e1c | 951 | cpp | C++ | parrot/src/platform/window/WindowsInput.cpp | MiloHX/Parrot | 159f583b2e43396dcc42dc3456a9c5d3fb043133 | [
"Apache-2.0"
] | null | null | null | parrot/src/platform/window/WindowsInput.cpp | MiloHX/Parrot | 159f583b2e43396dcc42dc3456a9c5d3fb043133 | [
"Apache-2.0"
] | null | null | null | parrot/src/platform/window/WindowsInput.cpp | MiloHX/Parrot | 159f583b2e43396dcc42dc3456a9c5d3fb043133 | [
"Apache-2.0"
] | null | null | null | #include "prpch.h"
#include "parrot/core/Input.h"
#include "parrot/core/Application.h"
#include <GLFW/glfw3.h>
namespace parrot {
bool Input::isKeyPressed(KeyCode key_code) {
auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow());
auto state = glfwGetKey(window, (int)key_code);
return state == GLFW_PRESS || state == GLFW_REPEAT;
}
bool Input::isMouseButtonPressed(MouseButton button) {
auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow());
auto state = glfwGetMouseButton(window, (int)button);
return state == GLFW_PRESS;
}
std::pair<float, float> Input::getMousePosition() {
auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow());
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
return { (float)xpos, (float)ypos };
}
} | 31.7 | 97 | 0.660358 | MiloHX |
a81c28f908580e4b72c1a296b135dffb13f02f75 | 266 | cc | C++ | week6/memory/unit_tests.cc | yxc07/EEP_520_Winter2022 | 6a66e957c8afe78ed3703fda6113e55ccf5b66b2 | [
"MIT"
] | 13 | 2020-01-10T00:25:27.000Z | 2020-09-14T20:26:23.000Z | week6/memory/unit_tests.cc | yxc07/EEP_520_Winter2022 | 6a66e957c8afe78ed3703fda6113e55ccf5b66b2 | [
"MIT"
] | null | null | null | week6/memory/unit_tests.cc | yxc07/EEP_520_Winter2022 | 6a66e957c8afe78ed3703fda6113e55ccf5b66b2 | [
"MIT"
] | 19 | 2021-04-07T02:39:30.000Z | 2021-12-12T00:40:22.000Z | #include <math.h>
#include <float.h> /* defines DBL_EPSILON */
#include <assert.h>
#include "gtest/gtest.h"
namespace {
TEST(Examples, Allocation) {
int * x = new int;
double * p = new double[10];
delete x;
delete[] p;
}
}
| 16.625 | 44 | 0.556391 | yxc07 |
a81e53f2970260f975b22689b898ea41f80ff1a0 | 684 | cpp | C++ | game/server/entities/CInfoIntermission.cpp | sohl-modders/SOHLEnhanced | 71358d28bf65ba600f268368d2e4521c4158da72 | [
"Unlicense"
] | null | null | null | game/server/entities/CInfoIntermission.cpp | sohl-modders/SOHLEnhanced | 71358d28bf65ba600f268368d2e4521c4158da72 | [
"Unlicense"
] | null | null | null | game/server/entities/CInfoIntermission.cpp | sohl-modders/SOHLEnhanced | 71358d28bf65ba600f268368d2e4521c4158da72 | [
"Unlicense"
] | null | null | null | #include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "CInfoIntermission.h"
LINK_ENTITY_TO_CLASS( info_intermission, CInfoIntermission );
void CInfoIntermission::Spawn( void )
{
SetAbsOrigin( GetAbsOrigin() );
SetSolidType( SOLID_NOT );
GetEffects() = EF_NODRAW;
SetViewAngle( g_vecZero );
SetNextThink( 2 );// let targets spawn!
}
void CInfoIntermission::Think( void )
{
// find my target
CBaseEntity* pTarget = UTIL_FindEntityByTargetname( nullptr, GetTarget() );
if( pTarget )
{
Vector vecViewAngle = UTIL_VecToAngles( ( pTarget->GetAbsOrigin() - GetAbsOrigin() ).Normalize() );
vecViewAngle.x = -vecViewAngle.x;
SetViewAngle( vecViewAngle );
}
} | 22.064516 | 101 | 0.726608 | sohl-modders |
a81e6ab93db01b6e0a76440e11a5c8f8d7f5d203 | 2,797 | cpp | C++ | Engine/Source/Runtime/ApplicationCore/Private/IOS/IOSWindow.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/ApplicationCore/Private/IOS/IOSWindow.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/ApplicationCore/Private/IOS/IOSWindow.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "IOSWindow.h"
#include "IOSAppDelegate.h"
#include "IOSView.h"
FIOSWindow::~FIOSWindow()
{
// NOTE: The Window is invalid here!
// Use NativeWindow_Destroy() instead.
}
TSharedRef<FIOSWindow> FIOSWindow::Make()
{
return MakeShareable( new FIOSWindow() );
}
FIOSWindow::FIOSWindow()
{
}
void FIOSWindow::Initialize( class FIOSApplication* const Application, const TSharedRef< FGenericWindowDefinition >& InDefinition, const TSharedPtr< FIOSWindow >& InParent, const bool bShowImmediately )
{
OwningApplication = Application;
Definition = InDefinition;
Window = [[UIApplication sharedApplication] keyWindow];
#if !PLATFORM_TVOS
if(InParent.Get() != NULL)
{
dispatch_async(dispatch_get_main_queue(),^ {
#ifdef __IPHONE_8_0
if ([UIAlertController class])
{
UIAlertController* AlertController = [UIAlertController alertControllerWithTitle:@""
message:@"Error: Only one UIWindow may be created on iOS."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* okAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"OK", nil)
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action)
{
[AlertController dismissViewControllerAnimated : YES completion : nil];
}
];
[AlertController addAction : okAction];
[[IOSAppDelegate GetDelegate].IOSController presentViewController : AlertController animated : YES completion : nil];
}
else
#endif
{
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0
UIAlertView* AlertView = [[UIAlertView alloc] initWithTitle:@""
message:@"Error: Only one UIWindow may be created on iOS."
delegate:nil
cancelButtonTitle:NSLocalizedString(@"Ok", nil)
otherButtonTitles:nil];
[AlertView show];
[AlertView release];
#endif
}
} );
}
#endif
}
FPlatformRect FIOSWindow::GetScreenRect()
{
// get the main view's frame
IOSAppDelegate* AppDelegate = (IOSAppDelegate*)[[UIApplication sharedApplication] delegate];
UIView* View = AppDelegate.IOSView;
CGRect Frame = [View frame];
CGFloat Scale = View.contentScaleFactor;
FPlatformRect ScreenRect;
ScreenRect.Top = Frame.origin.y * Scale;
ScreenRect.Bottom = (Frame.origin.y + Frame.size.height) * Scale;
ScreenRect.Left = Frame.origin.x * Scale;
ScreenRect.Right = (Frame.origin.x + Frame.size.width) * Scale;
return ScreenRect;
}
bool FIOSWindow::GetFullScreenInfo( int32& X, int32& Y, int32& Width, int32& Height ) const
{
FPlatformRect ScreenRect = GetScreenRect();
X = ScreenRect.Left;
Y = ScreenRect.Top;
Width = ScreenRect.Right - ScreenRect.Left;
Height = ScreenRect.Bottom - ScreenRect.Top;
return true;
}
| 28.252525 | 202 | 0.711477 | windystrife |
a81fbc3068040a3d53bacb11d79f84ff5eff593e | 7,253 | cpp | C++ | CaWE/MapEditor/Commands/Delete.cpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | CaWE/MapEditor/Commands/Delete.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | CaWE/MapEditor/Commands/Delete.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#include "Delete.hpp"
#include "Select.hpp"
#include "../CompMapEntity.hpp"
#include "../MapDocument.hpp"
#include "../MapEntRepres.hpp"
#include "../MapPrimitive.hpp"
using namespace MapEditor;
CommandDeleteT::CommandDeleteT(MapDocumentT& MapDoc, MapElementT* DeleteElem)
: m_MapDoc(MapDoc),
m_Entities(),
m_EntityParents(),
m_EntityIndices(),
m_DeletePrims(),
m_DeletePrimsParents(),
m_CommandSelect(NULL)
{
ArrayT<MapElementT*> DeleteElems;
DeleteElems.PushBack(DeleteElem);
Init(DeleteElems);
}
CommandDeleteT::CommandDeleteT(MapDocumentT& MapDoc, const ArrayT<MapElementT*>& DeleteElems)
: m_MapDoc(MapDoc),
m_Entities(),
m_EntityParents(),
m_EntityIndices(),
m_DeletePrims(),
m_DeletePrimsParents(),
m_CommandSelect(NULL)
{
Init(DeleteElems);
}
void CommandDeleteT::Init(const ArrayT<MapElementT*>& DeleteElems)
{
// Split the list of elements into a list of primitives and a list of entities.
// The lists are checked for duplicates (and kept free of them).
for (unsigned long ElemNr = 0; ElemNr < DeleteElems.Size(); ElemNr++)
{
MapElementT* Elem = DeleteElems[ElemNr];
if (Elem->GetType() == &MapEntRepresT::TypeInfo)
{
// Double-check that this is really a MapEntRepresT.
wxASSERT(Elem->GetParent()->GetRepres() == Elem);
IntrusivePtrT<cf::GameSys::EntityT> Entity = Elem->GetParent()->GetEntity();
// The root entity (the world) cannot be deleted.
// (The if-tests below are three versions of the logically same check.)
if (Elem->GetParent()->IsWorld()) continue;
if (Entity == Entity->GetRoot()) continue;
if (Entity->GetParent() == NULL) continue;
m_Entities.PushBack(Entity);
m_EntityParents.PushBack(Entity->GetParent());
m_EntityIndices.PushBack(-1);
}
else
{
// Double-check that this is really *not* a MapEntRepresT.
wxASSERT(Elem->GetParent()->GetRepres() != Elem);
MapPrimitiveT* Prim = dynamic_cast<MapPrimitiveT*>(Elem);
wxASSERT(Prim);
if (m_DeletePrims.Find(Prim) == -1)
{
m_DeletePrims.PushBack(Prim);
m_DeletePrimsParents.PushBack(Prim->GetParent());
}
}
}
// Remove entities from m_Entities that are already in the tree of another entity.
// This also removes any duplicates from m_Entities.
for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
{
for (unsigned long TreeNr = 0; TreeNr < m_Entities.Size(); TreeNr++)
{
if (EntNr != TreeNr && m_Entities[TreeNr]->Has(m_Entities[EntNr]))
{
m_Entities.RemoveAt(EntNr);
m_EntityParents.RemoveAt(EntNr);
m_EntityIndices.RemoveAt(EntNr);
EntNr--;
break;
}
}
}
// Remove primitives from m_DeletePrims whose entire entity is deleted anyways.
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
{
for (unsigned long TreeNr = 0; TreeNr < m_Entities.Size(); TreeNr++)
{
if (m_Entities[TreeNr]->Has(m_DeletePrims[PrimNr]->GetParent()->GetEntity()))
{
m_DeletePrims.RemoveAt(PrimNr);
m_DeletePrimsParents.RemoveAt(PrimNr);
PrimNr--;
break;
}
}
}
// Build the combined list of all deleted elements in order to unselect them.
ArrayT<MapElementT*> Unselect;
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
Unselect.PushBack(m_DeletePrims[PrimNr]);
for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
{
IntrusivePtrT<CompMapEntityT> MapEnt = GetMapEnt(m_Entities[EntNr]);
Unselect.PushBack(MapEnt->GetAllMapElements());
}
m_CommandSelect = CommandSelectT::Remove(&m_MapDoc, Unselect);
}
CommandDeleteT::~CommandDeleteT()
{
delete m_CommandSelect;
if (m_Done)
{
// for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
// delete m_Entities[EntNr];
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
delete m_DeletePrims[PrimNr];
}
}
bool CommandDeleteT::Do()
{
wxASSERT(!m_Done);
if (m_Done) return false;
if (m_Entities.Size() == 0 && m_DeletePrims.Size() == 0)
{
// If there is nothing to delete, e.g. because only the world representation
// was selected (and dropped in Init()), bail out early.
return false;
}
// Deselect any affected elements that are selected.
m_CommandSelect->Do();
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
{
m_MapDoc.Remove(m_DeletePrims[PrimNr]);
}
for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++)
{
IntrusivePtrT<cf::GameSys::EntityT> Entity = m_Entities[EntNr];
wxASSERT(m_EntityParents[EntNr]->GetChildren().Find(Entity) >= 0);
// The proper index number can only be determined here, because removing a child
// may change the index numbers of its siblings.
m_EntityIndices[EntNr] = m_EntityParents[EntNr]->GetChildren().Find(Entity);
m_MapDoc.Remove(Entity);
}
// Update all observers.
m_MapDoc.UpdateAllObservers_Deleted(m_DeletePrims);
m_MapDoc.UpdateAllObservers_Deleted(m_Entities);
m_Done = true;
return true;
}
void CommandDeleteT::Undo()
{
wxASSERT(m_Done);
if (!m_Done) return;
for (unsigned long RevNr = 0; RevNr < m_Entities.Size(); RevNr++)
{
const unsigned long EntNr = m_Entities.Size() - RevNr - 1;
// This call to AddChild() should never see a reason to modify the name of the m_Entities[EntNr]
// to make it unique among its siblings -- it used to be there and was unique, after all.
m_MapDoc.Insert(m_Entities[EntNr], m_EntityParents[EntNr], m_EntityIndices[EntNr]);
}
for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++)
m_MapDoc.Insert(m_DeletePrims[PrimNr], m_DeletePrimsParents[PrimNr]);
// Update all observers.
m_MapDoc.UpdateAllObservers_Created(m_Entities);
m_MapDoc.UpdateAllObservers_Created(m_DeletePrims);
// Select the previously selected elements again.
m_CommandSelect->Undo();
m_Done = false;
}
wxString CommandDeleteT::GetName() const
{
const unsigned long Sum = m_Entities.Size() + m_DeletePrims.Size();
if (m_Entities.Size() == 0)
{
return (Sum == 1) ? "Delete 1 primitive" : wxString::Format("Delete %lu primitives", Sum);
}
if (m_DeletePrims.Size() == 0)
{
return (Sum == 1) ? "Delete 1 entity" : wxString::Format("Delete %lu entities", Sum);
}
return (Sum == 1) ? "Delete 1 element" : wxString::Format("Delete %lu elements", Sum);
}
| 30.220833 | 104 | 0.624293 | dns |
a821f5ce6f823d289435a671b6a4dd3dafcac6bc | 1,674 | cpp | C++ | core/src/opt/dedicate_to_window.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 731 | 2020-05-07T06:22:59.000Z | 2022-03-31T16:36:03.000Z | core/src/opt/dedicate_to_window.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 67 | 2020-07-20T19:46:42.000Z | 2022-03-31T15:34:47.000Z | core/src/opt/dedicate_to_window.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 15 | 2021-01-29T04:49:11.000Z | 2022-03-04T22:16:31.000Z | #include "opt/dedicate_to_window.hpp"
#if defined(DEBUG)
#include <iostream>
#endif
#include <windows.h>
#include "bind/emu/edi_change_mode.hpp"
#include "bind/mode/change_mode.hpp"
#include "err_logger.hpp"
#include "g_params.hpp"
#include "io/mouse.hpp"
#include "key/key_absorber.hpp"
#include "key/keycode_def.hpp"
#include "opt/vcmdline.hpp"
namespace
{
HWND target_hwnd = NULL ;
HWND past_hwnd = NULL ;
}
namespace vind
{
Dedicate2Window::Dedicate2Window()
: OptionCreator("dedicate_to_window")
{}
void Dedicate2Window::do_enable() const {
}
void Dedicate2Window::do_disable() const {
}
void Dedicate2Window::enable_targeting() {
if(gparams::get_b("dedicate_to_window")) {
target_hwnd = GetForegroundWindow() ;
past_hwnd = NULL ;
VCmdLine::print(GeneralMessage("-- TARGET ON --")) ;
}
}
void Dedicate2Window::disable_targeting() {
if(gparams::get_b("dedicate_to_window")) {
target_hwnd = NULL ;
past_hwnd = NULL ;
VCmdLine::print(GeneralMessage("-- TARGET OFF --")) ;
}
}
void Dedicate2Window::do_process() const {
if(!target_hwnd) return ;
auto foreground_hwnd = GetForegroundWindow() ;
//is selected window changed?
if(past_hwnd == foreground_hwnd) {
return ;
}
if(target_hwnd == foreground_hwnd) { //other -> target
ToEdiNormal::sprocess(true) ;
}
else if(past_hwnd == target_hwnd) { //target -> other
ToInsert::sprocess(true) ;
}
past_hwnd = foreground_hwnd ;
}
}
| 23.577465 | 65 | 0.608124 | pit-ray |
a82284e760da949fcf7edb3069eefbdff1b53d4d | 36,450 | cpp | C++ | VirtualBox-5.0.0/src/VBox/Runtime/tools/RTSignTool.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | 1 | 2015-04-30T14:18:45.000Z | 2015-04-30T14:18:45.000Z | VirtualBox-5.0.0/src/VBox/Runtime/tools/RTSignTool.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | VirtualBox-5.0.0/src/VBox/Runtime/tools/RTSignTool.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | /* $Id: RTSignTool.cpp $ */
/** @file
* IPRT - Signing Tool.
*/
/*
* Copyright (C) 2006-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/assert.h>
#include <iprt/buildconfig.h>
#include <iprt/err.h>
#include <iprt/getopt.h>
#include <iprt/file.h>
#include <iprt/initterm.h>
#include <iprt/ldr.h>
#include <iprt/message.h>
#include <iprt/mem.h>
#include <iprt/path.h>
#include <iprt/stream.h>
#include <iprt/string.h>
#include <iprt/crypto/x509.h>
#include <iprt/crypto/pkcs7.h>
#include <iprt/crypto/store.h>
#ifdef VBOX
# include <VBox/sup.h> /* Certificates */
#endif
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/** Help detail levels. */
typedef enum RTSIGNTOOLHELP
{
RTSIGNTOOLHELP_USAGE,
RTSIGNTOOLHELP_FULL
} RTSIGNTOOLHELP;
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
static RTEXITCODE HandleHelp(int cArgs, char **papszArgs);
static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
static RTEXITCODE HandleVersion(int cArgs, char **papszArgs);
/*
* The 'extract-exe-signer-cert' command.
*/
static RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm, "extract-exe-signer-cert [--ber|--cer|--der] [--exe|-e] <exe> [--output|-o] <outfile.cer>\n");
return RTEXITCODE_SUCCESS;
}
static RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs)
{
/*
* Parse arguments.
*/
static const RTGETOPTDEF s_aOptions[] =
{
{ "--ber", 'b', RTGETOPT_REQ_NOTHING },
{ "--cer", 'c', RTGETOPT_REQ_NOTHING },
{ "--der", 'd', RTGETOPT_REQ_NOTHING },
{ "--exe", 'e', RTGETOPT_REQ_STRING },
{ "--output", 'o', RTGETOPT_REQ_STRING },
};
const char *pszExe = NULL;
const char *pszOut = NULL;
RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER;
RTGETOPTSTATE GetState;
int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
AssertRCReturn(rc, RTEXITCODE_FAILURE);
RTGETOPTUNION ValueUnion;
int ch;
while ((ch = RTGetOpt(&GetState, &ValueUnion)))
{
switch (ch)
{
case 'e': pszExe = ValueUnion.psz; break;
case 'o': pszOut = ValueUnion.psz; break;
case 'b': fCursorFlags = 0; break;
case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break;
case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break;
case 'V': return HandleVersion(cArgs, papszArgs);
case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL);
case VINF_GETOPT_NOT_OPTION:
if (!pszExe)
pszExe = ValueUnion.psz;
else if (!pszOut)
pszOut = ValueUnion.psz;
else
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz);
break;
default:
return RTGetOptPrintError(ch, &ValueUnion);
}
}
if (!pszExe)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
if (!pszOut)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given.");
if (RTPathExists(pszOut))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut);
/*
* Do it.
*/
/* Open the executable image and query the PKCS7 info. */
RTLDRMOD hLdrMod;
rc = RTLdrOpen(pszExe, RTLDR_O_FOR_VALIDATION, enmLdrArch, &hLdrMod);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszExe, rc);
RTEXITCODE rcExit = RTEXITCODE_FAILURE;
#ifdef DEBUG
size_t cbBuf = 64;
#else
size_t cbBuf = _512K;
#endif
void *pvBuf = RTMemAlloc(cbBuf);
size_t cbRet = 0;
rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbRet);
if (rc == VERR_BUFFER_OVERFLOW && cbRet < _4M && cbRet > 0)
{
RTMemFree(pvBuf);
cbBuf = cbRet;
pvBuf = RTMemAlloc(cbBuf);
rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbRet);
}
if (RT_SUCCESS(rc))
{
static RTERRINFOSTATIC s_StaticErrInfo;
RTErrInfoInitStatic(&s_StaticErrInfo);
/*
* Decode the output.
*/
RTASN1CURSORPRIMARY PrimaryCursor;
RTAsn1CursorInitPrimary(&PrimaryCursor, pvBuf, (uint32_t)cbRet, &s_StaticErrInfo.Core,
&g_RTAsn1DefaultAllocator, fCursorFlags, "exe");
RTCRPKCS7CONTENTINFO Pkcs7Ci;
rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, &Pkcs7Ci, "pkcs7");
if (RT_SUCCESS(rc))
{
if (RTCrPkcs7ContentInfo_IsSignedData(&Pkcs7Ci))
{
PCRTCRPKCS7SIGNEDDATA pSd = Pkcs7Ci.u.pSignedData;
if (pSd->SignerInfos.cItems == 1)
{
PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSd->SignerInfos.paItems[0].IssuerAndSerialNumber;
PCRTCRX509CERTIFICATE pCert;
pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSd->Certificates,
&pISN->Name, &pISN->SerialNumber);
if (pCert)
{
/*
* Write it out.
*/
RTFILE hFile;
rc = RTFileOpen(&hFile, pszOut, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE);
if (RT_SUCCESS(rc))
{
uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb;
rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr,
cbCert, NULL);
if (RT_SUCCESS(rc))
{
rc = RTFileClose(hFile);
if (RT_SUCCESS(rc))
{
hFile = NIL_RTFILE;
rcExit = RTEXITCODE_SUCCESS;
RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszOut);
}
else
RTMsgError("RTFileClose failed: %Rrc", rc);
}
else
RTMsgError("RTFileWrite failed: %Rrc", rc);
RTFileClose(hFile);
}
else
RTMsgError("Error opening '%s': %Rrc", pszOut, rc);
}
else
RTMsgError("Certificate not found.");
}
else
RTMsgError("SignerInfo count: %u", pSd->SignerInfos.cItems);
}
else
RTMsgError("No PKCS7 content: ContentType=%s", Pkcs7Ci.ContentType.szObjId);
RTAsn1VtDelete(&Pkcs7Ci.SeqCore.Asn1Core);
}
else
RTMsgError("RTPkcs7ContentInfoDecodeAsn1 failed: %Rrc - %s", rc, s_StaticErrInfo.szMsg);
}
else
RTMsgError("RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc", pszExe, rc);
RTMemFree(pvBuf);
rc = RTLdrClose(hLdrMod);
if (RT_FAILURE(rc))
rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc);
return rcExit;
}
#ifndef IPRT_IN_BUILD_TOOL
/*
* The 'verify-exe' command.
*/
static RTEXITCODE HelpVerifyExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm,
"verify-exe [--verbose|--quiet] [--kernel] [--root <root-cert.der>] [--additional <supp-cert.der>]\n"
" [--type <win|osx>] <exe1> [exe2 [..]]\n");
return RTEXITCODE_SUCCESS;
}
typedef struct VERIFYEXESTATE
{
RTCRSTORE hRootStore;
RTCRSTORE hKernelRootStore;
RTCRSTORE hAdditionalStore;
bool fKernel;
int cVerbose;
enum { kSignType_Windows, kSignType_OSX } enmSignType;
uint64_t uTimestamp;
RTLDRARCH enmLdrArch;
} VERIFYEXESTATE;
#ifdef VBOX
/** Certificate store load set.
* Declared outside HandleVerifyExe because of braindead gcc visibility crap. */
struct STSTORESET
{
RTCRSTORE hStore;
PCSUPTAENTRY paTAs;
unsigned cTAs;
};
#endif
/**
* @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK,
* Standard code signing. Use this for Microsoft SPC.}
*/
static DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags,
void *pvUser, PRTERRINFO pErrInfo)
{
VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
uint32_t cPaths = hCertPaths != NIL_RTCRX509CERTPATHS ? RTCrX509CertPathsGetPathCount(hCertPaths) : 0;
/*
* Dump all the paths.
*/
if (pState->cVerbose > 0)
{
for (uint32_t iPath = 0; iPath < cPaths; iPath++)
{
RTPrintf("---\n");
RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut);
*pErrInfo->pszMsg = '\0';
}
RTPrintf("---\n");
}
/*
* Test signing certificates normally doesn't have all the necessary
* features required below. So, treat them as special cases.
*/
if ( hCertPaths == NIL_RTCRX509CERTPATHS
&& RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0)
{
RTMsgInfo("Test signed.\n");
return VINF_SUCCESS;
}
if (hCertPaths == NIL_RTCRX509CERTPATHS)
RTMsgInfo("Signed by trusted certificate.\n");
/*
* Standard code signing capabilites required.
*/
int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo);
if ( RT_SUCCESS(rc)
&& (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA))
{
/*
* If kernel signing, a valid certificate path must be anchored by the
* microsoft kernel signing root certificate. The only alternative is
* test signing.
*/
if (pState->fKernel && hCertPaths != NIL_RTCRX509CERTPATHS)
{
uint32_t cFound = 0;
uint32_t cValid = 0;
for (uint32_t iPath = 0; iPath < cPaths; iPath++)
{
bool fTrusted;
PCRTCRX509NAME pSubject;
PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo;
int rcVerify;
rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo,
NULL, NULL /*pCertCtx*/, &rcVerify);
AssertRCBreak(rc);
if (RT_SUCCESS(rcVerify))
{
Assert(fTrusted);
cValid++;
/* Search the kernel signing root store for a matching anchor. */
RTCRSTORECERTSEARCH Search;
rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(pState->hKernelRootStore, pSubject, &Search);
AssertRCBreak(rc);
PCRTCRCERTCTX pCertCtx;
while ((pCertCtx = RTCrStoreCertSearchNext(pState->hKernelRootStore, &Search)) != NULL)
{
PCRTCRX509SUBJECTPUBLICKEYINFO pPubKeyInfo;
if (pCertCtx->pCert)
pPubKeyInfo = &pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo;
else if (pCertCtx->pTaInfo)
pPubKeyInfo = &pCertCtx->pTaInfo->PubKey;
else
pPubKeyInfo = NULL;
if (RTCrX509SubjectPublicKeyInfo_Compare(pPubKeyInfo, pPublicKeyInfo) == 0)
cFound++;
RTCrCertCtxRelease(pCertCtx);
}
int rc2 = RTCrStoreCertSearchDestroy(pState->hKernelRootStore, &Search); AssertRC(rc2);
}
}
if (RT_SUCCESS(rc) && cFound == 0)
rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "Not valid kernel code signature.");
if (RT_SUCCESS(rc) && cValid != 2)
RTMsgWarning("%u valid paths, expected 2", cValid);
}
}
return rc;
}
/** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */
static DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature,
void const *pvSignature, size_t cbSignature,
PRTERRINFO pErrInfo, void *pvUser)
{
VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser;
switch (enmSignature)
{
case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA:
{
PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pvSignature;
RTTIMESPEC ValidationTime;
RTTimeSpecSetSeconds(&ValidationTime, pState->uTimestamp);
/*
* Dump the signed data if so requested.
*/
if (pState->cVerbose)
RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut);
/*
* Do the actual verification. Will have to modify this so it takes
* the authenticode policies into account.
*/
return RTCrPkcs7VerifySignedData(pContentInfo,
RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY
| RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT
| RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT,
pState->hAdditionalStore, pState->hRootStore, &ValidationTime,
VerifyExecCertVerifyCallback, pState, pErrInfo);
}
default:
return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", enmSignature);
}
return VINF_SUCCESS;
}
/** Worker for HandleVerifyExe. */
static RTEXITCODE HandleVerifyExeWorker(VERIFYEXESTATE *pState, const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo)
{
/*
* Open the executable image and verify it.
*/
RTLDRMOD hLdrMod;
int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, pState->enmLdrArch, &hLdrMod);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszFilename, rc);
rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &pState->uTimestamp, sizeof(pState->uTimestamp));
if (RT_SUCCESS(rc))
{
rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo));
if (RT_SUCCESS(rc))
RTMsgInfo("'%s' is valid.\n", pszFilename);
else
RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc - %s\n", pszFilename, rc, pStaticErrInfo->szMsg);
}
else
RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", pszFilename, rc);
int rc2 = RTLdrClose(hLdrMod);
if (RT_FAILURE(rc2))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc2);
if (RT_FAILURE(rc))
return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED;
return RTEXITCODE_SUCCESS;
}
static RTEXITCODE HandleVerifyExe(int cArgs, char **papszArgs)
{
RTERRINFOSTATIC StaticErrInfo;
/* Note! This code does not try to clean up the crypto stores on failure.
This is intentional as the code is only expected to be used in a
one-command-per-process environment where we do exit() upon
returning from this function. */
/*
* Parse arguments.
*/
static const RTGETOPTDEF s_aOptions[] =
{
{ "--kernel", 'k', RTGETOPT_REQ_NOTHING },
{ "--root", 'r', RTGETOPT_REQ_STRING },
{ "--additional", 'a', RTGETOPT_REQ_STRING },
{ "--add", 'a', RTGETOPT_REQ_STRING },
{ "--type", 't', RTGETOPT_REQ_STRING },
{ "--verbose", 'v', RTGETOPT_REQ_NOTHING },
{ "--quiet", 'q', RTGETOPT_REQ_NOTHING },
};
VERIFYEXESTATE State =
{
NIL_RTCRSTORE, NIL_RTCRSTORE, NIL_RTCRSTORE, false, false,
VERIFYEXESTATE::kSignType_Windows, 0, RTLDRARCH_WHATEVER
};
int rc = RTCrStoreCreateInMem(&State.hRootStore, 0);
if (RT_SUCCESS(rc))
rc = RTCrStoreCreateInMem(&State.hKernelRootStore, 0);
if (RT_SUCCESS(rc))
rc = RTCrStoreCreateInMem(&State.hAdditionalStore, 0);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc);
RTGETOPTSTATE GetState;
rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
AssertRCReturn(rc, RTEXITCODE_FAILURE);
RTGETOPTUNION ValueUnion;
int ch;
while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION)
{
switch (ch)
{
case 'r': case 'a':
rc = RTCrStoreCertAddFromFile(ch == 'r' ? State.hRootStore : State.hAdditionalStore, 0, ValueUnion.psz,
RTErrInfoInitStatic(&StaticErrInfo));
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error loading certificate '%s': %Rrc - %s",
ValueUnion.psz, rc, StaticErrInfo.szMsg);
break;
case 't':
if (!strcmp(ValueUnion.psz, "win") || !strcmp(ValueUnion.psz, "windows"))
State.enmSignType = VERIFYEXESTATE::kSignType_Windows;
else if (!strcmp(ValueUnion.psz, "osx") || !strcmp(ValueUnion.psz, "apple"))
State.enmSignType = VERIFYEXESTATE::kSignType_OSX;
else
return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signing type: '%s'", ValueUnion.psz);
break;
case 'k': State.fKernel = true; break;
case 'v': State.cVerbose++; break;
case 'q': State.cVerbose = 0; break;
case 'V': return HandleVersion(cArgs, papszArgs);
case 'h': return HelpVerifyExe(g_pStdOut, RTSIGNTOOLHELP_FULL);
default: return RTGetOptPrintError(ch, &ValueUnion);
}
}
if (ch != VINF_GETOPT_NOT_OPTION)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given.");
/*
* Populate the certificate stores according to the signing type.
*/
#ifdef VBOX
unsigned cSets = 0;
struct STSTORESET aSets[6];
#endif
switch (State.enmSignType)
{
case VERIFYEXESTATE::kSignType_Windows:
#ifdef VBOX
aSets[cSets].hStore = State.hRootStore;
aSets[cSets].paTAs = g_aSUPTimestampTAs;
aSets[cSets].cTAs = g_cSUPTimestampTAs;
cSets++;
aSets[cSets].hStore = State.hRootStore;
aSets[cSets].paTAs = g_aSUPSpcRootTAs;
aSets[cSets].cTAs = g_cSUPSpcRootTAs;
cSets++;
aSets[cSets].hStore = State.hRootStore;
aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
cSets++;
aSets[cSets].hStore = State.hKernelRootStore;
aSets[cSets].paTAs = g_aSUPNtKernelRootTAs;
aSets[cSets].cTAs = g_cSUPNtKernelRootTAs;
cSets++;
#endif
break;
case VERIFYEXESTATE::kSignType_OSX:
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Mac OS X executable signing is not implemented.");
}
#ifdef VBOX
for (unsigned i = 0; i < cSets; i++)
for (unsigned j = 0; j < aSets[i].cTAs; j++)
{
rc = RTCrStoreCertAddEncoded(aSets[i].hStore, RTCRCERTCTX_F_ENC_TAF_DER, aSets[i].paTAs[j].pch,
aSets[i].paTAs[j].cb, RTErrInfoInitStatic(&StaticErrInfo));
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTCrStoreCertAddEncoded failed (%u/%u): %s",
i, j, StaticErrInfo.szMsg);
}
#endif
/*
* Do it.
*/
RTEXITCODE rcExit;
for (;;)
{
rcExit = HandleVerifyExeWorker(&State, ValueUnion.psz, &StaticErrInfo);
if (rcExit != RTEXITCODE_SUCCESS)
break;
/*
* Next file
*/
ch = RTGetOpt(&GetState, &ValueUnion);
if (ch == 0)
break;
if (ch != VINF_GETOPT_NOT_OPTION)
{
rcExit = RTGetOptPrintError(ch, &ValueUnion);
break;
}
}
/*
* Clean up.
*/
uint32_t cRefs;
cRefs = RTCrStoreRelease(State.hRootStore); Assert(cRefs == 0);
cRefs = RTCrStoreRelease(State.hKernelRootStore); Assert(cRefs == 0);
cRefs = RTCrStoreRelease(State.hAdditionalStore); Assert(cRefs == 0);
return rcExit;
}
#endif /* !IPRT_IN_BUILD_TOOL */
/*
* The 'make-tainfo' command.
*/
static RTEXITCODE HelpMakeTaInfo(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm,
"make-tainfo [--verbose|--quiet] [--cert <cert.der>] [-o|--output] <tainfo.der>\n");
return RTEXITCODE_SUCCESS;
}
typedef struct MAKETAINFOSTATE
{
int cVerbose;
const char *pszCert;
const char *pszOutput;
} MAKETAINFOSTATE;
/** @callback_method_impl{FNRTASN1ENCODEWRITER} */
static DECLCALLBACK(int) handleMakeTaInfoWriter(const void *pvBuf, size_t cbToWrite, void *pvUser, PRTERRINFO pErrInfo)
{
return RTStrmWrite((PRTSTREAM)pvUser, pvBuf, cbToWrite);
}
static RTEXITCODE HandleMakeTaInfo(int cArgs, char **papszArgs)
{
/*
* Parse arguments.
*/
static const RTGETOPTDEF s_aOptions[] =
{
{ "--cert", 'c', RTGETOPT_REQ_STRING },
{ "--output", 'o', RTGETOPT_REQ_STRING },
{ "--verbose", 'v', RTGETOPT_REQ_NOTHING },
{ "--quiet", 'q', RTGETOPT_REQ_NOTHING },
};
RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER;
MAKETAINFOSTATE State = { 0, NULL, NULL };
RTGETOPTSTATE GetState;
int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
AssertRCReturn(rc, RTEXITCODE_FAILURE);
RTGETOPTUNION ValueUnion;
int ch;
while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
{
switch (ch)
{
case 'c':
if (State.pszCert)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --cert option can only be used once.");
State.pszCert = ValueUnion.psz;
break;
case 'o':
case VINF_GETOPT_NOT_OPTION:
if (State.pszOutput)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Multiple output files specified.");
State.pszOutput = ValueUnion.psz;
break;
case 'v': State.cVerbose++; break;
case 'q': State.cVerbose = 0; break;
case 'V': return HandleVersion(cArgs, papszArgs);
case 'h': return HelpMakeTaInfo(g_pStdOut, RTSIGNTOOLHELP_FULL);
default: return RTGetOptPrintError(ch, &ValueUnion);
}
}
if (!State.pszCert)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No input certificate was specified.");
if (!State.pszOutput)
return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file was specified.");
/*
* Read the certificate.
*/
RTERRINFOSTATIC StaticErrInfo;
RTCRX509CERTIFICATE Certificate;
rc = RTCrX509Certificate_ReadFromFile(&Certificate, State.pszCert, 0, &g_RTAsn1DefaultAllocator,
RTErrInfoInitStatic(&StaticErrInfo));
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading certificate from %s: %Rrc - %s",
State.pszCert, rc, StaticErrInfo.szMsg);
/*
* Construct the trust anchor information.
*/
RTCRTAFTRUSTANCHORINFO TrustAnchor;
rc = RTCrTafTrustAnchorInfo_Init(&TrustAnchor, &g_RTAsn1DefaultAllocator);
if (RT_SUCCESS(rc))
{
/* Public key. */
Assert(RTCrX509SubjectPublicKeyInfo_IsPresent(&TrustAnchor.PubKey));
RTCrX509SubjectPublicKeyInfo_Delete(&TrustAnchor.PubKey);
rc = RTCrX509SubjectPublicKeyInfo_Clone(&TrustAnchor.PubKey, &Certificate.TbsCertificate.SubjectPublicKeyInfo,
&g_RTAsn1DefaultAllocator);
if (RT_FAILURE(rc))
RTMsgError("RTCrX509SubjectPublicKeyInfo_Clone failed: %Rrc", rc);
RTAsn1Core_ResetImplict(RTCrX509SubjectPublicKeyInfo_GetAsn1Core(&TrustAnchor.PubKey)); /* temporary hack. */
/* Key Identifier. */
PCRTASN1OCTETSTRING pKeyIdentifier = NULL;
if (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_SUBJECT_KEY_IDENTIFIER)
pKeyIdentifier = Certificate.TbsCertificate.T3.pSubjectKeyIdentifier;
else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_AUTHORITY_KEY_IDENTIFIER)
&& RTCrX509Certificate_IsSelfSigned(&Certificate)
&& RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier) )
pKeyIdentifier = &Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier;
else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_OLD_AUTHORITY_KEY_IDENTIFIER)
&& RTCrX509Certificate_IsSelfSigned(&Certificate)
&& RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier) )
pKeyIdentifier = &Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier;
if (pKeyIdentifier && pKeyIdentifier->Asn1Core.cb > 0)
{
Assert(RTAsn1OctetString_IsPresent(&TrustAnchor.KeyIdentifier));
RTAsn1OctetString_Delete(&TrustAnchor.KeyIdentifier);
rc = RTAsn1OctetString_Clone(&TrustAnchor.KeyIdentifier, pKeyIdentifier, &g_RTAsn1DefaultAllocator);
if (RT_FAILURE(rc))
RTMsgError("RTAsn1OctetString_Clone failed: %Rrc", rc);
RTAsn1Core_ResetImplict(RTAsn1OctetString_GetAsn1Core(&TrustAnchor.KeyIdentifier)); /* temporary hack. */
}
else
RTMsgWarning("No key identifier found or has zero length.");
/* Subject */
if (RT_SUCCESS(rc))
{
Assert(!RTCrTafCertPathControls_IsPresent(&TrustAnchor.CertPath));
rc = RTCrTafCertPathControls_Init(&TrustAnchor.CertPath, &g_RTAsn1DefaultAllocator);
if (RT_SUCCESS(rc))
{
Assert(RTCrX509Name_IsPresent(&TrustAnchor.CertPath.TaName));
RTCrX509Name_Delete(&TrustAnchor.CertPath.TaName);
rc = RTCrX509Name_Clone(&TrustAnchor.CertPath.TaName, &Certificate.TbsCertificate.Subject,
&g_RTAsn1DefaultAllocator);
if (RT_SUCCESS(rc))
{
RTAsn1Core_ResetImplict(RTCrX509Name_GetAsn1Core(&TrustAnchor.CertPath.TaName)); /* temporary hack. */
rc = RTCrX509Name_RecodeAsUtf8(&TrustAnchor.CertPath.TaName, &g_RTAsn1DefaultAllocator);
if (RT_FAILURE(rc))
RTMsgError("RTCrX509Name_RecodeAsUtf8 failed: %Rrc", rc);
}
else
RTMsgError("RTCrX509Name_Clone failed: %Rrc", rc);
}
else
RTMsgError("RTCrTafCertPathControls_Init failed: %Rrc", rc);
}
/* Check that what we've constructed makes some sense. */
if (RT_SUCCESS(rc))
{
rc = RTCrTafTrustAnchorInfo_CheckSanity(&TrustAnchor, 0, RTErrInfoInitStatic(&StaticErrInfo), "TAI");
if (RT_FAILURE(rc))
RTMsgError("RTCrTafTrustAnchorInfo_CheckSanity failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
}
if (RT_SUCCESS(rc))
{
/*
* Encode it and write it to the output file.
*/
uint32_t cbEncoded;
rc = RTAsn1EncodePrepare(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, &cbEncoded,
RTErrInfoInitStatic(&StaticErrInfo));
if (RT_SUCCESS(rc))
{
if (State.cVerbose >= 1)
RTAsn1Dump(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), 0, 0, RTStrmDumpPrintfV, g_pStdOut);
PRTSTREAM pStrm;
rc = RTStrmOpen(State.pszOutput, "wb", &pStrm);
if (RT_SUCCESS(rc))
{
rc = RTAsn1EncodeWrite(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER,
handleMakeTaInfoWriter, pStrm, RTErrInfoInitStatic(&StaticErrInfo));
if (RT_SUCCESS(rc))
{
rc = RTStrmClose(pStrm);
if (RT_SUCCESS(rc))
RTMsgInfo("Successfully wrote TrustedAnchorInfo to '%s'.", State.pszOutput);
else
RTMsgError("RTStrmClose failed: %Rrc");
}
else
{
RTMsgError("RTAsn1EncodeWrite failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
RTStrmClose(pStrm);
}
}
else
RTMsgError("Error opening '%s' for writing: %Rrcs", State.pszOutput, rc);
}
else
RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg);
}
RTCrTafTrustAnchorInfo_Delete(&TrustAnchor);
}
else
RTMsgError("RTCrTafTrustAnchorInfo_Init failed: %Rrc", rc);
RTCrX509Certificate_Delete(&Certificate);
return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}
/*
* The 'version' command.
*/
static RTEXITCODE HelpVersion(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm, "version\n");
return RTEXITCODE_SUCCESS;
}
static RTEXITCODE HandleVersion(int cArgs, char **papszArgs)
{
RTPrintf("%s\n", RTBldCfgVersion());
return RTEXITCODE_SUCCESS;
}
/**
* Command mapping.
*/
static struct
{
/** The command. */
const char *pszCmd;
/**
* Handle the command.
* @returns Program exit code.
* @param cArgs Number of arguments.
* @param papszArgs The argument vector, starting with the command name.
*/
RTEXITCODE (*pfnHandler)(int cArgs, char **papszArgs);
/**
* Produce help.
* @returns RTEXITCODE_SUCCESS to simplify handling '--help' in the handler.
* @param pStrm Where to send help text.
* @param enmLevel The level of the help information.
*/
RTEXITCODE (*pfnHelp)(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel);
}
/** Mapping commands to handler and helper functions. */
const g_aCommands[] =
{
{ "extract-exe-signer-cert", HandleExtractExeSignerCert, HelpExtractExeSignerCert },
#ifndef IPRT_IN_BUILD_TOOL
{ "verify-exe", HandleVerifyExe, HelpVerifyExe },
#endif
{ "make-tainfo", HandleMakeTaInfo, HelpMakeTaInfo },
{ "help", HandleHelp, HelpHelp },
{ "--help", HandleHelp, NULL },
{ "-h", HandleHelp, NULL },
{ "version", HandleVersion, HelpVersion },
{ "--version", HandleVersion, NULL },
{ "-V", HandleVersion, NULL },
};
/*
* The 'help' command.
*/
static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel)
{
RTStrmPrintf(pStrm, "help [cmd-patterns]\n");
return RTEXITCODE_SUCCESS;
}
static RTEXITCODE HandleHelp(int cArgs, char **papszArgs)
{
RTSIGNTOOLHELP enmLevel = cArgs <= 1 ? RTSIGNTOOLHELP_USAGE : RTSIGNTOOLHELP_FULL;
uint32_t cShowed = 0;
for (uint32_t iCmd = 0; iCmd < RT_ELEMENTS(g_aCommands); iCmd++)
{
if (g_aCommands[iCmd].pfnHelp)
{
bool fShow;
if (cArgs <= 1)
fShow = true;
else
{
for (int iArg = 1; iArg < cArgs; iArg++)
if (RTStrSimplePatternMultiMatch(papszArgs[iArg], RTSTR_MAX, g_aCommands[iCmd].pszCmd, RTSTR_MAX, NULL))
{
fShow = true;
break;
}
}
if (fShow)
{
g_aCommands[iCmd].pfnHelp(g_pStdOut, enmLevel);
cShowed++;
}
}
}
return cShowed ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}
int main(int argc, char **argv)
{
int rc = RTR3InitExe(argc, &argv, 0);
if (RT_FAILURE(rc))
return RTMsgInitFailure(rc);
/*
* Parse global arguments.
*/
int iArg = 1;
/* none presently. */
/*
* Command dispatcher.
*/
if (iArg < argc)
{
const char *pszCmd = argv[iArg];
uint32_t i = RT_ELEMENTS(g_aCommands);
while (i-- > 0)
if (!strcmp(g_aCommands[i].pszCmd, pszCmd))
return g_aCommands[i].pfnHandler(argc - iArg, &argv[iArg]);
RTMsgError("Unknown command '%s'.", pszCmd);
}
else
RTMsgError("No command given. (try --help)");
return RTEXITCODE_SYNTAX;
}
| 38.530655 | 129 | 0.570233 | egraba |
a82396571fb885084e14cbe0c347a9d3c040b36c | 1,702 | cpp | C++ | math/fibonacci.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | math/fibonacci.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | math/fibonacci.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | /**
* @file
* @brief Generate fibonacci sequence
*
* Calculate the the value on Fibonacci's sequence given an
* integer as input.
* \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f]
*
* @see fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp
*/
#include <cassert>
#include <iostream>
/**
* Recursively compute sequences
* @param n input
* @returns n-th element of the Fbinacci's sequence
*/
uint64_t fibonacci(uint64_t n)
{
/* If the input is 0 or 1 just return the same
This will set the first 2 values of the sequence */
if (n <= 1)
{
return n;
}
/* Add the last 2 values of the sequence to get next */
return fibonacci(n - 1) + fibonacci(n - 2);
}
/**
* Function for testing the fibonacci() function with a few
* test cases and assert statement.
* @returns `void`
*/
static void test()
{
uint64_t test_case_1 = fibonacci(0);
assert(test_case_1 == 0);
std::cout << "Passed Test 1!" << std::endl;
uint64_t test_case_2 = fibonacci(1);
assert(test_case_2 == 1);
std::cout << "Passed Test 2!" << std::endl;
uint64_t test_case_3 = fibonacci(2);
assert(test_case_3 == 1);
std::cout << "Passed Test 3!" << std::endl;
uint64_t test_case_4 = fibonacci(3);
assert(test_case_4 == 2);
std::cout << "Passed Test 4!" << std::endl;
uint64_t test_case_5 = fibonacci(4);
assert(test_case_5 == 3);
std::cout << "Passed Test 5!" << std::endl;
uint64_t test_case_6 = fibonacci(15);
assert(test_case_6 == 610);
std::cout << "Passed Test 6!" << std::endl << std::endl;
}
/// Main function
int main()
{
test();
int n = 0;
std::cin >> n;
assert(n >= 0);
std::cout << "F(" << n << ")= " << fibonacci(n) << std::endl;
}
| 25.029412 | 69 | 0.62926 | dvijaymanohar |
a82466ae6673a5f0ef3d223463a800485c27c369 | 31,786 | cpp | C++ | Source/Core/FileFormat/XML/TinyXML.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | Source/Core/FileFormat/XML/TinyXML.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | Source/Core/FileFormat/XML/TinyXML.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************/
/**
* @file TinyXML.cpp
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id: TinyXML.cpp 631 2010-10-10 02:15:35Z naohisa.sakamoto $
*/
/****************************************************************************/
/*
Copyright (c) 2000 Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "TinyXML.h"
#include <cctype>
#include <kvs/DebugNew>
namespace { template <typename T> void Ignore( T ){} }
const char* TiXmlBase::errorString[ TIXML_ERROR_STRING_COUNT ] =
{
"No error.",
"Failed to open file.",
"Memory allocation failed.",
"Error parsing Element.",
"Failed to read Element name",
"Error reading Element value.",
"Error reading Attributes.",
"Error: empty tag.",
"Error reading end tag.",
"Error parsing Unknown.",
"Error parsing Comment.",
"Error parsing Declaration.",
};
const char* TiXmlBase::SkipWhiteSpace( const char* p )
{
while ( p && *p &&
( isspace( *p ) || *p == '\n' || *p == '\r' ) )
p++;
return p;
}
const char* TiXmlBase::ReadName( const char* p, std::string* name )
{
*name = "";
const char* start = p;
// Names start with letters or underscores.
// After that, they can be letters, underscores, numbers,
// hyphens, or colons. (Colons are valid ony for namespaces,
// but tinyxml can't tell namespaces from names.)
if ( p && ( isalpha( *p ) || *p == '_' ) )
{
p++;
while( p && *p &&
( isalnum( *p )
|| *p == '_'
|| *p == '-'
|| *p == ':' ) )
{
p++;
}
name->append( start, p - start );
return p;
}
return 0;
}
const char* TiXmlBase::ReadText(
const char* p,
std::string* text,
bool trimWhiteSpace,
const char* endTag,
bool caseInsensitive )
{
::Ignore( caseInsensitive );
*text = "";
if ( !trimWhiteSpace // certain tags always keep whitespace
/*|| !condenseWhiteSpace*/ ) // if true, whitespace is always kept
{
// Keep all the white space.
while ( p && *p
&& strncmp( p, endTag, strlen(endTag) ) != 0
)
{
char c = *(p++);
(* text) += c;
}
}
else
{
bool whitespace = false;
// Remove leading white space:
p = SkipWhiteSpace( p );
while ( p && *p
&& strncmp( p, endTag, strlen(endTag) ) != 0 )
{
if ( *p == '\r' || *p == '\n' )
{
whitespace = true;
++p;
}
else if ( isspace( *p ) )
{
whitespace = true;
++p;
}
else
{
// If we've found whitespace, add it before the
// new character. Any whitespace just becomes a space.
if ( whitespace )
{
(* text) += ' ';
whitespace = false;
}
char c = *(p++);
(* text) += c;
}
}
}
return p + strlen( endTag );
}
const char* TiXmlDocument::Parse( const char* start )
{
// Parse away, at the document level. Since a document
// contains nothing but other tags, most of what happens
// here is skipping white space.
const char* p = start;
p = SkipWhiteSpace( p );
if ( !p || !*p )
{
error = true;
errorDesc = "Document empty.";
}
while ( p && *p )
{
if ( *p != '<' )
{
error = true;
errorDesc = "The '<' symbol that starts a tag was not found.";
break;
}
else
{
TiXmlNode* node = IdentifyAndParse( &p );
if ( node )
{
LinkEndChild( node );
}
}
p = SkipWhiteSpace( p );
}
return 0; // Return null is fine for a document: once it is read, the parsing is over.
}
TiXmlNode* TiXmlNode::IdentifyAndParse( const char** where )
{
const char* p = *where;
TiXmlNode* returnNode = 0;
assert( *p == '<' );
TiXmlDocument* doc = GetDocument();
p = SkipWhiteSpace( p+1 );
// What is this thing?
// - Elements start with a letter or underscore, but xml is reserved.
// - Comments: <!--
// - Everthing else is unknown to tinyxml.
//
if ( tolower( *(p+0) ) == '?'
&& tolower( *(p+1) ) == 'x'
&& tolower( *(p+2) ) == 'm'
&& tolower( *(p+3) ) == 'l' )
{
#ifdef DEBUG_PARSER
printf( "XML parsing Declaration\n" );
#endif
returnNode = new TiXmlDeclaration();
}
else if ( isalpha( *p ) || *p == '_' )
{
#ifdef DEBUG_PARSER
printf( "XML parsing Element\n" );
#endif
returnNode = new TiXmlElement( "" );
}
else if ( *(p+0) == '!'
&& *(p+1) == '-'
&& *(p+2) == '-' )
{
#ifdef DEBUG_PARSER
printf( "XML parsing Comment\n" );
#endif
returnNode = new TiXmlComment();
}
else if ( strncmp(p, "![CDATA[", 8) == 0 )
{
TiXmlNode* cdataNode = new TiXmlCData();
if ( !cdataNode )
{
if ( doc ) doc->SetError( TIXML_ERROR_OUT_OF_MEMORY );
return 0;
}
returnNode = cdataNode;
}
else
{
#ifdef DEBUG_PARSER
printf( "XML parsing Comment\n" );
#endif
returnNode = new TiXmlUnknown();
}
if ( returnNode )
{
// Set the parent, so it can report errors
returnNode->parent = this;
p = returnNode->Parse( p );
}
else
{
if ( doc )
doc->SetError( TIXML_ERROR_OUT_OF_MEMORY );
p = 0;
}
*where = p;
return returnNode;
}
const char* TiXmlElement::Parse( const char* p )
{
TiXmlDocument* document = GetDocument();
p = SkipWhiteSpace( p );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT );
return 0;
}
// Read the name.
p = ReadName( p, &value );
if ( !p )
{
if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME );
return 0;
}
std::string endTag = "</";
endTag += value;
endTag += ">";
// Check for and read attributes. Also look for an empty
// tag or an end tag.
while ( p && *p )
{
p = SkipWhiteSpace( p );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
if ( *p == '/' )
{
// Empty tag.
if ( *(p+1) != '>' )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY );
return 0;
}
return p+2;
}
else if ( *p == '>' )
{
// Done with attributes (if there were any.)
// Read the value -- which can include other
// elements -- read the end tag, and return.
p = ReadValue( p+1 ); // Note this is an Element method, and will set the error if one happens.
if ( !p )
return 0;
// We should find the end tag now
std::string buf( p, endTag.size() );
if ( endTag == buf )
{
return p+endTag.size();
}
else
{
if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG );
return 0;
}
}
else
{
// Try to read an element:
TiXmlAttribute attrib;
attrib.SetDocument( document );
p = attrib.Parse( p );
if ( p )
{
SetAttribute( attrib.Name(), attrib.Value() );
}
}
}
return 0;
}
const char* TiXmlElement::ReadValue( const char* p )
{
TiXmlDocument* document = GetDocument();
// Read in text and elements in any order.
p = SkipWhiteSpace( p );
while ( p && *p )
{
const char* start = p;
while ( *p && *p != '<' )
p++;
if ( !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE );
return 0;
}
if ( p != start )
{
// Take what we have, make a text element.
TiXmlText* text = new TiXmlText();
if ( !text )
{
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY );
return 0;
}
text->Parse( start );
if ( !text->Blank() )
LinkEndChild( text );
else
delete text;
}
else
{
// We hit a '<'
// Have we hit a new element or an end tag?
if ( *(p+1) == '/' )
{
return p; // end tag
}
else
{
// TiXmlElement* element = new TiXmlElement( "" );
//
// if ( element )
// {
// p = element->Parse( p+1 );
// if ( p )
// LinkEndChild( element );
// }
// else
// {
// if ( document ) document->SetError( ERROR_OUT_OF_MEMORY );
// return 0;
// }
TiXmlNode* node = IdentifyAndParse( &p );
if ( node )
{
LinkEndChild( node );
}
else
{
return 0;
}
}
}
}
return 0;
}
const char* TiXmlUnknown::Parse( const char* p )
{
const char* end = strchr( p, '>' );
if ( !end )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_PARSING_UNKNOWN );
return 0;
}
else
{
value = std::string( p, end-p );
// value.resize( end - p );
return end + 1; // return just past the '>'
}
}
const char* TiXmlComment::Parse( const char* p )
{
assert( *p == '!' && *(p+1) == '-' && *(p+2) == '-' );
// Find the end, copy the parts between to the value of
// this object, and return.
const char* start = p+3;
const char* end = strstr( p, "-->" );
if ( !end )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_PARSING_COMMENT );
return 0;
}
else
{
// Assemble the comment, removing the white space.
bool whiteSpace = false;
const char* q;
for( q=start; q<end; q++ )
{
if ( isspace( *q ) )
{
if ( !whiteSpace )
{
value += ' ';
whiteSpace = true;
}
}
else
{
value += *q;
whiteSpace = false;
}
}
// value = std::string( start, end-start );
return end + 3; // return just past the '>'
}
}
const char* TiXmlAttribute::Parse( const char* p )
{
// Read the name, the '=' and the value.
p = ReadName( p, &name );
if ( !p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
p = SkipWhiteSpace( p );
if ( !p || *p != '=' )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
p = SkipWhiteSpace( p+1 );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
return 0;
}
const char* end = 0;
const char* start = p+1;
const char* past = 0;
if ( *p == '\'' )
{
end = strchr( start, '\'' );
past = end+1;
}
else if ( *p == '"' )
{
end = strchr( start, '"' );
past = end+1;
}
else
{
// All attribute values should be in single or double quotes.
// But this is such a common error that the parser will try
// its best, even without them.
start--;
for ( end = start; *end; end++ )
{
if ( isspace( *end ) || *end == '/' || *end == '>' )
break;
}
past = end;
}
value = std::string( start, end-start );
return past;
}
const char* TiXmlText::Parse( const char* p )
{
value = "";
bool ignoreWhite = true;
const char* end = "<";
p = ReadText( p, &value, ignoreWhite, end, false );
if ( p )
return p-1; // don't truncate the '<'
return 0;
#if 0
// Remove leading white space:
p = SkipWhiteSpace( p );
while ( *p && *p != '<' )
{
if ( *p == '\r' || *p == '\n' )
{
whitespace = true;
}
else if ( isspace( *p ) )
{
whitespace = true;
}
else
{
// If we've found whitespace, add it before the
// new character. Any whitespace just becomes a space.
if ( whitespace )
{
value += ' ';
whitespace = false;
}
value += *p;
}
p++;
}
// Keep white space before the '<'
if ( whitespace )
value += ' ';
return p;
#endif
}
const char* TiXmlCData::Parse( const char* p )
{
value = "";
bool ignoreWhite = false;
p += 8;
const char* end = "]]>";
p = ReadText( p, &value, ignoreWhite, end, false );
if ( p )
return p;
return 0;
}
const char* TiXmlDeclaration::Parse( const char* p )
{
// Find the beginning, find the end, and look for
// the stuff in-between.
const char* start = p+4;
const char* end = strstr( start, "?>" );
// Be nice to the user:
if ( !end )
{
end = strstr( start, ">" );
end++;
}
else
{
end += 2;
}
if ( !end )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_PARSING_DECLARATION );
return 0;
}
else
{
const char* p;
p = strstr( start, "version" );
if ( p && p < end )
{
TiXmlAttribute attrib;
attrib.Parse( p );
version = attrib.Value();
}
p = strstr( start, "encoding" );
if ( p && p < end )
{
TiXmlAttribute attrib;
attrib.Parse( p );
encoding = attrib.Value();
}
p = strstr( start, "standalone" );
if ( p && p < end )
{
TiXmlAttribute attrib;
attrib.Parse( p );
standalone = attrib.Value();
}
}
return end;
}
bool TiXmlText::Blank()
{
for ( unsigned i=0; i<value.size(); i++ )
if ( !isspace( value[i] ) )
return false;
return true;
}
TiXmlNode::TiXmlNode( NodeType _type )
{
parent = 0;
type = _type;
firstChild = 0;
lastChild = 0;
prev = 0;
next = 0;
}
TiXmlNode::~TiXmlNode()
{
TiXmlNode* node = firstChild;
TiXmlNode* temp = 0;
while ( node )
{
temp = node;
node = node->next;
delete temp;
}
}
void TiXmlNode::Clear()
{
TiXmlNode* node = firstChild;
TiXmlNode* temp = 0;
while ( node )
{
temp = node;
node = node->next;
delete temp;
}
firstChild = 0;
lastChild = 0;
}
TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node )
{
node->parent = this;
node->prev = lastChild;
node->next = 0;
if ( lastChild )
lastChild->next = node;
else
firstChild = node; // it was an empty list.
lastChild = node;
return node;
}
TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis )
{
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
return LinkEndChild( node );
}
TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis )
{
if ( beforeThis->parent != this )
return 0;
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
node->parent = this;
node->next = beforeThis;
node->prev = beforeThis->prev;
beforeThis->prev->next = node;
beforeThis->prev = node;
return node;
}
TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis )
{
if ( afterThis->parent != this )
return 0;
TiXmlNode* node = addThis.Clone();
if ( !node )
return 0;
node->parent = this;
node->prev = afterThis;
node->next = afterThis->next;
afterThis->next->prev = node;
afterThis->next = node;
return node;
}
TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis )
{
if ( replaceThis->parent != this )
return 0;
TiXmlNode* node = withThis.Clone();
if ( !node )
return 0;
node->next = replaceThis->next;
node->prev = replaceThis->prev;
if ( replaceThis->next )
replaceThis->next->prev = node;
else
lastChild = node;
if ( replaceThis->prev )
replaceThis->prev->next = node;
else
firstChild = node;
delete replaceThis;
return node;
}
bool TiXmlNode::RemoveChild( TiXmlNode* removeThis )
{
if ( removeThis->parent != this )
{
assert( 0 );
return false;
}
if ( removeThis->next )
removeThis->next->prev = removeThis->prev;
else
lastChild = removeThis->prev;
if ( removeThis->prev )
removeThis->prev->next = removeThis->next;
else
firstChild = removeThis->next;
delete removeThis;
return true;
}
TiXmlNode* TiXmlNode::FirstChild( const std::string& value ) const
{
TiXmlNode* node;
for ( node = firstChild; node; node = node->next )
{
if ( node->Value() == value )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::LastChild( const std::string& value ) const
{
TiXmlNode* node;
for ( node = lastChild; node; node = node->prev )
{
if ( node->Value() == value )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous )
{
if ( !previous )
{
return FirstChild();
}
else
{
assert( previous->parent == this );
return previous->NextSibling();
}
}
TiXmlNode* TiXmlNode::IterateChildren( const std::string& val, TiXmlNode* previous )
{
if ( !previous )
{
return FirstChild( val );
}
else
{
assert( previous->parent == this );
return previous->NextSibling( val );
}
}
TiXmlNode* TiXmlNode::NextSibling( const std::string& value ) const
{
TiXmlNode* node;
for ( node = next; node; node = node->next )
{
if ( node->Value() == value )
return node;
}
return 0;
}
TiXmlNode* TiXmlNode::PreviousSibling( const std::string& value ) const
{
TiXmlNode* node;
for ( node = prev; node; node = node->prev )
{
if ( node->Value() == value )
return node;
}
return 0;
}
void TiXmlElement::RemoveAttribute( const std::string& name )
{
TiXmlAttribute* node = attributeSet.Find( name );
if ( node )
{
attributeSet.Remove( node );
delete node;
}
}
TiXmlElement* TiXmlNode::FirstChildElement() const
{
TiXmlNode* node;
for ( node = FirstChild();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::FirstChildElement( const std::string& value ) const
{
TiXmlNode* node;
for ( node = FirstChild( value );
node;
node = node->NextSibling( value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::NextSiblingElement() const
{
TiXmlNode* node;
for ( node = NextSibling();
node;
node = node->NextSibling() )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlElement* TiXmlNode::NextSiblingElement( const std::string& value ) const
{
TiXmlNode* node;
for ( node = NextSibling( value );
node;
node = node->NextSibling( value ) )
{
if ( node->ToElement() )
return node->ToElement();
}
return 0;
}
TiXmlDocument* TiXmlNode::GetDocument() const
{
const TiXmlNode* node;
for( node = this; node; node = node->parent )
{
if ( node->ToDocument() )
return node->ToDocument();
}
return 0;
}
// TiXmlElement::TiXmlElement()
// : TiXmlNode( TiXmlNode::ELEMENT )
// {
// }
TiXmlElement::TiXmlElement( const std::string& _value )
: TiXmlNode( TiXmlNode::ELEMENT )
{
firstChild = lastChild = 0;
value = _value;
}
TiXmlElement::~TiXmlElement()
{
while( attributeSet.First() )
{
TiXmlAttribute* node = attributeSet.First();
attributeSet.Remove( node );
delete node;
}
}
const std::string* TiXmlElement::Attribute( const std::string& name ) const
{
TiXmlAttribute* node = attributeSet.Find( name );
if ( node )
return &(node->Value() );
return 0;
}
const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const
{
const std::string* s = Attribute( name );
if ( s )
*i = atoi( s->c_str() );
else
*i = 0;
return s;
}
void TiXmlElement::SetAttribute( const std::string& name, int val )
{
char buf[64];
sprintf( buf, "%d", val );
std::string v = buf;
SetAttribute( name, v );
}
void TiXmlElement::SetAttribute( const std::string& name, const std::string& value )
{
TiXmlAttribute* node = attributeSet.Find( name );
if ( node )
{
node->SetValue( value );
return;
}
TiXmlAttribute* attrib = new TiXmlAttribute( name, value );
if ( attrib )
{
attributeSet.Add( attrib );
}
else
{
TiXmlDocument* document = GetDocument();
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY );
}
}
void TiXmlElement::Print( FILE* fp, int depth )
{
int i;
for ( i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "<%s", value.c_str() );
TiXmlAttribute* attrib;
for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
{
fprintf( fp, " " );
attrib->Print( fp, 0 );
}
// If this node has children, give it a closing tag. Else
// make it an empty tag.
TiXmlNode* node;
if ( firstChild )
{
fprintf( fp, ">" );
for ( node = firstChild; node; node=node->NextSibling() )
{
if ( !node->ToText() )
fprintf( fp, "\n" );
node->Print( fp, depth+1 );
}
fprintf( fp, "\n" );
for ( i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "</%s>", value.c_str() );
}
else
{
fprintf( fp, " />" );
}
}
TiXmlNode* TiXmlElement::Clone() const
{
TiXmlElement* clone = new TiXmlElement( Value() );
if ( !clone )
return 0;
CopyToClone( clone );
// Clone the attributes, then clone the children.
TiXmlAttribute* attribute = 0;
for( attribute = attributeSet.First();
attribute;
attribute = attribute->Next() )
{
clone->SetAttribute( attribute->Name(), attribute->Value() );
}
TiXmlNode* node = 0;
for ( node = firstChild; node; node = node->NextSibling() )
{
clone->LinkEndChild( node->Clone() );
}
return clone;
}
TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT )
{
error = false;
// factory = new TiXmlFactory();
}
TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT )
{
// factory = new TiXmlFactory();
value = documentName;
error = false;
}
// void TiXmlDocument::SetFactory( TiXmlFactory* f )
// {
// delete factory;
// factory = f;
// }
bool TiXmlDocument::LoadFile()
{
return LoadFile( value );
}
bool TiXmlDocument::SaveFile()
{
return SaveFile( value );
}
bool TiXmlDocument::LoadFile( FILE* fp )
{
// Delete the existing data:
Clear();
unsigned size, first;
first = ftell( fp );
fseek( fp, 0, SEEK_END );
size = ftell( fp ) - first + 1;
fseek( fp, first, SEEK_SET );
char* buf = new char[size];
char* p = buf;
while( fgets( p, size, fp ) )
{
p = strchr( p, 0 );
}
fclose( fp );
Parse( buf );
delete [] buf;
if ( !Error() )
return true;
return false;
}
bool TiXmlDocument::LoadFile( const std::string& filename )
{
// Delete the existing data:
Clear();
// Load the new data:
FILE* fp = fopen( filename.c_str(), "r" );
if ( fp )
{
return LoadFile(fp);
}
else
{
SetError( TIXML_ERROR_OPENING_FILE );
}
return false;
}
bool TiXmlDocument::SaveFile( const std::string& filename )
{
FILE* fp = fopen( filename.c_str(), "w" );
if ( fp )
{
Print( fp, 0 );
fclose( fp );
return true;
}
return false;
}
TiXmlNode* TiXmlDocument::Clone() const
{
TiXmlDocument* clone = new TiXmlDocument();
if ( !clone )
return 0;
CopyToClone( clone );
clone->error = error;
clone->errorDesc = errorDesc;
TiXmlNode* node = 0;
for ( node = firstChild; node; node = node->NextSibling() )
{
clone->LinkEndChild( node->Clone() );
}
return clone;
}
void TiXmlDocument::Print( FILE* fp, int )
{
TiXmlNode* node;
for ( node=FirstChild(); node; node=node->NextSibling() )
{
node->Print( fp, 0 );
fprintf( fp, "\n" );
}
}
TiXmlAttribute* TiXmlAttribute::Next()
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( next->value.empty() && next->name.empty() )
return 0;
return next;
}
TiXmlAttribute* TiXmlAttribute::Previous()
{
// We are using knowledge of the sentinel. The sentinel
// have a value or name.
if ( prev->value.empty() && prev->name.empty() )
return 0;
return prev;
}
void TiXmlAttribute::Print( FILE* fp, int )
{
if ( value.find( '\"' ) != std::string::npos )
fprintf( fp, "%s='%s'", name.c_str(), value.c_str() );
else
fprintf( fp, "%s=\"%s\"", name.c_str(), value.c_str() );
}
void TiXmlComment::Print( FILE* fp, int depth )
{
for ( int i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "<!--%s-->", value.c_str() );
}
TiXmlNode* TiXmlComment::Clone() const
{
TiXmlComment* clone = new TiXmlComment();
if ( !clone )
return 0;
CopyToClone( clone );
return clone;
}
void TiXmlText::Print( FILE* fp, int )
{
fprintf( fp, "%s", value.c_str() );
}
TiXmlNode* TiXmlText::Clone() const
{
TiXmlText* clone = 0;
clone = new TiXmlText();
if ( !clone )
return 0;
CopyToClone( clone );
return clone;
}
TiXmlDeclaration::TiXmlDeclaration( const std::string& _version,
const std::string& _encoding,
const std::string& _standalone )
: TiXmlNode( TiXmlNode::DECLARATION )
{
version = _version;
encoding = _encoding;
standalone = _standalone;
}
void TiXmlDeclaration::Print( FILE* fp, int )
{
std::string out = "<?xml ";
if ( !version.empty() )
{
out += "version=\"";
out += version;
out += "\" ";
}
if ( !encoding.empty() )
{
out += "encoding=\"";
out += encoding;
out += "\" ";
}
if ( !standalone.empty() )
{
out += "standalone=\"";
out += standalone;
out += "\" ";
}
out += "?>";
fprintf( fp, "%s", out.c_str() );
}
TiXmlNode* TiXmlDeclaration::Clone() const
{
TiXmlDeclaration* clone = new TiXmlDeclaration();
if ( !clone )
return 0;
CopyToClone( clone );
clone->version = version;
clone->encoding = encoding;
clone->standalone = standalone;
return clone;
}
void TiXmlUnknown::Print( FILE* fp, int depth )
{
for ( int i=0; i<depth; i++ )
fprintf( fp, " " );
fprintf( fp, "<%s>", value.c_str() );
}
TiXmlNode* TiXmlUnknown::Clone() const
{
TiXmlUnknown* clone = new TiXmlUnknown();
if ( !clone )
return 0;
CopyToClone( clone );
return clone;
}
TiXmlAttributeSet::TiXmlAttributeSet()
{
sentinel.next = &sentinel;
sentinel.prev = &sentinel;
}
TiXmlAttributeSet::~TiXmlAttributeSet()
{
assert( sentinel.next == &sentinel );
assert( sentinel.prev == &sentinel );
}
void TiXmlAttributeSet::Add( TiXmlAttribute* addMe )
{
assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set.
addMe->next = &sentinel;
addMe->prev = sentinel.prev;
sentinel.prev->next = addMe;
sentinel.prev = addMe;
}
void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe )
{
TiXmlAttribute* node;
for( node = sentinel.next; node != &sentinel; node = node->next )
{
if ( node == removeMe )
{
node->prev->next = node->next;
node->next->prev = node->prev;
node->next = 0;
node->prev = 0;
return;
}
}
assert( 0 ); // we tried to remove a non-linked attribute.
}
TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const
{
TiXmlAttribute* node;
for( node = sentinel.next; node != &sentinel; node = node->next )
{
if ( node->Name() == name )
return node;
}
return 0;
}
| 22.119694 | 107 | 0.499528 | CCSEPBVR |
a824816e60c082aed1336fc418f8799592b85388 | 5,988 | cpp | C++ | gapid_tests/command_buffer_tests/vkCmdClearDepthStencilImage_test/main.cpp | iburinoc/vulkan_test_applications | f1c8ed9660c446fe04cb9fd9a51ad96417ea1801 | [
"Apache-2.0"
] | null | null | null | gapid_tests/command_buffer_tests/vkCmdClearDepthStencilImage_test/main.cpp | iburinoc/vulkan_test_applications | f1c8ed9660c446fe04cb9fd9a51ad96417ea1801 | [
"Apache-2.0"
] | null | null | null | gapid_tests/command_buffer_tests/vkCmdClearDepthStencilImage_test/main.cpp | iburinoc/vulkan_test_applications | f1c8ed9660c446fe04cb9fd9a51ad96417ea1801 | [
"Apache-2.0"
] | null | null | null | /* 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 "support/entry/entry.h"
#include "support/log/log.h"
#include "vulkan_helpers/vulkan_application.h"
#include "vulkan_wrapper/sub_objects.h"
#include <algorithm>
int main_entry(const entry::entry_data* data) {
data->log->LogInfo("Application Startup");
vulkan::VulkanApplication app(data->root_allocator, data->log.get(), data);
vulkan::VkDevice& device = app.device();
{
// 1. Clear a 2D single layer, single mip level depth/stencil image
const VkExtent3D image_extent{32, 32, 1};
const VkImageCreateInfo image_create_info{
/* sType = */ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
/* pNext = */ nullptr,
/* flags = */ 0,
/* imageType = */ VK_IMAGE_TYPE_2D,
/* format = */ VK_FORMAT_D16_UNORM,
/* extent = */ image_extent,
/* mipLevels = */ 1,
/* arrayLayers = */ 1,
/* samples = */ VK_SAMPLE_COUNT_1_BIT,
/* tiling = */ VK_IMAGE_TILING_OPTIMAL,
/* usage = */ VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
/* sharingMode = */ VK_SHARING_MODE_EXCLUSIVE,
/* queueFamilyIndexCount = */ 0,
/* pQueueFamilyIndices = */ nullptr,
/* initialLayout = */ VK_IMAGE_LAYOUT_UNDEFINED,
};
vulkan::ImagePointer image_ptr = app.CreateAndBindImage(&image_create_info);
// Clear value and range
const float depth_clear_float = 0.2;
unsigned short depth_clear_unorm = depth_clear_float * 0xffff;
VkClearDepthStencilValue clear_depth_stencil{
depth_clear_float, // depth
1, // stencil, not used here as the format does not contain stencil
// data.
};
VkImageSubresourceRange clear_range{
VK_IMAGE_ASPECT_DEPTH_BIT, // aspectMask
0, // baseMipLevel
1, // levelCount
0, // baseArrayLayer
1, // layerCount
};
// Get command buffer and call the vkCmdClearDepthStencilImage command
vulkan::VkCommandBuffer cmd_buf = app.GetCommandBuffer();
::VkCommandBuffer raw_cmd_buf = cmd_buf.get_command_buffer();
VkCommandBufferBeginInfo cmd_buf_begin_info{
VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, 0, nullptr};
cmd_buf->vkBeginCommandBuffer(cmd_buf, &cmd_buf_begin_info);
VkImageMemoryBarrier image_barrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
0, // srcAccessMask
VK_ACCESS_TRANSFER_WRITE_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_UNDEFINED, // oldLayout
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // newLayout
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
*image_ptr, // image
{VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1}, // subresourceRange
};
cmd_buf->vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &image_barrier);
cmd_buf->vkCmdClearDepthStencilImage(
cmd_buf, // commandBuffer
*image_ptr, // image
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // imageLayout
&clear_depth_stencil, // pDepthStencil
1, // rangeCount
&clear_range // pRagnes
);
cmd_buf->vkEndCommandBuffer(cmd_buf);
VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO,
nullptr,
0,
nullptr,
nullptr,
1,
&raw_cmd_buf,
0,
nullptr};
app.render_queue()->vkQueueSubmit(app.render_queue(), 1, &submit_info,
static_cast<VkFence>(VK_NULL_HANDLE));
app.render_queue()->vkQueueWaitIdle(app.render_queue());
// Dump the data in the cleared image
containers::vector<uint8_t> dump_data(data->root_allocator);
app.DumpImageLayersData(
image_ptr.get(), {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 0, 1}, {0, 0, 0},
image_extent, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &dump_data, {});
// Check the dump data
containers::vector<unsigned short> expected_data(
vulkan::GetImageExtentSizeInBytes(image_extent, VK_FORMAT_D16_UNORM) /
sizeof(unsigned short),
depth_clear_unorm, data->root_allocator);
LOG_ASSERT(==, data->log, expected_data.size(),
dump_data.size() / sizeof(unsigned short));
unsigned short* dump_data_ptr =
reinterpret_cast<unsigned short*>(dump_data.data());
std::for_each(expected_data.begin(), expected_data.end(),
[&data, &dump_data_ptr](unsigned short d) {
LOG_ASSERT(==, data->log, d, *dump_data_ptr++);
});
}
data->log->LogInfo("Application Shutdown");
return 0;
}
| 44.029412 | 80 | 0.599699 | iburinoc |
a824d6666c16ea26d15ceacbfbee3ebc419a324d | 367 | cpp | C++ | Chapter11/exercises/exercise_10/exercise_10.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | Chapter11/exercises/exercise_10/exercise_10.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | Chapter11/exercises/exercise_10/exercise_10.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | #include "exercise_10.h"
void f()
{
string s = "a series of whitespace seperated words";
vector<string> substrings = split(s);
for (auto substring : substrings)
{
cout << substring << endl;
}
}
int main()
{
try
{
f();
}
catch (...)
{
cout << "MAJOR ERROR\n";
return -1;
}
return 0;
} | 14.115385 | 56 | 0.490463 | JohnWoods11 |
a828ffbdc32c283c53263bbe75a44bebde5e3ebf | 2,008 | hpp | C++ | Server Lib/Game Server/GAME/player_mail_box.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 23 | 2021-10-31T00:20:21.000Z | 2022-03-26T07:24:40.000Z | Server Lib/Game Server/GAME/player_mail_box.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 5 | 2021-10-31T18:44:51.000Z | 2022-03-25T18:04:26.000Z | Server Lib/Game Server/GAME/player_mail_box.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 18 | 2021-10-20T02:31:56.000Z | 2022-02-01T11:44:36.000Z | // Arquivo player_mail_box.hpp
// Criado em 13/01/2021 as 09:52 por Acrisio
// Defini��o da classe PlayerMailBox
#pragma once
#ifndef _STDA_PLAYER_MAIL_BOX_HPP
#define _STDA_PLAYER_MAIL_BOX_HPP
#if defined(_WIN32)
#include <Windows.h>
#elif defined(__linux__)
#include "../../Projeto IOCP/UTIL/WinPort.h"
#include <pthread.h>
#include <unistd.h>
#endif
#include <map>
#include "../TYPE/pangya_game_st.h"
#include "../../Projeto IOCP/PANGYA_DB/pangya_db.h"
namespace stdA {
constexpr uint64_t EXPIRES_CACHE_TIME = 3 * 1000ull; // 3 Segundos
constexpr uint32_t NUM_OF_EMAIL_PER_PAGE = 20u; // 20 Emails por p�gina
constexpr uint32_t LIMIT_OF_UNREAD_EMAIL = 300u; // 300 Emails n�o lidos que pode enviar para o player
class PlayerMailBox {
public:
PlayerMailBox();
virtual ~PlayerMailBox();
void init(std::map< int32_t, EmailInfoEx >& _emails, uint32_t _uid);
void clear();
std::vector< MailBox > getPage(uint32_t _page);
std::vector< MailBox > getAllUnreadEmail();
uint32_t getTotalPages();
void addNewEmailArrived(int32_t _id);
EmailInfo getEmailInfo(int32_t _id, bool _ler = true);
// Deleta todos os itens quem tem no email, eles j� foram tirados do email pelo player
void leftItensFromEmail(int32_t _id);
// Deleta 1 ou mais emails de uma vez
void deleteEmail(int32_t* _a_id, uint32_t _count);
protected:
// Methods Static
static void SQLDBResponse(uint32_t _msg_id, pangya_db& _pangya_db, void* _arg);
static bool sort_last_arrived(MailBox& _rhs, MailBox& _lhs);
protected:
// Unsafe thread sync
bool checkLastUpdate();
void checkAndUpdate();
// Unsafe thread sync
void copyEmailInfoExToMailBox(EmailInfoEx& _email, MailBox& _mail);
void update();
protected:
uint32_t m_uid;
std::map< int32_t, EmailInfoEx > m_emails;
SYSTEMTIME m_last_update;
#if defined(_WIN32)
CRITICAL_SECTION m_cs;
#elif defined(__linux__)
pthread_mutex_t m_cs;
#endif
};
}
#endif // !_STDA_PLAYER_MAIL_BOX_HPP
| 23.904762 | 104 | 0.728586 | CCasusensa |
a82a53cca49e1fc369df95cd846299eed232c6d7 | 1,855 | cpp | C++ | src/wiztk/base/string.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 37 | 2017-11-22T14:15:33.000Z | 2021-11-25T20:39:39.000Z | src/wiztk/base/string.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 3 | 2018-03-01T12:44:22.000Z | 2021-01-04T23:14:41.000Z | src/wiztk/base/string.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 10 | 2017-11-25T19:09:11.000Z | 2020-12-02T02:05:47.000Z | /*
* Copyright 2017 The WizTK Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "wiztk/base/string.hpp"
#include <unicode/utf.h>
#include <unicode/unistr.h>
#include <unicode/ustream.h>
#include <unicode/stringpiece.h>
namespace wiztk {
namespace base {
String::String(const char *str) {
// TODO: temporary workaround, optimize this by ICU later:
icu::UnicodeString unicode = icu::UnicodeString::fromUTF8(icu::StringPiece(str));
assign(unicode.getBuffer());
}
String::String(const char16_t *str) {
assign(reinterpret_cast<const UChar *>(str));
}
String::String(const char32_t *str) {
// TODO: temporary workaround, optimize this by ICU later.
icu::UnicodeString unicode =
icu::UnicodeString::fromUTF32(reinterpret_cast<const UChar32 *>(str),
static_cast<uint32_t>(std::char_traits<char32_t>::length(str)));
assign(unicode.getBuffer());
}
std::ostream &operator<<(std::ostream &out, const String &str) {
// TODO: This create and copy the string array from String16 to icu::UnicodeString, find a better way for performance.
return out << icu::UnicodeString(str.data());
}
std::string String::ToUTF8() const {
std::string utf8;
icu::UnicodeString unicode = data();
unicode.toUTF8String(utf8);
return utf8;
}
} // namespace base
} // namespace wiztk
| 30.409836 | 120 | 0.712129 | wiztk |
a82df48d367f2b32a7cc49feef4c00bce3105606 | 15,546 | cpp | C++ | sdk/channel.cpp | faming-wang/QTeamSpeak3 | 41f6161cb87be7029c5d91ab4a33062d91445c64 | [
"Apache-2.0"
] | 2 | 2021-12-28T15:49:43.000Z | 2022-03-27T08:05:12.000Z | sdk/channel.cpp | faming-wang/QTeamSpeak3 | 41f6161cb87be7029c5d91ab4a33062d91445c64 | [
"Apache-2.0"
] | null | null | null | sdk/channel.cpp | faming-wang/QTeamSpeak3 | 41f6161cb87be7029c5d91ab4a33062d91445c64 | [
"Apache-2.0"
] | null | null | null | #include "channel.h"
#include "library.h"
#include "fileinfo.h"
#include "connection.h"
#include "filetransfer.h"
#include "private/cachemanager_p.h"
#include "private/interfacemanager_p.h"
namespace TeamSpeakSdk {
class Channel::Private
{
public:
int getInt(const Channel* channel, ChannelProperty flag)
{
return api().getChannelVariableAsInt(channel, flag);
}
uint64 getUInt64(const Channel* channel, ChannelProperty flag)
{
return api().getChannelVariableAsUInt64(channel, flag);
}
QString getString(const Channel* channel, ChannelProperty flag)
{
return api().getChannelVariableAsString(channel, flag);
}
void setInt(Channel* channel, ChannelProperty flag, int value)
{
api().setChannelVariableAsInt(channel, flag, value);
flushChannelUpdates(channel);
}
void setUInt64(Channel* channel, ChannelProperty flag, uint64 value)
{
api().setChannelVariableAsUInt64(channel, flag, value);
flushChannelUpdates(channel);
}
void setString(Channel* channel, ChannelProperty flag, const QString& value)
{
api().setChannelVariableAsString(channel, flag, value);
flushChannelUpdates(channel);
}
void flushChannelUpdates(Channel* channel)
{
if (channel->id() == 0)
return;
}
ID id = 0;
Connection* connection = nullptr;
struct Cache
{
QString name;
QString topic;
} cached;
};
/*!
* \class Channel
*
* \brief
*/
Channel::Channel(Connection* connection)
: d(new Private)
{
d->connection = connection;
}
Channel::Channel(Connection* connection, ID id, bool waitForProperties)
: Channel(connection)
{
setId(id);
refreshProperties(waitForProperties);
}
Channel::~Channel()
{
delete d;
}
Channel::Channel(const Channel& other) Q_DECL_NOTHROW
: d(new Private)
{
*d = *other.d;
}
Channel::Channel(Channel&& other) Q_DECL_NOTHROW
{
*d = *other.d;
}
void Channel::swap(Channel&& other)
{
qSwap(d, other.d);
}
Channel& Channel::operator=(const Channel& other) Q_DECL_NOTHROW
{
swap(std::move(Channel(other)));
return *this;
}
Channel& Channel::operator=(Channel&& other) Q_DECL_NOTHROW
{
swap(std::move(Channel(std::move(other))));
return *this;
}
bool Channel::operator==(const Channel& o) const Q_DECL_NOTHROW
{
if ((this) == &o)
return true;
return connection() == o.connection() && id() == o.id();
}
/*!
* ID of the channel
*/
Channel::ID Channel::id() const
{
return d->id;
}
void Channel::setId(ID id)
{
d->id = id;
}
/*!
* Server Connection
*/
Connection* Channel::connection() const
{
return d->connection;
}
void Channel::setConnection(Connection* server)
{
d->connection = server;
}
/*!
* The parent channel
*/
Channel* Channel::parent() const
{
return api().getParentChannelOfChannel(this);
}
/*!
* List of all clients in the channel, if the channel is currently subscribed.
*/
QList<Client*> Channel::clients() const
{
return api().getChannelClientList(this);
}
QList<Channel*> Channel::channels() const
{
return QList<Channel*>();
}
/*!
* Name of the channel
*/
QString Channel::name() const
{
return d->cached.name;
}
void Channel::setName(const QString& value)
{
d->setString(this, ChannelProperty::Name, value);
}
/*!
* Single-line channel topic
*/
QString Channel::topic() const
{
return d->cached.topic;
}
void Channel::setTopic(const QString& value)
{
d->setString(this, ChannelProperty::Topic, value);
}
/*!
* Optional channel description. Can have multiple lines.
* Needs to be request with \sa getChannelDescription().
*/
QString Channel::description() const
{
return d->getString(this, ChannelProperty::Description);
}
void Channel::setDescription(const QString& value)
{
d->setString(this, ChannelProperty::Description, value);
}
/*!
* Optional password for password-protected channels.
*/
void Channel::setPassword(const QString& value)
{
d->setString(this, ChannelProperty::Password, value);
}
/*!
* Codec used for this channel
*/
CodecType Channel::codec() const
{
return CodecType(d->getInt(this, ChannelProperty::Codec));
}
void Channel::setCodec(CodecType value)
{
d->setInt(this, ChannelProperty::Codec, utils::underlay(value));
}
/*!
* Quality of channel codec of this channel.
* Valid values range from 0 to 10, default is 7.
* Higher values result in better speech quality but more bandwidth usage
*/
int Channel::codecQuality() const
{
return d->getInt(this, ChannelProperty::CodecQuality);
}
void Channel::setCodecQuality(int value)
{
d->setInt(this, ChannelProperty::CodecQuality, value);
}
/*!
* Number of maximum clients who can join this channel
*/
int Channel::maxClients() const
{
return d->getInt(this, ChannelProperty::Maxclients);
}
void Channel::setMaxClients(int value)
{
d->setInt(this, ChannelProperty::Maxclients, value);
}
/*!
* Number of maximum clients who can join this channel and all subchannels
*/
int Channel::maxFamilyClients() const
{
return d->getInt(this, ChannelProperty::Maxfamilyclients);
}
void Channel::setMaxFamilyClients(int value)
{
d->setInt(this, ChannelProperty::Maxfamilyclients, value);
}
/*!
* \sa order() is the \sa channel() after which this channel is sorted.
* <see lang word="null" meaning its going to be the first \sa channel() under \sa parent()
*/
Channel* Channel::order() const
{
const auto orderId = d->getUInt64(this, ChannelProperty::Order);
return connection()->getChannel(orderId);
}
void Channel::setOrder(const Channel* value)
{
d->setUInt64(this, ChannelProperty::Order, value ? value->id() : 0);
}
/*!
* Permanent channels will be restored when the server restarts.
*/
bool Channel::isPermanent() const
{
return d->getInt(this, ChannelProperty::FlagPermanent) != 0;
}
void Channel::setPermanent(bool value)
{
d->setInt(this, ChannelProperty::FlagPermanent, value ? 1 : 0);
}
/*!
* Semi-permanent channels are not automatically deleted when the last user left
* but will not be restored when the server restarts.
*/
bool Channel::isSemiPermanent() const
{
return d->getInt(this, ChannelProperty::FlagSemiPermanent) != 0;
}
void Channel::setSemiPermanent(bool value)
{
d->setInt(this, ChannelProperty::FlagSemiPermanent, value ? 1 : 0);
}
/*!
* Channel is the default channel.
* There can only be one default channel per server.
* New users who did not configure a channel to join on login in ts3client_startConnection will automatically join the default channel.
*/
bool Channel::isDefault() const
{
return d->getInt(this, ChannelProperty::FlagDefault) != 0;
}
void Channel::setDefault(bool value)
{
d->setInt(this, ChannelProperty::FlagDefault, value ? 1 : 0);
}
/*!
* If set, channel is password protected.
* The password itself is stored in ChannelPassword
*/
bool Channel::isPasswordProtected() const
{
return d->getInt(this, ChannelProperty::FlagPassword) != 0;
}
/*!
* Latency of this channel.
* Allows to increase the packet size resulting in less bandwidth usage at the cost of higher latency.
* A value of 1 (default) is the best setting for lowest latency and best quality.
* If bandwidth or network quality are restricted, increasing the latency factor can help stabilize the connection.
* Higher latency values are only possible for low-quality codec and codec quality settings.
*/
int Channel::codecLatencyFactor() const
{
return d->getInt(this, ChannelProperty::CodecLatencyFactor);
}
void Channel::setCodecLatencyFactor(int value)
{
d->setInt(this, ChannelProperty::CodecLatencyFactor, value);
}
/*!
* If true, this channel is not using encrypted voice data.
* If false, voice data is encrypted for this channel.
* Note that channel voice data encryption can be globally disabled or enabled for the virtual server.
* Changing this flag makes only sense if global voice data encryption is set to be configured per channel.
*/
bool Channel::codecIsUnencrypted() const
{
return d->getInt(this, ChannelProperty::CodecIsUnencrypted) != 0;
}
void Channel::setCodecIsUnencrypted(bool value)
{
d->setInt(this, ChannelProperty::CodecIsUnencrypted, value ? 1 : 0);
}
time::seconds Channel::deleteDelay() const
{
const auto time = d->getInt(this, ChannelProperty::DeleteDelay);
return time::seconds(time);
}
void Channel::setDeleteDelay(const time::seconds& value)
{
d->setInt(this, ChannelProperty::DeleteDelay, int(value.count()));
}
time::seconds Channel::channelEmptyTime() const
{
const auto time = api().getChannelEmptySecs(this);
return time::seconds(time);
}
/*!
* Uploads a local file to the server
* \a "file" Path of the local file, which is to be uploaded.
* \a "overwrite" when false, upload will abort if remote file exists
* \a "resume" If we have a previously halted transfer: true = resume, false = restart transfer
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous upload operation.
*/
void Channel::sendFile(const FileTransferOption& option)
{
api().sendFile(
this,
option.password,
option.file.fileName(),
option.overwrite,
option.resume,
option.file.dir().path(),
TODO_RETURN_CODE
);
}
/*!
* Download a file from the server.
* \a "fileName" Filename of the remote file, which is to be downloaded.
* \a "destinationDirectory" Local target directory name where the download file should be saved.
* \a "overwrite" when false, download will abort if local file exists
* \a "resume" If we have a previously halted transfer: true = resume, false = restart transfer
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* \a "cancellationToken" The token to monitor for cancellation requests. The default value is \sa "CancellationToken.None"
* Returns \c A task that represents the asynchronous download operation.
*/
void Channel::requestFile(const FileTransferOption& option)
{
api().requestFile(
this,
option.password,
option.file.fileName(),
option.overwrite,
option.resume,
option.file.dir().path(),
TODO_RETURN_CODE
);
}
/*!
* Query list of files in a directory.
* \a "path" Path inside the channel, defining the subdirectory. Top level path is ??
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that returns the list of files contained in path
*/
void Channel::getFileList(const QString& path, const QString& channelPassword)
{
api().requestFileList(this, channelPassword, path, TODO_RETURN_CODE);
}
/*!
* Query information of a specified file. The answer from the server will trigger \sa "Connection.FileInfoReceived" with the requested information.
* \a "file" File name we want to request info from, needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::getFileInfo(const QString& file, const QString& channelPassword)
{
api().requestFileInfo(this, channelPassword, file, TODO_RETURN_CODE);
}
/*!
* Create a directory.
* \a path Name of the directory to create. The directory name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a password Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::mkdir(const QString& path, const QString& password)
{
api().requestCreateDirectory(this, password, path, TODO_RETURN_CODE);
}
/*!
* Moves or renames a file. If the source and target channels and paths are the same, the file will simply be renamed.
* \a "file" Old name of the file. The file name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* \a "toFile" New name of the file. The new name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "toChannel" Target channel, to which we want to move the file.
* \a "toChannelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::moveFile(const QString& file, const QString& toFile, const QString& channelPassword, const Channel* toChannel, const QString& toChannelPassword)
{
api().requestRenameFile(
this,
channelPassword,
toChannel ? toChannel : this,
toChannelPassword,
file,
toFile,
TODO_RETURN_CODE
);
}
/*!
* Delete one or more remote files on the server.
* \a "files" List of files we request to be deleted. The file names need to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory.
* \a "channelPassword" Optional channel password. Pass empty string or null if unused.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::deleteFile(const QStringList& files, const QString& channelPassword)
{
api().requestDeleteFile(this, channelPassword, files, TODO_RETURN_CODE);
}
/*!
* Request updating the channel description
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::getChannelDescription() const
{
api().requestChannelDescription(this, TODO_RETURN_CODE);
}
/*!
* Removes the channel from the server
* \a "force" If true, the channel will be deleted even when it is not empty.
* Clients within the deleted channel are transfered to the default channel.
* Any contained subchannels are removed as well.
* If \c false, the server will refuse to delete a channel that is not empty.
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::remove(bool force)
{
api().requestChannelDelete(this, force, TODO_RETURN_CODE);
}
/*!
* Send a text message to the channel
* \a "message" The text message
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::sendTextMessage(const QString& message)
{
api().requestSendChannelTextMsg(this, message, TODO_RETURN_CODE);
}
/*!
* Move the channel to a new parent channel
* \a "newParent" The parent channel where the moved channel is to be inserted as child. Use null to insert as top-level channel.
* \a "newChannelOrder" the \sa "Channel" after which <see langword="this" \sa "Channel" is sorted. <see langword="null" meaning its going to be the first \sa "Channel" under <paramref name="newParent".
* Returns \c A task that represents the asynchronous operation.
*/
void Channel::moveTo(Channel* newParent, Channel* newChannelOrder)
{
if (utils::has_null(newParent))
return;
if (!utils::is_same_server(connection(), newParent, newChannelOrder))
return;
api().requestChannelMove(this, newParent, newChannelOrder, TODO_RETURN_CODE);
}
void Channel::flushUpdates()
{
d->flushChannelUpdates(this);
}
void Channel::refreshProperties(bool wait)
{
}
} // namespace TeamSpeakSdk
| 28.010811 | 206 | 0.714782 | faming-wang |
a82e009eff96960c9c4b4c3c9dc07c64513b00b1 | 3,165 | hpp | C++ | Source/Core/Common/SimMatrix4.hpp | andraantariksa/PlasmaEngine | 481ea008ed15b531476533a6f675bc9bfdfa7db2 | [
"MIT"
] | 70 | 2020-10-19T15:17:36.000Z | 2022-03-29T06:23:20.000Z | Source/Core/Common/SimMatrix4.hpp | andraantariksa/PlasmaEngine | 481ea008ed15b531476533a6f675bc9bfdfa7db2 | [
"MIT"
] | 90 | 2020-10-21T09:56:03.000Z | 2022-02-19T18:36:37.000Z | Source/Core/Common/SimMatrix4.hpp | andraantariksa/PlasmaEngine | 481ea008ed15b531476533a6f675bc9bfdfa7db2 | [
"MIT"
] | 13 | 2020-12-28T20:18:57.000Z | 2022-01-20T08:43:29.000Z | // MIT Licensed (see LICENSE.md).
#pragma once
namespace Math
{
namespace Simd
{
// loading
SimMat4 LoadMat4x4(const scalar vals[16]);
SimMat4 SetMat4x4(scalar m00,
scalar m01,
scalar m02,
scalar m03,
scalar m10,
scalar m11,
scalar m12,
scalar m13,
scalar m20,
scalar m21,
scalar m22,
scalar m23,
scalar m30,
scalar m31,
scalar m32,
scalar m33);
SimMat4 UnAlignedLoadMat4x4(const scalar vals[16]);
// storing
void StoreMat4x4(scalar vals[16], SimMat4Param mat);
void UnAlignedStoreMat4x4(scalar vals[16], SimMat4Param mat);
// default matrix sets
SimMat4 ZeroOutMat4x4();
SimMat4 IdentityMat4x4();
// basis elements
SimVec BasisX(SimMat4Param mat);
SimVec BasisY(SimMat4Param mat);
SimVec BasisZ(SimMat4Param mat);
SimVec BasisW(SimMat4Param mat);
SimMat4 SetBasisX(SimMat4Param mat, SimVecParam value);
SimMat4 SetBasisY(SimMat4Param mat, SimVecParam value);
SimMat4 SetBasisZ(SimMat4Param mat, SimVecParam value);
SimMat4 SetBasisW(SimMat4Param mat, SimVecParam value);
// basic arithmetic
SimMat4 Add(SimMat4Param lhs, SimMat4Param rhs);
SimMat4 Subtract(SimMat4Param lhs, SimMat4Param rhs);
SimMat4 Multiply(SimMat4Param lhs, SimMat4Param rhs);
SimMat4 Scale(SimMat4Param mat, scalar scale);
SimMat4 ComponentScale(SimMat4Param lhs, SimMat4Param rhs);
SimMat4 ComponentDivide(SimMat4Param lhs, SimMat4Param rhs);
// matrix vector arithmetic
SimVec TransformPoint(SimMat4Param mat, SimVecParam vec);
SimVec TransposeTransformPoint(SimMat4Param mat, SimVecParam vec);
SimVec TransformNormal(SimMat4Param mat, SimVecParam vec);
SimVec TransposeTransformNormal(SimMat4Param mat, SimVecParam vec);
SimVec TransformPointProjected(SimMat4Param mat, SimVecParam vec);
// transform building
SimMat4 BuildScale(SimVecParam scale);
SimMat4 BuildRotation(SimVecParam axis, scalar angle);
SimMat4 BuildRotation(SimVecParam quat);
SimMat4 BuildTranslation(SimVecParam translation);
SimMat4 BuildTransform(SimVecParam translation, SimVecParam axis, scalar angle, SimVecParam scale);
SimMat4 BuildTransform(SimVecParam translation, SimVecParam quat, SimVecParam scale);
SimMat4 BuildTransform(SimVecParam translation, SimMat4Param rot, SimVecParam scale);
// transposes the upper 3x3 of the 4x4 and leaves the remaining elements alone
SimMat4 TransposeUpper3x3(SimMat4Param mat);
SimMat4 Transpose4x4(SimMat4Param mat);
SimMat4 AffineInverse4x4(SimMat4Param transform);
SimMat4 AffineInverseWithScale4x4(SimMat4Param transform);
// basic logic
SimMat4 Equal(SimMat4Param mat1, SimMat4Param mat2);
// arithmetic operators
SimMat4 operator+(SimMat4Param lhs, SimMat4Param rhs);
SimMat4 operator-(SimMat4Param lhs, SimMat4Param rhs);
SimMat4 operator*(SimMat4Param lhs, SimMat4Param rhs);
// vector with scalar arithmetic operators
SimMat4 operator*(SimMat4Param lhs, scalar rhs);
SimMat4 operator/(SimMat4Param lhs, scalar rhs);
} // namespace Simd
} // namespace Math
#include "Math/SimMatrix4.inl"
| 35.965909 | 99 | 0.747235 | andraantariksa |
a8311a4c4cfe6fae6f6f99cf742aabb34308bc4b | 14,601 | cpp | C++ | source/Articles/Serialization/serialization_demo.cpp | rioscode/DataDrivenRendering | b200c10e44e84c6d50355dfc0dd0f592752a47c7 | [
"Zlib"
] | 164 | 2019-06-30T18:14:38.000Z | 2022-03-13T14:36:10.000Z | source/Articles/Serialization/serialization_demo.cpp | rioscode/DataDrivenRendering | b200c10e44e84c6d50355dfc0dd0f592752a47c7 | [
"Zlib"
] | null | null | null | source/Articles/Serialization/serialization_demo.cpp | rioscode/DataDrivenRendering | b200c10e44e84c6d50355dfc0dd0f592752a47c7 | [
"Zlib"
] | 11 | 2019-09-11T13:40:59.000Z | 2022-01-28T09:24:24.000Z |
#include "serialization_demo.hpp"
#include "serialization_examples.hpp"
#include "blob.hpp"
#include <iostream>
#include <stdint.h>
#include <stdarg.h>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
// Allocator //////////////////////////////////////////////////////////////
void* Allocator::allocate( sizet size, sizet alignment ) {
return malloc( size );
}
void* Allocator::allocate( sizet size, sizet alignment, cstring file, i32 line ) {
return malloc( size );
}
void Allocator::deallocate( void* pointer ) {
free( pointer );
}
// Log ////////////////////////////////////////////////////////////////////
static constexpr u32 k_string_buffer_size = 1024 * 1024;
static char log_buffer[ k_string_buffer_size ];
static void output_console( char* log_buffer_ ) {
printf( "%s", log_buffer_ );
}
static void output_visual_studio( char* log_buffer_ ) {
OutputDebugStringA( log_buffer_ );
}
void hprint( cstring format, ... ) {
va_list args;
va_start( args, format );
vsnprintf_s( log_buffer, k_string_buffer_size, format, args );
log_buffer[ k_string_buffer_size - 1 ] = '\0';
va_end( args );
output_console( log_buffer );
#if defined(_MSC_VER)
output_visual_studio( log_buffer );
#endif // _MSC_VER
}
// CharArray //////////////////////////////////////////////////////////////
void CharArray::init( Allocator* allocator_, cstring string ) {
size = ( u32 )( strlen( string ) + 1 );
capacity = size;
allocator = allocator_;
data = ( char* )halloca( size, allocator );
strcpy( data, string );
}
// File ///////////////////////////////////////////////////////////////////
static long file_get_size( FILE* f ) {
long fileSizeSigned;
fseek( f, 0, SEEK_END );
fileSizeSigned = ftell( f );
fseek( f, 0, SEEK_SET );
return fileSizeSigned;
}
char* file_read_binary( cstring filename, Allocator* allocator, sizet* size ) {
char* out_data = 0;
FILE* file = fopen( filename, "rb" );
if ( file ) {
// TODO: Use filesize or read result ?
sizet filesize = file_get_size( file );
out_data = ( char* )halloca( filesize + 1, allocator );
fread( out_data, filesize, 1, file );
out_data[ filesize ] = 0;
if ( size )
*size = filesize;
fclose( file );
}
return out_data;
}
char* file_read_text( cstring filename, Allocator* allocator, sizet* size ) {
char* text = 0;
FILE* file = fopen( filename, "r" );
if ( file ) {
sizet filesize = file_get_size( file );
text = ( char* )halloca( filesize + 1, allocator );
// Correct: use elementcount as filesize, bytes_read becomes the actual bytes read
// AFTER the end of line conversion for Windows (it uses \r\n).
sizet bytes_read = fread( text, 1, filesize, file );
text[ bytes_read ] = 0;
if ( size )
*size = filesize;
fclose( file );
}
return text;
}
void file_write_binary( cstring filename, void* memory, sizet size ) {
FILE* file = fopen( filename, "wb" );
fwrite( memory, size, 1, file );
fclose( file );
}
// Vec2s //////////////////////////////////////////////////////////////////
// Forward declaration for template specialization.
template<>
void BlobSerializer::serialize<vec2s>( vec2s* data );
// Serialization binary
template<>
void BlobSerializer::serialize<vec2s>( vec2s* data ) {
serialize( &data->x );
serialize( &data->y );
}
// OtherData //////////////////////////////////////////////////////////////
// Data structure added just to have a pointer to test.
//
struct OtherData {
f32 a;
u32 b;
};
template<>
void BlobSerializer::serialize<OtherData>( OtherData* data ) {
serialize( &data->a );
serialize( &data->b );
}
// GameDataV0 /////////////////////////////////////////////////////////////
//
// First version of the game data.
// Used to write older binaries and test versioning.
struct GameDataV0 : public Blob {
vec2s position;
RelativeArray<u32> all_effs;
OtherData other;
RelativeString name;
RelativePointer<OtherData> other_pointer;
static constexpr u32 k_version = 0;
}; // struct GameDataV0
template<>
void BlobSerializer::serialize<GameDataV0>( GameDataV0* data ) {
serialize( &data->position );
serialize( &data->all_effs );
serialize( &data->other );
serialize( &data->name );
serialize( &data->other_pointer );
}
//
// Second version of game data.
//
struct GameDataV1 : public Blob {
vec2s position;
RelativeArray<u32> all_effs;
OtherData other;
RelativeArray<u32> all_cs; // Added in V1
RelativeString name;
RelativePointer<OtherData> other_pointer;
static constexpr u32 k_version = 1;
}; // struct GameDataV1
template<>
void BlobSerializer::serialize<GameDataV1>( GameDataV1* data ) {
serialize( &data->position );
serialize( &data->all_effs );
serialize( &data->other );
if ( serializer_version > 0 ) {
serialize( &data->all_cs );
}
serialize( &data->name );
serialize( &data->other_pointer );
}
//
//
struct GameData : public Blob {
vec2s position;
RelativeArray<u32> all_effs;
OtherData other;
RelativeArray<u32> all_cs; // Added in V1
Array<u32> all_as; // Added in V2
CharArray new_name; // Added in V2
RelativeString name;
RelativePointer<OtherData> other_pointer;
static constexpr u32 k_version = 2;
}; // struct GameData
template<>
void BlobSerializer::serialize<GameData>( GameData* data ) {
serialize( &data->position );
serialize( &data->all_effs );
serialize( &data->other );
if ( serializer_version > 0 ) {
serialize( &data->all_cs );
}
else {
data->all_cs.set_empty();
}
if ( serializer_version > 1 ) {
serialize( &data->all_as );
serialize( &data->new_name );
}
else {
}
serialize( &data->name );
serialize( &data->other_pointer );
}
static Allocator s_heap_allocator;
int main() {
hprint( "Serialization demo\n" );
Allocator* allocator = &s_heap_allocator;
// 1. Resource Compilation and Inspection /////////////////////////////
compile_cutscene( allocator, "..//data//articles//serializationdemo//cutscene.json", "..//data//bin//cutscene.bin" );
inspect_cutscene( allocator, "..//data//bin//cutscene.bin" );
compile_scene( allocator, "..//data//articles//serializationdemo//new_game.json", "..//data//bin//new_game.bin" );
inspect_scene( allocator, "..//data//bin//new_game.bin" );
// 2. Write GameDataV0 binary
BlobSerializer write_blob_v0, read_blob_v0;
{
// NOTE: this is a non-optimal way of writing the blob, but still doable.
// Write V0 and read with GameData (V2)
char* memory = (char*)malloc( 1000 );
memset( memory, 0, 1000 );
GameDataV0* writing_data = ( GameDataV0* )memory;
writing_data->position = { 100,200 };
writing_data->other.a = 7.0f;
writing_data->other.b = 0xffff;
u32* effs = ( u32* )( memory + sizeof( GameDataV0 ) );
*effs = 0xffffffff;
char* name_memory = ( char* )( effs + 1 );
strcpy( name_memory, "IncredibleName" );
OtherData* other_pointer = ( OtherData* )( name_memory + strlen( name_memory ) + 1 );
other_pointer->a = 16.f;
other_pointer->b = 0xaaaaaaaa;
// Close to the allocate_and_set method used in blobs.
// Calculate the offset for the arrays
writing_data->all_effs.set( ( char* )effs, 1 );
writing_data->name.set( name_memory, strlen( name_memory ) );
// Calculate the offset for the pointer
writing_data->other_pointer.set( ( char* )other_pointer );
// Write to blob using serialization methods, by passing the writing data.
write_blob_v0.write_and_serialize( allocator, 0, 1000, writing_data );
//
GameData* game_data = read_blob_v0.read<GameData>( allocator, GameData::k_version, write_blob_v0.blob_memory, write_blob_v0.allocated_offset * 2 );
if ( game_data ) {
OtherData* other_data = game_data->other_pointer.get();
hy_assert( game_data->position.x == 100.f );
hy_assert( other_data->a == 16.f );
hy_assert( other_data->b == 0xaaaaaaaa );
hy_assert( strcmp( game_data->name.c_str(), "IncredibleName" ) == 0 );
hy_assert( game_data->all_effs[ 0 ] == 0xffffffff );
hprint( "V0 Read Done %s!\n", game_data->name.c_str() );
}
}
// Write GameDataV1 binary
BlobSerializer write_blob_v1, read_blob_v1;
{
// Use write blob to already fill the data.
// Allocate just a blob with 200 bytes
GameDataV1* game_data_v1 = write_blob_v1.write_and_prepare<GameDataV1>( allocator, 1, 200 );
game_data_v1->position.x = 700.f;
game_data_v1->position.y = 42.f;
u32 all_effs[] = { 0xffffffff, 0xffffffff };
write_blob_v1.allocate_and_set( game_data_v1->all_effs, 2, all_effs );
// other
game_data_v1->other.a = 8.f;
game_data_v1->other.b = 0xbbbbbbbb;
// all c
u32 all_cs[] = { 0xcccccccc, 0xcccccccc, 0xcccccccc };
write_blob_v1.allocate_and_set( game_data_v1->all_cs, 3, all_cs );
// name
cstring name_string = "GameDataV1Awesomeness";
write_blob_v1.allocate_and_set( game_data_v1->name, "%s", name_string );
// other pointer
write_blob_v1.allocate_and_set( game_data_v1->other_pointer, nullptr );
OtherData* other_data_pointed = game_data_v1->other_pointer.get();
other_data_pointed->a = 32.f;
other_data_pointed->b = 0xdddddddd;
// Read V1 blob, again with the v2 serializer.
GameData* game_data = read_blob_v1.read<GameData>( allocator, GameData::k_version, write_blob_v1.blob_memory, write_blob_v1.allocated_offset * 2 );
if ( game_data ) {
OtherData* other_data = game_data->other_pointer.get();
hy_assert( game_data->position.x == 700.f );
hy_assert( game_data->other.a == 8.f );
hy_assert( game_data->other.b == 0xbbbbbbbb );
hy_assert( other_data->a == 32.f );
hy_assert( other_data->b == 0xdddddddd );
hy_assert( strcmp( game_data->name.c_str(), "GameDataV1Awesomeness" ) == 0 );
hy_assert( game_data->all_effs[ 1 ] == 0xffffffff );
hy_assert( game_data->other_pointer->a == 32.f );
hprint( "V1 Read Done %s!\n", game_data->name.c_str() );
}
}
// Write GameDataV2 binary
BlobSerializer write_blob_v2, read_blob_v2, read_blob_v2_serialized;
{
GameData* game_data = write_blob_v2.write_and_prepare<GameData>( allocator, GameData::k_version, 300 );
game_data->position.x = 700.f;
game_data->position.y = 42.f;
u32 all_effs[] = { 0xffffffff, 0xffffffff };
write_blob_v2.allocate_and_set( game_data->all_effs, 2, all_effs );
// other
game_data->other.a = 8.f;
game_data->other.b = 0xbbbbbbbb;
// all c
u32 all_cs[] = { 0xcccccccc, 0xcccccccc, 0xcccccccc };
write_blob_v2.allocate_and_set( game_data->all_cs, 3, all_cs );
// all as
u32 all_as[] = { 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa };
write_blob_v2.allocate_and_set( game_data->all_as, 4, all_as );
// new name
cstring new_name_string = "GameDataV2Plus";
write_blob_v2.allocate_and_set( game_data->new_name, new_name_string );
// name
cstring name_string = "GameDataV2Awesomeness";
write_blob_v2.allocate_and_set( game_data->name, "%s", name_string );
// other pointer
write_blob_v2.allocate_and_set( game_data->other_pointer, nullptr );
OtherData* other_data_pointed = game_data->other_pointer.get();
other_data_pointed->a = 32.f;
other_data_pointed->b = 0xdddddddd;
// Read V2 blob. This is MEMORY MAPPED.
GameData* mmap_game_data = read_blob_v2.read<GameData>( allocator, GameData::k_version, write_blob_v2.blob_memory, write_blob_v2.allocated_offset * 2 );
// Force serialization of game data and test fields.
GameData* serialized_game_data = read_blob_v2_serialized.read<GameData>( allocator, GameData::k_version, write_blob_v2.blob_memory, write_blob_v2.allocated_offset * 2, true );
if ( mmap_game_data && serialized_game_data ) {
OtherData* mmap_other_data = mmap_game_data->other_pointer.get();
OtherData* serialized_other_data = serialized_game_data->other_pointer.get();
hy_assert( mmap_game_data->position.x == serialized_game_data->position.x );
hy_assert( mmap_game_data->position.x == 700.f );
hy_assert( mmap_other_data->a == serialized_other_data->a );
hy_assert( mmap_other_data->a == 32.f );
hy_assert( mmap_other_data->b == serialized_other_data->b );
hy_assert( mmap_other_data->b == 0xdddddddd );
hy_assert( strcmp( mmap_game_data->name.c_str(), serialized_game_data->name.c_str() ) == 0 );
hy_assert( mmap_game_data->all_effs[ 1 ] == serialized_game_data->all_effs[ 1 ] );
hy_assert( mmap_game_data->all_effs[ 1 ] == 0xffffffff );
hy_assert( mmap_game_data->other_pointer->a == serialized_game_data->other_pointer->a );
hy_assert( mmap_game_data->all_as.get()[3] == serialized_game_data->all_as[ 3 ] );
hy_assert( serialized_game_data->all_as[ 3 ] == 0xaaaaaaaa );
hy_assert( serialized_game_data->all_as[ 0 ] == 0xaaaaaaaa );
hy_assert( mmap_game_data->all_as.get()[ 3 ] == 0xaaaaaaaa );
hy_assert( mmap_game_data->all_as.get()[ 0 ] == 0xaaaaaaaa );
cstring aa0 = mmap_game_data->new_name.get();
hy_assert( strcmp( mmap_game_data->new_name.get(), "GameDataV2Plus" ) == 0 );
cstring aa1 = serialized_game_data->new_name.c_str();
hy_assert( strcmp( serialized_game_data->new_name.c_str(), "GameDataV2Plus" ) == 0 );
hprint( "V2 Read Done %s!\n", mmap_game_data->name.c_str() );
}
}
hprint( "Test finished SUCCESSFULLY!\n" );
}
| 35.183133 | 183 | 0.606465 | rioscode |
a831a4a671483363466c72a4efb8812d5d95a62b | 23,938 | cpp | C++ | lib/Common/Common/Tick.cpp | satheeshravi/ChakraCore | 3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5 | [
"MIT"
] | 1 | 2021-11-07T18:56:21.000Z | 2021-11-07T18:56:21.000Z | lib/Common/Common/Tick.cpp | MaxMood96/ChakraCore | 9d9fea268ce1ae6c00873fd966a6a2be048f3455 | [
"MIT"
] | null | null | null | lib/Common/Common/Tick.cpp | MaxMood96/ChakraCore | 9d9fea268ce1ae6c00873fd966a6a2be048f3455 | [
"MIT"
] | 1 | 2021-09-04T23:26:57.000Z | 2021-09-04T23:26:57.000Z | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "CommonCommonPch.h"
#include "Common/Tick.h"
namespace Js {
uint64 Tick::s_luFreq;
uint64 Tick::s_luBegin;
#if DBG
uint64 Tick::s_DEBUG_luStart = 0;
uint64 Tick::s_DEBUG_luSkip = 0;
#endif
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// struct Tick
///
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// Tick::Tick
///
/// Tick() initializes a new Tick instance to an "empty" time. This instance
/// must be assigned to another Tick instance or Now() to have value.
///
///----------------------------------------------------------------------------
Tick::Tick()
{
m_luTick = 0;
}
///----------------------------------------------------------------------------
///
/// Tick::Tick
///
/// Tick() initializes a new Tick instance to a specific time, in native
/// time units.
///
///----------------------------------------------------------------------------
Tick::Tick(
uint64 luTick) // Tick, in internal units
{
m_luTick = luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::FromMicroseconds
///
/// FromMicroseconds() returns a Tick instance from a given time in
/// microseconds.
///
///----------------------------------------------------------------------------
Tick
Tick::FromMicroseconds(
uint64 luTime) // Time, in microseconds
{
//
// Ensure we can convert losslessly.
//
#if DBG
const uint64 luMaxTick = _UI64_MAX / s_luFreq;
AssertMsg(luTime <= luMaxTick, "Ensure time can be converted losslessly");
#endif // DBG
//
// Create the Tick
//
uint64 luTick = luTime * s_luFreq / ((uint64) 1000000);
return Tick(luTick);
}
///----------------------------------------------------------------------------
///
/// Tick::FromQPC
///
/// FromQPC() returns a Tick instance from a given QPC time.
///
///----------------------------------------------------------------------------
Tick
Tick::FromQPC(
uint64 luTime) // Time, in QPC units
{
return Tick(luTime - s_luBegin);
}
///----------------------------------------------------------------------------
///
/// Tick::ToQPC
///
/// ToQPC() returns the QPC time for this time instance
///
///----------------------------------------------------------------------------
uint64
Tick::ToQPC()
{
return (m_luTick + s_luBegin);
}
///----------------------------------------------------------------------------
///
/// Tick::operator +
///
/// operator +()
///
///----------------------------------------------------------------------------
Tick
Tick::operator +(
TickDelta tdChange // RHS TickDelta
) const
{
return Tick(m_luTick + tdChange.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// Tick::operator -
///
/// operator -()
///
///----------------------------------------------------------------------------
Tick
Tick::operator -(
TickDelta tdChange // RHS TickDelta
) const
{
return Tick(m_luTick - tdChange.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// Tick::operator -
///
/// operator -()
///
///----------------------------------------------------------------------------
TickDelta
Tick::operator -(
Tick timeOther // RHS Tick
) const
{
return TickDelta(m_luTick - timeOther.m_luTick);
}
///----------------------------------------------------------------------------
///
/// Tick::operator ==
///
/// operator ==()
///
///----------------------------------------------------------------------------
bool
Tick::operator ==(
Tick timeOther // RHS Tick
) const
{
return m_luTick == timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator !=
///
/// operator !=()
///
///----------------------------------------------------------------------------
bool
Tick::operator !=(
Tick timeOther // RHS Tick
) const
{
return m_luTick != timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator <
///
/// operator <()
///
///----------------------------------------------------------------------------
bool
Tick::operator <(
Tick timeOther // RHS Tick
) const
{
return m_luTick < timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator <=
///
/// operator <=()
///
///----------------------------------------------------------------------------
bool
Tick::operator <=(
Tick timeOther // RHS Tick
) const
{
return m_luTick <= timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator >
///
/// operator >()
///
///----------------------------------------------------------------------------
bool
Tick::operator >(
Tick timeOther // RHS Tick
) const
{
return m_luTick > timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///
/// Tick::operator >=
///
/// operator >=()
///
///----------------------------------------------------------------------------
bool
Tick::operator >=(
Tick timeOther // RHS Tick
) const
{
return m_luTick >= timeOther.m_luTick;
}
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// struct TickDelta
///
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///----------------------------------------------------------------------------
///
/// TickDelta::TickDelta
///
/// TickDelta() initializes a new TickDelta instance to "zero" delta.
///
///----------------------------------------------------------------------------
TickDelta::TickDelta()
{
m_lnDelta = 0;
}
///----------------------------------------------------------------------------
///
/// TickDelta::TickDelta
///
/// TickDelta() initializes a new TickDelta instance to a specific time delta,
/// in native time units.
///
///----------------------------------------------------------------------------
TickDelta::TickDelta(
int64 lnDelta)
{
m_lnDelta = lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::ToMicroseconds
///
/// ToMicroseconds() returns the time delta, in microseconds. The time is
/// rounded to the nearest available whole units.
///
///----------------------------------------------------------------------------
int64
TickDelta::ToMicroseconds() const
{
if (*this == Infinite())
{
return _I64_MAX;
}
//
// Ensure we can convert losslessly.
//
const int64 lnMinTimeDelta = _I64_MIN / ((int64) 1000000);
const int64 lnMaxTimeDelta = _I64_MAX / ((int64) 1000000);
AssertMsg((m_lnDelta <= lnMaxTimeDelta) && (m_lnDelta >= lnMinTimeDelta),
"Ensure delta can be converted to microseconds losslessly");
//
// Compute the microseconds.
//
int64 lnFreq = (int64) Tick::s_luFreq;
int64 lnTickDelta = (m_lnDelta * ((int64) 1000000)) / lnFreq;
return lnTickDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::FromMicroseconds
///
/// FromMicroseconds() returns a TickDelta instance from a given delta in
/// microseconds.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::FromMicroseconds(
int64 lnTimeDelta) // Time delta, in 1/1000^2 sec
{
AssertMsg(lnTimeDelta != _I64_MAX, "Use Infinite() to create an infinite TickDelta");
//
// Ensure that we can convert losslessly.
//
int64 lnFreq = (int64) Tick::s_luFreq;
#if DBG
const int64 lnMinTimeDelta = _I64_MIN / lnFreq;
const int64 lnMaxTimeDelta = _I64_MAX / lnFreq;
AssertMsg((lnTimeDelta <= lnMaxTimeDelta) && (lnTimeDelta >= lnMinTimeDelta),
"Ensure delta can be converted to native format losslessly");
#endif // DBG
//
// Create the TickDelta
//
int64 lnTickDelta = (lnTimeDelta * lnFreq) / ((int64) 1000000);
TickDelta td(lnTickDelta);
AssertMsg(td != Infinite(), "Can not create infinite TickDelta");
return td;
}
///----------------------------------------------------------------------------
///
/// TickDelta::FromMicroseconds
///
/// FromMicroseconds() returns a TickDelta instance from a given delta in
/// microseconds.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::FromMicroseconds(
int nTimeDelta) // Tick delta, in 1/1000^2 sec
{
AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta");
return FromMicroseconds((int64) nTimeDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::FromMilliseconds
///
/// FromMilliseconds() returns a TickDelta instance from a given delta in
/// milliseconds.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::FromMilliseconds(
int nTimeDelta) // Tick delta, in 1/1000^1 sec
{
AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta");
return FromMicroseconds(((int64) nTimeDelta) * ((int64) 1000));
}
///----------------------------------------------------------------------------
///
/// TickDelta::Infinite
///
/// Infinite() returns a time-delta infinitely far away.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::Infinite()
{
return TickDelta(_I64_MAX);
}
///----------------------------------------------------------------------------
///
/// TickDelta::IsForward
///
/// IsForward() returns whether adding this TickDelta to a given Tick will
/// not move the time backwards.
///
///----------------------------------------------------------------------------
bool
TickDelta::IsForward() const
{
return m_lnDelta >= 0;
}
///----------------------------------------------------------------------------
///
/// TickDelta::IsBackward
///
/// IsBackward() returns whether adding this TickDelta to a given Tick will
/// not move the time forwards.
///
///----------------------------------------------------------------------------
bool
TickDelta::IsBackward() const
{
return m_lnDelta <= 0;
}
///----------------------------------------------------------------------------
///
/// TickDelta::Abs
///
/// Abs() returns the absolute value of the TickDelta.
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::Abs(TickDelta tdOther)
{
return TickDelta(tdOther.m_lnDelta < 0 ? -tdOther.m_lnDelta : tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator %
///
/// operator %()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator %(
TickDelta tdOther // RHS TickDelta
) const
{
return TickDelta(m_lnDelta % tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator \
///
/// operator \() - Divides one TickDelta by another, in TickDelta units
///
///----------------------------------------------------------------------------
int64
TickDelta::operator /(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta / tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator +
///
/// operator +()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator +(
TickDelta tdOther // RHS TickDelta
) const
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
return TickDelta(m_lnDelta + tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator -
///
/// operator -()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator -(
TickDelta tdOther // RHS TickDelta
) const
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
return TickDelta(m_lnDelta - tdOther.m_lnDelta);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator *
///
/// operator *()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator *(
int nScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
return TickDelta(m_lnDelta * nScale);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator *
///
/// operator *()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator *(
float flScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
return TickDelta((int64) (((double) m_lnDelta) * ((double) flScale)));
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator /
///
/// operator /()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator /(
int nScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
AssertMsg(nScale != 0, "Can not scale by 0");
return TickDelta(m_lnDelta / nScale);
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator /
///
/// operator /()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator /(
float flScale // RHS scale
) const
{
AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
AssertMsg(flScale != 0, "Can not scale by 0");
return TickDelta((int64) (((double) m_lnDelta) / ((double) flScale)));
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator +=
///
/// operator +=()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator +=(
TickDelta tdOther) // RHS TickDelta
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
m_lnDelta = m_lnDelta + tdOther.m_lnDelta;
return *this;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator -=
///
/// operator -=()
///
///----------------------------------------------------------------------------
TickDelta
TickDelta::operator -=(
TickDelta tdOther) // RHS TickDelta
{
AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
"Can not combine infinite TickDeltas");
m_lnDelta = m_lnDelta - tdOther.m_lnDelta;
return *this;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator ==
///
/// operator ==()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator ==(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta == tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator !=
///
/// operator !=()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator !=(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta != tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator <
///
/// operator <()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator <(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta < tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator <=
///
/// operator <=()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator <=(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta <= tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator >
///
/// operator >()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator >(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta > tdOther.m_lnDelta;
}
///----------------------------------------------------------------------------
///
/// TickDelta::operator >=
///
/// operator >=()
///
///----------------------------------------------------------------------------
bool
TickDelta::operator >=(
TickDelta tdOther // RHS TickDelta
) const
{
return m_lnDelta >= tdOther.m_lnDelta;
}
void Tick::InitType()
{
/* CheckWin32( */ QueryPerformanceFrequency((LARGE_INTEGER *) &s_luFreq);
/* CheckWin32( */ QueryPerformanceCounter((LARGE_INTEGER *) &s_luBegin);
#if DBG
s_luBegin += s_DEBUG_luStart;
#endif
//
// Ensure that we have a sufficient amount of time so that we can handle useful time operations.
//
uint64 nSec = _UI64_MAX / s_luFreq;
if (nSec < 5 * 60)
{
#if FIXTHIS
PromptInvalid("QueryPerformanceFrequency() will not provide at least 5 minutes");
return Results::GenericFailure;
#endif
}
}
Tick Tick::Now()
{
// Determine our current time
uint64 luCurrent = s_luBegin;
/* Verify( */ QueryPerformanceCounter((LARGE_INTEGER *) &luCurrent);
#if DBG
luCurrent += s_DEBUG_luStart + s_DEBUG_luSkip;
#endif
// Create a Tick instance, using our delta since we started tracking time.
uint64 luDelta = luCurrent - s_luBegin;
return Tick(luDelta);
}
uint64 Tick::ToMicroseconds() const
{
//
// Convert time in microseconds (1 / 1000^2). Because of the finite precision and wrap-around,
// this math depends on where the Tick is.
//
const uint64 luOneSecUs = (uint64) 1000000;
const uint64 luSafeTick = _UI64_MAX / luOneSecUs;
if (m_luTick < luSafeTick)
{
//
// Small enough to convert directly into microseconds.
//
uint64 luTick = (m_luTick * luOneSecUs) / s_luFreq;
return luTick;
}
else
{
//
// Number is too large, so we need to do this is stages.
// 1. Compute the number of seconds
// 2. Convert the remainder
// 3. Add the two parts together
//
uint64 luSec = m_luTick / s_luFreq;
uint64 luRemain = m_luTick - luSec * s_luFreq;
uint64 luTick = (luRemain * luOneSecUs) / s_luFreq;
luTick += luSec * luOneSecUs;
return luTick;
}
}
int TickDelta::ToMilliseconds() const
{
if (*this == Infinite())
{
return _I32_MAX;
}
int64 nTickUs = ToMicroseconds();
int64 lnRound = 500;
if (nTickUs < 0)
{
lnRound = -500;
}
int64 lnDelta = (nTickUs + lnRound) / ((int64) 1000);
AssertMsg((lnDelta <= INT_MAX) && (lnDelta >= INT_MIN), "Ensure no overflow");
return (int) lnDelta;
}
}
| 27.202273 | 105 | 0.346228 | satheeshravi |
a8324d2bedcb89d34a4eaa17764ad8753ea6118e | 10,440 | cpp | C++ | source/tests/api_tests.cpp | tkonolige/timemory | 1662925a3a7b6dfb1b7bba08ebd366d3fe38194a | [
"MIT"
] | 284 | 2019-08-06T17:41:39.000Z | 2022-03-25T23:37:47.000Z | source/tests/api_tests.cpp | tkonolige/timemory | 1662925a3a7b6dfb1b7bba08ebd366d3fe38194a | [
"MIT"
] | 123 | 2019-08-06T03:09:54.000Z | 2022-02-26T01:51:36.000Z | source/tests/api_tests.cpp | tkonolige/timemory | 1662925a3a7b6dfb1b7bba08ebd366d3fe38194a | [
"MIT"
] | 26 | 2019-12-06T22:21:09.000Z | 2022-03-23T09:34:29.000Z | // MIT License
//
// Copyright (c) 2020, The Regents of the University of California,
// through Lawrence Berkeley National Laboratory (subject to receipt of any
// required approvals from the U.S. Dept. of Energy). 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 "test_macros.hpp"
TIMEMORY_TEST_DEFAULT_MAIN
#include "timemory/timemory.hpp"
//--------------------------------------------------------------------------------------//
namespace details
{
// Get the current tests name
inline std::string
get_test_name()
{
return std::string(::testing::UnitTest::GetInstance()->current_test_suite()->name()) +
"." + ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
// this function consumes approximately "n" milliseconds of real time
inline void
do_sleep(long n)
{
std::this_thread::sleep_for(std::chrono::milliseconds(n));
}
// this function consumes an unknown number of cpu resources
inline long
fibonacci(long n)
{
return (n < 2) ? n : (fibonacci(n - 1) + fibonacci(n - 2));
}
// this function consumes approximately "t" milliseconds of cpu time
void
consume(long n)
{
// a mutex held by one lock
mutex_t mutex;
// acquire lock
lock_t hold_lk(mutex);
// associate but defer
lock_t try_lk(mutex, std::defer_lock);
// get current time
auto now = std::chrono::steady_clock::now();
// try until time point
while(std::chrono::steady_clock::now() < (now + std::chrono::milliseconds(n)))
try_lk.try_lock();
}
// get a random entry from vector
template <typename Tp>
void
random_fill(std::vector<Tp>& v, Tp scale, Tp offset = 1.0)
{
std::mt19937 rng;
rng.seed(std::random_device()());
std::generate(v.begin(), v.end(), [&]() {
return (scale * std::generate_canonical<Tp, 10>(rng)) + offset;
});
}
// get a random entry from vector
template <typename Tp>
size_t
random_entry(const std::vector<Tp>& v)
{
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> dist(0, v.size() - 1);
return v.at(dist(rng));
}
} // namespace details
//--------------------------------------------------------------------------------------//
class api_tests : public ::testing::Test
{
protected:
TIMEMORY_TEST_DEFAULT_SUITE_BODY
};
namespace os = ::tim::os;
namespace project = ::tim::project;
namespace category = ::tim::category;
namespace tpls = ::tim::tpls;
namespace trait = ::tim::trait;
using namespace tim::component;
using tim_bundle_t = tim::component_bundle<project::timemory, wall_clock, cpu_clock>;
using cali_bundle_t = tim::component_bundle<tpls::caliper, caliper_marker, wall_clock>;
using time_bundle_t = tim::component_tuple<wall_clock, cpu_clock, num_minor_page_faults,
read_bytes, written_bytes>;
using os_bundle_t = tim::component_bundle<os::agnostic, wall_clock, cpu_clock>;
//--------------------------------------------------------------------------------------//
TEST_F(api_tests, enum_vs_macro)
{
namespace component = tim::component;
auto macro_sz = std::tuple_size<tim::type_list<TIMEMORY_COMPONENT_TYPES>>::value;
auto enum_sz =
TIMEMORY_NATIVE_COMPONENTS_END - TIMEMORY_NATIVE_COMPONENT_INTERNAL_SIZE;
EXPECT_EQ(macro_sz, enum_sz);
}
//--------------------------------------------------------------------------------------//
TEST_F(api_tests, placeholder)
{
using nothing_placeholder = placeholder<nothing>;
auto in_complete = tim::is_one_of<nothing_placeholder, tim::complete_types_t>::value;
auto in_avail = tim::is_one_of<nothing_placeholder, tim::available_types_t>::value;
EXPECT_FALSE(in_complete) << "complete_types_t: "
<< tim::demangle<tim::complete_types_t>() << std::endl;
EXPECT_FALSE(in_avail) << "available_types_t: "
<< tim::demangle<tim::available_types_t>() << std::endl;
}
//--------------------------------------------------------------------------------------//
TEST_F(api_tests, timemory)
{
using test_t = project::timemory;
auto incoming = trait::runtime_enabled<test_t>::get();
trait::runtime_enabled<test_t>::set(false);
tim_bundle_t _obj(details::get_test_name());
_obj.start();
details::consume(1000);
_obj.stop();
EXPECT_NEAR(_obj.get<wall_clock>()->get(), 0.0, 1.0e-6);
EXPECT_NEAR(_obj.get<cpu_clock>()->get(), 0.0, 1.0e-6);
trait::runtime_enabled<test_t>::set(incoming);
}
//--------------------------------------------------------------------------------------//
TEST_F(api_tests, tpls)
{
using test_t = tpls::caliper;
auto incoming = trait::runtime_enabled<test_t>::get();
trait::runtime_enabled<test_t>::set(false);
EXPECT_FALSE(trait::runtime_enabled<test_t>::get());
EXPECT_FALSE(trait::runtime_enabled<caliper_marker>::get());
cali_bundle_t _obj(details::get_test_name());
_obj.start();
details::consume(1000);
_obj.stop();
std::cout << "tpls::caliper available == " << std::boolalpha << "[compile-time "
<< tim::trait::is_available<test_t>::value << "] [run-time "
<< trait::runtime_enabled<test_t>::get() << "]\n";
if(tim::trait::is_available<test_t>::value)
{
EXPECT_NEAR(_obj.get<wall_clock>()->get(), 0.0, 1.0e-6) << "obj: " << _obj;
}
else
{
EXPECT_EQ(_obj.get<wall_clock>(), nullptr) << "obj: " << _obj;
}
trait::runtime_enabled<test_t>::set(incoming);
}
//--------------------------------------------------------------------------------------//
TEST_F(api_tests, category)
{
// a type in a non-timing category that should still be enabled
#if defined(TIMEMORY_UNIX)
using check_type = num_minor_page_faults;
#elif defined(TIMEMORY_WINDOWS)
using check_type = read_bytes;
#endif
using test_t = category::timing;
auto incoming = trait::runtime_enabled<test_t>::get();
trait::runtime_enabled<test_t>::set(false);
using wc_api_t = trait::component_apis_t<wall_clock>;
using wc_true_t = tim::mpl::get_true_types_t<trait::runtime_configurable, wc_api_t>;
using wc_false_t = tim::mpl::get_false_types_t<trait::runtime_configurable, wc_api_t>;
using apitypes_t = typename trait::runtime_enabled<wall_clock>::api_type_list;
puts("");
PRINT_HERE("component-apis : %s", tim::demangle<wc_api_t>().c_str());
PRINT_HERE("true-types : %s", tim::demangle<wc_false_t>().c_str());
PRINT_HERE("false-types : %s", tim::demangle<wc_true_t>().c_str());
PRINT_HERE("type-traits : %s", tim::demangle<apitypes_t>().c_str());
puts("");
EXPECT_FALSE(trait::runtime_enabled<wall_clock>::get());
EXPECT_FALSE(trait::runtime_enabled<cpu_clock>::get());
EXPECT_TRUE(trait::runtime_enabled<check_type>::get());
time_bundle_t _obj(details::get_test_name());
_obj.start();
details::consume(500);
for(size_t i = 0; i < 10; ++i)
{
std::vector<double> _data(10000, 0.0);
details::random_fill(_data, 10.0, 1.0);
{
std::ofstream ofs{ TIMEMORY_JOIN("", ".", details::get_test_name(), "_data",
i, ".txt") };
for(auto& itr : _data)
ofs << std::fixed << std::setprecision(6) << itr << " ";
}
auto _data_cpy = _data;
_data.clear();
_data.resize(10000, 0.0);
{
std::ifstream ifs{ TIMEMORY_JOIN("", ".", details::get_test_name(), "_data",
i, ".txt") };
for(auto& itr : _data)
ifs >> itr;
}
for(size_t j = 0; j < _data.size(); ++j)
EXPECT_NEAR(_data.at(j), _data_cpy.at(j), 1.0e-3);
auto val = details::random_entry(_data);
EXPECT_GE(val, 1.0);
EXPECT_LE(val, 11.0);
}
_obj.stop();
ASSERT_TRUE(_obj.get<wall_clock>() != nullptr);
ASSERT_TRUE(_obj.get<cpu_clock>() != nullptr);
ASSERT_TRUE(_obj.get<check_type>() != nullptr);
EXPECT_NEAR(_obj.get<wall_clock>()->get(), 0.0, 1.0e-6);
EXPECT_NEAR(_obj.get<cpu_clock>()->get(), 0.0, 1.0e-6);
#if defined(TIMEMORY_UNIX)
EXPECT_GT(_obj.get<check_type>()->get(), 0);
#elif defined(TIMEMORY_WINDOWS)
EXPECT_GT(std::get<0>(_obj.get<check_type>()->get()), 0);
EXPECT_GT(std::get<1>(_obj.get<check_type>()->get()), 0);
EXPECT_NEAR(std::get<0>(_obj.get<read_bytes>()->get()),
std::get<0>(_obj.get<written_bytes>()->get()), 1.0e-3);
#endif
trait::runtime_enabled<test_t>::set(incoming);
}
//--------------------------------------------------------------------------------------//
TEST_F(api_tests, os)
{
trait::apply<trait::runtime_enabled>::set<os::supports_unix, os::supports_windows,
cpu_clock>(false);
os_bundle_t _obj(details::get_test_name());
_obj.start();
details::consume(1000);
_obj.stop();
EXPECT_NEAR(_obj.get<wall_clock>()->get(), 1.0, 0.1);
EXPECT_NEAR(_obj.get<cpu_clock>()->get(), 0.0, 1.0e-6);
trait::apply<trait::runtime_enabled>::set<os::supports_unix, os::supports_windows,
cpu_clock>(true);
}
//--------------------------------------------------------------------------------------//
| 35.151515 | 90 | 0.598659 | tkonolige |
a83420610dd94d8b6dd2ecd189c5a44d95f63d08 | 5,146 | cpp | C++ | rviz/src/image_view/image_view.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 5 | 2020-01-14T06:45:59.000Z | 2021-03-11T11:22:35.000Z | rviz/src/image_view/image_view.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 2 | 2019-02-12T21:55:08.000Z | 2019-02-20T01:01:24.000Z | rviz/src/image_view/image_view.cpp | romi2002/rviz | 8b2fcc1838e079d0e365894abd7cfd7b255b8d8b | [
"BSD-3-Clause-Clear"
] | 9 | 2018-09-09T20:48:17.000Z | 2021-03-11T11:22:52.000Z | /*
* 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, Inc. 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.
*/
#include <QtGlobal>
#include <QTimer>
#include "rviz/ogre_helpers/qt_ogre_render_window.h"
#include "rviz/ogre_helpers/initialization.h"
#include "rviz/image/ros_image_texture.h"
#include "ros/ros.h"
#include <ros/package.h>
#include <OgreRoot.h>
#include <OgreRenderWindow.h>
#include <OgreSceneManager.h>
#include <OgreViewport.h>
#include <OgreRectangle2D.h>
#include <OgreMaterial.h>
#include <OgreMaterialManager.h>
#include <OgreTextureUnitState.h>
#include <OgreSharedPtr.h>
#include <OgreTechnique.h>
#include <OgreSceneNode.h>
#include "image_view.h"
using namespace rviz;
ImageView::ImageView( QWidget* parent )
: QtOgreRenderWindow( parent )
, texture_it_(nh_)
{
setAutoRender(false);
scene_manager_ = ogre_root_->createSceneManager( Ogre::ST_GENERIC, "TestSceneManager" );
}
ImageView::~ImageView()
{
delete texture_;
}
void ImageView::showEvent( QShowEvent* event )
{
QtOgreRenderWindow::showEvent( event );
V_string paths;
paths.push_back(ros::package::getPath(ROS_PACKAGE_NAME) + "/ogre_media/textures");
initializeResources(paths);
setCamera( scene_manager_->createCamera( "Camera" ));
std::string resolved_image = nh_.resolveName("image");
if( resolved_image == "/image" )
{
ROS_WARN("image topic has not been remapped");
}
std::stringstream title;
title << "rviz Image Viewer [" << resolved_image << "]";
setWindowTitle( QString::fromStdString( title.str() ));
texture_ = new ROSImageTexture();
try
{
texture_->clear();
texture_sub_.reset(new image_transport::SubscriberFilter());
texture_sub_->subscribe(texture_it_, "image", 1, image_transport::TransportHints("raw"));
texture_sub_->registerCallback(boost::bind(&ImageView::textureCallback, this, _1));
}
catch (ros::Exception& e)
{
ROS_ERROR("%s", (std::string("Error subscribing: ") + e.what()).c_str());
}
Ogre::MaterialPtr material =
Ogre::MaterialManager::getSingleton().create( "Material",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
material->setCullingMode(Ogre::CULL_NONE);
material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(true);
material->getTechnique(0)->setLightingEnabled(false);
Ogre::TextureUnitState* tu = material->getTechnique(0)->getPass(0)->createTextureUnitState();
tu->setTextureName(texture_->getTexture()->getName());
tu->setTextureFiltering( Ogre::TFO_NONE );
Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true);
rect->setCorners(-1.0f, 1.0f, 1.0f, -1.0f);
rect->setMaterial(material->getName());
rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1);
Ogre::AxisAlignedBox aabb;
aabb.setInfinite();
rect->setBoundingBox(aabb);
Ogre::SceneNode* node = scene_manager_->getRootSceneNode()->createChildSceneNode();
node->attachObject(rect);
node->setVisible(true);
QTimer* timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( onTimer() ));
timer->start( 33 );
}
void ImageView::onTimer()
{
ros::spinOnce();
static bool first = true;
try
{
if( texture_->update() )
{
if( first )
{
first = false;
resize( texture_->getWidth(), texture_->getHeight() );
}
}
ogre_root_->renderOneFrame();
}
catch( UnsupportedImageEncoding& e )
{
ROS_ERROR("%s", e.what());
}
if( !nh_.ok() )
{
close();
}
}
void ImageView::textureCallback(const sensor_msgs::Image::ConstPtr& msg)
{
if (texture_) {
texture_->addMessage(msg);
}
}
| 30.630952 | 108 | 0.70754 | romi2002 |
a835acabb3e537773fa18ad0e8d4e4db1ae03ed1 | 2,932 | cc | C++ | gpdb/src/model/DescribeSlowLogRecordsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | gpdb/src/model/DescribeSlowLogRecordsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | gpdb/src/model/DescribeSlowLogRecordsRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/gpdb/model/DescribeSlowLogRecordsRequest.h>
using AlibabaCloud::Gpdb::Model::DescribeSlowLogRecordsRequest;
DescribeSlowLogRecordsRequest::DescribeSlowLogRecordsRequest() :
RpcServiceRequest("gpdb", "2016-05-03", "DescribeSlowLogRecords")
{
setMethod(HttpRequest::Method::Post);
}
DescribeSlowLogRecordsRequest::~DescribeSlowLogRecordsRequest()
{}
std::string DescribeSlowLogRecordsRequest::getStartTime()const
{
return startTime_;
}
void DescribeSlowLogRecordsRequest::setStartTime(const std::string& startTime)
{
startTime_ = startTime;
setParameter("StartTime", startTime);
}
int DescribeSlowLogRecordsRequest::getPageNumber()const
{
return pageNumber_;
}
void DescribeSlowLogRecordsRequest::setPageNumber(int pageNumber)
{
pageNumber_ = pageNumber;
setParameter("PageNumber", std::to_string(pageNumber));
}
std::string DescribeSlowLogRecordsRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void DescribeSlowLogRecordsRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setParameter("AccessKeyId", accessKeyId);
}
int DescribeSlowLogRecordsRequest::getPageSize()const
{
return pageSize_;
}
void DescribeSlowLogRecordsRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::string DescribeSlowLogRecordsRequest::getDBInstanceId()const
{
return dBInstanceId_;
}
void DescribeSlowLogRecordsRequest::setDBInstanceId(const std::string& dBInstanceId)
{
dBInstanceId_ = dBInstanceId;
setParameter("DBInstanceId", dBInstanceId);
}
long DescribeSlowLogRecordsRequest::getSQLId()const
{
return sQLId_;
}
void DescribeSlowLogRecordsRequest::setSQLId(long sQLId)
{
sQLId_ = sQLId;
setParameter("SQLId", std::to_string(sQLId));
}
std::string DescribeSlowLogRecordsRequest::getEndTime()const
{
return endTime_;
}
void DescribeSlowLogRecordsRequest::setEndTime(const std::string& endTime)
{
endTime_ = endTime;
setParameter("EndTime", endTime);
}
std::string DescribeSlowLogRecordsRequest::getDBName()const
{
return dBName_;
}
void DescribeSlowLogRecordsRequest::setDBName(const std::string& dBName)
{
dBName_ = dBName;
setParameter("DBName", dBName);
}
| 24.847458 | 85 | 0.760914 | iamzken |
a8373d2a8b68ee46f2203c509b7341604c44253a | 4,544 | cpp | C++ | Source/Dynamics/Joints/b2DistanceJoint.cpp | Rinnegatamante/Box2D | e4e218f5ec0d5e8fab5d6a8f54079066e8dc0a16 | [
"Zlib"
] | 4 | 2017-05-31T08:39:37.000Z | 2018-04-22T02:51:18.000Z | Source/Dynamics/Joints/b2DistanceJoint.cpp | Rinnegatamante/Box2D | e4e218f5ec0d5e8fab5d6a8f54079066e8dc0a16 | [
"Zlib"
] | null | null | null | Source/Dynamics/Joints/b2DistanceJoint.cpp | Rinnegatamante/Box2D | e4e218f5ec0d5e8fab5d6a8f54079066e8dc0a16 | [
"Zlib"
] | 1 | 2018-03-10T21:25:01.000Z | 2018-03-10T21:25:01.000Z | /*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2DistanceJoint.h"
#include "../b2Body.h"
#include "../b2World.h"
// C = norm(p2 - p1) - L
// u = (p2 - p1) / norm(p2 - p1)
// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// J = [-u -cross(r1, u) u cross(r2, u)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def)
: b2Joint(def)
{
m_localAnchor1 = b2MulT(m_body1->m_R, def->anchorPoint1 - m_body1->m_position);
m_localAnchor2 = b2MulT(m_body2->m_R, def->anchorPoint2 - m_body2->m_position);
b2Vec2 d = def->anchorPoint2 - def->anchorPoint1;
m_length = d.Length();
m_impulse = 0.0f;
}
void b2DistanceJoint::InitVelocityConstraints()
{
// Compute the effective mass matrix.
b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1);
b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2);
m_u = m_body2->m_position + r2 - m_body1->m_position - r1;
// Handle singularity.
float32 length = m_u.Length();
if (length > b2_linearSlop)
{
m_u *= 1.0f / length;
}
else
{
m_u.Set(0.0f, 0.0f);
}
float32 cr1u = b2Cross(r1, m_u);
float32 cr2u = b2Cross(r2, m_u);
m_mass = m_body1->m_invMass + m_body1->m_invI * cr1u * cr1u + m_body2->m_invMass + m_body2->m_invI * cr2u * cr2u;
b2Assert(m_mass > FLT_EPSILON);
m_mass = 1.0f / m_mass;
if (b2World::s_enableWarmStarting)
{
b2Vec2 P = m_impulse * m_u;
m_body1->m_linearVelocity -= m_body1->m_invMass * P;
m_body1->m_angularVelocity -= m_body1->m_invI * b2Cross(r1, P);
m_body2->m_linearVelocity += m_body2->m_invMass * P;
m_body2->m_angularVelocity += m_body2->m_invI * b2Cross(r2, P);
}
else
{
m_impulse = 0.0f;
}
}
void b2DistanceJoint::SolveVelocityConstraints(const b2TimeStep& step)
{
NOT_USED(step);
b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1);
b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2);
// Cdot = dot(u, v + cross(w, r))
b2Vec2 v1 = m_body1->m_linearVelocity + b2Cross(m_body1->m_angularVelocity, r1);
b2Vec2 v2 = m_body2->m_linearVelocity + b2Cross(m_body2->m_angularVelocity, r2);
float32 Cdot = b2Dot(m_u, v2 - v1);
float32 impulse = -m_mass * Cdot;
m_impulse += impulse;
b2Vec2 P = impulse * m_u;
m_body1->m_linearVelocity -= m_body1->m_invMass * P;
m_body1->m_angularVelocity -= m_body1->m_invI * b2Cross(r1, P);
m_body2->m_linearVelocity += m_body2->m_invMass * P;
m_body2->m_angularVelocity += m_body2->m_invI * b2Cross(r2, P);
}
bool b2DistanceJoint::SolvePositionConstraints()
{
b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1);
b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2);
b2Vec2 d = m_body2->m_position + r2 - m_body1->m_position - r1;
float32 length = d.Normalize();
float32 C = length - m_length;
C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection);
float32 impulse = -m_mass * C;
m_u = d;
b2Vec2 P = impulse * m_u;
m_body1->m_position -= m_body1->m_invMass * P;
m_body1->m_rotation -= m_body1->m_invI * b2Cross(r1, P);
m_body2->m_position += m_body2->m_invMass * P;
m_body2->m_rotation += m_body2->m_invI * b2Cross(r2, P);
m_body1->m_R.Set(m_body1->m_rotation);
m_body2->m_R.Set(m_body2->m_rotation);
return b2Abs(C) < b2_linearSlop;
}
b2Vec2 b2DistanceJoint::GetAnchor1() const
{
return m_body1->m_position + b2Mul(m_body1->m_R, m_localAnchor1);
}
b2Vec2 b2DistanceJoint::GetAnchor2() const
{
return m_body2->m_position + b2Mul(m_body2->m_R, m_localAnchor2);
}
b2Vec2 b2DistanceJoint::GetReactionForce(float32 invTimeStep) const
{
b2Vec2 F = (m_impulse * invTimeStep) * m_u;
return F;
}
float32 b2DistanceJoint::GetReactionTorque(float32 invTimeStep) const
{
NOT_USED(invTimeStep);
return 0.0f;
}
| 30.911565 | 114 | 0.715009 | Rinnegatamante |
a837fbb242363b0e25206911742f4adb148db774 | 3,009 | cc | C++ | routing-algos/alg/nth-element-test.cc | uluyol/routing-algos | a43ab38b70d0301e38f0114df651edbffa730d4c | [
"Apache-2.0"
] | null | null | null | routing-algos/alg/nth-element-test.cc | uluyol/routing-algos | a43ab38b70d0301e38f0114df651edbffa730d4c | [
"Apache-2.0"
] | null | null | null | routing-algos/alg/nth-element-test.cc | uluyol/routing-algos | a43ab38b70d0301e38f0114df651edbffa730d4c | [
"Apache-2.0"
] | null | null | null | #include "routing-algos/alg/nth-element.h"
#include <algorithm>
#include <vector>
#include "absl/strings/substitute.h"
#include "absl/types/span.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace routing_algos {
namespace {
std::vector<int64_t> RoutingAlgosNth(const std::vector<int64_t>& arg, int n) {
std::vector<int64_t> result = arg;
routing_algos::NthElement(result.begin(), result.begin() + n, result.end());
return result;
}
std::vector<int64_t> StdNth(const std::vector<int64_t>& arg, int n) {
std::vector<int64_t> result = arg;
std::nth_element(result.begin(), result.begin() + n, result.end());
return result;
}
class NthElementExhaustiveTest
: public testing::TestWithParam<std::vector<int64_t>> {};
TEST_P(NthElementExhaustiveTest, MatchesStd) {
for (int i = 0; i < GetParam().size(); i++) {
SCOPED_TRACE(absl::Substitute("i = $0", i));
auto result_routing_algos = RoutingAlgosNth(GetParam(), i);
auto result_std = StdNth(GetParam(), i);
EXPECT_THAT(result_routing_algos[i], testing::Eq(result_std[i]));
EXPECT_THAT(absl::MakeSpan(result_routing_algos).subspan(0, i),
testing::Each(testing::Le(result_routing_algos[i])));
}
}
struct SampledTest {
std::vector<int64_t> data;
std::vector<int> ns;
};
class NthElementSampledTest : public testing::TestWithParam<SampledTest> {};
TEST_P(NthElementSampledTest, MatchesStd) {
for (int i : GetParam().ns) {
auto result_routing_algos = RoutingAlgosNth(GetParam().data, i);
auto result_std = StdNth(GetParam().data, i);
EXPECT_THAT(result_routing_algos[i], testing::Eq(result_std[i]));
EXPECT_THAT(absl::MakeSpan(result_routing_algos).subspan(0, i),
testing::Each(testing::Le(result_routing_algos[i])));
}
}
std::vector<int64_t> RandomData(int n) {
std::vector<int64_t> data(n, 0);
for (int i = 0; i < n; i++) {
data[i] = rand() % 55;
}
return data;
}
std::vector<int64_t> RepeatN(int n, int64_t v) {
return std::vector<int64_t>(n, v);
}
INSTANTIATE_TEST_SUITE_P(Sampled, NthElementExhaustiveTest,
testing::Values(RandomData(1), RandomData(10),
RandomData(111), RandomData(301),
RepeatN(257, 0), RepeatN(30, 4981)));
INSTANTIATE_TEST_SUITE_P(Sampled, NthElementSampledTest,
testing::Values(
SampledTest{
RandomData(5000),
{0, 1, 555, 1123, 4999},
},
SampledTest{
RandomData(51003),
{0, 1, 555, 3, 49945},
},
SampledTest{
RepeatN(5000, 4),
{0, 1, 555, 1123, 4999},
}));
} // namespace
} // namespace routing_algos | 32.706522 | 78 | 0.576936 | uluyol |
a838c02cff96887784d3c09cf72212709326dc94 | 1,454 | cpp | C++ | aws-cpp-sdk-comprehendmedical/source/model/UnmappedAttribute.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-comprehendmedical/source/model/UnmappedAttribute.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-comprehendmedical/source/model/UnmappedAttribute.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/comprehendmedical/model/UnmappedAttribute.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ComprehendMedical
{
namespace Model
{
UnmappedAttribute::UnmappedAttribute() :
m_type(EntityType::NOT_SET),
m_typeHasBeenSet(false),
m_attributeHasBeenSet(false)
{
}
UnmappedAttribute::UnmappedAttribute(JsonView jsonValue) :
m_type(EntityType::NOT_SET),
m_typeHasBeenSet(false),
m_attributeHasBeenSet(false)
{
*this = jsonValue;
}
UnmappedAttribute& UnmappedAttribute::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Type"))
{
m_type = EntityTypeMapper::GetEntityTypeForName(jsonValue.GetString("Type"));
m_typeHasBeenSet = true;
}
if(jsonValue.ValueExists("Attribute"))
{
m_attribute = jsonValue.GetObject("Attribute");
m_attributeHasBeenSet = true;
}
return *this;
}
JsonValue UnmappedAttribute::Jsonize() const
{
JsonValue payload;
if(m_typeHasBeenSet)
{
payload.WithString("Type", EntityTypeMapper::GetNameForEntityType(m_type));
}
if(m_attributeHasBeenSet)
{
payload.WithObject("Attribute", m_attribute.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace ComprehendMedical
} // namespace Aws
| 19.131579 | 81 | 0.730399 | lintonv |
a839ffd484c7fd98863c93f320b1ea7ad649a04d | 11,800 | cpp | C++ | examples/tensorrt-samples/python/fc_plugin_caffe_mnist/plugin/FullyConnected.cpp | storypku/cuda-support-for-bazel | b76b3095e5dc495a8e7b8e29c96674547d66deaa | [
"Apache-2.0"
] | 11 | 2020-05-29T01:30:18.000Z | 2022-01-27T02:34:09.000Z | examples/tensorrt-samples/python/fc_plugin_caffe_mnist/plugin/FullyConnected.cpp | storypku/cuda-support-for-bazel | b76b3095e5dc495a8e7b8e29c96674547d66deaa | [
"Apache-2.0"
] | 1 | 2020-06-16T11:41:56.000Z | 2020-06-16T11:41:56.000Z | examples/tensorrt-samples/python/fc_plugin_caffe_mnist/plugin/FullyConnected.cpp | storypku/cuda-support-for-bazel | b76b3095e5dc495a8e7b8e29c96674547d66deaa | [
"Apache-2.0"
] | 2 | 2020-09-14T20:12:27.000Z | 2021-12-09T04:38:41.000Z | /*
* Copyright 1993-2019 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO LICENSEE:
*
* This source code and/or documentation ("Licensed Deliverables") are
* subject to NVIDIA intellectual property rights under U.S. and
* international Copyright laws.
*
* These Licensed Deliverables contained herein is PROPRIETARY and
* CONFIDENTIAL to NVIDIA and is being provided under the terms and
* conditions of a form of NVIDIA software license agreement by and
* between NVIDIA and Licensee ("License Agreement") or electronically
* accepted by Licensee. Notwithstanding any terms or conditions to
* the contrary in the License Agreement, reproduction or disclosure
* of the Licensed Deliverables to any third party without the express
* written consent of NVIDIA is prohibited.
*
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
* SPECIAL, INDIRECT, INCIDENTAL, 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 THESE LICENSED DELIVERABLES.
*
* U.S. Government End Users. These Licensed Deliverables are a
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
* 1995), consisting of "commercial computer software" and "commercial
* computer software documentation" as such terms are used in 48
* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
* U.S. Government End Users acquire the Licensed Deliverables with
* only those rights set forth herein.
*
* Any use of the Licensed Deliverables in individual and commercial
* software must include, in the user documentation and internal
* comments to the code, the above Disclaimer and U.S. Government End
* Users Notice.
*/
#include <cassert>
#include <cstring>
#include <cuda_runtime_api.h>
#include <cudnn.h>
#include <cublas_v2.h>
#include <iostream>
#include <stdexcept>
#include <array>
#include "NvInfer.h"
#include "FullyConnected.h"
#define CHECK(status) { if (status != 0) throw std::runtime_error(__FILE__ + __LINE__ + std::string{"CUDA Error: "} + std::to_string(status)); }
namespace
{
constexpr const char* FC_PLUGIN_VERSION{"1"};
constexpr const char* FC_PLUGIN_NAME{"FCPlugin"};
// Helpers to move data to/from the GPU.
nvinfer1::Weights copyToDevice(const void* hostData, int count)
{
void* deviceData;
CHECK(cudaMalloc(&deviceData, count * sizeof(float)));
CHECK(cudaMemcpy(deviceData, hostData, count * sizeof(float), cudaMemcpyHostToDevice));
return nvinfer1::Weights{nvinfer1::DataType::kFLOAT, deviceData, count};
}
nvinfer1::Weights makeDeviceCopy(nvinfer1::Weights deviceWeights)
{
void* deviceData;
CHECK(cudaMalloc(&deviceData, deviceWeights.count * sizeof(float)));
CHECK(cudaMemcpy(deviceData, deviceWeights.values, deviceWeights.count * sizeof(float), cudaMemcpyDeviceToDevice));
return nvinfer1::Weights{nvinfer1::DataType::kFLOAT, deviceData, deviceWeights.count};
}
int copyFromDevice(char* hostBuffer, nvinfer1::Weights deviceWeights)
{
*reinterpret_cast<int*>(hostBuffer) = deviceWeights.count;
CHECK(cudaMemcpy(hostBuffer + sizeof(int), deviceWeights.values, deviceWeights.count * sizeof(float), cudaMemcpyDeviceToHost));
return sizeof(int) + deviceWeights.count * sizeof(float);
}
}
nvinfer1::PluginFieldCollection FCPluginCreator::mFC{};
std::vector<nvinfer1::PluginField> FCPluginCreator::mPluginAttributes;
REGISTER_TENSORRT_PLUGIN(FCPluginCreator);
// In this simple case we're going to infer the number of output channels from the bias weights.
// The knowledge that the kernel weights are weights[0] and the bias weights are weights[1] was
// divined from the caffe innards
FCPlugin::FCPlugin(const nvinfer1::Weights* weights, int nbWeights)
{
assert(nbWeights == 2);
mKernelWeights = copyToDevice(weights[0].values, weights[0].count);
mBiasWeights = copyToDevice(weights[1].values, weights[1].count);
}
// Copy from existing device weights
FCPlugin::FCPlugin(const nvinfer1::Weights& deviceKernel, const nvinfer1::Weights& deviceBias)
{
mKernelWeights = makeDeviceCopy(deviceKernel);
mBiasWeights = makeDeviceCopy(deviceBias);
}
// Create the plugin at runtime from a byte stream.
FCPlugin::FCPlugin(const void* data, size_t length)
{
const char* d = reinterpret_cast<const char*>(data);
const char* check = d;
// Deserialize kernel.
const int kernelCount = reinterpret_cast<const int*>(d)[0];
mKernelWeights = copyToDevice(d + sizeof(int), kernelCount);
d += sizeof(int) + mKernelWeights.count * sizeof(float);
// Deserialize bias.
const int biasCount = reinterpret_cast<const int*>(d)[0];
mBiasWeights = copyToDevice(d + sizeof(int), biasCount);
d += sizeof(int) + mBiasWeights.count * sizeof(float);
// Check that the sizes are what we expected.
assert(d == check + length);
}
// Free buffers.
FCPlugin::~FCPlugin()
{
cudaFree(const_cast<void*>(mKernelWeights.values));
mKernelWeights.values = nullptr;
cudaFree(const_cast<void*>(mBiasWeights.values));
mBiasWeights.values = nullptr;
}
int FCPlugin::getNbOutputs() const
{
return 1;
}
nvinfer1::Dims FCPlugin::getOutputDimensions(int index, const nvinfer1::Dims* inputs, int nbInputDims)
{
assert(index == 0 && nbInputDims == 1 && inputs[0].nbDims == 3);
return nvinfer1::DimsCHW{static_cast<int>(mBiasWeights.count), 1, 1};
}
int FCPlugin::initialize()
{
CHECK(cudnnCreate(&mCudnn));
CHECK(cublasCreate(&mCublas));
// Create cudnn tensor descriptors for bias addition.
CHECK(cudnnCreateTensorDescriptor(&mSrcDescriptor));
CHECK(cudnnCreateTensorDescriptor(&mDstDescriptor));
return 0;
}
void FCPlugin::terminate()
{
CHECK(cudnnDestroyTensorDescriptor(mSrcDescriptor));
CHECK(cudnnDestroyTensorDescriptor(mDstDescriptor));
CHECK(cublasDestroy(mCublas));
CHECK(cudnnDestroy(mCudnn));
}
// This plugin requires no workspace memory during build time.
size_t FCPlugin::getWorkspaceSize(int maxBatchSize) const
{
return 0;
}
int FCPlugin::enqueue(int batchSize, const void* const* inputs, void** outputs, void* workspace, cudaStream_t stream)
{
int nbOutputChannels = mBiasWeights.count;
int nbInputChannels = mKernelWeights.count / nbOutputChannels;
constexpr float kONE = 1.0f, kZERO = 0.0f;
// Do matrix multiplication.
cublasSetStream(mCublas, stream);
cudnnSetStream(mCudnn, stream);
CHECK(cublasSgemm(mCublas, CUBLAS_OP_T, CUBLAS_OP_N, nbOutputChannels, batchSize, nbInputChannels, &kONE,
reinterpret_cast<const float*>(mKernelWeights.values), nbInputChannels,
reinterpret_cast<const float*>(inputs[0]), nbInputChannels, &kZERO,
reinterpret_cast<float*>(outputs[0]), nbOutputChannels));
// Add bias.
CHECK(cudnnSetTensor4dDescriptor(mSrcDescriptor, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, 1, nbOutputChannels, 1, 1));
CHECK(cudnnSetTensor4dDescriptor(mDstDescriptor, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, batchSize, nbOutputChannels, 1, 1));
CHECK(cudnnAddTensor(mCudnn, &kONE, mSrcDescriptor, mBiasWeights.values, &kONE, mDstDescriptor, outputs[0]));
return 0;
}
size_t FCPlugin::getSerializationSize() const
{
return sizeof(int) * 2 + mKernelWeights.count * sizeof(float) + mBiasWeights.count * sizeof(float);
}
void FCPlugin::serialize(void* buffer) const
{
char* d = reinterpret_cast<char*>(buffer);
const char* check = d;
d += copyFromDevice(d, mKernelWeights);
d += copyFromDevice(d, mBiasWeights);
assert(d == check + getSerializationSize());
}
// For this sample, we'll only support float32 with NCHW.
bool FCPlugin::supportsFormat(nvinfer1::DataType type, nvinfer1::PluginFormat format) const
{
return (type == nvinfer1::DataType::kFLOAT && format == nvinfer1::PluginFormat::kNCHW);
}
const char* FCPlugin::getPluginType() const
{
return FC_PLUGIN_NAME;
}
const char* FCPlugin::getPluginVersion() const
{
return FC_PLUGIN_VERSION;
}
void FCPlugin::destroy()
{
delete this;
}
IPluginV2Ext* FCPlugin::clone() const
{
IPluginV2Ext* plugin = new FCPlugin(mKernelWeights, mBiasWeights);
plugin->setPluginNamespace(mPluginNamespace.c_str());
return plugin;
}
void FCPlugin::setPluginNamespace(const char* pluginNamespace)
{
mPluginNamespace = pluginNamespace;
}
const char* FCPlugin::getPluginNamespace() const
{
return mPluginNamespace.c_str();
}
DataType FCPlugin::getOutputDataType(int index, const nvinfer1::DataType* inputTypes, int nbInputs) const
{
return DataType::kFLOAT;
}
bool FCPlugin::isOutputBroadcastAcrossBatch(int outputIndex, const bool* inputIsBroadcasted, int nbInputs) const
{
return false;
}
bool FCPlugin::canBroadcastInputAcrossBatch(int inputIndex) const
{
return false;
}
void FCPlugin::configurePlugin(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs,
const DataType* inputTypes, const DataType* outputTypes, const bool* inputIsBroadcast,
const bool* outputIsBroadcast, PluginFormat floatFormat, int maxBatchSize)
{
assert(nbInputs == 1 && inputDims[0].d[1] == 1 && inputDims[0].d[2] == 1);
assert(nbOutputs == 1 && outputDims[0].d[1] == 1 && outputDims[0].d[2] == 1);
assert(mKernelWeights.count == inputDims[0].d[0] * inputDims[0].d[1] * inputDims[0].d[2] * mBiasWeights.count);
}
void FCPlugin::attachToContext(cudnnContext* cudnnContext, cublasContext* cublasContext, IGpuAllocator* gpuAllocator)
{
}
void FCPlugin::detachFromContext() {}
//
// Plugin Creator
//
FCPluginCreator::FCPluginCreator()
{
mFC.nbFields = mPluginAttributes.size();
mFC.fields = mPluginAttributes.data();
}
void FCPluginCreator::setPluginNamespace(const char* libNamespace)
{
mNamespace = libNamespace;
}
const char* FCPluginCreator::getPluginNamespace() const
{
return mNamespace.c_str();
}
const char* FCPluginCreator::getPluginName() const
{
return FC_PLUGIN_NAME;
}
const char* FCPluginCreator::getPluginVersion() const
{
return FC_PLUGIN_VERSION;
}
const PluginFieldCollection* FCPluginCreator::getFieldNames()
{
return &mFC;
}
IPluginV2Ext* FCPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc)
{
std::array<Weights, 2> weights{};
for (int i = 0; i < fc->nbFields; ++i)
{
std::string fieldName(fc->fields[i].name);
if (fieldName.compare("kernel") == 0)
{
weights[0].values = fc->fields[i].data;
weights[0].count = fc->fields[i].length;
weights[0].type = nvinfer1::DataType::kFLOAT;
}
if (fieldName.compare("bias") == 0)
{
weights[1].values = fc->fields[i].data;
weights[1].count = fc->fields[i].length;
weights[1].type = nvinfer1::DataType::kFLOAT;
}
}
return new FCPlugin(static_cast<void*>(weights.data()), weights.size());
}
IPluginV2Ext* FCPluginCreator::deserializePlugin(const char* name, const void* serialData, size_t serialLength)
{
auto* plugin = new FCPlugin(serialData, serialLength);
plugin->setPluginNamespace(mNamespace.c_str());
return plugin;
}
| 34.302326 | 145 | 0.737203 | storypku |
a83a6eb63f2269281aac94928d0c6c00d9bcf0f4 | 352 | cpp | C++ | Baekjoon/9517.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/9517.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/9517.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(void)
{
int k, n, time = 210, ans, t;
char z;
bool check = false;
cin >> k >> n;
for (int i = 0; i < n; i++)
{
cin >> t >> z;
if (time - t <= 0 && !check)
{
ans = k;
check = true;
}
else
{
time -= t;
if (z == 'T')
k = (k + 1) > 8 ? 1 : (k + 1);
}
}
cout << ans;
}
| 13.538462 | 34 | 0.431818 | Twinparadox |
a83b984f807c976a21a2e59b11972e2944e47229 | 202 | cpp | C++ | source/code/utilities/web/chrome/version/chrome_version.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/utilities/web/chrome/version/chrome_version.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/utilities/web/chrome/version/chrome_version.cpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #include <iostream>
#include "code/utilities/web/chrome/version/chrome_version_getter.hpp"
int main(){
auto version = Chrome_Version_Getter::Get_Version();
std::cout << version << std::endl;
}
| 25.25 | 70 | 0.722772 | luxe |
a83fb78974f672a4c3357c07ef956dd0652742e1 | 1,642 | cc | C++ | ui/gfx/surface/accelerated_surface_wayland.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | ui/gfx/surface/accelerated_surface_wayland.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | ui/gfx/surface/accelerated_surface_wayland.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011 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 "ui/gfx/surface/accelerated_surface_wayland.h"
#include <wayland-egl.h>
#include "third_party/angle/include/EGL/egl.h"
#include "third_party/angle/include/EGL/eglext.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#include "ui/wayland/wayland_display.h"
AcceleratedSurface::AcceleratedSurface(const gfx::Size& size)
: size_(size),
image_(NULL),
pixmap_(NULL),
texture_(0) {
EGLDisplay edpy = gfx::GLSurfaceEGL::GetHardwareDisplay();
pixmap_ = wl_egl_pixmap_create(size_.width(),
size_.height(),
0);
image_ = eglCreateImageKHR(
edpy, EGL_NO_CONTEXT, EGL_NATIVE_PIXMAP_KHR, (void*) pixmap_, NULL);
glGenTextures(1, &texture_);
GLint current_texture = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture);
glBindTexture(GL_TEXTURE_2D, texture_);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image_);
glBindTexture(GL_TEXTURE_2D, current_texture);
}
AcceleratedSurface::~AcceleratedSurface() {
glDeleteTextures(1, &texture_);
eglDestroyImageKHR(gfx::GLSurfaceEGL::GetHardwareDisplay(), image_);
wl_egl_pixmap_destroy(pixmap_);
}
| 33.510204 | 74 | 0.741169 | gavinp |
a8404dda110c45eb70affbde1ba34a9131348b3b | 1,329 | cc | C++ | garnet/bin/ktrace_provider/reader.cc | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | garnet/bin/ktrace_provider/reader.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | garnet/bin/ktrace_provider/reader.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2017 The Fuchsia 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 "garnet/bin/ktrace_provider/reader.h"
#include <lib/zircon-internal/ktrace.h>
namespace ktrace_provider {
Reader::Reader(const char* buffer, size_t buffer_size)
: current_(buffer), marker_(buffer), end_(buffer + buffer_size) {}
const ktrace_header_t* Reader::ReadNextRecord() {
if (AvailableBytes() < sizeof(ktrace_header_t)) {
ReadMoreData();
}
if (AvailableBytes() < sizeof(ktrace_header_t)) {
FX_VLOGS(10) << "No more records";
return nullptr;
}
auto record = reinterpret_cast<const ktrace_header_t*>(current_);
if (AvailableBytes() < KTRACE_LEN(record->tag)) {
ReadMoreData();
}
if (AvailableBytes() < KTRACE_LEN(record->tag)) {
FX_VLOGS(10) << "No more records, incomplete last record";
return nullptr;
}
record = reinterpret_cast<const ktrace_header_t*>(current_);
current_ += KTRACE_LEN(record->tag);
number_bytes_read_ += KTRACE_LEN(record->tag);
number_records_read_ += 1;
FX_VLOGS(10) << "Importing ktrace event 0x" << std::hex << KTRACE_EVENT(record->tag) << ", size "
<< std::dec << KTRACE_LEN(record->tag);
return record;
}
} // namespace ktrace_provider
| 27.6875 | 99 | 0.693755 | dahlia-os |
a8406d8f8511fcf91865a302766e08e3ac7df248 | 13,537 | cpp | C++ | controllers/nrt_software/plugins_misc/src/contact_test.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 1 | 2019-12-02T07:10:42.000Z | 2019-12-02T07:10:42.000Z | controllers/nrt_software/plugins_misc/src/contact_test.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | null | null | null | controllers/nrt_software/plugins_misc/src/contact_test.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 2 | 2020-10-22T19:06:44.000Z | 2021-06-07T03:32:52.000Z | #include <config.h>
#include <mwoibn/loaders/robot.h>
#include <mwoibn/robot_class/robot_ros_nrt.h>
#include <mwoibn/robot_class/robot_xbot_nrt.h>
#include <mwoibn/visualization_tools/rviz_track_point.h>
#include <mwoibn/point_handling/robot_points_handler.h>
// std::vector<mwoibn::Vector3>
// contactPoints(mwoibn::robot_class::Robot& robot,
// mwoibn::point_handling::PositionsHandler& wheels)
//{
// mwoibn::Vector3 ground, wheel, x, point;
// std::vector<mwoibn::Vector3> points;
// ground << 0, 0, 1; // flat ground
// double R = 0.010, r = 0.068;
// for (int i = 0; i < wheels.size(); i++)
// {
// points.push_back(point);
// }
// // std::cout << std::endl;
// return points;
//}
class Flow
{
public:
Flow(mwoibn::robot_class::Robot& robot,
mwoibn::point_handling::PositionsHandler& wheels)
: _robot(robot), _wheels(wheels), _contacts("ROOT", _robot)
{
_ground << 0, 0, 1;
for (auto link : _robot.getLinks("wheels"))
{
_contacts.addPoint(link);
_current.push_back(mwoibn::Vector3::Zero());
_spherical.push_back(mwoibn::Vector3::Zero());
_modelDiff.push_back(mwoibn::Vector3::Zero());
_equationDiff.push_back(mwoibn::Vector3::Zero());
_flowDiff.push_back(mwoibn::Vector3::Zero());
}
_contacts.computeChain();
_contactPoints();
// init estimation
_estimated = _current;
_fromPosDiff = _current;
_contacts.setFullStatesWorld(
_current, robot.state.position.get());
}
virtual ~Flow() {
}
void update()
{
std::vector<mwoibn::Vector3> _previous = _current;
_contactPoints(); // update contact position
_contacts.setFullStatesWorld(
_current,
_robot.state.position.get()); // update handler
double test = ((_current[0] - _previous[0]).norm() +
(_current[1] - _previous[1]).norm() +
(_current[2] - _previous[2]).norm() +
(_current[3] - _previous[3]).norm());
for (int i = 0; i < _wheels.size(); i++)
_fromPosDiff[i] += (_current[i] - _previous[i]);
_flowDerivatives(); // update flow derivative
_flowEstimates(); // estimate current contact
_sphericalPoints(); // compute spherical estimation
_modelDerivatives(); // compute contact point derivative
_equationDerivatives(); // compute from my equation
nr++;
if (test > mwoibn::EPS)
{
std::cout << "nr\t" << nr << "\n";
std::cout << "from position"
<< "\t";
for (int i = 0; i < _wheels.size(); i++)
std::cout << (_current[i][0] - _previous[i][0]) / _robot.rate() / nr
<< "\t"
<< (_current[i][1] - _previous[i][1]) / _robot.rate() / nr
<< "\t"
<< (_current[i][2] - _previous[i][2]) / _robot.rate() / nr
<< "\t";
std::cout << std::endl;
std::cout << "estimated"
<< "\t";
for (int i = 0; i < _wheels.size(); i++)
std::cout << _estimated[i][0] << "\t" << _estimated[i][1] << "\t"
<< _estimated[i][2] << "\t";
std::cout << std::endl;
std::cout << "point\t"
<< "\t";
for (int i = 0; i < _wheels.size(); i++)
std::cout << _equationDiff[i][0] << "\t" << _equationDiff[i][1] << "\t"
<< _equationDiff[i][2] << "\t";
std::cout << std::endl;
std::cout << "from positions"
<< "\t";
for (int i = 0; i < _wheels.size(); i++)
std::cout << _current[i][0] << "\t" << _current[i][1] << "\t"
<< _current[i][2] << "\t";
std::cout << std::endl;
std::cout << "models\t"
<< "\t";
for (int i = 0; i < _wheels.size(); i++)
std::cout << _modelDiff[i][0] << "\t" << _modelDiff[i][1] << "\t"
<< _modelDiff[i][2] << "\t";
std::cout << std::endl;
nr = 0;
}
}
mwoibn::Vector3& getContact(int i) {
return _current[i];
}
mwoibn::Vector3& getEstimate(int i) {
return _estimated[i];
}
mwoibn::Vector3& getSpherical(int i) {
return _spherical[i];
}
mwoibn::Vector3& getModelDiff(int i) {
return _modelDiff[i];
}
mwoibn::Vector3& getEquationDiff(int i) {
return _equationDiff[i];
}
protected:
double R = 0.010, r = 0.068;
int nr = 0;
mwoibn::robot_class::Robot& _robot;
mwoibn::point_handling::PositionsHandler& _wheels; // wheels centers
mwoibn::point_handling::PositionsHandler _contacts; // contact points
std::vector<mwoibn::Vector3> _current, _estimated, _modelDiff, _equationDiff,
_fromPosDiff, _flowDiff, _spherical;
mwoibn::Vector3 _ground, _wheel_axis, _x;
mwoibn::Matrix3 _skew(mwoibn::Vector3 vec)
{
mwoibn::Matrix3 skew;
skew << 0, -vec[2], vec[1], vec[2], 0, -vec[0], -vec[1], vec[0], 0;
// std::cout << skew << std::endl;
return skew;
}
void _sphericalPoints()
{
for (int i = 0; i < _wheels.size(); i++)
_sphericalPoint(i);
}
void _sphericalPoint(int i)
{
_spherical[i] = _robot.contacts().contact(i).getPosition().head(3);
}
void _contactPoints()
{
for (int i = 0; i < _wheels.size(); i++)
_contactPoint(i);
}
void _modelDerivatives()
{
for (int i = 0; i < _wheels.size(); i++)
_modelDerivative(i);
}
void _modelDerivative(int i)
{
mwoibn::Matrix jacobian = _contacts.point(i).getPositionJacobian();
_modelDiff[i] =
jacobian *
_robot.state.velocity.get(); // *
//_robot.rate();
}
void _contactPoint(int i)
{
_wheel_axis = _wheels.point(i).getRotationWorld().col(2); // z axis
_x = _wheel_axis * _ground.transpose() * _wheel_axis;
_x.normalize();
std::cout << "norm: " << _x.norm() << std::endl;
_current[i] = _x * R - _ground * (r + R);
_current[i] += _wheels.getPointStateWorld(i);
}
void _equationDerivatives()
{
for (int i = 0; i < _wheels.size(); i++)
_equationDerivative(i);
}
void _equationDerivative(int i)
{
_wheel_axis = _wheels.point(i).getRotationWorld().col(2); // z axis
mwoibn::Matrix jacobian = _wheels.point(i).getOrientationJacobian();
mwoibn::Matrix jacobian_pos = _wheels.point(i).getPositionJacobian();
mwoibn::Matrix3 temp =
-_skew(_current[i] - _wheels.getPointStateWorld(i));
// temp = temp * R;
// temp += _skew(_ground) * r;
_equationDiff[i] =
jacobian * _robot.state.velocity.get();
_equationDiff[i] = temp * _equationDiff[i];
_equationDiff[i] +=
jacobian_pos *
_robot.state.velocity.get();
//_equationDiff[i] = _equationDiff[i] * _robot.rate();
}
void _flowEstimates()
{
for (int i = 0; i < _wheels.size(); i++)
_flowEstimate(i);
}
void _flowEstimate(int i) {
_estimated[i] += _flowDiff[i] * _robot.rate();
}
void _flowDerivatives()
{
for (int i = 0; i < _wheels.size(); i++)
_flowDerivative(i);
}
void _flowDerivative(int i)
{
_wheel_axis = _wheels.point(i).getRotationWorld().col(2); // z axis
mwoibn::Matrix jacobian = _wheels.point(i).getOrientationJacobian();
mwoibn::Matrix jacobian_pos = _wheels.point(i).getPositionJacobian();
mwoibn::Matrix3 temp =
-_skew(_wheel_axis * _ground.transpose() * _wheel_axis);
temp -= _wheel_axis * _ground.transpose() * _skew(_wheel_axis);
// if (i == 0)
// {
// mwoibn::Matrix3 temp1 =
// -_skew(_wheel_axis * _ground.transpose() * _wheel_axis);
// mwoibn::Vector3 vec1 =
// temp1 * jacobian *
// _robot.state.velocity.get();
// std::cout << "1\t" << vec1[0] << "\t" << vec1[1] << "\t" << vec1[2]
// << "\n";
// temp1 = -_wheel_axis * _ground.transpose() * _skew(_wheel_axis);
// vec1 = temp1 * jacobian *
// _robot.state.velocity.get();
// std::cout << "2\t" << vec1[0] << "\t" << vec1[1] << "\t" << vec1[2]
// << "\n";
// }
_flowDiff[i] =
jacobian * _robot.state.velocity.get();
_flowDiff[i] = temp * _flowDiff[i];
_flowDiff[i] = _flowDiff[i] * R;
_flowDiff[i] += jacobian_pos *
_robot.state.velocity.get();
}
};
int main(int argc, char** argv)
{
static const mwoibn::visualization_tools::Utils::TYPE tracker_type =
mwoibn::visualization_tools::Utils::TYPE::POINT;
ros::init(argc, argv,
"contacts_test"); // initalize node needed for the service
ros::NodeHandle n;
ros::Publisher pub;
std::string path = std::string(DRIVING_FRAMEWORK_WORKSPACE);
mwoibn::loaders::Robot loader;
mwoibn::robot_class::Robot& robot = loader.init(
path + "DrivingFramework/locomotion_framework/configs/mwoibn_v2.yaml",
"simulated");
mwoibn::point_handling::PositionsHandler wheels_ph("ROOT", robot,
robot.getLinks("wheels"));
mwoibn::visualization_tools::RvizTrackPoint track_current("rviz/current");
mwoibn::visualization_tools::RvizTrackPoint track_new("rviz/new");
mwoibn::visualization_tools::RvizTrackPoint track_estimated("rviz/estimated");
Flow flow(robot, wheels_ph);
double edge = 0.001;
for (int i = 0; i < robot.contacts().size(); i++)
{
// RED: current equation
track_current.initMarker(tracker_type, "world", edge, edge, edge);
// GREEN: new equation
track_new.initMarker(tracker_type, "world", edge, edge, edge);
// BLUE: estimated new
track_estimated.initMarker(tracker_type, "world", edge, edge, edge);
}
for (int i = 0; i < robot.contacts().size(); i++)
{
track_current.setColor(i, 1, 0, 0);
track_new.setColor(i, 0, 1, 0);
track_estimated.setColor(i, 1, 1, 0);
}
std::cout.precision(10);
std::cout << std::fixed;
// std::cout
// << "1_new[x]\t1_new[y]\t1_new[z]\t1_simp[x]\t1_simp[y]\t1_simp[z]\t";
// std::cout
// << "1_mdt[x]\t1_mdt[y]\t1_mdt[z]\t1_edt[x]\t1_edt[y]\t1_edt[z]\t";
// std::cout
// << "2_new[x]\t2_new[y]\t2_new[z]\t2_simp[x]\t2_simp[y]\t2_simp[z]\t";
// std::cout
// << "2_mdt[x]\t2_mdt[y]\t2_mdt[z]\t2_edt[x]\t2_edt[y]\t2_edt[z]\t";
// std::cout
// << "3_new[x]\t3_new[y]\t3_new[z]\t3_simp[x]\t3_simp[y]\t3_simp[z]\t";
// std::cout
// << "3_mdt[x]\t3_mdt[y]\t3_mdt[z]\t3_edt[x]\t3_edt[y]\t3_edt[z]\t";
// std::cout
// << "4_new[x]\t4_new[y]\t4_new[z]\t4_simp[x]\t4_simp[y]\t4_simp[z]\t";
// std::cout
// << "4_mdt[x]\t4_mdt[y]\t4_mdt[z]\t4_edt[x]\t4_edt[y]\t4_edt[z]\n";
int i = 0;
while (ros::ok())
{
// std::vector<mwoibn::Vector3> new_contacts = contactPoints(robot,
// wheels_ph);
for (int i = 0; i < wheels_ph.size(); i++)
{
track_current.updateMarker(i, flow.getSpherical(i));
track_new.updateMarker(i, flow.getContact(i));
track_estimated.updateMarker(i, flow.getEstimate(i));
// std::cout << flow.getContact(i)[0] << "\t" <<
// flow.getContact(i)[1]
// << "\t" << flow.getContact(i)[2] << "\t";
// std::cout << flow.getEstimate(i)[0] << "\t" <<
// flow.getEstimate(i)[1]
// << "\t" << flow.getEstimate(i)[2] << "\t";
// std::cout << flow.getModelDiff(i)[0] << "\t" <<
// flow.getModelDiff(i)[1]
// << "\t" << flow.getModelDiff(i)[2] << "\t";
// std::cout << flow.getEquationDiff(i)[0] << "\t" <<
// flow.getEquationDiff(i)[1]
// << "\t" << flow.getEquationDiff(i)[2] << "\t";
}
std::cout << std::endl;
flow.update();
track_estimated.publish();
track_current.publish();
track_new.publish();
robot.update();
}
}
| 33.342365 | 95 | 0.492945 | ADVRHumanoids |
a840ed153da786ca61ed206500aa281b57cb970d | 5,840 | cpp | C++ | src/states/IntroState.cpp | CEDV-2016/arrow | 512c5875bcefa3ae09614609f4a2f69f5df467ed | [
"MIT"
] | null | null | null | src/states/IntroState.cpp | CEDV-2016/arrow | 512c5875bcefa3ae09614609f4a2f69f5df467ed | [
"MIT"
] | null | null | null | src/states/IntroState.cpp | CEDV-2016/arrow | 512c5875bcefa3ae09614609f4a2f69f5df467ed | [
"MIT"
] | null | null | null | #include "IntroState.hpp"
#include "MainState.hpp"
template<> IntroState* Ogre::Singleton<IntroState>::msSingleton = 0;
IntroState::IntroState():
_physicsMgr(NULL),
_mapMgr(NULL),
_overlayMgr(NULL),
_cameraMgr(NULL),
_shootMgr(NULL),
_collisionMgr(NULL),
_characterMgr(NULL)
{}
void
IntroState::enter ()
{
if (_root == NULL)
{
_root = Ogre::Root::getSingletonPtr();
}
if (_sceneMgr == NULL)
{
_sceneMgr = _root->getSceneManager("SceneManager");
}
if (_camera == NULL)
{
_camera = _sceneMgr->createCamera("MainCamera");
}
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().hide();
_viewport = _root->getAutoCreatedWindow()->addViewport(_camera);
_viewport->setBackgroundColour(Ogre::ColourValue(0.3, 0.8, 0.8));
// Creating and placing camera
_camera->setPosition( Ogre::Vector3(0, 0, 10) );
_camera->lookAt( Ogre::Vector3(0, 0, 8) );
_camera->setNearClipDistance(0.001);
_camera->setFarClipDistance(1000);
_camera->setFOVy(Ogre::Degree(38));
double width = _viewport->getActualWidth();
double height = _viewport->getActualHeight();
_camera->setAspectRatio(width / height);
_sceneMgr->setAmbientLight( Ogre::ColourValue(1, 1, 1) );
_sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
_sceneMgr->setShadowTextureCount(30);
_sceneMgr->setShadowTextureSize(512);
initializeManagers();
createGUI();
loadBackgroundImage();
_exitGame = false;
}
void IntroState::initializeManagers()
{
if (_physicsMgr == NULL)
{
_physicsMgr = new MyPhysicsManager( _sceneMgr );
}
if (_mapMgr == NULL)
{
_mapMgr = new MapManager( _sceneMgr, MyPhysicsManager::getSingletonPtr()->getPhysicWorld() );
}
if (_overlayMgr == NULL)
{
_overlayMgr = new MyOverlayManager();
}
if (_cameraMgr == NULL)
{
_cameraMgr = new CameraManager( _sceneMgr );
}
if (_shootMgr == NULL)
{
_shootMgr = new ShootManager( _sceneMgr );
}
if (_collisionMgr == NULL)
{
_collisionMgr = new MyCollisionManager( _sceneMgr );
}
if (_characterMgr == NULL)
{
_characterMgr = new CharacterManager( _sceneMgr );
}
}
void
IntroState::exit()
{
_sceneMgr->clearScene();
_root->getAutoCreatedWindow()->removeAllViewports();
}
void
IntroState::pause ()
{
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();
Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->hide();
_intro->hide();
}
void
IntroState::resume ()
{
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().hide();
Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->show();
_intro->show();
}
bool
IntroState::frameStarted
(const Ogre::FrameEvent& evt)
{
MapManager::getSingletonPtr()->update( evt.timeSinceLastFrame );
return true;
}
bool
IntroState::frameEnded
(const Ogre::FrameEvent& evt)
{
if (_exitGame)
return false;
return true;
}
void
IntroState::keyPressed
(const OIS::KeyEvent &e)
{
}
void
IntroState::keyReleased
(const OIS::KeyEvent &e )
{
if (e.key == OIS::KC_ESCAPE)
{
_exitGame = true;
}
else if (e.key == OIS::KC_SPACE)
{
pushState(MainState::getSingletonPtr());
}
}
void
IntroState::mouseMoved
(const OIS::MouseEvent &e)
{
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(e.state.X.abs, e.state.Y.abs);
}
void
IntroState::mousePressed
(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
}
void
IntroState::mouseReleased
(const OIS::MouseEvent &e, OIS::MouseButtonID id)
{
}
IntroState*
IntroState::getSingletonPtr ()
{
return msSingleton;
}
IntroState&
IntroState::getSingleton ()
{
assert(msSingleton);
return *msSingleton;
}
void IntroState::createGUI()
{
if(_intro == NULL)
{
_intro = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("splash.layout");
CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->addChild(_intro);
}
else
{
_intro->show();
}
Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->show();
}
void IntroState::loadBackgroundImage()
{
// Randmonly select background
std::string _all_backgrounds[3] {"oil.jpg", "cubism.jpg", "glass.jpg"};
unsigned seed = std::time(0);
std::srand(seed);
std::random_shuffle(&_all_backgrounds[0], &_all_backgrounds[sizeof(_all_backgrounds)/sizeof(*_all_backgrounds)]);
Ogre::TexturePtr m_backgroundTexture = Ogre::TextureManager::getSingleton().createManual("BackgroundTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,640, 480, 0, Ogre::PF_BYTE_BGR,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
Ogre::Image m_backgroundImage;
m_backgroundImage.load(_all_backgrounds[0], Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
m_backgroundTexture->loadImage(m_backgroundImage);
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("BackgroundMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
material->getTechnique(0)->getPass(0)->createTextureUnitState("BackgroundTexture");
material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
_rect = new Ogre::Rectangle2D(true);
_rect->setCorners(-1.0, 1.0, 1.0, -1.0);
_rect->setMaterial("BackgroundMaterial");
_rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND);
_rect->setBoundingBox(Ogre::AxisAlignedBox(-100000.0*Ogre::Vector3::UNIT_SCALE, 100000.0*Ogre::Vector3::UNIT_SCALE));
_backgroundNode = _sceneMgr->getRootSceneNode()->createChildSceneNode("BackgroundMenu");
_backgroundNode->attachObject(_rect);
MapManager::getSingletonPtr()->fadeIn();
}
| 26.188341 | 259 | 0.693836 | CEDV-2016 |
a842b886c04195753104f238791fe553759048cb | 391 | cpp | C++ | 101/strings/string_adjacent_find.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | 2 | 2021-04-21T07:59:45.000Z | 2021-05-13T05:53:00.000Z | 101/strings/string_adjacent_find.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | null | null | null | 101/strings/string_adjacent_find.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | 1 | 2021-04-17T15:32:18.000Z | 2021-04-17T15:32:18.000Z | #include "../../headers.h"
/*
* Something to remember here is that:
* all these functions - take iterators as I/P's.
* But iterators are more like pointers and they v
* can be incremented or decremented
*/
int main()
{
string s = "accenllt";
string::iterator it = adjacent_find(s.begin()+2,s.end());
cout << "The result is: " << it - s.begin() << endl;
return 0;
} | 24.4375 | 61 | 0.621483 | hariharanragothaman |
61b41538e3a47fea982a03c17debc8f290f63c45 | 935 | cpp | C++ | VBoxLayout.cpp | Evgenii-Evgenevich/qt-the-interface | 0d12d110b09b5ff9c52adc7da70104b219220267 | [
"Apache-2.0"
] | null | null | null | VBoxLayout.cpp | Evgenii-Evgenevich/qt-the-interface | 0d12d110b09b5ff9c52adc7da70104b219220267 | [
"Apache-2.0"
] | null | null | null | VBoxLayout.cpp | Evgenii-Evgenevich/qt-the-interface | 0d12d110b09b5ff9c52adc7da70104b219220267 | [
"Apache-2.0"
] | null | null | null | #include "VBoxLayout.h"
#include <QVBoxLayout>
#include <QPoint>
VBoxLayout::VBoxLayout()
: VBoxLayout(nullptr)
{
}
VBoxLayout::VBoxLayout(QWidget* parent)
: QWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setAlignment(Qt::AlignTop);
layout->setSpacing(0);
}
void VBoxLayout::add(QWidget* widget)
{
widget->setParent(this);
layout()->addWidget(widget);
}
void VBoxLayout::drop(QWidget* widget, QPoint pos)
{
QVBoxLayout* m_layout = static_cast<QVBoxLayout*>(layout());
pos.setX(width() / 2);
if (QWidget* child = childAt(pos))
{
if (child == widget) return;
int idx = m_layout->indexOf(child);
int const x = pos.x() - child->pos().x();
int const h = child->height() / 2;
if (x > h) ++idx;
m_layout->insertWidget(idx, widget);
}
else
{
m_layout->addWidget(widget);
}
widget->setParent(this);
}
void VBoxLayout::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
}
| 19.479167 | 61 | 0.685561 | Evgenii-Evgenevich |
61b647543eaf0c661aefaba8d2b1ee2acb064019 | 15,267 | cpp | C++ | src/world.cpp | bplaat/vroemvroem | 22cf628b4e4e0e3dd9a7008af21f4288ec5ea7a4 | [
"MIT"
] | 1 | 2020-11-01T10:26:09.000Z | 2020-11-01T10:26:09.000Z | src/world.cpp | bplaat/vroemvroem | 22cf628b4e4e0e3dd9a7008af21f4288ec5ea7a4 | [
"MIT"
] | null | null | null | src/world.cpp | bplaat/vroemvroem | 22cf628b4e4e0e3dd9a7008af21f4288ec5ea7a4 | [
"MIT"
] | null | null | null | // VroemVroem - World
#include "world.hpp"
#include "noise.hpp"
#include "objects/terrain.hpp"
#include "objects/driver.hpp"
#include "utils.hpp"
#include "config.hpp"
#include "timer.hpp"
#include <map>
#include <cmath>
World::World(uint64_t seed, int width, int height)
: seed(seed), width(width), height(height)
{
random = std::make_unique<Random>(seed);
terrainMap = std::make_unique<uint8_t[]>(height * width);
objectMap = std::make_unique<uint8_t[]>(height * width);
FastNoiseLite heightNoise;
heightNoise.SetNoiseType(FastNoiseLite::NoiseType_OpenSimplex2);
heightNoise.SetSeed(seed);
FastNoiseLite objectsNoise;
objectsNoise.SetNoiseType(FastNoiseLite::NoiseType_OpenSimplex2);
objectsNoise.SetSeed(seed + 1);
// Generate terrain and natures
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
float h = heightNoise.GetNoise((float)x, (float)y);
float o = objectsNoise.GetNoise((float)x, (float)y);
if (h >= 0.9) {
terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::SNOW1), static_cast<int>(Objects::Terrain::Type::SNOW2));
}
else if (h >= 0.8) {
if (o >= 0.2 && random->random(1, 6) == 1) {
natures.push_back(std::make_unique<Objects::Nature>(natures.size(), Objects::Nature::Type::GOLD, x + 0.5, y + 0.5));
objectMap[y * width + x] = 1;
}
else if (o < 0.2 && random->random(1, 6) == 1) {
natures.push_back(std::make_unique<Objects::Nature>(natures.size(), Objects::Nature::Type::STONE, x + 0.5, y + 0.5));
objectMap[y * width + x] = 1;
}
terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::STONE1), static_cast<int>(Objects::Terrain::Type::STONE2));
}
else if (h >= 0.7) {
terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::DIRT1), static_cast<int>(Objects::Terrain::Type::DIRT2));
}
else if (h >= 0.1) {
if (h >= 0.4 && o >= 0.3 && random->random(1, random->random(1, 2)) == 1) {
if (random->random(1, 4) <= 3) {
natures.push_back(std::make_unique<Objects::Nature>(
natures.size(),
static_cast<Objects::Nature::Type>(random->random(static_cast<int>(Objects::Nature::Type::BEECH), static_cast<int>(Objects::Nature::Type::FIR_SMALL))),
x + 0.5,
y + 0.5
));
} else {
natures.push_back(std::make_unique<Objects::Nature>(
natures.size(),
static_cast<Objects::Nature::Type>(random->random(static_cast<int>(Objects::Nature::Type::TRUNK), static_cast<int>(Objects::Nature::Type::TRUNK_SMALL))),
x + 0.5,
y + 0.5
));
}
objectMap[y * width + x] = 1;
}
else if (o < 0.4 && random->random(1, 15) == 1) {
natures.push_back(std::make_unique<Objects::Nature>(
natures.size(),
static_cast<Objects::Nature::Type>(random->random(static_cast<int>(Objects::Nature::Type::BUSHES), static_cast<int>(Objects::Nature::Type::BERRIES))),
x + 0.5,
y + 0.5
));
objectMap[y * width + x] = 1;
}
terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::GRASS1), static_cast<int>(Objects::Terrain::Type::GRASS2));
}
else if (h >= -0.1) {
terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::SAND1), static_cast<int>(Objects::Terrain::Type::SAND2));
}
else if (h >= -0.6) {
terrainMap[y * width + x] = static_cast<int>(Objects::Terrain::Type::WATER);
}
else {
terrainMap[y * width + x] = static_cast<int>(Objects::Terrain::Type::WATER_DEEP);
}
}
}
// Generate cities
for (int i = 0; i < sqrt(height * width) / 3; i++) {
int x;
int y;
do {
x = random->random(0, width - 1);
y = random->random(0, height - 1);
} while (terrainMap[y * width + x] <= 2);
cities.push_back(std::make_unique<Objects::City>(cities.size(), Objects::City::randomName(random.get()), x + 0.5, y + 0.5, 0));
}
// Generate houses
for (auto &city : cities) {
int target_population = random->random(50, random->random(100, random->random(200, random->random(300, 1000))));
int spread = ceil(target_population / random->random(20, random->random(20, 30)));
for (int j = 0; j < ceil(target_population / 4); j++) {
int x;
int y;
int attempt = 0;
do {
x = (int)city->getX() + random->random(-spread, spread);
y = (int)city->getY() + random->random(-spread, spread);
attempt++;
} while (!(
attempt == spread ||
(
x >= 0 && y >= 0 && x < width && y < height &&
terrainMap[y * width + x] >= static_cast<int>(Objects::Terrain::Type::SAND1) &&
objectMap[y * width + x] == 0
)
));
if (attempt == spread) {
continue;
}
int population = random->random(2, 6);
houses.push_back(std::make_unique<Objects::House>(
houses.size(),
static_cast<Objects::House::Type>(random->random(static_cast<int>(Objects::House::Type::HOUSE), static_cast<int>(Objects::House::Type::SHOP))),
x + 0.5,
y + 0.5,
population
));
objectMap[y * width + x] = 1;
city->setPopulation(city->getPopulation() + population);
}
}
// Generate roads
std::map<int, int> cityCount;
for (size_t i = 0; i < cities.size() / 8; i++) {
Objects::City *city = cities.at(random->random(0, cities.size() - 1)).get();
int lanes = random->random(1, random->random(1, 3));
for (size_t j = 0; j < cities.size() / 8; j++) {
Objects::City *otherCity;
size_t attempt = 0;
do {
otherCity = cities.at(random->random(0, cities.size() - 1)).get();
attempt++;
} while (!(
attempt == cities.size() * 2 ||
(
sqrt(
(city->getX() - otherCity->getX()) * (city->getX() - otherCity->getX()) +
(city->getY() - otherCity->getY()) * (city->getY() - otherCity->getY())
) < 75 &&
cityCount[otherCity->getId()] < 2
)
));
if (attempt == cities.size() * 2) {
break;
}
roads.push_back(std::make_unique<Objects::Road>(
roads.size(),
city->getX(),
city->getY(),
otherCity->getX(),
otherCity->getY(),
lanes,
random->random(60, 120)
));
cityCount[city->getId()]++;
cityCount[otherCity->getId()]++;
city = otherCity;
}
}
// Create start vehicles
for (size_t i = 0; i < cities.size(); i++) {
addVehicle();
}
// Start vehicle timer
vehicleTimer = SDL_AddTimer(Config::vehicleTimeout, Timer::callback, reinterpret_cast<void *>(vehicleTimerEventCode));
}
uint64_t World::getSeed() const {
return seed;
}
int World::getWidth() const {
return width;
}
int World::getHeight() const {
return height;
}
std::vector<const Objects::Nature *> World::getNatures() const {
std::vector<const Objects::Nature *> naturePointers;
for (auto const &nature : natures) {
naturePointers.push_back(nature.get());
}
return naturePointers;
}
std::vector<const Objects::House *> World::getHouses() const {
std::vector<const Objects::House *> housePointers;
for (auto const &house : houses) {
housePointers.push_back(house.get());
}
return housePointers;
}
std::vector<const Objects::City *> World::getCities() const {
std::vector<const Objects::City *> cityPointers;
for (auto const &city : cities) {
cityPointers.push_back(city.get());
}
return cityPointers;
}
std::vector<const Objects::Road *> World::getRoads() const {
std::vector<const Objects::Road *> roadPointers;
for (auto const &road : roads) {
roadPointers.push_back(road.get());
}
return roadPointers;
}
std::vector<const Objects::Vehicle *> World::getVehicles() const {
std::vector<const Objects::Vehicle *> vehiclePointers;
for (auto const &vehicle : vehicles) {
vehiclePointers.push_back(vehicle.get());
}
return vehiclePointers;
}
std::vector<const Objects::Explosion *> World::getExplosions() const {
std::vector<const Objects::Explosion *> explosionPointers;
for (auto const &explosion : explosions) {
explosionPointers.push_back(explosion.get());
}
return explosionPointers;
}
bool World::handleEvent(const SDL_Event *event) {
// Pass event to explosions
for (auto const &explosion : explosions) {
if (explosion->handleEvent(event)) {
return true;
}
}
// Create vehicle on timer
if (event->type == SDL_USEREVENT && event->user.code == vehicleTimerEventCode) {
for (size_t i = 0; i < cities.size() / 4; i++) {
addVehicle();
}
return true;
}
return false;
}
void World::update(float delta) {
// Update vehicles
for (auto &vehicle : vehicles) {
vehicle->update(delta);
}
// Check collision
for (auto &vehicle : vehicles) {
if (vehicle->getDriver() && !vehicle->getDriver()->isArrived()) {
for (auto &otherVehicle : vehicles) {
if (vehicle->getId() != otherVehicle->getId()) {
if (otherVehicle->getDriver() && !otherVehicle->getDriver()->isArrived()) {
if (
sqrt(
(vehicle->getX() - otherVehicle->getX()) * (vehicle->getX() - otherVehicle->getX()) +
(vehicle->getY() - otherVehicle->getY()) * (vehicle->getY() - otherVehicle->getY())
) < 1
) {
vehicle->crash();
otherVehicle->crash();
explosions.push_back(std::make_unique<Objects::Explosion>(
explosions.size(),
static_cast<Objects::Explosion::Type>(random->random(static_cast<int>(Objects::Explosion::Type::FIRE), static_cast<int>(Objects::Explosion::Type::SMOKE))),
vehicle->getX(),
vehicle->getY()
));
}
}
}
}
}
}
}
void World::draw(std::shared_ptr<Canvas> canvas, const Camera *camera) const {
std::unique_ptr<Rect> canvasRect = canvas->getRect();
// Draw terrain tiles
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int tileSize = Camera::zoomLevels[camera->getZoom()];
Rect tileRect = {
(int)(x * tileSize - (camera->getX() * tileSize - canvasRect->width / 2)),
(int)(y * tileSize - (camera->getY() * tileSize - canvasRect->height / 2)),
tileSize,
tileSize
};
if (canvasRect->collides(&tileRect)) {
Objects::Terrain::getImage(static_cast<Objects::Terrain::Type>(terrainMap[y * width + x]))->draw(&tileRect);
}
}
}
// Draw natures
for (auto const &nature : natures) {
nature->draw(canvas, camera);
}
// Draw houses
for (auto const &house : houses) {
house->draw(canvas, camera);
}
// Draw roads
for (auto const &road : roads) {
road->draw(canvas, camera);
}
// Draw not arrived vehicles
for (auto const &vehicle : vehicles) {
const Objects::Driver *driver = vehicle->getDriver();
if (driver && !driver->isArrived()) {
vehicle->draw(canvas, camera);
}
}
// Draw explosions
for (auto const &explosion : explosions) {
explosion->draw(canvas, camera);
}
// Draw cities
for (auto const &city : cities) {
city->draw(canvas, camera);
}
}
void World::addVehicle() {
Objects::City *city = cities.at(random->random(0, cities.size() - 1)).get();
float x = 0;
float y = 0;
float destinationX = 0;
float destinationY = 0;
int lanes;
for (const auto &road : roads) {
if (random->random(1, 2) == 1 && road->getX() == city->getX() && road->getY() == city->getY()) {
x = road->getX() + 0.5;
y = road->getY() + 0.5;
destinationX = road->getEndX() + 0.5;
destinationY = road->getEndY() + 0.5;
lanes = road->getLanes();
break;
}
if (random->random(1, 2) == 1 && road->getEndX() == city->getX() && road->getEndY() == city->getY()) {
x = road->getEndX() + 0.5;
y = road->getEndY() + 0.5;
destinationX = road->getX() + 0.5;
destinationY = road->getY() + 0.5;
lanes = road->getLanes();
break;
}
}
if (destinationX == 0) {
return;
}
if (abs(x - destinationX) > abs(y - destinationY)) {
y -= lanes - random->random(0, lanes);
destinationY -= lanes - random->random(0, lanes);
} else {
x -= lanes - random->random(0, lanes);
destinationX -= lanes - random->random(0, lanes);
}
float angle = atan2(y - destinationY, x - destinationX);
std::unique_ptr<Objects::Vehicle> vehicle = std::make_unique<Objects::Vehicle>(
vehicles.size(),
static_cast<Objects::Vehicle::Type>(random->random(static_cast<int>(Objects::Vehicle::Type::STANDARD), static_cast<int>(Objects::Vehicle::Type::MOTOR_CYCLE))),
x,
y,
static_cast<Objects::Vehicle::Color>(random->random(static_cast<int>(Objects::Vehicle::Color::BLACK), static_cast<int>(Objects::Vehicle::Color::YELLOW))),
angle
);
vehicle->setDriver(std::move(std::make_unique<Objects::Driver>(vehicle.get(), destinationX, destinationY)));
vehicles.push_back(std::move(vehicle));
}
| 35.504651 | 187 | 0.510906 | bplaat |
61b65a186189ac6441e0e7609a22f179ba4fc99c | 813 | hpp | C++ | include/ptk/util/Math.hpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | include/ptk/util/Math.hpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | include/ptk/util/Math.hpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | //
// util/Math.hpp
// pTK
//
// Created by Robin Gustafsson on 2021-12-11.
//
#ifndef PTK_UTIL_MATH_HPP
#define PTK_UTIL_MATH_HPP
// C++ Headers
#include <cmath>
#include <string>
namespace pTK
{
/** This file is purely for the need of math functions.
Since in Linux apparently some math functions, like ceilf
are defined in the global namespace and not in std.
*/
namespace Math
{
static inline float ceilf(float arg)
{
// This is apparently needed in Linux.
// Since, ceilf is in the global namespace?!
// Can't use std::ceilf.
using namespace std;
// This will call whatever is defined outside this function.
return ::ceilf(arg);
}
}
}
#endif // PTK_UTIL_MATH_HPP
| 19.357143 | 72 | 0.601476 | Knobin |
61b7f2e8c315ca859282984ab3bab03a08b60802 | 15,876 | inl | C++ | Library/Sources/Stroika/Foundation/Streams/SharedMemoryStream.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Library/Sources/Stroika/Foundation/Streams/SharedMemoryStream.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Library/Sources/Stroika/Foundation/Streams/SharedMemoryStream.inl | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_SharedMemoryStream_inl_
#define _Stroika_Foundation_Streams_SharedMemoryStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <mutex>
#include "../Execution/WaitableEvent.h"
namespace Stroika::Foundation::Streams {
/*
********************************************************************************
******************* SharedMemoryStream<ELEMENT_TYPE>::Rep_ *********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class SharedMemoryStream<ELEMENT_TYPE>::Rep_ : public InputOutputStream<ELEMENT_TYPE>::_IRep {
public:
using ElementType = ELEMENT_TYPE;
private:
bool fIsOpenForRead_{true};
public:
Rep_ ()
: fData_{}
, fReadCursor_{fData_.begin ()}
, fWriteCursor_{fData_.begin ()}
{
}
Rep_ (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: Rep_{}
{
Write (start, end);
}
Rep_ (const Rep_&) = delete;
~Rep_ () = default;
nonvirtual Rep_& operator= (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
return true;
}
virtual void CloseWrite () override
{
Require (IsOpenWrite ());
{
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
fClosedForWrites_ = true;
}
fMoreDataWaiter_.Set ();
}
virtual bool IsOpenWrite () const override
{
return not fClosedForWrites_;
}
virtual void CloseRead () override
{
Require (IsOpenRead ());
fIsOpenForRead_ = false;
}
virtual bool IsOpenRead () const override
{
return fIsOpenForRead_;
}
virtual size_t Read (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
Require (IsOpenRead ());
size_t nRequested = intoEnd - intoStart;
tryAgain:
fMoreDataWaiter_.Wait ();
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; // hold lock for everything EXCEPT wait
Assert ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
size_t nAvail = fData_.end () - fReadCursor_;
if (nAvail == 0 and not fClosedForWrites_) {
fMoreDataWaiter_.Reset (); // ?? @todo consider - is this a race? If we reset at same time(apx) as someone else sets
goto tryAgain; // cannot wait while we hold lock
}
size_t nCopied = min (nAvail, nRequested);
{
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#else
copy (fReadCursor_, fReadCursor_ + nCopied, intoStart);
#endif
fReadCursor_ = fReadCursor_ + nCopied;
}
return nCopied; // this can be zero on EOF
}
virtual optional<size_t> ReadNonBlocking (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
Require (IsOpenRead ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
size_t nDefinitelyAvail = fData_.end () - fReadCursor_;
if (nDefinitelyAvail > 0) {
return this->_ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, nDefinitelyAvail);
}
else if (fClosedForWrites_) {
return this->_ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, 0);
}
else {
return {}; // if nothing available, but not closed for write, no idea if more to come
}
}
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
Require (start != nullptr or start == end);
Require (end != nullptr or start == end);
Require (IsOpenWrite ());
if (start != end) {
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
size_t roomLeft = fData_.end () - fWriteCursor_;
size_t roomRequired = end - start;
fMoreDataWaiter_.Set (); // just means MAY be more data - readers check
if (roomLeft < roomRequired) {
size_t curReadOffset = fReadCursor_ - fData_.begin ();
size_t curWriteOffset = fWriteCursor_ - fData_.begin ();
const size_t kChunkSize_ = 128; // WAG: @todo tune number...
Containers::ReserveSpeedTweekAddN (fData_, roomRequired - roomLeft, kChunkSize_);
fData_.resize (curWriteOffset + roomRequired);
fReadCursor_ = fData_.begin () + curReadOffset;
fWriteCursor_ = fData_.begin () + curWriteOffset;
Assert (fWriteCursor_ < fData_.end ());
}
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (start, start + roomRequired, fWriteCursor_);
#else
copy (start, start + roomRequired, fWriteCursor_);
#endif
fWriteCursor_ += roomRequired;
Assert (fReadCursor_ < fData_.end ()); // < because we wrote at least one byte and that didnt move read cursor
Assert (fWriteCursor_ <= fData_.end ());
}
}
virtual void Flush () override
{
// nothing todo - write 'writes thru'
}
virtual SeekOffsetType GetReadOffset () const override
{
Require (IsOpenRead ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
Require (IsOpenRead ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
fMoreDataWaiter_.Set (); // just means MAY be more data - readers check
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
SeekOffsetType uOffset = static_cast<SeekOffsetType> (offset);
if (uOffset > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uOffset);
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fReadCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
} break;
case Whence::eFromEnd: {
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset);
if (uNewOffset > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset);
} break;
}
Ensure ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ()));
return fReadCursor_ - fData_.begin ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
Require (IsOpenWrite ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return fWriteCursor_ - fData_.begin ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
Require (IsOpenWrite ());
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
fMoreDataWaiter_.Set (); // just means MAY be more data - readers check
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
if (static_cast<SeekOffsetType> (offset) > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (offset);
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fWriteCursor_ - fData_.begin ();
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
if (static_cast<size_t> (newOffset) > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
} break;
case Whence::eFromEnd: {
Streams::SignedSeekOffsetType newOffset = fData_.size () + offset;
if (newOffset < 0) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
if (static_cast<size_t> (newOffset) > fData_.size ()) [[UNLIKELY_ATTR]] {
Execution::Throw (range_error{"seek"});
}
fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset);
} break;
}
Ensure ((fData_.begin () <= fWriteCursor_) and (fWriteCursor_ <= fData_.end ()));
return fWriteCursor_ - fData_.begin ();
}
vector<ElementType> AsVector () const
{
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return fData_;
}
string AsString () const
{
[[maybe_unused]] auto&& critSec = lock_guard{fMutex_};
return string (reinterpret_cast<const char*> (Containers::Start (fData_)), reinterpret_cast<const char*> (Containers::End (fData_)));
}
private:
mutable recursive_mutex fMutex_;
Execution::WaitableEvent fMoreDataWaiter_{Execution::WaitableEvent::eManualReset}; // not a race cuz always set/reset when holding fMutex; no need to pre-set cuz auto set when someone adds data (Write)
vector<ElementType> fData_;
typename vector<ElementType>::iterator fReadCursor_;
typename vector<ElementType>::iterator fWriteCursor_;
bool fClosedForWrites_{false};
};
/*
********************************************************************************
********************** SharedMemoryStream<ELEMENT_TYPE> ************************
********************************************************************************
*/
DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wattributes\"")
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New ([[maybe_unused]] Execution::InternallySynchronized internallySynchronized) -> Ptr
{
// always return internally synchronized rep
return make_shared<Rep_> ();
}
DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wattributes\"")
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) -> Ptr
{
return make_shared<Rep_> (start, end);
}
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (Execution::InternallySynchronized internallySynchronized, const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) -> Ptr
{
return New (start, end);
}
template <typename ELEMENT_TYPE>
template <typename TEST_TYPE, enable_if_t<is_same_v<TEST_TYPE, byte>>*>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (const Memory::BLOB& blob) -> Ptr
{
return New (blob.begin (), blob.end ());
}
template <typename ELEMENT_TYPE>
template <typename TEST_TYPE, enable_if_t<is_same_v<TEST_TYPE, byte>>*>
inline auto SharedMemoryStream<ELEMENT_TYPE>::New (Execution::InternallySynchronized internallySynchronized, const Memory::BLOB& blob) -> Ptr
{
return New (blob.begin (), blob.end ());
}
/*
********************************************************************************
****************** SharedMemoryStream<ELEMENT_TYPE>::Ptr ***********************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline SharedMemoryStream<ELEMENT_TYPE>::Ptr::Ptr (const shared_ptr<Rep_>& from)
: inherited{from}
{
}
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::Ptr::GetRepConstRef_ () const -> const Rep_&
{
// reinterpret_cast faster than dynamic_cast - check equivalent
Assert (dynamic_cast<const Rep_*> (&inherited::_GetRepConstRef ()) == reinterpret_cast<const Rep_*> (&inherited::_GetRepConstRef ()));
return *reinterpret_cast<const Rep_*> (&inherited::_GetRepConstRef ());
}
template <typename ELEMENT_TYPE>
inline auto SharedMemoryStream<ELEMENT_TYPE>::Ptr::GetRepRWRef_ () const -> Rep_&
{
// reinterpret_cast faster than dynamic_cast - check equivalent
Assert (dynamic_cast<Rep_*> (&inherited::_GetRepRWRef ()) == reinterpret_cast<Rep_*> (&inherited::_GetRepRWRef ()));
return *reinterpret_cast<Rep_*> (&inherited::_GetRepRWRef ());
}
template <>
template <>
inline vector<byte> SharedMemoryStream<byte>::Ptr::As () const
{
return GetRepConstRef_ ().AsVector ();
}
template <>
template <>
inline vector<Characters::Character> SharedMemoryStream<Characters::Character>::Ptr::As () const
{
return GetRepConstRef_ ().AsVector ();
}
}
#endif /*_Stroika_Foundation_Streams_SharedMemoryStream_inl_*/
| 46.285714 | 223 | 0.536155 | SophistSolutions |
61b8c36017aa8cc5fcde9d64eaa10785fd200957 | 1,468 | hh | C++ | ehunter/core/LogSum.hh | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 122 | 2017-01-06T16:19:31.000Z | 2022-03-08T00:05:50.000Z | ehunter/core/LogSum.hh | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 90 | 2017-01-04T00:23:34.000Z | 2022-02-27T12:55:52.000Z | ehunter/core/LogSum.hh | bw2/ExpansionHunter | 6a6005a4bae2c49f56ec8997a301b70a75b042b6 | [
"BSL-1.0",
"Apache-2.0"
] | 35 | 2017-03-02T13:39:58.000Z | 2022-03-30T17:34:11.000Z | //
// ExpansionHunter
// Copyright (c) 2020 Illumina, Inc.
//
// Author: Konrad Scheffler <kscheffler@illumina.com>
//
// 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.
//
// These utility functions were copied from source code of Strelka Small Variant Caller.
#pragma once
#include <boost/math/special_functions/log1p.hpp>
// returns log(1+x), switches to log1p function when abs(x) is small
static double log1p_switch(const double x)
{
// TODO Justify this switch point. Related discussion:
// http://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf
static const double smallx_thresh(0.01);
if (std::abs(x) < smallx_thresh)
{
return boost::math::log1p(x);
}
else
{
return std::log(1 + x);
}
}
// Returns the equivalent of log(exp(x1)+exp(x2))
static double getLogSum(double x1, double x2)
{
if (x1 < x2)
std::swap(x1, x2);
return x1 + log1p_switch(std::exp(x2 - x1));
} | 29.959184 | 88 | 0.696185 | bw2 |
61b9074c8ecfb30b5f80214514fc2e3315fae2b0 | 275 | cpp | C++ | Challenges/Challenge64/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | Challenges/Challenge64/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | Challenges/Challenge64/src/main.cpp | GamesTrap/PracticeChallenges | 46ad8b2c18515a9740910162381a3dea18be72ab | [
"MIT"
] | null | null | null | #include <cassert>
#include <cstdint>
#include <algorithm>
#include <string>
std::string MakeUpperCase(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
}
int main()
{
assert(MakeUpperCase("hello") == "HELLO");
return 0;
} | 16.176471 | 64 | 0.669091 | GamesTrap |
61b9a58c7748bd4a3d4259c7bf73a1bef26a9cdc | 77,621 | cc | C++ | net/instaweb/rewriter/server_context_test.cc | wernight/incubator-pagespeed-mod | 51214eea728b1615c25667aac818c0fe107cc332 | [
"Apache-2.0"
] | null | null | null | net/instaweb/rewriter/server_context_test.cc | wernight/incubator-pagespeed-mod | 51214eea728b1615c25667aac818c0fe107cc332 | [
"Apache-2.0"
] | null | null | null | net/instaweb/rewriter/server_context_test.cc | wernight/incubator-pagespeed-mod | 51214eea728b1615c25667aac818c0fe107cc332 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Unit-test the server context
#include "net/instaweb/rewriter/public/server_context.h"
#include <cstddef> // for size_t
#include "base/logging.h"
#include "net/instaweb/http/public/async_fetch.h"
#include "net/instaweb/http/public/counting_url_async_fetcher.h"
#include "net/instaweb/http/public/http_cache.h"
#include "net/instaweb/http/public/http_cache_failure.h"
#include "net/instaweb/http/public/http_value.h"
#include "net/instaweb/http/public/mock_url_fetcher.h"
#include "net/instaweb/rewriter/input_info.pb.h"
#include "net/instaweb/rewriter/public/beacon_critical_images_finder.h"
#include "net/instaweb/rewriter/public/critical_finder_support_util.h"
#include "net/instaweb/rewriter/public/critical_images_finder.h"
#include "net/instaweb/rewriter/public/critical_selector_finder.h"
#include "net/instaweb/rewriter/public/css_outline_filter.h"
#include "net/instaweb/rewriter/public/domain_lawyer.h"
#include "net/instaweb/rewriter/public/file_load_policy.h"
#include "net/instaweb/rewriter/public/mock_resource_callback.h"
#include "net/instaweb/rewriter/public/output_resource.h"
#include "net/instaweb/rewriter/public/output_resource_kind.h"
#include "net/instaweb/rewriter/public/resource.h"
#include "net/instaweb/rewriter/public/resource_namer.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_filter.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/rewrite_query.h"
#include "net/instaweb/rewriter/public/rewrite_test_base.h"
#include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h"
#include "net/instaweb/rewriter/rendered_image.pb.h"
#include "net/instaweb/util/public/mock_property_page.h"
#include "net/instaweb/util/public/property_cache.h"
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/mock_message_handler.h"
#include "pagespeed/kernel/base/mock_timer.h"
#include "pagespeed/kernel/base/ref_counted_ptr.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
#include "pagespeed/kernel/base/statistics.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_hash.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/base/timer.h"
#include "pagespeed/kernel/cache/lru_cache.h"
#include "pagespeed/kernel/html/html_element.h"
#include "pagespeed/kernel/html/html_parse_test_base.h"
#include "pagespeed/kernel/http/content_type.h"
#include "pagespeed/kernel/http/google_url.h"
#include "pagespeed/kernel/http/http_names.h"
#include "pagespeed/kernel/http/request_headers.h"
#include "pagespeed/kernel/http/response_headers.h"
#include "pagespeed/kernel/http/user_agent_matcher.h"
#include "pagespeed/kernel/http/user_agent_matcher_test_base.h"
#include "pagespeed/kernel/util/url_escaper.h"
namespace {
const char kResourceUrl[] = "http://example.com/image.png";
const char kResourceUrlBase[] = "http://example.com";
const char kResourceUrlPath[] = "/image.png";
const char kOptionsHash[] = "1234";
const char kUrlPrefix[] = "http://www.example.com/";
} // namespace
namespace net_instaweb {
class VerifyContentsCallback : public Resource::AsyncCallback {
public:
VerifyContentsCallback(const ResourcePtr& resource,
const GoogleString& contents)
: Resource::AsyncCallback(resource),
contents_(contents),
called_(false) {}
VerifyContentsCallback(const OutputResourcePtr& resource,
const GoogleString& contents)
: Resource::AsyncCallback(ResourcePtr(resource)),
contents_(contents),
called_(false) {}
void Done(bool lock_failure, bool resource_ok) override {
EXPECT_FALSE(lock_failure);
EXPECT_STREQ(contents_, resource()->ExtractUncompressedContents());
called_ = true;
}
void AssertCalled() { EXPECT_TRUE(called_); }
GoogleString contents_;
bool called_;
};
class ServerContextTest : public RewriteTestBase {
protected:
// Fetches data (which is expected to exist) for given resource,
// but making sure to go through the path that checks for its
// non-existence and potentially doing locking, too.
// Note: resource must have hash set.
bool FetchExtantOutputResourceHelper(const OutputResourcePtr& resource,
StringAsyncFetch* async_fetch) {
async_fetch->set_response_headers(resource->response_headers());
RewriteFilter* null_filter = nullptr; // We want to test the cache only.
EXPECT_TRUE(rewrite_driver()->FetchOutputResource(resource, null_filter,
async_fetch));
rewrite_driver()->WaitForCompletion();
EXPECT_TRUE(async_fetch->done());
return async_fetch->success();
}
// Helper for testing of FetchOutputResource. Assumes that output_resource
// is to be handled by the filter with 2-letter code filter_id, and
// verifies result to match expect_success and expect_content.
void TestFetchOutputResource(const OutputResourcePtr& output_resource,
const char* filter_id, bool expect_success,
StringPiece expect_content) {
ASSERT_TRUE(output_resource.get());
RewriteFilter* filter = rewrite_driver()->FindFilter(filter_id);
ASSERT_TRUE(filter != nullptr);
StringAsyncFetch fetch_result(CreateRequestContext());
EXPECT_TRUE(rewrite_driver()->FetchOutputResource(output_resource, filter,
&fetch_result));
rewrite_driver()->WaitForCompletion();
EXPECT_TRUE(fetch_result.done());
EXPECT_EQ(expect_success, fetch_result.success());
EXPECT_EQ(expect_content, fetch_result.buffer());
}
GoogleString GetOutputResource(const OutputResourcePtr& resource) {
StringAsyncFetch fetch(RequestContext::NewTestRequestContext(
server_context()->thread_system()));
EXPECT_TRUE(FetchExtantOutputResourceHelper(resource, &fetch));
return fetch.buffer();
}
// Returns whether there was an existing copy of data for the resource.
// If not, makes sure the resource is wrapped.
bool TryFetchExtantOutputResource(const OutputResourcePtr& resource) {
StringAsyncFetch dummy_fetch(CreateRequestContext());
return FetchExtantOutputResourceHelper(resource, &dummy_fetch);
}
// Asserts that the given url starts with an appropriate prefix;
// then cuts off that prefix.
virtual void RemoveUrlPrefix(const GoogleString& prefix, GoogleString* url) {
EXPECT_TRUE(StringPiece(*url).starts_with(prefix));
url->erase(0, prefix.length());
}
OutputResourcePtr CreateOutputResourceForFetch(const StringPiece& url) {
RewriteFilter* dummy;
rewrite_driver()->SetBaseUrlForFetch(url);
GoogleUrl gurl(url);
return rewrite_driver()->DecodeOutputResource(gurl, &dummy);
}
ResourcePtr CreateInputResourceAndReadIfCached(const StringPiece& url) {
rewrite_driver()->SetBaseUrlForFetch(url);
GoogleUrl resource_url(url);
bool unused;
ResourcePtr resource(rewrite_driver()->CreateInputResource(
resource_url, RewriteDriver::InputRole::kUnknown, &unused));
if ((resource.get() != nullptr) && !ReadIfCached(resource)) {
resource.clear();
}
return resource;
}
// Tests for the lifecycle and various flows of a named output resource.
void TestNamed() {
const char* filter_prefix = RewriteOptions::kCssFilterId;
const char* name = "I.name"; // valid name for CSS filter.
const char* contents = "contents";
GoogleString failure_reason;
OutputResourcePtr output(rewrite_driver()->CreateOutputResourceWithPath(
kUrlPrefix, filter_prefix, name, kRewrittenResource, &failure_reason));
ASSERT_TRUE(output.get() != nullptr);
EXPECT_EQ("", failure_reason);
// Check name_key against url_prefix/fp.name
GoogleString name_key = output->name_key();
RemoveUrlPrefix(kUrlPrefix, &name_key);
EXPECT_EQ(output->full_name().EncodeIdName(), name_key);
// Make sure the resource hasn't already been created. We do need to give it
// a hash for fetching to do anything.
output->SetHash("42");
EXPECT_FALSE(TryFetchExtantOutputResource(output));
EXPECT_FALSE(output->IsWritten());
{
// Check that a non-blocking attempt to create another resource
// with the same name returns quickly. We don't need a hash in this
// case since we're just trying to create the resource, not fetch it.
OutputResourcePtr output1(rewrite_driver()->CreateOutputResourceWithPath(
kUrlPrefix, filter_prefix, name, kRewrittenResource,
&failure_reason));
ASSERT_TRUE(output1.get() != nullptr);
EXPECT_EQ("", failure_reason);
EXPECT_FALSE(output1->IsWritten());
}
{
// Here we attempt to create the object with the hash and fetch it.
// The fetch fails as there is no active filter to resolve it.
ResourceNamer namer;
namer.CopyFrom(output->full_name());
namer.set_hash("0");
namer.set_ext("txt");
GoogleString name = StrCat(kUrlPrefix, namer.Encode());
OutputResourcePtr output1(CreateOutputResourceForFetch(name));
ASSERT_TRUE(output1.get() != nullptr);
// blocking but stealing
EXPECT_FALSE(TryFetchExtantOutputResource(output1));
}
// Write some data
ASSERT_TRUE(output->has_hash());
EXPECT_EQ(kRewrittenResource, output->kind());
EXPECT_TRUE(rewrite_driver()->Write(
ResourceVector(), contents, &kContentTypeText, "utf-8", output.get()));
EXPECT_TRUE(output->IsWritten());
// Check that hash and ext are correct.
EXPECT_EQ("0", output->hash());
EXPECT_EQ("txt", output->extension());
EXPECT_STREQ("utf-8", output->charset());
// With the URL (which contains the hash), we can retrieve it
// from the http_cache.
OutputResourcePtr output4(CreateOutputResourceForFetch(output->url()));
EXPECT_EQ(output->url(), output4->url());
EXPECT_EQ(contents, GetOutputResource(output4));
}
bool ResourceIsCached() {
ResourcePtr resource(CreateResource(kResourceUrlBase, kResourceUrlPath));
return ReadIfCached(resource);
}
void StartRead() {
ResourcePtr resource(CreateResource(kResourceUrlBase, kResourceUrlPath));
InitiateResourceRead(resource);
}
GoogleString MakeEvilUrl(const StringPiece& host, const StringPiece& name) {
GoogleString escaped_abs;
UrlEscaper::EncodeToUrlSegment(name, &escaped_abs);
// Do not use Encode, which will make the URL non-evil.
// TODO(matterbury): Rewrite this for a non-standard UrlNamer?
return StrCat("http://", host, "/dir/123/", escaped_abs,
".pagespeed.jm.0.js");
}
// Accessor for ServerContext field; also cleans up
// deferred_release_rewrite_drivers_.
void EnableRewriteDriverCleanupMode(bool s) {
server_context()->trying_to_cleanup_rewrite_drivers_ = s;
server_context()->deferred_release_rewrite_drivers_.clear();
}
// Creates a response with given ttl and extra cache control under given URL.
void SetCustomCachingResponse(const StringPiece& url, int ttl_ms,
const StringPiece& extra_cache_control) {
ResponseHeaders response_headers;
DefaultResponseHeaders(kContentTypeCss, ttl_ms, &response_headers);
response_headers.SetDateAndCaching(http_cache()->timer()->NowMs(),
ttl_ms * Timer::kSecondMs,
extra_cache_control);
response_headers.ComputeCaching();
SetFetchResponse(AbsolutifyUrl(url), response_headers, "payload");
}
// Creates a resource with given ttl and extra cache control under given URL.
ResourcePtr CreateCustomCachingResource(
const StringPiece& url, int ttl_ms,
const StringPiece& extra_cache_control) {
SetCustomCachingResponse(url, ttl_ms, extra_cache_control);
GoogleUrl gurl(AbsolutifyUrl(url));
rewrite_driver()->SetBaseUrlForFetch(kTestDomain);
bool unused;
ResourcePtr resource(rewrite_driver()->CreateInputResource(
gurl, RewriteDriver::InputRole::kUnknown, &unused));
VerifyContentsCallback callback(resource, "payload");
resource->LoadAsync(Resource::kLoadEvenIfNotCacheable,
rewrite_driver()->request_context(), &callback);
callback.AssertCalled();
return resource;
}
void RefererTest(const RequestHeaders* headers, bool is_background_fetch) {
GoogleString url = "test.jpg";
rewrite_driver()->SetBaseUrlForFetch(kTestDomain);
SetCustomCachingResponse(url, 100, "foo");
GoogleUrl gurl(AbsolutifyUrl(url));
bool unused;
ResourcePtr resource(rewrite_driver()->CreateInputResource(
gurl, RewriteDriver::InputRole::kImg, &unused));
if (!is_background_fetch) {
rewrite_driver()->SetRequestHeaders(*headers);
}
resource->set_is_background_fetch(is_background_fetch);
VerifyContentsCallback callback(resource, "payload");
resource->LoadAsync(Resource::kLoadEvenIfNotCacheable,
rewrite_driver()->request_context(), &callback);
callback.AssertCalled();
}
void DefaultHeaders(ResponseHeaders* headers) {
SetDefaultLongCacheHeaders(&kContentTypeCss, headers);
}
const RewriteDriver* decoding_driver() {
return server_context()->decoding_driver_;
}
RewriteOptions* GetCustomOptions(const StringPiece& url,
RequestHeaders* request_headers,
RewriteOptions* domain_options) {
// The default url_namer does not yield any name-derived options, and we
// have not specified any URL params or request-headers, so there will be
// no custom options, and no errors.
GoogleUrl gurl(url);
RewriteOptions* copy_options =
domain_options != nullptr ? domain_options->Clone() : nullptr;
RewriteQuery rewrite_query;
RequestContextPtr null_request_context;
EXPECT_TRUE(server_context()->GetQueryOptions(null_request_context, nullptr,
&gurl, request_headers,
nullptr, &rewrite_query));
RewriteOptions* options = server_context()->GetCustomOptions(
request_headers, copy_options, rewrite_query.ReleaseOptions());
return options;
}
void CheckExtendCache(RewriteOptions* options, bool x) {
EXPECT_EQ(x, options->Enabled(RewriteOptions::kExtendCacheCss));
EXPECT_EQ(x, options->Enabled(RewriteOptions::kExtendCacheImages));
EXPECT_EQ(x, options->Enabled(RewriteOptions::kExtendCacheScripts));
}
};
TEST_F(ServerContextTest, CustomOptionsWithNoUrlNamerOptions) {
// The default url_namer does not yield any name-derived options, and we
// have not specified any URL params or request-headers, so there will be
// no custom options, and no errors.
RequestHeaders request_headers;
std::unique_ptr<RewriteOptions> options(
GetCustomOptions("http://example.com/", &request_headers, nullptr));
ASSERT_TRUE(options.get() == nullptr);
// Now put a query-param in, just turning on PageSpeed. The core filters
// should be enabled.
options.reset(GetCustomOptions("http://example.com/?PageSpeed=on",
&request_headers, nullptr));
ASSERT_TRUE(options.get() != nullptr);
EXPECT_TRUE(options->enabled());
CheckExtendCache(options.get(), true);
EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss));
EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferJavascript));
// Now explicitly enable a filter, which should disable others.
options.reset(
GetCustomOptions("http://example.com/?PageSpeedFilters=extend_cache",
&request_headers, nullptr));
ASSERT_TRUE(options.get() != nullptr);
CheckExtendCache(options.get(), true);
EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss));
EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferJavascript));
// Now put a request-header in, turning off pagespeed. request-headers get
// priority over query-params.
request_headers.Add("PageSpeed", "off");
options.reset(GetCustomOptions("http://example.com/?PageSpeed=on",
&request_headers, nullptr));
ASSERT_TRUE(options.get() != nullptr);
EXPECT_FALSE(options->enabled());
// Now explicitly enable a bogus filter, which should will cause the
// options to be uncomputable.
GoogleUrl gurl("http://example.com/?PageSpeedFilters=bogus_filter");
RewriteQuery rewrite_query;
RequestContextPtr null_request_context;
EXPECT_FALSE(server_context()->GetQueryOptions(
null_request_context, options.get(), &gurl, &request_headers, nullptr,
&rewrite_query));
// The default url_namer does not yield any name-derived options, and we
// have not specified any URL params or request-headers, and kXRequestedWith
// header is set with bogus value, so there will be no custom options, and no
// errors.
request_headers.Add(HttpAttributes::kXRequestedWith, "bogus");
options.reset(
GetCustomOptions("http://example.com/", &request_headers, nullptr));
ASSERT_TRUE(options.get() == nullptr);
// The default url_namer does not yield any name-derived options, and we
// have not specified any URL params or request-headers, but kXRequestedWith
// header is set to 'XmlHttpRequest', so there will be custom options with
// all js inserting filters disabled.
request_headers.RemoveAll(HttpAttributes::kXRequestedWith);
request_headers.Add(HttpAttributes::kXRequestedWith,
HttpAttributes::kXmlHttpRequest);
options.reset(
GetCustomOptions("http://example.com/", &request_headers, nullptr));
// Disable DelayImages for XmlHttpRequests.
ASSERT_TRUE(options.get() != nullptr);
EXPECT_TRUE(options->enabled());
EXPECT_FALSE(options->Enabled(RewriteOptions::kDelayImages));
// As kDelayImages filter is present in the disabled list, so it will not get
// enabled even if it is enabled via EnableFilter().
options->EnableFilter(RewriteOptions::kDelayImages);
EXPECT_FALSE(options->Enabled(RewriteOptions::kDelayImages));
options->EnableFilter(RewriteOptions::kCachePartialHtmlDeprecated);
EXPECT_FALSE(options->Enabled(RewriteOptions::kCachePartialHtmlDeprecated));
options->EnableFilter(RewriteOptions::kDeferIframe);
EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferIframe));
options->EnableFilter(RewriteOptions::kDeferJavascript);
EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferJavascript));
options->EnableFilter(RewriteOptions::kFlushSubresources);
EXPECT_FALSE(options->Enabled(RewriteOptions::kFlushSubresources));
options->EnableFilter(RewriteOptions::kLazyloadImages);
EXPECT_FALSE(options->Enabled(RewriteOptions::kLazyloadImages));
options->EnableFilter(RewriteOptions::kLocalStorageCache);
EXPECT_FALSE(options->Enabled(RewriteOptions::kLocalStorageCache));
options->EnableFilter(RewriteOptions::kPrioritizeCriticalCss);
EXPECT_FALSE(options->Enabled(RewriteOptions::kPrioritizeCriticalCss));
}
TEST_F(ServerContextTest, CustomOptionsWithUrlNamerOptions) {
// Inject a url-namer that will establish a domain configuration.
RewriteOptions namer_options(factory()->thread_system());
namer_options.EnableFilter(RewriteOptions::kCombineJavascript);
namer_options.EnableFilter(RewriteOptions::kDelayImages);
RequestHeaders request_headers;
std::unique_ptr<RewriteOptions> options(GetCustomOptions(
"http://example.com/", &request_headers, &namer_options));
// Even with no query-params or request-headers, we get the custom
// options as domain options provided as argument.
ASSERT_TRUE(options.get() != nullptr);
EXPECT_TRUE(options->enabled());
CheckExtendCache(options.get(), false);
EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss));
EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript));
EXPECT_TRUE(options->Enabled(RewriteOptions::kDelayImages));
// Now combine with query params, which turns core-filters on.
options.reset(GetCustomOptions("http://example.com/?PageSpeed=on",
&request_headers, &namer_options));
ASSERT_TRUE(options.get() != nullptr);
EXPECT_TRUE(options->enabled());
CheckExtendCache(options.get(), true);
EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss));
EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript));
// Explicitly enable a filter in query-params, which will turn off
// the core filters that have not been explicitly enabled. Note
// that explicit filter-setting in query-params overrides completely
// the options provided as a parameter.
options.reset(
GetCustomOptions("http://example.com/?PageSpeedFilters=combine_css",
&request_headers, &namer_options));
ASSERT_TRUE(options.get() != nullptr);
EXPECT_TRUE(options->enabled());
CheckExtendCache(options.get(), false);
EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss));
EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineJavascript));
// Now explicitly enable a bogus filter, which should will cause the
// options to be uncomputable.
GoogleUrl gurl("http://example.com/?PageSpeedFilters=bogus_filter");
RewriteQuery rewrite_query;
RequestContextPtr null_request_context;
EXPECT_FALSE(server_context()->GetQueryOptions(
null_request_context, options.get(), &gurl, &request_headers, nullptr,
&rewrite_query));
request_headers.Add(HttpAttributes::kXRequestedWith, "bogus");
options.reset(GetCustomOptions("http://example.com/", &request_headers,
&namer_options));
// Don't disable DelayImages for Non-XmlHttpRequests.
ASSERT_TRUE(options.get() != nullptr);
EXPECT_TRUE(options->enabled());
CheckExtendCache(options.get(), false);
EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss));
EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript));
EXPECT_TRUE(options->Enabled(RewriteOptions::kDelayImages));
request_headers.RemoveAll(HttpAttributes::kXRequestedWith);
request_headers.Add(HttpAttributes::kXRequestedWith,
HttpAttributes::kXmlHttpRequest);
options.reset(GetCustomOptions("http://example.com/", &request_headers,
&namer_options));
// Disable DelayImages for XmlHttpRequests.
ASSERT_TRUE(options.get() != nullptr);
EXPECT_TRUE(options->enabled());
CheckExtendCache(options.get(), false);
EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss));
EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript));
EXPECT_FALSE(options->Enabled(RewriteOptions::kDelayImages));
}
TEST_F(ServerContextTest, QueryOptionsWithInvalidUrl) {
RequestHeaders request_headers;
GoogleUrl gurl("bogus");
ASSERT_FALSE(gurl.IsWebValid());
RewriteQuery rewrite_query;
RequestContextPtr null_request_context;
EXPECT_FALSE(server_context()->GetQueryOptions(
null_request_context, options(), &gurl, &request_headers, nullptr,
&rewrite_query));
}
TEST_F(ServerContextTest, TestNamed) { TestNamed(); }
TEST_F(ServerContextTest, TestOutputInputUrl) {
options()->EnableFilter(RewriteOptions::kRewriteJavascriptExternal);
rewrite_driver()->AddFilters();
GoogleString url =
Encode("http://example.com/dir/123/", RewriteOptions::kJavascriptMinId,
"0", "orig", "js");
SetResponseWithDefaultHeaders("http://example.com/dir/123/orig",
kContentTypeJavascript, "foo() /*comment */;",
100);
OutputResourcePtr output_resource(CreateOutputResourceForFetch(url));
TestFetchOutputResource(output_resource, RewriteOptions::kJavascriptMinId,
true, "foo();");
}
// Test to make sure we do not let a crafted output resource URL to get us to
// fetch and host things from a non-lawyer permitted external host; which could
// lead to XSS vulnerabilities or a firewall bypass.
TEST_F(ServerContextTest, TestOutputInputUrlEvil) {
options()->EnableFilter(RewriteOptions::kRewriteJavascriptExternal);
rewrite_driver()->AddFilters();
GoogleString url = MakeEvilUrl("example.com", "http://www.evil.com");
SetResponseWithDefaultHeaders("http://www.evil.com/", kContentTypeJavascript,
"foo() /*comment */;", 100);
OutputResourcePtr output_resource(CreateOutputResourceForFetch(url));
TestFetchOutputResource(output_resource, RewriteOptions::kJavascriptMinId,
false, "");
}
TEST_F(ServerContextTest, TestOutputInputUrlBusy) {
EXPECT_TRUE(options()->WriteableDomainLawyer()->AddOriginDomainMapping(
"www.busy.com", "example.com", "", message_handler()));
options()->EnableFilter(RewriteOptions::kRewriteJavascriptExternal);
rewrite_driver()->AddFilters();
GoogleString url = MakeEvilUrl("example.com", "http://www.busy.com");
SetResponseWithDefaultHeaders("http://www.busy.com/", kContentTypeJavascript,
"foo() /*comment */;", 100);
OutputResourcePtr output_resource(CreateOutputResourceForFetch(url));
TestFetchOutputResource(output_resource, RewriteOptions::kJavascriptMinId,
false, "");
}
// Check that we can origin-map a domain referenced from an HTML file
// to 'localhost', but rewrite-map it to 'cdn.com'. This was not working
// earlier because RewriteDriver::CreateInputResource was mapping to the
// rewrite domain, preventing us from finding the origin-mapping when
// fetching the URL.
TEST_F(ServerContextTest, TestMapRewriteAndOrigin) {
ASSERT_TRUE(options()->WriteableDomainLawyer()->AddOriginDomainMapping(
"localhost", kTestDomain, "", message_handler()));
EXPECT_TRUE(options()->WriteableDomainLawyer()->AddRewriteDomainMapping(
"cdn.com", kTestDomain, message_handler()));
ResourcePtr input(
CreateResource(StrCat(kTestDomain, "index.html"), "style.css"));
ASSERT_TRUE(input.get() != nullptr);
EXPECT_EQ(StrCat(kTestDomain, "style.css"), input->url());
// The absolute input URL is in test.com, but we will only be
// able to serve it from localhost, per the origin mapping above.
static const char kStyleContent[] = "style content";
const int kOriginTtlSec = 300;
SetResponseWithDefaultHeaders("http://localhost/style.css", kContentTypeCss,
kStyleContent, kOriginTtlSec);
EXPECT_TRUE(ReadIfCached(input));
// When we rewrite the resource as an ouptut, it will show up in the
// CDN per the rewrite mapping.
GoogleString failure_reason;
OutputResourcePtr output(rewrite_driver()->CreateOutputResourceFromResource(
RewriteOptions::kCacheExtenderId, rewrite_driver()->default_encoder(),
nullptr, input, kRewrittenResource, &failure_reason));
ASSERT_TRUE(output.get() != nullptr);
EXPECT_EQ("", failure_reason);
// We need to 'Write' an output resource before we can determine its
// URL.
rewrite_driver()->Write(ResourceVector(), StringPiece(kStyleContent),
&kContentTypeCss, StringPiece(), output.get());
EXPECT_EQ(Encode("http://cdn.com/", "ce", "0", "style.css", "css"),
output->url());
}
class MockRewriteFilter : public RewriteFilter {
public:
explicit MockRewriteFilter(RewriteDriver* driver) : RewriteFilter(driver) {}
~MockRewriteFilter() override {}
const char* id() const override { return "mk"; }
const char* Name() const override { return "mock_filter"; }
void StartDocumentImpl() override {}
void StartElementImpl(HtmlElement* element) override {}
void EndElementImpl(HtmlElement* element) override {}
private:
DISALLOW_COPY_AND_ASSIGN(MockRewriteFilter);
};
class CreateMockRewriterCallback
: public TestRewriteDriverFactory::CreateRewriterCallback {
public:
CreateMockRewriterCallback() {}
~CreateMockRewriterCallback() override {}
RewriteFilter* Done(RewriteDriver* driver) override {
return new MockRewriteFilter(driver);
}
private:
DISALLOW_COPY_AND_ASSIGN(CreateMockRewriterCallback);
};
class MockPlatformConfigCallback
: public TestRewriteDriverFactory::PlatformSpecificConfigurationCallback {
public:
explicit MockPlatformConfigCallback(RewriteDriver** result_ptr)
: result_ptr_(result_ptr) {}
void Done(RewriteDriver* driver) override { *result_ptr_ = driver; }
private:
RewriteDriver** result_ptr_;
DISALLOW_COPY_AND_ASSIGN(MockPlatformConfigCallback);
};
// Tests that platform-specific configuration hook runs for various
// factory methods.
TEST_F(ServerContextTest, TestPlatformSpecificConfiguration) {
RewriteDriver* rec_normal_driver = nullptr;
RewriteDriver* rec_custom_driver = nullptr;
MockPlatformConfigCallback normal_callback(&rec_normal_driver);
MockPlatformConfigCallback custom_callback(&rec_custom_driver);
factory()->AddPlatformSpecificConfigurationCallback(&normal_callback);
RewriteDriver* normal_driver = server_context()->NewRewriteDriver(
RequestContext::NewTestRequestContext(server_context()->thread_system()));
EXPECT_EQ(normal_driver, rec_normal_driver);
factory()->ClearPlatformSpecificConfigurationCallback();
normal_driver->Cleanup();
factory()->AddPlatformSpecificConfigurationCallback(&custom_callback);
RewriteDriver* custom_driver = server_context()->NewCustomRewriteDriver(
new RewriteOptions(factory()->thread_system()),
RequestContext::NewTestRequestContext(server_context()->thread_system()));
EXPECT_EQ(custom_driver, rec_custom_driver);
custom_driver->Cleanup();
}
// Tests that platform-specific rewriters are used for decoding fetches.
TEST_F(ServerContextTest, TestPlatformSpecificRewritersDecoding) {
GoogleString url =
Encode("http://example.com/dir/123/", "mk", "0", "orig", "js");
GoogleUrl gurl(url);
RewriteFilter* dummy;
// Without the mock rewriter enabled, this URL should not be decoded.
OutputResourcePtr bad_output(
decoding_driver()->DecodeOutputResource(gurl, &dummy));
ASSERT_TRUE(bad_output.get() == nullptr);
// With the mock rewriter enabled, this URL should be decoded.
CreateMockRewriterCallback callback;
factory()->AddCreateRewriterCallback(&callback);
factory()->set_add_platform_specific_decoding_passes(true);
factory()->RebuildDecodingDriverForTests(server_context());
// TODO(sligocki): Do we still want to expose decoding_driver() for
// platform-specific rewriters? Or should we just use IsPagespeedResource()
// in these tests?
OutputResourcePtr good_output(
decoding_driver()->DecodeOutputResource(gurl, &dummy));
ASSERT_TRUE(good_output.get() != nullptr);
EXPECT_EQ(url, good_output->url());
}
// Tests that platform-specific rewriters are used for decoding fetches even
// if they are only added in AddPlatformSpecificRewritePasses, not
// AddPlatformSpecificDecodingPasses. Required for backwards compatibility.
TEST_F(ServerContextTest, TestPlatformSpecificRewritersImplicitDecoding) {
GoogleString url =
Encode("http://example.com/dir/123/", "mk", "0", "orig", "js");
GoogleUrl gurl(url);
RewriteFilter* dummy;
// The URL should be decoded even if AddPlatformSpecificDecodingPasses is
// suppressed.
CreateMockRewriterCallback callback;
factory()->AddCreateRewriterCallback(&callback);
factory()->set_add_platform_specific_decoding_passes(false);
factory()->RebuildDecodingDriverForTests(server_context());
OutputResourcePtr good_output(
decoding_driver()->DecodeOutputResource(gurl, &dummy));
ASSERT_TRUE(good_output.get() != nullptr);
EXPECT_EQ(url, good_output->url());
}
// DecodeOutputResource should drop query
TEST_F(ServerContextTest, TestOutputResourceFetchQuery) {
GoogleString url =
Encode("http://example.com/dir/123/", "jm", "0", "orig", "js");
RewriteFilter* dummy;
GoogleUrl gurl(StrCat(url, "?query"));
OutputResourcePtr output_resource(
rewrite_driver()->DecodeOutputResource(gurl, &dummy));
ASSERT_TRUE(output_resource.get() != nullptr);
EXPECT_EQ(url, output_resource->url());
}
// Input resources and corresponding output resources should keep queries
TEST_F(ServerContextTest, TestInputResourceQuery) {
const char kUrl[] = "test?param";
ResourcePtr resource(CreateResource(kResourceUrlBase, kUrl));
ASSERT_TRUE(resource.get() != nullptr);
EXPECT_EQ(StrCat(GoogleString(kResourceUrlBase), "/", kUrl), resource->url());
GoogleString failure_reason;
OutputResourcePtr output(rewrite_driver()->CreateOutputResourceFromResource(
"sf", rewrite_driver()->default_encoder(), nullptr, resource,
kRewrittenResource, &failure_reason));
ASSERT_TRUE(output.get() != nullptr);
EXPECT_EQ("", failure_reason);
GoogleString included_name;
EXPECT_TRUE(UrlEscaper::DecodeFromUrlSegment(output->name(), &included_name));
EXPECT_EQ(GoogleString(kUrl), included_name);
}
TEST_F(ServerContextTest, TestRemember404) {
// Make sure our resources remember that a page 404'd, for limited time.
http_cache()->set_failure_caching_ttl_sec(kFetchStatusUncacheableError,
10000);
http_cache()->set_failure_caching_ttl_sec(kFetchStatus4xxError, 100);
ResponseHeaders not_found;
SetDefaultLongCacheHeaders(&kContentTypeHtml, ¬_found);
not_found.SetStatusAndReason(HttpStatus::kNotFound);
SetFetchResponse("http://example.com/404", not_found, "");
ResourcePtr resource(
CreateInputResourceAndReadIfCached("http://example.com/404"));
EXPECT_EQ(nullptr, resource.get());
HTTPValue value_out;
ResponseHeaders headers_out;
EXPECT_EQ(
HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatus4xxError),
HttpBlockingFind("http://example.com/404", http_cache(), &value_out,
&headers_out));
AdvanceTimeMs(150 * Timer::kSecondMs);
EXPECT_EQ(kNotFoundResult,
HttpBlockingFind("http://example.com/404", http_cache(), &value_out,
&headers_out));
}
TEST_F(ServerContextTest, TestRememberDropped) {
// Fake resource being dropped by adding the appropriate header to the
// resource proper.
ResponseHeaders not_found;
SetDefaultLongCacheHeaders(&kContentTypeHtml, ¬_found);
not_found.SetStatusAndReason(HttpStatus::kNotFound);
not_found.Add(HttpAttributes::kXPsaLoadShed, "1");
SetFetchResponse("http://example.com/404", not_found, "");
ResourcePtr resource(
CreateInputResourceAndReadIfCached("http://example.com/404"));
EXPECT_EQ(nullptr, resource.get());
HTTPValue value_out;
ResponseHeaders headers_out;
EXPECT_EQ(
HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusDropped),
HttpBlockingFind("http://example.com/404", http_cache(), &value_out,
&headers_out));
AdvanceTimeMs(11 * Timer::kSecondMs);
EXPECT_EQ(kNotFoundResult,
HttpBlockingFind("http://example.com/404", http_cache(), &value_out,
&headers_out));
}
TEST_F(ServerContextTest, TestNonCacheable) {
const char kContents[] = "ok";
// Make sure that when we get non-cacheable resources
// we mark the fetch as not cacheable in the cache.
ResponseHeaders no_cache;
SetDefaultLongCacheHeaders(&kContentTypeHtml, &no_cache);
no_cache.Replace(HttpAttributes::kCacheControl, "no-cache");
no_cache.ComputeCaching();
SetFetchResponse("http://example.com/", no_cache, kContents);
ResourcePtr resource(CreateResource("http://example.com/", "/"));
ASSERT_TRUE(resource.get() != nullptr);
VerifyContentsCallback callback(resource, kContents);
resource->LoadAsync(Resource::kReportFailureIfNotCacheable,
rewrite_driver()->request_context(), &callback);
callback.AssertCalled();
HTTPValue value_out;
ResponseHeaders headers_out;
EXPECT_EQ(HTTPCache::FindResult(HTTPCache::kRecentFailure,
kFetchStatusUncacheable200),
HttpBlockingFind("http://example.com/", http_cache(), &value_out,
&headers_out));
}
TEST_F(ServerContextTest, TestNonCacheableReadResultPolicy) {
// Make sure we report the success/failure for non-cacheable resources
// depending on the policy. (TestNonCacheable also covers the value).
ResponseHeaders no_cache;
SetDefaultLongCacheHeaders(&kContentTypeHtml, &no_cache);
no_cache.Replace(HttpAttributes::kCacheControl, "no-cache");
no_cache.ComputeCaching();
SetFetchResponse("http://example.com/", no_cache, "stuff");
ResourcePtr resource1(CreateResource("http://example.com/", "/"));
ASSERT_TRUE(resource1.get() != nullptr);
MockResourceCallback callback1(resource1, factory()->thread_system());
resource1->LoadAsync(Resource::kReportFailureIfNotCacheable,
rewrite_driver()->request_context(), &callback1);
EXPECT_TRUE(callback1.done());
EXPECT_FALSE(callback1.success());
ResourcePtr resource2(CreateResource("http://example.com/", "/"));
ASSERT_TRUE(resource2.get() != nullptr);
MockResourceCallback callback2(resource2, factory()->thread_system());
resource2->LoadAsync(Resource::kLoadEvenIfNotCacheable,
rewrite_driver()->request_context(), &callback2);
EXPECT_TRUE(callback2.done());
EXPECT_TRUE(callback2.success());
}
TEST_F(ServerContextTest, TestRememberEmpty) {
// Make sure our resources remember that a page is empty, for limited time.
http_cache()->set_failure_caching_ttl_sec(kFetchStatusEmpty, 100);
ResponseHeaders headers;
SetDefaultLongCacheHeaders(&kContentTypeHtml, &headers);
headers.SetStatusAndReason(HttpStatus::kOK);
static const char kUrl[] = "http://example.com/empty.html";
SetFetchResponse(kUrl, headers, "");
ResourcePtr resource(CreateInputResourceAndReadIfCached(kUrl));
EXPECT_EQ(nullptr, resource.get());
HTTPValue value_out;
ResponseHeaders headers_out;
EXPECT_EQ(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusEmpty),
HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out));
AdvanceTimeMs(150 * Timer::kSecondMs);
EXPECT_EQ(kNotFoundResult,
HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out));
}
TEST_F(ServerContextTest, TestNotRememberEmptyRedirect) {
// Parallel to TestRememberEmpty for empty 301 redirect.
http_cache()->set_failure_caching_ttl_sec(kFetchStatusEmpty, 100);
ResponseHeaders headers;
SetDefaultLongCacheHeaders(&kContentTypeHtml, &headers);
headers.SetStatusAndReason(HttpStatus::kMovedPermanently);
headers.Add(HttpAttributes::kLocation, "http://example.com/destination.html");
static const char kUrl[] = "http://example.com/redirect.html";
SetFetchResponse(kUrl, headers, "");
ResourcePtr resource(CreateInputResourceAndReadIfCached(kUrl));
EXPECT_EQ(nullptr, resource.get());
HTTPValue value_out;
ResponseHeaders headers_out;
// Currently we are remembering 301 as not cacheable, but in the future if
// that changes the important thing here is that we don't remember non-200
// as empty (and thus fail to use them.
EXPECT_NE(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusEmpty),
HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out));
AdvanceTimeMs(150 * Timer::kSecondMs);
EXPECT_NE(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusEmpty),
HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out));
}
TEST_F(ServerContextTest, TestVaryOption) {
// Make sure that when we get non-cacheable resources
// we mark the fetch as not-cacheable in the cache.
options()->set_respect_vary(true);
ResponseHeaders no_cache;
const char kContents[] = "ok";
SetDefaultLongCacheHeaders(&kContentTypeHtml, &no_cache);
no_cache.Add(HttpAttributes::kVary, HttpAttributes::kAcceptEncoding);
no_cache.Add(HttpAttributes::kVary, HttpAttributes::kUserAgent);
no_cache.ComputeCaching();
SetFetchResponse("http://example.com/", no_cache, kContents);
ResourcePtr resource(CreateResource("http://example.com/", "/"));
ASSERT_TRUE(resource.get() != nullptr);
VerifyContentsCallback callback(resource, kContents);
resource->LoadAsync(Resource::kReportFailureIfNotCacheable,
rewrite_driver()->request_context(), &callback);
callback.AssertCalled();
EXPECT_FALSE(resource->IsValidAndCacheable());
HTTPValue valueOut;
ResponseHeaders headersOut;
EXPECT_EQ(HTTPCache::FindResult(HTTPCache::kRecentFailure,
kFetchStatusUncacheable200),
HttpBlockingFind("http://example.com/", http_cache(), &valueOut,
&headersOut));
}
TEST_F(ServerContextTest, TestOutlined) {
// Outliner resources should not produce extra cache traffic
// due to rname/ entries we can't use anyway.
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(0, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
GoogleString failure_reason;
OutputResourcePtr output_resource(
rewrite_driver()->CreateOutputResourceWithPath(
kUrlPrefix, CssOutlineFilter::kFilterId, "_", kOutlinedResource,
&failure_reason));
ASSERT_TRUE(output_resource.get() != nullptr);
EXPECT_EQ("", failure_reason);
EXPECT_EQ(nullptr, output_resource->cached_result());
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(0, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
rewrite_driver()->Write(ResourceVector(), "foo", &kContentTypeCss,
StringPiece(), output_resource.get());
EXPECT_EQ(nullptr, output_resource->cached_result());
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(1, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
// Now try fetching again. It should not get a cached_result either.
output_resource.reset(rewrite_driver()->CreateOutputResourceWithPath(
kUrlPrefix, CssOutlineFilter::kFilterId, "_", kOutlinedResource,
&failure_reason));
ASSERT_TRUE(output_resource.get() != nullptr);
EXPECT_EQ("", failure_reason);
EXPECT_EQ(nullptr, output_resource->cached_result());
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(1, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
}
TEST_F(ServerContextTest, TestOnTheFly) {
// Test to make sure that an on-fly insert does not insert the data,
// just the rname/
// For derived resources we can and should use the rewrite
// summary/metadata cache
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(0, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
GoogleString failure_reason;
OutputResourcePtr output_resource(
rewrite_driver()->CreateOutputResourceWithPath(
kUrlPrefix, RewriteOptions::kCssFilterId, "_", kOnTheFlyResource,
&failure_reason));
ASSERT_TRUE(output_resource.get() != nullptr);
EXPECT_EQ("", failure_reason);
EXPECT_EQ(nullptr, output_resource->cached_result());
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(0, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
rewrite_driver()->Write(ResourceVector(), "foo", &kContentTypeCss,
StringPiece(), output_resource.get());
EXPECT_TRUE(output_resource->cached_result() != nullptr);
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(0, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
}
TEST_F(ServerContextTest, TestNotGenerated) {
// For derived resources we can and should use the rewrite
// summary/metadata cache
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(0, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
GoogleString failure_reason;
OutputResourcePtr output_resource(
rewrite_driver()->CreateOutputResourceWithPath(
kUrlPrefix, RewriteOptions::kCssFilterId, "_", kRewrittenResource,
&failure_reason));
ASSERT_TRUE(output_resource.get() != nullptr);
EXPECT_EQ("", failure_reason);
EXPECT_EQ(nullptr, output_resource->cached_result());
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(0, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
rewrite_driver()->Write(ResourceVector(), "foo", &kContentTypeCss,
StringPiece(), output_resource.get());
EXPECT_TRUE(output_resource->cached_result() != nullptr);
EXPECT_EQ(0, lru_cache()->num_hits());
EXPECT_EQ(0, lru_cache()->num_misses());
EXPECT_EQ(1, lru_cache()->num_inserts());
EXPECT_EQ(0, lru_cache()->num_identical_reinserts());
}
TEST_F(ServerContextTest, TestHandleBeaconNoLoadParam) {
EXPECT_FALSE(server_context()->HandleBeacon(
"", UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext()));
}
TEST_F(ServerContextTest, TestHandleBeaconInvalidLoadParam) {
EXPECT_FALSE(server_context()->HandleBeacon(
"ets=asd", UserAgentMatcherTestBase::kChromeUserAgent,
CreateRequestContext()));
}
TEST_F(ServerContextTest, TestHandleBeaconNoUrl) {
EXPECT_FALSE(server_context()->HandleBeacon(
"ets=load:34", UserAgentMatcherTestBase::kChromeUserAgent,
CreateRequestContext()));
}
TEST_F(ServerContextTest, TestHandleBeaconInvalidUrl) {
EXPECT_FALSE(server_context()->HandleBeacon(
"url=%2f%2finvalidurl&ets=load:34",
UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext()));
}
TEST_F(ServerContextTest, TestHandleBeaconMissingValue) {
EXPECT_FALSE(server_context()->HandleBeacon(
"url=http%3A%2F%2Flocalhost%3A8080%2Findex.html&ets=load:",
UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext()));
}
TEST_F(ServerContextTest, TestHandleBeacon) {
EXPECT_TRUE(server_context()->HandleBeacon(
"url=http%3A%2F%2Flocalhost%3A8080%2Findex.html&ets=load:34",
UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext()));
}
class BeaconTest : public ServerContextTest {
protected:
BeaconTest() : property_cache_(nullptr) {}
~BeaconTest() override {}
void SetUp() override {
ServerContextTest::SetUp();
property_cache_ = server_context()->page_property_cache();
property_cache_->set_enabled(true);
const PropertyCache::Cohort* beacon_cohort =
SetupCohort(property_cache_, RewriteDriver::kBeaconCohort);
server_context()->set_beacon_cohort(beacon_cohort);
server_context()->set_critical_images_finder(new BeaconCriticalImagesFinder(
beacon_cohort, factory()->nonce_generator(), statistics()));
server_context()->set_critical_selector_finder(
new BeaconCriticalSelectorFinder(
beacon_cohort, factory()->nonce_generator(), statistics()));
ResetDriver();
candidates_.insert("#foo");
candidates_.insert(".bar");
candidates_.insert("img");
}
void ResetDriver() {
rewrite_driver()->Clear();
SetDriverRequestHeaders();
}
MockPropertyPage* MockPageForUA(StringPiece user_agent) {
UserAgentMatcher::DeviceType device_type =
server_context()->user_agent_matcher()->GetDeviceTypeForUA(user_agent);
MockPropertyPage* page = NewMockPage(kUrlPrefix, kOptionsHash, device_type);
property_cache_->Read(page);
return page;
}
void InsertCssBeacon(StringPiece user_agent) {
// Simulate effects on pcache of CSS beacon insertion.
rewrite_driver()->set_property_page(MockPageForUA(user_agent));
factory()->mock_timer()->AdvanceMs(
options()->beacon_reinstrument_time_sec() * Timer::kSecondMs);
last_beacon_metadata_ =
server_context()->critical_selector_finder()->PrepareForBeaconInsertion(
candidates_, rewrite_driver());
ASSERT_EQ(kBeaconWithNonce, last_beacon_metadata_.status);
ASSERT_FALSE(last_beacon_metadata_.nonce.empty());
rewrite_driver()->property_page()->WriteCohort(
server_context()->beacon_cohort());
}
void InsertImageBeacon(StringPiece user_agent) {
// Simulate effects on pcache of image beacon insertion.
rewrite_driver()->set_property_page(MockPageForUA(user_agent));
// Some of the critical image tests send enough beacons with the same set of
// images that we can go into low frequency beaconing mode, so advance time
// by the low frequency rebeacon interval.
factory()->mock_timer()->AdvanceMs(
options()->beacon_reinstrument_time_sec() * Timer::kSecondMs *
kLowFreqBeaconMult);
last_beacon_metadata_ =
server_context()->critical_images_finder()->PrepareForBeaconInsertion(
rewrite_driver());
ASSERT_EQ(kBeaconWithNonce, last_beacon_metadata_.status);
ASSERT_FALSE(last_beacon_metadata_.nonce.empty());
rewrite_driver()->property_page()->WriteCohort(
server_context()->beacon_cohort());
}
// Send a beacon through ServerContext::HandleBeacon and verify that the
// property cache entries for critical images, critical selectors and rendered
// dimensions of images were updated correctly.
void TestBeacon(const StringSet* critical_image_hashes,
const StringSet* critical_css_selectors,
const GoogleString* rendered_images_json_map,
StringPiece user_agent) {
ASSERT_EQ(kBeaconWithNonce, last_beacon_metadata_.status)
<< "Remember to insert a beacon!";
// Setup the beacon_url and pass to HandleBeacon.
GoogleString beacon_url = StrCat(
"url=http%3A%2F%2Fwww.example.com"
"&oh=",
kOptionsHash, "&n=", last_beacon_metadata_.nonce);
if (critical_image_hashes != nullptr) {
StrAppend(&beacon_url, "&ci=");
AppendJoinCollection(&beacon_url, *critical_image_hashes, ",");
}
if (critical_css_selectors != nullptr) {
StrAppend(&beacon_url, "&cs=");
AppendJoinCollection(&beacon_url, *critical_css_selectors, ",");
}
if (rendered_images_json_map != nullptr) {
StrAppend(&beacon_url, "&rd=", *rendered_images_json_map);
}
EXPECT_TRUE(server_context()->HandleBeacon(beacon_url, user_agent,
CreateRequestContext()));
// Read the property cache value for critical images, and verify that it has
// the expected value.
ResetDriver();
std::unique_ptr<MockPropertyPage> page(MockPageForUA(user_agent));
rewrite_driver()->set_property_page(page.release());
if (critical_image_hashes != nullptr) {
critical_html_images_ =
server_context()->critical_images_finder()->GetHtmlCriticalImages(
rewrite_driver());
}
if (critical_css_selectors != nullptr) {
critical_css_selectors_ =
server_context()->critical_selector_finder()->GetCriticalSelectors(
rewrite_driver());
}
if (rendered_images_json_map != nullptr) {
rendered_images_.reset(
server_context()
->critical_images_finder()
->ExtractRenderedImageDimensionsFromCache(rewrite_driver()));
}
}
PropertyCache* property_cache_;
// These fields hold data deserialized from the pcache after TestBeacon.
StringSet critical_html_images_;
StringSet critical_css_selectors_;
// This field holds the data deserialized from pcache after a BeaconTest call.
std::unique_ptr<RenderedImages> rendered_images_;
// This field holds candidate critical css selectors.
StringSet candidates_;
BeaconMetadata last_beacon_metadata_;
};
TEST_F(BeaconTest, BasicPcacheSetup) {
const PropertyCache::Cohort* cohort =
property_cache_->GetCohort(RewriteDriver::kBeaconCohort);
UserAgentMatcher::DeviceType device_type =
server_context()->user_agent_matcher()->GetDeviceTypeForUA(
UserAgentMatcherTestBase::kChromeUserAgent);
std::unique_ptr<MockPropertyPage> page(
NewMockPage(kUrlPrefix, kOptionsHash, device_type));
property_cache_->Read(page.get());
PropertyValue* property = page->GetProperty(cohort, "critical_images");
EXPECT_FALSE(property->has_value());
}
TEST_F(BeaconTest, HandleBeaconRenderedDimensionsofImages) {
GoogleString img1 = "http://www.example.com/img1.png";
GoogleString hash1 = IntegerToString(
HashString<CasePreserve, unsigned>(img1.c_str(), img1.size()));
options()->EnableFilter(RewriteOptions::kResizeToRenderedImageDimensions);
RenderedImages rendered_images;
RenderedImages_Image* images = rendered_images.add_image();
images->set_src(hash1);
images->set_rendered_width(40);
images->set_rendered_height(50);
GoogleString json_map_rendered_dimensions = StrCat(
"{\"", hash1, "\":{\"rw\":40,", "\"rh\":50,\"ow\":160,\"oh\":200}}");
InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
TestBeacon(nullptr, nullptr, &json_map_rendered_dimensions,
UserAgentMatcherTestBase::kChromeUserAgent);
ASSERT_FALSE(rendered_images_.get() == nullptr);
EXPECT_EQ(1, rendered_images_->image_size());
EXPECT_STREQ(hash1, rendered_images_->image(0).src());
EXPECT_EQ(40, rendered_images_->image(0).rendered_width());
EXPECT_EQ(50, rendered_images_->image(0).rendered_height());
}
TEST_F(BeaconTest, HandleBeaconCritImages) {
GoogleString img1 = "http://www.example.com/img1.png";
GoogleString img2 = "http://www.example.com/img2.png";
GoogleString hash1 = IntegerToString(
HashString<CasePreserve, unsigned>(img1.c_str(), img1.size()));
GoogleString hash2 = IntegerToString(
HashString<CasePreserve, unsigned>(img2.c_str(), img2.size()));
StringSet critical_image_hashes;
critical_image_hashes.insert(hash1);
InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
TestBeacon(&critical_image_hashes, nullptr, nullptr,
UserAgentMatcherTestBase::kChromeUserAgent);
EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ","));
// Beacon both images as critical. Since we require 80% support, img2 won't
// show as critical until we've beaconed four times. It doesn't require five
// beacon results because we weight recent beacon values more heavily and
// beacon support decays over time.
critical_image_hashes.insert(hash2);
for (int i = 0; i < 3; ++i) {
InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
TestBeacon(&critical_image_hashes, nullptr, nullptr,
UserAgentMatcherTestBase::kChromeUserAgent);
EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ","));
}
GoogleString expected = StrCat(hash1, ",", hash2);
InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
TestBeacon(&critical_image_hashes, nullptr, nullptr,
UserAgentMatcherTestBase::kChromeUserAgent);
EXPECT_STREQ(expected, JoinCollection(critical_html_images_, ","));
// Test with a different user agent, providing support only for img1.
critical_image_hashes.clear();
critical_image_hashes.insert(hash1);
InsertImageBeacon(UserAgentMatcherTestBase::kIPhoneUserAgent);
TestBeacon(&critical_image_hashes, nullptr, nullptr,
UserAgentMatcherTestBase::kIPhoneUserAgent);
EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ","));
// Beacon once more with the original user agent and with only img1; img2
// loses 80% support again.
InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
TestBeacon(&critical_image_hashes, nullptr, nullptr,
UserAgentMatcherTestBase::kChromeUserAgent);
EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ","));
}
TEST_F(BeaconTest, HandleBeaconCriticalCss) {
InsertCssBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
StringSet critical_css_selector;
critical_css_selector.insert("%23foo");
critical_css_selector.insert(".bar");
critical_css_selector.insert("%23noncandidate");
TestBeacon(nullptr, &critical_css_selector, nullptr,
UserAgentMatcherTestBase::kChromeUserAgent);
EXPECT_STREQ("#foo,.bar", JoinCollection(critical_css_selectors_, ","));
// Send another beacon response, and make sure we are storing a history of
// responses.
InsertCssBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
critical_css_selector.clear();
critical_css_selector.insert(".bar");
critical_css_selector.insert("img");
critical_css_selector.insert("%23noncandidate");
TestBeacon(nullptr, &critical_css_selector, nullptr,
UserAgentMatcherTestBase::kChromeUserAgent);
EXPECT_STREQ("#foo,.bar,img", JoinCollection(critical_css_selectors_, ","));
}
TEST_F(BeaconTest, EmptyCriticalCss) {
InsertCssBeacon(UserAgentMatcherTestBase::kChromeUserAgent);
StringSet empty_critical_selectors;
TestBeacon(nullptr, &empty_critical_selectors, nullptr,
UserAgentMatcherTestBase::kChromeUserAgent);
EXPECT_TRUE(critical_css_selectors_.empty());
}
class ResourceFreshenTest : public ServerContextTest {
protected:
void SetUp() override {
ServerContextTest::SetUp();
HTTPCache::InitStats(statistics());
expirations_ = statistics()->GetVariable(HTTPCache::kCacheExpirations);
CHECK(expirations_ != nullptr);
SetDefaultLongCacheHeaders(&kContentTypePng, &response_headers_);
response_headers_.SetStatusAndReason(HttpStatus::kOK);
response_headers_.RemoveAll(HttpAttributes::kCacheControl);
response_headers_.RemoveAll(HttpAttributes::kExpires);
}
Variable* expirations_;
ResponseHeaders response_headers_;
};
// Many resources expire in 5 minutes, because that is our default for
// when caching headers are not present. This test ensures that iff
// we ask for the resource when there's just a minute left, we proactively
// fetch it rather than allowing it to expire.
TEST_F(ResourceFreshenTest, TestFreshenImminentlyExpiringResources) {
SetupWaitFetcher();
FetcherUpdateDateHeaders();
// Make sure we don't try to insert non-cacheable resources
// into the cache wastefully, but still fetch them well.
int max_age_sec =
RewriteOptions::kDefaultImplicitCacheTtlMs / Timer::kSecondMs;
response_headers_.Add(HttpAttributes::kCacheControl,
absl::StrFormat("max-age=%d", max_age_sec));
SetFetchResponse(kResourceUrl, response_headers_, "foo");
// The test here is not that the ReadIfCached will succeed, because
// it's a fake url fetcher.
StartRead();
CallFetcherCallbacks();
EXPECT_TRUE(ResourceIsCached());
// Now let the time expire with no intervening fetches to freshen the cache.
// This is because we do not proactively initiate refreshes for all resources;
// only the ones that are actually asked for on a regular basis. So a
// completely inactive site will not see its resources freshened.
AdvanceTimeMs((max_age_sec + 1) * Timer::kSecondMs);
expirations_->Clear();
StartRead();
EXPECT_EQ(1, expirations_->Get());
expirations_->Clear();
CallFetcherCallbacks();
EXPECT_TRUE(ResourceIsCached());
// But if we have just a little bit of traffic then when we get a request
// for a soon-to-expire resource it will auto-freshen.
AdvanceTimeMs((1 + (max_age_sec * 4) / 5) * Timer::kSecondMs);
EXPECT_TRUE(ResourceIsCached());
CallFetcherCallbacks(); // freshens cache.
AdvanceTimeMs((max_age_sec / 5) * Timer::kSecondMs);
EXPECT_TRUE(ResourceIsCached()); // Yay, no cache misses after 301 seconds
EXPECT_EQ(0, expirations_->Get());
}
// Tests that freshining will not be performed when we have caching
// forced. Nothing will ever be evicted due to time, so there is no
// need to freshen.
TEST_F(ResourceFreshenTest, NoFreshenOfForcedCachedResources) {
http_cache()->set_force_caching(true);
FetcherUpdateDateHeaders();
response_headers_.Add(HttpAttributes::kCacheControl, "max-age=0");
SetFetchResponse(kResourceUrl, response_headers_, "foo");
// We should get just 1 fetch. If we were aggressively freshening
// we would get 2.
EXPECT_TRUE(ResourceIsCached());
EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count());
// There should be no extra fetches required because our cache is
// still active. We shouldn't have needed an extra fetch to freshen,
// either, because the cache expiration time is irrelevant -- we are
// forcing caching so we consider the resource to always be fresh.
// So even after an hour we should have no expirations.
AdvanceTimeMs(1 * Timer::kHourMs);
EXPECT_TRUE(ResourceIsCached());
EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count());
// Nothing expires with force-caching on.
EXPECT_EQ(0, expirations_->Get());
}
// Tests that freshining will not occur for short-lived resources,
// which could impact the performance of the server.
TEST_F(ResourceFreshenTest, NoFreshenOfShortLivedResources) {
FetcherUpdateDateHeaders();
int max_age_sec =
RewriteOptions::kDefaultImplicitCacheTtlMs / Timer::kSecondMs - 1;
response_headers_.Add(HttpAttributes::kCacheControl,
absl::StrFormat("max-age=%d", max_age_sec));
SetFetchResponse(kResourceUrl, response_headers_, "foo");
EXPECT_TRUE(ResourceIsCached());
EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count());
// There should be no extra fetches required because our cache is
// still active. We shouldn't have needed an extra fetch to freshen,
// either.
AdvanceTimeMs((max_age_sec - 1) * Timer::kSecondMs);
EXPECT_TRUE(ResourceIsCached());
EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count());
EXPECT_EQ(0, expirations_->Get());
// Now let the resource expire. We'll need another fetch since we did not
// freshen.
AdvanceTimeMs(2 * Timer::kSecondMs);
EXPECT_TRUE(ResourceIsCached());
EXPECT_EQ(2, counting_url_async_fetcher()->fetch_count());
EXPECT_EQ(1, expirations_->Get());
}
class ServerContextShardedTest : public ServerContextTest {
protected:
void SetUp() override {
ServerContextTest::SetUp();
EXPECT_TRUE(options()->WriteableDomainLawyer()->AddShard(
"example.com", "shard0.com,shard1.com", message_handler()));
}
};
TEST_F(ServerContextShardedTest, TestNamed) {
GoogleString url =
Encode("http://example.com/dir/123/", "jm", "0", "orig", "js");
GoogleString failure_reason;
OutputResourcePtr output_resource(
rewrite_driver()->CreateOutputResourceWithPath(
"http://example.com/dir/", "jm", "orig.js", kRewrittenResource,
&failure_reason));
ASSERT_TRUE(output_resource.get());
EXPECT_EQ("", failure_reason);
ASSERT_TRUE(rewrite_driver()->Write(ResourceVector(), "alert('hello');",
&kContentTypeJavascript, StringPiece(),
output_resource.get()));
// This always gets mapped to shard0 because we are using the mock
// hasher for the content hash. Note that the sharding sensitivity
// to the hash value is tested in DomainLawyerTest.Shard, and will
// also be covered in a system test.
EXPECT_EQ(Encode("http://shard0.com/dir/", "jm", "0", "orig.js", "js"),
output_resource->url());
}
TEST_F(ServerContextTest, TestMergeNonCachingResponseHeaders) {
ResponseHeaders input, output;
input.Add("X-Extra-Header", "Extra Value"); // should be copied to output
input.Add(HttpAttributes::kCacheControl, "max-age=300"); // should not be
server_context()->MergeNonCachingResponseHeaders(input, &output);
ConstStringStarVector v;
EXPECT_FALSE(output.Lookup(HttpAttributes::kCacheControl, &v));
ASSERT_TRUE(output.Lookup("X-Extra-Header", &v));
ASSERT_EQ(1, v.size());
EXPECT_EQ("Extra Value", *v[0]);
}
class ServerContextCacheControlTest : public ServerContextTest {
protected:
void SetUp() override {
ServerContextTest::SetUp();
implicit_public_100_ = CreateCustomCachingResource("ipub_100", 100, "");
implicit_public_200_ = CreateCustomCachingResource("ipub_200", 200, "");
explicit_public_200_ =
CreateCustomCachingResource("epub_200", 200, ",public");
private_300_ = CreateCustomCachingResource("pri_300", 300, ",private");
private_400_ = CreateCustomCachingResource("pri_400", 400, ",private");
no_cache_150_ = CreateCustomCachingResource("noc_150", 400, ",no-cache");
no_store_200_ = CreateCustomCachingResource("nos_200", 200, ",no-store");
DefaultHeaders(&response_headers_);
}
GoogleString LongCacheTtl() const {
return StrCat("max-age=",
Integer64ToString(ServerContext::kGeneratedMaxAgeMs /
Timer::kSecondMs));
}
bool HasCacheControl(StringPiece value) {
return response_headers_.HasValue(HttpAttributes::kCacheControl, value);
}
ResourcePtr implicit_public_100_;
ResourcePtr implicit_public_200_;
ResourcePtr explicit_public_200_;
ResourcePtr private_300_;
ResourcePtr private_400_;
ResourcePtr no_cache_150_;
ResourcePtr no_store_200_;
ResourceVector resources_;
ResponseHeaders response_headers_;
};
TEST_F(ServerContextCacheControlTest, ImplicitPublic) {
// If we feed in just implicitly public resources, we should get
// something with ultra-long TTL, regardless of how soon they
// expire.
resources_.push_back(implicit_public_100_);
resources_.push_back(implicit_public_200_);
server_context()->ApplyInputCacheControl(resources_, &response_headers_);
EXPECT_STREQ(LongCacheTtl(),
response_headers_.Lookup1(HttpAttributes::kCacheControl));
}
TEST_F(ServerContextCacheControlTest, ExplicitPublic) {
// An explicit 'public' gets reflected in the output.
resources_.push_back(explicit_public_200_);
server_context()->ApplyInputCacheControl(resources_, &response_headers_);
EXPECT_TRUE(HasCacheControl("public"));
EXPECT_FALSE(HasCacheControl("private"));
EXPECT_TRUE(HasCacheControl(LongCacheTtl()));
}
TEST_F(ServerContextCacheControlTest, Private) {
// If an input is private, however, we must mark output appropriately
// and not cache-extend.
resources_.push_back(implicit_public_100_);
resources_.push_back(private_300_);
resources_.push_back(private_400_);
server_context()->ApplyInputCacheControl(resources_, &response_headers_);
EXPECT_FALSE(HasCacheControl("public"));
EXPECT_TRUE(HasCacheControl("private"));
EXPECT_TRUE(HasCacheControl("max-age=100"));
}
TEST_F(ServerContextCacheControlTest, NoCache) {
// Similarly no-cache should be incorporated --- but then we also need
// to have 0 ttl.
resources_.push_back(implicit_public_100_);
resources_.push_back(private_300_);
resources_.push_back(private_400_);
resources_.push_back(no_cache_150_);
server_context()->ApplyInputCacheControl(resources_, &response_headers_);
EXPECT_FALSE(HasCacheControl("public"));
EXPECT_TRUE(HasCacheControl("no-cache"));
EXPECT_TRUE(HasCacheControl("max-age=0"));
}
TEST_F(ServerContextCacheControlTest, NoStore) {
// Make sure we save no-store as well.
resources_.push_back(implicit_public_100_);
resources_.push_back(private_300_);
resources_.push_back(private_400_);
resources_.push_back(no_cache_150_);
resources_.push_back(no_store_200_);
server_context()->ApplyInputCacheControl(resources_, &response_headers_);
EXPECT_FALSE(HasCacheControl("public"));
EXPECT_TRUE(HasCacheControl("no-cache"));
EXPECT_TRUE(HasCacheControl("no-store"));
EXPECT_TRUE(HasCacheControl("max-age=0"));
}
TEST_F(ServerContextTest, WriteChecksInputVector) {
// Make sure ->Write incorporates the cache control info from inputs,
// and doesn't cache a private resource improperly. Also make sure
// we get the charset right (including quoting).
ResourcePtr private_400(
CreateCustomCachingResource("pri_400", 400, ",private"));
// Should have the 'it's not cacheable!' entry here; see also below.
EXPECT_EQ(1, http_cache()->cache_inserts()->Get());
GoogleString failure_reason;
OutputResourcePtr output_resource(
rewrite_driver()->CreateOutputResourceFromResource(
"cf", rewrite_driver()->default_encoder(), nullptr /* no context*/,
private_400, kRewrittenResource, &failure_reason));
ASSERT_TRUE(output_resource.get() != nullptr);
EXPECT_EQ("", failure_reason);
rewrite_driver()->Write(ResourceVector(1, private_400), "boo!",
&kContentTypeText,
"\"\\koi8-r\"", // covers escaping behavior, too.
output_resource.get());
ResponseHeaders* headers = output_resource->response_headers();
EXPECT_FALSE(headers->HasValue(HttpAttributes::kCacheControl, "public"));
EXPECT_TRUE(headers->HasValue(HttpAttributes::kCacheControl, "private"));
EXPECT_TRUE(headers->HasValue(HttpAttributes::kCacheControl, "max-age=400"));
EXPECT_STREQ("text/plain; charset=\"\\koi8-r\"",
headers->Lookup1(HttpAttributes::kContentType));
// Make sure nothing extra in the cache at this point.
EXPECT_EQ(1, http_cache()->cache_inserts()->Get());
}
TEST_F(ServerContextTest, IsPagespeedResource) {
GoogleUrl rewritten(
Encode("http://shard0.com/dir/", "jm", "0", "orig.js", "js"));
EXPECT_TRUE(server_context()->IsPagespeedResource(rewritten));
GoogleUrl normal("http://jqueryui.com/jquery-1.6.2.js");
EXPECT_FALSE(server_context()->IsPagespeedResource(normal));
}
TEST_F(ServerContextTest, PartlyFailedFetch) {
// Regression test for invalid Resource state when the fetch physically
// succeeds but does not get added to cache due to invalid cacheability.
// In that case, we would end up with headers claiming successful fetch,
// but an HTTPValue without headers set (which would also crash on
// access if no data was emitted by fetcher via Write).
static const char kCssName[] = "a.css";
GoogleString abs_url = AbsolutifyUrl(kCssName);
ResponseHeaders non_cacheable;
SetDefaultLongCacheHeaders(&kContentTypeCss, &non_cacheable);
non_cacheable.SetDateAndCaching(start_time_ms() /* date */, 0 /* ttl */,
"private, no-cache");
non_cacheable.ComputeCaching();
SetFetchResponse(abs_url, non_cacheable, "foo");
// We tell the fetcher to quash the zero-bytes writes, as that behavior
// (which Serf has) made the bug more severe, with not only
// loaded() and HttpStatusOk() lying, but also contents() crashing.
mock_url_fetcher()->set_omit_empty_writes(true);
// We tell the fetcher to output the headers and then immediately fail.
mock_url_fetcher()->set_fail_after_headers(true);
GoogleUrl gurl(abs_url);
SetBaseUrlForFetch(abs_url);
bool is_authorized;
ResourcePtr resource = rewrite_driver()->CreateInputResource(
gurl, RewriteDriver::InputRole::kStyle, &is_authorized);
ASSERT_TRUE(resource.get() != nullptr);
EXPECT_TRUE(is_authorized);
MockResourceCallback callback(resource, factory()->thread_system());
resource->LoadAsync(Resource::kReportFailureIfNotCacheable,
rewrite_driver()->request_context(), &callback);
EXPECT_TRUE(callback.done());
EXPECT_FALSE(callback.success());
EXPECT_FALSE(resource->IsValidAndCacheable());
EXPECT_FALSE(resource->loaded());
EXPECT_FALSE(resource->HttpStatusOk())
<< " Unexpectedly got access to resource contents:"
<< resource->ExtractUncompressedContents();
}
TEST_F(ServerContextTest, LoadFromFileReadAsync) {
// This reads a resource twice, to make sure that there is no misbehavior
// (read: check failures or crashes) when cache invalidation logic tries to
// deal with FileInputResource.
const char kContents[] = "lots of bits of data";
options()->file_load_policy()->Associate("http://test.com/", "/test/");
GoogleUrl test_url("http://test.com/a.css");
// Init file resources.
WriteFile("/test/a.css", kContents);
SetBaseUrlForFetch("http://test.com");
bool unused;
ResourcePtr resource(rewrite_driver()->CreateInputResource(
test_url, RewriteDriver::InputRole::kStyle, &unused));
VerifyContentsCallback callback(resource, kContents);
resource->LoadAsync(Resource::kReportFailureIfNotCacheable,
rewrite_driver()->request_context(), &callback);
callback.AssertCalled();
resource = rewrite_driver()->CreateInputResource(
test_url, RewriteDriver::InputRole::kStyle, &unused);
VerifyContentsCallback callback2(resource, kContents);
resource->LoadAsync(Resource::kReportFailureIfNotCacheable,
rewrite_driver()->request_context(), &callback2);
callback2.AssertCalled();
}
namespace {
void CheckMatchesHeaders(const ResponseHeaders& headers,
const InputInfo& input) {
ASSERT_TRUE(input.has_type());
EXPECT_EQ(InputInfo::CACHED, input.type());
EXPECT_EQ(headers.has_last_modified_time_ms(),
input.has_last_modified_time_ms());
EXPECT_EQ(headers.last_modified_time_ms(), input.last_modified_time_ms());
ASSERT_TRUE(input.has_expiration_time_ms());
EXPECT_EQ(headers.CacheExpirationTimeMs(), input.expiration_time_ms());
ASSERT_TRUE(input.has_date_ms());
EXPECT_EQ(headers.date_ms(), input.date_ms());
}
} // namespace
TEST_F(ServerContextTest, FillInPartitionInputInfo) {
// Test for Resource::FillInPartitionInputInfo.
const char kUrl[] = "http://example.com/page.html";
const char kContents[] = "bits";
SetBaseUrlForFetch("http://example.com/");
ResponseHeaders headers;
SetDefaultLongCacheHeaders(&kContentTypeHtml, &headers);
headers.ComputeCaching();
SetFetchResponse(kUrl, headers, kContents);
GoogleUrl gurl(kUrl);
bool unused;
ResourcePtr resource(rewrite_driver()->CreateInputResource(
gurl, RewriteDriver::InputRole::kUnknown, &unused));
VerifyContentsCallback callback(resource, kContents);
resource->LoadAsync(Resource::kReportFailureIfNotCacheable,
rewrite_driver()->request_context(), &callback);
callback.AssertCalled();
InputInfo with_hash, without_hash;
resource->FillInPartitionInputInfo(Resource::kIncludeInputHash, &with_hash);
resource->FillInPartitionInputInfo(Resource::kOmitInputHash, &without_hash);
CheckMatchesHeaders(headers, with_hash);
CheckMatchesHeaders(headers, without_hash);
ASSERT_TRUE(with_hash.has_input_content_hash());
EXPECT_STREQ("zEEebBNnDlISRim4rIP30", with_hash.input_content_hash());
EXPECT_FALSE(without_hash.has_input_content_hash());
resource->response_headers()->RemoveAll(HttpAttributes::kLastModified);
resource->response_headers()->ComputeCaching();
EXPECT_FALSE(resource->response_headers()->has_last_modified_time_ms());
InputInfo without_last_modified;
resource->FillInPartitionInputInfo(Resource::kOmitInputHash,
&without_last_modified);
CheckMatchesHeaders(*resource->response_headers(), without_last_modified);
}
// Test of referer for BackgroundFetch: When the resource fetching request
// header misses referer, we set the driver base url as its referer.
TEST_F(ServerContextTest, TestRefererBackgroundFetch) {
RefererTest(nullptr, true);
EXPECT_EQ(rewrite_driver()->base_url().Spec(),
mock_url_fetcher()->last_referer());
}
// Test of referer for NonBackgroundFetch: When the resource fetching request
// header misses referer and the original request referer header misses, no
// referer would be added.
TEST_F(ServerContextTest, TestRefererNonBackgroundFetch) {
RequestHeaders headers;
RefererTest(&headers, false);
EXPECT_EQ("", mock_url_fetcher()->last_referer());
}
// Test of referer for NonBackgroundFetch: When the resource fetching request
// header misses referer but the original request header has referer set, we set
// this referer as the referer of resource fetching request.
TEST_F(ServerContextTest, TestRefererNonBackgroundFetchWithDriverRefer) {
RequestHeaders headers;
const char kReferer[] = "http://other.com/";
headers.Add(HttpAttributes::kReferer, kReferer);
RefererTest(&headers, false);
EXPECT_EQ(kReferer, mock_url_fetcher()->last_referer());
}
// Regression test for RewriteTestBase::DefaultResponseHeaders, which is based
// on ServerContext methods. It used to not set 'Expires' correctly.
TEST_F(ServerContextTest, RewriteTestBaseDefaultResponseHeaders) {
ResponseHeaders headers;
DefaultResponseHeaders(kContentTypeCss, 100 /* ttl_sec */, &headers);
int64 expire_time_ms = 0;
ASSERT_TRUE(
headers.ParseDateHeader(HttpAttributes::kExpires, &expire_time_ms));
EXPECT_EQ(timer()->NowMs() + 100 * Timer::kSecondMs, expire_time_ms);
}
} // namespace net_instaweb
| 43.146748 | 80 | 0.733719 | wernight |
61bb9fffd12b78f13328c8d191118c5f6d699d1e | 5,018 | cpp | C++ | src/scene/lightsource.cpp | agarwalutkarsh554/OpenSpace | 5b3f2f10d33121ed40bb9833d79197897f13a857 | [
"MIT"
] | null | null | null | src/scene/lightsource.cpp | agarwalutkarsh554/OpenSpace | 5b3f2f10d33121ed40bb9833d79197897f13a857 | [
"MIT"
] | null | null | null | src/scene/lightsource.cpp | agarwalutkarsh554/OpenSpace | 5b3f2f10d33121ed40bb9833d79197897f13a857 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2021 *
* *
* 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 <openspace/scene/lightsource.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/util/factorymanager.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/dictionary.h>
#include <ghoul/misc/templatefactory.h>
namespace {
constexpr const char* KeyType = "Type";
constexpr const char* KeyIdentifier = "Identifier";
constexpr openspace::properties::Property::PropertyInfo EnabledInfo = {
"Enabled",
"Enabled",
"Whether the light source is enabled or not"
};
} // namespace
namespace openspace {
bool LightSource::isEnabled() const {
return _enabled;
}
documentation::Documentation LightSource::Documentation() {
using namespace openspace::documentation;
return {
"Light Source",
"core_light_source",
{
{
KeyType,
new StringAnnotationVerifier("Must name a valid LightSource type"),
Optional::No,
"The type of the light source that is described in this element. "
"The available types of light sources depend on the configuration "
"of the application and can be written to disk on "
"application startup into the FactoryDocumentation."
},
{
KeyIdentifier,
new StringVerifier,
Optional::No,
"The identifier of the light source."
},
{
EnabledInfo.identifier,
new BoolVerifier,
Optional::Yes,
EnabledInfo.description
}
}
};
}
std::unique_ptr<LightSource> LightSource::createFromDictionary(
const ghoul::Dictionary& dictionary)
{
documentation::testSpecificationAndThrow(Documentation(), dictionary, "LightSource");
const std::string timeFrameType = dictionary.value<std::string>(KeyType);
auto factory = FactoryManager::ref().factory<LightSource>();
LightSource* source = factory->create(timeFrameType, dictionary);
const std::string identifier = dictionary.value<std::string>(KeyIdentifier);
source->setIdentifier(identifier);
return std::unique_ptr<LightSource>(source);
}
LightSource::LightSource()
: properties::PropertyOwner({ "LightSource" })
, _enabled(EnabledInfo, true)
{
addProperty(_enabled);
}
LightSource::LightSource(const ghoul::Dictionary& dictionary)
: properties::PropertyOwner({ "LightSource" })
, _enabled(EnabledInfo, true)
{
if (dictionary.hasValue<bool>(EnabledInfo.identifier)) {
_enabled = dictionary.value<bool>(EnabledInfo.identifier);
}
addProperty(_enabled);
}
bool LightSource::initialize() {
return true;
}
} // namespace openspace
| 40.144 | 90 | 0.548824 | agarwalutkarsh554 |
61bba88a498af9245f6f854201678d903305b16e | 222 | cpp | C++ | predavanje1/petlje3.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | predavanje1/petlje3.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | predavanje1/petlje3.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | #include <iostream>
using std::cout;
int main(void)
{
for (int i = 0; i < 10;)
{
cout << i;
}
int i = 0;
for (;;)
{
cout << i;
}
}
// i jedan i drugi for loop rade infinite loop | 13.875 | 46 | 0.459459 | Miillky |
61be1ed9419420046c10b11190d437708114aa91 | 714 | cpp | C++ | tests/Basic/ConsoleLogger/main.cpp | cash2/cash2 | 6ac125db7002d8b04232750e7bf8b46b46f6481f | [
"BSD-3-Clause"
] | 5 | 2018-12-29T11:47:17.000Z | 2021-04-30T11:40:15.000Z | tests/Basic/ConsoleLogger/main.cpp | aphivantrakul/cash2 | 6ac125db7002d8b04232750e7bf8b46b46f6481f | [
"BSD-3-Clause"
] | 2 | 2019-07-10T15:53:44.000Z | 2021-06-26T17:41:46.000Z | tests/Basic/ConsoleLogger/main.cpp | aphivantrakul/cash2 | 6ac125db7002d8b04232750e7bf8b46b46f6481f | [
"BSD-3-Clause"
] | 10 | 2018-11-25T18:45:50.000Z | 2022-03-21T17:19:42.000Z | // Copyright (c) 2018-2021 The Cash2 developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "gtest/gtest.h"
#include "Logging/ConsoleLogger.h"
using namespace Logging;
// constructor
TEST(ConsoleLogger, 1)
{
ConsoleLogger logger1;
Level level = Level::DEBUGGING;
ConsoleLogger logger2(level);
ConsoleLogger logger3(Level::FATAL);
ConsoleLogger logger4(Level::ERROR);
ConsoleLogger logger5(Level::WARNING);
ConsoleLogger logger6(Level::INFO);
ConsoleLogger logger7(Level::TRACE);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 24.62069 | 71 | 0.747899 | cash2 |
61be9fcc0639c62a17f02b085e37c2698ffd833c | 8,712 | cpp | C++ | source/JsonValidation.cpp | 0xflotus/mariana-trench | 6c8c28a2b89a9eea70c09cae9b594ae4594d97a6 | [
"MIT"
] | null | null | null | source/JsonValidation.cpp | 0xflotus/mariana-trench | 6c8c28a2b89a9eea70c09cae9b594ae4594d97a6 | [
"MIT"
] | 4 | 2021-08-21T07:51:53.000Z | 2022-02-27T20:22:41.000Z | source/JsonValidation.cpp | LaudateCorpus1/mariana-trench | 35595e2782d823a5ed9908dd4fe3bdc06d611ba1 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <sstream>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem/fstream.hpp>
#include <fmt/format.h>
#include <mariana-trench/Assert.h>
#include <mariana-trench/JsonValidation.h>
#include <mariana-trench/Log.h>
#include <mariana-trench/Redex.h>
namespace marianatrench {
namespace {
std::string invalid_argument_message(
const Json::Value& value,
const std::optional<std::string>& field,
const std::string& expected) {
auto field_information = field ? fmt::format(" for field `{}`", *field) : "";
return fmt::format(
"Error validating `{}`. Expected {}{}.",
boost::algorithm::trim_copy(JsonValidation::to_styled_string(value)),
expected,
field_information);
}
} // namespace
JsonValidationError::JsonValidationError(
const Json::Value& value,
const std::optional<std::string>& field,
const std::string& expected)
: std::invalid_argument(invalid_argument_message(value, field, expected)) {}
void JsonValidation::validate_object(const Json::Value& value) {
if (value.isNull() || !value.isObject()) {
throw JsonValidationError(
value, /* field */ std::nullopt, /* expected */ "non-null object");
}
}
const Json::Value& JsonValidation::object(
const Json::Value& value,
const std::string& field) {
validate_object(value);
const auto& attribute = value[field];
if (attribute.isNull() || !attribute.isObject()) {
throw JsonValidationError(value, field, /* expected */ "non-null object");
}
return attribute;
}
std::string JsonValidation::string(const Json::Value& value) {
if (value.isNull() || !value.isString()) {
throw JsonValidationError(
value, /* field */ std::nullopt, /* expected */ "string");
}
return value.asString();
}
std::string JsonValidation::string(
const Json::Value& value,
const std::string& field) {
validate_object(value);
const auto& string = value[field];
if (string.isNull() || !string.isString()) {
throw JsonValidationError(value, field, /* expected */ "string");
}
return string.asString();
}
int JsonValidation::integer(const Json::Value& value) {
if (value.isNull() || !value.isInt()) {
throw JsonValidationError(
value, /* field */ std::nullopt, /* expected */ "integer");
}
return value.asInt();
}
int JsonValidation::integer(
const Json::Value& value,
const std::string& field) {
validate_object(value);
const auto& integer = value[field];
if (integer.isNull() || !integer.isInt()) {
throw JsonValidationError(value, field, /* expected */ "integer");
}
return integer.asInt();
}
bool JsonValidation::boolean(const Json::Value& value) {
if (value.isNull() || !value.isBool()) {
throw JsonValidationError(
value, /* field */ std::nullopt, /* expected */ "boolean");
}
return value.asBool();
}
bool JsonValidation::boolean(
const Json::Value& value,
const std::string& field) {
validate_object(value);
const auto& boolean = value[field];
if (boolean.isNull() || !boolean.isBool()) {
throw JsonValidationError(value, field, /* expected */ "boolean");
}
return boolean.asBool();
}
const Json::Value& JsonValidation::null_or_array(const Json::Value& value) {
if (!value.isNull() && !value.isArray()) {
throw JsonValidationError(
value, /* field */ std::nullopt, /* expected */ "null or array");
}
return value;
}
const Json::Value& JsonValidation::null_or_array(
const Json::Value& value,
const std::string& field) {
validate_object(value);
const auto& null_or_array = value[field];
if (!null_or_array.isNull() && !null_or_array.isArray()) {
throw JsonValidationError(value, field, /* expected */ "null or array");
}
return null_or_array;
}
const Json::Value& JsonValidation::nonempty_array(
const Json::Value& value,
const std::string& field) {
validate_object(value);
const auto& nonempty_array = value[field];
if (nonempty_array.isNull() || !nonempty_array.isArray() ||
nonempty_array.empty()) {
throw JsonValidationError(value, field, /* expected */ "non-empty array");
}
return nonempty_array;
}
const Json::Value& JsonValidation::object_or_string(
const Json::Value& value,
const std::string& field) {
validate_object(value);
const auto& attribute = value[field];
if (attribute.isNull() || (!attribute.isObject() && !attribute.isString())) {
throw JsonValidationError(value, field, /* expected */ "object or string");
}
return attribute;
}
DexType* JsonValidation::dex_type(const Json::Value& value) {
auto type_name = JsonValidation::string(value);
auto* type = redex::get_type(type_name);
if (!type) {
throw JsonValidationError(
value,
/* field */ std::nullopt,
/* expected */ "existing type name");
}
return type;
}
DexType* JsonValidation::dex_type(
const Json::Value& value,
const std::string& field) {
auto type_name = JsonValidation::string(value, field);
auto* type = redex::get_type(type_name);
if (!type) {
throw JsonValidationError(
value,
field,
/* expected */ "existing type name");
}
return type;
}
DexFieldRef* JsonValidation::dex_field(const Json::Value& value) {
auto field_name = JsonValidation::string(value);
auto* dex_field = redex::get_field(field_name);
if (!dex_field) {
throw JsonValidationError(
value, /* field */ std::nullopt, /* expected */ "existing field name");
}
return dex_field;
}
DexFieldRef* JsonValidation::dex_field(
const Json::Value& value,
const std::string& field) {
auto field_name = JsonValidation::string(value, field);
auto* dex_field = redex::get_field(field_name);
if (!dex_field) {
throw JsonValidationError(
value, field, /* expected */ "existing field name");
}
return dex_field;
}
Json::Value JsonValidation::parse_json(std::string string) {
std::istringstream stream(std::move(string));
static const auto reader = Json::CharReaderBuilder();
std::string errors;
Json::Value json;
if (!Json::parseFromStream(reader, stream, &json, &errors)) {
throw std::invalid_argument(fmt::format("Invalid json: {}", errors));
}
return json;
}
Json::Value JsonValidation::parse_json_file(
const boost::filesystem::path& path) {
boost::filesystem::ifstream file;
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
file.open(path, std::ios_base::binary);
} catch (const std::ifstream::failure&) {
ERROR(1, "Could not open json file: `{}`.", path.string());
throw;
}
static const auto reader = Json::CharReaderBuilder();
std::string errors;
Json::Value json;
if (!Json::parseFromStream(reader, file, &json, &errors)) {
throw std::invalid_argument(
fmt::format("File `{}` is not valid json: {}", path.string(), errors));
}
return json;
}
Json::Value JsonValidation::parse_json_file(const std::string& path) {
return parse_json_file(boost::filesystem::path(path));
}
namespace {
Json::StreamWriterBuilder compact_writer_builder() {
Json::StreamWriterBuilder writer;
writer["indentation"] = "";
return writer;
}
Json::StreamWriterBuilder styled_writer_builder() {
Json::StreamWriterBuilder writer;
writer["indentation"] = " ";
return writer;
}
} // namespace
std::unique_ptr<Json::StreamWriter> JsonValidation::compact_writer() {
static const auto writer_builder = compact_writer_builder();
return std::unique_ptr<Json::StreamWriter>(writer_builder.newStreamWriter());
}
std::unique_ptr<Json::StreamWriter> JsonValidation::styled_writer() {
static const auto writer_builder = styled_writer_builder();
return std::unique_ptr<Json::StreamWriter>(writer_builder.newStreamWriter());
}
void JsonValidation::write_json_file(
const boost::filesystem::path& path,
const Json::Value& value) {
boost::filesystem::ofstream file;
file.exceptions(std::ofstream::failbit | std::ofstream::badbit);
file.open(path, std::ios_base::binary);
compact_writer()->write(value, &file);
file << "\n";
file.close();
}
std::string JsonValidation::to_styled_string(const Json::Value& value) {
std::ostringstream string;
styled_writer()->write(value, &string);
return string.str();
}
void JsonValidation::update_object(
Json::Value& left,
const Json::Value& right) {
mt_assert(left.isObject());
mt_assert(right.isObject());
for (const auto& key : right.getMemberNames()) {
left[key] = right[key];
}
}
} // namespace marianatrench
| 28.847682 | 80 | 0.680096 | 0xflotus |
61c258a5695408e8a195255a39381d1ffa2d27eb | 4,066 | hpp | C++ | src/mongocxx/options/data_key.hpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/options/data_key.hpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/options/data_key.hpp | lzlzymy/mongo-cxx-driver | bcdeb3ad9412f6b7b87a45dc3384ad18759ac572 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 MongoDB 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.
#pragma once
#include <string>
#include <vector>
#include <bsoncxx/document/view_or_value.hpp>
#include <bsoncxx/stdx/optional.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/config/prelude.hpp>
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
class client_encryption;
namespace options {
///
/// Class representing options for data key generation for encryption.
///
class MONGOCXX_API data_key {
public:
///
/// Sets a KMS-specific key used to encrypt the new data key.
///
/// If the KMS provider is "aws" the masterKey is required and has the following fields:
///
/// {
/// region: String,
/// key: String, // The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
/// endpoint: Optional<String> // An alternate host identifier to send KMS requests to. May
/// include port number. Defaults to "kms.<region>.amazonaws.com"
/// }
///
/// If the KMS provider is "azure" the masterKey is required and has the following fields:
///
/// {
/// keyVaultEndpoint: String, // Host with optional port. Example: "example.vault.azure.net".
/// keyName: String,
/// keyVersion: Optional<String> // A specific version of the named key, defaults to using
/// the key's primary version.
/// }
///
/// If the KMS provider is "gcp" the masterKey is required and has the following fields:
///
/// {
/// projectId: String,
/// location: String,
/// keyRing: String,
/// keyName: String,
/// keyVersion: Optional<String>, // A specific version of the named key, defaults to using
/// the key's primary version.
/// endpoint: Optional<String> // Host with optional port. Defaults to
/// "cloudkms.googleapis.com".
/// }
///
/// If the KMS provider is "local" the masterKey is not applicable.
///
/// @param master_key
/// The document representing the master key.
///
/// @return
/// A reference to this object.
///
/// @see https://docs.mongodb.com/manual/core/security-client-side-encryption-key-management/
///
data_key& master_key(bsoncxx::document::view_or_value master_key);
///
/// Gets the master key.
///
/// @return
/// An optional document containing the master key.
///
const stdx::optional<bsoncxx::document::view_or_value>& master_key() const;
///
/// Sets an optional list of string alternate names used to reference the key.
/// If a key is created with alternate names, then encryption may refer to the
/// key by the unique alternate name instead of by _id.
///
/// @param key_alt_names
/// The alternate names for the key.
///
/// @return
/// A reference to this object.
///
/// @see https://docs.mongodb.com/manual/reference/method/getClientEncryption/
///
data_key& key_alt_names(std::vector<std::string> key_alt_names);
///
/// Gets the alternate names for the data key.
///
/// @return
/// The alternate names for the data key.
///
const std::vector<std::string>& key_alt_names() const;
private:
friend class mongocxx::client_encryption;
MONGOCXX_PRIVATE void* convert() const;
stdx::optional<bsoncxx::document::view_or_value> _master_key;
std::vector<std::string> _key_alt_names;
};
} // namespace options
MONGOCXX_INLINE_NAMESPACE_END
} // namespace mongocxx
| 32.015748 | 100 | 0.652484 | lzlzymy |
61c2fc452c05e65d2f31a88f5076353bfb6237a0 | 10,532 | cpp | C++ | src/mfx/pi/export.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/pi/export.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/pi/export.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | /*****************************************************************************
export.cpp
Author: Laurent de Soras, 2016
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/Err.h"
#include "mfx/piapi/FactoryTpl.h"
#include "mfx/pi/adsr/EnvAdsr.h"
#include "mfx/pi/adsr/EnvAdsrDesc.h"
#include "mfx/pi/bmp1/BigMuff1.h"
#include "mfx/pi/bmp1/BigMuff1Desc.h"
#include "mfx/pi/click/Click.h"
#include "mfx/pi/click/ClickDesc.h"
#include "mfx/pi/colorme/ColorMe.h"
#include "mfx/pi/colorme/ColorMeDesc.h"
#include "mfx/pi/cpx/Compex.h"
#include "mfx/pi/cpx/CompexDesc.h"
#include "mfx/pi/dclip/DiodeClipper.h"
#include "mfx/pi/dclip/DiodeClipperDesc.h"
#include "mfx/pi/dist1/DistoSimple.h"
#include "mfx/pi/dist1/DistoSimpleDesc.h"
#include "mfx/pi/dist2/Disto2x.h"
#include "mfx/pi/dist2/Disto2xDesc.h"
#include "mfx/pi/dist3/Dist3.h"
#include "mfx/pi/dist3/Dist3Desc.h"
#include "mfx/pi/distapf/DistApf.h"
#include "mfx/pi/distapf/DistApfDesc.h"
#include "mfx/pi/distpwm/DistoPwm.h"
#include "mfx/pi/distpwm/DistoPwmDesc.h"
#include "mfx/pi/distpwm2/DistoPwm2.h"
#include "mfx/pi/distpwm2/DistoPwm2Desc.h"
#include "mfx/pi/dly0/Delay.h"
#include "mfx/pi/dly0/DelayDesc.h"
#include "mfx/pi/dly1/Delay.h"
#include "mfx/pi/dly1/DelayDesc.h"
#include "mfx/pi/dly2/Delay2.h"
#include "mfx/pi/dly2/Delay2Desc.h"
#include "mfx/pi/dtone1/DistTone.h"
#include "mfx/pi/dtone1/DistToneDesc.h"
#include "mfx/pi/dwm/DryWet.h"
#include "mfx/pi/dwm/DryWetDesc.h"
#include "mfx/pi/envf/EnvFollow.h"
#include "mfx/pi/envf/EnvFollowDesc.h"
#include "mfx/pi/freqsh/FrequencyShifter.h"
#include "mfx/pi/freqsh/FreqShiftDesc.h"
#include "mfx/pi/flancho/Flancho.h"
#include "mfx/pi/flancho/FlanchoDesc.h"
#include "mfx/pi/fsplit/FreqSplit.h"
#include "mfx/pi/fsplit/FreqSplitDesc.h"
#include "mfx/pi/fv/Freeverb.h"
#include "mfx/pi/fv/FreeverbDesc.h"
#include "mfx/pi/hcomb/HyperComb.h"
#include "mfx/pi/hcomb/HyperCombDesc.h"
#include "mfx/pi/iifix/IIFix.h"
#include "mfx/pi/iifix/IIFixDesc.h"
#include "mfx/pi/lfo1/Lfo.h"
#include "mfx/pi/lfo1/LfoDesc.h"
#include "mfx/pi/lpfs/Squeezer.h"
#include "mfx/pi/lpfs/SqueezerDesc.h"
#include "mfx/pi/moog1/MoogLpf.h"
#include "mfx/pi/moog1/MoogLpfDesc.h"
#include "mfx/pi/nzbl/NoiseBleach.h"
#include "mfx/pi/nzbl/NoiseBleachDesc.h"
#include "mfx/pi/nzcl/NoiseChlorine.h"
#include "mfx/pi/nzcl/NoiseChlorineDesc.h"
#include "mfx/pi/osdet/OnsetDetect.h"
#include "mfx/pi/osdet/OnsetDetectDesc.h"
//#include "mfx/pi/osdet2/OnsetDetect2.h"
//#include "mfx/pi/osdet2/OnsetDetect2Desc.h"
#include "mfx/pi/peq/PEq.h"
#include "mfx/pi/peq/PEqDesc.h"
#include "mfx/pi/phase1/Phaser.h"
#include "mfx/pi/phase1/PhaserDesc.h"
#include "mfx/pi/phase2/Phaser2.h"
#include "mfx/pi/phase2/Phaser2Desc.h"
#include "mfx/pi/pidet/PitchDetect.h"
#include "mfx/pi/pidet/PitchDetectDesc.h"
#include "mfx/pi/psh1/PitchShift1.h"
#include "mfx/pi/psh1/PitchShift1Desc.h"
#include "mfx/pi/ramp/Ramp.h"
#include "mfx/pi/ramp/RampDesc.h"
#include "mfx/pi/smood/SkoolMood.h"
#include "mfx/pi/smood/SkoolMoodDesc.h"
#include "mfx/pi/syn0/Synth0.h"
#include "mfx/pi/syn0/Synth0Desc.h"
#include "mfx/pi/spkem/SpeakerEmu.h"
#include "mfx/pi/spkem/SpeakerEmuDesc.h"
#include "mfx/pi/testgen/TestGen.h"
#include "mfx/pi/testgen/TestGenDesc.h"
#include "mfx/pi/tost/ToStereo.h"
#include "mfx/pi/tost/ToStereoDesc.h"
#include "mfx/pi/trem1/Tremolo.h"
#include "mfx/pi/trem1/TremoloDesc.h"
#include "mfx/pi/tremh/HarmTrem.h"
#include "mfx/pi/tremh/HarmTremDesc.h"
#include "mfx/pi/tuner/Tuner.h"
#include "mfx/pi/tuner/TunerDesc.h"
#include "mfx/pi/wah1/Wah.h"
#include "mfx/pi/wah1/WahDesc.h"
#include "mfx/pi/wah2/Wah2.h"
#include "mfx/pi/wah2/Wah2Desc.h"
#include "mfx/pi/export.h"
#include <cassert>
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
fstb_EXPORT (int fstb_CDECL enum_factories (std::vector <std::shared_ptr <mfx::piapi::FactoryInterface> > &fact_list))
{
int ret_val = fstb::Err_OK;
try
{
static const std::vector <std::shared_ptr <mfx::piapi::FactoryInterface> > l =
{
mfx::piapi::FactoryTpl <mfx::pi::dwm::DryWetDesc , mfx::pi::dwm::DryWet >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::tuner::TunerDesc , mfx::pi::tuner::Tuner >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dist1::DistoSimpleDesc , mfx::pi::dist1::DistoSimple >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::freqsh::FreqShiftDesc , mfx::pi::freqsh::FrequencyShifter >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::trem1::TremoloDesc , mfx::pi::trem1::Tremolo >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::wah1::WahDesc , mfx::pi::wah1::Wah >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dtone1::DistToneDesc , mfx::pi::dtone1::DistTone >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::iifix::IIFixDesc , mfx::pi::iifix::IIFix >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::flancho::FlanchoDesc , mfx::pi::flancho::Flancho >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dly1::DelayDesc , mfx::pi::dly1::Delay >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::cpx::CompexDesc , mfx::pi::cpx::Compex >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::fv::FreeverbDesc , mfx::pi::fv::Freeverb >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc < 4> , mfx::pi::peq::PEq < 4> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc < 8> , mfx::pi::peq::PEq < 8> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc <16> , mfx::pi::peq::PEq <16> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::phase1::PhaserDesc , mfx::pi::phase1::Phaser >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::lpfs::SqueezerDesc , mfx::pi::lpfs::Squeezer >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::lfo1::LfoDesc <false> , mfx::pi::lfo1::Lfo <false> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::envf::EnvFollowDesc , mfx::pi::envf::EnvFollow >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dist2::Disto2xDesc , mfx::pi::dist2::Disto2x >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::spkem::SpeakerEmuDesc , mfx::pi::spkem::SpeakerEmu >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::tost::ToStereoDesc , mfx::pi::tost::ToStereo >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::distpwm::DistoPwmDesc , mfx::pi::distpwm::DistoPwm >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::tremh::HarmTremDesc , mfx::pi::tremh::HarmTrem >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::nzbl::NoiseBleachDesc , mfx::pi::nzbl::NoiseBleach >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::nzcl::NoiseChlorineDesc , mfx::pi::nzcl::NoiseChlorine >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::click::ClickDesc , mfx::pi::click::Click >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::wah2::Wah2Desc , mfx::pi::wah2::Wah2 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::ramp::RampDesc , mfx::pi::ramp::Ramp >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dly2::Delay2Desc , mfx::pi::dly2::Delay2 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::colorme::ColorMeDesc , mfx::pi::colorme::ColorMe >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::phase2::Phaser2Desc , mfx::pi::phase2::Phaser2 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::pidet::PitchDetectDesc , mfx::pi::pidet::PitchDetect >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::osdet::OnsetDetectDesc , mfx::pi::osdet::OnsetDetect >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::syn0::Synth0Desc , mfx::pi::syn0::Synth0 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::hcomb::HyperCombDesc , mfx::pi::hcomb::HyperComb >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::testgen::TestGenDesc , mfx::pi::testgen::TestGen >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::psh1::PitchShift1Desc , mfx::pi::psh1::PitchShift1 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::distpwm2::DistoPwm2Desc , mfx::pi::distpwm2::DistoPwm2 >::create ()
// , mfx::piapi::FactoryTpl <mfx::pi::osdet2::OnsetDetect2Desc, mfx::pi::osdet2::OnsetDetect2 >::create () // Does not work well enough
, mfx::piapi::FactoryTpl <mfx::pi::distapf::DistApfDesc , mfx::pi::distapf::DistApf >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::lfo1::LfoDesc <true> , mfx::pi::lfo1::Lfo <true> >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::adsr::EnvAdsrDesc , mfx::pi::adsr::EnvAdsr >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dly0::DelayDesc , mfx::pi::dly0::Delay >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::fsplit::FreqSplitDesc , mfx::pi::fsplit::FreqSplit >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dist3::Dist3Desc , mfx::pi::dist3::Dist3 >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::moog1::MoogLpfDesc , mfx::pi::moog1::MoogLpf >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::dclip::DiodeClipperDesc , mfx::pi::dclip::DiodeClipper >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::smood::SkoolMoodDesc , mfx::pi::smood::SkoolMood >::create ()
, mfx::piapi::FactoryTpl <mfx::pi::bmp1::BigMuff1Desc , mfx::pi::bmp1::BigMuff1 >::create ()
};
fact_list = l;
}
catch (...)
{
assert (false);
ret_val = fstb::Err_EXCEPTION;
fact_list.clear ();
}
return ret_val;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 48.759259 | 140 | 0.613749 | mikelange49 |
61c35abcbffe63b9b7b3707595211d052b775b1d | 7,894 | cpp | C++ | src/config/QsConfig.cpp | li-lili/qingstor-sdk-c-and-cpp | 9dbe6799231e7df8d237adab39f3c01351d51cff | [
"Apache-1.1"
] | null | null | null | src/config/QsConfig.cpp | li-lili/qingstor-sdk-c-and-cpp | 9dbe6799231e7df8d237adab39f3c01351d51cff | [
"Apache-1.1"
] | null | null | null | src/config/QsConfig.cpp | li-lili/qingstor-sdk-c-and-cpp | 9dbe6799231e7df8d237adab39f3c01351d51cff | [
"Apache-1.1"
] | null | null | null | // +-------------------------------------------------------------------------
// | Copyright (C) 2017 Yunify, Inc.
// +-------------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0 (the "License");
// | you may not use this work except in compliance with the License.
// | You may obtain a copy of the License in the LICENSE file, or 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 <yaml/yaml.h>
#include <plog/Log.h>
#include "QsConfig.h"
#include "StringUtils.h"
#include <map>
namespace QingStor
{
static const char *CONFIG_KEY_ACCESS_KEY_ID = "access_key_id";
static const char *CONFIG_KEY_SECRET_ACCESS_KEY = "secret_access_key";
static const char *CONFIG_KEY_HOST = "host";
static const char *CONFIG_KEY_PORT = "port";
static const char *CONFIG_KEY_PROTOCOL = "protocol";
static const char *CONFIG_KEY_CONNECTION_RETRIES = "connection_retries";
static const char *CONFIG_KEY_ADDITIONAL_USER_AGENT = "additional_user_agent";
static const char *CONFIG_KEY_TIMEOUT_PERIOD = "timeOutPeriod";
// Default value
static const char *DEFAULT_HOST = "qingstor.com";
static const char *DEFAULT_PROTOCOL = "https";
static const char *DEFAULT_ADDITIONAL_USER_AGENT = "";
static int DEFAULT_RETRIES = 3;
static int DEFAULT_PORT = 443;
static int DEFAULT_TIMEOUT_PERIOD = 3;
QsConfig::QsConfig(const std::string & access_key_id, const std::string & secret_access_key)
: additionalUserAgent(DEFAULT_ADDITIONAL_USER_AGENT),
accessKeyId(access_key_id),secretAccessKey(secret_access_key),
host(DEFAULT_HOST),protocol(DEFAULT_PROTOCOL),
port(DEFAULT_PORT),connectionRetries(DEFAULT_RETRIES),
timeOutPeriod(DEFAULT_TIMEOUT_PERIOD)
{
}
QsError QsConfig::LoadConfigFile(const std::string &config_file)
{
FILE *fh = NULL;
yaml_parser_t parser;
yaml_token_t token;
std::map<std::string, std::string> kvs;
std::string token_key;
std::string token_value;
bool reach_key = false;
bool reach_value = false;
/* Initialize parser */
if (!yaml_parser_initialize(&parser))
{
LOG_FATAL << "couldn't initialize yaml parser";
}
/* Open configuration file */
if ((fh = fopen(config_file.c_str(), "rb")) == NULL)
{
yaml_parser_delete(&parser);
LOG_FATAL << "couldn't open configure file " << config_file.c_str();
}
/* Set input file */
yaml_parser_set_input_file(&parser, fh);
do
{
yaml_parser_scan(&parser, &token);
switch (token.type)
{
case YAML_STREAM_START_TOKEN:
case YAML_STREAM_END_TOKEN:
case YAML_BLOCK_SEQUENCE_START_TOKEN:
case YAML_BLOCK_ENTRY_TOKEN:
case YAML_BLOCK_END_TOKEN:
case YAML_BLOCK_MAPPING_START_TOKEN:
break;
case YAML_KEY_TOKEN:
{
reach_key = true;
}
break;
case YAML_VALUE_TOKEN:
{
reach_value = true;
}
break;
case YAML_SCALAR_TOKEN:
{
bool config_invalid = false;
if (reach_key)
{
token_key = std::string((const char *)(token.data.scalar.value));
reach_key = false;
break;
}
else if (reach_value)
{
token_value = std::string((const char *)(token.data.scalar.value));
reach_value = false;
if (token_key.empty() || token_value.empty())
{
config_invalid = true;
}
}
else
{
config_invalid = true;
}
if (config_invalid)
{
yaml_token_delete(&token);
yaml_parser_delete(&parser);
fclose(fh);
LOG_FATAL << "YAML configuration is invalid";
return QS_ERR_INVAILD_CONFIG_FILE;
}
else
{
kvs.insert(std::pair<std::string, std::string>(token_key, token_value));
token_key.clear();
token_value.clear();
}
}
break;
default:
{
yaml_token_delete(&token);
yaml_parser_delete(&parser);
fclose(fh);
LOG_FATAL << "YAML configuration is invalid with token type" << token.type;
return QS_ERR_INVAILD_CONFIG_FILE;
}
break;
}
if (token.type != YAML_STREAM_END_TOKEN)
{
yaml_token_delete(&token);
}
}
while (token.type != YAML_STREAM_END_TOKEN);
yaml_token_delete(&token);
yaml_parser_delete(&parser);
fclose(fh);
/* Go through the interested configurations */
if (kvs[std::string(CONFIG_KEY_ACCESS_KEY_ID)].empty())
{
LOG_FATAL << "YAML configuration is invalid with token type" << token.type;
return QS_ERR_INVAILD_CONFIG_FILE;
}
else
{
accessKeyId = kvs[std::string(CONFIG_KEY_ACCESS_KEY_ID)];
}
if (kvs[std::string(CONFIG_KEY_SECRET_ACCESS_KEY)].empty())
{
return QS_ERR_INVAILD_CONFIG_FILE;
}
else
{
secretAccessKey = kvs[std::string(CONFIG_KEY_SECRET_ACCESS_KEY)];
}
if (kvs[std::string(CONFIG_KEY_HOST)].empty())
{
host = DEFAULT_HOST;
}
else
{
host = kvs[std::string(CONFIG_KEY_HOST)];
}
if (kvs[std::string(CONFIG_KEY_PORT)].empty())
{
port = DEFAULT_PORT;
}
else
{
std::string port_str = kvs[std::string(CONFIG_KEY_PORT)];
int tmp_prot = atoi(port_str.c_str());
if (tmp_prot <= 0 || tmp_prot > 65535)
{
LOG_WARNING << "Configuration Port" << port_str.c_str() << "is invalid, using default vaule:" << DEFAULT_PORT;
tmp_prot = DEFAULT_PORT;
}
port = tmp_prot;
}
if (kvs[std::string(CONFIG_KEY_PROTOCOL)].empty())
{
protocol = DEFAULT_PROTOCOL;
}
else
{
protocol = kvs[std::string(CONFIG_KEY_PROTOCOL)];
}
if (kvs[std::string(CONFIG_KEY_CONNECTION_RETRIES)].empty())
{
connectionRetries = 3;
}
else
{
std::string retries_str = kvs[std::string(CONFIG_KEY_CONNECTION_RETRIES)];
int retries = atoi(retries_str.c_str());
if (retries <= 0 || retries > 16)
{
LOG_WARNING << "Configuration connection retries" << retries_str.c_str() << " is invalid, using default value:" << DEFAULT_RETRIES;
retries = DEFAULT_RETRIES;
}
connectionRetries = retries;
}
if (kvs[std::string(CONFIG_KEY_TIMEOUT_PERIOD)].empty())
{
timeOutPeriod = 3;
}
else
{
std::string timeOutPeriod_str = kvs[std::string(CONFIG_KEY_TIMEOUT_PERIOD)];
int timeOut = atoi(timeOutPeriod_str.c_str());
if (connectionRetries <= 0)
{
LOG_WARNING << "Configuration connection retries" << timeOutPeriod_str.c_str() << " is invalid, using default value:" << DEFAULT_RETRIES;
timeOutPeriod = DEFAULT_TIMEOUT_PERIOD;
}
timeOutPeriod = timeOut;
}
if (kvs[std::string(CONFIG_KEY_ADDITIONAL_USER_AGENT)].empty())
{
additionalUserAgent = "";
}
else
{
additionalUserAgent = kvs[std::string(CONFIG_KEY_ADDITIONAL_USER_AGENT)];
}
return QS_ERR_NO_ERROR;
}
}
| 30.715953 | 149 | 0.589308 | li-lili |
61c4dca75fa183567326eb278e80d3571bf396ab | 2,358 | hpp | C++ | hitagi/ecs/include/hitagi/ecs/schedule.hpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | null | null | null | hitagi/ecs/include/hitagi/ecs/schedule.hpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | null | null | null | hitagi/ecs/include/hitagi/ecs/schedule.hpp | L-Sun/game_engine | e153280dae975c2770a202ca3b55e672626a172e | [
"MIT"
] | null | null | null | #pragma once
#include <hitagi/ecs/world.hpp>
#include <hitagi/utils/concepts.hpp>
#include <memory_resource>
#include <typeindex>
#include <vector>
#include <functional>
namespace hitagi::ecs {
class Schedule {
struct ITask {
virtual void Run(World&) = 0;
};
template <typename Func>
struct Task : public ITask {
Task(std::string_view name, Func&& task)
: task_name(name), task(std::move(task)) {}
Task(const Task&) = delete;
Task& operator=(const Task&) = delete;
Task(Task&&) noexcept = default;
Task& operator=(Task&&) noexcept = default;
void Run(World& world) final;
std::pmr::string task_name;
Func task;
};
public:
Schedule(World& world) : m_World(world) {}
// Do task on the entities that contains components indicated at parameters.
template <typename Func>
requires utils::unique_parameter_types<Func>
Schedule& Register(std::string_view name, Func&& task);
void Run() {
for (auto&& task : m_Tasks) {
task->Run(m_World);
}
}
private:
World& m_World;
std::pmr::vector<std::shared_ptr<ITask>> m_Tasks;
};
template <typename Func>
requires utils::unique_parameter_types<Func>
Schedule& Schedule::Register(std::string_view name, Func&& task) {
std::shared_ptr<ITask> task_info = std::make_shared<Task<Func>>(name, std::forward<Func>(task));
m_Tasks.emplace_back(std::move(task_info));
return *this;
}
template <typename Func>
void Schedule::Task<Func>::Run(World& world) {
[&]<std::size_t... I>(std::index_sequence<I...>) {
using traits = utils::function_traits<Func>;
for (const std::shared_ptr<IArchetype>& archetype : world.GetArchetypes<typename traits::template arg<I>::type...>()) {
auto num_entities = archetype->NumEntities();
auto components_array = std::make_tuple(archetype->GetComponentArray<typename traits::template arg<I>::type>()...);
for (std::size_t index = 0; index < num_entities; index++) {
task(std::get<I>(components_array)[index]...);
}
};
}
(std::make_index_sequence<utils::function_traits<Func>::args_size>{});
}
} // namespace hitagi::ecs | 29.848101 | 127 | 0.608991 | L-Sun |
61c53ea977a2920e076d66ff383436ffa83a2479 | 3,935 | cc | C++ | ppapi/proxy/plugin_message_filter.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ppapi/proxy/plugin_message_filter.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ppapi/proxy/plugin_message_filter.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2011 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 "ppapi/proxy/plugin_message_filter.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/task/single_thread_task_runner.h"
#include "ipc/ipc_channel.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/proxy/resource_message_params.h"
#include "ppapi/proxy/resource_reply_thread_registrar.h"
#include "ppapi/shared_impl/ppapi_globals.h"
#include "ppapi/shared_impl/proxy_lock.h"
#include "ppapi/shared_impl/resource.h"
#include "ppapi/shared_impl/resource_tracker.h"
namespace ppapi {
namespace proxy {
PluginMessageFilter::PluginMessageFilter(
std::set<PP_Instance>* seen_instance_ids,
scoped_refptr<ResourceReplyThreadRegistrar> registrar)
: seen_instance_ids_(seen_instance_ids),
resource_reply_thread_registrar_(registrar),
sender_(NULL) {
}
PluginMessageFilter::~PluginMessageFilter() {
}
void PluginMessageFilter::OnFilterAdded(IPC::Channel* channel) {
sender_ = channel;
}
void PluginMessageFilter::OnFilterRemoved() {
sender_ = NULL;
}
bool PluginMessageFilter::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PluginMessageFilter, message)
IPC_MESSAGE_HANDLER(PpapiMsg_ReserveInstanceId, OnMsgReserveInstanceId)
IPC_MESSAGE_HANDLER(PpapiPluginMsg_ResourceReply, OnMsgResourceReply)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
bool PluginMessageFilter::Send(IPC::Message* msg) {
if (sender_)
return sender_->Send(msg);
delete msg;
return false;
}
void PluginMessageFilter::AddResourceMessageFilter(
const scoped_refptr<ResourceMessageFilter>& filter) {
resource_filters_.push_back(filter);
}
// static
void PluginMessageFilter::DispatchResourceReplyForTest(
const ResourceMessageReplyParams& reply_params,
const IPC::Message& nested_msg) {
DispatchResourceReply(reply_params, nested_msg);
}
void PluginMessageFilter::OnMsgReserveInstanceId(PP_Instance instance,
bool* usable) {
// If |seen_instance_ids_| is set to NULL, we are not supposed to see this
// message.
CHECK(seen_instance_ids_);
// See the message definition for how this works.
if (seen_instance_ids_->find(instance) != seen_instance_ids_->end()) {
// Instance ID already seen, reject it.
*usable = false;
return;
}
// This instance ID is new so we can return that it's usable and mark it as
// used for future reference.
seen_instance_ids_->insert(instance);
*usable = true;
}
void PluginMessageFilter::OnMsgResourceReply(
const ResourceMessageReplyParams& reply_params,
const IPC::Message& nested_msg) {
for (const auto& filter_ptr : resource_filters_) {
if (filter_ptr->OnResourceReplyReceived(reply_params, nested_msg))
return;
}
scoped_refptr<base::SingleThreadTaskRunner> target =
resource_reply_thread_registrar_->GetTargetThread(reply_params,
nested_msg);
target->PostTask(FROM_HERE, base::BindOnce(&DispatchResourceReply,
reply_params, nested_msg));
}
// static
void PluginMessageFilter::DispatchResourceReply(
const ResourceMessageReplyParams& reply_params,
const IPC::Message& nested_msg) {
ProxyAutoLock lock;
Resource* resource = PpapiGlobals::Get()->GetResourceTracker()->GetResource(
reply_params.pp_resource());
if (!resource) {
DVLOG_IF(1, reply_params.sequence() != 0)
<< "Pepper resource reply message received but the resource doesn't "
"exist (probably has been destroyed).";
return;
}
resource->OnReplyReceived(reply_params, nested_msg);
}
} // namespace proxy
} // namespace ppapi
| 32.520661 | 78 | 0.732147 | zealoussnow |
61c68a6f6b29b393cb18a9650126ea67b6df83bd | 7,055 | cpp | C++ | Coin3D/src/nodes/SoTexture3Transform.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/nodes/SoTexture3Transform.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/nodes/SoTexture3Transform.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | /**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* 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 copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/
/*!
\class SoTexture3Transform SoTexture3Transform.h Inventor/nodes/SoTexture3Transform.h
\brief The SoTexture3Transform class is used to define 3D texture transformations.
\ingroup nodes
Textures applied to shapes in the scene can be transformed by
"prefixing" in the state with instances of this node
type. Translations, rotations and scaling in 3D can all be done.
The default settings of this node's fields equals a "null
transform", ie no transformation.
\COIN_CLASS_EXTENSION
<b>FILE FORMAT/DEFAULTS:</b>
\code
Texture3Transform {
translation 0 0 0
rotation 0 0 1 0
scaleFactor 1 1 1
scaleOrientation 0 0 1 0
center 0 0 0
}
\endcode
\sa SoTexture2Transform
\since Coin 2.0
\since TGS Inventor 2.6
*/
// *************************************************************************
#include <Inventor/nodes/SoTexture3Transform.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/actions/SoPickAction.h>
#include <Inventor/actions/SoGetMatrixAction.h>
#include <Inventor/actions/SoCallbackAction.h>
#include <Inventor/elements/SoGLMultiTextureMatrixElement.h>
#include <Inventor/elements/SoTextureUnitElement.h>
#include <Inventor/elements/SoGLCacheContextElement.h>
#include <Inventor/C/glue/gl.h>
#include "nodes/SoSubNodeP.h"
// *************************************************************************
/*!
\var SoSFVec3f SoTexture3Transform::translation
Texture coordinate translation. Default value is [0, 0, 0].
*/
/*!
\var SoSFRotation SoTexture3Transform::rotation
Texture coordinate rotation (s is x-axis, t is y-axis and r is
z-axis). Defaults to an identity rotation (ie zero rotation).
*/
/*!
\var SoSFVec3f SoTexture3Transform::scaleFactor
Texture coordinate scale factors. Default value is [1, 1, 1].
*/
/*!
\var SoSFRotation SoTexture3Transform::scaleOrientation
The orientation the texture is set to before scaling. Defaults to
an identity rotation (ie zero rotation).
*/
/*!
\var SoSFVec3f SoTexture3Transform::center
Center for scale and rotation. Default value is [0, 0, 0].
*/
// *************************************************************************
SO_NODE_SOURCE(SoTexture3Transform);
/*!
Constructor.
*/
SoTexture3Transform::SoTexture3Transform(void)
{
SO_NODE_INTERNAL_CONSTRUCTOR(SoTexture3Transform);
SO_NODE_ADD_FIELD(translation, (0.0f, 0.0f, 0.0f));
SO_NODE_ADD_FIELD(rotation, (SbRotation(SbVec3f(0.0f, 0.0f, 1.0f), 0.0f)));
SO_NODE_ADD_FIELD(scaleFactor, (1.0f, 1.0f, 1.0f));
SO_NODE_ADD_FIELD(scaleOrientation, (SbRotation(SbVec3f(0.0f, 0.0f, 1.0f), 0.0f)));
SO_NODE_ADD_FIELD(center, (0.0f, 0.0f, 0.0f));
}
/*!
Destructor.
*/
SoTexture3Transform::~SoTexture3Transform()
{
}
// Documented in superclass.
void
SoTexture3Transform::initClass(void)
{
SO_NODE_INTERNAL_INIT_CLASS(SoTexture3Transform, SO_FROM_INVENTOR_1);
SO_ENABLE(SoGLRenderAction, SoGLMultiTextureMatrixElement);
SO_ENABLE(SoCallbackAction, SoMultiTextureMatrixElement);
SO_ENABLE(SoPickAction, SoMultiTextureMatrixElement);
}
// Documented in superclass.
void
SoTexture3Transform::GLRender(SoGLRenderAction * action)
{
SoState * state = action->getState();
int unit = SoTextureUnitElement::get(state);
const cc_glglue * glue =
cc_glglue_instance(SoGLCacheContextElement::get(state));
int maxunits = cc_glglue_max_texture_units(glue);
if (unit < maxunits) {
SbMatrix mat;
mat.setTransform(this->translation.getValue(),
this->rotation.getValue(),
this->scaleFactor.getValue(),
this->scaleOrientation.getValue(),
this->center.getValue());
SoMultiTextureMatrixElement::mult(state, this, unit, mat);
}
else {
// we already warned in SoTextureUnit. I think it's best to just
// ignore the texture here so that all textures for non-supported
// units will be ignored. pederb, 2003-11-11
}
}
// Documented in superclass.
void
SoTexture3Transform::doAction(SoAction *action)
{
SoState * state = action->getState();
int unit = SoTextureUnitElement::get(state);
SbMatrix mat;
mat.setTransform(this->translation.getValue(),
this->rotation.getValue(),
this->scaleFactor.getValue(),
this->scaleOrientation.getValue(),
this->center.getValue());
SoMultiTextureMatrixElement::mult(action->getState(), this, unit, mat);
}
// Documented in superclass.
void
SoTexture3Transform::callback(SoCallbackAction *action)
{
SoTexture3Transform::doAction(action);
}
// Documented in superclass.
void
SoTexture3Transform::getMatrix(SoGetMatrixAction * action)
{
int unit = SoTextureUnitElement::get(action->getState());
if (unit == 0) {
SbMatrix mat;
mat.setTransform(this->translation.getValue(),
this->rotation.getValue(),
this->scaleFactor.getValue(),
this->scaleOrientation.getValue(),
this->center.getValue());
action->getTextureMatrix().multLeft(mat);
action->getTextureInverse().multRight(mat.inverse());
}
}
// Documented in superclass.
void
SoTexture3Transform::pick(SoPickAction * action)
{
SoTexture3Transform::doAction(action);
}
| 32.511521 | 87 | 0.684054 | pniaz20 |
61c6e5bf52e58a4345395807b6b716cb117a5f27 | 72,439 | cxx | C++ | Pulsar/src/PulsarSpectrum.cxx | fermi-lat/celestialSources | aaa2a2275b767088c23fde64b407afdac3493208 | [
"BSD-3-Clause"
] | null | null | null | Pulsar/src/PulsarSpectrum.cxx | fermi-lat/celestialSources | aaa2a2275b767088c23fde64b407afdac3493208 | [
"BSD-3-Clause"
] | null | null | null | Pulsar/src/PulsarSpectrum.cxx | fermi-lat/celestialSources | aaa2a2275b767088c23fde64b407afdac3493208 | [
"BSD-3-Clause"
] | 1 | 2017-08-31T21:10:27.000Z | 2017-08-31T21:10:27.000Z | /////////////////////////////////////////////////
// File PulsarSpectrum.cxx
// Implementation of PulsarSpectrum class
//////////////////////////////////////////////////
#include "Pulsar/PulsarSpectrum.h"
#include "Pulsar/PulsarConstants.h"
#include "SpectObj/SpectObj.h"
#include "flux/SpectrumFactory.h"
#include "facilities/commonUtilities.h"
#include "facilities/Util.h"
#include <cmath>
#include <cstdlib>
#include <vector>
#define DEBUG 0
using namespace cst;
//======================================================================
// copied from atErrors.h
//----------------------------------------------------------------------
/* Error Code of atFunctions. */
#define NOT_CONVERGED 10 /*equation was not solved*/
//----------------------------------------------------------------------
// copied from atKepler.c (& modified)
//----------------------------------------------------------------------
//#include "atFunctions.h"
//#include "atError.h"
//#include <math.h>
/*
* solve Kepler equation (KEPLER) g + e sin E = E
*/
int atKepler(
double g, /* input: mean anomaly */
double eccent, /* input: eccentricity */
double *e) /* output: eccentric anomaly */
{
static double eps = 1e-7;
static int imax = 50;
int i;
static double error, deltae, d__1;
*e = g;
if (g == 0.) return 0;
for (i=0; i<imax; i++) {
deltae = (g - *e + eccent * std::sin(*e)) / (1. - eccent * std::cos(*e));
*e += deltae;
error = (d__1 = deltae / *e, std::fabs(d__1));
if (error < eps) return 0;
}
return NOT_CONVERGED;
}
/////////////////////////////////////////////////
ISpectrumFactory &PulsarSpectrumFactory()
{
static SpectrumFactory<PulsarSpectrum> myFactory;
return myFactory;
}
/////////////////////////////////////////////////
/*!
* \param params string containing the XML parameters
*
* This method takes from the XML file the name of the pulsar to be simulated, the model
* to be used and the parameters specific for the choosen model. Then extracts from the
* TXT DataList file the characteristics of the choosen pulsar (e.g. period, flux, period derivatives
* ,ephemerides, flux, etc...)
* The names of DataList files are defined in the file <i>PulsarDataList.txt</i><br>
* The parameters are:<br>
* <ul>
* <li> Pulsar name;
* <li> Flux, expressed in ph/cm2/s (E>100MeV);
* <li> Ephemerides type (P=period and derivatives;F=frequency and derivatives)
* <li> Period,pdot,p2dot or f0,f1,f2;
* <li> Start of ephemerides validity range (in MJD);
* <li> Reference Epoch, t0 (in MJD);
* <li> End of ephemerides validity range (in MJD);
* </ul>
* The parameters taken from XML file are:<br>
* <ul>
* <li> Pulsar name;
* <li> Position (RA,dec) in degrees;
* <li> Minimum and maximum energy of extracted photons (in keV);
* <li> Model choosen (default = 1, phenomenological);
* <li> Random seed;
* <li> Model-dependend parameters;
* </ul>
* Then it calls the PulsarSim class in order to have the TH2D histogram.
* For more informations and for a brief tutorial about the use of PulsarSpectrum you can look at:
* <br>
* <a href="#dejager02">http://www.pi.infn.it/~razzano/Pulsar/PulsarSpTutor/PulsarSpTutor.htm </a>
*/
PulsarSpectrum::PulsarSpectrum(const std::string& params)
: m_solSys(astro::SolarSystem::EARTH), m_params(params)
{
m_ff=false;
// Reset all variables;
m_RA = 0.0;
m_dec = 0.0;
m_l = 0.0;
m_b = 0.0;
m_flux = 0.0;
m_ephemType = "";
m_period = 0.0;
m_pdot = 0.0;
m_p2dot = 0.0;
m_f0 = 0.0;
m_f1 = 0.0;
m_f2 = 0.0;
m_f0NoNoise = 0.0;
m_f1NoNoise = 0.0;
m_f2NoNoise = 0.0;
m_N0 = 0.0;
m_t0Init = 0.0;
m_t0 = 0.0;
m_t0End = 0.0;
m_phi0 = 0.0;
m_model = 0;
m_seed = 0;
m_TimingNoiseModel = 0;
m_TimingNoiseActivity = 0.;
m_TimingNoiseRMS = 0.;
m_TimingNoiseMeanRate=0.;
m_TimingNoiseTimeNextEvent=0.;
m_BinaryFlag = 0;
m_Porb = 0;
m_Porb_dot = 0.;
m_asini = 0;
m_xdot = 0.;
m_ecc = 0;
m_ecc_dot = 0.;
m_omega = 0;
m_omega_dot = 0.;
m_gamma = 0.;
m_shapiro_r = 0.;
m_shapiro_s = 0.;
m_t0PeriastrMJD = 0;
m_t0AscNodeMJD = 0;
m_PPN =0.;
m_FT2_startMET = -1.;
m_FT2_stopMET =-1.;
m_Sim_startMET = -1.;
m_Sim_stopMET =-1.;
m_UseFT2 = 0;
//Read from XML file
m_PSRname = parseParamList(params,0).c_str(); // Pulsar name
m_RA = std::atof(parseParamList(params,1).c_str()); // Pulsar Right Ascension
m_dec = std::atof(parseParamList(params,2).c_str()); // Pulsar Declination
m_enphmin = std::atof(parseParamList(params,3).c_str()); // minimum energy of extracted photons
m_enphmax = std::atof(parseParamList(params,4).c_str()); // minimum energy of extracted photons
m_model = std::atoi(parseParamList(params,5).c_str()); // choosen model
m_seed = std::atoi(parseParamList(params,6).c_str()); //Model Parameters: Random seed
//Setting random seed
m_PSpectrumRandom = new TRandom;
m_PSpectrumRandom->SetSeed(m_seed);
if (m_model == 1) //Phenomenological model
{
m_ppar0 = std::atoi(parseParamList(params,7).c_str()); //Model Parameters: Number of peaks
m_ppar1 = std::atof(parseParamList(params,8).c_str()); // model parameters
m_ppar2 = std::atof(parseParamList(params,9).c_str());
m_ppar3 = std::atof(parseParamList(params,10).c_str());
m_ppar4 = std::atof(parseParamList(params,11).c_str());
}
else
if (m_model == 2) //PulsarShape model
{
m_ppar0 = std::atoi(parseParamList(params,7).c_str()); //Model Parameters: Use normalization?
m_PSRShapeName = parseParamList(params,8).c_str(); // model parameters
}
//look for pulsar data directory, following, in the order $PULSARDATA, $SKYMODEL_DIR/pulsars or $PULSARROOT/data
// std::string m_pulsardata_dir;
if (::getenv("PULSAR_OUTPUT_LEVEL"))
{
const char * outlevel = ::getenv("PULSAR_OUTPUT_LEVEL");
m_OutputLevel = atoi(outlevel);
if ((m_OutputLevel<0) || (m_OutputLevel>2))
m_OutputLevel=1;
}
else
{
m_OutputLevel=1;
}
if (::getenv("PULSARDATA"))
{
const char * psrdata = ::getenv("PULSARDATA");
m_pulsardata_dir = std::string(psrdata);
}
else if (::getenv("SKYMODEL_DIR"))
{
const char * psrdata = ::getenv("SKYMODEL_DIR");
m_pulsardata_dir = std::string(psrdata)+"/pulsars";
}
else
{
const char * psrdata = ::getenv("PULSARROOT");
m_pulsardata_dir = std::string(psrdata)+"/data";
}
if (m_OutputLevel>1)
{
WriteToLog("PULSARDATA used is: "+std::string(m_pulsardata_dir));
}
// Determine start and end time for FT2 or orbit file
try {
const astro::PointingHistory & history = astro::GPS::instance()->history();
// throw(NoHistoryError);
m_FT2_startMET = history.startTime();
m_FT2_stopMET = history.endTime();
m_UseFT2 = 1;
} catch (astro::GPS::NoHistoryError & )
{
m_FT2_startMET = Spectrum::startTime();
m_FT2_stopMET = astro::GPS::instance()->endTime();
}
m_Sim_startMET = Spectrum::startTime();
m_Sim_stopMET = astro::GPS::instance()->endTime();
//Init SolarSystem stuffs useful for barycentric decorrections
astro::JulianDate JDStart(StartMissionDateMJD+JDminusMJD);
m_earthOrbit = new astro::EarthOrbit(JDStart);
astro::SkyDir m_PulsarDir(m_RA,m_dec,astro::SkyDir::EQUATORIAL);
m_PulsarVectDir = m_PulsarDir.dir();
m_GalDir = std::make_pair(m_PulsarDir.l(),m_PulsarDir.b());
m_l = m_GalDir.first;
m_b = m_GalDir.second;
//Load Pulsar General data from PulsarDataList.txt
LoadPulsarData(m_pulsardata_dir,0);
if (!(::getenv("PULSAR_NO_DB")))
{
//Save the output txt file..
int DbFlag = saveDbTxtFile();
if ((DbFlag !=1) && (m_OutputLevel>1))
WriteToLog("WARNING! Problem in saving SimPulsars_spin.txt");
}
//Binary Pulsar Data
if (m_BinaryFlag ==1)
{
LoadPulsarData(m_pulsardata_dir,1); //loading orbital data from PulsarBinDataList.txt
if (!(::getenv("PULSAR_NO_DB")))
{
int BinDbFlag = saveBinDbTxtFile();
if ((BinDbFlag !=1) && (m_OutputLevel>1))
WriteToLog("WARNING! Problem in saving SimPulsars_bin.txt");
}
}
if (m_TimingNoiseModel != 0)
{
InitTimingNoise();
}
//Instantiate an object of PulsarSim class
m_Pulsar = new PulsarSim(m_PSRname, m_seed, m_flux, m_enphmin, m_enphmax, m_period);
//Instantiate an object of SpectObj class
if (m_model == 1)
{
m_spectrum = new SpectObj(m_Pulsar->PSRPhenom(double(m_ppar0), m_ppar1,m_ppar2,m_ppar3,m_ppar4),1);
m_spectrum->SetAreaDetector(EventSource::totalArea());
}
else
if (m_model == 2)
{
m_spectrum = new SpectObj(m_Pulsar->PSRShape(m_PSRShapeName,m_ppar0),1);
m_spectrum->SetAreaDetector(EventSource::totalArea());
}
else
{
std::cout << "ERROR! Model choice not implemented " << std::endl;
exit(1);
}
if (m_OutputLevel > 0)
{
//Redirect output to a subdirectory
const char * pulsarOutDir = ::getenv("PULSAROUTFILES");
// override obssim if running in Gleam environment
if( pulsarOutDir!=0)
m_LogFileName = std::string(pulsarOutDir) + "/" + m_PSRname + "Log.txt";
else
m_LogFileName = m_PSRname + "Log.txt";
char temp[200];
sprintf(temp,"** Output Level set to: %d",m_OutputLevel);
WriteToLog(std::string(temp));
WritePulsarLog();
}
}
/////////////////////////////////////////////////
PulsarSpectrum::~PulsarSpectrum()
{
delete m_Pulsar;
delete m_spectrum;
delete m_earthOrbit;
delete m_PSpectrumRandom;
}
/////////////////////////////////////////////////
double PulsarSpectrum::flux(double time) const
{
double flux;
flux = m_spectrum->flux(time,m_enphmin);
return flux;
}
/////////////////////////////////////////////////
/*!
* \param time time to start the computing of the next photon
*
* This method find the time when the next photon will come. It takes into account decorrections due to
* ephemerides and period derivatives and barycentric decorrections. This method also check for
* changes in the ephemerides validity range.
* For the ephemerides decorrections the parameters used are:
* <ul>
* <li> <i>Epoch</i>, espressed in MJD;</li>
* <li> <i>Initial Phase Phi0</i>;</li>
* <li> <i>First Period derivative</i>;</li>
* <li> <i>Second Period derivative</i>;</li>
* </ul>
* <br>
* The barycentric decorrections takes into account conversion TDB->TT, Geometrical and Shapiro delays.
* This method also calls the interval method in SpectObj class to determine the next photon in a rest-frame without
* ephemerides effects.
*/
double PulsarSpectrum::interval(double time)
{
double timeTildeDecorr = time + (StartMissionDateMJD)*SecsOneDay; //Arrival time decorrected
//check if time is before FT2 start
if (time < m_FT2_startMET)
{
timeTildeDecorr+=(m_FT2_startMET-time)+510.;
}
//this should be corrected before applying barycentryc decorr + ephem de-corrections
double timeTilde = 0;
timeTilde = timeTildeDecorr + getBaryCorr(timeTildeDecorr,0);
double timeTildeDemodulated =0.;
//binary demodulation
if (m_BinaryFlag ==0)
{
timeTildeDemodulated = timeTilde;
}
else
{
if (::getenv("PULSAR_OUT_BIN"))
{
timeTildeDemodulated = getIterativeDemodulatedTime(timeTilde,1);
}
else
{
timeTildeDemodulated = getIterativeDemodulatedTime(timeTilde,0);
}
// std::cout <<"\n****Test inverso:"<< timeTildeDemodulated-(StartMissionDateMJD)*SecsOneDay << " con correzioni" << getBinaryDemodulationInverse(timeTildeDemodulated)-(StartMissionDateMJD)*SecsOneDay << std::endl;
// std::cout << " indietro -->" << getIterativeDemodulatedTime(getBinaryDemodulationInverse(timeTildeDemodulated),0)-(StartMissionDateMJD)*SecsOneDay << std::endl;
}
//Phase assignment
double intPart=0.; //Integer part
// double PhaseNoNoise,PhaseWithNoise=0.;
//Apply timing noise
if (m_TimingNoiseModel !=0)
{
ApplyTimingNoise(timeTildeDemodulated);
}
double initTurns = getTurns(timeTildeDemodulated); //Turns made at this time
double tStart = modf(initTurns,&intPart)*m_period; // Start time for interval
if (tStart < 0.)
tStart+=m_period;
if (DEBUG)
{
std::cout << std::setprecision(30) << "\n" << timeTilde -(StartMissionDateMJD)*SecsOneDay
<< " turns are " << getTurns(timeTilde)
<< " phase is " << tStart/m_period << " phi0 is " << m_phi0 << std::endl;
}
CheckEphemeridesValidity(timeTildeDemodulated,initTurns);;
if (DEBUG)
{
if ((int(timeTilde - (StartMissionDateMJD)*SecsOneDay) % 1000) < 1.5)
std::cout << "\n\n** " << m_PSRname << " Time is: "
<< timeTildeDecorr-(StartMissionDateMJD)*SecsOneDay << " s MET in TT | "
<< timeTilde-(StartMissionDateMJD)*SecsOneDay << "s. MET in SSB in TDB (barycorr.) | "
<< timeTildeDemodulated-(StartMissionDateMJD)*SecsOneDay
<< "s. MET in SSB in TDB (barycorr. + demod.)| "
<< std::endl;
}
//Log out the barycentric corrections
double bl=0;
if (::getenv("PULSAR_OUT_BARY"))
bl = getBaryCorr(timeTilde,1);
//In case of binary add a modulation...
if (m_BinaryFlag ==1)
{
double ModFactor = 0.5;
double intOrb;
// double Modulation = 1+ModFactor*sin(2*M_PI*modf(initTurns,&intOrb)-DegToRad*m_omega+0.5*M_PI);
double OrbPhase = getOrbitalPhase(timeTildeDemodulated);
double Modulation = 1+ModFactor*std::sin(2*M_PI*OrbPhase-DegToRad*m_omega+0.5*M_PI);
if (DEBUG)
std::cout << std::setprecision(12)<<timeTildeDecorr - (StartMissionDateMJD)*SecsOneDay<< " OrbPhase " << OrbPhase << std::endl;
//std::cout << std::setprecision(12)<<TrueAn<<" " <<modf(TrueAn,&intOrb)<<" " << Modulation<<std::endl;
m_spectrum->SetFluxFactor(Modulation);
}
//Ephemerides calculations...
double inte = m_spectrum->interval(tStart,m_enphmin); //deltaT (in system where Pdot = 0
double inteTurns = inte/m_period; // conversion to # of turns
double totTurns = initTurns + inteTurns + m_phi0; //Total turns at the nextTimeTilde
//Applying timingnoise
double nextTimeTildeDemodulated = retrieveNextTimeTilde(timeTildeDemodulated, totTurns, (ephemCorrTol/m_period));
double nextTimeTilde = 0.;
double nextTimeTildeDecorr = 0.;
//inverse of binary demodulation and of barycentric corrections
if (m_BinaryFlag == 0)
{
nextTimeTilde = nextTimeTildeDemodulated;
nextTimeTildeDecorr = getDecorrectedTime(nextTimeTilde); //Barycentric decorrections
}
else
{
nextTimeTilde = getBinaryDemodulationInverse(nextTimeTildeDemodulated);
nextTimeTildeDecorr = getDecorrectedTime(nextTimeTilde); //Barycentric decorrections
}
if (DEBUG)
{
std::cout << std::setprecision(15) << "\nTimeTildeDecorr at Spacecraft (TT) is: "
<< timeTildeDecorr - (StartMissionDateMJD)*SecsOneDay << "s." << std::endl;
std::cout << "Arrival time after start of the simulation : "
<< timeTildeDecorr - (StartMissionDateMJD)*SecsOneDay -Spectrum::startTime() << " s." << std::endl;
std::cout << std::setprecision(15) <<" TimeTilde at SSB (in TDB) is: "
<< timeTilde - (StartMissionDateMJD)*SecsOneDay << "sec." << std::endl;
std::cout << std::setprecision(15) <<" TimeTildeDemodulated: "
<< timeTildeDemodulated - (StartMissionDateMJD)*SecsOneDay
<< "sec.; phase=" << modf(initTurns,&intPart) << std::endl;
std::cout << std::setprecision(15) <<" nextTimeTildeDemodulated at SSB (in TDB) is: "
<< nextTimeTildeDemodulated - (StartMissionDateMJD)*SecsOneDay << " s." << std::endl;
std::cout << std::setprecision(15) <<" nextTimeTilde at SSB (in TDB) is: "
<< nextTimeTilde - (StartMissionDateMJD)*SecsOneDay << " s." << std::endl;
std::cout << std::setprecision(15) <<" nextTimeTilde decorrected (TT) is: "
<< nextTimeTildeDecorr - (StartMissionDateMJD)*SecsOneDay << " s." << std::endl;
std::cout << " corrected is "
<< nextTimeTildeDecorr + getBaryCorr(nextTimeTildeDecorr,0) - (StartMissionDateMJD)*SecsOneDay << std::endl;
std::cout << std::setprecision(15) <<" -->Interval is " << nextTimeTildeDecorr - timeTildeDecorr << std::endl;
}
// double interv = nextTimeTildeDecorr - timeTildeDecorr;
double interv = nextTimeTildeDecorr-(time + (StartMissionDateMJD)*SecsOneDay);
if (interv <= 0.)
interv = m_periodVect[0]/100.;
return interv;
}
/////////////////////////////////////////////
/*!
* \param time time where the number of turns is computed
*
* This method compute the number of turns made by the pulsar according to the ephemerides.
* <br>
* <blockquote>
* f(t) = f<sub>0</sub> + f<sub>1</sub>(t - t<sub>0</sub>) +
* f<sub>2</sub>/2(t - t<sub>0</sub>)<sup>2</sup>.
* <br>The number of turns is related to the ephemerides as:<br>
* dN(t) = N<sub>0</sub> + phi<sub>0</sub> + f<sub>0</sub> + f<sub>1</sub>(t-t<sub>0</sub>) + 1/2f<sub>2</sub>(t-t<sub>0</sub>)<sup>2</sup>
* </blockquote>
* <br>where
* <blockquote>
*<ul>
* <li> t<sub>0</sub> is an ephemeris epoch.In this simulator epoch must be expressed in MJD;</li>
* <li> N<sub>0</sub> is the number of turns at epoch t<sub>0</sub>;
* <li> phi<sub>0</sub> is the phase shift at epoch t<sub>0</sub>;
* <li>f<sub>0</sub> pulse frequency at time t<sub>0</sub> (usually given in Hz)</li>,
* <li>f<sub>1</sub> the 1st time derivative of frequency at time t< sub>0</sub> (Hz s<sup>-1</sup>);</li>
* <li>f<sub>2</sub> the 2nd time derivative of frequency at time t<sub>0</sub> (Hz s<sup>-2</sup>).</li>
* </ul>
* </blockquote>
*/
double PulsarSpectrum::getTurns( double time )
{
double dt = time - m_t0*SecsOneDay;
return m_phi0 + m_N0 + m_f0*dt + 0.5*m_f1*dt*dt + ((m_f2*dt*dt*dt)/6.0);
}
/////////////////////////////////////////////
/*!
* \param tTilde Time from where retrieve the nextTime;
* \param totalTurns Number of turns completed by the pulsar at nextTime;
* \param err Phase tolerance between totalTurns and the number of turns at nextTime
*
* <br>In this method a recursive way is used to find the <i>nextTime</i>. Starting at <i>tTilde</i>, the method returns
* nextTime, the time where the number of turns completed by the pulsar is equal to totalTurns (within the choosen tolerance).
*/
double PulsarSpectrum::retrieveNextTimeTilde( double tTilde, double totalTurns, double err )
{
double tTildeUp,NTup = 0.;
double tTildeDown,NTdown = 0;
tTildeUp = tTilde;
tTildeDown = tTilde;
NTdown = totalTurns - getTurns(tTildeDown);
NTup = totalTurns - getTurns(tTildeUp);
int u = 0;
int nIterations = 0;
while ((NTdown*NTup)>0)
{
u++;
tTildeUp = tTilde+m_period*pow(2.0,u);
NTdown = totalTurns - getTurns(tTildeDown);
NTup = totalTurns - getTurns(tTildeUp);
}
double tTildeMid = (tTildeDown+tTildeUp)/2.0;
double NTmid = totalTurns - getTurns(tTildeMid);
while(fabs(NTmid) > err )
{
nIterations++;
if ((fabs(NTmid) < err) || (nIterations > 200)) break;
NTmid = totalTurns - getTurns(tTildeMid);
NTdown = totalTurns - getTurns(tTildeDown);
if ((NTmid*NTdown)>0)
{
tTildeDown = tTildeMid;
tTildeMid = (tTildeDown+tTildeUp)/2.0;
}
else
{
tTildeUp = tTildeMid;
tTildeMid = (tTildeDown+tTildeUp)/2.0;
}
}
if (DEBUG)
{
std::cout << "** RetrieveNextTimeTilde " << std::endl;
std::cout << std::setprecision(30) << " Stop up is " << tTildeUp << " NT " << NTup << std::endl;
std::cout << std::setprecision(30) << " down is " << tTildeDown << " NT " << NTdown << " u= " << u << std::endl;
std::cout << std::setprecision(30) << " mid is " << tTildeMid << " NT " << NTmid << " u= " << u << std::endl;
std::cout << " nextTimeTilde is " << tTildeMid << std::endl;
}
return tTildeMid;
}
/////////////////////////////////////////////
/*!
* \param ttInput Photon arrival time at spacecraft in Terrestrial Time (expressed in MJD converted in seconds)
*
* <br>
* This method computes the barycentric corrections for the photon arrival time at spacecraft and returns
* the time in Solar System Barycentric Time. The corrections implemented at the moment are:
* <ul>
* <li> Conversion from TT to TDB;
* <li> Geometric Time Delay due to light propagation in Solar System;
* <li> Relativistic Shapiro delay;
* </ul>
*/
double PulsarSpectrum::getBaryCorr( double ttInput, int LogCorrFlag)
{
if (((ttInput-(StartMissionDateMJD)*SecsOneDay)+510)>m_FT2_stopMET)
{
if (m_OutputLevel>1)
{
char temp[200];
sprintf(temp,"WARNING!!!Arrival time after FT2 end. No barycentric correction! at t=%.f",ttInput);
WriteToLog(std::string(temp));
}
return 0.;
}
//Start Date;
astro::JulianDate ttJD(StartMissionDateMJD+JDminusMJD);
ttJD = ttJD+(ttInput - (StartMissionDateMJD)*SecsOneDay)/SecsOneDay;
if (DEBUG)
{
std::cout << std::setprecision(30) << "\nBarycentric Corrections for time " << ttJD << " (JD)" << std::endl;
}
// Conversion TT to TDB, from JDMissionStart (that glbary uses as MJDref)
double tdb_min_tt = m_earthOrbit->tdb_minus_tt(ttJD);
double timeMET = ttInput - (StartMissionDateMJD)*SecsOneDay;
CLHEP::Hep3Vector scPos;
//Exception error in case of time not in the range of available position (when using a FT2 file)
try {
// std::cout<<astro::GPS::time()<<std::endl;
//astro::GPS::update(timeMET);
// std::cout<<astro::GPS::time()<<std::endl;
astro::GPS::instance()->time(timeMET);
scPos = astro::GPS::instance()->position(timeMET);
} catch (astro::PointingHistory::TimeRangeError & )
{
if (DEBUG)
{
std::cout << "WARNING! FT2 Time Error at " << std::setprecision(30) << timeMET << std::endl;
}
if ((timeMET+510)>=m_FT2_stopMET)
{
return 0.;
}
}
//Correction due to geometric time delay of light propagation
//GLAST position
CLHEP::Hep3Vector GeomVect = (scPos/clight);
double GLASTPosGeom = GeomVect.dot(m_PulsarVectDir);
double GeomCorr = 0;
double EarthPosGeom =0.;
try{
//Earth position
GeomVect = - m_solSys.getBarycenter(ttJD);
EarthPosGeom = GeomVect.dot(m_PulsarVectDir);
GeomVect = (scPos/clight) - m_solSys.getBarycenter(ttJD);
GeomCorr = GeomVect.dot(m_PulsarVectDir);
} catch (astro::SolarSystem::BadDate & )
{
std::cout << "WARNING! JD Bad Date " << ttJD <<std::endl;
GeomCorr = 0.;
}
//Correction due to Shapiro delay.
CLHEP::Hep3Vector sunV = m_solSys.getSolarVector(ttJD);
// Angle of source-sun-observer
double costheta = - sunV.dot(m_PulsarVectDir) / ( sunV.mag() * m_PulsarVectDir.mag() );
double m = 4.9271e-6; // m = G * Msun / c^3
double ShapiroCorr = 2.0 * m * log(1+costheta);
if (DEBUG)
{
std::cout << std::setprecision(20) << "** --> TDB-TT = " << tdb_min_tt << std::endl;
std::cout << std::setprecision(20) << "** --> Geom. delay = " << GeomCorr << std::endl;
std::cout << std::setprecision(20) << "** --> Shapiro delay = " << ShapiroCorr << std::endl;
std::cout << std::setprecision(20) << "** ====> Total= " << tdb_min_tt + GeomCorr + ShapiroCorr << " s." <<std::endl;
}
if ((LogCorrFlag == 1) && (ttInput-StartMissionDateMJD*SecsOneDay > 0.))
{
double intPart=0.;
double PhaseOut = getTurns(ttInput);
PhaseOut = modf(PhaseOut,&intPart); // phase for linear evolution
if (PhaseOut < 0)
PhaseOut++;
std::ofstream BaryCorrLogFile((m_PSRname + "BaryCorr.log").c_str(),std::ios::app);
BaryCorrLogFile << std::setprecision(20)
<< timeMET << "\t" << PhaseOut << "\t" << GLASTPosGeom << "\t"<< EarthPosGeom << "\t"
<< GeomCorr << "\t" << tdb_min_tt << "\t" << ShapiroCorr << std::endl;
BaryCorrLogFile.close();
}
return tdb_min_tt + GeomCorr + ShapiroCorr; //seconds
}
/////////////////////////////////////////////
/*!
* \param tInput Photon arrival time do be demodulated
* \param LogFlag Flag for writing output
*
* <br>
* This method compute the binary demodulation in an iterative way
* using the getBinaryDemodulation method
*/
double PulsarSpectrum::getIterativeDemodulatedTime(double tInput, int LogFlag)
{
double timeDemodulated = tInput+getBinaryDemodulation(tInput,0);
double TargetTime = tInput;
double delay = getBinaryDemodulation(tInput,0);
int i=0;
while ((fabs(timeDemodulated-delay-TargetTime) > DemodTol) && ( i < 50))
{
i++;
timeDemodulated = TargetTime+delay;
delay = getBinaryDemodulation(timeDemodulated,0);
// std::cout << "Step " << i << " t= " << timeDemodulated-(StartMissionDateMJD)*SecsOneDay<<std::endl;
}
if (LogFlag == 1)
{
delay = getBinaryDemodulation(timeDemodulated,1);
}
return timeDemodulated;
}
/////////////////////////////////////////////
/*!
* \param tInput Photon arrival time do be demodulated
* <br>
* This method returns the true anomaly
*/
double PulsarSpectrum::getTrueAnomaly(double tInput)
{
//double BinaryRoemerDelay = 0.;
double dt = tInput-m_t0PeriastrMJD*SecsOneDay;
double OmegaMean = 2*M_PI/m_Porb;
double EccAnConst = OmegaMean*(dt - 0.5*(dt*dt*(m_Porb_dot/m_Porb)));
//Calculate Eccenctric Anomaly solving Kepler equation using the atKepler function
double EccentricAnomaly = 0.;
int status = atKepler(EccAnConst, m_ecc, &EccentricAnomaly); //AtKepler
// atKepler not converged
if (0 != status) {
throw std::runtime_error("atKepler did not converge.");
}
//Calculate True Anomaly
double TrueAnomaly = 2.0 * std::atan(std::sqrt((1.0+m_ecc)/(1.0-m_ecc))*std::tan(EccentricAnomaly*0.5));
TrueAnomaly = TrueAnomaly + 2*M_PI*floor((EccentricAnomaly - TrueAnomaly)/ (2*M_PI));
while ((TrueAnomaly - EccentricAnomaly) > M_PI) TrueAnomaly -= 2*M_PI;
while ((EccentricAnomaly - TrueAnomaly) > M_PI) TrueAnomaly += 2*M_PI;
return TrueAnomaly;
}
/////////////////////////////////////////////
/*!
* \param tInput Photon arrival time do be demodulated
* <br>
* This method returns the true anomaly
*/
double PulsarSpectrum::getOrbitalPhase(double tInput)
{
//double BinaryRoemerDelay = 0.;
double dt = tInput-m_t0PeriastrMJD*SecsOneDay;
double dp = dt/m_Porb;
// Compute the complete phase.
double phase = dp * (1. - dp *m_Porb_dot / 2.0);
double intOrb;
double OrbPhase = modf(phase,&intOrb);
if (OrbPhase<0)
OrbPhase+=1;
return OrbPhase;
}
/////////////////////////////////////////////
/*!
* \param tInput Photon arrival time do be demodulated
* \param LogFlag Flag for writing output
*
* <br>
* This method compute the binary demodulation using the orbital parameters
* of the pulsar. The corrections computed are:
*
*<ul>
* <li> Roemer delay
* <li> Einstein delay
* <li> Shapiro delay
*</ul>
*/
double PulsarSpectrum::getBinaryDemodulation( double tInput, int LogDemodFlag)
{
double BinaryRoemerDelay = 0.;
double dt = tInput-m_t0PeriastrMJD*SecsOneDay;
double OmegaMean = 2*M_PI/m_Porb;
double EccAnConst = OmegaMean*(dt - 0.5*(dt*dt*(m_Porb_dot/m_Porb)));
//Calculate Eccenctric Anomaly solving Kepler equation using the atKepler function
double EccentricAnomaly = 0.;
int status = atKepler(EccAnConst, m_ecc, &EccentricAnomaly); //AtKepler
// atKepler not converged
if (0 != status) {
throw std::runtime_error("atKepler did not converge.");
}
//Calculate True Anomaly
double TrueAnomaly = 2.0 * std::atan(std::sqrt((1.0+m_ecc)/(1.0-m_ecc))*std::tan(EccentricAnomaly*0.5));
TrueAnomaly = TrueAnomaly + 2*M_PI*floor((EccentricAnomaly - TrueAnomaly)/ (2*M_PI));
while ((TrueAnomaly - EccentricAnomaly) > M_PI) TrueAnomaly -= 2*M_PI;
while ((EccentricAnomaly - TrueAnomaly) > M_PI) TrueAnomaly += 2*M_PI;
// Calculate longitude of periastron using m_omega_dot
double Omega = DegToRad*m_omega + DegToRad*m_omega_dot*(TrueAnomaly/OmegaMean);
// compute projected semimajor axis using x_dot
double asini = m_asini + m_xdot*dt;
//Binary Roemer delay
BinaryRoemerDelay = ((std::cos(EccentricAnomaly)-m_ecc)*std::sin(Omega)
+ std::sin(EccentricAnomaly)*std::cos(Omega)*std::sqrt(1-m_ecc*m_ecc));
//Einstein Delay
double BinaryEinsteinDelay = m_gamma*std::sin(EccentricAnomaly);
//Shapiro binary delay
double BinaryShapiroDelay = -2.0*m_shapiro_r*log(1.-m_ecc*std::cos(EccentricAnomaly)-m_shapiro_s*BinaryRoemerDelay);
BinaryRoemerDelay = asini*BinaryRoemerDelay;
if (DEBUG)
{
std::cout << "\n** Binary modulations t=" << std::setprecision(15) << tInput-(StartMissionDateMJD)*SecsOneDay
<< " dt=" << tInput - m_t0PeriastrMJD*SecsOneDay << std::endl;
std::cout << "** Ecc.Anomaly=" << EccentricAnomaly << " deg. True Anomaly=" << TrueAnomaly << " deg." << std::endl;
std::cout << "** Omega=" << Omega << " rad. Major Semiaxis " << asini << " light-sec" << std::endl;
std::cout << "** --> Binary Roemer Delay=" << BinaryRoemerDelay << " s." << std::endl;
std::cout << "** --> Binary Einstein Delay=" << BinaryEinsteinDelay << " s." << std::endl;
std::cout << "** --> Binary Shapiro Delay=" << BinaryShapiroDelay << " s." << std::endl;
}
if ((LogDemodFlag==1) && (tInput-StartMissionDateMJD*SecsOneDay > 0.))
{
std::ofstream BinDemodLogFile((m_PSRname + "BinDemod.log").c_str(),std::ios::app);
BinDemodLogFile << std::setprecision(15)
<< tInput-StartMissionDateMJD*SecsOneDay << "\t" << tInput - m_t0PeriastrMJD*SecsOneDay << "\t"
<< EccentricAnomaly << "\t" << TrueAnomaly << "\t"
<< Omega << "\t" << m_ecc << "\t" << asini << "\t"
<< BinaryRoemerDelay << "\t"
<< BinaryEinsteinDelay << "\t"
<< BinaryShapiroDelay << "\t" << std::endl;
BinDemodLogFile.close();
}
return -1.*(BinaryRoemerDelay+BinaryEinsteinDelay+BinaryShapiroDelay);
}
/////////////////////////////////////////////
/*!
* \param CorrectedTime Photon arrival time at SSB (TDB expressed in MJD)
*
* <br>
* This method returns the correspondent decorrected time starting from a photon arrival time
* at the Solar System barycenter expressed in Barycentric Dynamical Time. This function uses the bisection method
* for inverting barycentric corrections <br>
* The corrections implemented at the moment are:
* <ul>
* <li> Conversion from TT to TDB;
* <li> Geometric Time Delay due to light propagation in Solar System;
* <li> Relativistic Shapiro delay;
* </ul>
*/
double PulsarSpectrum::getDecorrectedTime(double CorrectedTime)
{
// double CorrectedTime = 54.2342.;
double deltaT = 510.;
double tcurr = CorrectedTime-deltaT;
double fcurr = tcurr + getBaryCorr(tcurr,0); // fx(tcurr);
// double fcurr_ct = CorrectedTime;
if (DEBUG)
{
std::cout << "Get decorrected time from time t=" << CorrectedTime << std::endl;
}
//double deltaStep = 10.;
int s = 0;
int SignDirection = 0;
//std::cout << "\n\n***\ntstart= " << tcurr << " -->fcurr= " << fcurr
// << " -->fcurr_CT= " << fcurr_ct << " inital delta=" << deltaStep << std::endl;
if (CorrectedTime <= fcurr) // function increasing
{
// std::cout << "Case 1: de-crescent function" << std::endl;
SignDirection = 1;
}
else
{
//std::cout << "Case 2: crescent function" << std::endl;
SignDirection = 2;
}
double deltaStep = pow(10.,(2.-s));
while ( fabs(CorrectedTime-fcurr) > baryCorrTol)
{
if (SignDirection == 1)
{
while (fcurr > CorrectedTime)
{
tcurr = tcurr+deltaStep;
fcurr = tcurr + getBaryCorr(tcurr,0); //fx(tcurr);
// std::cout << std::setprecision(30) << " tcurr=>" << tcurr << " fcurr " << fcurr
// << "df=" << CorrectedTime-fcurr << std::endl;
}
}
else
while (fcurr < CorrectedTime)
{
tcurr = tcurr+deltaStep;
fcurr = tcurr + getBaryCorr(tcurr,0); //fx(tcurr);
//std::cout << std::setprecision(30) << " tcurr=>" << tcurr << " fcurr " << fcurr
// << "df=" << CorrectedTime-fcurr << std::endl;
}
tcurr = tcurr-deltaStep;
fcurr = tcurr + getBaryCorr(tcurr,0); //fx(tcurr);
s++;
deltaStep = pow(10.,(2.-s));
//std::cout << "\n" << m_PSRname << " Target superated, decreasing to " << deltaStep
// << " and starting again1 from " << tcurr << std::endl;
//std::cout << std::setprecision(30) << CorrectedTime <<
//" <--" << fcurr << " df=" << CorrectedTime-fcurr << std::endl;
if ((s > 10) || (deltaStep < 1e-7))
{
//std::cout << "Skipping ! " << std::endl;
break;
}
}
if (DEBUG)
{
std::cout << std::setprecision(30) << s << " -> " << CorrectedTime
<< " <--" << fcurr
<< " df=" << CorrectedTime-fcurr << std::endl;
}
return tcurr;
}
/////////////////////////////////////////////
/*!
* \param CorrectedTime Photon arrival time Modulatedat SSB (TDB expressed in MJD)
*
* <br>
* This method returns the correspondent inverse-demodulated time of each photons, includingRoemer delay, Einstein delay
* and Shapiro delay
*/
double PulsarSpectrum::getBinaryDemodulationInverse( double CorrectedTime)
{
double deltaMin = m_asini*(1.+m_ecc);//-m_asini*std::sqrt(1.-m_ecc*m_ecc);
double tcurr = CorrectedTime-deltaMin;
double fcurr = getIterativeDemodulatedTime(tcurr,0);
// double fcurr_ct = CorrectedTime;
if (DEBUG)
{
std::cout << "Get inverse demodulated time for t=" << CorrectedTime << std::endl;
}
//double deltaStep = 10.;
int s = 0;
int SignDirection = 0;
double StartStep = 1.0*int(log10(fabs(deltaMin/10.)));
double deltaStep = pow(10.,(StartStep-s));
//std::cout << "START " << StartStep << " dmin " << deltaMin << std::endl;
if (CorrectedTime <= fcurr) // function increasing
{
// std::cout << "Case 1: de-crescent function" << std::endl;
SignDirection = 1;
}
else
{
//std::cout << "Case 2: crescent function" << std::endl;
SignDirection = 2;
}
/*
std::cout << "\n\n***\n"<<m_PSRname<<"tstart= " << tcurr << " -->fcurr= " << fcurr
<< " -->fcurr_CT= " << CorrectedTime << " inital delta="
<< deltaStep << " sign" << SignDirection << std::endl;
*/
//double tModMid=0.;
int nMaxStepIterations=0;
while ( fabs(CorrectedTime-fcurr) > InverseDemodTol)
{
nMaxStepIterations=0;
if (SignDirection == 1)
{
while ((fcurr > CorrectedTime) && (nMaxStepIterations <1000))
{
tcurr = tcurr+deltaStep;
fcurr = getIterativeDemodulatedTime(tcurr,0);
nMaxStepIterations++;
if (fcurr < CorrectedTime)
{
break;
}
//std::cout << std::setprecision(30) << nMaxStepIterations <<" tcurr=>" << tcurr << " fcurr " << fcurr
// << "df=" << CorrectedTime-fcurr << std::endl;
}
}
else
while ((fcurr < CorrectedTime) && (nMaxStepIterations <1000))
{
tcurr = tcurr+deltaStep;
fcurr = getIterativeDemodulatedTime(tcurr,0);
nMaxStepIterations++;
//std::cout << std::setprecision(30) << nMaxStepIterations << " tcurr=>" << tcurr << " fcurr " << fcurr
//<< "df=" << CorrectedTime-fcurr << std::endl;
if (fcurr > CorrectedTime)
{
break;
}
}
tcurr = tcurr-deltaStep;
fcurr = getIterativeDemodulatedTime(tcurr,0);
s++;
deltaStep = pow(10.,(StartStep-s));
//std::cout << "\n" << m_PSRname << " Target superated, decreasing to " << deltaStep
// << " and starting again1 from " << tcurr << std::endl;
//std::cout << std::setprecision(30) << CorrectedTime <<
//" <--" << fcurr << " df=" << CorrectedTime-fcurr << std::endl;
if ((s > 8) || (deltaStep < 1e-7))
{
//std::cout << "Skipping ! " << std::endl;
break;
}
}
// std::cout << std::setprecision(30) << s << " -> " << CorrectedTime
// << " <--" << fcurr
// << " df=" << CorrectedTime-fcurr << std::endl;
return tcurr;
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* This method gets from the ASCII <i>PulsarDatalist.txt</i> file stored in <i>/data</i> directory)
* the names of the files that contain the pulsars parameters. The default one is <i>BasicDataList.txt</i>.
* This method returns a integer status code (1 is Ok, 0 is failure)
*/
int PulsarSpectrum::getPulsarFromDataList(std::string sourceFileName)
{
double startTime = 0.;//Spectrum::startTime();
double endTime = 0.;//astro::GPS::instance()->endTime();
if (m_UseFT2 == 1)
{
startTime = m_FT2_startMET + (550/86400.);
endTime = m_FT2_stopMET - (550/86400.);
} else
{
startTime = m_Sim_startMET + (550/86400.);
endTime = m_Sim_stopMET - (550/86400.);
}
int Status = 0;
std::ifstream PulsarDataTXT;
if (DEBUG)
{
std::cout << "\nOpening Pulsar Datalist File : " << sourceFileName << std::endl;
}
PulsarDataTXT.open(sourceFileName.c_str(), std::ios::in);
if (! PulsarDataTXT.is_open())
{
throw "Error! Cannot open file ";
}
else {
char aLine[400];
PulsarDataTXT.getline(aLine,400);
char tempName[15] = "";
double flux, ephem0, ephem1, ephem2, t0Init, t0, t0End, txbary, phi0, period, pdot, p2dot, f0, f1, f2, phas;
char ephemType[15] = "";
int tnmodel, binflag;
while (PulsarDataTXT.eof() != 1)
{
PulsarDataTXT >> tempName >> flux >> ephemType >> ephem0 >> ephem1 >> ephem2
>> t0Init >> t0 >> t0End >> txbary >> tnmodel >> binflag;
// std::cout << tempName << flux << ephemType << ephem0 << ephem1 << ephem2
// << t0Init << t0 << t0End << txbary << tnmodel << binflag <<std::endl;
if (std::string(tempName) == m_PSRname)
{
Status = 1;
m_flux = flux;
m_TimingNoiseModel = tnmodel;
m_ephemType = ephemType;
m_BinaryFlag = binflag;
//Check if txbary or t0 are before start of the simulation
double startMJD = StartMissionDateMJD+(startTime/86400.)+(550/86400.);
// std::cout << "T0 " << t0 << " start " << startMJD << std::endl;
if ((t0 < startMJD) || (txbary < startMJD))
{
if (m_OutputLevel>1)
{
char temp[200];
sprintf(temp,"Warning! Epoch t0 out the simulation range (t0-tStart=%.10f) s.: changing to MJD=%d",(t0-startMJD),startMJD);
WriteToLog(std::string(temp));
}
t0 = startMJD;
txbary = startMJD;
}
//Check if txbary or t0 are after start of the simulation
double endMJD = StartMissionDateMJD+(endTime/86400.)-(550/86400.);
// std::cout << "T0 " << t0 << " start " << startMJD << std::endl;
if ((t0 > endMJD) || (txbary > endMJD))
{
if (m_OutputLevel>1)
{
char temp[200];
sprintf(temp,"Warning! Epoch t0 out the simulation range (t0-tEnd=%.10f) s.: changing to MJD=%d",
(t0-endMJD),endMJD);
WriteToLog(std::string(temp));
sprintf(temp,"** Tnd at %d corresp. to MJD %d",endTime,endMJD);
WriteToLog(std::string(temp));
}
t0 = endMJD;
txbary = endMJD;
}
m_t0InitVect.push_back(t0Init);
m_t0Vect.push_back(t0);
m_t0EndVect.push_back(t0End);
m_txbaryVect.push_back(txbary);
//Period-type ephemerides
if (std::string(ephemType) == "P")
{
period = ephem0;
pdot = ephem1;
p2dot = ephem2;
f0 = 1.0/period;
f1 = -pdot/(period*period);
f2 = 2*pow((pdot/period),2.0)/period - p2dot/(period*period);
}
else if (std::string(ephemType) == "F")
{
//Frequency-style ephemrides
f0 = ephem0;
f1 = ephem1;
f2 = ephem2;
period = 1.0/f0;
}
m_periodVect.push_back(period);
m_pdotVect.push_back(pdot);
m_p2dotVect.push_back(p2dot);
m_f0Vect.push_back(f0);
m_f1Vect.push_back(f1);
m_f2Vect.push_back(f2);
double dt = (txbary-t0)*SecsOneDay;
phi0 = -1.0*(f0*dt
+ (f1/2.0)*dt*dt
+ (f2/6.0)*dt*dt*dt);
phi0 = modf(phi0,&phas);
if (phi0 < 0. )
phi0++;
m_phi0Vect.push_back(phi0);
}
}
}
return Status;
}
/////////////////////////////////////////////
/*!
* \param pulsar_data_dir: $PULSARDATA directory;
* \param DataType: Type of data to be loaded (0=General data; 1=Orbital Data);
*
* <br>
* This method load pulsar general data (flux, spin parameters, etc..) of
* orbital data (kepler parameters, etc..) according to DataType parameter
* Datafiles containing parameters must be specified in $PULSARDATA/PulsarDataList.txt
* for general data or $PULSARDATA/PulsarBinDataList.txt for orbital data
*
*/
void PulsarSpectrum::LoadPulsarData(std::string pulsar_data_dir, int DataType = 0)
{
//Scan PulsarDataList.txt for Pulsar general data
std::string ListFileName;
if (DataType == 0)
{
ListFileName = facilities::commonUtilities::joinPath(pulsar_data_dir, "PulsarDataList.txt");
if (DEBUG)
{
std::cout << "Reading General Data" << std::endl;
}
}
else if (DataType == 1)
{
ListFileName = facilities::commonUtilities::joinPath(pulsar_data_dir, "PulsarBinDataList.txt");
if (DEBUG)
{
std::cout << "Reading Orbital Data" << std::endl;
}
}
//new block for reading lines
//max
try
{
CheckFileExistence(ListFileName);
std::ifstream ListFile(ListFileName.c_str());
std::string dataline;
std::vector<std::string> datalines;
while (std::getline(ListFile, dataline, '\n'))
{
if (dataline != "" && dataline != " "
&& dataline.find_first_of('#') != 0)
{
datalines.push_back(dataline);
}
}
// After lines are parsed, each DataList is processed...
int PulsarFound=0;
int l=0;
while ((l<datalines.size()) && (PulsarFound!=1))
{
std::string CompletePathFileName = facilities::commonUtilities::joinPath(pulsar_data_dir,datalines[l]);
try
{
if (DataType == 0)
{
PulsarFound = getPulsarFromDataList(CompletePathFileName);
}
else if (DataType == 1)
{
PulsarFound = getOrbitalDataFromBinDataList(CompletePathFileName);
}
}
catch (char const *error) //DataList does not exists....
{
if (m_OutputLevel>1)
{
WriteToLog("WARNING!"+std::string(error)+std::string(CompletePathFileName)
+"... skip to next ASCII Data list file");
}
}
l++;
}
if (PulsarFound == 0)//if no Datalist contains pulsars...
{
std::cout << "ERROR! Unable to find pulsar " << m_PSRname
<< " in any DataList. Check $PULSARDATA" << std::endl;
exit(1);
}
//if requested, initialize log output for barycentric corrections
if (::getenv("PULSAR_OUT_BARY"))
{
std::ofstream BaryCorrLogFile((m_PSRname + "BaryCorr.log").c_str());
BaryCorrLogFile << "\nPulsar" << m_PSRname
<< " : Barycentric corrections log generated by PulsarSpectrum"
<< std::endl;
BaryCorrLogFile << "tMET\tTDB-TT\tGeomDelay\tShapiroDelay" << std::endl;
BaryCorrLogFile.close();
}
//if requested, initialize log output for barycentric corrections
if ((m_BinaryFlag ==1) && (::getenv("PULSAR_OUT_BIN")))
{
std::ofstream BinDemodLogFile((m_PSRname + "BinDemod.log").c_str());
BinDemodLogFile << "tMET\tdt\tE\tAt\tOmega\tecc\tasini\tdt_Roemer\tdt_einstein\tdt_shapiro"
<< std::endl;
BinDemodLogFile.close();
}
}
catch (char const *error) //DataList.txt of BinDataList.txt does not exists...
{
std::cerr << error << ListFileName << std::endl;
exit(1);
}
if (DataType == 0)
{
//Assign as starting ephemeris the first entry of the vectors...
m_t0Init = m_t0InitVect[0];
m_t0 = m_t0Vect[0];
m_t0End = m_t0EndVect[0];
m_period = m_periodVect[0];
m_pdot = m_pdotVect[0];
m_p2dot = m_p2dotVect[0];
m_f0 = m_f0Vect[0];
m_f1 = m_f1Vect[0];
m_f2 = m_f2Vect[0];
m_f0NoNoise = m_f0Vect[0];
m_f1NoNoise = m_f1Vect[0];
m_f2NoNoise = m_f2Vect[0];
m_phi0 = m_phi0Vect[0];
}
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* This method gets the orbital parameters of the binary pulsar from a
* <i>BinDataList/i> file among those specified in the<i>/data/PulsarBinDataList</i>
*
* The orbital parameters are:
*
* m_Porb Orbital period;
* m_asini Projected major semiaxis;
* m_eccentr eccentricity;
* m_omega longitude of periastron;
* m_t0PeriastronMJD epoch of periastron passage;
* m_t0AscNodeMJD Epoch of the ascending node;
*
* The key for finding pulsar is the name of the files that contain the pulsars parameters.
* The default one is <i>BasicDataList.txt</i>.
* Extra parameters are used to specify a PPN parameterization for General Relativity;
* This method returns a integer status code (1 is Ok, 0 is failure)
*/
int PulsarSpectrum::getOrbitalDataFromBinDataList(std::string sourceBinFileName)
{
int Status = 0;
std::ifstream PulsarBinDataTXT;
if (DEBUG)
{
std::cout << "\nOpening Binary Pulsar BinDatalist File : " << sourceBinFileName << std::endl;
}
PulsarBinDataTXT.open(sourceBinFileName.c_str(), std::ios::in);
if (! PulsarBinDataTXT.is_open())
{
throw "Error!Cannot open file";
// std::cout << "Error opening BinDatalist file " << sourceBinFileName
// << " (check whether $PULSARDATA is set)" << std::endl;
//Status = 0;
//exit(1);
}
char aLine[400];
PulsarBinDataTXT.getline(aLine,400);
char tempName[30];
double porb,asini,ecc,omega,t0peri,t0asc,ppn;
while (PulsarBinDataTXT.eof() != 1)
{
PulsarBinDataTXT >> tempName >> porb >> asini >> ecc >> omega >> t0peri >> t0asc >> ppn;
if (std::string(tempName) == m_PSRname)
{
Status = 1;
m_Porb = porb;
m_asini = asini;
m_ecc = ecc;
m_omega = omega;
m_t0PeriastrMJD = t0peri;
m_t0AscNodeMJD = t0asc;
m_PPN = ppn;
}
}
return Status;
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* Initialize variable related to timing noise
*/
void PulsarSpectrum::InitTimingNoise()
{
if (::getenv("PULSAR_OUT_TNOISE"))
{
std::ofstream TimingNoiseLogFile((m_PSRname + "TimingNoise.log").c_str());
TimingNoiseLogFile << "Timing Noise log file using model: " << m_TimingNoiseModel << std::endl;
TimingNoiseLogFile << "tMET\tA\tS0\tS1\tS2\tf0_l\tf0_n\tf1_l\tf1_n\tf2_l\tf2_n\tPhi_l\tPhi_n"
<<std::endl;
TimingNoiseLogFile.close();
}
//define a default mean rate of about 1 day
m_TimingNoiseMeanRate = 1/86400.;
// according to Poisson statistics
double startTime = Spectrum::startTime();
//Determine next Timing noise event according to the rate R m_TimingNoiseRate
m_TimingNoiseTimeNextEvent = startTime -log(1.-m_PSpectrumRandom->Uniform(1.0))/m_TimingNoiseMeanRate;
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* TnoiseInputTime input time where to apply noise
*
* Do the timing noise calculation on ephemerides
*/
void PulsarSpectrum::ApplyTimingNoise(double TnoiseInputTime)
{
double intPart=0.; //Integer part
double PhaseNoNoise,PhaseWithNoise=0.;
//Check for a next Timing noise event
if ((TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay) > m_TimingNoiseTimeNextEvent)
{
//interval according to Poisson statistics
m_TimingNoiseTimeNextEvent+= -log(1.-m_PSpectrumRandom->Uniform(1.0))/m_TimingNoiseMeanRate;
if (DEBUG)
{
std::cout << std::setprecision(30)<<"Timing Noise Event!Next Event at t="
<< m_TimingNoiseTimeNextEvent << " |dt="
<< m_TimingNoiseTimeNextEvent
-(TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay) <<std::endl;
}
//Timing noise managing...
double S0=0.;
double S1=0.;
double S2=0.;
if (m_TimingNoiseModel ==1) // Timing Noise #1
{
m_f2 = 0;
PhaseNoNoise = getTurns(TnoiseInputTime);
PhaseNoNoise = modf(PhaseNoNoise,&intPart); // phase for linear evolution
if ( PhaseNoNoise <0.)
PhaseNoNoise+=1.;
m_TimingNoiseActivity = 6.6 + 0.6*log10(m_pdot) + m_PSpectrumRandom->Gaus(0,0.5);
//estimate an f2
double Sign = m_PSpectrumRandom->Uniform();
if (Sign > 0.5)
m_f2 = ((m_f0*6.*std::pow(10.,m_TimingNoiseActivity))*1e-24);
else
m_f2 = -1.0*((m_f0*6.*std::pow(10.,m_TimingNoiseActivity))*1e-24);
}
else if ((m_TimingNoiseModel >1) && (m_TimingNoiseModel < 5)) // Timing Noise RW -Cordes-Downs
{
m_f2 = 0.;
double tempPhi0 = m_phi0;
m_phi0 = 0.;
double tempF0 = m_f0;
m_f0 = m_f0NoNoise;
double tempF1 = m_f1;
m_f1 = m_f1NoNoise;
PhaseNoNoise = getTurns(TnoiseInputTime);
PhaseNoNoise = modf(PhaseNoNoise,&intPart); // phase for linear evolution
if ( PhaseNoNoise <0.)
PhaseNoNoise+=1.;
//Determine Crab RMS
double dt_days = (TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay)/SecsOneDay;
double s_rms_crab = 0.012*pow((dt_days/1628),1.5);
//Activity parameter
//m_TimingNoiseActivity = -1.37+0.71*log10(m_pdot*1E15);
//double s_rms = pow(10.0,m_TimingNoiseActivity)*s_rms_crab;
m_TimingNoiseActivity = -1.37+0.71*log(m_pdot*1E15);
double s_rms = exp(m_TimingNoiseActivity)*s_rms_crab;
if (m_TimingNoiseModel ==2) //Case 1 :PN
{
S0 = (3.7*3.7*s_rms*s_rms)*(2/(SecsOneDay*dt_days));
m_TimingNoiseRMS = std::sqrt((S0/m_TimingNoiseMeanRate));
m_phi0 = tempPhi0+m_PSpectrumRandom->Gaus(0,m_TimingNoiseRMS);
// std::cout << std::setprecision(30) << "A="<<m_TimingNoiseActivity<<" dt"<<dt_days << " s_rms" << s_rms <<
//" S0 " << S0 << " RMS " << m_TimingNoiseRMS << " phi0 " << m_phi0 << std::endl;
}
else if (m_TimingNoiseModel ==3) //Case 2 :PN
{
S1 =(15.5*15.5*s_rms*s_rms)*(12./pow((SecsOneDay*dt_days),3));
m_TimingNoiseRMS = std::sqrt((S1/m_TimingNoiseMeanRate));
m_f0 = tempF0+m_PSpectrumRandom->Gaus(0,m_TimingNoiseRMS);
//std::cout << std::setprecision(30) << "A="<<m_TimingNoiseActivity<<" dt"<<dt_days << " s_rms" << s_rms <<
//" S1 " << S1 << " RMS " << m_TimingNoiseRMS << " f0 " << m_f0 << std::endl;
}
else if (m_TimingNoiseModel ==4) //Case 3 :SN
{
S2 =(23.7*23.7*s_rms*s_rms)*(120./pow((SecsOneDay*dt_days),5));
m_TimingNoiseRMS = std::sqrt((S2/m_TimingNoiseMeanRate));
m_f1 = tempF1+m_PSpectrumRandom->Gaus(0,m_TimingNoiseRMS);
//std::cout << std::setprecision(30) << "A="<<m_TimingNoiseActivity<<" dt"<<dt_days << " s_rms" << s_rms <<
// " S2 " << S2 << " RMS " << m_TimingNoiseRMS << " f1 " << m_f1 << std::endl;
}
}
if ((DEBUG) || (::getenv("PULSAR_OUT_TNOISE")))
{
PhaseWithNoise = getTurns(TnoiseInputTime);
PhaseWithNoise = modf(PhaseWithNoise,&intPart); // phase for linear evolution
if ( PhaseWithNoise <0.)
PhaseWithNoise+=1.;
}
if (::getenv("PULSAR_OUT_TNOISE"))
{
std::ofstream TimingNoiseLogFile((m_PSRname + "TimingNoise.log").c_str(),std::ios::app);
m_f2NoNoise = 0.;
double ft_l = GetFt(TnoiseInputTime,m_f0NoNoise,m_f1NoNoise,m_f2NoNoise);
double ft_n = GetFt(TnoiseInputTime,m_f0,m_f1,m_f2);
double ft1_l = GetF1t(TnoiseInputTime,m_f1NoNoise,m_f2NoNoise);
double ft1_n = GetF1t(TnoiseInputTime,m_f1,m_f2);
double ft2_l = m_f2NoNoise;//
double ft2_n = m_f2;//
TimingNoiseLogFile << std::setprecision(30) << TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay
<< "\t" << m_TimingNoiseActivity
<< "\t" << S0
<< "\t" << S1
<< "\t" << S2
<< "\t" <<ft_l << "\t" << ft_n
<< "\t" <<ft1_l << "\t" << ft1_n
<< "\t" <<ft2_l << "\t" << ft2_n
<< "\t" << PhaseNoNoise << "\t" << PhaseWithNoise << std::endl;
}
if (DEBUG)
{
std::cout << std::setprecision(30) << " Activity=" << m_TimingNoiseActivity
<< "f2=" << m_f2 << " PN=" << PhaseWithNoise
<< " dPhi=" << PhaseWithNoise-PhaseNoNoise <<std::endl;
}
}
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* This method check if the current time is within valid ephemerides
*/
void PulsarSpectrum::CheckEphemeridesValidity(double EphCheckTime, double initTurns)
{
//Checks whether ephemerides (period,pdot, etc..) are within validity ranges
if (((EphCheckTime/SecsOneDay) < m_t0Init) || ((EphCheckTime/SecsOneDay) > m_t0End))
{
if (m_OutputLevel>1)
{
WriteToLog("WARNING! Time is out of range of validity for pulsar "+std::string(m_PSRname)
+": Switching to new ephemerides set...");
}
for (unsigned int e=0; e < m_t0Vect.size();e++)
if (((EphCheckTime/SecsOneDay) > m_t0InitVect[e]) && ((EphCheckTime/SecsOneDay) < m_t0EndVect[e]))
{
m_t0Init = m_t0InitVect[e];
m_t0 = m_t0Vect[e];
m_t0End = m_t0EndVect[e];
m_f0 = m_f0Vect[e];
m_f1 = m_f1Vect[e];
m_f2 = m_f2Vect[e];
m_f0NoNoise = m_f0Vect[e];
m_f1NoNoise = m_f1Vect[e];
m_f2NoNoise = m_f2Vect[e];
m_period = m_periodVect[e];
m_pdot = m_pdotVect[e];
m_p2dot = m_p2dotVect[e];
m_phi0 = m_phi0Vect[e];
if (m_OutputLevel>1)
{
WriteToLog("Valid Ephemerides set found:");
char temp[200];
sprintf(temp,"MJD(%d-%d) --> Epoch t0 = MJD %d",m_t0Init,m_t0End,m_t0);
WriteToLog(std::string(temp));
sprintf(temp,"f0: %.f Hz | f1: %.e Hz/s | f2 %.e Hz/s2 ",m_f0,m_f1,m_f2);
WriteToLog(std::string(temp));
sprintf(temp,"P0: %.f s | P1: %.e s/s | P2 %.e s/s2 ",m_period,m_pdot,m_p2dot);
WriteToLog(std::string(temp));
}
//Re-instantiate PulsarSim and SpectObj
delete m_Pulsar;
m_Pulsar = new PulsarSim(m_PSRname, m_seed, m_flux, m_enphmin, m_enphmax, m_period);
if (m_model == 1)
{
delete m_spectrum;
m_spectrum = new SpectObj(m_Pulsar->PSRPhenom(double(m_ppar0), m_ppar1,m_ppar2,m_ppar3,m_ppar4),1);
m_spectrum->SetAreaDetector(EventSource::totalArea());
}
m_N0 = m_N0 + initTurns - getTurns(EphCheckTime); //Number of turns at next t0
double intN0;
double N0frac = modf(m_N0,&intN0); // Start time for interval
m_N0 = m_N0 - N0frac;
if (m_OutputLevel > 1)
{
std::cout << std::setprecision(20) << " Turns now are " << initTurns
<< " ; at t0 " << m_N0 << std::endl;
}
//m_phi0 = m_phi0 - N0frac;
if (DEBUG)
{
std::cout << std::setprecision(20) << " At Next t0 Number of Turns will be: " << m_N0 << std::endl;
}
}
else
{
if (m_OutputLevel>1)
{
WriteToLog("WARNING! Valid ephemerides not found!Proceeding with the old ones");
}
}
}
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* This method saves the relevant information in a file, named SimPulsar_spin.txt.
* The format of this ASCII file is such that it can be given to gtpulsardb to produce
* a D4-compatible FITS file, that can be used with pulsePhase
*/
int PulsarSpectrum::saveDbTxtFile()
{
int Flag = 0;
std::string DbOutputFileName = "SimPulsars_spin.txt";
std::ifstream DbInputFile;
//Checks if the file exists
DbInputFile.open(DbOutputFileName.c_str(), std::ios::in);
if (! DbInputFile.is_open())
{
Flag = 0;
}
else
{
Flag = 1;
}
DbInputFile.close();
if (DEBUG)
{
std::cout << "Saving Pulsar ephemerides on file " << DbOutputFileName << std::endl;
}
std::ofstream DbOutputFile;
if (Flag == 0)
{
DbOutputFile.open(DbOutputFileName.c_str(), std::ios::out);
DbOutputFile << "# Simulated pulsars output file generated by PulsarSpectrum." << std::endl;
DbOutputFile << "SPIN_PARAMETERS\n";
DbOutputFile << "EPHSTYLE = FREQ\n\n# Then, a column header." << std::endl;
DbOutputFile << "PSRNAME RA DEC EPOCH_INT EPOCH_FRAC TOAGEO_INT TOAGEO_FRAC TOABARY_INT TOABARY_FRAC ";
DbOutputFile << "F0 F1 F2 RMS VALID_SINCE VALID_UNTIL BINARY_FLAG SOLAR_SYSTEM_EPHEMERIS OBSERVER_CODE" <<std::endl;
DbOutputFile.close();
}
//Writes out the infos of the file
DbOutputFile.open(DbOutputFileName.c_str(),std::ios::app);
double tempInt, tempFract;
for (unsigned int ep = 0; ep < m_periodVect.size(); ep++)
{
DbOutputFile << "\"" << m_PSRname << std::setprecision(10) << "\" " << m_RA << " " << m_dec << " ";
tempFract = modf(m_t0Vect[ep],&tempInt);
DbOutputFile << std::setprecision (8) << tempInt << " " << tempFract << " ";
tempFract = getDecorrectedTime(m_txbaryVect[ep]*SecsOneDay)/SecsOneDay;
tempFract = modf(tempFract,&tempInt);
DbOutputFile << std::setprecision (8) << tempInt << " " << tempFract << " ";
tempFract = modf(m_txbaryVect[ep],&tempInt);
DbOutputFile << std::setprecision (8) << tempInt << " " << tempFract << " ";
std::string BinFlag;
if (m_BinaryFlag==0)
BinFlag = "F";
else if (m_BinaryFlag==1)
BinFlag = "T";
std::string SolarEph;
if (::getenv("PULSAR_EPH"))
{
const char * soleph = ::getenv("PULSAR_EPH");
SolarEph = " \"" + std::string(soleph) + "\"";
}
else
{
SolarEph = " \"JPL DE405\"";
}
DbOutputFile << std::setprecision(14)
<< m_f0Vect[ep] << " " << m_f1Vect[ep] << " " << m_f2Vect[ep] << " "
<< m_TimingNoiseRMS*1e3 << " "
<< m_t0InitVect[ep] << " " << m_t0EndVect[ep] << " "
<< BinFlag << SolarEph << " MR" << std::endl;
}
DbOutputFile.close();
if (DEBUG)
if (Flag == 0)
{
std::cout << "Database Output file created from scratch " << std::endl;
}
else
{
std::cout << "Appendended data to existing Database output file" << std::endl;
}
return Flag;
}
/////////////////////////////////////////////
/*!
* \param NameFileToCheck
*
* <br>
* This method simply check the file and return an exception
*/
void PulsarSpectrum::CheckFileExistence(std::string NameFileToCheck)
{
std::ifstream FileToCheck;
FileToCheck.open(NameFileToCheck.c_str(), std::ios::in);
if (!FileToCheck.is_open())
{
throw "Error!Cannot open file";
}
FileToCheck.close();
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* This method saves the relevant orbital parameters in a file, named SimPulsar_bin.txt.
* The format of this ASCII file is such that it can be given to gtpulsardb to produce
* a D4-compatible FITS file, that can be used with pulsePhase
*/
int PulsarSpectrum::saveBinDbTxtFile()
{
int Flag = 0;
std::string DbBinOutputFileName = "SimPulsars_bin.txt";
std::ifstream DbBinInputFile;
//Checks if the file exists
DbBinInputFile.open(DbBinOutputFileName.c_str(), std::ios::in);
if (! DbBinInputFile.is_open())
{
Flag = 0;
}
else
{
Flag = 1;
}
DbBinInputFile.close();
if (DEBUG)
{
std::cout << "Saving Pulsar Orbital Data on file " << DbBinOutputFileName << std::endl;
}
std::ofstream DbBinOutputFile;
if (Flag == 0)
{
DbBinOutputFile.open(DbBinOutputFileName.c_str(), std::ios::out);
DbBinOutputFile << "# Simulated pulsars orbital data output file generated by PulsarSpectrum." << std::endl;
DbBinOutputFile << "ORBITAL_PARAMETERS\nEPHSTYLE = DD /Simplified model\n# This file can be converted to a D4 fits file using:" << std::endl;
DbBinOutputFile << "# >gtpulsardb SimPulsars_bin.txt" << std::endl;
DbBinOutputFile << "PSRNAME PB PBDOT A1 XDOT ECC ECCDOT OM OMDOT T0 GAMMA SHAPIRO_R SHAPIRO_S OBSERVER_CODE SOLAR_SYSTEM_EPHEMERIS" << std::endl;;
DbBinOutputFile.close();
}
//Writes out the infos of the file
DbBinOutputFile.open(DbBinOutputFileName.c_str(),std::ios::app);
DbBinOutputFile << "\"" << m_PSRname << "\" "; // pulsar name
DbBinOutputFile << std::setprecision(10) << m_Porb << " " << m_Porb_dot << " "; // Orbital period and derivative
DbBinOutputFile << std::setprecision(10) << m_asini << " " << m_xdot << " "; // Projected semi-mayor axis and derivative
DbBinOutputFile << std::setprecision(10) << m_ecc << " " << m_ecc_dot << " "; // Eccentricity and derivative
DbBinOutputFile << std::setprecision(10) << m_omega << " " << m_omega_dot << " "; // Long. Periastron and derivative
DbBinOutputFile << std::setprecision(10) << m_t0PeriastrMJD << " " << m_gamma << " "; // t0 of Periastron and PPN gamma
//Shapiro Parameters
DbBinOutputFile << std::setprecision(10) << m_shapiro_r << " " << m_shapiro_s; //Shapiro Parameters
std::string SolarEph;
if (::getenv("PULSAR_EPH"))
{
const char * soleph = ::getenv("PULSAR_EPH");
SolarEph = " \"" + std::string(soleph) + "\"";
}
else
{
SolarEph = " \"JPL DE405\"";
}
DbBinOutputFile << " MR "<<SolarEph<<std::endl;// Observer code and ephemerides
DbBinOutputFile.close();
//In this case a summary D4 file is created
std::ofstream DbSumInputFile("SimPulsars_summary.txt");
DbSumInputFile << "SimPulsars_spin.txt\nSimPulsars_bin.txt" <<std::endl;
DbSumInputFile.close();
if (DEBUG)
if (Flag == 0)
{
std::cout << "Database for Binary pulsars file created from scratch " << std::endl;
}
else
{
std::cout << "Database for Binary pulsars appended to existing binary Database output file" << std::endl;
}
return Flag;
}
/////////////////////////////////////////////
/*!
* \param None
*
* <br>
* This method saves the relevant information about pulsar in a log file
*/
void PulsarSpectrum::WritePulsarLog()
{
//Write infos to Log file
std::ofstream PulsarLog(m_LogFileName.c_str(),std::ios::app);
PulsarLog << "** PulsarSpectrum: " << "******** PulsarSpectrum Log for pulsar" << m_PSRname << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Name : " << m_PSRname << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Position : (RA,Dec)=(" << m_RA << "," << m_dec
<< ") ; (l,b)=(" << m_l << "," << m_b << ")" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Flux above 100 MeV : " << m_flux << " ph/cm2/s " << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Enphmin: " << m_enphmin << " keV | Enphmax: " << m_enphmax << " keV" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl;
//Write info about FT2
if (m_UseFT2 == 0)
{
PulsarLog << "** PulsarSpectrum: "<< "** No FT2 file used " << std::endl;
}
else
PulsarLog << "** PulsarSpectrum: "<< "** FT2 file used " << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Start time:" << std::setprecision(30) << m_FT2_startMET << " s. MET | End time:"
<< m_FT2_stopMET << " s. MET" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Simulation start at " << m_Sim_startMET << " s. MET and ends at :"
<< m_Sim_stopMET << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl;
//Writes down on Log all the ephemerides
for (unsigned int n=0; n < m_t0Vect.size(); n++)
{
PulsarLog << "** PulsarSpectrum: "<< "** Ephemerides valid from " << m_t0InitVect[n]
<< " to " << m_t0EndVect[n] << " (MJD): " << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Epoch (MJD) : " << m_t0Vect[n] << std::endl;
PulsarLog << "** PulsarSpectrum: "<< std::setprecision(8) << "** TxBary (MJD) where fiducial point (phi=0) is reached : "
<< m_txbaryVect[n] << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Phi0 (at Epoch t0) : " << m_phi0Vect[n] << std::endl;
if (m_ephemType == "P")
{
PulsarLog << "** PulsarSpectrum: "<< "** Ephemerides type: PERIOD" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** Period : "
<< m_periodVect[n] << " s. | f0: " << m_f0Vect[n] << std::endl;
PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** Pdot : "
<< m_pdotVect[n] << " | f1: " << m_f1Vect[n] << std::endl;
PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** P2dot : "
<< m_p2dotVect[n] << " | f2: " << m_f2Vect[n] << std::endl;
}
else if (m_ephemType == "F")
{
PulsarLog << "** PulsarSpectrum: "<< "**Ephemerides type: FREQUENCY" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** Period : "
<< m_periodVect[n] << " s. | f0: " << m_f0Vect[n] << std::endl;
PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** f1: " << m_f1Vect[n] << std::endl;
PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** f2: " << m_f2Vect[n] << std::endl;
}
}
//MJDRef
PulsarLog << "** PulsarSpectrum: "<< "** Mission Reference time: MJD " << StartMissionDateMJD << " ("
<< std::setprecision(12) << (StartMissionDateMJD+JDminusMJD)*SecsOneDay
<< " sec.)" << std::endl;
//SimulationModel
if (m_model ==1)
{
PulsarLog << "** PulsarSpectrum: "<< "** Model chosen : " << m_model
<< " --> Using Phenomenological Pulsar Model " << std::endl;
} else if (m_model == 2)
{
PulsarLog << "** PulsarSpectrum: "<< "** Model chosen : " << m_model
<< " --> Using External 2-D Pulsar Shape" << std::endl;
}
PulsarLog << "** PulsarSpectrum: "<< "** Effective Area set to : " << m_spectrum->GetAreaDetector() << " m^2 " << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl;
//Timing noise
if (m_TimingNoiseModel == 1) // Timing model #1 - Delta8 parameter (Arzoumanian94)
{
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel
<< " (Stability parameter, Arzoumanian 1994)" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl;
}
else if (m_TimingNoiseModel == 2) //Timing model #2 - PN Random Walk (Cordes-Downs 1985)
{
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel
<< " (PN Random Walk; Cordes-Downs 1985)" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl;
}
else if (m_TimingNoiseModel == 3) //Timing model #3 - FN Random Walk (Cordes-Downs 1985)
{
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel
<< " (FN Random Walk; Cordes-Downs 1985)" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl;
}
else if (m_TimingNoiseModel == 4) //Timing model #4 - SN Random Walk (Cordes-Downs 1985)
{
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel
<< " (SN Random Walk; Cordes-Downs 1985)" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl;
}
//Orbital info
if (m_BinaryFlag == 1)
{
PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Pulsar in a Binary System! Orbital Data:" << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Orbital period: " << m_Porb << " s." << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Projected major semiaxis (a * sini): " << m_asini << " lightsec." <<std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Eccentricity: " << m_ecc << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Longitude of periastron: " << m_omega << " deg." << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Epoch of Periastron (MJD): " << m_t0PeriastrMJD << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "** Epoch of Ascending Node (MJD): " << m_t0AscNodeMJD << std::endl;
if (m_PPN ==0)
PulsarLog << "** PulsarSpectrum: "<< "** No Post Newtonian Parameterization " << std::endl;
PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl;
}
PulsarLog.close();
}
//////////////////////////////////////////////////////////
// no longer used
/////////////////////////////////////////////////////////
double PulsarSpectrum::GetEccentricAnomaly(double mytime)
{
double OmegaMean = 2*M_PI/m_Porb;
double dtime = (mytime-m_t0PeriastrMJD*SecsOneDay);
double EccAnConst = OmegaMean*(dtime - 0.5*(m_Porb_dot/m_Porb)*dtime*dtime);
double Edown = 0.;
double EccAnDown = Edown-(m_ecc*std::sin(Edown))-EccAnConst;
double Eup = 2*M_PI;
double EccAnUp = Eup-(m_ecc*std::sin(Eup))-EccAnConst;
double Emid = 0.5*(Eup + Edown);
double EccAnMid = Emid-(m_ecc*std::sin(Emid))-EccAnConst;
int i=0;
while (fabs(EccAnMid) > 5e-7)
{
if ((EccAnDown*EccAnMid) < 0)
{
Eup = Emid;
EccAnUp = EccAnMid;
}
else
{
Edown = Emid;
EccAnDown = EccAnMid;
}
i++;
Emid = 0.5*(Eup + Edown);
EccAnMid = Emid-(m_ecc*std::sin(Emid))-EccAnConst;
if (fabs(EccAnMid) < 5e-7)
break;
}
return Emid;
}
/////////////////////////////////////////////
double PulsarSpectrum::energy(double time)
{
return m_spectrum->energy(time,m_enphmin)*1.0e-3; //MeV
}
/////////////////////////////////////////////
/*!
* \param time input time for calculating f(t)
*
* This method computes the frequency at a given instant t
*
*/
double PulsarSpectrum::GetFt(double time, double myf0, double myf1, double myf2)
{
double dt = time - m_t0*SecsOneDay;
return myf0 + myf1*dt + 0.5*myf2*dt*dt;
}
/////////////////////////////////////////////
/*!
* \param time input time for calculating f'(t)
*
* This method computes the frequency first derivativeat a given instant t
*
*/
double PulsarSpectrum::GetF1t(double time, double myf1, double myf2)
{
double dt = time - m_t0*SecsOneDay;
return myf1 + myf2*dt;
}
/////////////////////////////////////////////
/*!
* \param input String to be parsed;
* \param index Position of the parameter to be extracted from input;
*
* <br>
* From a string contained in the XML file a parameter is extracted according to the position
* specified in <i>index</i>
*/
std::string PulsarSpectrum::parseParamList(std::string input, unsigned int index)
{
std::vector<std::string> output;
unsigned int i=0;
int StrLength=input.length();
while (i<StrLength)
{
i=input.find_first_of(",");
std::string f = ( input.substr(0,i).c_str() );
//std::cout << "i=" <<"sub " << f <<std::endl;
input=input.substr(i+1);
output.push_back(f);
}
if(index>=output.size()) return "";
return output[index];
}
/* old code:
std::string PulsarSpectrum::parseParamList(std::string input, unsigned int index)
{
std::vector<std::string> output;
unsigned int i=0;
for(;!input.empty() && i!=std::string::npos;){
i=input.find_first_of(",");
std::string f = ( input.substr(0,i).c_str() );
output.push_back(f);
input= input.substr(i+1);
}
if(index>=output.size()) return "";
return output[index];
}
*/
//////////////////////////////////////////////////
/*!
* \param Line line to be written in the output log file
*
* This method writes a line into a log file
*/
void PulsarSpectrum::WriteToLog(std::string Line)
{
std::ofstream PulsarLog(m_LogFileName.c_str(),std::ios::app);
PulsarLog << "** PulsarSpectrum: " << Line << std::endl;
PulsarLog.close();
}
| 32.066844 | 225 | 0.606455 | fermi-lat |
61c85db3194feee5de3deb95c62836eccb25eb34 | 925 | cpp | C++ | FurnishAR/Library/Bee/artifacts/Android/x6ly2/dopq_metadata0.lump.cpp | mactrix-markjohn/FurnishAR | 1fd36d2417d938611de8706e2c0956bd70efa4ec | [
"MIT"
] | null | null | null | FurnishAR/Library/Bee/artifacts/Android/x6ly2/dopq_metadata0.lump.cpp | mactrix-markjohn/FurnishAR | 1fd36d2417d938611de8706e2c0956bd70efa4ec | [
"MIT"
] | null | null | null | FurnishAR/Library/Bee/artifacts/Android/x6ly2/dopq_metadata0.lump.cpp | mactrix-markjohn/FurnishAR | 1fd36d2417d938611de8706e2c0956bd70efa4ec | [
"MIT"
] | null | null | null | //Generated lump file. generated by Bee.NativeProgramSupport.Lumping
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/CustomAttributeCreator.cpp"
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/CustomAttributeDataReader.cpp"
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/FieldLayout.cpp"
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/GenericMetadata.cpp"
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/GenericSharing.cpp"
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/Il2CppGenericContextCompare.cpp"
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/Il2CppGenericMethodHash.cpp"
#include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/Il2CppSignature.cpp"
| 92.5 | 114 | 0.823784 | mactrix-markjohn |
61cb646052d8bf082a49814e04b57dfd0c0c6672 | 603 | cpp | C++ | src/Papyrus/ExtendedObjectTypes.cpp | fireundubh/PapyrusExtenderSSE | 9816f9be76883b301a25349665f3a923d4fdc964 | [
"MIT"
] | 1 | 2021-08-30T20:33:43.000Z | 2021-08-30T20:33:43.000Z | src/Papyrus/ExtendedObjectTypes.cpp | fireundubh/PapyrusExtenderSSE | 9816f9be76883b301a25349665f3a923d4fdc964 | [
"MIT"
] | null | null | null | src/Papyrus/ExtendedObjectTypes.cpp | fireundubh/PapyrusExtenderSSE | 9816f9be76883b301a25349665f3a923d4fdc964 | [
"MIT"
] | null | null | null | #include "Papyrus/ExtendedObjectTypes.h"
auto extendedObjectTypes::RegisterTypes(VM* a_vm) -> bool
{
if (!a_vm) {
logger::critical("Object types - couldn't get VMState"sv);
return false;
}
a_vm->RegisterObjectType(vm_cast<RE::BGSFootstepSet>(), "FootstepSet");
logger::info("Registered footstep set object type"sv);
a_vm->RegisterObjectType(vm_cast<RE::BGSLightingTemplate>(), "LightingTemplate");
logger::info("Registered lighting template object type"sv);
a_vm->RegisterObjectType(vm_cast<RE::BGSDebris>(), "Debris");
logger::info("Registered debris object type"sv);
return true;
}
| 27.409091 | 82 | 0.742952 | fireundubh |
61cc0d987e8dea83ee8fb068e28b4a4f1fda37af | 933 | cpp | C++ | codeforces/498_3/b.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | 2 | 2018-06-26T09:52:14.000Z | 2018-07-12T15:02:01.000Z | codeforces/498_3/b.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | null | null | null | codeforces/498_3/b.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
map<int, int> m;
int n,k;
scanf("%d%d", &n, &k);
vector<int> a(n);
vector<int> b(n);
for(int i = 0; i<n; i++){
scanf("%d", &a[i]);
b[i] = a[i];
}
sort(b.rbegin(), b.rend());
for(int i = 0; i<k; i++)
if(m.find(b[i]) == m.end())
m[b[i]] = 1;
else
m[b[i]] += 1;
int sz = 0;
vector<int> ans;
for(int i = 0; i<n; i++){
sz++;
if(m.find(a[i]) != m.end() && m[a[i]] > 0)
{
ans.push_back(sz);
sz = 0;
m[a[i]] -= 1;
}
if(ans.size() == k-1)
break;
}
sz = 0;
for(int i = 0; i<k; i++)
sz += b[i];
printf("%d\n", sz);
sz = 0;
for(int i = 0; i < (k-1); i++){
printf("%d ", ans[i]);
sz += ans[i];
}
printf("%d\n", n-sz);
return 0;
}
| 15.048387 | 49 | 0.347267 | sidgairo18 |
61cc3f6fe9d8448581fa7c53b86a37faaf36c236 | 1,330 | cpp | C++ | WaveletTL/Rd/regularity.cpp | kedingagnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 3 | 2018-05-20T15:25:58.000Z | 2021-01-19T18:46:48.000Z | WaveletTL/Rd/regularity.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | null | null | null | WaveletTL/Rd/regularity.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 2 | 2019-04-24T18:23:26.000Z | 2020-09-17T10:00:27.000Z | // implementation for regularity.h
#include <algebra/vector.h>
#include <algebra/matrix.h>
#include <numerics/eigenvalues.h>
using namespace MathTL;
namespace WaveletTL
{
template <class MASK>
AutocorrelationMask<MASK>::AutocorrelationMask()
{
MASK a;
// b(k) = \sum_m a(k+m)*a(m)/2
const int k1 = a.begin().index()[0];
const int k2 = a.rbegin().index()[0];
for (int k = k1-k2; k <= k2-k1; k++)
for (int m = k1; m <= k2; m++)
if (m+k >= k1 && m+k <= k2)
set_coefficient(MultiIndex<int,1>(k),
get_coefficient(MultiIndex<int,1>(k))
+ a.get_coefficient(MultiIndex<int,1>(m))
* a.get_coefficient(MultiIndex<int,1>(m+k))/2.0);
}
template <class MASK>
double
Sobolev_regularity()
{
double r = 0;
// setup the autocorrelation mask according to the given mask
AutocorrelationMask<MASK> b;
// cout << "* the autocorrelation mask of a=" << MASK() << " is " << b << endl;
// setup A=(b_{2i-j})_{i,j\in\Omega}
const int N = b.rbegin().index()[0]; // offset for A
Matrix<double> A(2*N+1, 2*N+1);
for (int i = -N; i <= N; i++)
for (int j = -N; j <= N; j++)
A(N+i, N+j) = b.get_coefficient(MultiIndex<int,1>(2*i-j));
cout << "A=" << endl << A << endl;
// TODO: solve nonsymmetric eigenvalue problem here!
return r;
}
}
| 25.576923 | 83 | 0.586466 | kedingagnumerikunimarburg |
61cc8219de8035df8fdc8782a75bf9ced1f8f25e | 366 | cpp | C++ | C++Code/1009.cpp | CrystianPrintes20/ProjetoUri | 92a88ae2671a556f4d418c3605e9a2c6933dc9d8 | [
"MIT"
] | null | null | null | C++Code/1009.cpp | CrystianPrintes20/ProjetoUri | 92a88ae2671a556f4d418c3605e9a2c6933dc9d8 | [
"MIT"
] | null | null | null | C++Code/1009.cpp | CrystianPrintes20/ProjetoUri | 92a88ae2671a556f4d418c3605e9a2c6933dc9d8 | [
"MIT"
] | null | null | null | //Questão: Salario com Bonus
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string NOME;
float SALARIO, TOTALV, TOTAL;
cin >> NOME;
cout << fixed << setprecision(2);
cin >> SALARIO >> TOTALV;
cout << fixed << setprecision(2);
cout << "TOTAL = R$ "<<((TOTALV*15)/100) + SALARIO <<endl;
return 0;
} | 20.333333 | 61 | 0.620219 | CrystianPrintes20 |
61cd0148c0ed710a92985060567c32874034ab39 | 5,529 | cpp | C++ | unittest/wpilib/AnalogTrigger.cpp | fsxfreak/FRC-2015 | 0ee7c5c363fda77b3cf0ae7ea123b6bbbe89aa58 | [
"MIT"
] | 2 | 2015-01-10T23:11:46.000Z | 2015-02-09T04:28:03.000Z | unittest/wpilib/AnalogTrigger.cpp | fsxfreak/FRC-2015 | 0ee7c5c363fda77b3cf0ae7ea123b6bbbe89aa58 | [
"MIT"
] | null | null | null | unittest/wpilib/AnalogTrigger.cpp | fsxfreak/FRC-2015 | 0ee7c5c363fda77b3cf0ae7ea123b6bbbe89aa58 | [
"MIT"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "AnalogTrigger.h"
#include "AnalogInput.h"
//#include "NetworkCommunication/UsageReporting.h"
#include "Resource.h"
#include "WPIErrors.h"
/**
* Initialize an analog trigger from a channel.
*/
void AnalogTrigger::InitTrigger(uint32_t channel)
{
void* port = getPort(channel);
int32_t status = 0;
uint32_t index = 0;
m_trigger = initializeAnalogTrigger(port, &index, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
m_index = index;
HALReport(HALUsageReporting::kResourceType_AnalogTrigger, channel);
}
/**
* Constructor for an analog trigger given a channel number.
*
* @param channel The channel number on the roboRIO to represent. 0-3 are on-board 4-7 are on the MXP port.
*/
AnalogTrigger::AnalogTrigger(int32_t channel)
{
InitTrigger(channel);
}
/**
* Construct an analog trigger given an analog input.
* This should be used in the case of sharing an analog channel between the
* trigger and an analog input object.
* @param channel The pointer to the existing AnalogInput object
*/
AnalogTrigger::AnalogTrigger(AnalogInput *input)
{
InitTrigger(input->GetChannel());
}
AnalogTrigger::~AnalogTrigger()
{
int32_t status = 0;
cleanAnalogTrigger(m_trigger, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Set the upper and lower limits of the analog trigger.
* The limits are given in ADC codes. If oversampling is used, the units must be scaled
* appropriately.
* @param lower The lower limit of the trigger in ADC codes (12-bit values).
* @param upper The upper limit of the trigger in ADC codes (12-bit values).
*/
void AnalogTrigger::SetLimitsRaw(int32_t lower, int32_t upper)
{
if (StatusIsFatal()) return;
int32_t status = 0;
setAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Set the upper and lower limits of the analog trigger.
* The limits are given as floating point voltage values.
* @param lower The lower limit of the trigger in Volts.
* @param upper The upper limit of the trigger in Volts.
*/
void AnalogTrigger::SetLimitsVoltage(float lower, float upper)
{
if (StatusIsFatal()) return;
int32_t status = 0;
setAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Configure the analog trigger to use the averaged vs. raw values.
* If the value is true, then the averaged value is selected for the analog trigger, otherwise
* the immediate value is used.
* @param useAveragedValue If true, use the Averaged value, otherwise use the instantaneous reading
*/
void AnalogTrigger::SetAveraged(bool useAveragedValue)
{
if (StatusIsFatal()) return;
int32_t status = 0;
setAnalogTriggerAveraged(m_trigger, useAveragedValue, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Configure the analog trigger to use a filtered value.
* The analog trigger will operate with a 3 point average rejection filter. This is designed to
* help with 360 degree pot applications for the period where the pot crosses through zero.
* @param useFilteredValue If true, use the 3 point rejection filter, otherwise use the unfiltered value
*/
void AnalogTrigger::SetFiltered(bool useFilteredValue)
{
if (StatusIsFatal()) return;
int32_t status = 0;
setAnalogTriggerFiltered(m_trigger, useFilteredValue, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
}
/**
* Return the index of the analog trigger.
* This is the FPGA index of this analog trigger instance.
* @return The index of the analog trigger.
*/
uint32_t AnalogTrigger::GetIndex()
{
if (StatusIsFatal()) return ~0ul;
return m_index;
}
/**
* Return the InWindow output of the analog trigger.
* True if the analog input is between the upper and lower limits.
* @return True if the analog input is between the upper and lower limits.
*/
bool AnalogTrigger::GetInWindow()
{
if (StatusIsFatal()) return false;
int32_t status = 0;
bool result = getAnalogTriggerInWindow(m_trigger, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
return result;
}
/**
* Return the TriggerState output of the analog trigger.
* True if above upper limit.
* False if below lower limit.
* If in Hysteresis, maintain previous state.
* @return True if above upper limit. False if below lower limit. If in Hysteresis, maintain previous state.
*/
bool AnalogTrigger::GetTriggerState()
{
if (StatusIsFatal()) return false;
int32_t status = 0;
bool result = getAnalogTriggerTriggerState(m_trigger, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
return result;
}
/**
* Creates an AnalogTriggerOutput object.
* Gets an output object that can be used for routing.
* Caller is responsible for deleting the AnalogTriggerOutput object.
* @param type An enum of the type of output object to create.
* @return A pointer to a new AnalogTriggerOutput object.
*/
AnalogTriggerOutput *AnalogTrigger::CreateOutput(AnalogTriggerType type)
{
if (StatusIsFatal()) return NULL;
return new AnalogTriggerOutput(this, type);
}
| 33.107784 | 108 | 0.735214 | fsxfreak |
61cdb6830aa2f20207477bba3589e8919d3fa8fa | 2,422 | cpp | C++ | 3rdParty/fuerte/src/requests.cpp | LLcat1217/arangodb | 67c51272915699e0a489e1f8d9da786f4226221a | [
"Apache-2.0"
] | null | null | null | 3rdParty/fuerte/src/requests.cpp | LLcat1217/arangodb | 67c51272915699e0a489e1f8d9da786f4226221a | [
"Apache-2.0"
] | null | null | null | 3rdParty/fuerte/src/requests.cpp | LLcat1217/arangodb | 67c51272915699e0a489e1f8d9da786f4226221a | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include <fuerte/requests.h>
namespace arangodb { namespace fuerte { inline namespace v1 {
std::unique_ptr<Request> createRequest(RestVerb verb, ContentType contentType) {
auto request = std::make_unique<Request>();
request->header.restVerb = verb;
request->header.contentType(contentType);
request->header.acceptType(contentType);
return request;
}
// For User
std::unique_ptr<Request> createRequest(RestVerb verb, std::string const& path,
StringMap const& parameters,
VPackBuffer<uint8_t> payload) {
auto request = createRequest(verb, ContentType::VPack);
request->header.path = path;
request->header.parameters = parameters;
request->addVPack(std::move(payload));
return request;
}
std::unique_ptr<Request> createRequest(RestVerb verb, std::string const& path,
StringMap const& parameters,
VPackSlice const payload) {
auto request = createRequest(verb, ContentType::VPack);
request->header.path = path;
request->header.parameters = parameters;
request->addVPack(payload);
return request;
}
std::unique_ptr<Request> createRequest(RestVerb verb, std::string const& path,
StringMap const& parameters) {
auto request = createRequest(verb, ContentType::VPack);
request->header.path = path;
request->header.parameters = parameters;
return request;
}
}}} // namespace arangodb::fuerte::v1
| 37.84375 | 80 | 0.632122 | LLcat1217 |
61cfe29536646ed07ebd6673f1874cad2b3bbae9 | 1,543 | cpp | C++ | clang-tools-extra/clang-tidy/llvmlibc/LLVMLibcTidyModule.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | clang-tools-extra/clang-tidy/llvmlibc/LLVMLibcTidyModule.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang-tools-extra/clang-tidy/llvmlibc/LLVMLibcTidyModule.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===--- LLVMLibcTidyModule.cpp - clang-tidy ------------------------------===//
//
// 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 "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "CalleeNamespaceCheck.h"
#include "ImplementationInNamespaceCheck.h"
#include "RestrictSystemLibcHeadersCheck.h"
namespace clang {
namespace tidy {
namespace llvm_libc {
class LLVMLibcModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<CalleeNamespaceCheck>(
"llvmlibc-callee-namespace");
CheckFactories.registerCheck<ImplementationInNamespaceCheck>(
"llvmlibc-implementation-in-namespace");
CheckFactories.registerCheck<RestrictSystemLibcHeadersCheck>(
"llvmlibc-restrict-system-libc-headers");
}
};
// Register the LLVMLibcTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<LLVMLibcModule>
X("llvmlibc-module", "Adds LLVM libc standards checks.");
} // namespace llvm_libc
// This anchor is used to force the linker to link in the generated object file
// and thus register the LLVMLibcModule.
volatile int LLVMLibcModuleAnchorSource = 0;
} // namespace tidy
} // namespace clang
| 35.068182 | 80 | 0.711601 | mkinsner |
61d61c350d825f939835a4ace0b4f4c65439de72 | 11,679 | cxx | C++ | src/Cxx/Visualization/Kitchen.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 81 | 2020-08-10T01:44:30.000Z | 2022-03-23T06:46:36.000Z | src/Cxx/Visualization/Kitchen.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 2 | 2020-09-12T17:33:52.000Z | 2021-04-15T17:33:09.000Z | src/Cxx/Visualization/Kitchen.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 27 | 2020-08-17T07:09:30.000Z | 2022-02-15T03:44:58.000Z | #include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkLineSource.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkStreamTracer.h>
#include <vtkStructuredGrid.h>
#include <vtkStructuredGridGeometryFilter.h>
#include <vtkStructuredGridOutlineFilter.h>
#include <vtkStructuredGridReader.h>
#include <array>
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " kitchen.vtk" << std::endl;
return EXIT_FAILURE;
}
double range[2];
vtkNew<vtkNamedColors> colors;
// Set the furniture colors.
std::array<unsigned char, 4> furnColor{{204, 204, 153, 255}};
colors->SetColor("Furniture", furnColor.data());
vtkNew<vtkRenderer> aren;
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer(aren);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin);
//
// Read data
//
vtkNew<vtkStructuredGridReader> reader;
reader->SetFileName(argv[1]);
reader->Update(); // force a read to occur
reader->GetOutput()->GetLength();
double maxTime = 0.0;
if (reader->GetOutput()->GetPointData()->GetScalars())
{
reader->GetOutput()->GetPointData()->GetScalars()->GetRange(range);
}
if (reader->GetOutput()->GetPointData()->GetVectors())
{
auto maxVelocity =
reader->GetOutput()->GetPointData()->GetVectors()->GetMaxNorm();
maxTime = 4.0 * reader->GetOutput()->GetLength() / maxVelocity;
}
//
// Outline around data
//
vtkNew<vtkStructuredGridOutlineFilter> outlineF;
outlineF->SetInputConnection(reader->GetOutputPort());
vtkNew<vtkPolyDataMapper> outlineMapper;
outlineMapper->SetInputConnection(outlineF->GetOutputPort());
vtkNew<vtkActor> outline;
outline->SetMapper(outlineMapper);
outline->GetProperty()->SetColor(colors->GetColor3d("LampBlack").GetData());
//
// Set up shaded surfaces (i.e., supporting geometry)
//
vtkNew<vtkStructuredGridGeometryFilter> doorGeom;
doorGeom->SetInputConnection(reader->GetOutputPort());
doorGeom->SetExtent(27, 27, 14, 18, 0, 11);
vtkNew<vtkPolyDataMapper> mapDoor;
mapDoor->SetInputConnection(doorGeom->GetOutputPort());
mapDoor->ScalarVisibilityOff();
vtkNew<vtkActor> door;
door->SetMapper(mapDoor);
door->GetProperty()->SetColor(colors->GetColor3d("Burlywood").GetData());
vtkNew<vtkStructuredGridGeometryFilter> window1Geom;
window1Geom->SetInputConnection(reader->GetOutputPort());
window1Geom->SetExtent(0, 0, 9, 18, 6, 12);
vtkNew<vtkPolyDataMapper> mapWindow1;
mapWindow1->SetInputConnection(window1Geom->GetOutputPort());
mapWindow1->ScalarVisibilityOff();
vtkNew<vtkActor> window1;
window1->SetMapper(mapWindow1);
window1->GetProperty()->SetColor(colors->GetColor3d("SkyBlue").GetData());
window1->GetProperty()->SetOpacity(.6);
vtkNew<vtkStructuredGridGeometryFilter> window2Geom;
window2Geom->SetInputConnection(reader->GetOutputPort());
window2Geom->SetExtent(5, 12, 23, 23, 6, 12);
vtkNew<vtkPolyDataMapper> mapWindow2;
mapWindow2->SetInputConnection(window2Geom->GetOutputPort());
mapWindow2->ScalarVisibilityOff();
vtkNew<vtkActor> window2;
window2->SetMapper(mapWindow2);
window2->GetProperty()->SetColor(colors->GetColor3d("SkyBlue").GetData());
window2->GetProperty()->SetOpacity(.6);
vtkNew<vtkStructuredGridGeometryFilter> klower1Geom;
klower1Geom->SetInputConnection(reader->GetOutputPort());
klower1Geom->SetExtent(17, 17, 0, 11, 0, 6);
vtkNew<vtkPolyDataMapper> mapKlower1;
mapKlower1->SetInputConnection(klower1Geom->GetOutputPort());
mapKlower1->ScalarVisibilityOff();
vtkNew<vtkActor> klower1;
klower1->SetMapper(mapKlower1);
klower1->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData());
vtkNew<vtkStructuredGridGeometryFilter> klower2Geom;
klower2Geom->SetInputConnection(reader->GetOutputPort());
klower2Geom->SetExtent(19, 19, 0, 11, 0, 6);
vtkNew<vtkPolyDataMapper> mapKlower2;
mapKlower2->SetInputConnection(klower2Geom->GetOutputPort());
mapKlower2->ScalarVisibilityOff();
vtkNew<vtkActor> klower2;
klower2->SetMapper(mapKlower2);
klower2->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData());
vtkNew<vtkStructuredGridGeometryFilter> klower3Geom;
klower3Geom->SetInputConnection(reader->GetOutputPort());
klower3Geom->SetExtent(17, 19, 0, 0, 0, 6);
vtkNew<vtkPolyDataMapper> mapKlower3;
mapKlower3->SetInputConnection(klower3Geom->GetOutputPort());
mapKlower3->ScalarVisibilityOff();
vtkNew<vtkActor> klower3;
klower3->SetMapper(mapKlower3);
klower3->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData());
vtkNew<vtkStructuredGridGeometryFilter> klower4Geom;
klower4Geom->SetInputConnection(reader->GetOutputPort());
klower4Geom->SetExtent(17, 19, 11, 11, 0, 6);
vtkNew<vtkPolyDataMapper> mapKlower4;
mapKlower4->SetInputConnection(klower4Geom->GetOutputPort());
mapKlower4->ScalarVisibilityOff();
vtkNew<vtkActor> klower4;
klower4->SetMapper(mapKlower4);
klower4->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData());
vtkNew<vtkStructuredGridGeometryFilter> klower5Geom;
klower5Geom->SetInputConnection(reader->GetOutputPort());
klower5Geom->SetExtent(17, 19, 0, 11, 0, 0);
vtkNew<vtkPolyDataMapper> mapKlower5;
mapKlower5->SetInputConnection(klower5Geom->GetOutputPort());
mapKlower5->ScalarVisibilityOff();
vtkNew<vtkActor> klower5;
klower5->SetMapper(mapKlower5);
klower5->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData());
vtkNew<vtkStructuredGridGeometryFilter> klower6Geom;
klower6Geom->SetInputConnection(reader->GetOutputPort());
klower6Geom->SetExtent(17, 19, 0, 7, 6, 6);
vtkNew<vtkPolyDataMapper> mapKlower6;
mapKlower6->SetInputConnection(klower6Geom->GetOutputPort());
mapKlower6->ScalarVisibilityOff();
vtkNew<vtkActor> klower6;
klower6->SetMapper(mapKlower6);
klower6->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData());
vtkNew<vtkStructuredGridGeometryFilter> klower7Geom;
klower7Geom->SetInputConnection(reader->GetOutputPort());
klower7Geom->SetExtent(17, 19, 9, 11, 6, 6);
vtkNew<vtkPolyDataMapper> mapKlower7;
mapKlower7->SetInputConnection(klower7Geom->GetOutputPort());
mapKlower7->ScalarVisibilityOff();
vtkNew<vtkActor> klower7;
klower7->SetMapper(mapKlower7);
klower7->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData());
vtkNew<vtkStructuredGridGeometryFilter> hood1Geom;
hood1Geom->SetInputConnection(reader->GetOutputPort());
hood1Geom->SetExtent(17, 17, 0, 11, 11, 16);
vtkNew<vtkPolyDataMapper> mapHood1;
mapHood1->SetInputConnection(hood1Geom->GetOutputPort());
mapHood1->ScalarVisibilityOff();
vtkNew<vtkActor> hood1;
hood1->SetMapper(mapHood1);
hood1->GetProperty()->SetColor(colors->GetColor3d("Silver").GetData());
vtkNew<vtkStructuredGridGeometryFilter> hood2Geom;
hood2Geom->SetInputConnection(reader->GetOutputPort());
hood2Geom->SetExtent(19, 19, 0, 11, 11, 16);
vtkNew<vtkPolyDataMapper> mapHood2;
mapHood2->SetInputConnection(hood2Geom->GetOutputPort());
mapHood2->ScalarVisibilityOff();
vtkNew<vtkActor> hood2;
hood2->SetMapper(mapHood2);
hood2->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData());
vtkNew<vtkStructuredGridGeometryFilter> hood3Geom;
hood3Geom->SetInputConnection(reader->GetOutputPort());
hood3Geom->SetExtent(17, 19, 0, 0, 11, 16);
vtkNew<vtkPolyDataMapper> mapHood3;
mapHood3->SetInputConnection(hood3Geom->GetOutputPort());
mapHood3->ScalarVisibilityOff();
vtkNew<vtkActor> hood3;
hood3->SetMapper(mapHood3);
hood3->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData());
vtkNew<vtkStructuredGridGeometryFilter> hood4Geom;
hood4Geom->SetInputConnection(reader->GetOutputPort());
hood4Geom->SetExtent(17, 19, 11, 11, 11, 16);
vtkNew<vtkPolyDataMapper> mapHood4;
mapHood4->SetInputConnection(hood4Geom->GetOutputPort());
mapHood4->ScalarVisibilityOff();
vtkNew<vtkActor> hood4;
hood4->SetMapper(mapHood4);
hood4->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData());
vtkNew<vtkStructuredGridGeometryFilter> hood6Geom;
hood6Geom->SetInputConnection(reader->GetOutputPort());
hood6Geom->SetExtent(17, 19, 0, 11, 16, 16);
vtkNew<vtkPolyDataMapper> mapHood6;
mapHood6->SetInputConnection(hood6Geom->GetOutputPort());
mapHood6->ScalarVisibilityOff();
vtkNew<vtkActor> hood6;
hood6->SetMapper(mapHood6);
hood6->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData());
vtkNew<vtkStructuredGridGeometryFilter> cookingPlateGeom;
cookingPlateGeom->SetInputConnection(reader->GetOutputPort());
cookingPlateGeom->SetExtent(17, 19, 7, 9, 6, 6);
vtkNew<vtkPolyDataMapper> mapCookingPlate;
mapCookingPlate->SetInputConnection(cookingPlateGeom->GetOutputPort());
mapCookingPlate->ScalarVisibilityOff();
vtkNew<vtkActor> cookingPlate;
cookingPlate->SetMapper(mapCookingPlate);
cookingPlate->GetProperty()->SetColor(colors->GetColor3d("Tomato").GetData());
vtkNew<vtkStructuredGridGeometryFilter> filterGeom;
filterGeom->SetInputConnection(reader->GetOutputPort());
filterGeom->SetExtent(17, 19, 7, 9, 11, 11);
vtkNew<vtkPolyDataMapper> mapFilter;
mapFilter->SetInputConnection(filterGeom->GetOutputPort());
mapFilter->ScalarVisibilityOff();
vtkNew<vtkActor> filter;
filter->SetMapper(mapFilter);
filter->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData());
//
// regular streamlines
//
vtkNew<vtkLineSource> line;
line->SetResolution(39);
line->SetPoint1(0.08, 2.50, 0.71);
line->SetPoint2(0.08, 4.50, 0.71);
vtkNew<vtkPolyDataMapper> rakeMapper;
rakeMapper->SetInputConnection(line->GetOutputPort());
vtkNew<vtkActor> rake;
rake->SetMapper(rakeMapper);
vtkNew<vtkStreamTracer> streamers;
// streamers->DebugOn();
streamers->SetInputConnection(reader->GetOutputPort());
streamers->SetSourceConnection(line->GetOutputPort());
streamers->SetMaximumPropagation(maxTime);
streamers->SetInitialIntegrationStep(.5);
streamers->SetMinimumIntegrationStep(.1);
streamers->SetIntegratorType(2);
streamers->Update();
vtkNew<vtkPolyDataMapper> streamersMapper;
streamersMapper->SetInputConnection(streamers->GetOutputPort());
streamersMapper->SetScalarRange(range);
vtkNew<vtkActor> lines;
lines->SetMapper(streamersMapper);
lines->GetProperty()->SetColor(colors->GetColor3d("Black").GetData());
aren->TwoSidedLightingOn();
aren->AddActor(outline);
aren->AddActor(door);
aren->AddActor(window1);
aren->AddActor(window2);
aren->AddActor(klower1);
aren->AddActor(klower2);
aren->AddActor(klower3);
aren->AddActor(klower4);
aren->AddActor(klower5);
aren->AddActor(klower6);
aren->AddActor(klower7);
aren->AddActor(hood1);
aren->AddActor(hood2);
aren->AddActor(hood3);
aren->AddActor(hood4);
aren->AddActor(hood6);
aren->AddActor(cookingPlate);
aren->AddActor(filter);
aren->AddActor(lines);
aren->AddActor(rake);
aren->SetBackground(colors->GetColor3d("SlateGray").GetData());
vtkNew<vtkCamera> aCamera;
aren->SetActiveCamera(aCamera);
aren->ResetCamera();
aCamera->SetFocalPoint(3.505, 2.505, 1.255);
aCamera->SetPosition(3.505, 24.6196, 1.255);
aCamera->SetViewUp(0, 0, 1);
aCamera->Azimuth(60);
aCamera->Elevation(30);
aCamera->Dolly(1.4);
aren->ResetCameraClippingRange();
renWin->SetSize(640, 512);
renWin->Render();
renWin->SetWindowName("Kitchen");
// interact with data
iren->Start();
return EXIT_SUCCESS;
}
| 36.496875 | 80 | 0.749037 | ajpmaclean |
61d63eecc6be6ba1e2c3ed135b698baa02d990bf | 347 | cpp | C++ | src/OpenCLInvertexIndex.cpp | Gabriele91/Word-indexing-in-web-page.reduce | 792874f5c306c90354ab23a686cfcb0d1298e159 | [
"MIT"
] | null | null | null | src/OpenCLInvertexIndex.cpp | Gabriele91/Word-indexing-in-web-page.reduce | 792874f5c306c90354ab23a686cfcb0d1298e159 | [
"MIT"
] | null | null | null | src/OpenCLInvertexIndex.cpp | Gabriele91/Word-indexing-in-web-page.reduce | 792874f5c306c90354ab23a686cfcb0d1298e159 | [
"MIT"
] | null | null | null | #include <OpenCLInvertexIndex.h>
/**
* WordMapInvertedIndex::InvertedIndexMap
*/
const char* WordMapInvertedIndex::InvertedIndexMap::at(cl_uint i) const
{
return (const char*)data() + word_capacity()*i;
}
const char* WordMapInvertedIndex::InvertedIndexMap::operator[](cl_uint i) const
{
return (const char*)data() + word_capacity()*i;
} | 26.692308 | 79 | 0.73487 | Gabriele91 |
61d7917ccdb0209ed5dad36a7111e39482e93646 | 903 | hpp | C++ | include/PlayerCardCreator.hpp | eduardoweiland/placarduino | b536d8f40855a052e8ff140d79edd8e2a2c76a75 | [
"Unlicense"
] | 3 | 2018-01-13T13:18:42.000Z | 2022-02-24T01:30:55.000Z | include/PlayerCardCreator.hpp | eduardoweiland/placarduino | b536d8f40855a052e8ff140d79edd8e2a2c76a75 | [
"Unlicense"
] | null | null | null | include/PlayerCardCreator.hpp | eduardoweiland/placarduino | b536d8f40855a052e8ff140d79edd8e2a2c76a75 | [
"Unlicense"
] | null | null | null | #pragma once
#include "App.hpp"
#include "RisingEdgeButton.h"
#include "SmartCard.h"
#include <LiquidCrystal_I2C.h>
#include <stdint.h>
#include <WString.h>
class PlayerCardCreator : public App
{
public:
PlayerCardCreator();
void init();
void run();
private:
LiquidCrystal_I2C lcd;
RisingEdgeButton charUpButton;
RisingEdgeButton charDownButton;
RisingEdgeButton walkLeftButton;
RisingEdgeButton walkRightButton;
RisingEdgeButton writeButton;
uint8_t rfidKey[MFRC522::MF_KEY_SIZE];
SmartCard smartCard;
String playerName;
uint8_t charIndexUnderCursor;
char *statusLine;
void setupLCD();
void showControlHints();
void showName();
bool executeNameChanges();
void resetName();
bool writeNameToCard();
void clearLine(const int number);
char nextChar(const char current);
char prevChar(const char current);
};
| 21.5 | 42 | 0.717608 | eduardoweiland |
61dfe6113b40ebe81dcd9be9532a0a5149d7ac15 | 745 | tpp | C++ | cml/vector/subvector_ops.tpp | egorodet/CML | e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f | [
"BSL-1.0"
] | 125 | 2015-07-22T11:39:51.000Z | 2022-03-06T13:41:44.000Z | cml/vector/subvector_ops.tpp | egorodet/CML | e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f | [
"BSL-1.0"
] | 45 | 2015-06-03T15:50:08.000Z | 2021-05-26T01:35:01.000Z | cml/vector/subvector_ops.tpp | egorodet/CML | e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f | [
"BSL-1.0"
] | 28 | 2015-06-03T09:26:26.000Z | 2022-03-06T13:42:06.000Z | /* -*- C++ -*- ------------------------------------------------------------
@@COPYRIGHT@@
*-----------------------------------------------------------------------*/
/** @file
*/
#ifndef __CML_VECTOR_SUBVECTOR_OPS_TPP
#error "vector/subvector_ops.tpp not included correctly"
#endif
namespace cml {
template<class Sub> inline auto
subvector(const readable_vector<Sub>& sub, int i)
-> subvector_node<const Sub&>
{
return subvector_node<const Sub&>(sub.actual(), i);
}
template<class Sub> inline auto
subvector(readable_vector<Sub>&& sub, int i)
-> subvector_node<Sub&&>
{
return subvector_node<Sub&&>((Sub&&) sub, i);
}
} // namespace cml
// -------------------------------------------------------------------------
// vim:ft=cpp:sw=2
| 24.032258 | 76 | 0.495302 | egorodet |
61e1c1b3b736b3c6fce106e044aeabd67a4139f0 | 4,112 | cpp | C++ | src/geometry/mesh.cpp | masonium/twinkle | 853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6 | [
"MIT"
] | 2 | 2016-09-20T06:01:03.000Z | 2020-12-03T23:22:19.000Z | src/geometry/mesh.cpp | masonium/twinkle | 853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6 | [
"MIT"
] | null | null | null | src/geometry/mesh.cpp | masonium/twinkle | 853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iterator>
#include <iostream>
#include "mesh.h"
#include "geometry/isect_util.h"
using std::copy;
using std::ostream_iterator;
using std::cerr;
MeshTri::MeshTri(const Mesh* m, int f, const uint v[3]) :
mesh(m), ti(f)
{
copy(v, v+3, vi);
}
scalar_fp ray_triangle_intersection_accel(const Ray& ray, scalar_fp max_t, const MeshTriAccel& accel)
{
auto u = (accel.k + 1) % 3, v = (accel.k + 2) % 3;
auto denom = (ray.direction[u] * accel.nu + ray.direction[v] * accel.nv + ray.direction[accel.k]);
if (fabs(denom) < 0.0001)
return sfp_none;
auto num = accel.nd - ray.position[u] * accel.nu - ray.position[v] * accel.nv - ray.position[accel.k];
scalar t = num / denom;
if (t < EPSILON)
return sfp_none;
scalar_fp t_prop(t);
if (max_t < t_prop)
return sfp_none;
scalar hu = ray.position[u] + ray.direction[u] * t;
scalar hv = ray.position[v] + ray.direction[v] * t;
scalar beta = hu * accel.b_nu + hv * accel.b_nv + accel.b_d;
if (beta < 0)
return sfp_none;
scalar gamma = hu * accel.c_nu + hv * accel.c_nv + accel.c_d;
if (gamma < 0)
return sfp_none;
scalar alpha = 1 - beta - gamma;
if (alpha < 0 || alpha > 1)
return sfp_none;
return t_prop;
}
scalar_fp MeshTri::intersect(const Ray& ray, scalar_fp max_t, SubGeo& geo) const
{
return ray_triangle_intersection_accel(ray, max_t, mesh->accel(ti));
}
Vec3 MeshTri::normal(const Vec3& point) const
{
return (_p(1) - _p(0)).cross(_p(2) - _p(0)).normal();
}
bounds::AABB MeshTri::get_bounding_box() const
{
return bounds::AABB(min(min(_p(0), _p(1)), _p(2)),
max(max(_p(0), _p(1)), _p(2)));
}
void MeshTri::texture_coord(const Vec3& pos, const Vec3& normal,
scalar& uv_u, scalar& uv_v) const
{
const auto& accel = mesh->accel(ti);
auto u = (accel.k + 1) % 3, v = (accel.k + 2) % 3;
scalar hu = pos[u];
scalar hv = pos[v];
scalar beta = hu * accel.b_nu + hv * accel.b_nv + accel.b_d;
scalar gamma = hu * accel.c_nu + hv * accel.c_nv + accel.c_d;
scalar alpha = 1 - beta - gamma;
auto uv = mesh->uv(vi[0]) * alpha + mesh->uv(vi[1]) * gamma + mesh->uv(vi[2]) * beta;
uv_u = uv[0];
uv_v = uv[1];
}
////////////////////////////////////////////////////////////////////////////////
bounds::AABB Mesh::get_bounding_box() const
{
auto bb = bounds::AABB{Vec3::zero, Vec3::zero};
return accumulate(tris.begin(), tris.end(), bb,
[](const auto& bb, const auto& tri)
{
return bounds::AABB::box_union(bb, tri.get_bounding_box());
});
}
scalar_fp Mesh::intersect(const Ray& r, scalar_fp max_t, SubGeo& subgeo) const
{
scalar_fp best_t = max_t;
for (auto i = 0u; i < tris.size(); ++i)
{
auto& tri = tris[i];
auto t = tri.intersect(r, best_t, subgeo);
if (t < best_t)
{
best_t = t;
subgeo = i;
}
}
return best_t;
}
Vec3 Mesh::normal(SubGeo subgeo, const Vec3& point) const
{
return tris[subgeo].normal(point);
}
void Mesh::texture_coord(SubGeo subgeo, const Vec3& pos, const Vec3& normal,
scalar& u, scalar& v) const
{
return tris[subgeo].texture_coord(pos, normal, u, v);
}
////////////////////////////////////////////////////////////////////////////////
MeshTriAccel::MeshTriAccel(const Vec3& p0, const Vec3& p1, const Vec3& p2)
{
const auto b = p1 - p0;
const auto c = p2 - p0;
const auto N = b.cross(c);
const auto aN = N.abs();
if (aN.x >= aN.y && aN.x >= aN.z)
this->k = 0;
else if (aN.y >= aN.x && aN.y >= aN.z)
this->k = 1;
else
this->k = 2;
int k = this->k;
int u = (this->k + 1) % 3, v = (this->k + 2) % 3;
this->nu = N[u] / N[k];
this->nv = N[v] / N[k];
this->nd = p0.dot(N) / N[k];
scalar inv_area = 1.0 / (b[u] * c[v] - b[v] * c[u]);
this->b_nu = -b[v] * inv_area;
this->b_nv = b[u] * inv_area;
this->b_d = (b[v] * p0[u] - b[u] * p0[v]) * inv_area;
this->c_nu = c[v] * inv_area;
this->c_nv = -c[u] * inv_area;
this->c_d = (c[u] * p0[v] - c[v] * p0[u]) * inv_area;
}
| 26.191083 | 104 | 0.558366 | masonium |
61e2f177664fac27a161d426320bc381ce4ac98b | 3,646 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/eglfs/deviceintegration/eglfs_viv_wl/qeglfsvivwlintegration.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qeglfsvivwlintegration.h"
#include <EGL/eglvivante.h>
#include <QDebug>
#include <wayland-server.h>
QT_BEGIN_NAMESPACE
void QEglFSVivWaylandIntegration::platformInit()
{
QEglFSDeviceIntegration::platformInit();
int width, height;
bool multiBufferNotEnabledYet = qEnvironmentVariableIsEmpty("FB_MULTI_BUFFER");
bool multiBuffer = qEnvironmentVariableIsEmpty("QT_EGLFS_IMX6_NO_FB_MULTI_BUFFER");
if (multiBufferNotEnabledYet && multiBuffer) {
qWarning() << "QEglFSVivWaylandIntegration will set environment variable FB_MULTI_BUFFER=2 to enable double buffering and vsync.\n"
<< "If this is not desired, you can override this via: export QT_EGLFS_IMX6_NO_FB_MULTI_BUFFER=1";
qputenv("FB_MULTI_BUFFER", "2");
}
mWaylandDisplay = wl_display_create();
mNativeDisplay = fbGetDisplay(mWaylandDisplay);
fbGetDisplayGeometry(mNativeDisplay, &width, &height);
mScreenSize.setHeight(height);
mScreenSize.setWidth(width);
}
QSize QEglFSVivWaylandIntegration::screenSize() const
{
return mScreenSize;
}
EGLNativeDisplayType QEglFSVivWaylandIntegration::platformDisplay() const
{
return mNativeDisplay;
}
EGLNativeWindowType QEglFSVivWaylandIntegration::createNativeWindow(QPlatformWindow *window, const QSize &size, const QSurfaceFormat &format)
{
Q_UNUSED(window)
Q_UNUSED(format)
EGLNativeWindowType eglWindow = fbCreateWindow(mNativeDisplay, 0, 0, size.width(), size.height());
return eglWindow;
}
void QEglFSVivWaylandIntegration::destroyNativeWindow(EGLNativeWindowType window)
{
fbDestroyWindow(window);
}
void *QEglFSVivWaylandIntegration::wlDisplay() const
{
return mWaylandDisplay;
}
QT_END_NAMESPACE
| 36.46 | 141 | 0.730664 | GrinCash |
61e4b83cba47ce5809ebef70d0ee6f8febe7a39d | 4,989 | cc | C++ | source/param_array.cc | nsoblath/param | 250c45ce7dc2d8fe6cb6fa1820d231ebb6674a18 | [
"Apache-2.0"
] | null | null | null | source/param_array.cc | nsoblath/param | 250c45ce7dc2d8fe6cb6fa1820d231ebb6674a18 | [
"Apache-2.0"
] | null | null | null | source/param_array.cc | nsoblath/param | 250c45ce7dc2d8fe6cb6fa1820d231ebb6674a18 | [
"Apache-2.0"
] | null | null | null | /*
* param_array.cc
*
* Created on: Jan 14, 2014
* Author: nsoblath
*/
#define PARAM_API_EXPORTS
#include <sstream>
using std::string;
using std::stringstream;
#include "param_array.hh"
#include "param_base_impl.hh"
#include "param_node.hh"
namespace param
{
param_array::param_array() :
param(),
f_contents()
{
}
param_array::param_array( const param_array& orig ) :
param( orig ),
f_contents( orig.f_contents.size() )
{
for( unsigned ind = 0; ind < f_contents.size(); ++ind )
{
f_contents[ind] = orig.f_contents[ ind ]->clone();
}
}
param_array::param_array( param_array&& orig ) :
param( std::move(orig) ),
f_contents( orig.f_contents.size() )
{
for( unsigned ind = 0; ind < f_contents.size(); ++ind )
{
f_contents[ind] = orig.f_contents[ ind ]->move_clone();
}
orig.clear();
}
param_array::~param_array()
{
}
param_array& param_array::operator=( const param_array& rhs )
{
this->param::operator=( rhs );
clear();
resize( rhs.size()) ;
for( unsigned ind = 0; ind < rhs.f_contents.size(); ++ind )
{
f_contents[ind] = rhs.f_contents[ ind ]->clone();
}
return *this;
}
param_array& param_array::operator=( param_array&& rhs )
{
this->param::operator=( std::move(rhs) );
clear();
resize( rhs.size()) ;
for( unsigned ind = 0; ind < rhs.f_contents.size(); ++ind )
{
f_contents[ind] = rhs.f_contents[ ind ]->move_clone();
}
rhs.clear();
return *this;
}
void param_array::resize( unsigned a_size )
{
f_contents.resize( a_size );
for( auto it = f_contents.begin(); it != f_contents.end(); ++it )
{
if( ! *it ) it->reset( new param() );
}
return;
}
bool param_array::has_subset( const param& a_subset ) const
{
if( ! a_subset.is_array() ) return false;
const param_array& t_subset_array = a_subset.as_array();
if( t_subset_array.size() > f_contents.size() ) return false;
contents::const_iterator t_this_it = f_contents.begin();
contents::const_iterator t_that_it = t_subset_array.f_contents.begin();
while( t_that_it != t_subset_array.f_contents.end() ) // loop condition is on a_subset because it's smaller or equal to this
{
if( ! (*t_this_it)->has_subset( **t_that_it ) ) return false;
++t_this_it;
++t_that_it;
}
return true;
}
void param_array::merge( const param_array& a_object )
{
//LDEBUG( dlog, "merging array with " << a_object.size() << " items:\n" << a_object );
if( size() < a_object.size() ) resize( a_object.size() );
for( unsigned index = 0; index < size(); ++index )
{
if( f_contents.at( index )->is_null() )
{
//LDEBUG( dlog, "have a null object at <" << index << ">; adding <" << a_object[index] << ">" );
assign( index, a_object[index] );
continue;
}
param& t_param = (*this)[index];
if( t_param.is_value() && a_object[index].is_value() )
{
//LDEBUG( dlog, "replacing the value at <" << index << "> with <" << a_object[index] << ">" );
t_param.as_value() = a_object[index].as_value();
continue;
}
if( t_param.is_node() && a_object[index].is_node() )
{
//LDEBUG( dlog, "merging nodes at <" << index << ">" )
t_param.as_node().merge( a_object[index].as_node() );
continue;
}
if( t_param.is_array() && a_object[index].is_array() )
{
//LDEBUG( dlog, "merging array at <" << index << ">" );
t_param.as_array().merge( a_object[index].as_array() );
continue;
}
//LDEBUG( dlog, "generic replace" );
assign( index, a_object[index] );
}
return;
}
std::string param_array::to_string() const
{
stringstream out;
string indentation;
for ( unsigned i=0; i<param::s_indent_level; ++i )
indentation += " ";
out << '\n' << indentation << "[\n";
param::s_indent_level++;
for( contents::const_iterator it = f_contents.begin(); it != f_contents.end(); ++it )
{
out << indentation << " " << **it << '\n';
}
param::s_indent_level--;
out << indentation << "]\n";
return out.str();
}
PARAM_API std::ostream& operator<<(std::ostream& out, const param_array& a_value)
{
return out << a_value.to_string();
}
} /* namespace param */
| 29.347059 | 132 | 0.512928 | nsoblath |
61e7823fd086418ee4a9902a56b2d99a1e676e02 | 17,317 | cpp | C++ | apps/phan_app/src/main.cpp | phiwen96/Phan | 61bd47d57dc6d0e7a92c6e9db676f5d76ed8edb4 | [
"Apache-2.0"
] | 3 | 2021-03-15T12:57:32.000Z | 2021-03-15T15:34:07.000Z | apps/phan_app/src/main.cpp | phiwen96/Phan | 61bd47d57dc6d0e7a92c6e9db676f5d76ed8edb4 | [
"Apache-2.0"
] | null | null | null | apps/phan_app/src/main.cpp | phiwen96/Phan | 61bd47d57dc6d0e7a92c6e9db676f5d76ed8edb4 | [
"Apache-2.0"
] | 1 | 2021-03-15T13:36:21.000Z | 2021-03-15T13:36:21.000Z | #include "main.hpp"
//$(sej$(aaa){AAA}$(bajs$(moa){kmkd}){tej$(haha){kmkm}}){kukens fitta}
//$(bajskmkd){tej$(haha){kmkd}}
//template <bool DO_LOUD = true>
struct Process
{
vector <pair <string, string>> declaredVariables;
Context declVar;
// Context pasteVar;
// comment::Context commentVal;
// string str;
Process () : declVar {nullptr, declaredVariables, new STATE ("begin")}
{
// declVar.state -> context = &declVar;
// pasteVar.state -> context = &pasteVar;
// commentVal.state -> context = &commentVal;
}
string process (string str)
{
// cout << endl << "input: " << endl << str << endl;
for (auto i = str.begin(); i < str.end(); ++i)
{
declVar.process (i);
}
str = declVar.result;
if(STATE ("done")* d = dynamic_cast<STATE ("done")*>(declVar.state))
{
} else {
str += declVar.potential;
}
// cout << endl << "declare: " << endl << str << endl;
// cout << endl << "variables: " << endl;
// for (auto& i : declaredVariables)
// {
// cout << i.first << " = " << i.second << endl;
// }
declVar.result.clear ();
return str;
}
};
void fileApp (Process& p, filesystem::path const& inputPath, filesystem::path const& outputPath) {
string input = readFileIntoString (inputPath);
ofstream outputFile (outputPath);
if (!outputFile.is_open ())
throw runtime_error ("could not open file " + outputPath.string());
outputFile << p.process (input);
outputFile.close ();
}
void folderApp (Process& p, filesystem::path inputPath)
{
filesystem::rename (inputPath, filesystem::path{inputPath}.replace_filename (p.process (inputPath.filename ())));
inputPath = filesystem::path{inputPath}.replace_filename (p.process (inputPath.filename ()));
set <filesystem::path> all;
set <filesystem::path> subdirs;
set <filesystem::path> subfiles;
for (auto& i : filesystem::directory_iterator (inputPath))
{
auto renamed = filesystem::path {i.path().parent_path()} /= p.process (i.path().filename());
all.insert (renamed);
filesystem::rename (i.path(), renamed);
if (filesystem::is_directory (renamed))
{
subdirs.insert (renamed);
} else if (filesystem::is_regular_file (renamed))
{
if (renamed.extension() == ".ph")
{
p.process (readFileIntoString (renamed));
filesystem::remove (renamed);
} else
{
subfiles.insert (renamed);
}
}
}
for (auto const& filename : subfiles)
{
fileApp (p, filename, filename);
}
for (auto const& dirname : subdirs)
{
folderApp (p, dirname);
}
}
//template <bool DO_LOUD = true>
void app (filesystem::path const& inputPath, filesystem::path outputPath) {
// filesystem::path p {inputPath};
// cout << filesystem::exists(inputPath) << endl;
// cout << filesystem::is_directory (p) << endl;
// cout << p.extension() << endl;
// cout << p.stem() << endl;
// cout << p.filename() << endl;
if (not filesystem::exists (inputPath)) {
// string warn = "file " + inputPath + "does not exists";
throw runtime_error ("file " + inputPath.string() + "does not exists");
}
if (filesystem::exists (outputPath)) {
// throw runtime_error ("file already exists");
}
Process p;
// outputPath.replace_filename (p.process (inputPath.filename ()));
// outputPath += p.process (inputPath.stem());
if (filesystem::is_directory (inputPath))
{
// cout << outputPath << endl;
outputPath/=inputPath.filename ();
outputPath = filesystem::path{outputPath}.replace_filename (p.process (outputPath.filename ()));
// cout << outputPath << endl;
// return;
filesystem::copy (inputPath, outputPath, std::filesystem::copy_options::recursive);
folderApp (p, outputPath);
} else if (filesystem::is_regular_file (inputPath))
{
fileApp (p, inputPath, outputPath);
} else
{
throw runtime_error ("");
}
}
string warning = "";
void assert_folder(string const& inputPath, string const& outputPath, string& warning) {
// cout << inputPath << endl;
app (inputPath, outputPath);
}
template <bool DO_LOUD = true>
void assert_file(string const& inputPath, string const& outputPath, string const& facitPath, string& warning) {
app (inputPath, outputPath);
string result = readFileIntoString (outputPath);
string facit = readFileIntoString (facitPath);
if constexpr (not DO_LOUD) {
if (result != facit)
{
string warn = "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n";
throw runtime_error (warn);
}
} else {
if (result != facit)
{
warning += "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n";
}
}
}
#define LOUD(x) x
#define ASSERT_FILE(file, DO_LOUD) assert_file <DO_LOUD> (string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (file)), warning);
#define ASSERT_FOLDER(folder, DO_LOUD) assert_folder (string (TEST_FOLDERS_PRE_PATH) + string (BOOST_PP_STRINGIZE (folder)), string (TEST_FOLDERS_POST_PATH), warning);
#define ASSERT_FILE_SEQ(r, data, file) assert_file (string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (file)), string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (file)), warning);
#define ASSERT_FILES_2(seqFiles) BOOST_PP_SEQ_FOR_EACH(ASSERT_FILE_SEQ, -, seqFiles);
#define ASSERT_FILES(...) ASSERT_FILES_2 (BOOST_PP_TUPLE_TO_SEQ (__VA_ARGS__));
#define PSTR(x) decltype (const_str {x})
template <class T0, class T1>
concept same = std::is_same_v<T0, T1>;
//byte
namespace input{
struct Context;
struct State
{
virtual void process (char const* str, Context& ctx) {}
};
struct Context
{
State* state {nullptr};
string input;
vector <string> outputs;
void process (char const* str);
};
struct Begin : State
{
virtual void process (char const* str, Context& ctx);
};
struct Input : State
{
virtual void process (char const* str, Context& ctx)
{
// cout << "Input::process" << endl;
ctx.input = str;
ctx.state = new Begin;
// delete this;
}
};
struct Output : State
{
virtual void process (char const* str, Context& ctx)
{
// cout << "Output::process" << endl;
if (strcmp (str, "--input") == 0)
{
ctx.state = new Input;
// delete this;
} else
{
ctx.outputs.push_back (string {str});
}
}
};
void Context::process (char const* str)
{
// cout << "Context::process" << endl;
state -> process (str, *this);
}
void Begin::process (char const* str, Context& ctx)
{
// cout << "Begin::process" << endl;
if (strcmp (str, "--input") == 0)
{
cout << "--input" << endl;
ctx.state = new Input;
// ctx.state = static_cast <Input*> (ctx.state);
// delete this;
} else if (strcmp (str, "--output") == 0)
{
ctx.state = new Output;
} else
{
throw runtime_error ("");
}
}
}
#if defined (Debug)
auto main (int, char**) -> int
{
int argc = 5;
char** argv = new char*[argc]{new char[]{}, new char[]{"--input"}, new char[]{"/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_pre/1.hpp"}, new char[]{"--output"}, new char[]{"/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_post/1.hpp"}};
input::Context ctx {new input::Begin};
#elif defined (Release)
auto main (int argc, char** argv) -> int
{
#endif
for (char** it = argv + 1; it < argv + argc; ++it)
{
ctx.process (*it);
}
if (ctx.input.empty ())
{
throw runtime_error ("must provide an input file");
} else if (ctx.outputs.empty ())
{
throw runtime_error ("must provide one or more output file");
}
app (ctx.input, ctx.outputs.front ());
return 0;
// int argc = 2;
// auto** argv = new char*[argc]{new char*{"bajs"}, new char*{"--input"}, new char*{"då"}, new char*{"--output"}, new char*{"ssss"}};
#if defined (Release)
#endif
// string ss;
// getline(cin, ss);
#if defined (Debug)
cout << "kuk" << endl;
removeFolderContent (TEST_FOLDERS_POST_PATH);
ASSERT_FILE (4.hpp, LOUD (1))
ASSERT_FOLDER (&(root){philips bibliotek}, LOUD(1))
return 0;
ASSERT_FOLDER ($(root){philip}, LOUD(1))
ASSERT_FILE (1.hpp, LOUD (0))
ASSERT_FILE (declare.hpp, LOUD (0))
ASSERT_FILE (4.hpp, LOUD (0))
ASSERT_FILE (paste.hpp, LOUD (0))
#else
cout << "kiss" << endl;
app (argv [1], argv [2]);
#endif
#ifdef Debug
#define ANTAL TEST_FILE_COUNT
// #define TEST_SINGEL_FILE paste.hpp
#ifdef TEST_SINGEL_FILE
string inputPath = string (TEST_FILES_PRE_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE));
string outputPath = string (TEST_FILES_POST_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE));
string facitPath = string (TEST_FILES_FACIT_PATH) + string (BOOST_PP_STRINGIZE (TEST_SINGEL_FILE));
app (inputPath, outputPath);
string result = readFileIntoString (outputPath);
string facit = readFileIntoString (facitPath);
if (result != facit)
{
warning += "\n\n\t" + outputPath + "\n\t != " + "\n\t" + facitPath + "\n\n\n";
}
#endif
#ifdef TEST_ALL_FILES
array <string, TEST_FILE_COUNT> test_files_pre;
array <string, TEST_FILE_COUNT> test_files_post;
array <string, TEST_FILE_COUNT> test_files_facit;
#define PRE(z, n, text) test_files_pre [n] = BOOST_PP_CAT (text, n);
#define POST(z, n, text) test_files_post [n] = BOOST_PP_CAT (text, n);
#define FACIT(z, n, text) test_files_facit [n] = BOOST_PP_CAT (text, n);
BOOST_PP_REPEAT (TEST_FILE_COUNT, PRE, TEST_FILE_PRE_)
BOOST_PP_REPEAT (TEST_FILE_COUNT, POST, TEST_FILE_POST_)
BOOST_PP_REPEAT (TEST_FILE_COUNT, FACIT, TEST_FILE_FACIT_)
for (int i = 0; i < ANTAL; ++i)
{
string inputPath = test_files_pre [i];
string outputPath = test_files_post [i];
string facitPath = test_files_facit [i];
app (inputPath, outputPath);
string result = readFileIntoString (outputPath);
string facit = readFileIntoString (facitPath);
// string post = readFileIntoString (test_files_post[i]);
// string facit = readFileIntoString (test_files_facit[i]);
if (result != facit)
{
warning += "\n\n\t" + test_files_post[i] + "\n\t != " + "\n\t" + test_files_facit[i] + "\n\n\n";
}
}
#endif
if (warning != "") {
// throw runtime_error (warning);
cout << warning << endl;
}
return 0;
#endif
#ifdef DEBUGGING
ifstream infile;
infile.open ("/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_pre/test0.hpp");
ofstream outfile;
outfile.open ("/Users/philipwenkel/GitHub/phan/tests/test_phan_app/testFiles_post/test0.hpp");
#else
ifstream infile;
infile.open (argv[1]);
ofstream outfile;
outfile.open (argv[2]);
#endif
auto remove_beginning_spaces = bind (remove_beginning_chars, _1, ' ');
auto remove_beginning_newlines = bind (remove_beginning_chars, _1, '\n');
string outtext = readFileIntoString(infile);
// auto extractors = array <extractor, 1> {extractor{"${", "}"}};
// auto extractors = array <extractor, 1> {extractor{"${", "}"}};
auto stringVariableDeclerationExtractor = extractor {"$(", ")"};
auto stringValueDeclerationExtractor = extractor {"{", "}"};
auto stringVariablePasterExtractor = extractor {"${", "}"};
// auto stringVariablePasteExtractor = extractor {"${", "}"};
vector <pair <string, string>> declaredVariables;
{
// Process p;
// p.process (outtext);
}
outfile << outtext;
// cout << first_signature (str, first_parser) << endl;
PROCC ((
template <int>
struct gpu;
$(1)
{
a # = comment # ?(name)?{explanation}
€ = _function (_anonymous/_non-anonymous) # ?[?_scope_var = @(_var)?]?(0 ?i? 0)?{}??(_function_name)?
$ = _variable (_non-anonymous){_code} # (_name){}
@ = _paste
template <>
struct gpu <${0 i 10}> # {_public change all in scope}
{
$(0 i 4) # {everyting refering to i will clone for times}
// # int i${i} -> int i0123
@(i)<1 10>
@(i)<1 10> -> {@} 12345678910
@<0 2> -> {ph} phph
2
@(hej) <-> ${0#} 02 02
-1
@(hej#) <-> ${0#} -10 0-1
2
@(#hej) <-> ${0#} 022 02
2
${0#} -> @(#hej) 002 02
kuk @<1 3> &{ph&} kuk ph1ph2ph3
fitta @<1 3> -> {ph&} kuk fitta ph123 kuk
@<1 3> -> &{ph} phphph
@(hej) <-> {0} 0 0
@(hej) () 0
@(hej) <- {1} 1 ()
@(hej) -> {2@} () 21
@(hej) 1 ()
@(hej) <-> {3@} 3 31
@(hej@) <-> {kuk} "snopphejkuk"
@(hej) {philip@} philipkuk
@{i} -> {int i} kommer bli int i int i int i int i
@{i} -> {int@ i@} int0 i0 int1 i1 int2 i2 int3 i3
${i} 0123
$(str){philip} "philip"
${str} -> {int i@} -> {kuk @ hora} "kuk int iphilip hora"
$(hej){kukens fitta} kukens fitta
${hej} kukens fitta
int i${0 10} = 0; #{_private}
int j€(0 5)(k) = 3; #{public}
€[j = @(i)](0 i 3){int i@(i + 1) = @(j);}(myFun)
// €[j = @(i)](0 i 3){int i@(i) = @(j);} anonymous
// 0 i 3 prio före 0 i 10 -> därför sätter vi om namnet till j
// 0 i 3 is internal dvs endast inne i {} och i refererar inget utanför
$(_stat_int){static $(con){constexpr} int} fitta = GPU_COUNT;
ERROR-> $(_stat){kiss}
@(_stat_int) count = GPU_COUNT;
${static} constexpr uint32_t max_image_dimension_1D = GPU_${i}_MAX_IMAGE_DIMENSION_1D;
@(st) int i = 3;
};
}
)(0)(string s));
// cout << s << endl;
// PROCC ((
// template <int>
// struct gpu;
//
// $(1)
// {
// € = inline
// $ = declare variable, only visible to the current scope
// and to those below
//
// template <>
// struct gpu <$(0 i 10)>
// {
// int $(0 j 10) = 0;
//
// €[j = @(i)](0 i 3){int i@(i) = @(j);}(myFun)
// 0 i 3 prio före 0 i 10 -> därför sätter vi om namnet till j
// 0 i 3 is internal dvs endast inne i {} och i refererar inget utanför
// $(stat){static $(con){constexpr} int} fitta = GPU_COUNT;
// ERROR-> $(stat){kiss}
// @(stat) count = GPU_COUNT;
// ${static} constexpr uint32_t max_image_dimension_1D = GPU_${i}_MAX_IMAGE_DIMENSION_1D;
// @(st) int i = 3;
// };
// }
// )(0)(string s));
// cout << s << endl;
std::vector<double> input = {1.2, 2.3, 3.4, 4.5};
// cout << "hello world" << endl;
return 0;
}
string first_signature (string const& first, string const& second, string str, auto&& fun)
{
auto a1 = str.find(first);
while (a1 != string::npos)
{
if (int a2 = str.find (second); a2 != string::npos)
{
string replac = fun (string (str.begin() + a1, str.begin() + a2 + 1));
str.replace (str.begin() + a1, str.begin() + a2 + 1, replac);
}
else
{
break;
}
a1 = str.find ("${");
}
// string res;
// for (auto const& i : str)
// res += i;
return str;
}
| 25.097101 | 271 | 0.528671 | phiwen96 |
61eb07f98c7125ea350f13d4f10df1b68125aa6b | 6,601 | cc | C++ | L1Trigger/TrackTrigger/src/TTClusterAlgorithm_official.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | L1Trigger/TrackTrigger/src/TTClusterAlgorithm_official.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | L1Trigger/TrackTrigger/src/TTClusterAlgorithm_official.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | /*! \brief Implementation of methods of TTClusterAlgorithm_official
* \details Here, in the source file, the methods which do depend
* on the specific type <T> that can fit the template.
*
* \author Nicola Pozzobon
* \date 2013, Jul 12
*
*/
#include "L1Trigger/TrackTrigger/interface/TTClusterAlgorithm_official.h"
/// Function to compare clusters and sort them by row
template <>
bool TTClusterAlgorithm_official<Ref_Phase2TrackerDigi_>::CompareClusters(const Ref_Phase2TrackerDigi_& a,
const Ref_Phase2TrackerDigi_& b) {
return (a->row() < b->row());
}
/// Clustering operations
template <>
void TTClusterAlgorithm_official<Ref_Phase2TrackerDigi_>::Cluster(
std::vector<std::vector<Ref_Phase2TrackerDigi_> >& output,
const std::vector<Ref_Phase2TrackerDigi_>& input,
bool isPS) const {
/// Prepare the output
output.clear();
/// Prepare a proper hit container
std::map<unsigned int, std::vector<Ref_Phase2TrackerDigi_> > mapHitsByColumn;
/// Map all the hits by column index
typename std::vector<Ref_Phase2TrackerDigi_>::const_iterator inputIterator;
inputIterator = input.begin();
while (inputIterator != input.end()) {
mapHitsByColumn[(**inputIterator).column()].push_back(*inputIterator);
++inputIterator;
}
/// 1D Clusters must be stored properly <column, first row index>
std::map<std::pair<unsigned int, unsigned int>, std::vector<Ref_Phase2TrackerDigi_> > map1DCluByColRow;
/// Loop over the mapped hits
typename std::map<unsigned int, std::vector<Ref_Phase2TrackerDigi_> >::iterator mapIterHbC;
mapIterHbC = mapHitsByColumn.begin();
while (mapIterHbC != mapHitsByColumn.end()) {
/// Collect hits sharing column index and
/// differing by 1 in row index
typename std::vector<Ref_Phase2TrackerDigi_>::iterator inputIterator;
inputIterator = mapIterHbC->second.begin();
/// Loop over single column
while (inputIterator != mapIterHbC->second.end()) {
std::vector<Ref_Phase2TrackerDigi_> temp;
temp.push_back(*inputIterator);
inputIterator = mapIterHbC->second.erase(inputIterator);
typename std::vector<Ref_Phase2TrackerDigi_>::iterator inputIterator2;
inputIterator2 = inputIterator;
/// Nested loop
while (inputIterator2 != mapIterHbC->second.end()) {
/// Check col/row and add to the cluster
if ((temp.back()->column() == (**inputIterator2).column()) &&
((**inputIterator2).row() - temp.back()->row() == 1)) {
temp.push_back(*inputIterator2);
inputIterator2 = mapIterHbC->second.erase(inputIterator2);
} else
break;
} /// End of nested loop
/// Sort the vector elements by row index
std::sort(temp.begin(), temp.end(), CompareClusters);
/// Put the cluster in the map
map1DCluByColRow.insert(std::make_pair(std::make_pair(mapIterHbC->first, temp.at(0)->row()), temp));
inputIterator = inputIterator2;
} /// End of loop over single column
++mapIterHbC;
} /// End of loop over mapped hits
/// Cluster over the second dimension
/// only in PS modules!
typename std::map<std::pair<unsigned int, unsigned int>, std::vector<Ref_Phase2TrackerDigi_> >::iterator
mapIter1DCbCR0;
typename std::map<std::pair<unsigned int, unsigned int>, std::vector<Ref_Phase2TrackerDigi_> >::iterator
mapIter1DCbCR1;
mapIter1DCbCR0 = map1DCluByColRow.begin();
unsigned int lastCol = mapIter1DCbCR0->first.first;
while (mapIter1DCbCR0 != map1DCluByColRow.end()) {
/// Add the hits
std::vector<Ref_Phase2TrackerDigi_> candCluster;
candCluster.insert(candCluster.end(), mapIter1DCbCR0->second.begin(), mapIter1DCbCR0->second.end());
if (isPS) {
/// Loop over the other elements of the map
mapIter1DCbCR1 = map1DCluByColRow.begin();
while (mapIter1DCbCR1 != map1DCluByColRow.end()) {
/// Skip same element
if (mapIter1DCbCR1 == mapIter1DCbCR0) {
++mapIter1DCbCR1;
continue;
}
/// Skip non-contiguous column
if (std::abs((int)(mapIter1DCbCR1->first.first) - (int)lastCol) != 1) {
++mapIter1DCbCR1;
continue;
}
/// Column is contiguous
/// Update the "last column index"
/// This should be safe as maps are sorted structures by construction
lastCol = mapIter1DCbCR1->first.first;
/// Check that the cluster is good to be clustered
/// Get first row
unsigned int iRow0 = mapIter1DCbCR0->first.second;
unsigned int iRow1 = mapIter1DCbCR1->first.second;
/// Get the max row in the cluster
unsigned int jRow0 = mapIter1DCbCR0->second.back()->row();
unsigned int jRow1 = mapIter1DCbCR1->second.back()->row();
/// Check if they overlap
if ((iRow1 >= iRow0 && iRow1 <= jRow0) || (jRow1 >= iRow0 && jRow1 <= jRow0)) {
/// If so, add the hits to the cluster!
candCluster.insert(candCluster.end(), mapIter1DCbCR1->second.begin(), mapIter1DCbCR1->second.end());
map1DCluByColRow.erase(mapIter1DCbCR1++);
} else {
++mapIter1DCbCR1;
}
} /// End of nested loop
map1DCluByColRow.erase(mapIter1DCbCR0++);
/// Check output
/// Sort the vector by row index
std::sort(candCluster.begin(), candCluster.end(), CompareClusters);
/*
std::cout << candCluster.at(0)->row() - candCluster.back()->row() << " / "
<< static_cast<int>(candCluster.at(0)->row() - candCluster.back()->row()) << " / "
<< abs( candCluster.at(0)->row() - candCluster.back()->row() ) << " / "
<< std::abs( candCluster.at(0)->row() - candCluster.back()->row() ) << " / "
<< mWidthCut << std::endl;
*/
if (std::abs(static_cast<int>(candCluster.at(0)->row() - candCluster.back()->row())) <
mWidthCut || /// one should add 1 to use <=
mWidthCut < 1) {
output.push_back(candCluster);
}
} /// End of isPS
else {
map1DCluByColRow.erase(mapIter1DCbCR0++);
/// Check output
/// Sort the vector by row index
std::sort(candCluster.begin(), candCluster.end(), CompareClusters);
if (std::abs(static_cast<int>(candCluster.at(0)->row() - candCluster.back()->row())) <
mWidthCut || /// one should add 1 to use <=
mWidthCut < 1) {
output.push_back(candCluster);
}
} /// End of non-PS case
} /// End of loop over mapped 1D Clusters
}
| 38.377907 | 110 | 0.636722 | ckamtsikis |
61ec78bc504440fd6c6131e4ba6f70d528b421c3 | 20,822 | cpp | C++ | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/bf16/jit_avx512_core_s16_copy_an_kern.cpp | goswamig/training_results_v0.7 | 4278ce8a0f3d4db6b5e6054277724ca36278d7a3 | [
"Apache-2.0"
] | 48 | 2020-07-29T18:09:23.000Z | 2021-10-09T01:53:33.000Z | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/bf16/jit_avx512_core_s16_copy_an_kern.cpp | goswamig/training_results_v0.7 | 4278ce8a0f3d4db6b5e6054277724ca36278d7a3 | [
"Apache-2.0"
] | 9 | 2021-04-02T02:28:07.000Z | 2022-03-26T18:23:59.000Z | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/bf16/jit_avx512_core_s16_copy_an_kern.cpp | lablup/training_results_v0.7 | f5bb59aa0f8b18b602763abe47d1d24d0d54b197 | [
"Apache-2.0"
] | 42 | 2020-08-01T06:41:24.000Z | 2022-01-20T10:33:08.000Z | /*******************************************************************************
* 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.
*******************************************************************************/
#include "common_s16.hpp"
#include "jit_generator.hpp"
namespace mkldnn {
namespace impl {
namespace cpu {
jit_avx512_core_s16_copy_an_kern::jit_avx512_core_s16_copy_an_kern() :
jit_generator(nullptr, S16_COPY_KERNEL_CODE_SIZE) {
#ifndef _WIN32
#define M rdi
#define N rsi
#define A rdx
#define LDA rcx
#define ALPHA r8
#define B r9
#define I rax
#define A1 r10
#define A2 r8
#define LDA3 r11
#else
#define M rcx
#define N rdx
#define A r8
#define LDA r9
#define ALPHA rax
#define B rdi
#define I rax
#define A1 rsi
#define A2 r10
#define LDA3 r11
#define ARG_ALPHA 40+stacksize+rsp
#define ARG_B 48+stacksize+rsp
#endif
inLocalLabel();
{
Xbyak::Label l1e8;
Xbyak::Label l24;
Xbyak::Label l2c8;
Xbyak::Label l2fc;
Xbyak::Label l30c;
Xbyak::Label l318;
Xbyak::Label l32c;
Xbyak::Label l38;
Xbyak::Label l44c;
Xbyak::Label l4e8;
Xbyak::Label l510;
Xbyak::Label l520;
Xbyak::Label l52c;
Xbyak::Label l540;
Xbyak::Label l5dc;
Xbyak::Label l630;
Xbyak::Label l658;
Xbyak::Label l668;
Xbyak::Label l674;
Xbyak::Label l688;
Xbyak::Label l730;
Xbyak::Label l78c;
Xbyak::Label l7c0;
Xbyak::Label l7dc;
Xbyak::Label l7ec;
Xbyak::Label l7f8;
Xbyak::Label l808;
Xbyak::Label l884;
Xbyak::Label l8cc;
Xbyak::Label l8f8;
Xbyak::Label l914;
Xbyak::Label l924;
Xbyak::Label l930;
Xbyak::Label l940;
Xbyak::Label l9b8;
Xbyak::Label l9fc;
Xbyak::Label la28;
Xbyak::Label la44;
Xbyak::Label la52;
Xbyak::Label la5c;
Xbyak::Label la6c;
Xbyak::Label lae4;
Xbyak::Label lb2c;
Xbyak::Label lb5c;
Xbyak::Label lb74;
Xbyak::Label lb84;
preamble();
#ifdef _WIN32
auto stacksize = get_size_of_abi_save_regs();
mov(ALPHA, ptr[ARG_ALPHA]);
mov(B, ptr[ARG_B]);
#endif
mov(M, qword[M]);
mov(N, qword[N]);
mov(LDA, qword[LDA]);
shl(LDA, 1);
lea(LDA3, ptr[LDA+LDA*2]);
sub(A, -128);
sub(B, -128);
cmp(N, 0x30);
jl(l30c, T_NEAR);
align(4);
L(l24);
mov(A1, A);
add(A, 0x60);
mov(I, M);
sar(I, 0x2);
jle(l1e8, T_NEAR);
align(4);
L(l38);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x80], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x60], ymm2);
vmovdqu(xmm0, xword[A1-0x60]);
vmovdqu(xmm1, xword[A1+LDA*1-0x60]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x40], ymm2);
vmovdqu(xmm0, xword[A1-0x50]);
vmovdqu(xmm1, xword[A1+LDA*1-0x50]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x20], ymm2);
vmovdqu(xmm0, xword[A1-0x40]);
vmovdqu(xmm1, xword[A1+LDA*1-0x40]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B], ymm2);
vmovdqu(xmm0, xword[A1-0x30]);
vmovdqu(xmm1, xword[A1+LDA*1-0x30]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x20], ymm2);
lea(A1, ptr[A1+LDA*2]);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x40], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x60], ymm2);
vmovdqu(xmm0, xword[A1-0x60]);
vmovdqu(xmm1, xword[A1+LDA*1-0x60]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x80], ymm2);
vmovdqu(xmm0, xword[A1-0x50]);
vmovdqu(xmm1, xword[A1+LDA*1-0x50]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0xa0], ymm2);
vmovdqu(xmm0, xword[A1-0x40]);
vmovdqu(xmm1, xword[A1+LDA*1-0x40]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0xc0], ymm2);
vmovdqu(xmm0, xword[A1-0x30]);
vmovdqu(xmm1, xword[A1+LDA*1-0x30]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0xe0], ymm2);
lea(A1, ptr[A1+LDA*2]);
sub(B, -384);
dec(I);
jg(l38, T_NEAR);
align(4);
L(l1e8);
test(M, 0x2);
jle(l2c8, T_NEAR);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x80], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x60], ymm2);
vmovdqu(xmm0, xword[A1-0x60]);
vmovdqu(xmm1, xword[A1+LDA*1-0x60]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x40], ymm2);
vmovdqu(xmm0, xword[A1-0x50]);
vmovdqu(xmm1, xword[A1+LDA*1-0x50]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x20], ymm2);
vmovdqu(xmm0, xword[A1-0x40]);
vmovdqu(xmm1, xword[A1+LDA*1-0x40]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B], ymm2);
vmovdqu(xmm0, xword[A1-0x30]);
vmovdqu(xmm1, xword[A1+LDA*1-0x30]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x20], ymm2);
lea(A1, ptr[A1+LDA*2]);
sub(B, -192);
align(4);
L(l2c8);
test(M, 0x1);
jle(l2fc, T_NEAR);
vmovdqu(ymm0, yword[A1-0x80]);
vmovdqu(ymm1, yword[A1-0x60]);
vmovdqu(ymm2, yword[A1-0x40]);
vmovdqu(yword[B-0x80], ymm0);
vmovdqu(yword[B-0x60], ymm1);
vmovdqu(yword[B-0x40], ymm2);
sub(B, -96);
align(4);
L(l2fc);
sub(N, 0x30);
cmp(N, 0x30);
jge(l24, T_NEAR);
align(4);
L(l30c);
cmp(N, 0x20);
jl(l520, T_NEAR);
align(4);
L(l318);
mov(A1, A);
add(A, 0x40);
mov(I, M);
sar(I, 0x2);
jle(l44c, T_NEAR);
align(4);
L(l32c);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x80], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x60], ymm2);
vmovdqu(xmm0, xword[A1-0x60]);
vmovdqu(xmm1, xword[A1+LDA*1-0x60]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x40], ymm2);
vmovdqu(xmm0, xword[A1-0x50]);
vmovdqu(xmm1, xword[A1+LDA*1-0x50]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x20], ymm2);
lea(A1, ptr[A1+LDA*2]);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x20], ymm2);
vmovdqu(xmm0, xword[A1-0x60]);
vmovdqu(xmm1, xword[A1+LDA*1-0x60]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x40], ymm2);
vmovdqu(xmm0, xword[A1-0x50]);
vmovdqu(xmm1, xword[A1+LDA*1-0x50]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B+0x60], ymm2);
lea(A1, ptr[A1+LDA*2]);
sub(B, -256);
dec(I);
jg(l32c, T_NEAR);
align(4);
L(l44c);
test(M, 0x2);
jle(l4e8, T_NEAR);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x80], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x60], ymm2);
vmovdqu(xmm0, xword[A1-0x60]);
vmovdqu(xmm1, xword[A1+LDA*1-0x60]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x40], ymm2);
vmovdqu(xmm0, xword[A1-0x50]);
vmovdqu(xmm1, xword[A1+LDA*1-0x50]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x20], ymm2);
lea(A1, ptr[A1+LDA*2]);
sub(B, -128);
align(4);
L(l4e8);
test(M, 0x1);
jle(l510, T_NEAR);
vmovdqu(ymm0, yword[A1-0x80]);
vmovdqu(ymm1, yword[A1-0x60]);
add(A1, LDA);
vmovdqu(yword[B-0x80], ymm0);
vmovdqu(yword[B-0x60], ymm1);
sub(B, -64);
align(4);
L(l510);
sub(N, 0x20);
cmp(N, 0x20);
jge(l318, T_NEAR);
align(4);
L(l520);
cmp(N, 0x10);
jl(l668, T_NEAR);
align(4);
L(l52c);
mov(A1, A);
add(A, 0x20);
mov(I, M);
sar(I, 0x2);
jle(l5dc, T_NEAR);
align(4);
L(l540);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x80], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x60], ymm2);
lea(A1, ptr[A1+LDA*2]);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x40], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x20], ymm2);
lea(A1, ptr[A1+LDA*2]);
sub(B, -128);
dec(I);
jg(l540, T_NEAR);
align(4);
L(l5dc);
test(M, 0x2);
jle(l630, T_NEAR);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1+LDA*1-0x80]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x80], ymm2);
vmovdqu(xmm0, xword[A1-0x70]);
vmovdqu(xmm1, xword[A1+LDA*1-0x70]);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm2, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x60], ymm2);
lea(A1, ptr[A1+LDA*2]);
sub(B, -64);
align(4);
L(l630);
test(M, 0x1);
jle(l658, T_NEAR);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xmm1, xword[A1-0x70]);
vmovdqu(xword[B-0x80], xmm0);
vmovdqu(xword[B-0x70], xmm1);
sub(B, -32);
align(4);
L(l658);
sub(N, 0x10);
cmp(N, 0x10);
jge(l52c, T_NEAR);
align(4);
L(l668);
cmp(N, 0x8);
jl(l7ec, T_NEAR);
align(4);
L(l674);
mov(A1, A);
add(A, 0x10);
mov(I, M);
sar(I, 0x3);
jle(l730, T_NEAR);
align(4);
L(l688);
vmovdqu(xmm0, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm1, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm2, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm3, xword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm4, xmm0, xmm1);
vpunpckhwd(xmm5, xmm0, xmm1);
vperm2f128(ymm0, ymm4, ymm5, 0x20);
vpunpcklwd(xmm4, xmm2, xmm3);
vpunpckhwd(xmm5, xmm2, xmm3);
vperm2f128(ymm2, ymm4, ymm5, 0x20);
vmovdqu(yword[B-0x80], ymm0);
vmovdqu(yword[B-0x60], ymm2);
vmovdqu(xmm0, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm1, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm2, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm3, xword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm4, xmm0, xmm1);
vpunpckhwd(xmm5, xmm0, xmm1);
vperm2f128(ymm0, ymm4, ymm5, 0x20);
vpunpcklwd(xmm4, xmm2, xmm3);
vpunpckhwd(xmm5, xmm2, xmm3);
vperm2f128(ymm2, ymm4, ymm5, 0x20);
vmovdqu(yword[B-0x40], ymm0);
vmovdqu(yword[B-0x20], ymm2);
sub(B, -128);
dec(I);
jg(l688, T_NEAR);
align(4);
L(l730);
test(M, 0x4);
jle(l78c, T_NEAR);
vmovdqu(xmm0, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm1, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm2, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm3, xword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm4, xmm0, xmm1);
vpunpckhwd(xmm5, xmm0, xmm1);
vperm2f128(ymm0, ymm4, ymm5, 0x20);
vpunpcklwd(xmm4, xmm2, xmm3);
vpunpckhwd(xmm5, xmm2, xmm3);
vperm2f128(ymm2, ymm4, ymm5, 0x20);
vmovdqu(yword[B-0x80], ymm0);
vmovdqu(yword[B-0x60], ymm2);
sub(B, -64);
align(4);
L(l78c);
test(M, 0x2);
jle(l7c0, T_NEAR);
vmovdqu(xmm0, xword[A1-0x80]);
add(A1, LDA);
vmovdqu(xmm1, xword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm2, xmm0, xmm1);
vpunpckhwd(xmm3, xmm0, xmm1);
vperm2f128(ymm0, ymm2, ymm3, 0x20);
vmovdqu(yword[B-0x80], ymm0);
sub(B, -32);
align(4);
L(l7c0);
test(M, 0x1);
jle(l7dc, T_NEAR);
vmovdqu(xmm0, xword[A1-0x80]);
vmovdqu(xword[B-0x80], xmm0);
sub(B, -16);
align(4);
L(l7dc);
sub(N, 0x8);
cmp(N, 0x8);
jge(l674, T_NEAR);
align(4);
L(l7ec);
cmp(N, 0x4);
jl(l924, T_NEAR);
align(4);
L(l7f8);
mov(A1, A);
add(A, 0x8);
mov(I, M);
sar(I, 0x3);
jle(l884, T_NEAR);
align(4);
L(l808);
vmovq(xmm0, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm1, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm2, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm3, qword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vpunpcklwd(xmm2, xmm2, xmm3);
vperm2f128(ymm0, ymm0, ymm2, 0x20);
vmovdqu(yword[B-0x80], ymm0);
vmovq(xmm0, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm1, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm2, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm3, qword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vpunpcklwd(xmm2, xmm2, xmm3);
vperm2f128(ymm0, ymm0, ymm2, 0x20);
vmovdqu(yword[B-0x60], ymm0);
sub(B, -64);
dec(I);
jg(l808, T_NEAR);
align(4);
L(l884);
test(M, 0x4);
jle(l8cc, T_NEAR);
vmovq(xmm0, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm1, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm2, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm3, qword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vpunpcklwd(xmm2, xmm2, xmm3);
vmovdqu(xword[B-0x80], xmm0);
vmovdqu(xword[B-0x70], xmm2);
sub(B, -32);
align(4);
L(l8cc);
test(M, 0x2);
jle(l8f8, T_NEAR);
vmovq(xmm0, qword[A1-0x80]);
add(A1, LDA);
vmovq(xmm1, qword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vmovdqu(xword[B-0x80], xmm0);
sub(B, -16);
align(4);
L(l8f8);
test(M, 0x1);
jle(l914, T_NEAR);
vmovq(xmm0, qword[A1-0x80]);
vmovq(qword[B-0x80], xmm0);
sub(B, -8);
align(4);
L(l914);
sub(N, 0x4);
cmp(N, 0x4);
jge(l7f8, T_NEAR);
align(4);
L(l924);
cmp(N, 0x2);
jl(la52, T_NEAR);
align(4);
L(l930);
mov(A1, A);
add(A, 0x4);
mov(I, M);
sar(I, 0x3);
jle(l9b8, T_NEAR);
align(4);
L(l940);
vmovd(xmm0, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm1, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm2, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm3, dword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vpunpcklwd(xmm2, xmm2, xmm3);
vpunpcklqdq(xmm0, xmm0, xmm2);
vmovdqu(xword[B-0x80], xmm0);
vmovd(xmm0, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm1, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm2, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm3, dword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vpunpcklwd(xmm2, xmm2, xmm3);
vpunpcklqdq(xmm0, xmm0, xmm2);
vmovdqu(xword[B-0x70], xmm0);
sub(B, -32);
dec(I);
jg(l940, T_NEAR);
align(4);
L(l9b8);
test(M, 0x4);
jle(l9fc, T_NEAR);
vmovd(xmm0, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm1, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm2, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm3, dword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vpunpcklwd(xmm2, xmm2, xmm3);
vpunpcklqdq(xmm0, xmm0, xmm2);
vmovdqu(xword[B-0x80], xmm0);
sub(B, -16);
align(4);
L(l9fc);
test(M, 0x2);
jle(la28, T_NEAR);
vmovd(xmm0, dword[A1-0x80]);
add(A1, LDA);
vmovd(xmm1, dword[A1-0x80]);
add(A1, LDA);
vpunpcklwd(xmm0, xmm0, xmm1);
vmovq(qword[B-0x80], xmm0);
sub(B, -8);
align(4);
L(la28);
test(M, 0x1);
jle(la44, T_NEAR);
vmovd(xmm0, dword[A1-0x80]);
vmovd(dword[B-0x80], xmm0);
sub(B, -4);
align(4);
L(la44);
sub(N, 0x2);
cmp(N, 0x2);
jge(l930, T_NEAR);
align(4);
L(la52);
cmp(N, 0x1);
jl(lb84, T_NEAR);
align(4);
L(la5c);
mov(A1, A);
add(A, 0x2);
mov(LDA3, M);
sar(LDA3, 0x3);
jle(lae4, T_NEAR);
align(4);
L(la6c);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x0);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x1);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x2);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x3);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x4);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x5);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x6);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x7);
vmovdqu(xword[B-0x80], xmm0);
sub(B, -16);
dec(LDA3);
jg(la6c, T_NEAR);
align(4);
L(lae4);
test(M, 0x4);
jle(lb2c, T_NEAR);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x0);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x1);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x2);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x3);
vmovq(qword[B-0x80], xmm0);
sub(B, -8);
align(4);
L(lb2c);
test(M, 0x2);
jle(lb5c, T_NEAR);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x0);
mov(ax, word[A1-0x80]);
add(A1, LDA);
vpinsrw(xmm0, xmm0, eax, 0x1);
vmovd(dword[B-0x80], xmm0);
sub(B, -4);
align(4);
L(lb5c);
test(M, 0x1);
jle(lb74, T_NEAR);
mov(ax, word[A1-0x80]);
mov(word[B-0x80], ax);
sub(B, -2);
align(4);
L(lb74);
sub(N, 0x1);
cmp(N, 0x1);
jge(la5c, T_NEAR);
align(4);
L(lb84);
postamble();
}
outLocalLabel();
#undef M
#undef N
#undef A
#undef LDA
#undef ALPHA
#undef B
#undef I
#undef A1
#undef A2
#undef LDA3
#ifdef _WIN32
#undef ARG_ALPHA
#undef ARG_B
#endif
}
}
}
}
| 24.127462 | 80 | 0.592786 | goswamig |
61ee79cd70ea8ea30a159d70ad57ba85261744be | 1,436 | cpp | C++ | CWTW-Pro.cpp | jr4qpv/cwtw-pro | 5b3340e27ef4d606ad1833b6ee4bf27815f89dfb | [
"MIT"
] | null | null | null | CWTW-Pro.cpp | jr4qpv/cwtw-pro | 5b3340e27ef4d606ad1833b6ee4bf27815f89dfb | [
"MIT"
] | null | null | null | CWTW-Pro.cpp | jr4qpv/cwtw-pro | 5b3340e27ef4d606ad1833b6ee4bf27815f89dfb | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
//---------------------------------------------------------------------------
USEFORM("UAbout.cpp", AboutBox);
USEFORM("UEdit.cpp", EditFile);
USEFORM("URegInf.cpp", RegInf);
USEFORM("UReg.cpp", Regist);
USEFORM("UMain.cpp", Main);
USEFORM("UEnv.cpp", Env);
//---------------------------------------------------------------------------
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
HANDLE mx = CreateMutex(NULL, true, L"SingleInstanceProgram");
if (GetLastError()) {
ShowMessage("CWTW-Proは既に実行されています!");
return -1;
}
try
{
Application->Initialize();
Application->MainFormOnTaskBar = true;
Application->CreateForm(__classid(TMain), &Main);
Application->CreateForm(__classid(TAboutBox), &AboutBox);
Application->CreateForm(__classid(TEditFile), &EditFile);
Application->CreateForm(__classid(TRegist), &Regist);
Application->CreateForm(__classid(TRegInf), &RegInf);
Application->CreateForm(__classid(TEnv), &Env);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
ReleaseMutex(mx);
return 0;
}
//---------------------------------------------------------------------------
| 26.592593 | 78 | 0.548747 | jr4qpv |
61eecc43c9d264ef7163665bc71d09e160c624ce | 1,865 | cpp | C++ | linked_list/merge_two_linked_list.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | linked_list/merge_two_linked_list.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | linked_list/merge_two_linked_list.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | // Merge two Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
} *first = NULL, *second = NULL, *third = NULL;
void Display(struct Node *p)
{
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
void create(int A[], int n)
{
int i;
struct Node *t, *last;
first = (struct Node *)malloc(sizeof(struct Node));
first->data = A[0];
first->next = NULL;
last = first;
}
for (int i = 1; i < n; i++)
{
t = (struct Node *)malloc(sizeof(struct Node));
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
void create2(int A[], int n)
{
int i;
struct Node *t, *last;
second = (struct Node *)malloc(sizeof(struct Node));
second->data = A[0];
second->next = NULL;
last = second;
}
for (i = 1; i < n; i++)
{
t = (struct Node *)malloc(sizeof(struct Node));
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
void Merge(struct Node *p, struct Node *q)
{
struct Node *last;
if (p->data < q->data)
{
third = last = p;
p = p->next;
third->next = NULL;
}
else
{
third = last = q;
q = q->next;
third->next = NULL;
}
while (p && q)
{
if (p->data < q->data)
{
last->next = p;
last = p;
p = p->next;
last->next = NULL;
}
else
{
last->next = q;
last = q;
q = q->next;
last->next = NULL;
}
}
if (p)
{
last->next = p;
}
if (q)
{
last->next = q;
}
}
int main()
{
int A[] = {10, 20, 40, 50, 60};
int B[] = {15, 18, 25, 30, 55};
create(A, 5);
create2(B, 5);
Merge(frist, second);
Display(third);
}
return 0; | 18.284314 | 56 | 0.447721 | M1NH42 |
61f01de1655fafffb7a5485e5778a3114378a7c5 | 2,973 | cpp | C++ | DREAM3DReviewFilters/HEDM/MicFields.cpp | JDuffeyBQ/DREAM3DReview | 098ddc60d1c53764e09e21e08d4636233071be31 | [
"BSD-3-Clause"
] | null | null | null | DREAM3DReviewFilters/HEDM/MicFields.cpp | JDuffeyBQ/DREAM3DReview | 098ddc60d1c53764e09e21e08d4636233071be31 | [
"BSD-3-Clause"
] | 18 | 2017-09-01T23:13:02.000Z | 2021-09-02T12:58:57.000Z | DREAM3DReviewFilters/HEDM/MicFields.cpp | JDuffeyBQ/DREAM3DReview | 098ddc60d1c53764e09e21e08d4636233071be31 | [
"BSD-3-Clause"
] | 9 | 2017-09-01T23:15:17.000Z | 2021-09-21T13:24:19.000Z | /* ============================================================================
* Copyright (c) 2010, Michael A. Jackson (BlueQuartz Software)
* Copyright (c) 2010, Dr. Michael A. Groeber (US Air Force Research Laboratories
* 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 Michael A. Groeber, Michael A. Jackson, the US Air Force,
* BlueQuartz Software nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This code was written under United States Air Force Contract number
* FA8650-07-D-5800
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "MicFields.h"
#include "MicConstants.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MicFields::MicFields() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MicFields::~MicFields() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
std::vector<std::string> MicFields::getFieldNames()
{
std::vector<std::string> features;
features.push_back(Mic::Euler1);
features.push_back(Mic::Euler2);
features.push_back(Mic::Euler3);
features.push_back(Mic::Confidence);
features.push_back(Mic::Phase);
features.push_back(Mic::X);
features.push_back(Mic::Y);
return features;
}
| 45.045455 | 83 | 0.587622 | JDuffeyBQ |
61f29e1436d2d9c5c30bd40a750d56683c1a3a70 | 1,883 | cc | C++ | src/core/lib/config/core_configuration.cc | blueice123/grpc | 72171a33269073a4c09940e948e82b93bf0fcf97 | [
"Apache-2.0"
] | 7 | 2019-03-26T02:47:46.000Z | 2021-03-25T08:05:37.000Z | src/core/lib/config/core_configuration.cc | blueice123/grpc | 72171a33269073a4c09940e948e82b93bf0fcf97 | [
"Apache-2.0"
] | 15 | 2017-06-20T10:02:58.000Z | 2021-05-06T02:23:13.000Z | src/core/lib/config/core_configuration.cc | blueice123/grpc | 72171a33269073a4c09940e948e82b93bf0fcf97 | [
"Apache-2.0"
] | 13 | 2017-12-06T12:39:29.000Z | 2022-03-29T05:50:44.000Z | // Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <grpc/impl/codegen/port_platform.h>
#include "src/core/lib/config/core_configuration.h"
namespace grpc_core {
std::atomic<CoreConfiguration*> CoreConfiguration::config_{nullptr};
CoreConfiguration::Builder::Builder() = default;
CoreConfiguration* CoreConfiguration::Builder::Build() {
return new CoreConfiguration(this);
}
CoreConfiguration::CoreConfiguration(Builder* builder)
: handshaker_registry_(builder->handshaker_registry_.Build()) {}
const CoreConfiguration& CoreConfiguration::BuildNewAndMaybeSet() {
// Construct builder, pass it up to code that knows about build configuration
Builder builder;
BuildCoreConfiguration(&builder);
// Use builder to construct a confguration
CoreConfiguration* p = builder.Build();
// Try to set configuration global - it's possible another thread raced us
// here, in which case we drop the work we did and use the one that got set
// first
CoreConfiguration* expected = nullptr;
if (!config_.compare_exchange_strong(expected, p, std::memory_order_acq_rel,
std::memory_order_acquire)) {
delete p;
return *expected;
}
return *p;
}
void CoreConfiguration::Reset() {
delete config_.exchange(nullptr, std::memory_order_acquire);
}
} // namespace grpc_core
| 34.236364 | 79 | 0.740308 | blueice123 |
61f5e46c89b2fbc043d053bbca67fe26ad796ae9 | 560 | cpp | C++ | francor_base/src/algorithm/transform.cpp | franc0r/libfrancor | 7dc28349949dbad2da219f2bda5c5cf21cb7f7d8 | [
"BSD-3-Clause"
] | null | null | null | francor_base/src/algorithm/transform.cpp | franc0r/libfrancor | 7dc28349949dbad2da219f2bda5c5cf21cb7f7d8 | [
"BSD-3-Clause"
] | null | null | null | francor_base/src/algorithm/transform.cpp | franc0r/libfrancor | 7dc28349949dbad2da219f2bda5c5cf21cb7f7d8 | [
"BSD-3-Clause"
] | null | null | null | /**
* Algorithm and estimation function regarding transform.
* \author Christian Merkl (knueppl@gmx.de)
* \date 2. November 2019
*/
#include "francor_base/algorithm/transform.h"
#include "francor_base/transform.h"
namespace francor {
namespace base {
namespace algorithm {
namespace transform {
void transformPointVector(const Transform2d& transform, Point2dVector& points)
{
for (auto& point : points)
point = transform * point;
}
} // end namespace transform
} // end namespace algorithm
} // end namespace base
} // end namespace francor | 18.666667 | 78 | 0.733929 | franc0r |
61f60ed77aa8cfe906e4913e9326b833cef4ce25 | 5,782 | cpp | C++ | PhysX_3.4/Snippets/SnippetSpatialIndex/SnippetSpatialIndex.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | PhysX_3.4/Snippets/SnippetSpatialIndex/SnippetSpatialIndex.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | PhysX_3.4/Snippets/SnippetSpatialIndex/SnippetSpatialIndex.cpp | DoubleTT-Changan/0715 | acbd071531ca4f3e2a82525b92f60824178c39fa | [
"Unlicense"
] | null | null | null | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// ****************************************************************************
// This snippet illustrates simple use of the PxSpatialIndex data structure
//
// Note that spatial index has been marked as deprecated and will be removed
// in future releases
//
// We create a number of spheres, and raycast against them in a random direction
// from the origin. When a raycast hits a sphere, we teleport it to a random
// location
// ****************************************************************************
#include <ctype.h>
#include "PxPhysicsAPI.h"
#include "../SnippetCommon/SnippetPrint.h"
#include "../SnippetUtils/SnippetUtils.h"
using namespace physx;
PxDefaultAllocator gAllocator;
PxDefaultErrorCallback gErrorCallback;
PxFoundation* gFoundation = NULL;
static const PxU32 SPHERE_COUNT = 500;
float rand01()
{
return float(rand())/RAND_MAX;
}
struct Sphere : public PxSpatialIndexItem
{
Sphere()
{
radius = 1;
resetPosition();
}
Sphere(PxReal r)
: radius(r)
{
resetPosition();
}
void resetPosition()
{
do
{
position = PxVec3(rand01()-0.5f, rand01()-0.5f, rand01()-0.5f)*(5+rand01()*5);
}
while (position.normalize()==0.0f);
}
PxBounds3 getBounds()
{
// Geometry queries err on the side of reporting positive results in the face of floating point inaccuracies.
// To ensure that a geometry query only reports true when the bounding boxes in the BVH overlap, use
// getWorldBounds, which has a third parameter that scales the bounds slightly (default is scaling by 1.01f)
return PxGeometryQuery::getWorldBounds(PxSphereGeometry(radius), PxTransform(position));
}
PxVec3 position;
PxReal radius;
PxSpatialIndexItemId id;
};
Sphere gSpheres[SPHERE_COUNT];
PxSpatialIndex* gBvh;
void init()
{
gFoundation = PxCreateFoundation(PX_FOUNDATION_VERSION, gAllocator, gErrorCallback);
gBvh = PxCreateSpatialIndex();
// insert the spheres into the BVH, recording the ID so we can later update them
for(PxU32 i=0;i<SPHERE_COUNT;i++)
gSpheres[i].id = gBvh->insert(gSpheres[i], gSpheres[i].getBounds());
// force a full rebuild of the BVH
gBvh->rebuildFull();
// hint that should rebuild over the course of approximately 20 rebuildStep() calls
gBvh->setIncrementalRebuildRate(20);
}
struct HitCallback : public PxSpatialLocationCallback
{
HitCallback(const PxVec3 p, const PxVec3& d): position(p), direction(d), closest(FLT_MAX), hitSphere(NULL) {}
PxAgain onHit(PxSpatialIndexItem& item, PxReal distance, PxReal& shrunkDistance)
{
PX_UNUSED(distance);
Sphere& s = static_cast<Sphere&>(item);
PxRaycastHit hitData;
// the ray hit the sphere's AABB, now we do a ray-sphere intersection test to find out if the ray hit the sphere
PxU32 hit = PxGeometryQuery::raycast(position, direction,
PxSphereGeometry(s.radius), PxTransform(s.position),
1e6, PxHitFlag::eDEFAULT,
1, &hitData);
// if the raycast hit and it's closer than what we had before, shrink the maximum length of the raycast
if(hit && hitData.distance < closest)
{
closest = hitData.distance;
hitSphere = &s;
shrunkDistance = hitData.distance;
}
// and continue the query
return true;
}
PxVec3 position, direction;
PxReal closest;
Sphere* hitSphere;
};
void step()
{
for(PxU32 hits=0; hits<10;)
{
// raycast in a random direction from the origin, and teleport the closest sphere we find
PxVec3 dir = PxVec3(rand01()-0.5f, rand01()-0.5f, rand01()-0.5f).getNormalized();
HitCallback callback(PxVec3(0), dir);
gBvh->raycast(PxVec3(0), dir, FLT_MAX, callback);
Sphere* hit = callback.hitSphere;
if(hit)
{
hit->resetPosition();
gBvh->update(hit->id, hit->getBounds());
hits++;
}
}
// run an incremental rebuild step in the background
gBvh->rebuildStep();
}
void cleanup()
{
gBvh->release();
gFoundation->release();
printf("SnippetSpatialIndex done.\n");
}
int snippetMain(int, const char*const*)
{
static const PxU32 frameCount = 100;
init();
for(PxU32 i=0; i<frameCount; i++)
step();
cleanup();
return 0;
}
| 29.350254 | 114 | 0.706849 | DoubleTT-Changan |
61f6326e14124616ca2b9fc6968570ca5e135f84 | 2,932 | cpp | C++ | src/util/util_env.cpp | Gcenx/DXVK-macOS | 9e5c61bf885ae1af0c506326d2b4cb5dabd4327c | [
"Zlib"
] | null | null | null | src/util/util_env.cpp | Gcenx/DXVK-macOS | 9e5c61bf885ae1af0c506326d2b4cb5dabd4327c | [
"Zlib"
] | null | null | null | src/util/util_env.cpp | Gcenx/DXVK-macOS | 9e5c61bf885ae1af0c506326d2b4cb5dabd4327c | [
"Zlib"
] | null | null | null | #include <array>
#include <cstdlib>
#include <filesystem>
#include <numeric>
#ifdef __linux__
#include <unistd.h>
#include <limits.h>
#endif
#include "util_env.h"
#include "./com/com_include.h"
namespace dxvk::env {
std::string getEnvVar(const char* name) {
#ifdef _WIN32
std::vector<WCHAR> result;
result.resize(MAX_PATH + 1);
DWORD len = ::GetEnvironmentVariableW(str::tows(name).c_str(), result.data(), MAX_PATH);
result.resize(len);
return str::fromws(result.data());
#else
const char* result = std::getenv(name);
return result ? result : "";
#endif
}
size_t matchFileExtension(const std::string& name, const char* ext) {
auto pos = name.find_last_of('.');
if (pos == std::string::npos)
return pos;
bool matches = std::accumulate(name.begin() + pos + 1, name.end(), true,
[&ext] (bool current, char a) {
if (a >= 'A' && a <= 'Z')
a += 'a' - 'A';
return current && *ext && a == *(ext++);
});
return matches ? pos : std::string::npos;
}
std::string getExeName() {
std::string fullPath = getExePath();
auto n = fullPath.find_last_of(env::PlatformDirSlash);
return (n != std::string::npos)
? fullPath.substr(n + 1)
: fullPath;
}
std::string getExeBaseName() {
auto exeName = getExeName();
#ifdef _WIN32
auto extp = matchFileExtension(exeName, "exe");
if (extp != std::string::npos)
exeName.erase(extp);
#endif
return exeName;
}
std::string getExePath() {
#if defined(_WIN32)
std::vector<WCHAR> exePath;
exePath.resize(MAX_PATH + 1);
DWORD len = ::GetModuleFileNameW(NULL, exePath.data(), MAX_PATH);
exePath.resize(len);
return str::fromws(exePath.data());
#elif defined(__linux__)
std::array<char, PATH_MAX> exePath = {};
size_t count = readlink("/proc/self/exe", exePath.data(), exePath.size());
return std::string(exePath.begin(), exePath.begin() + count);
#endif
}
void setThreadName(const std::string& name) {
#ifdef _WIN32
using SetThreadDescriptionProc = HRESULT (WINAPI *) (HANDLE, PCWSTR);
static auto proc = reinterpret_cast<SetThreadDescriptionProc>(
::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription"));
if (proc != nullptr) {
auto wideName = std::vector<WCHAR>(name.length() + 1);
str::tows(name.c_str(), wideName.data(), wideName.size());
(*proc)(::GetCurrentThread(), wideName.data());
}
#else
std::array<char, 16> posixName = {};
dxvk::str::strlcpy(posixName.data(), name.c_str(), 16);
::pthread_setname_np(pthread_self(), posixName.data());
#endif
}
bool createDirectory(const std::string& path) {
#ifdef _WIN32
WCHAR widePath[MAX_PATH];
str::tows(path.c_str(), widePath);
return !!CreateDirectoryW(widePath, nullptr);
#else
return std::filesystem::create_directories(path);
#endif
}
}
| 23.837398 | 92 | 0.632674 | Gcenx |
61f637fa2f200b9157965d01624ea87e69cb5358 | 805 | cpp | C++ | Codeforces/PetyaAndCountryyard.cpp | canis-majoris123/CompetitiveProgramming | be6c208abe6e0bd748c3bb0e715787506d73588d | [
"MIT"
] | null | null | null | Codeforces/PetyaAndCountryyard.cpp | canis-majoris123/CompetitiveProgramming | be6c208abe6e0bd748c3bb0e715787506d73588d | [
"MIT"
] | null | null | null | Codeforces/PetyaAndCountryyard.cpp | canis-majoris123/CompetitiveProgramming | be6c208abe6e0bd748c3bb0e715787506d73588d | [
"MIT"
] | null | null | null | //https://codeforces.com/contest/66/problem/B
#include<bits/stdc++.h>
using namespace std ;
#define aakriti long long int
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
aakriti number ;
cin >> number ;
aakriti arr[number], ans = 1 ;
for(int i = 0; i <number ; i++)
cin >> arr[i] ;
for(int i = 0; i < number; i++)
{
aakriti cnt = 1 ;
for(int j = i -1; j >= 0; j--)
{
if(arr[j] <= arr[j + 1])
cnt++;
else
break;
}
for(int j = i + 1; j < number; j++)
{
if(arr[j] <= arr[j - 1])
cnt++;
else
break;
}
ans = max(ans, cnt);
}
cout << ans ;
}
| 23 | 46 | 0.397516 | canis-majoris123 |
61fa6c8997b825a5c9ac510bf49ef6cacc267cfa | 26,507 | cpp | C++ | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/Kismet2/StructureEditorUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2016-10-01T21:35:52.000Z | 2016-10-01T21:35:52.000Z | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/Kismet2/StructureEditorUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | null | null | null | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/Kismet2/StructureEditorUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2021-04-27T08:48:33.000Z | 2021-04-27T08:48:33.000Z | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "UnrealEd.h"
#include "StructureEditorUtils.h"
#include "ScopedTransaction.h"
#include "Kismet2NameValidators.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "EdGraphSchema_K2.h"
#include "ObjectTools.h"
#include "Editor/UnrealEd/Public/Kismet2/CompilerResultsLog.h"
#include "Editor/UnrealEd/Public/EditorModes.h"
#include "Editor/KismetCompiler/Public/KismetCompilerModule.h"
#include "Toolkits/AssetEditorManager.h"
#include "Editor/DataTableEditor/Public/IDataTableEditor.h"
#include "Engine/UserDefinedStruct.h"
#include "Engine/DataTable.h"
#define LOCTEXT_NAMESPACE "Structure"
//////////////////////////////////////////////////////////////////////////
// FStructEditorManager
FStructureEditorUtils::FStructEditorManager& FStructureEditorUtils::FStructEditorManager::Get()
{
static TSharedRef< FStructEditorManager > EditorManager( new FStructEditorManager() );
return *EditorManager;
}
//////////////////////////////////////////////////////////////////////////
// FStructureEditorUtils
UUserDefinedStruct* FStructureEditorUtils::CreateUserDefinedStruct(UObject* InParent, FName Name, EObjectFlags Flags)
{
UUserDefinedStruct* Struct = NULL;
if (UserDefinedStructEnabled())
{
Struct = NewObject<UUserDefinedStruct>(InParent, Name, Flags);
check(Struct);
Struct->EditorData = NewObject<UUserDefinedStructEditorData>(Struct, NAME_None, RF_Transactional);
check(Struct->EditorData);
Struct->Guid = FGuid::NewGuid();
Struct->SetMetaData(TEXT("BlueprintType"), TEXT("true"));
Struct->Bind();
Struct->StaticLink(true);
Struct->Status = UDSS_Error;
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
AddVariable(Struct, FEdGraphPinType(K2Schema->PC_Boolean, FString(), NULL, false, false));
}
}
return Struct;
}
FStructureEditorUtils::EStructureError FStructureEditorUtils::IsStructureValid(const UScriptStruct* Struct, const UStruct* RecursionParent, FString* OutMsg)
{
check(Struct);
if (Struct == RecursionParent)
{
if (OutMsg)
{
*OutMsg = FString::Printf(*LOCTEXT("StructureRecursion", "Recursion: Struct cannot have itself as a member variable. Struct '%s', recursive parent '%s'").ToString(),
*Struct->GetFullName(), *RecursionParent->GetFullName());
}
return EStructureError::Recursion;
}
const UScriptStruct* FallbackStruct = GetFallbackStruct();
if (Struct == FallbackStruct)
{
if (OutMsg)
{
*OutMsg = LOCTEXT("StructureUnknown", "Struct unknown (deleted?)").ToString();
}
return EStructureError::FallbackStruct;
}
if (Struct->GetStructureSize() <= 0)
{
if (OutMsg)
{
*OutMsg = FString::Printf(*LOCTEXT("StructureSizeIsZero", "Struct '%s' is empty").ToString(), *Struct->GetFullName());
}
return EStructureError::EmptyStructure;
}
if (const UUserDefinedStruct* UDStruct = Cast<const UUserDefinedStruct>(Struct))
{
if (UDStruct->Status != EUserDefinedStructureStatus::UDSS_UpToDate)
{
if (OutMsg)
{
*OutMsg = FString::Printf(*LOCTEXT("StructureNotCompiled", "Struct '%s' is not compiled").ToString(), *Struct->GetFullName());
}
return EStructureError::NotCompiled;
}
for (const UProperty* P = Struct->PropertyLink; P; P = P->PropertyLinkNext)
{
const UStructProperty* StructProp = Cast<const UStructProperty>(P);
if (NULL == StructProp)
{
if (const UArrayProperty* ArrayProp = Cast<const UArrayProperty>(P))
{
StructProp = Cast<const UStructProperty>(ArrayProp->Inner);
}
}
if (StructProp)
{
if ((NULL == StructProp->Struct) || (FallbackStruct == StructProp->Struct))
{
if (OutMsg)
{
*OutMsg = FString::Printf(*LOCTEXT("StructureUnknownProperty", "Struct unknown (deleted?). Parent '%s' Property: '%s'").ToString(),
*Struct->GetFullName(), *StructProp->GetName());
}
return EStructureError::FallbackStruct;
}
FString OutMsgInner;
const EStructureError Result = IsStructureValid(
StructProp->Struct,
RecursionParent ? RecursionParent : Struct,
OutMsg ? &OutMsgInner : NULL);
if (EStructureError::Ok != Result)
{
if (OutMsg)
{
*OutMsg = FString::Printf(*LOCTEXT("StructurePropertyErrorTemplate", "Struct '%s' Property '%s' Error ( %s )").ToString(),
*Struct->GetFullName(), *StructProp->GetName(), *OutMsgInner);
}
return Result;
}
}
}
}
return EStructureError::Ok;
}
bool FStructureEditorUtils::CanHaveAMemberVariableOfType(const UUserDefinedStruct* Struct, const FEdGraphPinType& VarType, FString* OutMsg)
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
if ((VarType.PinCategory == K2Schema->PC_Struct) && Struct)
{
if (const UScriptStruct* SubCategoryStruct = Cast<const UScriptStruct>(VarType.PinSubCategoryObject.Get()))
{
const EStructureError Result = IsStructureValid(SubCategoryStruct, Struct, OutMsg);
if (EStructureError::Ok != Result)
{
return false;
}
}
else
{
if (OutMsg)
{
*OutMsg = LOCTEXT("StructureIncorrectStructType", "Incorrect struct type in a structure member variable.").ToString();
}
return false;
}
}
else if ((VarType.PinCategory == K2Schema->PC_Exec)
|| (VarType.PinCategory == K2Schema->PC_Wildcard)
|| (VarType.PinCategory == K2Schema->PC_MCDelegate)
|| (VarType.PinCategory == K2Schema->PC_Delegate))
{
if (OutMsg)
{
*OutMsg = LOCTEXT("StructureIncorrectTypeCategory", "Incorrect type for a structure member variable.").ToString();
}
return false;
}
else
{
const auto PinSubCategoryClass = Cast<const UClass>(VarType.PinSubCategoryObject.Get());
if (PinSubCategoryClass && PinSubCategoryClass->IsChildOf(UBlueprint::StaticClass()))
{
if (OutMsg)
{
*OutMsg = LOCTEXT("StructureUseBlueprintReferences", "Struct cannot use any blueprint references").ToString();
}
return false;
}
}
return true;
}
struct FMemberVariableNameHelper
{
static FName Generate(UUserDefinedStruct* Struct, const FString& NameBase, const FGuid Guid, FString* OutFriendlyName = NULL)
{
check(Struct);
FString Result;
if (!NameBase.IsEmpty())
{
const FName NewNameBase(*NameBase);
if (ensure(NewNameBase.IsValidXName(INVALID_OBJECTNAME_CHARACTERS)))
{
Result = NameBase;
}
}
if (Result.IsEmpty())
{
Result = TEXT("MemberVar");
}
const uint32 UniqueNameId = CastChecked<UUserDefinedStructEditorData>(Struct->EditorData)->GenerateUniqueNameIdForMemberVariable();
const FString FriendlyName = FString::Printf(TEXT("%s_%u"), *Result, UniqueNameId);
if (OutFriendlyName)
{
*OutFriendlyName = FriendlyName;
}
const FName NameResult = *FString::Printf(TEXT("%s_%s"), *FriendlyName, *Guid.ToString(EGuidFormats::Digits));
check(NameResult.IsValidXName(INVALID_OBJECTNAME_CHARACTERS));
return NameResult;
}
static FGuid GetGuidFromName(const FName Name)
{
const FString NameStr = Name.ToString();
const int32 GuidStrLen = 32;
if (NameStr.Len() > (GuidStrLen + 1))
{
const int32 UnderscoreIndex = NameStr.Len() - GuidStrLen - 1;
if (TCHAR('_') == NameStr[UnderscoreIndex])
{
const FString GuidStr = NameStr.Right(GuidStrLen);
FGuid Guid;
if (FGuid::ParseExact(GuidStr, EGuidFormats::Digits, Guid))
{
return Guid;
}
}
}
return FGuid();
}
};
bool FStructureEditorUtils::AddVariable(UUserDefinedStruct* Struct, const FEdGraphPinType& VarType)
{
if (Struct)
{
const FScopedTransaction Transaction( LOCTEXT("AddVariable", "Add Variable") );
ModifyStructData(Struct);
FString ErrorMessage;
if (!CanHaveAMemberVariableOfType(Struct, VarType, &ErrorMessage))
{
UE_LOG(LogBlueprint, Warning, TEXT("%s"), *ErrorMessage);
return false;
}
const FGuid Guid = FGuid::NewGuid();
FString DisplayName;
const FName VarName = FMemberVariableNameHelper::Generate(Struct, FString(), Guid, &DisplayName);
check(NULL == GetVarDesc(Struct).FindByPredicate(FStructureEditorUtils::FFindByNameHelper<FStructVariableDescription>(VarName)));
check(IsUniqueVariableDisplayName(Struct, DisplayName));
FStructVariableDescription NewVar;
NewVar.VarName = VarName;
NewVar.FriendlyName = DisplayName;
NewVar.SetPinType(VarType);
NewVar.VarGuid = Guid;
NewVar.bDontEditoOnInstance = false;
NewVar.bInvalidMember = false;
GetVarDesc(Struct).Add(NewVar);
OnStructureChanged(Struct);
return true;
}
return false;
}
bool FStructureEditorUtils::RemoveVariable(UUserDefinedStruct* Struct, FGuid VarGuid)
{
if(Struct)
{
const auto OldNum = GetVarDesc(Struct).Num();
const bool bAllowToMakeEmpty = false;
if (bAllowToMakeEmpty || (OldNum > 1))
{
const FScopedTransaction Transaction(LOCTEXT("RemoveVariable", "Remove Variable"));
ModifyStructData(Struct);
GetVarDesc(Struct).RemoveAll(FFindByGuidHelper<FStructVariableDescription>(VarGuid));
if (OldNum != GetVarDesc(Struct).Num())
{
OnStructureChanged(Struct);
return true;
}
}
else
{
UE_LOG(LogBlueprint, Log, TEXT("Member variable cannot be removed. User Defined Structure cannot be empty"));
}
}
return false;
}
bool FStructureEditorUtils::RenameVariable(UUserDefinedStruct* Struct, FGuid VarGuid, const FString& NewDisplayNameStr)
{
if (Struct)
{
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
if (VarDesc
&& !NewDisplayNameStr.IsEmpty()
&& FName(*NewDisplayNameStr).IsValidXName(INVALID_OBJECTNAME_CHARACTERS)
&& IsUniqueVariableDisplayName(Struct, NewDisplayNameStr))
{
const FScopedTransaction Transaction(LOCTEXT("RenameVariable", "Rename Variable"));
ModifyStructData(Struct);
VarDesc->FriendlyName = NewDisplayNameStr;
//>>> TEMPORARY it's more important to prevent changes in structs instances, than to have consistent names
if (GetGuidFromPropertyName(VarDesc->VarName).IsValid())
//<<< TEMPORARY
{
const FName NewName = FMemberVariableNameHelper::Generate(Struct, NewDisplayNameStr, VarGuid);
check(NULL == GetVarDesc(Struct).FindByPredicate(FFindByNameHelper<FStructVariableDescription>(NewName)))
VarDesc->VarName = NewName;
}
OnStructureChanged(Struct);
return true;
}
}
return false;
}
bool FStructureEditorUtils::ChangeVariableType(UUserDefinedStruct* Struct, FGuid VarGuid, const FEdGraphPinType& NewType)
{
if (Struct)
{
FString ErrorMessage;
if(!CanHaveAMemberVariableOfType(Struct, NewType, &ErrorMessage))
{
UE_LOG(LogBlueprint, Warning, TEXT("%s"), *ErrorMessage);
return false;
}
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
if(VarDesc)
{
const bool bChangedType = (VarDesc->ToPinType() != NewType);
if (bChangedType)
{
const FScopedTransaction Transaction(LOCTEXT("ChangeVariableType", "Change Variable Type"));
ModifyStructData(Struct);
VarDesc->VarName = FMemberVariableNameHelper::Generate(Struct, VarDesc->FriendlyName, VarDesc->VarGuid);
VarDesc->DefaultValue = FString();
VarDesc->SetPinType(NewType);
OnStructureChanged(Struct);
return true;
}
}
}
return false;
}
bool FStructureEditorUtils::ChangeVariableDefaultValue(UUserDefinedStruct* Struct, FGuid VarGuid, const FString& NewDefaultValue)
{
auto ValidateDefaultValue = [](const FStructVariableDescription& VarDesc, const FString& InNewDefaultValue) -> bool
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
const FEdGraphPinType PinType = VarDesc.ToPinType();
bool bResult = false;
//TODO: validation for values, that are not passed by string
if (PinType.PinCategory == K2Schema->PC_Text)
{
bResult = true;
}
else if ((PinType.PinCategory == K2Schema->PC_Object)
|| (PinType.PinCategory == K2Schema->PC_Interface)
|| (PinType.PinCategory == K2Schema->PC_Class)
|| (PinType.PinCategory == K2Schema->PC_AssetClass)
|| (PinType.PinCategory == K2Schema->PC_Asset))
{
// K2Schema->DefaultValueSimpleValidation finds an object, passed by path, invalid
bResult = true;
}
else
{
bResult = K2Schema->DefaultValueSimpleValidation(PinType, FString(), InNewDefaultValue, NULL, FText::GetEmpty());
}
return bResult;
};
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
if (VarDesc
&& (NewDefaultValue != VarDesc->DefaultValue)
&& ValidateDefaultValue(*VarDesc, NewDefaultValue))
{
bool bAdvancedValidation = true;
if (!NewDefaultValue.IsEmpty())
{
const auto Property = FindField<UProperty>(Struct, VarDesc->VarName);
FStructOnScope StructDefaultMem(Struct);
bAdvancedValidation = StructDefaultMem.IsValid() && Property &&
FBlueprintEditorUtils::PropertyValueFromString(Property, NewDefaultValue, StructDefaultMem.GetStructMemory());
}
if (bAdvancedValidation)
{
const FScopedTransaction Transaction(LOCTEXT("ChangeVariableDefaultValue", "Change Variable Default Value"));
ModifyStructData(Struct);
VarDesc->DefaultValue = NewDefaultValue;
OnStructureChanged(Struct);
return true;
}
}
return false;
}
bool FStructureEditorUtils::IsUniqueVariableDisplayName(const UUserDefinedStruct* Struct, const FString& DisplayName)
{
if(Struct)
{
for (auto& VarDesc : GetVarDesc(Struct))
{
if (VarDesc.FriendlyName == DisplayName)
{
return false;
}
}
return true;
}
return false;
}
FString FStructureEditorUtils::GetVariableDisplayName(const UUserDefinedStruct* Struct, FGuid VarGuid)
{
const auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
return VarDesc ? VarDesc->FriendlyName : FString();
}
bool FStructureEditorUtils::UserDefinedStructEnabled()
{
static FBoolConfigValueHelper UseUserDefinedStructure(TEXT("UserDefinedStructure"), TEXT("bUseUserDefinedStructure"));
return UseUserDefinedStructure;
}
void FStructureEditorUtils::RecreateDefaultInstanceInEditorData(UUserDefinedStruct* Struct)
{
auto StructEditorData = Struct ? CastChecked<UUserDefinedStructEditorData>(Struct->EditorData) : nullptr;
if (StructEditorData)
{
StructEditorData->RecreateDefaultInstance();
}
}
bool FStructureEditorUtils::Fill_MakeStructureDefaultValue(const UUserDefinedStruct* Struct, uint8* StructData)
{
bool bResult = true;
if (Struct && StructData)
{
auto StructEditorData = CastChecked<UUserDefinedStructEditorData>(Struct->EditorData);
const uint8* DefaultInstance = StructEditorData->GetDefaultInstance();
if (DefaultInstance)
{
Struct->CopyScriptStruct(StructData, DefaultInstance);
}
else
{
bResult = false;
}
}
return bResult;
}
bool FStructureEditorUtils::Fill_MakeStructureDefaultValue(const UProperty* Property, uint8* PropertyData)
{
bool bResult = true;
if (const UStructProperty* StructProperty = Cast<const UStructProperty>(Property))
{
if (const UUserDefinedStruct* InnerStruct = Cast<const UUserDefinedStruct>(StructProperty->Struct))
{
bResult &= Fill_MakeStructureDefaultValue(InnerStruct, PropertyData);
}
}
else if (const UArrayProperty* ArrayProp = Cast<const UArrayProperty>(Property))
{
StructProperty = Cast<const UStructProperty>(ArrayProp->Inner);
const UUserDefinedStruct* InnerStruct = StructProperty ? Cast<const UUserDefinedStruct>(StructProperty->Struct) : NULL;
if(InnerStruct)
{
FScriptArrayHelper ArrayHelper(ArrayProp, PropertyData);
for (int32 Index = 0; Index < ArrayHelper.Num(); ++Index)
{
uint8* const ValuePtr = ArrayHelper.GetRawPtr(Index);
bResult &= Fill_MakeStructureDefaultValue(InnerStruct, ValuePtr);
}
}
}
return bResult;
}
void FStructureEditorUtils::CompileStructure(UUserDefinedStruct* Struct)
{
if (Struct)
{
IKismetCompilerInterface& Compiler = FModuleManager::LoadModuleChecked<IKismetCompilerInterface>(KISMET_COMPILER_MODULENAME);
FCompilerResultsLog Results;
Compiler.CompileStructure(Struct, Results);
}
}
void FStructureEditorUtils::OnStructureChanged(UUserDefinedStruct* Struct)
{
if (Struct)
{
Struct->Status = EUserDefinedStructureStatus::UDSS_Dirty;
CompileStructure(Struct);
Struct->MarkPackageDirty();
}
}
//TODO: Move to blueprint utils
void FStructureEditorUtils::RemoveInvalidStructureMemberVariableFromBlueprint(UBlueprint* Blueprint)
{
if (Blueprint)
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
const UScriptStruct* FallbackStruct = GetFallbackStruct();
FString DislpayList;
TArray<FName> ZombieMemberNames;
for (int32 VarIndex = 0; VarIndex < Blueprint->NewVariables.Num(); ++VarIndex)
{
const FBPVariableDescription& Var = Blueprint->NewVariables[VarIndex];
if (Var.VarType.PinCategory == K2Schema->PC_Struct)
{
const UScriptStruct* ScriptStruct = Cast<const UScriptStruct>(Var.VarType.PinSubCategoryObject.Get());
const bool bInvalidStruct = (NULL == ScriptStruct) || (FallbackStruct == ScriptStruct);
if (bInvalidStruct)
{
DislpayList += Var.FriendlyName.IsEmpty() ? Var.VarName.ToString() : Var.FriendlyName;
DislpayList += TEXT("\n");
ZombieMemberNames.Add(Var.VarName);
}
}
}
if (ZombieMemberNames.Num())
{
auto Response = FMessageDialog::Open(
EAppMsgType::OkCancel,
FText::Format(
LOCTEXT("RemoveInvalidStructureMemberVariable_Msg", "The following member variables in blueprint '{0}' have invalid type. Would you like to remove them? \n\n{1}"),
FText::FromString(Blueprint->GetFullName()),
FText::FromString(DislpayList)
));
check((EAppReturnType::Ok == Response) || (EAppReturnType::Cancel == Response));
if (EAppReturnType::Ok == Response)
{
Blueprint->Modify();
for (auto NameIter = ZombieMemberNames.CreateConstIterator(); NameIter; ++NameIter)
{
const FName Name = *NameIter;
Blueprint->NewVariables.RemoveAll(FFindByNameHelper<FBPVariableDescription>(Name)); //TODO: Add RemoveFirst to TArray
FBlueprintEditorUtils::RemoveVariableNodes(Blueprint, Name);
}
}
}
}
}
TArray<FStructVariableDescription>& FStructureEditorUtils::GetVarDesc(UUserDefinedStruct* Struct)
{
check(Struct);
return CastChecked<UUserDefinedStructEditorData>(Struct->EditorData)->VariablesDescriptions;
}
const TArray<FStructVariableDescription>& FStructureEditorUtils::GetVarDesc(const UUserDefinedStruct* Struct)
{
check(Struct);
return CastChecked<const UUserDefinedStructEditorData>(Struct->EditorData)->VariablesDescriptions;
}
FString FStructureEditorUtils::GetTooltip(const UUserDefinedStruct* Struct)
{
const auto StructEditorData = Struct ? Cast<const UUserDefinedStructEditorData>(Struct->EditorData) : NULL;
return StructEditorData ? StructEditorData->ToolTip : FString();
}
bool FStructureEditorUtils::ChangeTooltip(UUserDefinedStruct* Struct, const FString& InTooltip)
{
auto StructEditorData = Struct ? Cast<UUserDefinedStructEditorData>(Struct->EditorData) : NULL;
if (StructEditorData && (InTooltip != StructEditorData->ToolTip))
{
const FScopedTransaction Transaction(LOCTEXT("ChangeTooltip", "Change UDS Tooltip"));
StructEditorData->Modify();
StructEditorData->ToolTip = InTooltip;
Struct->SetMetaData(FBlueprintMetadata::MD_Tooltip, *StructEditorData->ToolTip);
return true;
}
return false;
}
FString FStructureEditorUtils::GetVariableTooltip(const UUserDefinedStruct* Struct, FGuid VarGuid)
{
const auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
return VarDesc ? VarDesc->ToolTip : FString();
}
bool FStructureEditorUtils::ChangeVariableTooltip(UUserDefinedStruct* Struct, FGuid VarGuid, const FString& InTooltip)
{
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
if (VarDesc && (InTooltip != VarDesc->ToolTip))
{
const FScopedTransaction Transaction(LOCTEXT("ChangeVariableTooltip", "Change UDS Variable Tooltip"));
ModifyStructData(Struct);
VarDesc->ToolTip = InTooltip;
auto Property = FindField<UProperty>(Struct, VarDesc->VarName);
if (Property)
{
Property->SetMetaData(FBlueprintMetadata::MD_Tooltip, *VarDesc->ToolTip);
}
return true;
}
return false;
}
bool FStructureEditorUtils::ChangeEditableOnBPInstance(UUserDefinedStruct* Struct, FGuid VarGuid, bool bInIsEditable)
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
const bool bNewDontEditoOnInstance = !bInIsEditable;
if (VarDesc && (bNewDontEditoOnInstance != VarDesc->bDontEditoOnInstance))
{
const FScopedTransaction Transaction(LOCTEXT("ChangeVariableOnBPInstance", "Change variable editable on BP instance"));
ModifyStructData(Struct);
VarDesc->bDontEditoOnInstance = bNewDontEditoOnInstance;
OnStructureChanged(Struct);
return true;
}
return false;
}
bool FStructureEditorUtils::MoveVariable(UUserDefinedStruct* Struct, FGuid VarGuid, EMoveDirection MoveDirection)
{
if (Struct)
{
const bool bMoveUp = (EMoveDirection::MD_Up == MoveDirection);
auto& DescArray = GetVarDesc(Struct);
const int32 InitialIndex = bMoveUp ? 1 : 0;
const int32 IndexLimit = DescArray.Num() - (bMoveUp ? 0 : 1);
for (int32 Index = InitialIndex; Index < IndexLimit; ++Index)
{
if (DescArray[Index].VarGuid == VarGuid)
{
const FScopedTransaction Transaction(LOCTEXT("ReorderVariables", "Varaibles reordered"));
ModifyStructData(Struct);
DescArray.Swap(Index, Index + (bMoveUp ? -1 : 1));
OnStructureChanged(Struct);
return true;
}
}
}
return false;
}
void FStructureEditorUtils::ModifyStructData(UUserDefinedStruct* Struct)
{
UUserDefinedStructEditorData* EditorData = Struct ? Cast<UUserDefinedStructEditorData>(Struct->EditorData) : NULL;
ensure(EditorData);
if (EditorData)
{
EditorData->Modify();
}
}
bool FStructureEditorUtils::CanEnableMultiLineText(const UUserDefinedStruct* Struct, FGuid VarGuid)
{
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
if (VarDesc)
{
auto Property = FindField<UProperty>(Struct, VarDesc->VarName);
if (Property)
{
// Can only set multi-line text on string and text properties
return Property->IsA(UStrProperty::StaticClass())
|| Property->IsA(UTextProperty::StaticClass());
}
}
return false;
}
bool FStructureEditorUtils::ChangeMultiLineTextEnabled(UUserDefinedStruct* Struct, FGuid VarGuid, bool bIsEnabled)
{
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
if (CanEnableMultiLineText(Struct, VarGuid) && VarDesc->bEnableMultiLineText != bIsEnabled)
{
const FScopedTransaction Transaction(LOCTEXT("ChangeMultiLineTextEnabled", "Change Multi-line Text Enabled"));
ModifyStructData(Struct);
VarDesc->bEnableMultiLineText = bIsEnabled;
auto Property = FindField<UProperty>(Struct, VarDesc->VarName);
if (Property)
{
if (VarDesc->bEnableMultiLineText)
{
Property->SetMetaData("MultiLine", TEXT("true"));
}
else
{
Property->RemoveMetaData("MultiLine");
}
}
return true;
}
return false;
}
bool FStructureEditorUtils::IsMultiLineTextEnabled(const UUserDefinedStruct* Struct, FGuid VarGuid)
{
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
if (CanEnableMultiLineText(Struct, VarGuid))
{
return VarDesc->bEnableMultiLineText;
}
return false;
}
bool FStructureEditorUtils::CanEnable3dWidget(const UUserDefinedStruct* Struct, FGuid VarGuid)
{
const auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
const auto PropertyStruct = VarDesc ? Cast<const UStruct>(VarDesc->SubCategoryObject.Get()) : NULL;
return FEdMode::CanCreateWidgetForStructure(PropertyStruct);
}
bool FStructureEditorUtils::Change3dWidgetEnabled(UUserDefinedStruct* Struct, FGuid VarGuid, bool bIsEnabled)
{
auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
const auto PropertyStruct = VarDesc ? Cast<const UStruct>(VarDesc->SubCategoryObject.Get()) : NULL;
if (FEdMode::CanCreateWidgetForStructure(PropertyStruct) && (VarDesc->bEnable3dWidget != bIsEnabled))
{
const FScopedTransaction Transaction(LOCTEXT("Change3dWidgetEnabled", "Change 3d Widget Enabled"));
ModifyStructData(Struct);
VarDesc->bEnable3dWidget = bIsEnabled;
auto Property = FindField<UProperty>(Struct, VarDesc->VarName);
if (Property)
{
if (VarDesc->bEnable3dWidget)
{
Property->SetMetaData(FEdMode::MD_MakeEditWidget, TEXT("true"));
}
else
{
Property->RemoveMetaData(FEdMode::MD_MakeEditWidget);
}
}
return true;
}
return false;
}
bool FStructureEditorUtils::Is3dWidgetEnabled(const UUserDefinedStruct* Struct, FGuid VarGuid)
{
const auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
const auto PropertyStruct = VarDesc ? Cast<const UStruct>(VarDesc->SubCategoryObject.Get()) : NULL;
return VarDesc && VarDesc->bEnable3dWidget && FEdMode::CanCreateWidgetForStructure(PropertyStruct);
}
FGuid FStructureEditorUtils::GetGuidForProperty(const UProperty* Property)
{
auto UDStruct = Property ? Cast<const UUserDefinedStruct>(Property->GetOwnerStruct()) : NULL;
auto VarDesc = UDStruct ? GetVarDesc(UDStruct).FindByPredicate(FFindByNameHelper<FStructVariableDescription>(Property->GetFName())) : NULL;
return VarDesc ? VarDesc->VarGuid : FGuid();
}
UProperty* FStructureEditorUtils::GetPropertyByGuid(const UUserDefinedStruct* Struct, const FGuid VarGuid)
{
const auto VarDesc = GetVarDescByGuid(Struct, VarGuid);
return VarDesc ? FindField<UProperty>(Struct, VarDesc->VarName) : NULL;
}
FGuid FStructureEditorUtils::GetGuidFromPropertyName(const FName Name)
{
return FMemberVariableNameHelper::GetGuidFromName(Name);
}
struct FReinstanceDataTableHelper
{
// TODO: shell we cache the dependency?
static TArray<UDataTable*> GetTablesDependentOnStruct(UUserDefinedStruct* Struct)
{
TArray<UDataTable*> Result;
if (Struct)
{
TArray<UObject*> DataTables;
GetObjectsOfClass(UDataTable::StaticClass(), DataTables);
for (auto DataTableObj : DataTables)
{
auto DataTable = Cast<UDataTable>(DataTableObj);
if (DataTable && (Struct == DataTable->RowStruct))
{
Result.Add(DataTable);
}
}
}
return Result;
}
};
void FStructureEditorUtils::BroadcastPreChange(UUserDefinedStruct* Struct)
{
FStructureEditorUtils::FStructEditorManager::Get().PreChange(Struct, EStructureEditorChangeInfo::Changed);
auto DataTables = FReinstanceDataTableHelper::GetTablesDependentOnStruct(Struct);
for (auto DataTable : DataTables)
{
DataTable->CleanBeforeStructChange();
}
}
void FStructureEditorUtils::BroadcastPostChange(UUserDefinedStruct* Struct)
{
auto DataTables = FReinstanceDataTableHelper::GetTablesDependentOnStruct(Struct);
for (auto DataTable : DataTables)
{
DataTable->RestoreAfterStructChange();
}
FStructureEditorUtils::FStructEditorManager::Get().PostChange(Struct, EStructureEditorChangeInfo::Changed);
}
#undef LOCTEXT_NAMESPACE
| 31.295159 | 170 | 0.74154 | armroyce |
61fb39d1e35e1a1b445ad7aef886ef04bdf8e3b9 | 4,017 | cpp | C++ | source/A344279.cpp | SoumyadeepDhar/IntegerSequences | e2b08c8fa1fdc53e4a8807e3fb1ecccd179fe864 | [
"MIT"
] | null | null | null | source/A344279.cpp | SoumyadeepDhar/IntegerSequences | e2b08c8fa1fdc53e4a8807e3fb1ecccd179fe864 | [
"MIT"
] | null | null | null | source/A344279.cpp | SoumyadeepDhar/IntegerSequences | e2b08c8fa1fdc53e4a8807e3fb1ecccd179fe864 | [
"MIT"
] | null | null | null | /*
* A344279.cpp
*
* Created on: 14-May-2021
*
* Author: Soumyadeep Dhar
*
* A344279: Numbers a(n)=m such that |m| is the smallest, k=n*m and r=(n^2+1)*m
* for two quadratic equations of the form t^2+k*t+r = 0 and t^2+r*t+k^2 = 0
* have non-zero integer roots, where k is the coefficient of t and r is the
* constant in first equation, which has non-zero roots p and q
* (i.e., {k, r, p, q} ∈ ℤ≠, k=p+q and r=p*q). Also r is the coefficient of t
* and k^2 is the constant in second equation, which has non-zero roots u and v
* (i.e., {r, k, u, v} ∈ ℤ≠, r=u+v and k^2=u*v).
*
* Example: -1, -4, -1, -16, 9, -36, 5, -1, -81, -100, -121, -4, 9, -196, -225,
* -256, 8, 5, -361, -400, -1, -484, -529, -576, -625, -676, -729, -784,
* -841, -900, -961, -1024, -9, 9, -1225, -1296, -1369, -1444, -1521,
* -1600, -1681, -1764, -1849, -1936, -2025, -2116, 5, -2304, -2401, -2500
*
* A344279: https://oeis.org/A344279/b344279.txt
*
* Sequence Author: Soumyadeep Dhar, May 14, 2021
*
*/
#include <map>
#include <tuple>
#include <iomanip>
#include "largeint.h"
#include "processor.h"
using LargeInteger = ns::dn::li::LargeInt;
using LargeIntegerSequence = ns::dn::is::IntegerSequenceProcessor<ns::dn::is::A344279>;
// Process input data to generate next elements of the sequence
template <>
unsigned int LargeIntegerSequence::generate()
{
int _count = 1;
std::pair<unsigned int, std::string> _element;
// keep result values
std::map<long long int, std::tuple
< long long int
, long long int
, long long int
, long long int
, long long int
, long long int
, long long int
, long long int>> _results;
for (long long int n = 1; n <= 225; n++)
{
// Check all numbers upto 100
for (long long int c = 1; c <= 250000; c++)
{
bool isFound = false;
for (auto s : {1, -1})
{
// Find 'a * b' as initial expected 'm'
long long int m = s*c*(n*n + 1);
// Find 'a * b' as initial expected 'k'
long long int k = s*c*n;
// Get k^2 value
long long int kk = (k * k);
// Find possible (a, b) as root of the equation
// x^2 -kx + m (where a + b = k and a * b = m)
long long int a = (k + sqrt(kk - (4 * m))) / 2;
long long int b = k - a;
// Ignore non integer roots
if(m != (a * b)) continue;
// For all possible roots of the equation
// x^2 - mx + k^2 (where x + y = m and x * y = k^2)
long long int y = (m + sqrt((m * m) - (4 * kk))) / 2;
long long int x = m - y;
// If valid roots found
if (kk != (x * y)) continue;
// Store result
_results[n] = std::make_tuple(c*s, k, m, kk, a, b, x, y);
// Print output results
std::cout << " " << std::setw(9) << n;
std::cout << " " << std::setw(9) << c*s;
std::cout << " " << std::setw(9) << k;
std::cout << " " << std::setw(9) << m;
std::cout << " " << std::setw(9) << kk;
std::cout << " " << std::setw(9) << a;
std::cout << " " << std::setw(9) << b;
std::cout << " " << std::setw(9) << x;
std::cout << " " << std::setw(9) << y << std::endl;
// Mark solution found
isFound = true;
break;
}
// No need to search further as result already found
if(isFound) break;
}
}
// Store shorted result data
_count = 1;
for (auto _x : _results)
{
_element.first = _count;
_element.second = std::to_string(std::get<0>(_x.second));
// Write output data
_ouWriter << _element;
// Update element count
_count++;
}
return 0;
}
int main()
{
// Initialize sequence
LargeIntegerSequence seqA344279("../data/oeis/b000290.txt", "../data/oeis/b000290.txt", "../data/A344279.txt");
// Generate sequence
seqA344279.generate();
return 0;
} | 29.108696 | 113 | 0.52004 | SoumyadeepDhar |