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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8f80c838ff86b3a778f6b22384ef7d21882094b1 | 688 | cpp | C++ | 20160813_ABC043_Complete/c.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | 20160813_ABC043_Complete/c.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | 20160813_ABC043_Complete/c.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | // インクルード
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <iomanip>
// 名前空間省略
using namespace std;
// メイン
int main()
{
// 入出力の高速化
ios::sync_with_stdio(false);
cin.tie(nullptr);
// 表示精度変更
cout << fixed << setprecision(16);
int n;
cin >> n;
vector<int> a(n);
for(int i=0;i<n;i++) cin >> a[i];
int ans=(1<<30);
// -100 ~ 100まで全探索
for(int i=-100;i<=100;i++){
int sum=0;
// コスト計算
for(int j=0;j<n;j++){
sum += (a[j]-i)*(a[j]-i);
}
// 最小値を保存
ans = min(ans,sum);
}
cout << ans << endl;
}
| 15.636364 | 38 | 0.472384 | miyalab |
8f8383e60bbdfaf947e7ee28a2e9f7032078d580 | 10,370 | cpp | C++ | src/ui/widget/SourceCodeLocationWidget.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/ui/widget/SourceCodeLocationWidget.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/ui/widget/SourceCodeLocationWidget.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | #include "SourceCodeLocationWidget.h"
#include "application/AppSettings.h"
#include "application/GlobalConstants.h"
#include "ui/ToastNotificationWidget.h"
#include "util/NetworkUtils.h"
#include "view/StandardItemView.h"
SourceCodeLocationWidget::SourceCodeLocationWidget(QWidget *parent)
: QWidget(parent)
{
setupUi();
setupSignalsAndSlots();
loadSettings();
}
void SourceCodeLocationWidget::setValues(const QString &szProjectName, const QString &szSourceLocation)
{
lineEditProject->setText(szProjectName);
lineEditSourceLocation->setText(szSourceLocation);
}
QStringList SourceCodeLocationWidget::getProjectNames()
{
QStringList szaProjectNames;
szaProjectNames.reserve(tableModelLocations->rowCount());
for (int nRow = 0; nRow < tableModelLocations->rowCount(); ++nRow) {
const QString szProjectName = tableModelLocations->item(nRow, SourceCodeLocationsEnum::COLUMN_PROJECT_NAME)->text();
if (szaProjectNames.contains(szProjectName) == false) {
szaProjectNames.append(szProjectName);
}
}
return szaProjectNames;
}
void SourceCodeLocationWidget::buttonSaveLocationPushed(bool checked)
{
Q_UNUSED(checked)
const QString szProjectName = lineEditProject->text();
const QString szSourceLocation = lineEditSourceLocation->text();
if (szSourceLocation.isEmpty() == true) {
ToastNotificationWidget::showMessage(this, tr("Please add source location"), ToastNotificationWidget::ERROR, 2000);
return;
}
if (tableModelLocations->indexOf(szProjectName, SourceCodeLocationsEnum::COLUMN_PROJECT_NAME) == -1) {
emit newProjectAdded(szProjectName);
}
int nRow;
while ((nRow = tableModelLocations->indexOf(szSourceLocation, SourceCodeLocationsEnum::COLUMN_SOURCE_PATH)) != -1) {
//found entry with same path
if (tableModelLocations->item(nRow, SourceCodeLocationsEnum::COLUMN_PROJECT_NAME)->text() == szProjectName) {
//entry also has same project name
ToastNotificationWidget::showMessage(this, tr("Combination Project/Source already exists"), ToastNotificationWidget::INFO, 2000);
return;
}
}
//NOTE The same location can be added to different project without being a global location, so this is not checked. Ex: adding a location to 2 projects, but not to a 3rd one
QList<QStandardItem *> myTableRow;
myTableRow.append(new QStandardItem(szProjectName));
myTableRow.append(new QStandardItem(szSourceLocation));
tableModelLocations->appendRow(myTableRow);
saveSettings();
}
void SourceCodeLocationWidget::buttonPickLocationPushed(bool bState)
{
Q_UNUSED(bState)
QFileDialog *myFileDialog = new QFileDialog(this);
myFileDialog->setAcceptMode(QFileDialog::AcceptOpen);
myFileDialog->setFileMode(QFileDialog::Directory);
myFileDialog->setOption(QFileDialog::ShowDirsOnly, true);
myFileDialog->open();
QObject::connect(myFileDialog, &QFileDialog::fileSelected,
this, [ myFileDialog, this ](const QString & szFolder) {
lineEditSourceLocation->setText(szFolder);
myFileDialog->deleteLater();
}
);
}
void SourceCodeLocationWidget::setupUi()
{
int nCurrentRow = 0;
QGridLayout *myMainLayout = new QGridLayout(this);
myMainLayout->setContentsMargins(10, 10, 10, 10);
myMainLayout->setSpacing(20);
QHBoxLayout *myEditsLayout = new QHBoxLayout();
{
lineEditProject = new QLineEdit(this);
lineEditProject->setPlaceholderText(tr("Project"));
lineEditProject->setToolTip(tr("Project Name"));
lineEditSourceLocation = new QLineEdit(this);
lineEditSourceLocation->setPlaceholderText(tr("Source path"));
lineEditSourceLocation->setToolTip(tr("Source code path"));
pushButtonPickLocation = new QPushButton(this);
pushButtonPickLocation->setCheckable(false);
pushButtonPickLocation->setText(tr("Pick path"));
pushButtonSaveLocation = new QPushButton(this);
pushButtonSaveLocation->setCheckable(false);
pushButtonSaveLocation->setText(tr("Save"));
connect(lineEditProject, SIGNAL(returnPressed()), pushButtonSaveLocation, SLOT(click()));
connect(lineEditSourceLocation, SIGNAL(returnPressed()), pushButtonSaveLocation, SLOT(click()));
myEditsLayout->addWidget(lineEditProject);
myEditsLayout->addWidget(lineEditSourceLocation);
myEditsLayout->addWidget(pushButtonPickLocation);
myEditsLayout->addWidget(pushButtonSaveLocation);
}
{
tableModelLocations = new SourceCodeLocationsModel(this);
tableModelLocations->setAllowDuplicates(false);
// tableModelLocations->setSortColumn(SourceCodeLocationsEnum::COLUMN_PROJECT_NAME);
tableViewLocations = new StandardItemView(this);
tableViewLocations->setAlternatingRowColors(true);
tableViewLocations->setModel(tableModelLocations);
tableViewLocations->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
// tableViewLocations->setSortingEnabled(true);
tableViewLocations->setShowGrid(true);
tableViewLocations->setContextMenuPolicy(Qt::CustomContextMenu);
tableViewLocations->setSelectionMode(QAbstractItemView::ExtendedSelection);
tableViewLocations->setSelectionBehavior(QAbstractItemView::SelectRows);
tableViewLocations->setWordWrap(false);
tableViewLocations->setDragDropMode(QAbstractItemView::InternalMove); //TODO //allows reordering
//Horizontal
tableViewLocations->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
tableViewLocations->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
tableViewLocations->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
tableViewLocations->horizontalHeader()->setHighlightSections(false);
tableViewLocations->horizontalHeader()->setStretchLastSection(true);
//Vertical
tableViewLocations->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
tableViewLocations->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
tableViewLocations->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
tableViewLocations->verticalHeader()->setVisible(false);
}
myMainLayout->addLayout(myEditsLayout, nCurrentRow, 0);
++nCurrentRow;
// myMainLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed), 0, 1);
myMainLayout->addWidget(tableViewLocations, nCurrentRow, 0, 2, -1);
this->setLayout(myMainLayout);
this->setAttribute(Qt::WA_DeleteOnClose, false);
// this->setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
// this->resize(800, 600); //TODO doesn't work with large font sizes
// this->setWindowIcon(QIcon(":/icons/themes/icons/appIcon.svg"));
// this->setWindowTitle(tr("Source Code Location Manager"));
// this->hide(); //using embed mode in OptionsWidget. May change in the future
}
void SourceCodeLocationWidget::setupSignalsAndSlots()
{
connect(pushButtonPickLocation, &QPushButton::clicked,
this, &SourceCodeLocationWidget::buttonPickLocationPushed);
connect(pushButtonSaveLocation, &QPushButton::clicked,
this, &SourceCodeLocationWidget::buttonSaveLocationPushed);
}
void SourceCodeLocationWidget::loadSettings()
{
const QString szSourceLocations = AppSettings::getValue(AppSettings::KEY_CODE_SOURCE_LOCATION).toString();
if (szSourceLocations.isEmpty() == false) {
const QStringList szaSourceLocations = szSourceLocations.split(GlobalConstants::SEPARATOR_SETTINGS_LIST);
if (szSourceLocations.contains(GlobalConstants::SEPARATOR_SETTINGS_LIST_2) == true) {
for (int nRow = 0; nRow < szaSourceLocations.size(); ++nRow) {
const QStringList szaSourceLocation = szaSourceLocations.at(nRow).split(GlobalConstants::SEPARATOR_SETTINGS_LIST_2);
if (szaSourceLocation.size() != SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS) {
ToastNotificationWidget::showMessage(this, tr("Could not parse source location: ") + szaSourceLocations.at(nRow), ToastNotificationWidget::ERROR, 3000);
continue;
}
QList<QStandardItem *> myTableRow;
for (int nCol = 0; nCol < SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS; ++nCol) {
myTableRow.append(new QStandardItem(szaSourceLocation.at(nCol)));
}
tableModelLocations->appendRow(myTableRow);
}
} else { //parse first data type, containing only source locations
for (int nRow = 0; nRow < szaSourceLocations.size(); ++nRow) {
QList<QStandardItem *> myTableRow;
myTableRow.append(new QStandardItem());
myTableRow.append(new QStandardItem(szaSourceLocations.at(nRow)));
tableModelLocations->appendRow(myTableRow);
}
}
}
}
void SourceCodeLocationWidget::saveSettings()
{
QStringList szaSourceLocations;
szaSourceLocations.reserve(tableModelLocations->rowCount());
for (int nRow = 0; nRow < tableModelLocations->rowCount(); ++nRow) {
QStringList szaSourceLocation;
for (int nColumn = 0; nColumn < SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS; ++nColumn) {
const QString szText = tableModelLocations->item(nRow, nColumn)->text();
szaSourceLocation.append(szText);
}
szaSourceLocations.append(szaSourceLocation.join(GlobalConstants::SEPARATOR_SETTINGS_LIST_2));
}
AppSettings::setValue(AppSettings::KEY_CODE_SOURCE_LOCATION, szaSourceLocations.join(GlobalConstants::SEPARATOR_SETTINGS_LIST));
}
void SourceCodeLocationWidget::hideEvent(QHideEvent *event)
{
emit aboutToHide();
QWidget::hideEvent(event);
saveSettings();
lineEditProject->clear();
lineEditSourceLocation->clear();
}
void SourceCodeLocationWidget::closeEvent(QCloseEvent *event)
{
emit aboutToHide();
QWidget::closeEvent(event);
}
| 38.265683 | 177 | 0.708486 | vitorjna |
8f8473751b532346aab55db7660f6b0ceecd08a1 | 24,939 | cpp | C++ | components/scream/src/share/atm_process/atmosphere_process.cpp | ambrad/scream | 52da60f65e870b8a3994bdbf4a6022fdcac7cab5 | [
"BSD-3-Clause"
] | null | null | null | components/scream/src/share/atm_process/atmosphere_process.cpp | ambrad/scream | 52da60f65e870b8a3994bdbf4a6022fdcac7cab5 | [
"BSD-3-Clause"
] | null | null | null | components/scream/src/share/atm_process/atmosphere_process.cpp | ambrad/scream | 52da60f65e870b8a3994bdbf4a6022fdcac7cab5 | [
"BSD-3-Clause"
] | null | null | null | #include "share/atm_process/atmosphere_process.hpp"
#include "share/util/scream_timing.hpp"
#include "ekat/ekat_assert.hpp"
#include <set>
#include <stdexcept>
#include <string>
namespace scream
{
AtmosphereProcess::
AtmosphereProcess (const ekat::Comm& comm, const ekat::ParameterList& params)
: m_comm (comm)
, m_params (params)
{
if (m_params.isParameter("Logger")) {
m_atm_logger = m_params.get<std::shared_ptr<logger_t>>("Logger");
} else {
// Create a console-only logger, that logs all ranks
using namespace ekat::logger;
using logger_impl_t = Logger<LogNoFile,LogAllRanks>;
m_atm_logger = std::make_shared<logger_impl_t>("",LogLevel::trace,m_comm);
}
if (m_params.isParameter("Number of Subcycles")) {
m_num_subcycles = m_params.get<int>("Number of Subcycles");
}
EKAT_REQUIRE_MSG (m_num_subcycles>0,
"Error! Invalid number of subcycles in param list " + m_params.name() + ".\n"
" - Num subcycles: " + std::to_string(m_num_subcycles) + "\n");
m_timer_prefix = m_params.get<std::string>("Timer Prefix","EAMxx::");
}
void AtmosphereProcess::initialize (const TimeStamp& t0, const RunType run_type) {
if (this->type()!=AtmosphereProcessType::Group) {
start_timer (m_timer_prefix + this->name() + "::init");
}
set_fields_and_groups_pointers();
m_time_stamp = t0;
initialize_impl(run_type);
if (this->type()!=AtmosphereProcessType::Group) {
stop_timer (m_timer_prefix + this->name() + "::init");
}
}
void AtmosphereProcess::run (const int dt) {
start_timer (m_timer_prefix + this->name() + "::run");
if (m_params.get("Enable Precondition Checks", true)) {
// Run 'pre-condition' property checks stored in this AP
run_precondition_checks();
}
EKAT_REQUIRE_MSG ( (dt % m_num_subcycles)==0,
"Error! The number of subcycle iterations does not exactly divide the time step.\n"
" - Atm proc name: " + this->name() + "\n"
" - Num subcycles: " + std::to_string(m_num_subcycles) + "\n"
" - Time step : " + std::to_string(dt) + "\n");
// Let the derived class do the actual run
auto dt_sub = dt / m_num_subcycles;
for (m_subcycle_iter=0; m_subcycle_iter<m_num_subcycles; ++m_subcycle_iter) {
run_impl(dt_sub);
}
if (m_params.get("Enable Postcondition Checks", true)) {
// Run 'post-condition' property checks stored in this AP
run_postcondition_checks();
}
m_time_stamp += dt;
if (m_update_time_stamps) {
// Update all output fields time stamps
update_time_stamps ();
}
stop_timer (m_timer_prefix + this->name() + "::run");
}
void AtmosphereProcess::finalize (/* what inputs? */) {
finalize_impl(/* what inputs? */);
}
void AtmosphereProcess::set_required_field (const Field& f) {
// Sanity check
EKAT_REQUIRE_MSG (has_required_field(f.get_header().get_identifier()),
"Error! Input field is not required by this atm process.\n"
" field id: " + f.get_header().get_identifier().get_id_string() + "\n"
" atm process: " + this->name() + "\n"
"Something is wrong up the call stack. Please, contact developers.\n");
if (not ekat::contains(m_fields_in,f)) {
m_fields_in.emplace_back(f);
}
// AtmosphereProcessGroup is just a "container" of *real* atm processes,
// so don't add me as customer if I'm an atm proc group.
if (this->type()!=AtmosphereProcessType::Group) {
// Add myself as customer to the field
add_me_as_customer(f);
}
set_required_field_impl (f);
}
void AtmosphereProcess::set_computed_field (const Field& f) {
// Sanity check
EKAT_REQUIRE_MSG (has_computed_field(f.get_header().get_identifier()),
"Error! Input field is not computed by this atm process.\n"
" field id: " + f.get_header().get_identifier().get_id_string() + "\n"
" atm process: " + this->name() + "\n"
"Something is wrong up the call stack. Please, contact developers.\n");
if (not ekat::contains(m_fields_out,f)) {
m_fields_out.emplace_back(f);
}
// AtmosphereProcessGroup is just a "container" of *real* atm processes,
// so don't add me as provider if I'm an atm proc group.
if (this->type()!=AtmosphereProcessType::Group) {
// Add myself as provider for the field
add_me_as_provider(f);
}
set_computed_field_impl (f);
}
void AtmosphereProcess::set_required_group (const FieldGroup& group) {
// Sanity check
EKAT_REQUIRE_MSG (has_required_group(group.m_info->m_group_name,group.grid_name()),
"Error! This atmosphere process does not require the input group.\n"
" group name: " + group.m_info->m_group_name + "\n"
" grid name : " + group.grid_name() + "\n"
" atm process: " + this->name() + "\n"
"Something is wrong up the call stack. Please, contact developers.\n");
if (not ekat::contains(m_groups_in,group)) {
m_groups_in.emplace_back(group);
// AtmosphereProcessGroup is just a "container" of *real* atm processes,
// so don't add me as customer if I'm an atm proc group.
if (this->type()!=AtmosphereProcessType::Group) {
if (group.m_bundle) {
add_me_as_customer(*group.m_bundle);
} else {
for (auto& it : group.m_fields) {
add_me_as_customer(*it.second);
}
}
}
}
set_required_group_impl(group);
}
void AtmosphereProcess::set_computed_group (const FieldGroup& group) {
// Sanity check
EKAT_REQUIRE_MSG (has_computed_group(group.m_info->m_group_name,group.grid_name()),
"Error! This atmosphere process does not compute the input group.\n"
" group name: " + group.m_info->m_group_name + "\n"
" grid name : " + group.grid_name() + "\n"
" atm process: " + this->name() + "\n"
"Something is wrong up the call stack. Please, contact developers.\n");
if (not ekat::contains(m_groups_out,group)) {
m_groups_out.emplace_back(group);
// AtmosphereProcessGroup is just a "container" of *real* atm processes,
// so don't add me as provider if I'm an atm proc group.
if (this->type()!=AtmosphereProcessType::Group) {
if (group.m_bundle) {
add_me_as_provider(*group.m_bundle);
} else {
for (auto& it : group.m_fields) {
add_me_as_provider(*it.second);
}
}
}
}
set_computed_group_impl(group);
}
void AtmosphereProcess::run_precondition_checks () const {
// Run all pre-condition property checks
for (const auto& it : m_precondition_checks) {
const auto& pc = it.second;
auto check_result = pc->check();
if (check_result.pass) {
continue;
}
// Failed check.
if (pc->can_repair()) {
// Ok, just fix it
pc->repair();
} else if (it.first==CheckFailHandling::Warning) {
// Still ok, but warn the user
log (LogLevel::warn,
"WARNING: Pre-condition property check failed.\n"
" - Property check name: " + pc->name() + "\n"
" - Atmosphere process name: " + name() + "\n"
" - Atmosphere process MPI Rank: " + std::to_string(m_comm.rank()) + "\n"
" - Message: " + check_result.msg);
} else {
// No hope. Crash.
EKAT_ERROR_MSG(
"Error! Failed pre-condition check (cannot be repaired).\n"
" - Atm process name: " + name() + "\n"
" - Property check name: " + pc->name() + "\n"
" - Atmosphere process MPI Rank: " + std::to_string(m_comm.rank()) + "\n"
" - Message: " + check_result.msg);
}
}
}
void AtmosphereProcess::run_postcondition_checks () const {
// Run all post-condition property checks
for (const auto& it : m_postcondition_checks) {
const auto& pc = it.second;
auto check_result = pc->check();
if (check_result.pass) {
continue;
}
// Failed check.
if (pc->can_repair()) {
// Ok, just fix it
pc->repair();
std::cout << "WARNING: Post-condition property check failed and repaired.\n"
" - Property check name: " + pc->name() + "\n"
" - Atmosphere process name: " + name() + "\n"
" - Atmosphere process MPI Rank: " + std::to_string(m_comm.rank()) + "\n";
} else if (it.first==CheckFailHandling::Warning) {
// Still ok, but warn the user
log (LogLevel::warn,
"WARNING: Post-condition property check failed.\n"
" - Property check name: " + pc->name() + "\n"
" - Atmosphere process name: " + name() + "\n"
" - Atmosphere process MPI Rank: " + std::to_string(m_comm.rank()) + "\n"
" - Error message: " + check_result.msg);
} else {
// No hope. Crash.
EKAT_ERROR_MSG(
"Error! Failed post-condition check (cannot be repaired).\n"
" - Atm process name: " + name() + "\n"
" - Property check name: " + pc->name() + "\n"
" - Atmosphere process MPI Rank: " + std::to_string(m_comm.rank()) + "\n"
" - Error message: " + check_result.msg);
}
}
}
bool AtmosphereProcess::has_required_field (const FieldIdentifier& id) const {
for (const auto& it : m_required_field_requests) {
if (it.fid==id) {
return true;
}
}
return false;
}
bool AtmosphereProcess::has_computed_field (const FieldIdentifier& id) const {
for (const auto& it : m_computed_field_requests) {
if (it.fid==id) {
return true;
}
}
return false;
}
bool AtmosphereProcess::has_required_group (const std::string& name, const std::string& grid) const {
for (const auto& it : m_required_group_requests) {
if (it.name==name && it.grid==grid) {
return true;
}
}
return false;
}
bool AtmosphereProcess::has_computed_group (const std::string& name, const std::string& grid) const {
for (const auto& it : m_computed_group_requests) {
if (it.name==name && it.grid==grid) {
return true;
}
}
return false;
}
void AtmosphereProcess::log (const LogLevel lev, const std::string& msg) const {
m_atm_logger->log(lev,msg);
}
void AtmosphereProcess::set_update_time_stamps (const bool do_update) {
m_update_time_stamps = do_update;
}
void AtmosphereProcess::update_time_stamps () {
const auto& t = timestamp();
// Update *all* output fields/groups, regardless of whether
// they were touched at all during this time step.
// TODO: this might have to be changed
for (auto& f : m_fields_out) {
f.get_header().get_tracking().update_time_stamp(t);
}
for (auto& g : m_groups_out) {
if (g.m_bundle) {
g.m_bundle->get_header().get_tracking().update_time_stamp(t);
} else {
for (auto& f : g.m_fields) {
f.second->get_header().get_tracking().update_time_stamp(t);
}
}
}
}
void AtmosphereProcess::add_me_as_provider (const Field& f) {
f.get_header_ptr()->get_tracking().add_provider(weak_from_this());
}
void AtmosphereProcess::add_me_as_customer (const Field& f) {
f.get_header_ptr()->get_tracking().add_customer(weak_from_this());
}
void AtmosphereProcess::add_internal_field (const Field& f) {
m_internal_fields.push_back(f);
}
const Field& AtmosphereProcess::
get_field_in(const std::string& field_name, const std::string& grid_name) const {
return get_field_in_impl(field_name,grid_name);
}
Field& AtmosphereProcess::
get_field_in(const std::string& field_name, const std::string& grid_name) {
return get_field_in_impl(field_name,grid_name);
}
const Field& AtmosphereProcess::
get_field_in(const std::string& field_name) const {
return get_field_in_impl(field_name);
}
Field& AtmosphereProcess::
get_field_in(const std::string& field_name) {
return get_field_in_impl(field_name);
}
const Field& AtmosphereProcess::
get_field_out(const std::string& field_name, const std::string& grid_name) const {
return get_field_out_impl(field_name,grid_name);
}
Field& AtmosphereProcess::
get_field_out(const std::string& field_name, const std::string& grid_name) {
return get_field_out_impl(field_name,grid_name);
}
const Field& AtmosphereProcess::
get_field_out(const std::string& field_name) const {
return get_field_out_impl (field_name);
}
Field& AtmosphereProcess::
get_field_out(const std::string& field_name) {
return get_field_out_impl (field_name);
}
const FieldGroup& AtmosphereProcess::
get_group_in(const std::string& group_name, const std::string& grid_name) const {
return get_group_in_impl (group_name,grid_name);
}
FieldGroup& AtmosphereProcess::
get_group_in(const std::string& group_name, const std::string& grid_name) {
return get_group_in_impl (group_name,grid_name);
}
const FieldGroup& AtmosphereProcess::
get_group_in(const std::string& group_name) const {
return get_group_in_impl(group_name);
}
FieldGroup& AtmosphereProcess::
get_group_in(const std::string& group_name) {
return get_group_in_impl(group_name);
}
const FieldGroup& AtmosphereProcess::
get_group_out(const std::string& group_name, const std::string& grid_name) const {
return get_group_out_impl(group_name,grid_name);
}
FieldGroup& AtmosphereProcess::
get_group_out(const std::string& group_name, const std::string& grid_name) {
return get_group_out_impl(group_name,grid_name);
}
const FieldGroup& AtmosphereProcess::
get_group_out(const std::string& group_name) const {
return get_group_out_impl(group_name);
}
FieldGroup& AtmosphereProcess::
get_group_out(const std::string& group_name) {
return get_group_out_impl(group_name);
}
const Field& AtmosphereProcess::
get_internal_field(const std::string& field_name, const std::string& grid_name) const {
return get_internal_field_impl(field_name,grid_name);
}
Field& AtmosphereProcess::
get_internal_field(const std::string& field_name, const std::string& grid_name) {
return get_internal_field_impl(field_name,grid_name);
}
Field& AtmosphereProcess::
get_internal_field(const std::string& field_name) {
return get_internal_field_impl(field_name);
}
const Field& AtmosphereProcess::
get_internal_field(const std::string& field_name) const {
return get_internal_field_impl(field_name);
}
void AtmosphereProcess::set_fields_and_groups_pointers () {
for (auto& f : m_fields_in) {
const auto& fid = f.get_header().get_identifier();
m_fields_in_pointers[fid.name()][fid.get_grid_name()] = &f;
}
for (auto& f : m_fields_out) {
const auto& fid = f.get_header().get_identifier();
m_fields_out_pointers[fid.name()][fid.get_grid_name()] = &f;
}
for (auto& g : m_groups_in) {
const auto& group_name = g.m_info->m_group_name;
m_groups_in_pointers[group_name][g.grid_name()] = &g;
}
for (auto& g : m_groups_out) {
const auto& group_name = g.m_info->m_group_name;
m_groups_out_pointers[group_name][g.grid_name()] = &g;
}
for (auto& f : m_internal_fields) {
const auto& fid = f.get_header().get_identifier();
m_internal_fields_pointers[fid.name()][fid.get_grid_name()] = &f;
}
}
void AtmosphereProcess::
alias_field_in (const std::string& field_name,
const std::string& grid_name,
const std::string& alias_name)
{
try {
m_fields_in_pointers[alias_name][grid_name] = m_fields_in_pointers.at(field_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate input field for aliasing request.\n"
" - field name: " + field_name + "\n"
" - grid name: " + grid_name + "\n");
}
}
void AtmosphereProcess::
alias_field_out (const std::string& field_name,
const std::string& grid_name,
const std::string& alias_name)
{
try {
m_fields_out_pointers[alias_name][grid_name] = m_fields_out_pointers.at(field_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate output field for aliasing request.\n"
" - field name: " + field_name + "\n"
" - grid name: " + grid_name + "\n");
}
}
void AtmosphereProcess::
alias_group_in (const std::string& group_name,
const std::string& grid_name,
const std::string& alias_name)
{
try {
m_groups_in_pointers[alias_name][grid_name] = m_groups_in_pointers.at(group_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate input group for aliasing request.\n"
" - group name: " + group_name + "\n"
" - grid name: " + grid_name + "\n");
}
}
void AtmosphereProcess::
alias_group_out (const std::string& group_name,
const std::string& grid_name,
const std::string& alias_name)
{
try {
m_groups_out_pointers[alias_name][grid_name] = m_groups_out_pointers.at(group_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate output group for aliasing request.\n"
" - group name: " + group_name + "\n"
" - grid name: " + grid_name + "\n");
}
}
Field& AtmosphereProcess::
get_field_in_impl(const std::string& field_name, const std::string& grid_name) const {
try {
return *m_fields_in_pointers.at(field_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate input field in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" field name: " + field_name + "\n"
" grid name: " + grid_name + "\n");
}
}
Field& AtmosphereProcess::
get_field_in_impl(const std::string& field_name) const {
try {
auto& copies = m_fields_in_pointers.at(field_name);
EKAT_REQUIRE_MSG (copies.size()==1,
"Error! Attempt to find input field providing only the name,\n"
" but multiple copies (on different grids) are present.\n"
" field name: " + field_name + "\n"
" atm process: " + this->name() + "\n"
" number of copies: " + std::to_string(copies.size()) + "\n");
return *copies.begin()->second;
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate input field in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" field name: " + field_name + "\n");
}
}
Field& AtmosphereProcess::
get_field_out_impl(const std::string& field_name, const std::string& grid_name) const {
try {
return *m_fields_out_pointers.at(field_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate output field in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" field name: " + field_name + "\n"
" grid name: " + grid_name + "\n");
}
}
Field& AtmosphereProcess::
get_field_out_impl(const std::string& field_name) const {
try {
auto& copies = m_fields_out_pointers.at(field_name);
EKAT_REQUIRE_MSG (copies.size()==1,
"Error! Attempt to find output field providing only the name,\n"
" but multiple copies (on different grids) are present.\n"
" field name: " + field_name + "\n"
" atm process: " + this->name() + "\n"
" number of copies: " + std::to_string(copies.size()) + "\n");
return *copies.begin()->second;
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate output field in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" field name: " + field_name + "\n");
}
}
FieldGroup& AtmosphereProcess::
get_group_in_impl(const std::string& group_name, const std::string& grid_name) const {
try {
return *m_groups_in_pointers.at(group_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate input group in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" group name: " + group_name + "\n"
" grid name: " + grid_name + "\n");
}
}
FieldGroup& AtmosphereProcess::
get_group_in_impl(const std::string& group_name) const {
try {
auto& copies = m_groups_in_pointers.at(group_name);
EKAT_REQUIRE_MSG (copies.size()==1,
"Error! Attempt to find input group providing only the name,\n"
" but multiple copies (on different grids) are present.\n"
" group name: " + group_name + "\n"
" atm process: " + this->name() + "\n"
" number of copies: " + std::to_string(copies.size()) + "\n");
return *copies.begin()->second;
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate input group in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" group name: " + group_name + "\n");
}
}
FieldGroup& AtmosphereProcess::
get_group_out_impl(const std::string& group_name, const std::string& grid_name) const {
try {
return *m_groups_out_pointers.at(group_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate output group in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" group name: " + group_name + "\n"
" grid name: " + grid_name + "\n");
}
}
FieldGroup& AtmosphereProcess::
get_group_out_impl(const std::string& group_name) const {
try {
auto& copies = m_groups_out_pointers.at(group_name);
EKAT_REQUIRE_MSG (copies.size()==1,
"Error! Attempt to find output group providing only the name,\n"
" but multiple copies (on different grids) are present.\n"
" group name: " + group_name + "\n"
" atm process: " + this->name() + "\n"
" number of copies: " + std::to_string(copies.size()) + "\n");
return *copies.begin()->second;
} catch (const std::out_of_range&) {
// std::out_of_range would message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate output group in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" group name: " + group_name + "\n");
}
}
Field& AtmosphereProcess::
get_internal_field_impl(const std::string& field_name, const std::string& grid_name) const {
try {
return *m_internal_fields_pointers.at(field_name).at(grid_name);
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate internal field in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" field name: " + field_name + "\n"
" grid name: " + grid_name + "\n");
}
}
Field& AtmosphereProcess::
get_internal_field_impl(const std::string& field_name) const {
try {
auto& copies = m_internal_fields_pointers.at(field_name);
EKAT_REQUIRE_MSG (copies.size()==1,
"Error! Attempt to find internal field providing only the name,\n"
" but multiple copies (on different grids) are present.\n"
" field name: " + field_name + "\n"
" atm process: " + this->name() + "\n"
" number of copies: " + std::to_string(copies.size()) + "\n");
return *copies.begin()->second;
} catch (const std::out_of_range&) {
// std::out_of_range message would not help detecting where
// the exception originated, so print a more meaningful message.
EKAT_ERROR_MSG (
"Error! Could not locate internal field in this atm proces.\n"
" atm proc name: " + this->name() + "\n"
" field name: " + field_name + "\n");
}
}
} // namespace scream
| 35.475107 | 102 | 0.659489 | ambrad |
8f87424c5a5f33c3f4bf0f55c8035c445918160d | 1,832 | cpp | C++ | tests/src/src/cpp/test_factory/TypePropertiesTest.cpp | Bhaskers-Blu-Org2/pmod | 92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a | [
"MIT"
] | 19 | 2019-06-16T02:29:24.000Z | 2022-03-01T23:20:25.000Z | tests/src/src/cpp/test_factory/TypePropertiesTest.cpp | microsoft/pmod | 92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a | [
"MIT"
] | null | null | null | tests/src/src/cpp/test_factory/TypePropertiesTest.cpp | microsoft/pmod | 92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a | [
"MIT"
] | 5 | 2019-11-03T11:40:25.000Z | 2020-08-05T14:56:13.000Z | /***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* File:TypePropertiesTest.cpp
****/
#include "TestModelFastInternal.g.h"
#include <pmod/library/object_factory.h>
#include <pal/pal_thread.h>
using namespace foundation;
using namespace foundation::library;
using namespace pmod::library;
typedef TestModel::_FastTypePropertiesBase CTypeProperties;
typedef ObjectFactory<CTypeProperties, TestModel::TypeProperties::IIDType, ObservableObjectOptions::None, true> CTypeProperties_Factory;
typedef TestModel::_FastTypePropertiesTestBase CTypePropertiesTest_BaseType;
class CTypePropertiesTest :
public CTypePropertiesTest_BaseType
{
public:
HRESULT _InitializeModel(IDispatcher *pWorkingDisptcher)
{
// Set value of TypeProperties property
CTypeProperties_Factory::CreateInstanceAs(this->_typePropertiesValue.GetAddressOf());
// define working dispatcher
this->SetLocalWorkingDispatcher(pWorkingDisptcher);
return S_OK;
}
protected:
HRESULT ChangePropertyAsyncInternal(UINT32 propertyId, foundation::IInspectable * propertyValue, const foundation::AsyncOperationClassPtr& async_operation_class_ptr) override
{
this->_typePropertiesValue->SetProperty(propertyId, propertyValue);
return async_operation_class_ptr.SetCompleted(S_OK);
}
private:
};
typedef ObjectFactory<CTypePropertiesTest, TestModel::TypePropertiesTest::IIDType, ObservableObjectOptions::None, true> CTypePropertiesTest_Factory;
HRESULT CreateTypePropertiesTest(IDispatcher *pWorkingDisptcher, TestModel::ITypePropertiesTest **pp)
{
return CTypePropertiesTest_Factory::CreateInstanceAs(pp, pWorkingDisptcher);
}
| 35.230769 | 179 | 0.774017 | Bhaskers-Blu-Org2 |
8f8c0bce4d25e2e8d7057dc628f324230e63271a | 4,465 | hxx | C++ | Integer1.hxx | zaimoni/Franc | 54c41949676e0e4e2fdba00b7bb7813b1b45e649 | [
"BSL-1.0"
] | null | null | null | Integer1.hxx | zaimoni/Franc | 54c41949676e0e4e2fdba00b7bb7813b1b45e649 | [
"BSL-1.0"
] | null | null | null | Integer1.hxx | zaimoni/Franc | 54c41949676e0e4e2fdba00b7bb7813b1b45e649 | [
"BSL-1.0"
] | null | null | null | // Integer1.hxx
// definition of IntegerNumeral
#ifndef INTEGERNUMERAL_DEF
#define INTEGERNUMERAL_DEF
#if !defined(ABSTRACTCLASS_DEF)
#error Include Class.hxx *before* Integer1.hxx
#endif
#include "MetaCon6.hxx"
#include "__IntegerNumeral.hxx"
// This type works in base 10^9
enum PowersOfTen {
TEN_TO_0 = 1,
TEN_TO_1 = 10,
TEN_TO_2 = 100,
TEN_TO_3 = 1000,
TEN_TO_4 = 10000,
TEN_TO_5 = 100000,
TEN_TO_6 = 1000000,
TEN_TO_7 = 10000000,
TEN_TO_8 = 100000000,
TEN_TO_9 = 1000000000,
WRAPLB = 1000000000
};
class IntegerNumeral;
namespace zaimoni {
template<>
struct is_polymorphic_final<IntegerNumeral> : public std::true_type {};
}
class IntegerNumeral final : public MetaConceptZeroArgs,public _IntegerNumeral
{
public:
IntegerNumeral() : MetaConceptZeroArgs(IntegerNumeral_MC) {};
IntegerNumeral(const IntegerNumeral& src) = default;
IntegerNumeral(IntegerNumeral&& src) = default;
IntegerNumeral& operator=(const IntegerNumeral& src) = default;
IntegerNumeral& operator=(IntegerNumeral&& src) = default;
explicit IntegerNumeral(unsigned short src) : MetaConceptZeroArgs(IntegerNumeral_MC),_IntegerNumeral(src) {};
explicit IntegerNumeral(signed short src) : MetaConceptZeroArgs(IntegerNumeral_MC),_IntegerNumeral(src) {};
explicit IntegerNumeral(unsigned long src) : MetaConceptZeroArgs(IntegerNumeral_MC),_IntegerNumeral(src) {};
explicit IntegerNumeral(signed long src) : MetaConceptZeroArgs(IntegerNumeral_MC),_IntegerNumeral(src) {};
explicit IntegerNumeral(const char* src) : MetaConceptZeroArgs(IntegerNumeral_MC),_IntegerNumeral(src) {};
virtual ~IntegerNumeral() = default;
// inherited from MetaConcept
void CopyInto(MetaConcept*& dest) const override {CopyInto_ForceSyntaxOK(*this,dest);}; // can throw memory failure
void CopyInto(IntegerNumeral*& dest) const {CopyInto_ForceSyntaxOK(*this,dest);}; // can throw memory failure
void MoveInto(MetaConcept*& dest) override { zaimoni::MoveIntoV2(std::move(*this), dest); }
void MoveInto(IntegerNumeral*& dest) { zaimoni::MoveIntoV2(std::move(*this), dest); }
bool operator==(signed short rhs) const {return _IntegerNumeral::operator==(rhs);};
bool operator==(unsigned short rhs) const {return _IntegerNumeral::operator==(rhs);};
// Type ID functions
virtual const AbstractClass* UltimateType() const;
constexpr static bool IsType(ExactType_MC x) { return IntegerNumeral_MC == x; }
// Evaluation functions
std::pair<std::function<bool()>, std::function<bool(MetaConcept*&)> > canEvaluate() const override { return std::pair<std::function<bool()>, std::function<bool(MetaConcept*&)> >(); }
virtual bool CanEvaluate() const;
virtual bool CanEvaluateToSameType() const;
virtual bool SyntaxOK() const {return _IntegerNumeral::SyntaxOK();};
virtual bool Evaluate(MetaConcept*& dest); // same, or different type
virtual bool DestructiveEvaluateToSameType(); // overwrites itself iff returns true
// text I/O functions
bool IsOne() const {return _IntegerNumeral::IsOne();};
bool IsZero() const {return _IntegerNumeral::IsZero();};
virtual bool IsPositive() const {return _IntegerNumeral::IsPositive();};
virtual bool IsNegative() const {return _IntegerNumeral::IsNegative();};
virtual bool SmallDifference(const MetaConcept& rhs, signed long& Result) const;
// Formal manipulation functions
virtual bool SelfInverse(const ExactType_MC Operation);
virtual bool SelfInverseTo(const MetaConcept& rhs, const ExactType_MC Operation) const;
// IntegerNumeral specific functions
const IntegerNumeral& operator=(signed short src);
const IntegerNumeral& operator=(unsigned short src);
const IntegerNumeral& operator=(signed long src);
const IntegerNumeral& operator=(unsigned long src);
static bool ConvertToIntegerNumeral(MetaConcept*& dest,const char* Text);
// this goes here because of the automatic memory management
bool DestructiveAddABBothZ(IntegerNumeral*& A, IntegerNumeral*& B);
protected:
virtual bool EqualAux2(const MetaConcept& rhs) const;
virtual bool InternalDataLTAux(const MetaConcept& rhs) const;
virtual bool SyntacticalStandardLTAux(const MetaConcept& rhs) const;
std::string to_s_aux() const override { return _IntegerNumeral::to_s(); }
virtual bool _IsOne() const {return _IntegerNumeral::IsOne();};
virtual bool _IsZero() const {return _IntegerNumeral::IsZero();};
};
#endif
| 44.207921 | 184 | 0.74804 | zaimoni |
8f8f47f9f3162c68e63f7c660aecf8a93df3f47a | 1,225 | cc | C++ | src/utils/simple_http_client.cc | negibokken/toyscopy | f82d7b3e16d2088e74f036aedc7602a84af781e2 | [
"MIT"
] | 9 | 2019-12-31T10:33:14.000Z | 2021-11-21T00:35:19.000Z | src/utils/simple_http_client.cc | negibokken/toyscopy | f82d7b3e16d2088e74f036aedc7602a84af781e2 | [
"MIT"
] | 18 | 2019-11-01T16:08:08.000Z | 2021-01-09T10:40:39.000Z | src/utils/simple_http_client.cc | negibokken/toyscopy | f82d7b3e16d2088e74f036aedc7602a84af781e2 | [
"MIT"
] | 1 | 2022-03-16T06:22:41.000Z | 2022-03-16T06:22:41.000Z | #include "simple_http_client.h"
namespace ToyScopyUtil {
inline size_t write(void* contents, size_t size, size_t nmemb, std::string* s) {
size_t newLength = size * nmemb;
try {
s->append((char*)contents, newLength);
} catch (std::bad_alloc& e) {
// handle memory problem
return 0;
}
return newLength;
}
inline std::string getProtocolfromUrl(std::string url) {
int cnt = 0;
char protocol[4096];
for (int i = 0; i < url.size(); i++) {
if (url[i] == ':') {
if (i + 2 > url.size()) {
return "invalid";
}
if (url[i + 1] == '/' && url[i + 2] == '/') {
protocol[cnt] = '\0';
return protocol;
}
}
protocol[cnt] = url[i];
}
return protocol;
}
std::string ToyScopyUtil::SimpleHttpClient::fetch(std::string url) {
if (getProtocolfromUrl(url) == "invalid") {
return "";
}
CURL* curl = curl_easy_init();
std::string s = "";
if (curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
return s;
}
} // namespace ToyScopyUtil | 24.019608 | 80 | 0.602449 | negibokken |
8f9113a54dd64e37202c551bfa14f417142a00f4 | 3,067 | cpp | C++ | Src/StateMachine.cpp | Condzi/Engine | 10f6acdf33b24b8d0aab9efcec570821a73423a1 | [
"MIT"
] | 1 | 2018-07-30T10:51:23.000Z | 2018-07-30T10:51:23.000Z | Src/StateMachine.cpp | Condzi/Engine | 10f6acdf33b24b8d0aab9efcec570821a73423a1 | [
"MIT"
] | null | null | null | Src/StateMachine.cpp | Condzi/Engine | 10f6acdf33b24b8d0aab9efcec570821a73423a1 | [
"MIT"
] | null | null | null | /*
Conrad 'Condzi' Kubacki 2018
https://github.com/condzi
*/
#include "Engine/EnginePCH.hpp"
#include "Engine/StateMachine.hpp"
namespace con::priv
{
std::unique_ptr<State> con::priv::StateFactory::createState( StateID id )
{
auto result = functions.find( id );
if ( result != functions.end() )
return result->second();
print( LogPriority::Error, "no scene of id %.", id );
return nullptr;
}
}
namespace con
{
void StateMachine::push( StateID id )
{
requestAction( { Operation::Push, id } );
}
void StateMachine::pop()
{
requestAction( { Operation::Pop } );
}
void StateMachine::enableCurrentState()
{
requestAction( { Operation::Enable } );
}
void StateMachine::disableCurrentState()
{
requestAction( { Operation::Disable } );
}
void StateMachine::update()
{
applyActions();
updateStates();
}
std::optional<State*> StateMachine::getStateOnTop()
{
if ( states.empty() )
return {};
return states.back().get();
}
std::string StateMachine::loggerName() const
{
return "State Machine";
}
void StateMachine::requestAction( Action && action )
{
auto op = [&] {
switch ( action.operation ) {
case Operation::Push: return "Push";
case Operation::Pop: return "Pop";
case Operation::Enable: return "Enable";
case Operation::Disable: return "Disable";
}
}( );
if ( action.operation == Operation::Push )
print( LogPriority::Info, "request %, scene id: %.", op, action.state );
else
print( LogPriority::Info, "request %.", op );
actionBuffer.emplace_back( std::move( action ) );
}
void StateMachine::applyPush( StateID id )
{
auto state = factory.createState( id );
if ( state ) {
state->StateMachine = this;
state->_setId( id );
// passing 'Push' as argument to have coloring.
print( LogPriority::Info, "applying %, state id: %.", "Push", id );
states.emplace_back( std::move( state ) )->onPush();
} else
print( LogPriority::Error, "failed to apply %, state id: %.", "Push", id );
}
void StateMachine::applyPop()
{
if ( states.empty() )
return print( LogPriority::Error, "failed to apply %: empty stack.", "Pop" );
print( LogPriority::Info, "applying %.", "Pop" );
states.back()->onPop();
states.pop_back();
}
void StateMachine::applyEnable()
{
if ( states.empty() )
return print( LogPriority::Error, "failed to apply %: empty stack.", "Enable" );
states.back()->enable();
}
void StateMachine::applyDisable()
{
if ( states.empty() )
return print( LogPriority::Error, "failed to apply %: empty stack.", "Disable" );
states.back()->disable();
}
void StateMachine::applyActions()
{
pendingActions = actionBuffer;
actionBuffer.clear();
// Action is that small it's not worth using reference
for ( auto action : pendingActions ) {
switch ( action.operation ) {
case Operation::Push: applyPush( action.state ); break;
case Operation::Pop: applyPop(); break;
case Operation::Enable: applyEnable(); break;
case Operation::Disable: applyDisable(); break;
}
}
pendingActions.clear();
}
void StateMachine::updateStates()
{
for ( auto& state : states )
state->_update();
}
}
| 21.006849 | 83 | 0.669384 | Condzi |
8f95ac97a3c2c03c73f0225eb249aa8e02deb818 | 19,917 | cpp | C++ | aspects/electrical/sar/GunnsSolarArrayRegulator.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | aspects/electrical/sar/GunnsSolarArrayRegulator.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | aspects/electrical/sar/GunnsSolarArrayRegulator.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | /***************************************** TRICK HEADER ********************************************
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
PURPOSE:
(Provides the classes for modeling the GUNNS Solar Array Regulator.)
REQUIREMENTS:
()
REFERENCE:
()
ASSUMPTIONS AND LIMITATIONS:
()
LIBRARY DEPENDENCY:
(
(aspects/electrical/sar/GunnsSolarArrayRegulator.o)
(aspects/electrical/Converter/ConverterElect.o)
(core/GunnsBasicConductor.o)
(common/sensors/SensorAnalog.o)
(core/GunnsBasicLink.o)
(software/exceptions/TsInitializationException.o)
)
PROGRAMMERS:
(
(Mike Moore) (L3) (2015-01)
)
**************************************************************************************************/
#include "aspects/electrical/sar/GunnsSolarArrayRegulator.hh"
#include "software/exceptions/TsInitializationException.hh"
#include "core/GunnsBasicConductor.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] name (--) Name of the link being created
/// @param[in] nodes (--) Pointer to nodes
/// @param[in] battery (--) Pointer to the battery in the network.
/// @param[in] outVoltageSensorConfig (--) output voltage sensor configuration data
/// @param[in] outCurrentSensorConfig (--) output current sensor configuration data
/// @param[in] outputConductance (one/ohm) Converter's ON conductance on the load side of the link
/// @param[in] converterOffConductance (one/ohm) Converter's OFF conductance of the link
/// @param[in] tripPriority (--) Trip tier for this link in gunns network
/// @param[in] standbyPower (W) Standby Power when converter disables its output
/// @param[in] trickleChargeRate (amp) Minimum voltage that this load can operate at.
/// @param[in] regulatedVoltageLowLimit (amp) Lower limit of the voltage output of the regulator
/// @param[in] regulatedVoltageHighLimit (amp) Upper limit of the voltage output of the regulator
///
/// @details Constructs the Solar Array Regulator Config data
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulatorConfigData::GunnsSolarArrayRegulatorConfigData(const std::string& name,
GunnsNodeList* nodes,
const GunnsBasicConductor* battery,
const SensorAnalogConfigData* outVoltageSensorConfig,
const SensorAnalogConfigData* outCurrentSensorConfig,
const double outputConductance,
const double converterOffConductance,
const int tripPriority,
const double standbyPower,
const double trickleChargeRate,
const double regulatedVoltageLowLimit,
const double regulatedVoltageHighLimit)
:
ConverterElectConfigData(name, nodes, outVoltageSensorConfig, outCurrentSensorConfig, outputConductance, converterOffConductance,
tripPriority, standbyPower),
mBattery(battery),
mNominalTrickleChargeRate(trickleChargeRate),
mRegulatedVoltageLowLimit(regulatedVoltageLowLimit),
mRegulatedVoltageHighLimit(regulatedVoltageHighLimit)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Object to copy from
///
/// @details Copy Constructs the Solar Array Regulator Config data
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulatorConfigData::GunnsSolarArrayRegulatorConfigData(
const GunnsSolarArrayRegulatorConfigData& that)
:
ConverterElectConfigData(that),
mBattery(that.mBattery),
mNominalTrickleChargeRate(that.mNominalTrickleChargeRate),
mRegulatedVoltageLowLimit(that.mRegulatedVoltageLowLimit),
mRegulatedVoltageHighLimit(that.mRegulatedVoltageHighLimit)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Destructs the Solar Array Regulator Config Data Object
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulatorConfigData::~GunnsSolarArrayRegulatorConfigData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] malfBlockageFlag (--) Flag to enable blockage in the link
/// @param[in] malfBlockageValue (--) Value to use for blockage calculation - basic link data
/// @param[in] outVoltageSensorInput (--) output voltage sensor data to set the instance input data
/// @param[in] outCurrentSensorInput (--) output current sensor data to set the instance input data
/// @param[in] malfOpOverCurrentFlag (--) Malfunction flag to override the output over current Limit
/// @param[in] malfOpOverVoltageFlag (--) Malfunction flag to override the output over voltage limit
/// @param[in] malfRegulatedVoltageFlag (--) Malfunction flag to override the regulated voltage Limit
/// @param[in] inputVoltage (V) Input voltage to the converter
/// @param[in] regulatedVoltage (V) Regualted voltage coming out from the converter
/// @param[in] efficiency (--) Efficiency of the converter conversion process
/// @param[in] opOverCurrentLimit (amp) Output over current limit
/// @param[in] opOverVoltageLimit (V) Output over voltage limit (hardware)
/// @param[in] opOverCurrentTripActive (--) Output over current trip active
/// @param[in] opOverVoltageTripActive (--) Output over voltage trip active
/// @param[in] inputOverVoltageLimit (V) Input over voltage limit of the converter
/// @param[in] inputUnderVoltageLimit (V) Input under voltage limit of the converter
/// @param[in] inOverVoltageTripActive (--) Input over voltage trip active
/// @param[in] inUnderVoltageTripActive (--) Input under voltage trip active
///
/// @details Default constructs this Solar Array Regulator input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulatorInputData::GunnsSolarArrayRegulatorInputData(const bool malfBlockageFlag,
const double malfBlockageValue,
const SensorAnalogInputData* outVoltageSensorInput,
const SensorAnalogInputData* outCurrentSensorInput,
const bool malfOpOverCurrentFlag,
const bool malfOpOverVoltageFlag,
const bool malfRegulatedVoltageFlag,
const double inputVoltage,
const double regulatedVoltage,
const double efficiency,
const double opOverCurrentLimit,
const double opOverVoltageLimit,
const bool opOverCurrentTripActive,
const bool opOverVoltageTripActive,
const double inputOverVoltageLimit,
const double inputUnderVoltageLimit,
const bool inOverVoltageTripActive,
const bool inUnderVoltageTripActive,
const double proportionalGain,
const double derivativeGain)
:
ConverterElectInputData(malfBlockageFlag, malfBlockageValue, outVoltageSensorInput, outCurrentSensorInput, malfOpOverCurrentFlag,
malfOpOverVoltageFlag, malfRegulatedVoltageFlag, inputVoltage, regulatedVoltage, efficiency, opOverCurrentLimit,
opOverVoltageLimit, opOverCurrentTripActive, opOverVoltageTripActive, inputOverVoltageLimit, inputUnderVoltageLimit,
inOverVoltageTripActive, inUnderVoltageTripActive),
mProportionalGain(proportionalGain),
mDerivativeGain(derivativeGain)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Object to copy
///
/// @details Copy constructs this Solar Array Regulator input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulatorInputData::GunnsSolarArrayRegulatorInputData(const GunnsSolarArrayRegulatorInputData& that)
:
ConverterElectInputData(that),
mProportionalGain(that.mProportionalGain),
mDerivativeGain(that.mDerivativeGain)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this Solar Array Regulator input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulatorInputData::~GunnsSolarArrayRegulatorInputData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Constructs the Solar Array Regulator Object
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulator::GunnsSolarArrayRegulator():
mInitFlag(false),
mBattery(0),
mDesiredChargeCurrent(0.0),
mPreviousChargeCurrentError(0.0),
mKp(0.0),
mKd(0.0),
mRegulatedVoltageLowLimit(0.0),
mRegulatedVoltageHighLimit(0.0),
mControlledVoltage(0.0),
mMinInVoltage(0.0),
mMarginTurnOnVoltage(0.0)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Destructs the Solar Array Regulator Object
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsSolarArrayRegulator::~GunnsSolarArrayRegulator()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] configData (--) Reference to Solar Array Regulator Config Data
/// @param[in] inputData (--) Reference to Solar Array Regulator Input Data
/// @param[in,out] networkLinks (--) Reference to the Network Link Vector
/// @param[in] port0 (--) Port 0 Mapping
/// @param[in] port1 (--) Port 1 Mapping
/// @param[in] port2 (--) Port 2 Mapping
/// @param[in] port3 (--) Port 3 Mapping
///
/// @throws TsInitializationException
///
/// @details Initializes the Solar Array Regulator with config and input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsSolarArrayRegulator::initialize(const GunnsSolarArrayRegulatorConfigData& configData,
const GunnsSolarArrayRegulatorInputData& inputData,
std::vector<GunnsBasicLink*>& networkLinks,
const int port0,
const int port1,
const int port2,
const int port3)
{
/// - Reset init flag.
mInitFlag = false;
/// - Initialize the parent class.
ConverterElect::initialize(configData, inputData, networkLinks, port0, port1, port2, port3);
/// - Initialize class attributes.
mBattery = configData.mBattery;
mDesiredChargeCurrent = configData.mNominalTrickleChargeRate;
mRegulatedVoltageLowLimit = configData.mRegulatedVoltageLowLimit;
mRegulatedVoltageHighLimit = configData.mRegulatedVoltageHighLimit;
mKp = inputData.mProportionalGain;
mKd = inputData.mDerivativeGain;
/// - Validate the model configuration.
validate();
/// - Just go ahead and default the converter to be on.
setConverterOnCmd(true);
/// - Warn of deprecation due to obsolescence by GunnsElectPvRegConv.
GUNNS_WARNING("this link is deprecated! It is obsoleted by GunnsElectPvRegConv.");
/// - Set init flag on successful validation.
mInitFlag = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @throws TsInitializationException
///
/// @details Validates the solar array regulator
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsSolarArrayRegulator::validate() const
{
/// - Issue an error if the battery pointer is null. This link cannot function
/// without a valid reference to a battery.
if (mBattery == 0) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
" Solar Array Regulator has a null reference to the battery link. This link cannot function without a valid battery reference (BattElect type).");
}
/// - Issue an error on battery trickle charge rate being set to less than zero.
if (mDesiredChargeCurrent < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
" Desired battery charge current is < 0. This indicates a battery discharge, and is therefore not a valid value.");
}
/// - Issue an error when the regulated low voltage limit is zero or below.
if (mRegulatedVoltageLowLimit < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Config Data",
" Desired regulated voltage lower limit is < 0. This is not a valid voltage.");
}
/// - Issue an error when the regulated high voltage limit is zero or below.
if (mRegulatedVoltageHighLimit < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Config Data",
" Desired regulated voltage lower limit is < 0. This is not a valid voltage.");
}
/// - Issue an error when the regulated high voltage limit is less than or equal to the low limit voltage.
if (mRegulatedVoltageHighLimit <= mRegulatedVoltageLowLimit) {
GUNNS_ERROR(TsInitializationException, "Invalid Config Data",
" Desired regulated voltage lower limit is greater than or equal to the upper limit. This is not a valid voltage range.");
}
/// - Issue an error when the controller proportional gain is set to less than zero.
if (mKp < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Input Data",
" Desired proportional gain for the battery charge current feedback controller is < 0. This is not a valid controller gain.");
}
/// - Issue an error when the controller derivative gain is set to less than zero.
if (mKd < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Input Data",
" Desired derivative gain for the battery charge current feedback controller is < 0. This is not a valid controller gain.");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Link time step
/// @param[in] minorstep (--) The minor step number that the network is on (not used)
/// @return void
/// @details Updates the link during the minor time step
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsSolarArrayRegulator::minorStep(const double dt, const int __attribute__((unused)) minorstep)
{
computeFlows(dt);
ConverterElect::step(dt);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] timeStep (s) Time step
/// @return void
/// @details Method to update admittance and source potential of the link.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsSolarArrayRegulator::step(const double timeStep)
{
/// - Perform the automatic voltage regulator control.
updateControl(timeStep);
ConverterElect::step(timeStep);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] timeStep (s) Time step
/// @return void
/// @details Method to update the battery current feedback controller.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsSolarArrayRegulator::updateControl(const double timeStep)
{
/// - This is necessary if done in a non-linear GUNNS minor step b/c the BattElect link
/// is a linear link and the Battery current will not vary across a minor step. To be on the
/// safe side, we calculate this value ourselves.
double* battPotentialVector = mBattery->getPotentialVector();
double* battAdmittanceMatrix = mBattery->getAdmittanceMatrix();
double* battSourceVector = mBattery->getSourceVector();
double battCurrent = ((battPotentialVector[1] - battPotentialVector[0]) * battAdmittanceMatrix[0]) + battSourceVector[0];
/// - Calculate the error and an approximation of the derivative of the error in order to apply P-D
/// feedback control to the regulated ouput voltage based on the error in the desired battery current
double chargeCurrentError = mDesiredChargeCurrent - battCurrent;
double chargeCurrentErrorDot = (chargeCurrentError - mPreviousChargeCurrentError) / timeStep;
/// - We must cache this value across calls to this function in order to properly calculate the charge current
/// error derivative term in the next pass.
mPreviousChargeCurrentError = chargeCurrentError;
/// - Apply proportional-derivative feedback control and the voltage saturation limits to the controlled
/// output voltage.
mControlledVoltage += mKp*chargeCurrentError + mKd*chargeCurrentErrorDot;
mControlledVoltage = MsMath::limitRange(mRegulatedVoltageLowLimit, mControlledVoltage, mRegulatedVoltageHighLimit);
/// - Final step is to update the RegulatedVoltage term that the ConverterElect base class uses to perform
/// its converter function. The base class step function will be called after this.
mRegulatedVoltage = mControlledVoltage;
}
| 56.262712 | 166 | 0.544359 | nasa |
8f981c90f5cfaf6f6d485231292f6cb867dcc33e | 5,335 | cpp | C++ | engine/src/render/PointLight.cpp | Birdy2014/Birdy3d | 96421f262ab6ba7448cae8381063aab32ac830fe | [
"MIT"
] | 1 | 2021-11-01T20:22:41.000Z | 2021-11-01T20:22:41.000Z | engine/src/render/PointLight.cpp | Birdy2014/Birdy3d | 96421f262ab6ba7448cae8381063aab32ac830fe | [
"MIT"
] | 1 | 2021-11-02T12:45:20.000Z | 2021-11-02T12:45:20.000Z | engine/src/render/PointLight.cpp | Birdy2014/Birdy3d | 96421f262ab6ba7448cae8381063aab32ac830fe | [
"MIT"
] | 1 | 2021-11-02T12:28:58.000Z | 2021-11-02T12:28:58.000Z | #include "render/PointLight.hpp"
#include "core/ResourceManager.hpp"
#include "ecs/Entity.hpp"
#include "ecs/Scene.hpp"
#include "render/ModelComponent.hpp"
#include "render/Shader.hpp"
#include <glm/gtc/matrix_transform.hpp>
namespace Birdy3d::render {
PointLight::PointLight(glm::vec3 ambient, glm::vec3 diffuse, float linear, float quadratic, bool shadow_enabled)
: ambient(ambient)
, diffuse(diffuse)
, linear(linear)
, quadratic(quadratic)
, shadow_enabled(shadow_enabled) { }
void PointLight::setup_shadow_map() {
m_depth_shader = core::ResourceManager::get_shader("point_light_depth.glsl");
// framebuffer
glGenFramebuffers(1, &m_shadow_map_fbo);
// shadow map
glGenTextures(1, &m_shadow_map);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_shadow_map);
for (unsigned int i = 0; i < 6; i++)
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
// bind framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, m_shadow_map_fbo);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_shadow_map, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void PointLight::use(const Shader& lightShader, int id, int textureid) {
if (!m_shadow_map_updated) {
gen_shadow_map();
m_shadow_map_updated = true;
}
std::string name = "pointLights[" + std::to_string(id) + "].";
lightShader.use();
lightShader.set_bool(name + "shadow_enabled", shadow_enabled);
lightShader.set_vec3(name + "position", entity->transform.world_position());
lightShader.set_vec3(name + "ambient", ambient);
lightShader.set_vec3(name + "diffuse", diffuse);
lightShader.set_float(name + "linear", linear);
lightShader.set_float(name + "quadratic", quadratic);
glActiveTexture(GL_TEXTURE0 + textureid);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_shadow_map);
lightShader.set_int(name + "shadowMap", textureid);
lightShader.set_float(name + "far", m_far);
}
void PointLight::gen_shadow_map() {
glm::vec3 world_pos = entity->transform.world_position();
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
glBindFramebuffer(GL_FRAMEBUFFER, m_shadow_map_fbo);
glClear(GL_DEPTH_BUFFER_BIT);
glCullFace(GL_FRONT);
glEnable(GL_DEPTH_TEST);
m_depth_shader->use();
float aspect = (float)SHADOW_WIDTH / (float)SHADOW_HEIGHT;
float near = 1.0f;
glm::mat4 shadow_proj = glm::perspective(glm::radians(90.0f), aspect, near, m_far);
m_depth_shader->set_mat4("shadowMatrices[0]", shadow_proj * glm::lookAt(world_pos, world_pos + glm::vec3(1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
m_depth_shader->set_mat4("shadowMatrices[1]", shadow_proj * glm::lookAt(world_pos, world_pos + glm::vec3(-1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
m_depth_shader->set_mat4("shadowMatrices[2]", shadow_proj * glm::lookAt(world_pos, world_pos + glm::vec3(0.0, 1.0, 0.0), glm::vec3(0.0, 0.0, 1.0)));
m_depth_shader->set_mat4("shadowMatrices[3]", shadow_proj * glm::lookAt(world_pos, world_pos + glm::vec3(0.0, -1.0, 0.0), glm::vec3(0.0, 0.0, -1.0)));
m_depth_shader->set_mat4("shadowMatrices[4]", shadow_proj * glm::lookAt(world_pos, world_pos + glm::vec3(0.0, 0.0, 1.0), glm::vec3(0.0, -1.0, 0.0)));
m_depth_shader->set_mat4("shadowMatrices[5]", shadow_proj * glm::lookAt(world_pos, world_pos + glm::vec3(0.0, 0.0, -1.0), glm::vec3(0.0, -1.0, 0.0)));
m_depth_shader->set_float("far_plane", m_far);
m_depth_shader->set_vec3("lightPos", world_pos);
for (auto m : entity->scene->get_components<ModelComponent>(false, true)) {
m->render_depth(*m_depth_shader);
}
// reset framebuffer and viewport
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, viewport[2], viewport[3]);
glClear(GL_DEPTH_BUFFER_BIT);
glCullFace(GL_BACK);
}
void PointLight::start() {
setup_shadow_map();
}
void PointLight::update() {
if (shadow_enabled)
m_shadow_map_updated = false;
}
void PointLight::serialize(serializer::Adapter& adapter) {
adapter("shadow_enabled", shadow_enabled);
adapter("ambient", ambient);
adapter("diffuse", diffuse);
adapter("linear", linear);
adapter("quadratic", quadratic);
adapter("far", m_far);
}
BIRDY3D_REGISTER_DERIVED_TYPE_DEF(ecs::Component, PointLight);
}
| 45.598291 | 158 | 0.667104 | Birdy2014 |
8f984605c4290d323c814c4dff1f0b5f4dec7ef6 | 1,077 | cpp | C++ | src/autowiring/test/CreationRulesTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | src/autowiring/test/CreationRulesTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | src/autowiring/test/CreationRulesTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | // Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/Decoration.hpp"
#include <autowiring/CreationRules.h>
class CreationRulesTest:
public testing::Test
{};
struct AlignedFreer {
void operator()(void* pMem) const {
autowiring::aligned_free(pMem);
}
};
TEST_F(CreationRulesTest, AlignedAllocation) {
// Use a vector because we don't want the underlying allocator to give us the same memory block
// over and over--we are, after all, freeing memory and then immediately asking for another block
// with identical size requirements.
std::vector<std::unique_ptr<void, AlignedFreer>> memory;
memory.resize(100);
// Allocate one byte of 256-byte aligned memory 100 times. If the aligned allocator isn't working
// properly, then the odds are good that at least one of these allocations will be wrong.
for (auto& ptr : memory) {
ptr.reset(autowiring::aligned_malloc(1, 256));
ASSERT_EQ(0UL, (size_t)ptr.get() % 256) << "Aligned allocator did not return a correctly aligned pointer";
}
}
| 35.9 | 110 | 0.732591 | CaseyCarter |
8f9fa5b376ff08bc48eaa354b32bf9de2c6647d1 | 2,023 | cpp | C++ | BashuOJ-Code/3088.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/3088.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/3088.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#define ri register int
#define ll long long
using namespace std;
const int MAXN=1000005;
const int INF=0x7fffffff/2;
int n,m,Q,Slope[5],h[MAXN];
struct Line{int l,r,p,b;};
struct Segment{int s,t;};
struct heap
{
int pos,b;
bool operator <(const heap &rhs)
const {return b>rhs.b;}
};
Segment query[MAXN];
Line a[MAXN];
int f[MAXN][21];
bool bj[MAXN];
priority_queue<heap>q;
vector<int>st[MAXN],ed[MAXN];
inline int min(const int &a,const int &b){return a<b?a:b;}
inline const int getint()
{
int num=0,bj=1;
char c=getchar();
while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(isdigit(c))num=num*10+c-'0',c=getchar();
return num*bj;
}
void ST()
{
memset(f,0x3f,sizeof(f));
for(ri i=1;i<=n;i++)f[i][0]=h[i];
for(ri j=1;j<=log2(n);j++)
for(ri i=1;i+((1<<j)-1)<=n;i++)
f[i][j]=min(f[i][j-1],f[i+(1<<(j-1))][j-1]);
}
inline int RMQ(int x,int y)
{
if(x>y)swap(x,y);
int k=(int)log2(y-x+1);
return min(f[x][k],f[y-(1<<k)+1][k]);
}
int main()
{
for(ri i=1;i<=3;i++)Slope[i]=getint();
n=getint();
for(ri i=1;i<=n;i++)h[i]=getint();
m=getint();
for(ri i=1;i<=m;i++)
{
int l=getint(),r=getint(),p=getint(),b=getint();
a[i]=(Line){l,r,p,b};
st[l].push_back(i);
ed[r].push_back(i);
}
Q=getint();
for(ri i=1;i<=Q;i++)
{
int s=getint(),t=getint();
query[i]=(Segment){s,t};
}
for(ri Type=1;Type<=3;Type++)
{
while(!q.empty())q.pop();
for(ri i=1;i<=n;i++)
{
vector<int>::iterator it;
for(it=st[i].begin();it!=st[i].end();++it)
{
if(a[*it].p==Type)
{
bj[*it]=1;
q.push((heap){*it,a[*it].b});
}
}
while(!q.empty()&&!bj[q.top().pos])q.pop();
if(!q.empty())h[i]=min(h[i],Slope[Type]*i+q.top().b);
for(it=ed[i].begin();it!=ed[i].end();++it)
{
if(a[*it].p==Type)
bj[*it]=0;
}
}
}
ST();
for(ri i=1;i<=Q;i++)
printf("%d\n",RMQ(query[i].s,query[i].t));
return 0;
} | 20.434343 | 58 | 0.565991 | magicgh |
8fa172122e2e29bdaf5c7175351d35f131a84ab5 | 69,810 | cpp | C++ | thrift/gen-cpp/BlockMasterWorkerService.cpp | pspringer/AlluxioWorker | df07f554449c91b1e0f70abe2317b76903f97545 | [
"Apache-2.0"
] | null | null | null | thrift/gen-cpp/BlockMasterWorkerService.cpp | pspringer/AlluxioWorker | df07f554449c91b1e0f70abe2317b76903f97545 | [
"Apache-2.0"
] | null | null | null | thrift/gen-cpp/BlockMasterWorkerService.cpp | pspringer/AlluxioWorker | df07f554449c91b1e0f70abe2317b76903f97545 | [
"Apache-2.0"
] | null | null | null | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "BlockMasterWorkerService.h"
BlockMasterWorkerService_commitBlock_args::~BlockMasterWorkerService_commitBlock_args() throw() {
}
uint32_t BlockMasterWorkerService_commitBlock_args::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->workerId);
this->__isset.workerId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->usedBytesOnTier);
this->__isset.usedBytesOnTier = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->tierAlias);
this->__isset.tierAlias = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->blockId);
this->__isset.blockId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 5:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->length);
this->__isset.length = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_commitBlock_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_commitBlock_args");
xfer += oprot->writeFieldBegin("workerId", ::apache::thrift::protocol::T_I64, 1);
xfer += oprot->writeI64(this->workerId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("usedBytesOnTier", ::apache::thrift::protocol::T_I64, 2);
xfer += oprot->writeI64(this->usedBytesOnTier);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("tierAlias", ::apache::thrift::protocol::T_STRING, 3);
xfer += oprot->writeString(this->tierAlias);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("blockId", ::apache::thrift::protocol::T_I64, 4);
xfer += oprot->writeI64(this->blockId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("length", ::apache::thrift::protocol::T_I64, 5);
xfer += oprot->writeI64(this->length);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_commitBlock_pargs::~BlockMasterWorkerService_commitBlock_pargs() throw() {
}
uint32_t BlockMasterWorkerService_commitBlock_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_commitBlock_pargs");
xfer += oprot->writeFieldBegin("workerId", ::apache::thrift::protocol::T_I64, 1);
xfer += oprot->writeI64((*(this->workerId)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("usedBytesOnTier", ::apache::thrift::protocol::T_I64, 2);
xfer += oprot->writeI64((*(this->usedBytesOnTier)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("tierAlias", ::apache::thrift::protocol::T_STRING, 3);
xfer += oprot->writeString((*(this->tierAlias)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("blockId", ::apache::thrift::protocol::T_I64, 4);
xfer += oprot->writeI64((*(this->blockId)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("length", ::apache::thrift::protocol::T_I64, 5);
xfer += oprot->writeI64((*(this->length)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_commitBlock_result::~BlockMasterWorkerService_commitBlock_result() throw() {
}
uint32_t BlockMasterWorkerService_commitBlock_result::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_commitBlock_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("BlockMasterWorkerService_commitBlock_result");
if (this->__isset.e) {
xfer += oprot->writeFieldBegin("e", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->e.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_commitBlock_presult::~BlockMasterWorkerService_commitBlock_presult() throw() {
}
uint32_t BlockMasterWorkerService_commitBlock_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
BlockMasterWorkerService_getWorkerId_args::~BlockMasterWorkerService_getWorkerId_args() throw() {
}
uint32_t BlockMasterWorkerService_getWorkerId_args::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->workerNetAddress.read(iprot);
this->__isset.workerNetAddress = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_getWorkerId_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_getWorkerId_args");
xfer += oprot->writeFieldBegin("workerNetAddress", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->workerNetAddress.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_getWorkerId_pargs::~BlockMasterWorkerService_getWorkerId_pargs() throw() {
}
uint32_t BlockMasterWorkerService_getWorkerId_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_getWorkerId_pargs");
xfer += oprot->writeFieldBegin("workerNetAddress", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->workerNetAddress)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_getWorkerId_result::~BlockMasterWorkerService_getWorkerId_result() throw() {
}
uint32_t BlockMasterWorkerService_getWorkerId_result::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_getWorkerId_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("BlockMasterWorkerService_getWorkerId_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_I64, 0);
xfer += oprot->writeI64(this->success);
xfer += oprot->writeFieldEnd();
} else if (this->__isset.e) {
xfer += oprot->writeFieldBegin("e", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->e.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_getWorkerId_presult::~BlockMasterWorkerService_getWorkerId_presult() throw() {
}
uint32_t BlockMasterWorkerService_getWorkerId_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
BlockMasterWorkerService_heartbeat_args::~BlockMasterWorkerService_heartbeat_args() throw() {
}
uint32_t BlockMasterWorkerService_heartbeat_args::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->workerId);
this->__isset.workerId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_MAP) {
{
this->usedBytesOnTiers.clear();
uint32_t _size13;
::apache::thrift::protocol::TType _ktype14;
::apache::thrift::protocol::TType _vtype15;
xfer += iprot->readMapBegin(_ktype14, _vtype15, _size13);
uint32_t _i17;
for (_i17 = 0; _i17 < _size13; ++_i17)
{
std::string _key18;
xfer += iprot->readString(_key18);
int64_t& _val19 = this->usedBytesOnTiers[_key18];
xfer += iprot->readI64(_val19);
}
xfer += iprot->readMapEnd();
}
this->__isset.usedBytesOnTiers = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_LIST) {
{
this->removedBlockIds.clear();
uint32_t _size20;
::apache::thrift::protocol::TType _etype23;
xfer += iprot->readListBegin(_etype23, _size20);
this->removedBlockIds.resize(_size20);
uint32_t _i24;
for (_i24 = 0; _i24 < _size20; ++_i24)
{
xfer += iprot->readI64(this->removedBlockIds[_i24]);
}
xfer += iprot->readListEnd();
}
this->__isset.removedBlockIds = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_MAP) {
{
this->addedBlocksOnTiers.clear();
uint32_t _size25;
::apache::thrift::protocol::TType _ktype26;
::apache::thrift::protocol::TType _vtype27;
xfer += iprot->readMapBegin(_ktype26, _vtype27, _size25);
uint32_t _i29;
for (_i29 = 0; _i29 < _size25; ++_i29)
{
std::string _key30;
xfer += iprot->readString(_key30);
std::vector<int64_t> & _val31 = this->addedBlocksOnTiers[_key30];
{
_val31.clear();
uint32_t _size32;
::apache::thrift::protocol::TType _etype35;
xfer += iprot->readListBegin(_etype35, _size32);
_val31.resize(_size32);
uint32_t _i36;
for (_i36 = 0; _i36 < _size32; ++_i36)
{
xfer += iprot->readI64(_val31[_i36]);
}
xfer += iprot->readListEnd();
}
}
xfer += iprot->readMapEnd();
}
this->__isset.addedBlocksOnTiers = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_heartbeat_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_heartbeat_args");
xfer += oprot->writeFieldBegin("workerId", ::apache::thrift::protocol::T_I64, 1);
xfer += oprot->writeI64(this->workerId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("usedBytesOnTiers", ::apache::thrift::protocol::T_MAP, 2);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_I64, static_cast<uint32_t>(this->usedBytesOnTiers.size()));
std::map<std::string, int64_t> ::const_iterator _iter37;
for (_iter37 = this->usedBytesOnTiers.begin(); _iter37 != this->usedBytesOnTiers.end(); ++_iter37)
{
xfer += oprot->writeString(_iter37->first);
xfer += oprot->writeI64(_iter37->second);
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("removedBlockIds", ::apache::thrift::protocol::T_LIST, 3);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I64, static_cast<uint32_t>(this->removedBlockIds.size()));
std::vector<int64_t> ::const_iterator _iter38;
for (_iter38 = this->removedBlockIds.begin(); _iter38 != this->removedBlockIds.end(); ++_iter38)
{
xfer += oprot->writeI64((*_iter38));
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("addedBlocksOnTiers", ::apache::thrift::protocol::T_MAP, 4);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_LIST, static_cast<uint32_t>(this->addedBlocksOnTiers.size()));
std::map<std::string, std::vector<int64_t> > ::const_iterator _iter39;
for (_iter39 = this->addedBlocksOnTiers.begin(); _iter39 != this->addedBlocksOnTiers.end(); ++_iter39)
{
xfer += oprot->writeString(_iter39->first);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I64, static_cast<uint32_t>(_iter39->second.size()));
std::vector<int64_t> ::const_iterator _iter40;
for (_iter40 = _iter39->second.begin(); _iter40 != _iter39->second.end(); ++_iter40)
{
xfer += oprot->writeI64((*_iter40));
}
xfer += oprot->writeListEnd();
}
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_heartbeat_pargs::~BlockMasterWorkerService_heartbeat_pargs() throw() {
}
uint32_t BlockMasterWorkerService_heartbeat_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_heartbeat_pargs");
xfer += oprot->writeFieldBegin("workerId", ::apache::thrift::protocol::T_I64, 1);
xfer += oprot->writeI64((*(this->workerId)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("usedBytesOnTiers", ::apache::thrift::protocol::T_MAP, 2);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_I64, static_cast<uint32_t>((*(this->usedBytesOnTiers)).size()));
std::map<std::string, int64_t> ::const_iterator _iter41;
for (_iter41 = (*(this->usedBytesOnTiers)).begin(); _iter41 != (*(this->usedBytesOnTiers)).end(); ++_iter41)
{
xfer += oprot->writeString(_iter41->first);
xfer += oprot->writeI64(_iter41->second);
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("removedBlockIds", ::apache::thrift::protocol::T_LIST, 3);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I64, static_cast<uint32_t>((*(this->removedBlockIds)).size()));
std::vector<int64_t> ::const_iterator _iter42;
for (_iter42 = (*(this->removedBlockIds)).begin(); _iter42 != (*(this->removedBlockIds)).end(); ++_iter42)
{
xfer += oprot->writeI64((*_iter42));
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("addedBlocksOnTiers", ::apache::thrift::protocol::T_MAP, 4);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_LIST, static_cast<uint32_t>((*(this->addedBlocksOnTiers)).size()));
std::map<std::string, std::vector<int64_t> > ::const_iterator _iter43;
for (_iter43 = (*(this->addedBlocksOnTiers)).begin(); _iter43 != (*(this->addedBlocksOnTiers)).end(); ++_iter43)
{
xfer += oprot->writeString(_iter43->first);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I64, static_cast<uint32_t>(_iter43->second.size()));
std::vector<int64_t> ::const_iterator _iter44;
for (_iter44 = _iter43->second.begin(); _iter44 != _iter43->second.end(); ++_iter44)
{
xfer += oprot->writeI64((*_iter44));
}
xfer += oprot->writeListEnd();
}
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_heartbeat_result::~BlockMasterWorkerService_heartbeat_result() throw() {
}
uint32_t BlockMasterWorkerService_heartbeat_result::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->success.read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_heartbeat_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("BlockMasterWorkerService_heartbeat_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRUCT, 0);
xfer += this->success.write(oprot);
xfer += oprot->writeFieldEnd();
} else if (this->__isset.e) {
xfer += oprot->writeFieldBegin("e", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->e.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_heartbeat_presult::~BlockMasterWorkerService_heartbeat_presult() throw() {
}
uint32_t BlockMasterWorkerService_heartbeat_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += (*(this->success)).read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
BlockMasterWorkerService_registerWorker_args::~BlockMasterWorkerService_registerWorker_args() throw() {
}
uint32_t BlockMasterWorkerService_registerWorker_args::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->workerId);
this->__isset.workerId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_LIST) {
{
this->storageTiers.clear();
uint32_t _size45;
::apache::thrift::protocol::TType _etype48;
xfer += iprot->readListBegin(_etype48, _size45);
this->storageTiers.resize(_size45);
uint32_t _i49;
for (_i49 = 0; _i49 < _size45; ++_i49)
{
xfer += iprot->readString(this->storageTiers[_i49]);
}
xfer += iprot->readListEnd();
}
this->__isset.storageTiers = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_MAP) {
{
this->totalBytesOnTiers.clear();
uint32_t _size50;
::apache::thrift::protocol::TType _ktype51;
::apache::thrift::protocol::TType _vtype52;
xfer += iprot->readMapBegin(_ktype51, _vtype52, _size50);
uint32_t _i54;
for (_i54 = 0; _i54 < _size50; ++_i54)
{
std::string _key55;
xfer += iprot->readString(_key55);
int64_t& _val56 = this->totalBytesOnTiers[_key55];
xfer += iprot->readI64(_val56);
}
xfer += iprot->readMapEnd();
}
this->__isset.totalBytesOnTiers = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_MAP) {
{
this->usedBytesOnTiers.clear();
uint32_t _size57;
::apache::thrift::protocol::TType _ktype58;
::apache::thrift::protocol::TType _vtype59;
xfer += iprot->readMapBegin(_ktype58, _vtype59, _size57);
uint32_t _i61;
for (_i61 = 0; _i61 < _size57; ++_i61)
{
std::string _key62;
xfer += iprot->readString(_key62);
int64_t& _val63 = this->usedBytesOnTiers[_key62];
xfer += iprot->readI64(_val63);
}
xfer += iprot->readMapEnd();
}
this->__isset.usedBytesOnTiers = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 5:
if (ftype == ::apache::thrift::protocol::T_MAP) {
{
this->currentBlocksOnTiers.clear();
uint32_t _size64;
::apache::thrift::protocol::TType _ktype65;
::apache::thrift::protocol::TType _vtype66;
xfer += iprot->readMapBegin(_ktype65, _vtype66, _size64);
uint32_t _i68;
for (_i68 = 0; _i68 < _size64; ++_i68)
{
std::string _key69;
xfer += iprot->readString(_key69);
std::vector<int64_t> & _val70 = this->currentBlocksOnTiers[_key69];
{
_val70.clear();
uint32_t _size71;
::apache::thrift::protocol::TType _etype74;
xfer += iprot->readListBegin(_etype74, _size71);
_val70.resize(_size71);
uint32_t _i75;
for (_i75 = 0; _i75 < _size71; ++_i75)
{
xfer += iprot->readI64(_val70[_i75]);
}
xfer += iprot->readListEnd();
}
}
xfer += iprot->readMapEnd();
}
this->__isset.currentBlocksOnTiers = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_registerWorker_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_registerWorker_args");
xfer += oprot->writeFieldBegin("workerId", ::apache::thrift::protocol::T_I64, 1);
xfer += oprot->writeI64(this->workerId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("storageTiers", ::apache::thrift::protocol::T_LIST, 2);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->storageTiers.size()));
std::vector<std::string> ::const_iterator _iter76;
for (_iter76 = this->storageTiers.begin(); _iter76 != this->storageTiers.end(); ++_iter76)
{
xfer += oprot->writeString((*_iter76));
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("totalBytesOnTiers", ::apache::thrift::protocol::T_MAP, 3);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_I64, static_cast<uint32_t>(this->totalBytesOnTiers.size()));
std::map<std::string, int64_t> ::const_iterator _iter77;
for (_iter77 = this->totalBytesOnTiers.begin(); _iter77 != this->totalBytesOnTiers.end(); ++_iter77)
{
xfer += oprot->writeString(_iter77->first);
xfer += oprot->writeI64(_iter77->second);
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("usedBytesOnTiers", ::apache::thrift::protocol::T_MAP, 4);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_I64, static_cast<uint32_t>(this->usedBytesOnTiers.size()));
std::map<std::string, int64_t> ::const_iterator _iter78;
for (_iter78 = this->usedBytesOnTiers.begin(); _iter78 != this->usedBytesOnTiers.end(); ++_iter78)
{
xfer += oprot->writeString(_iter78->first);
xfer += oprot->writeI64(_iter78->second);
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("currentBlocksOnTiers", ::apache::thrift::protocol::T_MAP, 5);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_LIST, static_cast<uint32_t>(this->currentBlocksOnTiers.size()));
std::map<std::string, std::vector<int64_t> > ::const_iterator _iter79;
for (_iter79 = this->currentBlocksOnTiers.begin(); _iter79 != this->currentBlocksOnTiers.end(); ++_iter79)
{
xfer += oprot->writeString(_iter79->first);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I64, static_cast<uint32_t>(_iter79->second.size()));
std::vector<int64_t> ::const_iterator _iter80;
for (_iter80 = _iter79->second.begin(); _iter80 != _iter79->second.end(); ++_iter80)
{
xfer += oprot->writeI64((*_iter80));
}
xfer += oprot->writeListEnd();
}
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_registerWorker_pargs::~BlockMasterWorkerService_registerWorker_pargs() throw() {
}
uint32_t BlockMasterWorkerService_registerWorker_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BlockMasterWorkerService_registerWorker_pargs");
xfer += oprot->writeFieldBegin("workerId", ::apache::thrift::protocol::T_I64, 1);
xfer += oprot->writeI64((*(this->workerId)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("storageTiers", ::apache::thrift::protocol::T_LIST, 2);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>((*(this->storageTiers)).size()));
std::vector<std::string> ::const_iterator _iter81;
for (_iter81 = (*(this->storageTiers)).begin(); _iter81 != (*(this->storageTiers)).end(); ++_iter81)
{
xfer += oprot->writeString((*_iter81));
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("totalBytesOnTiers", ::apache::thrift::protocol::T_MAP, 3);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_I64, static_cast<uint32_t>((*(this->totalBytesOnTiers)).size()));
std::map<std::string, int64_t> ::const_iterator _iter82;
for (_iter82 = (*(this->totalBytesOnTiers)).begin(); _iter82 != (*(this->totalBytesOnTiers)).end(); ++_iter82)
{
xfer += oprot->writeString(_iter82->first);
xfer += oprot->writeI64(_iter82->second);
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("usedBytesOnTiers", ::apache::thrift::protocol::T_MAP, 4);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_I64, static_cast<uint32_t>((*(this->usedBytesOnTiers)).size()));
std::map<std::string, int64_t> ::const_iterator _iter83;
for (_iter83 = (*(this->usedBytesOnTiers)).begin(); _iter83 != (*(this->usedBytesOnTiers)).end(); ++_iter83)
{
xfer += oprot->writeString(_iter83->first);
xfer += oprot->writeI64(_iter83->second);
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("currentBlocksOnTiers", ::apache::thrift::protocol::T_MAP, 5);
{
xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_LIST, static_cast<uint32_t>((*(this->currentBlocksOnTiers)).size()));
std::map<std::string, std::vector<int64_t> > ::const_iterator _iter84;
for (_iter84 = (*(this->currentBlocksOnTiers)).begin(); _iter84 != (*(this->currentBlocksOnTiers)).end(); ++_iter84)
{
xfer += oprot->writeString(_iter84->first);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I64, static_cast<uint32_t>(_iter84->second.size()));
std::vector<int64_t> ::const_iterator _iter85;
for (_iter85 = _iter84->second.begin(); _iter85 != _iter84->second.end(); ++_iter85)
{
xfer += oprot->writeI64((*_iter85));
}
xfer += oprot->writeListEnd();
}
}
xfer += oprot->writeMapEnd();
}
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_registerWorker_result::~BlockMasterWorkerService_registerWorker_result() throw() {
}
uint32_t BlockMasterWorkerService_registerWorker_result::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t BlockMasterWorkerService_registerWorker_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("BlockMasterWorkerService_registerWorker_result");
if (this->__isset.e) {
xfer += oprot->writeFieldBegin("e", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->e.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
BlockMasterWorkerService_registerWorker_presult::~BlockMasterWorkerService_registerWorker_presult() throw() {
}
uint32_t BlockMasterWorkerService_registerWorker_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->e.read(iprot);
this->__isset.e = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
void BlockMasterWorkerServiceClient::commitBlock(const int64_t workerId, const int64_t usedBytesOnTier, const std::string& tierAlias, const int64_t blockId, const int64_t length)
{
send_commitBlock(workerId, usedBytesOnTier, tierAlias, blockId, length);
recv_commitBlock();
}
void BlockMasterWorkerServiceClient::send_commitBlock(const int64_t workerId, const int64_t usedBytesOnTier, const std::string& tierAlias, const int64_t blockId, const int64_t length)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("commitBlock", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_commitBlock_pargs args;
args.workerId = &workerId;
args.usedBytesOnTier = &usedBytesOnTier;
args.tierAlias = &tierAlias;
args.blockId = &blockId;
args.length = &length;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void BlockMasterWorkerServiceClient::recv_commitBlock()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("commitBlock") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
BlockMasterWorkerService_commitBlock_presult result;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.e) {
throw result.e;
}
return;
}
int64_t BlockMasterWorkerServiceClient::getWorkerId(const ::WorkerNetAddress& workerNetAddress)
{
send_getWorkerId(workerNetAddress);
return recv_getWorkerId();
}
void BlockMasterWorkerServiceClient::send_getWorkerId(const ::WorkerNetAddress& workerNetAddress)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("getWorkerId", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_getWorkerId_pargs args;
args.workerNetAddress = &workerNetAddress;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
int64_t BlockMasterWorkerServiceClient::recv_getWorkerId()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("getWorkerId") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
int64_t _return;
BlockMasterWorkerService_getWorkerId_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
if (result.__isset.e) {
throw result.e;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "getWorkerId failed: unknown result");
}
void BlockMasterWorkerServiceClient::heartbeat( ::Command& _return, const int64_t workerId, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::vector<int64_t> & removedBlockIds, const std::map<std::string, std::vector<int64_t> > & addedBlocksOnTiers)
{
send_heartbeat(workerId, usedBytesOnTiers, removedBlockIds, addedBlocksOnTiers);
recv_heartbeat(_return);
}
void BlockMasterWorkerServiceClient::send_heartbeat(const int64_t workerId, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::vector<int64_t> & removedBlockIds, const std::map<std::string, std::vector<int64_t> > & addedBlocksOnTiers)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("heartbeat", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_heartbeat_pargs args;
args.workerId = &workerId;
args.usedBytesOnTiers = &usedBytesOnTiers;
args.removedBlockIds = &removedBlockIds;
args.addedBlocksOnTiers = &addedBlocksOnTiers;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void BlockMasterWorkerServiceClient::recv_heartbeat( ::Command& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("heartbeat") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
BlockMasterWorkerService_heartbeat_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
if (result.__isset.e) {
throw result.e;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "heartbeat failed: unknown result");
}
void BlockMasterWorkerServiceClient::registerWorker(const int64_t workerId, const std::vector<std::string> & storageTiers, const std::map<std::string, int64_t> & totalBytesOnTiers, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::map<std::string, std::vector<int64_t> > & currentBlocksOnTiers)
{
send_registerWorker(workerId, storageTiers, totalBytesOnTiers, usedBytesOnTiers, currentBlocksOnTiers);
recv_registerWorker();
}
void BlockMasterWorkerServiceClient::send_registerWorker(const int64_t workerId, const std::vector<std::string> & storageTiers, const std::map<std::string, int64_t> & totalBytesOnTiers, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::map<std::string, std::vector<int64_t> > & currentBlocksOnTiers)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("registerWorker", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_registerWorker_pargs args;
args.workerId = &workerId;
args.storageTiers = &storageTiers;
args.totalBytesOnTiers = &totalBytesOnTiers;
args.usedBytesOnTiers = &usedBytesOnTiers;
args.currentBlocksOnTiers = ¤tBlocksOnTiers;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void BlockMasterWorkerServiceClient::recv_registerWorker()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("registerWorker") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
BlockMasterWorkerService_registerWorker_presult result;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.e) {
throw result.e;
}
return;
}
bool BlockMasterWorkerServiceProcessor::dispatchCall(::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, const std::string& fname, int32_t seqid, void* callContext) {
ProcessMap::iterator pfn;
pfn = processMap_.find(fname);
if (pfn == processMap_.end()) {
return ::AlluxioServiceProcessor::dispatchCall(iprot, oprot, fname, seqid, callContext);
}
(this->*(pfn->second))(seqid, iprot, oprot, callContext);
return true;
}
void BlockMasterWorkerServiceProcessor::process_commitBlock(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("BlockMasterWorkerService.commitBlock", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "BlockMasterWorkerService.commitBlock");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "BlockMasterWorkerService.commitBlock");
}
BlockMasterWorkerService_commitBlock_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "BlockMasterWorkerService.commitBlock", bytes);
}
BlockMasterWorkerService_commitBlock_result result;
try {
iface_->commitBlock(args.workerId, args.usedBytesOnTier, args.tierAlias, args.blockId, args.length);
} catch ( ::AlluxioTException &e) {
result.e = e;
result.__isset.e = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "BlockMasterWorkerService.commitBlock");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("commitBlock", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "BlockMasterWorkerService.commitBlock");
}
oprot->writeMessageBegin("commitBlock", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "BlockMasterWorkerService.commitBlock", bytes);
}
}
void BlockMasterWorkerServiceProcessor::process_getWorkerId(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("BlockMasterWorkerService.getWorkerId", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "BlockMasterWorkerService.getWorkerId");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "BlockMasterWorkerService.getWorkerId");
}
BlockMasterWorkerService_getWorkerId_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "BlockMasterWorkerService.getWorkerId", bytes);
}
BlockMasterWorkerService_getWorkerId_result result;
try {
result.success = iface_->getWorkerId(args.workerNetAddress);
result.__isset.success = true;
} catch ( ::AlluxioTException &e) {
result.e = e;
result.__isset.e = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "BlockMasterWorkerService.getWorkerId");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("getWorkerId", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "BlockMasterWorkerService.getWorkerId");
}
oprot->writeMessageBegin("getWorkerId", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "BlockMasterWorkerService.getWorkerId", bytes);
}
}
void BlockMasterWorkerServiceProcessor::process_heartbeat(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("BlockMasterWorkerService.heartbeat", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "BlockMasterWorkerService.heartbeat");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "BlockMasterWorkerService.heartbeat");
}
BlockMasterWorkerService_heartbeat_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "BlockMasterWorkerService.heartbeat", bytes);
}
BlockMasterWorkerService_heartbeat_result result;
try {
iface_->heartbeat(result.success, args.workerId, args.usedBytesOnTiers, args.removedBlockIds, args.addedBlocksOnTiers);
result.__isset.success = true;
} catch ( ::AlluxioTException &e) {
result.e = e;
result.__isset.e = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "BlockMasterWorkerService.heartbeat");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("heartbeat", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "BlockMasterWorkerService.heartbeat");
}
oprot->writeMessageBegin("heartbeat", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "BlockMasterWorkerService.heartbeat", bytes);
}
}
void BlockMasterWorkerServiceProcessor::process_registerWorker(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("BlockMasterWorkerService.registerWorker", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "BlockMasterWorkerService.registerWorker");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "BlockMasterWorkerService.registerWorker");
}
BlockMasterWorkerService_registerWorker_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "BlockMasterWorkerService.registerWorker", bytes);
}
BlockMasterWorkerService_registerWorker_result result;
try {
iface_->registerWorker(args.workerId, args.storageTiers, args.totalBytesOnTiers, args.usedBytesOnTiers, args.currentBlocksOnTiers);
} catch ( ::AlluxioTException &e) {
result.e = e;
result.__isset.e = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "BlockMasterWorkerService.registerWorker");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("registerWorker", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "BlockMasterWorkerService.registerWorker");
}
oprot->writeMessageBegin("registerWorker", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "BlockMasterWorkerService.registerWorker", bytes);
}
}
::boost::shared_ptr< ::apache::thrift::TProcessor > BlockMasterWorkerServiceProcessorFactory::getProcessor(const ::apache::thrift::TConnectionInfo& connInfo) {
::apache::thrift::ReleaseHandler< BlockMasterWorkerServiceIfFactory > cleanup(handlerFactory_);
::boost::shared_ptr< BlockMasterWorkerServiceIf > handler(handlerFactory_->getHandler(connInfo), cleanup);
::boost::shared_ptr< ::apache::thrift::TProcessor > processor(new BlockMasterWorkerServiceProcessor(handler));
return processor;
}
void BlockMasterWorkerServiceConcurrentClient::commitBlock(const int64_t workerId, const int64_t usedBytesOnTier, const std::string& tierAlias, const int64_t blockId, const int64_t length)
{
int32_t seqid = send_commitBlock(workerId, usedBytesOnTier, tierAlias, blockId, length);
recv_commitBlock(seqid);
}
int32_t BlockMasterWorkerServiceConcurrentClient::send_commitBlock(const int64_t workerId, const int64_t usedBytesOnTier, const std::string& tierAlias, const int64_t blockId, const int64_t length)
{
int32_t cseqid = this->sync_.generateSeqId();
::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_);
oprot_->writeMessageBegin("commitBlock", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_commitBlock_pargs args;
args.workerId = &workerId;
args.usedBytesOnTier = &usedBytesOnTier;
args.tierAlias = &tierAlias;
args.blockId = &blockId;
args.length = &length;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
sentry.commit();
return cseqid;
}
void BlockMasterWorkerServiceConcurrentClient::recv_commitBlock(const int32_t seqid)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
// the read mutex gets dropped and reacquired as part of waitForWork()
// The destructor of this sentry wakes up other clients
::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid);
while(true) {
if(!this->sync_.getPending(fname, mtype, rseqid)) {
iprot_->readMessageBegin(fname, mtype, rseqid);
}
if(seqid == rseqid) {
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
sentry.commit();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("commitBlock") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
// in a bad state, don't commit
using ::apache::thrift::protocol::TProtocolException;
throw TProtocolException(TProtocolException::INVALID_DATA);
}
BlockMasterWorkerService_commitBlock_presult result;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.e) {
sentry.commit();
throw result.e;
}
sentry.commit();
return;
}
// seqid != rseqid
this->sync_.updatePending(fname, mtype, rseqid);
// this will temporarily unlock the readMutex, and let other clients get work done
this->sync_.waitForWork(seqid);
} // end while(true)
}
int64_t BlockMasterWorkerServiceConcurrentClient::getWorkerId(const ::WorkerNetAddress& workerNetAddress)
{
int32_t seqid = send_getWorkerId(workerNetAddress);
return recv_getWorkerId(seqid);
}
int32_t BlockMasterWorkerServiceConcurrentClient::send_getWorkerId(const ::WorkerNetAddress& workerNetAddress)
{
int32_t cseqid = this->sync_.generateSeqId();
::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_);
oprot_->writeMessageBegin("getWorkerId", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_getWorkerId_pargs args;
args.workerNetAddress = &workerNetAddress;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
sentry.commit();
return cseqid;
}
int64_t BlockMasterWorkerServiceConcurrentClient::recv_getWorkerId(const int32_t seqid)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
// the read mutex gets dropped and reacquired as part of waitForWork()
// The destructor of this sentry wakes up other clients
::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid);
while(true) {
if(!this->sync_.getPending(fname, mtype, rseqid)) {
iprot_->readMessageBegin(fname, mtype, rseqid);
}
if(seqid == rseqid) {
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
sentry.commit();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("getWorkerId") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
// in a bad state, don't commit
using ::apache::thrift::protocol::TProtocolException;
throw TProtocolException(TProtocolException::INVALID_DATA);
}
int64_t _return;
BlockMasterWorkerService_getWorkerId_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
sentry.commit();
return _return;
}
if (result.__isset.e) {
sentry.commit();
throw result.e;
}
// in a bad state, don't commit
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "getWorkerId failed: unknown result");
}
// seqid != rseqid
this->sync_.updatePending(fname, mtype, rseqid);
// this will temporarily unlock the readMutex, and let other clients get work done
this->sync_.waitForWork(seqid);
} // end while(true)
}
void BlockMasterWorkerServiceConcurrentClient::heartbeat( ::Command& _return, const int64_t workerId, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::vector<int64_t> & removedBlockIds, const std::map<std::string, std::vector<int64_t> > & addedBlocksOnTiers)
{
int32_t seqid = send_heartbeat(workerId, usedBytesOnTiers, removedBlockIds, addedBlocksOnTiers);
recv_heartbeat(_return, seqid);
}
int32_t BlockMasterWorkerServiceConcurrentClient::send_heartbeat(const int64_t workerId, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::vector<int64_t> & removedBlockIds, const std::map<std::string, std::vector<int64_t> > & addedBlocksOnTiers)
{
int32_t cseqid = this->sync_.generateSeqId();
::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_);
oprot_->writeMessageBegin("heartbeat", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_heartbeat_pargs args;
args.workerId = &workerId;
args.usedBytesOnTiers = &usedBytesOnTiers;
args.removedBlockIds = &removedBlockIds;
args.addedBlocksOnTiers = &addedBlocksOnTiers;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
sentry.commit();
return cseqid;
}
void BlockMasterWorkerServiceConcurrentClient::recv_heartbeat( ::Command& _return, const int32_t seqid)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
// the read mutex gets dropped and reacquired as part of waitForWork()
// The destructor of this sentry wakes up other clients
::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid);
while(true) {
if(!this->sync_.getPending(fname, mtype, rseqid)) {
iprot_->readMessageBegin(fname, mtype, rseqid);
}
if(seqid == rseqid) {
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
sentry.commit();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("heartbeat") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
// in a bad state, don't commit
using ::apache::thrift::protocol::TProtocolException;
throw TProtocolException(TProtocolException::INVALID_DATA);
}
BlockMasterWorkerService_heartbeat_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
sentry.commit();
return;
}
if (result.__isset.e) {
sentry.commit();
throw result.e;
}
// in a bad state, don't commit
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "heartbeat failed: unknown result");
}
// seqid != rseqid
this->sync_.updatePending(fname, mtype, rseqid);
// this will temporarily unlock the readMutex, and let other clients get work done
this->sync_.waitForWork(seqid);
} // end while(true)
}
void BlockMasterWorkerServiceConcurrentClient::registerWorker(const int64_t workerId, const std::vector<std::string> & storageTiers, const std::map<std::string, int64_t> & totalBytesOnTiers, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::map<std::string, std::vector<int64_t> > & currentBlocksOnTiers)
{
int32_t seqid = send_registerWorker(workerId, storageTiers, totalBytesOnTiers, usedBytesOnTiers, currentBlocksOnTiers);
recv_registerWorker(seqid);
}
int32_t BlockMasterWorkerServiceConcurrentClient::send_registerWorker(const int64_t workerId, const std::vector<std::string> & storageTiers, const std::map<std::string, int64_t> & totalBytesOnTiers, const std::map<std::string, int64_t> & usedBytesOnTiers, const std::map<std::string, std::vector<int64_t> > & currentBlocksOnTiers)
{
int32_t cseqid = this->sync_.generateSeqId();
::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_);
oprot_->writeMessageBegin("registerWorker", ::apache::thrift::protocol::T_CALL, cseqid);
BlockMasterWorkerService_registerWorker_pargs args;
args.workerId = &workerId;
args.storageTiers = &storageTiers;
args.totalBytesOnTiers = &totalBytesOnTiers;
args.usedBytesOnTiers = &usedBytesOnTiers;
args.currentBlocksOnTiers = ¤tBlocksOnTiers;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
sentry.commit();
return cseqid;
}
void BlockMasterWorkerServiceConcurrentClient::recv_registerWorker(const int32_t seqid)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
// the read mutex gets dropped and reacquired as part of waitForWork()
// The destructor of this sentry wakes up other clients
::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid);
while(true) {
if(!this->sync_.getPending(fname, mtype, rseqid)) {
iprot_->readMessageBegin(fname, mtype, rseqid);
}
if(seqid == rseqid) {
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
sentry.commit();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("registerWorker") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
// in a bad state, don't commit
using ::apache::thrift::protocol::TProtocolException;
throw TProtocolException(TProtocolException::INVALID_DATA);
}
BlockMasterWorkerService_registerWorker_presult result;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.e) {
sentry.commit();
throw result.e;
}
sentry.commit();
return;
}
// seqid != rseqid
this->sync_.updatePending(fname, mtype, rseqid);
// this will temporarily unlock the readMutex, and let other clients get work done
this->sync_.waitForWork(seqid);
} // end while(true)
}
| 33.354037 | 330 | 0.656596 | pspringer |
8fa1afbc0840585b82c990f9b8dcd8c42a399cba | 898 | cpp | C++ | class 11.cpp | AxlidinovJ/masalalar_C | ca48c0db29155016a729fbe23030d4a638175d9b | [
"MIT"
] | 3 | 2021-12-02T20:28:27.000Z | 2021-12-08T10:21:24.000Z | class 11.cpp | AxlidnovJ/masalalar_C | e0643137e115d7b9b26651a0d5acc24bc79f8d4f | [
"MIT"
] | null | null | null | class 11.cpp | AxlidnovJ/masalalar_C | e0643137e115d7b9b26651a0d5acc24bc79f8d4f | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
using namespace std;
class Uchburchak{
private:
int a, b, c;
public:
void setter(int x, int y, int z){
a = x; b = y; c = z;
}
int per_getter(){
int p;
p = a + b + c;
return p;
}
double yuza_getter(){
double s, p;
p = (a + b + c) / 2;
s = sqrt(p * (p - a) * (p - b) * (p - c));
return s;
}
void turi(int a, int b, int c){
if(a==b or a==c or b==c){
cout<<"\nTeng yonli ";
}else if(a!=b or a!=c or b!=c){
cout<<"\nTurli tomonli";
}else if(a==b==c){
cout<<"\nTeng tomonli";
}
}
};
int main(){
Uchburchak u1;
int a, b, c;
cout << " a = "; cin >> a;
cout << " b = "; cin >> b;
cout << " c = "; cin >> c;
u1.setter(a, b, c);
cout << "per = " << u1.per_getter() << endl;
cout << "yuza = " << u1.yuza_getter();
u1.turi(a,b,c);
return 0;
} | 16.327273 | 47 | 0.45657 | AxlidinovJ |
8fa3b61e812f9168c39a33e35cc43ccc6921b9ec | 8,795 | cpp | C++ | Cpp/SDK/SortableColumnButton_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 1 | 2020-08-15T08:31:55.000Z | 2020-08-15T08:31:55.000Z | Cpp/SDK/SortableColumnButton_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 2 | 2020-08-15T08:43:56.000Z | 2021-01-15T05:04:48.000Z | Cpp/SDK/SortableColumnButton_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 2 | 2020-08-10T12:05:42.000Z | 2021-02-12T19:56:10.000Z | // Name: S, Version: b
#include "../SDK.h"
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function SortableColumnButton.SortableColumnButton_C.Set Sort State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// ESQSortStates SortState (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// bool bSelected (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void USortableColumnButton_C::Set_Sort_State(ESQSortStates SortState, bool bSelected)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.Set Sort State");
USortableColumnButton_C_Set_Sort_State_Params params;
params.SortState = SortState;
params.bSelected = bSelected;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.Set Arrow
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
ESlateVisibility USortableColumnButton_C::Set_Arrow()
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.Set Arrow");
USortableColumnButton_C_Set_Arrow_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SortableColumnButton.SortableColumnButton_C.Set Text
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FText Text (BlueprintVisible, BlueprintReadOnly, Parm)
void USortableColumnButton_C::Set_Text(const struct FText& Text)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.Set Text");
USortableColumnButton_C_Set_Text_Params params;
params.Text = Text;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.Update Widget
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void USortableColumnButton_C::Update_Widget()
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.Update Widget");
USortableColumnButton_C_Update_Widget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.Set Selected
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool bSelected (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void USortableColumnButton_C::Set_Selected(bool bSelected)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.Set Selected");
USortableColumnButton_C_Set_Selected_Params params;
params.bSelected = bSelected;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.BndEvt__Button_K2Node_ComponentBoundEvent_17_OnButtonClickedEvent__DelegateSignature
// (BlueprintEvent)
void USortableColumnButton_C::BndEvt__Button_K2Node_ComponentBoundEvent_17_OnButtonClickedEvent__DelegateSignature()
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.BndEvt__Button_K2Node_ComponentBoundEvent_17_OnButtonClickedEvent__DelegateSignature");
USortableColumnButton_C_BndEvt__Button_K2Node_ComponentBoundEvent_17_OnButtonClickedEvent__DelegateSignature_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.PreConstruct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// bool IsDesignTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void USortableColumnButton_C::PreConstruct(bool IsDesignTime)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.PreConstruct");
USortableColumnButton_C_PreConstruct_Params params;
params.IsDesignTime = IsDesignTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// float InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void USortableColumnButton_C::Tick(const struct FGeometry& MyGeometry, float InDeltaTime)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.Tick");
USortableColumnButton_C_Tick_Params params;
params.MyGeometry = MyGeometry;
params.InDeltaTime = InDeltaTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void USortableColumnButton_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.Construct");
USortableColumnButton_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.ExecuteUbergraph_SortableColumnButton
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void USortableColumnButton_C::ExecuteUbergraph_SortableColumnButton(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.ExecuteUbergraph_SortableColumnButton");
USortableColumnButton_C_ExecuteUbergraph_SortableColumnButton_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.OnHover__DelegateSignature
// (Public, Delegate, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool bHovered (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void USortableColumnButton_C::OnHover__DelegateSignature(bool bHovered)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.OnHover__DelegateSignature");
USortableColumnButton_C_OnHover__DelegateSignature_Params params;
params.bHovered = bHovered;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SortableColumnButton.SortableColumnButton_C.OnClicked__DelegateSignature
// (Public, Delegate, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool bIsAscending (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<E_SortType> Sort_Type (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void USortableColumnButton_C::OnClicked__DelegateSignature(bool bIsAscending, TEnumAsByte<E_SortType> Sort_Type)
{
static auto fn = UObject::FindObject<UFunction>("Function SortableColumnButton.SortableColumnButton_C.OnClicked__DelegateSignature");
USortableColumnButton_C_OnClicked__DelegateSignature_Params params;
params.bIsAscending = bIsAscending;
params.Sort_Type = Sort_Type;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 35.18 | 190 | 0.758158 | MrManiak |
8fa4713a2e7dc53bfa5940f3bf6f498171ff84a3 | 9,156 | cxx | C++ | main/dbaccess/source/ui/misc/datasourceconnector.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/dbaccess/source/ui/misc/datasourceconnector.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/dbaccess/source/ui/misc/datasourceconnector.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbui.hxx"
#ifndef _DBAUI_DATASOURCECONNECTOR_HXX_
#include "datasourceconnector.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX
#include <comphelper/namedvaluecollection.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef SVTOOLS_FILENOTATION_HXX
#include <svl/filenotation.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif
#ifndef _CPPUHELPER_EXC_HLP_HXX_
#include <cppuhelper/exc_hlp.hxx>
#endif
#ifndef _DBU_MISC_HRC_
#include "dbu_misc.hrc"
#endif
#include "moduledbu.hxx"
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::frame;
using namespace ::dbtools;
using ::svt::OFileNotation;
//=====================================================================
//= ODatasourceConnector
//=====================================================================
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector(const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent)
:m_pErrorMessageParent(_pMessageParent)
,m_xORB(_rxORB)
{
}
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector( const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent,
const ::rtl::OUString& _rContextInformation )
:m_pErrorMessageParent(_pMessageParent)
,m_xORB(_rxORB)
,m_sContextInformation( _rContextInformation )
{
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect( const ::rtl::OUString& _rDataSourceName,
::dbtools::SQLExceptionInfo* _pErrorInfo ) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
// get the data source
Reference< XDataSource > xDatasource(
getDataSourceByName( _rDataSourceName, m_pErrorMessageParent, m_xORB, _pErrorInfo ),
UNO_QUERY
);
if ( xDatasource.is() )
xConnection = connect( xDatasource, _pErrorInfo );
return xConnection;
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const Reference< XDataSource>& _xDataSource,
::dbtools::SQLExceptionInfo* _pErrorInfo ) const
{
Reference< XConnection > xConnection;
OSL_ENSURE( isValid() && _xDataSource.is(), "ODatasourceConnector::connect: invalid object or argument!" );
if ( !isValid() || !_xDataSource.is() )
return xConnection;
// get user/password
::rtl::OUString sPassword, sUser;
sal_Bool bPwdRequired = sal_False;
Reference<XPropertySet> xProp(_xDataSource,UNO_QUERY);
try
{
xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPassword;
xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED) >>= bPwdRequired;
xProp->getPropertyValue(PROPERTY_USER) >>= sUser;
}
catch(Exception&)
{
DBG_UNHANDLED_EXCEPTION();
}
// try to connect
SQLExceptionInfo aInfo;
try
{
if (bPwdRequired && !sPassword.getLength())
{ // password required, but empty -> connect using an interaction handler
Reference< XCompletedConnection > xConnectionCompletion( _xDataSource, UNO_QUERY_THROW );
Reference< XModel > xModel( getDataSourceOrModel( _xDataSource ), UNO_QUERY_THROW );
::comphelper::NamedValueCollection aArgs( xModel->getArgs() );
Reference< XInteractionHandler > xHandler( aArgs.getOrDefault( "InteractionHandler", Reference< XInteractionHandler >() ) );
if ( !xHandler.is() )
{
// instantiate the default SDB interaction handler
xHandler = Reference< XInteractionHandler >( m_xORB->createInstance( SERVICE_TASK_INTERACTION_HANDLER ), UNO_QUERY );
if ( !xHandler.is() )
ShowServiceNotAvailableError(m_pErrorMessageParent, (::rtl::OUString)SERVICE_TASK_INTERACTION_HANDLER, sal_True);
}
if ( xHandler.is() )
{
xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
}
}
else
{
xConnection = _xDataSource->getConnection(sUser, sPassword);
}
}
catch( const SQLException& )
{
aInfo = ::cppu::getCaughtException();
}
catch(const Exception&)
{
DBG_UNHANDLED_EXCEPTION();
}
if ( !aInfo.isValid() )
{
// there was no error during connecting, but perhaps a warning?
Reference< XWarningsSupplier > xConnectionWarnings( xConnection, UNO_QUERY );
if ( xConnectionWarnings.is() )
{
try
{
Any aWarnings( xConnectionWarnings->getWarnings() );
if ( aWarnings.hasValue() )
{
String sMessage( ModuleRes( STR_WARNINGS_DURING_CONNECT ) );
sMessage.SearchAndReplaceAscii( "$buttontext$", Button::GetStandardText( BUTTON_MORE ) );
sMessage = OutputDevice::GetNonMnemonicString( sMessage );
SQLWarning aContext;
aContext.Message = sMessage;
aContext.NextException = aWarnings;
aInfo = aContext;
}
xConnectionWarnings->clearWarnings();
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
}
else
{
if ( m_sContextInformation.getLength() )
{
SQLException aError;
aError.Message = m_sContextInformation;
aError.NextException = aInfo.get();
aInfo = aError;
}
}
// was there an error?
if ( aInfo.isValid() )
{
if ( _pErrorInfo )
{
*_pErrorInfo = aInfo;
}
else
{
showError( aInfo, m_pErrorMessageParent, m_xORB );
}
}
return xConnection;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
| 33.416058 | 140 | 0.608344 | Grosskopf |
8fa6c2251bfd2763376a566e2971b11d84362056 | 2,512 | cc | C++ | modules/synApps_5_6/support/motor-6-7/motorApp/MotorSrc/motorUtilAux.cc | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | modules/synApps_5_6/support/motor-6-7/motorApp/MotorSrc/motorUtilAux.cc | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | modules/synApps_5_6/support/motor-6-7/motorApp/MotorSrc/motorUtilAux.cc | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | /*
FILENAME... motorUtilAux.cc
USAGE... Motor Record Utility Support.
Version: $Revision: 9857 $
Modified By: $Author: sluiter $
Last Modified: $Date: 2009-12-09 10:21:24 -0600 (Wed, 09 Dec 2009) $
HeadURL: $URL: https://subversion.xor.aps.anl.gov/synApps/motor/tags/R6-7/motorApp/MotorSrc/motorUtilAux.cc $
*/
/*
* Original Author: Kevin Peterson (kmpeters@anl.gov)
* Date: December 11, 2002
*
* UNICAT
* Advanced Photon Source
* Argonne National Laboratory
*
* Current Author: Ron Sluiter
*
* Notes:
* - A Channel Access (CA) oriented file had to be created separate from the
* primary motorUtil.cc file because CA and record access code cannot both
* reside in the same file; each defines (redefines) the DBR's.
*
* Modification Log:
* -----------------
* .01 03-06-06 rls Fixed wrong call; replaced dbGetNRecordTypes() with
* dbGetNRecords().
* .02 03-20-07 tmm sprintf() does not include terminating null in num of chars
* converted, so getMotorList was not allocating space for it.
* .03 09-09-08 rls Visual C++ link errors on improper pdbbase declaration.
*/
#include <string.h>
#include <cantProceed.h>
#include <dbStaticLib.h>
#include <errlog.h>
#include "dbAccessDefs.h"
/* ----- Function Declarations ----- */
char **getMotorList();
/* ----- --------------------- ----- */
extern int numMotors;
/* ----- --------------------- ----- */
char ** getMotorList()
{
DBENTRY dbentry, *pdbentry = &dbentry;
long status;
char **paprecords = 0, temp[PVNAME_STRINGSZ];
int num_entries = 0, length = 0, index = 0;
dbInitEntry(pdbbase,pdbentry);
status = dbFindRecordType(pdbentry,"motor");
if (status)
errlogPrintf("getMotorList(): No record description\n");
while (!status)
{
num_entries = dbGetNRecords(pdbentry);
paprecords = (char **) callocMustSucceed(num_entries, sizeof(char *),
"getMotorList(1st)");
status = dbFirstRecord(pdbentry);
while (!status)
{
length = sprintf(temp, "%s", dbGetRecordName(pdbentry));
paprecords[index] = (char *) callocMustSucceed(length+1,
sizeof(char), "getMotorList(2nd)");
strcpy(paprecords[index], temp);
status = dbNextRecord(pdbentry);
index++;
}
numMotors = index;
}
dbFinishEntry(pdbentry);
return(paprecords);
}
| 29.552941 | 116 | 0.59992 | A2-Collaboration |
8faa21fc4f32d49cb9eaa405dd7554a463191c11 | 3,628 | cc | C++ | schemelib/scheme/kinematics/Director.gtest.cc | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 25 | 2019-07-23T01:03:48.000Z | 2022-03-31T04:16:08.000Z | schemelib/scheme/kinematics/Director.gtest.cc | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 13 | 2018-01-30T17:45:57.000Z | 2022-03-28T11:02:44.000Z | schemelib/scheme/kinematics/Director.gtest.cc | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 14 | 2018-02-08T01:42:28.000Z | 2022-03-31T12:56:17.000Z | #include <gtest/gtest.h>
#include "scheme/nest/NEST.hh"
#include "scheme/nest/pmap/ScaleMap.hh"
#include "scheme/kinematics/Director.hh"
#include "scheme/numeric/X1dim.hh"
#include "scheme/util/Timer.hh"
namespace scheme { namespace kinematics { namespace test_director {
using std::cout;
using std::endl;
using numeric::X1dim;
struct TestScene : public SceneBase<X1dim>
{
TestScene() : SceneBase<X1dim>() {}
virtual ~TestScene(){}
void add_position( X1dim const & x ) {
this->positions_.push_back(x);
update_symmetry(positions_.size());
}
virtual shared_ptr<SceneBase<X1dim> > clone_deep() const { return make_shared<TestScene>(*this); }
};
std::ostream & operator<<( std::ostream & out, TestScene const & s ){
out << "TestScene";
BOOST_FOREACH( X1dim x, s.positions_ ) out << "\t" << x;
return out;
}
TEST( Director, test_NestDirector ){
typedef scheme::nest::NEST<1,X1dim> Nest1D;
TestScene scene;
scene.add_position(0);
scene.add_position(0);
scene.add_position(0);
scene.add_position(0);
NestDirector< Nest1D, typename Nest1D::Index > d0(0);
NestDirector< Nest1D, typename Nest1D::Index > d2(2);
d0.set_scene( 7, 3, scene );
ASSERT_EQ( Nest1D().set_and_get(7,3) , scene.position(0) );
ASSERT_EQ( X1dim(0.0) , scene.position(1) );
ASSERT_EQ( X1dim(0.0) , scene.position(2) );
ASSERT_EQ( X1dim(0.0) , scene.position(3) );
d2.set_scene( 7, 3, scene );
ASSERT_EQ( Nest1D().set_and_get(7,3) , scene.position(0) );
ASSERT_EQ( X1dim(0.0) , scene.position(1) );
ASSERT_EQ( Nest1D().set_and_get(7,3) , scene.position(2) );
ASSERT_EQ( X1dim(0.0) , scene.position(3) );
}
TEST( Director, test_TreeDirector ){
// cout << "Director" << endl;
TestScene scene;
scene.add_position(0);
scene.add_position(0);
// cout << scene << endl;
shared_ptr<scheme::nest::NestBase<> > x1nest = make_shared<scheme::nest::NEST<1,X1dim> >(1);
shared_ptr<scheme::nest::NestBase<> > x1nest2 = make_shared<scheme::nest::NEST<1,X1dim> >(2);
shared_ptr< SceneTree< X1dim > > child = make_shared< SceneTree< X1dim > >(10);
child->add_body(1);
child->add_position_nest(x1nest2);
shared_ptr< SceneTree< X1dim > > root = make_shared< SceneTree< X1dim > >(20);
root->add_body(0);
root->add_position_nest(x1nest);
root->add_child(child);
TreeDirector< numeric::X1dim > director(root);
nest::NEST<2,util::SimpleArray<2>,nest::pmap::ScaleMap> refnest(
util::SimpleArray<2>(20.0,10.0),
util::SimpleArray<2>(21.0,12.0),
util::SimpleArray<2,uint64_t>(1,2)
);
util::Timer<> t;
int count = 0;
for( int resl = 0; resl < 8; ++resl ){
// cout << "================== resl " << resl << " ======================" << endl;
for( uint64_t i = 0; i < director.size(resl, (typename TreeDirector< numeric::X1dim >::BigIndex)(0)); ++i){
util::SimpleArray<2> tmp = refnest.set_and_get(i,resl);
// scene.set_position( 0, tmp[0] );
// scene.set_position( 1, tmp[1] );
director.set_scene( i, resl, scene );
++count;
// cout << scene << " " << refnest.set_and_get(i,resl) << endl;
ASSERT_EQ( scene.position(0)[0], tmp[0] );
ASSERT_EQ( scene.position(1)[0], tmp[1] );
}
}
cout << "set_scene rate: " << (double)count / t.elapsed() << " / sec " << endl;
shared_ptr<SceneBase<X1dim> > test = scene.clone_deep();
// cout << test->position(0) << " " << scene.position(0) << endl;
ASSERT_EQ( test->position(0)[0] , scene.position(0)[0] );
test->set_position(0,0);
// cout << test->position(0) << " " << scene.position(0) << endl;
ASSERT_NE( test->position(0)[0] , scene.position(0)[0] );
}
}
}
}
| 29.258065 | 109 | 0.639195 | YaoYinYing |
8fb1348a5c091202eaeb38da562337b36adc2e32 | 593 | cpp | C++ | Data structures and algorithms/SortingMethods/SortingMethods/BubbleSort.cpp | AdemTsranchaliev/SI-FMI-2019 | fc7811dd54519511a84ffc99c30197f9f753ce08 | [
"MIT"
] | null | null | null | Data structures and algorithms/SortingMethods/SortingMethods/BubbleSort.cpp | AdemTsranchaliev/SI-FMI-2019 | fc7811dd54519511a84ffc99c30197f9f753ce08 | [
"MIT"
] | null | null | null | Data structures and algorithms/SortingMethods/SortingMethods/BubbleSort.cpp | AdemTsranchaliev/SI-FMI-2019 | fc7811dd54519511a84ffc99c30197f9f753ce08 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
void BubleSort(int arr[],int n);
int main()
{
int arr[7] = { 8,2,10,20,-1,4,4 };
}
void BubleSort(int arr[], int n)
{
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-i;-1 j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void SelectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min = 0;
for (int j = i+1; j < n ; j++)
{
if (arr[i]>arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
| 11.86 | 36 | 0.440135 | AdemTsranchaliev |
8fb1a29dd8f461f49827b2d346c56c2941884be8 | 2,073 | cpp | C++ | Chapter06/MacroGuardValidator.cpp | PacktPublishing/LLVM-Techniques-Tips-and-Best-Practices-Clang-and-Middle-End-Libraries | c1c87c460afac9854be946a1a8f71c92ad59c14d | [
"MIT"
] | 73 | 2021-04-24T05:37:44.000Z | 2022-03-22T00:39:09.000Z | Chapter06/MacroGuardValidator.cpp | PacktPublishing/LLVM-Techniques-Tips-and-Best-Practices | c1c87c460afac9854be946a1a8f71c92ad59c14d | [
"MIT"
] | null | null | null | Chapter06/MacroGuardValidator.cpp | PacktPublishing/LLVM-Techniques-Tips-and-Best-Practices | c1c87c460afac9854be946a1a8f71c92ad59c14d | [
"MIT"
] | 21 | 2021-05-06T07:42:26.000Z | 2022-03-19T03:40:01.000Z | #include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "MacroGuardValidator.h"
using namespace clang;
using namespace macro_guard;
void MacroGuardValidator::MacroDefined(const Token &MacroNameTok,
const MacroDirective *MD) {
const auto *MI = MD->getMacroInfo();
if (MI->tokens_empty()) return;
for (const auto *ArgII : ArgsToEnclosed) {
// First, check if this macro really has this argument
if (llvm::none_of(MI->params(), [ArgII](const IdentifierInfo *II) {
return ArgII == II;
})) {
auto *MacroNameII = MacroNameTok.getIdentifierInfo();
assert(MacroNameII);
auto NameTokLoc = MacroNameTok.getLocation();
llvm::errs() << "[WARNING] Can't find argument '" << ArgII->getName() << "' ";
llvm::errs() << "at macro '" << MacroNameII->getName() << "'(";
llvm::errs() << NameTokLoc.printToString(SM) << ")\n";
continue;
}
for (auto TokIdx = 0U, TokSize = MI->getNumTokens();
TokIdx < TokSize; ++TokIdx) {
auto CurTok = *(MI->tokens_begin() + TokIdx);
if (CurTok.getIdentifierInfo() == ArgII) {
// Check if previous and successor Tokens are parenthesis
if (TokIdx > 0 && TokIdx < TokSize - 1) {
auto PrevTok = *(MI->tokens_begin() + TokIdx - 1),
NextTok = *(MI->tokens_begin() + TokIdx + 1);
if (PrevTok.is(tok::l_paren) && NextTok.is(tok::r_paren))
continue;
}
// The argument is not enclosed
auto TokLoc = CurTok.getLocation();
llvm::errs() << "[WARNING] In " << TokLoc.printToString(SM) << ": ";
llvm::errs() << "macro argument '" << ArgII->getName()
<< "' is not enclosed by parenthesis\n";
}
}
}
// Also clear the storage after one check
ArgsToEnclosed.clear();
}
| 37.690909 | 84 | 0.579836 | PacktPublishing |
2630ec8a3760317999e45c17f64d502b5928e572 | 1,714 | hpp | C++ | testing/TestCases.hpp | leighgarbs/toolbox | fd9ceada534916fa8987cfcb5220cece2188b304 | [
"MIT"
] | null | null | null | testing/TestCases.hpp | leighgarbs/toolbox | fd9ceada534916fa8987cfcb5220cece2188b304 | [
"MIT"
] | null | null | null | testing/TestCases.hpp | leighgarbs/toolbox | fd9ceada534916fa8987cfcb5220cece2188b304 | [
"MIT"
] | null | null | null | #if !defined TEST_CASES_HPP
#define TEST_CASES_HPP
#include <list>
#include <string>
#include "Test.hpp"
// This class allows sets of related Tests to be grouped and executed together.
// It does this by storing an internal list of Tests and then implementing the
// Test::body() pure virtual member function in such a way that when a TestCases
// (which is itself a Test) is run, all tests in its internal list are run and
// the result of all those tests is aggregated into a single result and
// returned. See documentation for the TestCases::body() function for a
// description of how test case results are aggregated.
class TestCases : public Test
{
public:
// Sets the name
TestCases(const std::string& name);
// Deletes all the added test cases
virtual ~TestCases();
// Adds all test cases by calling addTestCases(), then runs them all in the
// order they were added. Test::FAILED is returned if any test cases fail
// (return Test::FAILED). If no test cases fail and at least one test case
// passed (returned Test::PASSED), Test::PASSED is returned. If no test
// cases pass or fail, Test::SKIPPED is returned.
virtual Test::Result body();
protected:
// Adds a test case to the end of the list of test cases that will be run
// when run() is called
void addTestCase(Test* test);
// Derived classes must implement this to add their desired test cases using
// addTestCase()
virtual void addTestCases() = 0;
private:
std::list<Test*> test_cases;
};
//==============================================================================
inline void TestCases::addTestCase(Test* test)
{
test_cases.push_back(test);
}
#endif
| 31.163636 | 80 | 0.675613 | leighgarbs |
2631940a9d543bd88499c7313eadefa622d8f7c6 | 2,964 | cc | C++ | src/master/SerialMaster.cc | jedbrown/pakman | 16f605a2dd153f00829b596cce3cdd458b6cefb5 | [
"BSD-3-Clause"
] | null | null | null | src/master/SerialMaster.cc | jedbrown/pakman | 16f605a2dd153f00829b596cce3cdd458b6cefb5 | [
"BSD-3-Clause"
] | null | null | null | src/master/SerialMaster.cc | jedbrown/pakman | 16f605a2dd153f00829b596cce3cdd458b6cefb5 | [
"BSD-3-Clause"
] | null | null | null | #include <string>
#include <memory>
#include <utility>
#include <assert.h>
#include "system/system_call.h"
#include "controller/AbstractController.h"
#include "SerialMaster.h"
// Construct from pointer to program terminated flag
SerialMaster::SerialMaster(const Command& simulator,
bool *p_program_terminated) : AbstractMaster(p_program_terminated),
m_simulator(simulator)
{
}
// Probe whether Master is active
bool SerialMaster::isActive() const
{
return m_state != terminated;
}
// Iterate
void SerialMaster::iterate()
{
// This function should never be called recursively
assert(!m_entered);
m_entered = true;
// This function should never be called if the Master has
// terminated
assert(m_state != terminated);
// Check for program termination interrupt
if (programTerminated())
{
// Terminate Master
m_state = terminated;
return;
}
// If there is at least one pending task, execute the task
processTask();
// Call controller
if (auto p_controller = m_p_controller.lock())
p_controller->iterate();
m_entered = false;
}
// Returns true if more pending tasks are needed
bool SerialMaster::needMorePendingTasks() const
{
return m_pending_tasks.size() < 1;
}
// Push pending task
void SerialMaster::pushPendingTask(const std::string& input_string)
{
m_pending_tasks.push(input_string);
}
// Returns whether finished tasks queue is empty
bool SerialMaster::finishedTasksEmpty() const
{
return m_finished_tasks.empty();
}
// Returns reference to front finished task
AbstractMaster::TaskHandler& SerialMaster::frontFinishedTask()
{
return m_finished_tasks.front();
}
// Pop finished task
void SerialMaster::popFinishedTask()
{
m_finished_tasks.pop();
}
// Flush finished and pending tasks
void SerialMaster::flush()
{
while (!m_finished_tasks.empty()) m_finished_tasks.pop();
while (!m_pending_tasks.empty()) m_pending_tasks.pop();
}
// Terminate Master
void SerialMaster::terminate()
{
m_state = terminated;
return;
}
// Processes a task from pending queue if there is one and places it in
// the finished queue when done.
void SerialMaster::processTask()
{
// Return immediately if there are no pending tasks
if (m_pending_tasks.empty())
return;
// Else, pop a pending task, process it and push it to the finished queue
TaskHandler& current_task = m_pending_tasks.front();
// Process current task and get output string and error code
std::string output_string;
int error_code;
std::tie(output_string, error_code) =
system_call_error_code(m_simulator, current_task.getInputString());
// Record output string and error code
current_task.recordOutputAndErrorCode(output_string, error_code);
// Move task to finished queue
m_finished_tasks.push(std::move(m_pending_tasks.front()));
// Pop pending queue
m_pending_tasks.pop();
}
| 23.903226 | 77 | 0.714238 | jedbrown |
26350fffa805e379b02e92ee7183e96db5c3d18a | 1,443 | cpp | C++ | spine-cpp/src/spine/Bone.cpp | damucz/spine-runtimes | 7eae2176162e3c1aac56a3bc3ca9c86f9654a27c | [
"BSD-2-Clause"
] | 2 | 2016-05-23T20:13:32.000Z | 2021-02-03T23:46:38.000Z | spine-cpp/src/spine/Bone.cpp | damucz/spine-runtimes | 7eae2176162e3c1aac56a3bc3ca9c86f9654a27c | [
"BSD-2-Clause"
] | null | null | null | spine-cpp/src/spine/Bone.cpp | damucz/spine-runtimes | 7eae2176162e3c1aac56a3bc3ca9c86f9654a27c | [
"BSD-2-Clause"
] | 6 | 2015-02-16T16:20:43.000Z | 2018-07-08T06:05:01.000Z | #include <math.h>
#include <stdexcept>
#include <spine/Bone.h>
#include <spine/BoneData.h>
#ifndef M_PI // fix for windows removing precious information
#define M_PI 3.14159265358979323846
#endif
namespace spine {
Bone::Bone (BoneData *data) :
data(data),
parent(0),
x(data->x),
y(data->y),
rotation(data->rotation),
scaleX(data->scaleX),
scaleY(data->scaleY) {
if (!data) throw std::invalid_argument("data cannot be null.");
}
void Bone::setToBindPose () {
x = data->x;
y = data->y;
rotation = data->rotation;
scaleX = data->scaleX;
scaleY = data->scaleY;
}
void Bone::updateWorldTransform (bool flipX, bool flipY) {
if (parent) {
worldX = x * parent->m00 + y * parent->m01 + parent->worldX;
worldY = x * parent->m10 + y * parent->m11 + parent->worldY;
worldScaleX = parent->worldScaleX * scaleX;
worldScaleY = parent->worldScaleY * scaleY;
worldRotation = parent->worldRotation + rotation;
} else {
worldX = x;
worldY = y;
worldScaleX = scaleX;
worldScaleY = scaleY;
worldRotation = rotation;
}
float radians = (float)(worldRotation * M_PI / 180);
float cos = cosf(radians);
float sin = sinf(radians);
m00 = cos * worldScaleX;
m10 = sin * worldScaleX;
m01 = -sin * worldScaleY;
m11 = cos * worldScaleY;
if (flipX) {
m00 = -m00;
m01 = -m01;
}
if (flipY) {
m10 = -m10;
m11 = -m11;
}
if (data->flipY) {
m10 = -m10;
m11 = -m11;
}
}
} /* namespace spine */
| 21.220588 | 64 | 0.641026 | damucz |
26355cc569cfa486632991b5be49c6fbc91a4d1e | 1,089 | cpp | C++ | A/1044.cpp | chenjiajia9411/PATest | 061c961f5d7bf7b23c3a1b70d3d443cb57263700 | [
"Apache-2.0"
] | 1 | 2017-11-24T15:06:29.000Z | 2017-11-24T15:06:29.000Z | A/1044.cpp | chenjiajia9411/PAT | 061c961f5d7bf7b23c3a1b70d3d443cb57263700 | [
"Apache-2.0"
] | null | null | null | A/1044.cpp | chenjiajia9411/PAT | 061c961f5d7bf7b23c3a1b70d3d443cb57263700 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
typedef struct {
int begin;
int end;
} result;
int main()
{
int n,m;
cin>>n>>m;
vector<int> v(n);
for(int i = 0; i < n; i++) cin>>v[i];
vector<result> r;
int min_difference = numeric_limits<int>::max();
for(int begin = 0,end = 0,sum = v.front(); begin < n;)
{
if(sum >= m)
{
if(sum - m <= min_difference)
{
if(sum - m < min_difference)
{
min_difference = sum - m;
r.clear();
}
result temp;
temp.begin = begin;
temp.end = end;
r.push_back(temp);
}
begin++;
end = begin;
sum = v[begin];
}
else if(end < n)
{
end++;
sum += v[end];
}
else break;
}
for_each(r.begin(),r.end(),[&](result a)->void{cout<<a.begin + 1<<"-"<<a.end + 1<<endl;});
}
| 22.22449 | 94 | 0.413223 | chenjiajia9411 |
263d857501f25ba65dbafc51a09c5a56a4ca4f53 | 823 | cpp | C++ | src/RunMetadata.cpp | bio-nim/pbbam | d3bf59e90865ef3b39bf50f19fd846db42bb0fe1 | [
"BSD-3-Clause-Clear"
] | 21 | 2016-04-26T20:46:41.000Z | 2022-03-01T01:55:55.000Z | src/RunMetadata.cpp | bio-nim/pbbam | d3bf59e90865ef3b39bf50f19fd846db42bb0fe1 | [
"BSD-3-Clause-Clear"
] | 25 | 2015-09-03T22:18:01.000Z | 2019-08-27T14:47:39.000Z | src/RunMetadata.cpp | bio-nim/pbbam | d3bf59e90865ef3b39bf50f19fd846db42bb0fe1 | [
"BSD-3-Clause-Clear"
] | 20 | 2015-11-24T15:54:26.000Z | 2022-03-14T03:49:18.000Z | #include "PbbamInternalConfig.h"
#include <pbbam/RunMetadata.h>
#include "RunMetadataParser.h"
namespace PacBio {
namespace BAM {
// ----------------------
// RunMetadata
// ----------------------
CollectionMetadata RunMetadata::Collection(const std::string& metadataXmlFn)
{
return RunMetadataParser::LoadCollection(metadataXmlFn);
}
CollectionMetadata RunMetadata::Collection(std::istream& in)
{
return RunMetadataParser::LoadCollection(in);
}
std::map<std::string, CollectionMetadata> RunMetadata::Collections(
const std::string& runMetadataXmlFn)
{
return RunMetadataParser::LoadCollections(runMetadataXmlFn);
}
std::map<std::string, CollectionMetadata> RunMetadata::Collections(std::istream& in)
{
return RunMetadataParser::LoadCollections(in);
}
} // namespace BAM
} // namespace PacBio
| 22.861111 | 84 | 0.720535 | bio-nim |
263d9a3e46d754966994a417afcc6fbfad79b1fa | 666 | hh | C++ | src/include/log.hh | tomblackwhite/alpha-emu | a371f7d094acbf02c83aa3940ff043f033b7cfe8 | [
"BSD-2-Clause"
] | null | null | null | src/include/log.hh | tomblackwhite/alpha-emu | a371f7d094acbf02c83aa3940ff043f033b7cfe8 | [
"BSD-2-Clause"
] | null | null | null | src/include/log.hh | tomblackwhite/alpha-emu | a371f7d094acbf02c83aa3940ff043f033b7cfe8 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <filesystem>
#include <spdlog/spdlog.h>
namespace filesystem = std::filesystem;
class Log {
public:
// using TextSink = sinks::synchronous_sink<sinks::text_ostream_backend>;
//初始化log
Log(filesystem::path filePath = "") : m_filePath(filePath) {}
void info(std::string_view str) const { spdlog::info("{}", str); }
void warn(std::string_view str) const { spdlog::warn("{}", str); }
void error(std::string_view str) const { spdlog::error("{}", str); }
void debug(std::string_view str) const { spdlog::debug("{}", str); }
static Log& GetInstance(){
static Log log;
return log;
}
private:
filesystem::path m_filePath;
};
| 30.272727 | 75 | 0.674174 | tomblackwhite |
263e68702d09cc979b8659452db449638263da33 | 9,180 | cpp | C++ | src/gLists.cpp | xnevs/FocusSearchCpp | 65ad71b8de09d879bed5c6f98b5487bdba233e12 | [
"MIT"
] | 1 | 2019-01-05T15:35:47.000Z | 2019-01-05T15:35:47.000Z | src/gLists.cpp | xnevs/FocusSearchCpp | 65ad71b8de09d879bed5c6f98b5487bdba233e12 | [
"MIT"
] | null | null | null | src/gLists.cpp | xnevs/FocusSearchCpp | 65ad71b8de09d879bed5c6f98b5487bdba233e12 | [
"MIT"
] | 1 | 2021-09-16T02:18:08.000Z | 2021-09-16T02:18:08.000Z | /*
* gLists.cpp
*
* Created on: Feb 27, 2012
* Author: bovi
*/
/*
Copyright (c) 2013 by Rosalba Giugno
FocusSearchC++ is part of the RI Project.
FocusSearchC++ is a C++ implementation of the original software developed in
Modula2 and provided by the authors of:
Ullmann JR: Bit-vector algorithms for binary constraint satisfaction and
subgraph isomorphism. J. Exp. Algorithmics 2011, 15:1.6:1.1-1.6:1.64.
FocusSearchC++ is provided under the terms of The MIT License (MIT):
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 "defdebug.h"
//#define MSL_CALLS
//#define MSL_INSTRS
//#define MSL_CICLES
//#define MSL_INS
//#define MSL_DOMAINS
#include "gLists.h"
void o_gLists_t::mcSeLists(
o_domains_t& o_domains,
o_match_state_t& o_mstate,
o_vars_order_t& o_varsorder
){
#ifdef MSL_CALLS
std::cout<<">>gLists::mcSeLists\n";
#endif
//M2: VAR
//M2: iDomain, row: domainType;
//M2: matPtr: bitMatrixPointerType;
//M2: ptr: adjVarPtrType;
//M2: seListPtr, seList, iPtr, jPtr: DlistPtrType;
//M2: i, j, u, v, jOrd, firstVar, ordLastSingleton: CARDINAL;
domain_t iDomain, row;
bitMatrix_t *matPtr;
adjVar_rec_t *ptr;
Dlist_rec_t *seListPtr, *seList, *iPtr, *jPtr;
cardinal_t i, j, u, v, jOrd, firstVar, ordLastSingleton;
//M2: BEGIN
//M2: firstVar:= varAtOrd[0]; ordLastSingleton:= 0; --a
//M2: IF Dcards[firstVar] = 1 THEN --b
//M2: valueAt[firstVar]^:= Dlists[firstVar]^.value; firstVar:= varAtOrd[1];
//M2: END;
#ifdef MSL_DOMAINS
o_mstate.print_valueAt(pattern);
#endif
firstVar = o_varsorder.varAtOrd[0];
ordLastSingleton = 0;
if(o_domains.Dcards[firstVar] == 1){
*(o_mstate.valueAt[firstVar]) = o_domains.Dlists[firstVar]->value;
firstVar = o_varsorder.varAtOrd[1];
}
#ifdef MSL_DOMAINS
o_mstate.print_valueAt(pattern);
#endif
//M2: FOR jOrd:= 1 TO alphaUB DO
//M2: j:= varAtOrd[jOrd]; --c
for(jOrd = 1; jOrd < pattern.nof_nodes; jOrd++){
j = o_varsorder.varAtOrd[jOrd];
#ifdef MSL_CICLES
std::cout<<".gLists::mcSeLists: j="<<j<<"\n";
#endif
//M2: IF Dcards[j] > 1 THEN
//M2: ptr:= adjVarInfo[j]; --d
if(o_domains.Dcards[j] > 1){
ptr = adjVarInfo[j];
#ifdef MSL_INS
std::cout<<"j= "<<j<<"; jOrd= "<<jOrd<<"; ";
if(ptr == NULL)std::cout<<"adjVarInfo["<<j<<"] = ptr == NUL\n";
else std::cout<<"adjVarInfo["<<j<<"] = ptr != NUL\n";
#endif
//M2: LOOP --e
//M2: IF ptr = NIL THEN
//M2: meepCard('No SeList for j = ', j, 4); meepCard(', jOrd = ', jOrd, 2); peepLn; HALT
//M2: END;
//M2: IF ordOfVar[ptr^.adjVar] < jOrd THEN i:= ptr^.adjVar; EXIT END;
//M2: ptr:= ptr^.next;
//M2: END;
while(true){
if(ptr == NULL){
std::cout<<"gLists: No SeLits for j="<<j<<"\n";
exit(1);
}
#ifdef MSL_INS
std::cout<<"o_varsorder.ordOfVar["<<ptr->adjVar<<"] < jOrd\n";
std::cout<<"\t=>"<<o_varsorder.ordOfVar[ptr->adjVar]<<" < "<<jOrd<<"\n";
#endif
if(o_varsorder.ordOfVar[ptr->adjVar] < jOrd){
i = ptr->adjVar;
break;
}
ptr = ptr->next;
}
//M2: selector[j]:= valueAt[i]; (* i is the selector for j *)
//M2: iDomain:= Dsets[i];
//M2: iPtr:= Dlists[i]; matPtr:= ptr^.jMiPtr; --f
//M2:
o_mstate.selector[j] = o_mstate.valueAt[i];
iDomain = o_domains.Dsets[i];
iPtr = o_domains.Dlists[i];
matPtr = (ptr->jMiPtr);
//M2: WHILE iPtr # NIL DO --g
//M2: u:= iPtr^.value; row:= matPtr^[u]; jPtr:= Dlists[j]; seList:= NIL; --h
//M2: WHILE jPtr # NIL DO --i
//M2: v:= jPtr^.value;
//M2: IF v IN row THEN
//M2: NEW(seListPtr);
//M2: WITH seListPtr^ DO value:= v; nextValue:= seList END;
//M2: seList:= seListPtr;
//M2: END;
//M2: jPtr:= jPtr^.nextValue;
//M2: END;
//M2: seLists[j,u]:= seList; iPtr:= iPtr^.nextValue;
//M2: END;
while(iPtr != NULL){
#ifdef MSL_INS
std::cout<<".while.iPtr\n";
#endif
u = iPtr->value;
row = *((matPtr)[u]);
jPtr = o_domains.Dlists[j];
seList = NULL;
while(jPtr != NULL){
#ifdef MSL_INS
std::cout<<".while.jPtr\n";
#endif
v = jPtr->value;
if(row.get(v)){
#ifdef MSL_INS
std::cout<<".row.get(v) == true\n";
#endif
seListPtr = new Dlist_rec_t();
seListPtr->value = v;
seListPtr->nextValue = seList;
seList = seListPtr;
}
#ifdef MSL_INS
std::cout<<"<.while.jPtr\n";
#endif
jPtr = jPtr->nextValue;
}
#ifdef MSL_INS
std::cout<<"END.while.jPtr\n";
#endif
seLists[j][u] = seList;
iPtr = iPtr->nextValue;
}
//M2: ELSE ordLastSingleton:= jOrd; valueAt[j]^:= Dlists[j]^.value; --j
//M2: END; (* IF Dcards > *)
}else{
ordLastSingleton = jOrd;
*(o_mstate.valueAt[j]) = o_domains.Dlists[j]->value;
#ifdef MSL_DOMAINS
o_mstate.print_valueAt(pattern);
#endif
}
//M2: END; (* FOR j *)
}
#ifdef MSL_INS
std::cout<<"<.while\n";
#endif
#ifdef DL_INSTRCS
std::cout<<"-gLists::mcSeLists:--\n";
#endif
//M2: IF ordLastSingleton > 0 THEN
//M2: firstVar:= varAtOrd[ordLastSingleton + 1]; --k
//M2: j:= varAtOrd[0]; valueAt[j]^:= Dlists[j]^.value; --l
//M2: END;
if(ordLastSingleton > 0){
firstVar = o_varsorder.varAtOrd[ordLastSingleton + 1];
j = o_varsorder.varAtOrd[0];
*(o_mstate.valueAt[j]) = o_domains.Dlists[j]->value;
}
//M2: END mcSeLists;
#ifdef DL_CALLS
std::cout<<"<gLists::mcSeLists\n";
#endif
};
void o_gLists_t::mcAdjVarInfo(o_predicate_t& o_predicates, bool isordered){
#ifdef DL_CALLS
std::cout<<">>o_gLists_t::mcAdjVarInfo()\n";
#endif
//M2: VAR
//M2: ptr: adjVarPtrType;
//M2: g, i, k, first, second, otherVar: CARDINAL;
//M2: BEGIN
//M2: degree:= cardPatternType{0 BY nAlpha};
//M2: FOR g:= 1 TO eAlpha DO
//M2: FOR k:= 0 TO 1 DO
//M2: first:= alphaEdges[g, 0];
//M2: second:= alphaEdges[g, 1];
//M2: NEW(ptr); ptr^.lineNo:= g;
//M2: IF k = 0 THEN
//M2: i:= first;
//M2: ptr^.adjVar:= second;
//M2: ptr^.iMjPtr:= Rb1[g];
//M2: ptr^.jMiPtr:= Rb2[g];
//M2: INC(degree[first]); INC(degree[second]);
//M2: ELSE
//M2: i:= second;
//M2: ptr^.adjVar:= first;
//M2: ptr^.iMjPtr:= Rb2[g];
//M2: ptr^.jMiPtr:= Rb1[g]
//M2: END;
//M2: ptr^.next:= adjVarInfo[i];
//M2: adjVarInfo[i]:= ptr;
//M2: END;
//M2: END;
//M2: END mcAdjVarInfo;
//adjVarInfo = new adjVar_rec_t*[pattern.nof_nodes];//see gLists.h
// init_degree(pattern);
// init_adjVarInfo(pattern);
//
//
// for(u_size_t i = 0; i<pattern.nof_nodes; i++)
// adjVarInfo[i] = NULL;
adjVar_rec_t *ptr;
cardinal_t first, second, otherVar;
for(u_size_t g = 0; g<pattern.nof_edges; g++){
first = pattern.edges[g].source;
second = pattern.edges[g].target;
adjVar_rec_t *ptr = new adjVar_rec_t();
ptr->lineNo = g;
ptr->adjVar = second;
ptr->iMjPtr = o_predicates.Rb1[g];
ptr->jMiPtr = o_predicates.Rb2[g];
// ptr->e = g;
// ptr->iMjPtr_size = reference.nof_nodes;
// ptr->node = first;
// if(isordered){ ptr->direction = ETYPE_F;}
// else{ ptr->direction = ETYPE_N;}
ptr->next = adjVarInfo[first];
adjVarInfo[first] = ptr;
//
degree[first]++;
degree[second]++;
//
adjVar_rec_t *ptr2 = new adjVar_rec_t();
ptr2->lineNo = g;
ptr2->adjVar = first;
ptr2->iMjPtr = o_predicates.Rb2[g];
ptr2->jMiPtr = o_predicates.Rb1[g];
// ptr2->e = g;
// ptr2->iMjPtr_size = reference.nof_nodes;
// ptr2->node = second;
//
// if(isordered){ ptr->direction = ETYPE_B;}
// else{ ptr->direction = ETYPE_N;}
ptr2->next = adjVarInfo[second];
adjVarInfo[second] = ptr2;
}
#ifdef DL_CALLS
std::cout<<"<o_gLists_t::mcAdjVarInfo()\n";
#endif
};
| 28.958991 | 97 | 0.590087 | xnevs |
263ed64a680453e1ce31ed1c7336c5bc7b9c56eb | 9,971 | cpp | C++ | Source/Cpp/WfCpp_Statement.cpp | vczh2/Workflow | 7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1 | [
"RSA-MD"
] | 1 | 2018-10-17T16:00:38.000Z | 2018-10-17T16:00:38.000Z | Source/Cpp/WfCpp_Statement.cpp | vczh2/Workflow | 7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1 | [
"RSA-MD"
] | null | null | null | Source/Cpp/WfCpp_Statement.cpp | vczh2/Workflow | 7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1 | [
"RSA-MD"
] | null | null | null | #include "WfCpp.h"
namespace vl
{
namespace workflow
{
namespace cppcodegen
{
using namespace collections;
using namespace reflection;
using namespace reflection::description;
using namespace analyzer;
class WfGenerateStatementVisitor : public Object, public WfStatement::IVisitor
{
public:
WfCppConfig* config;
Ptr<FunctionRecord> functionRecord;
stream::StreamWriter& writer;
WString prefixBlock;
WString prefix;
ITypeInfo* returnType;
WfGenerateStatementVisitor(WfCppConfig* _config, Ptr<FunctionRecord> _functionRecord, stream::StreamWriter& _writer, const WString& _prefixBlock, const WString& _prefix, ITypeInfo* _returnType)
:config(_config)
, functionRecord(_functionRecord)
, writer(_writer)
, prefixBlock(_prefixBlock)
, prefix(_prefix)
, returnType(_returnType)
{
}
void Call(Ptr<WfStatement> node, WString prefixDelta = WString(L"\t", false))
{
GenerateStatement(config, functionRecord, writer, node, prefix, prefixDelta, returnType);
}
void Visit(WfBreakStatement* node)override
{
writer.WriteString(prefix);
writer.WriteLine(L"break;");
}
void Visit(WfContinueStatement* node)override
{
writer.WriteString(prefix);
writer.WriteLine(L"continue;");
}
void Visit(WfReturnStatement* node)override
{
writer.WriteString(prefix);
if (node->expression)
{
writer.WriteString(L"return ");
GenerateExpression(config, writer, node->expression, returnType);
writer.WriteLine(L";");
}
else
{
writer.WriteLine(L"return;");
}
}
void Visit(WfDeleteStatement* node)override
{
writer.WriteString(prefix);
writer.WriteString(L"::vl::__vwsn::This(");
GenerateExpression(config, writer, node->expression, nullptr);
writer.WriteLine(L")->Dispose(true);");
}
void Visit(WfRaiseExceptionStatement* node)override
{
if (node->expression)
{
writer.WriteString(prefix);
writer.WriteString(L"throw ::vl::Exception(");
auto result = config->manager->expressionResolvings[node->expression.Obj()];
bool throwString = result.type->GetTypeDescriptor() == description::GetTypeDescriptor<WString>();
if (!throwString)
{
writer.WriteString(L"::vl::__vwsn::This(");
}
GenerateExpression(config, writer, node->expression, result.type.Obj());
if (!throwString)
{
writer.WriteString(L".Obj())->GetMessage()");
}
writer.WriteLine(L");");
}
else
{
writer.WriteString(prefix);
writer.WriteLine(L"throw;");
}
}
void Visit(WfIfStatement* node)override
{
writer.WriteString(prefix);
while (node)
{
writer.WriteString(L"if (");
if (node->type)
{
auto result = config->manager->expressionResolvings[node->expression.Obj()];
auto scope = config->manager->nodeScopes[node].Obj();
auto typeInfo = CreateTypeInfoFromType(scope, node->type);
writer.WriteString(L"auto ");
writer.WriteString(config->ConvertName(node->name.value));
writer.WriteString(L" = ");
ConvertType(config, writer, result.type.Obj(), typeInfo.Obj(), [&]() {GenerateExpression(config, writer, node->expression, nullptr); }, false);
}
else
{
GenerateExpression(config, writer, node->expression, TypeInfoRetriver<bool>::CreateTypeInfo().Obj());
}
writer.WriteLine(L")");
Call(node->trueBranch);
if (node->falseBranch)
{
writer.WriteString(prefix);
if (auto ifStat = node->falseBranch.Cast<WfIfStatement>())
{
writer.WriteString(L"else ");
node = ifStat.Obj();
continue;
}
else
{
writer.WriteLine(L"else");
Call(node->falseBranch);
}
}
break;
}
}
void Visit(WfWhileStatement* node)override
{
writer.WriteString(prefix);
writer.WriteString(L"while (");
GenerateExpression(config, writer, node->condition, TypeInfoRetriver<bool>::CreateTypeInfo().Obj());
writer.WriteLine(L")");
Call(node->statement);
}
void Visit(WfTryStatement* node)override
{
auto exName = L"__vwsne_" + itow(functionRecord->exprCounter++);
WString tryPrefix = prefix;
if (node->finallyStatement)
{
auto blockName = L"__vwsnb_" + itow(functionRecord->blockCounter++);
tryPrefix += L"\t";
writer.WriteString(prefix);
writer.WriteLine(L"{");
writer.WriteString(tryPrefix);
writer.WriteString(L"auto ");
writer.WriteString(blockName);
writer.WriteLine(L" = [&]()");
GenerateStatement(config, functionRecord, writer, node->finallyStatement, tryPrefix, WString(L"\t", false), returnType);
writer.WriteString(tryPrefix);
writer.WriteLine(L";");
writer.WriteString(tryPrefix);
writer.WriteString(L"::vl::__vwsn::RunOnExit<::vl::RemoveCVR<decltype(");
writer.WriteString(blockName);
writer.WriteString(L")>::Type> ");
writer.WriteString(blockName);
writer.WriteString(L"_dtor(&");
writer.WriteString(blockName);
writer.WriteLine(L");");
}
WString bodyPrefix = tryPrefix + L"\t";
writer.WriteString(tryPrefix);
writer.WriteLine(L"try");
writer.WriteString(tryPrefix);
writer.WriteLine(L"{");
GenerateStatement(config, functionRecord, writer, node->protectedStatement, bodyPrefix, WString(L"\t", false), returnType);
writer.WriteString(tryPrefix);
writer.WriteLine(L"}");
writer.WriteString(tryPrefix);
writer.WriteString(L"catch(const ::vl::Exception&");
if (node->catchStatement)
{
writer.WriteString(L" ");
writer.WriteString(exName);
}
writer.WriteLine(L")");
writer.WriteString(tryPrefix);
writer.WriteLine(L"{");
if (node->catchStatement)
{
writer.WriteString(bodyPrefix);
writer.WriteString(L"auto ");
writer.WriteString(config->ConvertName(node->name.value));
writer.WriteString(L" = ::vl::reflection::description::IValueException::Create(");
writer.WriteString(exName);
writer.WriteLine(L".Message());");
GenerateStatement(config, functionRecord, writer, node->catchStatement, bodyPrefix, WString(L"\t", false), returnType);
}
writer.WriteString(tryPrefix);
writer.WriteLine(L"}");
if (node->finallyStatement)
{
writer.WriteString(prefix);
writer.WriteLine(L"}");
}
}
void Visit(WfBlockStatement* node)override
{
writer.WriteString(prefixBlock);
writer.WriteLine(L"{");
auto oldPrefix = prefix;
if (node->endLabel.value != L"")
{
auto name = config->ConvertName(node->endLabel.value, L"__vwsnl_" + itow(functionRecord->labelCounter++) + L"_");
functionRecord->labelNames.Add(node->endLabel.value, name);
writer.WriteString(prefixBlock);
writer.WriteLine(L"\t{");
prefix += L"\t";
}
FOREACH(Ptr<WfStatement>, statement, node->statements)
{
statement = SearchUntilNonVirtualStatement(statement);
if (statement.Cast<WfBlockStatement>())
{
Call(statement);
}
else
{
Call(statement, WString::Empty);
}
}
if (node->endLabel.value != L"")
{
prefix = oldPrefix;
writer.WriteString(prefixBlock);
writer.WriteLine(L"\t}");
writer.WriteString(prefixBlock);
writer.WriteString(L"\t");
writer.WriteString(functionRecord->labelNames[node->endLabel.value]);
writer.WriteLine(L":;");
functionRecord->labelNames.Remove(node->endLabel.value);
}
writer.WriteString(prefixBlock);
writer.WriteLine(L"}");
}
void Visit(WfGotoStatement* node)override
{
writer.WriteString(prefix);
writer.WriteString(L"goto ");
writer.WriteString(functionRecord->labelNames[node->label.value]);
writer.WriteLine(L";");
}
void Visit(WfExpressionStatement* node)override
{
writer.WriteString(prefix);
GenerateExpression(config, writer, node->expression, nullptr, false);
writer.WriteLine(L";");
}
void Visit(WfVariableStatement* node)override
{
auto scope = config->manager->nodeScopes[node->variable.Obj()];
auto symbol = scope->symbols[node->variable->name.value][0].Obj();
writer.WriteString(prefix);
if (node->variable->expression)
{
writer.WriteString(L"auto");
}
else
{
writer.WriteString(config->ConvertType(symbol->typeInfo.Obj()));
}
writer.WriteString(L" ");
writer.WriteString(config->ConvertName(node->variable->name.value));
if (node->variable->expression)
{
writer.WriteString(L" = ");
GenerateExpression(config, writer, node->variable->expression, symbol->typeInfo.Obj());
}
writer.WriteLine(L";");
}
void Visit(WfVirtualCseStatement* node)override
{
node->expandedStatement->Accept(this);
}
void Visit(WfCoroutineStatement* node)override
{
CHECK_FAIL(L"WfGenerateStatementVisitor::Visit(WfCoroutineStatement*)#Internal error, All coroutine statements do not generate C++ code.");
}
void Visit(WfStateMachineStatement* node)override
{
CHECK_FAIL(L"WfGenerateStatementVisitor::Visit(WfStateMachineStatement*)#Internal error, All state machine statements do not generate C++ code.");
}
};
void GenerateStatement(WfCppConfig* config, Ptr<FunctionRecord> functionRecord, stream::StreamWriter& writer, Ptr<WfStatement> node, const WString& prefix, const WString& prefixDelta, reflection::description::ITypeInfo* returnType)
{
WfGenerateStatementVisitor visitor(config, functionRecord, writer, prefix, prefix + prefixDelta, returnType);
node->Accept(&visitor);
}
}
}
} | 30.306991 | 234 | 0.64497 | vczh2 |
2642754770705bde48bb61534d60f348c5bdcede | 4,290 | cpp | C++ | AudioDataTag.cpp | luotuo44/FlvExploere | daf15700ec2ab0114d13352d3d395ecd99851720 | [
"BSD-3-Clause"
] | 1 | 2019-12-30T03:55:14.000Z | 2019-12-30T03:55:14.000Z | AudioDataTag.cpp | luotuo44/FlvExploere | daf15700ec2ab0114d13352d3d395ecd99851720 | [
"BSD-3-Clause"
] | null | null | null | AudioDataTag.cpp | luotuo44/FlvExploere | daf15700ec2ab0114d13352d3d395ecd99851720 | [
"BSD-3-Clause"
] | null | null | null | //Author: luotuo44@gmail.com
//Use of this source code is governed by a BSD-style license
#include"AudioDataTag.h"
#include<assert.h>
#include<fstream>
#include<iostream>
#include<vector>
#include<string>
#include"helper.h"
using uchar = unsigned char;
namespace FLV
{
AudioDataTag::AudioDataTag(std::ifstream &in)
: m_in(in)
{
}
void AudioDataTag::parse()
{
parseHeader();
parseBody();
parseTailer();
}
//从第二个字节开始,第一个字节已经被client读取,用于确定是何种tag
void AudioDataTag::parseHeader()
{
readTagHeader();
m_start_count_read_bytes = true;
}
void AudioDataTag::parseBody()
{
readTagData();
}
void AudioDataTag::parseTailer()
{
readPreTagSize();
}
std::vector<std::vector<std::string>> AudioDataTag::getPrintTable()const
{
std::vector<std::vector<std::string>> vec = {
{"ts", "codec type", "sample rate", "sample depth", "sound type", "tag data len"},
{std::to_string(m_tag_ts), codecTypeString(), sampleRateTypeString(), sampleDepthTypeString(), soundTypeString(), std::to_string(m_tag_data_len)}
};
return vec;
}
void AudioDataTag::print(std::ostream &os, const std::string &prefix, const std::string &suffix)
{
os<<prefix<<"ts = "<<m_tag_ts<<"\tcodec type "<<codecTypeString()<<"\tsample rate = "<<sampleRateTypeString()
<<"\tsample depth = "<<sampleDepthTypeString()<<"\tsound type ="<<soundTypeString()<<suffix;
}
std::string AudioDataTag::codecTypeString()const
{
static std::string codec_type_str[] = {
"unknown",
"Linear PCM, platform endian",
"ADPCM",
"MP3",
"Linear PCM, little endian",
"Nellymoser 16 kHz mono",
"Nellymoser 8 kHz mono",
"Nellymoser",
"G.711 A-law logarithmic PCM",
"G.711 mu-law logarithmic PCM",
"reserved",
"AAC",
"Speex",
"None",//12 undefined
"None",//13 undefined
"MP3 8 KHz",
"Device-specific sound"
};
return codec_type_str[m_codec_type + 1];
}
std::string AudioDataTag::sampleRateTypeString()const
{
static std::string sample_rate_str[] = {
"unknown",
"5.5 kHz",
"11 kHz",
"22 kHz",
"44 kHz"
};
return sample_rate_str[m_sample_rate_type + 1];
}
std::string AudioDataTag::sampleDepthTypeString()const
{
static std::string sample_depth_str[] = {
"unknown",
"8-bit samples",
"16-bit samples"
};
return sample_depth_str[m_sample_depth_type + 1];
}
std::string AudioDataTag::soundTypeString()const
{
static std::string sound_type_str[] = {
"unknown",
"Mono sound",
"Stereo sound"
};
return sound_type_str[m_sound_type + 1];
}
//=======================================================================================
void AudioDataTag::readBytes(char *arr, size_t bytes)
{
m_in.read(arr, bytes);
if( m_start_count_read_bytes )
m_read_bytes += bytes;
}
size_t AudioDataTag::readInt(size_t bytes)
{
if( bytes == 0)
return 0;
std::vector<uchar> vec(bytes);
readBytes(vec.data(), bytes);
size_t val = Helper::getSizeValue(vec);
return val;
}
//从第二个字节开始,第一个字节已经被client读取,用于确定是何种tag
void AudioDataTag::readTagHeader()
{
//读取tag data 长度
m_tag_data_len = readInt(3);
//读取tag 时间戳
std::vector<uchar> ts(4);
readBytes(ts.data()+1, 3);
readBytes(ts.data(), 1);
m_tag_ts = Helper::getSizeValue(ts);
//读取stream id
std::vector<uchar> stream_id(3);
readBytes(stream_id.data(), stream_id.size());
}
void AudioDataTag::readAudioHeader()
{
char ch;
readBytes(&ch, 1);
parseMetaData(ch);
if( m_codec_type == 10)//AAC
{
//需要继续读取
}
}
void AudioDataTag::readTagData()
{
readAudioHeader();
m_in.seekg(m_tag_data_len-m_read_bytes, std::ios_base::cur);
}
void AudioDataTag::readPreTagSize()
{
size_t prev_tag_size = readInt(4);
assert(prev_tag_size == m_tag_data_len + 11);
(void)prev_tag_size;
}
void AudioDataTag::parseMetaData(char ch)
{
m_codec_type = Helper::getNBits<4>(ch, 4);
m_sample_rate_type = Helper::getNBits<2>(ch, 2);
m_sample_depth_type = Helper::getNBits<1>(ch, 1);
m_sound_type = Helper::getNBits<1>(ch, 0);
}
}
| 18.177966 | 153 | 0.617016 | luotuo44 |
26489745db97f4973174a1baaccdd46ae2fd8b96 | 7,108 | cpp | C++ | applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Deformables/Forces/LINEAR_POINT_ATTRACTION.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Deformables/Forces/LINEAR_POINT_ATTRACTION.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Deformables/Forces/LINEAR_POINT_ATTRACTION.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | //#####################################################################
// Copyright 2010.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Matrices/MATRIX.h>
#include <PhysBAM_Geometry/Topology_Based_Geometry/TRIANGULATED_AREA.h>
#include <PhysBAM_Solids/PhysBAM_Deformables/Forces/LINEAR_POINT_ATTRACTION.h>
#include <PhysBAM_Solids/PhysBAM_Deformables/Particles/PARTICLES.h>
using namespace PhysBAM;
//#####################################################################
// Constructor
//#####################################################################
template<class TV> LINEAR_POINT_ATTRACTION<TV>::
LINEAR_POINT_ATTRACTION(T_MESH& mesh,const TV& pt,T coefficient_input)
:BASE(dynamic_cast<PARTICLES<TV>&>(mesh.particles)),surface(mesh),coefficient(coefficient_input),point(pt),dt(0),apply_explicit_forces(true),apply_implicit_forces(true)
{
mesh.mesh.elements.Flattened().Get_Unique(referenced_particles);
}
//#####################################################################
// Destructor
//#####################################################################
template<class TV> LINEAR_POINT_ATTRACTION<TV>::
~LINEAR_POINT_ATTRACTION()
{
}
//#####################################################################
// Function Add_Velocity_Independent_Forces
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Add_Velocity_Independent_Forces(ARRAY_VIEW<TV> F,const T time) const
{
if(apply_explicit_forces)
for(int i=1;i<=referenced_particles.m;i++){int p=referenced_particles(i);
F(p)+=coefficient*(point-surface.particles.X(p));}
}
//#####################################################################
// Function Update_Position_Based_State
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Update_Position_Based_State(const T time,const bool is_position_update)
{
}
//#####################################################################
// Function Add_Velocity_Dependent_Forces
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Add_Velocity_Dependent_Forces(ARRAY_VIEW<const TV> V,ARRAY_VIEW<TV> F,const T time) const
{
if(apply_implicit_forces)
for(int i=1;i<=referenced_particles.m;i++){int p=referenced_particles(i);
F(p)-=dt*coefficient*V(p);}
}
//#####################################################################
// Function Add_Force_Differential
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Add_Force_Differential(ARRAY_VIEW<const TV> dX,ARRAY_VIEW<TV> dF,const T time) const
{
}
//#####################################################################
// Function Enforce_Definiteness
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Enforce_Definiteness(const bool enforce_definiteness_input)
{
}
//#####################################################################
// Function Add_Implicit_Velocity_Independent_Forces
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Add_Implicit_Velocity_Independent_Forces(ARRAY_VIEW<const TV> V,ARRAY_VIEW<TV> F,const T time) const
{
}
//#####################################################################
// Function Velocity_Dependent_Forces_Size
//#####################################################################
template<class TV> int LINEAR_POINT_ATTRACTION<TV>::
Velocity_Dependent_Forces_Size() const
{
int size=0;
if(apply_implicit_forces) size+=referenced_particles.m*TV::m;
return size;
}
//#####################################################################
// Function Add_Velocity_Dependent_Forces_First_Half
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Add_Velocity_Dependent_Forces_First_Half(ARRAY_VIEW<const TV> V,ARRAY_VIEW<T> aggregate,const T time) const
{
T c=sqrt(dt*coefficient);
if(apply_implicit_forces)
for(int i=1;i<=referenced_particles.m;i++){int p=referenced_particles(i);
TV t=c*V(p);
for(int a=1;a<=TV::m;a++) aggregate((i-1)*TV::m+a)=t(a);}
}
//#####################################################################
// Function Add_Velocity_Dependent_Forces_Second_Half
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Add_Velocity_Dependent_Forces_Second_Half(ARRAY_VIEW<const T> aggregate,ARRAY_VIEW<TV> F,const T time) const
{
T c=sqrt(dt*coefficient);
if(apply_implicit_forces)
for(int i=1;i<=referenced_particles.m;i++){int p=referenced_particles(i);
TV t;
for(int a=1;a<=TV::m;a++) t(a)=aggregate((i-1)*TV::m+a);
F(p)+=c*t;}
}
//#####################################################################
// Function Initialize_CFL
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Initialize_CFL(ARRAY_VIEW<typename BASE::FREQUENCY_DATA> frequency)
{
}
//#####################################################################
// Function CFL_Strain_Rate
//#####################################################################
template<class TV> typename TV::SCALAR LINEAR_POINT_ATTRACTION<TV>::
CFL_Strain_Rate() const
{
return FLT_MAX;
}
//#####################################################################
// Function Add_Dependencies
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Add_Dependencies(SEGMENT_MESH& dependency_mesh) const
{
surface.mesh.Add_Dependencies(dependency_mesh);
}
//#####################################################################
// Function Update_Mpi
//#####################################################################
template<class TV> void LINEAR_POINT_ATTRACTION<TV>::
Update_Mpi(const ARRAY<bool>& particle_is_simulated,MPI_SOLIDS<TV>* mpi_solids)
{
}
//#####################################################################
// Function Potential_Energy
//#####################################################################
template<class TV> typename TV::SCALAR LINEAR_POINT_ATTRACTION<TV>::
Potential_Energy(const T time) const
{
T pe=0;
if(apply_explicit_forces)
for(int i=1;i<=referenced_particles.m;i++){int p=referenced_particles(i);
pe+=coefficient/2*(surface.particles.X(p)-point).Magnitude_Squared();}
return pe;
}
template class LINEAR_POINT_ATTRACTION<VECTOR<float,2> >;
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
template class LINEAR_POINT_ATTRACTION<VECTOR<double,2> >;
#endif
| 45.858065 | 172 | 0.50605 | schinmayee |
2654b5e3efc5be1d0082f933405667a1ae294b99 | 1,394 | cpp | C++ | Engine/Buffer.cpp | vazgriz/VoxelGame | 28b85445dc64606aecd840c977fb0557008e37a0 | [
"MIT"
] | 49 | 2020-02-12T21:09:07.000Z | 2021-11-19T00:43:55.000Z | Engine/Buffer.cpp | vazgriz/VoxelGame | 28b85445dc64606aecd840c977fb0557008e37a0 | [
"MIT"
] | 3 | 2020-08-11T14:36:00.000Z | 2020-08-17T08:50:11.000Z | Engine/Buffer.cpp | vazgriz/VoxelGame | 28b85445dc64606aecd840c977fb0557008e37a0 | [
"MIT"
] | 4 | 2020-02-18T08:55:16.000Z | 2021-05-13T01:50:37.000Z | #include "Engine/Buffer.h"
using namespace VoxelEngine;
BufferState::BufferState(Engine* engine, vk::Buffer&& buffer, VmaAllocation allocation) : buffer(std::move(buffer)) {
this->engine = engine;
this->allocation = allocation;
}
BufferState::BufferState(BufferState&& other) : buffer(std::move(other.buffer)) {
engine = other.engine;
allocation = other.allocation;
other.allocation = {};
}
BufferState& BufferState::operator = (BufferState&& other) {
engine = other.engine;
allocation = other.allocation;
other.allocation = VK_NULL_HANDLE;
return *this;
}
BufferState::~BufferState() {
vmaFreeMemory(engine->getGraphics().memory().allocator(), allocation);
}
Buffer::Buffer(Engine& engine, const vk::BufferCreateInfo& info, const VmaAllocationCreateInfo& allocInfo) {
m_engine = &engine;
VmaAllocator allocator = engine.getGraphics().memory().allocator();
info.marshal();
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, info.getInfo(), &allocInfo, &buffer, &allocation, &m_allocationInfo);
m_bufferState = std::make_unique<BufferState>(m_engine, vk::Buffer(engine.getGraphics().device(), buffer, true, &info), allocation);
}
Buffer::~Buffer() {
m_engine->renderGraph().queueDestroy(std::move(*m_bufferState));
}
void* Buffer::getMapping() const {
return m_allocationInfo.pMappedData;
} | 30.304348 | 135 | 0.716643 | vazgriz |
26590ee46fa324305d9056a31b982b5229718cb6 | 2,512 | cc | C++ | examples/hough_extruder_main.cc | WLChopSticks/vpp | 2e17b21c56680bcfa94292ef5117f73572bf277d | [
"MIT"
] | 624 | 2015-01-05T16:40:41.000Z | 2022-03-01T03:09:43.000Z | examples/hough_extruder_main.cc | WLChopSticks/vpp | 2e17b21c56680bcfa94292ef5117f73572bf277d | [
"MIT"
] | 10 | 2015-01-22T20:50:13.000Z | 2018-05-15T10:41:34.000Z | examples/hough_extruder_main.cc | WLChopSticks/vpp | 2e17b21c56680bcfa94292ef5117f73572bf277d | [
"MIT"
] | 113 | 2015-01-19T11:58:35.000Z | 2022-03-28T05:15:20.000Z | #include <iostream>
#include <time.h>
#include "hough_extruder_example.hh"
#include <chrono>
using namespace std;
using namespace Eigen;
using namespace cv;
using namespace vpp;
using namespace std::chrono;
int main(int argc, char *argv[])
{
// Start the computation of the time used by the function to compute
high_resolution_clock::time_point t1 = high_resolution_clock::now();
/**
* @brief fast_dht_matching
* This function allows to perform fast dense one-to-one Hough Transform
* The fisrt parameter represents the type media you want to use. you can use either an image or a video
* The second parameter represents the value of theta you want to use. This parameter defines the height of the array accumulator
* The third parameter represents the scaling which will be used for rho. This parameter can be used to reduced the size of the accumulator
* The parameter Type_video_hough represents the way the user wants to use after the tracking
* The parameter Type_Lines defines the way we describe lines. A line can be described by polar coordinates , the list of all points forming this lines , by the extremities of this lines
* The parameter With_Kalman_Filter represents the facts if the user wants to use kalman filter to perform prediction
* The parameter With_Transparency represents the way the user wants to print the trajectories with transpenrcy
* The parameter With_Entries represents the fact if the user wants the tracking to be performed with entries
*/
fast_dht_matching(dense_ht,Theta_max::SMALL, Sclare_rho::SAME,
Type_video_hough::ALL_POINTS,
Type_output::ORIGINAL_VIDEO,
Type_Lines::ONLY_POLAR,
Frequence::ALL_FRAME,
With_Kalman_Filter::NO,
With_Transparency::YES,
With_Entries::YES,
_rayon_exclusion_theta = 15,
_rayon_exclusion_rho = 12,
_slot_hough = 1,
_link_of_video_image = "m.png",
_acc_threshold = 100,
_m_first_lines = 5,
_max_trajectory_length = 5,
_nombre_max_frame_without_update =5);/**/
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>( t2 - t1 ).count();
//Show the time used to compute
cout << "la duree " << duration << endl ;
return 0;
}
| 47.396226 | 190 | 0.678742 | WLChopSticks |
265e672da87c5a8a88e40c9ae7d868741a0f41d6 | 2,246 | hpp | C++ | include/ipmi_to_redfish_hooks.hpp | tohas1986/intel-ipmi-oem | ca99ef5912b9296e09c8f9cb246ce291f9970750 | [
"Apache-2.0"
] | null | null | null | include/ipmi_to_redfish_hooks.hpp | tohas1986/intel-ipmi-oem | ca99ef5912b9296e09c8f9cb246ce291f9970750 | [
"Apache-2.0"
] | null | null | null | include/ipmi_to_redfish_hooks.hpp | tohas1986/intel-ipmi-oem | ca99ef5912b9296e09c8f9cb246ce291f9970750 | [
"Apache-2.0"
] | null | null | null | /*
// Copyright (c) 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.
*/
#pragma once
#include <storagecommands.hpp>
namespace intel_oem::ipmi::sel
{
bool checkRedfishHooks(uint16_t recordID, uint8_t recordType,
uint32_t timestamp, uint16_t generatorID, uint8_t evmRev,
uint8_t sensorType, uint8_t sensorNum, uint8_t eventType,
uint8_t eventData1, uint8_t eventData2,
uint8_t eventData3);
bool checkRedfishHooks(uint8_t generatorID, uint8_t evmRev, uint8_t sensorType,
uint8_t sensorNum, uint8_t eventType, uint8_t eventData1,
uint8_t eventData2, uint8_t eventData3);
namespace redfish_hooks
{
struct SELData
{
int generatorID;
int sensorNum;
int eventType;
int offset;
int eventData2;
int eventData3;
};
enum class BIOSSensors
{
memoryRASConfigStatus = 0x02,
biosPOSTError = 0x06,
intelUPILinkWidthReduced = 0x09,
memoryRASModeSelect = 0x12,
bootEvent = 0x83,
};
enum class BIOSSMISensors
{
mirroringRedundancyState = 0x01,
memoryECCError = 0x02,
legacyPCIError = 0x03,
pcieFatalError = 0x04,
pcieCorrectableError = 0x05,
sparingRedundancyState = 0x11,
memoryParityError = 0x13,
pcieFatalError2 = 0x14,
biosRecovery = 0x15,
adddcError = 0x20,
};
enum class BIOSEventTypes
{
digitalDiscrete = 0x09,
discreteRedundancyStates = 0x0b,
sensorSpecificOffset = 0x6f,
oemDiscrete0 = 0x70,
oemDiscrete1 = 0x71,
oemDiscrete6 = 0x76,
oemDiscrete7 = 0x77,
reservedA0 = 0xa0,
reservedF0 = 0xf0,
};
} // namespace redfish_hooks
} // namespace intel_oem::ipmi::sel
| 28.43038 | 80 | 0.691451 | tohas1986 |
265e76f8f5673089b30487c90c8cee60c9f4dfc2 | 1,839 | cpp | C++ | GeeksForGeeks/C Plus Plus/Chocolate_Distribution_Problem.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 4 | 2021-06-19T14:15:34.000Z | 2021-06-21T13:53:53.000Z | GeeksForGeeks/C Plus Plus/Chocolate_Distribution_Problem.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 2 | 2021-07-02T12:41:06.000Z | 2021-07-12T09:37:50.000Z | GeeksForGeeks/C Plus Plus/Chocolate_Distribution_Problem.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 3 | 2021-06-19T15:19:20.000Z | 2021-07-02T17:24:51.000Z | /*
Problem Statement:
------------------
Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates.
There are M students, the task is to distribute chocolate packets among M students such that :
1. Each student gets exactly one packet.
2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum.
Example 1:
---------
Input:
N = 8, M = 5
A = {3, 4, 1, 9, 56, 7, 9, 12}
Output: 6
Explanation: The minimum difference between maximum chocolates and minimum chocolates is 9 - 3 = 6 by choosing following M packets : {3, 4, 9, 7, 9}.
Example 2:
---------
Input:
N = 7, M = 3
A = {7, 3, 2, 4, 9, 12, 56}
Output: 2
Explanation: The minimum difference between maximum chocolates and minimum chocolates is 4 - 2 = 2 by choosing following M packets : {3, 2, 4}.
Your Task: You don't need to take any input or print anything. Your task is to complete the function findMinDiff() which takes array A[ ], N and M as input parameters
and returns the minimum possible difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student.
Expected Time Complexity: O(N*Log(N))
Expected Auxiliary Space: O(1)
*/
// Link --> https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1
// Code:
class Solution
{
public:
long long findMinDiff(vector<long long> a, long long n, long long m)
{
sort(a.begin(), a.end());
long long minDifference = INT_MAX;
for(long long i=0 ; i<(n-m+1) ; i++)
{
if(abs(a[i] - a[i+m-1]) < minDifference)
minDifference = abs(a[i] - a[i+m-1]);
}
return minDifference;
}
};
| 36.78 | 172 | 0.677542 | ankit-sr |
265eb2b49680b8932ba23fad9cf73db463c4dc83 | 7,490 | cpp | C++ | Path planning visualizer/src/Grid.cpp | wholol/graph-visualizer | d63b20b9b6846ec86face6db131eca56c030f280 | [
"MIT"
] | 4 | 2020-10-02T14:34:43.000Z | 2021-11-15T11:42:20.000Z | Path planning visualizer/src/Grid.cpp | wholol/graph-visualizer | d63b20b9b6846ec86face6db131eca56c030f280 | [
"MIT"
] | null | null | null | Path planning visualizer/src/Grid.cpp | wholol/graph-visualizer | d63b20b9b6846ec86face6db131eca56c030f280 | [
"MIT"
] | 1 | 2021-07-09T09:32:26.000Z | 2021-07-09T09:32:26.000Z | #include "Grid.h"
#include <iostream>
#include <thread>
Grid::Grid(int screenwidth, int screenheight, const sf::Mouse& mouse, sf::RenderWindow& createwindow)
:screenwidth(screenwidth),
screenheight(screenheight),
mouse(mouse),
createwindow(createwindow)
{
/*compute Number of Tiles*/
NumTilesX = screenwidth / TileDimension;
NumTilesY = screenheight / TileDimension;
/* initialize default src and targ et pos*/
srcpos = { 0 ,0 };
targetpos = { NumTilesX - 1 , NumTilesY - 1 };
for (int i = 0; i < NumTilesX * NumTilesY; ++i) { //initialize all tile objects
TileMap.emplace_back(sf::Vector2f(TileDimension, TileDimension)); //costruct dimensions
}
for (int x = 0; x < NumTilesX; ++x) {
for (int y = 0; y < NumTilesY; ++y) {
TileMap[x * NumTilesX + y].setPosition(sf::Vector2f(x * TileDimension, y * TileDimension));
TileMap[x * NumTilesX + y].setFillColor(openTileColour);
TileMap[x * NumTilesX + y].setOutlineColor(sf::Color::Black);
TileMap[x * NumTilesX + y].setOutlineThickness(-OutlineThickness);
}
}
/* colour src and target pos*/
TileMap[srcpos.posx * NumTilesX + srcpos.posy].setFillColor(srcTileColour);
TileMap[targetpos.posx * NumTilesX + targetpos.posy].setFillColor(targetTileColour);
}
void Grid::drawGrid()
{
for (const auto& Tiles : TileMap) {
createwindow.draw(Tiles);
} //draw tiles
}
void Grid::drawPath()
{
if (vertices.size() > 0) {
createwindow.draw(&vertices[0], vertices.size(), sf::Lines);
}
}
void Grid::setObstacle()
{
int mouseposx = mouse.getPosition(createwindow).x;
int mouseposy = mouse.getPosition(createwindow).y;
int x = (int)(mouseposx / TileDimension); //scale mouse coodinates
int y = (int)(mouseposy / TileDimension); //scale mouse coordinats
if (outofBounds(x, y)) {
return;
}
Location mouseloc = { x , y }; //cache mouse location of the grid
//reset obstacle colour to open colour
if (getTileColor(mouseloc) == obstacleTileColour) {
setTileColor(mouseloc, openTileColour);
Obstacles.erase(std::remove(Obstacles.begin(), Obstacles.end(), mouseloc), Obstacles.end());
return;
}
if (getTileColor(mouseloc) == srcTileColour) { //do not set obstacle for src colour
return;
}
if (getTileColor(mouseloc) == targetTileColour) { //do not set obstacle for colourd tile
return;
}
setTileColor(mouseloc, obstacleTileColour); //set the tile colour
Obstacles.emplace_back(mouseloc);
}
void Grid::setTarget()
{
int mouseposx = mouse.getPosition(createwindow).x;
int mouseposy = mouse.getPosition(createwindow).y;
int x = (int)(mouseposx / TileDimension);
int y = (int)(mouseposy / TileDimension);
if (outofBounds(x, y)) {
return;
}
Location prevTargetLoc; //cache the previous Target location
Location mouseLoc = { x , y };
if (getTileColor(mouseLoc) == targetTileColour) {
changingTargetPos = true; //set putting source position to true
prevTargetLoc = { x , y };
}
while (changingTargetPos) { //while the user is tryig to change the position of the source.
int mouseposx = mouse.getPosition(createwindow).x;
int mouseposy = mouse.getPosition(createwindow).y;
int x = (int)(mouseposx / TileDimension);
int y = (int)(mouseposy / TileDimension);
Location newTargetLoc = { x , y }; //keep polling for new target location
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) {
if (getTileColor(newTargetLoc) == obstacleTileColour) { //if tile is obstacle, continue
continue;
}
if (getTileColor(newTargetLoc) == srcTileColour) { //if user chooses target tile
changingSrcPos = false; //do not let changing target pos be true if user is trying to chang src pos.
continue;
}
if (getTileColor(newTargetLoc) == openTileColour) { //if the new target tile is open
setTileColor(newTargetLoc, targetTileColour); //set the tile colour
updateTargetPos(newTargetLoc); //update the target position.
setTileColor(prevTargetLoc, openTileColour); //set the tile colour of the old target position to open
changingTargetPos = false;
break;
}
}
}
}
void Grid::setSource()
{
int mouseposx = mouse.getPosition(createwindow).x;
int mouseposy = mouse.getPosition(createwindow).y;
int x = (int)(mouseposx / TileDimension);
int y = (int)(mouseposy / TileDimension);
if (outofBounds(x, y)) {
return;
}
Location prevSrcLoc; //cache the previous source location
Location mouseLoc = { x , y };
if (getTileColor(mouseLoc) == srcTileColour) {
changingSrcPos = true; //set putting source position to true
prevSrcLoc = { x , y };
}
while (changingSrcPos) { //while the user is tryig to change the position of the source.
int mouseposx = mouse.getPosition(createwindow).x;
int mouseposy = mouse.getPosition(createwindow).y;
int x = (int)(mouseposx / TileDimension);
int y = (int)(mouseposy / TileDimension);
Location newSrcLoc = { x , y };
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) {
if (getTileColor(newSrcLoc) == obstacleTileColour) {
continue;
}
if (getTileColor(newSrcLoc) == targetTileColour) { //if user chooses target tile
changingTargetPos = false; //do not let changing target pos be true if user is trying to chang src pos.
continue;
}
if (getTileColor(newSrcLoc) == openTileColour) { //if the new src tile is open
setTileColor(newSrcLoc, srcTileColour); //set the tile colour
updateSrcPos(newSrcLoc); //update the source position.
setTileColor(prevSrcLoc, openTileColour); //set the tile colour of the old src position to open
changingSrcPos = false;
break;
}
}
}
}
void Grid::ColourVisitedTile(const Location& loc)
{
if (loc == srcpos || loc == targetpos) return; //do not recolour srcpos
setTileColor(loc, visitedTileColour);
}
void Grid::ColourVisitingTile(const Location& loc)
{
if (loc == srcpos || loc == targetpos) return; //do not recolour target pos
setTileColor(loc, visitngTileColour);
}
void Grid::ColourPathTile(const Location& loc_1 , const Location& loc_2)
{
vertices.push_back(sf::Vertex(sf::Vector2f(loc_1.posx * TileDimension + (TileDimension / 2), loc_1.posy * TileDimension + (TileDimension / 2))));
vertices.push_back(sf::Vertex(sf::Vector2f(loc_2.posx * TileDimension + (TileDimension / 2), loc_2.posy * TileDimension + (TileDimension / 2))));
}
void Grid::resetGrid()
{
for (auto& tile : TileMap) {
if (tile.getFillColor() == obstacleTileColour) {
continue;
}
tile.setFillColor(openTileColour);
}
setTileColor(srcpos, srcTileColour);
setTileColor(targetpos, targetTileColour);
vertices.clear();
}
std::vector<Location> Grid::getObstacleLocation() const
{
return Obstacles;
}
std::tuple<int, int> Grid::getTileNums() const
{
return std::make_tuple(NumTilesX, NumTilesY);
}
Location Grid::getTargetPos() const
{
return targetpos;
}
Location Grid::getSrcPos() const
{
return srcpos;
}
void Grid::updateSrcPos(const Location& loc)
{
srcpos.posx = loc.posx;
srcpos.posy = loc.posy;
}
void Grid::updateTargetPos(const Location& loc)
{
targetpos.posx = loc.posx;
targetpos.posy = loc.posy;
}
sf::Color Grid::getTileColor(const Location& loc) const
{
return TileMap[loc.posx * NumTilesX + loc.posy].getFillColor();
}
void Grid::setTileColor(const Location& loc ,const sf::Color& color)
{
TileMap[loc.posx * NumTilesX + loc.posy].setFillColor(color);
}
bool Grid::outofBounds(int x, int y)
{
if (x < 0 || y < 0 || x >= screenwidth || y >= screenheight) { //bound check
return true;
}
return false;
}
| 27.947761 | 146 | 0.702403 | wholol |
265f9e8140388f40f794cbcee767b6213ddf0839 | 24 | cpp | C++ | ExercicesCours/Bureaux/Imprimante.cpp | MamadouBarri/OOP-Cpp | a00f2eff50666ab0ca5461bb1caab6c83cfb5933 | [
"MIT"
] | null | null | null | ExercicesCours/Bureaux/Imprimante.cpp | MamadouBarri/OOP-Cpp | a00f2eff50666ab0ca5461bb1caab6c83cfb5933 | [
"MIT"
] | null | null | null | ExercicesCours/Bureaux/Imprimante.cpp | MamadouBarri/OOP-Cpp | a00f2eff50666ab0ca5461bb1caab6c83cfb5933 | [
"MIT"
] | null | null | null | #include "Imprimante.h"
| 12 | 23 | 0.75 | MamadouBarri |
265fe908e1cdd09ce0559bedcb32a0d19133feb5 | 121 | cpp | C++ | test/NoiseGenerator_test.cpp | leiz86/staircase_code_simulator | bba297c1c1fbb4921855b0e4f43afb505c1235fa | [
"Apache-2.0"
] | null | null | null | test/NoiseGenerator_test.cpp | leiz86/staircase_code_simulator | bba297c1c1fbb4921855b0e4f43afb505c1235fa | [
"Apache-2.0"
] | null | null | null | test/NoiseGenerator_test.cpp | leiz86/staircase_code_simulator | bba297c1c1fbb4921855b0e4f43afb505c1235fa | [
"Apache-2.0"
] | null | null | null | /*
* NoiseGenerator_test.cpp
*
* Created on: Nov 26, 2017
* Author: leizhang
*/
#include <NoiseGenerator.h>
| 12.1 | 28 | 0.628099 | leiz86 |
2663d55719e175bb44c8b22cd16e5299476c07b4 | 1,634 | cpp | C++ | vlc_linux/vlc-3.0.16/modules/gui/skins2/events/evt_special.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/skins2/events/evt_special.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/skins2/events/evt_special.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*****************************************************************************
* evt_special.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id: afa1d1f87334adf30bdb4ef194974f71b54e40e5 $
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "evt_special.hpp"
const std::string EvtSpecial::getAsString() const
{
std::string event = "special";
// Add the action
if( m_action == kShow )
event += ":show";
else if( m_action == kHide )
event += ":hide";
else if( m_action == kEnable )
event += ":enable";
else if( m_action == kDisable )
event += ":disable";
else
msg_Warn( getIntf(), "unknown action type" );
return event;
}
| 34.765957 | 80 | 0.579559 | Brook1711 |
266a9ad44d2dd4daea13178aac7d0e06a0c12ff8 | 5,039 | hpp | C++ | include/grid_based_planner.hpp | dabinkim-LGOM/lsc_planner | 88dcb1de59bac810d1b1fd194fe2b8d24d1860c9 | [
"MIT"
] | 9 | 2021-09-04T15:14:57.000Z | 2022-03-29T04:34:13.000Z | include/grid_based_planner.hpp | dabinkim-LGOM/lsc_planner | 88dcb1de59bac810d1b1fd194fe2b8d24d1860c9 | [
"MIT"
] | null | null | null | include/grid_based_planner.hpp | dabinkim-LGOM/lsc_planner | 88dcb1de59bac810d1b1fd194fe2b8d24d1860c9 | [
"MIT"
] | 4 | 2021-09-29T11:32:54.000Z | 2022-03-06T05:24:33.000Z | #ifndef LSC_PLANNER_GRIDBASEDPLANNER_HPP
#define LSC_PLANNER_GRIDBASEDPLANNER_HPP
#include <Astar-3D/astarplanner.h>
#include <dynamicEDT3D/dynamicEDTOctomap.h>
#include <mission.hpp>
#include <param.hpp>
#include <util.hpp>
#include <geometry.hpp>
#include <utility>
#define GP_OCCUPIED 1
#define GP_EMPTY 0
#define GP_INFINITY 10000
// Wrapper for grid based path planner
namespace DynamicPlanning {
struct GridVector{
public:
GridVector(){
data = {-1, -1, -1};
}
GridVector(int i, int j, int k){
data = {i, j, k};
}
GridVector operator+(const GridVector& other_node) const;
GridVector operator-(const GridVector& other_node) const;
GridVector operator*(int integer) const;
GridVector operator-() const;
bool operator== (const GridVector &other_node) const;
bool operator< (const GridVector &other_node) const;
int dot(const GridVector& other_agent) const;
double norm() const;
int i() const { return data[0]; }
int j() const { return data[1]; }
int k() const { return data[2]; }
int& operator[](unsigned int idx) { return data[idx]; }
const int& operator[](unsigned int idx) const { return data[idx]; }
std::array<int,3> toArray() const { return data; }
private:
std::array<int,3> data{-1,-1,-1};
};
struct GridInfo{
std::array<double,3> grid_min;
std::array<double,3> grid_max;
std::array<int,3> dim;
};
struct GridMap{
std::vector<std::vector<std::vector<int>>> grid;
int getValue(GridVector grid_node) const{
return grid[grid_node[0]][grid_node[1]][grid_node[2]];
}
void setValue(GridVector grid_node, int value){
grid[grid_node[0]][grid_node[1]][grid_node[2]] = value;
}
};
struct GridMission{
GridVector start_point;
GridVector goal_point;
};
typedef std::vector<octomap::point3d> path_t;
typedef std::vector<GridVector> gridpath_t;
struct PlanResult{
path_t path;
gridpath_t grid_path;
};
class GridBasedPlanner {
public:
GridBasedPlanner(const std::shared_ptr<DynamicEDTOctomap>& _distmap_obj,
const DynamicPlanning::Mission &_mission,
const DynamicPlanning::Param &_param);
path_t plan(const octomap::point3d& current_position,
const octomap::point3d& goal_position,
int agent_id,
double agent_radius,
double agent_downwash,
const std::vector<dynamic_msgs::Obstacle>& obstacles = {},
const std::set<int>& high_priority_obstacle_ids = {});
// Getter
std::vector<octomap::point3d> getFreeGridPoints();
// Goal
octomap::point3d findLOSFreeGoal(const octomap::point3d& current_position,
const octomap::point3d& goal_position,
const std::vector<dynamic_msgs::Obstacle>& obstacles,
double agent_radius,
const std::vector<octomap::point3d>& additional_check_positions = {});
private:
Mission mission;
Param param;
std::shared_ptr<DynamicEDTOctomap> distmap_obj;
GridInfo grid_info{};
GridMap grid_map;
GridMission grid_mission;
PlanResult plan_result;
void updateGridInfo(const octomap::point3d& current_position, double agent_radius);
void updateGridMap(const octomap::point3d& current_position,
const std::vector<dynamic_msgs::Obstacle>& obstacles,
double agent_radius,
double agent_downwash,
const std::set<int>& high_priority_obstacle_ids = {});
void updateGridMission(const octomap::point3d& current_position,
const octomap::point3d& goal_position,
int agent_id);
bool isValid(const GridVector& grid_node);
bool isOccupied(const GridMap& map, const GridVector& grid_node);
static gridpath_t plan_impl(const GridMap& grid_map, const GridMission& grid_mission);
static gridpath_t planAstar(const GridMap& grid_map, const GridMission& grid_mission);
path_t gridPathToPath(const gridpath_t& grid_path) const;
octomap::point3d gridVectorToPoint3D(const GridVector& grid_vector) const;
octomap::point3d gridVectorToPoint3D(const GridVector& grid_vector, int dimension) const;
GridVector point3DToGridVector(const octomap::point3d& point) const;
bool castRay(const octomap::point3d& current_position, const octomap::point3d& goal_position,
double agent_radius);
};
}
#endif //LSC_PLANNER_GRIDBASEDPLANNER_HPP
| 33.818792 | 111 | 0.609248 | dabinkim-LGOM |
2672c5e5a8bef72d163fd4d3809f0385a820ad4d | 6,516 | cpp | C++ | demo/cpp/deepq.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 57 | 2015-02-16T06:43:24.000Z | 2022-03-16T06:21:36.000Z | demo/cpp/deepq.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 4 | 2016-03-08T09:51:09.000Z | 2021-03-29T10:18:55.000Z | demo/cpp/deepq.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 27 | 2015-03-28T19:55:34.000Z | 2022-01-09T15:03:15.000Z | #include "opencv2/opencv.hpp"
#include "profile.h"
using namespace cv;
using namespace std;
inline float sigmoid(float x) {
return 1.0f / (1.0f + exp(-1*x));
}
inline float sigmoid_sym(float x) {
float t = x * x * 2.751;
return 0.5f * (1.0f - t) / (1.0f + t);
}
inline float relu(float x) {
return (x > 0) ? x : 0; //0.01f * x;
}
inline float linear(float x) {
return 1.0/(x*x*5+1);
}
inline float act(float x) {
return linear(x);
}
struct Deepq {
struct Experience {
Mat state;
int action;
float reward;
Experience(const Mat &s=Mat(), int a=0, float r=0) : state(s), action(a), reward(r) {}
};
const size_t MaxExp = 1000;
float gamma;
int current,nactions,batchsize,age;
vector<Experience> e;
Ptr<ml::ANN_MLP> nn;
RNG rng;
Deepq(int nin, int nout, int batch) : gamma(0.05f), current(0), nactions(nout), batchsize(batch), age(0), rng(getTickCount()) {
Mat_<int> layers(1,4); layers << nin, 256, 256, nout;
nn = ml::ANN_MLP::create();
nn->setLayerSizes(layers);
nn->setTrainMethod(ml::ANN_MLP::BACKPROP, 0.001);
nn->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM);
nn->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS, 1, 0.0001));
}
// todo: we need independant test data, not the train set
float loss() {
PROFILE
Mat data, labels(MaxExp-1, nactions, CV_32F, 0.0f);
for (int i=1; i<MaxExp; i++) {
data.push_back(e[i].state);
labels.at<float>(i-1, e[i-1].action) = act(gamma*e[i-1].reward);
}
return nn->calcError(ml::TrainData::create(data,0,labels), false, noArray());
}
int forward(const Mat &state, bool learn) {
PROFILE
int action = 0;
age ++;
int n = rng.uniform(0, 10);
if (n>3 || (!nn->isTrained())) {
action = rng.uniform(0, nactions);
} else {
action = (int)nn->predict(state);
}
if (1) {
// save experience
// (we don't know the reward yet)
Experience ex(state, action, 0);
if (e.size() < MaxExp) {
e.push_back(ex);
} else {
e[current] = ex;
}
}
return action;
}
void backward(float reward) {
PROFILE
e[current].reward = reward;
current ++;
current %= MaxExp;
int flag = nn->isTrained() ? 0 : 1+2+4;
if (e.size() < batchsize) {
Mat labels(1, nactions, CV_32F, 0.0f);
randu(labels, 0, 1.0/nactions);
nn->train(ml::TrainData::create(e.back().state, 0, labels), flag);
return;
}
for (int b=0; b<batchsize; b++) {
PROFILEX("batch")
// "dream" a random experience
size_t i = theRNG().uniform(0, e.size()-1);
Experience &cur = e[i];
Experience &nxt = e[(i+1) % e.size()];
// max policy
float maxval=0;
int maxid=0;
{
PROFILEX("policy")
Mat_<float> res;
nn->predict(cur.state, res);
if ((b<3)&&(age%150==0))cerr << age << format(" {%6.3f %6.3f %6.3f} ",res(0),res(1),res(2));
for (int r=0; r<res.total(); r++) {
float v = res.at<float>(r);
if (v > maxval) {
maxid = r;
maxval = v;
}
}
}
// update network weights on next state
{
PROFILEX("train")
Mat_<float> labels(1, nactions, 0.0f);
float activation = act(gamma * maxval * cur.reward);
labels(0, cur.action) = activation;
bool ok = nn->train(ml::TrainData::create(nxt.state, 0, labels), flag); // update
if ((b<3) && (age%150==0))cerr << format("{%5.3f %5.3f %5.3f} %d %d %5.3f %5.3f %5.3f",labels(0),labels(1),labels(2),cur.action,maxid,maxval,cur.reward,activation) << endl;
}
// cost ?
}
if (age % 3000 == 0)
nn->save("rlmaze.xml");
}
};
typedef vector<Point3f> Pills; // x,y,color
Point3f newPill(const Mat &maze) {
return Point3f{
float(theRNG().uniform(0, maze.cols)),
float(theRNG().uniform(0, maze.rows)),
float(theRNG().uniform(0, 2)*2-1)
};
}
Pills randomPills(const Mat &maze) {
Pills pills;
for (int i=0; i<20; i++) {
pills.push_back(newPill(maze));
}
return pills;
}
struct Pacman {
Deepq brain;
Point pos;
int rad, srad, angle;
bool learn;
Pacman() : brain(9,3,16), pos(20,120), rad(10), srad(50), angle(90), learn(true) {}
bool sense(Mat &maze, Mat &state) {
state = Mat(1,9,CV_32F,0.0f);
bool can_move = true;
//float weights[9] = {0.6, 0.7, 0.8, 1.0, 1.2, 1.0, 0.8, 0.7, 0.6}; // prefer forward
float weights[9] = {1,1,1,1,1,1,1,1,1}; // straight
//float weights[9] = {1,1,0.9,0.5,0.3,0.5,0.9,1,1};
for (int k=0,i=-60; i<=60; i+=15,k++) {
double s = sin((i+angle)*CV_PI/180);
double c = cos((i+angle)*CV_PI/180);
Point p2(pos.x+s*srad, pos.y+c*srad);
LineIterator it(maze, pos, p2, 8);
int r=0;
float food = 0.0f;
for (; r<srad; r++) {
Vec3b & pixel = maze.at<Vec3b>(it.pos());
if (pixel[0] > 50)
pixel[1] = pixel[2] = 0; // set g and b to 0, leaves blue line
else {
bool g = pixel[1] > 50;
bool r = pixel[2] > 50;
food = (g && !r) ? 1.0f : (!g && r) ? -1.0f : -0.3f;
break;
}
it++;
}
if (r<rad+3 && food<=0) can_move = false;
state.at<float>(0,k) = (food + weights[k]) * (float)r / srad;
}
return can_move;
}
void move(Mat &maze) {
Mat state;
bool can_move = sense(maze, state);
int action = brain.forward(state, learn);
switch(action) {
case 0:
if (can_move) {
double s = sin(angle*CV_PI/180);
double c = cos(angle*CV_PI/180);
pos = Point(pos.x+s*3, pos.y+c*3);
}
break;
case 1: angle -= 10; break;
case 2: angle += 10; break;
}
if (! learn) return;
//float reward = can_move ? sum(state)[0] : 0.1f;
float reward = sum(state)[0];
brain.backward(reward);
}
void draw(Mat &draw) {
circle(draw,pos,rad,Scalar(255,0,0),-1,CV_AA);
}
};
int main() {
Mat img = imread("maze.png");
Pills pills = randomPills(img);
Pacman pac;
while(1) {
Mat maze = img.clone();
if ((pac.brain.age>1100) && (pac.brain.age % 500==0))
cerr << endl << "loss: " << pac.brain.loss() << endl;
pac.move(maze);
pac.draw(maze);
for (auto p=pills.begin(); p!=pills.end(); p++) {
if (abs(pac.pos.x-p->x)<pac.rad+5+7 && abs(pac.pos.y-p->y)<pac.rad+5+7) {
cerr << "- " << *p;
*p = newPill(maze);
cerr << " + " << *p << endl;
} else {
circle(maze,Point(p->x,p->y),7,(p->z>0?Scalar(0,0,180):Scalar(0,180,0)), -1, LINE_AA);
}
}
imshow("maze", maze);
int k = waitKey(3);
if (k =='r') pills = randomPills(maze);
if (k ==27) break;
if (k=='l') { pac.learn = ! pac.learn; cerr << "learn " << pac.learn << " " << pac.brain.age << endl; }
}
return 0;
}
| 27.263598 | 176 | 0.570135 | berak |
2675cf7fe66182e56a62f448aa2611e77cc38856 | 215 | cpp | C++ | Programming/C++/Recursion/easy/DigitProduct.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | Programming/C++/Recursion/easy/DigitProduct.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | Programming/C++/Recursion/easy/DigitProduct.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | #include <iostream>
using namespace std;
int prod(int n)
{
if (n % 10 == n)
{
return n;
}
return (n % 10) * prod(n / 10);
}
int main()
{
int ans = prod(12345);
cout << ans << endl;
}
| 13.4375 | 35 | 0.488372 | shreejitverma |
2679449964f5055fd3443048f784dbb13d5b2a39 | 2,858 | hpp | C++ | third_party/easywsclient/easywsclient.hpp | RobLoach/ion | 9e659416fb04bb3d3a67df1e018d7c2ccab9d468 | [
"Apache-2.0"
] | 1 | 2020-03-12T12:49:31.000Z | 2020-03-12T12:49:31.000Z | third_party/easywsclient/easywsclient.hpp | RobLoach/ion | 9e659416fb04bb3d3a67df1e018d7c2ccab9d468 | [
"Apache-2.0"
] | null | null | null | third_party/easywsclient/easywsclient.hpp | RobLoach/ion | 9e659416fb04bb3d3a67df1e018d7c2ccab9d468 | [
"Apache-2.0"
] | null | null | null | #ifndef EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD
#define EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD
// This code comes from:
// https://github.com/dhbaird/easywsclient
//
// To get the latest version:
// wget https://raw.github.com/dhbaird/easywsclient/master/easywsclient.hpp
// wget https://raw.github.com/dhbaird/easywsclient/master/easywsclient.cpp
#include <stdio.h>
#include <string>
namespace easywsclient {
class WebSocket {
public:
// Google change: expose opcode in header file.
enum Opcode {
CONTINUATION = 0x0,
TEXT_FRAME = 0x1,
BINARY_FRAME = 0x2,
CLOSE = 0x8,
PING = 0x9,
PONG = 0xa,
};
typedef WebSocket * pointer;
typedef enum readyStateValues { CLOSING, CLOSED, CONNECTING, OPEN } readyStateValues;
// Factories:
static pointer create_dummy();
static pointer from_url(const std::string& url, const std::string& origin = std::string());
static pointer from_url_no_mask(const std::string& url, const std::string& origin = std::string());
// Interfaces:
virtual ~WebSocket() { }
virtual void poll(int timeout = 0) = 0; // timeout in milliseconds
virtual void send(const std::string& message) = 0;
virtual void sendPing() = 0;
virtual void close() = 0;
virtual readyStateValues getReadyState() const = 0;
template<class Callable>
void dispatch(Callable callable) { // N.B. this is compatible with both C++11 lambdas, functors and C function pointers
struct _Callback : public Callback {
Callable& callable;
_Callback(Callable& callable) : callable(callable) { }
void operator()(const std::string& message) { callable(message); }
};
_Callback callback(callable);
_dispatch(callback);
}
// Google change: provide low-level frame-sending. Not totally comprehensive:
// for example, it doesn't allow a mask to be specified. Doesn't do any
// verification; it's your responsibility to ensure that the frames you send
// are valid with respect to RFC 6455... for example: don't send a continuation
// frame without first sending a binary/text frame without the FIN bit set.
virtual void sendData(Opcode opcode, const std::string& message, bool fin) = 0;
// Google change: provide a way to reroute all info/error messages. Setting
// to NULL disables all output.
static void setMessageStream(FILE *stream) { messageStream = stream; }
protected:
struct Callback {
// Google change: add virtual destructor.
virtual ~Callback() {}
virtual void operator()(const std::string& message) = 0;
};
static FILE *messageStream;
virtual void _dispatch(Callback& callable) = 0;
};
} // namespace easywsclient
#endif /* EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD */
| 36.177215 | 123 | 0.684395 | RobLoach |
267aa65c510760702f68bcedb31fd02455d75427 | 5,927 | cpp | C++ | models/lnd/clm/src/iac/giac/gcam/cvs/objects/containers/source/output_meta_data.cpp | E3SM-Project/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 9 | 2018-05-15T02:10:40.000Z | 2020-01-10T18:27:31.000Z | models/lnd/clm/src/iac/giac/gcam/cvs/objects/containers/source/output_meta_data.cpp | zhangyue292/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 3 | 2018-10-12T18:41:56.000Z | 2019-11-12T15:18:49.000Z | models/lnd/clm/src/iac/giac/gcam/cvs/objects/containers/source/output_meta_data.cpp | zhangyue292/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 3 | 2018-05-15T02:10:33.000Z | 2021-04-06T17:45:49.000Z | /*
* LEGAL NOTICE
* This computer software was prepared by Battelle Memorial Institute,
* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830
* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE
* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY
* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this
* sentence must appear on any copies of this computer software.
*
* EXPORT CONTROL
* User agrees that the Software will not be shipped, transferred or
* exported into any country or used in any manner prohibited by the
* United States Export Administration Act or any other applicable
* export laws, restrictions or regulations (collectively the "Export Laws").
* Export of the Software may require some form of license or other
* authority from the U.S. Government, and failure to obtain such
* export control license may result in criminal liability under
* U.S. laws. In addition, if the Software is identified as export controlled
* items under the Export Laws, User represents and warrants that User
* is not a citizen, or otherwise located within, an embargoed nation
* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)
* and that User is not otherwise prohibited
* under the Export Laws from receiving the Software.
*
* Copyright 2011 Battelle Memorial Institute. All Rights Reserved.
* Distributed as open-source under the terms of the Educational Community
* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php
*
* For further details, see: http://www.globalchange.umd.edu/models/gcam/
*
*/
/*!
* \file output_meta_data.cpp
* \ingroup Objects
* \brief The OutputMetaData class source file
* \author Josh Lurz
*/
#include "util/base/include/definitions.h"
#include <xercesc/dom/DOMNode.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include "containers/include/output_meta_data.h"
#include "util/base/include/ivisitor.h"
#include "util/base/include/xml_helper.h"
#include "util/logger/include/ilogger.h"
using namespace std;
using namespace xercesc;
//! Constructor
OutputMetaData::OutputMetaData() {
}
/*! \brief Get the XML node name in static form for comparison when parsing XML.
*
* This public function accesses the private constant string, XML_NAME.
* This way the tag is always consistent for both read-in and output and can be easily changed.
* The "==" operator that is used when parsing, required this second function to return static.
* \note A function cannot be static and virtual.
* \author Josh Lurz, James Blackwood
* \return The constant XML_NAME as a static.
*/
const std::string& OutputMetaData::getXMLNameStatic() {
const static string XML_NAME = "output-meta-data";
return XML_NAME;
}
/*! \brief Write out XML data for input.
* \param aOut Output stream.
* \param aTabs Tabs object.
*/
void OutputMetaData::toInputXML( ostream& aOut, Tabs* aTabs ) const {
XMLWriteOpeningTag ( getXMLNameStatic(), aOut, aTabs );
typedef list<string>::const_iterator CListIterator;
map<string, string> attrs;
for( CListIterator iter = mPrimaryFuels.begin(); iter != mPrimaryFuels.end(); ++iter ) {
attrs[ "var" ] = *iter;
XMLWriteElementWithAttributes( "", "primary-fuel", aOut, aTabs, attrs );
}
for( CListIterator iter = mSummableVariables.begin(); iter != mSummableVariables.end(); ++iter ) {
attrs[ "var" ] = *iter;
XMLWriteElementWithAttributes( "", "summable", aOut, aTabs, attrs );
}
for( CListIterator iter = mHasYearVariables.begin(); iter != mHasYearVariables.end(); ++iter ) {
attrs[ "var" ] = *iter;
XMLWriteElementWithAttributes( "", "has-year", aOut, aTabs, attrs );
}
XMLWriteElement( mScenarioSummary, "summary", aOut, aTabs );
XMLWriteClosingTag( getXMLNameStatic(), aOut, aTabs );
}
/*! \brief Parse the meta-data from XML.
* \details The model does not use this meta-data internally but reads it from
* the input XML file here and passes that information along to both the
* database output xml and the derived xml input file.
* \param aNode Root node of the object's DOM subtree.
*/
void OutputMetaData::XMLParse( const DOMNode* aNode ) {
/*! \pre make sure we were passed a valid node. */
assert( aNode );
// get all child nodes.
const DOMNodeList* nodeList = aNode->getChildNodes();
// loop through the child nodes.
for( unsigned int i = 0; i < nodeList->getLength(); i++ ){
const DOMNode* curr = nodeList->item( i );
if( curr->getNodeType() != DOMNode::ELEMENT_NODE ){
continue;
}
const string nodeName = XMLHelper<string>::safeTranscode( curr->getNodeName() );
if( nodeName == "primary-fuel" ){
mPrimaryFuels.push_back( XMLHelper<string>::getAttr( curr, "var" ) );
}
else if( nodeName == "summable" ){
mSummableVariables.push_back( XMLHelper<string>::getAttr( curr, "var" ) );
}
else if( nodeName == "has-year" ){
mHasYearVariables.push_back( XMLHelper<string>::getAttr( curr, "var" ) );
}
else if ( nodeName == "summary" ){
mScenarioSummary = XMLHelper<string>::getValue( curr );
}
else {
ILogger& mainLog = ILogger::getLogger( "main_log" );
mainLog.setLevel( ILogger::WARNING );
mainLog << "Unrecognized text string: " << nodeName << " found while parsing " << getXMLNameStatic() << "." << endl;
}
}
}
void OutputMetaData::accept( IVisitor* aVisitor, const int aPeriod ) const {
aVisitor->startVisitOutputMetaData( this, aPeriod );
aVisitor->endVisitOutputMetaData( this, aPeriod );
}
//! Get the primary fuel list. Remove this function once the output database is removed.
const list<string>& OutputMetaData::getPrimaryFuelList() const {
return mPrimaryFuels;
}
| 41.447552 | 128 | 0.694112 | E3SM-Project |
267c8afa092ea699a5484eaeaeece0ee086640df | 7,361 | cpp | C++ | PointPersistentList.cpp | spratt/PersistentList | 4f2f5b8beddfb86e22cc824cff76dad63cc6e88c | [
"0BSD"
] | 2 | 2016-04-18T05:29:25.000Z | 2016-06-17T05:47:36.000Z | PointPersistentList.cpp | spratt/PersistentList | 4f2f5b8beddfb86e22cc824cff76dad63cc6e88c | [
"0BSD"
] | null | null | null | PointPersistentList.cpp | spratt/PersistentList | 4f2f5b8beddfb86e22cc824cff76dad63cc6e88c | [
"0BSD"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 - 2012 by //
// Simon Pratt //
// (All rights reserved) //
///////////////////////////////////////////////////////////////////////////////
// //
// FILE: PointPersistentList.cpp //
// //
// MODULE: Persistent List //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <assert.h>
#include <iostream>
#include <vector>
#include <map>
#include "PersistentList.h"
#include "PointPersistentList.h"
#include "array_utilities.h"
#include "sort/heap_sort.h"
using namespace std;
using namespace array_utilities;
namespace persistent_list {
/////////////////////////////////////////////////////////////////////////////
// Point2d implementation //
/////////////////////////////////////////////////////////////////////////////
bool operator>(const Point2d& a, const Point2d& b) {
return a.x > b.x;
}
ostream& operator<<(ostream& os, const Point2d& p) {
os << "(" << p.x << "," << p.y << ")";
return os;
}
/////////////////////////////////////////////////////////////////////////////
// PointPersistentList implementation //
/////////////////////////////////////////////////////////////////////////////
// assumes points_sorted_by_x is sorted in descending order
int PointPersistentList::binarySearchX(coord_t x) {
int index = -1;
int begin = 0, end = (int)points_sorted_by_x.size()-1;
while(begin <= end) {
index = (begin+end)/2;
Point2d p = points_sorted_by_x[index];
// found the point
if(p.x == x) {
break;
}
// current point is smaller than desired
// since the array is sorted descending, we know that the
// desired point must lie in the preceding portion
else if(p.x < x) {
// search the preceding portion of the array
end = index -1;
} else {
// otherwise, search the following portion of the array
begin = index +1;
}
}
return index;
}
int PointPersistentList::insertPoints(Point2d* points, int npoints) {
assert(npoints > 0);
// sort the points by x coordinate O(nlogn)
// descending
sort::heap_sort(points,0,npoints-1);
// for each point
for(int i = npoints-1; i >= 0; --i) { // O(n)
// insert into structure
if(points_right.insert(points[i]) == 0) // O(logn)
// if not a duplicate, add to points sorted by x
points_sorted_by_x.push_back(points[i]);// O(1)
}
// lock the structure against any more points being inserted
points_right.lock();
// success
return 0;
}
size_t PointPersistentList::memoryUsage() {
return (sizeof(Point2d) * points_sorted_by_x.size()) +
points_right.memoryUsage();
}
vector< Point2d > PointPersistentList::enumerateNE(coord_t x, coord_t y) {
vector< Point2d > v;
// determine the time at which to search by searching for the x
int index = binarySearchX(x);
// if set of points is empty, bail out
if(index == -1) return v;
// while the closest point is too small
while(points_sorted_by_x[index].x < x) {
// check the previous point, which should be larger since the
// array is sorted by x descending
--index;
// if we have passed the beginning of the array, then there are no
// points within the query region
if(index < 0)
return v;
}
// get the first node in this list at time index
ListNode<Point2d, Point2d::yxdesc >* pln = points_right.getList(index);
// while the current point is not null and has a greater or equal
// y than the query
while(pln != NULL && pln->data.y >= y) {
// push the point onto the list to be returned
v.push_back(pln->data);
// move on to next point
pln = pln->getNext(index);
}
return v;
}
Point2d* PointPersistentList::highestNE(coord_t x, coord_t y) {
// determine the time at which to search by searching for the x
int index = binarySearchX(x);
// if set of points is empty, bail out
if(index == -1) return NULL;
// while the closest point is too small
while(points_sorted_by_x[index].x < x) {
// check the previous point, which should be larger since the
// array is sorted by x descending
--index;
// if we have passed the beginning of the array, then there are no
// points within the query region
if(index < 0)
return NULL;
}
// get the first node in this list at time index
ListNode<Point2d, Point2d::yxdesc >* pln = points_right.getList(index);
// if there are no points NE of the given point, return null
if(pln == NULL || pln->data.y < y) return NULL;
// since the list is sorted by y coordinate descending, the first
// node is the highest
return &(pln->data);
}
Point2d* PointPersistentList::leftMostNE(coord_t x, coord_t y) {
Point2d* leftMost = NULL;
// determine the time at which to search by searching for the x
int index = binarySearchX(x);
// if set of points is empty, bail out
if(index == -1) return NULL;
// while the closest point is too small
while(points_sorted_by_x[index].x < x) {
// check the previous point, which should be larger since the
// array is sorted by x descending
--index;
// if we have passed the beginning of the array, then there are no
// points within the query region
if(index < 0)
return NULL;
}
// get the first node in this list at time index
ListNode<Point2d, Point2d::yxdesc >* pln = points_right.getList(index);
// if there are no points NE of the given point, return null
if(pln == NULL || pln->data.y < y) return NULL;
// take the first point as left most for now
leftMost = &(pln->data);
// set pln to its next pointer
pln = pln->getNext(index);
// iterate over nodes in the list until:
// - we reach the end
// OR
// - the points are no longer NE of the query point
while(pln != NULL && pln->data.y >= y) {
// check if point is more left than current left most
if(pln->data.x < leftMost->x)
leftMost = &(pln->data);
// set pln to its next pointer
pln = pln->getNext(index);
}
// return the left most point
return leftMost;
}
ListNode<Point2d, Point2d::yxdesc >* PointPersistentList::getList(int t) {
return points_right.getList(t);
}
void PointPersistentList::printArray() {
print(vectorToArray(points_sorted_by_x),(int)points_sorted_by_x.size());
}
size_t PointPersistentList::size() {
return points_sorted_by_x.size();
}
}
| 37.943299 | 79 | 0.52914 | spratt |
267f14b83683bdb1167b4596f72110cba41b72b4 | 2,069 | cpp | C++ | libraries/ClockHardware/src/Display.cpp | e-noyau/wordclock | 5de70473e291514ee726fe737a3fee84abc33dd5 | [
"MIT"
] | 1 | 2019-08-31T16:57:00.000Z | 2019-08-31T16:57:00.000Z | libraries/ClockHardware/src/Display.cpp | e-noyau/wordclock | 5de70473e291514ee726fe737a3fee84abc33dd5 | [
"MIT"
] | 2 | 2019-09-01T13:20:26.000Z | 2020-11-02T09:02:29.000Z | libraries/ClockHardware/src/Display.cpp | e-noyau/wordclock | 5de70473e291514ee726fe737a3fee84abc33dd5 | [
"MIT"
] | 1 | 2020-11-01T22:21:57.000Z | 2020-11-01T22:21:57.000Z | #define DEBUG 1
#include "logging.h"
#include "Display.h"
Display::Display(ClockFace& clockFace, uint8_t pin)
: _clockFace(clockFace),
_pixels(ClockFace::pixelCount(), pin),
_brightnessController(_pixels),
_animations(ClockFace::pixelCount(), NEO_CENTISECONDS) {}
void Display::setup() {
_pixels.Begin();
_brightnessController.setup();
}
void Display::loop() {
// TODO This has nothing to do here, remove somewhere else.
// // If the "boot" button is pressed, move time forward. It's a crude way to
// // set the time.
// bool buttonPressed = digitalRead(0) != HIGH;
// if ((!animations.IsAnimating()) && (buttonPressed)) {
// DateTime now = rtc.now() + TimeSpan(20);
// rtc.adjust(now);
// }
// // Adjust the display to show the right time
// showtime(buttonPressed? 20 : TIME_CHANGE_ANIMATION_SPEED);
// break;
_brightnessController.loop();
_animations.UpdateAnimations();
_pixels.Show();
}
void Display::updateForTime(int hour, int minute, int second, int animationSpeed) {
if (!_clockFace.stateForTime(hour, minute, second)) {
return; // Nothing to update.
}
static const RgbColor white = RgbColor(0xff, 0xff, 0xff);
static const RgbColor black = RgbColor(0x00, 0x00, 0x00);
DLOG("Time: ");
DLOG(hour);
DLOG(":");
DLOGLN(minute);
// For all the LED animate a change from the current visible state to the new
// one.
const std::vector<bool>& state = _clockFace.getState();
for (int index = 0; index < state.size(); index++) {
RgbColor originalColor = _pixels.GetPixelColor(index);
RgbColor targetColor = state[index] ? white : black;
AnimUpdateCallback animUpdate = [=](const AnimationParam& param) {
float progress = NeoEase::QuadraticIn(param.progress);
RgbColor updatedColor = RgbColor::LinearBlend(
originalColor, targetColor, progress);
_pixels.SetPixelColor(index, updatedColor);
};
_animations.StartAnimation(index, animationSpeed, animUpdate);
}
}
| 30.426471 | 83 | 0.661189 | e-noyau |
267f9a3260a634ed85b817cd9f4cac70543b3145 | 2,593 | hpp | C++ | software/motion_estimate/vo_estimate/src/registeration/registeration.hpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 92 | 2016-01-14T21:03:50.000Z | 2021-12-01T17:57:46.000Z | software/motion_estimate/vo_estimate/src/registeration/registeration.hpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 62 | 2016-01-16T18:08:14.000Z | 2016-03-24T15:16:28.000Z | software/motion_estimate/vo_estimate/src/registeration/registeration.hpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 41 | 2016-01-14T21:26:58.000Z | 2022-03-28T03:10:39.000Z | #ifndef registeration_HPP_
#define registeration_HPP_
#include <lcm/lcm-cpp.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <bot_lcmgl_client/lcmgl.h>
#include <estimate-pose/pose_estimator.hpp>
#include <pronto_utils/pronto_lcm.hpp>
#include <pronto_utils/pronto_vis.hpp>
struct ImageFeature{
int track_id;
Eigen::Vector2d uv; ///< unrectified, distorted, orig. coords
Eigen::Vector2d base_uv; ///< unrectified, distorted, base level
Eigen::Vector3d uvd; ///< rectified, undistorted, base level
Eigen::Vector3d xyz;
Eigen::Vector4d xyzw;
uint8_t color[3];
// @todo what more is needed?
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
struct FrameMatch{
std::vector<int> featuresA_indices;
std::vector<int> featuresB_indices;
std::vector<ImageFeature> featuresA;
std::vector<ImageFeature> featuresB;
pose_estimator::PoseEstimateStatus status; // 0 = sucess, 0 = too few matches, 1 = too few inliers
Eigen::Isometry3d delta; // A->B transform : where is B relative to A
int n_inliers;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
typedef boost::shared_ptr<FrameMatch> FrameMatchPtr;
class Reg
{
public:
typedef boost::shared_ptr<Reg> Ptr;
typedef boost::shared_ptr<const Reg> ConstPtr;
Reg (boost::shared_ptr<lcm::LCM> &lcm_);
void align_images(cv::Mat &img0, cv::Mat &img1,
std::vector<ImageFeature> &features0, std::vector<ImageFeature> &features1,
int64_t utime0, int64_t utime1, FrameMatchPtr &match);
void draw_both_reg(std::vector<ImageFeature> features0, std::vector<ImageFeature> features1,
Eigen::Isometry3d pose0, Eigen::Isometry3d pose1);
void draw_reg(std::vector<ImageFeature> features, int status, Eigen::Isometry3d pose);
void send_both_reg(std::vector<ImageFeature> features0, std::vector<ImageFeature> features1,
Eigen::Isometry3d pose0, Eigen::Isometry3d pose1,
int64_t utime0, int64_t utime1 );
void send_both_reg_inliers(std::vector<ImageFeature> features0, std::vector<ImageFeature> features1,
Eigen::Isometry3d pose0, Eigen::Isometry3d pose1,
std::vector<int> feature_inliers0, std::vector<int> feature_inliers1 ,
int64_t utime0, int64_t utime1);
void send_lcm_image(cv::Mat &img, std::string channel );
private:
boost::shared_ptr<lcm::LCM> lcm_;
bot_lcmgl_t* lcmgl_;
pronto_vis* pc_vis_;
bool verbose_;
};
#endif
| 30.869048 | 107 | 0.695719 | liangfok |
268036a70e851def99db8cf36ad5448f9b7acfae | 837 | cpp | C++ | check_if_it_is_a_straight_line.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | check_if_it_is_a_straight_line.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | check_if_it_is_a_straight_line.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/check-if-it-is-a-straight-line/
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
vector<int> og_slope = {coordinates[1][1] - coordinates[0][1], coordinates[1][0] - coordinates[0][0]};
float orig_slope = og_slope[1] == 0 ? LONG_MAX : (float)og_slope[0]/(float)og_slope[1];
vector<int> curr_slope = og_slope;
float slope = orig_slope;
for(int i = 1; i < coordinates.size()-1; i++) {
curr_slope = {coordinates[i+1][1] - coordinates[i][1], coordinates[i+1][0] - coordinates[i][0]};
slope = curr_slope[1] == 0 ? LONG_MAX : (float)curr_slope[0]/(float)curr_slope[1];
if (orig_slope != slope) return false;
}
return true;
}
}; | 38.045455 | 110 | 0.568698 | shafitek |
2680f353d7a0913800427847fd51269880685504 | 2,059 | hpp | C++ | practice2/io_service_pool.hpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 47 | 2016-05-20T08:49:47.000Z | 2022-01-03T01:17:07.000Z | practice2/io_service_pool.hpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | null | null | null | practice2/io_service_pool.hpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 37 | 2016-07-25T04:52:08.000Z | 2022-02-14T03:55:08.000Z | // Copyright (c) 2016
// Author: Chrono Law
#ifndef _PRO_BOOST_IO_SERVICE_HPP
#define _PRO_BOOST_IO_SERVICE_HPP
#include <algorithm>
#include <boost/assert.hpp>
#include <boost/noncopyable.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/functional/factory.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
class io_service_pool final : boost::noncopyable
{
public:
typedef boost::asio::io_service ios_type;
typedef boost::asio::io_service::work work_type;
typedef boost::ptr_vector<ios_type> io_services_type;
typedef boost::ptr_vector<work_type> works_type;
private:
io_services_type m_io_services;
works_type m_works;
boost::thread_group m_threads;
std::size_t m_next_io_service;
public:
explicit io_service_pool(int n = 1):
m_next_io_service(0)
{
BOOST_ASSERT(n > 0);
init(n);
}
private:
void init(int n)
{
for (int i = 0;i < n; ++i)
{
m_io_services.push_back(
boost::factory<ios_type*>()());
m_works.push_back(
boost::factory<work_type*>()
(m_io_services.back()));
}
}
public:
ios_type& get()
{
if (m_next_io_service >= m_io_services.size())
{ m_next_io_service = 0; }
return m_io_services[m_next_io_service++];
}
public:
void start()
{
if (m_threads.size() > 0)
{ return; }
for(ios_type& ios : m_io_services)
{
m_threads.create_thread(
boost::bind(&ios_type::run,
boost::ref(ios)));
}
}
void run()
{
start();
m_threads.join_all();
}
public:
void stop()
{
m_works.clear();
std::for_each(m_io_services.begin(), m_io_services.end(),
boost::bind(&ios_type::stop, _1));
}
};
#endif // _PRO_BOOST_IO_SERVICE_HPP
| 22.626374 | 65 | 0.587178 | MaxHonggg |
26830acc9d41ff5118bca2ae17e5e7c5e04edf76 | 8,659 | cpp | C++ | artifacts/old_dataset_versions/minimal_commits_v02/qulacs/qulacs#73/before/observable.cpp | MattePalte/Bugs-Quantum-Computing-Platforms | 0c1c805fd5dfce465a8955ee3faf81037023a23e | [
"MIT"
] | 3 | 2021-11-08T11:46:42.000Z | 2021-12-27T10:13:38.000Z | artifacts/minimal_bugfixes/qulacs/qulacs#73/before/observable.cpp | MattePalte/Bugs-Quantum-Computing-Platforms | 0c1c805fd5dfce465a8955ee3faf81037023a23e | [
"MIT"
] | 2 | 2021-11-09T14:57:09.000Z | 2022-01-12T12:35:58.000Z | artifacts/old_dataset_versions/minimal_commits_v02/qulacs/qulacs#73/before/observable.cpp | MattePalte/Bugs-Quantum-Computing-Platforms | 0c1c805fd5dfce465a8955ee3faf81037023a23e | [
"MIT"
] | null | null | null |
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include "observable.hpp"
#include "pauli_operator.hpp"
#include "type.hpp"
#include "utility.hpp"
#include "state.hpp"
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <utility>
bool check_Pauli_operator(const Observable* observable, const PauliOperator* pauli_operator);
bool check_Pauli_operator(const Observable* observable, const PauliOperator* pauli_operator) {
auto vec = pauli_operator->get_index_list();
UINT val = 0;
if (vec.size() > 0) {
val = std::max(val, *std::max_element(vec.begin(), vec.end()));
}
return val < (observable->get_qubit_count());
}
Observable::Observable(UINT qubit_count){
_qubit_count = qubit_count;
}
Observable::~Observable(){
for(auto& term : this->_operator_list){
delete term;
}
}
void Observable::add_operator(const PauliOperator* mpt){
PauliOperator* _mpt = mpt->copy();
if (!check_Pauli_operator(this, _mpt)) {
std::cerr << "Error: Observable::add_operator(const PauliOperator*): pauli_operator applies target qubit of which the index is larger than qubit_count" << std::endl;
return;
}
this->_operator_list.push_back(_mpt);
}
void Observable::add_operator(CPPCTYPE coef, std::string pauli_string) {
PauliOperator* _mpt = new PauliOperator(pauli_string, coef);
if (!check_Pauli_operator(this, _mpt)) {
std::cerr << "Error: Observable::add_operator(double,std::string): pauli_operator applies target qubit of which the index is larger than qubit_count" << std::endl;
return;
}
this->add_operator(_mpt);
}
CPPCTYPE Observable::get_expectation_value(const QuantumStateBase* state) const {
if (this->_qubit_count != state->qubit_count) {
std::cerr << "Error: Observable::get_expectation_value(const QuantumStateBase*): invalid qubit count" << std::endl;
return 0.;
}
CPPCTYPE sum = 0;
for (auto pauli : this->_operator_list) {
sum += pauli->get_expectation_value(state);
}
return sum;
}
CPPCTYPE Observable::get_transition_amplitude(const QuantumStateBase* state_bra, const QuantumStateBase* state_ket) const {
if (this->_qubit_count != state_bra->qubit_count || this->_qubit_count != state_ket->qubit_count) {
std::cerr << "Error: Observable::get_transition_amplitude(const QuantumStateBase*, const QuantumStateBase*): invalid qubit count" << std::endl;
return 0.;
}
CPPCTYPE sum = 0;
for (auto pauli : this->_operator_list) {
sum += pauli->get_transition_amplitude(state_bra, state_ket);
}
return sum;
}
namespace observable{
Observable* create_observable_from_openfermion_file(std::string file_path){
UINT qubit_count = 0;
UINT imag_idx;
UINT str_idx;
std::ifstream ifs;
ifs.open(file_path);
double coef_real, coef_imag;
if (!ifs){
std::cerr << "ERROR: Cannot open file" << std::endl;
return NULL;
}
std::string str;
std::vector<CPPCTYPE> coefs;
std::vector<std::string> ops;
while (getline(ifs, str)) {
std::vector<std::string> elems;
std::vector<std::string> index_list;
elems = split(str, "()[]+");
if (elems.size() < 3){
continue;
}
imag_idx = 1;
str_idx = 3;
if (elems[0].find("j") != std::string::npos){
coef_real = 0;
imag_idx = 0;
str_idx = 1;
} else if (elems[1].find("j") != std::string::npos){
coef_real = std::stod(elems[imag_idx-1]);
} else {
continue;
}
coef_imag = std::stod(elems[imag_idx]);
chfmt(elems[str_idx]);
CPPCTYPE coef(coef_real, coef_imag);
coefs.push_back(coef);
ops.push_back(elems[str_idx]);
index_list = split(elems[str_idx], "XYZ ");
for (UINT i = 0; i < index_list.size(); ++i){
UINT n = std::stoi(index_list[i]) + 1;
if (qubit_count < n)
qubit_count = n;
}
}
if (!ifs.eof()){
std::cerr << "ERROR: Invalid format" << std::endl;
return NULL;
}
ifs.close();
Observable* observable = new Observable(qubit_count);
for (UINT i = 0; i < ops.size(); ++i){
observable->add_operator(new PauliOperator(ops[i].c_str(), coefs[i]));
}
return observable;
}
Observable* create_observable_from_openfermion_text(std::string text){
UINT qubit_count = 0;
UINT imag_idx;
UINT str_idx;
std::vector<std::string> lines;
std::vector<CPPCTYPE> coefs;
std::vector<std::string> ops;
double coef_real, coef_imag;
lines = split(text, "\n");
for (std::string line: lines){
std::vector<std::string> elems;
std::vector<std::string> index_list;
elems = split(line, "()[]+");
if (elems.size() < 3){
continue;
}
imag_idx = 1;
str_idx = 3;
if (elems[0].find("j") != std::string::npos){
coef_real = 0;
imag_idx = 0;
str_idx = 1;
} else if (elems[1].find("j") != std::string::npos){
coef_real = std::stod(elems[imag_idx-1]);
} else {
continue;
}
coef_imag = std::stod(elems[imag_idx]);
chfmt(elems[str_idx]);
CPPCTYPE coef(coef_real, coef_imag);
coefs.push_back(coef);
ops.push_back(elems[str_idx]);
index_list = split(elems[str_idx], "XYZ ");
for (UINT i = 0; i < index_list.size(); ++i){
UINT n = std::stoi(index_list[i]) + 1;
if (qubit_count < n)
qubit_count = n;
}
}
Observable* observable = new Observable(qubit_count);
for (UINT i = 0; i < ops.size(); ++i){
observable->add_operator(new PauliOperator(ops[i].c_str(), coefs[i]));
}
return observable;
}
std::pair<Observable*, Observable*> create_split_observable(std::string file_path){
UINT qubit_count = 0;
UINT imag_idx;
UINT str_idx;
std::ifstream ifs;
ifs.open(file_path);
if (!ifs){
std::cerr << "ERROR: Cannot open file" << std::endl;
return std::make_pair((Observable*)NULL, (Observable*)NULL);
}
// loading lines and check qubit_count
std::string str;
std::vector<CPPCTYPE> coefs;
std::vector<std::string> ops;
double coef_real, coef_imag;
while (getline(ifs, str)) {
std::vector<std::string> elems;
std::vector<std::string> index_list;
elems = split(str, "()[]+");
if (elems.size() < 3){
continue;
}
imag_idx = 1;
str_idx = 3;
if (elems[0].find("j") != std::string::npos){
coef_real = 0;
imag_idx = 0;
str_idx = 1;
} else if (elems[1].find("j") == std::string::npos){
coef_real = std::stod(elems[imag_idx-1]);
} else {
continue;
}
coef_imag = std::stod(elems[imag_idx]);
chfmt(elems[str_idx]);
CPPCTYPE coef(coef_real, coef_imag);
coefs.push_back(coef);
ops.push_back(elems[str_idx]);
index_list = split(elems[str_idx], "XYZ ");
for (UINT i = 0; i < index_list.size(); ++i){
UINT n = std::stoi(index_list[i]) + 1;
if (qubit_count < n)
qubit_count = n;
}
}
if (!ifs.eof()){
std::cerr << "ERROR: Invalid format" << std::endl;
return std::make_pair((Observable*)NULL, (Observable*)NULL);
}
ifs.close();
Observable* observable_diag = new Observable(qubit_count);
Observable* observable_non_diag = new Observable(qubit_count);
for (UINT i = 0; i < ops.size(); ++i){
if (ops[i].find("X") != std::string::npos || ops[i].find("Y") != std::string::npos){
observable_non_diag->add_operator(new PauliOperator(ops[i].c_str(), coefs[i]));
}else{
observable_diag->add_operator(new PauliOperator(ops[i].c_str(), coefs[i]));
}
}
return std::make_pair(observable_diag, observable_non_diag);
}
}
| 31.373188 | 167 | 0.55757 | MattePalte |
26832ab1b1912bbfccb387c12a21eaefeba2696e | 2,446 | hpp | C++ | src/libs/ml_models/src/svm_impl/params_types_details.hpp | boazsade/machine_learinig_models | eb1f9eda0e4e25a6d028b25682dfb20628a20624 | [
"MIT"
] | null | null | null | src/libs/ml_models/src/svm_impl/params_types_details.hpp | boazsade/machine_learinig_models | eb1f9eda0e4e25a6d028b25682dfb20628a20624 | [
"MIT"
] | null | null | null | src/libs/ml_models/src/svm_impl/params_types_details.hpp | boazsade/machine_learinig_models | eb1f9eda0e4e25a6d028b25682dfb20628a20624 | [
"MIT"
] | null | null | null | #pragma once
#include "kernel_args.h"
#include "training_args.h"
#include "type_args.h"
#include "libs/ml_models/svm_types.h"
#include <iosfwd>
namespace mlmodels
{
namespace svm
{
namespace detail
{
template<type_t Type, kernel_type Kernel>
struct params_base
{
static const constexpr type_t type = Type;
static const constexpr kernel_type kernel = Kernel;
};
template<type_t Type>
struct RBF_params : params_base<Type, RBF>,
rbf_args
{
//using rbf_args::rbf_args;
constexpr RBF_params() = default;
constexpr RBF_params(const rbf_args& arg) :
rbf_args{arg}
{
}
};
template<type_t Type>
struct sig_params : params_base<Type, SIGMOID>,
sig_args
{
using sig_args::sig_args;
};
template<type_t Type>
struct poly_params : params_base<Type, POLY>,
poly_args
{
using poly_args::poly_args;
};
template<type_t Type>
struct RBF_train_params : RBF_params<Type>,
base_train_params
{
constexpr RBF_train_params() = default;
constexpr RBF_train_params(const rbf_args& rbf,
const base_train_params& other) :
RBF_params<Type>{rbf}, base_train_params{other}
{
}
};
template<type_t Type>
struct sig_train_params : sig_params<Type>,
base_train_params
{
constexpr sig_train_params() = default;
constexpr sig_train_params(const sig_params<Type>& rbf,
const base_train_params& other) :
sig_params<Type>{rbf}, base_train_params{other}
{
}
};
template<type_t Type>
struct poly_train_params : poly_params<Type>,
base_train_params
{
constexpr poly_train_params() = default;
constexpr poly_train_params(const poly_params<Type>& rbf,
const base_train_params& other) :
poly_params<Type>{rbf}, base_train_params{other}
{
}
};
template<type_t Type, kernel_type Kernel>
struct default_train_params : params_base<Type, Kernel>,
base_train_params
{
using base_train_params::base_train_params;
};
} // end of namespace detail
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
//
} // end of namesapce svm
} // end of mlmodels
| 23.519231 | 79 | 0.589943 | boazsade |
2683768304b4c65bfcb18ebd18f3da8f8ce02556 | 583 | cpp | C++ | Solutions/ENTEXAM.cpp | nikramakrishnan/codechef-solutions | f7ab2199660275e972a387541ecfc24fd358e03e | [
"MIT"
] | 1 | 2022-03-26T09:38:02.000Z | 2022-03-26T09:38:02.000Z | Solutions/ENTEXAM.cpp | nikramakrishnan/codechef-solutions | f7ab2199660275e972a387541ecfc24fd358e03e | [
"MIT"
] | null | null | null | Solutions/ENTEXAM.cpp | nikramakrishnan/codechef-solutions | f7ab2199660275e972a387541ecfc24fd358e03e | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int t,n,k,e;
long long int m,score,smark,min;
cin>>t;
while(t--){
cin>>n>>k>>e>>m;
long long int marks[n-1];
for(int i=0;i<n-1;i++){
marks[i]=0;
for(int j=0;j<e;j++){
cin>>score;
marks[i]+=score;
}
}
smark=0;
for(int i=0;i<e-1;i++){
cin>>score;
smark+=score;
}
sort(marks,marks+(n-1));
min=(marks[n-k-1]+1)-smark;
if(min>m) cout<<"Impossible"<<endl;
else{
if(min<0) cout<<"0"<<endl;
else cout<<min<<endl;
}
}
}
| 18.21875 | 35 | 0.511149 | nikramakrishnan |
269318de806dfe825259006c755701b4b1c0815a | 2,700 | hpp | C++ | external/boost_1_60_0/qsboost/function_types/detail/classifier.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | 1 | 2019-06-27T17:54:13.000Z | 2019-06-27T17:54:13.000Z | external/boost_1_60_0/qsboost/function_types/detail/classifier.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | external/boost_1_60_0/qsboost/function_types/detail/classifier.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null |
// (C) Copyright Tobias Schwinger
//
// Use modification and distribution are subject to the boost Software License,
// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt).
//------------------------------------------------------------------------------
#ifndef QSBOOST_FT_DETAIL_CLASSIFIER_HPP_INCLUDED
#define QSBOOST_FT_DETAIL_CLASSIFIER_HPP_INCLUDED
#include <qsboost/type.hpp>
#include <qsboost/config.hpp>
#include <qsboost/type_traits/is_reference.hpp>
#include <qsboost/type_traits/add_reference.hpp>
#include <qsboost/function_types/config/config.hpp>
#include <qsboost/function_types/property_tags.hpp>
namespace qsboost { namespace function_types { namespace detail {
template<typename T> struct classifier;
template<std::size_t S> struct char_array { typedef char (&type)[S]; };
template<bits_t Flags, bits_t CCID, std::size_t Arity> struct encode_charr
{
typedef typename char_array<
::qsboost::function_types::detail::encode_charr_impl<Flags,CCID,Arity>::value
>::type type;
};
#if defined(QSBOOST_MSVC) || (defined(__BORLANDC__) && !defined(QSBOOST_DISABLE_WIN32))
# define QSBOOST_FT_DECL __cdecl
#else
# define QSBOOST_FT_DECL /**/
#endif
char QSBOOST_FT_DECL classifier_impl(...);
#define QSBOOST_FT_variations QSBOOST_FT_function|QSBOOST_FT_pointer|\
QSBOOST_FT_member_pointer
#define QSBOOST_FT_type_function(cc,name) QSBOOST_FT_SYNTAX( \
R QSBOOST_PP_EMPTY,QSBOOST_PP_LPAREN,cc,* QSBOOST_PP_EMPTY,name,QSBOOST_PP_RPAREN)
#define QSBOOST_FT_type_function_pointer(cc,name) QSBOOST_FT_SYNTAX( \
R QSBOOST_PP_EMPTY,QSBOOST_PP_LPAREN,cc,** QSBOOST_PP_EMPTY,name,QSBOOST_PP_RPAREN)
#define QSBOOST_FT_type_member_function_pointer(cc,name) QSBOOST_FT_SYNTAX( \
R QSBOOST_PP_EMPTY,QSBOOST_PP_LPAREN,cc,T0::** QSBOOST_PP_EMPTY,name,QSBOOST_PP_RPAREN)
#define QSBOOST_FT_al_path qsboost/function_types/detail/classifier_impl
#include <qsboost/function_types/detail/pp_loop.hpp>
template<typename T> struct classifier_bits
{
static typename qsboost::add_reference<T>::type tester;
QSBOOST_STATIC_CONSTANT(bits_t,value = (bits_t)sizeof(
qsboost::function_types::detail::classifier_impl(& tester)
)-1);
};
template<typename T> struct classifier
{
typedef detail::constant<
::qsboost::function_types::detail::decode_bits<
::qsboost::function_types::detail::classifier_bits<T>::value
>::tag_bits >
bits;
typedef detail::full_mask mask;
typedef detail::constant<
::qsboost::function_types::detail::decode_bits<
::qsboost::function_types::detail::classifier_bits<T>::value
>::arity >
function_arity;
};
} } } // namespace ::boost::function_types::detail
#endif
| 30.681818 | 91 | 0.745926 | wouterboomsma |
2695673ba193afca2154c218a40a5c38a5c4848a | 6,112 | cpp | C++ | digsby/ext/src/BuddyList/ContactData.cpp | ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | [
"Python-2.0"
] | 35 | 2015-08-15T14:32:38.000Z | 2021-12-09T16:21:26.000Z | digsby/ext/src/BuddyList/ContactData.cpp | niterain/digsby | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | [
"Python-2.0"
] | 4 | 2015-09-12T10:42:57.000Z | 2017-02-27T04:05:51.000Z | digsby/ext/src/BuddyList/ContactData.cpp | niterain/digsby | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | [
"Python-2.0"
] | 15 | 2015-07-10T23:58:07.000Z | 2022-01-23T22:16:33.000Z | #include "precompiled.h"
#include "config.h"
#include "BuddyListSorter.h"
#include "Group.h"
#include "StringUtils.h"
#include "Sorters.h"
#include <sstream>
using std::wostringstream;
using std::endl;
static const wstring special_prefix = L"SpecialGroup_";
static const wstring group_postfix = L"group";
wstring getSpecialGroupKey(const Node* node)
{
if (node->hasFlag(FlagOfflineGroup))
return special_prefix + wstringToLower(node->name()) + group_postfix;
else if (node->hasFlag(FlagFakeGroup))
return special_prefix + L"fakeroot" + group_postfix;
else
return special_prefix + wstringToLower(node->name());
}
/**
* Returns a string identifier based on all the network groups the given Contact Node
* is in.
*/
wstring groupNames(const Node* n, const wstring& fakeRootName)
{
wstring groupNames;
Node* parent = n->parent();
if (!parent)
return groupNames;
if (n->isLeaf())
if (parent->hasFlag(FlagRootGroup) ||
parent->hasFlag(FlagFakeGroup) ||
// sort buddies in real groups named the same as the fake root group as if
// they are actually in the fake root group
(!fakeRootName.empty() &&
CaseInsensitiveEqual(fakeRootName, parent->name())))
return fakeRootGroupKey();
while (parent->parent()) {
if (parent->data()) {
Group* g = reinterpret_cast<Group*>(parent->data());
if (!g->root() && parent->parent()) {
if (!groupNames.empty())
groupNames = wstring(L"##") + groupNames;
groupNames = wstringToLower(g->name()) + groupNames;
}
} else {
return getSpecialGroupKey(parent);
}
parent = parent->parent();
}
return groupNames;
}
static const wstring groupCategory = L"__groups__";
/**
* Sets category and key to the correct userOrder lookup values for the given Node.
*/
void userOrderInfo(const Node* node, const wstring& fakeRootName, wstring& category, wstring& key)
{
Elem* elem = node->data();
if (!elem) {
// no elem means this is a "fake" Group created by one of the sorters
key = getSpecialGroupKey(node);
category = groupCategory;
} else {
if (Contact* contact = elem->asContact()) {
category = groupNames(node, fakeRootName);
key = contact->name();
// HACK until buddy transition is complete
if (key.substr(0, 13) != L"Metacontact #") {
Account* account = contact->buddies()[0]->account();
key = account->service() + L"/" + account->protocolUsername() + L"/" + key;
}
} else {
Group* group = elem->asGroup();
BL_ASSERT(group);
if (node->hasFlag(FlagFakeGroup))
key = getSpecialGroupKey(node);
else if (!fakeRootName.empty() && CaseInsensitiveEqual(fakeRootName, group->name()))
key = fakeRootGroupKey();
else
key = wstringToLower(group->name());
category = groupCategory;
}
}
}
int Contacts::userOrder(const Node* node, const wstring& fakeRootName, const wstring& givenCategory)
{
wstring category, key;
int val = 0;
// printf("userOrder(%ws) -> \n", node->repr().c_str());
userOrderInfo(node, fakeRootName, category, key);
wstring cat = givenCategory.empty() ? category : givenCategory;
if (!cat.empty()) {
val = m_order[cat].index(key);
// printf(" (%ws, %ws) -> %d\n", cat.c_str(), key.c_str(), val);
} else {
// printf(" <<NONE>>\n");
}
return val;
}
Contacts::~Contacts()
{
// delete all Accounts (must come before contact deletion,
// buddies in these accounts will be deleted, removing them from the contacts)
foreach (AccountMap::value_type a, m_accounts)
delete a.second;
// delete all Contacts
foreach (ContactMap::value_type i, m_contacts)
delete i.second;
}
void Contacts::removeAllContacts()
{
foreach (ContactMap::value_type i, m_contacts) {
Contact* contact = i.second;
delete contact;
}
m_contacts.clear();
}
void Contacts::setDirty(bool dirty) {
foreach (AccountMap::value_type a, m_accounts)
a.second->setDirty(dirty);
}
wstring Contacts::contactReprs() const
{
wostringstream s;
foreach (ContactMap::value_type i, m_contacts) {
Contact* contact = i.second;
s << contact->name() << " (status=" << contact->status()
<< ", online=" << contact->online() << ")" << endl;
foreach (Buddy* buddy, contact->buddies()) {
s << " " << buddy->name() << " (service="
<< buddy->service() << ", status=" << buddy->status()
<< ")" << endl;
}
}
return s.str();
}
ElemOrderIndices::ElemOrderIndices()
: m_nextIndex(0)
{}
size_t ElemOrderIndices::index(const wstring& key)
{
// already in the map?
IndexMap::const_iterator i = m_indicesMap.find(key);
if (i != m_indicesMap.end())
return i->second;
// else append to list and update indices map
size_t idx = m_nextIndex++;
m_indicesMap[key] = idx;
return idx;
}
void ElemOrderIndices::_add(const wstring& key, size_t index)
{
m_indicesMap[key] = index;
m_nextIndex = index + 1;
}
struct OrderPairs //: public binary_function<const Pair&, const Pair&, bool>
{
typedef std::pair<wstring, int> Pair;
bool operator()(const Pair& a, const Pair& b) { return a.second < b.second; }
};
vector<wstring> ElemOrderIndices::values()
{
typedef std::pair<wstring, int> Pair;
// Get all items: (wstring, index)
vector<Pair> items;
foreach (Pair p, m_indicesMap)
items.push_back(p);
// Sort by index.
std::sort(items.begin(), items.end(), OrderPairs());
// Build list of just (wstring)
vector<wstring> values;
foreach (Pair p, items)
values.push_back(p.first);
return values;
}
| 28.560748 | 100 | 0.596859 | ifwe |
2696d74d7b50c3b2ca803fcc5ac36157ade14a90 | 9,265 | cpp | C++ | src/core/renderer.cpp | SirBob01/EnigmaEngine | 48ddc114ac2afb1dd7733517d735fb1f855f5b84 | [
"MIT"
] | 3 | 2019-12-05T07:17:37.000Z | 2020-03-12T07:44:55.000Z | src/core/renderer.cpp | SirBob01/EnigmaEngine | 48ddc114ac2afb1dd7733517d735fb1f855f5b84 | [
"MIT"
] | 7 | 2019-10-01T02:39:11.000Z | 2020-05-20T03:44:36.000Z | src/core/renderer.cpp | SirBob01/Dynamo-Engine | 48ddc114ac2afb1dd7733517d735fb1f855f5b84 | [
"MIT"
] | null | null | null | #include "renderer.h"
namespace Dynamo {
Renderer::Renderer(Display *display, bool vsync) {
display_ = display;
border_color_ = {0, 0, 0};
fill_ = {0, 0, 0};
}
void Renderer::set_render_target(Sprite *dest) {
if(dest) {
// Blend rendering over target sprite
SDL_SetRenderTarget(display_->get_renderer(), dest->get_base());
}
else {
// Default render target is the main display
SDL_SetRenderTarget(display_->get_renderer(), nullptr);
}
}
Color Renderer::get_fill(Color color) {
return fill_;
}
Color Renderer::get_borderfill() {
return border_color_;
}
void Renderer::set_fill(Color color) {
Vec2D logic_dim = display_->get_dimensions();
draw_rect(nullptr, {logic_dim/2, logic_dim}, color, true);
fill_ = color;
}
void Renderer::set_borderfill(Color color) {
border_color_ = color;
}
void Renderer::draw_sprite(Sprite *dest, Sprite *source, Vec2D position,
RenderBlend mode) {
AABB aabb = {position, source->get_dimensions()};
if(!source->get_visible() ||
source->get_alpha() <= 0) {
return;
}
SDL_SetTextureBlendMode(
source->get_base(),
static_cast<SDL_BlendMode>(mode)
);
// Render source on dest
set_render_target(dest);
SDL_Rect target_rect = aabb.convert_to_rect();
SDL_RenderCopyEx(
display_->get_renderer(),
source->get_base(),
nullptr,
&target_rect,
source->get_angle(),
nullptr,
source->get_flip()
);
// Render actual source texture on its base
set_render_target(source);
SDL_SetRenderDrawColor(display_->get_renderer(), 0, 0, 0, 0);
SDL_RenderClear(display_->get_renderer());
SDL_RenderCopy(
display_->get_renderer(),
source->get_texture(),
&source->get_source(),
nullptr
);
set_render_target(nullptr);
}
void Renderer::draw_point(Sprite *dest, Vec2D point,
Color color, RenderBlend mode) {
SDL_SetRenderDrawBlendMode(
display_->get_renderer(),
static_cast<SDL_BlendMode>(mode)
);
SDL_SetRenderDrawColor(
display_->get_renderer(),
color.r, color.g, color.b, color.a
);
set_render_target(dest);
SDL_Point sdl_point = point.convert_to_point();
SDL_RenderDrawPoint(
display_->get_renderer(),
sdl_point.x,
sdl_point.y
);
set_render_target(nullptr);
}
void Renderer::draw_line(Sprite *dest, Vec2D point1, Vec2D point2,
Color color, RenderBlend mode) {
SDL_SetRenderDrawBlendMode(
display_->get_renderer(),
static_cast<SDL_BlendMode>(mode)
);
SDL_SetRenderDrawColor(
display_->get_renderer(),
color.r, color.g, color.b, color.a
);
set_render_target(dest);
SDL_Point sdl_p1 = point1.convert_to_point();
SDL_Point sdl_p2 = point2.convert_to_point();
SDL_RenderDrawLine(
display_->get_renderer(),
sdl_p1.x,
sdl_p1.y,
sdl_p2.x,
sdl_p2.y
);
set_render_target(nullptr);
}
void Renderer::draw_rect(Sprite *dest, AABB box,
Color color, bool fill, RenderBlend mode) {
SDL_SetRenderDrawBlendMode(
display_->get_renderer(),
static_cast<SDL_BlendMode>(mode)
);
SDL_SetRenderDrawColor(
display_->get_renderer(),
color.r, color.g, color.b, color.a
);
set_render_target(dest);
SDL_Rect rect = box.convert_to_rect();
if(fill) {
SDL_RenderFillRect(display_->get_renderer(), &rect);
}
else {
SDL_RenderDrawRect(display_->get_renderer(), &rect);
}
set_render_target(nullptr);
}
void Renderer::draw_circle(Sprite *dest, Vec2D center, int radius,
Color color, bool fill, RenderBlend mode) {
// Midpoint algorithm generates circle points
int x = radius;
int y = 0;
int p = 1 - radius;
int cx = center.x;
int cy = center.y;
std::vector<SDL_Point> points;
while(x >= y) {
points.push_back({cx + x, cy + y});
points.push_back({cx - x, cy + y});
points.push_back({cx + y, cy + x});
points.push_back({cx - y, cy + x});
points.push_back({cx + x, cy - y});
points.push_back({cx - x, cy - y});
points.push_back({cx + y, cy - x});
points.push_back({cx - y, cy - x});
if(p <= 0) {
p += 2*y + 1;
}
else {
x--;
p += 2*y - 2*x + 1;
}
y++;
}
// Batch render the points
SDL_SetRenderDrawBlendMode(
display_->get_renderer(),
static_cast<SDL_BlendMode>(mode)
);
SDL_SetRenderDrawColor(
display_->get_renderer(),
color.r, color.g, color.b, color.a
);
set_render_target(dest);
if(!fill) {
SDL_RenderDrawPoints(
display_->get_renderer(),
&points[0],
points.size()
);
}
else {
SDL_RenderDrawLines(
display_->get_renderer(),
&points[0],
points.size()
);
}
set_render_target(nullptr);
}
void Renderer::draw_polygon(Sprite *dest, Vec2D points[], int n,
Color color, bool fill, RenderBlend mode) {
if(!fill) {
for(int i = 0; i < n; i++) {
draw_line(dest, points[i], points[(i+1)%n], color, mode);
}
}
else {
float nodes_x[n];
int nodes, row, i, j;
Vec2D min = points[0], max = points[0];
// Find minimum and maximum coordinates in polygon
for(i = 0; i < n; i++) {
if(points[i].y < min.y) {
min.y = points[i].y;
}
if(points[i].y > max.y) {
max.y = points[i].y;
}
if(points[i].x < min.x) {
min.x = points[i].x;
}
if(points[i].x > max.x) {
max.x = points[i].x;
}
}
// Generate and draw lines between nodes
for(row = min.y; row < max.y; row++) {
nodes = 0;
j = n - 1;
for(i = 0; i < n; i++) {
if(points[i].y < row && points[j].y >= row ||
points[j].y < row && points[i].y >= row) {
nodes_x[nodes++] = (
(points[i].x + (row - points[i].y) /
(points[j].y - points[i].y) *
(points[j].x - points[i].x))
);
}
j = i;
}
for(i = 0; i < nodes - 1;) {
if(nodes_x[i] > nodes_x[i + 1]) {
std::swap(nodes_x[i], nodes_x[i + 1]);
if(i) {
i--;
}
}
else {
i++;
}
}
for(i = 0; i < nodes; i += 2) {
if(nodes_x[i] >= max.x) {
break;
}
if(nodes_x[i + 1] > min.x) {
if(nodes_x[i] < min.x) {
nodes_x[i] = min.x;
}
if(nodes_x[i + 1] > max.x) {
nodes_x[i + 1] = max.x;
}
Vec2D start = {
nodes_x[i],
static_cast<float>(row)
};
Vec2D end = {
nodes_x[i + 1],
static_cast<float>(row)
};
draw_line(dest, start, end, color, mode);
}
}
}
}
}
void Renderer::refresh() {
SDL_SetRenderDrawBlendMode(
display_->get_renderer(),
SDL_BLENDMODE_NONE
);
SDL_SetRenderDrawColor(
display_->get_renderer(),
border_color_.r, border_color_.g, border_color_.b, 0xFF
);
SDL_RenderPresent(display_->get_renderer());
SDL_RenderClear(display_->get_renderer());
}
}
| 30.883333 | 76 | 0.442957 | SirBob01 |
26976b2c34ca90778497b275896674ce02071acc | 1,375 | cpp | C++ | spoopy/tools/vole/source/olderfiles/illumestimators/iic/misc/get_file.cpp | rodrigobressan/PADify | 362db2b3a33793ac53f938e89f90a6ecdf778e89 | [
"MIT"
] | 12 | 2019-11-26T07:44:08.000Z | 2021-03-03T09:51:43.000Z | spoopy/tools/vole/source/illumestimators/iic/misc/get_file.cpp | rodrigobressan/PADify | 362db2b3a33793ac53f938e89f90a6ecdf778e89 | [
"MIT"
] | 13 | 2020-01-28T22:09:41.000Z | 2022-03-11T23:43:37.000Z | spoopy/tools/vole/source/illumestimators/iic/misc/get_file.cpp | rodrigobressan/PADify | 362db2b3a33793ac53f938e89f90a6ecdf778e89 | [
"MIT"
] | 5 | 2020-01-02T09:52:42.000Z | 2022-02-21T15:45:23.000Z | #include <fstream>
#include <boost/version.hpp>
#if BOOST_VERSION >= 104400
#define VOLE_GET_FILE_IMPLEMENT_FILESYSTEM 1
#ifndef BOOST_FILESYSTEM_VERSION
#define BOOST_FILESYSTEM_VERSION 3
#endif
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
#endif
#include "get_file.h"
namespace vole { namespace GetFile {
bool create_path(std::string directory)
{
#ifndef VOLE_GET_FILE_IMPLEMENT_FILESYSTEM
return false;
#else
path p(directory);
if (exists(p)) return (is_directory(p) ? true : false);
// non-existing: try to create directories recursively, fatal failure
// if one of these directories can not be created.
// boost::system::error_code ec;
return create_directories(p); //, ec);
#endif // VOLE_GET_FILE_IMPLEMENT_FILESYSTEM
}
bool create_file_and_path(std::string file)
{
#ifndef VOLE_GET_FILE_IMPLEMENT_FILESYSTEM
return false;
#else // VOLE_GET_FILE_IMPLEMENT_FILESYSTEM
path p(file);
if (exists(p)) return (is_directory(p) ? false : true);
if (p.has_parent_path() && !create_path(p.parent_path().generic_string())) return false;
// test-open the file for writing;
std::ofstream testMe(file.c_str(), std::ios::app);
if (!testMe.good()) return false;
testMe.close();
return true;
#endif // VOLE_GET_FILE_IMPLEMENT_FILESYSTEM
}
} } // end namespace vole::GetFile
| 25.462963 | 91 | 0.722909 | rodrigobressan |
2698312aae743931996097469472fdf91ec54465 | 1,464 | hpp | C++ | plugins/libimhex/include/hex/helpers/crypto.hpp | Laxer3a/psdebugtool | 41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb | [
"MIT"
] | 4 | 2021-05-09T23:33:54.000Z | 2022-03-06T10:16:31.000Z | plugins/libimhex/include/hex/helpers/crypto.hpp | Laxer3a/psdebugtool | 41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb | [
"MIT"
] | null | null | null | plugins/libimhex/include/hex/helpers/crypto.hpp | Laxer3a/psdebugtool | 41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb | [
"MIT"
] | 6 | 2021-05-09T21:41:48.000Z | 2021-09-08T10:54:28.000Z | #pragma once
#include <hex.hpp>
#include <array>
#include <optional>
#include <string>
#include <vector>
namespace hex::prv { class Provider; }
namespace hex::crypt {
void initialize();
void exit();
u16 crc16(prv::Provider* &data, u64 offset, size_t size, u16 polynomial, u16 init);
u32 crc32(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init);
std::array<u8, 16> md5(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 20> sha1(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 28> sha224(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 32> sha256(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 48> sha384(prv::Provider* &data, u64 offset, size_t size);
std::array<u8, 64> sha512(prv::Provider* &data, u64 offset, size_t size);
std::vector<u8> decode64(const std::vector<u8> &input);
std::vector<u8> encode64(const std::vector<u8> &input);
enum class AESMode : u8 {
ECB = 0,
CBC = 1,
CFB128 = 2,
CTR = 3,
GCM = 4,
CCM = 5,
OFB = 6,
XTS = 7
};
enum class KeyLength : u8 {
Key128Bits = 0,
Key192Bits = 1,
Key256Bits = 2
};
std::vector<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input);
} | 30.5 | 171 | 0.60041 | Laxer3a |
2699125626aca087b562a1e959e2a3e6e7b56ed6 | 441 | cpp | C++ | src/Level.cpp | savageking-io/evelengine | f4f31419077e3467db271e82b05164eafa521eb7 | [
"Apache-2.0"
] | null | null | null | src/Level.cpp | savageking-io/evelengine | f4f31419077e3467db271e82b05164eafa521eb7 | [
"Apache-2.0"
] | null | null | null | src/Level.cpp | savageking-io/evelengine | f4f31419077e3467db271e82b05164eafa521eb7 | [
"Apache-2.0"
] | null | null | null | #include "Level.hpp"
namespace EvelEngine
{
Level::Level(const std::string& seed) : _seed(seed)
{
}
Level::~Level()
{
}
bool Level::handleCommand(const std::string& command)
{
return false;
}
std::string Level::getSeed()
{
return _seed;
}
void Level::build()
{
}
double Level::perlin(double x, double y, double z)
{
return 0.0;
}
}
| 11.918919 | 57 | 0.514739 | savageking-io |
2699f90f69e1ce68dbb0c49794345af5e0f70fca | 6,174 | cc | C++ | cpp/src/arrow/compare_benchmark.cc | timkpaine/arrow | a96297e65e17e728e4321cdecc7ace146e1363fb | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 9,734 | 2016-02-17T13:22:12.000Z | 2022-03-31T09:35:00.000Z | cpp/src/arrow/compare_benchmark.cc | timkpaine/arrow | a96297e65e17e728e4321cdecc7ace146e1363fb | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 11,470 | 2016-02-19T15:30:28.000Z | 2022-03-31T23:27:21.000Z | cpp/src/arrow/compare_benchmark.cc | XpressAI/arrow | eafd885e06f6bbc1eb169ed64016f804c1810bec | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 2,637 | 2016-02-17T10:56:29.000Z | 2022-03-31T08:20:13.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <memory>
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "arrow/array.h"
#include "arrow/compare.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/util/benchmark_util.h"
#include "arrow/util/logging.h"
#include "arrow/util/macros.h"
namespace arrow {
constexpr auto kSeed = 0x94378165;
static void BenchmarkArrayRangeEquals(const std::shared_ptr<Array>& array,
benchmark::State& state) {
const auto left_array = array;
// Make sure pointer equality can't be used as a shortcut
// (should we would deep-copy child_data and buffers?)
const auto right_array =
MakeArray(array->data()->Copy())->Slice(1, array->length() - 1);
for (auto _ : state) {
const bool are_ok = ArrayRangeEquals(*left_array, *right_array,
/*left_start_idx=*/1,
/*left_end_idx=*/array->length() - 2,
/*right_start_idx=*/0);
if (ARROW_PREDICT_FALSE(!are_ok)) {
ARROW_LOG(FATAL) << "Arrays should have compared equal";
}
}
}
static void ArrayRangeEqualsInt32(benchmark::State& state) {
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto array = rng.Int32(args.size, 0, 100, args.null_proportion);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsFloat32(benchmark::State& state) {
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto array = rng.Float32(args.size, 0, 100, args.null_proportion);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsBoolean(benchmark::State& state) {
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto array = rng.Boolean(args.size, /*true_probability=*/0.3, args.null_proportion);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsString(benchmark::State& state) {
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto array =
rng.String(args.size, /*min_length=*/0, /*max_length=*/15, args.null_proportion);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsFixedSizeBinary(benchmark::State& state) {
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto array = rng.FixedSizeBinary(args.size, /*byte_width=*/8, args.null_proportion);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsListOfInt32(benchmark::State& state) {
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto values = rng.Int32(args.size * 10, 0, 100, args.null_proportion);
// Force empty list null entries, since it is overwhelmingly the common case.
auto array = rng.List(*values, /*size=*/args.size, args.null_proportion,
/*force_empty_nulls=*/true);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsStruct(benchmark::State& state) {
// struct<int32, utf8>
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto values1 = rng.Int32(args.size, 0, 100, args.null_proportion);
auto values2 =
rng.String(args.size, /*min_length=*/0, /*max_length=*/15, args.null_proportion);
auto null_bitmap = rng.NullBitmap(args.size, args.null_proportion);
auto array = *StructArray::Make({values1, values2},
std::vector<std::string>{"ints", "strs"}, null_bitmap);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsSparseUnion(benchmark::State& state) {
// sparse_union<int32, utf8>
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto values1 = rng.Int32(args.size, 0, 100, args.null_proportion);
auto values2 =
rng.String(args.size, /*min_length=*/0, /*max_length=*/15, args.null_proportion);
auto array = rng.SparseUnion({values1, values2}, args.size);
BenchmarkArrayRangeEquals(array, state);
}
static void ArrayRangeEqualsDenseUnion(benchmark::State& state) {
// dense_union<int32, utf8>
RegressionArgs args(state, /*size_is_bytes=*/false);
auto rng = random::RandomArrayGenerator(kSeed);
auto values1 = rng.Int32(args.size, 0, 100, args.null_proportion);
auto values2 =
rng.String(args.size, /*min_length=*/0, /*max_length=*/15, args.null_proportion);
auto array = rng.DenseUnion({values1, values2}, args.size);
BenchmarkArrayRangeEquals(array, state);
}
BENCHMARK(ArrayRangeEqualsInt32)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsFloat32)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsBoolean)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsString)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsFixedSizeBinary)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsListOfInt32)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsStruct)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsSparseUnion)->Apply(RegressionSetArgs);
BENCHMARK(ArrayRangeEqualsDenseUnion)->Apply(RegressionSetArgs);
} // namespace arrow
| 37.418182 | 89 | 0.723518 | timkpaine |
269a29ed1856c4578d99a34f6d309425867d5b98 | 7,171 | cxx | C++ | Rendering/OSPRay/vtkOSPRayPass.cxx | romangrothausmann/VTK | 60cce86963f29f8f569a7a31348019e095267a50 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OSPRay/vtkOSPRayPass.cxx | romangrothausmann/VTK | 60cce86963f29f8f569a7a31348019e095267a50 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OSPRay/vtkOSPRayPass.cxx | romangrothausmann/VTK | 60cce86963f29f8f569a7a31348019e095267a50 | [
"BSD-3-Clause"
] | 1 | 2020-01-13T07:19:25.000Z | 2020-01-13T07:19:25.000Z | /*=========================================================================
Prograxq: Visualization Toolkit
Module: vtkOSPRayPass.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCamera.h"
#include "vtkCameraPass.h"
#include "vtkLightsPass.h"
#include "vtkObjectFactory.h"
#include "vtkOSPRayPass.h"
#include "vtkOSPRayRendererNode.h"
#include "vtkOSPRayViewNodeFactory.h"
#include "vtkOverlayPass.h"
#include "vtkOpaquePass.h"
#include "vtkRenderPassCollection.h"
#include "vtkRenderState.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkSequencePass.h"
#include "vtkSequencePass.h"
#include "vtkVolumetricPass.h"
#include "ospray/ospray.h"
#include <sstream>
#include <stdexcept>
class vtkOSPRayPassInternals : public vtkRenderPass
{
public:
static vtkOSPRayPassInternals *New();
vtkTypeMacro(vtkOSPRayPassInternals,vtkRenderPass);
vtkOSPRayPassInternals()
{
this->Factory = 0;
}
~vtkOSPRayPassInternals()
{
this->Factory->Delete();
}
void Render(const vtkRenderState *s) override
{
this->Parent->RenderInternal(s);
}
vtkOSPRayViewNodeFactory *Factory;
vtkOSPRayPass *Parent;
};
int vtkOSPRayPass::OSPDeviceRefCount = 0;
// ----------------------------------------------------------------------------
vtkStandardNewMacro(vtkOSPRayPassInternals);
// ----------------------------------------------------------------------------
vtkStandardNewMacro(vtkOSPRayPass);
// ----------------------------------------------------------------------------
vtkOSPRayPass::vtkOSPRayPass()
{
this->SceneGraph = nullptr;
vtkOSPRayPass::OSPInit();
vtkOSPRayViewNodeFactory *vnf = vtkOSPRayViewNodeFactory::New();
this->Internal = vtkOSPRayPassInternals::New();
this->Internal->Factory = vnf;
this->Internal->Parent = this;
this->CameraPass = vtkCameraPass::New();
this->LightsPass = vtkLightsPass::New();
this->SequencePass = vtkSequencePass::New();
this->VolumetricPass = vtkVolumetricPass::New();
this->OverlayPass = vtkOverlayPass::New();
this->RenderPassCollection = vtkRenderPassCollection::New();
this->RenderPassCollection->AddItem(this->LightsPass);
this->RenderPassCollection->AddItem(this->Internal);
this->RenderPassCollection->AddItem(this->OverlayPass);
this->SequencePass->SetPasses(this->RenderPassCollection);
this->CameraPass->SetDelegatePass(this->SequencePass);
}
// ----------------------------------------------------------------------------
vtkOSPRayPass::~vtkOSPRayPass()
{
this->SetSceneGraph(nullptr);
this->Internal->Delete();
this->Internal = 0;
if (this->CameraPass)
{
this->CameraPass->Delete();
this->CameraPass = 0;
}
if (this->LightsPass)
{
this->LightsPass->Delete();
this->LightsPass = 0;
}
if (this->SequencePass)
{
this->SequencePass->Delete();
this->SequencePass = 0;
}
if (this->VolumetricPass)
{
this->VolumetricPass->Delete();
this->VolumetricPass = 0;
}
if (this->OverlayPass)
{
this->OverlayPass->Delete();
this->OverlayPass = 0;
}
if (this->RenderPassCollection)
{
this->RenderPassCollection->Delete();
this->RenderPassCollection = 0;
}
vtkOSPRayPass::OSPShutdown();
}
// ----------------------------------------------------------------------------
void vtkOSPRayPass::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
// ----------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkOSPRayPass, SceneGraph, vtkOSPRayRendererNode)
// ----------------------------------------------------------------------------
void vtkOSPRayPass::Render(const vtkRenderState *s)
{
if (!this->SceneGraph)
{
vtkRenderer *ren = s->GetRenderer();
if (ren)
{
this->SceneGraph = vtkOSPRayRendererNode::SafeDownCast
(this->Internal->Factory->CreateNode(ren));
}
}
this->CameraPass->Render(s);
}
// ----------------------------------------------------------------------------
void vtkOSPRayPass::RenderInternal(const vtkRenderState *s)
{
this->NumberOfRenderedProps=0;
if (this->SceneGraph)
{
this->SceneGraph->TraverseAllPasses();
// copy the result to the window
vtkRenderer *ren = s->GetRenderer();
vtkRenderWindow *rwin =
vtkRenderWindow::SafeDownCast(ren->GetVTKWindow());
int viewportX, viewportY;
int viewportWidth, viewportHeight;
int right = 0;
if (rwin)
{
if (rwin->GetStereoRender() == 1)
{
if (rwin->GetStereoType() == VTK_STEREO_CRYSTAL_EYES)
{
vtkCamera *camera = ren->GetActiveCamera();
if (camera)
{
if (!camera->GetLeftEye())
{
right = 1;
}
}
}
}
}
ren->GetTiledSizeAndOrigin(&viewportWidth,&viewportHeight,
&viewportX,&viewportY);
vtkOSPRayRendererNode* oren= vtkOSPRayRendererNode::SafeDownCast
(this->SceneGraph->GetViewNodeFor(ren));
int layer = ren->GetLayer();
if (layer == 0)
{
rwin->SetZbufferData(
viewportX, viewportY,
viewportX+viewportWidth-1,
viewportY+viewportHeight-1,
this->SceneGraph->GetZBuffer());
rwin->SetRGBACharPixelData(
viewportX, viewportY,
viewportX+viewportWidth-1,
viewportY+viewportHeight-1,
this->SceneGraph->GetBuffer(),
0, vtkOSPRayRendererNode::GetCompositeOnGL(ren), right);
}
else
{
float *ontoZ = rwin->GetZbufferData
(viewportX, viewportY,
viewportX+viewportWidth-1,
viewportY+viewportHeight-1);
unsigned char *ontoRGBA = rwin->GetRGBACharPixelData
(viewportX, viewportY,
viewportX+viewportWidth-1,
viewportY+viewportHeight-1,
0, right);
oren->WriteLayer(ontoRGBA, ontoZ, viewportWidth, viewportHeight, layer);
rwin->SetZbufferData(
viewportX, viewportY,
viewportX+viewportWidth-1,
viewportY+viewportHeight-1,
ontoZ);
rwin->SetRGBACharPixelData(
viewportX, viewportY,
viewportX+viewportWidth-1,
viewportY+viewportHeight-1,
ontoRGBA,
0, vtkOSPRayRendererNode::GetCompositeOnGL(ren), right);
delete[] ontoZ;
delete[] ontoRGBA;
}
}
}
// ----------------------------------------------------------------------------
void vtkOSPRayPass::OSPInit()
{
if (OSPDeviceRefCount == 0)
{
ospInit(nullptr, nullptr);
}
OSPDeviceRefCount++;
}
// ----------------------------------------------------------------------------
void vtkOSPRayPass::OSPShutdown()
{
--OSPDeviceRefCount;
if (OSPDeviceRefCount == 0)
{
ospShutdown();
}
}
| 27.580769 | 79 | 0.583322 | romangrothausmann |
269e08c717cf9a64a61af768825f81398a0e64cb | 2,132 | cpp | C++ | source/binhex.cpp | Numerics88/n88util | b5362590a3d9b96ff16ecb9a9b60f260272b00b9 | [
"MIT"
] | null | null | null | source/binhex.cpp | Numerics88/n88util | b5362590a3d9b96ff16ecb9a9b60f260272b00b9 | [
"MIT"
] | 4 | 2019-11-05T17:24:31.000Z | 2019-11-20T21:01:47.000Z | source/binhex.cpp | Besler/n88util | aa15d4f80f1b69142a48db34b055142f867aef7f | [
"MIT"
] | 1 | 2018-05-31T19:09:12.000Z | 2018-05-31T19:09:12.000Z | // Copyright (c) Eric Nodwell
// See LICENSE for details.
#include "n88util/binhex.hpp"
#include <cstring>
#include <cstdio>
#include <cstdlib>
namespace n88util
{
const char valid_hex_chars[] = "0123456789ABCDEF";
//-----------------------------------------------------------------------
int bintohex(const unsigned char *buf, long len, char** hex)
{
if (len < 0)
{
*hex = NULL;
return 0;
}
*hex = (char*)malloc(2*len+1);
if (!*hex)
{
return 0;
}
char* h = *hex;
h[2*len] = '\0';
char c[3];
while (len--)
{
sprintf(c, "%02X", *buf++);
strncpy(h, c, 2);
h += 2;
}
return 1;
}
//-----------------------------------------------------------------------
// This is not particularly efficient, because the output is written
// to a temporary internal buffer and then copied.
int bintohex(const unsigned char *buf, long len, std::string& hex)
{
hex.clear();
char* tmp = NULL;
if (!bintohex(buf,len,&tmp))
{
free(tmp);
return 0;
}
hex = tmp;
free(tmp);
return 1;
}
//-----------------------------------------------------------------------
int hextobin(const char *hex, unsigned char** buf, long *len)
{
*len = strlen(hex)/2;
*buf = (unsigned char*)malloc(*len);
if (!*buf)
{
*len = 0;
return 0;
}
unsigned char* b = *buf;
long l = *len;
char c[3];
int x;
while (l--)
{
c[2] = c[1] = c[0] = '\0';
strncpy(c, hex, 2);
if (!strchr(valid_hex_chars, c[0]) || !strchr(valid_hex_chars, c[1]))
{
free(*buf);
*buf = NULL;
*len = 0;
return 0;
}
if (sscanf(c, "%X", &x) != 1)
{
free(*buf);
*buf = NULL;
*len = 0;
return 0;
}
*b++ = x;
hex += 2;
}
return 1;
}
//-----------------------------------------------------------------------
int hextobin(const std::string& hex, unsigned char** buf, long *len)
{
return hextobin(hex.c_str(), buf, len);
}
} // namespace n88util
| 21.108911 | 75 | 0.425422 | Numerics88 |
26a4224f486141596420a88bc99b27d29ee417d8 | 5,083 | cpp | C++ | compiler/llvm/c_src/Diagnostics.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 2,939 | 2019-08-29T16:52:20.000Z | 2022-03-31T05:42:30.000Z | compiler/llvm/c_src/Diagnostics.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 235 | 2019-08-29T23:44:13.000Z | 2022-03-17T11:43:25.000Z | compiler/llvm/c_src/Diagnostics.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 95 | 2019-08-29T19:11:28.000Z | 2022-01-03T05:14:16.000Z | #include "lumen/llvm/Diagnostics.h"
#include "lumen/llvm/RustString.h"
#include "llvm-c/Core.h"
#include "llvm-c/Types.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CBindingWrapping.h"
#include "llvm/Support/Casting.h"
using namespace lumen;
using llvm::dyn_cast_or_null;
using llvm::isa;
typedef struct LLVMOpaqueSMDiagnostic *LLVMSMDiagnosticRef;
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(llvm::SMDiagnostic, LLVMSMDiagnosticRef);
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(llvm::DiagnosticInfo, LLVMDiagnosticInfoRef);
DiagnosticKind lumen::toDiagnosticKind(llvm::DiagnosticKind kind) {
switch (kind) {
case llvm::DK_InlineAsm:
return DiagnosticKind::InlineAsm;
case llvm::DK_ResourceLimit:
return DiagnosticKind::ResourceLimit;
case llvm::DK_StackSize:
return DiagnosticKind::StackSize;
case llvm::DK_Linker:
return DiagnosticKind::Linker;
case llvm::DK_DebugMetadataVersion:
return DiagnosticKind::DebugMetadataVersion;
case llvm::DK_DebugMetadataInvalid:
return DiagnosticKind::DebugMetadataInvalid;
case llvm::DK_ISelFallback:
return DiagnosticKind::ISelFallback;
case llvm::DK_SampleProfile:
return DiagnosticKind::SampleProfile;
case llvm::DK_OptimizationRemark:
return DiagnosticKind::OptimizationRemark;
case llvm::DK_OptimizationRemarkMissed:
return DiagnosticKind::OptimizationRemarkMissed;
case llvm::DK_OptimizationRemarkAnalysis:
return DiagnosticKind::OptimizationRemarkAnalysis;
case llvm::DK_OptimizationRemarkAnalysisFPCommute:
return DiagnosticKind::OptimizationRemarkAnalysisFPCommute;
case llvm::DK_OptimizationRemarkAnalysisAliasing:
return DiagnosticKind::OptimizationRemarkAnalysisAliasing;
case llvm::DK_MachineOptimizationRemark:
return DiagnosticKind::MachineOptimizationRemark;
case llvm::DK_MachineOptimizationRemarkMissed:
return DiagnosticKind::MachineOptimizationRemarkMissed;
case llvm::DK_MachineOptimizationRemarkAnalysis:
return DiagnosticKind::MachineOptimizationRemarkAnalysis;
case llvm::DK_MIRParser:
return DiagnosticKind::MIRParser;
case llvm::DK_PGOProfile:
return DiagnosticKind::PGOProfile;
case llvm::DK_MisExpect:
return DiagnosticKind::MisExpect;
case llvm::DK_Unsupported:
return DiagnosticKind::Unsupported;
default:
return DiagnosticKind::Other;
}
}
extern "C" DiagnosticKind
LLVMLumenGetDiagInfoKind(LLVMDiagnosticInfoRef di) {
llvm::DiagnosticInfo *info = unwrap(di);
return toDiagnosticKind((llvm::DiagnosticKind)info->getKind());
}
extern "C" void
LLVMLumenWriteSMDiagnosticToString(LLVMSMDiagnosticRef d, RustStringRef str) {
RawRustStringOstream out(str);
unwrap(d)->print("", out);
}
extern "C" void
LLVMLumenWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef di, RustStringRef str) {
RawRustStringOstream out(str);
llvm::DiagnosticPrinterRawOStream printer(out);
unwrap(di)->print(printer);
}
extern "C" bool
LLVMLumenIsVerboseOptimizationDiagnostic(LLVMDiagnosticInfoRef di) {
// Undefined to call this not on an optimization diagnostic!
llvm::DiagnosticInfoOptimizationBase *opt =
static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(di));
return opt->isVerbose();
}
extern "C" void
LLVMLumenUnpackOptimizationDiagnostic(LLVMDiagnosticInfoRef di, RustStringRef passNameOut,
RustStringRef remarkNameOut,
LLVMValueRef *functionOut,
LLVMValueRef *codeRegionOut,
unsigned *line, unsigned *column, bool *isVerbose,
RustStringRef filenameOut,
RustStringRef messageOut) {
// Undefined to call this not on an optimization diagnostic!
llvm::DiagnosticInfoOptimizationBase *opt =
static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(di));
*isVerbose = opt->isVerbose();
RawRustStringOstream passNameOS(passNameOut);
passNameOS << opt->getPassName();
RawRustStringOstream remarkNameOS(remarkNameOut);
remarkNameOS << opt->getRemarkName();
*functionOut = wrap(&opt->getFunction());
*codeRegionOut = nullptr;
if (auto irOpt = dyn_cast_or_null<llvm::DiagnosticInfoIROptimization>(opt)) {
*codeRegionOut = wrap(irOpt->getCodeRegion());
}
if (opt->isLocationAvailable()) {
llvm::DiagnosticLocation loc = opt->getLocation();
*line = loc.getLine();
*column = loc.getColumn();
RawRustStringOstream filenameOS(filenameOut);
filenameOS << loc.getAbsolutePath();
}
RawRustStringOstream messageOS(messageOut);
messageOS << opt->getMsg();
}
extern "C" void
LLVMLumenUnpackISelFallbackDiagnostic(LLVMDiagnosticInfoRef di, LLVMValueRef *functionOut) {
llvm::DiagnosticInfoISelFallback *opt =
static_cast<llvm::DiagnosticInfoISelFallback *>(unwrap(di));
*functionOut = wrap(&opt->getFunction());
}
| 35.795775 | 92 | 0.734802 | mlwilkerson |
26a53835e890a7486faebe6d8fd2b791c564a5cb | 14,685 | cpp | C++ | src/IoTHubDevice.cpp | markrad/Arduino-IoTHubDevice | 141f439b7c5064c66c3c603ae395cae2dab7b96d | [
"MIT"
] | null | null | null | src/IoTHubDevice.cpp | markrad/Arduino-IoTHubDevice | 141f439b7c5064c66c3c603ae395cae2dab7b96d | [
"MIT"
] | null | null | null | src/IoTHubDevice.cpp | markrad/Arduino-IoTHubDevice | 141f439b7c5064c66c3c603ae395cae2dab7b96d | [
"MIT"
] | null | null | null | #include "IoTHubDevice.h"
#include <AzureIoTProtocol_MQTT.h>
#include <AzureIoTUtility.h>
#include <azure_c_shared_utility/connection_string_parser.h>
#include <azure_c_shared_utility/shared_util_options.h>
#include "iothub_client_version.h"
using namespace std;
IoTHubDevice::IoTHubDevice(const char *connectionString, Protocol protocol) :
_messageCallback(NULL),
_messageCallbackUC(NULL),
_connectionStatusCallback(NULL),
_connectionStatusCallbackUC(NULL),
_unknownDeviceMethodCallback(NULL),
_unknownDeviceMethodCallbackUC(NULL),
_deviceTwinCallback(NULL),
_deviceTwinCallbackUC(NULL),
_logging(false),
_x509Certificate(NULL),
_x509PrivateKey(NULL),
_deviceHandle(NULL),
_startResult(-1)
{
_connectionString = connectionString;
_protocol = protocol;
}
IoTHubDevice::IoTHubDevice(const char *connectionString, const char *x509Certificate, const char *x509PrivateKey, Protocol protocol) :
_messageCallback(NULL),
_messageCallbackUC(NULL),
_connectionStatusCallback(NULL),
_connectionStatusCallbackUC(NULL),
_unknownDeviceMethodCallback(NULL),
_unknownDeviceMethodCallbackUC(NULL),
_deviceTwinCallback(NULL),
_deviceTwinCallbackUC(NULL),
_logging(false),
_x509Certificate(x509Certificate),
_x509PrivateKey(x509PrivateKey),
_deviceHandle(NULL),
_startResult(-1)
{
_connectionString = connectionString;
_protocol = protocol;
}
IoTHubDevice::~IoTHubDevice()
{
if (_deviceHandle != NULL)
{
Stop();
}
}
int IoTHubDevice::Start()
{
int result = _startResult = 0;
DList_InitializeListHead(&_outstandingEventList);
DList_InitializeListHead(&_outstandingReportedStateEventList);
_parsedCS = new MapUtil(connectionstringparser_parse_from_char(_connectionString), true);
if (_parsedCS == NULL)
{
LogError("Failed to parse connection string");
result = __FAILURE__;
}
else if (_parsedCS->ContainsKey("X509") && (_x509Certificate == NULL || _x509PrivateKey == NULL))
{
LogError("X509 requires certificate and private key");
result = __FAILURE__;
}
else
{
if ((_x509Certificate == NULL && _x509PrivateKey != NULL) ||
(_x509Certificate != NULL && _x509PrivateKey == NULL))
{
LogError("X509 values must both be provided or neither be provided");
result = __FAILURE__;
}
else
{
platform_init();
_deviceHandle = IoTHubClient_LL_CreateFromConnectionString(_connectionString, GetProtocol(_protocol));
if (_deviceHandle == NULL)
{
LogError("Failed to create IoT hub handle");
result = __FAILURE__;
}
else
{
if (_x509Certificate != NULL)
{
if (
(IoTHubClient_LL_SetOption(GetHandle(), OPTION_X509_CERT, _x509Certificate) != IOTHUB_CLIENT_OK) ||
(IoTHubClient_LL_SetOption(GetHandle(), OPTION_X509_PRIVATE_KEY, _x509PrivateKey) != IOTHUB_CLIENT_OK)
)
{
LogError("Failed to set X509 parameters");
result = __FAILURE__;
}
}
if (result == 0)
{
if (
(IoTHubClient_LL_SetConnectionStatusCallback(GetHandle(), InternalConnectionStatusCallback, this) != IOTHUB_CLIENT_OK) ||
(IoTHubClient_LL_SetMessageCallback(GetHandle(), InternalMessageCallback, this) != IOTHUB_CLIENT_OK) ||
(IoTHubClient_LL_SetDeviceMethodCallback(GetHandle(), InternalDeviceMethodCallback, this) != IOTHUB_CLIENT_OK) ||
(IoTHubClient_LL_SetDeviceTwinCallback(GetHandle(), InternalDeviceTwinCallback, this) != IOTHUB_CLIENT_OK)
)
{
LogError("Failed to set up callbacks");
result = __FAILURE__;
}
}
}
}
}
_startResult = result;
return result;
}
void IoTHubDevice::Stop()
{
if (_deviceHandle != NULL)
{
IoTHubClient_LL_Destroy(_deviceHandle);
_deviceHandle = NULL;
_startResult = -1;
}
platform_deinit();
while (!DList_IsListEmpty(&_outstandingEventList))
{
PDLIST_ENTRY work = _outstandingEventList.Flink;
DList_RemoveEntryList(work);
delete work;
}
while(!DList_IsListEmpty(&_outstandingReportedStateEventList))
{
PDLIST_ENTRY work = _outstandingReportedStateEventList.Flink;
DList_RemoveEntryList(work);
delete work;
}
for (map<std::string, DeviceMethodUserContext *>::iterator it = _deviceMethods.begin(); it != _deviceMethods.end(); it++)
{
delete it->second;
}
delete _parsedCS;
}
IoTHubDevice::MessageCallback IoTHubDevice::SetMessageCallback(MessageCallback messageCallback, void *userContext)
{
MessageCallback temp = _messageCallback;
_messageCallback = messageCallback;
_messageCallbackUC = userContext;
return temp;
}
IOTHUB_CLIENT_LL_HANDLE IoTHubDevice::GetHandle() const
{
if (_deviceHandle == NULL)
{
LogError("Function called with null device handle");
}
else if (_startResult != 0)
{
LogError("Function called after Start function failed with %d", _startResult);
}
return _deviceHandle;
}
const char *IoTHubDevice::GetHostName()
{
return _parsedCS->GetValue("HostName");
}
const char *IoTHubDevice::GetDeviceId()
{
return _parsedCS->GetValue("DeviceId");
}
const char *IoTHubDevice::GetVersion()
{
return IoTHubClient_GetVersionString();
}
IOTHUB_CLIENT_STATUS IoTHubDevice::GetSendStatus()
{
IOTHUB_CLIENT_STATUS result = IOTHUB_CLIENT_SEND_STATUS_IDLE;
IoTHubClient_LL_GetSendStatus(GetHandle(), &result);
return result;
}
IoTHubDevice::ConnectionStatusCallback IoTHubDevice::SetConnectionStatusCallback(ConnectionStatusCallback connectionStatusCallback, void *userContext)
{
ConnectionStatusCallback temp = _connectionStatusCallback;
_connectionStatusCallback = connectionStatusCallback;
_connectionStatusCallbackUC = userContext;
}
IoTHubDevice::DeviceMethodCallback IoTHubDevice::SetDeviceMethodCallback(const char *methodName, DeviceMethodCallback deviceMethodCallback, void *userContext)
{
DeviceMethodUserContext *deviceMethodUserContext = new DeviceMethodUserContext(deviceMethodCallback, userContext);
map<std::string, DeviceMethodUserContext *>::iterator it;
DeviceMethodCallback temp = NULL;
it = _deviceMethods.find(methodName);
if (it == _deviceMethods.end())
{
_deviceMethods[methodName] = deviceMethodUserContext;
}
else
{
temp = it->second->deviceMethodCallback;
delete it->second;
if (deviceMethodCallback != NULL)
{
it->second = deviceMethodUserContext;
}
else
{
_deviceMethods.erase(it);
}
}
return temp;
}
IoTHubDevice::UnknownDeviceMethodCallback IoTHubDevice::SetUnknownDeviceMethodCallback(UnknownDeviceMethodCallback unknownDeviceMethodCallback, void *userContext)
{
UnknownDeviceMethodCallback temp = _unknownDeviceMethodCallback;
_unknownDeviceMethodCallback = unknownDeviceMethodCallback;
_unknownDeviceMethodCallbackUC = userContext;
return temp;
}
IoTHubDevice::DeviceTwinCallback IoTHubDevice::SetDeviceTwinCallback(DeviceTwinCallback deviceTwinCallback, void *userContext)
{
DeviceTwinCallback temp = _deviceTwinCallback;
_deviceTwinCallback = deviceTwinCallback;
_deviceTwinCallbackUC = userContext;
return temp;
}
IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const string &message, EventConfirmationCallback eventConfirmationCallback, void *userContext)
{
IOTHUB_CLIENT_RESULT result;
result = SendEventAsync(message.c_str(), eventConfirmationCallback, userContext);
return result;
}
IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const char *message, EventConfirmationCallback eventConfirmationCallback, void *userContext)
{
IoTHubMessage *hubMessage = new IoTHubMessage(message);
IOTHUB_CLIENT_RESULT result;
result = SendEventAsync(hubMessage, eventConfirmationCallback, userContext);
delete hubMessage;
return result;
}
IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const uint8_t *message, size_t length, EventConfirmationCallback eventConfirmationCallback, void *userContext)
{
IoTHubMessage *hubMessage = new IoTHubMessage(message, length);
IOTHUB_CLIENT_RESULT result;
result = SendEventAsync(hubMessage, eventConfirmationCallback, userContext);
delete hubMessage;
return result;
}
IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const IoTHubMessage *message, EventConfirmationCallback eventConfirmationCallback, void *userContext)
{
MessageUserContext *messageUC = new MessageUserContext(this, eventConfirmationCallback, userContext);
IOTHUB_CLIENT_RESULT result;
result = IoTHubClient_LL_SendEventAsync(GetHandle(), message->GetHandle(), InternalEventConfirmationCallback, messageUC);
if (result == IOTHUB_CLIENT_OK)
{
DList_InsertTailList(&_outstandingEventList, &(messageUC->dlistEntry));
}
return result;
}
IOTHUB_CLIENT_RESULT IoTHubDevice::SendReportedState(const char* reportedState, ReportedStateCallback reportedStateCallback, void* userContext)
{
ReportedStateUserContext *reportedStateUC = new ReportedStateUserContext(this, reportedStateCallback, userContext);
IOTHUB_CLIENT_RESULT result;
result = IoTHubClient_LL_SendReportedState(GetHandle(), (const unsigned char *)reportedState, strlen(reportedState), InternalReportedStateCallback, reportedStateUC);
if (result == IOTHUB_CLIENT_OK)
{
DList_InsertTailList(&_outstandingReportedStateEventList, &(reportedStateUC->dlistEntry));
}
}
void IoTHubDevice::DoWork()
{
IoTHubClient_LL_DoWork(GetHandle());
}
int IoTHubDevice::WaitingEventsCount()
{
PDLIST_ENTRY listEntry = &_outstandingEventList;
int count = 0;
while (listEntry->Flink != &_outstandingEventList)
{
count++;
listEntry = listEntry->Flink;
}
return count;
}
void IoTHubDevice::SetLogging(bool value)
{
_logging = value;
IoTHubClient_LL_SetOption(GetHandle(), OPTION_LOG_TRACE, &_logging);
}
void IoTHubDevice::SetTrustedCertificate(const char *value)
{
_certificate = value;
if (_certificate != NULL)
{
IoTHubClient_LL_SetOption(GetHandle(), OPTION_TRUSTED_CERT, _certificate);
}
}
IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubDevice::InternalMessageCallback(IOTHUB_MESSAGE_HANDLE message, void *userContext)
{
IoTHubDevice *that = (IoTHubDevice *)userContext;
IOTHUBMESSAGE_DISPOSITION_RESULT result = IOTHUBMESSAGE_REJECTED;
if (that->_messageCallback != NULL)
{
IoTHubMessage *msg = new IoTHubMessage(message);
result = that->_messageCallback(*that, *msg, that->_messageCallbackUC);
delete msg;
}
return result;
}
void IoTHubDevice::InternalConnectionStatusCallback(IOTHUB_CLIENT_CONNECTION_STATUS result, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void* userContext)
{
IoTHubDevice *that = (IoTHubDevice *)userContext;
if (that->_connectionStatusCallback != NULL)
{
that->_connectionStatusCallback(*that, result, reason, that->_connectionStatusCallbackUC);
}
}
void IoTHubDevice::InternalEventConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContext)
{
MessageUserContext *messageUC = (MessageUserContext *)userContext;
if (messageUC->eventConfirmationCallback != NULL)
{
messageUC->eventConfirmationCallback(*(messageUC->iotHubDevice), result, messageUC->userContext);
}
DList_RemoveEntryList(&(messageUC->dlistEntry));
delete messageUC;
}
void IoTHubDevice::InternalReportedStateCallback(int status_code, void* userContext)
{
ReportedStateUserContext *reportedStateUC = (ReportedStateUserContext *)userContext;
if (reportedStateUC->reportedStateCallback != NULL)
{
reportedStateUC->reportedStateCallback(*(reportedStateUC->iotHubDevice), status_code, reportedStateUC->userContext);
}
DList_RemoveEntryList(&(reportedStateUC->dlistEntry));
delete reportedStateUC;
}
int IoTHubDevice::InternalDeviceMethodCallback(const char *methodName, const unsigned char *payload, size_t size, unsigned char **response, size_t *responseSize, void *userContext)
{
IoTHubDevice *that = (IoTHubDevice *)userContext;
map<std::string, DeviceMethodUserContext *>::iterator it;
int status = 999;
it = that->_deviceMethods.find(methodName);
if (it != that->_deviceMethods.end())
{
status = it->second->deviceMethodCallback(*that, payload, size, response, responseSize, it->second->userContext);
}
else if (that->_unknownDeviceMethodCallback != NULL)
{
status = that->_unknownDeviceMethodCallback(*that, methodName, payload, size, response, responseSize, that->_unknownDeviceMethodCallbackUC);
}
else
{
status = 501;
const char* RESPONSE_STRING = "{ \"Response\": \"Unknown method requested.\" }";
*responseSize = strlen(RESPONSE_STRING);
if ((*response = (unsigned char *)malloc(*responseSize)) == NULL)
{
status = -1;
}
else
{
memcpy(*response, RESPONSE_STRING, *responseSize);
}
}
return status;
}
void IoTHubDevice::InternalDeviceTwinCallback(DEVICE_TWIN_UPDATE_STATE update_state, const unsigned char* payLoad, size_t size, void* userContext)
{
IoTHubDevice *that = (IoTHubDevice *)userContext;
if (that->_deviceTwinCallback != NULL)
{
char *json = new char[size + 1];
memcpy(json, payLoad, size);
json[size] = '\0';
that->_deviceTwinCallback(update_state, json, that->_deviceTwinCallbackUC);
delete [] json;
}
}
IOTHUB_CLIENT_TRANSPORT_PROVIDER IoTHubDevice::GetProtocol(IoTHubDevice::Protocol protocol)
{
IOTHUB_CLIENT_TRANSPORT_PROVIDER result = NULL;
// Currently only MQTT is supported on Arduino - no WebSockets and no proxy
switch (protocol)
{
case Protocol::MQTT:
result = MQTT_Protocol;
break;
default:
break;
}
return result;
}
| 30.466805 | 180 | 0.696425 | markrad |
26aa3df43224ccb4c97803e02a3a4ae684c1edca | 7,710 | cc | C++ | mediasoup-client/src/main/jni/media_manager.cc | commonprogress/mediasoupdemo | 435d9c5cea81fbe2fb979eb10ecc1f9a45302c01 | [
"MIT"
] | 5 | 2020-04-18T15:29:27.000Z | 2020-09-21T02:47:49.000Z | audioeffect/src/main/jni/media_manager.cc | commonprogress/mediasoupdemo | 435d9c5cea81fbe2fb979eb10ecc1f9a45302c01 | [
"MIT"
] | null | null | null | audioeffect/src/main/jni/media_manager.cc | commonprogress/mediasoupdemo | 435d9c5cea81fbe2fb979eb10ecc1f9a45302c01 | [
"MIT"
] | 4 | 2020-05-17T08:15:12.000Z | 2021-08-23T08:47:10.000Z | /*
* Wire
* Copyright (C) 2016 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <jni.h>
#include <pthread.h>
#ifdef ANDROID
#include <android/log.h>
//#include "webrtc/voice_engine/include/voe_base.h"
#endif
#include "avs_mediamgr.h"
#include <re.h>
#include <avs.h>
#include "mm_platform_android.h"
#include <stdlib.h>
#include <pthread.h>
static jfieldID mmfid;
struct jmm {
struct mediamgr *mm;
jobject self;
};
struct jmm *self2mm(JNIEnv *env, jobject self)
{
jlong ptr = env->GetLongField(self, mmfid);
struct jmm *jmm = (struct jmm *)((void*)ptr);
return jmm;
}
#ifndef ANDROID // Android simulator dosnt include mm_platform_android.c
int mm_android_jni_init(JNIEnv *env, jobject jobj, jobject ctx){
return 0;
}
void mm_android_jni_cleanup(JNIEnv *env, jobject jobj){
return;
}
bool mm_android_jni_java_get_initialized()
{
return false;
}
void mm_android_jni_on_playback_route_changed(enum mediamgr_auplay new_route, void *arg){
return;
}
void mm_android_jni_on_media_category_changed(enum mediamgr_state state, void *arg){
return;
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_attach
(JNIEnv *env, jobject self, jobject ctx)
{
struct jmm *jmm;
int err;
debug("MediaManager_attach called from thread %lu \n", pthread_self());
if (!mm_android_jni_java_get_initialized()) {
mm_android_jni_init(env, self, ctx);
}
jmm = (struct jmm *)mem_zalloc(sizeof(*jmm), NULL);
if (!jmm) {
err = ENOMEM;
goto out;
}
jmm->self = env->NewGlobalRef(self);
err = mediamgr_alloc(&jmm->mm, mm_android_jni_on_media_category_changed, NULL);
if (err) {
warning("jni: media_manager: cannot allocate mm: %d\n", err);
goto out;
}
debug("mediamgr_alloc allocated at %p \n", jmm->mm);
mediamgr_register_route_change_h(jmm->mm, mm_android_jni_on_playback_route_changed, NULL);
jclass mmClass;
if ((mmClass= env->FindClass("com/waz/media/manager/MediaManager")) == NULL){
error("Could not find class com/waz/media/manager/MediaManager \n");
}
mmfid = env->GetFieldID(mmClass, "mmPointer", "J");
if (mmfid == NULL) {
error("Could not find mm_field \n");
}
env->SetLongField(self, mmfid, (jlong)((void *)jmm));
out:
if (err) {
mem_deref((void *)jmm);
}
}
JNIEXPORT void Java_com_waz_media_manager_MediaManager_detach
(JNIEnv *env, jobject self)
{
struct jmm *jmm = self2mm(env, self);
jobject jobj;
jmm->mm = (struct mediamgr *)mem_deref(jmm->mm);
mm_android_jni_cleanup(env, self);
jobj = jmm->self;
jmm->self = NULL;
env->DeleteGlobalRef(jobj);
mem_deref(jmm);
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_playMedia
(JNIEnv *env, jobject self, jstring jmedia_name)
{
struct jmm *jmm;
jmm = self2mm(env, self);
const char *media_name = env->GetStringUTFChars(jmedia_name, 0);
debug("call mediamgr_play_media at %p \n", jmm->mm);
mediamgr_play_media(jmm->mm, media_name);
if (media_name) {
env->ReleaseStringUTFChars(jmedia_name, media_name);
}
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_stopMedia
(JNIEnv *env, jobject self, jstring jmedia_name)
{
struct jmm *jmm;
jmm = self2mm(env, self);
const char *media_name = env->GetStringUTFChars(jmedia_name, 0);
debug("call mediamgr_stop_media at %p \n", jmm->mm);
mediamgr_stop_media(jmm->mm, media_name);
if (media_name) {
env->ReleaseStringUTFChars(jmedia_name, media_name);
}
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_EnableSpeaker
(JNIEnv *env, jobject self, bool enable)
{
struct jmm *jmm;
jmm = self2mm(env, self);
debug("call mediamgr_enable_speaker at %p \n", jmm->mm);
mediamgr_enable_speaker(jmm->mm, enable);
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_registerMedia
(JNIEnv *env, jobject self, jstring jmedia_name, jobject player_obj, bool mixing, bool incall, int intensity)
{
struct jmm *jmm;
jmm = self2mm(env, self);
const char *media_name = env->GetStringUTFChars(jmedia_name, 0);
jobject refobj = env->NewGlobalRef(player_obj);
debug("mediamgr_registerMedia = %s \n", media_name);
int priority = 0;
if(strlen(media_name) >= strlen("ringing")){
if( strncmp(media_name, "ringing", strlen("ringing")) == 0){
priority = 1;
}
}
mediamgr_register_media(jmm->mm, media_name, (void*)refobj, mixing, incall, intensity, priority, false);
if (media_name) {
env->ReleaseStringUTFChars(jmedia_name, media_name);
}
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_unregisterMedia
(JNIEnv *env, jobject self, jstring jmedia_name)
{
struct jmm *jmm;
jmm = self2mm(env, self);
const char *media_name = env->GetStringUTFChars(jmedia_name, 0);
debug("mediamgr_unregisterMedia = %s \n", media_name);
mediamgr_unregister_media(jmm->mm, media_name);
if (media_name) {
env->ReleaseStringUTFChars(jmedia_name, media_name);
}
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_setCallState
(JNIEnv *env, jobject self, bool incall)
{
struct jmm *jmm;
mediamgr_state state;
jmm = self2mm(env, self);
debug("mediamgr_set_call_state = %d \n", incall);
if(incall){
state = MEDIAMGR_STATE_INCALL;
} else {
state = MEDIAMGR_STATE_NORMAL;
}
mediamgr_set_call_state(jmm->mm, state);
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_setVideoCallState
(JNIEnv *env, jobject self)
{
struct jmm *jmm;
mediamgr_state state = MEDIAMGR_STATE_INVIDEOCALL;
jmm = self2mm(env, self);
debug("mediamgr_set_call_state to video call \n");
mediamgr_set_call_state(jmm->mm, state);
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_setIntensityAll
(JNIEnv *env, jobject self)
{
mediamgr_sound_mode mode = MEDIAMGR_SOUND_MODE_ALL;
struct jmm *jmm;
mediamgr_state state;
jmm = self2mm(env, self);
debug("mediamgr_intensity_all \n");
mediamgr_set_sound_mode(jmm->mm, mode);
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_setIntensitySome
(JNIEnv *env, jobject self)
{
mediamgr_sound_mode mode = MEDIAMGR_SOUND_MODE_SOME;
struct jmm *jmm;
mediamgr_state state;
jmm = self2mm(env, self);
debug("mediamgr_intensity_some \n");
mediamgr_set_sound_mode(jmm->mm, mode);
}
JNIEXPORT void JNICALL Java_com_waz_media_manager_MediaManager_setIntensityNone
(JNIEnv *env, jobject self)
{
mediamgr_sound_mode mode = MEDIAMGR_SOUND_MODE_NONE;
struct jmm *jmm;
mediamgr_state state;
jmm = self2mm(env, self);
debug("mediamgr_intensity_none \n");
mediamgr_set_sound_mode(jmm->mm, mode);
}
#ifdef __cplusplus
}
#endif
| 25.278689 | 117 | 0.696628 | commonprogress |
564f1b6135a5f53c29f793ebfb93046a8d1ff3f6 | 576 | hpp | C++ | include/GameConstant.hpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | include/GameConstant.hpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | include/GameConstant.hpp | Tastyep/SFML-GameCore-2D | 51dfcd7f3a098b2efa76754703999c6b8d22369d | [
"MIT"
] | null | null | null | #ifndef GAME_CORE_GAME_CONSTANT_HPP
#define GAME_CORE_GAME_CONSTANT_HPP
#include <chrono>
#include <string>
#include <SFML/System/Vector2.hpp>
const std::string kAssetDir = "../assets/";
const std::string kMapDir = "../maps/";
const std::string kConfigDir = "../config/";
const int kMapNumberLength = 2;
const int kFrameRate = 30;
const auto kTimeStepDuration = std::chrono::milliseconds(1000) / kFrameRate;
const float kTimeStep = 1.0f / static_cast<float>(kFrameRate);
const int kTileSize = 32;
const sf::Vector2f kSpriteOrigin{ kTileSize / 2, kTileSize / 2 };
#endif
| 26.181818 | 76 | 0.744792 | Tastyep |
5651d2bd52737a29a23ca3e051ab6c2493bad1c8 | 293 | hpp | C++ | union-find/cpp/include/UnionFind.hpp | goldsborough/algs4 | 5f711f06ebc1da598cfbaeee16db0531f79e3fee | [
"MIT"
] | 17 | 2017-03-06T10:11:41.000Z | 2021-04-28T11:21:36.000Z | union-find/cpp/include/UnionFind.hpp | goldsborough/algs4 | 5f711f06ebc1da598cfbaeee16db0531f79e3fee | [
"MIT"
] | null | null | null | union-find/cpp/include/UnionFind.hpp | goldsborough/algs4 | 5f711f06ebc1da598cfbaeee16db0531f79e3fee | [
"MIT"
] | 6 | 2016-11-23T07:31:46.000Z | 2021-03-10T09:58:12.000Z | #ifndef UNION_FIND_HPP
#define UNION_FIND_HPP
class UnionFind
{
public:
UnionFind(int N)
: _N(N)
{ }
virtual ~UnionFind() = default;
virtual void makeUnion(int p, int q) = 0;
virtual bool connected(int p, int q) const = 0;
protected:
int _N;
};
#endif /* UNION_FIND_HPP */ | 12.73913 | 48 | 0.665529 | goldsborough |
5654a2f4a46186c3c7a641ed3c9cdf32af96bdbe | 2,164 | cc | C++ | util/misc/no_cfi_icall_test.cc | dark-richie/crashpad | d573ac113bd5fce5cc970bb5ae76a235a1431a5d | [
"Apache-2.0"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | util/misc/no_cfi_icall_test.cc | dark-richie/crashpad | d573ac113bd5fce5cc970bb5ae76a235a1431a5d | [
"Apache-2.0"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | util/misc/no_cfi_icall_test.cc | dark-richie/crashpad | d573ac113bd5fce5cc970bb5ae76a235a1431a5d | [
"Apache-2.0"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/misc/no_cfi_icall.h"
#include <stdio.h>
#include "build/build_config.h"
#include "gtest/gtest.h"
#if defined(OS_WIN)
#include <windows.h>
#include "util/win/get_function.h"
#else
#include <dlfcn.h>
#include <sys/types.h>
#include <unistd.h>
#endif
namespace crashpad {
namespace test {
namespace {
TEST(NoCfiIcall, NullptrIsFalse) {
NoCfiIcall<void (*)(void) noexcept> call(nullptr);
ASSERT_FALSE(call);
}
int TestFunc() noexcept {
return 42;
}
TEST(NoCfiIcall, SameDSOICall) {
NoCfiIcall<decltype(TestFunc)*> call(&TestFunc);
ASSERT_TRUE(call);
ASSERT_EQ(call(), 42);
}
TEST(NoCfiIcall, CrossDSOICall) {
#if defined(OS_WIN)
static const NoCfiIcall<decltype(GetCurrentProcessId)*> call(
GET_FUNCTION_REQUIRED(L"kernel32.dll", GetCurrentProcessId));
ASSERT_TRUE(call);
EXPECT_EQ(call(), GetCurrentProcessId());
#else
static const NoCfiIcall<decltype(getpid)*> call(dlsym(RTLD_NEXT, "getpid"));
ASSERT_TRUE(call);
EXPECT_EQ(call(), getpid());
#endif
}
TEST(NoCfiIcall, Args) {
#if !defined(OS_WIN)
static const NoCfiIcall<decltype(snprintf)*> call(
dlsym(RTLD_NEXT, "snprintf"));
ASSERT_TRUE(call);
char buf[1024];
// Regular args.
memset(buf, 0, sizeof(buf));
ASSERT_GT(call(buf, sizeof(buf), "Hello!"), 0);
EXPECT_STREQ(buf, "Hello!");
// Variadic args.
memset(buf, 0, sizeof(buf));
ASSERT_GT(call(buf, sizeof(buf), "%s, %s!", "Hello", "World"), 0);
EXPECT_STREQ(buf, "Hello, World!");
#endif
}
} // namespace
} // namespace test
} // namespace crashpad
| 24.873563 | 78 | 0.708872 | dark-richie |
56569ab5db1a01e21fa92a106fba8941ef26e08c | 3,798 | cc | C++ | src/tritonsort/mapreduce/functions/map/ParseNetworkMapFunction.cc | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | 11 | 2015-12-14T05:35:17.000Z | 2021-11-08T22:02:32.000Z | src/tritonsort/mapreduce/functions/map/ParseNetworkMapFunction.cc | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | null | null | null | src/tritonsort/mapreduce/functions/map/ParseNetworkMapFunction.cc | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | 8 | 2015-12-22T19:31:16.000Z | 2020-12-15T12:09:00.000Z | #include <arpa/inet.h>
#include <string.h>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <sstream>
#include <vector>
#include "core/Hash.h"
#include "core/Params.h"
#include "ParseNetworkMapFunction.h"
ParseNetworkMapFunction::ParseNetworkMapFunction(uint64_t _numVertices,
std::string _fileURL,
uint64_t _maxNeighbors,
uint64_t _mypeerid,
uint64_t _numPeers)
: numVertices(_numVertices), fileURL(_fileURL),
maxNeighbors(_maxNeighbors), mypeerid(_mypeerid), numPeers(_numPeers) {
}
/**
map function is run once on each peer
Each peer responsible to generate adjacency lists for approximately
(numVertices / numPeers) vertices, in order of 'mypeerid'
*/
void ParseNetworkMapFunction::map(KeyValuePair& kvPair,
KVPairWriterInterface& writer) {
fprintf(stdout, "At node id %ld (out of %ld): num vertices %ld, URL %s \n",
mypeerid, numPeers, numVertices, fileURL.c_str());
// two additional slots
// to store <number of edges> and <page rank value>
uint64_t maxAdjListSize = (numVertices < maxNeighbors) ?
numVertices : maxNeighbors;
uint64_t *outputValue = new uint64_t[maxAdjListSize + 2];
uint64_t numVerticesPerPeer = numVertices / numPeers;
if(numVertices % numPeers != 0){
numVerticesPerPeer++;
}
uint64_t beginningVertex = mypeerid * numVerticesPerPeer;
uint64_t endingVertex = beginningVertex + numVerticesPerPeer;
if(endingVertex > numVertices){
endingVertex = numVertices;
}
std::ifstream ifs(fileURL.c_str());
ABORT_IF(!ifs.good(), "Cannot open %s\n", fileURL.c_str());
std::string line;
uint64_t lineno = 0;
uint64_t numParsed = 0;
while(getline(ifs, line)){
if(lineno < beginningVertex){
lineno++;
continue;
} else if(lineno >= endingVertex){
break;
} else {
std::istringstream iss(line);
std::vector<std::string> tokens;
copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> > (tokens));
uint64_t numEdges = atol(tokens.at(1).c_str());
ABORT_IF(numEdges != tokens.size() - 2, "Mismatch in network edge info %d,"
"tokens %d at vtex %s\n", numEdges, tokens.size(), tokens.at(0).c_str());
if(numEdges > maxNeighbors){
numEdges = maxNeighbors;
}
//fprintf(stdout, "At vertex %ld, %ld edges: ",
// atol(tokens.at(0).c_str()), numEdges);
for(uint64_t j = 0; j < numEdges; j++){
uint64_t nid = atol(tokens.at(j+2).c_str());
outputValue[j + 1] = Hash::hash(nid);
//fprintf(stdout, "%ld ", nid);
}
//fprintf(stdout, "\n");
double initialPageRank = 1.0 / numVertices;
outputValue[0] = numEdges;
memcpy(&outputValue[numEdges + 1], &initialPageRank, sizeof(double));
KeyValuePair outputKVPair;
uint64_t key = Hash::hash(atol(tokens.at(0).c_str()));
outputKVPair.setKey(reinterpret_cast<const uint8_t *>(&key),
sizeof(uint64_t));
outputKVPair.setValue(reinterpret_cast<const uint8_t *>(outputValue),
(numEdges + 2) * sizeof(uint64_t));
writer.write(outputKVPair);
lineno++;
numParsed++;
}
}
ABORT_IF(numParsed != endingVertex - beginningVertex,
"Mismatch in parsing network\n");
delete[] outputValue;
ifs.close();
}
| 32.461538 | 81 | 0.602686 | anku94 |
5658d170b507d311ce22b495e17562ae0dc31f4e | 3,496 | cpp | C++ | lib/msdf-atlas-gen/msdf-atlas-gen/json-export.cpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | 8 | 2021-01-18T12:06:21.000Z | 2022-02-13T17:12:56.000Z | lib/msdf-atlas-gen/msdf-atlas-gen/json-export.cpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | null | null | null | lib/msdf-atlas-gen/msdf-atlas-gen/json-export.cpp | Tearnote/Minote | 35f63fecc01cf9199db1098256277465e1d41d1e | [
"MIT"
] | null | null | null |
#include "json-export.h"
namespace msdf_atlas {
static const char * imageTypeString(ImageType type) {
switch (type) {
case ImageType::HARD_MASK:
return "hardmask";
case ImageType::SOFT_MASK:
return "softmask";
case ImageType::SDF:
return "sdf";
case ImageType::PSDF:
return "psdf";
case ImageType::MSDF:
return "msdf";
case ImageType::MTSDF:
return "mtsdf";
}
return nullptr;
}
bool exportJSON(msdfgen::FontHandle *font, const GlyphGeometry *glyphs, int glyphCount, double fontSize, double pxRange, int atlasWidth, int atlasHeight, ImageType imageType, const char *filename) {
msdfgen::FontMetrics fontMetrics;
if (!msdfgen::getFontMetrics(fontMetrics, font))
return false;
double fsScale = 1/fontMetrics.emSize;
FILE *f = fopen(filename, "w");
if (!f)
return false;
fputs("{", f);
// Atlas properties
fputs("\"atlas\":{", f); {
fprintf(f, "\"type\":\"%s\",", imageTypeString(imageType));
if (imageType == ImageType::SDF || imageType == ImageType::PSDF || imageType == ImageType::MSDF || imageType == ImageType::MTSDF)
fprintf(f, "\"distanceRange\":%.17g,", pxRange);
fprintf(f, "\"size\":%.17g,", fontSize);
fprintf(f, "\"width\":%d,", atlasWidth);
fprintf(f, "\"height\":%d,", atlasHeight);
fputs("\"yOrigin\":\"bottom\"", f);
} fputs("},", f);
// Font metrics
fputs("\"metrics\":{", f); {
fprintf(f, "\"lineHeight\":%.17g,", fsScale*fontMetrics.lineHeight);
fprintf(f, "\"ascender\":%.17g,", fsScale*fontMetrics.ascenderY);
fprintf(f, "\"descender\":%.17g,", fsScale*fontMetrics.descenderY);
fprintf(f, "\"underlineY\":%.17g,", fsScale*fontMetrics.underlineY);
fprintf(f, "\"underlineThickness\":%.17g", fsScale*fontMetrics.underlineThickness);
} fputs("},", f);
// Glyph mapping
fputs("\"glyphs\":[", f);
for (int i = 0; i < glyphCount; ++i) {
fputs(i == 0 ? "{" : ",{", f);
fprintf(f, "\"index\":%u,", glyphs[i].getCodepoint());
fprintf(f, "\"advance\":%.17g", fsScale*glyphs[i].getAdvance());
double l, b, r, t;
glyphs[i].getQuadPlaneBounds(l, b, r, t);
if (l || b || r || t)
fprintf(f, ",\"planeBounds\":{\"left\":%.17g,\"bottom\":%.17g,\"right\":%.17g,\"top\":%.17g}", fsScale*l, fsScale*b, fsScale*r, fsScale*t);
glyphs[i].getQuadAtlasBounds(l, b, r, t);
if (l || b || r || t)
fprintf(f, ",\"atlasBounds\":{\"left\":%.17g,\"bottom\":%.17g,\"right\":%.17g,\"top\":%.17g}", l, b, r, t);
fputs("}", f);
}
fputs("],", f);
// Kerning pairs
fputs("\"kerning\":[", f);
bool firstPair = true;
for (int i = 0; i < glyphCount; ++i) {
for (int j = 0; j < glyphCount; ++j) {
double kerning;
if (msdfgen::getKerning(kerning, font, glyphs[i].getCodepoint(), glyphs[j].getCodepoint()) && kerning) {
fputs(firstPair ? "{" : ",{", f);
fprintf(f, "\"index1\":%u,", glyphs[i].getCodepoint());
fprintf(f, "\"index2\":%u,", glyphs[j].getCodepoint());
fprintf(f, "\"advance\":%.17g", fsScale*kerning);
fputs("}", f);
firstPair = false;
}
}
}
fputs("]", f);
fputs("}\n", f);
fclose(f);
return true;
}
}
| 36.416667 | 198 | 0.52889 | Tearnote |
5658e14dd90d2d7b69f49e411d60b901c3e9a0ad | 302 | cpp | C++ | components/wear_levelling/crc32.cpp | BU-EC444/esp-idf | 5963de1caf284b14ddfed11e52730a55e3783a3d | [
"Apache-2.0"
] | 4 | 2022-03-15T22:43:28.000Z | 2022-03-28T01:25:08.000Z | components/wear_levelling/crc32.cpp | BU-EC444/esp-idf | 5963de1caf284b14ddfed11e52730a55e3783a3d | [
"Apache-2.0"
] | null | null | null | components/wear_levelling/crc32.cpp | BU-EC444/esp-idf | 5963de1caf284b14ddfed11e52730a55e3783a3d | [
"Apache-2.0"
] | 2 | 2022-02-04T21:36:58.000Z | 2022-02-09T12:22:48.000Z | /*
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "crc32.h"
#include "esp32/rom/crc.h"
unsigned int crc32::crc32_le(unsigned int crc, unsigned char const *buf, unsigned int len)
{
return ::crc32_le(crc, buf, len);
}
| 23.230769 | 90 | 0.708609 | BU-EC444 |
565aa3e6a8c46d3ca8b5b8b2a754675be785089f | 477 | cpp | C++ | various/boost_examples/tokenizer2.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | 14 | 2019-04-23T13:45:10.000Z | 2022-03-12T18:26:47.000Z | various/boost_examples/tokenizer2.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | null | null | null | various/boost_examples/tokenizer2.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | 9 | 2019-09-01T15:17:45.000Z | 2020-11-13T20:31:36.000Z | #include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
using namespace boost;
using namespace std;
int main(){
char_separator<char> sep("e", " ", keep_empty_tokens);
string s = "This is a text. Surpise, some more text!!!";
tokenizer<char_separator<char>> tok(s, sep);
for(auto word: tok){
cout << "<" << word << ">" << endl;
}
}
/*
<This>
< >
<is>
< >
<a>
< >
<t>
<xt.>
< >
<Surpis>
<,>
< >
<som>
<>
< >
<mor>
<>
< >
<t>
<xt!!!>
*/
| 12.230769 | 60 | 0.536688 | chgogos |
565c266eb9e7976165ad836ad0bc9eb62426eed2 | 6,013 | cpp | C++ | Kiryanov/04/hw_04.cpp | mtrempoltsev/msu_cpp_autumn_2018 | 9272511ddfaa78332cfabda071b5fa3a9aee79cf | [
"MIT"
] | 16 | 2018-09-27T13:59:59.000Z | 2019-10-01T21:33:40.000Z | Kiryanov/04/hw_04.cpp | mtrempoltsev/msu_cpp_autumn_2018 | 9272511ddfaa78332cfabda071b5fa3a9aee79cf | [
"MIT"
] | 2 | 2018-10-17T20:56:15.000Z | 2018-10-24T00:02:42.000Z | Kiryanov/04/hw_04.cpp | mtrempoltsev/msu_cpp_autumn_2018 | 9272511ddfaa78332cfabda071b5fa3a9aee79cf | [
"MIT"
] | 22 | 2018-09-27T14:00:16.000Z | 2019-12-17T19:44:33.000Z | #include <iostream>
#include <string>
#include<cstring>
#include <cstdlib>
#include <math.h>
#include <algorithm>
using namespace std;
class BigInt
{
int get_extra_dozen(int64_t& num) const
{
int res;
if (num >= pow(10, available_orders))
{
res = num / pow(10, available_orders);
num = num % int64_t(pow(10, available_orders));
}
else
res = 0;
return res;
}
void delete_zeros(BigInt& num) const
{
for (size_t i = num.size_ - 1; i > 0; i--)
{
if (num.value[i] == 0)
num.size_--;
else
break;
}
}
void new_order(BigInt& num, const int extra_dozen) const
{
if (extra_dozen != 0)
{
num.value = (int64_t*)realloc(num.value, (num.size_ + 1) * sizeof(int64_t));
num.value[size_] = extra_dozen;
num.size_++;
}
}
void edit(BigInt& num) const
{
num.sign = (num.value[num.size_ - 1] > 0) ? 1 : -1;
int extra_dozen = 0;
int sign_;
for (size_t i = 0; i < num.size_; i++)
{
sign_ = (num.value[i] > 0) ? 1 : -1;
num.value[i] += extra_dozen;
if (num.sign != sign_)
{
num.value[i] = pow(10, available_orders) + num.sign*num.value[i];
extra_dozen = -num.sign;
}
else
extra_dozen = 0;
}
for (size_t i = 0; i < num.size_; i++)
num.value[i] = abs(num.value[i]);
delete_zeros(num);
}
const int64_t available_orders = 18;
size_t size_;
int sign;
int64_t* value;
public:
BigInt() :size_(1), sign(1), value(new int64_t[1]) { value[0] = 0; }
BigInt(const int64_t& x)
:size_((x < pow(10, available_orders)) ? 1 : 2),
sign((x>0) ? 1 : -1),
value(new int64_t[size_])
{
if (size_ == 1)
value[0] = sign * x;
else
{
value[0] = (x % int64_t(pow(10, available_orders)))*sign;
value[1] = (x / pow(10, available_orders))*sign;
}
}
BigInt(const int x)
:size_(1),
sign((x>0) ? 1 : -1),
value(new int64_t[size_])
{
value[0] = int64_t(x)*sign;
}
BigInt(const char* input)
:size_(strlen(input) % available_orders == 0 ? strlen(input) / available_orders : strlen(input) / available_orders + 1),
sign(1),
value(new int64_t[size_])
{
string s = input;
if (input[0] == '-')
{
sign = -1;
s = s.substr(1);
if (s.length() % available_orders == 0)
size_ -= 1;
}
size_t i = 0;
for (i; i < size_ - 1; i++)
value[i] = atoi(s.substr(s.length() - (i + 1)* available_orders, available_orders).c_str());
value[size_ - 1] = atoi(s.substr(0, s.length() - i * available_orders).c_str());
}
BigInt(const BigInt& copied)
:size_(copied.size_),
sign(copied.sign),
value(new int64_t[size_])
{
for (size_t i = 0; i < size_; i++)
value[i] = copied.value[i];
}
~BigInt() { delete[] value; }
BigInt& operator=(const BigInt& copied)
{
sign = copied.sign;
size_ = copied.size_;
delete[] value;
value = new int64_t[size_];
for (size_t i = 0; i < size_; i++)
value[i] = copied.value[i];
return *this;
}
BigInt& operator=(const int64_t& num)
{
BigInt tmp(num);
*this = tmp;
return *this;
}
BigInt& operator=(const char* num)
{
BigInt tmp(num);
*this = tmp;
return *this;
}
BigInt operator+(const BigInt& other) const
{
int extra_dozen = 0;
BigInt res;
if (other.size_ > size_)
{
delete[] res.value;
res.value = new int64_t[other.size_];
res.size_ = other.size_;
for (size_t i = 0; i < size_; i++)
{
res.value[i] = other.sign*other.value[i] + extra_dozen + value[i] * sign;
extra_dozen = get_extra_dozen(res.value[i]);
}
for (size_t i = size_; i < other.size_; i++)
{
res.value[i] = other.sign*other.value[i] + extra_dozen;
extra_dozen = get_extra_dozen(res.value[i]);
}
}
else
{
delete[] res.value;
res.value = new int64_t[size_];
res.size_ = size_;
for (size_t i = 0; i < other.size_; i++)
{
res.value[i] = other.sign*other.value[i] + extra_dozen + value[i] * sign;
extra_dozen = get_extra_dozen(res.value[i]);
}
for (size_t i = other.size_; i < size_; i++)
{
res.value[i] = extra_dozen + value[i] * sign;
extra_dozen = get_extra_dozen(res.value[i]);
if (extra_dozen == 0)
break;
}
}
new_order(res, extra_dozen);
delete_zeros(res);
edit(res);
return res;
}
BigInt operator-() const
{
BigInt res = *this;
if (!(size_ == 1 && value[0] == 0))
res.sign *= -1;
return res;
}
BigInt operator-(const BigInt& other) const
{
BigInt res = *this + (-other);
return res;
}
const bool operator==(const BigInt& other) const
{
if (size_ != other.size_)
return false;
if (sign != other.sign)
return false;
for (size_t i = 0; i < size_; i++)
{
if (value[i] != other.value[i])
return false;
}
return true;
}
const bool operator>(const BigInt& other) const
{
if (sign == -1)
{
if (other.sign == 1 || size_ > other.size_)
return false;
if (size_ < other.size_)
return true;
for (size_t i = size_ - 1; i > 0; i--)
{
if (value[i] > other.value[i])
return false;
}
return value[0] < other.value[0];
}
if (sign == 1)
{
if (other.sign == -1 || size_ > other.size_)
return true;
if (size_ < other.size_)
return false;
for (int i = size_ - 1; i >= 0; i--)
{
if (value[i] < other.value[i])
return false;
}
return value[0] > other.value[0];
}
return true;
}
const bool operator>=(const BigInt& other) const
{
return *this > other || *this == other;
}
const bool operator<(const BigInt& other) const
{
return !(*this >= other);
}
const bool operator<=(const BigInt& other) const
{
return !(*this > other);
}
const bool operator!=(const BigInt& other) const
{
return !(*this == other);
}
friend ostream& operator << (ostream& out, const BigInt& num);
};
ostream& operator << (ostream& out, const BigInt& num)
{
out << num.sign*num.value[num.size_ - 1];
for (int i = num.size_ - 2; i >= 0; i--)
{
for (int j = 17; j > 0; j--)
{
if (num.value[i] / int64_t(pow(10, j)) == 0)
out << 0;
else
break;
}
out << num.value[i];
}
return out;
}
| 20.177852 | 122 | 0.5844 | mtrempoltsev |
5660785b9399aeb42d402e6540b34e4715b9e617 | 227 | hpp | C++ | nek/container/function/clear.hpp | nekko1119/nek | be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7 | [
"BSD-3-Clause"
] | null | null | null | nek/container/function/clear.hpp | nekko1119/nek | be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7 | [
"BSD-3-Clause"
] | null | null | null | nek/container/function/clear.hpp | nekko1119/nek | be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7 | [
"BSD-3-Clause"
] | null | null | null | #ifndef NEK_CONTAINER_FUNCTION_CLEAR_HPP
#define NEK_CONTAINER_FUNCTION_CLEAR_HPP
namespace nek
{
template <class Container>
void clear(Container& con)
{
con.erase(con.begin(), con.end());
}
}
#endif
| 16.214286 | 42 | 0.696035 | nekko1119 |
5660f2499aa3741496a10854ba6ad622b13408fd | 228 | cpp | C++ | engine/commands/help/source/unit_tests/HelpKeyboardCommandMap_test.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/commands/help/source/unit_tests/HelpKeyboardCommandMap_test.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/commands/help/source/unit_tests/HelpKeyboardCommandMap_test.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "gtest/gtest.h"
TEST(SW_Engine_Commands_Help_HelpKeyboardCommandMap, serialization_id)
{
HelpKeyboardCommandMap hkcm;
EXPECT_EQ(ClassIdentifier::CLASS_ID_HELP_KEYBOARD_COMMAND_MAP, hkcm.get_class_identifier());
}
| 25.333333 | 94 | 0.842105 | sidav |
566170271eb4daf27aa579be681655190d96bbdd | 717 | cpp | C++ | codeforces/992C - Nastya and a Wardrobe.cpp | Dijkstraido-2/online-judge | 31844cd8fbd5038cc5ebc6337d68229cef133a30 | [
"MIT"
] | 1 | 2018-12-25T23:55:19.000Z | 2018-12-25T23:55:19.000Z | codeforces/992C - Nastya and a Wardrobe.cpp | Dijkstraido-2/online-judge | 31844cd8fbd5038cc5ebc6337d68229cef133a30 | [
"MIT"
] | null | null | null | codeforces/992C - Nastya and a Wardrobe.cpp | Dijkstraido-2/online-judge | 31844cd8fbd5038cc5ebc6337d68229cef133a30 | [
"MIT"
] | null | null | null | //============================================================================
// Problem : 992C - Nastya and a Wardrobe
// Category : Math
//============================================================================
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1e9+7;
ll sub(ll a, ll b) { return (a%MOD - b%MOD + MOD) % MOD; }
ll mul(ll a, ll b) { return a%MOD * (b%MOD) % MOD; }
ll modP(ll b, ll p) { return !p? 1 : mul(modP(b*b%MOD, p/2), p&1? b:1); }
int main()
{
ll x,k;
while(cin >> x >> k)
{
if(x == 0)
cout << 0 << '\n';
else
cout << sub(mul(modP(2, k+1), x), sub(modP(2, k), 1)) << '\n';
}
return 0;
} | 24.724138 | 78 | 0.380753 | Dijkstraido-2 |
5661b5f36d221b58f79703e7dd72da42a570675e | 17,272 | cpp | C++ | Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/StoryGraphObject.cpp | Xian-Yun-Jun/StoryGraph | 36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b | [
"MIT"
] | 126 | 2016-12-24T13:58:18.000Z | 2022-03-10T03:20:47.000Z | Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/StoryGraphObject.cpp | Xian-Yun-Jun/StoryGraph | 36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b | [
"MIT"
] | 5 | 2017-01-05T08:23:30.000Z | 2018-01-30T19:38:33.000Z | Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/StoryGraphObject.cpp | Xian-Yun-Jun/StoryGraph | 36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b | [
"MIT"
] | 45 | 2016-12-25T02:21:45.000Z | 2022-02-14T16:06:58.000Z | // Copyright 2016 Dmitriy Pavlov
#include "StoryGraphObject.h"
#include "StoryGraph.h"
#include "StoryScenObject.h"
#include "HUD_StoryGraph.h"
#include "CustomNods.h"
#include "StoryGraphWiget.h"
#if WITH_EDITORONLY_DATA
#include "AssetEditorManager.h"
#include "Developer/DesktopPlatform/Public/DesktopPlatformModule.h"
#endif //WITH_EDITORONLY_DATA
int UStoryGraphObject::CharNum;
int UStoryGraphObject::QuestNum;
int UStoryGraphObject::PlaceTriggerNum;
int UStoryGraphObject::DialogTriggerNum;
int UStoryGraphObject::OthersNum;
int UStoryGraphObject::InventoryItemNum;
UStoryGraphObject::UStoryGraphObject()
{
Category = "Default";
ObjName = FText::FromString("New Object" + FString::FromInt(OthersNum++));
ObjectType = EStoryObjectType::Non;
}
TSubclassOf<UStoryGraphObject> UStoryGraphObject::GetClassFromStoryObjectType(EStoryObjectType EnumValue)
{
switch (EnumValue)
{
case EStoryObjectType::Character:
return UStoryGraphCharecter::StaticClass();
case EStoryObjectType::Quest:
return UStoryGraphQuest::StaticClass();
case EStoryObjectType::DialogTrigger:
return UStoryGraphDialogTrigger::StaticClass();
case EStoryObjectType::PlaceTrigger:
return UStoryGraphPlaceTrigger::StaticClass();
case EStoryObjectType::InventoryItem:
return UStoryGraphInventoryItem::StaticClass();
case EStoryObjectType::Others:
return UStoryGraphOthers::StaticClass();
default:
return UStoryGraphObject::StaticClass();
}
}
FString UStoryGraphObject::GetObjectTypeEnumAsString(EStoryObjectType EnumValue)
{
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EStoryObjectType"), true);
if (!EnumPtr) return FString("Invalid");
return EnumPtr->GetNameStringByIndex((int)EnumValue);
}
FString UStoryGraphObject::GetObjectToolTip(EStoryObjectType EnumValue)
{
switch (EnumValue)
{
case EStoryObjectType::Character:
return "Character has dialogs.";
case EStoryObjectType::Quest:
return "List of all available quests. After you added quest, will available start quest node.";
case EStoryObjectType::DialogTrigger:
return "Special facility for interaction dialogue(meesage) graph and main graph.";
case EStoryObjectType::PlaceTrigger:
return "PlaceTrigger - interactive object on map.";
case EStoryObjectType::InventoryItem:
return "Story object which can be added to inventory.";
case EStoryObjectType::Others:
return "Objects that do not have states. But can get messages.";
default:
return "Non.";
}
}
void UStoryGraphObject::SetCurentState(int NewState)
{
ObjectState = NewState;
((UStoryGraph*)GetOuter())->RefreshExecutionTrees();
}
void UStoryGraphObject::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys)
{
Propertys.clear();
Propertys.insert(std::pair<FString, XMLProperty>("ObjName", XMLProperty(ObjName.ToString())));
Propertys.insert(std::pair<FString, XMLProperty>("ObjectType", XMLProperty(GetEnumValueAsString<EStoryObjectType>("EStoryObjectType", ObjectType))));
Propertys.insert(std::pair<FString, XMLProperty>("Category", XMLProperty( Category)));
Propertys.insert(std::pair<FString, XMLProperty>("Comment", XMLProperty(Comment)));
}
void UStoryGraphObject::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys)
{
ObjName = FText::FromString(Propertys["ObjName"].Val);
Category = Propertys["Category"].Val;
Comment = Propertys["Comment"].Val;
}
//UStoryGraphObjectWithScenObject.........................................................
UStoryGraphObjectWithScenObject::UStoryGraphObjectWithScenObject()
{
IsScenObjectActive = true;
DependetNodes.Add(ENodeType::GetStoryGraphObjectState);
DependetNodes.Add(ENodeType::SetScenObjectActive);
DependetNodes.Add(ENodeType::SendMessageCsen);
DependetNodes.Add(ENodeType::AddTargetObjectToPhase);
}
void UStoryGraphObjectWithScenObject::InitializeObject()
{
SetActiveStateOfScenObjects();
TArray<IStoryScenObject*> ScenObjects;
GetScenObjects(ScenObjects);
for (int i = 0; i < ObjectMesssageStack.Num(); i++)
{
for (int j = 0; j < ScenObjects.Num(); j++)
{
ScenObjects[j]->SendMessageToScenObject(ObjectMesssageStack[i]);
}
}
}
void UStoryGraphObjectWithScenObject::SetActiveStateOfScenObjects()
{
TArray<IStoryScenObject*> ScenObjects;
GetScenObjects(ScenObjects);
for (int i = 0; i < ScenObjects.Num(); i++)
{
ScenObjects[i]->RefreshScenObjectActive();
}
}
void UStoryGraphObjectWithScenObject::SetScenObjectActive(bool Active)
{
IsScenObjectActive = Active;
SetActiveStateOfScenObjects();
}
void UStoryGraphObjectWithScenObject::SendMessageToScenObject(FString Message)
{
TArray<IStoryScenObject*> ScenObjects;
GetScenObjects(ScenObjects);
for (int i = 0; i < ScenObjects.Num(); i++)
{
ScenObjects[i]->SendMessageToScenObject(Message);
}
ObjectMesssageStack.Add(Message);
}
void UStoryGraphObjectWithScenObject::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys)
{
Super::GetXMLSavingProperty(Propertys);
Propertys.insert(std::pair<FString, XMLProperty>("IsScenObjectActive", XMLProperty(IsScenObjectActive ? "true" : "false" )));
}
void UStoryGraphObjectWithScenObject::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys)
{
Super::LoadPropertyFromXML(Propertys);
IsScenObjectActive = Propertys["IsScenObjectActive"].Val == "true" ? true : false;
}
//UStoryGraphCharecter.................................................................................
UStoryGraphCharecter::UStoryGraphCharecter()
{
ObjName = FText::FromString("New Character" + FString::FromInt(CharNum++));
ObjectType = EStoryObjectType::Character;
DependetNodes.Add(ENodeType::AddDialog);
}
void UStoryGraphCharecter::GetObjectStateAsString(TArray<FString>& States)
{
int i = 0;
while (i < GetNumberEnums("ECharecterStates"))
{
States.Add(GetEnumValueAsString<ECharecterStates>("ECharecterStates", (ECharecterStates)i++));
}
}
void UStoryGraphCharecter::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects)
{
TExstractScenObgects<IStoryScenObject, ACharecter_StoryGraph>(ScenObjects, ScenCharecters, ScenCharecterPointers);
}
void UStoryGraphCharecter::GetScenObjects(TArray<AActor*>& ScenObjects)
{
TExstractScenObgects<AActor, ACharecter_StoryGraph>(ScenObjects, ScenCharecters, ScenCharecterPointers);
}
void UStoryGraphCharecter::SetScenObjectRealPointers()
{
ScenCharecterPointers.Empty();
for (int i = 0; i < ScenCharecters.Num(); i++)
{
ScenCharecterPointers.Add(ScenCharecters[i].Get());
}
RealPointersActive = true;
}
void UStoryGraphCharecter::ClearScenObjects()
{
ScenCharecters.Empty();
}
void UStoryGraphCharecter::GetInternallySaveObjects(TArray<UObject*>& Objects, int WantedObjectsNum)
{
for (int i = 0; i < GarphNods.Num(); i++)
{
if (Cast<UDialogStartNode>(GarphNods[i]))
{
Objects.Add(GarphNods[i]);
}
}
}
void UStoryGraphCharecter::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys)
{
Super::GetXMLSavingProperty(Propertys);
Propertys.insert(std::pair<FString, XMLProperty>("DefaultAnswer", XMLProperty(DefaultAnswer.ToString())));
}
void UStoryGraphCharecter::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys)
{
Super::LoadPropertyFromXML(Propertys);
DefaultAnswer = FText::FromString(Propertys["DefaultAnswer"].Val);
}
//UStoryGraphQuest.................................................................................
UStoryGraphQuest::UStoryGraphQuest()
{
ObjName = FText::FromString("New Quest" + FString::FromInt(QuestNum++));
ObjectType = EStoryObjectType::Quest;
MainQuest = true;
DependetNodes.Add(ENodeType::GetStoryGraphObjectState);
DependetNodes.Add(ENodeType::QuestStart);
DependetNodes.Add(ENodeType::CancelQuest);
}
void UStoryGraphQuest::GetObjectStateAsString(TArray<FString>& States)
{
int i = 0;
while (i < GetNumberEnums("EQuestStates"))
{
States.Add(GetEnumValueAsString<EQuestStates>("EQuestStates", (EQuestStates)i++));
}
}
void UStoryGraphQuest::SetCurentState(int NewState)
{
FText Mesg;
ObjectState = NewState;
switch ((EQuestStates)NewState)
{
case EQuestStates::Active:
Mesg = FText::Format(NSLOCTEXT("StoryGraph", "Quest active", "New quest {0}"), ObjName);
break;
case EQuestStates::Canceled:
Mesg = FText::Format(NSLOCTEXT("StoryGraph", "Quest cancel", "Quest {0} cancel"), ObjName);
break;
case EQuestStates::Complite:
Mesg = FText::Format(NSLOCTEXT("StoryGraph", "Quest complite", "Quest {0} complite"), ObjName);
break;
}
if (AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>(((UStoryGraph*)GetOuter())->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD()))
{
if (HUD->GameScreen)
{
HUD->GameScreen->AddMessageOnScreen(Mesg, 5);
}
}
((UStoryGraph*)GetOuter())->QuestStateWasChange = true;
}
void UStoryGraphQuest::AddPhase(UQuestPhase* Phase)
{
if (QuestPhase.Num() == 0)
{
SetCurentState((int)EQuestStates::Active);
}
else
{
if (AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>((((UStoryGraph*)GetOuter())->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD())))
{
FText Mesg = FText::Format(NSLOCTEXT("StoryGraph", "AddQuestPhaseMessage2", "Quest {0} changed"), ObjName);
if (HUD->GameScreen)
{
HUD->GameScreen->AddMessageOnScreen(Mesg, 5);
}
}
}
QuestPhase.Add(Phase);
}
void UStoryGraphQuest::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys)
{
Super::GetXMLSavingProperty(Propertys);
Propertys.insert(std::pair<FString, XMLProperty>("MainQuest", XMLProperty(MainQuest ? "true" : "false")));
}
void UStoryGraphQuest::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys)
{
Super::LoadPropertyFromXML(Propertys);
MainQuest = Propertys["MainQuest"].Val == "true" ? true : false;
}
//UStoryGraphPlaceTrigger.................................................................................
UStoryGraphPlaceTrigger::UStoryGraphPlaceTrigger()
{
ObjName = FText::FromString("Place Trigger" + FString::FromInt(PlaceTriggerNum++));
ObjectType = EStoryObjectType::PlaceTrigger;
ObjectState = (int)EPlaceTriggerStates::UnActive;
DependetNodes.Add(ENodeType::AddMessageBranch);
}
void UStoryGraphPlaceTrigger::GetObjectStateAsString(TArray<FString>& States)
{
int i = 0;
while (i < GetNumberEnums("EPlaceTriggerStates"))
{
States.Add(GetEnumValueAsString<EPlaceTriggerStates>("EPlaceTriggerStates", (EPlaceTriggerStates)i++));
}
}
void UStoryGraphPlaceTrigger::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects)
{
TExstractScenObgects<IStoryScenObject, APlaceTrigger_StoryGraph>(ScenObjects, ScenTriggers, PlaceTriggerPointers);
}
void UStoryGraphPlaceTrigger::GetScenObjects(TArray<AActor*>& ScenObjects)
{
TExstractScenObgects<AActor, APlaceTrigger_StoryGraph>(ScenObjects, ScenTriggers, PlaceTriggerPointers);
}
void UStoryGraphPlaceTrigger::SetScenObjectRealPointers()
{
PlaceTriggerPointers.Empty();
for (int i = 0; i < ScenTriggers.Num(); i++)
{
PlaceTriggerPointers.Add(ScenTriggers[i].Get());
}
RealPointersActive = true;
}
void UStoryGraphPlaceTrigger::ClearScenObjects()
{
ScenTriggers.Empty();
}
void UStoryGraphPlaceTrigger::GetInternallySaveObjects(TArray<UObject*>& Objects, int WantedObjectsNum)
{
for (int i = 0; i < GarphNods.Num(); i++)
{
if (Cast<UDialogStartNode>(GarphNods[i]))
{
Objects.Add(GarphNods[i]);
}
}
}
void UStoryGraphPlaceTrigger::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys)
{
Super::GetXMLSavingProperty(Propertys);
Propertys.insert(std::pair<FString, XMLProperty>("DefaultAnswer", XMLProperty(DefaultAnswer.ToString())));
Propertys.insert(std::pair<FString, XMLProperty>("PlaceTriggerType", XMLProperty(GetEnumValueAsString<EPlaceTriggerType>("EPlaceTriggerType", PlaceTriggerType))));
}
void UStoryGraphPlaceTrigger::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys)
{
Super::LoadPropertyFromXML(Propertys);
DefaultAnswer = FText::FromString(Propertys["DefaultAnswer"].Val);
PlaceTriggerType = GetEnumValueFromString<EPlaceTriggerType>("EPlaceTriggerType", Propertys["PlaceTriggerType"].Val);
}
//UStoryGraphDialogTrigger.................................................................................
UStoryGraphDialogTrigger::UStoryGraphDialogTrigger()
{
ObjName = FText::FromString("Dialog Trigger" + FString::FromInt(DialogTriggerNum++));
ObjectType = EStoryObjectType::DialogTrigger;
DependetNodes.Add(ENodeType::GetStoryGraphObjectState);
DependetNodes.Add(ENodeType::SetDialogTrigger);
}
void UStoryGraphDialogTrigger::GetObjectStateAsString(TArray<FString>& States)
{
int i = 0;
while (i < GetNumberEnums("EDialogTriggerStates"))
{
States.Add(GetEnumValueAsString<EDialogTriggerStates>("EDialogTriggerStates", (EDialogTriggerStates)i++));
}
}
//UStoryGraphInventoryItem.................................................................................
UStoryGraphInventoryItem::UStoryGraphInventoryItem()
{
ObjName = FText::FromString("Inventory Item" + FString::FromInt(InventoryItemNum++));
ObjectType = EStoryObjectType::InventoryItem;
InventoryItemWithoutScenObject = false;
DependetNodes.Add(ENodeType::SetInventoryItemState);
DependetNodes.Add(ENodeType::SetInventoryItemStateFromMessage);
}
void UStoryGraphInventoryItem::GetObjectStateAsString(TArray<FString>& States)
{
States.Add("UnActive");
States.Add("OnLevel");
if (InventoryItemPhase.Num() == 0)
{
States.Add("InInventory");
}
else
{
for (int i = 0; i < InventoryItemPhase.Num(); i++)
{
States.Add(InventoryItemPhase[i].ToString());
}
}
}
void UStoryGraphInventoryItem::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects)
{
TExstractScenObgects<IStoryScenObject, AInventoryItem_StoryGraph>(ScenObjects, ScenInventoryItems, InventoryItemPointers);
}
void UStoryGraphInventoryItem::GetScenObjects(TArray<AActor*>& ScenObjects)
{
TExstractScenObgects<AActor, AInventoryItem_StoryGraph>(ScenObjects, ScenInventoryItems, InventoryItemPointers);
}
void UStoryGraphInventoryItem::SetScenObjectRealPointers()
{
InventoryItemPointers.Empty();
for (int i = 0; i < ScenInventoryItems.Num(); i++)
{
InventoryItemPointers.Add(ScenInventoryItems[i].Get());
}
RealPointersActive = true;
}
void UStoryGraphInventoryItem::ClearScenObjects()
{
ScenInventoryItems.Empty();
}
void UStoryGraphInventoryItem::SetCurentState(int NewState)
{
if (NewState == 0)
{
SetScenObjectActive(false);
}
else if (NewState > 0)
{
if (!IsScenObjectActive)
{
SetScenObjectActive(false);
}
}
if (NewState == 1)
{
ObjectState = (int)EInventoryItemeStates::OnLevel;
}
else if (NewState > 1)
{
ObjectState = (int)EInventoryItemeStates::InInventory;
}
if (InventoryItemPhase.Num() > 0 && NewState > 1)
{
CurrentItemPhase = NewState - 2;
}
((UStoryGraph*)GetOuter())->RefreshExecutionTrees();
}
int UStoryGraphInventoryItem::GetCurentState()
{
if (!IsScenObjectActive)
{
return 0;
}
if (ObjectState == (int)EInventoryItemeStates::OnLevel)
{
return 1;
}
if (ObjectState == (int)EInventoryItemeStates::InInventory)
{
if (InventoryItemPhase.Num() > 0)
{
return CurrentItemPhase + 2;
}
else
{
return 2;
}
}
return 0;
}
void UStoryGraphInventoryItem::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys)
{
Super::GetXMLSavingProperty(Propertys);
Propertys.insert(std::pair<FString, XMLProperty>("InventoryItemWithoutScenObject", XMLProperty(InventoryItemWithoutScenObject ? "true" : "false")));
Propertys.insert(std::pair<FString, XMLProperty>("Arr_InventoryItemPhase", XMLProperty("")));
XMLProperty& InventoryItemPhasePointer = Propertys["Arr_InventoryItemPhase"];
for (int i = 0; i < InventoryItemPhase.Num(); i++)
{
InventoryItemPhasePointer.Propertys.insert(std::pair<FString, XMLProperty>(FString::FromInt(i), XMLProperty( InventoryItemPhase[i].ToString())));
}
}
void UStoryGraphInventoryItem::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys)
{
Super::LoadPropertyFromXML(Propertys);
InventoryItemWithoutScenObject = Propertys["InventoryItemWithoutScenObject"].Val == "true" ? true : false;
for (auto it = Propertys["Arr_InventoryItemPhase"].Propertys.begin(); it != Propertys["Arr_InventoryItemPhase"].Propertys.end(); ++it)
{
InventoryItemPhase.Add(FText::FromString(it->second.Val));
}
}
//UStoryGraphOthers.................................................................................
UStoryGraphOthers::UStoryGraphOthers()
{
ObjName = FText::FromString("Object" + FString::FromInt(OthersNum++));
ObjectType = EStoryObjectType::Others;
DependetNodes.RemoveSingle(ENodeType::GetStoryGraphObjectState);
}
void UStoryGraphOthers::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects)
{
TExstractScenObgects<IStoryScenObject, AOtherActor_StoryGraph>(ScenObjects, ScenOtherObjects, OtherPointers);
}
void UStoryGraphOthers::GetScenObjects(TArray<AActor*>& ScenObjects)
{
TExstractScenObgects<AActor, AOtherActor_StoryGraph>(ScenObjects, ScenOtherObjects, OtherPointers);
}
void UStoryGraphOthers::SetScenObjectRealPointers()
{
OtherPointers.Empty();
for (int i = 0; i < ScenOtherObjects.Num(); i++)
{
OtherPointers.Add(ScenOtherObjects[i].Get());
}
RealPointersActive = true;
}
void UStoryGraphOthers::ClearScenObjects()
{
ScenOtherObjects.Empty();
} | 26.130106 | 164 | 0.739868 | Xian-Yun-Jun |
56624ea6e4db7e72c41abca7c028bf32bca9a125 | 42 | hpp | C++ | addons/vehicles_land/XEH_PREP.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | addons/vehicles_land/XEH_PREP.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | addons/vehicles_land/XEH_PREP.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | PREP(BushMasterHitEH);
PREP(JackelHitEH);
| 14 | 22 | 0.809524 | SOCOMD |
5662d65d009fa7924de76c821f89520b84721156 | 1,574 | cxx | C++ | Src/Projects/manager_PostProcessing/MAIN.cxx | musterchef/OpenMoBu | b98e9f8d6182d84e54da1b790bbe69620ea818de | [
"BSD-3-Clause"
] | 53 | 2018-04-21T14:16:46.000Z | 2022-03-19T11:27:37.000Z | Src/Projects/manager_PostProcessing/MAIN.cxx | musterchef/OpenMoBu | b98e9f8d6182d84e54da1b790bbe69620ea818de | [
"BSD-3-Clause"
] | 6 | 2019-06-05T16:37:29.000Z | 2021-09-20T07:17:03.000Z | Src/Projects/manager_PostProcessing/MAIN.cxx | musterchef/OpenMoBu | b98e9f8d6182d84e54da1b790bbe69620ea818de | [
"BSD-3-Clause"
] | 10 | 2019-02-22T18:43:59.000Z | 2021-09-02T18:53:37.000Z |
/** \file MAIN.cxx
Sergei <Neill3d> Solokhin 2018
GitHub page - https://github.com/Neill3d/OpenMoBu
Licensed under The "New" BSD License - https://github.com/Neill3d/OpenMoBu/blob/master/LICENSE
*/
//--- SDK include
#include <fbsdk/fbsdk.h>
#ifdef KARCH_ENV_WIN
#include <windows.h>
#endif
#include "postprocessing_data.h"
// for back compatibility
extern "C" { FILE __iob_func[3] = { *stdin,*stdout,*stderr }; }
//--- Library declaration
FBLibraryDeclare( manager_postprocessing )
{
FBLibraryRegister(PostProcessingAssociation);
FBLibraryRegister( Manager_PostProcessing );
FBLibraryRegister(PostPersistentData);
FBLibraryRegisterElement(PostPersistentData);
FBLibraryRegister(ORManip_Template);
//FBLibraryRegisterStorable(ORHUDElementCustom);
}
FBLibraryDeclareEnd;
/************************************************
* Library functions.
************************************************/
extern bool InitializeSockets();
extern void ShutdownSockets();
bool FBLibrary::LibInit() { return true; }
bool FBLibrary::LibOpen() {
//InitializeSockets();
return true; }
bool FBLibrary::LibReady() {
PostPersistentData::AddPropertiesToPropertyViewManager();
return true;
}
bool FBLibrary::LibClose() {
//ShutdownSockets();
return true; }
bool FBLibrary::LibRelease() { return true; }
/**
* \mainpage Post Processing Manager
* \section intro Introduction
* Manager that injects rendering callback and grabs frame information
* color and depth information is used to apply post processing filters
*/
| 24.215385 | 94 | 0.691233 | musterchef |
566566612126c19727fe46fd806e58fcef23e6c0 | 2,372 | cpp | C++ | ecs/src/v2/model/ResizePostPaidServerOption.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | ecs/src/v2/model/ResizePostPaidServerOption.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | ecs/src/v2/model/ResizePostPaidServerOption.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/ecs/v2/model/ResizePostPaidServerOption.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ecs {
namespace V2 {
namespace Model {
ResizePostPaidServerOption::ResizePostPaidServerOption()
{
flavorRef_ = "";
flavorRefIsSet_ = false;
mode_ = "";
modeIsSet_ = false;
}
ResizePostPaidServerOption::~ResizePostPaidServerOption() = default;
void ResizePostPaidServerOption::validate()
{
}
web::json::value ResizePostPaidServerOption::toJson() const
{
web::json::value val = web::json::value::object();
if(flavorRefIsSet_) {
val[utility::conversions::to_string_t("flavorRef")] = ModelBase::toJson(flavorRef_);
}
if(modeIsSet_) {
val[utility::conversions::to_string_t("mode")] = ModelBase::toJson(mode_);
}
return val;
}
bool ResizePostPaidServerOption::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("flavorRef"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("flavorRef"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setFlavorRef(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("mode"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("mode"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setMode(refVal);
}
}
return ok;
}
std::string ResizePostPaidServerOption::getFlavorRef() const
{
return flavorRef_;
}
void ResizePostPaidServerOption::setFlavorRef(const std::string& value)
{
flavorRef_ = value;
flavorRefIsSet_ = true;
}
bool ResizePostPaidServerOption::flavorRefIsSet() const
{
return flavorRefIsSet_;
}
void ResizePostPaidServerOption::unsetflavorRef()
{
flavorRefIsSet_ = false;
}
std::string ResizePostPaidServerOption::getMode() const
{
return mode_;
}
void ResizePostPaidServerOption::setMode(const std::string& value)
{
mode_ = value;
modeIsSet_ = true;
}
bool ResizePostPaidServerOption::modeIsSet() const
{
return modeIsSet_;
}
void ResizePostPaidServerOption::unsetmode()
{
modeIsSet_ = false;
}
}
}
}
}
}
| 20.273504 | 100 | 0.671585 | yangzhaofeng |
566a4d89f934a44b604fcd743438594aaa2f4903 | 245 | inl | C++ | include/volt/gpu/resource.inl | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | include/volt/gpu/resource.inl | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | include/volt/gpu/resource.inl | voltengine/volt | fbefe2e0a8e461b6130ffe926870c4848bd6e7d1 | [
"MIT"
] | null | null | null | namespace volt::gpu {
template<typename T>
void resource::map(const std::function<void(T &)> &callback, access_modes access, size_t offset) {
map([&](void *data) {
callback(*reinterpret_cast<T *>(data));
}, access, sizeof(T), offset);
}
}
| 22.272727 | 98 | 0.677551 | voltengine |
566c3ff1d99ece1dcefd71776b50e495cede1b91 | 12,204 | hxx | C++ | main/unotools/inc/unotools/moduleoptions.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/unotools/inc/unotools/moduleoptions.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/unotools/inc/unotools/moduleoptions.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
#define INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#include "unotools/unotoolsdllapi.h"
#include <salhelper/singletonref.hxx>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <osl/mutex.hxx>
#include <unotools/options.hxx>
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define FEATUREFLAG_BASICIDE 0x00000020
#define FEATUREFLAG_MATH 0x00000100
#define FEATUREFLAG_CHART 0x00000200
#define FEATUREFLAG_CALC 0x00000800
#define FEATUREFLAG_DRAW 0x00001000
#define FEATUREFLAG_WRITER 0x00002000
#define FEATUREFLAG_IMPRESS 0x00008000
#define FEATUREFLAG_INSIGHT 0x00010000
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is necessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtModuleOptions_Impl;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about installation state of modules
@descr Use these class to get installation state of different office modules like writer, calc etc
Further you can ask for additional informations; e.g. name of standard template file, which
should be used by corresponding module; or short/long name of these module factory.
@implements -
@base -
@devstatus ready to use
@threadsafe yes
*//*-*************************************************************************************************************/
class UNOTOOLS_DLLPUBLIC SvtModuleOptions: public utl::detail::Options
{
//-------------------------------------------------------------------------------------------------------------
// public const declarations!
//-------------------------------------------------------------------------------------------------------------
public:
enum EModule
{
E_SWRITER = 0,
E_SCALC = 1,
E_SDRAW = 2,
E_SIMPRESS = 3,
E_SMATH = 4,
E_SCHART = 5,
E_SSTARTMODULE = 6,
E_SBASIC = 7,
E_SDATABASE = 8,
E_SWEB = 9,
E_SGLOBAL = 10
};
/*ATTENTION:
If you change these enum ... don't forget to change reading/writing and order of configuration values too!
See "SvtModuleOptions_Impl::impl_GetSetNames()" and his ctor for further informations.
*/
enum EFactory
{
E_UNKNOWN_FACTORY = -1,
E_WRITER = 0,
E_WRITERWEB = 1,
E_WRITERGLOBAL = 2,
E_CALC = 3,
E_DRAW = 4,
E_IMPRESS = 5,
E_MATH = 6,
E_CHART = 7,
E_STARTMODULE = 8,
E_DATABASE = 9,
E_BASIC = 10
};
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
SvtModuleOptions();
virtual ~SvtModuleOptions();
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
sal_Bool IsModuleInstalled ( EModule eModule ) const;
::rtl::OUString GetModuleName ( EModule eModule ) const;
::rtl::OUString GetModuleName ( EFactory eFactory ) const;
::rtl::OUString GetFactoryName ( EFactory eFactory ) const;
::rtl::OUString GetFactoryShortName ( EFactory eFactory ) const;
::rtl::OUString GetFactoryStandardTemplate( EFactory eFactory ) const;
::rtl::OUString GetFactoryWindowAttributes( EFactory eFactory ) const;
::rtl::OUString GetFactoryEmptyDocumentURL( EFactory eFactory ) const;
::rtl::OUString GetFactoryDefaultFilter ( EFactory eFactory ) const;
sal_Bool IsDefaultFilterReadonly ( EFactory eFactory ) const;
sal_Int32 GetFactoryIcon ( EFactory eFactory ) const;
static sal_Bool ClassifyFactoryByName ( const ::rtl::OUString& sName ,
EFactory& eFactory );
void SetFactoryStandardTemplate( EFactory eFactory ,
const ::rtl::OUString& sTemplate );
void SetFactoryWindowAttributes( EFactory eFactory ,
const ::rtl::OUString& sAttributes);
void SetFactoryDefaultFilter ( EFactory eFactory ,
const ::rtl::OUString& sFilter );
//_______________________________________
/** @short return the corresponding application ID for the given
document service name.
*/
static EFactory ClassifyFactoryByServiceName(const ::rtl::OUString& sName);
//_______________________________________
/** @short return the corresponding application ID for the given
short name.
*/
static EFactory ClassifyFactoryByShortName(const ::rtl::OUString& sName);
//_______________________________________
/** @short return the corresponding application ID for the given properties.
@descr Because this search base on filters currently (till we have a better solution)
a result is not guaranteed everytimes. May a filter does not exists for the specified
content (but a FrameLoader which is not bound to any application!) ... or
the given properties describe a stream (and we make no deep detection inside here!).
@attention The module BASIC can't be detected here. Because it does not
has an own URL schema.
@param sURL
the complete URL!
@param lMediaDescriptor
additional informations
@return A suitable enum value. See EFactory above.
*/
static EFactory ClassifyFactoryByURL(const ::rtl::OUString& sURL ,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lMediaDescriptor);
//_______________________________________
/** @short return the corresponding application ID for the given properties.
@descr Here we try to use the list of supported service names of the given model
to find out the right application module.
@attention The module BASIC can't be detected here. Because it does not
support any model/ctrl/view paradigm.
@param xModel
the document model
@return A suitable enum value. See EFactory above.
*/
static EFactory ClassifyFactoryByModel(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel);
::rtl::OUString GetDefaultModuleName();
//---------------------------------------------------------------------------------------------------------
// old interface ...
//---------------------------------------------------------------------------------------------------------
sal_Bool IsMath () const;
sal_Bool IsChart () const;
sal_Bool IsCalc () const;
sal_Bool IsDraw () const;
sal_Bool IsWriter () const;
sal_Bool IsImpress () const;
sal_Bool IsBasicIDE () const;
sal_Bool IsDataBase () const;
sal_uInt32 GetFeatures() const;
::com::sun::star::uno::Sequence < ::rtl::OUString > GetAllServiceNames();
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
UNOTOOLS_DLLPRIVATE static ::osl::Mutex& impl_GetOwnStaticMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double defined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtModuleOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtModuleOptions
#endif // #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
| 48.047244 | 144 | 0.518519 | Grosskopf |
566e94fbc34e559b0d13bc828d176a9d942fc6a0 | 2,440 | cpp | C++ | Src/Graphics/OpenGL_Desktop.cpp | Eae02/jamlib | 66193bc11fee3a8964f2af0aca6c20cdf56b3b4c | [
"Zlib"
] | null | null | null | Src/Graphics/OpenGL_Desktop.cpp | Eae02/jamlib | 66193bc11fee3a8964f2af0aca6c20cdf56b3b4c | [
"Zlib"
] | null | null | null | Src/Graphics/OpenGL_Desktop.cpp | Eae02/jamlib | 66193bc11fee3a8964f2af0aca6c20cdf56b3b4c | [
"Zlib"
] | null | null | null | #include "OpenGL.hpp"
#ifndef JM_USE_GLES
#include <iostream>
#include <string_view>
#include <SDL_video.h>
namespace jm::detail
{
bool hasModernGL;
float maxAnistropy;
static std::string glVendorName;
void OpenGLMessageCallback(GLenum, GLenum type, GLuint id, GLenum severity, GLsizei length,
const GLchar* message, const void*)
{
if (id == 1286)
return;
if (glVendorName == "Intel Open Source Technology Center")
{
if (id == 17 || id == 14) //Clearing integer framebuffer attachments.
return;
}
const char* severityString = "N";
if (severity == GL_DEBUG_SEVERITY_HIGH || type == GL_DEBUG_TYPE_ERROR)
{
severityString = "E";
}
else if (severity == GL_DEBUG_SEVERITY_LOW || severity == GL_DEBUG_SEVERITY_MEDIUM)
{
severityString = "W";
}
std::string_view messageView(message, static_cast<size_t>(length));
//Some vendors include a newline at the end of the message. This removes the newline if present.
if (messageView.back() == '\n')
{
messageView = messageView.substr(0, messageView.size() - 1);
}
std::cout << "GL[" << severityString << id << "]: " << messageView << std::endl;
if (type == GL_DEBUG_TYPE_ERROR)
std::abort();
}
static const char* RequiredExtensions[] =
{
"GL_ARB_texture_storage"
};
static const char* ModernExtensions[] =
{
"GL_ARB_direct_state_access",
"GL_ARB_buffer_storage"
};
bool InitializeOpenGL(bool debug)
{
if (gl3wInit())
{
std::cerr << "Error initializing OpenGL\n";
return false;
}
glVendorName = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
for (const char* ext : RequiredExtensions)
{
if (!SDL_GL_ExtensionSupported(ext))
{
std::cerr << "Required OpenGL extension not supported: '" << ext << "'.\n";
return false;
}
}
hasModernGL = true;
for (const char* ext : ModernExtensions)
{
if (!SDL_GL_ExtensionSupported(ext))
{
hasModernGL = false;
break;
}
}
if (SDL_GL_ExtensionSupported("GL_EXT_texture_filter_anisotropic"))
{
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &maxAnistropy);
}
if (debug && glDebugMessageCallback)
{
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(OpenGLMessageCallback, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE);
}
return true;
}
}
#endif
| 22.385321 | 107 | 0.672131 | Eae02 |
5670ea398c3074eec3f9b7f4ad7d41390ef5f111 | 2,775 | cpp | C++ | src/engine/TextureHandle.cpp | foxostro/arbarlith2 | 820ffc8c3efcb636eb2c639487815fb9aabdc82e | [
"BSD-3-Clause"
] | 1 | 2019-04-09T18:42:00.000Z | 2019-04-09T18:42:00.000Z | src/engine/TextureHandle.cpp | foxostro/arbarlith2 | 820ffc8c3efcb636eb2c639487815fb9aabdc82e | [
"BSD-3-Clause"
] | null | null | null | src/engine/TextureHandle.cpp | foxostro/arbarlith2 | 820ffc8c3efcb636eb2c639487815fb9aabdc82e | [
"BSD-3-Clause"
] | null | null | null | /*
Original Author: Andrew Fox
E-Mail: mailto:foxostro@gmail.com
Copyright (c) 2006-2007,2009 Game Creation Society
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 Game Creation Society 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 Game Creation Society ``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 Game Creation Society 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 "stdafx.h"
#include "gl.h"
#include "Effect.h"
#include "TextureHandle.h"
namespace Engine {
TextureHandle::TextureHandle(void)
{
fileName="(nill)";
width=height=0;
alpha=false;
id=0;
}
TextureHandle::TextureHandle(const string &fileName, int width, int height, bool alpha, GLuint id)
{
this->fileName = fileName;
this->width = width;
this->height = height;
this->alpha = alpha;
this->id = id;
}
void TextureHandle::release(void)
{
glDeleteTextures(1, &id);
id=0;
}
void TextureHandle::reaquire(void)
{
release();
Image img(fileName);
int depth = img.getDepth();
// get a new id
glGenTextures(1, &id);
// and bind it as the present texture
glBindTexture(GL_TEXTURE_2D, id);
// Set the texture filtering according to global performance settings
Effect::setTextureFilters();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// now build mipmaps from the texture data
gluBuild2DMipmaps(GL_TEXTURE_2D,
depth,
img.getWidth(),
img.getHeight(),
depth==4 ? GL_RGBA : GL_RGB,
GL_UNSIGNED_BYTE,
img.getImage());
}
}; // namespace
| 29.521277 | 98 | 0.751712 | foxostro |
56747c5c47b952021c2d327e8348876d709436fa | 103 | cpp | C++ | src/core/BaseException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | null | null | null | src/core/BaseException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | 26 | 2017-12-13T12:45:32.000Z | 2018-02-06T11:08:04.000Z | src/core/BaseException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | null | null | null | #include "BaseException.h"
BaseException::BaseException(const char *message) :
_msg(message)
{
}
| 12.875 | 51 | 0.718447 | Neomer |
56751572e61863567d4db6c72a9bc76d54be5050 | 9,240 | cpp | C++ | Assignments/Curl/src/CurlAppController.cpp | prince-chrismc/Data-Communication | 04df3591ac726c1f330788b6b24cdb15309b5461 | [
"MIT"
] | null | null | null | Assignments/Curl/src/CurlAppController.cpp | prince-chrismc/Data-Communication | 04df3591ac726c1f330788b6b24cdb15309b5461 | [
"MIT"
] | null | null | null | Assignments/Curl/src/CurlAppController.cpp | prince-chrismc/Data-Communication | 04df3591ac726c1f330788b6b24cdb15309b5461 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2018 Chris McArthur, prince.chrismc(at)gmail(dot)com
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 "CurlAppController.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include "ActiveSocket.h"
CurlAppController::CurlAppController( int argc, char ** argv )
: m_oCliParser( argc, argv )
, m_eCommand( Http::RequestMethod::Invalid )
, m_bVerbose( false )
{
readCommandLineArgs();
}
void CurlAppController::readCommandLineArgs()
{
auto itor = m_oCliParser.cbegin();
moreArgsToRead( itor, MISSING_GET_OR_POST );
if( *itor == "help" ) printUsageGivenArgs();
else if( *itor == "get" ) m_eCommand = Http::RequestMethod::Get;
else if( *itor == "post" ) m_eCommand = Http::RequestMethod::Post;
else { printUsageGivenArgs(); throw std::invalid_argument( MISSING_GET_OR_POST.data() ); }
switch( m_eCommand )
{
case Http::RequestMethod::Get:
// Continue parsing GET args
parseGetOptions( ++itor );
break;
case Http::RequestMethod::Post:
// Continue parsing POST args
parsePostOptions( ++itor );
break;
default:
break;
}
}
void CurlAppController::Run()
{
switch( m_eCommand )
{
case Http::RequestMethod::Get:
case Http::RequestMethod::Post:
break;
default:
throw std::runtime_error( "If you see this please don't look for the developer to report a bug =)" );
}
if( m_bVerbose ) std::cout << "Starting..." << std::endl;
CActiveSocket oClient;
bool retval = true;
if( retval )
{
if( m_bVerbose ) std::cout << "Connectioning to " << m_oHref.m_sHostName << " on port " << 80 << "..." << std::endl;
retval = oClient.Open( m_oHref.m_sHostName.c_str(), m_oHref.m_nPortNumber );
if( !retval && m_bVerbose ) std::cout << "Connection could not be established!" << std::endl;
}
if( retval )
{
if( m_bVerbose ) std::cout << "Building Request..." << std::endl;
HttpRequest oReq( m_eCommand, m_oHref.m_sUri, Http::Version::v10, m_oHref.m_sHostName + std::to_string( m_oHref.m_nPortNumber ) );
for( auto& oFeildNameAndValue : m_oExtraHeaders )
{
oReq.SetMessageHeader( oFeildNameAndValue.first, oFeildNameAndValue.second );
}
oReq.AppendMessageBody( m_sBody );
std::string sRawRequest = oReq.GetWireFormat();
if( m_bVerbose ) std::cout << "Raw request:" << std::endl << std::endl << sRawRequest << std::endl << std::endl << "Sending...";
retval = oClient.Send( (uint8_t*)sRawRequest.c_str(), sRawRequest.size() );
}
HttpResponseParser oResponseParserParser;
if( retval )
{
if( m_bVerbose ) std::cout << "Receiving..." << std::endl;
int32_t bytes_rcvd = -1;
do
{
bytes_rcvd = oClient.Receive( 1024 );
if( bytes_rcvd <= 0 ) break;
if( m_bVerbose ) std::cout << "Appending " << bytes_rcvd << " bytes of data..." << std::endl;
} while( !oResponseParserParser.AppendResponseData( oClient.GetData() ) );
if( m_bVerbose ) std::cout << "Transmission Completed..." << std::endl;
}
if( retval )
{
HttpResponse oRes = oResponseParserParser.GetHttpResponse();
if( m_bVerbose ) std::cout << "Closing..." << std::endl;
oClient.Close();
if( m_bVerbose ) std::cout << std::endl << std::endl << "Here's the response!" << std::endl << std::endl;
std::cout << oRes.GetWireFormat();
std::cout.flush();
}
}
//
// Printing
//
void CurlAppController::printGeneralUsage()
{
std::cout << "General Usage\r\n httpc help\r\nhttpc is a curl - like application but supports HTTP protocol only.\r\nUsage:\r\n httpc command [ arguments ]\r\nThe commands are:\r\n";
std::cout << " get executes a HTTP GET request and prints the response.\r\n post executes a HTTP POST request and prints the response.\r\n";
std::cout << "Other arguments are:\r\n help prints extremely helpful screen.\r\nUse 'httpc help [ command ]' for more information about a command." << std::endl;
}
void CurlAppController::printGetUsage()
{
std::cout << "Get Usage\r\n httpc help get\r\nGet executes a HTTP GET request for a given URL.\r\nUsage:\r\n httpc get [ -v ] [ -h key:value ] URL\r\n";
std::cout << "-v Prints the detail of the response such as protocol, status, and headers.\r\n";
std::cout << "-h key:value Associates headers to the HTTP Request with the format 'key:value'. Can specify many in a row.\r\n" << std::endl;
}
void CurlAppController::printPostUsage()
{
std::cout << "Post Usage\r\nhttpc help post\r\nPost executes a HTTP POST request for a given URL with inline data or from file.\r\nUsage:\r\n";
std::cout << " httpc post [ -v ] [ -h key:value ] [ -d inline-data | -f file ] URL\r\n";
std::cout << "-v Prints the detail of the response such as protocol, status,and headers.\r\n";
std::cout << "-h key:value Associates headers to HTTP Request with the format 'key:value'. Can specify many in a row.\r\n";
std::cout << "-d string Associates an inline data to the body HTTP POST request.\r\n";
std::cout << "-f file Associates the content of a file to the body HTTP POST request.\r\n";
std::cout << "Either [ -d ] or [ -f ] can be used but not both." << std::endl;
}
void CurlAppController::printUsageGivenArgs() const
{
switch( m_eCommand )
{
case Http::RequestMethod::Get: printGetUsage(); break;
case Http::RequestMethod::Post: printPostUsage(); break;
default: printGeneralUsage(); break;
}
}
//
// Prasing
//
void CurlAppController::parseGetOptions( CommandLineParser::ArgIterator itor )
{
parseVerboseOption( itor );
parseHeaderOption( itor );
parseUrlOption( itor );
}
void CurlAppController::parsePostOptions( CommandLineParser::ArgIterator itor )
{
parseVerboseOption( itor );
parseHeaderOption( itor );
moreArgsToRead( itor, MISSING_URL );
if( *itor == "-d" )
{
moreArgsToRead( ++itor, MISSING_URL );
m_sBody = *itor;
++itor;
}
else if( *itor == "-f" )
{
moreArgsToRead( ++itor, MISSING_URL );
std::ifstream fileReader( *itor, std::ios::in | std::ios::binary | std::ios::ate );
if( !fileReader ) { printPostUsage(); throw std::invalid_argument( "Unable to use file specified with -f switch" ); }
const size_t size = fileReader.tellg();
m_sBody.resize( size + 1, '\0' ); // construct buffer
fileReader.seekg( 0 ); // rewind
fileReader.read( m_sBody.data(), size );
++itor;
}
parseUrlOption( itor );
}
void CurlAppController::parseVerboseOption( CommandLineParser::ArgIterator& itor )
{
moreArgsToRead( itor, MISSING_URL );
if( *itor == "-v" )
{
m_bVerbose = true;
++itor;
}
}
void CurlAppController::parseHeaderOption( CommandLineParser::ArgIterator& itor )
{
moreArgsToRead( itor, MISSING_URL );
while( *itor == "-h" )
{
std::string sHeardOptAndValue( *( ++itor ) );
const size_t iSeperatorIndex = sHeardOptAndValue.find( ':' );
if( iSeperatorIndex == std::string::npos ) { printUsageGivenArgs(); throw std::invalid_argument( "Poorly formatted key:value for -h switch" ); }
m_oExtraHeaders.emplace_back( sHeardOptAndValue.substr( 0, iSeperatorIndex ), sHeardOptAndValue.substr( iSeperatorIndex + 1 ) );
++itor;
moreArgsToRead( itor, MISSING_URL );
}
}
void CurlAppController::parseUrlOption( CommandLineParser::ArgIterator & itor )
{
moreArgsToRead( itor, MISSING_URL );
try
{
m_oHref = HrefParser().Parse( *itor ).GetHref();
}
catch( const HrefParser::ParseError& e )
{
printUsageGivenArgs();
throw e;
}
}
void CurlAppController::moreArgsToRead( CommandLineParser::ArgIterator itor, std::string_view errMsg ) const
{
if( itor == m_oCliParser.cend() )
{
printUsageGivenArgs();
throw std::invalid_argument( errMsg.data() );
}
}
| 34.477612 | 190 | 0.643615 | prince-chrismc |
567dc8c02e6d9572d168cb4090d34b542068725c | 2,619 | cc | C++ | zetasql/testing/test_catalog.cc | wbsouza/zetasql-formatter | 3db113adee8d4fcb27dc978123dc75079442bf69 | [
"Apache-2.0"
] | 1,779 | 2019-04-23T19:41:49.000Z | 2022-03-31T18:53:18.000Z | zetasql/testing/test_catalog.cc | wbsouza/zetasql-formatter | 3db113adee8d4fcb27dc978123dc75079442bf69 | [
"Apache-2.0"
] | 94 | 2019-05-22T00:30:05.000Z | 2022-03-31T06:26:09.000Z | zetasql/testing/test_catalog.cc | wbsouza/zetasql-formatter | 3db113adee8d4fcb27dc978123dc75079442bf69 | [
"Apache-2.0"
] | 153 | 2019-04-23T22:45:41.000Z | 2022-02-18T05:44:10.000Z | //
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "zetasql/testing/test_catalog.h"
#include "absl/status/status.h"
#include "zetasql/base/case.h"
#include "zetasql/base/map_util.h"
#include "zetasql/base/status_macros.h"
namespace zetasql {
TestCatalog::~TestCatalog() {
}
absl::Status TestCatalog::GetErrorForName(const std::string& name) const {
const absl::Status* error =
zetasql_base::FindOrNull(errors_, absl::AsciiStrToLower(name));
if (error != nullptr) {
return *error;
} else {
return absl::OkStatus();
}
}
absl::Status TestCatalog::GetTable(const std::string& name, const Table** table,
const FindOptions& options) {
ZETASQL_RETURN_IF_ERROR(GetErrorForName(name));
return SimpleCatalog::GetTable(name, table, options);
}
absl::Status TestCatalog::GetFunction(const std::string& name,
const Function** function,
const FindOptions& options) {
ZETASQL_RETURN_IF_ERROR(GetErrorForName(name));
return SimpleCatalog::GetFunction(name, function, options);
}
absl::Status TestCatalog::GetType(const std::string& name, const Type** type,
const FindOptions& options) {
ZETASQL_RETURN_IF_ERROR(GetErrorForName(name));
return SimpleCatalog::GetType(name, type, options);
}
absl::Status TestCatalog::GetCatalog(const std::string& name, Catalog** catalog,
const FindOptions& options) {
ZETASQL_RETURN_IF_ERROR(GetErrorForName(name));
return SimpleCatalog::GetCatalog(name, catalog, options);
}
void TestCatalog::AddError(const std::string& name, const absl::Status& error) {
zetasql_base::InsertOrDie(&errors_, absl::AsciiStrToLower(name), error);
}
TestFunction::TestFunction(
const std::string& function_name, Function::Mode mode,
const std::vector<FunctionSignature>& function_signatures)
: Function(function_name, "TestFunction", mode, function_signatures) {}
TestFunction::~TestFunction() {
}
} // namespace zetasql
| 34.012987 | 80 | 0.695304 | wbsouza |
5680aaa33ec13e91f86761d8d57d331ad60694ca | 1,643 | cc | C++ | net/tools/quic/quic_simple_server_socket.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 | net/tools/quic/quic_simple_server_socket.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 250 | 2018-02-02T23:16:57.000Z | 2022-03-21T06:09:53.000Z | net/tools/quic/quic_simple_server_socket.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) 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/tools/quic/quic_simple_server_socket.h"
#include "net/base/net_errors.h"
#include "net/log/net_log_source.h"
#include "net/third_party/quiche/src/quic/core/quic_constants.h"
namespace net {
std::unique_ptr<UDPServerSocket> CreateQuicSimpleServerSocket(
const IPEndPoint& address,
IPEndPoint* server_address) {
auto socket =
std::make_unique<UDPServerSocket>(/*net_log=*/nullptr, NetLogSource());
socket->AllowAddressReuse();
int rc = socket->Listen(address);
if (rc < 0) {
LOG(ERROR) << "Listen() failed: " << ErrorToString(rc);
return nullptr;
}
// These send and receive buffer sizes are sized for a single connection,
// because the default usage of QuicSimpleServer is as a test server with
// one or two clients. Adjust higher for use with many clients.
rc = socket->SetReceiveBufferSize(
static_cast<int32_t>(quic::kDefaultSocketReceiveBuffer));
if (rc < 0) {
LOG(ERROR) << "SetReceiveBufferSize() failed: " << ErrorToString(rc);
return nullptr;
}
rc = socket->SetSendBufferSize(20 * quic::kMaxOutgoingPacketSize);
if (rc < 0) {
LOG(ERROR) << "SetSendBufferSize() failed: " << ErrorToString(rc);
return nullptr;
}
rc = socket->GetLocalAddress(server_address);
if (rc < 0) {
LOG(ERROR) << "GetLocalAddress() failed: " << ErrorToString(rc);
return nullptr;
}
VLOG(1) << "Listening on " << server_address->ToString();
return socket;
}
} // namespace net
| 30.425926 | 77 | 0.695679 | zealoussnow |
5683264e2c7c942ce2ef5fe75106d2d2e92ca956 | 486 | cpp | C++ | tests/realapplications/libHX_overflow/libHX-3.4/src/tx-compile.cpp | GYJQTYL2/DoubleTake | cdcd0200bb364b5343beae72756420e6c3954a6f | [
"MIT"
] | 19 | 2015-09-17T18:10:14.000Z | 2021-08-16T11:26:33.000Z | tests/realapplications/libHX_overflow/libHX-3.4/src/tx-compile.cpp | GYJQTYL2/DoubleTake | cdcd0200bb364b5343beae72756420e6c3954a6f | [
"MIT"
] | 17 | 2015-04-27T14:33:42.000Z | 2016-05-23T20:15:48.000Z | tests/realapplications/libHX_overflow/libHX-3.4/src/tx-compile.cpp | plasma-umass/DoubleTake | cdcd0200bb364b5343beae72756420e6c3954a6f | [
"MIT"
] | 13 | 2015-07-29T15:15:00.000Z | 2021-01-15T04:53:21.000Z | /* This file is for testing the cumulative include */
#ifndef __cplusplus
# include <stdlib.h>
#else
# include <cstdlib>
#endif
#include <libHX.h>
#define ZZ 64
int main(void)
{
unsigned long bitmap[HXbitmap_size(unsigned long, 64)];
if (HX_init() <= 0)
abort();
printf("sizeof bitmap: %zu, array_size: %zu\n",
sizeof(bitmap), ARRAY_SIZE(bitmap));
HXbitmap_set(bitmap, 0);
printf(HX_STRINGIFY(1234+2 +2) "," HX_STRINGIFY(ZZ) "\n");
HX_exit();
return EXIT_SUCCESS;
}
| 20.25 | 59 | 0.683128 | GYJQTYL2 |
568bb161de43b5b938b17aa4a4ffaf46f4661dbc | 11,031 | cpp | C++ | aegisub/src/search_replace_engine.cpp | rcombs/Aegisub | 58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50 | [
"ISC"
] | 1 | 2018-02-12T02:44:57.000Z | 2018-02-12T02:44:57.000Z | aegisub/src/search_replace_engine.cpp | rcombs/Aegisub | 58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50 | [
"ISC"
] | null | null | null | aegisub/src/search_replace_engine.cpp | rcombs/Aegisub | 58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50 | [
"ISC"
] | 2 | 2018-02-12T03:46:24.000Z | 2018-02-12T14:36:07.000Z | // Copyright (c) 2013, Thomas Goyne <plorkyeran@aegisub.org>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// Aegisub Project http://www.aegisub.org/
#include "config.h"
#include "search_replace_engine.h"
#include "ass_dialogue.h"
#include "ass_file.h"
#include "include/aegisub/context.h"
#include "selection_controller.h"
#include "text_selection_controller.h"
#include <libaegisub/of_type_adaptor.h>
#include <libaegisub/util.h>
#include <boost/locale.hpp>
#include <wx/msgdlg.h>
static const size_t bad_pos = -1;
namespace {
auto get_dialogue_field(SearchReplaceSettings::Field field) -> decltype(&AssDialogue::Text) {
switch (field) {
case SearchReplaceSettings::Field::TEXT: return &AssDialogue::Text;
case SearchReplaceSettings::Field::STYLE: return &AssDialogue::Style;
case SearchReplaceSettings::Field::ACTOR: return &AssDialogue::Actor;
case SearchReplaceSettings::Field::EFFECT: return &AssDialogue::Effect;
}
throw agi::InternalError("Bad field for search", nullptr);
}
std::string const& get_normalized(const AssDialogue *diag, decltype(&AssDialogue::Text) field) {
auto& value = const_cast<AssDialogue*>(diag)->*field;
auto normalized = boost::locale::normalize(value.get());
if (normalized != value)
value = normalized;
return value.get();
}
typedef std::function<MatchState (const AssDialogue*, size_t)> matcher;
class noop_accessor {
boost::flyweight<std::string> AssDialogue::*field;
size_t start;
public:
noop_accessor(SearchReplaceSettings::Field f) : field(get_dialogue_field(f)), start(0) { }
std::string get(const AssDialogue *d, size_t s) {
start = s;
return get_normalized(d, field).substr(s);
}
MatchState make_match_state(size_t s, size_t e, boost::u32regex *r = nullptr) {
return MatchState(s + start, e + start, r);
}
};
class skip_tags_accessor {
boost::flyweight<std::string> AssDialogue::*field;
std::vector<std::pair<size_t, size_t>> blocks;
size_t start;
void parse_str(std::string const& str) {
blocks.clear();
size_t ovr_start = bad_pos;
size_t i = 0;
for (auto const& c : str) {
if (c == '{' && ovr_start == bad_pos)
ovr_start = i;
else if (c == '}' && ovr_start != bad_pos) {
blocks.emplace_back(ovr_start, i);
ovr_start = bad_pos;
}
++i;
}
}
public:
skip_tags_accessor(SearchReplaceSettings::Field f) : field(get_dialogue_field(f)), start(0) { }
std::string get(const AssDialogue *d, size_t s) {
auto const& str = get_normalized(d, field);
parse_str(str);
std::string out;
size_t last = s;
for (auto const& block : blocks) {
if (block.second < s) continue;
if (block.first > last)
out.append(str.begin() + last, str.begin() + block.first);
last = block.second + 1;
}
if (last < str.size())
out.append(str.begin() + last, str.end());
start = s;
return out;
}
MatchState make_match_state(size_t s, size_t e, boost::u32regex *r = nullptr) {
s += start;
e += start;
// Shift the start and end of the match to be relative to the unstripped
// match
for (auto const& block : blocks) {
// Any blocks before start are irrelevant as they're included in `start`
if (block.second < s) continue;
// Skip over blocks at the very beginning of the match
// < should only happen if the cursor was within an override block
// when the user started a search
if (block.first <= s) {
size_t len = block.second - std::max(block.first, s) + 1;
s += len;
e += len;
continue;
}
assert(block.first > s);
// Blocks after the match are irrelevant
if (block.first >= e) break;
// Extend the match to include blocks within the match
// Note that blocks cannot be partially within the match
e += block.second - block.first + 1;
}
return MatchState(s, e, r);
}
};
template<typename Accessor>
matcher get_matcher(SearchReplaceSettings const& settings, Accessor&& a) {
if (settings.use_regex) {
int flags = boost::u32regex::perl;
if (!settings.match_case)
flags |= boost::u32regex::icase;
auto regex = boost::make_u32regex(settings.find, flags);
return [=](const AssDialogue *diag, size_t start) mutable -> MatchState {
boost::smatch result;
auto const& str = a.get(diag, start);
if (!u32regex_search(str, result, regex, start > 0 ? boost::match_not_bol : boost::match_default))
return MatchState();
return a.make_match_state(result.position(), result.position() + result.length(), ®ex);
};
}
bool full_match_only = settings.exact_match;
bool match_case = settings.match_case;
std::string look_for = settings.find;
if (!settings.match_case)
look_for = boost::locale::fold_case(look_for);
return [=](const AssDialogue *diag, size_t start) mutable -> MatchState {
const auto str = a.get(diag, start);
if (full_match_only && str.size() != look_for.size())
return MatchState();
if (match_case) {
const auto pos = str.find(look_for);
return pos == std::string::npos ? MatchState() : a.make_match_state(pos, pos + look_for.size());
}
const auto pos = agi::util::ifind(str, look_for);
return pos.first == bad_pos ? MatchState() : a.make_match_state(pos.first, pos.second);
};
}
template<typename Iterator, typename Container>
Iterator circular_next(Iterator it, Container& c) {
++it;
if (it == c.end())
it = c.begin();
return it;
}
}
std::function<MatchState (const AssDialogue*, size_t)> SearchReplaceEngine::GetMatcher(SearchReplaceSettings const& settings) {
if (settings.skip_tags)
return get_matcher(settings, skip_tags_accessor(settings.field));
return get_matcher(settings, noop_accessor(settings.field));
}
SearchReplaceEngine::SearchReplaceEngine(agi::Context *c)
: context(c)
, initialized(false)
{
}
void SearchReplaceEngine::Replace(AssDialogue *diag, MatchState &ms) {
auto& diag_field = diag->*get_dialogue_field(settings.field);
auto text = diag_field.get();
std::string replacement = settings.replace_with;
if (ms.re) {
auto to_replace = text.substr(ms.start, ms.end - ms.start);
replacement = u32regex_replace(to_replace, *ms.re, replacement, boost::format_first_only);
}
diag_field = text.substr(0, ms.start) + replacement + text.substr(ms.end);
ms.end = ms.start + replacement.size();
}
bool SearchReplaceEngine::FindReplace(bool replace) {
if (!initialized)
return false;
auto matches = GetMatcher(settings);
AssDialogue *line = context->selectionController->GetActiveLine();
auto it = context->ass->Line.iterator_to(*line);
size_t pos = 0;
MatchState replace_ms;
if (replace) {
if (settings.field == SearchReplaceSettings::Field::TEXT)
pos = context->textSelectionController->GetSelectionStart();
if ((replace_ms = matches(line, pos))) {
size_t end = bad_pos;
if (settings.field == SearchReplaceSettings::Field::TEXT)
end = context->textSelectionController->GetSelectionEnd();
if (end == bad_pos || (pos == replace_ms.start && end == replace_ms.end)) {
Replace(line, replace_ms);
pos = replace_ms.end;
context->ass->Commit(_("replace"), AssFile::COMMIT_DIAG_TEXT);
}
else {
// The current line matches, but it wasn't already selected,
// so the match hasn't been "found" and displayed to the user
// yet, so do that rather than replacing
context->textSelectionController->SetSelection(replace_ms.start, replace_ms.end);
return true;
}
}
}
// Search from the end of the selection to avoid endless matching the same thing
else if (settings.field == SearchReplaceSettings::Field::TEXT)
pos = context->textSelectionController->GetSelectionEnd();
// For non-text fields we just look for matching lines rather than each
// match within the line, so move to the next line
else if (settings.field != SearchReplaceSettings::Field::TEXT)
it = circular_next(it, context->ass->Line);
auto const& sel = context->selectionController->GetSelectedSet();
bool selection_only = sel.size() > 1 && settings.limit_to == SearchReplaceSettings::Limit::SELECTED;
do {
AssDialogue *diag = dynamic_cast<AssDialogue*>(&*it);
if (!diag) continue;
if (selection_only && !sel.count(diag)) continue;
if (settings.ignore_comments && diag->Comment) continue;
if (MatchState ms = matches(diag, pos)) {
if (selection_only)
// We're cycling through the selection, so don't muck with it
context->selectionController->SetActiveLine(diag);
else
context->selectionController->SetSelectionAndActive({ diag }, diag);
if (settings.field == SearchReplaceSettings::Field::TEXT)
context->textSelectionController->SetSelection(ms.start, ms.end);
return true;
}
} while (pos = 0, &*(it = circular_next(it, context->ass->Line)) != line);
// Replaced something and didn't find another match, so select the newly
// inserted text
if (replace_ms && settings.field == SearchReplaceSettings::Field::TEXT)
context->textSelectionController->SetSelection(replace_ms.start, replace_ms.end);
return true;
}
bool SearchReplaceEngine::ReplaceAll() {
if (!initialized)
return false;
size_t count = 0;
auto matches = GetMatcher(settings);
SubtitleSelection const& sel = context->selectionController->GetSelectedSet();
bool selection_only = settings.limit_to == SearchReplaceSettings::Limit::SELECTED;
for (auto diag : context->ass->Line | agi::of_type<AssDialogue>()) {
if (selection_only && !sel.count(diag)) continue;
if (settings.ignore_comments && diag->Comment) continue;
if (settings.use_regex) {
if (MatchState ms = matches(diag, 0)) {
auto& diag_field = diag->*get_dialogue_field(settings.field);
std::string const& text = diag_field.get();
count += distance(
boost::u32regex_iterator<std::string::const_iterator>(begin(text), end(text), *ms.re),
boost::u32regex_iterator<std::string::const_iterator>());
diag_field = u32regex_replace(text, *ms.re, settings.replace_with);
}
continue;
}
size_t pos = 0;
while (MatchState ms = matches(diag, pos)) {
++count;
Replace(diag, ms);
pos = ms.end;
}
}
if (count > 0) {
context->ass->Commit(_("replace"), AssFile::COMMIT_DIAG_TEXT);
wxMessageBox(wxString::Format(_("%i matches were replaced."), (int)count));
}
else {
wxMessageBox(_("No matches found."));
}
return true;
}
void SearchReplaceEngine::Configure(SearchReplaceSettings const& new_settings) {
settings = new_settings;
initialized = true;
}
| 31.60745 | 127 | 0.707279 | rcombs |
568dcaf91f6b658f3ca117f73325be96eb025ab7 | 777 | cpp | C++ | old-questions/2070-Chaitra/q3.cpp | B33pl0p/ioe-oop | 87162561e0ced7e7e9cc7c7a8354d535de16e1f5 | [
"MIT"
] | 4 | 2021-02-19T12:19:06.000Z | 2022-02-11T14:15:49.000Z | old-questions/2070-Chaitra/q3.cpp | B33pl0p/ioe-oop | 87162561e0ced7e7e9cc7c7a8354d535de16e1f5 | [
"MIT"
] | null | null | null | old-questions/2070-Chaitra/q3.cpp | B33pl0p/ioe-oop | 87162561e0ced7e7e9cc7c7a8354d535de16e1f5 | [
"MIT"
] | 12 | 2018-01-29T15:37:51.000Z | 2022-02-10T06:45:03.000Z | // Write a C++ program to join two strings using dynamics constructor concept
#include <iostream>
#include <string.h>
using namespace std;
class Strings {
char *str;
public:
Strings() {}
Strings(char *s) {
int length = strlen(s);
str = new char[length];
strcpy(str,s);
}
Strings join(Strings s) {
Strings temp;
int length = strlen(str) + strlen(s.str);
temp.str = new char[length];
strcpy(temp.str,str);
strcat(temp.str,s.str);
return temp;
}
void display() {
cout << str;
}
};
int main() {
Strings s1("Amit"),s2("Chaudhary"),s3;
s3 = s1.join(s2);
s3.display();
return 0;
}
| 22.2 | 77 | 0.503218 | B33pl0p |
5693a6b899434cd6f4a9b6d612f5815788b3aee2 | 558 | cpp | C++ | CLearn/DiscarnateLayer.cpp | JamesGlare/Neural-Net-LabView-DLL | d912e0bfd0231d22bcd27ae6a71ebfcb23129aba | [
"MIT"
] | 12 | 2018-07-23T17:07:29.000Z | 2021-04-26T01:46:48.000Z | CLearn/DiscarnateLayer.cpp | JamesGlare/Neural-Net-LabView-DLL | d912e0bfd0231d22bcd27ae6a71ebfcb23129aba | [
"MIT"
] | null | null | null | CLearn/DiscarnateLayer.cpp | JamesGlare/Neural-Net-LabView-DLL | d912e0bfd0231d22bcd27ae6a71ebfcb23129aba | [
"MIT"
] | 9 | 2019-05-06T13:19:39.000Z | 2021-03-23T01:10:25.000Z | #include "stdafx.h"
#include "DiscarnateLayer.h"
DiscarnateLayer::DiscarnateLayer(size_t _NOUT, size_t _NIN) : CNetLayer(_NOUT, _NIN) {};
DiscarnateLayer::DiscarnateLayer(size_t _NOUT, size_t _NIN, actfunc_t type) : CNetLayer(_NOUT, _NIN, type) {};
DiscarnateLayer::DiscarnateLayer(size_t _NOUT, actfunc_t type, CNetLayer& lower) : CNetLayer(_NOUT, type, lower) {};
void DiscarnateLayer::applyUpdate(const learnPars& pars, MAT& input, bool recursive) {
if (getHierachy() != hierarchy_t::output && recursive) {
above->applyUpdate(pars, input, true);
}
} | 46.5 | 116 | 0.752688 | JamesGlare |
5695d46f99c3f8c225d2745b02ecd287bbc5d6a8 | 7,409 | cpp | C++ | Refureku/Library/Tests/ArchetypeTests.cpp | Angelysse/Refureku | 1f01107c94cd81998068ce3fde02bb21c180166b | [
"MIT"
] | null | null | null | Refureku/Library/Tests/ArchetypeTests.cpp | Angelysse/Refureku | 1f01107c94cd81998068ce3fde02bb21c180166b | [
"MIT"
] | null | null | null | Refureku/Library/Tests/ArchetypeTests.cpp | Angelysse/Refureku | 1f01107c94cd81998068ce3fde02bb21c180166b | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <Refureku/Refureku.h>
#include "TestStruct.h"
#include "TestClass.h"
#include "TestClass2.h"
#include "TestEnum.h"
#include "TestNamespace.h"
#include "TypeTemplateClassTemplate.h"
//=========================================================
//=========== Archetype::getAccessSpecifier ===============
//=========================================================
TEST(Rfk_Archetype_getAccessSpecifier, FundamentalArchetypes)
{
EXPECT_EQ(rfk::getArchetype<void>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
EXPECT_EQ(rfk::getArchetype<int>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
EXPECT_EQ(rfk::getArchetype<char>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
EXPECT_EQ(rfk::getArchetype<long long>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
}
TEST(Rfk_Archetype_getAccessSpecifier, NonNestedStructClass)
{
EXPECT_EQ(rfk::getArchetype<TestClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
EXPECT_EQ(rfk::getArchetype<test_namespace::TestNamespaceNestedClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
}
TEST(Rfk_Archetype_getAccessSpecifier, PublicNestedStructClass)
{
EXPECT_EQ(rfk::getArchetype<TestStruct::NestedClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public);
EXPECT_EQ(rfk::getArchetype<TestStruct::NestedStruct>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public);
}
TEST(Rfk_Archetype_getAccessSpecifier, ProtectedNestedStructClass)
{
EXPECT_EQ(TestClass::staticGetArchetype().getNestedClassByName("NestedClass")->getAccessSpecifier(), rfk::EAccessSpecifier::Protected);
EXPECT_EQ(TestClass::staticGetArchetype().getNestedClassByName("NestedClass", rfk::EAccessSpecifier::Protected)->getAccessSpecifier(), rfk::EAccessSpecifier::Protected);
}
TEST(Rfk_Archetype_getAccessSpecifier, PrivateNestedStructClass)
{
EXPECT_EQ(TestClass::staticGetArchetype().getNestedStructByName("NestedStruct")->getAccessSpecifier(), rfk::EAccessSpecifier::Private);
EXPECT_EQ(TestClass::staticGetArchetype().getNestedStructByName("NestedStruct", rfk::EAccessSpecifier::Private)->getAccessSpecifier(), rfk::EAccessSpecifier::Private);
}
TEST(Rfk_Archetype_getAccessSpecifier, NonNestedClassTemplate)
{
EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
}
TEST(Rfk_Archetype_getAccessSpecifier, NamespaceNestedClassTemplate)
{
EXPECT_EQ(rfk::getArchetype<template_namespace::ClassTemplateInNamespace>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
}
TEST(Rfk_Archetype_getAccessSpecifier, ClassNestedClassTemplate)
{
EXPECT_EQ(rfk::getArchetype<ClassWithNestedClassTemplate::PublicClassTemplateInClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public);
}
TEST(Rfk_Archetype_getAccessSpecifier, NonNestedClassTemplateInstantiation)
{
EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate<int>>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
}
TEST(Rfk_Archetype_getAccessSpecifier, NonNestedEnum)
{
EXPECT_EQ(rfk::getEnum<TestEnum>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
EXPECT_EQ(rfk::getEnum<test_namespace::TestNamespaceNestedEnum>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined);
}
TEST(Rfk_Archetype_getAccessSpecifier, PublicNestedEnum)
{
EXPECT_EQ(rfk::getEnum<TestClass::NestedEnum>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public);
}
TEST(Rfk_Archetype_getAccessSpecifier, ProtectedNestedEnum)
{
EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("ProtectedNestedEnum")->getAccessSpecifier(), rfk::EAccessSpecifier::Protected);
EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("ProtectedNestedEnum", rfk::EAccessSpecifier::Protected)->getAccessSpecifier(), rfk::EAccessSpecifier::Protected);
}
TEST(Rfk_Archetype_getAccessSpecifier, PrivateNestedEnum)
{
EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("PrivateNestedEnum")->getAccessSpecifier(), rfk::EAccessSpecifier::Private);
EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("PrivateNestedEnum", rfk::EAccessSpecifier::Private)->getAccessSpecifier(), rfk::EAccessSpecifier::Private);
}
//=========================================================
//============== Archetype::getMemorySize =================
//=========================================================
TEST(Rfk_Archetype_getMemorySize, FundamentalType)
{
EXPECT_EQ(rfk::getArchetype<void>()->getMemorySize(), 0u);
EXPECT_EQ(rfk::getArchetype<std::nullptr_t>()->getMemorySize(), sizeof(std::nullptr_t));
EXPECT_EQ(rfk::getArchetype<bool>()->getMemorySize(), sizeof(bool));
EXPECT_EQ(rfk::getArchetype<char>()->getMemorySize(), sizeof(char));
EXPECT_EQ(rfk::getArchetype<signed char>()->getMemorySize(), sizeof(signed char));
EXPECT_EQ(rfk::getArchetype<unsigned char>()->getMemorySize(), sizeof(unsigned char));
EXPECT_EQ(rfk::getArchetype<wchar_t>()->getMemorySize(), sizeof(wchar_t));
EXPECT_EQ(rfk::getArchetype<char16_t>()->getMemorySize(), sizeof(char16_t));
EXPECT_EQ(rfk::getArchetype<char32_t>()->getMemorySize(), sizeof(char32_t));
EXPECT_EQ(rfk::getArchetype<short>()->getMemorySize(), sizeof(short));
EXPECT_EQ(rfk::getArchetype<unsigned short>()->getMemorySize(), sizeof(unsigned short));
EXPECT_EQ(rfk::getArchetype<int>()->getMemorySize(), sizeof(int));
EXPECT_EQ(rfk::getArchetype<unsigned int>()->getMemorySize(), sizeof(unsigned int));
EXPECT_EQ(rfk::getArchetype<long>()->getMemorySize(), sizeof(long));
EXPECT_EQ(rfk::getArchetype<unsigned long>()->getMemorySize(), sizeof(unsigned long));
EXPECT_EQ(rfk::getArchetype<long long>()->getMemorySize(), sizeof(long long));
EXPECT_EQ(rfk::getArchetype<unsigned long long>()->getMemorySize(), sizeof(unsigned long long));
EXPECT_EQ(rfk::getArchetype<float>()->getMemorySize(), sizeof(float));
EXPECT_EQ(rfk::getArchetype<double>()->getMemorySize(), sizeof(double));
EXPECT_EQ(rfk::getArchetype<long double>()->getMemorySize(), sizeof(long double));
}
TEST(Rfk_Archetype_getMemorySize, StructClass)
{
EXPECT_EQ(rfk::getArchetype<TestClass>()->getMemorySize(), sizeof(TestClass));
}
TEST(Rfk_Archetype_getMemorySize, ClassTemplate)
{
EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate>()->getMemorySize(), 0u); //Dependant type
}
TEST(Rfk_Archetype_getMemorySize, ClassTemplateInstantiation)
{
EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate<int>>()->getMemorySize(), sizeof(SingleTypeTemplateClassTemplate<int>));
}
TEST(Rfk_Archetype_getMemorySize, Enum)
{
EXPECT_EQ(rfk::getEnum<TestEnum>()->getMemorySize(), sizeof(TestEnum));
EXPECT_EQ(rfk::getEnum<TestEnumClass>()->getMemorySize(), sizeof(TestEnumClass));
}
//=========================================================
//============ Archetype::setAccessSpecifier ==============
//=========================================================
TEST(Rfk_Archetype_setAccessSpecifier, setAccessSpecifier)
{
rfk::Enum e("Test", 0u, rfk::getArchetype<int>(), nullptr);
e.setAccessSpecifier(rfk::EAccessSpecifier::Public);
EXPECT_EQ(e.getAccessSpecifier(), rfk::EAccessSpecifier::Public);
e.setAccessSpecifier(rfk::EAccessSpecifier::Protected);
EXPECT_EQ(e.getAccessSpecifier(), rfk::EAccessSpecifier::Protected);
e.setAccessSpecifier(rfk::EAccessSpecifier::Private);
EXPECT_EQ(e.getAccessSpecifier(), rfk::EAccessSpecifier::Private);
} | 47.8 | 178 | 0.749764 | Angelysse |
5696b3542f81e8931368f031251ff7ac2ec140fc | 6,487 | cpp | C++ | Algorithm Templates/Manacher's Algorithm.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 2 | 2019-11-10T18:42:11.000Z | 2020-07-04T07:05:22.000Z | Algorithm Templates/Manacher's Algorithm.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | null | null | null | Algorithm Templates/Manacher's Algorithm.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 1 | 2019-11-04T11:05:17.000Z | 2019-11-04T11:05:17.000Z | /**
@author - Rumman BUET CSE'15
Problem -
Idea -
Concept -
*/
#include <bits/stdc++.h>
#define m0(a) memset(a , 0 , sizeof(a))
using namespace std;
/************************************** END OF INITIALS ****************************************/
/**
* Linear time Manacher's algorithm to find longest palindromic substring.
* There are 4 cases to handle
* Case 1 : Right side palindrome is totally contained under current palindrome. In this case do not consider this as center.
* Case 2 : Current palindrome is proper suffix of input. Terminate the loop in this case. No better palindrom will be found on right.
* Case 3 : Right side palindrome is proper suffix and its corresponding left side palindrome is proper prefix of current palindrome. Make largest such point as
* next center.
* Case 4 : Right side palindrome is proper suffix but its left corresponding palindrome is be beyond current palindrome. Do not consider this
* as center because it will not extend at all.
*
* To handle even size palindromes replace input string with one containing $ between every input character and in start and end.
*/
int longestPalindromicSubstringLinear(string input) {
int index = 0;
//preprocess the input to convert it into type abc -> $a$b$c$ to handle even length case.
//Total size will be 2*n + 1 of this new array.
string newInput = "";
for (int i = 0; i < 2*input.length() + 1; i++) {
if (i % 2 != 0) {
newInput += input[index++];
} else {
newInput += '$';
}
}
// cout << newInput << endl ;
int newInputLength = static_cast<int>(newInput.length());
//create temporary array for holding largest palindrome at every point. There are 2*n + 1 such points.
int T[newInputLength];
m0(T);
int start = 0;
int end = 0;
//here i is the center.
for (int i = 0; i < newInputLength;) {
//expand around i. See how far we can go.
while (start > 0 && end < newInputLength - 1 && newInput[start - 1] == newInput[end + 1]) {
start--;
end++;
}
//set the longest value of palindrome around center i at T[i]
T[i] = end - start + 1;
//Case 2: this is case 2. Current palindrome is proper suffix of input. No need to proceed. Just break out of loop.
if (end == newInputLength - 1) {
break;
}
//Mark newCenter to be either end or end + 1 depending on if we dealing with even or old number input.
// etar karon hocche, # ke center dhore palin ber korar kono mane nai. as, even place gulate always # thakbe
int newCenter = end + (i % 2 == 0 ? 1 : 0);
for (int j = i + 1; j <= end; j++) {
// This part contains Case 3,4
/*
*
* Bangla explanation -
*
* j ki? - j hocche ashol palindrome er center er daan pasher part ta.
* ei j = range(center -> end)
*
* Case 1: jodi choto palindrome boro palindrome er moddhe included hoye jay.
* how is checked? - T[j] = min(T[i - (j - i)], 2 * (end - j) + 1); -> it ensures it
* Q: (2 * (end - j) + 1) diye ki bujhaay? - j ke center dhore palindrom er daane baame (end-j) ta kore
* element thaake. so, total element in that palindrom hobe 2 * (end-j) + 1. (1 hoche j ke shoho niye).
* Q: T[i - (j - i)] diye ki bujhaay? - Eta bujhaay i er mirror elelment ke center dhore banano
* palindrom er length koto hobe. ekhon chinta koro, (2 * (end - j) + 1) is the highest possible
* length of the palindrome centered at j. naaile onnora ore cover kore felto.
* So, -
* 1. T[i - (j - i)] > (2 * (end - j) + 1) ---> maane holo, baam dike ashol palin
* er edge over kore chole gese. so, eta ignore korbo ---> CASE : 4
*
*
* 2. T[i - (j - i)] < (2 * (end - j) + 1) ---> baam dike notun palin ashol palin er moddhe
* included hoye gese. notun kore etake hishab korar proyojon nai----> CASE : 1
*
*
* 3. T[i - (j - i)] == (2 * (end - j) + 1) ---> maane holo, baam dike edge thekei shuru
* hoise oi palindrom. maane PREFIX hoye gese eta. etake count kora lagbe ----> CASE : 3
*
*
* CASE 3: etaay arektu extra kaaj kora laage. karon, tumi to minimum ta niso but ekhono jano na
* je ashole konta minimum chilo T[i - (j - i)], naki (2 * (end - j) + 1). so, ami sure korte
* chaitesi je T[i - (j - i)] minimum hoilei kebol eta prefix hoye jaabe nicher check e
* and so, change ta hobe.
*
*
* if (j + T[i - (j - i)] / 2 == end) --> ei check ta kora lagtese case 3 te. keno?
* eta diye confirm kortese je 'j' theke palin nile sheta suffix o hobe. aar prefix to aagei hoilo ekbar.
* so, ultimately suffix , prefix duitai proof hoilo ---> CASE : 3 proved.
*
*
*/
//Case 1, 4: i - (j - i) is left mirror. Its possible left mirror might go beyond current center palindrome.
// So take minimum of either left side palindrome or distance of j to end.
T[j] = min(T[i - (j - i)], 2 * (end - j) + 1);
// Case 3: Only proceed if we get case 3. This check is to make sure we do not pick j as new
// center for case 1 or case 4
// As soon as we find a center lets break out of this inner while loop.
if (j + T[i - (j - i)] / 2 == end) {
newCenter = j;
break;
}
}
//make i as newCenter. Set right and left to atleast the value we already know should be matching based of left side palindrome.
i = newCenter;
end = i + T[i] / 2;
start = i - T[i] / 2;
}
//find the max palindrome in T and return it.
int max = INT_MIN;
for (int i = 0; i < newInputLength; i++) {
// cout << T[i] << " ";
int val;
val = T[i] / 2;
if (max < val) {
max = val;
}
}
cout << endl;
return max;
}
int main() {
// string str = "abaxabaxabybaxabyb";
string str = "ab";
cout << longestPalindromicSubstringLinear(str) << endl;
return 0;
}
| 41.318471 | 164 | 0.547094 | shamiul94 |
569c023e96c13aa84759740a3d8938a2c8e4c174 | 4,007 | cpp | C++ | nimbro_apc/hardware/apc_interface/src/status_display/status_display.cpp | warehouse-picking-automation-challenges/nimbro_picking | 857eee602beea9eebee45bbb67fce423b28f9db6 | [
"BSD-3-Clause"
] | 19 | 2017-11-02T03:05:51.000Z | 2020-12-02T19:40:15.000Z | nimbro_apc/hardware/apc_interface/src/status_display/status_display.cpp | warehouse-picking-automation-challenges/nimbro_picking | 857eee602beea9eebee45bbb67fce423b28f9db6 | [
"BSD-3-Clause"
] | null | null | null | nimbro_apc/hardware/apc_interface/src/status_display/status_display.cpp | warehouse-picking-automation-challenges/nimbro_picking | 857eee602beea9eebee45bbb67fce423b28f9db6 | [
"BSD-3-Clause"
] | 9 | 2017-09-16T02:20:39.000Z | 2020-05-24T14:06:35.000Z | // rqt plugin displaying the controller status
// Author: Max Schwarz <max.schwarz@uni-bonn.de>
#include "status_display.h"
#include <ros/node_handle.h>
#include <ros/service.h>
#include <QMessageBox>
#include <pluginlib/class_list_macros.h>
#include <apc_interface/DimLight.h>
#include <apc_interface/SuctionStrength.h>
#include <std_srvs/SetBool.h>
Q_DECLARE_METATYPE(apc_interface::ControllerStateConstPtr)
namespace apc_interface
{
StatusDisplay::StatusDisplay()
{
}
StatusDisplay::~StatusDisplay()
{
}
void StatusDisplay::initPlugin(qt_gui_cpp::PluginContext& ctx)
{
m_w = new QWidget();
m_ui.setupUi(m_w);
ctx.addWidget(m_w);
qRegisterMetaType<apc_interface::ControllerStateConstPtr>();
connect(this, SIGNAL(controllerStateReceived(apc_interface::ControllerStateConstPtr)),
SLOT(handleControllerState(apc_interface::ControllerStateConstPtr)),
Qt::QueuedConnection
);
ros::NodeHandle nh = getPrivateNodeHandle();
m_sub_state = nh.subscribe("/apc_interface/controller_state", 1, &StatusDisplay::controllerStateReceived, this);
connect(m_ui.vacuumButton, SIGNAL(clicked(bool)), SLOT(toggleVacuum()));
connect(m_ui.lightButton, SIGNAL(clicked(bool)), SLOT(toggleLight()));
connect(m_ui.vacuumPowerButton, SIGNAL(clicked(bool)), SLOT(toggleVacuumPower()));
connect(m_ui.strengthSlider, SIGNAL(valueChanged(int)), SLOT(updateSliderLabel(int)));
}
void StatusDisplay::shutdownPlugin()
{
m_sub_state.shutdown();
}
void StatusDisplay::handleControllerState(const apc_interface::ControllerStateConstPtr& msg)
{
QPalette bgOff = m_ui.vacuumLabel->palette();
QPalette bgHalf = bgOff;
QPalette bgOn = bgOff;
bgOff.setColor(QPalette::Window, Qt::red);
bgHalf.setColor(QPalette::Window, Qt::yellow);
bgOn.setColor(QPalette::Window, Qt::green);
m_ui.vacuumLabel->setText(
msg->vacuum_active ? "ON" : "OFF"
);
m_ui.vacuumLabel->setPalette(
msg->vacuum_active ? bgOn : bgOff
);
m_ui.lightLabel->setText(
QString("%1").arg((int)msg->light_duty)
);
m_ui.airVelocityLabel->setText(
QString("%1").arg(msg->air_velocity)
);
m_ui.airVelocityLowPassLabel->setText(
QString("%1").arg(msg->air_velocity_low_pass)
);
m_ui.airVelocityLabel->setPalette(
msg->object_well_attached ? bgOn : (msg->something_on_tip ? bgHalf : bgOff)
);
m_ui.vacuumPowerLabel->setText(
msg->vacuum_power_active ? "ON" : "OFF"
);
m_lastState = msg;
}
void StatusDisplay::toggleVacuum()
{
if(!m_lastState)
return;
std_srvs::SetBool srv;
apc_interface::SuctionStrength suction;
auto on = !m_lastState->vacuum_active;
srv.request.data = on;
suction.request.strength = (on) ?
(m_ui.strengthSlider->value() / 100.0f) : 0.0f;
if(!ros::service::call("/apc_interface/set_suction_strength", suction))
{
QMessageBox::critical(m_w, "Error", "Could not call suction service");
}
if(!ros::service::call("/apc_interface/switch_vacuum", srv))
{
QMessageBox::critical(m_w, "Error", "Could not call vacuum service");
}
}
void StatusDisplay::toggleVacuumPower()
{
if(!m_lastState)
return;
std_srvs::SetBool srv;
auto on = !m_lastState->vacuum_power_active;
srv.request.data = on;
if(!ros::service::call("/apc_interface/switch_vacuum_power", srv))
{
QMessageBox::critical(m_w, "Error", "Could not call vacuum_power service");
}
}
void StatusDisplay::toggleLight()
{
if(!m_lastState)
return;
apc_interface::DimLight srv;
srv.request.duty = m_lastState->light_duty ? 0 : 255;
if(!ros::service::call("/apc_interface/dim", srv))
{
QMessageBox::critical(m_w, "Error", "Could not call light service");
}
}
void StatusDisplay::updateSliderLabel(int ticks)
{
auto strength = (float)(ticks / 100.0f);
m_ui.strengthLabel->setText(
QString::number(strength)
);
if(m_lastState)
{
if(m_lastState->vacuum_active)
{
apc_interface::SuctionStrength s;
s.request.strength = strength;
ros::service::call(
"/apc_interface/set_suction_strength", s);
}
}
}
}
PLUGINLIB_EXPORT_CLASS(apc_interface::StatusDisplay, rqt_gui_cpp::Plugin)
| 23.432749 | 113 | 0.737709 | warehouse-picking-automation-challenges |
569e9d0f4461a985eaf46fdd6463078b6d953cca | 11,817 | hxx | C++ | Unparsed.hxx | zaimoni/Franc | 54c41949676e0e4e2fdba00b7bb7813b1b45e649 | [
"BSL-1.0"
] | null | null | null | Unparsed.hxx | zaimoni/Franc | 54c41949676e0e4e2fdba00b7bb7813b1b45e649 | [
"BSL-1.0"
] | null | null | null | Unparsed.hxx | zaimoni/Franc | 54c41949676e0e4e2fdba00b7bb7813b1b45e649 | [
"BSL-1.0"
] | null | null | null | // Unparsed.hxx
// header for UnparsedText
#ifndef UNPARSED_TEXT_DEF
#define UNPARSED_TEXT_DEF
#include "MetaCon6.hxx"
#include "Zaimoni.STL/AutoPtr.hpp"
class UnparsedText;
namespace zaimoni {
template<>
struct is_polymorphic_final<UnparsedText> : public std::true_type {};
}
class UnparsedText final : public MetaConceptZeroArgs
{
private:
autovalarray_ptr_throws<char> Text;
public:
typedef bool Recognize(const char*);
typedef bool Parse(MetaConcept*&, const char*);
enum SelfClassify_UT {
None_UT = 0x00, // LangConf
SemanticChar_UT = 0x01, // LangConf
LeadingIntegerNumeral_UT = 0x02,
QuasiSymbol_UT = 0x04,
QuasiEnglish_UT = 0x08,
VarName_UT = 0x10,
LogicKeyword_UT = 0x20,
PredCalcKeyword_UT = 0x40,
PrefixKeyword_UT = 0x80,
InfixSymbol_UT = 0x100,
HTMLTerminalTag_UT = 0x200,
JSEntity_UT = 0x400,
JSCharEntity_UT = 0x800,
HTMLStartTag_UT = 0x1000,
XMLSelfEndTag_UT = 0x2000,
Uninterpreted_UT = 0x8000 // LangConf
};
size_t LogicalLineNumber; // default 0, not manipulated by UnparsedText
size_t LogicalLineOrigin; // default 0, not manipulated by UnparsedText
const char* SourceFileName; // *NOT* owned; default NULL, not manipulated by UnparsedText
private:
unsigned short SelfClassifyBitmap;
static zaimoni::weakautoarray_ptr<Recognize*> EvalRecognizers;
static zaimoni::weakautoarray_ptr<Parse*> EvalParsers;
public:
explicit UnparsedText(char*& src);
UnparsedText(char*& src, bool Interpreted);
protected:
UnparsedText(char*& src, unsigned short NewSelfClassify);
public:
UnparsedText(const UnparsedText& src) = default;
UnparsedText(UnparsedText&& src) = default;
UnparsedText& operator=(const UnparsedText& src) = default;
UnparsedText& operator=(UnparsedText&& src) = default;
~UnparsedText() = default;
void CopyInto(MetaConcept*& dest) const override { CopyInto_ForceSyntaxOK(*this, dest); }; // can throw memory failure
void CopyInto(UnparsedText*& dest) const { CopyInto_ForceSyntaxOK(*this, dest); };
void MoveInto(MetaConcept*& dest) override { zaimoni::MoveIntoV2(std::move(*this), dest); }
void MoveInto(UnparsedText*& dest) { zaimoni::MoveIntoV2(std::move(*this), dest); }
static UnparsedText& up_reference(MetaConcept* src);
static const UnparsedText& up_reference(const MetaConcept* src);
static UnparsedText& up_reference(MetaConcept& src);
static const UnparsedText& up_reference(const MetaConcept& src);
static UnparsedText& fast_up_reference(MetaConcept* src);
static const UnparsedText& fast_up_reference(const MetaConcept* src);
// Type ID functions
const AbstractClass* UltimateType() const override { return 0; } // untyped i.e. free
constexpr static bool IsType(ExactType_MC x) { return UnparsedText_MC == x; }
unsigned int OpPrecedence() const override;
// Evaluation functions
std::pair<std::function<bool()>, std::function<bool(MetaConcept*&)> > canEvaluate() const override;
virtual bool CanEvaluate() const;
virtual bool CanEvaluateToSameType() const;
virtual bool SyntaxOK() const;
virtual bool Evaluate(MetaConcept*& dest); // same, or different type
virtual bool DestructiveEvaluateToSameType(); // overwrites itself iff returns true
// text I/O functions
const char* ViewKeyword() const override { return Text; }
size_t text_size() const { return Text.size(); }
void SwapWith(UnparsedText& Target);
// Pattern analysis: returns true if pattern found, and then fills the bounding coordinates
// Quotation marks do not include leading/trailing spaces, if any
// A QuasiEnglishNumeric ID is something that could eventually parse into an English word or
// number. Alphabetic characters and numeric characters are allowed. Interpreting decimal
// points comes later. An all-capital QuasiEnglishNumeric ID is biased towards being a
// math keyword; normal capitalization is biased towards English. Mixed letters and numbers
// is biased towards a math keyword.
// A QuasiSymbolID is something that could eventually parse into atomic punctuation, or a
// reasonable mathematical symbol. It cannot contain spaces, or alphabetic/numeric characters.
// While balanced syntactical items do not count, the QuasiSymbolID length-finder does not
// check for them (much).
// Franci interprets ...s' and ...z' as more likely to be english possessives than quotation
// endings.
// Franci interprets ' surrounded by letters as more likely to be English than quotation start/end
// Franci interprets '70 as a century-suppressed year
// Franci is aware of ' and " as single-variable derivative markers.
inline bool IsUnclassified(void) const {return None_UT==SelfClassifyBitmap;};
inline bool IsQuasiEnglishNumeric(void) const {return (LeadingIntegerNumeral_UT | QuasiEnglish_UT | VarName_UT) & SelfClassifyBitmap;};
inline bool IsQuasiSymbol(void) const {return QuasiSymbol_UT==SelfClassifyBitmap;};
bool IsQuasiSymbolEndingInMinusSign(void) const;
bool IsQuasiSymbolEndingInPlusSign(void) const;
inline bool IsSemanticChar(void) const {return SemanticChar_UT==SelfClassifyBitmap;};
bool IsSemanticChar(char Target) const;
inline bool IsLeadingIntegerNumeral(void) const {return LeadingIntegerNumeral_UT==SelfClassifyBitmap;};
inline bool IsQuasiEnglish(void) const {return QuasiEnglish_UT==SelfClassifyBitmap;};
inline bool IsVarName(void) const {return VarName_UT==SelfClassifyBitmap;};
bool IsQuasiEnglishOrVarName(void) const {return (QuasiEnglish_UT | VarName_UT) & SelfClassifyBitmap;};
inline bool IsLogicKeyword(void) const {return LogicKeyword_UT==SelfClassifyBitmap;};
bool IsLogicKeyword(const char* Target) const;
inline bool IsPredCalcKeyword(void) const {return PredCalcKeyword_UT==SelfClassifyBitmap;};
bool IsPredCalcKeyword(const char* Target) const;
inline bool IsPrefixKeyword(void) const {return PrefixKeyword_UT==SelfClassifyBitmap;};
bool IsPrefixKeyword(const char* Target) const;
inline bool IsInfixSymbol(void) const {return InfixSymbol_UT==SelfClassifyBitmap;};
bool IsInfixSymbol(const char* Target) const;
inline bool IsHTMLStartTag(void) const {return HTMLStartTag_UT==SelfClassifyBitmap;};
bool IsHTMLStartTag(const char* Target) const;
bool IsHTMLTerminalTag() const { return HTMLTerminalTag_UT == SelfClassifyBitmap; }
bool IsHTMLTerminalTag(const char* Target) const;
bool IsJSEntity() const { return JSEntity_UT == SelfClassifyBitmap; }
bool IsJSEntity(const char* Target) const;
bool IsJSCharEntity() const { return JSCharEntity_UT == SelfClassifyBitmap; }
bool IsJSCharEntity(const char* Target) const;
inline bool MustBeParsedInContext(void) const {return (HTMLTerminalTag_UT | JSEntity_UT | JSCharEntity_UT) & SelfClassifyBitmap;}
inline bool IsUninterpreted(void) const {return (Uninterpreted_UT & SelfClassifyBitmap) ? true : false;};
bool IsMultiplicationSymbol() const; // 2020-08-03: dead function? Cf. IsLogicalMultiplicationSign
inline bool IsLogicOrPredCalcKeyword(void) const {return (LogicKeyword_UT | PredCalcKeyword_UT) & SelfClassifyBitmap;};
inline bool IsLogic_Prefix_OrPredCalcKeyword(void) const {return (LogicKeyword_UT | PrefixKeyword_UT | PredCalcKeyword_UT) & SelfClassifyBitmap;};
inline bool IsSymbol(void) const {return (QuasiSymbol_UT | InfixSymbol_UT) & SelfClassifyBitmap;};
inline bool IsCharacter(char Target) const {return IsSemanticChar() && Text[0]==Target;};
// following implemented in Clause2.cxx
ExactType_MC TypeFor2AryClauseInfixKeyword(void) const;
// following implemented in Phrase2.cxx
ExactType_MC TypeFor2AryPhraseKeyword(void) const;
// following implemented in ClauseN.cxx
ExactType_MC TypeForNAryClauseKeyword(void) const;
// resume implementing in Unparsed.cxx
bool ArgCannotExtendLeftThroughThis(void) const;
bool ArgCannotExtendRightThroughThis(void) const;
bool IsLogicalPlusSign() const;
bool IsLogicalMultiplicationSign() const;
bool IsLogicalEllipsis() const;
bool IsLogicalInfinity() const { return IsJSEntity("infin"); }
size_t LengthOfNumericIntegerToSplitOff(void) const; // 2020-08-06 dead function?
bool AnyNonAlphabeticChars() const; // 2020-08-06 dead function?
size_t LengthOfQuasiEnglishNumericID() const; // 2020-08-06 dead function?
size_t LengthOfQuasiSymbolID() const;
size_t LengthOfHTMLStartTag() const; // 2020-08-06 dead function?
size_t LengthOfHTMLTerminalTag() const; // 2020-08-06 dead function?
// pattern processing
size_t CanSplitIntoTwoTexts() const;
bool SplitIntoTwoTexts(MetaConcept*& Text2);
void ZLSTarget(char const* Target, size_t length);
void ZLSTarget(char const* Target);
void ZLSTarget(char Target);
void DeleteNCharsAtIdx(size_t N, size_t i);
void InsertSourceAtIdx(const char* src, size_t i, size_t length);
void InsertSourceAtIdx(const char* src, size_t i);
void InsertSourceAtIdx(char src, size_t i);
void OverwriteNthPlaceWith(size_t N, const char* src, size_t length);
void OverwriteNthPlaceWith(size_t N, const char* src);
void OverwriteNthPlaceWith(size_t N, char src);
void OverwriteReverseNthPlaceWith(size_t N, char src);
void ReplaceTargetWithSource(char src, const char* Target);
void ReplaceTargetWithSource(char src, const char Target);
void TruncateByN(size_t N);
bool ConcatenateLHSTruncatedByN(UnparsedText& RHS,unsigned long N); // returns true iff success; RHS invalid then
bool IsString(const char* const Target) const {return 0==strcmp(Text,Target);};
bool IsSubstring(char Target,size_t Offset) const;
bool IsSubstring(const char* const Target,size_t Offset) const;
bool StartsWith(char Target) const;
bool StartsWith(const char* const Target) const;
bool EndsWith(char Target) const;
bool EndsAtOffsetWith(size_t Offset,char Target) const;
bool WS_Strip(void); // returns true if there is content left over
void WipeText(void);
void ExtractText(char*& dest) {Text.TransferOutAndNULL(dest);}; // destroys syntactical validity by NULLing Text; use this right before destruction.
void ImportText(char*& src);
bool PreChop(char*& Target, size_t strict_ub); // excises first n characters to string Target
void ScanThroughQuote(size_t& i, bool break_token_on_newline, char escaped_quotes, char escape);
void ScanThroughNewline(size_t& Offset);
bool ScanToChar(size_t& i,char Target) const;
static void InstallEvalRule(Recognize* new_recognizer,Parse* new_parser);
protected:
virtual bool EqualAux2(const MetaConcept& rhs) const;
virtual bool InternalDataLTAux(const MetaConcept& rhs) const;
std::string to_s_aux() const override;
private:
void TextSnip(const size_t Start, const size_t End);
void SpecializeSemantics(void);
};
template<char c> bool IsSemanticChar(const MetaConcept* x) {
if (const auto src = up_cast<UnparsedText>(x)) return src->IsSemanticChar(c);
return false;
}
inline bool IsHTMLStartTag(const MetaConcept* x, const char* Target)
{
if (const auto src = up_cast<UnparsedText>(x)) return src->IsHTMLStartTag(Target);
return false;
}
inline const char* IsHTMLTerminalTag(const MetaConcept* x)
{
if (const auto src = up_cast<UnparsedText>(x)) {
if (src->IsHTMLTerminalTag()) return src->ViewKeyword();
}
return 0;
}
inline bool IsHTMLTerminalTag(const MetaConcept* x, const char* Target)
{
if (const auto src = up_cast<UnparsedText>(x)) return src->IsHTMLTerminalTag(Target);
return false;
}
inline bool IsLogicKeyword(const MetaConcept* x, const char* Target)
{
if (const auto src = up_cast<UnparsedText>(x)) return src->IsLogicKeyword(Target);
return false;
}
inline bool RejectTextToVar(const MetaConcept* x)
{
if (const auto src = up_cast<UnparsedText>(x)) return !src->IsQuasiEnglishOrVarName();
return false;
}
#endif
| 46.70751 | 150 | 0.764915 | zaimoni |
56a1d4fbcb4734a67c644b256a5c4b66201a2bd2 | 1,731 | hpp | C++ | include/kobuki_core/logging.hpp | kobuki-base/kobuki_core | 5fb88169d010c3a23f24ff0ba7e9cb45b46b24e8 | [
"BSD-3-Clause"
] | 10 | 2020-06-01T05:05:27.000Z | 2022-01-18T13:19:58.000Z | include/kobuki_core/logging.hpp | clalancette/kobuki_core | e5bef97d3c1db24441508673e08c67be599faa84 | [
"BSD-3-Clause"
] | 28 | 2020-01-10T14:42:54.000Z | 2021-07-28T08:01:44.000Z | include/kobuki_core/logging.hpp | clalancette/kobuki_core | e5bef97d3c1db24441508673e08c67be599faa84 | [
"BSD-3-Clause"
] | 8 | 2020-02-04T09:59:18.000Z | 2021-08-29T01:59:38.000Z | /**
* @file include/kobuki_core/logging.hpp
*
* @brief Log levels and simple logging to screen.
*
* License: BSD
* https://raw.githubusercontent.com/kobuki-base/kobuki_core/license/LICENSE
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef KOBUKI_LOGGING_HPP_
#define KOBUKI_LOGGING_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include <iostream>
#include <string>
#include <ecl/console.hpp>
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace kobuki {
/*****************************************************************************
** Log Levels
*****************************************************************************/
/**
* @brief Internal logging levels.
*
* Kobuki will log to stdout the specified log level and higher. For example
* if WARNING is specified, it will log both warning and error messages. To
* disable logging, use NONE.
*
* To connect to your own logging infrastructure, use NONE and provide slots
* (callbacks) to the kobuki debug, info, warning and error signals.
*/
enum LogLevel {
DEBUG = 0,
INFO = 1,
WARNING = 2,
ERROR = 3,
NONE = 4
};
void logDebug(const std::string& message);
void logInfo(const std::string& message);
void logWarning(const std::string& message);
void logError(const std::string& message);
} // namespace kobuki
#endif /* KOBUKI_LOGGING_HPP_ */
| 28.85 | 79 | 0.450607 | kobuki-base |
56a221ea1597980da2511f1b2ac086226c64c8a0 | 9,156 | cpp | C++ | Packer/Packer/SourceCode/Exporter/ExSgMesh.cpp | GavWood/tutorials | d5140129b6acd6d61f6feedcd352c12e4ebabd40 | [
"BSD-2-Clause"
] | 8 | 2017-10-26T14:26:55.000Z | 2022-01-07T07:35:39.000Z | Packer/Packer/SourceCode/Exporter/ExSgMesh.cpp | GavWood/tutorials | d5140129b6acd6d61f6feedcd352c12e4ebabd40 | [
"BSD-2-Clause"
] | 1 | 2017-09-28T08:21:04.000Z | 2017-10-04T09:17:57.000Z | Packer/Packer/SourceCode/Exporter/ExSgMesh.cpp | GavWood/Game-Framework | d5140129b6acd6d61f6feedcd352c12e4ebabd40 | [
"BSD-2-Clause"
] | 1 | 2021-07-21T17:37:33.000Z | 2021-07-21T17:37:33.000Z | ////////////////////////////////////////////////////////////////////////////////
// ExSgMesh.cpp
// Includes
#include "StdAfx.h"
#include "ExMatrix.h"
#include "ExSgMesh.h"
#include "ExStrip.h"
#include "ExScene.h"
#include "ExIndexBuffer.h"
#include "ExVertexBuffer.h"
#include "ExVertex.h"
#include "SgRigidBody.h"
#include "ApConfig.h"
#include "PaTopState.h"
#include "FCollada.h"
#include "PaRendering.h"
////////////////////////////////////////////////////////////////////////////////
// Constructor
ExSgMesh::ExSgMesh( ExSgNode *pNode, ExScene *pScene )
{
m_pNode = pNode;
m_pScene = pScene;
}
////////////////////////////////////////////////////////////////////////////////
// Destructor
ExSgMesh::~ExSgMesh()
{
BtU32 nSize = (BtU32) m_materialBlocks.size();
for( BtU32 iMaterialBlock=0; iMaterialBlock<nSize; ++iMaterialBlock )
{
delete m_materialBlocks[iMaterialBlock];
}
}
void ExSgMesh::GroupDrawing()
{
MakeRenderGroups();
OptimiseGeometry();
BoundVertex();
}
////////////////////////////////////////////////////////////////////////////////
// MakeRenderGroups
void ExSgMesh::MakeRenderGroups()
{
// Cache the number of material blocks
BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size();
// Flatten the material blocks
for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ )
{
// Cache each material block
ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock];
// Cache the number of indices
BtU32 nIndices = (BtU32) pMaterialBlock->m_indices.size();
ExRenderBlock renderBlock;
for( BtU32 iIndex = 0; iIndex < nIndices; iIndex++ )
{
// Add the index
renderBlock.m_indices.push_back( pMaterialBlock->m_indices[iIndex] );
// Add the vertex
renderBlock.m_vertex.push_back( pMaterialBlock->m_pVertex[iIndex] );
}
// Add the render block
pMaterialBlock->m_renderBlocks.push_back( renderBlock );
}
}
////////////////////////////////////////////////////////////////////////////////
// OptimiseGeometry
void ExSgMesh::OptimiseGeometry()
{
// Cache the number of material blocks
BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size();
// Flatten the material blocks
for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ )
{
// Cache each material block
ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock];
// Cache the number of Render blocks
BtU32 nRenderBlocks = (BtU32) pMaterialBlock->m_renderBlocks.size();
// Flatten the Render blocks
for( BtU32 iRenderBlock=0; iRenderBlock<nRenderBlocks; iRenderBlock++ )
{
// Cache each render block
ExRenderBlock& renderBlock = pMaterialBlock->m_renderBlocks[iRenderBlock];
// Create the geometry stripper
ExGeometryOptimise optimise( pMaterialBlock, &renderBlock );
BtBool optimiseEnabled = m_pNode->isStripped();
(void)optimiseEnabled;
ErrorLog::Printf( "Merging similar vertex in node %s\r\n", m_pNode->pName() );
if( BtFalse )//m_pNode->isMergeLikeVertex() == BtTrue )
{
optimise.MergeVertex();
}
else
{
optimise.CopyVertexNoMerge();
}
if( m_pNode->isStripped() == BtTrue )
{
ErrorLog::Printf( "Stripping node %s\r\n", m_pNode->pName() );
optimise.Strip();
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// BoundVertex
void ExSgMesh::BoundVertex()
{
// Cache the number of material blocks
BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size();
// Flatten the material blocks
for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ )
{
// Cache each material block
ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock];
// Cache the number of Render blocks
BtU32 nRenderBlocks = (BtU32) pMaterialBlock->m_renderBlocks.size();
// Flatten the Render blocks
for( BtU32 iRenderBlock=0; iRenderBlock<nRenderBlocks; iRenderBlock++ )
{
// Cache each render block
ExRenderBlock& renderBlock = pMaterialBlock->m_renderBlocks[iRenderBlock];
// Cache the number of vertex
BtU32 nVertices = (BtU32) renderBlock.m_pOptimisedVertex.size();
// Add the vertex
for( BtU32 iVertex=0; iVertex<nVertices; iVertex++ )
{
// Cache each vertex
ExVertex* pVertex = (ExVertex*) renderBlock.m_pOptimisedVertex[iVertex];
// Cache each position
MtVector3 v3Position = pVertex->Position();
// Expand the bounding box
if( ( iMaterialBlock == 0 ) && ( iRenderBlock == 0 ) && ( iVertex == 0 ) )
{
m_AABB = MtAABB( v3Position, v3Position );
m_sphere = MtSphere( v3Position, 0 );
}
else
{
m_AABB.Min( v3Position.Min( m_AABB.Min() ) );
m_AABB.Max( v3Position.Max( m_AABB.Max() ) );
m_sphere.ExpandBy( v3Position );
}
}
}
}
int a=0;
a++;
}
////////////////////////////////////////////////////////////////////////////////
// MoveToVertexBuffer
void ExSgMesh::MoveToVertexBuffers()
{
// Cache the number of material blocks
BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size();
// Flatten the material blocks
for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ )
{
// Cache each material block
ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock];
// Cache the number of Render blocks
BtU32 nRenderBlocks = (BtU32) pMaterialBlock->m_renderBlocks.size();
// Flatten the Render blocks
for( BtU32 iRenderBlock=0; iRenderBlock<nRenderBlocks; iRenderBlock++ )
{
// Cache each render block
ExRenderBlock& renderBlock = pMaterialBlock->m_renderBlocks[iRenderBlock];
// Cache the number of vertex
BtU32 nVertices = (BtU32) renderBlock.m_pOptimisedVertex.size();
// Export only material blocks with primitives
if( nVertices > 0 )
{
BtU32 nBaseVertex = 0;
// Cache each vertex
ExVertex* pVertex = renderBlock.m_pOptimisedVertex[0];
// Get the vertex buffer
ExVertexBuffer* pVertexBuffer = m_pScene->pVertexBuffer( pVertex->GetVertexType() );
// Get the base vertex
nBaseVertex = pVertexBuffer->Size();
// Add the vertex
for( BtU32 iVertex=0; iVertex<nVertices; iVertex++ )
{
// Cache each vertex
ExVertex* pVertex = renderBlock.m_pOptimisedVertex[iVertex];
// Add each vertex
pVertexBuffer->AddVertex( pVertex );
}
BtU32 nBaseIndex = (BtU32) m_pScene->pIndexBuffer()->nSize();
BtU32 nIndices = 0;
BtU32 offset = 0;
if( PaTopState::Instance().IsBaseVertex() )
{
offset += nBaseVertex;
}
BtChar *pStr = m_pNode->pName();
if( strstr( pStr, "Wing" ) )
{
int a=0;
a++;
}
ExIndexBuffer *pIndexBuffer = m_pScene->pIndexBuffer();
// Add the indices
if( m_pNode->isStripped() == BtTrue )
{
nIndices = (BtU32) renderBlock.m_strippedIndex.size();
for( BtU32 iIndex=0; iIndex<nIndices; iIndex++ )
{
pIndexBuffer->AddIndex( renderBlock.m_strippedIndex[iIndex] + offset );
}
}
else
{
nIndices = (BtU32) renderBlock.m_optimisedIndex.size();
for( BtU32 iIndex=0; iIndex<nIndices; iIndex++ )
{
pIndexBuffer->AddIndex( renderBlock.m_optimisedIndex[iIndex] + offset );
}
}
// Add each primitive
RsIndexedPrimitive primitive;
BtU32 numprimitives = nIndices;
if( renderBlock.m_primitiveType == ExPT_STRIP )
{
numprimitives -= 2;
}
else if( renderBlock.m_primitiveType == ExPT_FAN )
{
numprimitives -= 2;
}
else if( renderBlock.m_primitiveType == ExPT_LIST )
{
numprimitives /= 3;
}
primitive.m_primitiveType = PaExportSizes::GetTriangleType(renderBlock.m_primitiveType);
primitive.m_baseVertexIndex = nBaseVertex;
primitive.m_startIndex = nBaseIndex;
primitive.m_minIndex = 0;
primitive.m_numVertices = nVertices;
primitive.m_primitives = numprimitives;
primitive.m_numIndices = nIndices;
primitive.m_indexType = 0; // Not set for now
renderBlock.m_primitives.push_back( primitive );
}
int a=0;
a++;
}
}
}
////////////////////////////////////////////////////////////////////////////////
// ChangeCoordinateSystem
void ExSgMesh::ChangeCoordinateSystem()
{
// Cache the number of material blocks
BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size();
// Flatten the material blocks
for( BtU32 nMaterialBlock=0; nMaterialBlock<nMaterialBlocks; nMaterialBlock++ )
{
// Cache each material block
ExMaterialBlock* pMaterialBlock = m_materialBlocks[nMaterialBlock];
// Cache the number of vertex
BtU32 nVertex = (BtU32) pMaterialBlock->m_pVertex.size();
// Flip the z position
for( BtU32 i=0; i<nVertex; i++ )
{
ExVertex* pVertex = pMaterialBlock->m_pVertex[i];
pVertex->ChangeCoordinateSystem();
}
}
}
///////////////////////////////////////////////////////////////////////////////
// CopyAttributes
void ExSgMesh::CopyAttributes()
{
m_pNode->m_meshFileData.m_AABB = m_AABB;
m_pNode->m_meshFileData.m_sphere = m_sphere;
m_pNode->m_meshFileData.m_nMaterials = (BtU32) m_pNode->m_materialBlocks.size();
}
| 26.386167 | 104 | 0.63543 | GavWood |
56a2d79362bfcd984696b77159fef85d19d581d3 | 3,213 | hpp | C++ | include/tools/types/common/enable_for/enable_for-2013.hpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | null | null | null | include/tools/types/common/enable_for/enable_for-2013.hpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | 49 | 2021-02-20T12:08:15.000Z | 2021-05-07T19:59:08.000Z | include/tools/types/common/enable_for/enable_for-2013.hpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | null | null | null | // [2020y-09m-04d][00:00:00] Idrisov Denis R.
// [2021y-02m-20d][18:40:18] Idrisov Denis R.
// [2021y-04m-10d][01:40:31] Idrisov Denis R. 100
//==============================================================================
//==============================================================================
#pragma once
#ifndef dTOOLS_ENABLE_FOR_2013_USED_
#define dTOOLS_ENABLE_FOR_2013_USED_ 100,2013
#include <tools/types/common/find_type.hpp>
//==============================================================================
//=== degradate-2013 ===========================================================
#ifndef dTOOLS_DEGRADATE_USED_
namespace tools
{
template<class t> class degradate
{
using x = ::std::remove_reference_t<t>;
public:
using type = ::std::remove_cv_t<x>;
};
template<class t>
using degradate_t = ::std::remove_cv_t<
::std::remove_reference_t<t>
>;
#define ddegradate(...) degradate_t<__VA_ARGS__>
} // namespace tools
#endif // !dTOOLS_DEGRADATE_USED_
//==============================================================================
//=== enable_if_find/disable_if_find =============== (degradate)(find_type) ====
namespace tools
{
// if type 't' is in the list 'args' --> compile
template<class ret, class t, class ...args>
using enable_if_find_t
= ::std::enable_if_t<
::tools::find_type<
::tools::degradate_t<t>, args...
>::value, ret
>;
// if type 't' is not in the list 'args' --> compile
template<class ret, class t, class ...args>
using disable_if_find_t
= ::std::enable_if_t<
!::tools::find_type<
::tools::degradate_t<t>, args...
>::value, ret
>;
#define dif_enabled(r, ...) \
::tools::enable_if_find_t<r, __VA_ARGS__>
#define dif_disabled(r, ...) \
::tools::disable_if_find_t<r, __VA_ARGS__>
} // namespace tools
//==============================================================================
//=== enable_for/disable_for ======================= (degradate)(find_type) ====
namespace tools
{
// if type 't' is in the list 'args' --> compile
template<class t, class ...args>
using enable_for_t
= ::std::enable_if_t<
::tools::find_type<
::tools::degradate_t<t>, args...
>::value
>;
// if type 't' is not in the list 'args' --> compile
template<class t, class ...args>
using disable_for_t
= ::std::enable_if_t<
!::tools::find_type<
::tools::degradate_t<t>, args...
>::value
>;
#define dfor_enabled_impl(...) ::tools::enable_for_t <__VA_ARGS__>*
#define dfor_disabled_impl(...) ::tools::disable_for_t<__VA_ARGS__>*
#define dfor_enabled(...) dfor_enabled_impl(__VA_ARGS__) = nullptr
#define dfor_disabled(...) dfor_disabled_impl(__VA_ARGS__) = nullptr
} // namespace tools
//==============================================================================
//==============================================================================
#endif // !dTOOLS_ENABLE_FOR_2013_USED_
| 33.123711 | 80 | 0.473078 | Kartonagnick |
56a628812a09eb037c743d847d4d560ba873b605 | 34,550 | cpp | C++ | src/MainWindow.cpp | Furkanzmc/ofQMake | 5032cf904cac7b3ced363ecf2eca618c04c4aa37 | [
"Unlicense"
] | 5 | 2016-06-05T09:02:08.000Z | 2018-03-07T23:26:39.000Z | src/MainWindow.cpp | Furkanzmc/ofxQProjectGenerator | 5032cf904cac7b3ced363ecf2eca618c04c4aa37 | [
"Unlicense"
] | 2 | 2016-03-26T16:51:07.000Z | 2016-06-02T18:18:00.000Z | src/MainWindow.cpp | Furkanzmc/ofQProjectGenerator | 5032cf904cac7b3ced363ecf2eca618c04c4aa37 | [
"Unlicense"
] | 1 | 2018-07-08T03:21:31.000Z | 2018-07-08T03:21:31.000Z | #include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDirIterator>
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
#include <QDesktopServices>
#include <QListWidgetItem>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUuid>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_OFPath("")
, m_OFAddonsPath("")
, m_OFAppTemplatePath("")
, m_AppPath("")
, m_AddonsPath("")
, m_PriFile("./data/openFrameworks-0.8.4.pri")
, m_IsAppNameValid(false)
, m_IsOFPathValid(false)
, m_IsAppFolderValid(false)
, m_IsUpdateProject(false)
, m_OFVersion(0)
{
ui->setupUi(this);
this->setWindowTitle("ofxProjectGenerator");
connect(ui->listWidget, &QListWidget::itemClicked, this, &MainWindow::updateSelectedAddons);
connect(ui->lineEditOfPath, &QLineEdit::textChanged, this, &MainWindow::listAddonNames);
connect(ui->lineEditAppName, &QLineEdit::textChanged, this, &MainWindow::checkAppNameValidity);
connect(ui->lineEditAppPath, &QLineEdit::textChanged, this, &MainWindow::checkAppFolderValidity);
connect(ui->buttonOfPath, &QPushButton::pressed, this, &MainWindow::browseOFPath);
connect(ui->buttonAppPath, &QPushButton::pressed, this, &MainWindow::browseAppPath);
connect(ui->buttonGenerate, &QPushButton::pressed, this, &MainWindow::generateProject);
connect(ui->menuRecent_Projects, &QMenu::triggered, this, &MainWindow::recentProjectSelected);
connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeOfVersion(int)));
QSettings settings;
ui->lineEditOfPath->setText(settings.value("of_path").toString());
fillRecentsMenu();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::changeOfVersion(int currentIndex)
{
m_OFVersion = currentIndex;
if (currentIndex == 0) {
m_PriFile = "./data/openFrameworks-0.8.4.pri";
}
else {
m_PriFile = "./data/openFrameworks-0.9.pri";
}
}
void MainWindow::listAddonNames()
{
ui->listWidget->clear();
m_OFPath = ui->lineEditOfPath->text() + "/";
m_OFAddonsPath = m_OFPath + "addons/";
m_OFAppTemplatePath = m_OFPath + "apps/myApps/emptyExample/";
QDirIterator dirIteratorTop(m_OFAddonsPath, QDirIterator::NoIteratorFlags);
if (dirIteratorTop.hasNext() == false) {
ui->lineEditOfPath->setStyleSheet("color: red");
m_IsOFPathValid = false;
}
else {
ui->lineEditOfPath->setStyleSheet("");
m_IsOFPathValid = true;
QSettings settings;
settings.setValue("of_path", ui->lineEditOfPath->text());
settings.sync();
}
while (dirIteratorTop.hasNext()) {
dirIteratorTop.next();
if (dirIteratorTop.fileName() == "." || dirIteratorTop.fileName() == "..") {
continue;
}
QListWidgetItem *item = new QListWidgetItem(ui->listWidget);
item->setText(dirIteratorTop.fileName());
item->setCheckState(Qt::CheckState::Unchecked);
}
}
void MainWindow::checkAppNameValidity(const QString &str)
{
if (str.contains(" ") || str.length() == 0) {
ui->lineEditAppName->setStyleSheet("color: red");
m_IsAppNameValid = false;
}
else {
ui->lineEditAppName->setStyleSheet("");
m_IsAppNameValid = true;
}
}
void MainWindow::checkAppFolderValidity(const QString &str)
{
QDir dir(str);
if (str.length() == 0 || dir.exists() == false) {
ui->lineEditAppPath->setStyleSheet("color: red");
m_IsAppFolderValid = false;
}
else if (dir.exists()) {
ui->lineEditAppPath->setStyleSheet("");
m_IsAppFolderValid = true;
}
}
void MainWindow::browseOFPath()
{
QFileDialog dialog(this, "Select OF Path");
const QString selectedDir = dialog.getExistingDirectory();
ui->lineEditOfPath->setText(selectedDir);
}
void MainWindow::browseAppPath()
{
QFileDialog dialog(this, "Select App Path");
const QString selectedDir = dialog.getExistingDirectory();
ui->lineEditAppPath->setText(selectedDir);
}
void MainWindow::updateSelectedAddons(QListWidgetItem *selectedItem)
{
if (selectedItem == nullptr) {
for (int i = 0; i < ui->listWidget->count(); i++) {
QListWidgetItem *item = ui->listWidget->item(i);
item->setCheckState(m_SelectedAddons.contains(item->text()) ? Qt::Checked : Qt::Unchecked);
}
}
else {
if (selectedItem->checkState() == Qt::Checked && m_SelectedAddons.contains(selectedItem->text()) == false) {
m_SelectedAddons.append(selectedItem->text());
}
else if (selectedItem->checkState() == Qt::Unchecked && m_SelectedAddons.contains(selectedItem->text())) {
m_SelectedAddons.removeAt(m_SelectedAddons.indexOf(selectedItem->text()));
}
}
}
void MainWindow::generateProject()
{
const QString errStr = getErrorString();
if (errStr.length() > 0) {
QMessageBox::warning(this, "Error!", "Please correct the following misteke(s).\n" + errStr, QMessageBox::Ok);
return;
}
// Put them in varriables in case we add new types of projects
const bool isCMakeProject = ui->radioButtonCmake->isChecked();
const bool isQMakeProject = ui->radioButtonQmake->isChecked();
const bool isVSProject = ui->radioButtonVS->isChecked();
if (isCMakeProject && m_OFVersion == 0) {
QMessageBox::information(this, "Sorry... :(", "Version 0.8.4 is not yet supported with Cmake.");
return;
}
if (isVSProject && m_OFVersion == 0) {
QMessageBox::information(this, "Sorry... :(", "Version 0.8.4 is not yet supported with Visual Studio 2015.");
return;
}
copyOFTemplateFiles();
if (isCMakeProject) {
generateCMakeProject();
}
else if (isQMakeProject) {
generateQMakeProject();
}
else if (isVSProject) {
generateVSProject();
}
QFile folder(m_AppPath);
if (folder.exists()) {
QDesktopServices::openUrl(QUrl("file:///" + m_AppPath));
}
saveProjectToRecents();
fillRecentsMenu();
// Clear the fields AFTER the project is saved to recents
ui->statusBar->showMessage("Project generated", 5000);
ui->lineEditAppName->clear();
for (int i = 0; i < ui->listWidget->count(); i++) {
QListWidgetItem *item = ui->listWidget->item(i);
item->setCheckState(Qt::Unchecked);
}
}
void MainWindow::generateQMakeProject()
{
QFile priFile(m_PriFile);
QFile::copy("./data/proFileTemplate.pro", m_AppPath + ui->lineEditAppName->text() + ".pro");
QFile proFile(m_AppPath + ui->lineEditAppName->text() + ".pro");
if (proFile.exists() && proFile.open(QIODevice::ReadWrite)) {
QString contents = QString(proFile.readAll());
QString priFileName = m_PriFile;
contents.replace("#PRI_FILE#", priFileName.replace(m_PriFile.left(m_PriFile.lastIndexOf("/") + 1), ""));
proFile.resize(0);
proFile.write(contents.toStdString().c_str());
proFile.close();
}
if (priFile.exists() && priFile.open(QIODevice::ReadOnly)) {
QString contents = QString(priFile.readAll());
// Insert OF path
QString ofPathWithoutSuffix = m_OFPath;
contents.replace("#OF_PATH#", "\"" + ofPathWithoutSuffix.remove(ofPathWithoutSuffix.length() - 1, 1) + "\"");
contents.replace("#AR#", m_OFVersion == 1 ? "x64" : "Win32");
insertAddonsQMake(contents);
// Write the changed pri file to the new path
QFile newPriFile(m_AppPath + m_PriFile.right(m_PriFile.length() - m_PriFile.lastIndexOf("/")));
if (newPriFile.open(QIODevice::WriteOnly)) {
newPriFile.write(contents.toStdString().c_str());
newPriFile.close();
}
}
priFile.close();
}
void MainWindow::generateCMakeProject()
{
const QString projCmakeFile = "./data/project_CMakeLists.txt";
const QString findCmakeFile = "./data/findOpenFrameworks-v0.9.cmake";
const QString ofCmakeFile = "./data/of_CMakeLists.txt";
// Open projCmakeFile and change the OF_PATH and PROJ_NAME
QFile file(projCmakeFile);
if (file.exists() == false) {
QMessageBox::warning(this, "Error!", "./data/project_CMakeLists.txt file doesn't exist!");
return;
}
// These files don't require any change, so copy them as they are.
QFile::copy(ofCmakeFile, m_OFPath + "/CMakeLists.txt");
file.setFileName(findCmakeFile);
if (file.open(QIODevice::ReadOnly)) {
QString contents = QString(file.readAll());
contents.replace("${ARCHITECTURE}", m_OFVersion == 1 ? "x64" : "Win32");
QFile newFile(m_OFPath + "/findOpenFrameworks-v0.9.cmake");
if (newFile.open(QIODevice::WriteOnly)) {
newFile.write(contents.toUtf8());
newFile.close();
}
}
file.close();
file.setFileName(projCmakeFile);
if (file.open(QIODevice::ReadOnly)) {
QString contents = QString(file.readAll());
contents.replace("${PROJ_NAME}", ui->lineEditAppName->text());
contents.replace("${OPENFRAMEWORKS_PATH}", m_OFPath);
QFile newFile(m_AppPath + "/CMakeLists.txt");
if (newFile.exists() == false && newFile.open(QIODevice::WriteOnly)) {
newFile.write(contents.toUtf8());
newFile.close();
}
}
file.close();
insertAddonsCMake();
}
void MainWindow::generateVSProject()
{
const QString appName = ui->lineEditAppName->text();
const QString slnFile = m_AppPath + appName + ".sln";
const QString vcxprojFile = m_AppPath + appName + ".vcxproj";
QFile file(slnFile);
if (file.open(QIODevice::ReadOnly)) {
QString contents = QString(file.readAll());
contents.replace("${OF_PATH}", m_OFPath);
contents.replace("mySketch", ui->lineEditAppName->text());
file.close();
file.open(QIODevice::WriteOnly);
file.write(contents.toUtf8());
file.close();
}
file.setFileName(vcxprojFile);
if (file.open(QIODevice::ReadOnly)) {
QString contents = QString(file.readAll());
contents.replace("${OF_PATH}", m_OFPath);
contents.replace("mySketch", ui->lineEditAppName->text());
file.close();
file.open(QIODevice::WriteOnly);
file.write(contents.toUtf8());
file.close();
}
insertAddonsVS();
}
QString MainWindow::getErrorString() const
{
QString errStr;
if (m_IsAppNameValid == false) {
errStr += "* Type a valid app name";
}
if (m_IsAppFolderValid == false) {
errStr += "\n* Type a valid app path";
}
if (m_IsOFPathValid == false) {
errStr += "\n* Type a valid openFrameworks path";
}
return errStr;
}
void MainWindow::insertAddonsQMake(QString &priContent)
{
if (m_SelectedAddons.size() == 0) {
return;
}
bool isCopyEnabled = ui->checkBox->isChecked();
QString addonRootPath = m_OFAddonsPath;
if (isCopyEnabled) {
QDir dir(m_AppPath);
if (dir.exists()) {
dir.mkdir("addons");
m_AddonsPath = m_AppPath + "addons/";
}
addonRootPath = m_AddonsPath;
for (int i = 0; i < m_SelectedAddons.size(); i++) {
const QString currentAddonName = m_SelectedAddons.at(i);
const QString srcAddonPath = m_OFAddonsPath + currentAddonName;
QDir dir(m_AddonsPath);
dir.mkdir(currentAddonName);
copyRecursively(srcAddonPath + "/src", m_AddonsPath + currentAddonName);
copyRecursively(srcAddonPath + "/libs", m_AddonsPath + currentAddonName);
}
}
QStringList includePaths;
for (int i = 0; i < m_SelectedAddons.size(); i++) {
const QString addonName = m_SelectedAddons.at(i);
priContent += "#" + addonName + "\n";
const QString addonPath = addonRootPath + addonName;
QStringList folderList;
folderList.append("/src");
folderList.append("/libs");
if (isCopyEnabled) {
priContent += "INCLUDEPATH += \"$$PWD/addons/" + addonName + "/src/" + "\"\n";
QDir libsDir(addonPath + "/libs");
if (libsDir.exists()) {
priContent += "INCLUDEPATH += \"$$PWD/addons/" + addonName + "/libs/" + "\"\n";
}
}
else {
priContent += "INCLUDEPATH += \"$$OF/addons/" + addonName + "/src/" + "\"\n";
QDir libsDir(addonPath + "/libs");
if (libsDir.exists()) {
priContent += "INCLUDEPATH += \"$$OF/addons/" + addonName + "/libs/" + "\"\n";
}
}
foreach (const QString &folder, folderList) {
QDirIterator dirIt(addonPath + folder, QDirIterator::Subdirectories);
while (dirIt.hasNext()) {
dirIt.next();
if (dirIt.fileName() == "." || dirIt.fileName() == "..") {
continue;
}
QString filePath = isCopyEnabled ? dirIt.filePath().replace(m_AddonsPath, "$$PWD/addons/") : dirIt.filePath();
filePath.replace(addonRootPath, "$$OF/addons/");
if (dirIt.fileInfo().isDir()) {
if (includePaths.contains(dirIt.fileInfo().absoluteDir().absolutePath()) == false) {
priContent += "INCLUDEPATH += \"" + filePath + "\"\n";
}
continue;
}
if (dirIt.fileInfo().suffix() == "cpp") {
priContent += "SOURCES += \"" + filePath + "\"\n";
}
else if (dirIt.fileInfo().suffix() == "h") {
priContent += "HEADERS += \"" + filePath + "\"\n";
}
else if (dirIt.fileInfo().suffix() == "lib") {
priContent += "LIBS += \"" + filePath + "\"\n";
}
}
}
}
}
void MainWindow::insertAddonsCMake()
{
if (m_SelectedAddons.size() == 0) {
return;
}
QString content = "";
bool isCopyEnabled = ui->checkBox->isChecked();
QString addonRootPath = m_OFAddonsPath;
if (isCopyEnabled) {
QDir dir(m_AppPath);
if (dir.exists()) {
dir.mkdir("addons");
m_AddonsPath = m_AppPath + "addons/";
}
addonRootPath = m_AddonsPath;
for (int i = 0; i < m_SelectedAddons.size(); i++) {
const QString currentAddonName = m_SelectedAddons.at(i);
const QString srcAddonPath = m_OFAddonsPath + currentAddonName;
QDir dir(m_AddonsPath);
dir.mkdir(currentAddonName);
copyRecursively(srcAddonPath + "/src", m_AddonsPath + currentAddonName);
copyRecursively(srcAddonPath + "/libs", m_AddonsPath + currentAddonName);
}
}
for (int i = 0; i < m_SelectedAddons.size(); i++) {
QStringList sources, headers, libs;
QStringList includePaths;
const QString addonName = m_SelectedAddons.at(i);
content += "#" + addonName + "\n";
const QString addonPath = addonRootPath + addonName;
QStringList folderList;
folderList.append("/src");
folderList.append("/libs");
if (isCopyEnabled) {
includePaths.append("addons/" + addonName + "/src");
QDir libsDir(addonPath + "/libs");
if (libsDir.exists()) {
includePaths.append("addons/" + addonName + "/libs");
}
}
else {
includePaths.append("${ADDONS_PATH}/" + addonName + "/src");
QDir libsDir(addonPath + "/libs");
if (libsDir.exists()) {
includePaths.append("${ADDONS_PATH}/" + addonName + "/libs");
}
}
for (const QString &folder : folderList) {
QDirIterator dirIt(addonPath + folder, QDirIterator::Subdirectories);
while (dirIt.hasNext()) {
dirIt.next();
if (dirIt.fileName() == "." || dirIt.fileName() == "..") {
continue;
}
QString filePath = isCopyEnabled ? dirIt.filePath().replace(m_AddonsPath, "addons/") : dirIt.filePath();
filePath.replace(addonRootPath, "${ADDONS_PATH}/");
if (dirIt.fileInfo().isDir()) {
if (includePaths.contains(dirIt.fileInfo().absoluteDir().absolutePath()) == false) {
includePaths.append(filePath);
}
continue;
}
if (dirIt.fileInfo().suffix() == "cpp") {
sources.append(filePath);
}
else if (dirIt.fileInfo().suffix() == "h") {
headers.append(filePath);
}
else if (dirIt.fileInfo().suffix() == "lib") {
libs.append(filePath);
}
}
}
// Add the paths to the content
content += "list(APPEND ADDONS_SRC\n";
for (const QString &src : sources) {
content += src + "\n";
}
content += ")\n\n";
content += "list(APPEND ADDONS_HEADERS\n";
for (const QString &header : headers) {
content += header + "\n";
}
content += ")\n\n";
content += "list(APPEND ADDONS_INCLUDE_PATH\n";
for (const QString &inc : includePaths) {
content += inc + "\n";
}
content += ")\n\n";
content += "list(APPEND ADDONS_LIBS\n";
for (const QString &lib : libs) {
content += lib + "\n";
}
content += ")\n\n";
QFile file(m_AppPath + "/ofAddons.cmake");
if (file.open(QIODevice::WriteOnly)) {
file.write(content.toUtf8());
}
file.close();
}
}
void MainWindow::insertAddonsVS()
{
QFile file;
const QString appName = ui->lineEditAppName->text();
const QString vcxprojFile = m_AppPath + appName + ".vcxproj";
const QString vcxprojFiltersFile = m_AppPath + appName + ".vcxproj.filters";
if (m_SelectedAddons.size() == 0) {
file.setFileName(vcxprojFile);
if (file.open(QIODevice::ReadOnly)) {
QString vcxprojFileContent = QString(file.readAll());
vcxprojFileContent.replace(";${ADDONS_INCLUDE}", "<!-- ;${ADDONS_INCLUDE} -->");
vcxprojFileContent.replace(";${ADDONS_LIBS}", "<!-- ;${ADDONS_LIBS} -->");
vcxprojFileContent.replace(";${ADDONS_LIBS_DIRECTORIES}", "<!-- ;${ADDONS_LIBS_DIRECTORIES} -->");
vcxprojFileContent.replace("${ADDONS_SRC}", "<!-- ;${ADDONS_SRC} -->");
vcxprojFileContent.replace("${ADDONS_HEADERS}", "<!-- ;${ADDONS_HEADERS} -->");
file.close();
file.open(QIODevice::WriteOnly);
file.write(vcxprojFileContent.toUtf8());
file.close();
}
file.setFileName(vcxprojFiltersFile);
if (file.open(QIODevice::ReadOnly)) {
QString vcxprojFileContent = QString(file.readAll());
vcxprojFileContent.replace("${ADDONS_FILTER_SRC}", "<!-- ${ADDONS_FILTER_SRC} -->");
vcxprojFileContent.replace("${ADDONS_FILTERS}", "<!-- ${ADDONS_FILTERS} -->");
vcxprojFileContent.replace("${ADDONS_FILTER_HEADERS}", "<!-- ${ADDONS_FILTER_HEADERS} -->");
file.close();
file.open(QIODevice::WriteOnly);
file.write(vcxprojFileContent.toUtf8());
file.close();
}
return;
}
bool isCopyEnabled = ui->checkBox->isChecked();
QString addonRootPath = m_OFAddonsPath;
if (isCopyEnabled) {
QDir dir(m_AppPath);
if (dir.exists()) {
dir.mkdir("addons");
m_AddonsPath = m_AppPath + "addons/";
}
addonRootPath = m_AddonsPath;
for (int i = 0; i < m_SelectedAddons.size(); i++) {
const QString currentAddonName = m_SelectedAddons.at(i);
const QString srcAddonPath = m_OFAddonsPath + currentAddonName;
QDir dir(m_AddonsPath);
dir.mkdir(currentAddonName);
copyRecursively(srcAddonPath + "/src", m_AddonsPath + currentAddonName);
copyRecursively(srcAddonPath + "/libs", m_AddonsPath + currentAddonName);
}
}
for (int i = 0; i < m_SelectedAddons.size(); i++) {
QList<std::pair<QString, QString>> sources, headers;
QList<std::pair<QString, QString>> libs;
QStringList includePaths;
const QString addonName = m_SelectedAddons.at(i);
const QString addonPath = addonRootPath + addonName;
QStringList folderList;
folderList.append("/src");
folderList.append("/libs");
if (isCopyEnabled) {
includePaths.append("addons/" + addonName + "/src");
QDir libsDir(addonPath + "/libs");
if (libsDir.exists()) {
includePaths.append("addons/" + addonName + "/libs");
}
}
else {
includePaths.append(addonPath + "/src");
QDir libsDir(addonPath + "/libs");
if (libsDir.exists()) {
includePaths.append(addonPath + "/libs");
}
}
for (const QString &folder : folderList) {
QDirIterator dirIt(addonPath + folder, QDirIterator::Subdirectories);
while (dirIt.hasNext()) {
dirIt.next();
if (dirIt.fileName() == "." || dirIt.fileName() == "..") {
continue;
}
QString filePath = isCopyEnabled ? dirIt.filePath().replace(m_AddonsPath, "addons/") : dirIt.filePath();
if (dirIt.fileInfo().isDir()) {
if (includePaths.contains(dirIt.fileInfo().absoluteDir().absolutePath()) == false) {
includePaths.append(filePath);
}
continue;
}
if (dirIt.fileInfo().suffix() == "cpp") {
sources.append(std::make_pair(addonName, filePath));
}
else if (dirIt.fileInfo().suffix() == "h") {
headers.append(std::make_pair(addonName, filePath));
}
else if (dirIt.fileInfo().suffix() == "lib") {
libs.append(std::make_pair(dirIt.fileName(), dirIt.path()));
}
}
}
// Add the paths to the content
QString addonsSrc, addonsFilterSrc, addonsFiltersHeaders;
for (auto &src : sources) {
addonsSrc += "<ClCompile Include=\"" + src.second.replace("/", "\\") + "\"/>\n";
addonsFilterSrc += "<ClCompile Include=\"" + src.second.replace("/", "\\") + "\"><Filter>addons\\" + src.first + "</Filter></ClCompile>";
}
file.setFileName(vcxprojFile);
if (file.open(QIODevice::ReadOnly)) {
QString vcxprojFileContent = QString(file.readAll());
if (vcxprojFileContent.indexOf("<!-- ;${ADDONS_SRC}") > 0) {
vcxprojFileContent.replace("<!-- ;${ADDONS_SRC} -->", addonsSrc);
}
else {
vcxprojFileContent.replace("${ADDONS_SRC}", addonsSrc);
}
file.close();
file.open(QIODevice::WriteOnly);
file.write(vcxprojFileContent.toUtf8());
file.close();
}
QString addonsHeaders;
for (auto &header : headers) {
addonsHeaders += "<ClCompile Include=\"" + header.second.replace("/", "\\") + "\"/>\n";
addonsFiltersHeaders += "<ClCompile Include=\"" + header.second.replace("/", "\\") + "\"><Filter>addons\\" + header.first + "</Filter></ClCompile>";
}
file.setFileName(vcxprojFile);
if (file.open(QIODevice::ReadOnly)) {
QString vcxprojFileContent = QString(file.readAll());
if (vcxprojFileContent.indexOf("<!-- ;${ADDONS_HEADERS}") > 0) {
vcxprojFileContent.replace("<!-- ;${ADDONS_HEADERS} -->", addonsHeaders);
}
else {
vcxprojFileContent.replace("${ADDONS_HEADERS}", addonsHeaders);
}
file.close();
file.open(QIODevice::WriteOnly);
file.write(vcxprojFileContent.toUtf8());
file.close();
}
// Add include path
QString addonsIncludePath;
for (QString &inc : includePaths) {
addonsIncludePath += inc.replace("/", "\\") + ";";
}
file.setFileName(vcxprojFile);
if (file.open(QIODevice::ReadOnly)) {
QString vcxprojFileContent = QString(file.readAll());
if (vcxprojFileContent.indexOf("<!-- ;${ADDONS_INCLUDE}") > 0) {
vcxprojFileContent.replace("<!-- ;${ADDONS_INCLUDE} -->", addonsIncludePath);
}
else {
vcxprojFileContent.replace("${ADDONS_INCLUDE}", addonsIncludePath);
}
file.close();
file.open(QIODevice::WriteOnly);
file.write(vcxprojFileContent.toUtf8());
file.close();
}
QString addonsLibs, addonsLibsDirectories;
for (auto &lib : libs) {
addonsLibs += lib.first + ";";
addonsLibsDirectories += lib.second.replace("/", "\\") + ";";
}
file.setFileName(vcxprojFile);
if (file.open(QIODevice::ReadOnly)) {
QString vcxprojFileContent = QString(file.readAll());
if (libs.size() == 0) {
addonsLibs = "";
addonsLibsDirectories = "";
}
if (vcxprojFileContent.indexOf("<!-- ;${ADDONS_LIBS}") > 0) {
vcxprojFileContent.replace("<!-- ;${ADDONS_LIBS} -->", addonsLibs);
}
else {
vcxprojFileContent.replace("${ADDONS_LIBS}", addonsLibs);
}
if (vcxprojFileContent.indexOf("<!-- ;${ADDONS_LIBS_DIRECTORIES}") > 0) {
vcxprojFileContent.replace("<!-- ;${ADDONS_LIBS_DIRECTORIES} -->", addonsLibsDirectories);
}
else {
vcxprojFileContent.replace("${ADDONS_LIBS_DIRECTORIES}", addonsLibsDirectories);
}
file.close();
file.open(QIODevice::WriteOnly);
file.write(vcxprojFileContent.toUtf8());
file.close();
}
// Add filters
QString addonsFilters;
for (const QString &name : m_SelectedAddons) {
QString filter = "<Filter Include=\"addons\\" + name + "\">\n";
const QString uuid = QUuid::createUuid().toString();
filter += "<UniqueIdentifier>" + uuid + "</UniqueIdentifier>\n";
filter += "</Filter>";
addonsFilters += filter + "\n";
}
file.setFileName(vcxprojFiltersFile);
if (file.open(QIODevice::ReadOnly)) {
QString vcxprojFileContent = QString(file.readAll());
if (vcxprojFileContent.indexOf("<!-- ${ADDONS_FILTERS}") > 0) {
vcxprojFileContent.replace("<!-- ${ADDONS_FILTERS} -->", addonsFilters);
}
else {
vcxprojFileContent.replace("${ADDONS_FILTERS}", addonsFilters);
}
if (vcxprojFileContent.indexOf("<!-- ${ADDONS_FILTER_HEADERS}") > 0) {
vcxprojFileContent.replace("<!-- ${ADDONS_FILTER_HEADERS} -->", addonsFiltersHeaders);
}
else {
vcxprojFileContent.replace("${ADDONS_FILTER_HEADERS}", addonsFiltersHeaders);
}
if (vcxprojFileContent.indexOf("<!-- ${ADDONS_FILTER_SRC}") > 0) {
vcxprojFileContent.replace("<!-- ${ADDONS_FILTER_SRC} -->", addonsFilterSrc);
}
else {
vcxprojFileContent.replace("${ADDONS_FILTER_SRC}", addonsFilterSrc);
}
file.close();
file.open(QIODevice::WriteOnly);
file.write(vcxprojFileContent.toUtf8());
file.close();
}
}
}
bool MainWindow::copyRecursively(const QString &srcFilePath, const QString &tgtFilePath) const
{
QFileInfo srcFileInfo(srcFilePath);
if (srcFileInfo.isDir()) {
QDir targetDir(tgtFilePath);
if (targetDir.exists() == false) {
targetDir.cdUp();
}
if (!targetDir.mkdir(srcFileInfo.fileName())) {
return false;
}
targetDir.cd(srcFileInfo.fileName());
QDir sourceDir(srcFilePath);
QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
for (const QString &fileName : fileNames) {
const QString newSrcFilePath = srcFilePath + QLatin1Char('/') + fileName;
const QString newTgtFilePath = targetDir.absolutePath() + QLatin1Char('/') + fileName;
if (!copyRecursively(newSrcFilePath, newTgtFilePath)) {
return false;
}
}
}
else if (!QFile::copy(srcFilePath, tgtFilePath)) {
return false;
}
return true;
}
void MainWindow::copyOFTemplateFiles()
{
QDir dir(ui->lineEditAppPath->text() + "/");
// Create the project dir and copy the template
if (dir.exists()) {
dir.mkdir(ui->lineEditAppName->text());
m_AppPath = ui->lineEditAppPath->text() + "/" + ui->lineEditAppName->text() + "/";
if (ui->radioButtonVS->isChecked()) {
dir.mkpath(m_AppPath + "src");
QFile::copy(m_OFAppTemplatePath + "src/main.cpp", m_AppPath + "src/main.cpp");
QFile::copy(m_OFAppTemplatePath + "src/ofApp.cpp", m_AppPath + "src/ofApp.cpp");
QFile::copy(m_OFAppTemplatePath + "src/ofApp.h", m_AppPath + "src/ofApp.h");
const QString slnFile = "./data/vs/mySketch.sln";
const QString vcxprojFile = "./data/vs/mySketch.vcxproj";
const QString vcxprojFiltersFile = "./data/vs/mySketch.vcxproj.filters";
const QString vcxprojUserFile = "./data/vs/mySketch.vcxproj.user";
const QString appName = ui->lineEditAppName->text();
QFile::copy(m_OFAppTemplatePath + "icon.rc", m_AppPath + "icon.rc");
QFile::copy(slnFile, m_AppPath + appName + ".sln");
QFile::copy(vcxprojFile, m_AppPath + appName + ".vcxproj");
QFile::copy(vcxprojFiltersFile, m_AppPath + appName + ".vcxproj.filters");
QFile::copy(vcxprojUserFile, m_AppPath + appName + ".vcxproj.user");
}
else {
QFile::copy(m_OFAppTemplatePath + "src/main.cpp", m_AppPath + "main.cpp");
QFile::copy(m_OFAppTemplatePath + "src/ofApp.cpp", m_AppPath + "ofApp.cpp");
QFile::copy(m_OFAppTemplatePath + "src/ofApp.h", m_AppPath + "ofApp.h");
}
}
}
void MainWindow::saveProjectToRecents()
{
QSettings settings;
QJsonDocument doc = QJsonDocument::fromBinaryData(settings.value("recent").toByteArray());
QJsonArray array = doc.object()["projects"].toArray();
int existingIndex = -1;
for (int i = 0; i < array.size(); i++) {
const QJsonObject proj = array.at(i).toObject();
if (proj["app_path"].toString() == ui->lineEditAppPath->text()) {
existingIndex = i;
break;
}
}
QJsonObject obj;
obj["of_path"] = ui->lineEditOfPath->text();
obj["app_name"] = ui->lineEditAppName->text();
obj["app_path"] = ui->lineEditAppPath->text();
obj["selected_addons"] = QJsonArray::fromStringList(m_SelectedAddons);
if (ui->radioButtonCmake->isChecked()) {
obj["project_type"] = "cmake";
}
else if (ui->radioButtonQmake->isChecked()) {
obj["project_type"] = "qmake";
}
else if (ui->radioButtonVS->isChecked()) {
obj["project_type"] = "vs2015";
}
obj["of_version"] = ui->comboBox->currentIndex();
if (existingIndex == -1) {
array.push_back(obj);
}
else {
array[existingIndex] = obj;
}
obj = doc.object();
obj["projects"] = array;
doc.setObject(obj);
settings.setValue("recent", doc.toBinaryData());
}
void MainWindow::fillRecentsMenu()
{
QSettings settings;
const QJsonDocument doc = QJsonDocument::fromBinaryData(settings.value("recent").toByteArray());
const QJsonObject obj = doc.object();
m_RecentProjectArray = obj["projects"].toArray();
ui->menuRecent_Projects->clear();
for (int i = 0; i < m_RecentProjectArray.size(); i++) {
const QJsonObject proj = m_RecentProjectArray.at(i).toObject();
const QString title = proj["app_name"].toString() + ": " + proj["app_path"].toString();
ui->menuRecent_Projects->addAction(title);
}
}
QJsonObject MainWindow::getRecentProject(const QString &appPath)
{
QJsonObject obj;
for (int i = 0; i < m_RecentProjectArray.size(); i++) {
const QJsonObject proj = m_RecentProjectArray.at(i).toObject();
if (proj["app_path"].toString() == appPath) {
obj = proj;
break;
}
}
return obj;
}
void MainWindow::recentProjectSelected(QAction *selected)
{
QString apppath = selected->text();
const QJsonObject project = getRecentProject(apppath.right(apppath.length() - apppath.indexOf(":") - 2));
ui->lineEditAppName->setText(project["app_name"].toString());
ui->lineEditAppPath->setText(project["app_path"].toString());
ui->lineEditOfPath->setText(project["of_path"].toString());
ui->comboBox->setCurrentIndex(project["of_version"].toInt());
if (project["project_type"].toString() == "cmake") {
ui->radioButtonCmake->setChecked(true);
ui->radioButtonQmake->setChecked(false);
ui->radioButtonVS->setChecked(false);
}
else if (project["project_type"].toString() == "qmake") {
ui->radioButtonCmake->setChecked(false);
ui->radioButtonQmake->setChecked(true);
ui->radioButtonVS->setChecked(false);
}
else if (project["project_type"].toString() == "vs2015") {
ui->radioButtonCmake->setChecked(false);
ui->radioButtonQmake->setChecked(false);
ui->radioButtonVS->setChecked(true);
}
m_SelectedAddons = project["selected_addons"].toVariant().toStringList();
updateSelectedAddons();
}
| 36.292017 | 160 | 0.577279 | Furkanzmc |
56aae3da6b829bd45813dd50738c6642332e38ff | 1,705 | cpp | C++ | src/utils/data.cpp | jlorenze/asl_fixedwing | 9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef | [
"MIT"
] | 4 | 2021-06-28T17:30:55.000Z | 2022-03-18T09:04:35.000Z | src/utils/data.cpp | jlorenze/asl_fixedwing | 9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef | [
"MIT"
] | 1 | 2021-08-31T16:22:13.000Z | 2021-08-31T16:36:15.000Z | src/utils/data.cpp | jlorenze/asl_fixedwing | 9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef | [
"MIT"
] | null | null | null | /**
@file data.cpp
Helper functions for saving and loading data
*/
#include <utils/data.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <Eigen/Dense>
/** Save matrix to .csv file. */
void Data::save_matrix(const std::string& file_name, Eigen::MatrixXd matrix) {
const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,
Eigen::DontAlignCols, ", ", "\n");
std::ofstream file(file_name); // open a file to write
if (file.is_open())
{
file << matrix.format(CSVFormat);
file.close();
}
}
/** Load matrix from .csv file */
Eigen::MatrixXd Data::load_matrix(const std::string& file_name) {
std::ifstream file(file_name); // open a file to read
if (!file.good()) {
std::cerr << "File: " << file_name << " does not exist" << std::endl;
exit(1);
}
// Read through file and extract all data elements
std::string row;
int i = 0; // row counter
std::string entry;
std::vector<double> entries;
while (std::getline(file, row)) {
std::stringstream row_stream(row);
while (std::getline(row_stream, entry, ',')) {
entries.push_back(std::stod(entry));
}
i++; // increment row counter
}
// Convert vector into matrix of proper shape
return Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(entries.data(), i, entries.size() / i);
}
/** Load vector from .csv file */
Eigen::VectorXd Data::load_vector(const std::string& file_name) {
Eigen::MatrixXd M = Data::load_matrix(file_name);
return Eigen::Map<Eigen::VectorXd>(M.data(), M.rows());
}
| 30.446429 | 133 | 0.614663 | jlorenze |
56ab20a2bf8e3c57aec1f51f51c6986961530fad | 1,347 | cpp | C++ | 697_find_shortest_subarray/find_shortest_subarray.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | 697_find_shortest_subarray/find_shortest_subarray.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | 697_find_shortest_subarray/find_shortest_subarray.cpp | Mengsen-W/algorithm | 66216b8601e416343a2cc191bd0f2f12eb282262 | [
"BSD-3-Clause"
] | null | null | null | /*
* @Author: Mengsen.Wang
* @Date: 2021-02-20 09:07:09
* @Last Modified by: Mengsen.Wang
* @Last Modified time: 2021-02-20 09:17:11
*/
#include <cassert>
#include <vector>
using namespace std;
int find_shortest_subarray(vector<int>& nums) {
//统计每个元素出现的频率
vector<int> req(50000, 0);
//最大度
int d = 0;
//每个元素第一次出现的位置
vector<int> first(50000, -1);
//每个元素最后一次出现的位置
vector<int> last(50000, -1);
int res = nums.size();
for (int i = 0; i < nums.size(); i++) {
req[nums[i]]++;
d = max(d, req[nums[i]]);
if (first[nums[i]] == -1) first[nums[i]] = i;
last[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++) {
if (req[nums[i]] == d) {
res = min(res, last[nums[i]] - first[nums[i]] + 1);
}
}
return res;
}
int main() {
vector<int> nums{};
nums = {1, 2, 2, 3, 1};
assert(find_shortest_subarray(nums) == 2);
nums = {1, 2, 2, 3, 1};
assert(find_shortest_subarray(nums) == 2);
nums = {1, 2, 2, 3};
assert(find_shortest_subarray(nums) == 2);
nums = {2, 2, 3, 1};
assert(find_shortest_subarray(nums) == 2);
nums = {1, 2, 2};
assert(find_shortest_subarray(nums) == 2);
nums = {2, 2, 3};
assert(find_shortest_subarray(nums) == 2);
nums = {2, 2};
assert(find_shortest_subarray(nums) == 2);
nums = {1, 2, 2, 3, 1, 4, 2};
assert(find_shortest_subarray(nums) == 6);
} | 24.490909 | 57 | 0.576095 | Mengsen-W |
56af4c64ed918d38fa3cfc169426d4d03daaf752 | 164,443 | cpp | C++ | Co-Simulation/Sumo/sumo-1.7.0/src/netedit/elements/additional/GNEAdditionalHandler.cpp | uruzahe/carla | 940c2ab23cce1eda1ef66de35f66b42d40865fb1 | [
"MIT"
] | null | null | null | Co-Simulation/Sumo/sumo-1.7.0/src/netedit/elements/additional/GNEAdditionalHandler.cpp | uruzahe/carla | 940c2ab23cce1eda1ef66de35f66b42d40865fb1 | [
"MIT"
] | null | null | null | Co-Simulation/Sumo/sumo-1.7.0/src/netedit/elements/additional/GNEAdditionalHandler.cpp | uruzahe/carla | 940c2ab23cce1eda1ef66de35f66b42d40865fb1 | [
"MIT"
] | null | null | null | /****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file GNEAdditionalHandler.cpp
/// @author Pablo Alvarez Lopez
/// @date Nov 2015
///
// Builds trigger objects for netedit
/****************************************************************************/
#include <config.h>
#include <utils/xml/XMLSubSys.h>
#include <netedit/changes/GNEChange_Additional.h>
#include <netedit/changes/GNEChange_TAZElement.h>
#include <netedit/GNEViewNet.h>
#include <netedit/GNEUndoList.h>
#include <netedit/GNENet.h>
#include <utils/options/OptionsCont.h>
#include <utils/vehicle/SUMORouteHandler.h>
#include "GNEAdditionalHandler.h"
#include "GNEBusStop.h"
#include "GNEAccess.h"
#include "GNECalibrator.h"
#include "GNECalibratorFlow.h"
#include "GNEChargingStation.h"
#include "GNEClosingLaneReroute.h"
#include "GNEClosingReroute.h"
#include "GNEContainerStop.h"
#include "GNEDestProbReroute.h"
#include "GNEDetectorE1.h"
#include "GNEDetectorE2.h"
#include "GNEDetectorE3.h"
#include "GNEDetectorEntryExit.h"
#include "GNEDetectorE1Instant.h"
#include "GNEParkingArea.h"
#include "GNEParkingSpace.h"
#include "GNERerouter.h"
#include "GNERerouterSymbol.h"
#include "GNERerouterInterval.h"
#include "GNERouteProbReroute.h"
#include "GNEParkingAreaReroute.h"
#include "GNERouteProbe.h"
#include "GNEVaporizer.h"
#include "GNEVariableSpeedSign.h"
#include "GNEVariableSpeedSignSymbol.h"
#include "GNEVariableSpeedSignStep.h"
#include "GNETAZ.h"
#include "GNETAZSourceSink.h"
// ===========================================================================
// GNEAdditionalHandler method definitions
// ===========================================================================
GNEAdditionalHandler::GNEAdditionalHandler(const std::string& file, GNENet* net, GNEAdditional* additionalParent) :
ShapeHandler(file, *net->getAttributeCarriers()),
myNet(net) {
myLastInsertedElement = new LastInsertedElement();
// check if we're loading values of another additionals (example: Rerouter values)
if (additionalParent) {
myLastInsertedElement->insertElement(additionalParent->getTagProperty().getTag());
myLastInsertedElement->commitAdditionalInsertion(additionalParent);
}
// define default values for shapes
setDefaults("", RGBColor::RED, Shape::DEFAULT_LAYER_POI, true);
}
GNEAdditionalHandler::~GNEAdditionalHandler() {
delete myLastInsertedElement;
}
void
GNEAdditionalHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) {
// Obtain tag of element
SumoXMLTag tag = static_cast<SumoXMLTag>(element);
// check if we're parsing a parameter
if (tag == SUMO_TAG_PARAM) {
// push element int stack
myLastInsertedElement->insertElement(tag);
// parse parameter
parseParameter(attrs);
} else if (tag != SUMO_TAG_NOTHING) {
// push element int stack
if (tag == SUMO_TAG_TRAIN_STOP) {
// ensure that access elements can find their parent in myLastInsertedElement
tag = SUMO_TAG_BUS_STOP;
}
myLastInsertedElement->insertElement(tag);
// Call parse and build depending of tag
switch (tag) {
case SUMO_TAG_POLY:
return parseAndBuildPoly(attrs);
case SUMO_TAG_POI:
return parseAndBuildPOI(attrs);
default:
// build additional
buildAdditional(myNet, true, tag, attrs, myLastInsertedElement);
}
}
}
void
GNEAdditionalHandler::myEndElement(int element) {
// Obtain tag of element
SumoXMLTag tag = static_cast<SumoXMLTag>(element);
switch (tag) {
case SUMO_TAG_TAZ: {
GNETAZElement* TAZ = myLastInsertedElement->getLastInsertedTAZElement();
if (TAZ != nullptr) {
if (TAZ->getTAZElementShape().size() == 0) {
Boundary b;
if (TAZ->getChildAdditionals().size() > 0) {
for (const auto& i : TAZ->getChildAdditionals()) {
b.add(i->getCenteringBoundary());
}
PositionVector boundaryShape;
boundaryShape.push_back(Position(b.xmin(), b.ymin()));
boundaryShape.push_back(Position(b.xmax(), b.ymin()));
boundaryShape.push_back(Position(b.xmax(), b.ymax()));
boundaryShape.push_back(Position(b.xmin(), b.ymax()));
boundaryShape.push_back(Position(b.xmin(), b.ymin()));
TAZ->setAttribute(SUMO_ATTR_SHAPE, toString(boundaryShape), myNet->getViewNet()->getUndoList());
}
}
}
break;
}
default:
break;
}
// pop last inserted element
myLastInsertedElement->popElement();
// execute myEndElement of ShapeHandler (needed to update myLastParameterised)
ShapeHandler::myEndElement(element);
}
Position
GNEAdditionalHandler::getLanePos(const std::string& poiID, const std::string& laneID, double lanePos, double lanePosLat) {
std::string edgeID;
int laneIndex;
NBHelpers::interpretLaneID(laneID, edgeID, laneIndex);
NBEdge* edge = myNet->retrieveEdge(edgeID)->getNBEdge();
if (edge == nullptr || laneIndex < 0 || edge->getNumLanes() <= laneIndex) {
WRITE_ERROR("Lane '" + laneID + "' to place poi '" + poiID + "' on is not known.");
return Position::INVALID;
}
if (lanePos < 0) {
lanePos = edge->getLength() + lanePos;
}
if (lanePos < 0 || lanePos > edge->getLength()) {
WRITE_WARNING("lane position " + toString(lanePos) + " for poi '" + poiID + "' is not valid.");
}
return edge->getLanes()[laneIndex].shape.positionAtOffset(lanePos, -lanePosLat);
}
bool
GNEAdditionalHandler::buildAdditional(GNENet* net, bool allowUndoRedo, SumoXMLTag tag, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
// Call parse and build depending of tag
switch (tag) {
case SUMO_TAG_BUS_STOP:
case SUMO_TAG_TRAIN_STOP:
return parseAndBuildBusStop(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_ACCESS:
return parseAndBuildAccess(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_CONTAINER_STOP:
return parseAndBuildContainerStop(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_CHARGING_STATION:
return parseAndBuildChargingStation(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_E1DETECTOR:
case SUMO_TAG_INDUCTION_LOOP:
return parseAndBuildDetectorE1(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_E2DETECTOR:
case SUMO_TAG_E2DETECTOR_MULTILANE:
case SUMO_TAG_LANE_AREA_DETECTOR:
return parseAndBuildDetectorE2(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_E3DETECTOR:
case SUMO_TAG_ENTRY_EXIT_DETECTOR:
return parseAndBuildDetectorE3(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_DET_ENTRY:
return parseAndBuildDetectorEntry(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_DET_EXIT:
return parseAndBuildDetectorExit(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_INSTANT_INDUCTION_LOOP:
return parseAndBuildDetectorE1Instant(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_ROUTEPROBE:
return parseAndBuildRouteProbe(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_VAPORIZER:
return parseAndBuildVaporizer(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_TAZ:
return parseAndBuildTAZ(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_TAZSOURCE:
return parseAndBuildTAZSource(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_TAZSINK:
return parseAndBuildTAZSink(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_VSS:
return parseAndBuildVariableSpeedSign(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_STEP:
return parseAndBuildVariableSpeedSignStep(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_CALIBRATOR:
case SUMO_TAG_LANECALIBRATOR:
return parseAndBuildCalibrator(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_PARKING_AREA:
return parseAndBuildParkingArea(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_PARKING_SPACE:
return parseAndBuildParkingSpace(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_FLOW_CALIBRATOR:
return parseAndBuildCalibratorFlow(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_REROUTER:
return parseAndBuildRerouter(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_INTERVAL:
return parseAndBuildRerouterInterval(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_CLOSING_LANE_REROUTE:
return parseAndBuildRerouterClosingLaneReroute(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_CLOSING_REROUTE:
return parseAndBuildRerouterClosingReroute(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_DEST_PROB_REROUTE:
return parseAndBuildRerouterDestProbReroute(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_PARKING_ZONE_REROUTE:
return parseAndBuildRerouterParkingAreaReroute(net, allowUndoRedo, attrs, insertedAdditionals);
case SUMO_TAG_ROUTE_PROB_REROUTE:
return parseAndBuildRerouterRouteProbReroute(net, allowUndoRedo, attrs, insertedAdditionals);
default:
return false;
}
}
GNEAdditional*
GNEAdditionalHandler::buildBusStop(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane,
const double startPos, const double endPos, const int parametersSet,
const std::string& name, const std::vector<std::string>& lines, int personCapacity, double parkingLength,
bool friendlyPosition, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_BUS_STOP, id, false) == nullptr) {
GNEAdditional* busStop = new GNEBusStop(id, lane, net, startPos, endPos, parametersSet, name, lines, personCapacity, parkingLength, friendlyPosition, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_BUS_STOP));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(busStop, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(busStop);
lane->addChildElement(busStop);
busStop->incRef("buildBusStop");
}
return busStop;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_BUS_STOP) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildAccess(GNENet* net, bool allowUndoRedo, GNEAdditional* busStop, GNELane* lane, double pos, const std::string& length, bool friendlyPos, bool blockMovement) {
// Check if busStop parent and lane is correct
if (lane == nullptr) {
throw ProcessError("Could not build " + toString(SUMO_TAG_ACCESS) + " in netedit; " + toString(SUMO_TAG_LANE) + " doesn't exist.");
} else if (busStop == nullptr) {
throw ProcessError("Could not build " + toString(SUMO_TAG_ACCESS) + " in netedit; " + toString(SUMO_TAG_BUS_STOP) + " parent doesn't exist.");
} else if (!accessCanBeCreated(busStop, lane->getParentEdge())) {
throw ProcessError("Could not build " + toString(SUMO_TAG_ACCESS) + " in netedit; " + toString(SUMO_TAG_BUS_STOP) + " parent already owns a Acces in the edge '" + lane->getParentEdge()->getID() + "'");
} else {
GNEAdditional* access = new GNEAccess(busStop, lane, net, pos, length, friendlyPos, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_ACCESS));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(access, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(access);
lane->addChildElement(access);
busStop->addChildElement(access);
access->incRef("buildAccess");
}
return access;
}
}
GNEAdditional*
GNEAdditionalHandler::buildContainerStop(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane, const double startPos, const double endPos, const int parametersSet,
const std::string& name, const std::vector<std::string>& lines, bool friendlyPosition, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_CONTAINER_STOP, id, false) == nullptr) {
GNEAdditional* containerStop = new GNEContainerStop(id, lane, net, startPos, endPos, parametersSet, name, lines, friendlyPosition, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_CONTAINER_STOP));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(containerStop, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(containerStop);
lane->addChildElement(containerStop);
containerStop->incRef("buildContainerStop");
}
return containerStop;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_CONTAINER_STOP) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildChargingStation(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane, const double startPos, const double endPos, const int parametersSet,
const std::string& name, double chargingPower, double efficiency, bool chargeInTransit, SUMOTime chargeDelay, bool friendlyPosition, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_CHARGING_STATION, id, false) == nullptr) {
GNEAdditional* chargingStation = new GNEChargingStation(id, lane, net, startPos, endPos, parametersSet, name, chargingPower, efficiency, chargeInTransit, chargeDelay, friendlyPosition, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_CHARGING_STATION));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(chargingStation, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(chargingStation);
lane->addChildElement(chargingStation);
chargingStation->incRef("buildChargingStation");
}
return chargingStation;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_CHARGING_STATION) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildParkingArea(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane, const double startPos, const double endPos, const int parametersSet,
const std::string& name, bool friendlyPosition, int roadSideCapacity, bool onRoad, double width, const std::string& length, double angle, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_PARKING_AREA, id, false) == nullptr) {
GNEAdditional* parkingArea = new GNEParkingArea(id, lane, net, startPos, endPos, parametersSet, name, friendlyPosition, roadSideCapacity, onRoad, width, length, angle, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_PARKING_AREA));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(parkingArea, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(parkingArea);
lane->addChildElement(parkingArea);
parkingArea->incRef("buildParkingArea");
}
return parkingArea;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_PARKING_AREA) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildParkingSpace(GNENet* net, bool allowUndoRedo, GNEAdditional* parkingAreaParent, Position pos, double width, double length, double angle, bool blockMovement) {
GNEAdditional* parkingSpace = new GNEParkingSpace(net, parkingAreaParent, pos, width, length, angle, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_PARKING_SPACE));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(parkingSpace, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(parkingSpace);
parkingAreaParent->addChildElement(parkingSpace);
parkingSpace->incRef("buildParkingSpace");
}
return parkingSpace;
}
GNEAdditional*
GNEAdditionalHandler::buildDetectorE1(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane, double pos, SUMOTime freq, const std::string& filename, const std::string& vehicleTypes, const std::string& name, bool friendlyPos, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_E1DETECTOR, id, false) == nullptr) {
GNEAdditional* detectorE1 = new GNEDetectorE1(id, lane, net, pos, freq, filename, vehicleTypes, name, friendlyPos, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_E1DETECTOR));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(detectorE1, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(detectorE1);
lane->addChildElement(detectorE1);
detectorE1->incRef("buildDetectorE1");
}
return detectorE1;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_E1DETECTOR) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildSingleLaneDetectorE2(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane, double pos, double length, const std::string& freq, const std::string& trafficLight,
const std::string& filename, const std::string& vehicleTypes, const std::string& name, SUMOTime timeThreshold, double speedThreshold, double jamThreshold, bool friendlyPos, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_E2DETECTOR, id, false) == nullptr) {
GNEAdditional* detectorE2 = new GNEDetectorE2(id, lane, net, pos, length, freq, trafficLight, filename, vehicleTypes, name, timeThreshold, speedThreshold, jamThreshold, friendlyPos, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_E2DETECTOR));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(detectorE2, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(detectorE2);
lane->addChildElement(detectorE2);
detectorE2->incRef("buildDetectorE2");
}
return detectorE2;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_E2DETECTOR) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildMultiLaneDetectorE2(GNENet* net, bool allowUndoRedo, const std::string& id, const std::vector<GNELane*>& lanes, double pos, double endPos, const std::string& freq, const std::string& trafficLight,
const std::string& filename, const std::string& vehicleTypes, const std::string& name, SUMOTime timeThreshold, double speedThreshold, double jamThreshold, bool friendlyPos, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_E2DETECTOR_MULTILANE, id, false) == nullptr) {
GNEDetectorE2* detectorE2 = new GNEDetectorE2(id, lanes, net, pos, endPos, freq, trafficLight, filename, vehicleTypes, name, timeThreshold, speedThreshold, jamThreshold, friendlyPos, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_E2DETECTOR_MULTILANE));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(detectorE2, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(detectorE2);
// use to avoid LNK2019
GNEAdditional* detectorE2Additional = detectorE2;
for (const auto& lane : lanes) {
lane->addChildElement(detectorE2Additional);
}
detectorE2->incRef("buildDetectorE2Multilane");
}
return detectorE2;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_E2DETECTOR_MULTILANE) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildDetectorE3(GNENet* net, bool allowUndoRedo, const std::string& id, Position pos, SUMOTime freq, const std::string& filename, const std::string& vehicleTypes,
const std::string& name, SUMOTime timeThreshold, double speedThreshold, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_E3DETECTOR, id, false) == nullptr) {
GNEAdditional* detectorE3 = new GNEDetectorE3(id, net, pos, freq, filename, vehicleTypes, name, timeThreshold, speedThreshold, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_E3DETECTOR));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(detectorE3, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(detectorE3);
detectorE3->incRef("buildDetectorE3");
}
return detectorE3;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_E3DETECTOR) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildDetectorEntry(GNENet* net, bool allowUndoRedo, GNEAdditional* E3Parent, GNELane* lane, double pos, bool friendlyPos, bool blockMovement) {
// Check if Detector E3 parent and lane is correct
if (lane == nullptr) {
throw ProcessError("Could not build " + toString(SUMO_TAG_DET_ENTRY) + " in netedit; " + toString(SUMO_TAG_LANE) + " doesn't exist.");
} else if (E3Parent == nullptr) {
throw ProcessError("Could not build " + toString(SUMO_TAG_DET_ENTRY) + " in netedit; " + toString(SUMO_TAG_E3DETECTOR) + " parent doesn't exist.");
} else {
GNEAdditional* entry = new GNEDetectorEntryExit(SUMO_TAG_DET_ENTRY, net, E3Parent, lane, pos, friendlyPos, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_DET_ENTRY));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(entry, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(entry);
lane->addChildElement(entry);
E3Parent->addChildElement(entry);
entry->incRef("buildDetectorEntry");
}
return entry;
}
}
GNEAdditional*
GNEAdditionalHandler::buildDetectorExit(GNENet* net, bool allowUndoRedo, GNEAdditional* E3Parent, GNELane* lane, double pos, bool friendlyPos, bool blockMovement) {
// Check if Detector E3 parent and lane is correct
if (lane == nullptr) {
throw ProcessError("Could not build " + toString(SUMO_TAG_DET_EXIT) + " in netedit; " + toString(SUMO_TAG_LANE) + " doesn't exist.");
} else if (E3Parent == nullptr) {
throw ProcessError("Could not build " + toString(SUMO_TAG_DET_EXIT) + " in netedit; " + toString(SUMO_TAG_E3DETECTOR) + " parent doesn't exist.");
} else {
GNEAdditional* exit = new GNEDetectorEntryExit(SUMO_TAG_DET_EXIT, net, E3Parent, lane, pos, friendlyPos, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_DET_EXIT));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(exit, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(exit);
lane->addChildElement(exit);
E3Parent->addChildElement(exit);
exit->incRef("buildDetectorExit");
}
return exit;
}
}
GNEAdditional*
GNEAdditionalHandler::buildDetectorE1Instant(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane, double pos, const std::string& filename, const std::string& vehicleTypes, const std::string& name, bool friendlyPos, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_INSTANT_INDUCTION_LOOP, id, false) == nullptr) {
GNEAdditional* detectorE1Instant = new GNEDetectorE1Instant(id, lane, net, pos, filename, vehicleTypes, name, friendlyPos, blockMovement);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_INSTANT_INDUCTION_LOOP));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(detectorE1Instant, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(detectorE1Instant);
lane->addChildElement(detectorE1Instant);
detectorE1Instant->incRef("buildDetectorE1Instant");
}
return detectorE1Instant;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_INSTANT_INDUCTION_LOOP) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildCalibrator(GNENet* net, bool allowUndoRedo, const std::string& id, GNELane* lane, double pos, const std::string& name, const std::string& outfile, const SUMOTime freq, const std::string& routeprobe, bool centerAfterCreation) {
if (net->retrieveAdditional(SUMO_TAG_CALIBRATOR, id, false) == nullptr) {
GNEAdditional* calibrator = new GNECalibrator(id, net, lane, pos, freq, name, outfile, routeprobe);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_CALIBRATOR));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(calibrator, true), true);
net->getViewNet()->getUndoList()->p_end();
// center after creation
if (centerAfterCreation) {
net->getViewNet()->centerTo(calibrator->getPositionInView(), false);
}
} else {
net->getAttributeCarriers()->insertAdditional(calibrator);
lane->addChildElement(calibrator);
calibrator->incRef("buildCalibrator");
}
return calibrator;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_CALIBRATOR) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildCalibrator(GNENet* net, bool allowUndoRedo, const std::string& id, GNEEdge* edge, double pos, const std::string& name, const std::string& outfile, const SUMOTime freq, const std::string& routeprobe, bool centerAfterCreation) {
if (net->retrieveAdditional(SUMO_TAG_CALIBRATOR, id, false) == nullptr) {
GNEAdditional* calibrator = new GNECalibrator(id, net, edge, pos, freq, name, outfile, routeprobe);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_CALIBRATOR));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(calibrator, true), true);
net->getViewNet()->getUndoList()->p_end();
// center after creation
if (centerAfterCreation) {
net->getViewNet()->centerTo(calibrator->getPositionInView(), false);
}
} else {
net->getAttributeCarriers()->insertAdditional(calibrator);
edge->addChildElement(calibrator);
calibrator->incRef("buildCalibrator");
}
return calibrator;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_CALIBRATOR) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildCalibratorFlow(GNENet* net, bool allowUndoRedo, GNEAdditional* calibratorParent, GNEDemandElement* route, GNEDemandElement* vType,
const std::string& vehsPerHour, const std::string& speed, const RGBColor& color, const std::string& departLane, const std::string& departPos,
const std::string& departSpeed, const std::string& arrivalLane, const std::string& arrivalPos, const std::string& arrivalSpeed, const std::string& line,
int personNumber, int containerNumber, bool reroute, const std::string& departPosLat, const std::string& arrivalPosLat, SUMOTime begin, SUMOTime end) {
// create Flow and add it to calibrator parent
GNEAdditional* flow = new GNECalibratorFlow(calibratorParent, vType, route, vehsPerHour, speed, color, departLane, departPos, departSpeed,
arrivalLane, arrivalPos, arrivalSpeed, line, personNumber, containerNumber, reroute,
departPosLat, arrivalPosLat, begin, end);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + flow->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(flow, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
calibratorParent->addChildElement(flow);
flow->incRef("buildCalibratorFlow");
}
return flow;
}
GNEAdditional*
GNEAdditionalHandler::buildRerouter(GNENet* net, bool allowUndoRedo, const std::string& id, Position pos, const std::vector<GNEEdge*>& edges, double prob, const std::string& name, const std::string& file, bool off, SUMOTime timeThreshold, const std::string& vTypes, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_REROUTER, id, false) == nullptr) {
// create reroute
GNEAdditional* rerouter = new GNERerouter(id, net, pos, name, file, prob, off, timeThreshold, vTypes, blockMovement);
// create rerouter Symbols
std::vector<GNEAdditional*> rerouterSymbols;
for (const auto& edge : edges) {
rerouterSymbols.push_back(new GNERerouterSymbol(rerouter, edge));
}
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_REROUTER));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(rerouter, true), true);
for (const auto& rerouterSymbol : rerouterSymbols) {
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(rerouterSymbol, true), true);
}
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(rerouter);
// add symbols
for (int i = 0; i < (int)edges.size(); i++) {
edges.at(i)->addChildElement(rerouterSymbols.at(i));
rerouterSymbols.at(i)->incRef("buildRerouterSymbol");
}
rerouter->incRef("buildRerouter");
}
// parse rerouter children
if (!file.empty()) {
// we assume that rerouter values files is placed in the same folder as the additional file
std::string currentAdditionalFilename = FileHelpers::getFilePath(OptionsCont::getOptions().getString("additional-files"));
// Create additional handler for parse rerouter values
GNEAdditionalHandler rerouterValuesHandler(currentAdditionalFilename + file, net, rerouter);
// disable validation for rerouters
XMLSubSys::setValidation("never", "auto", "auto");
// Run parser
if (!XMLSubSys::runParser(rerouterValuesHandler, currentAdditionalFilename + file, false)) {
WRITE_MESSAGE("Loading of " + file + " failed.");
}
// enable validation for rerouters
XMLSubSys::setValidation("auto", "auto", "auto");
}
return rerouter;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_REROUTER) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildRerouterInterval(GNENet* net, bool allowUndoRedo, GNEAdditional* rerouterParent, SUMOTime begin, SUMOTime end) {
// check if new interval will produce a overlapping
if (checkOverlappingRerouterIntervals(rerouterParent, begin, end)) {
// create rerouter interval and add it into rerouter parent
GNEAdditional* rerouterInterval = new GNERerouterInterval(rerouterParent, begin, end);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + rerouterInterval->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(rerouterInterval, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
rerouterParent->addChildElement(rerouterInterval);
rerouterInterval->incRef("buildRerouterInterval");
}
return rerouterInterval;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_INTERVAL) + " with begin '" + toString(begin) + "' and '" + toString(end) + "' in '" + rerouterParent->getID() + "' due overlapping.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildClosingLaneReroute(GNENet* net, bool allowUndoRedo, GNEAdditional* rerouterIntervalParent, GNELane* closedLane, SVCPermissions permissions) {
// create closing lane reorute
GNEAdditional* closingLaneReroute = new GNEClosingLaneReroute(rerouterIntervalParent, closedLane, permissions);
// add it to interval parent depending of allowUndoRedo
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + closingLaneReroute->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(closingLaneReroute, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
rerouterIntervalParent->addChildElement(closingLaneReroute);
closingLaneReroute->incRef("buildClosingLaneReroute");
}
return closingLaneReroute;
}
GNEAdditional*
GNEAdditionalHandler::buildClosingReroute(GNENet* net, bool allowUndoRedo, GNEAdditional* rerouterIntervalParent, GNEEdge* closedEdge, SVCPermissions permissions) {
// create closing reroute
GNEAdditional* closingReroute = new GNEClosingReroute(rerouterIntervalParent, closedEdge, permissions);
// add it to interval parent depending of allowUndoRedo
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + closingReroute->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(closingReroute, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
rerouterIntervalParent->addChildElement(closingReroute);
closingReroute->incRef("buildClosingReroute");
}
return closingReroute;
}
GNEAdditional*
GNEAdditionalHandler::builDestProbReroute(GNENet* net, bool allowUndoRedo, GNEAdditional* rerouterIntervalParent, GNEEdge* newEdgeDestination, double probability) {
// create dest probability reroute
GNEAdditional* destProbReroute = new GNEDestProbReroute(rerouterIntervalParent, newEdgeDestination, probability);
// add it to interval parent depending of allowUndoRedo
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + destProbReroute->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(destProbReroute, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
rerouterIntervalParent->addChildElement(destProbReroute);
destProbReroute->incRef("builDestProbReroute");
}
return destProbReroute;
}
GNEAdditional*
GNEAdditionalHandler::builParkingAreaReroute(GNENet* net, bool allowUndoRedo, GNEAdditional* rerouterIntervalParent, GNEAdditional* newParkingArea, double probability, bool visible) {
// create dest probability reroute
GNEAdditional* parkingAreaReroute = new GNEParkingAreaReroute(rerouterIntervalParent, newParkingArea, probability, visible);
// add it to interval parent depending of allowUndoRedo
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + parkingAreaReroute->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(parkingAreaReroute, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
rerouterIntervalParent->addChildElement(parkingAreaReroute);
parkingAreaReroute->incRef("builParkingAreaReroute");
}
return parkingAreaReroute;
}
GNEAdditional*
GNEAdditionalHandler::buildRouteProbReroute(GNENet* net, bool allowUndoRedo, GNEAdditional* rerouterIntervalParent, const std::string& newRouteId, double probability) {
// create rout prob rereoute
GNEAdditional* routeProbReroute = new GNERouteProbReroute(rerouterIntervalParent, newRouteId, probability);
// add it to interval parent depending of allowUndoRedo
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + routeProbReroute->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(routeProbReroute, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
rerouterIntervalParent->addChildElement(routeProbReroute);
routeProbReroute->incRef("buildRouteProbReroute");
}
return routeProbReroute;
}
GNEAdditional*
GNEAdditionalHandler::buildRouteProbe(GNENet* net, bool allowUndoRedo, const std::string& id, GNEEdge* edge, const std::string& freq, const std::string& name, const std::string& file, SUMOTime begin, bool centerAfterCreation) {
if (net->retrieveAdditional(SUMO_TAG_ROUTEPROBE, id, false) == nullptr) {
GNEAdditional* routeProbe = new GNERouteProbe(id, net, edge, freq, name, file, begin);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_ROUTEPROBE));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(routeProbe, true), true);
net->getViewNet()->getUndoList()->p_end();
// center after creation
if (centerAfterCreation) {
net->getViewNet()->centerTo(routeProbe->getPositionInView(), false);
}
} else {
net->getAttributeCarriers()->insertAdditional(routeProbe);
edge->addChildElement(routeProbe);
routeProbe->incRef("buildRouteProbe");
}
return routeProbe;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_ROUTEPROBE) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildVariableSpeedSign(GNENet* net, bool allowUndoRedo, const std::string& id, Position pos, const std::vector<GNELane*>& lanes, const std::string& name, bool blockMovement) {
if (net->retrieveAdditional(SUMO_TAG_VSS, id, false) == nullptr) {
// create VSS
GNEAdditional* variableSpeedSign = new GNEVariableSpeedSign(id, net, pos, name, blockMovement);
// create VSS Symbols
std::vector<GNEAdditional*> VSSSymbols;
for (const auto& lane : lanes) {
VSSSymbols.push_back(new GNEVariableSpeedSignSymbol(variableSpeedSign, lane));
}
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_VSS));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(variableSpeedSign, true), true);
for (const auto& VSSSymbol : VSSSymbols) {
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(VSSSymbol, true), true);
}
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertAdditional(variableSpeedSign);
// add symbols
for (int i = 0; i < (int)lanes.size(); i++) {
lanes.at(i)->addChildElement(VSSSymbols.at(i));
VSSSymbols.at(i)->incRef("buildVariableSpeedSignSymbol");
}
variableSpeedSign->incRef("buildVariableSpeedSign");
}
return variableSpeedSign;
} else {
throw ProcessError("Could not build " + toString(SUMO_TAG_VSS) + " with ID '" + id + "' in netedit; probably declared twice.");
}
}
GNEAdditional*
GNEAdditionalHandler::buildVariableSpeedSignStep(GNENet* net, bool allowUndoRedo, GNEAdditional* VSSParent, double time, double speed) {
// create Variable Speed Sign
GNEAdditional* variableSpeedSignStep = new GNEVariableSpeedSignStep(VSSParent, time, speed);
// add it depending of allow undoRedo
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + variableSpeedSignStep->getTagStr());
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(variableSpeedSignStep, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
VSSParent->addChildElement(variableSpeedSignStep);
variableSpeedSignStep->incRef("buildVariableSpeedSignStep");
}
return variableSpeedSignStep;
}
GNEAdditional*
GNEAdditionalHandler::buildVaporizer(GNENet* net, bool allowUndoRedo, GNEEdge* edge, SUMOTime startTime, SUMOTime endTime, const std::string& name, bool centerAfterCreation) {
GNEAdditional* vaporizer = new GNEVaporizer(net, edge, startTime, endTime, name);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_VAPORIZER));
net->getViewNet()->getUndoList()->add(new GNEChange_Additional(vaporizer, true), true);
net->getViewNet()->getUndoList()->p_end();
// center after creation
if (centerAfterCreation) {
net->getViewNet()->centerTo(vaporizer->getPositionInView(), false);
}
} else {
net->getAttributeCarriers()->insertAdditional(vaporizer);
edge->addChildElement(vaporizer);
vaporizer->incRef("buildVaporizer");
}
return vaporizer;
}
GNETAZElement*
GNEAdditionalHandler::buildTAZ(GNENet* net, bool allowUndoRedo, const std::string& id, const PositionVector& shape, const RGBColor& color, const std::vector<GNEEdge*>& edges, bool blockMovement) {
GNETAZElement* TAZ = new GNETAZ(id, net, shape, color, blockMovement);
// disable updating geometry of TAZ children during insertion (because in large nets provokes slowdowns)
net->disableUpdateGeometry();
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_TAZ));
net->getViewNet()->getUndoList()->add(new GNEChange_TAZElement(TAZ, true), true);
// create TAZEdges
for (const auto& edge : edges) {
// create TAZ Source using GNEChange_Additional
GNETAZElement* TAZSource = new GNETAZSourceSink(SUMO_TAG_TAZSOURCE, TAZ, edge, 1);
net->getViewNet()->getUndoList()->add(new GNEChange_TAZElement(TAZSource, true), true);
// create TAZ Sink using GNEChange_Additional
GNETAZElement* TAZSink = new GNETAZSourceSink(SUMO_TAG_TAZSINK, TAZ, edge, 1);
net->getViewNet()->getUndoList()->add(new GNEChange_TAZElement(TAZSink, true), true);
}
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertTAZElement(TAZ);
TAZ->incRef("buildTAZ");
for (const auto& edge : edges) {
// create TAZ Source
GNETAZElement* TAZSource = new GNETAZSourceSink(SUMO_TAG_TAZSOURCE, TAZ, edge, 1);
TAZSource->incRef("buildTAZ");
TAZ->addChildElement(TAZSource);
// create TAZ Sink
GNETAZElement* TAZSink = new GNETAZSourceSink(SUMO_TAG_TAZSINK, TAZ, edge, 1);
TAZSink->incRef("buildTAZ");
TAZ->addChildElement(TAZSink);
}
}
// enable updating geometry again and update geometry of TAZ
net->enableUpdateGeometry();
// update TAZ Frame
TAZ->updateGeometry();
TAZ->updateParentAdditional();
return TAZ;
}
GNETAZElement*
GNEAdditionalHandler::buildTAZSource(GNENet* net, bool allowUndoRedo, GNETAZElement* TAZ, GNEEdge* edge, double departWeight) {
GNETAZElement* TAZSink = nullptr;
// first check if a TAZSink in the same edge for the same TAZ
for (const auto& TAZElement : TAZ->getChildTAZElements()) {
if ((TAZElement->getTagProperty().getTag() == SUMO_TAG_TAZSINK) && (TAZElement->getAttribute(SUMO_ATTR_EDGE) == edge->getID())) {
TAZSink = TAZElement;
}
}
// check if TAZSink has to be created
if (TAZSink == nullptr) {
// Create TAZ with weight 0 (default)
TAZSink = new GNETAZSourceSink(SUMO_TAG_TAZSINK, TAZ, edge, 1);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_TAZSINK));
net->getViewNet()->getUndoList()->add(new GNEChange_TAZElement(TAZSink, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertTAZElement(TAZSink);
TAZSink->incRef("buildTAZSource");
}
}
// now check check if TAZSource exist
GNETAZElement* TAZSource = nullptr;
// first check if a TAZSink in the same edge for the same TAZ
for (const auto& TAZElement : TAZ->getChildTAZElements()) {
if ((TAZElement->getTagProperty().getTag() == SUMO_TAG_TAZSOURCE) && (TAZElement->getAttribute(SUMO_ATTR_EDGE) == edge->getID())) {
TAZSource = TAZElement;
}
}
// check if TAZSource has to be created
if (TAZSource == nullptr) {
// Create TAZ only with departWeight
TAZSource = new GNETAZSourceSink(SUMO_TAG_TAZSOURCE, TAZ, edge, departWeight);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_TAZSOURCE));
net->getViewNet()->getUndoList()->add(new GNEChange_TAZElement(TAZSource, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertTAZElement(TAZSource);
TAZSource->incRef("buildTAZSource");
}
} else {
// update TAZ Attribute
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("update " + toString(SUMO_TAG_TAZSOURCE));
TAZSource->setAttribute(SUMO_ATTR_WEIGHT, toString(departWeight), net->getViewNet()->getUndoList());
net->getViewNet()->getUndoList()->p_end();
} else {
TAZSource->setAttribute(SUMO_ATTR_WEIGHT, toString(departWeight), nullptr);
TAZSource->incRef("buildTAZSource");
}
}
return TAZSource;
}
GNETAZElement*
GNEAdditionalHandler::buildTAZSink(GNENet* net, bool allowUndoRedo, GNETAZElement* TAZ, GNEEdge* edge, double arrivalWeight) {
GNETAZElement* TAZSource = nullptr;
// first check if a TAZSink in the same edge for the same TAZ
for (const auto& TAZElement : TAZ->getChildTAZElements()) {
if ((TAZElement->getTagProperty().getTag() == SUMO_TAG_TAZSOURCE) && (TAZElement->getAttribute(SUMO_ATTR_EDGE) == edge->getID())) {
TAZSource = TAZElement;
}
}
// check if TAZSource has to be created
if (TAZSource == nullptr) {
// Create TAZ with empty value
TAZSource = new GNETAZSourceSink(SUMO_TAG_TAZSOURCE, TAZ, edge, 1);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_TAZSOURCE));
net->getViewNet()->getUndoList()->add(new GNEChange_TAZElement(TAZSource, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertTAZElement(TAZSource);
TAZSource->incRef("buildTAZSink");
}
}
GNETAZElement* TAZSink = nullptr;
// first check if a TAZSink in the same edge for the same TAZ
for (const auto& TAZElement : TAZ->getChildTAZElements()) {
if ((TAZElement->getTagProperty().getTag() == SUMO_TAG_TAZSINK) && (TAZElement->getAttribute(SUMO_ATTR_EDGE) == edge->getID())) {
TAZSink = TAZElement;
}
}
// check if TAZSink has to be created
if (TAZSink == nullptr) {
// Create TAZ only with arrivalWeight
TAZSink = new GNETAZSourceSink(SUMO_TAG_TAZSINK, TAZ, edge, arrivalWeight);
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("add " + toString(SUMO_TAG_TAZSINK));
net->getViewNet()->getUndoList()->add(new GNEChange_TAZElement(TAZSink, true), true);
net->getViewNet()->getUndoList()->p_end();
} else {
net->getAttributeCarriers()->insertTAZElement(TAZSink);
TAZSink->incRef("buildTAZSink");
}
} else {
// update TAZ Attribute
if (allowUndoRedo) {
net->getViewNet()->getUndoList()->p_begin("update " + toString(SUMO_TAG_TAZSINK));
TAZSink->setAttribute(SUMO_ATTR_WEIGHT, toString(arrivalWeight), net->getViewNet()->getUndoList());
net->getViewNet()->getUndoList()->p_end();
} else {
TAZSink->setAttribute(SUMO_ATTR_WEIGHT, toString(arrivalWeight), nullptr);
TAZSink->incRef("buildTAZSink");
}
}
return TAZSink;
}
double
GNEAdditionalHandler::getPosition(double pos, GNELane& lane, bool friendlyPos, const std::string& additionalID) {
if (pos < 0) {
pos = lane.getLaneShapeLength() + pos;
}
if (pos > lane.getLaneShapeLength()) {
if (friendlyPos) {
pos = lane.getLaneShapeLength() - (double) 0.1;
} else {
WRITE_WARNING("The position of additional '" + additionalID + "' lies beyond the lane's '" + lane.getID() + "' length.");
}
}
return pos;
}
bool GNEAdditionalHandler::checkAndFixDetectorPosition(double& pos, const double laneLength, const bool friendlyPos) {
if (fabs(pos) > laneLength) {
if (!friendlyPos) {
return false;
} else if (pos < 0) {
pos = 0;
} else if (pos > laneLength) {
pos = laneLength - 0.01;
}
}
return true;
}
bool GNEAdditionalHandler::fixE2DetectorPosition(double& pos, double& length, const double laneLength, const bool friendlyPos) {
if ((pos < 0) || ((pos + length) > laneLength)) {
if (!friendlyPos) {
return false;
} else if (pos < 0) {
pos = 0;
} else if (pos > laneLength) {
pos = laneLength - 0.01;
length = 0;
} else if ((pos + length) > laneLength) {
length = laneLength - pos - 0.01;
}
}
return true;
}
bool
GNEAdditionalHandler::accessCanBeCreated(GNEAdditional* busStopParent, GNEEdge* edge) {
// check that busStopParent is a busStop
assert(busStopParent->getTagProperty().getTag() == SUMO_TAG_BUS_STOP);
// check if exist another acces for the same busStop in the given edge
for (auto i : busStopParent->getChildAdditionals()) {
for (auto j : edge->getLanes()) {
if (i->getAttribute(SUMO_ATTR_LANE) == j->getID()) {
return false;
}
}
}
return true;
}
bool
GNEAdditionalHandler::checkOverlappingRerouterIntervals(GNEAdditional* rerouter, SUMOTime newBegin, SUMOTime newEnd) {
// check that rerouter is correct
assert(rerouter->getTagProperty().getTag() == SUMO_TAG_REROUTER);
// declare a vector to keep sorted rerouter children
std::vector<std::pair<SUMOTime, SUMOTime>> sortedIntervals;
// iterate over child additional
for (const auto& rerouterChild : rerouter->getChildAdditionals()) {
if (!rerouterChild->getTagProperty().isSymbol()) {
sortedIntervals.push_back(std::make_pair((SUMOTime)0., (SUMOTime)0.));
// set begin and end
sortedIntervals.back().first = TIME2STEPS(rerouterChild->getAttributeDouble(SUMO_ATTR_BEGIN));
sortedIntervals.back().second = TIME2STEPS(rerouterChild->getAttributeDouble(SUMO_ATTR_END));
}
}
// add new intervals
sortedIntervals.push_back(std::make_pair(newBegin, newEnd));
// sort children
std::sort(sortedIntervals.begin(), sortedIntervals.end());
// check overlapping after sorting
for (int i = 0; i < (int)sortedIntervals.size() - 1; i++) {
if (sortedIntervals.at(i).second > sortedIntervals.at(i + 1).first) {
return false;
}
}
return true;
}
bool
GNEAdditionalHandler::parseAndBuildVaporizer(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Vaporizer
const std::string edgeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_VAPORIZER, SUMO_ATTR_ID, abort);
SUMOTime begin = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, "", SUMO_TAG_VAPORIZER, SUMO_ATTR_BEGIN, abort);
SUMOTime end = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, "", SUMO_TAG_VAPORIZER, SUMO_ATTR_END, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_VAPORIZER, SUMO_ATTR_NAME, abort);
// extra check for center element after creation
bool centerAfterCreation = attrs.hasAttribute(GNE_ATTR_CENTER_AFTER_CREATION);
// Continue if all parameters were successfully loaded
if (!abort) {
// get GNEEdge
GNEEdge* edge = net->retrieveEdge(edgeID, false);
// check that all parameters are valid
if (edge == nullptr) {
WRITE_WARNING("The edge '" + edgeID + "' to use within the " + toString(SUMO_TAG_VAPORIZER) + " is not known.");
} else if (net->retrieveAdditional(SUMO_TAG_VAPORIZER, edgeID, false) != nullptr) {
WRITE_WARNING("There is already a " + toString(SUMO_TAG_VAPORIZER) + " in the edge '" + edgeID + "'.");
} else if (begin > end) {
WRITE_WARNING("Time interval of " + toString(SUMO_TAG_VAPORIZER) + " isn't valid. Attribute '" + toString(SUMO_ATTR_BEGIN) + "' is greater than attribute '" + toString(SUMO_ATTR_END) + "'.");
} else {
// build vaporizer
GNEAdditional* additionalCreated = buildVaporizer(net, allowUndoRedo, edge, begin, end, name, centerAfterCreation);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildTAZ(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Vaporizer
const std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_TAZ, SUMO_ATTR_ID, abort);
const PositionVector shape = GNEAttributeCarrier::parseAttributeFromXML<PositionVector>(attrs, id, SUMO_TAG_TAZ, SUMO_ATTR_SHAPE, abort);
RGBColor color = GNEAttributeCarrier::parseAttributeFromXML<RGBColor>(attrs, id, SUMO_TAG_TAZ, SUMO_ATTR_COLOR, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_TAZ, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// check edges
std::vector<std::string> edgeIDs;
if (attrs.hasAttribute(SUMO_ATTR_EDGES)) {
std::string parsedAttribute = attrs.get<std::string>(SUMO_ATTR_EDGES, id.c_str(), abort, false);
edgeIDs = GNEAttributeCarrier::parse<std::vector<std::string> >(parsedAttribute);
}
// check if all edge IDs are valid
std::vector<GNEEdge*> edges;
for (auto i : edgeIDs) {
GNEEdge* edge = net->retrieveEdge(i, false);
if (edge == nullptr) {
WRITE_WARNING("Invalid " + toString(SUMO_TAG_EDGE) + " with ID = '" + i + "' within taz '" + id + "'.");
abort = true;
} else {
edges.push_back(edge);
}
}
// Continue if all parameters were successfully loaded
if (!abort) {
// check that all parameters are valid
if (net->retrieveTAZElement(SUMO_TAG_TAZ, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_TAZ) + " with the same ID='" + id + "'.");
} else {
// save ID of last created element
GNETAZElement* TAZElementCreated = buildTAZ(net, allowUndoRedo, id, shape, color, edges, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitTAZElementInsertion(TAZElementCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildTAZSource(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Vaporizer
const std::string edgeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_TAZSOURCE, SUMO_ATTR_ID, abort);
const double departWeight = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, edgeID, SUMO_TAG_TAZSOURCE, SUMO_ATTR_WEIGHT, abort);
// Continue if all parameters were successfully loaded
if (!abort) {
// get edge and TAZ
GNEEdge* edge = net->retrieveEdge(edgeID, false);
GNETAZElement* TAZ = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
TAZ = insertedAdditionals->getTAZElementParent(net, SUMO_TAG_TAZ);
} else {
bool ok = true;
TAZ = net->retrieveTAZElement(SUMO_TAG_TAZ, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all parameters are valid
if (edge == nullptr) {
WRITE_WARNING("The edge '" + edgeID + "' to use within the " + toString(SUMO_TAG_TAZSOURCE) + " is not known.");
} else if (TAZ == nullptr) {
WRITE_WARNING("A " + toString(SUMO_TAG_TAZSOURCE) + " must be declared within the definition of a " + toString(SUMO_TAG_TAZ) + ".");
} else {
// save ID of last created element
GNETAZElement* additionalCreated = buildTAZSource(net, allowUndoRedo, TAZ, edge, departWeight);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitTAZElementInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildTAZSink(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Vaporizer
const std::string edgeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_TAZSINK, SUMO_ATTR_ID, abort);
const double arrivalWeight = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, edgeID, SUMO_TAG_TAZSINK, SUMO_ATTR_WEIGHT, abort);
// Continue if all parameters were successfully loaded
if (!abort) {
// get edge and TAZ
GNEEdge* edge = net->retrieveEdge(edgeID, false);
GNETAZElement* TAZ = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
TAZ = insertedAdditionals->getTAZElementParent(net, SUMO_TAG_TAZ);
} else {
bool ok = true;
TAZ = net->retrieveTAZElement(SUMO_TAG_TAZ, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all parameters are valid
if (edge == nullptr) {
WRITE_WARNING("The edge '" + edgeID + "' to use within the " + toString(SUMO_TAG_TAZSINK) + " is not known.");
} else if (TAZ == nullptr) {
WRITE_WARNING("A " + toString(SUMO_TAG_TAZSINK) + " must be declared within the definition of a " + toString(SUMO_TAG_TAZ) + ".");
} else {
// save ID of last created element
GNETAZElement* additionalCreated = buildTAZSink(net, allowUndoRedo, TAZ, edge, arrivalWeight);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitTAZElementInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRouteProbe(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of RouteProbe
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_ROUTEPROBE, SUMO_ATTR_ID, abort);
std::string edgeId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_ROUTEPROBE, SUMO_ATTR_EDGE, abort);
std::string freq = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_ROUTEPROBE, SUMO_ATTR_FREQUENCY, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_ROUTEPROBE, SUMO_ATTR_NAME, abort);
std::string file = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_ROUTEPROBE, SUMO_ATTR_FILE, abort);
SUMOTime begin = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, SUMO_TAG_ROUTEPROBE, SUMO_ATTR_BEGIN, abort);
// extra check for center element after creation
bool centerAfterCreation = attrs.hasAttribute(GNE_ATTR_CENTER_AFTER_CREATION);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get edge
GNEEdge* edge = net->retrieveEdge(edgeId, false);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_ROUTEPROBE, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_ROUTEPROBE) + " with the same ID='" + id + "'.");
} else if (edge == nullptr) {
// Write error if lane isn't valid
WRITE_WARNING("The edge '" + edgeId + "' to use within the " + toString(SUMO_TAG_ROUTEPROBE) + " '" + id + "' is not known.");
} else {
// Freq needs an extra check, because it can be empty
if (GNEAttributeCarrier::canParse<double>(freq)) {
if (GNEAttributeCarrier::parse<double>(freq) < 0) {
WRITE_WARNING(toString(SUMO_ATTR_FREQUENCY) + "of " + toString(SUMO_TAG_ROUTEPROBE) + "'" + id + "' cannot be negative.");
freq = "";
}
} else {
if (freq.empty()) {
WRITE_WARNING(toString(SUMO_ATTR_FREQUENCY) + "of " + toString(SUMO_TAG_ROUTEPROBE) + "'" + id + "' cannot be parsed to float.");
}
freq = "";
}
// save ID of last created element
GNEAdditional* additionalCreated = buildRouteProbe(net, allowUndoRedo, id, edge, freq, name, file, begin, centerAfterCreation);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildCalibratorFlow(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of calibrator flows
std::string vehicleTypeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_TYPE, abort);
std::string routeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_ROUTE, abort);
std::string vehsPerHour = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_VEHSPERHOUR, abort);
std::string speed = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_SPEED, abort);
RGBColor color = GNEAttributeCarrier::parseAttributeFromXML<RGBColor>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_COLOR, abort);
std::string departLane = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_DEPARTLANE, abort);
std::string departPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_DEPARTPOS, abort);
std::string departSpeed = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_DEPARTSPEED, abort);
std::string arrivalLane = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_ARRIVALLANE, abort);
std::string arrivalPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_ARRIVALPOS, abort);
std::string arrivalSpeed = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_ARRIVALSPEED, abort);
std::string line = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_LINE, abort);
int personNumber = GNEAttributeCarrier::parseAttributeFromXML<int>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_PERSON_NUMBER, abort);
int containerNumber = GNEAttributeCarrier::parseAttributeFromXML<int>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_CONTAINER_NUMBER, abort);
bool reroute = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_REROUTE, abort);
std::string departPosLat = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_DEPARTPOS_LAT, abort);
std::string arrivalPosLat = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_ARRIVALPOS_LAT, abort);
SUMOTime begin = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_BEGIN, abort);
SUMOTime end = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, "", SUMO_TAG_FLOW_CALIBRATOR, SUMO_ATTR_END, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain route, vehicle type and calibrator parent
GNEDemandElement* route = net->retrieveDemandElement(SUMO_TAG_ROUTE, routeID, false);
GNEDemandElement* vtype = net->retrieveDemandElement(SUMO_TAG_VTYPE, vehicleTypeID, false);
GNEAdditional* calibrator = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
calibrator = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_CALIBRATOR);
} else {
bool ok = true;
calibrator = net->retrieveAdditional(SUMO_TAG_CALIBRATOR, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all elements are valid
if (route == nullptr) {
WRITE_WARNING(toString(SUMO_TAG_FLOW_CALIBRATOR) + " cannot be created; their " + toString(SUMO_TAG_ROUTE) + " with ID = '" + routeID + "' doesn't exist");
abort = true;
} else if (vtype == nullptr) {
WRITE_WARNING(toString(SUMO_TAG_FLOW_CALIBRATOR) + " cannot be created; their " + toString(SUMO_TAG_VTYPE) + " with ID = '" + vehicleTypeID + "' doesn't exist");
abort = true;
} else if ((vehsPerHour.empty()) && (speed.empty())) {
WRITE_WARNING(toString(SUMO_TAG_FLOW_CALIBRATOR) + " cannot be created; At least parameters " + toString(SUMO_ATTR_VEHSPERHOUR) + " or " + toString(SUMO_ATTR_SPEED) + " has to be defined");
abort = true;
} else if (calibrator != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = buildCalibratorFlow(net, allowUndoRedo, calibrator, route, vtype, vehsPerHour, speed, color, departLane, departPos, departSpeed, arrivalLane, arrivalPos, arrivalSpeed,
line, personNumber, containerNumber, reroute, departPosLat, arrivalPosLat, begin, end);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildVariableSpeedSign(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of VSS
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_VSS, SUMO_ATTR_ID, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_VSS, SUMO_ATTR_NAME, abort);
GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_VSS, SUMO_ATTR_FILE, abort); // deprecated
std::string lanesIDs = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_VSS, SUMO_ATTR_LANES, abort);
Position pos = GNEAttributeCarrier::parseAttributeFromXML<Position>(attrs, id, SUMO_TAG_VSS, SUMO_ATTR_POSITION, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_VSS, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain lanes
std::vector<GNELane*> lanes;
if (GNEAttributeCarrier::canParse<std::vector<GNELane*> >(net, lanesIDs, true)) {
lanes = GNEAttributeCarrier::parse<std::vector<GNELane*> >(net, lanesIDs);
}
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_VSS, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_VSS) + " with the same ID='" + id + "'.");
} else if (lanes.size() == 0) {
WRITE_WARNING("A Variable Speed Sign needs at least one lane.");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildVariableSpeedSign(net, allowUndoRedo, id, pos, lanes, name, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildVariableSpeedSignStep(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// Load step values
double time = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_STEP, SUMO_ATTR_TIME, abort);
double speed = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_STEP, SUMO_ATTR_SPEED, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get Variable Speed Signal
GNEAdditional* variableSpeedSign = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
variableSpeedSign = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_VSS);
} else {
bool ok = true;
variableSpeedSign = net->retrieveAdditional(SUMO_TAG_VSS, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all parameters are valid
if (variableSpeedSign != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = buildVariableSpeedSignStep(net, allowUndoRedo, variableSpeedSign, time, speed);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRerouter(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Rerouter
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_REROUTER, SUMO_ATTR_ID, abort);
std::string edgesIDs = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_REROUTER, SUMO_ATTR_EDGES, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_REROUTER, SUMO_ATTR_NAME, abort);
std::string file = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_REROUTER, SUMO_ATTR_FILE, abort);
double probability = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_REROUTER, SUMO_ATTR_PROB, abort);
bool off = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_REROUTER, SUMO_ATTR_OFF, abort);
SUMOTime timeThreshold = attrs.getOptSUMOTimeReporting(SUMO_ATTR_HALTING_TIME_THRESHOLD, id.c_str(), abort, 0);
const std::string vTypes = attrs.getOpt<std::string>(SUMO_ATTR_VTYPES, id.c_str(), abort, "");
Position pos = GNEAttributeCarrier::parseAttributeFromXML<Position>(attrs, id, SUMO_TAG_REROUTER, SUMO_ATTR_POSITION, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_REROUTER, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain edges
std::vector<GNEEdge*> edges;
if (GNEAttributeCarrier::canParse<std::vector<GNEEdge*> >(net, edgesIDs, true)) {
edges = GNEAttributeCarrier::parse<std::vector<GNEEdge*> >(net, edgesIDs);
}
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_REROUTER, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_REROUTER) + " with the same ID='" + id + "'.");
} else if (edges.size() == 0) {
WRITE_WARNING("A rerouter needs at least one Edge");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildRerouter(net, allowUndoRedo, id, pos, edges, probability, name,
file, off, timeThreshold, vTypes, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRerouterInterval(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Rerouter
SUMOTime begin = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, "", SUMO_TAG_INTERVAL, SUMO_ATTR_BEGIN, abort);
SUMOTime end = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, "", SUMO_TAG_INTERVAL, SUMO_ATTR_END, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain rerouter
GNEAdditional* rerouter;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
rerouter = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_REROUTER);
} else {
bool ok = true;
rerouter = net->retrieveAdditional(SUMO_TAG_REROUTER, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// special case for load multiple intervals in the same rerouter
if (rerouter == nullptr) {
GNEAdditional* lastInsertedRerouterInterval = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
lastInsertedRerouterInterval = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_INTERVAL);
} else {
bool ok = true;
lastInsertedRerouterInterval = net->retrieveAdditional(SUMO_TAG_INTERVAL, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
if (lastInsertedRerouterInterval) {
rerouter = lastInsertedRerouterInterval->getParentAdditionals().at(0);
}
}
// check that rerouterInterval can be created
if (begin >= end) {
WRITE_WARNING(toString(SUMO_TAG_INTERVAL) + " cannot be created; Attribute " + toString(SUMO_ATTR_END) + " must be greather than " + toString(SUMO_ATTR_BEGIN) + ".");
} else if (rerouter != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = buildRerouterInterval(net, allowUndoRedo, rerouter, begin, end);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRerouterClosingLaneReroute(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Rerouter
std::string laneID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CLOSING_LANE_REROUTE, SUMO_ATTR_ID, abort);
std::string allow = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CLOSING_LANE_REROUTE, SUMO_ATTR_ALLOW, abort);
std::string disallow = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CLOSING_LANE_REROUTE, SUMO_ATTR_DISALLOW, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain lane and rerouter interval
GNELane* lane = net->retrieveLane(laneID, false, true);
GNEAdditional* rerouterInterval = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
rerouterInterval = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_INTERVAL);
} else {
bool ok = true;
rerouterInterval = net->retrieveAdditional(SUMO_TAG_INTERVAL, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all elements are valid
if (lane == nullptr) {
WRITE_WARNING("The lane '" + laneID + "' to use within the " + toString(SUMO_TAG_CLOSING_LANE_REROUTE) + " is not known.");
} else if (rerouterInterval != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = buildClosingLaneReroute(net, allowUndoRedo, rerouterInterval, lane, parseVehicleClasses(allow, disallow));
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRerouterClosingReroute(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Rerouter
std::string edgeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CLOSING_REROUTE, SUMO_ATTR_ID, abort);
std::string allow = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CLOSING_REROUTE, SUMO_ATTR_ALLOW, abort);
std::string disallow = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CLOSING_REROUTE, SUMO_ATTR_DISALLOW, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain edge and rerouter interval
GNEEdge* edge = net->retrieveEdge(edgeID, false);
GNEAdditional* rerouterInterval = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
rerouterInterval = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_INTERVAL);
} else {
bool ok = true;
rerouterInterval = net->retrieveAdditional(SUMO_TAG_INTERVAL, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all elements are valid
if (edge == nullptr) {
WRITE_WARNING("The edge '" + edgeID + "' to use within the " + toString(SUMO_TAG_CLOSING_REROUTE) + " is not known.");
} else if (rerouterInterval != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = buildClosingReroute(net, allowUndoRedo, rerouterInterval, edge, parseVehicleClasses(allow, disallow));
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRerouterDestProbReroute(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Rerouter
std::string edgeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_DEST_PROB_REROUTE, SUMO_ATTR_ID, abort);
double probability = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_DEST_PROB_REROUTE, SUMO_ATTR_PROB, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain edge and rerouter interval
GNEEdge* edge = net->retrieveEdge(edgeID, false);
GNEAdditional* rerouterInterval = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
rerouterInterval = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_INTERVAL);
} else {
bool ok = true;
rerouterInterval = net->retrieveAdditional(SUMO_TAG_INTERVAL, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all elements are valid
if (edge == nullptr) {
WRITE_WARNING("The edge '" + edgeID + "' to use within the " + toString(SUMO_TAG_DEST_PROB_REROUTE) + " is not known.");
} else if (rerouterInterval != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = builDestProbReroute(net, allowUndoRedo, rerouterInterval, edge, probability);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRerouterParkingAreaReroute(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Rerouter
std::string parkingAreaID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_PARKING_ZONE_REROUTE, SUMO_ATTR_ID, abort);
double probability = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_PARKING_ZONE_REROUTE, SUMO_ATTR_PROB, abort);
bool visible = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_PARKING_ZONE_REROUTE, SUMO_ATTR_VISIBLE, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain edge and rerouter interval
GNEAdditional* parkingArea = net->retrieveAdditional(SUMO_TAG_PARKING_AREA, parkingAreaID, false);
GNEAdditional* rerouterInterval = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
rerouterInterval = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_INTERVAL);
} else {
bool ok = true;
rerouterInterval = net->retrieveAdditional(SUMO_TAG_INTERVAL, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all elements are valid
if (parkingArea == nullptr) {
WRITE_WARNING("The parkingArea '" + parkingAreaID + "' to use within the " + toString(SUMO_TAG_PARKING_ZONE_REROUTE) + " is not known.");
} else if (rerouterInterval != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = builParkingAreaReroute(net, allowUndoRedo, rerouterInterval, parkingArea, probability, visible);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildRerouterRouteProbReroute(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Rerouter
std::string routeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_ROUTE_PROB_REROUTE, SUMO_ATTR_ID, abort);
double probability = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_ROUTE_PROB_REROUTE, SUMO_ATTR_PROB, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// obtain rerouter interval
GNEAdditional* rerouterInterval = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
rerouterInterval = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_INTERVAL);
} else {
bool ok = true;
rerouterInterval = net->retrieveAdditional(SUMO_TAG_INTERVAL, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all elements are valid
if (rerouterInterval != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = buildRouteProbReroute(net, allowUndoRedo, rerouterInterval, routeID, probability);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildBusStop(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of bus stop
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_BUS_STOP, SUMO_ATTR_ID, abort);
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_LANE, abort);
std::string startPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_STARTPOS, abort);
std::string endPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_ENDPOS, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_NAME, abort);
std::vector<std::string> lines = GNEAttributeCarrier::parseAttributeFromXML<std::vector<std::string> >(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_LINES, abort);
const int personCapacity = GNEAttributeCarrier::parseAttributeFromXML<int>(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_PERSON_CAPACITY, abort);
const double parkingLength = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_PARKING_LENGTH, abort);
bool friendlyPosition = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_BUS_STOP, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_BUS_STOP, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_BUS_STOP, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_BUS_STOP) + " with the same ID='" + id + "'.");
} else if (lane == nullptr) {
// Write error if lane isn't valid
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_BUS_STOP) + " '" + id + "' is not known.");
} else {
// declare variables for start and end position
double startPosDouble = 0;
double endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
const double stoppingPlaceLength = (endPosDouble - startPosDouble);
int parametersSet = 0;
// check if startPos and endPos were defined
if (GNEAttributeCarrier::canParse<double>(startPos)) {
startPosDouble = GNEAttributeCarrier::parse<double>(startPos);
parametersSet |= STOPPINGPLACE_STARTPOS_SET;
}
if (GNEAttributeCarrier::canParse<double>(endPos)) {
endPosDouble = GNEAttributeCarrier::parse<double>(endPos);
parametersSet |= STOPPINGPLACE_ENDPOS_SET;
}
// check if stoppingPlace has to be adjusted
SUMORouteHandler::StopPos checkStopPosResult = SUMORouteHandler::checkStopPos(startPosDouble, endPosDouble, lane->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, friendlyPosition);
// update start and end positions depending of checkStopPosResult
if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_STARTPOS) {
startPosDouble = 0;
endPosDouble = stoppingPlaceLength;
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_ENDPOS) {
startPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength() - stoppingPlaceLength;
endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_LANELENGTH) {
// Write error if position isn't valid
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_BUS_STOP) + " with ID = '" + id + "'.");
return false;
}
// save ID of last created element
GNEAdditional* additionalCreated = buildBusStop(net, allowUndoRedo, id, lane, startPosDouble, endPosDouble, parametersSet,
name, lines, personCapacity, parkingLength, friendlyPosition, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildContainerStop(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of container stop
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CONTAINER_STOP, SUMO_ATTR_ID, abort);
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CONTAINER_STOP, SUMO_ATTR_LANE, abort);
std::string startPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CONTAINER_STOP, SUMO_ATTR_STARTPOS, abort);
std::string endPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CONTAINER_STOP, SUMO_ATTR_ENDPOS, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CONTAINER_STOP, SUMO_ATTR_NAME, abort);
std::vector<std::string> lines = GNEAttributeCarrier::parseAttributeFromXML<std::vector<std::string> >(attrs, id, SUMO_TAG_CONTAINER_STOP, SUMO_ATTR_LINES, abort);
bool friendlyPosition = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_CONTAINER_STOP, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_CONTAINER_STOP, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_CONTAINER_STOP, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_CONTAINER_STOP) + " with the same ID='" + id + "'.");
} else if (lane == nullptr) {
// Write error if lane isn't valid
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_CONTAINER_STOP) + " '" + id + "' is not known.");
} else {
// declare variables for start and end position
double startPosDouble = 0;
double endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
const double stoppingPlaceLength = (endPosDouble - startPosDouble);
int parametersSet = 0;
// check if startPos and endPos were defined
if (GNEAttributeCarrier::canParse<double>(startPos)) {
startPosDouble = GNEAttributeCarrier::parse<double>(startPos);
parametersSet |= STOPPINGPLACE_STARTPOS_SET;
}
if (GNEAttributeCarrier::canParse<double>(endPos)) {
endPosDouble = GNEAttributeCarrier::parse<double>(endPos);
parametersSet |= STOPPINGPLACE_ENDPOS_SET;
}
// check if stoppingPlace has to be adjusted
SUMORouteHandler::StopPos checkStopPosResult = SUMORouteHandler::checkStopPos(startPosDouble, endPosDouble, lane->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, friendlyPosition);
// update start and end positions depending of checkStopPosResult
if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_STARTPOS) {
startPosDouble = 0;
endPosDouble = stoppingPlaceLength;
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_ENDPOS) {
startPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength() - stoppingPlaceLength;
endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_LANELENGTH) {
// Write error if position isn't valid
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_CONTAINER_STOP) + " with ID = '" + id + "'.");
return false;
}
// save ID of last created element
GNEAdditional* additionalCreated = buildContainerStop(net, allowUndoRedo, id, lane, startPosDouble, endPosDouble, parametersSet,
name, lines, friendlyPosition, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildAccess(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Entry
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_ACCESS, SUMO_ATTR_LANE, abort);
std::string position = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_ACCESS, SUMO_ATTR_POSITION, abort);
std::string length = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_ACCESS, SUMO_ATTR_LENGTH, abort);
bool friendlyPos = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_ACCESS, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_ACCESS, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Check if parsing of parameters was correct
if (!abort) {
double posDouble = GNEAttributeCarrier::parse<double>(position);
// get lane and busStop parent
GNELane* lane = net->retrieveLane(laneId, false, true);
GNEAdditional* busStop = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
busStop = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_BUS_STOP);
} else {
bool ok = true;
busStop = net->retrieveAdditional(SUMO_TAG_BUS_STOP, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all parameters are valid
if (lane == nullptr) {
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_ACCESS) + " is not known.");
} else if (busStop == nullptr) {
WRITE_WARNING("A " + toString(SUMO_TAG_ACCESS) + " must be declared within the definition of a " + toString(SUMO_TAG_BUS_STOP) + ".");
} else if (!checkAndFixDetectorPosition(posDouble, lane->getLaneShapeLength(), friendlyPos)) {
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_ACCESS) + ".");
} else if (!accessCanBeCreated(busStop, lane->getParentEdge())) {
WRITE_WARNING("Edge '" + lane->getParentEdge()->getID() + "' already has an Access for busStop '" + busStop->getID() + "'");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildAccess(net, allowUndoRedo, busStop, lane, posDouble, length, friendlyPos, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildChargingStation(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of charging station
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CHARGING_STATION, SUMO_ATTR_ID, abort);
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_LANE, abort);
std::string startPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_STARTPOS, abort);
std::string endPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_ENDPOS, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_NAME, abort);
double chargingPower = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_CHARGINGPOWER, abort);
double efficiency = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_EFFICIENCY, abort);
bool chargeInTransit = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_CHARGEINTRANSIT, abort);
SUMOTime chargeDelay = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_CHARGEDELAY, abort);
bool friendlyPosition = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_CHARGING_STATION, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_CHARGING_STATION, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_CHARGING_STATION, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_CHARGING_STATION) + " with the same ID='" + id + "'.");
} else if (lane == nullptr) {
// Write error if lane isn't valid
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_CHARGING_STATION) + " '" + id + "' is not known.");
} else {
// declare variables for start and end position
double startPosDouble = 0;
double endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
const double stoppingPlaceLength = (endPosDouble - startPosDouble);
int parametersSet = 0;
// check if startPos and endPos were defined
if (GNEAttributeCarrier::canParse<double>(startPos)) {
startPosDouble = GNEAttributeCarrier::parse<double>(startPos);
parametersSet |= STOPPINGPLACE_STARTPOS_SET;
}
if (GNEAttributeCarrier::canParse<double>(endPos)) {
endPosDouble = GNEAttributeCarrier::parse<double>(endPos);
parametersSet |= STOPPINGPLACE_ENDPOS_SET;
}
// check if stoppingPlace has to be adjusted
SUMORouteHandler::StopPos checkStopPosResult = SUMORouteHandler::checkStopPos(startPosDouble, endPosDouble, lane->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, friendlyPosition);
// update start and end positions depending of checkStopPosResult
if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_STARTPOS) {
startPosDouble = 0;
endPosDouble = stoppingPlaceLength;
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_ENDPOS) {
startPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength() - stoppingPlaceLength;
endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_LANELENGTH) {
// Write error if position isn't valid
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_CHARGING_STATION) + " with ID = '" + id + "'.");
return false;
}
// save ID of last created element
GNEAdditional* additionalCreated = buildChargingStation(net, allowUndoRedo, id, lane, startPosDouble, endPosDouble, parametersSet,
name, chargingPower, efficiency, chargeInTransit, chargeDelay, friendlyPosition, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildParkingArea(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of charging station
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_PARKING_AREA, SUMO_ATTR_ID, abort);
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_LANE, abort);
std::string startPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_STARTPOS, abort);
std::string endPos = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_ENDPOS, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_NAME, abort);
bool friendlyPosition = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_FRIENDLY_POS, abort);
int roadSideCapacity = GNEAttributeCarrier::parseAttributeFromXML<int>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_ROADSIDE_CAPACITY, abort);
bool onRoad = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_ONROAD, abort);
double width = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_WIDTH, abort);
std::string length = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_LENGTH, abort);
double angle = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_PARKING_AREA, SUMO_ATTR_ANGLE, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_PARKING_AREA, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_PARKING_AREA, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_PARKING_AREA) + " with the same ID='" + id + "'.");
} else if (lane == nullptr) {
// Write error if lane isn't valid
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_PARKING_AREA) + " '" + id + "' is not known.");
} else {
// declare variables for start and end position
double startPosDouble = 0;
double endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
const double stoppingPlaceLength = (endPosDouble - startPosDouble);
int parametersSet = 0;
// check if startPos and endPos were defined
if (GNEAttributeCarrier::canParse<double>(startPos)) {
startPosDouble = GNEAttributeCarrier::parse<double>(startPos);
parametersSet |= STOPPINGPLACE_STARTPOS_SET;
}
if (GNEAttributeCarrier::canParse<double>(endPos)) {
endPosDouble = GNEAttributeCarrier::parse<double>(endPos);
parametersSet |= STOPPINGPLACE_ENDPOS_SET;
}
// check if stoppingPlace has to be adjusted
SUMORouteHandler::StopPos checkStopPosResult = SUMORouteHandler::checkStopPos(startPosDouble, endPosDouble, lane->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, friendlyPosition);
// update start and end positions depending of checkStopPosResult
if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_STARTPOS) {
startPosDouble = 0;
endPosDouble = stoppingPlaceLength;
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_ENDPOS) {
startPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength() - stoppingPlaceLength;
endPosDouble = lane->getParentEdge()->getNBEdge()->getFinalLength();
} else if (checkStopPosResult == SUMORouteHandler::StopPos::STOPPOS_INVALID_LANELENGTH) {
// Write error if position isn't valid
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_PARKING_AREA) + " with ID = '" + id + "'.");
return false;
}
// save ID of last created element
GNEAdditional* additionalCreated = buildParkingArea(net, allowUndoRedo, id, lane, startPosDouble, endPosDouble, parametersSet,
name, friendlyPosition, roadSideCapacity, onRoad, width, length, angle, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildParkingSpace(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Parking Spaces
Position pos = GNEAttributeCarrier::parseAttributeFromXML<Position>(attrs, "", SUMO_TAG_PARKING_SPACE, SUMO_ATTR_POSITION, abort);
double width = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_PARKING_SPACE, SUMO_ATTR_WIDTH, abort);
double length = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_PARKING_SPACE, SUMO_ATTR_LENGTH, abort);
double angle = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_PARKING_SPACE, SUMO_ATTR_ANGLE, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_PARKING_SPACE, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get Parking Area Parent
GNEAdditional* parkingAreaParent = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
parkingAreaParent = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_PARKING_AREA);
} else {
bool ok = true;
parkingAreaParent = net->retrieveAdditional(SUMO_TAG_PARKING_AREA, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that Parking Area Parent exists
if (parkingAreaParent != nullptr) {
// save ID of last created element
GNEAdditional* additionalCreated = buildParkingSpace(net, allowUndoRedo, parkingAreaParent, pos, width, length, angle, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildCalibrator(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// due there is two differents calibrators, has to be parsed in a different way
std::string edgeID, laneId, id;
// change tag depending of XML parmeters
if (attrs.hasAttribute(SUMO_ATTR_EDGE)) {
id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_CALIBRATOR, SUMO_ATTR_ID, abort);
edgeID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CALIBRATOR, SUMO_ATTR_EDGE, abort);
std::string outfile = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CALIBRATOR, SUMO_ATTR_OUTPUT, abort);
double position = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_CALIBRATOR, SUMO_ATTR_POSITION, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CALIBRATOR, SUMO_ATTR_NAME, abort);
SUMOTime freq = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, SUMO_TAG_CALIBRATOR, SUMO_ATTR_FREQUENCY, abort);
std::string routeProbe = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_CALIBRATOR, SUMO_ATTR_ROUTEPROBE, abort);
// extra check for center element after creation
bool centerAfterCreation = attrs.hasAttribute(GNE_ATTR_CENTER_AFTER_CREATION);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer and edge
GNEEdge* edge = net->retrieveEdge(edgeID, false);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_CALIBRATOR, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_CALIBRATOR) + " with the same ID='" + id + "'.");
} else if (edge == nullptr) {
WRITE_WARNING("The edge '" + edgeID + "' to use within the " + toString(SUMO_TAG_CALIBRATOR) + " '" + id + "' is not known.");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildCalibrator(net, allowUndoRedo, id, edge, position, name, outfile, freq, routeProbe, centerAfterCreation);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
} else if (attrs.hasAttribute(SUMO_ATTR_LANE)) {
id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_LANECALIBRATOR, SUMO_ATTR_ID, abort);
laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_LANECALIBRATOR, SUMO_ATTR_LANE, abort);
std::string outfile = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_LANECALIBRATOR, SUMO_ATTR_OUTPUT, abort);
double position = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_LANECALIBRATOR, SUMO_ATTR_POSITION, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_LANECALIBRATOR, SUMO_ATTR_NAME, abort);
SUMOTime freq = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, SUMO_TAG_LANECALIBRATOR, SUMO_ATTR_FREQUENCY, abort);
std::string routeProbe = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_LANECALIBRATOR, SUMO_ATTR_ROUTEPROBE, abort);
// extra check for center element after creation
bool centerAfterCreation = attrs.hasAttribute(GNE_ATTR_CENTER_AFTER_CREATION);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_LANECALIBRATOR, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_CALIBRATOR) + " with the same ID='" + id + "'.");
} else if (lane == nullptr) {
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_CALIBRATOR) + " '" + id + "' is not known.");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildCalibrator(net, allowUndoRedo, id, lane, position, name, outfile, freq, routeProbe, centerAfterCreation);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
} else {
WRITE_WARNING("additional " + toString(SUMO_TAG_CALIBRATOR) + " must have either a lane or an edge attribute.");
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildDetectorE1(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of E1
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_E1DETECTOR, SUMO_ATTR_ID, abort);
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_E1DETECTOR, SUMO_ATTR_LANE, abort);
double position = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_E1DETECTOR, SUMO_ATTR_POSITION, abort);
SUMOTime frequency = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, SUMO_TAG_E1DETECTOR, SUMO_ATTR_FREQUENCY, abort);
std::string file = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_E1DETECTOR, SUMO_ATTR_FILE, abort);
std::string vehicleTypes = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_E1DETECTOR, SUMO_ATTR_VTYPES, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_E1DETECTOR, SUMO_ATTR_NAME, abort);
bool friendlyPos = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_E1DETECTOR, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_E1DETECTOR, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_E1DETECTOR, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_E1DETECTOR) + " with the same ID='" + id + "'.");
} else if (lane == nullptr) {
// Write error if lane isn't valid
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_E1DETECTOR) + " '" + id + "' is not known.");
} else if (!checkAndFixDetectorPosition(position, lane->getLaneShapeLength(), friendlyPos)) {
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_E1DETECTOR) + " with ID = '" + id + "'.");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildDetectorE1(net, allowUndoRedo, id, lane, position, frequency, file, vehicleTypes, name, friendlyPos, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildDetectorE2(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
// Tag E2 detectors can build either E2 single lanes or E2 multilanes, depending of attribute "lanes"
SumoXMLTag E2Tag = attrs.hasAttribute(SUMO_ATTR_LANES) ? SUMO_TAG_E2DETECTOR_MULTILANE : SUMO_TAG_E2DETECTOR;
bool abort = false;
// start parsing ID
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", E2Tag, SUMO_ATTR_ID, abort);
// parse attributes of E2 SingleLanes
std::string laneId = (E2Tag == SUMO_TAG_E2DETECTOR) ? GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_LANE, abort) : "";
double length = (E2Tag == SUMO_TAG_E2DETECTOR) ? GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, E2Tag, SUMO_ATTR_LENGTH, abort) : 0;
// parse attributes of E2 Multilanes
std::string laneIds = (E2Tag == SUMO_TAG_E2DETECTOR_MULTILANE) ? GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_LANES, abort) : "";
double endPos = (E2Tag == SUMO_TAG_E2DETECTOR_MULTILANE) ? GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, E2Tag, SUMO_ATTR_ENDPOS, abort) : 0;
// parse common attributes
double position = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, E2Tag, SUMO_ATTR_POSITION, abort);
std::string frequency = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_FREQUENCY, abort);
const std::string trafficLight = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_TLID, abort);
std::string file = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_FILE, abort);
std::string vehicleTypes = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_VTYPES, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_NAME, abort);
SUMOTime haltingTimeThreshold = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, E2Tag, SUMO_ATTR_HALTING_TIME_THRESHOLD, abort);
double haltingSpeedThreshold = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, E2Tag, SUMO_ATTR_HALTING_SPEED_THRESHOLD, abort);
double jamDistThreshold = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, E2Tag, SUMO_ATTR_JAM_DIST_THRESHOLD, abort);
bool friendlyPos = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, E2Tag, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, E2Tag, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// cont attribute is deprecated
GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, E2Tag, SUMO_ATTR_CONT, abort);
// Continue if all parameters were sucesfully loaded
if (!abort) {
// check if at leas lane or laneIDS are defined
if (laneId.empty() && laneIds.empty()) {
WRITE_WARNING("A " + toString(E2Tag) + " needs at least a lane or a list of lanes.");
} else if (!frequency.empty() && !trafficLight.empty()) {
WRITE_WARNING("Frecuency and TL cannot be defined at the same time.");
} else {
// update frequency (temporal)
if (frequency.empty() && trafficLight.empty()) {
frequency = "900.00";
}
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// get list of lanes
std::vector<GNELane*> lanes;
bool laneConsecutives = true;
if (GNEAttributeCarrier::canParse<std::vector<GNELane*> >(net, laneIds, false)) {
lanes = GNEAttributeCarrier::parse<std::vector<GNELane*> >(net, laneIds);
// check if lanes are consecutives
laneConsecutives = GNEAttributeCarrier::lanesConsecutives(lanes);
}
// check that all elements are valid
if (net->retrieveAdditional(E2Tag, id, false) != nullptr) {
// write error if neither lane nor lane aren't defined
WRITE_WARNING("There is another " + toString(E2Tag) + " with the same ID='" + id + "'.");
} else if (attrs.hasAttribute(SUMO_ATTR_LANE) && (lane == nullptr)) {
// Write error if lane isn't valid
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(E2Tag) + " '" + id + "' is not known.");
} else if (attrs.hasAttribute(SUMO_ATTR_LANES) && lanes.empty()) {
// Write error if lane isn't valid
WRITE_WARNING("The list of lanes cannot be empty.");
} else if (attrs.hasAttribute(SUMO_ATTR_LANES) && lanes.empty()) {
// Write error if lane isn't valid
WRITE_WARNING("The list of lanes '" + laneIds + "' to use within the " + toString(E2Tag) + " '" + id + "' isn't valid.");
} else if (!lanes.empty() && !laneConsecutives) {
WRITE_WARNING("The lanes '" + laneIds + "' to use within the " + toString(E2Tag) + " '" + id + "' aren't consecutives.");
} else if (lane && !fixE2DetectorPosition(position, length, lane->getParentEdge()->getNBEdge()->getFinalLength(), friendlyPos)) {
WRITE_WARNING("Invalid position for " + toString(E2Tag) + " with ID = '" + id + "'.");
} else if (!lanes.empty() && !fixE2DetectorPosition(position, length, lanes.front()->getParentEdge()->getNBEdge()->getFinalLength(), friendlyPos)) {
WRITE_WARNING("Invalid position for " + toString(E2Tag) + " with ID = '" + id + "'.");
} else if (!lanes.empty() && !fixE2DetectorPosition(endPos, length, lanes.back()->getParentEdge()->getNBEdge()->getFinalLength(), friendlyPos)) {
WRITE_WARNING("Invalid end position for " + toString(E2Tag) + " with ID = '" + id + "'.");
} else if (lane) {
// save ID of last created element
GNEAdditional* additionalCreated = buildSingleLaneDetectorE2(net, allowUndoRedo, id, lane, position, length, frequency, trafficLight, file, vehicleTypes,
name, haltingTimeThreshold, haltingSpeedThreshold, jamDistThreshold, friendlyPos, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildMultiLaneDetectorE2(net, allowUndoRedo, id, lanes, position, endPos, frequency, trafficLight, file, vehicleTypes,
name, haltingTimeThreshold, haltingSpeedThreshold, jamDistThreshold, friendlyPos, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildDetectorE3(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of E3
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_E3DETECTOR, SUMO_ATTR_ID, abort);
SUMOTime frequency = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, SUMO_TAG_E3DETECTOR, SUMO_ATTR_FREQUENCY, abort);
std::string file = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_E3DETECTOR, SUMO_ATTR_FILE, abort);
std::string vehicleTypes = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_E3DETECTOR, SUMO_ATTR_VTYPES, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_E3DETECTOR, SUMO_ATTR_NAME, abort);
SUMOTime haltingTimeThreshold = GNEAttributeCarrier::parseAttributeFromXML<SUMOTime>(attrs, id, SUMO_TAG_E3DETECTOR, SUMO_ATTR_HALTING_TIME_THRESHOLD, abort);
double haltingSpeedThreshold = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_E3DETECTOR, SUMO_ATTR_HALTING_SPEED_THRESHOLD, abort);
Position pos = GNEAttributeCarrier::parseAttributeFromXML<Position>(attrs, id, SUMO_TAG_E3DETECTOR, SUMO_ATTR_POSITION, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_E3DETECTOR, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_E3DETECTOR, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_E3DETECTOR) + " with the same ID='" + id + "'.");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildDetectorE3(net, allowUndoRedo, id, pos, frequency, file, vehicleTypes, name, haltingTimeThreshold, haltingSpeedThreshold, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildDetectorEntry(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Entry
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_DET_ENTRY, SUMO_ATTR_LANE, abort);
double position = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_DET_ENTRY, SUMO_ATTR_POSITION, abort);
bool friendlyPos = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_DET_ENTRY, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_DET_ENTRY, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Check if parsing of parameters was correct
if (!abort) {
// get lane and E3 parent
GNELane* lane = net->retrieveLane(laneId, false, true);
GNEAdditional* E3Parent = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
E3Parent = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_E3DETECTOR);
} else {
bool ok = true;
E3Parent = net->retrieveAdditional(SUMO_TAG_E3DETECTOR, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all parameters are valid
if (lane == nullptr) {
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_DET_ENTRY) + " is not known.");
} else if (!checkAndFixDetectorPosition(position, lane->getLaneShapeLength(), friendlyPos)) {
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_DET_ENTRY) + ".");
} else if (E3Parent) {
// save ID of last created element
GNEAdditional* additionalCreated = buildDetectorEntry(net, allowUndoRedo, E3Parent, lane, position, friendlyPos, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildDetectorExit(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of Exit
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_DET_EXIT, SUMO_ATTR_LANE, abort);
double position = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, "", SUMO_TAG_DET_EXIT, SUMO_ATTR_POSITION, abort);
bool friendlyPos = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_DET_EXIT, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_DET_EXIT, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Check if parsing of parameters was correct
if (!abort) {
// get lane and E3 parent
GNELane* lane = net->retrieveLane(laneId, false, true);
GNEAdditional* E3Parent = nullptr;
// obtain parent depending if we're loading or creating it using GNEAdditionalFrame
if (insertedAdditionals) {
E3Parent = insertedAdditionals->getAdditionalParent(net, SUMO_TAG_E3DETECTOR);
} else {
bool ok = true;
E3Parent = net->retrieveAdditional(SUMO_TAG_E3DETECTOR, attrs.get<std::string>(GNE_ATTR_PARENT, "", ok));
}
// check that all parameters are valid
if (lane == nullptr) {
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_DET_EXIT) + " is not known.");
} else if (!checkAndFixDetectorPosition(position, lane->getLaneShapeLength(), friendlyPos)) {
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_DET_EXIT) + ".");
} else if (E3Parent) {
// save ID of last created element
GNEAdditional* additionalCreated = buildDetectorExit(net, allowUndoRedo, E3Parent, lane, position, friendlyPos, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
bool
GNEAdditionalHandler::parseAndBuildDetectorE1Instant(GNENet* net, bool allowUndoRedo, const SUMOSAXAttributes& attrs, LastInsertedElement* insertedAdditionals) {
bool abort = false;
// parse attributes of E1Instant
std::string id = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_INSTANT_INDUCTION_LOOP, SUMO_ATTR_ID, abort);
std::string laneId = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_INSTANT_INDUCTION_LOOP, SUMO_ATTR_LANE, abort);
double position = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, id, SUMO_TAG_INSTANT_INDUCTION_LOOP, SUMO_ATTR_POSITION, abort);
std::string file = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_INSTANT_INDUCTION_LOOP, SUMO_ATTR_FILE, abort);
std::string vehicleTypes = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_INSTANT_INDUCTION_LOOP, SUMO_ATTR_VTYPES, abort);
std::string name = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, id, SUMO_TAG_INSTANT_INDUCTION_LOOP, SUMO_ATTR_NAME, abort);
bool friendlyPos = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_INSTANT_INDUCTION_LOOP, SUMO_ATTR_FRIENDLY_POS, abort);
// parse Netedit attributes
bool blockMovement = false;
if (attrs.hasAttribute(GNE_ATTR_BLOCK_MOVEMENT)) {
blockMovement = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, id, SUMO_TAG_INSTANT_INDUCTION_LOOP, GNE_ATTR_BLOCK_MOVEMENT, abort);
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// get pointer to lane
GNELane* lane = net->retrieveLane(laneId, false, true);
// check that all elements are valid
if (net->retrieveAdditional(SUMO_TAG_INSTANT_INDUCTION_LOOP, id, false) != nullptr) {
WRITE_WARNING("There is another " + toString(SUMO_TAG_INSTANT_INDUCTION_LOOP) + " with the same ID='" + id + "'.");
} else if (lane == nullptr) {
// Write error if lane isn't valid
WRITE_WARNING("The lane '" + laneId + "' to use within the " + toString(SUMO_TAG_INSTANT_INDUCTION_LOOP) + " '" + id + "' is not known.");
} else if (!checkAndFixDetectorPosition(position, lane->getLaneShapeLength(), friendlyPos)) {
WRITE_WARNING("Invalid position for " + toString(SUMO_TAG_INSTANT_INDUCTION_LOOP) + " with ID = '" + id + "'.");
} else {
// save ID of last created element
GNEAdditional* additionalCreated = buildDetectorE1Instant(net, allowUndoRedo, id, lane, position, file, vehicleTypes, name, friendlyPos, blockMovement);
// check if insertion has to be commited
if (insertedAdditionals) {
insertedAdditionals->commitAdditionalInsertion(additionalCreated);
}
return true;
}
}
return false;
}
// ===========================================================================
// private method definitions
// ===========================================================================
void
GNEAdditionalHandler::parseAndBuildPoly(const SUMOSAXAttributes& attrs) {
bool abort = false;
// parse attributes of polygons
std::string polygonID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_POLY, SUMO_ATTR_ID, abort);
PositionVector shape = GNEAttributeCarrier::parseAttributeFromXML<PositionVector>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_SHAPE, abort);
double layer = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_LAYER, abort);
bool fill = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, "", SUMO_TAG_POLY, SUMO_ATTR_FILL, abort);
double lineWidth = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_LINEWIDTH, abort);
std::string type = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_TYPE, abort);
RGBColor color = GNEAttributeCarrier::parseAttributeFromXML<RGBColor>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_COLOR, abort);
double angle = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_ANGLE, abort);
std::string imgFile = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_IMGFILE, abort);
bool relativePath = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, polygonID, SUMO_TAG_POLY, SUMO_ATTR_RELATIVEPATH, abort);
// check if ID is valid
if (SUMOXMLDefinitions::isValidTypeID(polygonID) == false) {
WRITE_WARNING("Invalid characters for polygon ID");
abort = true;
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// check if shape must be loaded as geo attribute
bool geo = false;
const GeoConvHelper* gch = myGeoConvHelper != nullptr ? myGeoConvHelper : &GeoConvHelper::getFinal();
if (attrs.getOpt<bool>(SUMO_ATTR_GEO, polygonID.c_str(), abort, false)) {
geo = true;
bool success = true;
for (int i = 0; i < (int)shape.size(); i++) {
success &= gch->x2cartesian_const(shape[i]);
}
if (!success) {
WRITE_WARNING("Unable to project coordinates for polygon '" + polygonID + "'.");
return;
}
}
// check if img file is absolute
if (imgFile != "" && !FileHelpers::isAbsolute(imgFile)) {
imgFile = FileHelpers::getConfigurationRelative(getFileName(), imgFile);
}
// create polygon, or show an error if polygon already exists
if (!myNet->getAttributeCarriers()->addPolygon(polygonID, type, color, layer, angle, imgFile, relativePath, shape, geo, fill, lineWidth, false)) {
WRITE_WARNING("Polygon with ID '" + polygonID + "' already exists.");
} else {
// commit shape element insertion
myLastInsertedElement->commitShapeInsertion(myNet->getAttributeCarriers()->getShapes().at(SUMO_TAG_POLY).at(polygonID));
}
}
}
void
GNEAdditionalHandler::parseAndBuildPOI(const SUMOSAXAttributes& attrs) {
bool abort = false;
const SumoXMLTag POITag = attrs.hasAttribute(SUMO_ATTR_LANE) ? SUMO_TAG_POILANE : SUMO_TAG_POI;
// parse attributes of POIs
std::string POIID = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, "", SUMO_TAG_POI, SUMO_ATTR_ID, abort);
// POIs can be defined using a X,Y position,...
Position pos = attrs.hasAttribute(SUMO_ATTR_X) ? GNEAttributeCarrier::parseAttributeFromXML<Position>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_POSITION, abort) : Position::INVALID;
// ... a Lon-Lat,...
double lon = attrs.hasAttribute(SUMO_ATTR_LON) ? GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_LON, abort) : GNEAttributeCarrier::INVALID_POSITION;
double lat = attrs.hasAttribute(SUMO_ATTR_LAT) ? GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_LAT, abort) : GNEAttributeCarrier::INVALID_POSITION;
// .. or as Lane-PosLane
std::string laneID = attrs.hasAttribute(SUMO_ATTR_LANE) ? GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, POIID, SUMO_TAG_POILANE, SUMO_ATTR_LANE, abort) : "";
double lanePos = attrs.hasAttribute(SUMO_ATTR_POSITION) ? GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POILANE, SUMO_ATTR_POSITION, abort) : GNEAttributeCarrier::INVALID_POSITION;
double lanePosLat = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POILANE, SUMO_ATTR_POSITION_LAT, abort);
// continue with common parameters
double layer = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_LAYER, abort);
std::string type = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_TYPE, abort);
RGBColor color = GNEAttributeCarrier::parseAttributeFromXML<RGBColor>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_COLOR, abort);
double angle = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_ANGLE, abort);
std::string imgFile = GNEAttributeCarrier::parseAttributeFromXML<std::string>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_IMGFILE, abort);
bool relativePath = GNEAttributeCarrier::parseAttributeFromXML<bool>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_RELATIVEPATH, abort);
double width = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_WIDTH, abort);
double height = GNEAttributeCarrier::parseAttributeFromXML<double>(attrs, POIID, SUMO_TAG_POI, SUMO_ATTR_HEIGHT, abort);
// check if ID is valid
if (SUMOXMLDefinitions::isValidTypeID(POIID) == false) {
WRITE_WARNING("Invalid characters for POI ID");
abort = true;
}
// Continue if all parameters were sucesfully loaded
if (!abort) {
// check if img file is absolute
if (imgFile != "" && !FileHelpers::isAbsolute(imgFile)) {
imgFile = FileHelpers::getConfigurationRelative(getFileName(), imgFile);
}
// check if lane exist
if (laneID != "" && !myNet->retrieveLane(laneID, false)) {
WRITE_WARNING("The lane '" + laneID + "' to use within the PoI '" + POIID + "' is not known.");
return;
}
// check position
bool useGeo = false;
// if position is invalid, then is either a POILane or a GEOPoi
if (pos == Position::INVALID) {
// try computing x,y from lane,pos
if (laneID != "") {
// if LaneID is defined, then is a POILane
pos = getLanePos(POIID, laneID, lanePos, lanePosLat);
} else {
// try computing x,y from lon,lat
if (lat == GNEAttributeCarrier::INVALID_POSITION || lon == GNEAttributeCarrier::INVALID_POSITION) {
WRITE_WARNING("Either (x, y), (lon, lat) or (lane, pos) must be specified for PoI '" + POIID + "'.");
return;
} else if (!GeoConvHelper::getFinal().usingGeoProjection()) {
WRITE_WARNING("(lon, lat) is specified for PoI '" + POIID + "' but no geo-conversion is specified for the network.");
return;
}
// set GEO Position
pos.set(lon, lat);
useGeo = true;
if (!GeoConvHelper::getFinal().x2cartesian_const(pos)) {
WRITE_WARNING("Unable to project coordinates for PoI '" + POIID + "'.");
return;
}
}
}
// create POI, or show an error if POI already exists
if (!myNet->getAttributeCarriers()->addPOI(POIID, type, color, pos, useGeo, laneID, lanePos, lanePosLat, layer, angle, imgFile, relativePath, width, height, false)) {
WRITE_WARNING("POI with ID '" + POIID + "' already exists.");
} else {
// commit shape element insertion
myLastInsertedElement->commitShapeInsertion(myNet->getAttributeCarriers()->getShapes().at(POITag).at(POIID));
}
}
}
void
GNEAdditionalHandler::parseParameter(const SUMOSAXAttributes& attrs) {
// we have two cases: if we're parsing a Shape or we're parsing an Additional
if (getLastParameterised()) {
bool ok = true;
std::string key;
if (attrs.hasAttribute(SUMO_ATTR_KEY)) {
// obtain key
key = attrs.get<std::string>(SUMO_ATTR_KEY, nullptr, ok);
if (key.empty()) {
WRITE_WARNING("Error parsing key from shape parameter. Key cannot be empty");
ok = false;
}
if (!SUMOXMLDefinitions::isValidParameterKey(key)) {
WRITE_WARNING("Error parsing key from shape parameter. Key contains invalid characters");
ok = false;
}
} else {
WRITE_WARNING("Error parsing key from shape parameter. Key doesn't exist");
ok = false;
}
// circumventing empty string test
const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : "";
// set parameter in last inserted additional
if (ok) {
WRITE_DEBUG("Inserting parameter '" + key + "|" + val + "' into shape.");
getLastParameterised()->setParameter(key, val);
}
} else if (myLastInsertedElement->getLastInsertedAdditional()) {
// first check if given additional supports parameters
if (myLastInsertedElement->getLastInsertedAdditional()->getTagProperty().hasParameters()) {
bool ok = true;
std::string key;
if (attrs.hasAttribute(SUMO_ATTR_KEY)) {
// obtain key
key = attrs.get<std::string>(SUMO_ATTR_KEY, nullptr, ok);
if (key.empty()) {
WRITE_WARNING("Error parsing key from additional parameter. Key cannot be empty");
ok = false;
}
if (!SUMOXMLDefinitions::isValidParameterKey(key)) {
WRITE_WARNING("Error parsing key from additional parameter. Key contains invalid characters");
ok = false;
}
} else {
WRITE_WARNING("Error parsing key from additional parameter. Key doesn't exist");
ok = false;
}
// circumventing empty string test
const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : "";
// check double values
if (myLastInsertedElement->getLastInsertedAdditional()->getTagProperty().hasDoubleParameters() && !GNEAttributeCarrier::canParse<double>(val)) {
WRITE_WARNING("Error parsing value from additional float parameter. Value cannot be parsed to float");
ok = false;
}
// set parameter in last inserted additional
if (ok) {
WRITE_DEBUG("Inserting parameter '" + key + "|" + val + "' into additional " + myLastInsertedElement->getLastInsertedAdditional()->getTagStr() + ".");
myLastInsertedElement->getLastInsertedAdditional()->setParameter(key, val);
}
} else {
WRITE_WARNING("Additionals of type '" + myLastInsertedElement->getLastInsertedAdditional()->getTagStr() + "' doesn't support parameters");
}
} else if (myLastInsertedElement->getLastInsertedShape()) {
// first check if given shape supports parameters
if (myLastInsertedElement->getLastInsertedShape()->getTagProperty().hasParameters()) {
bool ok = true;
std::string key;
if (attrs.hasAttribute(SUMO_ATTR_KEY)) {
// obtain key
key = attrs.get<std::string>(SUMO_ATTR_KEY, nullptr, ok);
if (key.empty()) {
WRITE_WARNING("Error parsing key from shape parameter. Key cannot be empty");
ok = false;
}
if (!SUMOXMLDefinitions::isValidParameterKey(key)) {
WRITE_WARNING("Error parsing key from shape parameter. Key contains invalid characters");
ok = false;
}
} else {
WRITE_WARNING("Error parsing key from shape parameter. Key doesn't exist");
ok = false;
}
// circumventing empty string test
const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : "";
// check double values
if (myLastInsertedElement->getLastInsertedShape()->getTagProperty().hasDoubleParameters() && !GNEAttributeCarrier::canParse<double>(val)) {
WRITE_WARNING("Error parsing value from shape float parameter. Value cannot be parsed to float");
ok = false;
}
// set parameter in last inserted shape
if (ok) {
WRITE_DEBUG("Inserting parameter '" + key + "|" + val + "' into shape " + myLastInsertedElement->getLastInsertedShape()->getTagStr() + ".");
myLastInsertedElement->getLastInsertedShape()->setParameter(key, val);
}
} else {
WRITE_WARNING("Shape of type '" + myLastInsertedElement->getLastInsertedShape()->getTagStr() + "' doesn't support parameters");
}
} else if (myLastInsertedElement->getLastInsertedTAZElement()) {
// first check if given TAZ supports parameters
if (myLastInsertedElement->getLastInsertedTAZElement()->getTagProperty().hasParameters()) {
bool ok = true;
std::string key;
if (attrs.hasAttribute(SUMO_ATTR_KEY)) {
// obtain key
key = attrs.get<std::string>(SUMO_ATTR_KEY, nullptr, ok);
if (key.empty()) {
WRITE_WARNING("Error parsing key from TAZ parameter. Key cannot be empty");
ok = false;
}
if (!SUMOXMLDefinitions::isValidParameterKey(key)) {
WRITE_WARNING("Error parsing key from TAZ parameter. Key contains invalid characters");
ok = false;
}
} else {
WRITE_WARNING("Error parsing key from TAZ parameter. Key doesn't exist");
ok = false;
}
// circumventing empty string test
const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : "";
// check double values
if (myLastInsertedElement->getLastInsertedTAZElement()->getTagProperty().hasDoubleParameters() && !GNEAttributeCarrier::canParse<double>(val)) {
WRITE_WARNING("Error parsing value from TAZ float parameter. Value cannot be parsed to float");
ok = false;
}
// set parameter in last inserted TAZ
if (ok) {
WRITE_DEBUG("Inserting parameter '" + key + "|" + val + "' into TAZ " + myLastInsertedElement->getLastInsertedTAZElement()->getTagStr() + ".");
myLastInsertedElement->getLastInsertedTAZElement()->setParameter(key, val);
}
} else {
WRITE_WARNING("TAZ of type '" + myLastInsertedElement->getLastInsertedTAZElement()->getTagStr() + "' doesn't support parameters");
}
} else {
WRITE_WARNING("Parameters has to be declared within the definition of an additional, shape or TAZ element");
}
}
// ===========================================================================
// GNEAdditionalHandler::LastInsertedElement method definitions
// ===========================================================================
void
GNEAdditionalHandler::LastInsertedElement::insertElement(SumoXMLTag tag) {
myInsertedElements.push_back(StackElement(tag));
}
void
GNEAdditionalHandler::LastInsertedElement::commitAdditionalInsertion(GNEAdditional* additional) {
myInsertedElements.back().additional = additional;
}
void
GNEAdditionalHandler::LastInsertedElement::commitShapeInsertion(GNEShape* shapeCreated) {
myInsertedElements.back().shape = shapeCreated;
}
void
GNEAdditionalHandler::LastInsertedElement::commitTAZElementInsertion(GNETAZElement* TAZElementCreated) {
myInsertedElements.back().TAZElement = TAZElementCreated;
}
void
GNEAdditionalHandler::LastInsertedElement::popElement() {
if (!myInsertedElements.empty()) {
myInsertedElements.pop_back();
}
}
GNEAdditional*
GNEAdditionalHandler::LastInsertedElement::getAdditionalParent(GNENet* net, SumoXMLTag expectedTag) const {
if (myInsertedElements.size() < 2) {
// currently we're finding parent additional in the additional XML root
WRITE_WARNING("A " + toString(myInsertedElements.back().tag) + " must be declared within the definition of a " + toString(expectedTag) + ".");
return nullptr;
} else {
if (myInsertedElements.size() < 2) {
// additional was hierarchically bad loaded, then return nullptr
return nullptr;
} else if ((myInsertedElements.end() - 2)->additional == nullptr) {
WRITE_WARNING(toString(expectedTag) + " parent of " + toString((myInsertedElements.end() - 1)->tag) + " was not loaded sucesfully.");
// parent additional wasn't sucesfully loaded, then return nullptr
return nullptr;
}
GNEAdditional* retrievedAdditional = nullptr;
// special case for rerouters
if ((myInsertedElements.size() == 3) && (myInsertedElements.at(0).tag == SUMO_TAG_REROUTER) && (myInsertedElements.at(1).tag == SUMO_TAG_INTERVAL)) {
retrievedAdditional = myInsertedElements.at(1).additional;
} else {
retrievedAdditional = net->retrieveAdditional((myInsertedElements.end() - 2)->tag, (myInsertedElements.end() - 2)->additional->getID(), false);
}
if (retrievedAdditional == nullptr) {
// additional doesn't exist
WRITE_WARNING("A " + toString((myInsertedElements.end() - 1)->tag) + " must be declared within the definition of a " + toString(expectedTag) + ".");
return nullptr;
} else if (retrievedAdditional->getTagProperty().getTag() != expectedTag) {
// invalid parent additional
WRITE_WARNING("A " + toString((myInsertedElements.end() - 1)->tag) + " cannot be declared within the definition of a " + retrievedAdditional->getTagStr() + ".");
return nullptr;
} else {
return retrievedAdditional;
}
}
}
GNEShape*
GNEAdditionalHandler::LastInsertedElement::getShapeParent(GNENet* net, SumoXMLTag expectedTag) const {
if (myInsertedElements.size() < 2) {
// currently we're finding parent shape in the shape XML root
WRITE_WARNING("A " + toString(myInsertedElements.back().tag) + " must be declared within the definition of a " + toString(expectedTag) + ".");
return nullptr;
} else {
if (myInsertedElements.size() < 2) {
// shape was hierarchically bad loaded, then return nullptr
return nullptr;
} else if ((myInsertedElements.end() - 2)->shape == nullptr) {
WRITE_WARNING(toString(expectedTag) + " parent of " + toString((myInsertedElements.end() - 1)->tag) + " was not loaded sucesfully.");
// parent shape wasn't sucesfully loaded, then return nullptr
return nullptr;
}
GNEShape* retrievedShape = net->retrieveShape((myInsertedElements.end() - 2)->tag, (myInsertedElements.end() - 2)->shape->getID(), false);
if (retrievedShape == nullptr) {
// shape doesn't exist
WRITE_WARNING("A " + toString((myInsertedElements.end() - 1)->tag) + " must be declared within the definition of a " + toString(expectedTag) + ".");
return nullptr;
} else if (retrievedShape->getTagProperty().getTag() != expectedTag) {
// invalid parent shape
WRITE_WARNING("A " + toString((myInsertedElements.end() - 1)->tag) + " cannot be declared within the definition of a " + retrievedShape->getTagStr() + ".");
return nullptr;
} else {
return retrievedShape;
}
}
}
GNETAZElement*
GNEAdditionalHandler::LastInsertedElement::getTAZElementParent(GNENet* net, SumoXMLTag expectedTag) const {
if (myInsertedElements.size() < 2) {
// currently we're finding parent TAZElement in the TAZElement XML root
WRITE_WARNING("A " + toString(myInsertedElements.back().tag) + " must be declared within the definition of a " + toString(expectedTag) + ".");
return nullptr;
} else {
if (myInsertedElements.size() < 2) {
// TAZElement was hierarchically bad loaded, then return nullptr
return nullptr;
} else if ((myInsertedElements.end() - 2)->TAZElement == nullptr) {
WRITE_WARNING(toString(expectedTag) + " parent of " + toString((myInsertedElements.end() - 1)->tag) + " was not loaded sucesfully.");
// parent TAZElement wasn't sucesfully loaded, then return nullptr
return nullptr;
}
GNETAZElement* retrievedTAZElement = net->retrieveTAZElement((myInsertedElements.end() - 2)->tag, (myInsertedElements.end() - 2)->TAZElement->getID(), false);
if (retrievedTAZElement == nullptr) {
// TAZElement doesn't exist
WRITE_WARNING("A " + toString((myInsertedElements.end() - 1)->tag) + " must be declared within the definition of a " + toString(expectedTag) + ".");
return nullptr;
} else if (retrievedTAZElement->getTagProperty().getTag() != expectedTag) {
// invalid parent TAZElement
WRITE_WARNING("A " + toString((myInsertedElements.end() - 1)->tag) + " cannot be declared within the definition of a " + retrievedTAZElement->getTagStr() + ".");
return nullptr;
} else {
return retrievedTAZElement;
}
}
}
GNEAdditional*
GNEAdditionalHandler::LastInsertedElement::getLastInsertedAdditional() const {
// ierate in reverse mode over myInsertedElements to obtain last inserted additional
for (std::vector<StackElement>::const_reverse_iterator i = myInsertedElements.rbegin(); i != myInsertedElements.rend(); i++) {
// we need to avoid Tag Param because isn't an additional
if (i->tag != SUMO_TAG_PARAM) {
return i->additional;
}
}
return nullptr;
}
GNEShape*
GNEAdditionalHandler::LastInsertedElement::getLastInsertedShape() const {
// ierate in reverse mode over myInsertedElements to obtain last inserted shape
for (std::vector<StackElement>::const_reverse_iterator i = myInsertedElements.rbegin(); i != myInsertedElements.rend(); i++) {
// we need to avoid Tag Param because isn't a shape
if (i->tag != SUMO_TAG_PARAM) {
return i->shape;
}
}
return nullptr;
}
GNETAZElement*
GNEAdditionalHandler::LastInsertedElement::getLastInsertedTAZElement() const {
// ierate in reverse mode over myInsertedElements to obtain last inserted TAZElement
for (std::vector<StackElement>::const_reverse_iterator i = myInsertedElements.rbegin(); i != myInsertedElements.rend(); i++) {
// we need to avoid Tag Param because isn't a TAZElement
if (i->tag != SUMO_TAG_PARAM) {
return i->TAZElement;
}
}
return nullptr;
}
GNEAdditionalHandler::LastInsertedElement::StackElement::StackElement(SumoXMLTag _tag) :
tag(_tag),
additional(nullptr),
shape(nullptr),
TAZElement(nullptr) {
}
/****************************************************************************/
| 56.763203 | 287 | 0.670603 | uruzahe |