hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
186146a1976071e4d56f2bd0d9d65970855524b7 | 12,290 | cpp | C++ | qrenderdoc/Code/QRDUtils.cpp | kvark/renderdoc | 7a289c8d53bdbdcf11cc8ba034fdca8cbeaf9673 | [
"MIT"
] | null | null | null | qrenderdoc/Code/QRDUtils.cpp | kvark/renderdoc | 7a289c8d53bdbdcf11cc8ba034fdca8cbeaf9673 | [
"MIT"
] | null | null | null | qrenderdoc/Code/QRDUtils.cpp | kvark/renderdoc | 7a289c8d53bdbdcf11cc8ba034fdca8cbeaf9673 | [
"MIT"
] | null | null | null | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016 Baldur Karlsson
*
* 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 "QRDUtils.h"
#include <QGuiApplication>
#include <QJsonDocument>
#include <QMenu>
#include <QMetaMethod>
QString ToQStr(const ResourceUsage usage, const GraphicsAPI apitype)
{
if(IsD3D(apitype))
{
switch(usage)
{
case eUsage_VertexBuffer: return "Vertex Buffer";
case eUsage_IndexBuffer: return "Index Buffer";
case eUsage_VS_Constants: return "VS - Constant Buffer";
case eUsage_GS_Constants: return "GS - Constant Buffer";
case eUsage_HS_Constants: return "HS - Constant Buffer";
case eUsage_DS_Constants: return "DS - Constant Buffer";
case eUsage_CS_Constants: return "CS - Constant Buffer";
case eUsage_PS_Constants: return "PS - Constant Buffer";
case eUsage_All_Constants: return "All - Constant Buffer";
case eUsage_SO: return "Stream Out";
case eUsage_VS_Resource: return "VS - Resource";
case eUsage_GS_Resource: return "GS - Resource";
case eUsage_HS_Resource: return "HS - Resource";
case eUsage_DS_Resource: return "DS - Resource";
case eUsage_CS_Resource: return "CS - Resource";
case eUsage_PS_Resource: return "PS - Resource";
case eUsage_All_Resource: return "All - Resource";
case eUsage_VS_RWResource: return "VS - UAV";
case eUsage_HS_RWResource: return "HS - UAV";
case eUsage_DS_RWResource: return "DS - UAV";
case eUsage_GS_RWResource: return "GS - UAV";
case eUsage_PS_RWResource: return "PS - UAV";
case eUsage_CS_RWResource: return "CS - UAV";
case eUsage_All_RWResource: return "All - UAV";
case eUsage_InputTarget: return "Colour Input";
case eUsage_ColourTarget: return "Rendertarget";
case eUsage_DepthStencilTarget: return "Depthstencil";
case eUsage_Indirect: return "Indirect argument";
case eUsage_Clear: return "Clear";
case eUsage_GenMips: return "Generate Mips";
case eUsage_Resolve: return "Resolve";
case eUsage_ResolveSrc: return "Resolve - Source";
case eUsage_ResolveDst: return "Resolve - Dest";
case eUsage_Copy: return "Copy";
case eUsage_CopySrc: return "Copy - Source";
case eUsage_CopyDst: return "Copy - Dest";
case eUsage_Barrier: return "Barrier";
default: break;
}
}
else if(apitype == eGraphicsAPI_OpenGL || apitype == eGraphicsAPI_Vulkan)
{
const bool vk = (apitype == eGraphicsAPI_Vulkan);
switch(usage)
{
case eUsage_VertexBuffer: return "Vertex Buffer";
case eUsage_IndexBuffer: return "Index Buffer";
case eUsage_VS_Constants: return "VS - Uniform Buffer";
case eUsage_GS_Constants: return "GS - Uniform Buffer";
case eUsage_HS_Constants: return "HS - Uniform Buffer";
case eUsage_DS_Constants: return "DS - Uniform Buffer";
case eUsage_CS_Constants: return "CS - Uniform Buffer";
case eUsage_PS_Constants: return "PS - Uniform Buffer";
case eUsage_All_Constants: return "All - Uniform Buffer";
case eUsage_SO: return "Transform Feedback";
case eUsage_VS_Resource: return "VS - Texture";
case eUsage_GS_Resource: return "GS - Texture";
case eUsage_HS_Resource: return "HS - Texture";
case eUsage_DS_Resource: return "DS - Texture";
case eUsage_CS_Resource: return "CS - Texture";
case eUsage_PS_Resource: return "PS - Texture";
case eUsage_All_Resource: return "All - Texture";
case eUsage_VS_RWResource: return "VS - Image/SSBO";
case eUsage_HS_RWResource: return "HS - Image/SSBO";
case eUsage_DS_RWResource: return "DS - Image/SSBO";
case eUsage_GS_RWResource: return "GS - Image/SSBO";
case eUsage_PS_RWResource: return "PS - Image/SSBO";
case eUsage_CS_RWResource: return "CS - Image/SSBO";
case eUsage_All_RWResource: return "All - Image/SSBO";
case eUsage_InputTarget: return "FBO Input";
case eUsage_ColourTarget: return "FBO Colour";
case eUsage_DepthStencilTarget: return "FBO Depthstencil";
case eUsage_Indirect: return "Indirect argument";
case eUsage_Clear: return "Clear";
case eUsage_GenMips: return "Generate Mips";
case eUsage_Resolve: return vk ? "Resolve" : "Framebuffer blit";
case eUsage_ResolveSrc: return vk ? "Resolve - Source" : "Framebuffer blit - Source";
case eUsage_ResolveDst: return vk ? "Resolve - Dest" : "Framebuffer blit - Dest";
case eUsage_Copy: return "Copy";
case eUsage_CopySrc: return "Copy - Source";
case eUsage_CopyDst: return "Copy - Dest";
case eUsage_Barrier: return "Barrier";
default: break;
}
}
return "Unknown";
}
QString ToQStr(const ShaderStageType stage, const GraphicsAPI apitype)
{
if(IsD3D(apitype))
{
switch(stage)
{
case eShaderStage_Vertex: return "Vertex";
case eShaderStage_Hull: return "Hull";
case eShaderStage_Domain: return "Domain";
case eShaderStage_Geometry: return "Geometry";
case eShaderStage_Pixel: return "Pixel";
case eShaderStage_Compute: return "Compute";
default: break;
}
}
else if(apitype == eGraphicsAPI_OpenGL || apitype == eGraphicsAPI_Vulkan)
{
switch(stage)
{
case eShaderStage_Vertex: return "Vertex";
case eShaderStage_Tess_Control: return "Tess. Control";
case eShaderStage_Tess_Eval: return "Tess. Eval";
case eShaderStage_Geometry: return "Geometry";
case eShaderStage_Fragment: return "Fragment";
case eShaderStage_Compute: return "Compute";
default: break;
}
}
return "Unknown";
}
bool SaveToJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion)
{
// marker that this data is valid
data[magicIdentifier] = magicVersion;
QJsonDocument doc = QJsonDocument::fromVariant(data);
if(doc.isEmpty() || doc.isNull())
{
qCritical() << "Failed to convert data to JSON document";
return false;
}
QByteArray jsontext = doc.toJson(QJsonDocument::Indented);
qint64 ret = f.write(jsontext);
if(ret != jsontext.size())
{
qCritical() << "Failed to write JSON data: " << ret << " " << f.errorString();
return false;
}
return true;
}
bool LoadFromJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion)
{
QByteArray json = f.readAll();
if(json.isEmpty())
{
qCritical() << "Read invalid empty JSON data from file " << f.errorString();
return false;
}
QJsonDocument doc = QJsonDocument::fromJson(json);
if(doc.isEmpty() || doc.isNull())
{
qCritical() << "Failed to convert file to JSON document";
return false;
}
data = doc.toVariant().toMap();
if(data.isEmpty() || !data.contains(magicIdentifier))
{
qCritical() << "Converted config data is invalid or unrecognised";
return false;
}
if(data[magicIdentifier].toUInt() != magicVersion)
{
qCritical() << "Converted config data is not the right version";
return false;
}
return true;
}
int GUIInvoke::methodIndex = -1;
void GUIInvoke::init()
{
GUIInvoke *invoke = new GUIInvoke();
methodIndex = invoke->metaObject()->indexOfMethod(QMetaObject::normalizedSignature("doInvoke()"));
}
void GUIInvoke::call(const std::function<void()> &f)
{
if(qApp->thread() == QThread::currentThread())
{
f();
return;
}
GUIInvoke *invoke = new GUIInvoke(f);
invoke->moveToThread(qApp->thread());
invoke->metaObject()->method(methodIndex).invoke(invoke, Qt::QueuedConnection);
}
void GUIInvoke::blockcall(const std::function<void()> &f)
{
if(qApp->thread() == QThread::currentThread())
{
f();
return;
}
GUIInvoke *invoke = new GUIInvoke(f);
invoke->moveToThread(qApp->thread());
invoke->metaObject()->method(methodIndex).invoke(invoke, Qt::BlockingQueuedConnection);
}
const QMessageBox::StandardButtons RDDialog::YesNoCancel =
QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
void RDDialog::show(QMenu *menu, QPoint pos)
{
menu->setWindowModality(Qt::ApplicationModal);
menu->popup(pos);
QEventLoop loop;
while(menu->isVisible())
{
loop.processEvents(QEventLoop::WaitForMoreEvents);
QCoreApplication::sendPostedEvents();
}
}
int RDDialog::show(QDialog *dialog)
{
dialog->setWindowModality(Qt::ApplicationModal);
dialog->show();
QEventLoop loop;
while(dialog->isVisible())
{
loop.processEvents(QEventLoop::WaitForMoreEvents);
QCoreApplication::sendPostedEvents();
}
return dialog->result();
}
QMessageBox::StandardButton RDDialog::messageBox(QMessageBox::Icon icon, QWidget *parent,
const QString &title, const QString &text,
QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
QMessageBox::StandardButton ret = defaultButton;
// if we're already on the right thread, this boils down to a function call
GUIInvoke::blockcall([&]() {
QMessageBox mb(icon, title, text, buttons, parent);
mb.setDefaultButton(defaultButton);
show(&mb);
ret = mb.standardButton(mb.clickedButton());
});
return ret;
}
QString RDDialog::getExistingDirectory(QWidget *parent, const QString &caption, const QString &dir,
QFileDialog::Options options)
{
QFileDialog fd(parent, caption, dir, QString());
fd.setAcceptMode(QFileDialog::AcceptOpen);
fd.setFileMode(QFileDialog::DirectoryOnly);
fd.setOptions(options);
show(&fd);
if(fd.result() == QFileDialog::Accepted)
{
QStringList files = fd.selectedFiles();
if(!files.isEmpty())
return files[0];
}
return QString();
}
QString RDDialog::getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter, QString *selectedFilter,
QFileDialog::Options options)
{
QFileDialog fd(parent, caption, dir, filter);
fd.setAcceptMode(QFileDialog::AcceptOpen);
fd.setOptions(options);
show(&fd);
if(fd.result() == QFileDialog::Accepted)
{
if(selectedFilter)
*selectedFilter = fd.selectedNameFilter();
QStringList files = fd.selectedFiles();
if(!files.isEmpty())
return files[0];
}
return QString();
}
QString RDDialog::getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter, QString *selectedFilter,
QFileDialog::Options options)
{
QFileDialog fd(parent, caption, dir, filter);
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.setOptions(options);
show(&fd);
if(fd.result() == QFileDialog::Accepted)
{
if(selectedFilter)
*selectedFilter = fd.selectedNameFilter();
QStringList files = fd.selectedFiles();
if(!files.isEmpty())
return files[0];
}
return QString();
}
| 32.342105 | 102 | 0.67201 | [
"geometry",
"transform"
] |
1867456351320d267bed9d162e6e81bdee92f736 | 7,057 | cpp | C++ | src/test/governance-approval-voting-test.cpp | artem-brazhnikov/crown-core | b9984d0472d08d4a8af8cd493194a520bbb4bc20 | [
"MIT"
] | 12 | 2018-08-26T13:59:10.000Z | 2022-01-02T14:31:27.000Z | src/test/governance-approval-voting-test.cpp | artem-brazhnikov/crown-core | b9984d0472d08d4a8af8cd493194a520bbb4bc20 | [
"MIT"
] | 43 | 2018-09-17T16:45:59.000Z | 2021-08-05T11:01:38.000Z | src/test/governance-approval-voting-test.cpp | artem-brazhnikov/crown-core | b9984d0472d08d4a8af8cd493194a520bbb4bc20 | [
"MIT"
] | 12 | 2018-06-11T01:11:03.000Z | 2022-01-03T10:57:10.000Z | // Copyright (c) 2014-2018 Crown developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>
#include "platform/governance-approval-voting.h"
#include "arith_uint256.h"
#include "utiltime.h"
#include "primitives/transaction.h"
static std::ostream& operator<<(std::ostream& os, uint256 value)
{
return os << value.ToString();
}
namespace
{
struct TestApprovalVotingFixture
{
uint256 agent006{ArithToUint256(0xA006)};
uint256 agent007{ArithToUint256(0xA007)};
uint256 agent008{ArithToUint256(0xA008)};
CTxIn voter1{CTxIn(COutPoint(ArithToUint256(1), 1 * COIN))};
CTxIn voter2{CTxIn(COutPoint(ArithToUint256(2), 1 * COIN))};
TestApprovalVotingFixture()
{
SetMockTime(525960000);
}
~TestApprovalVotingFixture()
{
SetMockTime(0);
}
Platform::Vote VoteFor(uint256 candidate, const CTxIn& voter, int64_t time = GetTime())
{
return {
candidate,
Platform::VoteValue::yes,
time,
voter
};
}
Platform::Vote VoteAgainst(uint256 candidate, const CTxIn& voter, int64_t time = GetTime())
{
return {
candidate,
Platform::VoteValue::no,
time,
voter
};
}
};
}
BOOST_FIXTURE_TEST_SUITE(TestApprovalVoting, TestApprovalVotingFixture)
BOOST_AUTO_TEST_CASE(EmptyRoundIsEmpty)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
auto agents = av.CalculateResult();
BOOST_CHECK(agents.empty());
}
BOOST_AUTO_TEST_CASE(VoteForOneAgent)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
av.RegisterCandidate(agent007);
av.AcceptVote(VoteFor(agent007, voter1));
auto agents = av.CalculateResult();
auto expected = std::vector<uint256>{agent007};
BOOST_CHECK_EQUAL_COLLECTIONS(agents.begin(), agents.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(VoteForUnregisteredCandidate)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
av.AcceptVote(VoteFor(agent007, voter1));
auto agents = av.CalculateResult();
BOOST_CHECK(agents.empty());
}
BOOST_AUTO_TEST_CASE(VoteForTwoAgents)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
av.RegisterCandidate(agent006);
av.RegisterCandidate(agent007);
av.RegisterCandidate(agent008);
av.AcceptVote(VoteFor(agent007, voter1));
av.AcceptVote(VoteFor(agent008, voter1));
auto agents = av.CalculateResult();
auto expected = std::vector<uint256>{agent007, agent008};
BOOST_CHECK_EQUAL_COLLECTIONS(agents.begin(), agents.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(VoteForTwoAgentsByTwoVoters)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
av.RegisterCandidate(agent006);
av.RegisterCandidate(agent007);
av.RegisterCandidate(agent008);
av.AcceptVote(VoteFor(agent007, voter1));
av.AcceptVote(VoteFor(agent008, voter1));
av.AcceptVote(VoteFor(agent006, voter2));
av.AcceptVote(VoteFor(agent007, voter2));
auto agents = av.CalculateResult();
auto expected = std::vector<uint256>{agent006, agent007, agent008};
BOOST_CHECK_EQUAL_COLLECTIONS(agents.begin(), agents.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(VoteForAndAgainst)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
av.RegisterCandidate(agent006);
av.RegisterCandidate(agent007);
av.RegisterCandidate(agent008);
av.AcceptVote(VoteFor(agent007, voter1));
av.AcceptVote(VoteFor(agent008, voter1));
av.AcceptVote(VoteAgainst(agent006, voter2));
av.AcceptVote(VoteAgainst(agent007, voter2));
auto agents = av.CalculateResult();
auto expected = std::vector<uint256>{agent008};
BOOST_CHECK_EQUAL_COLLECTIONS(agents.begin(), agents.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(NonZeroThreshold)
{
auto threshold = 1;
auto av = Platform::ApprovalVoting(threshold);
av.RegisterCandidate(agent006);
av.RegisterCandidate(agent007);
av.RegisterCandidate(agent008);
av.AcceptVote(VoteFor(agent007, voter1));
av.AcceptVote(VoteFor(agent008, voter1));
av.AcceptVote(VoteFor(agent006, voter2));
av.AcceptVote(VoteFor(agent007, voter2));
auto agents = av.CalculateResult(); // 006 && 008 have 1 vote, 007 has two votes
auto expected = std::vector<uint256>{agent007};
BOOST_CHECK_EQUAL_COLLECTIONS(agents.begin(), agents.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(DoubleVoting)
{
auto threshold = 1;
auto av = Platform::ApprovalVoting(threshold);
av.RegisterCandidate(agent007);
av.AcceptVote(VoteFor(agent007, voter1));
av.AcceptVote(VoteFor(agent007, voter1));
auto agents = av.CalculateResult();
BOOST_CHECK(agents.empty());
}
BOOST_AUTO_TEST_CASE(ChangeThreshold)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
av.RegisterCandidate(agent007);
av.AcceptVote(VoteFor(agent007, voter1));
BOOST_REQUIRE(!av.CalculateResult().empty());
av.SetThreshold(1);
BOOST_CHECK(av.CalculateResult().empty());
}
BOOST_AUTO_TEST_CASE(ChangeThresholdFiresNotification)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
auto fired = false;
auto OnChanged = [&fired](){ fired = true; };
av.NotifyResultChange(OnChanged);
av.SetThreshold(1);
BOOST_CHECK(fired);
}
BOOST_AUTO_TEST_CASE(AcceptVoteFiresNotification)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
auto fired = false;
auto OnChanged = [&fired](){ fired = true; };
av.NotifyResultChange(OnChanged);
av.RegisterCandidate(agent007);
av.AcceptVote(VoteFor(agent007, voter1));
BOOST_CHECK(fired);
}
BOOST_AUTO_TEST_CASE(RejectVoteDoesntFireNotification)
{
auto threshold = 0;
auto av = Platform::ApprovalVoting(threshold);
auto fired = false;
auto OnChanged = [&fired](){ fired = true; };
av.NotifyResultChange(OnChanged);
av.AcceptVote(VoteFor(agent007, voter1));
BOOST_CHECK(!fired);
}
BOOST_AUTO_TEST_SUITE_END()
| 27.893281 | 102 | 0.631855 | [
"vector"
] |
186add16d87e78889ce81a40c276e71a931b4772 | 59,174 | cpp | C++ | source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_RV2FP_Merged.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_RV2FP_Merged.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_hydraulic/source_code/models/coupling/Hyd_Coupling_RV2FP_Merged.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | #include "source_code\Hyd_Headers_Precompiled.h"
//#include "Hyd_Coupling_RV2FP_Merged.h"
//init static members
Tables *Hyd_Coupling_RV2FP_Merged::max_h_table=NULL;
//constructor
Hyd_Coupling_RV2FP_Merged::Hyd_Coupling_RV2FP_Merged(void){
this->floodplain_model=NULL;
this->river_model=NULL;
this->list_left.set_leftriver_bank_line(true);
this->list_right.set_leftriver_bank_line(false);
this->direct_coupling_flag_out=false;
this->direct_coupled_fpelem_out=NULL;
this->direct_coupled_elem_index_out=-1;
this->direct_coupled_fp_out=NULL;
this->direct_coupling_flag_in=false;
this->direct_coupled_fpelem_in=NULL;
this->direct_coupled_elem_index_in=-1;
this->direct_coupled_fp_in=NULL;
this->river_model_is_set=false;
this->number_fp_models=0;
//count the memory
Sys_Memory_Count::self()->add_mem(sizeof(Hyd_Coupling_RV2FP_Merged)-sizeof(Hyd_Coupling_Point_RV2FP_List)*2, _sys_system_modules::HYD_SYS);
}
//destructor
Hyd_Coupling_RV2FP_Merged::~Hyd_Coupling_RV2FP_Merged(void){
if(this->floodplain_model!=NULL){
delete []this->floodplain_model;
this->floodplain_model=NULL;
}
//count the memory
Sys_Memory_Count::self()->minus_mem(sizeof(Hyd_Coupling_RV2FP_Merged)-sizeof(Hyd_Coupling_Point_RV2FP_List)*2, _sys_system_modules::HYD_SYS);
}
//___________
//public
//Set the database table for the maximum waterlevels of the coupling points for each fpl-section: it sets the table name and the name of the columns and allocate them (static)
void Hyd_Coupling_RV2FP_Merged::set_max_h_table(QSqlDatabase *ptr_database){
if(Hyd_Coupling_RV2FP_Merged::max_h_table==NULL){
//make specific input for this class
const string tab_id_name=hyd_label::tab_coup_max;
string tab_id_col[13];
tab_id_col[0]=label::glob_id;
tab_id_col[1]=label::areastate_id;
tab_id_col[2]=label::measure_id;
tab_id_col[3]=label::applied_flag;
tab_id_col[4]=hyd_label::sz_bound_id;
tab_id_col[5]=risk_label::sz_break_id;
tab_id_col[6]=fpl_label::section_id;
tab_id_col[7]=hyd_label::coupling_point_max_h;
tab_id_col[8]=hyd_label::maxh;
tab_id_col[9]=hyd_label::coupling_point_max_h2break;
tab_id_col[10]=hyd_label::maxh2break;
tab_id_col[11]=hyd_label::time_maxh2break;
tab_id_col[12]=hyd_label::time_maxh;
try{
Hyd_Coupling_RV2FP_Merged::max_h_table= new Tables(tab_id_name, tab_id_col, sizeof(tab_id_col)/sizeof(tab_id_col[0]));
Hyd_Coupling_RV2FP_Merged::max_h_table->set_name(ptr_database, _sys_table_type::hyd);
}
catch(bad_alloc& t){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::set_max_h_table(QSqlDatabase *ptr_database)","Can not allocate the memory", "Check the memory", 10, false);
ostringstream info;
info<< "Info bad alloc: " << t.what() << endl;
msg.make_second_info(info.str());
throw msg;
}
catch(Error msg){
Hyd_Coupling_RV2FP_Merged::close_max_h_table();
throw msg;
}
}
}
//Create the database table for the maximum waterlevels of the coupling points for each fpl-section (static)
void Hyd_Coupling_RV2FP_Merged::create_max_h_table(QSqlDatabase *ptr_database){
if(Hyd_Coupling_RV2FP_Merged::max_h_table==NULL){
ostringstream cout;
cout << "Create maximum waterlevel table for the fpl-connection..." << endl ;
Sys_Common_Output::output_hyd->output_txt(&cout);
//make specific input for this class
const string tab_name=hyd_label::tab_coup_max;
const int num_col=13;
_Sys_data_tab_column tab_col[num_col];
//init
for(int i=0; i< num_col; i++){
tab_col[i].key_flag=false;
tab_col[i].unsigned_flag=false;
tab_col[i].primary_key_flag=false;
}
tab_col[0].name=label::glob_id;
tab_col[0].type=sys_label::tab_col_type_int;
tab_col[0].unsigned_flag=true;
tab_col[0].primary_key_flag=true;
tab_col[1].name=label::areastate_id;
tab_col[1].type=sys_label::tab_col_type_int;
tab_col[1].unsigned_flag=true;
tab_col[1].key_flag=true;
tab_col[2].name=label::measure_id;
tab_col[2].type=sys_label::tab_col_type_int;
tab_col[2].unsigned_flag=true;
tab_col[2].key_flag=true;
tab_col[3].name=label::applied_flag;
tab_col[3].type=sys_label::tab_col_type_bool;
tab_col[3].default_value="true";
tab_col[3].key_flag=true;
tab_col[4].name=hyd_label::sz_bound_id;
tab_col[4].type=sys_label::tab_col_type_int;
tab_col[4].unsigned_flag=true;
tab_col[4].key_flag=true;
tab_col[5].name=risk_label::sz_break_id;
tab_col[5].type=sys_label::tab_col_type_string;
tab_col[5].key_flag=true;
tab_col[6].name=fpl_label::section_id;
tab_col[6].type=sys_label::tab_col_type_int;
tab_col[6].unsigned_flag=true;
tab_col[6].key_flag=true;
tab_col[7].name=hyd_label::coupling_point_max_h;
tab_col[7].type=sys_label::tab_col_type_int;
tab_col[7].unsigned_flag=true;
tab_col[8].name=hyd_label::maxh;
tab_col[8].type=sys_label::tab_col_type_double;
tab_col[8].unsigned_flag=true;
tab_col[8].default_value="0.0";
tab_col[9].name=hyd_label::time_maxh;
tab_col[9].type=sys_label::tab_col_type_double;
tab_col[9].unsigned_flag=true;
tab_col[9].default_value="0.0";
tab_col[10].name=hyd_label::coupling_point_max_h2break;
tab_col[10].type=sys_label::tab_col_type_int;
tab_col[10].unsigned_flag=true;
tab_col[11].name=hyd_label::maxh2break;
tab_col[11].type=sys_label::tab_col_type_double;
tab_col[11].unsigned_flag=true;
tab_col[11].default_value="0.0";
tab_col[12].name=hyd_label::time_maxh2break;
tab_col[12].type=sys_label::tab_col_type_double;
tab_col[12].unsigned_flag=true;
tab_col[12].default_value="0.0";
try{
Hyd_Coupling_RV2FP_Merged::max_h_table= new Tables();
if(Hyd_Coupling_RV2FP_Merged::max_h_table->create_non_existing_tables(tab_name, tab_col, num_col,ptr_database, _sys_table_type::hyd)==false){
cout << " Table exists" << endl ;
Sys_Common_Output::output_hyd->output_txt(&cout);
};
}
catch(bad_alloc& t){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::max_h_table(QSqlDatabase *ptr_database)","Can not allocate the memory", "Check the memory", 10, false);
ostringstream info;
info<< "Info bad alloc: " << t.what() << endl;
msg.make_second_info(info.str());
throw msg;
}
catch(Error msg){
Hyd_Coupling_RV2FP_Merged::close_max_h_table();
throw msg;
}
Hyd_Coupling_RV2FP_Merged::close_max_h_table();
}
}
//Delete all data in the database table for the maximum waterlevels of the coupling points for each fpl-section (static)
void Hyd_Coupling_RV2FP_Merged::delete_data_max_h_table(QSqlDatabase *ptr_database){
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
//delete the table
Hyd_Coupling_RV2FP_Merged::max_h_table->delete_data_in_table(ptr_database);
}
//Delete all data in the database table for the maximum waterlevels of the coupling points for each fpl-section (static)
void Hyd_Coupling_RV2FP_Merged::delete_data_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id){
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
//delete the table
QSqlQuery query(*ptr_database);
ostringstream query_string;
query_string <<"DELETE FROM " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " WHERE " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " = " << id.area_state;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr;
Data_Base::database_request(&query, query_string.str(), ptr_database);
if(query.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::delete_data_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
}
//Delete all data in the database table for the maximum waterlevels of the coupling points for each fpl-section for the given identifier
void Hyd_Coupling_RV2FP_Merged::delete_data_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const string break_sz, const bool like_flag){
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
//delete the table
QSqlQuery query(*ptr_database);
ostringstream query_string;
query_string <<"DELETE FROM " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " WHERE " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " = " << id.area_state;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr;
query_string << " AND ";
if(like_flag==false){
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) << " = '" << break_sz<<"'";
}
else{
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) << " LIKE '" << break_sz<<"'";
}
Data_Base::database_request(&query, query_string.str(), ptr_database);
if(query.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::delete_data_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const string break_sz, const bool like_flag)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
}
//Delete all data in the database table for the maximum waterlevels of the coupling points for each fpl-section for the given identifier (static)
void Hyd_Coupling_RV2FP_Merged::delete_data_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_bound_sz, const string break_sc){
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
//delete the table
QSqlQuery query(*ptr_database);
ostringstream query_string;
query_string <<"DELETE FROM " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " WHERE " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " = " << id.area_state;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) << " = '" << break_sc <<"'";
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::sz_bound_id) << " = " << hyd_bound_sz <<"";
Data_Base::database_request(&query, query_string.str(), ptr_database);
if(query.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::delete_data_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_bound_sz, const string break_sc)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
}
//Close and delete the database table for the maximum waterlevels of the coupling points for each fpl-section (static)
void Hyd_Coupling_RV2FP_Merged::close_max_h_table(void){
if(Hyd_Coupling_RV2FP_Merged::max_h_table!=NULL){
delete Hyd_Coupling_RV2FP_Merged::max_h_table;
Hyd_Coupling_RV2FP_Merged::max_h_table=NULL;
}
}
//Switch the applied-flag in the database table for the maximum waterlevels of the coupling points for each fpl-section for the given identifier (static)
void Hyd_Coupling_RV2FP_Merged::switch_applied_flag_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const bool flag){
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
QSqlQueryModel query;
ostringstream query_string;
query_string <<"UPDATE ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " SET " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::applied_flag) << " = "<< functions::convert_boolean2string(flag);
query_string << " WHERE ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " = " << id.area_state;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr ;
Data_Base::database_request(&query, query_string.str(), ptr_database);
if(query.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::switch_applied_flag_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const bool flag)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
}
//Switch the applied-flag in the database table for the maximum waterlevels of the coupling points for each fpl-section for the given identifier (static)
void Hyd_Coupling_RV2FP_Merged::switch_applied_flag_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_sc, const bool flag){
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
QSqlQueryModel query;
ostringstream query_string;
query_string <<"UPDATE ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " SET " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::applied_flag) << " = "<< functions::convert_boolean2string(flag);
query_string << " WHERE ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " = " << id.area_state;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr ;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::sz_bound_id) << " = " << hyd_sc ;
Data_Base::database_request(&query, query_string.str(), ptr_database);
if(query.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::switch_applied_flag_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const bool flag)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
}
//Select the point id and the maximum waterlevel in the database table for the maximum waterlevels of the coupling points for each fpl-section for the given identifier
int Hyd_Coupling_RV2FP_Merged::set_hmax_in_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_sc, const string break_sc, const int fpl_sec, int *point_id, double *max_h){
QSqlQueryModel query;
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
ostringstream query_string;
query_string <<"SELECT ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh) <<" ";
query_string << " FROM " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " WHERE " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::applied_flag) << "= true";
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " =" << id.area_state;
query_string << " AND (";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << 0 ;
query_string << " OR " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr;
query_string << " ) " ;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::sz_bound_id) << " = " << hyd_sc;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) << " = '" << break_sc<<"'";
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(fpl_label::section_id) << " = " << fpl_sec;
Data_Base::database_request(&query, query_string.str(), ptr_database);
if(query.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::set_hmax_in_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_sc, const string break_sc, const int fpl_sec, int *point_id, double *max_h)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
//read the data out
*point_id=query.record(0).value((Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h)).c_str()).toInt();
*max_h=query.record(0).value((Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh)).c_str()).toDouble();
return query.rowCount();
}
//Select the point id and the maximum waterlevel in the database table for the maximum waterlevels for a break between river- and floodplainmodel
int Hyd_Coupling_RV2FP_Merged::set_hmax2break_in_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_sc, const string break_sc, const int fpl_sec, int *point_id, double *max_h2break){
QSqlQueryModel query;
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
ostringstream query_string;
query_string <<"SELECT ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h2break) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh2break) <<" ";
query_string << " FROM " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " WHERE " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::applied_flag) << "= true";
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " =" << id.area_state;
query_string << " AND (";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << 0 ;
query_string << " OR " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr;
query_string << " ) " ;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::sz_bound_id) << " = " << hyd_sc;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) << " = '" << break_sc<<"'";
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(fpl_label::section_id) << " = " << fpl_sec;
Data_Base::database_request(&query, query_string.str(), ptr_database);
if(query.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::set_hmax2break_in_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_sc, const string break_sc, const int fpl_sec, int *point_id, double *max_h2break)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
//read the data out
*point_id=query.record(0).value((Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h2break)).c_str()).toInt();
*max_h2break=query.record(0).value((Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh2break)).c_str()).toDouble();
return query.rowCount();
}
//Select all maximum waterlevel in the database table for the maximum waterlevels for a break between river- and floodplainmodel for a given scenario (static)
int Hyd_Coupling_RV2FP_Merged::set_hmax2break_in_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_sc, const string break_sc, QSqlQueryModel *query){
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
ostringstream query_string;
query_string <<"SELECT * ";
query_string << " FROM " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string << " WHERE " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::applied_flag) << "= true";
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " =" << id.area_state;
query_string << " AND (";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << 0 ;
query_string << " OR " ;
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << id.measure_nr;
query_string << " ) " ;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::sz_bound_id) << " = " << hyd_sc;
query_string << " AND ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) << " = '" << break_sc<<"'";
query_string << " ORDER BY ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::time_maxh);
Data_Base::database_request(query, query_string.str(), ptr_database);
if(query->lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::set_hmax2break_in_max_h_table(QSqlDatabase *ptr_database, const _sys_system_id id, const int hyd_sc, const string break_sc, QSqlQueryModel *query)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << query->lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
return query->rowCount();
}
//Copy the results of a given system id to another one in database table (static)
void Hyd_Coupling_RV2FP_Merged::copy_results(QSqlDatabase *ptr_database, const _sys_system_id src, const _sys_system_id dest){
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
int glob_id=0;
glob_id=Hyd_Coupling_RV2FP_Merged::max_h_table->maximum_int_of_column(Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::glob_id) ,ptr_database)+1;
QSqlQueryModel model;
ostringstream test_filter;
test_filter<< "SELECT ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::glob_id);
test_filter << " from " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
test_filter << " WHERE ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) << " = " << src.area_state;
test_filter << " AND ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) << " = " << src.measure_nr ;
//submit it to the datbase
Data_Base::database_request(&model, test_filter.str(), ptr_database);
if(model.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::copy_results(QSqlDatabase *ptr_database, const _sys_system_id src, const _sys_system_id dest)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << model.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
test_filter.str("");
ostringstream cout;
cout <<"Copy "<<model.rowCount()<<" maximum waterlevel results to the new measure state..."<<endl;
Sys_Common_Output::output_hyd->output_txt(&cout);
QSqlQueryModel model1;
for(int i=0; i< model.rowCount(); i++){
test_filter.str("");
test_filter << "INSERT INTO "<< Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
test_filter << " SELECT " << glob_id <<" , ";
test_filter << dest.area_state <<" , ";
test_filter << dest.measure_nr <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::applied_flag) <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::sz_bound_id) <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(fpl_label::section_id) <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h) <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh) <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h2break) <<" , ";
test_filter << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh2break) <<" ";
test_filter << " FROM " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() <<" ";
test_filter << " WHERE " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::glob_id) << " = ";
test_filter << model.record(i).value(Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::glob_id).c_str()).toInt();
Data_Base::database_request(&model1, test_filter.str(), ptr_database);
if(model1.lastError().isValid()==true){
Error msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::copy_results(QSqlDatabase *ptr_database, const _sys_system_id src, const _sys_system_id dest)","Invalid database request", "Check the database", 2, false);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << model1.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
throw msg;
}
glob_id++;
}
try{
Hyd_Coupling_RV2FP_Merged::switch_applied_flag_max_h_table(ptr_database, src, false);
}
catch(Error msg){
throw msg;
}
}
//Output final results of the maximum waterlevel of the coupling points to database (static)
void Hyd_Coupling_RV2FP_Merged::output_final_results(QSqlDatabase *ptr_database, const _sys_system_id id, const string id_break, const int bound_sc, const int fpl_sec_id, const _hyd_max_values max_h, const int point_id_h_max, const _hyd_max_values max_h2break, const int point_id_h_max2break){
//the table is set (the name and the column names) and allocated
try{
Hyd_Coupling_RV2FP_Merged::set_max_h_table(ptr_database);
}
catch(Error msg){
throw msg;
}
QSqlQuery model(*ptr_database);
int glob_id=0;
glob_id=Hyd_Coupling_RV2FP_Merged::max_h_table->maximum_int_of_column(Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::glob_id),ptr_database)+1;
ostringstream query_string;
query_string << "INSERT INTO " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name();
query_string <<" ( ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::glob_id) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::areastate_id) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::measure_id) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::sz_bound_id) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(risk_label::sz_break_id) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(label::applied_flag) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(fpl_label::section_id) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::time_maxh) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::coupling_point_max_h2break) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::maxh2break) <<" , ";
query_string << Hyd_Coupling_RV2FP_Merged::max_h_table->get_column_name(hyd_label::time_maxh2break) <<" ) ";
query_string << " VALUES ( ";
query_string << glob_id << " , " ;
query_string << id.area_state<< " , " ;
query_string << id.measure_nr<< " , " ;
query_string << bound_sc<< " , " ;
query_string <<"'"<< id_break<< "' , " ;
query_string <<""<< functions::convert_boolean2string(true) << " , " ;
query_string << fpl_sec_id << " , " ;
query_string << point_id_h_max << " , " ;
query_string << max_h.maximum << " , ";
query_string << max_h.time_point << " , ";
query_string << point_id_h_max2break << " , " ;
query_string << max_h2break.maximum << " , ";
query_string << max_h2break.time_point << " ) ";
Data_Base::database_request(&model, query_string.str(), ptr_database);
if(model.lastError().isValid()){
Warning msg;
msg.set_msg("Hyd_Coupling_RV2FP_Merged::output_final_results(QSqlDatabase *ptr_database, const _sys_system_id id, const string id_break, const int bound_sc, const int fpl_sec_id, const _hyd_max_values max_h, const int point_id_h_max, const _hyd_max_values max_h2break, const int point_id_h_max2break)","Invalid database request", "Check the database","Can not transfer the results",2);
ostringstream info;
info << "Table Name : " << Hyd_Coupling_RV2FP_Merged::max_h_table->get_table_name() << endl;
info << "Table error info: " << model.lastError().text().toStdString() << endl;
msg.make_second_info(info.str());
msg.output_msg(2);
}
}
//The pointer of the models for couplings are setted and the lists are merged
void Hyd_Coupling_RV2FP_Merged::set_ptr_coupling_with_merging(Hyd_Coupling_RV2FP *couplings){
if(couplings==NULL){
return;
}
else{
if(this->river_model==NULL && couplings->get_is_merged()==false){
this->river_model_is_set=true;
this->river_model=couplings->get_river_model();
this->add_floodplainmodel_pointer(couplings->get_floodplain_model());
//set the defining polysegment
this->list_left.set_defining_polysegment(couplings->list_left.get_defining_polysegment());
this->list_right.set_defining_polysegment(couplings->list_right.get_defining_polysegment());
//merge the lists
couplings->list_left.merge_coupling_list(&this->list_left);
couplings->list_right.merge_coupling_list(&this->list_right);
couplings->set_is_merged();
}
else if(this->river_model==couplings->get_river_model() && couplings->get_is_merged()==false){
this->add_floodplainmodel_pointer(couplings->get_floodplain_model());
//merge the lists
couplings->list_left.merge_coupling_list(&this->list_left);
couplings->list_right.merge_coupling_list(&this->list_right);
couplings->set_is_merged();
}
}
}
//Set up the list of fpl-section ids in the total merged lists (left/right)
void Hyd_Coupling_RV2FP_Merged::set_up_fpl_section_ids_list(void){
this->list_left.set_list_fpl_sec_id();
this->list_right.set_list_fpl_sec_id();
}
//Get the coupled river index
int Hyd_Coupling_RV2FP_Merged::get_river_index(void){
if(this->river_model!=NULL){
return this->river_model->Param_RV.get_river_number();
}
else{
return -1;
}
}
//Get a pointer to the coupled river model
Hyd_Model_River* Hyd_Coupling_RV2FP_Merged::get_river_model(void){
return this->river_model;
}
//Get the flag if the river model is already setted
bool Hyd_Coupling_RV2FP_Merged::get_river_model_is_setted(void){
return this->river_model_is_set;
}
//Get the number of coupled floodplains
int Hyd_Coupling_RV2FP_Merged::get_number_coupled_fp(void){
return this->number_fp_models;
}
//Get the index of a coupled floodplain model by the given index (number of coupled floodplain models)
int Hyd_Coupling_RV2FP_Merged::get_index_coupled_fp_models(const int index){
int index_fp=-1;
if(index<0 || index >=this->number_fp_models){
return index_fp=-1;
}
else{
index_fp=this->floodplain_model[index]->Param_FP.get_floodplain_number();
}
return index_fp;
}
//Synchronise the models
void Hyd_Coupling_RV2FP_Merged::synchronise_models(const double timepoint, const double delta_t, const bool time_check, const int internal_counter){
try{
this->list_left.syncronisation_models_bylistpoints(timepoint,delta_t, time_check, internal_counter);
this->list_right.syncronisation_models_bylistpoints(timepoint, delta_t, time_check, internal_counter);
if(time_check==false){
this->synchronise_direct_coupling_out();
this->synchronise_direct_coupling_in();
}
}
catch(Error msg){
ostringstream info;
info<<"Synchronisation between floodplains ";
for(int i=0; i<this->number_fp_models; i++){
info << this->floodplain_model[i]->Param_FP.get_floodplain_number() << ", ";
}
info<< " and river model " << this->river_model->Param_RV.get_river_number() << endl;
msg.make_second_info(info.str());
throw msg;
}
}
//Get the maximum waterlevel gradient
double Hyd_Coupling_RV2FP_Merged::get_maximum_h_grad(void){
double buffer=0.0;
double buffer_max=0.0;
buffer=this->list_left.get_maximum_h_grad();
if(buffer_max<buffer){
buffer_max=buffer;
}
buffer=this->list_right.get_maximum_h_grad();
if(buffer_max<buffer){
buffer_max=buffer;
}
return buffer_max;
}
//Reset the coupling discharges
void Hyd_Coupling_RV2FP_Merged::reset_coupling_discharges(void){
this->list_left.reset_coupling_discharge();
this->list_right.reset_coupling_discharge();
this->reset_direct_coupling_discharges_out();
this->reset_direct_coupling_discharges_in();
}
//Output the header for the coupled model indizes
void Hyd_Coupling_RV2FP_Merged::output_header_coupled_indices(ostringstream *cout){
*cout << "River to multiple floodplains..." << endl ;
*cout << "No." << W(12) << "Id_RV" << W(12) << "No_FPs" << W(12) << "Id_FPs"<< endl ;
Sys_Common_Output::output_hyd->output_txt(cout);
}
//Output the indexes of the coupled model
void Hyd_Coupling_RV2FP_Merged::output_index_coupled_models(ostringstream *cout, const int number){
*cout << number << W(10);
*cout << this->river_model->Param_RV.get_river_number() << W(12);
*cout << this->number_fp_models<<W(12);
for(int i=0; i<this->number_fp_models; i++){
*cout << this->floodplain_model[i]->Param_FP.get_floodplain_number() << " ";
}
*cout <<endl;
if(this->direct_coupling_flag_in==true){
*cout<< "2d->1D river inflow; Id_FP " << this->direct_coupled_fp_in->Param_FP.get_floodplain_number() << "; ID_Elem " << this->direct_coupled_elem_index_in << endl;
}
if(this->direct_coupling_flag_out==true){
*cout<< "1d->2D river outflow; Id_FP " << this->direct_coupled_fp_out->Param_FP.get_floodplain_number() << "; ID_Elem " << this->direct_coupled_elem_index_out << endl;
}
Sys_Common_Output::output_hyd->output_txt(cout);
}
//Output the setted coupling points in the list
void Hyd_Coupling_RV2FP_Merged::output_setted_coupling_points(void){
ostringstream cout;
ostringstream prefix;
prefix << "RV_" << this->river_model->Param_RV.get_river_number()<<"_FP_MERG> ";
Sys_Common_Output::output_hyd->set_userprefix(prefix.str());
cout << "List of coupling points (left river bank)" << endl ;
Sys_Common_Output::output_hyd->output_txt(&cout,true);
this->list_left.output_setted_members(&cout);
cout << "List of coupling points (right river bank)" << endl ;
Sys_Common_Output::output_hyd->output_txt(&cout, true);
this->list_right.output_setted_members(&cout);
//rewind the prefix
Sys_Common_Output::output_hyd->rewind_userprefix();
}
//Calculate and output final results of the maximum waterlevel of the coupling points to database
void Hyd_Coupling_RV2FP_Merged::calc_output_final_results(QSqlDatabase *ptr_database, const _sys_system_id id, const string id_break, const int bound_sc){
int sec_id=0;
int number_sec=0;
_hyd_max_values h_max;
h_max.maximum=0.0;
h_max.time_point=0.0;
int point_id_h_max=0;
_hyd_max_values h_max2break;
h_max2break.maximum=0.0;
h_max2break.time_point=0.0;
int point_id_h_max2break=0;
//left list
number_sec=this->list_left.get_ptr_fpl_section_ids()->count();
for(int i=0; i< number_sec; i++){
sec_id=this->list_left.get_ptr_fpl_section_ids()->at(i);
this->list_left.get_max_h2fpl(sec_id, &h_max, &point_id_h_max);
this->list_left.get_max_h2break(sec_id, &h_max2break, &point_id_h_max2break);
Hyd_Coupling_RV2FP_Merged::output_final_results(ptr_database, id, id_break, bound_sc, sec_id, h_max, point_id_h_max, h_max2break, point_id_h_max2break);
}
//right list
number_sec=this->list_right.get_ptr_fpl_section_ids()->count();
for(int i=0; i< number_sec; i++){
sec_id=this->list_right.get_ptr_fpl_section_ids()->at(i);
this->list_right.get_max_h2fpl(sec_id, &h_max, &point_id_h_max);
this->list_right.get_max_h2break(sec_id, &h_max2break, &point_id_h_max2break);
Hyd_Coupling_RV2FP_Merged::output_final_results(ptr_database, id, id_break, bound_sc, sec_id, h_max, point_id_h_max, h_max2break, point_id_h_max2break);
}
}
//Check if the river outflow profile is in a floodplain model and is not coupeld to other river models=> outflow goes to the floodplain
void Hyd_Coupling_RV2FP_Merged::check_river_outflow2floodplain(void){
//check if the last points of the couplings line are inside the floodplain
if(this->list_left.get_number_couplings()>0 && this->list_right.get_number_couplings()>0){
if(this->list_left.get_last_couplingpoint().get_coupling_flag()==true && this->list_right.get_last_couplingpoint().get_coupling_flag()==true){
//check if there is an coupling or a boundary is set to the outflow profile => no direct coupling
if(this->river_model->outflow_river_profile.get_h_outflow_is_given()!=true && this->river_model->outflow_river_profile.get_boundary_waterlevel_flag()!=true){
this->direct_coupling_flag_out=true;
try{
//init the direct coupling if needed
this->init_direct_coupling_out();
}
catch(Error msg){
throw msg;
}
}
}
}
}
//Get the flag, if direct RV2FP-coupling out of the outflow-profile is set
bool Hyd_Coupling_RV2FP_Merged::get_direct_coupling_flag_out(void){
return this->direct_coupling_flag_out;
}
//Check and set if the river inflow profile is in a floodplain model and is not coupeld to other river models=> inflow comes from the floodplain
void Hyd_Coupling_RV2FP_Merged::check_river_inflow2floodplain(void){
if(this->list_left.get_number_couplings()>0 && this->list_right.get_number_couplings()>0){
//check if the first points of the coupling line are inside the floodplain
if(this->list_left.get_first_couplingpoint().get_coupling_flag()==true && this->list_right.get_first_couplingpoint().get_coupling_flag()==true){
//check if there is an coupling or a boundary is set to the inflow profile => no direct coupling
if(this->river_model->inflow_river_profile.get_q_inflow_is_given()!=true && this->river_model->inflow_river_profile.get_boundary_point_flag()!=true){
this->direct_coupling_flag_in=true;
try{
//init the direct coupling if needed
this->init_direct_coupling_in();
}
catch(Error msg){
throw msg;
}
}
}
}
}
//Get the flag, if direct RV2FP-coupling into a inflow profile is set
bool Hyd_Coupling_RV2FP_Merged::get_direct_coupling_flag_in(void){
return this->direct_coupling_flag_in;
}
//Check coupling from one bank line to the other side of the river; the coupling is than not possible
void Hyd_Coupling_RV2FP_Merged::check_coupling2_other_river_side(void){
if(this->river_model!=NULL){
this->list_left.check_intercepting_riverbankline2connecting_segment(&this->river_model->river_rightline);
this->list_right.check_intercepting_riverbankline2connecting_segment(&this->river_model->river_leftline);
}
}
//Check coupling from one bank line to the other side of other rivers; the coupling is than not possible
void Hyd_Coupling_RV2FP_Merged::check_coupling2_other_river_side(Hyd_Coupling_RV2FP_Merged *other_river){
if(other_river!=NULL){
bool same_flag=false;
//check if there are same floodplains
for(int i=0; i<this->number_fp_models; i++){
for(int j=0; j < this->get_number_coupled_fp(); j++){
if(this->get_index_coupled_fp_models(i)==other_river->get_index_coupled_fp_models(j)){
same_flag=true;
break;
}
}
}
//check the intercepting
if(same_flag==true){
this->list_left.check_intercepting_riverbankline2connecting_segment(&other_river->get_river_model()->river_rightline);
this->list_right.check_intercepting_riverbankline2connecting_segment(&other_river->get_river_model()->river_rightline);
this->list_left.check_intercepting_riverbankline2connecting_segment(&other_river->get_river_model()->river_leftline);
this->list_right.check_intercepting_riverbankline2connecting_segment(&other_river->get_river_model()->river_leftline);
}
}
}
//Clone the river to floodplain merged coupling
void Hyd_Coupling_RV2FP_Merged::clone_couplings(Hyd_Coupling_RV2FP_Merged *coupling, Hyd_Hydraulic_System *system){
this->direct_coupling_flag_out=coupling->direct_coupling_flag_out;
this->direct_coupled_elem_index_out=coupling->direct_coupled_elem_index_out;
this->direct_coupling_flag_in=coupling->direct_coupling_flag_in;
this->direct_coupled_elem_index_in=coupling->direct_coupled_elem_index_in;
this->river_model_is_set=coupling->river_model_is_set;
if(coupling->direct_coupled_fp_in!=NULL){
this->direct_coupled_fp_in=system->get_ptr_floodplain_model(coupling->direct_coupled_fp_in->Param_FP.get_floodplain_number());
this->direct_coupled_fpelem_in=this->direct_coupled_fp_in->get_ptr_floodplain_elem(this->direct_coupled_elem_index_in);
if(this->direct_coupled_fpelem_in!=NULL){
this->direct_coupled_fpelem_in->element_type->set_coupling_data();
}
}
if(this->direct_coupled_fp_out!=NULL){
this->direct_coupled_fp_out=system->get_ptr_floodplain_model(coupling->direct_coupled_fp_out->Param_FP.get_floodplain_number());
this->direct_coupled_fpelem_out=this->direct_coupled_fp_out->get_ptr_floodplain_elem(this->direct_coupled_elem_index_out);
if(this->direct_coupled_fpelem_out!=NULL){
this->direct_coupled_fpelem_out->element_type->set_coupling_data();
}
}
if(coupling->river_model!=NULL){
this->river_model=system->get_ptr_river_model(coupling->river_model->Param_RV.get_river_number());
}
//set the fp-models
for(int i=0; i< coupling->number_fp_models; i++){
Hyd_Model_Floodplain *buffer;
buffer=system->get_ptr_floodplain_model(coupling->floodplain_model[i]->Param_FP.get_floodplain_number());
this->add_floodplainmodel_pointer(buffer);
}
//the lists
this->list_left.clone_list(&coupling->list_left, system, this->river_model->Param_RV.get_river_number());
this->list_right.clone_list(&coupling->list_right, system, this->river_model->Param_RV.get_river_number());
}
//__________
//private
//Add a pointer of additional floodplain models
void Hyd_Coupling_RV2FP_Merged::add_floodplainmodel_pointer(Hyd_Model_Floodplain *pointer){
if(pointer==NULL){
return;
}
//check if it is the same
for(int i=0; i< this->number_fp_models; i++){
if(this->floodplain_model[i]==pointer){
return;
}
}
//allocate a buffer
Hyd_Model_Floodplain **buffer=NULL;
try{
(buffer)=new Hyd_Model_Floodplain*[this->number_fp_models];
}
catch(bad_alloc &t){
Error msg=this->set_error(2);
ostringstream info;
info << t.what() << endl;
msg.make_second_info(info.str());
throw msg;
}
//copy it
for(int i=0; i< this->number_fp_models; i++){
buffer[i]=this->floodplain_model[i];
}
//delete the pointer
if(this->floodplain_model!=NULL){
delete []this->floodplain_model;
this->floodplain_model=NULL;
}
//count up
this->number_fp_models++;
//allocate new
try{
(this->floodplain_model)=new Hyd_Model_Floodplain*[this->number_fp_models];
}
catch(bad_alloc &t){
Error msg=this->set_error(2);
ostringstream info;
info << t.what() << endl;
msg.make_second_info(info.str());
throw msg;
}
//recopy it
for(int i=0; i< this->number_fp_models-1; i++){
this->floodplain_model[i]=buffer[i];
}
//set the last pointer
this->floodplain_model[this->number_fp_models-1]=pointer;
//delete the buffer
if(buffer!=NULL){
delete []buffer;
buffer=NULL;
}
}
//Initialize the direct RV2FP-coupling out of the outflow-profile
void Hyd_Coupling_RV2FP_Merged::init_direct_coupling_out(void){
if(this->direct_coupling_flag_out==true){
//get the mid point of the outflow profile
Geo_Point mid_point=this->river_model->outflow_river_profile.typ_of_profile->mid_point_global_x_y;
for(int i=0; i< this->number_fp_models;i++){
//get the element
this->direct_coupled_elem_index_out=this->floodplain_model[i]->raster.find_elem_index_by_point_withboundary(&mid_point);
if(this->direct_coupled_elem_index_out>=0){
if(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_out].get_elem_type()==_hyd_elem_type::DIKELINE_ELEM ||
this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_out].get_elem_type()==_hyd_elem_type::STANDARD_ELEM){
this->direct_coupling_flag_out=true;
this->direct_coupled_fpelem_out=&(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_out]);
if(this->direct_coupled_fpelem_out!=NULL){
this->direct_coupled_fpelem_out->element_type->set_coupling_data();
}
this->direct_coupled_fp_out=this->floodplain_model[i];
}
else if(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_out].get_elem_type()==_hyd_elem_type::NOFLOW_ELEM){
this->direct_coupling_flag_out=false;
this->direct_coupled_fpelem_out=NULL;
this->direct_coupled_elem_index_out=-1;
this->direct_coupled_fp_out=NULL;
//warning
Warning msg=this->set_warning(0);
ostringstream info;
info << "River number : " << this->river_model->Param_RV.get_river_number()<<endl;
info << "River name : " << this->river_model->Param_RV.get_river_name()<<endl;
info << "Floodplain number : " << this->floodplain_model[i]->Param_FP.get_floodplain_number()<<endl;
info << "Floodplain name : " << this->floodplain_model[i]->Param_FP.get_floodplain_name()<<endl;
msg.make_second_info(info.str());
msg.output_msg(2);
}
//search for a convenient neighbouring element
else{
this->floodplain_model[i]->raster.search_convenient_coupling_element(&this->direct_coupled_elem_index_out,this->river_model->outflow_river_profile.typ_of_profile->get_first_point()->get_global_x_y_coordinates(),
this->river_model->outflow_river_profile.typ_of_profile->get_last_point()->get_global_x_y_coordinates(),true);
if(this->direct_coupled_elem_index_out>=0){
this->direct_coupling_flag_out=true;
this->direct_coupled_fpelem_out=&(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_out]);
this->direct_coupled_fp_out=this->floodplain_model[i];
}
//no convenient element is found
else{
this->direct_coupling_flag_out=false;
this->direct_coupled_fpelem_out=NULL;
this->direct_coupled_elem_index_out=-1;
this->direct_coupled_fp_out=NULL;
}
}
}
//no element is found
else{
this->direct_coupling_flag_out=false;
this->direct_coupled_fpelem_out=NULL;
this->direct_coupled_elem_index_out=-1;
this->direct_coupled_fp_out=NULL;
}
}
}
//check it
try{
this->check_direct_coupling_out();
}
catch(Error msg){
throw msg;
}
//set the is direct set flag to the outflowprofile
if(this->direct_coupling_flag_out==true){
this->river_model->outflow_river_profile.set_h_outflow_is_given();
}
}
//Synchronise the direct RV2FP-coupling out of the outflow-profile
void Hyd_Coupling_RV2FP_Merged::synchronise_direct_coupling_out(void){
if(this->direct_coupling_flag_out==true){
double value=0.0;
//get discharge from the river outflow profile
value=this->river_model->outflow_river_profile.get_actual_river_discharge();
//set it to the floodplain element
this->direct_coupled_fpelem_out->element_type->add_coupling_discharge_rv_direct(value);
//get the height of the floodplain element
value=this->direct_coupled_fpelem_out->element_type->get_s_value();
this->river_model->outflow_river_profile.set_h_outflow_global(value);
}
}
//Reset the direct RV2FP-coupling out of the outflow-profile
void Hyd_Coupling_RV2FP_Merged::reset_direct_coupling_discharges_out(void){
if(this->direct_coupling_flag_out==true){
this->direct_coupled_fpelem_out->element_type->reset_coupling_discharge_rv_direct();
}
}
//Check the direct coupling
void Hyd_Coupling_RV2FP_Merged::check_direct_coupling_out(void){
if(this->direct_coupling_flag_out==true){
if(this->river_model->outflow_river_profile.typ_of_profile->get_global_z_min()<this->direct_coupled_fpelem_out->get_z_value()){
Error msg=this->set_error(0);
ostringstream info;
info <<"Outflow profile height: " << this->river_model->outflow_river_profile.typ_of_profile->get_global_z_min()<< label::m << endl;
info <<"Element height: " <<this->direct_coupled_fpelem_out->get_z_value()<<label::m << endl;
msg.make_second_info(info.str());
throw msg;
}
}
}
//Initialize the direct RV2FP-coupling into a inflow-profile
void Hyd_Coupling_RV2FP_Merged::init_direct_coupling_in(void){
if(this->direct_coupling_flag_in==true){
//get the mid point of the inflow profile
Geo_Point mid_point=this->river_model->inflow_river_profile.typ_of_profile->mid_point_global_x_y;
for(int i=0; i< this->number_fp_models;i++){
//get the element
this->direct_coupled_elem_index_in=this->floodplain_model[i]->raster.find_elem_index_by_point_withboundary(&mid_point);
if(this->direct_coupled_elem_index_in>=0){
if(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_in].get_elem_type()==_hyd_elem_type::DIKELINE_ELEM ||
this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_in].get_elem_type()==_hyd_elem_type::STANDARD_ELEM){
this->direct_coupling_flag_in=true;
this->direct_coupled_fpelem_in=&(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_in]);
if(this->direct_coupled_fpelem_in!=NULL){
this->direct_coupled_fpelem_in->element_type->set_coupling_data();
}
this->direct_coupled_fp_in=this->floodplain_model[i];
}
else if(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_in].get_elem_type()==_hyd_elem_type::NOFLOW_ELEM){
this->direct_coupling_flag_in=false;
this->direct_coupled_fpelem_in=NULL;
this->direct_coupled_elem_index_in=-1;
this->direct_coupled_fp_in=NULL;
//warning
Warning msg=this->set_warning(0);
ostringstream info;
info << "River number : " << this->river_model->Param_RV.get_river_number()<<endl;
info << "River name : " << this->river_model->Param_RV.get_river_name()<<endl;
info << "Floodplain number : " << this->floodplain_model[i]->Param_FP.get_floodplain_number()<<endl;
info << "Floodplain name : " << this->floodplain_model[i]->Param_FP.get_floodplain_name()<<endl;
msg.make_second_info(info.str());
msg.output_msg(2);
}
//search for a convenient neighbouring element
else{
this->floodplain_model[i]->raster.search_convenient_coupling_element(&this->direct_coupled_elem_index_in,this->river_model->inflow_river_profile.typ_of_profile->get_first_point()->get_global_x_y_coordinates(),
this->river_model->inflow_river_profile.typ_of_profile->get_last_point()->get_global_x_y_coordinates(),false);
if(this->direct_coupled_elem_index_in>=0){
this->direct_coupling_flag_in=true;
this->direct_coupled_fpelem_in=&(this->floodplain_model[i]->floodplain_elems[this->direct_coupled_elem_index_in]);
this->direct_coupled_fp_in=this->floodplain_model[i];
}
//no convenient element is found
else{
this->direct_coupling_flag_in=false;
this->direct_coupled_fpelem_in=NULL;
this->direct_coupled_elem_index_in=-1;
this->direct_coupled_fp_in=NULL;
}
}
}
//no element is found
else{
this->direct_coupling_flag_in=false;
this->direct_coupled_fpelem_in=NULL;
this->direct_coupled_elem_index_in=-1;
this->direct_coupled_fp_in=NULL;
}
}
}
//check it
try{
this->check_direct_coupling_in();
}
catch(Error msg){
throw msg;
}
//set the is direct set flag to the inflowprofile
if(this->direct_coupling_flag_in==true){
this->river_model->inflow_river_profile.set_h_inflow_is_given();
}
}
//Synchronise the direct RV2FP-coupling into a inflow-profile
void Hyd_Coupling_RV2FP_Merged::synchronise_direct_coupling_in(void){
if(this->direct_coupling_flag_in==true){
double value=0.0;
//get discharge from the river inflow profile
value=this->river_model->inflow_river_profile.get_actual_river_discharge();
//set it to the floodplain element
this->direct_coupled_fpelem_in->element_type->add_coupling_discharge_rv_direct((-1.0)*value);
//get the height of the floodplain element
value=this->direct_coupled_fpelem_in->element_type->get_s_value();
//set the height to the inflow profile
this->river_model->inflow_river_profile.set_global_h_boundary(value);
}
}
//Reset the direct RV2FP-coupling into a inflow-profile
void Hyd_Coupling_RV2FP_Merged::reset_direct_coupling_discharges_in(void){
if(this->direct_coupling_flag_in==true){
this->direct_coupled_fpelem_in->element_type->reset_coupling_discharge_rv_direct();
}
}
//Check the direct coupling into a inflow-profile
void Hyd_Coupling_RV2FP_Merged::check_direct_coupling_in(void){
if(this->direct_coupling_flag_in==true){
if(this->river_model->inflow_river_profile.typ_of_profile->get_global_z_min()<this->direct_coupled_fpelem_in->get_z_value()){
Error msg=this->set_error(1);
ostringstream info;
info <<"Inflow profile height: " << this->river_model->inflow_river_profile.typ_of_profile->get_global_z_min()<< label::m << endl;
info <<"Element height: " <<this->direct_coupled_fpelem_in->get_z_value()<<label::m << endl;
msg.make_second_info(info.str());
throw msg;
}
}
}
//set the error
Error Hyd_Coupling_RV2FP_Merged::set_error(const int err_type){
string place="Hyd_Coupling_RV2FP_Merged::";
string help;
string reason;
int type=0;
bool fatal=false;
stringstream info;
Error msg;
switch (err_type){
case 0://the element height is above the outflow profile
place.append("check_direct_coupling_out(void)");
reason="The direct coupled floodplain element is above the minimum global height of the outflow profile";
help="Check geometry of the floodplain and the river outflow";
info<<"Riverno.: "<< this->river_model->Param_RV.get_river_number() << endl;
info <<"Floodplainno.: "<<this->direct_coupled_fp_out->Param_FP.get_floodplain_number();
info << "; Elementno.: " << this->direct_coupled_elem_index_out << endl;
type=16;
break;
case 1://the element height is above the iflow profile
place.append("check_direct_coupling_in(void)");
reason="The direct coupled floodplain element is above the minimum global height of the inflow profile";
help="Check geometry of the floodplain and the river inflow";
info<<"Riverno.: "<< this->river_model->Param_RV.get_river_number() << endl;
info <<"Floodplainno.: "<<this->direct_coupled_fp_in->Param_FP.get_floodplain_number();
info << "; Elementno.: " << this->direct_coupled_elem_index_in << endl;
type=16;
break;
case 2://bad alloc
place.append("add_floodplainmodel_pointer(Hyd_Model_Floodplain *pointer)");
reason="Can not allocate the memory";
help="Check the memory";
type=10;
break;
default:
place.append("set_error(const int err_type)");
reason ="Unknown flag!";
help="Check the flags";
type=6;
}
msg.set_msg(place, reason, help, type, fatal);
msg.make_second_info(info.str());
return msg;
}
//Set warning(s)
Warning Hyd_Coupling_RV2FP_Merged::set_warning(const int warn_type){
string place="Hyd_Coupling_RV2FP_Merged::";
string help;
string reason;
string reaction;
int type=0;
Warning msg;
stringstream info;
switch (warn_type){
case 0://no direct inflow coupling is set
place.append("init_direct_coupling_in(void)");
reason="The inflow profile of the river is inside a floodplain directly at an explicitly set noflow-element";
help="Consider the physical plausibility of the model";
reaction="No direct inflow-coupling is set";
type=10;
break;
case 1://no direct outflow coupling is set
place.append("init_direct_coupling_in(void)");
reason="The outflow profile of the river is inside a floodplain directly at an explicitly set noflow-element";
help="Consider the physical plausibility of the model";
reaction="No direct outflow-coupling is set";
type=10;
break;
default:
place.append("set_warning(const int warn_type)");
reason ="Unknown flag!";
help="Check the flags";
type=5;
}
msg.set_msg(place,reason,help,reaction,type);
msg.make_second_info(info.str());
return msg;
}; | 44.727135 | 387 | 0.755822 | [
"geometry",
"model"
] |
186b8d051e47618db3858c93b7a6ad6435675aba | 3,667 | cpp | C++ | src/core/cpu_debug.cpp | gthev/gayaNES | a6ae9e3ba2a3dad79125994145ec680a6a1dad8b | [
"MIT"
] | null | null | null | src/core/cpu_debug.cpp | gthev/gayaNES | a6ae9e3ba2a3dad79125994145ec680a6a1dad8b | [
"MIT"
] | null | null | null | src/core/cpu_debug.cpp | gthev/gayaNES | a6ae9e3ba2a3dad79125994145ec680a6a1dad8b | [
"MIT"
] | null | null | null | #include <iostream>
#include <bitset>
#include <string>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <vector>
#include "cpu.hpp"
#define INSTR_START 0x00C0
/* CLI to debug CPU/CPUMEM
-> s : step
-> r : read memory, 'r 1234' to read $1234
compile with
g++ -o cputest cpu_debug.cpp cpu.cpp ppu_mem.cpp mem.cpp -lSDL2 -g
*/
void print_cpu_state(cpu6502 const& cpu, FullRamMemory *mem) {
cpu6502flags f = cpu.get_cpu_flags();
cpu6502regs r = cpu.get_cpu_regs();
cpu6502interrupts intps = cpu.get_cpu_intps();
UINT8 flags = flags_to_byte(f);
UINT8 next_op = mem->read(r.PC);
std::bitset<8> fb(flags);
std::printf("PC : $%04X [pointing to $%02X]\n", r.PC, next_op);
std::printf("A : $%02X\n", r.A);
std::printf("X : $%02X\n", r.X);
std::printf("Y : $%02X\n", r.Y);
std::printf("S : $%02X\n", r.S);
std::cout << "NV---IZC" << std::endl;
if(intps.CPUhalt) std::cout << "*** CPU HALTED ***\n";
if(intps.NMIPending) std::cout << "* NMI PENDING *\n";
if(intps.IRQPending) std::cout << "* IRQ PENDING *\n";
std::cout << fb << std::endl;
}
void print_mem_location(MEMADDR a, FullRamMemory *mem) {
UINT8 val = mem->read(a);
std::printf("$%04X : $%02X\n", a, val);
}
int main(int argc, char *argv[]) {
std::string s("CPU 6502 DEBUGGER. Enter instructions (in hex form), it will loaded"
" in memory at 0x0C00, and an instruction will be executed at every ENTER pressed."
);
std::string input;
bool cont = true;
FullRamMemory *mem = new FullRamMemory();
cpu6502 cpu = cpu6502(mem);
std::cout << s << std::endl;
do {
// interpret it as instructions
std::cout << ">>> ";
std::getline(std::cin, input);
int i = 0;
MEMADDR next_instr = INSTR_START;
try
{
while(i < input.length()) {
if(input[i] == ' ') {i++; continue;}
std::string byte_s = input.substr(i, (i+1 == input.length())?1:2);
UINT8 val = std::stoul(byte_s, 0, 16);
mem->write(next_instr++, val);
i+=2;
cont = false;
}
}
catch(const std::exception& e)
{
std::cerr << "An error occured : " << e.what() << '\n';
std::cout << "Please try again\n";
}
} while(cont);
cpu.init_cpu(INSTR_START);
cont = true;
while(cont) {
std::cout << "===================\n";
print_cpu_state(cpu, mem);
std::cout << ">>> ";
std::getline(std::cin, input);
std::vector<std::string> strs;
boost::split(strs, input, boost::is_any_of(" "));
std::string command = strs[0];
// ------------- step
if(input == "" || command == "s") {
if(!cpu.get_cpu_intps().CPUhalt) {
UINT8 nr_cycles = cpu.von_neumann_cycle();
std::printf("%d cycles\n",
(unsigned int)nr_cycles);
}
// -------------- read memory
} else if(command == "r") {
if(strs.size() != 2) {
std::cerr << "Command read used badly : r 1234\n";
continue;
}
MEMADDR val = std::stoul(strs[1], 0, 16);
std::printf("$%04X : $%02X\n", val, mem->read(val));
}
// ------------- default case
else {
//throw NotImplemented(input.c_str()); // hmm a bit too extrem
std::cerr << "Command unknown : " << command << std::endl;
continue;
}
}
return 0;
} | 29.103175 | 101 | 0.503681 | [
"vector"
] |
1879d727e8a2549867dabf910903e3de7396a6b1 | 1,844 | cpp | C++ | source/backend/cpu/CPUWhere.cpp | SunXuan90/MNN | dc0b62e817884f8fbc884f159b590feab2b0f0f8 | [
"Apache-2.0"
] | 1 | 2020-08-31T05:12:10.000Z | 2020-08-31T05:12:10.000Z | source/backend/cpu/CPUWhere.cpp | ryanstout/MNN | 82630820c04402e6282e7c717c4fc531c23808e2 | [
"Apache-2.0"
] | null | null | null | source/backend/cpu/CPUWhere.cpp | ryanstout/MNN | 82630820c04402e6282e7c717c4fc531c23808e2 | [
"Apache-2.0"
] | null | null | null | //
// CPUWhere.cpp
// MNN
//
// Created by MNN on 2018/08/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "backend/cpu/CPUWhere.hpp"
#include "backend/cpu/CPUBackend.hpp"
namespace MNN {
template <typename T>
std::vector<int32_t> _collect(Tensor* t) {
const T* ptr = t->host<T>();
std::vector<int32_t> collect;
for (int i = 0; i < t->elementSize(); i++) {
if (ptr[i] > 0) {
collect.push_back(i);
}
}
return collect;
}
ErrorCode CPUWhere::onExecute(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs) {
auto& ib = inputs[0]->buffer();
auto outputData = outputs[0]->host<int32_t>();
std::vector<int32_t> collect;
if (ib.type == halide_type_of<float>()) {
collect = _collect<float>(inputs[0]);
} else if (ib.type == halide_type_of<int32_t>()) {
collect = _collect<int32_t>(inputs[0]);
} else if (ib.type == halide_type_of<uint8_t>()) {
collect = _collect<uint8_t>(inputs[0]);
}
//MNN_ASSERT(outputs[0]->batch() == trueVec.size());
for (int i = 0; i < collect.size(); i++) {
int index = collect[i];
for (int j = 0; j < ib.dimensions; j++) {
int result = ib.dim[j].stride == 0 ? index : index / ib.dim[j].stride;
index = index - result * ib.dim[j].stride;
outputData[i * ib.dimensions + j] = result;
}
}
return NO_ERROR;
}
class CPUWhereCreator : public CPUBackend::Creator {
public:
virtual Execution* onCreate(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs,
const MNN::Op* op, Backend* backend) const override {
return new CPUWhere(backend);
}
};
REGISTER_CPU_OP_CREATOR(CPUWhereCreator, OpType_Where);
} // namespace MNN
| 30.229508 | 104 | 0.586768 | [
"vector"
] |
187a723f228ec8ebf0562d6864dae47391b40a38 | 8,333 | cpp | C++ | Samples/JTSP/JPBX/Call.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 1 | 2021-02-08T20:31:46.000Z | 2021-02-08T20:31:46.000Z | Samples/JTSP/JPBX/Call.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | null | null | null | Samples/JTSP/JPBX/Call.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 4 | 2019-11-14T03:47:33.000Z | 2021-03-08T01:18:05.000Z | /*******************************************************************/
//
// CALL.CPP
//
// Call object definitions
//
// Copyright (C) 1998 JulMar Technology, Inc.
// All rights reserved
//
// TSP++ Version 3.00 PBX/ACD Emulator Projects
// Internal Source Code - Do Not Release
//
// Modification History
// --------------------
// 1998/09/05 MCS@JulMar Initial revision
//
/*******************************************************************/
/*---------------------------------------------------------------*/
// INCLUDE FILES
/*---------------------------------------------------------------*/
#include "stdafx.h"
#include "jpbx.h"
#include "call.h"
#include "line.h"
#include "trunk.h"
/*---------------------------------------------------------------*/
// DEBUG INFORMATION
/*---------------------------------------------------------------*/
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*****************************************************************************
** Procedure: GetUniqueCallID
**
** Arguments: void
**
** Returns: unique DWORD for callid
**
** Description: Returns unique callid
**
*****************************************************************************/
static DWORD GetUniqueCallID()
{
static DWORD g_dwLastCallID = 0;
DWORD dwCallID;
do {
dwCallID = GetTickCount();
} while (dwCallID == g_dwLastCallID);
g_dwLastCallID = dwCallID;
return dwCallID;
}// GetUniqueCallID
/*****************************************************************************
** Procedure: CCall::CCall
**
** Arguments: 'pHandle' - Master call handle
** 'pLine' - Line owner for this object
** 'cidInfo' - Callerid information
**
** Returns: void
**
** Description: Constructor for the call object
**
*****************************************************************************/
CCall::CCall(CLineDevice* pLine, const CNetInfo& calleridInfo,
const CNetInfo& calledInfo, bool fPlaceCall) :
m_pLine(pLine), m_calleridInfo(calleridInfo),
m_calledidInfo(calledInfo), m_csState(Unknown), m_pOther(0)
{
m_dwCallID = GetUniqueCallID();
// Notify the line owner
m_pLine->OnCallCreated(this, fPlaceCall);
// Mark the current time
GetSystemTime(&m_stState);
}// CCall::CCall
/*****************************************************************************
** Procedure: CCall::CCall
**
** Arguments: 'pLine' - Line owner for this object
** 'pCall' - Call to attach to
**
** Returns: void
**
** Description: Constructor for the call object
**
*****************************************************************************/
CCall::CCall(CLineDevice* pLine, CCall& eCall) :
m_pLine(pLine), m_dwCallID(eCall.m_dwCallID), m_csState(Unknown),
m_calleridInfo(eCall.m_calleridInfo), m_calledidInfo(eCall.m_calledidInfo),
m_pOther(0)
{
// Attach to the other call
eCall.AttachCall(this);
// Notify the line owner
m_pLine->OnCallCreated(this, false);
// Determine the initial call state based on the other call.
OnChangeCallState(eCall.m_csState);
CopyMemory(&m_stState, &eCall.m_stState, sizeof(SYSTEMTIME));
}// CCall::CCall
/*****************************************************************************
** Procedure: CCall::~CCall
**
** Arguments: void
**
** Returns: void
**
** Description: Destructor for the call object
**
*****************************************************************************/
CCall::~CCall()
{
m_pLine->OnCallDestroyed(this, (m_dwCallID != 0));
if (m_csState != Disconnected && m_pOther != NULL)
{
CCall* pOther = m_pOther;
m_pOther = NULL;
if (pOther != NULL)
{
pOther->m_pOther = NULL;
pOther->m_dwCallID = 0;
delete pOther;
}
}
}// CCall::~CCall
/*****************************************************************************
** Procedure: CCall::Release
**
** Arguments: void
**
** Returns: void
**
** Description: Drops the call
**
*****************************************************************************/
void CCall::Release()
{
// If we have an attached call (other side), then show that
// this side disconnected from the conversation. This will
// cause this side to self-destruct.
CCall* pCall = GetAttachedCall();
if (pCall != NULL)
pCall->SetCallState(Disconnected);
// Otherwise, simply hangup
else
delete this;
}// CCall::Release
/*****************************************************************************
** Procedure: CCall::SetCallState
**
** Arguments: 'ncs' - New call state
**
** Returns: true/false if state was set
**
** Description: Sets the call state
**
*****************************************************************************/
void CCall::SetCallState(CallState ncs, bool fNotifyOther)
{
if (ncs != m_csState)
{
// Set the new callstate
m_csState = ncs;
// Mark the current time
GetSystemTime(&m_stState);
// Notify the line owner
m_pLine->OnCallStateChange(this);
// Notify the other side of the call - if THIS call
// is being disconnected, then it will be deleted
// with this notification.
if (m_pOther != NULL && fNotifyOther)
m_pOther->OnChangeCallState(ncs);
}
}// CCall::SetCallState
/*****************************************************************************
** Procedure: CCall::OnChangeCallState
**
** Arguments: 'ncs' - New call state
**
** Returns: void
**
** Description: Event which is called when the other side of a call
** changes state
**
*****************************************************************************/
void CCall::OnChangeCallState(CallState ncs)
{
// If the call is now disconnected, delete it.
if (ncs == Disconnected)
delete this;
else if (dynamic_cast<CTrunk*>(GetLineOwner()) == NULL)
{
if (GetCallState() != Holding)
{
if (ncs == Alerting)
SetCallState(WaitForAnswer, false);
else if (ncs == Connected)
SetCallState(Connected, false);
else if (ncs == Holding)
{
if (GetCallState() == Connected)
SetCallState(OtherSideHolding, false);
}
}
}
}// CCall::OnChangeCallState
/*****************************************************************************
** Procedure: CCall::MoveToLine
**
** Arguments: 'pLine' - New line owner
**
** Returns: void
**
** Description: Moves a call from one line to another
**
*****************************************************************************/
void CCall::MoveToLine(CLineDevice* pLine)
{
if (pLine == GetLineOwner())
return;
// Remove from the original line
m_pLine->OnCallDestroyed(this, false);
// Now mark the new line
m_pLine = pLine;
// Notify the line owner
m_pLine->OnCallCreated(this, false);
}// CCall::MoveToLine
/*****************************************************************************
** Procedure: CCall::Merge
**
** Arguments: 'pCall' - Call to copy into this one
**
** Returns: void
**
** Description: Replaces our call information (callerid, calledid)
**
*****************************************************************************/
void CCall::Merge(CCall* pCall)
{
// We are about to be attached to this call
if (pCall->GetAttachedCall() != NULL)
{
CCall* pOther = pCall->GetAttachedCall();
pOther->m_dwCallID = 0;
pOther->m_pOther = NULL;
pCall->m_pOther = NULL;
}
if (m_pOther != NULL)
{
m_pOther->m_pOther = NULL;
m_pOther = NULL;
}
// We get the callid and caller-info
m_dwCallID = pCall->m_dwCallID;
m_calleridInfo = pCall->m_calleridInfo;
m_calledidInfo = pCall->m_calledidInfo;
// Attach the two calls
AttachCall(pCall);
}// CCall::Copy
/*****************************************************************************
** Procedure: CCall::GetCallStateString
**
** Arguments: void
**
** Returns: String of call state
**
** Description: Returns the call state
**
*****************************************************************************/
CString CCall::GetCallStateString(int iType) const
{
UINT uiState[] = {
IDS_CS_UNKNOWN,
IDS_CS_DIALING,
IDS_CS_RINGING,
IDS_CS_ALERTING,
IDS_CS_ALERTING,
IDS_CS_CONNECTED,
IDS_CS_BUSY,
IDS_CS_DISCONNECTED,
IDS_CS_HOLDING,
IDS_CS_CONNECTED2,
IDS_CS_QUEUED
};
if (iType == -1)
iType = static_cast<int>(m_csState);
CString strBuff;
if (!strBuff.LoadString(uiState[iType]))
strBuff.LoadString(IDS_CS_UNKNOWN);
return strBuff;
}// CCall::GetCallStateString
| 25.024024 | 78 | 0.520941 | [
"object"
] |
187ba49e5762f41b64dce3ef3cf7a154bfcf3d99 | 68,233 | cpp | C++ | ExternalCode/libstructural/LibStructural/libstructural.cpp | dhlee4/Tinkercell_new | c4d1848bbb905f0e1f9e011837268ac80aff8711 | [
"BSD-3-Clause"
] | 1 | 2021-01-07T13:12:51.000Z | 2021-01-07T13:12:51.000Z | ExternalCode/libstructural/LibStructural/libstructural.cpp | dhlee4/Tinkercell_new | c4d1848bbb905f0e1f9e011837268ac80aff8711 | [
"BSD-3-Clause"
] | 7 | 2020-04-12T22:25:46.000Z | 2020-04-13T07:50:40.000Z | ExternalCode/libstructural/LibStructural/libstructural.cpp | daniel-anavaino/tinkercell | 7896a7f809a0373ab3c848d25e3691d10a648437 | [
"BSD-3-Clause"
] | 2 | 2020-04-12T21:57:01.000Z | 2020-04-12T21:59:29.000Z | #ifdef WIN32
#pragma warning(disable: 4996)
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <sstream>
#include "libstructural.h"
#include "libla.h"
#include "sbmlmodel.h"
#include "matrix.h"
#include "util.h"
#include "math.h"
#define SMALL_NUM 1.0E-9
#define PRINT_PRECISION 10
#define LINE "-----------------------------------------------------------------------------"
using namespace LIB_STRUCTURAL;
using namespace LIB_LA;
using namespace std;
#ifndef NO_SBML
// ----------------------------------------------------------------------------------------
// string loadSBML(string)
//
// This is the main method that the users should run their models with. The method takes
// the SBML file as an input (string). This could be in SBML level 1 or SBML level 2 format.
// The users should check the validity of the SBML files before loading it into the method.
// Conservation analysis is carried out using Householder QR algorithm to generate the L0
// matrix, from which other matrices of interest can subsequently be generated. The results
// of the analysis are output as a string and are also accessible from other methods in
// the API.
// ----------------------------------------------------------------------------------------
string LibStructural::loadSBML(string sSBML)
{
DELETE_IF_NON_NULL(_Model); _Model = new SBMLmodel(sSBML);
return analyzeWithQR();
}
string LibStructural::loadSBMLFromFile(string sFileName)
{
DELETE_IF_NON_NULL(_Model); _Model = SBMLmodel::FromFile(sFileName);
return analyzeWithQR();
}
//Initialization method, takes SBML as input
string LibStructural::loadSBMLwithTests(string sSBML)
{
DELETE_IF_NON_NULL(_Model); _Model = new SBMLmodel(sSBML);
stringstream oResult;
oResult << analyzeWithQR();
oResult << endl << endl;
oResult << getTestDetails();
return oResult.str();
}
void LibStructural::InitializeFromModel(LIB_STRUCTURAL::SBMLmodel& oModel)
{
numFloating = oModel.numFloatingSpecies();
numReactions = oModel.numReactions();
numBoundary = oModel.getModel()->getNumSpeciesWithBoundaryCondition();
_sModelName = (oModel.getModel()->isSetName() ? oModel.getModel()->getName() : oModel.getModel()->getId());
CREATE_ARRAY(spVec,int,numFloating);
CREATE_ARRAY(colVec,int,numReactions);
_consv_list.clear();
for (int i = 0; i < numFloating; i++)
{
const Species * species = oModel.getNthFloatingSpecies(i);
_speciesIndexList[i] = species->getId();
_speciesNamesList[i] = species->getName();
_speciesNamesList2[_speciesNamesList[i]] = i;
_speciesIndexList2[_speciesIndexList[i]] = i;
_speciesValueList[_speciesIndexList[i]] = ( species->isSetInitialConcentration() ? species->getInitialConcentration() : species->getInitialAmount());
_consv_list.push_back(_speciesIndexList[i]);
spVec[i] = i;
}
for (int i = 0; i < numReactions; i++)
{
const Reaction *reaction = oModel.getNthReaction(i);
_reactionIndexList[i] = reaction->getId();
_reactionNamesList[i] = reaction->getName();
colVec[i] = i;
}
for (int i = 0; i < numBoundary; i++)
{
const Species * species = oModel.getNthBoundarySpecies(i);
_bSpeciesIndexList[i] = species->getId();
_bSpeciesIndexList2[_bSpeciesIndexList[i]] = i;
_bSpeciesNamesList[i] = species->getName();
_bSpeciesNamesList2[_bSpeciesIndexList[i]] = i;
_bSpeciesValueList[_bSpeciesIndexList[i]] = ( species->isSetInitialConcentration() ? species->getInitialConcentration() : species->getInitialAmount());
}
}
#endif
void LibStructural::FreeMatrices()
{
// clear boundary species lists
_bSpeciesIndexList.clear(); _bSpeciesIndexList2.clear();
_bSpeciesNamesList.clear(); _bSpeciesNamesList2.clear();
_bSpeciesValueList.clear();
// clear reaction lists
_reactionIndexList.clear(); _reactionNamesList.clear();
// clear floating species lists
_speciesIndexList.clear(); _speciesIndexList2.clear();
_speciesNamesList.clear(); _speciesNamesList2.clear();
_speciesValueList.clear();
// delete allocated matrices
DELETE_IF_NON_NULL(_K0); DELETE_IF_NON_NULL(_N0);
DELETE_IF_NON_NULL(_Nr); DELETE_IF_NON_NULL(_L0);
DELETE_IF_NON_NULL(_L); DELETE_IF_NON_NULL(_K);
DELETE_IF_NON_NULL(_NullN); DELETE_IF_NON_NULL(_G);
DELETE_IF_NON_NULL(_Nmat); DELETE_IF_NON_NULL(_NmatT);
DELETE_IF_NON_NULL(_Nmat_orig); DELETE_IF_NON_NULL(_NmatT_orig);
// delete allocated arrays
DELETE_ARRAY_IF_NON_NULL(_T); DELETE_ARRAY_IF_NON_NULL(_IC);
DELETE_ARRAY_IF_NON_NULL(_BC);
DELETE_ARRAY_IF_NON_NULL(spVec); DELETE_ARRAY_IF_NON_NULL(colVec);
}
string LibStructural::GenerateResultString()
{
stringstream oBuffer;
oBuffer << LINE << endl << LINE << endl << "STRUCTURAL ANALYSIS MODULE : Results " << endl
<< LINE << endl << LINE << endl;
oBuffer << "Size of Stochiometric Matrix: " << _NumRows << " x " << _NumCols
<< " (Rank is " << _NumIndependent << ")";
if (_NumCols > 0)
{
oBuffer << endl << "Nonzero entries in Stochiometric Matrix: " << nz_count
<< " (" << _Sparsity << "% full)" << endl;
}
else
{
oBuffer << "This model has no reactions. " << endl;
}
oBuffer << endl << "Independent Species (" << _NumIndependent << ") :" << endl;
for (int i = 0; i < _NumIndependent; i++)
{
oBuffer << _speciesIndexList[spVec[i]];
if (i+1 < _NumIndependent) oBuffer << ", ";
}
oBuffer << endl << endl << "Dependent Species ";
if ((_NumRows == _NumIndependent) || (_NumCols == 0) || (zero_nmat))
{
oBuffer << ": NONE" << endl << endl;
}
else
{
oBuffer << "(" << _NumDependent << ") :" << endl;
for (int i = _NumIndependent; i < _NumRows; i++)
{
oBuffer << _speciesIndexList[spVec[i]];
if (i + 1 < _NumRows) oBuffer << ", ";
}
oBuffer << endl << endl;
}
oBuffer << "L0 : ";
if ((_NumRows == _NumIndependent))
{
oBuffer << "There are no dependencies. L0 is an EMPTY matrix";
}
else if ((_NumCols == 0))
{
oBuffer << "There are " << _NumRows << " dependencies. L0 is a " << _NumRows << "x" << _NumRows << " matrix.";
}
else if (zero_nmat)
{
oBuffer << "All " << _NumRows <<" species are independent. L is an identity matrix.";
}
else
{
oBuffer << "There " << (_NumDependent != 1 ? "are " : "is ")
<< _NumDependent << (_NumDependent != 1 ? " dependencies." : " dependency.")
<< " L0 is a " << _NumDependent << "x" << _NumIndependent << " matrix.";
}
oBuffer << endl << endl << "Conserved Entities";
if ((_NumCols == 0) || (zero_nmat))
{
oBuffer << endl;
for (int i=0; i<_NumRows; i++)
{
oBuffer << (i+1) << ": " << _speciesIndexList[spVec[i]] << endl;
}
}
else if (_NumRows == _NumIndependent)
{
oBuffer << ": NONE" << endl;
}
else
{
oBuffer << endl;
for (int i = 0; i < _NumDependent; i++)
{
oBuffer << (i+1) << ": " + _consv_list[i] << endl;
}
}
oBuffer << LINE << endl << LINE << endl
<< "Developed by the Computational Systems Biology Group at Keck Graduate Institute " << endl
<< "and the Saurolab at the Bioengineering Departmant at University of Washington." << endl
<< "Contact : Frank T. Bergmann (fbergman@u.washington.edu) or Herbert M. Sauro. " << endl << endl
<< " (previous authors) Ravishankar Rao Vallabhajosyula " << endl
<< LINE << endl << LINE << endl << endl;
return oBuffer.str();
}
void LibStructural::Initialize()
{
#ifndef NO_SBML
if (_Model != NULL)
{
// free used elements
// read species and reactions
InitializeFromModel(*_Model);
// build stoichiometry matrix
BuildStoichiometryMatrixFromModel(*_Model);
// initialize other matrices
InitializeFromStoichiometryMatrix(*_Nmat);
}
else
#endif
{
if (_Nmat->numCols() != _inputReactionNames.size())
{
_inputReactionNames.clear();
for (unsigned int i = 0; i < _Nmat->numCols(); i++)
{
stringstream sTemp; sTemp << i;
_inputReactionNames.push_back( sTemp.str() );
}
}
if (_Nmat->numRows() != _inputSpeciesNames.size())
{
_inputSpeciesNames.clear(); _inputValues.clear();
for (unsigned int i = 0; i < _Nmat->numRows(); i++)
{
stringstream sTemp; sTemp << i;
_inputSpeciesNames.push_back( sTemp.str() );
_inputValues.push_back ( 1.0 );
}
}
DoubleMatrix oCopy(*_Nmat);
InitializeFromStoichiometryMatrix( oCopy ,
_inputSpeciesNames, _inputReactionNames,
_inputValues);
}
}
void LibStructural::InitializeFromStoichiometryMatrix(DoubleMatrix& oMatrix,
vector<string>& speciesNames,
vector<string>& reactionNames,
vector<double>& concentrations)
{
// free used elements
FreeMatrices();
numFloating = speciesNames.size();
numReactions = reactionNames.size();
numBoundary = 0;
_sModelName = "untitled";
CREATE_ARRAY(spVec,int,numFloating);
CREATE_ARRAY(colVec,int,numReactions);
_consv_list.clear();
for (int i = 0; i < numFloating; i++)
{
_speciesIndexList[i] = speciesNames[i];
_speciesNamesList[i] = speciesNames[i];
_speciesNamesList2[_speciesNamesList[i]] = i;
_speciesIndexList2[_speciesIndexList[i]] = i;
_speciesValueList[_speciesIndexList[i]] = concentrations[i];
_consv_list.push_back(_speciesIndexList[i]);
spVec[i] = i;
}
for (int i = 0; i < numReactions; i++)
{
_reactionIndexList[i] = reactionNames[i];
_reactionNamesList[i] = reactionNames[i];
colVec[i] = i;
}
// initialize other matrices
InitializeFromStoichiometryMatrix(oMatrix);
}
void LibStructural::InitializeFromStoichiometryMatrix(DoubleMatrix& oMatrix)
{
_NumRows = oMatrix.numRows();
_NumCols = oMatrix.numCols();
if (_Nmat == NULL) _Nmat = new DoubleMatrix(oMatrix);
// number of non-zero elements
nz_count = 0;
for (int i=0; i<_NumRows; i++) {
for (int j=0; j<_NumCols; j++) {
if (fabs(oMatrix(i,j)) > _Tolerance) nz_count++;
}
}
zero_nmat = (nz_count == 0);
// get sparsity
_Sparsity = (double) (nz_count * 100)/(_NumRows*_NumCols);
// get transpose
DELETE_IF_NON_NULL(_NmatT); _NmatT = oMatrix.getTranspose();
// store copies of stoichimetry matrix and it's transpose
DELETE_IF_NON_NULL(_Nmat_orig); _Nmat_orig = new DoubleMatrix(oMatrix);
DELETE_IF_NON_NULL(_NmatT_orig);_NmatT_orig = new DoubleMatrix(*_NmatT);
// If the network has reactions only between boundary species, the stoichiometry matrix will be
// empty. This means that it is equivalent to a network without any reactions. Therefore, we need
// to construct the conservation matrices, dependent and independent species accordingly.
//
if (zero_nmat)
{
_NumIndependent = 0;
_NumDependent = 0;
_N0 = new DoubleMatrix(_NumDependent, _NumCols);
_K0 = new DoubleMatrix(_NumIndependent, _NumCols-_NumIndependent);
_Nr = new DoubleMatrix(_NumRows, _NumCols);
_K = new DoubleMatrix(_NumCols,_NumCols);
_NullN = new DoubleMatrix(_NumCols,_NumCols);
_L0 = new DoubleMatrix(_NumRows, _NumRows);
_L = new DoubleMatrix(_NumRows, _NumRows);
_G = new DoubleMatrix(_NumRows, _NumRows);
for (int i = 0; i < _NumRows; i++)
{
(*_L0)(i,i) =-1.0;
(*_G)(i,i) = 1.0;
}
for (int i = 0; i < _NumRows; i++)
{
for (int j = 0; j < _NumRows; j++)
{
(*_L)(i,j) = (*_L0) (j,i);
}
}
for (int i = 0; i < _NumCols; i++)
{
(*_K) (i,i) =-1.0;
(*_NullN) (i,i) =-1.0;
}
}
}
#ifndef NO_SBML
void LibStructural::BuildStoichiometryMatrixFromModel(LIB_STRUCTURAL::SBMLmodel& oModel)
{
_NumRows = numFloating;
_NumCols = numReactions;
DELETE_IF_NON_NULL(_Nmat); _Nmat = new DoubleMatrix(numFloating, numReactions);
for (int i = 0; i < numReactions; i++)
{
const Reaction* reaction = oModel.getNthReaction(i);
int numReactants = reaction->getNumReactants();
int numProducts = reaction->getNumProducts();
for (int j = 0; j < numReactants; j++)
{
const SpeciesReference* reference = reaction->getReactant(j);
if (_bSpeciesIndexList2.find(reference->getSpecies()) == _bSpeciesIndexList2.end())
{
int row_id = _speciesIndexList2[reference->getSpecies()];
(*_Nmat)(row_id,i) = (*_Nmat)(row_id,i) - (reference->getStoichiometry());
}
}
for (int j = 0; j < numProducts; j++)
{
const SpeciesReference* reference = reaction->getProduct(j);
if (_bSpeciesIndexList2.find(reference->getSpecies()) == _bSpeciesIndexList2.end())
{
int row_id = _speciesIndexList2[reference->getSpecies()];
(*_Nmat)(row_id,i) = (*_Nmat)(row_id,i) + (reference->getStoichiometry());
}
}
}
}
#endif
//Uses QR Decomposition for Conservation analysis
string LibStructural::analyzeWithQR()
{
stringstream oResult;
Initialize();
if (_NumRows == 0)
{
oResult << "Model has no floating species.";
}
else if (_NumCols == 0)
{
oResult << "Model has no Reactions.";
}
else
{
vector< DoubleMatrix*> oQRResult = LibLA::getInstance()->getQRWithPivot(*_NmatT);
DoubleMatrix *Q = oQRResult[0];
DoubleMatrix *R = oQRResult[1];
DoubleMatrix *P = oQRResult[2];
Util::gaussJordan(*R, _Tolerance);
// The rank is obtained by looking at the number of zero rows of R, which is
// a lower trapezoidal matrix.
_NumIndependent = Util::findRank(*R, _Tolerance);
_NumDependent = _NumRows - _NumIndependent;
DoubleMatrix L0t(_NumIndependent, _NumDependent);
for (int i = 0; i < _NumIndependent; i++)
{
for (int j = 0; j < _NumDependent; j++)
{
L0t(i,j) = (*R)(i,j+_NumIndependent);
}
}
DELETE_IF_NON_NULL(_L0); _L0 = L0t.getTranspose();
// reorder species
for (unsigned int i = 0; i < P->numRows(); i++)
{
for (unsigned int j = 0; j < P->numCols(); j++)
{
if ((*P)(i,j) == 1)
{
spVec[j]=i;
break;
}
}
}
DELETE_IF_NON_NULL(_G); _G = new DoubleMatrix(_NumDependent, _NumRows);
for (int i = 0; i < _NumDependent; i++)
{
for (int j = 0; j < _NumIndependent; j++)
{
(*_G)(i,j) = -(*_L0)(i,j);
}
(*_G)(i,_NumIndependent+i) = 1.0;
}
reorderNmatrix();
computeNrMatrix();
computeN0Matrix();
computeLinkMatrix();
computeConservedSums();
computeConservedEntities();
computeK0andKMatrices();
DELETE_IF_NON_NULL(Q); DELETE_IF_NON_NULL(R); DELETE_IF_NON_NULL(P);
oResult << GenerateResultString();
}
return oResult.str();
}
void LibStructural::reorderNmatrix()
{
DELETE_IF_NON_NULL(_Nmat); _Nmat = new DoubleMatrix(_NumRows, _NumCols);
for (int i=0; i<_NumRows; i++)
{
for (int j=0; j<_NumCols; j++)
{
(*_Nmat)(i,j) = (* _NmatT_orig)(j,spVec[i]);
}
}
}
void LibStructural::computeNrMatrix()
{
DELETE_IF_NON_NULL(_Nr); _Nr = new DoubleMatrix(_NumIndependent, _NumCols);
for (int i = 0; i < _NumIndependent; i++)
{
for (int j = 0; j < _NumCols; j++)
{
(*_Nr)(i,j) = (*_NmatT_orig)(j,spVec[i]);
}
}
}
void LibStructural::computeN0Matrix()
{
DELETE_IF_NON_NULL(_N0); _N0 = new DoubleMatrix(_NumDependent, _NumCols);
for (int i=0; i<_NumDependent; i++)
{
for (int j=0; j<_NumCols; j++)
{
(*_N0)(i,j) = (*_NmatT_orig)(j,spVec[_NumIndependent+i]);
}
}
}
void LibStructural::computeLinkMatrix()
{
DELETE_IF_NON_NULL(_L); _L = new DoubleMatrix(_NumRows, _NumIndependent);
for (int i=0; i<_NumIndependent; i++)
{
(*_L)(i,i) = 1.0;
}
for (int i=_NumIndependent; i<_NumRows; i++)
{
for (int j=0; j<_NumIndependent; j++)
{
(*_L)(i,j) = (*_L0)(i-_NumIndependent,j);
}
}
}
void LibStructural::computeConservedSums()
{
CREATE_ARRAY(_IC,double,numFloating);
for (int i=0; i<numFloating; i++)
{
_IC[i] = _speciesValueList[_speciesIndexList[spVec[i]]];
}
CREATE_ARRAY(_BC,double,numBoundary);
for (int i=0; i<numBoundary; i++)
{
_BC[i] = _bSpeciesValueList[_bSpeciesIndexList[i]];
}
DELETE_ARRAY_IF_NON_NULL(_T);
if ((_NumCols == 0) || (zero_nmat))
{
_T = new double[numFloating];
for (int i=0; i<numFloating; i++)
{
_T[i] = _IC[i];
}
}
else
{
_T = new double[_NumDependent]; memset(_T, 0, sizeof(double)*_NumDependent);
for (int i=0; i<_NumDependent; i++)
{
for (int j=0; j<numFloating; j++)
{
if (fabs((*_G)(i,j)) > _Tolerance)
{
_T[i] = _T[i] + (*_G)(i,j)*_IC[j];
}
}
}
}
}
void LibStructural::computeConservedEntities()
{
double gval; string spname;
_consv_list.clear();
if (_NumCols > 0)
{
for (int i=0; i<(_NumDependent); i++)
{
stringstream oBuilder;
for (int j=0; j<numFloating; j++)
{
gval = (*_G)(i,j);
if (fabs(gval) > 0.0)
{
spname = _speciesIndexList[spVec[j]];
if (gval < 0)
{
if (fabs(gval + 1) < _Tolerance)
oBuilder << " - " << spname;
else
oBuilder << " - " << fabs(gval) << " " << spname;
}
if (gval > 0)
{
if (fabs(gval - 1) < _Tolerance)
oBuilder << " + " << spname;
else
oBuilder << " + " << fabs(gval) << " " << spname;
}
}
}
_consv_list.push_back (oBuilder.str());
}
}
else
{
for (int i=0; i<_NumRows; i++)
{
_consv_list.push_back ( _speciesIndexList[spVec[i]] );
}
}
}
void LibStructural::computeK0andKMatrices()
{
DoubleMatrix Nmat_h(_NumRows, _NumCols);
for (int i = 0; i < _NumRows; i++)
{
for (int j = 0; j < _NumCols; j++)
{
Nmat_h(i,j) = (*_Nmat_orig)(spVec[i],j);
}
}
DoubleMatrix *Q; DoubleMatrix *R; DoubleMatrix *P;
if ((_NumRows == 1 ) && ( _NumCols == 1 ))
{
Q = new DoubleMatrix(1,1); (*Q)(0,0) = 1.0;
R = new DoubleMatrix(1,1); (*R)(0,0) = (*_NmatT)(0,0);
P = new DoubleMatrix(1,1); (*P)(0,0) = 1.0;
}
else if ((_NumRows == 1 ) && ( _NumCols > 1 ))
{
Q = new DoubleMatrix(1,1); (*Q)(0,0) = 1.0;
R = new DoubleMatrix(1,_NumCols);
P = new DoubleMatrix(_NumCols,_NumCols);
for (int i = 0; i < _NumCols; i++)
{
(*R)(0,i) = Nmat_h(0,i);
(*P)(i,i) = 1.0;
}
}
else
{
vector< DoubleMatrix *> oResult = LibLA::getInstance()->getQRWithPivot(Nmat_h);
Q = oResult[0]; R = oResult[1]; P = oResult[2];
}
//Util::gaussJordan(*R, _Tolerance);
Util::GaussJordan(*R, _Tolerance);
int nDependent = _NumCols-_NumIndependent;
DELETE_IF_NON_NULL(_K0); _K0 = new DoubleMatrix(_NumIndependent, nDependent);
for (int i=0; i <_NumIndependent; i++)
{
for (int j=0; j< _NumCols-_NumIndependent ; j++)
{
(*_K0)(i,j) = Util::RoundToTolerance( - (*R)(i,j+_NumIndependent), _Tolerance);
}
}
DELETE_IF_NON_NULL(_K); _K = new DoubleMatrix(_NumCols, _NumCols - _NumIndependent);
for (int i=0; i<(_NumCols - _NumIndependent); i++)
{
(*_K)(i,i) = 1.0;
}
for (int i=0; i<_NumIndependent ; i++)
{
for (int j=0; j<(_NumCols - _NumIndependent); j++)
{
(*_K)(i+(_NumCols - _NumIndependent),j) = (*_K0)(i,j);
}
}
// reorder species
for (unsigned int i = 0; i < P->numRows(); i++)
{
for (unsigned int j = 0; j < P->numCols(); j++)
{
if ((*P)(i,j) == 1)
{
colVec[j]=i;
break;
}
}
}
DELETE_IF_NON_NULL(_NullN); _NullN = new DoubleMatrix(*_K);
DELETE_IF_NON_NULL(Q); DELETE_IF_NON_NULL(R); DELETE_IF_NON_NULL(P);
}
//Uses LU Decomposition for Conservation analysis
string LibStructural::analyzeWithLU()
{
stringstream oResult;
LU_Result * oLUResult = NULL;
Initialize();
if (_NumRows == 0)
{
oResult << "Model has no floating species.";
}
else if (_NumCols == 0)
{
oResult << "Model has no Reactions.";
}
else
{
LU_Result * oLUResult = LibLA::getInstance()->getLU(*_NmatT);
DoubleMatrix* L = oLUResult->L;
DoubleMatrix* U = oLUResult->U;
IntMatrix* P = oLUResult->P;
// nInfo is zero if there are no singular values on Umat pivot positions
// if there are zeros, the columns of NmatT have to be permuted.
// First we check if nInfo is < 0 (illegal value) or if it is > 0 (this
// means a zero has been encountered on the diagonal while computing LU
// factorization). nInfo = 0 implies a successful exit. So we have to
// to swap the cols only if nInfo > 0
int nInfo = oLUResult->nInfo;
if (nInfo < 0 )
{
throw new ApplicationException("Exception in analyzeWithLU()", "Illegal Value encountered while performing LU Factorization");
}
else if (nInfo > 0)
{
// swap columns;
int z_pivot = nInfo-1;
//int nz_pivot = nInfo;
unsigned int pvt_id, col1, col2, col1_next;
col1 = z_pivot;
while (col1 < U->numRows())
{
col2 = col1 + 1;
col1_next = col2;
while (col2 < U->numRows())
{
pvt_id = z_pivot;
if (fabs((*U)(col2,col2)) < _Tolerance) { // then the pivot at U[i][i] is a zero
col2++;
continue;
}
// here we have found a nonzero pivot - so swap it with col1
_NmatT->swapCols(col1,col2);
U->swapCols(col1,col2);
int tmp = spVec[col1];
spVec[col1] = spVec[col2];
spVec[col2] = tmp;
break;
}
col1 = col1_next;
}
DELETE_IF_NON_NULL(oLUResult);
oLUResult = LibLA::getInstance()->getLU(*_NmatT);
L = oLUResult->L;
U = oLUResult->U;
P = oLUResult->P;
}
Util::gaussJordan(*U, _Tolerance);
// The rank is obtained by looking at the number of zero rows of R, which is
// a lower trapezoidal matrix.
_NumIndependent = Util::findRank(*U, _Tolerance);
_NumDependent = _NumRows - _NumIndependent;
DoubleMatrix L0t(_NumIndependent, _NumDependent);
for (int i = 0; i < _NumIndependent; i++)
{
for (int j = 0; j < _NumDependent; j++)
{
L0t(i,j) = (*U)(i,j+_NumIndependent);
}
}
_L0 = L0t.getTranspose();
DELETE_IF_NON_NULL(_G); _G = new DoubleMatrix(_NumDependent, _NumRows);
for (int i = 0; i < _NumDependent; i++)
{
for (int j = 0; j < _NumIndependent; j++)
{
(*_G)(i,j) = -(*_L0)(i,j);
}
(*_G)(i,_NumIndependent+i) = 1.0;
}
reorderNmatrix();
computeNrMatrix();
computeN0Matrix();
computeLinkMatrix();
computeConservedSums();
computeConservedEntities();
computeK0andKMatrices();
oResult << GenerateResultString();
}
DELETE_IF_NON_NULL(oLUResult);
return oResult.str();
}
//Uses LU Decomposition for Conservation analysis
string LibStructural::analyzeWithLUandRunTests()
{
stringstream oResult;
oResult << analyzeWithLU();
oResult << endl << endl;
oResult << getTestDetails();
return oResult.str();
}
//Uses fully pivoted LU Decomposition for Conservation analysis
string LibStructural::analyzeWithFullyPivotedLU()
{
stringstream oResult;
LU_Result * oLUResult = NULL;
Initialize();
if (_NumRows == 0)
{
oResult << "Model has no floating species.";
}
else if (_NumCols == 0)
{
oResult << "Model has no Reactions.";
}
else
{
if (zero_nmat)
{
oResult << "Model has empty stoiciometry matrix.";
}
else
{
oLUResult = LibLA::getInstance()->getLUwithFullPivoting(*_NmatT);
DoubleMatrix* L = oLUResult->L;
DoubleMatrix* U = oLUResult->U;
IntMatrix* P = oLUResult->P;
IntMatrix* Q = oLUResult->Q;
// nInfo is zero if there are no singular values on Umat pivot positions
// if there are zeros, the columns of NmatT have to be permuted.
// First we check if nInfo is < 0 (illegal value) or if it is > 0 (this
// means a zero has been encountered on the diagonal while computing LU
// factorization). nInfo = 0 implies a successful exit. So we have to
// to swap the cols only if nInfo > 0
int nInfo = oLUResult->nInfo;
if (nInfo < 0 )
{
throw new ApplicationException("Exception in analyzeWithLU()", "Illegal Value encountered while performing LU Factorization");
}
else if (nInfo > 0)
{
// swap columns;
int z_pivot = nInfo-1;
//int nz_pivot = nInfo;
unsigned int pvt_id, col1, col2, col1_next;
col1 = z_pivot;
while (col1 < U->numRows())
{
col2 = col1 + 1;
col1_next = col2;
while (col2 < U->numRows())
{
pvt_id = z_pivot;
if (fabs((*U)(col2,col2)) < _Tolerance) { // then the pivot at U[i][i] is a zero
col2++;
continue;
}
// here we have found a nonzero pivot - so swap it with col1
_NmatT->swapCols(col1,col2);
U->swapCols(col1,col2);
int tmp = spVec[col1];
spVec[col1] = spVec[col2];
spVec[col2] = tmp;
break;
}
col1 = col1_next;
}
DELETE_IF_NON_NULL(oLUResult);
oLUResult = LibLA::getInstance()->getLUwithFullPivoting(*_NmatT);
L = oLUResult->L;
U = oLUResult->U;
P = oLUResult->P;
Q = oLUResult->Q;
}
Util::gaussJordan(*U, _Tolerance);
// The rank is obtained by looking at the number of zero rows of R, which is
// a lower trapezoidal matrix.
_NumIndependent = Util::findRank(*U, _Tolerance);
_NumDependent = _NumRows - _NumIndependent;
DoubleMatrix L0t(_NumIndependent, _NumDependent);
for (int i = 0; i < _NumIndependent; i++)
{
for (int j = 0; j < _NumDependent; j++)
{
L0t(i,j) = (*U)(i,j+_NumIndependent);
}
}
DELETE_IF_NON_NULL(_L0); _L0 = L0t.getTranspose();
int count = 0;
for (unsigned int i=0; i<Q->numRows(); i++) {
for (unsigned int j=0; j<Q->numCols(); j++) {
if ((*Q)(i,j) == 1) {
if ((int)j < _NumRows) {
spVec[count] = j;
count = count + 1;
break;
}
}
}
}
DELETE_IF_NON_NULL(_G); _G = new DoubleMatrix(_NumDependent, _NumRows);
for (int i = 0; i < _NumDependent; i++)
{
for (int j = 0; j < _NumIndependent; j++)
{
(*_G)(i,j) = -(*_L0)(i,j);
}
(*_G)(i,_NumIndependent+i) = 1.0;
}
reorderNmatrix();
computeNrMatrix();
computeN0Matrix();
computeLinkMatrix();
computeConservedSums();
computeConservedEntities();
computeK0andKMatrices();
}
DELETE_IF_NON_NULL(oLUResult);
oResult << GenerateResultString();
}
return oResult.str();
}
//Uses fully pivoted LU Decomposition for Conservation analysis
string LibStructural::analyzeWithFullyPivotedLUwithTests()
{
stringstream oResult;
oResult << analyzeWithFullyPivotedLU();
oResult << endl << endl;
oResult << getTestDetails();
return oResult.str();
}
//Returns L0 Matrix
LibStructural::DoubleMatrix* LibStructural::getL0Matrix()
{
if ( (_NumRows == _NumIndependent) || (_NumRows == 0) || _L0 == NULL)
{
return new DoubleMatrix();
}
else if (_NumCols == 0 || zero_nmat)
{
return new DoubleMatrix(*_L0);
}
else
{
DoubleMatrix* oMatrix = new DoubleMatrix(_NumRows - _NumIndependent, _NumIndependent);
for (int i = 0; i < _NumRows - _NumIndependent; i++)
{
for (int j = 0; j < _NumIndependent; j++)
{
(*oMatrix)(i,j) = (*_L0)(i,j);
}
}
return oMatrix;
}
}
void LibStructural::getL0MatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getDependentSpecies();
oCols = getIndependentSpecies();
}
//Returns Nr Matrix
LibStructural::DoubleMatrix* LibStructural::getNrMatrix()
{
return _Nr;
}
void LibStructural::getNrMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getIndependentSpecies();
oCols = getReactions();
}
//Returns N0 Matrix
LibStructural::DoubleMatrix* LibStructural::getN0Matrix()
{
return _N0;
}
void LibStructural::getN0MatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getDependentSpecies();
oCols = getReactions();
}
//Returns L, the Link Matrix
LibStructural::DoubleMatrix* LibStructural::getLinkMatrix()
{
return _L;
}
void LibStructural::getLinkMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getReorderedSpecies();
oCols = getIndependentSpecies();
}
//Returns K0
LibStructural::DoubleMatrix* LibStructural::getK0Matrix()
{
return _K0;
}
void LibStructural::getK0MatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
vector<string> oReactionLables = getReorderedReactions();
DoubleMatrix *k0 = getK0Matrix();
int nDependent = k0->numCols();
int nIndependent = k0->numRows();
for (int i = 0; i < nDependent; i++)
{
oCols.push_back(oReactionLables[nIndependent + i]);
}
for (int i = 0; i < nIndependent; i++)
{
oRows.push_back(oReactionLables[i]);
}
}
//Returns Nullspace
LibStructural::DoubleMatrix* LibStructural::getKMatrix()
{
return _K;
}
void LibStructural::getKMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
vector<string> oReactionLables = getReorderedReactions();
DoubleMatrix *k0 = getK0Matrix();
int nDependent = k0->numCols();
int nIndependent = k0->numRows();
for (int i = 0; i < nDependent; i++)
{
oCols.push_back(oReactionLables[nIndependent + i]);
oRows.push_back(oReactionLables[nIndependent + i]);
}
for (int i = 0; i < nIndependent; i++)
{
oRows.push_back(oReactionLables[i]);
}
}
vector< string > LibStructural::getReorderedReactions()
{
vector< string > oResult;
for (int i = 0; i < numReactions; i++)
{
oResult.push_back(_reactionIndexList[colVec[i]]);
}
return oResult;
}
//Returns the reordered list of species
vector< string > LibStructural::getReorderedSpecies()
{
vector< string > oResult;
for (int i = 0; i < numFloating; i++)
{
oResult.push_back(_speciesIndexList[spVec[i]]);
}
return oResult;
}
//Returns the list of species
vector< string > LibStructural::getSpecies()
{
vector< string > oResult;
for (int i = 0; i < numFloating; i++)
{
oResult.push_back(_speciesIndexList[i]);
}
return oResult;
}
//Returns the actual names of the reordered species
vector< string > LibStructural::getReorderedSpeciesNamesList()
{
vector< string > oResult;
for (int i = 0; i < numFloating; i++)
{
oResult.push_back(_speciesNamesList[spVec[i]]);
}
return oResult;
}
//Returns the list of independent species
vector< string > LibStructural::getIndependentSpecies()
{
vector< string > oResult;
if (numFloating == 0)
return oResult;
else if (numReactions == 0 || zero_nmat)
{
return getReorderedSpecies();
}
else
{
for (int i=0; i<_NumIndependent; i++)
{
oResult.push_back(_speciesIndexList[spVec[i]]);
}
}
return oResult;
}
//! Returns the list of independent reactions
vector< string > LibStructural::getIndependentReactionIds()
{
vector <string> result;
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
for (int j = 0; j < nIndependent; j++)
{
result.push_back(_reactionIndexList[colVec[j]]);
}
return result;
}
//! Returns the list of dependent reactions
vector< string > LibStructural::getDependentReactionIds()
{
vector<string> result;
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
for (int j = 0; j < nDependent; j++)
{
result.push_back(_reactionIndexList[colVec[j + nIndependent]]);
}
return result;
}
//Returns the actual names of the independent species
vector< string > LibStructural::getIndependentSpeciesNamesList()
{
vector< string > oResult;
if (numFloating == 0)
return oResult;
else if (numReactions == 0 || zero_nmat)
{
return getReorderedSpeciesNamesList();
}
else
{
for (int i=0; i<_NumIndependent; i++)
{
oResult.push_back(_speciesNamesList[spVec[i]]);
}
}
return oResult;
}
//Returns the list of dependent species
vector< string > LibStructural::getDependentSpecies()
{
vector< string > oResult;
if (numFloating == 0 || numReactions == 0 || zero_nmat || _NumRows == _NumIndependent)
return oResult;
for (int i = 0; i < _NumDependent; i++)
{
oResult.push_back( _speciesIndexList[spVec[_NumIndependent+i]] );
}
return oResult;
}
//Returns the actual names of the dependent species
vector< string > LibStructural::getDependentSpeciesNamesList()
{
vector< string > oResult;
if (numFloating == 0 || numReactions == 0 || zero_nmat || _NumRows == _NumIndependent)
return oResult;
for (int i = 0; i < _NumDependent; i++)
{
oResult.push_back( _speciesNamesList[spVec[_NumIndependent+i]] );
}
return oResult;
}
//Returns Initial Conditions used in the model
vector< pair <string, double> > LibStructural::getInitialConditions()
{
vector< pair <string, double> > oResult;
for (int i = 0; i < _NumRows; i++)
{
oResult.push_back( pair< string, double> (_speciesIndexList[spVec[i]], _IC[i]));
}
return oResult;
}
//Returns the list of Reactions
vector< string > LibStructural::getReactions()
{
vector< string > oResult;
for (int i = 0; i < numReactions; i++)
{
oResult.push_back( _reactionIndexList[i] );
}
return oResult;
}
//Returns actual names of the Reactions
vector< string > LibStructural::getReactionsNamesList()
{
vector< string > oResult;
for (int i = 0; i < numReactions; i++)
{
oResult.push_back( _reactionNamesList[i] );
}
return oResult;
}
//Returns Gamma, the conservation law array
LibStructural::DoubleMatrix* LibStructural::getGammaMatrix()
{
return _G;
}
void LibStructural::getGammaMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
DoubleMatrix *G = getGammaMatrix();
for (unsigned int i = 0; i < G->numRows(); i++)
{
stringstream stream; stream << i;
oRows.push_back(stream.str());
}
oCols = getReorderedSpecies();
}
//Returns algebraic expressions for conserved cycles
vector< string > LibStructural::getConservedLaws()
{
vector <string > oResult;
if (_NumRows == 0 || _NumRows == _NumIndependent)
{
return oResult;
}
else if (numReactions == 0)
{
for (int i = 0; i < _NumRows; i++)
{
oResult.push_back(_consv_list[i]);
}
}
else
{
for (int i = 0; i < _NumRows-_NumIndependent; i++)
{
oResult.push_back(_consv_list[i]);
}
}
return oResult;
}
//Returns values for conserved cycles using Initial conditions
vector< double > LibStructural::getConservedSums()
{
vector< double > oResult;
if (_NumCols == 0 || zero_nmat)
{
computeConservedSums();
for (int i = 0; i < _NumRows; i++)
{
oResult.push_back(_T[i]);
}
}
else
{
for (int i = 0; i < _NumRows - _NumIndependent; i++)
{
oResult.push_back( _T[i] );
}
}
return oResult;
}
//Returns the original stoichiometry matrix
LibStructural::DoubleMatrix* LibStructural::getStoichiometryMatrix()
{
return _Nmat_orig;
}
void LibStructural::getStoichiometryMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getSpecies();
oCols = getReactions();
}
//Returns reordered stoichiometry matrix
LibStructural::DoubleMatrix* LibStructural::getReorderedStoichiometryMatrix()
{
return _Nmat;
}
void LibStructural::getReorderedStoichiometryMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getReorderedSpecies();
oCols = getReactions();
}
bool LibStructural::testConservationLaw_1()
{
bool bTest1 = true;
if (_G == NULL || _Nmat == NULL) return false;
DoubleMatrix* Zmat = Util::matMult((_NumRows-_NumIndependent), _NumRows, *_G, *_Nmat, _NumCols);
for (int i = 0; i < _NumRows - _NumIndependent; i++)
{
for (int j = 0; j < _NumCols; j++)
{
if (fabs((*Zmat)(i,j)) > _Tolerance)
{
delete Zmat;
return false;
}
}
}
delete Zmat;
return bTest1;
}
bool LibStructural::testConservationLaw_2()
{
if (_Nmat_orig == NULL) return false;
vector <double> singularVals = LibLA::getInstance()->getSingularValsBySVD(*_Nmat_orig);
_SvdRankNmat = min(_NumRows, _NumCols);
for (unsigned int i=0; i<singularVals.size(); i++)
{
if (fabs(singularVals[i]) < _Tolerance) _SvdRankNmat--;
}
if (_SvdRankNmat != _NumIndependent) return false;
return true;
}
bool LibStructural::testConservationLaw_3()
{
if (_Nr == NULL) return false;
vector <double> singularVals = LibLA::getInstance()->getSingularValsBySVD(*_Nr);
_SvdRankNr = _NumIndependent;
for (unsigned int i=0; i<singularVals.size(); i++)
{
if (fabs(singularVals[i]) < _Tolerance) _SvdRankNr--;
}
if (_SvdRankNr < _NumIndependent) return false;
return true;
}
bool LibStructural::testConservationLaw_4()
{
if (_Nmat == NULL) return false;
vector < DoubleMatrix* > oResult = LibLA::getInstance()->getQRWithPivot(*_Nmat);
DoubleMatrix* Q = oResult[0];
DoubleMatrix* R = oResult[1];
DoubleMatrix* P = oResult[2];
DoubleMatrix* Q11 = Util::getSubMatrix(Q->numRows(), Q->numCols(), _NumIndependent, _NumIndependent, 0, 0, *Q);
vector < Complex > q11Eigenvalues = LibLA::getInstance()->getEigenValues(*Q11);
_QrRankNmat = 0;
double absval = 0.0;
for (unsigned int i=0; i<q11Eigenvalues.size(); i++)
{
absval = sqrt( (q11Eigenvalues[i].Real)*(q11Eigenvalues[i].Real) + (q11Eigenvalues[i].Imag)*(q11Eigenvalues[i].Imag) );
if (absval > _Tolerance) _QrRankNmat++;
}
bool test4 = (_QrRankNmat == _NumIndependent);
DELETE_IF_NON_NULL(Q); DELETE_IF_NON_NULL(R); DELETE_IF_NON_NULL(P); DELETE_IF_NON_NULL(Q11);
return test4;
}
bool LibStructural::testConservationLaw_5()
{
if (_Nmat == NULL || _L0 == NULL) return false;
vector < DoubleMatrix* > oResult = LibLA::getInstance()->getQRWithPivot(*_Nmat);
DoubleMatrix* Q = oResult[0];
DoubleMatrix* R = oResult[1];
DoubleMatrix* P = oResult[2];
DoubleMatrix* Q11 = Util::getSubMatrix(Q->numRows(), Q->numCols(), _NumIndependent, _NumIndependent, 0, 0, *Q);
DoubleMatrix* Q21 = Util::getSubMatrix(Q->numRows(), Q->numCols(), Q->numRows() - _NumIndependent, _NumIndependent, _NumIndependent, 0, *Q);
DoubleMatrix* Q11inv = NULL;
if (Q11->numRows() * Q11->numCols() == 0)
{
Q11inv = new DoubleMatrix(0,0);
}
else
{
try { Q11inv = LibLA::getInstance()->inverse(*Q11); } catch (...) {}
if (Q11inv == NULL)
{
delete Q; delete R; delete P; delete Q11; delete Q21;
return false;
}
}
DoubleMatrix* L0x = Util::matMult((Q->numRows() - _NumIndependent), _NumIndependent, *Q21, *Q11inv, Q11inv->numCols());
bool test5 = true;
double val = 0.0;
for (unsigned int i=0; i<(Q->numRows() - _NumIndependent); i++)
{
for (int j=0; j<_NumIndependent; j++)
{
val = (*L0x)(i,j) - (*_L0)(i,j);
if (fabs(val) > _Tolerance)
{
test5 = false;
}
}
}
delete Q; delete R; delete P; delete Q11; delete Q21; delete Q11inv; delete L0x;
return test5;
}
// Returns the NIC Matrix (partition of linearly independent columns of Nr)
DoubleMatrix* LibStructural::getNICMatrix()
{
if (_Nr == NULL || _K0 == NULL) return NULL;
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
DoubleMatrix *oCopy = new DoubleMatrix(_Nr->numRows(), nIndependent);
for (unsigned int i = 0; i < _Nr->numRows(); i++)
{
for (int j = 0; j < nIndependent; j++)
{
(*oCopy)(i,j) = (*_Nr)(i, colVec[j]);
}
}
return oCopy;
}
// Returns the NDC Matrix (partition of linearly dependent columns of Nr)
DoubleMatrix* LibStructural::getNDCMatrix()
{
if (_Nr == NULL || _K0 == NULL) return NULL;
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
DoubleMatrix *oCopy = new DoubleMatrix(_Nr->numRows(), nDependent);
for (unsigned int i = 0; i < _Nr->numRows(); i++)
{
for (int j = 0; j < nDependent; j++)
{
(*oCopy)(i,j) = (*_Nr)(i, colVec[j + nIndependent]);
}
}
return oCopy;
}
void LibStructural::getColumnReorderedNrMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getReorderedSpecies();
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
for (int j = 0; j < nDependent; j++)
{
oCols.push_back(_reactionIndexList[colVec[j + nIndependent]]);
}
for (int j = 0; j < nIndependent; j++)
{
oCols.push_back(_reactionIndexList[colVec[j]]);
}
}
void LibStructural::getNICMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getReorderedSpecies();
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
for (int j = 0; j < nIndependent; j++)
{
oCols.push_back(_reactionIndexList[colVec[j]]);
}
}
void LibStructural::getNDCMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
oRows = getReorderedSpecies();
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
for (int j = 0; j < nDependent; j++)
{
oCols.push_back(_reactionIndexList[colVec[j + nIndependent]]);
}
}
DoubleMatrix* LibStructural::getColumnReorderedNrMatrix()
{
if (_Nr == NULL || _K0 == NULL) return NULL;
DoubleMatrix *oCopy = new DoubleMatrix(_Nr->numRows(), _Nr->numCols());
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
for (unsigned int i = 0; i < _Nr->numRows(); i++)
{
for (int j = 0; j < nDependent; j++)
{
(*oCopy)(i,j) = (*_Nr)(i, colVec[j + nIndependent]);
}
for (int j = 0; j < nIndependent; j++)
{
(*oCopy)(i,j + nDependent) = (*_Nr)(i, colVec[j]);
}
}
return oCopy;
}
DoubleMatrix* LibStructural::getFullyReorderedStoichiometryMatrix()
{
try
{
// get Column reordered Matrix
DoubleMatrix* oTemp = getColumnReorderedNrMatrix();
// then the result matrix will be the combined NR and N0 matrix
DoubleMatrix* oResult = new DoubleMatrix(oTemp->numRows() + _N0->numRows(), oTemp->numCols());
int nDependent = _K0->numCols();
int nIndependent = _Nr->numCols() - nDependent;
for (unsigned int i = 0; i < oTemp->numRows(); i++)
{
for (unsigned int j = 0; j < oTemp->numCols(); j++)
{
(*oResult)(i,j) = (*oTemp)(i,j);
}
}
// now fill the last rows with reordered N0;
for (unsigned int i = 0; i < _N0->numRows(); i++)
{
for (unsigned int i = 0; i < _Nr->numRows(); i++)
{
for (int j = 0; j < nDependent; j++)
{
(*oResult)(i+oTemp->numRows(),j) = (*_N0)(i, colVec[j + nIndependent]);
}
for (int j = 0; j < nIndependent; j++)
{
(*oResult)(i+oTemp->numRows(),j + nDependent) = (*_N0)(i, colVec[j]);
}
}
}
delete oTemp;
return oResult;
}
catch(...)
{
}
return NULL;
}
//! Returns Labels for the fully Reordered stoichiometry Matrix
/*!
\param oRows a string vector that will be overwritten to hold the row labels
\param oCols a string vector that will be overwritten to hold the column labels.
*/
void LibStructural::getFullyReorderedStoichiometryMatrixLabels(vector< string > &oRows, vector< string > &oCols )
{
getColumnReorderedNrMatrixLabels(oRows, oCols);
vector<string> dependent = getDependentSpecies();
vector<string>::iterator it;
for( it = dependent.begin(); it != dependent.end(); it++ )
oRows.push_back(*it);
}
bool LibStructural::testConservationLaw_6()
{
bool bTest1 = true;
if (_K0 == NULL || _NmatT == NULL) return false;
DoubleMatrix* oCopy = getColumnReorderedNrMatrix();
DoubleMatrix* Zmat = Util::matMult(*oCopy, *_K);
for (unsigned int i = 0; i < Zmat->numRows(); i++)
{
for (unsigned int j = 0; j < Zmat->numCols(); j++)
{
if (fabs((*Zmat)(i,j)) > _Tolerance)
{
delete Zmat; delete oCopy;
return false;
}
}
}
delete Zmat;delete oCopy;
return bTest1;
}
//Tests if conservation laws are correct
vector< string > LibStructural::validateStructuralMatrices()
{
vector < string > oResult;
if (testConservationLaw_1()) oResult.push_back("Pass");
else oResult.push_back("Fail");
if (testConservationLaw_2()) oResult.push_back("Pass");
else oResult.push_back("Fail");
if (testConservationLaw_3()) oResult.push_back("Pass");
else oResult.push_back("Fail");
if (testConservationLaw_4()) oResult.push_back("Pass");
else oResult.push_back("Fail");
if (testConservationLaw_5()) oResult.push_back("Pass");
else oResult.push_back("Fail");
if (testConservationLaw_6()) oResult.push_back("Pass");
else oResult.push_back("Fail");
return oResult;
}
//Return Details about conservation tests
string LibStructural::getTestDetails()
{
stringstream oBuffer;
vector < string > testResults = validateStructuralMatrices();
oBuffer << "Testing Validity of Conservation Laws." << endl << endl;
if (testResults[0] == "Pass")
oBuffer << "Passed Test 1 : Gamma*N = 0 (Zero matrix)" << endl;
else
oBuffer << "Failed Test 1 : Gamma*N != 0 (Zero matrix)" << endl;
if (testResults[1] == "Pass")
oBuffer << "Passed Test 2 : Rank(N) using SVD (" << _SvdRankNmat << ") is same as m0 (" << _NumIndependent << ")" << endl;
else
oBuffer << "Failed Test 2 : Rank(N) using SVD (" << _SvdRankNmat << ") is different from m0 (" << _NumIndependent << ")" << endl;
if (testResults[2] == "Pass")
oBuffer << "Passed Test 3 : Rank(NR) using SVD (" << _SvdRankNr << ") is same as m0 (" << _NumIndependent << ")" << endl;
else
oBuffer << "Failed Test 3 : Rank(NR) using SVD (" << _SvdRankNr << ") is different from m0 (" << _NumIndependent << ")" << endl;
if (testResults[3] == "Pass")
oBuffer << "Passed Test 4 : Rank(NR) using QR (" << _QrRankNmat << ") is same as m0 (" << _NumIndependent << ")" << endl;
else
oBuffer << "Failed Test 4 : Rank(NR) using QR (" << _QrRankNmat << ") is different from m0 (" << _NumIndependent << ")" << endl;
if (testResults[4] == "Pass")
oBuffer << "Passed Test 5 : L0 obtained with QR matches Q21*inv(Q11)" << endl;
else
oBuffer << "Failed Test 5 : L0 obtained with QR is different from Q21*inv(Q11)" << endl;
if (testResults[5] == "Pass")
oBuffer << "Passed Test 6 : N*K = 0 (Zero matrix)" << endl;
else
oBuffer << "Failed Test 6 : N*K != 0 (Zero matrix)" << endl;
return oBuffer.str();
}
//Returns the name of the model
string LibStructural::getModelName()
{
return _sModelName;
}
//Returns the total number of species
int LibStructural::getNumSpecies()
{
return numFloating;
}
//Returns the number of independent species
int LibStructural::getNumIndSpecies()
{
return _NumIndependent;
}
//Returns the number of dependent species
int LibStructural::getNumDepSpecies()
{
return _NumDependent;
}
//Returns the total number of reactions
int LibStructural::getNumReactions()
{
return numReactions;
}
//Returns the number of independent reactions
int LibStructural::getNumIndReactions()
{
return _Nr->numCols() - _K0->numCols();
}
//Returns the number of dependent reactions
int LibStructural::getNumDepReactions()
{
return _K0->numCols();
}
//Returns rank of stoichiometry matrix
int LibStructural::getRank()
{
return _NumIndependent;
}
//Returns the number of nonzero values in Stoichiometry matrix
double LibStructural::getNmatrixSparsity()
{
if ( (_NumRows == 0 ) || (_NumCols == 0) ) _Sparsity = 0.0;
return _Sparsity;
}
//Set user specified tolerance
void LibStructural::setTolerance(double dTolerance)
{
_Tolerance = dTolerance;
}
LibStructural* LibStructural::getInstance()
{
if (_Instance == NULL)
_Instance = new LibStructural();
return _Instance;
}
// load a new stoichiometry matrix and reset current loaded model
void LibStructural::loadStoichiometryMatrix (DoubleMatrix& oMatrix)
{
#ifndef NO_SBML
DELETE_IF_NON_NULL(_Model);
#endif
FreeMatrices();
_inputReactionNames.clear();
_inputSpeciesNames.clear();
_inputValues.clear();
DELETE_IF_NON_NULL(_Nmat);
_Nmat = new DoubleMatrix(oMatrix);
}
// load species names and initial values
void LibStructural::loadSpecies ( vector< string > &speciesNames, vector<double> &speciesValues)
{
_inputSpeciesNames.assign(speciesNames.begin(), speciesNames.end());
_inputValues.assign(speciesValues.begin(), speciesValues.end());
}
// load reaction names
void LibStructural::loadReactionNames ( vector< string > &reactionNames)
{
_inputReactionNames.assign(reactionNames.begin(), reactionNames.end());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// load a new stoichiometry matrix and reset current loaded model
LIB_EXTERN int LibStructural_loadStoichiometryMatrix ( const double ** inMatrix, const int nRows, const int nCols)
{
DoubleMatrix oMatrix(inMatrix, nRows, nCols);
LibStructural::getInstance()->loadStoichiometryMatrix( oMatrix );
return 0;
}
// load species names and initial values
LIB_EXTERN int LibStructural_loadSpecies ( const char** speciesNames, const double* speciesValues, const int nLength)
{
vector< string > oNames; vector< double> oValues;
for (int i = 0; i < nLength; i++)
{
oNames.push_back(string(speciesNames[i]));
oValues.push_back(speciesValues[i]);
}
LibStructural::getInstance()->loadSpecies(oNames, oValues);
return 0;
}
// load reaction names
LIB_EXTERN int LibStructural_loadReactionNames ( const char** reactionNames, const int nLength)
{
vector< string > oNames;
for (int i = 0; i < nLength; i++)
{
oNames.push_back(string(reactionNames[i]));
}
LibStructural::getInstance()->loadReactionNames(oNames);
return 0;
}
#ifndef NO_SBML
// Initialization method, takes SBML as input
LIB_EXTERN int LibStructural_loadSBML(const char* sSBML, char** oResult, int *nLength)
{
try
{
*oResult = strdup(LibStructural::getInstance()->loadSBML(string(sSBML)).c_str());
*nLength = strlen(*oResult);
return 0;
}
catch (...)
{
return -1;
}
}
LIB_EXTERN int LibStructural_loadSBMLFromFile(const char* sFileName, char* *outMessage, int *nLength)
{
try
{
*outMessage = strdup(LibStructural::getInstance()->loadSBMLFromFile(string(sFileName)).c_str());
*nLength = strlen(*outMessage);
return 0;
}
catch (...)
{
return -1;
}
}
//Initialization method, takes SBML as input
LIB_EXTERN int LibStructural_loadSBMLwithTests(const char* sSBML, char* *oResult, int *nLength)
{
try
{
string sResult = LibStructural::getInstance()->loadSBMLwithTests(string(sSBML));
(*oResult) = strdup(sResult.c_str());
(*nLength) = strlen(*oResult);
return 0;
}
catch(...)
{
return -1;
}
}
#endif
//Uses QR factorization for Conservation analysis
LIB_EXTERN int LibStructural_analyzeWithQR(char* *outMessage, int *nLength)
{
*outMessage = strdup(LibStructural::getInstance()->analyzeWithQR().c_str());
*nLength = strlen(*outMessage);
return 0;
}
//Uses LU Decomposition for Conservation analysis
LIB_EXTERN int LibStructural_analyzeWithLU(char* *outMessage, int *nLength)
{
*outMessage = strdup(LibStructural::getInstance()->analyzeWithLU().c_str());
*nLength = strlen(*outMessage);
return 0;
}
//Uses LU Decomposition for Conservation analysis
LIB_EXTERN int LibStructural_analyzeWithLUandRunTests(char* *outMessage, int *nLength)
{
*outMessage = strdup(LibStructural::getInstance()->analyzeWithLUandRunTests().c_str());
*nLength = strlen(*outMessage);
return 0;
}
//Uses fully pivoted LU Decomposition for Conservation analysis
LIB_EXTERN int LibStructural_analyzeWithFullyPivotedLU(char* *outMessage, int *nLength)
{
*outMessage = strdup(LibStructural::getInstance()->analyzeWithFullyPivotedLU().c_str());
*nLength = strlen(*outMessage);
return 0;
}
//Uses fully pivoted LU Decomposition for Conservation analysis
LIB_EXTERN int LibStructural_analyzeWithFullyPivotedLUwithTests(char* *outMessage, int *nLength)
{
*outMessage = strdup(LibStructural::getInstance()->analyzeWithFullyPivotedLUwithTests().c_str());
*nLength = strlen(*outMessage);
return 0;
}
//Returns L0 Matrix
LIB_EXTERN int LibStructural_getL0Matrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix *oTemp = LibStructural::getInstance()->getL0Matrix();
Util::CopyMatrix(*oTemp, *outMatrix, *outRows, *outCols);
delete oTemp;
return 0;
}
//Returns Nr Matrix
LIB_EXTERN int LibStructural_getNrMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getNrMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
//Returns N0 Matrix
LIB_EXTERN int LibStructural_getN0Matrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getN0Matrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
//Returns L, the Link Matrix
LIB_EXTERN int LibStructural_getLinkMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getLinkMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
//Returns K0
LIB_EXTERN int LibStructural_getK0Matrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getK0Matrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
//Returns K Matrix
LIB_EXTERN int LibStructural_getKMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getKMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
////Returns the reordered list of species
//LIB_EXTERN int LibStructural_getNthReorderedSpeciesId(int n,char* *outMessage, int *nLength)
//{
// outMessage = strdup(LibStructural::getInstance()->getReorderedSpecies()[n].c_str());
// nLength = strlen(outMessage);
// return nLength;
//}
////Returns the list of independent species
//LIB_EXTERN int LibStructural_getNthIndependentSpeciesId(int n,char* *outMessage, int *nLength)
//{
// outMessage = strdup(LibStructural::getInstance()->getIndependentSpecies()[n].c_str());
// nLength = strlen(outMessage);
// return nLength;
//}
////Returns the list of dependent species
//LIB_EXTERN int LibStructural_getNthDependentSpeciesId(int n,char* *outMessage, int *nLength)
//{
// outMessage = strdup(LibStructural::getInstance()->getDependentSpecies()[n].c_str());
// nLength = strlen(outMessage);
// return nLength;
//}
////Returns the list of Reactions
//LIB_EXTERN int LibStructural_getNthReactionId(int n,char* *outMessage, int *nLength)
//{
// outMessage = strdup(LibStructural::getInstance()->getReactions()[n].c_str());
// nLength = strlen(outMessage);
// return nLength;
//}
//Returns Gamma, the conservation law array
LIB_EXTERN int LibStructural_getGammaMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getGammaMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
////Returns algebraic expressions for conserved cycles
//LIB_EXTERN int LibStructural_getNthConservedEntity(int n,char* *outMessage, int *nLength)
//{
// outMessage = strdup(LibStructural::getInstance()->getConservedLaws()[n].c_str());
// nLength = strlen(outMessage);
// return nLength;
//}
//Returns values for conserved cycles using Initial conditions
LIB_EXTERN int LibStructural_getNumConservedSums()
{
return (int) LibStructural::getInstance()->getConservedSums().size();
}
//LIB_EXTERN double LibStructural_getNthConservedSum(int n)
//{
// return LibStructural::getInstance()->getConservedSums()[n];
//}
//Returns Initial Conditions used in the model
///LIB_EXTERN int vector< pair <string, double> > LibStructural_getInitialConditions();
//Returns the original stoichiometry matrix
LIB_EXTERN int LibStructural_getStoichiometryMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getStoichiometryMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
//Returns reordered stoichiometry matrix
LIB_EXTERN int LibStructural_getReorderedStoichiometryMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getReorderedStoichiometryMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
return 0;
}
//Tests if conservation laws are correct
LIB_EXTERN int LibStructural_validateStructuralMatrices(int* *outResults, int* outLength)
{
vector< string > oResult = LibStructural::getInstance()->validateStructuralMatrices();
*outResults = (int*) malloc(sizeof(int)*oResult.size()); memset(*outResults, 0, sizeof(int)*oResult.size());
*outLength = oResult.size();
for (int i = 0; i < *outLength; i++)
{
(*outResults)[i] = (int) (oResult[i]=="Pass");
}
return 0;
}
//Return Details about conservation tests
LIB_EXTERN int LibStructural_getTestDetails(char* *outMessage, int *nLength)
{
*outMessage = strdup(LibStructural::getInstance()->getTestDetails().c_str());
*nLength = strlen(*outMessage);
return 0;
}
//Returns the name of the model
LIB_EXTERN int LibStructural_getModelName(char* *outMessage, int *nLength)
{
*outMessage = strdup(LibStructural::getInstance()->getModelName().c_str());
*nLength = strlen(*outMessage);
return 0;
}
//Returns the total number of species
LIB_EXTERN int LibStructural_getNumSpecies()
{
return LibStructural::getInstance()->getNumSpecies();
}
//Returns the number of independent species
LIB_EXTERN int LibStructural_getNumIndSpecies()
{
return LibStructural::getInstance()->getNumIndSpecies();
}
//Returns the number of dependent species
LIB_EXTERN int LibStructural_getNumDepSpecies()
{
return LibStructural::getInstance()->getNumDepSpecies();
}
//Returns the total number of reactions
LIB_EXTERN int LibStructural_getNumReactions()
{
return LibStructural::getInstance()->getNumReactions();
}
//Returns the number of independent reactions
LIB_EXTERN int LibStructural_getNumIndReactions()
{
return LibStructural::getInstance()->getNumIndReactions();
}
//Returns the number of dependent reactions
LIB_EXTERN int LibStructural_getNumDepReactions()
{
return LibStructural::getInstance()->getNumDepReactions();
}
//Returns rank of stoichiometry matrix
LIB_EXTERN int LibStructural_getRank()
{
return LibStructural::getInstance()->getRank();
}
//Returns the number of nonzero values in Stoichiometry matrix
LIB_EXTERN double LibStructural_getNmatrixSparsity()
{
return LibStructural::getInstance()->getNmatrixSparsity();
}
//Set user specified tolerance
LIB_EXTERN void LibStructural_setTolerance(double dTolerance)
{
LibStructural::getInstance()->setTolerance(dTolerance);
}
LIB_EXTERN void LibStructural_freeVector(void* vector)
{
if (vector) free(vector);
}
LIB_EXTERN void LibStructural_freeMatrix(void** matrix, int numRows)
{
for (int i = 0; i < numRows; i++)
{
if (matrix[i]) free(matrix[i]);
}
free(matrix);
}
LIB_EXTERN int LibStructural_getConservedSums(double* *outArray, int *outLength)
{
vector<double> oSums = LibStructural::getInstance()->getConservedSums();
Util::CopyDoubleVector(oSums, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getConservedLaws(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getConservedLaws();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getReactionIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getReactions();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getDependentSpeciesIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getDependentSpecies();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getIndependentSpeciesIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getIndependentSpecies();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getDependentReactionIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getDependentReactionIds();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getIndependentReactionIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getIndependentReactionIds();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getReorderedReactionIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getReorderedReactions();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getSpeciesIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getSpecies();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getReorderedSpeciesIds(char** *outArray, int *outLength)
{
vector<string> oValues = LibStructural::getInstance()->getReorderedSpecies();
Util::CopyStringVector(oValues, *outArray, *outLength);
return 0;
}
LIB_EXTERN int LibStructural_getInitialConditions(char** *outVariableNames, double* *outValues, int *outLength)
{
vector< pair < string, double> > oInitialConditions = LibStructural::getInstance()->getInitialConditions();
*outLength = oInitialConditions.size();
*outVariableNames = (char**)malloc(sizeof(char*)**outLength); memset(*outVariableNames, 0, sizeof(char*)**outLength);
*outValues = (double*) malloc(sizeof(double)**outLength); memset(*outValues, 0, sizeof(double)**outLength);
for (int i = 0; i < *outLength; i++)
{
pair<string,double> oTemp = oInitialConditions[i];
(*outVariableNames)[i] = strdup(oTemp.first.c_str());
(*outValues)[i] = oTemp.second;
}
return 0;
}
LIB_EXTERN int LibStructural_getL0MatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural_getDependentSpeciesIds(outRowLabels, outRowCount);
LibStructural_getIndependentSpeciesIds(outColLabels, outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getNrMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural_getIndependentSpeciesIds(outRowLabels, outRowCount);
LibStructural_getReactionIds(outColLabels, outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getColumnReorderedNrMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
vector<string> oRows; vector<string> oCols;
LibStructural::getInstance()->getColumnReorderedNrMatrixLabels(oRows, oCols);
Util::CopyStringVector(oRows, *outRowLabels, *outRowCount);
Util::CopyStringVector(oCols, *outColLabels, *outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getColumnReorderedNrMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getColumnReorderedNrMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
delete oMatrix;
return 0;
}
// Returns the NIC Matrix (partition of linearly independent columns of Nr)
LIB_EXTERN int LibStructural_getNICMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getNICMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
delete oMatrix;
return 0;
}
// Returns the NDC Matrix (partition of linearly dependent columns of Nr)
LIB_EXTERN int LibStructural_getNDCMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getNDCMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
delete oMatrix;
return 0;
}
LIB_EXTERN int LibStructural_getNICMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
vector<string> oRows; vector<string> oCols;
LibStructural::getInstance()->getNICMatrixLabels(oRows, oCols);
Util::CopyStringVector(oRows, *outRowLabels, *outRowCount);
Util::CopyStringVector(oCols, *outColLabels, *outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getNDCMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
vector<string> oRows; vector<string> oCols;
LibStructural::getInstance()->getNDCMatrixLabels(oRows, oCols);
Util::CopyStringVector(oRows, *outRowLabels, *outRowCount);
Util::CopyStringVector(oCols, *outColLabels, *outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getN0MatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural_getDependentSpeciesIds(outRowLabels, outRowCount);
LibStructural_getReactionIds(outColLabels, outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getLinkMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural_getReorderedSpeciesIds(outRowLabels, outRowCount);
LibStructural_getIndependentSpeciesIds(outColLabels, outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getK0MatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural* instance = LibStructural::getInstance();
vector<string> oReactionLables = instance->getReorderedReactions();
DoubleMatrix *k0 = instance->getK0Matrix();
int nDependent = k0->numCols();
int nIndependent = k0->numRows();
*outRowCount = nIndependent;
*outColCount = nDependent;
*outRowLabels = (char**) malloc(sizeof(char*)**outRowCount); memset(*outRowLabels, 0, sizeof(char*)**outRowCount);
*outColLabels = (char**) malloc(sizeof(char*)**outColCount); memset(*outColLabels, 0, sizeof(char*)**outColCount);
for (int i = 0; i < nDependent; i++)
{
(*outColLabels)[i] = strdup(oReactionLables[nIndependent + i].c_str());
}
for (int i = 0; i < nIndependent; i++)
{
(*outRowLabels)[i] = strdup(oReactionLables[i].c_str());
}
return 0;
}
LIB_EXTERN int LibStructural_getKMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural* instance = LibStructural::getInstance();
vector<string> oReactionLables = instance->getReorderedReactions();
DoubleMatrix *k = instance->getKMatrix();
int nDependent = k->numCols();
int nIndependent = k->numRows() - nDependent;
*outRowCount = k->numRows();
*outColCount = nDependent;
*outRowLabels = (char**) malloc(sizeof(char*)**outRowCount); memset(*outRowLabels, 0, sizeof(char*)**outRowCount);
*outColLabels = (char**) malloc(sizeof(char*)**outColCount); memset(*outColLabels, 0, sizeof(char*)**outColCount);
for (int i = 0; i < nDependent; i++)
{
(*outColLabels)[i] = strdup(oReactionLables[nIndependent + i].c_str());
(*outRowLabels)[i] = strdup(oReactionLables[nIndependent + i].c_str());
}
for (int i = 0; i < nIndependent; i++)
{
(*outRowLabels)[i+nDependent] = strdup(oReactionLables[i].c_str());
}
return 0;
}
LIB_EXTERN int LibStructural_getGammaMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural_getReorderedSpeciesIds(outColLabels, outColCount);
DoubleMatrix *G = LibStructural::getInstance()->getGammaMatrix();
*outRowCount = G->numRows();
*outRowLabels = (char**) malloc(sizeof(char*)**outRowCount); memset(*outRowLabels, 0, sizeof(char*)**outRowCount);
for (int i = 0; i < *outRowCount; i++)
{
stringstream stream; stream << i;
(*outRowLabels)[i] = strdup(stream.str().c_str());
}
return 0;
}
LIB_EXTERN int LibStructural_getStoichiometryMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural_getSpeciesIds(outRowLabels, outRowCount);
LibStructural_getReactionIds(outColLabels, outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getFullyReorderedStoichiometryMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
vector<string> oRows; vector<string> oCols;
LibStructural::getInstance()->getFullyReorderedStoichiometryMatrixLabels(oRows, oCols);
Util::CopyStringVector(oRows, *outRowLabels, *outRowCount);
Util::CopyStringVector(oCols, *outColLabels, *outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getReorderedStoichiometryMatrixLabels(char** *outRowLabels, int *outRowCount, char** *outColLabels, int *outColCount)
{
LibStructural_getReorderedSpeciesIds(outRowLabels, outRowCount);
LibStructural_getReactionIds(outColLabels, outColCount);
return 0;
}
LIB_EXTERN int LibStructural_getFullyReorderedStoichiometryMatrix(double** *outMatrix, int* outRows, int *outCols)
{
DoubleMatrix* oMatrix = LibStructural::getInstance()->getFullyReorderedStoichiometryMatrix();
if (oMatrix == NULL)
return -1;
Util::CopyMatrix(*oMatrix, *outMatrix, *outRows, *outCols);
delete oMatrix;
return 0;
}
LIB_EXTERN double LibStructural_getTolerance()
{
return LibStructural::getInstance()->getTolerance();
}
LibStructural* LibStructural::_Instance = NULL;
| 26.092925 | 155 | 0.685504 | [
"vector",
"model"
] |
18826c519a975b58e6e4ed7cce2cc03ad669db27 | 3,821 | cpp | C++ | wave_vision/src/descriptor/brisk_descriptor.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 80 | 2017-03-12T18:57:33.000Z | 2022-03-30T11:44:33.000Z | wave_vision/src/descriptor/brisk_descriptor.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 210 | 2017-03-13T15:01:34.000Z | 2022-01-15T03:19:44.000Z | wave_vision/src/descriptor/brisk_descriptor.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 31 | 2017-08-14T16:54:52.000Z | 2022-01-21T06:44:16.000Z | #include "wave/vision/descriptor/brisk_descriptor.hpp"
namespace wave {
// Filesystem based constructor for BRISKDescriptorParams
BRISKDescriptorParams::BRISKDescriptorParams(const std::string &config_path) {
// Extract parameters from .yaml file.
ConfigParser parser;
std::vector<float> radius_list;
std::vector<int> number_list;
float d_max;
float d_min;
// Add parameters to parser, to be loaded. If path cannot be found, throw
// an exception
parser.addParam("radius_list", &radius_list);
parser.addParam("number_list", &number_list);
parser.addParam("d_max", &d_max);
parser.addParam("d_min", &d_min);
if (parser.load(config_path) != ConfigStatus::OK) {
throw std::invalid_argument(
"Failed to Load BRISKDescriptorParams Configuration");
}
this->radius_list = radius_list;
this->number_list = number_list;
this->d_max = d_max;
this->d_min = d_min;
}
// Default constructor. Struct may be default or user defined.
BRISKDescriptor::BRISKDescriptor(const BRISKDescriptorParams &config) {
// Ensure parameters are valid
this->checkConfiguration(config);
// OpenCV refers to this as a parameter for "index remapping of the bits."
// Kaehler and Bradski's book, "Learning OpenCV3: Computer Vision in C++
// with the OpenCV Library" states this parameter is unused, and should be
// omitted.
std::vector<int> index_change;
// Create cv::BRISK object with the desired parameters
this->brisk_descriptor = cv::BRISK::create(config.radius_list,
config.number_list,
config.d_max,
config.d_min,
index_change);
// Store configuration parameters within member struct
this->current_config = config;
}
void BRISKDescriptor::checkConfiguration(
const BRISKDescriptorParams &check_config) {
// Check that the size of radiusList and numberList are equal and positive
if (check_config.radius_list.size() == 0) {
throw std::invalid_argument("No parameters in radius_list!");
} else if (check_config.number_list.size() == 0) {
throw std::invalid_argument("No parameters in number_list!");
} else if (check_config.radius_list.size() !=
check_config.number_list.size()) {
throw std::invalid_argument(
"radius_list and number_list are of unequal size!");
}
// Ensure all values of radiusList are positive
for (const auto &radius : check_config.radius_list) {
if (radius < 0) {
throw std::invalid_argument(
"radius_list has a negative parameter!");
}
}
// Ensure all values of numberList are positive
for (auto &num_points : check_config.number_list) {
if (num_points < 0) {
throw std::invalid_argument(
"number_list has a negative parameter!");
}
}
// Ensure dMax and dMin are both positive, and check dMax is less than dMin
if (check_config.d_max < 0) {
throw std::invalid_argument("d_max is a negative value!");
} else if (check_config.d_min < 0) {
throw std::invalid_argument("d_min is a negative value!");
} else if (check_config.d_max > check_config.d_min) {
throw std::invalid_argument("d_max is greater than d_min!");
}
}
BRISKDescriptorParams BRISKDescriptor::getConfiguration() const {
return this->current_config;
}
cv::Mat BRISKDescriptor::extractDescriptors(
const cv::Mat &image, std::vector<cv::KeyPoint> &keypoints) {
cv::Mat descriptors;
this->brisk_descriptor->compute(image, keypoints, descriptors);
return descriptors;
}
} // namespace wave
| 35.71028 | 79 | 0.652185 | [
"object",
"vector"
] |
18864a1f63be67278d3848a27d7b963ed6b57faa | 1,998 | hpp | C++ | liblumi/include/Light.hpp | Rertsyd/LumiRT | d562fd786f769b385bc051e2ea8bcd26162a9dc6 | [
"MIT"
] | null | null | null | liblumi/include/Light.hpp | Rertsyd/LumiRT | d562fd786f769b385bc051e2ea8bcd26162a9dc6 | [
"MIT"
] | null | null | null | liblumi/include/Light.hpp | Rertsyd/LumiRT | d562fd786f769b385bc051e2ea8bcd26162a9dc6 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* ,, */
/* `7MMF' db `7MM"""Mq. MMP""MM""YMM */
/* MM MM `MM.P' MM `7 */
/* MM `7MM `7MM `7MMpMMMb.pMMMb. `7MM MM ,M9 MM */
/* MM MM MM MM MM MM MM MMmmdM9 MM */
/* MM , MM MM MM MM MM MM MM YM. MM */
/* MM ,M MM MM MM MM MM MM MM `Mb. MM */
/* .JMMmmmmMMM `Mbod"YML..JMML JMML JMML..JMML..JMML. .JMM. .JMML. */
/* */
/* ************************************************************************** */
#pragma once
#include "Material.hpp"
static constexpr double FarFarAway = 999.;
class Light
{
Light() = delete;
protected:
const RGBColor Color;
const double Intensity;
public:
Light(RGBColor clr, double it);
virtual ~Light() = default;
virtual RGBColor Illuminate(RGBColor& diffuse, const HitPoint& hp) const = 0;
virtual Vector GetDiffPos(const Vector& intersection) const = 0;
};
using uPtrLight = std::unique_ptr<Light>;
using LightList = std::vector<uPtrLight>;
class Point : public Light
{
Point() = delete;
const Vector Position;
public:
Point(RGBColor clr, double it, Vector pos);
virtual ~Point() = default;
virtual RGBColor Illuminate(RGBColor& diffuse, const HitPoint& hp) const;
virtual Vector GetDiffPos(const Vector& intersection) const;
};
class Directional : public Light
{
Directional() = delete;
const Vector Direction;
public:
Directional(RGBColor clr, double it, Vector dir);
virtual ~Directional() = default;
virtual RGBColor Illuminate(RGBColor& diffuse, const HitPoint& hp) const;
virtual Vector GetDiffPos(const Vector& intersection) const;
};
| 30.738462 | 80 | 0.494494 | [
"vector"
] |
18883f9c5d5fff13956909b55e3fafdcff74dabe | 1,510 | cpp | C++ | TG/bookcodes/ch3/uva11235.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | TG/bookcodes/ch3/uva11235.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | TG/bookcodes/ch3/uva11235.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa11235 Frequent Values
// Rujia Liu
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 100000 + 5;
const int maxlog = 20;
// 区间最*大*值
struct RMQ {
int d[maxn][maxlog];
void init(const vector<int>& A) {
int n = A.size();
for(int i = 0; i < n; i++) d[i][0] = A[i];
for(int j = 1; (1<<j) <= n; j++)
for(int i = 0; i + (1<<j) - 1 < n; i++)
d[i][j] = max(d[i][j-1], d[i + (1<<(j-1))][j-1]);
}
int query(int L, int R) {
int k = 0;
while((1<<(k+1)) <= R-L+1) k++; // 如果2^(k+1)<=R-L+1,那么k还可以加1
return max(d[L][k], d[R-(1<<k)+1][k]);
}
};
int a[maxn], num[maxn], left[maxn], right[maxn];
RMQ rmq;
int main() {
int n, q;
while(scanf("%d%d", &n, &q) == 2) {
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
a[n] = a[n-1] + 1; // 哨兵
int start = -1;
vector<int> count;
for(int i = 0; i <= n; i++) {
if(i == 0 || a[i] > a[i-1]) { // 新段开始
if(i > 0) {
count.push_back(i - start);
for(int j = start; j < i; j++) {
num[j] = count.size() - 1; left[j] = start; right[j] = i-1;
}
}
start = i;
}
}
rmq.init(count);
while(q--) {
int L, R, ans;
scanf("%d%d", &L, &R); L--; R--;
if(num[L] == num[R]) ans = R-L+1;
else {
ans = max(R-left[R]+1, right[L]-L+1);
if(num[L]+1 < num[R]) ans = max(ans, rmq.query(num[L]+1, num[R]-1));
}
printf("%d\n", ans);
}
}
return 0;
}
| 23.968254 | 76 | 0.437086 | [
"vector"
] |
188c8fd120a0917e7b2a12a65b14f6bbff634e90 | 2,046 | cpp | C++ | src/atria/xform/transducer/tst_sink.cpp | LaudateCorpus1/atria | db00646051833acde270b51ba6936e03f213a15a | [
"MIT"
] | 257 | 2015-09-23T22:02:46.000Z | 2021-12-13T16:57:06.000Z | src/atria/xform/transducer/tst_sink.cpp | Ableton/atria | db00646051833acde270b51ba6936e03f213a15a | [
"MIT"
] | 13 | 2016-01-03T02:13:24.000Z | 2019-05-13T07:47:55.000Z | src/atria/xform/transducer/tst_sink.cpp | LaudateCorpus1/atria | db00646051833acde270b51ba6936e03f213a15a | [
"MIT"
] | 31 | 2015-10-07T11:18:12.000Z | 2021-09-17T20:33:06.000Z | //
// Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include <atria/xform/into_vector.hpp>
#include <atria/xform/run.hpp>
#include <atria/xform/transducer/enumerate.hpp>
#include <atria/xform/transducer/sink.hpp>
#include <atria/prelude/comp.hpp>
#include <atria/prelude/identity.hpp>
#include <atria/testing/spies.hpp>
#include <atria/testing/gtest.hpp>
namespace atria {
namespace xform {
TEST(sink, sink)
{
auto v = std::vector<int> { 1, 2, 3, 6 };
auto r = std::vector<int> {};
run(sink([&](int x) { r.push_back(x); }), v);
EXPECT_EQ(v, r);
}
TEST(sink, moves_values_out_of_rvalue_container)
{
using elem = testing::copy_spy<>;
auto x = elem{};
auto v = std::vector<elem> { x, x, x, x };
auto copies = x.copied.count();
auto r = into_vector(comp(sink([](elem){}), enumerate), std::move(v));
EXPECT_EQ(x.copied.count(), copies);
EXPECT_EQ(r, (decltype(r) {0, 1, 2, 3}));
}
} // namespace xform
} // namespace atria
| 34.677966 | 77 | 0.717986 | [
"vector"
] |
18985d0570d9dc9bce44fd9948c8a387d69b16bd | 1,132 | cpp | C++ | Image.cpp | chaerim-kim/OpenGL-Leeds-Scene | d854a6939a56323e39dd2377853ca204736eb685 | [
"MIT"
] | 1 | 2021-01-10T16:11:59.000Z | 2021-01-10T16:11:59.000Z | Image.cpp | chaerim-kim/OpenGL-Leeds-Scene | d854a6939a56323e39dd2377853ca204736eb685 | [
"MIT"
] | null | null | null | Image.cpp | chaerim-kim/OpenGL-Leeds-Scene | d854a6939a56323e39dd2377853ca204736eb685 | [
"MIT"
] | null | null | null | #include "Image.h"
#include <vector>
#include <iostream>
#include <cstdlib>
Image::Image(const std::string& file_name)
{
p_qimage = new QImage(QString(file_name.c_str()));
_width = p_qimage->width();
_height = p_qimage->height();
_image = new GLubyte[_width*_height*3];
_image2 = new GLubyte[_width*_height*3];
_image3 = new GLubyte[_width*_height*3];
unsigned int nm = _width*_height;
for (unsigned int i = 0; i < nm; i++){
std::div_t part = std::div((int)i, (int)_width);
QRgb colval = p_qimage->pixel(_width-part.rem-1, part.quot);
_image[3*nm-3*i-3] = qRed(colval);
_image[3*nm-3*i-2] = qGreen(colval);
_image[3*nm-3*i-1] = qBlue(colval);
_image2[3*nm-3*i-3] = qRed(colval);
_image2[3*nm-3*i-2] = qGreen(colval);
_image2[3*nm-3*i-1] = qBlue(colval);
_image3[3*nm-3*i-3] = qRed(colval);
_image3[3*nm-3*i-2] = qGreen(colval);
_image3[3*nm-3*i-1] = qBlue(colval);
}
}
const GLubyte* Image::imageField() const
{
return _image;
return _image2;
return _image3;
}
Image::~Image()
{
delete _image;
delete _image2;
delete _image3;
delete p_qimage;
}
| 22.196078 | 64 | 0.640459 | [
"vector"
] |
18a6f55ea3f006a5b4dd597652a950c872b420d7 | 2,050 | cpp | C++ | sources/SceneGraph/Animation/spAnimationBaseStructures.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/SceneGraph/Animation/spAnimationBaseStructures.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/SceneGraph/Animation/spAnimationBaseStructures.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2016-10-31T06:08:44.000Z | 2019-08-02T16:12:33.000Z | /*
* Animation base structures file
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#include "SceneGraph/Animation/spAnimationBaseStructures.hpp"
#include "SceneGraph/spSceneMesh.hpp"
namespace sp
{
namespace scene
{
/*
* SVertexGroup structure
*/
SVertexGroup::SVertexGroup() :
Surface (0 ),
Index (0 ),
Weight (0.0f )
{
}
SVertexGroup::SVertexGroup(
scene::Mesh* BaseMesh, u32 SurfaceIndex, u32 VertexIndex, f32 VertexWeight) :
Surface (SurfaceIndex ),
Index (VertexIndex ),
Weight (VertexWeight )
{
setupVertex(BaseMesh);
}
SVertexGroup::SVertexGroup(
scene::Mesh* BaseMesh, u32 SurfaceIndex, u32 VertexIndex,
u8 TangentTexLayer, u8 BinormalTexLayer, f32 VertexWeight) :
Surface (SurfaceIndex ),
Index (VertexIndex ),
Weight (VertexWeight )
{
setupVertex(BaseMesh, TangentTexLayer, BinormalTexLayer);
}
SVertexGroup::~SVertexGroup()
{
}
void SVertexGroup::setupVertex(scene::Mesh* BaseMesh)
{
if (BaseMesh)
{
video::MeshBuffer* Surf = BaseMesh->getMeshBuffer(Surface);
if (Surf)
{
Position = Surf->getVertexCoord (Index);
Normal = Surf->getVertexNormal (Index);
}
}
}
void SVertexGroup::setupVertex(scene::Mesh* BaseMesh, u8 TangentTexLayer, u8 BinormalTexLayer)
{
if (BaseMesh)
{
video::MeshBuffer* Surf = BaseMesh->getMeshBuffer(Surface);
if (Surf)
{
Position = Surf->getVertexCoord (Index );
Normal = Surf->getVertexNormal (Index );
Tangent = Surf->getVertexTexCoord (Index, TangentTexLayer );
Binormal = Surf->getVertexTexCoord (Index, BinormalTexLayer);
}
}
}
} // /namespace scene
} // /namespace sp
// ================================================================================
| 23.563218 | 94 | 0.589268 | [
"mesh"
] |
18a7f6cb73af2f363e90f9000222639cad6c6201 | 29,914 | cc | C++ | tensorflow/core/kernels/dml_strided_slice_op.cc | BenjaminWegener/tensorflow-directml | ecdbdbd2691e17dcc462fc49138fc7cc1536b7d5 | [
"Apache-2.0"
] | 351 | 2020-09-01T08:36:28.000Z | 2022-03-29T06:54:29.000Z | tensorflow/core/kernels/dml_strided_slice_op.cc | BenjaminWegener/tensorflow-directml | ecdbdbd2691e17dcc462fc49138fc7cc1536b7d5 | [
"Apache-2.0"
] | 80 | 2020-09-02T01:57:33.000Z | 2022-03-28T08:51:57.000Z | tensorflow/core/kernels/dml_strided_slice_op.cc | BenjaminWegener/tensorflow-directml | ecdbdbd2691e17dcc462fc49138fc7cc1536b7d5 | [
"Apache-2.0"
] | 29 | 2020-09-14T06:29:58.000Z | 2022-03-01T09:21:17.000Z | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Portions Copyright (c) Microsoft Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/dml/dml_operator_helper.h"
#include "tensorflow/core/common_runtime/dml/dml_util.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/resource_var.h"
#include "tensorflow/core/kernels/dml_kernel_wrapper.h"
#include "tensorflow/core/kernels/dml_ops_common.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/util/strided_slice_op.h"
namespace tensorflow {
struct SimplifiedSlice {
dml::TensorDesc::Dimensions input_sizes;
dml::TensorDesc::Dimensions input_strides;
dml::TensorDesc::Dimensions output_sizes;
dml::SmallVector<uint32_t, 5> window_offset;
dml::SmallVector<uint32_t, 5> window_sizes;
dml::SmallVector<int32_t, 5> window_strides;
};
template <typename T>
void ShiftDim(T& vec, int shift_amount, uint32_t dim_count) {
std::rotate(vec.begin(), vec.begin() + shift_amount, vec.end());
vec.resize(dim_count);
}
// This helper may simplify an N-dimensional slice to a lower rank slice by
// coalescing dimensions that meet the following criteria:
// - Dimensions with size 1 are always coalesced.
// - Adjacent dimensions that are fully included in the slice are always
// coalesced.
// - A higher-order dimension that is partially included in the slice, and has
// no offset/stride, will be
// merged with lower-order dimensions that are fully included in the slice.
static absl::optional<SimplifiedSlice> SimplifySlice(
const TensorShape& input_shape,
const gtl::InlinedVector<int64, 4>& canonical_begins,
const gtl::InlinedVector<int64, 4>& canonical_ends,
const gtl::InlinedVector<int64, 4>& strides, uint32_t min_output_size = 4,
uint32_t max_output_size = 8) {
assert(input_shape.dims() == canonical_begins.size());
assert(input_shape.dims() == canonical_ends.size());
assert(input_shape.dims() == strides.size());
assert(max_output_size > 0);
SimplifiedSlice desc = {};
desc.input_sizes.resize(max_output_size, 1);
desc.input_strides.resize(max_output_size, 1);
desc.output_sizes.resize(max_output_size, 1);
desc.window_offset.resize(max_output_size, 0);
desc.window_sizes.resize(max_output_size, 1);
desc.window_strides.resize(max_output_size, 1);
int current_dim = max_output_size - 1;
// Insertion becomes a no-op if the shape cannot be simplified into the
// requested max_output_size.
auto InsertDim = [&](uint32_t input_size, uint32_t input_stride,
uint32_t output_size, uint32_t window_offset,
uint32_t window_size, int32_t window_stride) {
if (current_dim >= 0) {
desc.input_sizes[current_dim] = input_size;
desc.input_strides[current_dim] = input_stride;
desc.output_sizes[current_dim] = output_size;
desc.window_offset[current_dim] = window_offset;
desc.window_sizes[current_dim] = window_size;
desc.window_strides[current_dim] = window_stride;
}
current_dim--;
};
uint32_t coalesced = 1;
uint32_t total_stride = 1;
for (int i = input_shape.dims() - 1; i >= 0; i--) {
const uint32_t input_size = input_shape.dim_size(i);
const int32_t window_stride = static_cast<int32_t>(strides[i]);
// Here, begin and end contain the canonical values. This means that they
// cannot be negative when strides are positive. When strides are negative,
// end can only be positive or -1. See the ValidateStridedSliceOp function
// in strided_slice_op.cc for reference.
const int64 begin = canonical_begins[i];
const int64 end = canonical_ends[i];
CHECK(end >= -1);
uint32_t window_offset, window_size, output_size;
if (window_stride > 0) {
window_offset = begin;
window_size = end - begin;
output_size = 1 + (window_size - 1) / window_stride;
} else {
window_offset = end + 1; // +1 to convert exclusive to inclusive
window_size = begin - end;
output_size = 1 + (window_size - 1) / -window_stride;
}
if (input_size == output_size && window_stride > 0) {
// The dimension can be collapsed, since all of its elements are included
// in the slice. However, coalescing can only be performed if the elements
// are read in order (i.e. stride is positive).
coalesced *= input_size;
} else {
if (begin == 0 && window_stride == 1 && coalesced > 1) {
// The current dim is merged with all previously collapsed dims.This is
// only possible because slicing of the current dim emits elements
// adjacent to the previously collapsed dims. Some of the tail elements
// in the current dim won't be included in the slice, but they can be
// skipped by padding the input strides to account for the extra
// physical elements.
InsertDim(
/*inputSize */ coalesced * input_size,
/*inputStride */ total_stride,
/*outputSize */ coalesced * output_size,
/*windowOffset */ 0,
/*windowSize */ coalesced * output_size,
/*windowStride */ 1);
total_stride *= coalesced * input_size;
} else {
// The current dim cannot be merged at all, so (up to) two dims are
// inserted: the previously collapsed dims, if any, and a separate dim
// for the non-contiguous current dim.
if (coalesced > 1) {
InsertDim(
/*inputSize */ coalesced,
/*inputStride */ total_stride,
/*outputSize */ coalesced,
/*windowOffset */ 0,
/*windowSize */ coalesced,
/*windowStride */ 1);
total_stride *= coalesced;
}
InsertDim(
/*inputSize */ input_size,
/*inputStride */ total_stride,
/*outputSize */ output_size,
/*windowOffset */ window_offset,
/*windowSize */ window_size,
/*windowStride */ window_stride);
total_stride *= input_size;
}
coalesced = 1;
}
}
if (coalesced > 1) {
InsertDim(
/*inputSize */ coalesced,
/*inputStride */ total_stride,
/*outputSize */ coalesced,
/*windowOffset */ 0,
/*windowSize */ coalesced,
/*windowStride */ 1);
total_stride *= coalesced;
}
// current_dim is the index of the next dim to write; if it's -1, then all
// max_output_size dims have been filled (0 dims remain). Anything larger
// than -1 indicates padding.
int dims_remaining = current_dim + 1;
if (dims_remaining < 0) {
return absl::nullopt;
} else {
for (int i = current_dim; i >= 0; i--) {
desc.input_strides[current_dim--] = total_stride;
}
// DML is (in general) faster with fewer dims, so shift values left if there
// are leading padding dims. No need to use 5D shader if 4D is possible.
int max_shift = max_output_size - min_output_size;
int shift_amount = std::min<int>(max_shift, dims_remaining);
uint32_t dim_count = max_output_size - shift_amount;
ShiftDim(desc.input_sizes, shift_amount, dim_count);
ShiftDim(desc.input_strides, shift_amount, dim_count);
ShiftDim(desc.output_sizes, shift_amount, dim_count);
ShiftDim(desc.window_offset, shift_amount, dim_count);
ShiftDim(desc.window_sizes, shift_amount, dim_count);
ShiftDim(desc.window_strides, shift_amount, dim_count);
}
return desc;
}
class StridedSliceInitHelper : public InitializationHelper {
public:
struct Attributes {
explicit Attributes(OpKernelConstruction* ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask));
}
int32 begin_mask, end_mask;
int32 ellipsis_mask, new_axis_mask, shrink_axis_mask;
};
bool IsNoOpKernel(
OpKernelContext* ctx,
absl::Span<const TensorShape> output_shapes) const override {
const bool is_grad_op = ctx->num_inputs() == 5;
if (is_grad_op) {
// For StridedSliceGrad, the last input is the input gradient
return ctx->input(4).NumElements() == 0 ||
output_shapes[0].num_elements() == 0;
}
// StridedSlice is only a no-op if the first input or its output is empty
return ctx->input(0).NumElements() == 0 ||
output_shapes[0].num_elements() == 0;
}
StridedSliceInitHelper(OpKernelContext* ctx,
std::shared_ptr<const Attributes> attr) {
TensorShape processing_shape;
bool slice_dim0 = true;
bool is_simple_slice = true;
gtl::InlinedVector<int64, 4> begin;
gtl::InlinedVector<int64, 4> end;
gtl::InlinedVector<int64, 4> strides;
// StridedSliceGrad has a 5th tensor for dy.
bool is_grad_op = ctx->num_inputs() == 5;
// StridedSliceGrad stores shape in a 1D host tensor.
TensorShape input_shape;
if (is_grad_op) {
const Tensor& input_shape_tensor = ctx->input(0);
OP_REQUIRES(
ctx, input_shape_tensor.dims() == 1,
errors::InvalidArgument("shape must be 1-D, got shape.shape = ",
input_shape_tensor.shape().DebugString()));
if (input_shape_tensor.dtype() == DT_INT32) {
OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(
input_shape_tensor.vec<int32>(), &input_shape));
} else if (input_shape_tensor.dtype() == DT_INT64) {
OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(
input_shape_tensor.vec<int64>(), &input_shape));
} else {
LOG(FATAL) << "shape must have type int32 or int64.";
}
} else {
input_shape = ctx->input(0).shape();
}
OP_REQUIRES_OK(
ctx, ValidateStridedSliceOp(
&ctx->input(1), &ctx->input(2), ctx->input(3), input_shape,
attr->begin_mask, attr->end_mask, attr->ellipsis_mask,
attr->new_axis_mask, attr->shrink_axis_mask, &processing_shape,
&output_shape_, &is_identity_, &is_simple_slice, &slice_dim0,
&begin, &end, &strides));
// Check to make sure dy is consistent with the original slice.
if (is_grad_op) {
TensorShape dy_shape = ctx->input(4).shape();
OP_REQUIRES(
ctx, output_shape_ == dy_shape,
errors::InvalidArgument("shape of dy was ", dy_shape.DebugString(),
" instead of ", output_shape_.DebugString()));
output_shape_ = input_shape;
}
// Attempt to simplify the slice into a lower-rank slice.
simple_slice_ = SimplifySlice(input_shape, begin, end, strides);
if (!simple_slice_) {
OP_REQUIRES(
ctx, simple_slice_,
errors::InvalidArgument("DML only support slicing up to 8D inputs, "
"but received ",
input_shape.dims()));
}
}
const TensorShape& GetOutputShape() const { return output_shape_; }
const bool IsIdentity() const { return is_identity_; }
const absl::optional<SimplifiedSlice>& GetSimplifiedSlice() const {
return simple_slice_;
}
private:
TensorShape output_shape_;
absl::optional<SimplifiedSlice> simple_slice_;
bool is_identity_;
};
using InitHelper = StridedSliceInitHelper;
class StridedSliceShapeHelper : public ShapeHelper {
public:
std::vector<TensorShape> GetOutputShapes(
OpKernelContext* ctx,
const InitializationHelper* initialization_helper) const override {
auto init_helper = static_cast<const InitHelper*>(initialization_helper);
return {init_helper->GetOutputShape()};
}
};
class DmlStridedSliceKernel : public DmlKernel {
public:
using InitHelper = tensorflow::InitHelper;
explicit DmlStridedSliceKernel(DmlKernelConstruction* ctx,
const InitHelper* init_helper) {
CHECK(ctx->GetInputCount() == 4);
CHECK(ctx->GetOutputCount() == 1);
auto simple_slice = init_helper->GetSimplifiedSlice();
auto dtype_tf = ctx->GetInputDataType(0);
const DML_TENSOR_DATA_TYPE dtype_dml =
GetDmlDataTypeFromTfDataType(dtype_tf);
// TODO #24881131: 64-bit data support should be revisited
// TFDML #24881131
uint64_t end_padding_in_bytes = 0;
dml::TensorDesc::Dimensions output_strides(
simple_slice->output_sizes.size());
uint32_t stride = 1;
for (int i = simple_slice->output_sizes.size() - 1; i >= 0; i--) {
output_strides[i] = stride;
stride *= simple_slice->output_sizes[i];
}
if (Is64BitIntegerType(dtype_tf)) {
for (auto& stride : simple_slice->input_strides) {
stride *= 2;
}
for (int i = simple_slice->output_sizes.size() - 1; i >= 0; i--) {
output_strides[i] *= 2;
}
end_padding_in_bytes = sizeof(uint32_t);
}
DmlTensorInfo input;
input.kernel_index = 0;
input.desc =
DmlTensorDesc{dtype_dml, simple_slice->input_sizes,
simple_slice->input_strides, 0, end_padding_in_bytes};
DmlTensorInfo output;
output.kernel_index = 0;
output.desc = DmlTensorDesc{dtype_dml, simple_slice->output_sizes,
output_strides, 0, end_padding_in_bytes};
DmlKernelTensors tensors;
tensors.inputs = {input};
tensors.outputs = {output};
auto scope = dml::Graph(ctx->GetDmlDevice());
auto inputs = GetDmlTensorDescs(tensors.inputs);
auto result = dml::InputTensor(scope, 0, inputs[0]);
if (init_helper->IsIdentity()) {
result = dml::Identity(result);
} else {
result =
dml::Slice(result, simple_slice->window_offset,
simple_slice->window_sizes, simple_slice->window_strides);
}
// TFDML #24881131
if (Is64BitSignedIntegerType(ctx->GetOutputDataType(0))) {
result = dml::ConvertInt32ToInt64(result);
}
Microsoft::WRL::ComPtr<IDMLCompiledOperator> compiled_op =
scope.Compile(DML_EXECUTION_FLAG_NONE, {result});
Initialize(ctx, std::move(tensors), compiled_op.Get());
}
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("StridedSlice") \
.Device(DEVICE_DML) \
.TypeConstraint<type>("T") \
.HostMemory("begin") \
.HostMemory("end") \
.HostMemory("strides"), \
DmlKernelWrapper<DmlStridedSliceKernel, StridedSliceShapeHelper>)
// TODO(b/25387198): A special kernel exists for int32 (see
// strided_slice_op.cc).
TF_CALL_half(REGISTER_KERNEL);
TF_CALL_float(REGISTER_KERNEL);
TF_CALL_bool(REGISTER_KERNEL);
TF_CALL_int8(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
// ----------------------------------------
// StridedSliceGrad
// ----------------------------------------
class DmlStridedSliceGradKernel : public DmlKernel {
public:
using InitHelper = tensorflow::InitHelper;
explicit DmlStridedSliceGradKernel(DmlKernelConstruction* ctx,
const InitHelper* init_helper) {
CHECK(ctx->GetInputCount() == 5);
CHECK(ctx->GetOutputCount() == 1);
auto simple_slice = init_helper->GetSimplifiedSlice();
auto dtype_tf = ctx->GetInputDataType(4);
const DML_TENSOR_DATA_TYPE dtype_dml =
GetDmlDataTypeFromTfDataType(dtype_tf);
// TODO #24881131: 64-bit data support should be revisited
// TFDML #24881131
uint64_t end_padding_in_bytes = 0;
dml::TensorDesc::Dimensions output_strides(
simple_slice->output_sizes.size());
uint32_t stride = 1;
for (int i = simple_slice->output_sizes.size() - 1; i >= 0; i--) {
output_strides[i] = stride;
stride *= simple_slice->output_sizes[i];
}
if (Is64BitIntegerType(dtype_tf)) {
for (auto& stride : simple_slice->input_strides) {
stride *= 2;
}
for (int i = simple_slice->output_sizes.size() - 1; i >= 0; i--) {
output_strides[i] *= 2;
}
end_padding_in_bytes = sizeof(uint32_t);
}
DmlTensorInfo input;
input.kernel_index = 4;
input.desc = DmlTensorDesc{dtype_dml, simple_slice->output_sizes,
output_strides, 0, end_padding_in_bytes};
DmlTensorInfo output;
output.kernel_index = 0;
output.desc =
DmlTensorDesc{dtype_dml, simple_slice->input_sizes,
simple_slice->input_strides, 0, end_padding_in_bytes};
DmlKernelTensors tensors;
tensors.inputs = {input};
tensors.outputs = {output};
auto scope = dml::Graph(ctx->GetDmlDevice());
auto inputs = GetDmlTensorDescs(tensors.inputs);
auto result = dml::InputTensor(scope, 0, inputs[0]);
if (init_helper->IsIdentity()) {
result = dml::Identity(result);
} else {
result = dml::SliceGrad(
result, simple_slice->input_sizes, simple_slice->window_offset,
simple_slice->window_sizes, simple_slice->window_strides);
}
// TFDML #24881131
if (Is64BitSignedIntegerType(ctx->GetOutputDataType(0))) {
result = dml::ConvertInt32ToInt64(result);
}
Microsoft::WRL::ComPtr<IDMLCompiledOperator> compiled_op =
scope.Compile(DML_EXECUTION_FLAG_NONE, {result});
Initialize(ctx, std::move(tensors), compiled_op.Get());
}
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("StridedSliceGrad") \
.Device(DEVICE_DML) \
.TypeConstraint<type>("T") \
.HostMemory("shape") \
.HostMemory("begin") \
.HostMemory("end") \
.HostMemory("strides"), \
DmlKernelWrapper<DmlStridedSliceGradKernel, StridedSliceShapeHelper>)
// TODO(b/25387198): A special kernel exists for int32 (see
// strided_slice_op.cc).
TF_CALL_half(REGISTER_KERNEL);
TF_CALL_float(REGISTER_KERNEL);
TF_CALL_bool(REGISTER_KERNEL);
TF_CALL_int8(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
class StridedSliceAssignInitHelper : public InitializationHelper {
public:
struct Attributes {
explicit Attributes(OpKernelConstruction* ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask));
OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask));
}
int32 begin_mask, end_mask;
int32 ellipsis_mask, new_axis_mask, shrink_axis_mask;
};
bool IsNoOpKernel(
OpKernelContext* ctx,
absl::Span<const TensorShape> output_shapes) const override {
if (!output_shapes.empty() && output_shapes[0].num_elements() == 0) {
return true;
}
if (ctx->input(4).NumElements() == 0) {
return true;
}
auto lock_cleanup = gtl::MakeCleanup([this] { Unlock(); });
const Tensor input_tensor = GetInputTensor(ctx);
if (input_tensor.NumElements() == 0) {
return true;
}
return false;
}
StridedSliceAssignInitHelper(OpKernelContext* ctx,
std::shared_ptr<const Attributes> attr) {
DCHECK(ctx->input_is_ref(0) || ctx->input(0).dtype() == DT_RESOURCE);
if (ctx->input(0).dtype() == DT_RESOURCE) {
OP_REQUIRES_OK(
ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &input_resource_));
input_resource_->mu()->lock_shared();
locked_ = true;
}
const Tensor input = GetInputTensor(ctx);
TensorShape processing_shape;
bool slice_dim0 = true;
bool is_simple_slice = true;
gtl::InlinedVector<int64, 4> begin;
gtl::InlinedVector<int64, 4> end;
gtl::InlinedVector<int64, 4> strides;
TensorShape input_shape = input.shape();
TensorShape final_shape;
OP_REQUIRES_OK(
ctx, ValidateStridedSliceOp(
&ctx->input(1), &ctx->input(2), ctx->input(3), input_shape,
attr->begin_mask, attr->end_mask, attr->ellipsis_mask,
attr->new_axis_mask, attr->shrink_axis_mask, &processing_shape,
&final_shape, &is_identity_, &is_simple_slice, &slice_dim0,
&begin, &end, &strides));
if (processing_shape.num_elements()) {
TensorShape values_shape = ctx->input(4).shape();
OP_REQUIRES(
ctx, final_shape == values_shape,
errors::Unimplemented(
"sliced l-value shape ", final_shape.DebugString(),
" does not match r-value shape ", values_shape.DebugString(),
". Automatic broadcasting not ", "yet implemented."));
}
// Attempt to simplify the slice into a lower-rank slice.
simple_slice_ = SimplifySlice(input_shape, begin, end, strides);
if (!simple_slice_) {
OP_REQUIRES(
ctx, simple_slice_,
errors::InvalidArgument("DML only support slicing up to 8D inputs, "
"but received ",
input_shape.dims()));
}
}
Tensor GetInputTensor(OpKernelContext* ctx) const {
DCHECK(ctx->input_is_ref(0) || ctx->input(0).dtype() == DT_RESOURCE);
return input_resource_ ? *input_resource_->tensor()
: ctx->mutable_input(0, false);
}
void Unlock() const {
if (input_resource_ && locked_) {
input_resource_->mu()->unlock_shared();
locked_ = false;
}
}
const absl::optional<SimplifiedSlice>& GetSimplifiedSlice() const {
return simple_slice_;
}
const bool IsIdentity() const { return is_identity_; }
private:
absl::optional<SimplifiedSlice> simple_slice_;
core::RefCountPtr<Var> input_resource_;
mutable bool locked_ = false;
bool is_identity_;
};
class DmlStridedSliceAssignKernel : public DmlKernel {
public:
using InitHelper = StridedSliceAssignInitHelper;
explicit DmlStridedSliceAssignKernel(DmlKernelConstruction* ctx,
const InitHelper* init_helper) {
const Tensor input = init_helper->GetInputTensor(ctx->GetOpKernelContext());
const TensorShape& input_shape = input.shape();
const TensorShape& updates_shape = ctx->GetInputTensorShape(4);
auto simple_slice = init_helper->GetSimplifiedSlice();
auto dtype_tf = ctx->GetInputDataType(4);
dml::TensorDimensions collapsed_input_sizes = {
1,
1,
1,
static_cast<uint32_t>(input_shape.num_elements()),
};
dml::TensorDimensions collapsed_updates_sizes = {
1,
1,
1,
static_cast<uint32_t>(updates_shape.num_elements()),
};
DmlTensorInfo updates;
updates.kernel_index = 4;
updates.desc = DmlTensorDesc::Create(dtype_tf, collapsed_updates_sizes,
collapsed_updates_sizes);
DmlTensorInfo output;
output.kernel_index = 0;
output.desc = DmlTensorDesc::Create(dtype_tf, collapsed_input_sizes,
collapsed_input_sizes);
DmlKernelTensors tensors;
tensors.inputs = {updates};
if (!init_helper->IsIdentity()) {
DmlTensorInfo original_input;
original_input.kernel_index = 0;
original_input.desc = DmlTensorDesc::Create(
dtype_tf, collapsed_input_sizes, collapsed_input_sizes);
tensors.inputs.push_back(original_input);
}
tensors.outputs = {output};
if (input.dtype() != DT_RESOURCE) {
// The input ref and the output ref must refer to the same memory
tensors.output_refs_forwarding = {0};
}
auto scope = dml::Graph(ctx->GetDmlDevice());
auto inputs = GetDmlTensorDescs(tensors.inputs);
auto updates_tensor = dml::InputTensor(scope, 0, inputs[0]);
dml::Expression result;
if (init_helper->IsIdentity()) {
result = dml::Identity(updates_tensor);
} else {
auto original_input_tensor = dml::InputTensor(scope, 1, inputs[1]);
auto indices_start = dml::ScalarUnion(0, DML_TENSOR_DATA_TYPE_UINT32);
auto indices_delta = dml::ScalarUnion(1, DML_TENSOR_DATA_TYPE_UINT32);
auto indices = dml::FillValueSequence(scope, simple_slice->input_sizes,
DML_TENSOR_DATA_TYPE_UINT32,
indices_start, indices_delta);
auto sliced_indices =
dml::Slice(indices, simple_slice->window_offset,
simple_slice->window_sizes, simple_slice->window_strides);
sliced_indices =
dml::Reinterpret(sliced_indices, collapsed_updates_sizes, {});
result = dml::ScatterElements(original_input_tensor, sliced_indices,
updates_tensor, 3);
}
// TFDML #24881131
if (Is64BitSignedIntegerType(ctx->GetInputDataType(4))) {
result = dml::ConvertInt32ToInt64(result);
}
Microsoft::WRL::ComPtr<IDMLCompiledOperator> compiled_op =
scope.Compile(DML_EXECUTION_FLAG_NONE, {result});
Initialize(ctx, std::move(tensors), compiled_op.Get());
}
StatusOr<DmlGpuEvent> Compute(DmlKernelContext* ctx) const override {
auto init_helper = ctx->GetInitializationHelper<InitHelper>();
auto lock_cleanup =
gtl::MakeCleanup([init_helper] { init_helper->Unlock(); });
const Tensor input_tensor =
init_helper->GetInputTensor(ctx->GetOpKernelContext());
// Identity can be done in-place
if (init_helper->IsIdentity()) {
D3D12BufferRegion input_buffer =
ctx->GetDmlDeviceContext()->GetBufferForTensor(
ctx->GetInputTensor(4));
D3D12BufferRegion output_buffer =
ctx->GetDmlDeviceContext()->GetBufferForTensor(input_tensor);
absl::optional<DML_BUFFER_BINDING> input_bindings[] = {
input_buffer.GetBufferBinding(),
};
absl::optional<DML_BUFFER_BINDING> output_bindings[] = {
output_buffer.GetBufferBinding(),
};
return DmlKernel::Compute(ctx, input_bindings, output_bindings);
}
// Create input buffers
D3D12BufferRegion input_buffers[] = {
ctx->GetDmlDeviceContext()->GetBufferForTensor(
ctx->GetInputTensor(4)),
ctx->GetDmlDeviceContext()->GetBufferForTensor(input_tensor),
};
// Create input bindings
absl::optional<DML_BUFFER_BINDING> input_bindings[] = {
input_buffers[0].GetBufferBinding(),
input_buffers[1].GetBufferBinding(),
};
DmlBuffer output_buffer = ctx->GetDmlDeviceContext()->AllocateDefaultBuffer(
input_buffers[1].SizeInBytes());
absl::optional<DML_BUFFER_BINDING> output_bindings[] = {
output_buffer.GetBufferBinding(),
};
auto status_or_event =
DmlKernel::Compute(ctx, input_bindings, output_bindings);
if (!status_or_event.ok()) {
return status_or_event;
}
ctx->GetDmlDeviceContext()->CopyBufferToBuffer(input_buffers[1],
output_buffer.Region());
return ctx->GetDmlDeviceContext()->InsertUavBarrier();
}
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StridedSliceAssign") \
.Device(DEVICE_DML) \
.TypeConstraint<type>("T") \
.HostMemory("begin") \
.HostMemory("end") \
.HostMemory("strides"), \
DmlKernelWrapper<DmlStridedSliceAssignKernel, \
GetOutputShapeAsInputShapeHelper>) \
REGISTER_KERNEL_BUILDER( \
Name("ResourceStridedSliceAssign") \
.Device(DEVICE_DML) \
.TypeConstraint<type>("T") \
.HostMemory("ref") \
.HostMemory("begin") \
.HostMemory("end") \
.HostMemory("strides"), \
DmlKernelWrapper<DmlStridedSliceAssignKernel, NoOutputShapeHelper, \
DmlKernelCachePolicy::Never>) \
// TODO(b/25387198): A special kernel exists for int32 (see
// strided_slice_op.cc).
TF_CALL_half(REGISTER_KERNEL);
TF_CALL_float(REGISTER_KERNEL);
TF_CALL_bool(REGISTER_KERNEL);
TF_CALL_int8(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
} // namespace tensorflow | 37.022277 | 80 | 0.635522 | [
"shape",
"vector"
] |
18a94a759e44f71904c162d6d56a297a5a39979c | 748 | cpp | C++ | laser_odometry_core/src/laser_odometry_utils.cpp | Mastro93/laser_odometry | e580f3ab736ca8ebf8692e660d27272e2c56c403 | [
"Apache-2.0"
] | 57 | 2017-05-23T11:49:54.000Z | 2022-03-30T10:58:56.000Z | laser_odometry_core/src/laser_odometry_utils.cpp | NamDinhRobotics/laser_odometry | 464ce3de9671ac0f1cf3f9c583fb65974aaab929 | [
"Apache-2.0"
] | 19 | 2017-05-23T14:06:46.000Z | 2019-03-29T07:49:29.000Z | laser_odometry_core/src/laser_odometry_utils.cpp | NamDinhRobotics/laser_odometry | 464ce3de9671ac0f1cf3f9c583fb65974aaab929 | [
"Apache-2.0"
] | 27 | 2018-04-26T03:25:15.000Z | 2022-03-27T13:03:00.000Z | #include <laser_odometry_core/laser_odometry_utils.h>
namespace laser_odometry
{
namespace utils
{
void tfFromXYTheta(const double x, const double y, const double theta, Transform& t)
{
Eigen::AngleAxis<Scalar> rollAngle(0, Eigen::Vector3d::UnitX());
Eigen::AngleAxis<Scalar> pitchAngle(0, Eigen::Vector3d::UnitY());
Eigen::AngleAxis<Scalar> yawAngle(theta, Eigen::Vector3d::UnitZ());
Eigen::Quaternion<Scalar> q = rollAngle * pitchAngle * yawAngle;
t = q;
t.translation() = Eigen::Matrix<Scalar, 3, 1>(x, y, 0);
}
template <>
inline bool all_positive<float>(const std::vector<float> vec);
template <>
inline bool all_positive<double>(const std::vector<double> vec);
} /* namespace utils */
} /* namespace laser_odometry */
| 26.714286 | 84 | 0.717914 | [
"vector",
"transform"
] |
18ad7acd9309b880b23cb3bb2a435571e3943356 | 253 | cpp | C++ | variable.cpp | chrisBosse/CMSC330_P2 | b941ae2334727ea1229e4a0756e079385911ef9b | [
"MIT"
] | 1 | 2021-07-07T01:49:25.000Z | 2021-07-07T01:49:25.000Z | variable.cpp | chrisBosse/CMSC330_P2 | b941ae2334727ea1229e4a0756e079385911ef9b | [
"MIT"
] | null | null | null | variable.cpp | chrisBosse/CMSC330_P2 | b941ae2334727ea1229e4a0756e079385911ef9b | [
"MIT"
] | 1 | 2018-05-02T02:37:16.000Z | 2018-05-02T02:37:16.000Z | #include <strstream>
#include <vector>
using namespace std;
#include "expression.h"
#include "operand.h"
#include "variable.h"
#include "symboltable.h"
extern SymbolTable symbolTable;
double Variable::evaluate()
{
return symbolTable.lookUp(name);
}
| 15.8125 | 33 | 0.754941 | [
"vector"
] |
18b6ba062aace7e505d42b9ad7cf6162afefc7b5 | 697 | hpp | C++ | include/intersect_result.hpp | voyagingmk/comnode | cd73a3e58a074f7fce7eb47c4b053a199145cf99 | [
"MIT"
] | 9 | 2017-06-11T06:24:29.000Z | 2020-04-11T14:50:43.000Z | include/intersect_result.hpp | voyagingmk/comnode | cd73a3e58a074f7fce7eb47c4b053a199145cf99 | [
"MIT"
] | null | null | null | include/intersect_result.hpp | voyagingmk/comnode | cd73a3e58a074f7fce7eb47c4b053a199145cf99 | [
"MIT"
] | 1 | 2018-04-24T14:12:54.000Z | 2018-04-24T14:12:54.000Z | #ifndef INTERSECT_RESULT_HPP
#define INTERSECT_RESULT_HPP
#include "base.hpp"
class IntersectResult{
PtrGeometry m_geometry;
double m_distance;
PtrVector m_position;
PtrVector m_normal;
public:
IntersectResult();
IntersectResult(PtrGeometry, double, PtrVector, PtrVector);
IntersectResult(PtrGeometry, double, const Vector&, const Vector&);
void setGeometry(PtrGeometry ptrGeo){ m_geometry = ptrGeo;};
PtrGeometry getGeometry(){ return m_geometry; };
double getDistance(){ return m_distance; };
PtrVector getPosition(){ return m_position; };
PtrVector getNormal(){ return m_normal; };
public:
static PtrIntersectResult NoHit;
};
#endif // INTERSECT_RESULT_HPP
| 27.88 | 71 | 0.761836 | [
"vector"
] |
18c5fcea38eafdb5894318a54610bb4b402e160e | 1,358 | cpp | C++ | DataStructure/sparse_table.cpp | kmyk/rsk0315-library | 344f8f8c6c8c8951637154d6cb87cfb3dbc50376 | [
"MIT"
] | 7 | 2020-03-30T11:05:43.000Z | 2022-03-24T06:18:38.000Z | DataStructure/sparse_table.cpp | kmyk/rsk0315-library | 344f8f8c6c8c8951637154d6cb87cfb3dbc50376 | [
"MIT"
] | null | null | null | DataStructure/sparse_table.cpp | kmyk/rsk0315-library | 344f8f8c6c8c8951637154d6cb87cfb3dbc50376 | [
"MIT"
] | 2 | 2021-07-27T05:48:29.000Z | 2022-03-24T06:18:40.000Z | #ifndef H_sparse_table
#define H_sparse_table
/**
* @brief sparse table
* @author えびちゃん
*/
#include <cstddef>
#include <vector>
#include "utility/literals.cpp"
#include "integer/bit.cpp"
template <typename Band>
class sparse_table {
public:
using size_type = size_t;
using value_type = Band;
private:
std::vector<std::vector<value_type>> M_c;
public:
sparse_table() = default;
template <typename InputIt>
sparse_table(InputIt first, InputIt last) {
assign(first, last);
}
template <typename InputIt>
sparse_table(std::initializer_list<value_type> il) {
assign(il.begin(), il.end());
}
template <typename InputIt>
void assign(InputIt first, InputIt last) {
M_c.assign(1, std::vector<value_type>(first, last));
size_type n = M_c[0].size();
for (size_type i = 1, ii = 1; M_c.back().size() > ii; (++i, ii <<= 1)) {
M_c.emplace_back();
M_c.back().reserve(n - ii);
for (size_type j = ii; j < M_c[i-1].size(); ++j)
M_c[i].push_back(M_c[i-1][j] + M_c[i-1][j-ii]);
}
}
void assign(std::initializer_list<value_type> il) {
assign(il.begin(), il.end());
}
value_type fold(size_type l, size_type r) const {
if (l >= r) return {};
size_type e = ilog2(r-l);
r -= (1_zu << e) - 1;
return M_c[e][l] + M_c[e][r-1];
}
};
#endif /* !defined(H_sparse_table) */
| 22.262295 | 76 | 0.623711 | [
"vector"
] |
18c6dc222aa49a8d12f85fb0d0579f95a0e93db4 | 49,993 | cc | C++ | src/lib/HiFPlacer/placement/globalPlacement/GeneralSpreader.cc | magic3007/AMF-Placer | b6fbc10c37c3259c2b4f99ce0bb03c9d96bc29bd | [
"Apache-2.0"
] | 37 | 2021-09-25T04:31:27.000Z | 2022-03-24T13:46:52.000Z | src/lib/HiFPlacer/placement/globalPlacement/GeneralSpreader.cc | magic3007/AMF-Placer | b6fbc10c37c3259c2b4f99ce0bb03c9d96bc29bd | [
"Apache-2.0"
] | 5 | 2021-11-01T13:27:46.000Z | 2022-03-10T07:52:51.000Z | src/lib/HiFPlacer/placement/globalPlacement/GeneralSpreader.cc | magic3007/AMF-Placer | b6fbc10c37c3259c2b4f99ce0bb03c9d96bc29bd | [
"Apache-2.0"
] | 7 | 2021-09-26T07:34:09.000Z | 2022-02-15T08:06:20.000Z | /**
* @file GeneralSpreader.cc
* @author Tingyuan LIANG (tliang@connect.ust.hk)
* @brief This implementation file contains APIs' implementation of the GeneralSpreader which accounts for the cell
* spreading, which controls the cell density of specific resource type, under the device constraints for specific
* regions.
* @version 0.1
* @date 2021-10-02
*
* @copyright Copyright (c) 2021 Reconfiguration Computing Systems Lab, The Hong Kong University of Science and
* Technology. All rights reserved.
*
*/
#include "GeneralSpreader.h"
#include <cmath>
#include <omp.h>
#include <queue>
#include <thread>
GeneralSpreader::GeneralSpreader(PlacementInfo *placementInfo, std::map<std::string, std::string> &JSONCfg,
std::string &sharedCellType, int currentIteration, float capacityShrinkRatio,
bool verbose)
: placementInfo(placementInfo), JSONCfg(JSONCfg), sharedCellType(sharedCellType),
currentIteration(currentIteration), capacityShrinkRatio(capacityShrinkRatio), verbose(verbose),
binGrid(placementInfo->getBinGrid(placementInfo->getSharedBELTypeId(sharedCellType)))
{
overflowBins.clear();
if (JSONCfg.find("jobs") != JSONCfg.end())
{
nJobs = std::stoi(JSONCfg["jobs"]);
}
if (JSONCfg.find("SpreaderSimpleExpland") != JSONCfg.end())
{
useSimpleExpland = JSONCfg["SpreaderSimpleExpland"] == "true";
}
}
void GeneralSpreader::spreadPlacementUnits(float forgetRatio, unsigned int spreadRegionBinSizeLimit)
{
if (verbose) // usually commented for debug
print_status("GeneralSpreader: starts to spreadPlacementUnits for type: [" + sharedCellType + "]");
std::deque<int> overflowBinNumQ;
int loopCnt = 0;
// int nthreads = omp_get_num_threads();
// float totalBinNum = binGrid.size() * binGrid[0].size();
std::vector<int> historyTotalCellNum(0);
while (true)
{
if (loopCnt % 5 == 0)
{
for (auto &row : binGrid)
{
for (auto curBin : row)
{
curBin->resetBinShrinkRatio();
curBin->resetNoOverflowCounter();
curBin->resetOverflowCounter();
}
}
}
loopCnt++;
if (loopCnt > 10)
break;
if (JSONCfg.find("DumpLUTFFCoordTrace-GeneralSpreader") != JSONCfg.end())
{
std::string dumpFile = JSONCfg["DumpLUTFFCoordTrace-GeneralSpreader"];
}
if (verbose)
print_status("GeneralSpreader: finding overflow regions");
findOverflowBins(capacityShrinkRatio);
if (overflowBins.size() == 0)
break;
int totalCellNum = 0;
for (auto curBin : overflowBins)
totalCellNum += curBin->getCells().size();
if (verbose) // usually commented for debug
{
print_info("found " + std::to_string(overflowBins.size()) + " overflowed bins");
print_info("found " + std::to_string(totalCellNum) + " cells in them");
print_info("spread for " + std::to_string(loopCnt) + " iterations");
}
coveredBinSet.clear();
expandedRegions.clear();
std::set<PlacementInfo::PlacementUnit *> involvedPUs;
std::set<DesignInfo::DesignCell *> involvedCells;
std::vector<PlacementInfo::PlacementUnit *> involvedPUVec;
involvedPUVec.clear();
involvedPUs.clear();
involvedCells.clear();
for (auto curBin : overflowBins)
{
if (coveredBinSet.find(curBin) != coveredBinSet.end())
continue;
GeneralSpreader::SpreadRegion *newRegion =
expandFromABin(curBin, capacityShrinkRatio, spreadRegionBinSizeLimit);
coveredBinSet.insert(curBin);
bool overlappedWithPreviousRegion = false;
for (auto curRegion : expandedRegions)
{
if (curRegion->isRegionOverlap(newRegion))
{
overlappedWithPreviousRegion = true;
std::cout << "newRegion: "
<< " left:" << newRegion->left() << " right:" << newRegion->right()
<< " top:" << newRegion->top() << " bottom:" << newRegion->bottom() << "\n";
std::cout << "====================================================\n";
for (auto curbin0 : newRegion->getBinsInRegion())
{
std::cout << "-----------------\n";
std::cout << curbin0 << " sharedBELStr:" << curbin0->getSharedCellType()
<< " X: " << curbin0->X() << " Y: " << curbin0->Y() << " left:" << curbin0->left()
<< " right:" << curbin0->right() << " top:" << curbin0->top()
<< " bottom:" << curbin0->bottom() << "\n";
}
std::cout << "\n\n\nexistingRegion: "
<< " left:" << curRegion->left() << " right:" << curRegion->right()
<< " top:" << curRegion->top() << " bottom:" << curRegion->bottom() << "\n";
std::cout << "====================================================\n";
for (auto curbin0 : curRegion->getBinsInRegion())
{
std::cout << "-----------------\n";
std::cout << curbin0 << " sharedBELStr:" << curbin0->getSharedCellType()
<< " X: " << curbin0->X() << " Y: " << curbin0->Y() << " left:" << curbin0->left()
<< " right:" << curbin0->right() << " top:" << curbin0->top()
<< " bottom:" << curbin0->bottom() << "\n";
}
break;
}
}
if (!overlappedWithPreviousRegion)
{
coveredBinSet.insert(curBin);
expandedRegions.push_back(newRegion);
}
else
{
assert(false && "should not overlap");
delete newRegion;
}
}
if (nJobs > 4)
omp_set_num_threads(
4); // we don't need that high parallelism here since regionNum will be small in later iterations
#pragma omp parallel sections
{
#pragma omp section
{
if (verbose) // usually commented for debug
print_status("involved regions cover " + std::to_string(coveredBinSet.size()) + " bins.");
if (verbose)
{
print_status("GeneralSpreader: spreading cells in the regions");
}
int regionNum = expandedRegions.size();
if (coveredBinSet.size() > 256 && regionNum > 32)
{
#pragma omp parallel for schedule(dynamic, 4)
for (int regionId = 0; regionId < regionNum; regionId++)
{
GeneralSpreader::SpreadRegion *curRegion = expandedRegions[regionId];
assert(curRegion);
assert(curRegion->getCells().size() > 0);
SpreadRegion::SubBox *newBox =
new SpreadRegion::SubBox(placementInfo, curRegion, binGrid, capacityShrinkRatio, 100, true);
newBox->spreadAndPartition();
delete newBox;
}
}
else
{
for (int regionId = 0; regionId < regionNum; regionId++)
{
GeneralSpreader::SpreadRegion *curRegion = expandedRegions[regionId];
assert(curRegion);
assert(curRegion->getCells().size() > 0);
SpreadRegion::SubBox *newBox =
new SpreadRegion::SubBox(placementInfo, curRegion, binGrid, capacityShrinkRatio, 100, true);
newBox->spreadAndPartition();
delete newBox;
}
}
}
#pragma omp section
{
if (verbose)
print_status("GeneralSpreader: loading involved placement units");
for (auto curRegion : expandedRegions)
{
assert(curRegion);
assert(curRegion->getCells().size() > 0);
for (auto curCell : curRegion->getCells())
{
if (involvedCells.find(curCell) == involvedCells.end())
{
auto tmpPU = placementInfo->getPlacementUnitByCell(curCell);
if (involvedPUs.find(tmpPU) == involvedPUs.end())
{
involvedPUs.insert(tmpPU);
involvedPUVec.push_back(tmpPU);
}
involvedCells.insert(curCell);
}
}
}
}
}
omp_set_num_threads(nJobs);
for (auto curRegion : expandedRegions)
{
delete curRegion;
}
if (verbose)
print_status("GeneralSpreader: updating Placement Units With Spreaded Cell Locations");
updatePlacementUnitsWithSpreadedCellLocations(involvedPUs, involvedCells, involvedPUVec, forgetRatio);
if (verbose)
print_status("GeneralSpreader: updated Placement Units With Spreaded Cell Locations");
dumpLUTFFCoordinate();
}
if (verbose)
print_status("GeneralSpreader: processed all overflow regions");
recordSpreadedCellLocations();
if (JSONCfg.find("Dump Cell Density") != JSONCfg.end())
{
dumpSiteGridDensity(JSONCfg["Dump Cell Density"]);
}
dumpLUTFFCoordinate();
print_status("GeneralSpreader: accomplished spreadPlacementUnits for type: [" + sharedCellType + "]");
}
bool siteSortCmp(PlacementInfo::PlacementBinInfo *a, PlacementInfo::PlacementBinInfo *b)
{
return (a->getUtilizationRate() > b->getUtilizationRate());
}
void GeneralSpreader::findOverflowBins(float overflowThreshold)
{
overflowBins.clear();
overflowBinSet.clear();
for (auto &row : binGrid)
{
for (auto curBin : row)
{
if (curBin->isOverflow(overflowThreshold))
{
overflowBins.push_back(curBin);
overflowBinSet.insert(curBin);
curBin->countOverflow();
if (curBin->getOverflowCounter() > 5)
{
if (curBin->getBinShrinkRatio() > 0.8)
{
curBin->shrinkBinBy(0.015);
}
else
{
curBin->resetBinShrinkRatio();
}
curBin->resetOverflowCounter();
}
}
else
{
curBin->countNoOverflow();
curBin->resetOverflowCounter();
if (curBin->getNoOverflowCounter() > 5)
{
curBin->resetBinShrinkRatio();
}
}
}
}
sort(overflowBins.begin(), overflowBins.end(), siteSortCmp);
}
void GeneralSpreader::updatePlacementUnitsWithSpreadedCellLocationsWorker(
PlacementInfo *placementInfo, std::set<PlacementInfo::PlacementUnit *> &involvedPUs,
std::set<DesignInfo::DesignCell *> &involvedCells, std::vector<PlacementInfo::PlacementUnit *> &involvedPUVec,
float forgetRatio, int startId, int endId)
{
std::vector<PlacementInfo::Location> &cellLoc = placementInfo->getCellId2location();
for (int curPUID = startId; curPUID < endId; curPUID++)
{
assert((unsigned int)curPUID < involvedPUVec.size());
auto curPU = involvedPUVec[curPUID];
if (auto curUnpackedCell = dynamic_cast<PlacementInfo::PlacementUnpackedCell *>(curPU))
{
float cellX = curUnpackedCell->X();
float cellY = curUnpackedCell->Y();
DesignInfo::DesignCell *curCell = curUnpackedCell->getCell();
if (curPU->isFixed() || curPU->isLocked())
{
cellLoc[curCell->getCellId()].X = cellX;
cellLoc[curCell->getCellId()].Y = cellY;
}
else
{
makeCellInLegalArea(placementInfo, cellLoc[curCell->getCellId()].X, cellLoc[curCell->getCellId()].Y);
curPU->setSpreadLocation(cellLoc[curCell->getCellId()].X, cellLoc[curCell->getCellId()].Y, forgetRatio);
placementInfo->transferCellBinInfo(curCell->getCellId(), curPU->X(), curPU->Y());
cellLoc[curCell->getCellId()].X = curPU->X();
cellLoc[curCell->getCellId()].Y = curPU->Y();
}
}
else if (auto curMacro = dynamic_cast<PlacementInfo::PlacementMacro *>(curPU))
{
if (curPU->isFixed() || curPU->isLocked())
{
for (int vId = 0; vId < curMacro->getNumOfCells(); vId++)
{
float offsetX_InMacro, offsetY_InMacro;
DesignInfo::DesignCellType cellType;
curMacro->getVirtualCellInfo(vId, offsetX_InMacro, offsetY_InMacro, cellType);
float cellX = curMacro->X() + offsetX_InMacro;
float cellY = curMacro->Y() + offsetY_InMacro;
DesignInfo::DesignCell *curCell = curMacro->getCell(vId);
cellLoc[curCell->getCellId()].X = cellX;
cellLoc[curCell->getCellId()].Y = cellY;
}
}
else
{
double tmpTotalX = 0.0;
double tmpTotalY = 0.0;
int numCellsInvolvedInSpreading = 0;
for (int vId = 0; vId < curMacro->getNumOfCells(); vId++)
{
DesignInfo::DesignCell *curCell = curMacro->getCell(vId);
if (involvedCells.find(curCell) != involvedCells.end())
{
float offsetX_InMacro, offsetY_InMacro;
DesignInfo::DesignCellType cellType;
curMacro->getVirtualCellInfo(vId, offsetX_InMacro, offsetY_InMacro, cellType);
makeCellInLegalArea(placementInfo, cellLoc[curCell->getCellId()].X,
cellLoc[curCell->getCellId()].Y);
tmpTotalX += cellLoc[curCell->getCellId()].X - offsetX_InMacro;
tmpTotalY += cellLoc[curCell->getCellId()].Y - offsetY_InMacro;
numCellsInvolvedInSpreading++;
}
}
tmpTotalX /= (double)numCellsInvolvedInSpreading;
tmpTotalY /= (double)numCellsInvolvedInSpreading;
float curNewPUX = tmpTotalX;
float curNewPUY = tmpTotalY;
placementInfo->legalizeXYInArea(curPU, curNewPUX, curNewPUY);
curPU->setSpreadLocation(curNewPUX, curNewPUY, forgetRatio);
placementInfo->enforceLegalizeXYInArea(curPU);
for (int vId = 0; vId < curMacro->getNumOfCells(); vId++)
{
float offsetX_InMacro, offsetY_InMacro;
DesignInfo::DesignCellType cellType;
curMacro->getVirtualCellInfo(vId, offsetX_InMacro, offsetY_InMacro, cellType);
float cellX = curMacro->X() + offsetX_InMacro;
float cellY = curMacro->Y() + offsetY_InMacro;
DesignInfo::DesignCell *curCell = curMacro->getCell(vId);
placementInfo->transferCellBinInfo(curCell->getCellId(), cellX, cellY);
cellLoc[curCell->getCellId()].X = cellX;
cellLoc[curCell->getCellId()].Y = cellY;
}
}
}
}
}
void GeneralSpreader::updatePlacementUnitsWithSpreadedCellLocations(
std::set<PlacementInfo::PlacementUnit *> &involvedPUs, std::set<DesignInfo::DesignCell *> &involvedCells,
std::vector<PlacementInfo::PlacementUnit *> &involvedPUVec, float forgetRatio)
{
if (involvedPUs.size() > 100)
{
std::vector<std::thread *> threadsVec;
threadsVec.clear();
int eachThreadPUNum = involvedPUVec.size() / nJobs;
std::vector<std::pair<int, int>> startEndPairs;
startEndPairs.clear();
for (int threadId = 0, startId = 0, endId = eachThreadPUNum; threadId < nJobs;
threadId++, startId += eachThreadPUNum, endId += eachThreadPUNum)
{
if (threadId == nJobs - 1)
{
endId = involvedPUVec.size();
}
startEndPairs.emplace_back(startId, endId);
}
for (int threadId = 0; threadId < nJobs; threadId++)
{
std::thread *newThread = new std::thread(
GeneralSpreader::updatePlacementUnitsWithSpreadedCellLocationsWorker, placementInfo,
std::ref(involvedPUs), std::ref(involvedCells), std::ref(involvedPUVec), std::ref(forgetRatio),
std::ref(startEndPairs[threadId].first), std::ref(startEndPairs[threadId].second));
threadsVec.push_back(newThread);
}
for (int threadId = 0; threadId < nJobs; threadId++)
{
threadsVec[threadId]->join();
delete threadsVec[threadId];
}
}
else
{
std::vector<PlacementInfo::Location> &cellLoc = placementInfo->getCellId2location();
for (auto curPU : involvedPUVec)
{
if (auto curUnpackedCell = dynamic_cast<PlacementInfo::PlacementUnpackedCell *>(curPU))
{
float cellX = curUnpackedCell->X();
float cellY = curUnpackedCell->Y();
DesignInfo::DesignCell *curCell = curUnpackedCell->getCell();
if (curPU->isFixed() || curPU->isLocked())
{
cellLoc[curCell->getCellId()].X = cellX;
cellLoc[curCell->getCellId()].Y = cellY;
}
else
{
makeCellInLegalArea(placementInfo, cellLoc[curCell->getCellId()].X,
cellLoc[curCell->getCellId()].Y);
curPU->setSpreadLocation(cellLoc[curCell->getCellId()].X, cellLoc[curCell->getCellId()].Y,
forgetRatio);
placementInfo->transferCellBinInfo(curCell->getCellId(), curPU->X(), curPU->Y());
cellLoc[curCell->getCellId()].X = curPU->X();
cellLoc[curCell->getCellId()].Y = curPU->Y();
}
}
else if (auto curMacro = dynamic_cast<PlacementInfo::PlacementMacro *>(curPU))
{
if (curPU->isFixed() || curPU->isLocked())
{
for (int vId = 0; vId < curMacro->getNumOfCells(); vId++)
{
float offsetX_InMacro, offsetY_InMacro;
DesignInfo::DesignCellType cellType;
curMacro->getVirtualCellInfo(vId, offsetX_InMacro, offsetY_InMacro, cellType);
float cellX = curMacro->X() + offsetX_InMacro;
float cellY = curMacro->Y() + offsetY_InMacro;
DesignInfo::DesignCell *curCell = curMacro->getCell(vId);
cellLoc[curCell->getCellId()].X = cellX;
cellLoc[curCell->getCellId()].Y = cellY;
}
}
else
{
double tmpTotalX = 0.0;
double tmpTotalY = 0.0;
int numCellsInvolvedInSpreading = 0;
for (int vId = 0; vId < curMacro->getNumOfCells(); vId++)
{
DesignInfo::DesignCell *curCell = curMacro->getCell(vId);
if (involvedCells.find(curCell) != involvedCells.end())
{
float offsetX_InMacro, offsetY_InMacro;
DesignInfo::DesignCellType cellType;
curMacro->getVirtualCellInfo(vId, offsetX_InMacro, offsetY_InMacro, cellType);
makeCellInLegalArea(placementInfo, cellLoc[curCell->getCellId()].X,
cellLoc[curCell->getCellId()].Y);
tmpTotalX += cellLoc[curCell->getCellId()].X - offsetX_InMacro;
tmpTotalY += cellLoc[curCell->getCellId()].Y - offsetY_InMacro;
numCellsInvolvedInSpreading++;
}
}
tmpTotalX /= (double)numCellsInvolvedInSpreading;
tmpTotalY /= (double)numCellsInvolvedInSpreading;
float curNewPUX = tmpTotalX;
float curNewPUY = tmpTotalY;
placementInfo->legalizeXYInArea(curPU, curNewPUX, curNewPUY);
curPU->setSpreadLocation(curNewPUX, curNewPUY, forgetRatio);
placementInfo->enforceLegalizeXYInArea(curPU);
for (int vId = 0; vId < curMacro->getNumOfCells(); vId++)
{
float offsetX_InMacro, offsetY_InMacro;
DesignInfo::DesignCellType cellType;
curMacro->getVirtualCellInfo(vId, offsetX_InMacro, offsetY_InMacro, cellType);
float cellX = curMacro->X() + offsetX_InMacro;
float cellY = curMacro->Y() + offsetY_InMacro;
DesignInfo::DesignCell *curCell = curMacro->getCell(vId);
placementInfo->transferCellBinInfo(curCell->getCellId(), cellX, cellY);
cellLoc[curCell->getCellId()].X = cellX;
cellLoc[curCell->getCellId()].Y = cellY;
}
}
}
}
}
}
GeneralSpreader::SpreadRegion *GeneralSpreader::expandFromABin(PlacementInfo::PlacementBinInfo *curBin,
float capacityShrinkRatio, unsigned int numBinThr)
{ // Our Region Expanding (1.4x faster)
GeneralSpreader::SpreadRegion *resRegion =
new GeneralSpreader::SpreadRegion(curBin, placementInfo, binGrid, capacityShrinkRatio);
if (!useSimpleExpland)
{
while (resRegion->getOverflowRatio() > capacityShrinkRatio &&
resRegion->smartFindExpandDirection(coveredBinSet) && resRegion->getBinsInRegion().size() < numBinThr)
{
resRegion->smartExpand(coveredBinSet);
}
}
else
{
while (resRegion->getOverflowRatio() > capacityShrinkRatio &&
resRegion->simpleFindExpandDirection(coveredBinSet) && resRegion->getBinsInRegion().size() < numBinThr)
{
resRegion->simpleExpand(coveredBinSet);
}
}
// assert(!resRegion->isOverflow() && "TODO: how to handle the situation that the resource is not enough.");
return resRegion;
}
// GeneralSpreader::SpreadRegion *GeneralSpreader::expandFromABin(PlacementInfo::PlacementBinInfo *curBin,
// float capacityShrinkRatio)
// { // RippleFPGA Region Expanding
// GeneralSpreader::SpreadRegion *resRegion =
// new GeneralSpreader::SpreadRegion(curBin, placementInfo, binGrid, capacityShrinkRatio);
// while (resRegion->getOverflowRatio() > capacityShrinkRatio &&
// resRegion->simpleFindExpandDirection(coveredBinSet))
// {
// resRegion->simpleExpand(coveredBinSet);
// }
// // assert(!resRegion->isOverflow() && "TODO: how to handle the situation that the resource is not enough.");
// return resRegion;
// }
void GeneralSpreader::SpreadRegion::addBinRegion(int newRegionTopBinY, int newRegionBottomBinY, int newRegionLeftBinX,
int newRegionRightBinX,
std::set<PlacementInfo::PlacementBinInfo *> &coveredBinSet)
{
assert(!isRegionOverlap(newRegionTopBinY, newRegionBottomBinY, newRegionLeftBinX, newRegionRightBinX));
if (newRegionTopBinY > topBinY)
topBinY = newRegionTopBinY;
if (newRegionBottomBinY < bottomBinY)
bottomBinY = newRegionBottomBinY;
if (newRegionLeftBinX < leftBinX)
leftBinX = newRegionLeftBinX;
if (newRegionRightBinX > rightBinX)
rightBinX = newRegionRightBinX;
assert(0 <= newRegionBottomBinY);
assert(0 <= newRegionTopBinY);
assert((unsigned int)newRegionBottomBinY < binGrid.size());
assert((unsigned int)newRegionTopBinY < binGrid.size());
assert(0 <= newRegionLeftBinX);
assert(0 <= newRegionRightBinX);
assert((unsigned int)newRegionLeftBinX < binGrid[0].size());
assert((unsigned int)newRegionRightBinX < binGrid[0].size());
for (int i = newRegionBottomBinY; i <= newRegionTopBinY; i++)
for (int j = newRegionLeftBinX; j <= newRegionRightBinX; j++)
{
assert(binSetInRegion.find(binGrid[i][j]) == binSetInRegion.end());
assert(binGrid[i][j]->X() == j && binGrid[i][j]->Y() == i);
binsInRegion.push_back(binGrid[i][j]);
binSetInRegion.insert(binGrid[i][j]);
assert(coveredBinSet.find(binGrid[i][j]) == coveredBinSet.end());
coveredBinSet.insert(binGrid[i][j]);
for (auto curCell : binGrid[i][j]->getCells())
{
cellsInRegion.insert(curCell);
cellsInRegionVec.push_back(curCell);
}
totalCapacity += binGrid[i][j]->getCapacity();
totalUtilization += binGrid[i][j]->getUtilization();
}
overflowRatio = totalUtilization / totalCapacity;
}
void GeneralSpreader::recordSpreadedCellLocations()
{
for (auto tmpPU : placementInfo->getPlacementUnits())
{
tmpPU->recordSpreadLocatin();
}
}
void GeneralSpreader::SpreadRegion::SubBox::spreadAndPartition()
{
if (level == 0)
return;
if (topBinY - bottomBinY < minExpandSize - 1 && rightBinX - leftBinX < minExpandSize - 1)
{
return;
}
SubBox *boxA = nullptr, *boxB = nullptr;
if (dirIsH)
{
if (rightBinX - leftBinX >= minExpandSize - 1)
{
spreadCellsH(&boxA, &boxB);
}
if (!(boxA || boxB) && topBinY - bottomBinY >= minExpandSize - 1)
{
spreadCellsV(&boxA, &boxB);
}
}
else
{
if (topBinY - bottomBinY >= minExpandSize - 1)
{
spreadCellsV(&boxA, &boxB);
}
if (!(boxA || boxB) && rightBinX - leftBinX >= minExpandSize - 1)
{
spreadCellsH(&boxA, &boxB);
}
}
if (boxA)
{
boxA->spreadAndPartition();
}
if (boxB)
{
boxB->spreadAndPartition();
}
if (boxA)
delete boxA;
if (boxB)
delete boxB;
}
void GeneralSpreader::SpreadRegion::SubBox::spreadCellsH(SubBox **boxA, SubBox **boxB)
{
// refer to paper of POLAR and RippleFPGA
if (cellIds.size() == 0)
return;
if (cellIds.size() > 1)
quick_sort(cellIds, 0, cellIds.size() - 1, true);
std::vector<float> colCapacity(rightBinX - leftBinX + 1, 0.0);
float totalCapacity = 0;
assert(leftBinX >= 0);
assert(bottomBinY >= 0);
assert((unsigned int)topBinY < binGrid.size());
assert((unsigned int)rightBinX < binGrid[topBinY].size());
// calculate capacity
for (int binX = leftBinX; binX <= rightBinX; binX++)
{
for (int y = bottomBinY; y <= topBinY; y++)
{
float binCapacity = capacityShrinkRatio * binGrid[y][binX]->getCapacity();
colCapacity[binX - leftBinX] += binCapacity;
totalCapacity += binCapacity;
}
}
// get the boundary of the sub boxes
// @ | | @
// @ boxA | | boxB @
// @ | | @
int boxALeft = leftBinX;
int boxBRight = rightBinX;
for (int binX = leftBinX; binX <= rightBinX; binX++, boxALeft++)
{
if (colCapacity[binX - leftBinX] > 0)
break;
}
for (int binX = rightBinX; binX >= leftBinX; binX--, boxBRight--)
{
if (colCapacity[binX - leftBinX] > 0)
break;
}
if (boxBRight <= boxALeft)
{
return;
assert(false && "should not happen");
}
// | @ @ |
// | boxA @ @ boxB |
// | @ @ |
int boxARight = boxALeft;
int boxBLeft = boxBRight;
float leftCapacity = colCapacity[boxARight - leftBinX];
float rightCapacity = colCapacity[boxBLeft - leftBinX];
while (boxARight < boxBLeft - 1)
{
if (leftCapacity <= rightCapacity)
{
boxARight++;
leftCapacity += colCapacity[boxARight - leftBinX];
}
else
{
boxBLeft--;
rightCapacity += colCapacity[boxBLeft - leftBinX];
}
}
// splits the cells into two part
float leftUtilRatio = leftCapacity / totalCapacity;
float totalUtilization = 0;
for (auto cellId : cellIds)
{
totalUtilization += placementInfo->getActualOccupationByCellId(cellId);
}
float leftUtil = totalUtilization * leftUtilRatio;
int cutLineIdX = -1;
if (leftUtil > eps)
{
for (auto cellId : cellIds)
{
leftUtil -= placementInfo->getActualOccupationByCellId(cellId);
cutLineIdX++;
if (leftUtil <= eps)
break;
}
}
// assign cells into two subbox A and B
*boxA = new SubBox(this, topBinY, bottomBinY, boxALeft, boxARight, 0, cutLineIdX);
*boxB = new SubBox(this, topBinY, bottomBinY, boxBLeft, boxBRight, cutLineIdX + 1, cellIds.size() - 1);
std::vector<PlacementInfo::Location> &cellLoc = placementInfo->getCellId2location();
float overallOverflowRatio = totalUtilization / totalCapacity;
if (overallOverflowRatio < 1)
overallOverflowRatio = 1;
std::vector<int> &boxACellIds = (*boxA)->cellIds;
if (boxACellIds.size() > 0)
{
int cellInBinHead = boxACellIds.size() - 1;
int cellInBinTail = boxACellIds.size() - 1;
// spread cells' location in boxA
for (int binX = boxARight; binX >= boxALeft; binX--)
{
if (cellInBinTail < 0)
break;
float cArea = 0;
int num = 0;
float oldLoX = cellLoc[boxACellIds[cellInBinTail]].X;
float oldHiX = oldLoX;
for (cellInBinHead = cellInBinTail;
cellInBinHead >= 0 &&
(binX == boxALeft || (cArea / overallOverflowRatio <= colCapacity[binX - leftBinX] + eps));
--cellInBinHead)
{
cArea += placementInfo->getActualOccupationByCellId(boxACellIds[cellInBinHead]);
oldLoX = cellLoc[boxACellIds[cellInBinHead]].X;
num++;
}
cellInBinHead++;
if (num > 0)
{
assert(binX >= 0);
assert((unsigned int)binX < binGrid[bottomBinY].size());
float newLoX = binGrid[bottomBinY][binX]->left() + placementInfo->getBinGridW() / (num + 1.0);
float newHiX = binGrid[bottomBinY][binX]->right() - placementInfo->getBinGridW() / (num + 1.0);
float rangeold = oldHiX - oldLoX;
float rangenew = newHiX - newLoX;
assert(rangeold > -1e-5);
assert(rangenew > -1e-5);
if (fabs(rangeold) < 1e-5)
{
float newLoc = (newLoX + newHiX) / 2;
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxACellIds[ci]].X = newLoc;
}
}
else
{
float scale = rangenew / rangeold;
assert(scale > -1e-5);
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxACellIds[ci]].X = newLoX + (cellLoc[boxACellIds[ci]].X - oldLoX) * scale;
}
}
}
cellInBinTail = cellInBinHead - 1;
}
}
else
{
delete *boxA;
*boxA = nullptr;
}
std::vector<int> &boxBCellIds = (*boxB)->cellIds;
if (boxBCellIds.size() > 0)
{
int cellInBinHead = 0;
int cellInBinTail = 0;
// spread cells' location in boxB
for (int binX = boxBLeft; binX <= boxBRight; binX++)
{
if ((unsigned int)cellInBinHead >= boxBCellIds.size())
break;
float cArea = 0;
int num = 0;
float oldLoX = cellLoc[boxBCellIds[cellInBinHead]].X;
float oldHiX = oldLoX;
for (cellInBinTail = cellInBinHead;
(unsigned int)cellInBinTail < boxBCellIds.size() &&
(binX == boxBRight || (cArea / overallOverflowRatio <= colCapacity[binX - leftBinX] + eps));
cellInBinTail++)
{
cArea += placementInfo->getActualOccupationByCellId(boxBCellIds[cellInBinTail]);
oldHiX = cellLoc[boxBCellIds[cellInBinTail]].X;
num++;
}
cellInBinTail--;
assert(cellLoc[boxBCellIds[cellInBinTail]].X <= oldHiX + 1e-5);
if (num > 0)
{
assert(binX >= 0);
assert((unsigned int)binX < binGrid[bottomBinY].size());
float newLoX = binGrid[bottomBinY][binX]->left() + placementInfo->getBinGridW() / (num + 1.0);
float newHiX = binGrid[bottomBinY][binX]->right() - placementInfo->getBinGridW() / (num + 1.0);
float rangeold = oldHiX - oldLoX;
float rangenew = newHiX - newLoX;
assert(rangeold > -1e-5);
assert(rangenew > -1e-5);
if (fabs(rangeold) < 1e-5)
{
float newLoc = (newLoX + newHiX) / 2;
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxBCellIds[ci]].X = newLoc;
}
}
else
{
float scale = rangenew / rangeold;
assert(scale > -1e-5);
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxBCellIds[ci]].X = newLoX + (cellLoc[boxBCellIds[ci]].X - oldLoX) * scale;
}
}
}
cellInBinHead = cellInBinTail + 1;
}
}
else
{
delete *boxB;
*boxB = nullptr;
}
return;
}
void GeneralSpreader::SpreadRegion::SubBox::spreadCellsV(SubBox **boxA, SubBox **boxB)
{
// refer to paper of POLAR and RippleFPGA
if (cellIds.size() == 0)
return;
if (cellIds.size() > 1)
quick_sort(cellIds, 0, cellIds.size() - 1, false);
std::vector<float> colCapacity(topBinY - bottomBinY + 1, 0.0);
float totalCapacity = 0;
assert(leftBinX >= 0);
assert(bottomBinY >= 0);
assert((unsigned int)topBinY < binGrid.size());
assert((unsigned int)rightBinX < binGrid[topBinY].size());
// calculate capacity
for (int binY = bottomBinY; binY <= topBinY; binY++)
{
for (int binX = leftBinX; binX <= rightBinX; binX++)
{
float binCapacity = capacityShrinkRatio * binGrid[binY][binX]->getCapacity();
colCapacity[binY - bottomBinY] += binCapacity;
totalCapacity += binCapacity;
}
}
// get the boundary of the sub boxes
// @ @ @ @ @ @
//
// boxB
//
// ----------
// ----------
//
// boxA
//
// @ @ @ @ @ @
int boxABottom = bottomBinY;
int boxBTop = topBinY;
for (int binY = bottomBinY; binY <= topBinY; binY++, boxABottom++)
{
if (colCapacity[binY - bottomBinY] > 0)
break;
}
for (int binY = topBinY; binY >= bottomBinY; binY--, boxBTop--)
{
if (colCapacity[binY - bottomBinY] > 0)
break;
}
if (boxBTop <= boxABottom)
{
return;
assert(false && "should not happen");
}
// ----------
//
// boxB
//
// @ @ @ @ @ @
// @ @ @ @ @ @
//
//
// boxA
//
// ----------
int boxATop = boxABottom;
int boxBBottom = boxBTop;
float bottomCapacity = colCapacity[boxATop - bottomBinY];
float topCapacity = colCapacity[boxBBottom - bottomBinY];
while (boxATop < boxBBottom - 1)
{
if (bottomCapacity <= topCapacity)
{
boxATop++;
bottomCapacity += colCapacity[boxATop - bottomBinY];
}
else
{
boxBBottom--;
topCapacity += colCapacity[boxBBottom - bottomBinY];
}
}
// if (leftBinX == 26 && rightBinX == 26 && topBinY == 180 && bottomBinY == 179)
// {
// std::cout << "boxATop=" << boxATop << "\n";
// std::cout << "boxABottom=" << boxABottom << "\n";
// std::cout << "boxBTop=" << boxBTop << "\n";
// std::cout << "boxBBottom=" << boxBBottom << "\n";
// std::vector<PlacementInfo::Location> &cellLoc = placementInfo->getCellId2location();
// for (auto cellId : cellIds)
// {
// std::cout << "cell#" << cellId << " locX:" << cellLoc[cellId].X << " locY:" << cellLoc[cellId].Y << "\n";
// }
// }
// splits the cells into two part
float bottomUtilRatio = bottomCapacity / totalCapacity;
float totalUtilization = 0;
for (auto cellId : cellIds)
{
totalUtilization += placementInfo->getActualOccupationByCellId(cellId);
}
float bottomUtil = totalUtilization * bottomUtilRatio;
int cutLineIdX = -1;
if (bottomUtil > eps)
{
for (auto cellId : cellIds)
{
bottomUtil -= placementInfo->getActualOccupationByCellId(cellId);
cutLineIdX++;
if (bottomUtil <= eps)
break;
}
}
// assign cells into two subbox A and B
*boxA = new SubBox(this, boxATop, boxABottom, leftBinX, rightBinX, 0, cutLineIdX);
*boxB = new SubBox(this, boxBTop, boxBBottom, leftBinX, rightBinX, cutLineIdX + 1, cellIds.size() - 1);
std::vector<PlacementInfo::Location> &cellLoc = placementInfo->getCellId2location();
float overallOverflowRatio = totalUtilization / totalCapacity;
if (overallOverflowRatio < 1)
overallOverflowRatio = 1;
std::vector<int> &boxACellIds = (*boxA)->cellIds;
if (boxACellIds.size() > 0)
{
int cellInBinHead = boxACellIds.size() - 1;
int cellInBinTail = boxACellIds.size() - 1;
// spread cells' location in boxA
for (int binY = boxATop; binY >= boxABottom; binY--)
{
if (cellInBinTail < 0)
break;
float cArea = 0;
int num = 0;
float oriBottomY = cellLoc[boxACellIds[cellInBinTail]].Y;
float oriTopY = oriBottomY;
for (cellInBinHead = cellInBinTail;
cellInBinHead >= 0 &&
(binY == boxABottom || (cArea / overallOverflowRatio <= colCapacity[binY - bottomBinY] + eps));
--cellInBinHead)
{
cArea += placementInfo->getActualOccupationByCellId(boxACellIds[cellInBinHead]);
oriBottomY = cellLoc[boxACellIds[cellInBinHead]].Y;
num++;
}
cellInBinHead++;
if (num > 0)
{
assert(binY >= 0);
assert((unsigned int)binY < binGrid.size());
float newBottomY = binGrid[binY][leftBinX]->bottom() + placementInfo->getBinGridH() / (num + 1.0);
float newTopY = binGrid[binY][leftBinX]->top() - placementInfo->getBinGridH() / (num + 1.0);
assert(newTopY >= newBottomY);
float rangeold = oriTopY - oriBottomY;
float rangenew = newTopY - newBottomY;
assert(rangeold > -1e-5);
assert(rangenew > -1e-5);
if (fabs(rangeold) < 1e-5)
{
float newBottomc = (newBottomY + newTopY) / 2;
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxACellIds[ci]].Y = newBottomc;
}
}
else
{
float scale = rangenew / rangeold;
assert(scale > -1e-5);
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxACellIds[ci]].Y = newBottomY + (cellLoc[boxACellIds[ci]].Y - oriBottomY) * scale;
}
}
}
cellInBinTail = cellInBinHead - 1;
}
}
else
{
delete *boxA;
*boxA = nullptr;
}
std::vector<int> &boxBCellIds = (*boxB)->cellIds;
if (boxBCellIds.size() > 0)
{
int cellInBinHead = 0;
int cellInBinTail = 0;
// spread cells' location in boxB
for (int binY = boxBBottom; binY <= boxBTop; binY++)
{
if ((unsigned int)cellInBinHead >= boxBCellIds.size())
break;
float cArea = 0;
int num = 0;
float oriBottomY = cellLoc[boxBCellIds[cellInBinHead]].Y;
float oriTopY = oriBottomY;
for (cellInBinTail = cellInBinHead;
(unsigned int)cellInBinTail < boxBCellIds.size() &&
(binY == boxBTop || (cArea / overallOverflowRatio <= colCapacity[binY - bottomBinY] + eps));
cellInBinTail++)
{
cArea += placementInfo->getActualOccupationByCellId(boxBCellIds[cellInBinTail]);
oriTopY = cellLoc[boxBCellIds[cellInBinTail]].Y;
num++;
}
cellInBinTail--;
if (num > 0)
{
assert(binY >= 0);
assert((unsigned int)binY < binGrid.size());
float newBottomY = binGrid[binY][leftBinX]->bottom() + placementInfo->getBinGridH() / (num + 1.0);
float newTopY = binGrid[binY][leftBinX]->top() - placementInfo->getBinGridH() / (num + 1.0);
float rangeold = oriTopY - oriBottomY;
float rangenew = newTopY - newBottomY;
assert(rangeold > -1e-5);
assert(rangenew > -1e-5);
if (fabs(rangeold) < 1e-5)
{
float newBottomc = (newBottomY + newTopY) / 2;
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxBCellIds[ci]].Y = newBottomc;
}
}
else
{
float scale = rangenew / rangeold;
assert(scale > -1e-5);
for (int ci = cellInBinHead; ci <= cellInBinTail; ++ci)
{
cellLoc[boxBCellIds[ci]].Y = newBottomY + (cellLoc[boxBCellIds[ci]].Y - oriBottomY) * scale;
}
}
}
cellInBinHead = cellInBinTail + 1;
}
}
else
{
delete *boxB;
*boxB = nullptr;
}
return;
}
const std::string currentDateTime()
{
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
void GeneralSpreader::dumpSiteGridDensity(std::string dumpFileName)
{
dumpFileName =
dumpFileName + "-" + sharedCellType + "-" + currentDateTime() + "-" + std::to_string(dumpSiteGridDensityCnt);
print_status("GeneralSpreader: dumping density to: " + dumpFileName);
std::vector<std::vector<PlacementInfo::PlacementBinInfo *>> &curBinGrid =
placementInfo->getBinGrid(placementInfo->getSharedBELTypeId(sharedCellType));
std::ofstream outfile0(dumpFileName.c_str());
assert(outfile0.is_open() && outfile0.good() &&
"The path for site density dumping does not exist and please check your path settings");
for (auto &row : curBinGrid)
{
for (auto curBin : row)
{
outfile0 << curBin->getRealUtilizationRate() << " ";
}
outfile0 << "\n";
}
outfile0.close();
dumpSiteGridDensityCnt++;
}
void GeneralSpreader::dumpLUTFFCoordinate()
{
if (JSONCfg.find("DumpLUTFFCoordTrace-GeneralSpreader") != JSONCfg.end())
{
std::string dumpFile = JSONCfg["DumpLUTFFCoordTrace-GeneralSpreader"] + "-" + sharedCellType + "-" +
std::to_string(LUTFFCoordinateDumpCnt) + ".gz";
print_status("GeneralSpreader: dumping coordinate archieve to: " + dumpFile);
LUTFFCoordinateDumpCnt++;
if (dumpFile != "")
{
std::stringstream outfile0;
for (auto curPU : placementInfo->getPlacementUnits())
{
if (auto curUnpackedCell = dynamic_cast<PlacementInfo::PlacementUnpackedCell *>(curPU))
{
float cellX = curUnpackedCell->X();
float cellY = curUnpackedCell->Y();
DesignInfo::DesignCell *curCell = curUnpackedCell->getCell();
if (curCell->isFF() || curCell->isLUT())
{
outfile0 << cellX << " " << cellY << " " << curCell->getName() << "\n";
}
}
else if (auto curMacro = dynamic_cast<PlacementInfo::PlacementMacro *>(curPU))
{
for (int vId = 0; vId < curMacro->getNumOfCells(); vId++)
{
float offsetX_InMacro, offsetY_InMacro;
DesignInfo::DesignCellType cellType;
curMacro->getVirtualCellInfo(vId, offsetX_InMacro, offsetY_InMacro, cellType);
float cellX = curMacro->X() + offsetX_InMacro;
float cellY = curMacro->Y() + offsetY_InMacro;
if (DesignInfo::isFF(cellType) || DesignInfo::isLUT(cellType))
{
if (curMacro->getCell(vId))
outfile0 << cellX << " " << cellY << " " << curMacro->getCell(vId)->getName() << "\n";
else
outfile0 << cellX << " " << cellY << "\n";
}
}
}
}
writeStrToGZip(dumpFile, outfile0);
print_status("GeneralSpreader: dumped coordinate archieve to: " + dumpFile);
}
}
}
std::ostream &operator<<(std::ostream &os, GeneralSpreader::SpreadRegion::SubBox *curBox)
{
os << "Box: Top:" << curBox->top() << " Bottom:" << curBox->bottom() << " Left:" << curBox->left()
<< " Right:" << curBox->right();
return os;
}
void GeneralSpreader::DumpCellsCoordinate(std::string dumpFileName, GeneralSpreader::SpreadRegion *curRegion)
{
if (dumpFileName != "")
{
dumpCnt++;
dumpFileName = dumpFileName + "-" + std::to_string(dumpCnt) + ".gz";
// print_status("GeneralSpreader: dumping coordinate archieve to: " + dumpFileName);
std::stringstream outfile0;
std::vector<PlacementInfo::Location> &cellLoc = placementInfo->getCellId2location();
for (auto tmpCell : curRegion->getCells())
{
outfile0 << cellLoc[tmpCell->getCellId()].X << " " << cellLoc[tmpCell->getCellId()].Y << tmpCell << "\n";
}
writeStrToGZip(dumpFileName, outfile0);
// print_status("GeneralSpreader: dumped coordinate archieve to: " + dumpFileName);
}
}
void GeneralSpreader::DumpPUCoordinate(std::string dumpFileName,
std::vector<PlacementInfo::PlacementUnit *> &involvedPUVec)
{
if (dumpFileName != "")
{
dumpCnt++;
dumpFileName = dumpFileName + "-" + std::to_string(dumpCnt) + ".gz";
// print_status("GeneralSpreader: dumping coordinate archieve to: " + dumpFileName);
std::stringstream outfile0;
for (auto curPU : involvedPUVec)
{
outfile0 << curPU->X() << " " << curPU->Y() << " " << curPU << "\n";
}
writeStrToGZip(dumpFileName, outfile0);
// print_status("GeneralSpreader: dumped coordinate archieve to: " + dumpFileName);
}
} | 39.302673 | 120 | 0.523173 | [
"vector"
] |
18dd4731383dea63cad8bb18b4193c95b925ea57 | 1,275 | cpp | C++ | Part_A/Discrete_Frechet/Curve_discrete.cpp | EPantelaios/knn-and-clustering-with-timeseries | 3ae104068063c1152bd7c4cd148b05480a1936e9 | [
"MIT"
] | null | null | null | Part_A/Discrete_Frechet/Curve_discrete.cpp | EPantelaios/knn-and-clustering-with-timeseries | 3ae104068063c1152bd7c4cd148b05480a1936e9 | [
"MIT"
] | null | null | null | Part_A/Discrete_Frechet/Curve_discrete.cpp | EPantelaios/knn-and-clustering-with-timeseries | 3ae104068063c1152bd7c4cd148b05480a1936e9 | [
"MIT"
] | null | null | null | #include "Curve_discrete.hpp"
Curve_discrete::Curve_discrete(string id){
this->item_id = id;
this->dimension=0;
}
Curve_discrete::~Curve_discrete(){}
int Curve_discrete::add_curve_coordinate(curve_struct c){
polygonal_curve.push_back(c);
dimension = dimension + 1;
return 0;
}
int Curve_discrete::erase_coordinate(int index){
polygonal_curve.erase(polygonal_curve.begin()+index);
dimension = dimension - 1;
return 0;
}
vector<curve_struct> Curve_discrete::get_curve(){
return polygonal_curve;
}
string Curve_discrete::get_item_id(){
return item_id;
}
void Curve_discrete::print_curves(){
for(int i=0;i<polygonal_curve.size()-1;i++){
cout << "(" << polygonal_curve[i].x << ", " << polygonal_curve[i].y << "),\t";
}
int index=polygonal_curve.size() - 1;
cout << "(" << polygonal_curve[index].x << ", " << polygonal_curve[index].y << ")";
cout << endl << endl;
}
void Curve_discrete::set_init_curve(vector<curve_struct> curve){
this->init_curve = curve;
}
vector<curve_struct> Curve_discrete::get_init_curve(){
return this->init_curve;
}
void Curve_discrete::set_dimension(int d){
this->dimension = d;
}
int Curve_discrete::get_dimension(){
return this->dimension;
} | 18.75 | 87 | 0.672157 | [
"vector"
] |
18e2e5057db55a9556fc70f2757fc7c6a159815f | 6,112 | cpp | C++ | llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp | zard49/kokkos-clang | c519a032853e6507075de1807c5730b8239ab936 | [
"Unlicense"
] | 4 | 2015-10-21T05:51:05.000Z | 2015-12-19T06:27:44.000Z | llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp | losalamos/kokkos-clang | d68d9c63cea3dbaad33454e4ebc9df829bca24fe | [
"Unlicense"
] | null | null | null | llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp | losalamos/kokkos-clang | d68d9c63cea3dbaad33454e4ebc9df829bca24fe | [
"Unlicense"
] | 2 | 2019-11-16T19:03:05.000Z | 2020-03-19T08:32:37.000Z | //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file defines the WebAssembly-specific subclass of TargetMachine.
///
//===----------------------------------------------------------------------===//
#include "WebAssembly.h"
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "WebAssemblyTargetMachine.h"
#include "WebAssemblyTargetObjectFile.h"
#include "WebAssemblyTargetTransformInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
#define DEBUG_TYPE "wasm"
extern "C" void LLVMInitializeWebAssemblyTarget() {
// Register the target.
RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32);
RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64);
}
//===----------------------------------------------------------------------===//
// WebAssembly Lowering public interface.
//===----------------------------------------------------------------------===//
/// Create an WebAssembly architecture model.
///
WebAssemblyTargetMachine::WebAssemblyTargetMachine(
const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL)
: LLVMTargetMachine(T, TT.isArch64Bit()
? "e-p:64:64-i64:64-n32:64-S128"
: "e-p:32:32-i64:64-n32:64-S128",
TT, CPU, FS, Options, RM, CM, OL),
TLOF(make_unique<WebAssemblyTargetObjectFile>()) {
initAsmInfo();
// We need a reducible CFG, so disable some optimizations which tend to
// introduce irreducibility.
setRequiresStructuredCFG(true);
}
WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {}
const WebAssemblySubtarget *
WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
Attribute CPUAttr = F.getFnAttribute("target-cpu");
Attribute FSAttr = F.getFnAttribute("target-features");
std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
? CPUAttr.getValueAsString().str()
: TargetCPU;
std::string FS = !FSAttr.hasAttribute(Attribute::None)
? FSAttr.getValueAsString().str()
: TargetFS;
auto &I = SubtargetMap[CPU + FS];
if (!I) {
// This needs to be done before we create a new subtarget since any
// creation will depend on the TM and the code generation flags on the
// function that reside in TargetOptions.
resetTargetOptions(F);
I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
}
return I.get();
}
namespace {
/// WebAssembly Code Generator Pass Configuration Options.
class WebAssemblyPassConfig final : public TargetPassConfig {
public:
WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM)
: TargetPassConfig(TM, PM) {}
WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
return getTM<WebAssemblyTargetMachine>();
}
FunctionPass *createTargetRegisterAllocator(bool) override;
void addIRPasses() override;
bool addPreISel() override;
bool addInstSelector() override;
bool addILPOpts() override;
void addPreRegAlloc() override;
void addPostRegAlloc() override;
void addPreSched2() override;
void addPreEmitPass() override;
};
} // end anonymous namespace
TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() {
return TargetIRAnalysis([this](const Function &F) {
return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
});
}
TargetPassConfig *
WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
return new WebAssemblyPassConfig(this, PM);
}
FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
return nullptr; // No reg alloc
}
//===----------------------------------------------------------------------===//
// The following functions are called from lib/CodeGen/Passes.cpp to modify
// the CodeGen pass sequence.
//===----------------------------------------------------------------------===//
void WebAssemblyPassConfig::addIRPasses() {
// FIXME: the default for this option is currently POSIX, whereas
// WebAssembly's MVP should default to Single.
if (TM->Options.ThreadModel == ThreadModel::Single)
addPass(createLowerAtomicPass());
else
// Expand some atomic operations. WebAssemblyTargetLowering has hooks which
// control specifically what gets lowered.
addPass(createAtomicExpandPass(TM));
TargetPassConfig::addIRPasses();
}
bool WebAssemblyPassConfig::addPreISel() { return false; }
bool WebAssemblyPassConfig::addInstSelector() {
addPass(
createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
return false;
}
bool WebAssemblyPassConfig::addILPOpts() { return true; }
void WebAssemblyPassConfig::addPreRegAlloc() {}
void WebAssemblyPassConfig::addPostRegAlloc() {
// FIXME: the following passes dislike virtual registers. Disable them for now
// so that basic tests can pass. Future patches will remedy this.
//
// Fails with: Regalloc must assign all vregs.
disablePass(&PrologEpilogCodeInserterID);
// Fails with: should be run after register allocation.
disablePass(&MachineCopyPropagationID);
// TODO: Until we get ReverseBranchCondition support, MachineBlockPlacement
// can create ugly-looking control flow.
disablePass(&MachineBlockPlacementID);
}
void WebAssemblyPassConfig::addPreSched2() {}
void WebAssemblyPassConfig::addPreEmitPass() {
addPass(createWebAssemblyCFGStackify());
}
| 35.32948 | 80 | 0.67572 | [
"model"
] |
18f18be3df67d3336002c297e96452231c8ec592 | 1,316 | cc | C++ | nodejs/src/run_options_helper.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 6,036 | 2019-05-07T06:03:57.000Z | 2022-03-31T17:59:54.000Z | nodejs/src/run_options_helper.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 5,730 | 2019-05-06T23:04:55.000Z | 2022-03-31T23:55:56.000Z | nodejs/src/run_options_helper.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 1,566 | 2019-05-07T01:30:07.000Z | 2022-03-31T17:06:50.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "onnxruntime_cxx_api.h"
#include <napi.h>
#include <cmath>
#include "common.h"
#include "run_options_helper.h"
void ParseRunOptions(const Napi::Object options, Ort::RunOptions &runOptions) {
// Log severity level
if (options.Has("logSeverityLevel")) {
auto logLevelValue = options.Get("logSeverityLevel");
ORT_NAPI_THROW_TYPEERROR_IF(!logLevelValue.IsNumber(), options.Env(),
"Invalid argument: runOptions.logSeverityLevel must be a number.");
double logLevelNumber = logLevelValue.As<Napi::Number>().DoubleValue();
ORT_NAPI_THROW_RANGEERROR_IF(
std::floor(logLevelNumber) != logLevelNumber || logLevelNumber < 0 || logLevelNumber > 4, options.Env(),
"Invalid argument: runOptions.logSeverityLevel must be one of the following: 0, 1, 2, 3, 4.");
runOptions.SetRunLogSeverityLevel(static_cast<int>(logLevelNumber));
}
// Tag
if (options.Has("tag")) {
auto tagValue = options.Get("tag");
ORT_NAPI_THROW_TYPEERROR_IF(!tagValue.IsString(), options.Env(),
"Invalid argument: runOptions.tag must be a string.");
runOptions.SetRunTag(tagValue.As<Napi::String>().Utf8Value().c_str());
}
}
| 38.705882 | 112 | 0.68845 | [
"object"
] |
18f6da78a47bc2cb916dca2c7436a25fdc580cf1 | 2,794 | cpp | C++ | Study Material/ArabicCompetitiveProgramming-master/06 String Processing/Algorithms - String Processing - 04 - Aho-Corasick.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | 1 | 2019-12-19T06:51:20.000Z | 2019-12-19T06:51:20.000Z | Study Material/ArabicCompetitiveProgramming-master/06 String Processing/Algorithms - String Processing - 04 - Aho-Corasick.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | Study Material/ArabicCompetitiveProgramming-master/06 String Processing/Algorithms - String Processing - 04 - Aho-Corasick.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | #include<set>
#include<map>
#include<list>
#include<iomanip>
#include<cmath>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<complex>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
#define all(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
#define clr(v, d) memset(v, d, sizeof(v))
#define repi(i, j, n) for(int i=(j);i<(int)(n);++i)
#define repd(i, j, n) for(int i=(j);i>=(int)(n);--i)
#define repa(v) repi(i, 0, sz(v)) repi(j, 0, sz(v[i]))
#define rep(i, v) repi(i, 0, sz(v))
#define lp(i, cnt) repi(i, 0, cnt)
#define lpi(i, s, cnt) repi(i, s, cnt)
const int MAX = 26+1; //+1 to assign starting from 1
//TODO: Input limits, to be modified
const int MAX_PAT_LEN = 15;
const int MAX_PATS = 30;
char pats[MAX_PATS][MAX_PAT_LEN];
int nextNodeId = 0;
int cIdx(char c) {
return 1 + c-'a';
//return c; //in case any problems
}
//you can either use Large MAX (e.g. 260) or reassign string to smalled indices
struct node {
node* fail;
node* child[MAX];
vector<int> patIdx;
vector<char> chars;
int id;
node() {
clr(child, 0);
id = nextNodeId++;
}
void insert(char* str, int idx, bool firstCall = true) {
// You can remove next part, it just reassign string to indices to keep small mem
if(firstCall) {
char *t = str;
while(*t) *t = cIdx(*t), t++;
}
/////////////////////////////////
if (!*str) {
patIdx.push_back(idx);
} else {
if (!child[*str]) {
child[*str] = new node();
chars.push_back(*str);
}
child[*str]->insert(str + 1, idx, false);
}
}
};
void move(node* &k, char c) {
while (!k->child[c])
k = k->fail;
k = k->child[c];
}
node* buildAhoTree(char pat[][MAX_PAT_LEN], int len) {
node * root = new node();
lp(i, len) {
root->insert(pat[i], i);
}
queue<node*> q;
lp(i, MAX)
if (root->child[i])
q.push(root->child[i]), root->child[i]->fail = root;
else
root->child[i] = root; //Sentinel
node* cur;
while (!q.empty()) {
cur = q.front();
q.pop();
rep(i, cur->chars) {
int ch = cur->chars[i];
q.push(cur->child[ch]);
node* k = cur->fail;
move(k, ch);
cur->child[ch]->fail = k;
cur->child[ch]->patIdx.insert(cur->child[ch]->patIdx.end(), all(k->patIdx));
}
}
return root;
}
void match(const char* str, node* root, vector<vector<int> > & res) {
node* k = root;
for (int i = 0; str[i]; i++) {
move(k, str[i]);
rep(j, k->patIdx)
res[k->patIdx[j]].push_back(i);
}
}
int main() {
scanf("%s", arr);
int k;
scanf("%d", &k);
lp(i, k) {
scanf("%s", &pats[i]);
}
node* root = buildAhoTree(pats, k);
vector<vector<int> > res(k);
match(arr, root, res);
lp(i, k) {
if (sz(res[i]))
printf("y\n");
else
printf("n\n");
}
return 0;
}
| 18.878378 | 83 | 0.572298 | [
"vector"
] |
7a00cdf3b7a4975025b79f9e008b900031027e94 | 11,283 | hpp | C++ | src/adapt/UniformRefinerPattern_Hex8_Tet4_24.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 3 | 2017-08-08T21:06:02.000Z | 2020-01-08T13:23:36.000Z | src/adapt/UniformRefinerPattern_Hex8_Tet4_24.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2016-12-17T00:18:56.000Z | 2019-08-09T15:29:25.000Z | src/adapt/UniformRefinerPattern_Hex8_Tet4_24.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2017-11-30T07:02:41.000Z | 2019-08-05T17:07:04.000Z | // Copyright 2002 - 2008, 2010, 2011 National Technology Engineering
// Solutions of Sandia, LLC (NTESS). Under the terms of Contract
// DE-NA0003525 with NTESS, the U.S. Government retains certain rights
// in this software.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef adapt_UniformRefinerPattern_Hex8_Tet4_24_hpp
#define adapt_UniformRefinerPattern_Hex8_Tet4_24_hpp
#include "UniformRefinerPattern.hpp"
#include "UniformRefinerPattern_Quad4_Tri3_4.hpp"
namespace percept {
/** From Shards_BasicTopologies.hpp
*
* \brief Topological traits: Dimension = 3, Sides = 6, Edges = 12,
* Vertices = 8, and Nodes = 8, 20, or 27.
*
* <PRE>
* Linear 8-Node Hexahedron node locations.
*
* 7 6
* o------------------o
* /| /|
* / | / |
* / | / |
* / | / |
* / | / |
* / | / |
* 4 / | 5 / |
* o------------------o |
* | | | |
* | 3 o----------|-------o 2
* | / | /
* | / | /
* | / | /
* | / | /
* | / | /
* | / | /
* |/ |/
* o------------------o
* 0 1
*
*
* face numbering for symmetric hex to tet break pattern | typedef
* | MakeTypeList< IndexList< 0 , 1 , 8 > ,
* 7 | IndexList< 1 , 2 , 9 > ,
* o------------------o 6 | IndexList< 2 , 3 , 10 > ,
* /| /| | IndexList< 3 , 0 , 11 > ,
* / | / | | IndexList< 4 , 5 , 16 > ,
* / | 13 / | | IndexList< 5 , 6 , 17 > ,
* / | o / | | IndexList< 6 , 7 , 18 > ,
* / | o10 / | Node #14 is at centroid of element | IndexList< 7 , 4 , 19 > ,
* / | / | | IndexList< 0 , 4 , 12 > ,
* 4 / | 5 / | "2D surface" containing nodes | IndexList< 1 , 5 , 13 > ,
* o------------------o 9 | 0,1,5,4 has node 25 at center.... | IndexList< 2 , 6 , 14 > ,
* | 11o | 3 | o | | IndexList< 3 , 7 , 15 > >::type
* | o----------|-------o 2 | HexahedronEdgeNodeMap ;
* | / | / |
* | / 8 | / | typedef
* | / o | / | MakeTypeList< IndexList< 0, 1, 5, 4, 8, 13, 16, 12, 25 > ,
* | / o12 | / | IndexList< 1, 2, 6, 5, 9, 14, 17, 13, 24 > ,
* | / | / | IndexList< 2, 3, 7, 6, 10, 15, 18, 14, 26 > ,
* | / | / | IndexList< 0, 4, 7, 3, 12, 19, 15, 11, 23 > ,
* |/ |/ | IndexList< 0, 3, 2, 1, 11, 10, 9, 8, 21 > ,
* o------------------o | IndexList< 4, 5, 6, 7, 16, 17, 18, 19, 22 > >::type
* 0 1 | HexahedronFaceNodeMap ;
* |
* </PRE> |
*
*
*/
template <>
class UniformRefinerPattern<shards::Hexahedron<8>, shards::Tetrahedron<4>, 24 > : public URP<shards::Hexahedron<8>, shards::Tetrahedron<4> >
{
private:
UniformRefinerPattern<shards::Quadrilateral<4>, shards::Triangle<3>, 4, Specialization > *m_face_breaker;
public:
virtual bool edgeMarkIsEnough() { return false; }
UniformRefinerPattern(percept::PerceptMesh& eMesh, BlockNamesType block_names = BlockNamesType()) : URP<shards::Hexahedron<8>, shards::Tetrahedron<4> >(eMesh)
{
EXCEPTWATCH;
m_primaryEntityRank = stk::topology::ELEMENT_RANK;
setNeededParts(eMesh, block_names, false);
#define USE_FACE_BREAKER 1
#if USE_FACE_BREAKER
m_face_breaker = new UniformRefinerPattern<shards::Quadrilateral<4>, shards::Triangle<3>, 4, Specialization > (eMesh, block_names);
#endif
}
~UniformRefinerPattern()
{
if (m_face_breaker) delete m_face_breaker;
}
virtual void doBreak() {}
void fillNeededEntities(std::vector<NeededEntityType>& needed_entities)
{
needed_entities.resize(2);
needed_entities[0].first = m_eMesh.face_rank();
needed_entities[1].first = stk::topology::ELEMENT_RANK;
setToOne(needed_entities);
}
void setSubPatterns( std::vector<UniformRefinerPatternBase *>& bp, percept::PerceptMesh& eMesh )
{
EXCEPTWATCH;
bp.resize(1);
bp[0] = this;
#if USE_FACE_BREAKER
bp.push_back( m_face_breaker);
#endif
}
virtual unsigned getNumNewElemPerElem() { return 24u; }
void
createNewElements(percept::PerceptMesh& eMesh, NodeRegistry& nodeRegistry,
stk::mesh::Entity element, NewSubEntityNodesType& new_sub_entity_nodes, vector<stk::mesh::Entity>::iterator& element_pool,
vector<stk::mesh::Entity>::iterator& ft_element_pool,
stk::mesh::FieldBase *proc_rank_field=0)
{
EXCEPTWATCH;
const CellTopologyData * const cell_topo_data = m_eMesh.get_cell_topology(element);
typedef boost::tuple<stk::mesh::EntityId, stk::mesh::EntityId, stk::mesh::EntityId, stk::mesh::EntityId> tet_tuple_type;
static vector<tet_tuple_type> elems(24);
shards::CellTopology cell_topo(cell_topo_data);
const percept::MyPairIterRelation elem_nodes (m_eMesh, element, stk::topology::NODE_RANK);
// FIXME - maybe the computation of node coorinates should go in the calling code?
double tmp_x[3];
for (unsigned i_face = 0; i_face < 6; i_face++)
{
double * pts[4] = {FACE_COORD(i_face, 0), FACE_COORD(i_face, 1), FACE_COORD(i_face, 2), FACE_COORD(i_face, 3)};
double * mp = getCentroid(pts, 4, eMesh.get_spatial_dim(), tmp_x);
#if 0
std::cout << "pts = \n"
<< pts[0][0] << " " << pts[0][1] << " " << pts[0][2] << " \n"
<< pts[1][0] << " " << pts[1][1] << " " << pts[1][2] << " \n"
<< pts[2][0] << " " << pts[2][1] << " " << pts[2][2] << " \n"
<< pts[3][0] << " " << pts[3][1] << " " << pts[3][2] << " \n"
<< " centroid = "
<< mp[0] << " " << mp[1] << " " << mp[2] << std::endl;
#endif
//stk::mesh::Entity new_node =eMesh.createOrGetNode(FACE_N(i_face), mp);
eMesh.createOrGetNode(FACE_N(i_face), mp);
nodeRegistry.addToExistingParts(element, m_eMesh.face_rank(), i_face);
nodeRegistry.prolongateFields(element, m_eMesh.face_rank(), i_face);
}
nodeRegistry.prolongateCoords(element, stk::topology::ELEMENT_RANK, 0u);
nodeRegistry.addToExistingParts(element, stk::topology::ELEMENT_RANK, 0u);
nodeRegistry.prolongateFields(element, stk::topology::ELEMENT_RANK, 0u);
//#define C 14
// new_sub_entity_nodes[i][j]
#define CENTROID_N NN(stk::topology::ELEMENT_RANK, 0)
unsigned iele = 0;
for (unsigned i_face = 0; i_face < 6; i_face++)
{
for (unsigned i_tri_on_face = 0; i_tri_on_face < 4; i_tri_on_face++)
{
unsigned itf = cell_topo_data->side[i_face].node[ i_tri_on_face ];
unsigned itfp = cell_topo_data->side[i_face].node[ (i_tri_on_face + 1) % 4];
if ( itf > 7)
{
throw std::logic_error("UniformRefinerPattern_Hex8_Tet4_20 logic err");
}
elems[iele++] = tet_tuple_type(CENTROID_N, VERT_N(itf), VERT_N(itfp), FACE_N(i_face));
}
}
#undef CENTROID_N
// write a diagram of the refinement pattern as a vtk file, or a latex/tikz/pgf file
#define WRITE_DIAGRAM 0
#if WRITE_DIAGRAM
#endif
for (unsigned ielem=0; ielem < elems.size(); ielem++)
{
//stk::mesh::Entity newElement = eMesh.get_bulk_data()->declare_entity(Element, *element_id_pool, eMesh.getPart(interface_table::shards_Triangle_3) );
//stk::mesh::Entity newElement = eMesh.get_bulk_data()->declare_entity(Element, *element_id_pool, eMesh.getPart(interface_table::shards_Triangle_3) );
stk::mesh::Entity newElement = *element_pool;
if (proc_rank_field)
{
double *fdata = stk::mesh::field_data( *static_cast<const ScalarFieldType *>(proc_rank_field) , newElement );
fdata[0] = double(eMesh.owner_rank(newElement));
}
change_entity_parts(eMesh, element, newElement);
{
if (!elems[ielem].get<0>())
{
std::cout << "P[" << eMesh.get_rank() << " nid = 0 << " << std::endl;
exit(1);
}
}
eMesh.get_bulk_data()->declare_relation(newElement, eMesh.createOrGetNode(elems[ielem].get<0>()), 0);
eMesh.get_bulk_data()->declare_relation(newElement, eMesh.createOrGetNode(elems[ielem].get<1>()), 1);
eMesh.get_bulk_data()->declare_relation(newElement, eMesh.createOrGetNode(elems[ielem].get<2>()), 2);
eMesh.get_bulk_data()->declare_relation(newElement, eMesh.createOrGetNode(elems[ielem].get<3>()), 3);
set_parent_child_relations(eMesh, element, newElement, *ft_element_pool, ielem);
ft_element_pool++;
element_pool++;
}
}
};
}
#endif
| 45.680162 | 164 | 0.440397 | [
"mesh",
"vector"
] |
bb39f8149b31ed0fb11b7ef6268552ee02c16a86 | 574 | cc | C++ | LeetCode/Medium/DP/minimumTickets.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | LeetCode/Medium/DP/minimumTickets.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | LeetCode/Medium/DP/minimumTickets.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/minimum-cost-for-tickets/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int mincostTickets(vector<int> &days, vector<int> &costs) {
int n = days.size();
int dp[n][n];
fill_n(*dp, n * n, -1);
for (int i = 0; i < days.size(); i++) {
for (int j = i; j < days.size(); j++) {
if(i == j)
dp[i][j] = costs[0];
else if (j - i < 7)
dp[i][j] = min(costs[0]*(j-i+1), costs[1]);
else if (j - i < 20)
}
}
}
}; | 22.076923 | 61 | 0.477352 | [
"vector"
] |
bb3cf2393cfd5249ce8859f69d064de11f9bfeae | 948 | cpp | C++ | Codeforces/B677.cpp | amrfahmyy/Problem-Solving | 4c7540a1df3c4be206fc6dc6c77d754b513b314f | [
"Apache-2.0"
] | null | null | null | Codeforces/B677.cpp | amrfahmyy/Problem-Solving | 4c7540a1df3c4be206fc6dc6c77d754b513b314f | [
"Apache-2.0"
] | null | null | null | Codeforces/B677.cpp | amrfahmyy/Problem-Solving | 4c7540a1df3c4be206fc6dc6c77d754b513b314f | [
"Apache-2.0"
] | 1 | 2021-04-02T14:20:11.000Z | 2021-04-02T14:20:11.000Z | #include <bits/stdc++.h>
#define SLAY ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define PI 3.141592653589793238
#define ll long long
#define pii pair<int , int>
#define pll pair<long long , long long>
#define INPUT freopen("inp.txt", "r", stdin);
using namespace std;
int dx[] = { 0 , 0 , 1 , -1};
int dy[] = { 1 , -1 , 0 , 0};
int getmod(int x, int y , int mod ){return (((x - y)%mod)+mod)%mod;}
int main(){SLAY
int _=1 , tc=1;
// cin>>_;
while(_--){
ll n,h,k,ans=0;
cin>>n>>h>>k;
vector<ll>v(n);
for(int i = 0;i<n;i++)cin>>v[i];
int i =0;
ll inside=0;
while(i<n && h-inside >= v[i]){
inside +=v[i];
i++;
}
for(;i <n ;){
ll need = v[i]- (h-inside);
ll loops = ceil(1.0*need/k);
ans += loops;
inside -= loops*k;
inside = max(inside , (ll)0);
while(i<n && h-inside >= v[i]){
inside +=v[i];
i++;
}
}
ans+= ceil(1.0*inside/k);
cout<<ans;
cout<<endl;
}
return 0;
} | 21.066667 | 71 | 0.541139 | [
"vector"
] |
bb3f6118f0f6b1e08da5d66a6ec87ce3103ca108 | 1,304 | cpp | C++ | graph/detect-cycle-DGraph-using-kahns.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | graph/detect-cycle-DGraph-using-kahns.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | graph/detect-cycle-DGraph-using-kahns.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
// adj[v].push_back(u);
}
void displayGraph(vector<int> adj[], int v)
{
for (int i = 0; i < v; i++)
{
for (auto &&j : adj[i])
cout << j << " ";
cout << endl;
}
}
void storeIndegree(vector<int> adj[], int v, int indegree[])
{
for (int i = 0; i < v; i++)
{
for (auto j : adj[i])
indegree[j]++;
}
}
bool detectCycle(vector<int> adj[], int v)
{
int indegree[v + 1]{};
storeIndegree(adj, v, indegree);
queue<int> q;
for (int i = 0; i < v; i++)
{
if (indegree[i] == 0)
{
q.push(i);
}
}
int count = 0;
while (!q.empty())
{
int u = q.front();
q.pop();
for (auto i : adj[u])
{
indegree[i]--;
if (indegree[i] == 0)
q.push(i);
}
count++;
}
return (count != v);
}
int main()
{
vector<int> adj[4];
addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
addEdge(adj, 3, 1);
// displayGraph(adj, 4);
cout << detectCycle(adj, 4);
return 0;
} | 18.366197 | 61 | 0.416411 | [
"vector"
] |
bb57e5983e1743b25b150e1e2b0cc17cfbcfd639 | 6,896 | cpp | C++ | GUI.cpp | NicoSchumann/TicTacToe | df7349ebd82dfbc2561b4dc1b4627917d4067845 | [
"Unlicense"
] | 1 | 2018-08-29T21:12:52.000Z | 2018-08-29T21:12:52.000Z | GUI.cpp | NicoSchumann/TicTacToe | df7349ebd82dfbc2561b4dc1b4627917d4067845 | [
"Unlicense"
] | null | null | null | GUI.cpp | NicoSchumann/TicTacToe | df7349ebd82dfbc2561b4dc1b4627917d4067845 | [
"Unlicense"
] | null | null | null | #include "GUI.hpp"
/*--------------- class Canvas ------------------*/
Canvas::Canvas(sf::RenderWindow * window)
: m_window(window)
{
if (!m_texture.loadFromFile("images/64x32_tictactoe.png"))
{
std::cerr << "Texture file couldn't loaded!";
}
for (auto & sprite : m_sprite)
{
sprite = sf::Sprite(m_texture, sf::Rect<int>(64,0,32,32));
sprite.setOrigin(16,16);
}
resize();
}
Canvas::~Canvas()
{}
void
Canvas::resize()
{
sf::Vector2u wSize = m_window->getSize();
// Adjust the bars:
for (std::size_t i = 0; i < m_bar.size(); ++i)
{
m_bar[i].setFillColor(sf::Color(0xaa, 0xbb, 0xcc));
if (i % 2 == 0) // 0, 2; horizontal bars
{
m_bar[i].setOrigin(0, 2);
m_bar[i].setSize(sf::Vector2<float>(wSize.x, 5));
if (i == 0)
{
m_bar[i].setPosition(0, wSize.y / 3);
}
else
{
m_bar[i].setPosition(0, 2 * wSize.y / 3);
}
}
else // 1, 3; vertical bars
{
m_bar[i].setOrigin(2, 0);
m_bar[i].setSize(sf::Vector2<float>(5, wSize.y));
if (i == 1)
{
m_bar[i].setPosition(wSize.x / 3, 0);
}
else
{
m_bar[i].setPosition(2 * wSize.x / 3, 0);
}
}
}
// Adjust the marks:
m_sprite[0].setPosition(wSize.x / 6.0f * 1, wSize.y / 6.0f * 1);
m_sprite[1].setPosition(wSize.x / 6.0f * 3, wSize.y / 6.0f * 1);
m_sprite[2].setPosition(wSize.x / 6.0f * 5, wSize.y / 6.0f * 1);
m_sprite[3].setPosition(wSize.x / 6.0f * 1, wSize.y / 6.0f * 3);
m_sprite[4].setPosition(wSize.x / 6.0f * 3, wSize.y / 6.0f * 3);
m_sprite[5].setPosition(wSize.x / 6.0f * 5, wSize.y / 6.0f * 3);
m_sprite[6].setPosition(wSize.x / 6.0f * 1, wSize.y / 6.0f * 5);
m_sprite[7].setPosition(wSize.x / 6.0f * 3, wSize.y / 6.0f * 5);
m_sprite[8].setPosition(wSize.x / 6.0f * 5, wSize.y / 6.0f * 5);
}
void
Canvas::render()
{
m_window->clear(sf::Color::Black);
for (auto bar : m_bar)
{
m_window->draw(bar);
}
for (auto & sprite : m_sprite)
{
m_window->draw(sprite);
}
m_window->display();
}
void
Canvas::update(const Board & board)
{
for (int i = 0; i < 9; ++i)
{
Mark mark = board.getMark(i);
switch (mark)
{
case Mark::cross:
m_sprite[i].setTextureRect(sf::Rect<int>(0,0,32,32));
break;
case Mark::ring:
m_sprite[i].setTextureRect(sf::Rect<int>(32,0,32,32));
break;
default:
m_sprite[i].setTextureRect(sf::Rect<int>(64,0,32,32));
}
}
}
/*--------- class Game -------*/
Game::Game(sf::RenderWindow * window)
: m_window(window)
, m_canvas(window)
, m_currPlayer(Mark::cross)
, m_state(State::inProgress)
, m_currButtonNo(-1)
, m_done(false)
, m_aiPlayer(Mark::ring)
, m_ai(new MinimaxAi(m_aiPlayer))
{
resize();
}
Game::Game()
: Game(new sf::RenderWindow(sf::VideoMode(300,300),"TicTacToe"))
{}
Game::~Game()
{
delete m_window;
if (m_ai != nullptr) { delete m_ai; }
}
void
Game::handleInput()
{
// checks if AI is at draw and set AI's suggestion
if (m_state == State::inProgress
&& m_currPlayer == m_aiPlayer
&& m_ai != nullptr
)
{
m_currButtonNo = m_ai->getSuggestedField(m_board, m_currPlayer);
return;
}
sf::Event event;
m_window->waitEvent(event);
{
if (event.type == sf::Event::Closed)
{
m_done = true;
}
else if (event.type == sf::Event::Resized)
{
resize();
// m_canvas.resize();
}
else if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Right)
{
reset();
std::cerr << "hello"; // debug
}
else if (m_state == State::inProgress
&& event.mouseButton.button == sf::Mouse::Left
) {
m_currButtonNo = getButtonNo(event.mouseButton.x, event.mouseButton.y);
}
}
}
}
void
Game::resize()
{
sf::Vector2<unsigned int> wSize = m_window->getSize();
int bWidth = wSize.x/3;
int bHeight = wSize.y/3;
m_button[0] = sf::Rect<int>( 0, 0, bWidth, bHeight);
m_button[1] = sf::Rect<int>( bWidth, 0, bWidth, bHeight);
m_button[2] = sf::Rect<int>(2*bWidth, 0, bWidth, bHeight);
m_button[3] = sf::Rect<int>( 0, bHeight, bWidth, bHeight);
m_button[4] = sf::Rect<int>( bWidth, bHeight, bWidth, bHeight);
m_button[5] = sf::Rect<int>(2*bWidth, bHeight, bWidth, bHeight);
m_button[6] = sf::Rect<int>( 0, 2*bHeight, bWidth, bHeight);
m_button[7] = sf::Rect<int>( bWidth, 2*bHeight, bWidth, bHeight);
m_button[8] = sf::Rect<int>(2*bWidth, 2*bHeight, bWidth, bHeight);
}
int
Game::getButtonNo(const int x, const int y) const
{
for(std::size_t i = 0; i < m_button.size(); ++i)
{
if (m_button[i].contains(x,y))
{
return i;
}
}
return -1; // if something goes wrong
}
Mark
Game::getCurrPlayer() const
{
return m_currPlayer;
}
void
Game::toggleCurrPlayer()
{
m_currPlayer = (m_currPlayer == Mark::ring? Mark::cross : Mark::ring);
}
void
Game::update()
{
if (m_done)
{
m_window->close();
delete m_window;
return;
}
if (m_currButtonNo == -1)
{
return;
}
if (m_state != State::inProgress)
{
return;
}
if (m_board.getMark(m_currButtonNo) != Mark::empty)
{
std::cerr << "Game::update: board(m_currButtonNo is not empty!\n";
return;
}
if (m_currPlayer == Mark::cross)
{
m_board.setMark(Mark::cross, m_currButtonNo);
}
else if (m_currPlayer == Mark::ring)
{
m_board.setMark(Mark::ring, m_currButtonNo);
}
toggleCurrPlayer();
m_currButtonNo = -1;
m_canvas.update(m_board);
std::cerr << m_board << '\n'; // debug
m_state = m_board.evaluate();
}
bool
Game::isDone() const
{
return m_done;
}
void
Game::reset()
{
m_board.reset();
m_canvas.update(m_board);
render();
}
void
Game::render()
{
if (m_done) { return; }
m_canvas.render();
}
void
Game::intro()
{
// not yet implemented
}
void
Game::setRandomAI()
{
if (m_ai != nullptr) delete m_ai;
m_ai = new RandomAi;
}
void
Game::setMinimaxAI()
{
if (m_ai != nullptr) delete m_ai;
m_ai = new MinimaxAi;
}
void
Game::setNoAI()
{
if (m_ai != nullptr) delete m_ai;
m_ai = nullptr;
m_aiPlayer = Mark::empty;
}
void
Game::setAIPlayer(const Mark aiPlayer)
{
m_aiPlayer = aiPlayer;
}
| 22.535948 | 87 | 0.529727 | [
"render"
] |
bb58ec69c901015d78101c4ecddb3f6773339857 | 970 | cpp | C++ | logfiletest/parser/UserCommandFactory.cpp | maxperiod/aiongrindmeter2 | 91a54d7cb01957cd9e1439b89bbd03ddb63a76a7 | [
"MIT"
] | 2 | 2016-08-19T19:28:04.000Z | 2021-04-18T04:48:44.000Z | logfiletest/parser/UserCommandFactory.cpp | maxperiod/aiongrindmeter2 | 91a54d7cb01957cd9e1439b89bbd03ddb63a76a7 | [
"MIT"
] | null | null | null | logfiletest/parser/UserCommandFactory.cpp | maxperiod/aiongrindmeter2 | 91a54d7cb01957cd9e1439b89bbd03ddb63a76a7 | [
"MIT"
] | null | null | null | #include <map>
using namespace std;
#include "UserCommandFactory.h"
vector<string> UserCommandFactory::getUserCommand(const string& chatLine){
vector<string> arguments;
map<string, string> params;
if (parser->resembles(chatLine, "%0: .%1", params)){
string& name = params["%0"];
string& message = params["%1"];
const char* rawName = name.c_str();
const char* rawParams = message.c_str();
int stage = 0;
if (name[0] != '['){
for (int i = 1; i < message.length(); i ++){
if (rawParams[i] == ' '){
if (stage == 0) {
string command(rawParams, i);
arguments.push_back(command);
stage = i + 1;
//if (rawParams[i] == NULL) return arguments;
}
else if (rawParams[i-1] == ' '){
stage = i + 1;
//if (rawParams[i] == NULL) return arguments;
}
}
}
string argument(rawParams + stage, message.length() - stage);
arguments.push_back(argument);
}
}
return arguments;
} | 24.25 | 74 | 0.587629 | [
"vector"
] |
bb59b6df54989bd05e5ad708c848fbd199b9d989 | 584 | cpp | C++ | Valkyrie/source/scene/object.cpp | bachelor-whc/Valkyrie | 9254d100191f8c892a5cbc1ee68dc81470761c33 | [
"MIT"
] | 6 | 2016-12-28T05:23:25.000Z | 2018-10-23T14:04:38.000Z | Valkyrie/source/scene/object.cpp | bachelor-whc/Valkyrie | 9254d100191f8c892a5cbc1ee68dc81470761c33 | [
"MIT"
] | 14 | 2016-12-17T08:23:02.000Z | 2017-01-12T13:29:32.000Z | Valkyrie/source/scene/object.cpp | bachelorwhc/Valkyrie | 9254d100191f8c892a5cbc1ee68dc81470761c33 | [
"MIT"
] | null | null | null | #include "valkyrie/scene/object.h"
#include "valkyrie/component/component.h"
using namespace Valkyrie::Scene;
Object::Object() :
transform() {
}
Object::~Object() {
}
void Object::start() {
}
void Object::update() {
transform.update();
for (auto& component_ptr : m_component_ptrs) {
if(component_ptr->isEnabled())
component_ptr->update();
}
}
ValkyrieComponent::ComponentPtr Object::getComponentPtr(const std::string& component_name) {
if (m_component_index.count(component_name) > 0)
return m_component_ptrs[m_component_index[component_name]];
return nullptr;
}
| 18.83871 | 92 | 0.734589 | [
"object",
"transform"
] |
bb643031fa5e01d15d7e3347e651292edbe5af6d | 6,038 | cpp | C++ | ovc5/software/camera_device_driver/src/sensor_manager.cpp | mfkiwl/ovc-cyusb3014fpga | 565db766a05cb0207282e4c351ceea84016293e5 | [
"Apache-2.0"
] | 174 | 2018-03-27T23:30:27.000Z | 2022-03-28T13:48:22.000Z | ovc5/software/camera_device_driver/src/sensor_manager.cpp | mfkiwl/ovc-cyusb3014fpga | 565db766a05cb0207282e4c351ceea84016293e5 | [
"Apache-2.0"
] | 41 | 2018-03-30T16:25:39.000Z | 2022-03-28T09:00:36.000Z | ovc5/software/camera_device_driver/src/sensor_manager.cpp | mfkiwl/ovc-cyusb3014fpga | 565db766a05cb0207282e4c351ceea84016293e5 | [
"Apache-2.0"
] | 50 | 2018-04-01T01:44:03.000Z | 2022-03-11T05:58:30.000Z | #include "ovc5_driver/sensor_manager.hpp"
#include <unistd.h>
#include <iostream>
#include "ovc5_driver/camera_modules.hpp"
#include "ovc5_driver/i2c_driver.h"
SensorManager::SensorManager(const std::vector<camera_config_t> &cams,
int line_counter_dev, int trigger_timer_dev,
int primary_cam,
std::vector<std::string> server_ips)
: line_counter(line_counter_dev),
trigger_timer(trigger_timer_dev),
primary_cam_(primary_cam)
{
// Configure the ethernet client.
client = std::make_unique<EthernetClient>(server_ips);
// Configure the gpio chip.
gpio = std::make_unique<GPIOChip>(GPIO_CHIP_NUMBER);
int gpio_pin_num;
// Turn on the cameras with the enable pins.
for (camera_config_t cam : cams)
{
// This assumes that the enable pins are at EMIO addresses starting at zero
// and the index matches the numbering of the vdma devices.
gpio_pin_num = GPIO_EMIO_OFFSET + cam.id;
gpio->openPin(gpio_pin_num, GPIO_OUTPUT);
gpio->setValue(gpio_pin_num, true);
}
// Enables passing last line trigger from the selected mipi_csi2_rx_subsystem
// to the line counter.
gpio_pin_num = GPIO_SELECT_OFFSET + primary_cam;
gpio->openPin(gpio_pin_num, GPIO_OUTPUT);
gpio->setValue(gpio_pin_num, true);
// Turn on user LED to signify that the sensors are on.
gpio->openPin(GPIO_LED_PIN, GPIO_OUTPUT);
gpio->setValue(GPIO_LED_PIN, true);
// Open pin for triggering samples.
gpio->openPin(GPIO_TRIG_PIN, GPIO_OUTPUT);
gpio->setValue(GPIO_LED_PIN, false);
// Set up trigger timer at the configured frequency.
trigger_timer.PWM(DEFAULT_FRAME_RATE, 0.001);
// Sleep for a bit to allow cameras to boot up.
usleep(100000);
for (const camera_config_t &cam : cams)
{
int cam_id = cam.id;
int vdma_dev = cam.vdma_dev;
bool is_primary = primary_cam == cam_id;
I2CDriver i2c(cam.i2c_dev);
for (auto cam_module : CAMERA_MODULES)
{
if (cam_module.probe(i2c))
{
cameras.insert(
{cam_id,
cam_module.constructor(i2c, vdma_dev, cam_id, is_primary)});
break;
}
}
}
initCameras();
usleep(10000);
streamCameras();
}
void SensorManager::initCameras()
{
for (auto &[cam_id, camera] : cameras)
{
// Will initialize to default resolution and frame rate
if (!camera->initialise())
{
std::cout << "Camera initialization failed" << std::endl;
continue;
}
bool is_primary = cam_id == primary_cam_;
if (is_primary)
camera->setMain();
else
camera->setSecondary();
}
}
void SensorManager::streamCameras()
{
for (auto &[cam_id, camera] : cameras)
{
std::cout << "Enabling streaming" << std::endl;
camera->enableStreaming();
}
// Trigger a sampling event to read in the first frame.
gpio->setValue(GPIO_TRIG_PIN, true);
usleep(100);
gpio->setValue(GPIO_TRIG_PIN, false);
}
// The stereo only waits for a single interrupt from the first camera
std::map<int, unsigned char *> SensorManager::getFrames()
{
std::map<int, unsigned char *> frame_map;
// Trigger next frame immediately (circular buffer makes this okay).
// The first frame will be available by the trigger in streamCameras.
gpio->setValue(GPIO_TRIG_PIN, true);
usleep(100);
gpio->setValue(GPIO_TRIG_PIN, false);
// Start timer and wait for interrupt
line_counter.interruptAtLine(LINE_BUFFER_SIZE);
if (!line_counter.waitInterrupt())
{
return frame_map;
}
auto cam_it = cameras.begin();
while (cam_it != cameras.end())
{
frame_map.insert({cam_it->first, cam_it->second->getFrameNoInterrupt()});
++cam_it;
}
return frame_map;
}
void SensorManager::sendFrames()
{
auto frames = getFrames();
for (const auto &[cam_id, frame_ptr] : frames)
{
cameras[cam_id]->flushCache();
client->send_image(
(uint8_t)cam_id, frame_ptr, cameras[cam_id]->getCameraParams());
}
}
/* JSON Format
*
* {
* "frame_rate": float Optional: Global capture trigger in Hz.
* "cameras": [ List of camera-secific configurations.
* {
* "id": int Required: The hardware ID of the camera to adjust.
* "exposure": float Optional: Exposure time in milliseconds. Cannot go
* higher than 1/frame_rate.
* }
* ]
* }
*
* The json message is parsed in an optional fashion to let the user configure
* whatever they want to without changing other settings.
*/
void SensorManager::recvCommand()
{
auto node = client->recv_json();
if (nullptr == node)
{
return;
}
auto frame_rate = node->get("frame_rate", Json::Value::null);
if (Json::Value::null != frame_rate)
{
trigger_timer.PWM(frame_rate.asFloat(), 0.001);
}
auto camera_node = node->get("cameras", Json::Value::null);
if (Json::Value::null != camera_node)
{
for (auto cam : camera_node)
{
auto id_node = cam["id"];
if (Json::Value::null == id_node)
{
std::cout << "Received command for camera without an id. Unable to "
"apply settings."
<< std::endl;
continue;
}
int id = id_node.asInt();
if (0 == cameras.count(id))
{
std::cout << "Received command for camera " << id
<< " which is not initialized." << std::endl;
continue;
}
auto exposure_node = cam["exposure"];
if (Json::Value::null != exposure_node &&
cameras[id]->getCameraParams().dynamic_configs.exposure)
{
cameras[id]->updateExposure(exposure_node.asFloat());
std::cout << "Updated cam " << id << "'s exposure to "
<< exposure_node.asFloat() << std::endl;
}
}
}
}
int SensorManager::getNumCameras() const { return cameras.size(); }
SensorManager::~SensorManager()
{
std::cout << "Resetting sensors" << std::endl;
for (const auto &camera : cameras) camera.second->reset();
}
| 27.953704 | 79 | 0.640609 | [
"vector"
] |
bb667b6f97b9df8df1a68b57fc257eb3628c07bd | 19,669 | cc | C++ | db/http_parser_test.cc | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | db/http_parser_test.cc | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | db/http_parser_test.cc | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | #include <snappy.h>
#include <iostream>
#include "db/HttpParser.hpp"
#include "db/DB.pb.h"
#include "util/testutil.h"
namespace tsdb {
namespace db {
class ParserTest : public testing::Test {};
TEST_F(ParserTest, TestInsertParser1) {
std::string data(
"\
{\
\"samples\": [\
{\
\"type\": 1,\
\"lset\": {\"label1\":\"l1\", \"label2\":\"l2\"},\
\"lsets\": [\
{\"TS\":\"t1\"},\
{\"TS\":\"t2\"}\
],\
\"t\": 1625387863000,\
\"v\": [0.1, 0.2]\
},\
{\
\"type\": 1,\
\"id\": 100,\
\"slots\": [0, 1],\
\"t\": 1625387863000,\
\"v\": [0.1, 0.2]\
},\
{\
\"type\": 0,\
\"lset\": {\"label1\":\"l1\", \"label2\":\"l2\"},\
\"t\": 1625387863000,\
\"v\": [0.3]\
}\
]\
}\
");
// std::string
// data("{\"type\":1,\"id\":100,\"lset\":{\"label1\":\"l1\",\"label2\":\"l2\"},\"lsets\":[{\"TS\":\"t1\"},{\"TS\":\"t2\"}],\"t\":1625387863000,\"v\":[0.1,0.2]}");
InsertParser parser(data);
ASSERT_TRUE(parser.next());
ASSERT_EQ((InsertType)(kGroup), parser.type());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.lset()));
ASSERT_EQ(2, parser.lsets().size());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"TS", "t1"}}), parser.lsets()[0]));
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"TS", "t2"}}), parser.lsets()[1]));
ASSERT_EQ((int64_t)(1625387863000), parser.t());
ASSERT_EQ(std::vector<double>({0.1, 0.2}), parser.v());
ASSERT_TRUE(parser.next());
ASSERT_EQ((InsertType)(kGroup), parser.type());
ASSERT_EQ((uint64_t)(100), parser.id());
ASSERT_EQ(std::vector<int>({0, 1}), parser.slots());
ASSERT_EQ((int64_t)(1625387863000), parser.t());
ASSERT_EQ(std::vector<double>({0.1, 0.2}), parser.v());
ASSERT_TRUE(parser.next());
ASSERT_EQ((InsertType)(kTS), parser.type());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.lset()));
ASSERT_EQ((int64_t)(1625387863000), parser.t());
ASSERT_EQ(std::vector<double>({0.3}), parser.v());
ASSERT_FALSE(parser.next());
}
TEST_F(ParserTest, TestInsertParser2) {
// std::string data("\
// {\
// \"samples\": [\
// {\
// \"type\": 1,\
// \"lset\": {\"label1\":\"l1\", \"label2\":\"l2\"},\
// \"lsets\": [\
// {\"TS\":\"t1\"},\
// {\"TS\":\"t2\"}\
// ],\
// \"t\": 1625387863000,\
// \"v\": [0.1, 0.2]\
// },\
// {\
// \"type\": 1,\
// \"id\": 100,\
// \"t\": 1625387863000,\
// \"v\": [0.1, 0.2]\
// },\
// {\
// \"type\": 0,\
// \"lset\": {\"label1\":\"l1\", \"label2\":\"l2\"},\
// \"t\": 1625387863000,\
// \"v\": [0.3]\
// }\
// ]\
// }\
// ");
InsertEncoder encoder;
encoder.add({{"label1", "l1"}, {"label2", "l2"}},
{{{"TS", "t1"}}, {{"TS", "t2"}}}, 1625387863000, {0.1, 0.2});
encoder.add(100, 1625387863000, {0.1, 0.2});
encoder.add({{"label1", "l1"}, {"label2", "l2"}}, 1625387863000, 0.3);
encoder.close();
std::cout << encoder.str() << std::endl;
InsertParser parser(encoder.str());
ASSERT_TRUE(parser.next());
ASSERT_EQ((InsertType)(kGroup), parser.type());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.lset()));
ASSERT_EQ(2, parser.lsets().size());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"TS", "t1"}}), parser.lsets()[0]));
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"TS", "t2"}}), parser.lsets()[1]));
ASSERT_EQ((int64_t)(1625387863000), parser.t());
ASSERT_EQ(std::vector<double>({0.1, 0.2}), parser.v());
ASSERT_TRUE(parser.next());
ASSERT_EQ((InsertType)(kGroup), parser.type());
ASSERT_EQ((uint64_t)(100), parser.id());
ASSERT_EQ((int64_t)(1625387863000), parser.t());
ASSERT_EQ(std::vector<double>({0.1, 0.2}), parser.v());
ASSERT_TRUE(parser.next());
ASSERT_EQ((InsertType)(kTS), parser.type());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.lset()));
ASSERT_EQ((int64_t)(1625387863000), parser.t());
ASSERT_EQ(std::vector<double>({0.3}), parser.v());
ASSERT_FALSE(parser.next());
}
TEST_F(ParserTest, TestInsertResult1) {
{
InsertResultEncoder encoder;
encoder.add(0, {0, 1, 2, 3});
encoder.add(1, {});
encoder.add(2, {0, 1, 2, 3, 6});
encoder.add(3, {});
encoder.close();
InsertResultParser parser(encoder.str());
ASSERT_TRUE(parser.next());
ASSERT_EQ(0, parser.id());
ASSERT_EQ(std::vector<int>({0, 1, 2, 3}), parser.slots());
ASSERT_TRUE(parser.next());
ASSERT_EQ(1, parser.id());
ASSERT_EQ(std::vector<int>(), parser.slots());
ASSERT_TRUE(parser.next());
ASSERT_EQ(2, parser.id());
ASSERT_EQ(std::vector<int>({0, 1, 2, 3, 6}), parser.slots());
ASSERT_TRUE(parser.next());
ASSERT_EQ(3, parser.id());
ASSERT_EQ(std::vector<int>(), parser.slots());
ASSERT_FALSE(parser.next());
}
}
TEST_F(ParserTest, TestQueryParser1) {
std::string data(
"\
{\
\"matchers\": {\"label1\":\"l1\", \"label2\":\"l2\"},\
\"mint\": 1625387863000,\
\"maxt\": 1625387963000\
}\
");
QueryParser parser(data);
ASSERT_FALSE(parser.error());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.matchers()));
ASSERT_EQ((int64_t)(1625387863000), parser.mint());
ASSERT_EQ((int64_t)(1625387963000), parser.maxt());
}
TEST_F(ParserTest, TestQueryParser2) {
QueryEncoder encoder(1, label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
1625387863000, 1625387963000);
QueryParser parser(encoder.str());
ASSERT_FALSE(parser.error());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.matchers()));
ASSERT_EQ((int64_t)(1625387863000), parser.mint());
ASSERT_EQ((int64_t)(1625387963000), parser.maxt());
}
TEST_F(ParserTest, TestQueryResultEncoder1) {
{
QueryResultEncoder encoder;
encoder.write({{"label1", "l1"}, {"label2", "l2"}}, 0, {1, 2}, {10, 20});
encoder.close();
std::cout << encoder.str() << std::endl;
}
{
QueryResultEncoder encoder;
encoder.write({{"label1", "l1"}, {"label2", "l2"}},
{{{"ts", "1"}}, {{"ts", "2"}}}, 0, {0, 1}, {{1, 2}, {3, 4}},
{{10, 20}, {30, 40}});
encoder.close();
std::cout << encoder.str() << std::endl;
}
{
QueryResultEncoder encoder;
encoder.write({{"label1", "l1"}, {"label2", "l2"}}, 0, {1, 2}, {10, 20});
encoder.write({{"label1", "l1"}, {"label2", "l2"}},
{{{"ts", "1"}}, {{"ts", "2"}}}, 0, {0, 1}, {{1, 2}, {3, 4}},
{{10, 20}, {30, 40}});
encoder.close();
std::cout << encoder.str() << std::endl;
}
}
TEST_F(ParserTest, TestQueryResultParser1) {
{
QueryResultEncoder encoder;
encoder.write({{"label1", "l1"}, {"label2", "l2"}}, 0, {1, 2}, {10, 20});
encoder.write({{"label1", "l1"}, {"label2", "l2"}},
{{{"ts", "1"}}, {{"ts", "2"}}}, 1, {0, 1}, {{1, 2}, {3, 4}},
{{10, 20}, {30, 40}});
encoder.close();
std::cout << encoder.str() << std::endl;
QueryResultParser parser(encoder.str());
ASSERT_TRUE(parser.next());
ASSERT_EQ((uint64_t)(0), parser.id());
ASSERT_EQ(0, label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.lset()));
ASSERT_TRUE(parser.lsets().empty());
ASSERT_EQ(1, parser.timestamps().size());
ASSERT_EQ(1, parser.values().size());
ASSERT_EQ(std::vector<int64_t>({1, 2}), parser.timestamps()[0]);
ASSERT_EQ(std::vector<double>({10.0, 20.0}), parser.values()[0]);
ASSERT_TRUE(parser.next());
ASSERT_EQ((uint64_t)(1), parser.id());
ASSERT_EQ(0, label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}),
parser.lset()));
ASSERT_EQ(2, parser.lsets().size());
ASSERT_EQ(2, parser.timestamps().size());
ASSERT_EQ(2, parser.values().size());
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"ts", "1"}}), parser.lsets()[0]));
ASSERT_EQ(
0, label::lbs_compare(label::Labels({{"ts", "2"}}), parser.lsets()[1]));
ASSERT_EQ(std::vector<int64_t>({1, 2}), parser.timestamps()[0]);
ASSERT_EQ(std::vector<int64_t>({3, 4}), parser.timestamps()[1]);
ASSERT_EQ(std::vector<double>({10.0, 20.0}), parser.values()[0]);
ASSERT_EQ(std::vector<double>({30.0, 40.0}), parser.values()[1]);
ASSERT_FALSE(parser.next());
}
}
TEST_F(ParserTest, TestProtoInsertSamples1) {
InsertSamples samples;
{
InsertSample* tmp_sample = samples.add_samples();
tmp_sample->set_type(InsertSample_InsertType_GROUP);
Tags* tmp_lset = tmp_sample->mutable_lset();
NewTags(label::Labels({{"label1", "l1"}, {"label2", "l2"}}), tmp_lset);
tmp_lset = tmp_sample->add_lsets();
NewTags(label::Labels({{"TS", "t1"}}), tmp_lset);
tmp_lset = tmp_sample->add_lsets();
NewTags(label::Labels({{"TS", "t2"}}), tmp_lset);
tmp_sample->set_t(1625387863000);
tmp_sample->add_v(0.1);
tmp_sample->add_v(0.2);
}
{
InsertSample* tmp_sample = samples.add_samples();
tmp_sample->set_type(InsertSample_InsertType_GROUP);
tmp_sample->set_id(100);
tmp_sample->add_slots(0);
tmp_sample->add_slots(1);
tmp_sample->set_t(1625387863000);
tmp_sample->add_v(0.1);
tmp_sample->add_v(0.2);
}
{
InsertSample* tmp_sample = samples.add_samples();
tmp_sample->set_type(InsertSample_InsertType_TS);
Tags* tmp_lset = tmp_sample->mutable_lset();
NewTags(label::Labels({{"label1", "l1"}, {"label2", "l2"}}), tmp_lset);
tmp_sample->set_t(1625387863000);
tmp_sample->add_v(0.3);
}
std::string data;
samples.SerializeToString(&data);
std::string compressed_data;
snappy::Compress(data.data(), data.size(), &compressed_data);
std::string decompressed_data;
snappy::Uncompress(compressed_data.data(), compressed_data.size(),
&decompressed_data);
InsertSamples parsed_samples;
parsed_samples.ParseFromString(decompressed_data);
ASSERT_EQ(3, parsed_samples.samples_size());
{
InsertSample tmp_sample = parsed_samples.samples(0);
label::Labels lset;
NewTags(&lset, tmp_sample.mutable_lset());
ASSERT_EQ(0,
label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_EQ(2, tmp_sample.lsets_size());
lset.clear();
NewTags(&lset, tmp_sample.mutable_lsets(0));
ASSERT_EQ(0, label::lbs_compare(label::Labels({{"TS", "t1"}}), lset));
lset.clear();
NewTags(&lset, tmp_sample.mutable_lsets(1));
ASSERT_EQ(0, label::lbs_compare(label::Labels({{"TS", "t2"}}), lset));
ASSERT_EQ((int64_t)(1625387863000), tmp_sample.t());
ASSERT_EQ(2, tmp_sample.v_size());
ASSERT_EQ(0.1, tmp_sample.v(0));
ASSERT_EQ(0.2, tmp_sample.v(1));
}
{
InsertSample tmp_sample = parsed_samples.samples(1);
ASSERT_EQ(2, tmp_sample.slots_size());
ASSERT_EQ(0, tmp_sample.slots(0));
ASSERT_EQ(1, tmp_sample.slots(1));
ASSERT_EQ((int64_t)(1625387863000), tmp_sample.t());
ASSERT_EQ(2, tmp_sample.v_size());
ASSERT_EQ(0.1, tmp_sample.v(0));
ASSERT_EQ(0.2, tmp_sample.v(1));
}
{
InsertSample tmp_sample = parsed_samples.samples(2);
label::Labels lset;
NewTags(&lset, tmp_sample.mutable_lset());
ASSERT_EQ(0,
label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_EQ((int64_t)(1625387863000), tmp_sample.t());
ASSERT_EQ(1, tmp_sample.v_size());
ASSERT_EQ(0.3, tmp_sample.v(0));
}
}
TEST_F(ParserTest, TestProtoInsertSamples2) {
InsertSamples samples;
Add(&samples, {{"label1", "l1"}, {"label2", "l2"}},
{{{"TS", "t1"}}, {{"TS", "t2"}}}, 1625387863000, {0.1, 0.2});
Add(&samples, 100, {0, 1}, 1625387863000, {0.1, 0.2});
Add(&samples, {{"label1", "l1"}, {"label2", "l2"}}, 1625387863000, 0.3);
std::string data;
samples.SerializeToString(&data);
std::string compressed_data;
snappy::Compress(data.data(), data.size(), &compressed_data);
std::string decompressed_data;
snappy::Uncompress(compressed_data.data(), compressed_data.size(),
&decompressed_data);
InsertSamples parsed_samples;
parsed_samples.ParseFromString(decompressed_data);
ASSERT_EQ(3, parsed_samples.samples_size());
{
InsertSample tmp_sample = parsed_samples.samples(0);
label::Labels lset;
NewTags(&lset, tmp_sample.mutable_lset());
ASSERT_EQ(0,
label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_EQ(2, tmp_sample.lsets_size());
lset.clear();
NewTags(&lset, tmp_sample.mutable_lsets(0));
ASSERT_EQ(0, label::lbs_compare(label::Labels({{"TS", "t1"}}), lset));
lset.clear();
NewTags(&lset, tmp_sample.mutable_lsets(1));
ASSERT_EQ(0, label::lbs_compare(label::Labels({{"TS", "t2"}}), lset));
ASSERT_EQ((int64_t)(1625387863000), tmp_sample.t());
ASSERT_EQ(2, tmp_sample.v_size());
ASSERT_EQ(0.1, tmp_sample.v(0));
ASSERT_EQ(0.2, tmp_sample.v(1));
}
{
InsertSample tmp_sample = parsed_samples.samples(1);
ASSERT_EQ(2, tmp_sample.slots_size());
ASSERT_EQ(0, tmp_sample.slots(0));
ASSERT_EQ(1, tmp_sample.slots(1));
ASSERT_EQ((int64_t)(1625387863000), tmp_sample.t());
ASSERT_EQ(2, tmp_sample.v_size());
ASSERT_EQ(0.1, tmp_sample.v(0));
ASSERT_EQ(0.2, tmp_sample.v(1));
}
{
InsertSample tmp_sample = parsed_samples.samples(2);
label::Labels lset;
NewTags(&lset, tmp_sample.mutable_lset());
ASSERT_EQ(0,
label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_EQ((int64_t)(1625387863000), tmp_sample.t());
ASSERT_EQ(1, tmp_sample.v_size());
ASSERT_EQ(0.3, tmp_sample.v(0));
}
}
TEST_F(ParserTest, TestProtoQuery1) {
QueryRequest qr;
qr.set_return_metric(true);
Tags* tags = qr.mutable_lset();
NewTags(label::Labels({{"label1", "l1"}, {"label2", "l2"}}), tags);
qr.set_mint(0);
qr.set_maxt(100);
std::string data;
qr.SerializeToString(&data);
std::string compressed_data;
snappy::Compress(data.data(), data.size(), &compressed_data);
std::string decompressed_data;
snappy::Uncompress(compressed_data.data(), compressed_data.size(),
&decompressed_data);
QueryRequest qr2;
qr2.ParseFromString(decompressed_data);
label::Labels lset;
NewTags(&lset, qr2.mutable_lset());
ASSERT_EQ(0, label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_TRUE(qr2.return_metric());
ASSERT_EQ(0, qr2.mint());
ASSERT_EQ(100, qr2.maxt());
}
TEST_F(ParserTest, TestProtoQuery2) {
QueryRequest qr;
Add(&qr, true, {{"label1", "l1"}, {"label2", "l2"}}, 0, 100);
std::string data;
qr.SerializeToString(&data);
std::string compressed_data;
snappy::Compress(data.data(), data.size(), &compressed_data);
std::string decompressed_data;
snappy::Uncompress(compressed_data.data(), compressed_data.size(),
&decompressed_data);
QueryRequest qr2;
qr2.ParseFromString(decompressed_data);
label::Labels lset;
NewTags(&lset, qr2.mutable_lset());
ASSERT_EQ(0, label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_TRUE(qr2.return_metric());
ASSERT_EQ(0, qr2.mint());
ASSERT_EQ(100, qr2.maxt());
}
TEST_F(ParserTest, TestProtoQueryResult1) {
std::string data, compressed_data, decompressed_data;
{
QueryResults results;
Add(&results, {{"label1", "l1"}, {"label2", "l2"}}, 0, {1, 2}, {10, 20});
Add(&results, {{"label1", "l1"}, {"label2", "l2"}},
{{{"ts", "1"}}, {{"ts", "2"}}}, 1, {{1, 2}, {3, 4}},
{{10, 20}, {30, 40}});
data.clear();
compressed_data.clear();
results.SerializeToString(&data);
snappy::Compress(data.data(), data.size(), &compressed_data);
}
{
QueryResults results;
decompressed_data.clear();
snappy::Uncompress(compressed_data.data(), compressed_data.size(),
&decompressed_data);
results.ParseFromString(decompressed_data);
ASSERT_EQ(2, results.results_size());
{
label::Labels lset;
std::vector<int64_t> t;
std::vector<double> v;
uint64_t id;
Parse(&results, 0, &lset, &id, &t, &v);
ASSERT_EQ(0,
label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_EQ(0, id);
ASSERT_EQ(std::vector<int64_t>({1, 2}), t);
ASSERT_EQ(std::vector<double>({10, 20}), v);
}
{
label::Labels lset;
std::vector<label::Labels> lsets;
std::vector<std::vector<int64_t>> t;
std::vector<std::vector<double>> v;
uint64_t id;
Parse(&results, 1, &lset, &lsets, &id, &t, &v);
ASSERT_EQ(0,
label::lbs_compare(
label::Labels({{"label1", "l1"}, {"label2", "l2"}}), lset));
ASSERT_EQ(2, lsets.size());
ASSERT_EQ(0, label::lbs_compare(label::Labels({{"ts", "1"}}), lsets[0]));
ASSERT_EQ(0, label::lbs_compare(label::Labels({{"ts", "2"}}), lsets[1]));
ASSERT_EQ(1, id);
ASSERT_EQ(std::vector<std::vector<int64_t>>({{1, 2}, {3, 4}}), t);
ASSERT_EQ(std::vector<std::vector<double>>({{10, 20}, {30, 40}}), v);
}
}
{
QueryResults results;
Add(&results, {}, 0, {1, 2}, {10, 20});
Add(&results, {}, {}, 1, {{1, 2}, {3, 4}}, {{10, 20}, {30, 40}});
data.clear();
compressed_data.clear();
results.SerializeToString(&data);
snappy::Compress(data.data(), data.size(), &compressed_data);
}
{
QueryResults results;
decompressed_data.clear();
snappy::Uncompress(compressed_data.data(), compressed_data.size(),
&decompressed_data);
results.ParseFromString(decompressed_data);
ASSERT_EQ(2, results.results_size());
{
label::Labels lset;
std::vector<int64_t> t;
std::vector<double> v;
uint64_t id;
Parse(&results, 0, &lset, &id, &t, &v);
ASSERT_TRUE(lset.empty());
ASSERT_EQ(0, id);
ASSERT_EQ(std::vector<int64_t>({1, 2}), t);
ASSERT_EQ(std::vector<double>({10, 20}), v);
}
{
label::Labels lset;
std::vector<label::Labels> lsets;
std::vector<std::vector<int64_t>> t;
std::vector<std::vector<double>> v;
uint64_t id;
Parse(&results, 1, &lset, &lsets, &id, &t, &v);
ASSERT_TRUE(lset.empty());
ASSERT_TRUE(lsets.empty());
ASSERT_EQ(1, id);
ASSERT_EQ(std::vector<std::vector<int64_t>>({{1, 2}, {3, 4}}), t);
ASSERT_EQ(std::vector<std::vector<double>>({{10, 20}, {30, 40}}), v);
}
}
}
} // namespace db
} // namespace tsdb
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 33.112795 | 164 | 0.566424 | [
"vector"
] |
bb76abedc173c73a608a7a544512fe1633ac91c8 | 11,774 | cpp | C++ | src/game.cpp | merlinblack/oyunum | d37d753108ef0460f7fd50f5a135ae2c95dc046d | [
"MIT"
] | 1 | 2019-01-18T04:51:39.000Z | 2019-01-18T04:51:39.000Z | src/game.cpp | merlinblack/oyunum | d37d753108ef0460f7fd50f5a135ae2c95dc046d | [
"MIT"
] | null | null | null | src/game.cpp | merlinblack/oyunum | d37d753108ef0460f7fd50f5a135ae2c95dc046d | [
"MIT"
] | null | null | null | #include "game.h"
#include "git_versioning.h"
#include <iostream>
using std::cout;
using std::endl;
// in binding.cpp
void register_all_classes( lua_State* L );
// in colortext.cpp
void test_colored_text( ALLEGRO_FONT* font );
void Game::initialiseAllegro()
{
al_init();
al_install_mouse();
al_install_keyboard();
al_init_image_addon();
al_init_font_addon();
al_init_ttf_addon();
}
bool Game::createDisplay()
{
//al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_REQUIRE);
al_set_new_display_flags( ALLEGRO_RESIZABLE );
display = al_create_display( SCREEN_W, SCREEN_H );
if( display == nullptr )
return false;
al_set_window_title( display, "My Game" );
resize();
return true;
}
void Game::resize()
{
width = al_get_display_width( display );
height = al_get_display_height( display );
scaleX = width / (float)SCREEN_W;
scaleY = height / (float)SCREEN_H;
cout << "X scale: " << scaleX << endl;
cout << "Y scale: " << scaleY << endl;
cout << endl;
ALLEGRO_TRANSFORM trans;
al_identity_transform(&trans);
al_scale_transform(&trans, scaleX, scaleY);
al_use_transform(&trans);
}
void Game::registerEventSources()
{
al_wait_for_vsync();
frameTimer = al_create_timer( 1.0 / 30.0 ); // 30 FPS
scriptTimer = al_create_timer( 1.0 / 90.0 ); // Update script called 90x per second (kept to a multiple of FPS)
eventQueue = al_create_event_queue();
al_register_event_source( eventQueue, al_get_keyboard_event_source() );
al_register_event_source( eventQueue, al_get_mouse_event_source() );
al_register_event_source( eventQueue, al_get_display_event_source(display) );
al_register_event_source( eventQueue, al_get_timer_event_source(frameTimer) );
al_register_event_source( eventQueue, al_get_timer_event_source(scriptTimer) );
al_start_timer( frameTimer );
al_start_timer( scriptTimer );
}
void Game::initialiseLua()
{
L = luaL_newstate();
luaL_openlibs( L );
register_all_classes( L );
lua_pushlightuserdata( L, this );
lua_setfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX );
lua_register( L, "quit", Game::quit );
lua_register( L, "setTimerDivider", Game::setTimerDivider );
FontBinding::push( L, font );
lua_setglobal( L, "fixed_font" );
RenderListBinding::push( L, renderlist );
lua_setglobal( L, "renderlist" );
LuaRef info = LuaRef::newTable( L );
info["width"] = SCREEN_W;
info["height"] = SCREEN_H;
info["gitver"] = GIT_REPO_VERSION_STR;
info["luaver"] = LUA_VERSION;
info.push();
lua_setglobal( L, "info" );
}
bool Game::boot()
{
renderlist = std::make_shared<RenderList>();
initialiseAllegro();
if( ! createDisplay() )
return false;
registerEventSources();
font = std::make_shared<Font>( "data/fixed_font.tga", 0, 0 );
icon = al_load_bitmap( "data/icon.tga" );
if( !font || !icon )
return false;
al_set_display_icon( display, icon );
initialiseLua();
FontPtr console_font = std::make_shared<Font>( "data/liberation_mono/LiberationMono-Bold.ttf", -16, ALLEGRO_TTF_NO_KERNING );
console = std::make_shared<Console>( L, console_font, SCREEN_W );
console->setOrder(255);
console->print( std::string( "Está es una prueba\n^red^Bu bir test\nOne\t1\nTwo\t2\nÜç\t3\nDört\t4" ) );
console->print( std::string( "^yellow^" GIT_REPO_VERSION_STR ));
return true;
}
void Game::setScene()
{
using std::make_shared;
RenderListPtr rl = make_shared<RenderList>();
rl->add( make_shared<Rectangle>( SCREEN_W-480, SCREEN_H-35, SCREEN_W-330, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200)));
rl->add( make_shared<Rectangle>( SCREEN_W-320, SCREEN_H-35, SCREEN_W-170, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200)));
rl->add( make_shared<Rectangle>( SCREEN_W-160, SCREEN_H-35, SCREEN_W-10, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200)));
fpsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-85, SCREEN_H-30 );
rl->add( fpsText );
spsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-245, SCREEN_H-30 );
rl->add( spsText );
memText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-405, SCREEN_H-30 );
rl->add( memText );
rl->setOrder( 254 );
renderlist->insert( std::move(rl) );
}
void Game::run()
{
if( luaL_dofile( L, "scripts/main.lua" ) )
{
std::cerr << lua_tostring( L, -1 ) << std::endl;
return;
}
LuaRef luaUpdate( L, "update" );
LuaRef luaKeyEvent( L, "keyEvent" );
LuaRef luaMouseEvent( L, "mouseEvent" );
// Check scripts are sane.
if( ! luaUpdate.isFunction() )
{
std::cerr << "Lua update function is not defined." << std::endl;
shouldStop = true;
}
if( ! luaKeyEvent.isFunction() )
{
std::cerr << "Lua keyEvent function is not defined." << std::endl;
shouldStop = true;
}
if( ! luaMouseEvent.isFunction() )
{
std::cerr << "Lua mouseEvent function is not defined." << std::endl;
shouldStop = true;
}
int fps_accum = 0;
int fps_worst = 1000;
int fps_best = 0;
int sps_accum = 0;
int sps_worst = 1000;
int sps_best = 0;
double update_time = al_get_time();
double t;
bool redraw = false;
bool scriptrun = false;
while( ! shouldStop )
{
ALLEGRO_EVENT event;
al_wait_for_event( eventQueue, &event );
t = al_get_time();
if( t - update_time >= 1 ) // Every second ...
{
update_time = t;
if( fps_best < fps_accum ) { fps_best = fps_accum; }
if( fps_worst > fps_accum ) { fps_worst = fps_accum; }
fpsText->clearText();
fpsText << "FPS: " << fps_accum << "/" << fps_best << "/" << fps_worst;
fps_accum = 0;
if( sps_best < sps_accum ) { sps_best = sps_accum; }
if( sps_worst > sps_accum ) { sps_worst = sps_accum; }
spsText->clearText();
spsText << "SPS: " << sps_accum << "/" << sps_best << "/" << sps_worst;
sps_accum = 0;
memText->clearText();
memText << "Lua Mem " << lua_gc( L, LUA_GCCOUNT, 0 ) << "kb";
}
if( event.type == ALLEGRO_EVENT_DISPLAY_CLOSE )
break;
try {
if( event.type == ALLEGRO_EVENT_KEY_CHAR )
{
if( event.keyboard.keycode == ALLEGRO_KEY_ESCAPE )
{
if( console->isVisible() )
{
console->toggleVisibility();
continue;
}
else
{
// We grab it here, as 'quit' may change depending
// on what is happening.
LuaRef quit( L, "quit" );
if( quit.isFunction() ) {
quit();
}
continue;
}
}
if( console->isVisible() )
{
if( console->injectKeyPress( event ) )
{
redraw = true;
continue;
}
}
else
{
if( event.keyboard.keycode == ALLEGRO_KEY_TILDE
|| event.keyboard.keycode == ALLEGRO_KEY_BACKQUOTE ) // Mac OS X
{
console->toggleVisibility();
continue;
}
}
luaKeyEvent( al_get_time(), event.keyboard.keycode, event.keyboard.unichar );
}
if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == frameTimer )
{
redraw = true;
}
if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == scriptTimer )
{
scriptrun = true;
}
if( scriptrun && al_is_event_queue_empty( eventQueue ) )
{
sps_accum++;
luaUpdate( t );
console->resume();
scriptrun = false;
}
if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN ) {
luaMouseEvent( al_get_time(), "down", event.mouse.button );
}
if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP ) {
luaMouseEvent( al_get_time(), "up", event.mouse.button );
}
if( event.type == ALLEGRO_EVENT_MOUSE_AXES || event.type == ALLEGRO_EVENT_MOUSE_WARPED ) {
luaMouseEvent( al_get_time(), "move", event.mouse.button,
event.mouse.x / scaleX,
event.mouse.y / scaleY,
event.mouse.z,
event.mouse.dx / scaleX,
event.mouse.dy / scaleY,
event.mouse.dz
);
}
if( event.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY ) {
luaMouseEvent( al_get_time(), "enter", event.mouse.button,
event.mouse.x / scaleX,
event.mouse.y / scaleY,
event.mouse.z
);
}
if( event.type == ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY ) {
luaMouseEvent( al_get_time(), "leave", event.mouse.button,
event.mouse.x / scaleX,
event.mouse.y / scaleY,
event.mouse.z
);
}
}
catch( LuaException &e )
{
std::cerr << e.what() << std::endl;
}
if( event.type == ALLEGRO_EVENT_DISPLAY_RESIZE )
{
al_acknowledge_resize( display );
resize();
redraw = true;
}
if( redraw && al_is_event_queue_empty( eventQueue ) )
{
fps_accum++;
redraw = false;
al_clear_to_color( al_map_rgb( 43, 73, 46 ) );
renderlist->render();
console->render();
al_wait_for_vsync();
al_flip_display();
}
}
}
void Game::deregisterEventSources()
{
if( eventQueue )
{
al_destroy_event_queue( eventQueue );
eventQueue = nullptr;
}
}
void Game::destroyDisplay()
{
if( display )
{
al_destroy_display( display );
display = nullptr;
}
}
Game::~Game()
{
console.reset();
if( L ) {
lua_close( L );
}
deregisterEventSources();
destroyDisplay();
}
int Game::quit( lua_State *L )
{
lua_getfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX );
Game* self = static_cast<Game*>(lua_touserdata( L, -1 ));
self->shouldStop = true;
return 0;
}
int Game::setTimerDivider( lua_State *L )
{
static const char* keys[] = { "fps", "sps", nullptr };
lua_getfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX );
Game* self = static_cast<Game*>(lua_touserdata( L, -1 ));
int which = luaL_checkoption( L, 1, nullptr, keys );
float divider = luaL_checknumber( L, 2 );
switch( which )
{
case 0:
al_set_timer_speed( self->frameTimer, 1.0 / divider );
break;
case 1:
al_set_timer_speed( self->scriptTimer, 1.0 / divider );
break;
default:
return luaL_error( L, "First parameter should be either 'fps' or 'sps'." );
break;
}
return 0;
}
| 28.167464 | 129 | 0.542806 | [
"render"
] |
bb7b90108e14941f220d57030898cfc49b81777f | 15,821 | cpp | C++ | src/Program.cpp | LailaElbeheiry/haystack | 62bcd3f3874a2de393124fbc4e0edc09ed6f02e9 | [
"Apache-2.0"
] | null | null | null | src/Program.cpp | LailaElbeheiry/haystack | 62bcd3f3874a2de393124fbc4e0edc09ed6f02e9 | [
"Apache-2.0"
] | null | null | null | src/Program.cpp | LailaElbeheiry/haystack | 62bcd3f3874a2de393124fbc4e0edc09ed6f02e9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019, ETH Zurich
*/
#include <algorithm>
#include "Program.h"
#include "isl-helpers.h"
#include "op.h"
void Program::extractScop(std::string SourceFile, std::string ScopFunction) {
const char *Function = ScopFunction.empty() ? NULL : ScopFunction.c_str();
pet_scop *PetScop = pet_scop_extract_from_C_source(Context_.get(), SourceFile.c_str(), Function);
if (PetScop == nullptr) {
printf("-> exit(-1) cannot extract scope\n");
exit(-1);
}
Printer_ = isl_printer_to_file(Context_.get(), stdout);
// get the schedule and access information
// (the tagged accesses allow us to distinguish multiple accesses of the same array)
Schedule_ = isl::manage(pet_scop_get_schedule(PetScop));
Reads_ = isl::manage(pet_scop_get_tagged_may_reads(PetScop));
Writes_ = isl::manage(pet_scop_get_tagged_may_writes(PetScop));
// check if the schedule is bounded
auto checkIfBounded = [](isl::set Set) {
if (!Set.is_bounded()) {
printf("-> exit(-1) schedule not bounded\n");
exit(-1);
}
return isl::stat::ok();
};
Schedule_.get_domain().foreach_set(checkIfBounded);
// extract the array information
for (int idx = 0; idx < PetScop->n_array; idx++) {
isl::set Extent = isl::manage_copy(PetScop->arrays[idx]->extent);
// ignore scalars
if (Extent.dim(isl::dim::set) == 0)
continue;
// store the array information
std::string Name = Extent.get_tuple_name();
ArrayExtents_[Name] = Extent;
ElementSizes_[Name] = PetScop->arrays[idx]->element_size;
}
// extract the reads and writes
extractReferences();
// compute detailed access information
ScopLoc_ = std::make_pair(pet_loc_get_start(PetScop->loc), pet_loc_get_end(PetScop->loc));
for (int idx = 0; idx < PetScop->n_stmt; idx++) {
// extract the statement info
pet_expr *Expression = pet_tree_expr_get_expr(PetScop->stmts[idx]->body);
isl::space Space = isl::manage(pet_stmt_get_space(PetScop->stmts[idx]));
std::string Statement = Space.get_tuple_name(isl::dim::set);
// extract the access info
auto printExpression = [](__isl_keep pet_expr *Expr, void *User) {
if (pet_expr_access_is_read(Expr) || pet_expr_access_is_write(Expr)) {
isl::id RefId = isl::manage(pet_expr_access_get_ref_id(Expr));
std::string Name = RefId.to_str();
isl::multi_pw_aff Index = isl::manage(pet_expr_access_get_index(Expr));
// filter the array accesses
if (Index.dim(isl::dim::out) > 0 && Index.has_tuple_id(isl::dim::out)) {
std::string Access = Index.get_tuple_name(isl::dim::out);
// process the array dimensions
for (int i = 0; i < Index.dim(isl::dim::out); ++i) {
std::vector<std::string> Expressions;
auto IndexExpr = Index.get_pw_aff(i);
auto extractExpr = [&](isl::set Set, isl::aff Aff) {
Access += "[" + isl::printExpression(Aff) + "]";
return isl::stat::ok();
};
IndexExpr.foreach_piece(extractExpr);
}
// find the access info
auto AccessInfos = (std::vector<access_info> *)User;
auto Iter = AccessInfos->begin();
do {
// find the pet references and update the access description
Iter = std::find_if(Iter, AccessInfos->end(), [&](access_info AccessInfo) {
if (AccessInfo.Access == Name)
return true;
return false;
});
if (Iter != AccessInfos->end() && Iter->Access == Name) {
Iter->Access = Access;
Iter++;
}
} while (Iter != AccessInfos->end());
}
}
return 0;
};
pet_expr_foreach_access_expr(Expression, printExpression, &AccessInfos_[Statement]);
// get the line number
pet_loc *Loc = pet_tree_get_loc(PetScop->stmts[idx]->body);
int Line = pet_loc_get_line(Loc);
int Start = pet_loc_get_start(Loc);
int Stop = pet_loc_get_end(Loc);
pet_loc_free(Loc);
// store the access information
for (auto &Access : AccessInfos_[Statement]) {
Access.Line = Line;
Access.Start = Start;
Access.Stop = Stop;
}
pet_expr_free(Expression);
}
// extend the schedule and the read and write maps with an access dimension
extendSchedule();
Reads_ = extendAccesses(Reads_, false);
Writes_ = extendAccesses(Writes_, true);
// compute the access domain
AccessDomain_ = Reads_.domain().unite(Writes_.domain()).coalesce();
// free the pet scop
pet_scop_free(PetScop);
}
void Program::extendSchedule() {
// extend the schedule with the reference dimension
ScheduleMap_ = Schedule_.get_map().intersect_domain(Schedule_.get_domain());
isl::union_map ScheduleExt = isl::map::empty(ScheduleMap_.get_space());
auto extendSchedule = [&](isl::map Schedule) {
std::string Statement = Schedule.get_tuple_name(isl::dim::in);
if (!(ReadReferences_[Statement].empty() && WriteReferences_[Statement].empty())) {
// extend the schedule
Schedule = Schedule.insert_dims(isl::dim::in, Schedule.dim(isl::dim::in), 1);
Schedule = Schedule.insert_dims(isl::dim::out, Schedule.dim(isl::dim::out), 1);
Schedule = Schedule.set_tuple_name(isl::dim::in, Statement);
// connect the new dimension
isl::local_space LSIn = isl::local_space(Schedule.domain().get_space());
isl::local_space LSOut = isl::local_space(Schedule.range().get_space());
isl::pw_aff VarIn = isl::pw_aff::var_on_domain(LSIn, isl::dim::set, Schedule.dim(isl::dim::in) - 1);
isl::pw_aff VarOut = isl::pw_aff::var_on_domain(LSOut, isl::dim::set, Schedule.dim(isl::dim::out) - 1);
isl::map EqualConstraint = VarIn.eq_map(VarOut);
Schedule = Schedule.intersect(EqualConstraint);
// compute the reference range
isl::pw_aff Min = VarIn * 0;
isl::pw_aff Max = VarIn * 0 + ReadReferences_[Statement].size() + WriteReferences_[Statement].size();
isl::set LowerBound = VarIn.ge_set(Min);
isl::set UpperBound = VarIn.lt_set(Max);
Schedule = Schedule.intersect_domain(LowerBound);
Schedule = Schedule.intersect_domain(UpperBound);
ScheduleExt = ScheduleExt.unite(isl::union_map(Schedule));
}
return isl::stat::ok();
};
ScheduleMap_.foreach_map(extendSchedule);
ScheduleMap_ = ScheduleExt;
}
void Program::extractReferences() {
// extract the read and write references
auto extractReads = [&](isl::map Map) {
if (ElementSizes_.count(Map.get_tuple_name(isl::dim::out)) > 0) {
std::string Statement = Map.domain().unwrap().get_tuple_name(isl::dim::in);
std::string Reference = Map.domain().unwrap().get_tuple_name(isl::dim::out);
ReadReferences_[Statement].push_back(Reference);
}
return isl::stat::ok();
};
Reads_.foreach_map(extractReads);
auto extractWrites = [&](isl::map Map) {
if (ElementSizes_.count(Map.get_tuple_name(isl::dim::out)) > 0) {
std::string Statement = Map.domain().unwrap().get_tuple_name(isl::dim::in);
std::string Reference = Map.domain().unwrap().get_tuple_name(isl::dim::out);
WriteReferences_[Statement].push_back(Reference);
}
return isl::stat::ok();
};
Writes_.foreach_map(extractWrites);
// sort the references
auto compare = [](std::string &S1, std::string &S2) {
if (S1.length() == S2.length())
return S1 < S2;
else
return S1.length() < S2.length();
};
for (auto &ReadReferences : ReadReferences_)
std::sort(ReadReferences.second.begin(), ReadReferences.second.end(), compare);
for (auto &WriteReferences : WriteReferences_)
std::sort(WriteReferences.second.begin(), WriteReferences.second.end(), compare);
// compute the access info
AccessInfos_.clear();
for (auto &ReadReferences : ReadReferences_) {
for (int i = 0; i < ReadReferences.second.size(); ++i) {
AccessInfos_[ReadReferences.first].push_back(
{ReadReferences.first + "(R" + std::to_string(i) + ")", ReadReferences.second[i], Read, 0, 0, 0});
}
}
for (auto &WriteReferences : WriteReferences_) {
for (int i = 0; i < WriteReferences.second.size(); ++i) {
AccessInfos_[WriteReferences.first].push_back(
{WriteReferences.first + "(W" + std::to_string(i) + ")", WriteReferences.second[i], Write, 0, 0, 0});
}
}
}
isl::union_map Program::extendAccesses(isl::union_map Accesses, bool WriteReferences) {
// extend the access map
isl::union_map AccessesExt = isl::map::empty(Accesses.get_space());
auto extendAccesses = [&](isl::map Access) {
std::string Statement = Access.domain().unwrap().get_tuple_name(isl::dim::in);
std::string Reference = Access.domain().unwrap().get_tuple_name(isl::dim::out);
std::string Array = Access.get_tuple_name(isl::dim::out);
if (ElementSizes_.count(Array) > 0) {
// get the reference offset
long Distance = 0;
if (WriteReferences) {
auto Iter = std::find(WriteReferences_[Statement].begin(), WriteReferences_[Statement].end(), Reference);
assert(Iter != WriteReferences_[Statement].end());
Distance = std::distance(WriteReferences_[Statement].begin(), Iter) + ReadReferences_[Statement].size();
} else {
auto Iter = std::find(ReadReferences_[Statement].begin(), ReadReferences_[Statement].end(), Reference);
assert(Iter != ReadReferences_[Statement].end());
Distance = std::distance(ReadReferences_[Statement].begin(), Iter);
}
// extend the map with the offset
Access = Access.insert_dims(isl::dim::in, Access.dim(isl::dim::in), 1);
Access = Access.set_tuple_name(isl::dim::in, Statement);
// set the offset number
isl::local_space LSIn = isl::local_space(Access.domain().get_space());
isl::pw_aff VarIn = isl::pw_aff::var_on_domain(LSIn, isl::dim::set, Access.dim(isl::dim::in) - 1);
isl::pw_aff Offset = VarIn * 0 + Distance;
isl::set EqualConstraint = VarIn.eq_set(Offset);
Access = Access.intersect_domain(EqualConstraint);
AccessesExt = AccessesExt.unite(isl::union_map(Access));
}
return isl::stat::ok();
};
Accesses.foreach_map(extendAccesses);
return AccessesExt;
}
//XXX:Equivalent to linearize
void Program::computeAccessToLine(isl::set Parameters) {
if (AccessToLine_.is_null()) {
// compute the access map
AccessToLine_ = isl::map::empty(Writes_.get_space());
AccessToElement_ = isl::map::empty(Writes_.get_space());
for (auto Array : ArrayExtents_) {
// extract the array information
std::string Name = Array.first;
isl::set Extent = Array.second;
// apply the parameters
if (!Parameters.is_null()) {
Extent = Extent.intersect_params(Parameters);
}
// map the access to the array offsets
isl::map AccessToArray = isl::map::identity(Extent.get_space().map_from_set());
AccessToElement_ = AccessToElement_.unite(isl::union_map(AccessToArray));
// compute elements per cache line
long ElementsPerCacheLine = MachineModel_.CacheLineSize / ElementSizes_[Name];
AccessToArray = introduceCacheLines(Name, AccessToArray, ElementsPerCacheLine);
AccessToLine_ = AccessToLine_.unite(isl::union_map(AccessToArray));
AccessToLine_ = AccessToLine_.coalesce();
}
// compose the memory accesses with access map
isl::union_map Accesses = Reads_.unite(Writes_);
AccessToLine_ = Accesses.apply_range(AccessToLine_);
AccessToLine_ = AccessToLine_.coalesce();
AccessToElement_ = Accesses.apply_range(AccessToElement_);
AccessToElement_ = AccessToElement_.coalesce();
}
}
void Program::computeAccessToLineAndSet(isl::set Parameters) {
if (AccessToLine_.is_null() || AccessToSet_.is_null()) {
// compute the access map
AccessToLine_ = isl::map::empty(Writes_.get_space());
AccessToSet_ = isl::map::empty(Writes_.get_space());
AccessToElement_ = isl::map::empty(Writes_.get_space());
long NumSet = MachineModel_.CacheSizes[0] / (MachineModel_.CacheLineSize * MachineModel_.Assoc);
for (auto Array : ArrayExtents_) {
// extract the array information
std::string Name = Array.first;
isl::set Extent = Array.second;
// apply the parameters
if (!Parameters.is_null()) {
Extent = Extent.intersect_params(Parameters);
}
// map the access to the array offsets
isl::map AccessToArray = isl::map::identity(Extent.get_space().map_from_set());
isl::map AccessToArray2 = isl::map::identity(Extent.get_space().map_from_set());
AccessToElement_ = AccessToElement_.unite(isl::union_map(AccessToArray));
// compute elements per cache line
long ElementsPerCacheLine = MachineModel_.CacheLineSize / ElementSizes_[Name];
AccessToArray = introduceCacheLines(Name, AccessToArray, ElementsPerCacheLine);
AccessToArray2 = introduceCacheSets(Name, AccessToArray, NumSet);
AccessToLine_ = AccessToLine_.unite(isl::union_map(AccessToArray));
AccessToLine_ = AccessToLine_.coalesce();
AccessToSet_ = AccessToSet_.unite(isl::union_map(AccessToArray2));
AccessToSet_ = AccessToSet_.coalesce();
}
// compose the memory accesses with access map
isl::union_map Accesses = Reads_.unite(Writes_);
AccessToLine_ = Accesses.apply_range(AccessToLine_);
AccessToLine_ = AccessToLine_.coalesce();
AccessToElement_ = Accesses.apply_range(AccessToElement_);
AccessToElement_ = AccessToElement_.coalesce();
AccessToSet_ = Accesses.apply_range(AccessToSet_);
AccessToSet_ = AccessToSet_.coalesce();
// isl_printer *p = Printer_;
// printf("AccesstoLine_:\n");
// p = isl_printer_print_union_map(p, AccessToLine_.get());
// printf("\n");
// printf("AccesstoSet_, where numset = %ld:\n", NumSet);
// p = isl_printer_print_union_map(p, AccessToSet_.get());
// printf("\n");
// isl_printer_free(p);
}
}
isl::map Program::introduceCacheLines(std::string Name, isl::map AccessToArray, long ElementsPerCacheLine) const {
// introduce additional dimension that divides the innermost dimension by the cache line size
int Dim = AccessToArray.dim(isl::dim::out) - 1;
AccessToArray = AccessToArray.add_dims(isl::dim::out, 1);
isl::local_space LS = isl::local_space(AccessToArray.range().get_space());
isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, Dim);
isl::pw_aff VarPrime = isl::pw_aff::var_on_domain(LS, isl::dim::set, Dim + 1);
isl::set ConstraintOne = (ElementsPerCacheLine * VarPrime).le_set(Var);
isl::set ConstraintTwo = Var.le_set(ElementsPerCacheLine * VarPrime + (ElementsPerCacheLine - 1));
AccessToArray = AccessToArray.intersect_range(ConstraintOne).intersect_range(ConstraintTwo);
AccessToArray = AccessToArray.project_out(isl::dim::out, Dim, 1);
AccessToArray = AccessToArray.set_tuple_name(isl::dim::out, Name);
// return the resulting array
return AccessToArray;
}
isl::map Program::introduceCacheSets(std::string Name, isl::map AccessToArray, long NumberOfCacheSets) const {
int Dim = AccessToArray.dim(isl::dim::out) - 1;
AccessToArray = AccessToArray.add_dims(isl::dim::out, 1);
isl::local_space LS = isl::local_space(AccessToArray.range().get_space());
isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, Dim);
isl::pw_aff VarPrime = isl::pw_aff::var_on_domain(LS, isl::dim::set, Dim + 1);
isl::pw_aff Modulo = Var.mod(isl::val(Var.get_ctx(), NumberOfCacheSets));
isl::set Constraint = VarPrime.eq_set(Modulo);
AccessToArray = AccessToArray.intersect_range(Constraint);
// AccessToArray = AccessToArray.project_out(isl::dim::out, 0, Dim + 1);
AccessToArray = AccessToArray.set_tuple_name(isl::dim::out, Name);
// return the resulting array
return AccessToArray;
}
| 44.192737 | 114 | 0.676127 | [
"vector"
] |
bb9a625f7d5370cfa4f042b34c629abbdd2deab8 | 5,605 | hpp | C++ | em_unet/src/PyGreentea/evaluation/src_cython/zi/ai/random_forest.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 10 | 2018-09-13T17:37:22.000Z | 2020-05-08T16:20:42.000Z | em_unet/src/PyGreentea/evaluation/src_cython/zi/ai/random_forest.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 1 | 2018-12-02T14:17:39.000Z | 2018-12-02T20:59:26.000Z | em_unet/src/PyGreentea/evaluation/src_cython/zi/ai/random_forest.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 2 | 2019-03-03T12:06:10.000Z | 2020-04-12T13:23:02.000Z | //
// Copyright (C) 2010 Aleksandar Zlateski <zlateski@mit.edu>
// ----------------------------------------------------------
//
// 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/>.
//
#ifndef ZI_AI_RANDOM_FOREST_HPP
#define ZI_AI_RANDOM_FOREST_HPP 1
#include <zi/ai/decision_tree.hpp>
#include <zi/concurrency/mutex.hpp>
#include <zi/concurrency/thread.hpp>
#include <zi/concurrency/task_manager.hpp>
#include <zi/bits/bind.hpp>
#include <zi/utility/address_of.hpp>
#include <cstddef>
#include <cmath>
namespace zi {
namespace ai {
template< class T, class Splitter >
class random_forest
{
private:
std::vector< decision_tree< T, Splitter > > trees_;
zi::mutex lock_;
typedef random_forest< T, Splitter > this_random_forest_type;
public:
explicit random_forest()
: trees_(),
lock_()
{
}
explicit random_forest( uint32_t n,
const std::vector< T >& patterns,
const std::vector< uint32_t >& positives,
const std::vector< uint32_t >& negatives,
const Splitter& splitter = Splitter() )
: trees_(),
lock_()
{
create( n, patterns, positives, negatives, splitter );
}
void create_single_tree( const std::vector< T >* patterns,
const std::vector< uint32_t >* positives,
const std::vector< uint32_t >* negatives,
const Splitter* splitter )
{
uint32_t total = positives->size() + negatives->size();
std::vector< uint32_t > bag_positives;
std::vector< uint32_t > bag_negatives;
for ( uint32_t j = 0; j < total; ++j )
{
if ( std::rand() % 2 )
{
uint32_t rnd = static_cast< uint32_t >( std::rand() % positives->size() );
bag_positives.push_back( positives->operator[]( rnd ) );
}
else
{
uint32_t rnd = static_cast< uint32_t >( std::rand() % negatives->size() );
bag_negatives.push_back( negatives->operator[]( rnd ) );
}
}/*
for ( uint32_t j = 0; j < total; ++j )
{
uint32_t rnd = static_cast< uint32_t >( std::rand() % total );
if ( rnd < positives->size() )
{
//j += 5;
bag_positives.push_back( positives->operator[]( rnd ) );
}
else
{
bag_negatives.push_back( negatives->operator[]( rnd - positives->size() ) );
}
}
/*
std::cout << "Current sizes: " << bag_positives.size()
<< ", " << bag_negatives.size() << "\n" << std::flush;
// balance the data
while ( bag_negatives.size() > bag_positives.size() && bag_negatives.size() > 0 )
{
std::swap( bag_negatives[ std::rand() % bag_negatives.size() ], bag_negatives.back() );
bag_negatives.pop_back();
}
while ( bag_negatives.size() < bag_positives.size() && bag_positives.size() > 0 )
{
std::swap( bag_positives[ std::rand() % bag_positives.size() ], bag_positives.back() );
bag_positives.pop_back();
}
*/
std::cout << "Actual sizes: " << bag_positives.size()
<< ", " << bag_negatives.size() << "\n" << std::flush;
decision_tree< T, Splitter > new_tree( *patterns, bag_positives,
bag_negatives, splitter->next(), 1 );//6.233 );
{
zi::mutex::guard g( lock_ );
trees_.push_back( new_tree );
std::cout << "Generated " << trees_.size() << " th tree\n";
std::cout << " >> depth: " << new_tree.depth() << "\n" << std::flush;
}
}
void create( uint32_t n,
const std::vector< T >& patterns,
const std::vector< uint32_t >& positives,
const std::vector< uint32_t >& negatives,
const Splitter& splitter = Splitter() )
{
zi::task_manager::simple tm( 32 );
for ( uint32_t i = 0; i < n; ++i )
{
tm.push_back( zi::run_fn
( zi::bind
( &this_random_forest_type::create_single_tree, this,
&patterns, &positives, &negatives, &splitter ) ));
}
tm.start();
tm.join();
std::cout << "\n";
}
double eval( const T& pattern ) const
{
if ( trees_.size() )
{
double res = 0;
FOR_EACH( it, trees_ )
{
res += it->eval( pattern );
}
return res / trees_.size();
}
return -1;
}
double operator()( const T& pattern ) const
{
return eval( pattern );
}
};
} // namespace ai
} // namespace zi
#endif
| 30.134409 | 99 | 0.518822 | [
"vector"
] |
bb9ba310a239a639e12bbf27633e30d92eaa5251 | 3,930 | cpp | C++ | rcnn-mxnet/imageutils.cpp | yf225/mlcpp | 12d6f8224d7d6305a191c7afd2d5510e0a15299f | [
"BSD-2-Clause"
] | 268 | 2018-04-11T15:06:57.000Z | 2022-02-15T08:18:03.000Z | rcnn-mxnet/imageutils.cpp | soma2000-lang/mlcpp | afb08c0c81bdd2c68710831e8d4b233005ab3750 | [
"BSD-2-Clause"
] | 14 | 2019-02-10T22:19:17.000Z | 2020-07-23T05:55:50.000Z | rcnn-mxnet/imageutils.cpp | soma2000-lang/mlcpp | afb08c0c81bdd2c68710831e8d4b233005ab3750 | [
"BSD-2-Clause"
] | 67 | 2018-04-19T21:15:14.000Z | 2022-03-24T17:11:00.000Z | #include "imageutils.h"
std::pair<cv::Mat, float> LoadImage(const std::string& file_name,
uint32_t short_side,
uint32_t long_side) {
auto img = cv::imread(file_name);
if (!img.empty()) {
img.convertTo(img, CV_32FC3);
float scale = 0;
// resize
auto im_min_max = std::minmax(img.rows, img.cols);
scale =
static_cast<float>(short_side) / static_cast<float>(im_min_max.first);
// prevent bigger axis from being more than max_size:
if (std::round(scale * im_min_max.second) > long_side) {
scale =
static_cast<float>(long_side) / static_cast<float>(im_min_max.second);
}
cv::resize(img, img, cv::Size(), static_cast<double>(scale),
static_cast<double>(scale), cv::INTER_LINEAR);
return {img, scale};
}
return {cv::Mat(), 0};
}
std::tuple<cv::Mat, float> LoadImageFitSize(const std::string& file_name,
uint32_t height,
uint32_t width) {
auto img = cv::imread(file_name);
if (!img.empty()) {
img.convertTo(img, CV_32FC3);
float scale = 1.f;
// assume that an image width in most cases is bigger than height
float ratio = static_cast<float>(img.cols) / static_cast<float>(img.rows);
auto new_height = static_cast<int>(width / ratio);
if (new_height <= static_cast<int>(height)) {
scale = static_cast<float>(new_height) / static_cast<float>(img.rows);
} else {
ratio = static_cast<float>(img.rows) / static_cast<float>(img.cols);
auto new_width = static_cast<int>(height / ratio);
assert(new_width <= static_cast<int>(width));
scale = static_cast<float>(new_width) / static_cast<float>(img.cols);
}
// resize
cv::resize(img, img, cv::Size(), static_cast<double>(scale),
static_cast<double>(scale),
scale >= 1.f ? cv::INTER_LINEAR : cv::INTER_AREA);
// pad
int bottom = static_cast<int>(height) - img.rows;
int right = static_cast<int>(width) - img.cols;
assert(right >= 0 && bottom >= 0);
cv::copyMakeBorder(img, img, 0, bottom, 0, right, cv::BORDER_CONSTANT,
cv::Scalar(0, 0, 0, 0));
return {img, scale};
}
return {cv::Mat(), 0};
}
std::vector<float> CVToMxnetFormat(const cv::Mat& img) {
assert(img.type() == CV_32FC3);
auto size = img.channels() * img.rows * img.cols;
std::vector<float> array(static_cast<size_t>(size));
size_t k = 0;
// Convert to from BGR
for (int c = 2; c >= 0; --c) {
for (int y = 0; y < img.rows; ++y) {
for (int x = 0; x < img.cols; ++x) {
auto t = (y * img.cols + x) * 3 + c;
array[k] = img.ptr<float>()[t];
++k;
}
}
}
return array;
}
void ShowResult(const std::vector<Detection>& detection,
const std::string& file_name,
const std::string& out_file_name,
const std::vector<std::string>& classes,
float thresh) {
auto img = cv::imread(file_name);
if (!img.empty()) {
img.convertTo(img, CV_32FC3);
for (auto& det : detection) {
if (det.class_id > 0 && det.score > thresh) {
cv::Point tl(static_cast<int>(det.x1), static_cast<int>(det.y1));
cv::Point br(static_cast<int>(det.x2), static_cast<int>(det.y2));
cv::rectangle(img, tl, br, cv::Scalar(1, 0, 0));
cv::putText(img,
classes[static_cast<size_t>(det.class_id)] + " - " +
std::to_string(det.score),
cv::Point(tl.x + 5, tl.y + 5), // Coordinates
cv::FONT_HERSHEY_COMPLEX_SMALL, // Font
1.0, // Scale. 2.0 = 2x bigger
cv::Scalar(100, 100, 255)); // BGR Color
}
}
cv::imwrite(out_file_name, img);
}
}
| 36.728972 | 80 | 0.554453 | [
"vector"
] |
bba4cb827d27f7bd48a05b20975424fba910b10e | 385 | cpp | C++ | Solution/0001.Two_Sum/0001.Two_Sum.cpp | xleslie/LeetCode | 0af08817b3922e1bbc558091963fd4ff65a506ea | [
"MIT"
] | null | null | null | Solution/0001.Two_Sum/0001.Two_Sum.cpp | xleslie/LeetCode | 0af08817b3922e1bbc558091963fd4ff65a506ea | [
"MIT"
] | null | null | null | Solution/0001.Two_Sum/0001.Two_Sum.cpp | xleslie/LeetCode | 0af08817b3922e1bbc558091963fd4ff65a506ea | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> m;
for(int i=0;i<nums.size();++i)
{
int anchor=target-nums[i]; //trick 把要找的目标值记录下来,以免重复计算
if(m.count(anchor)==0)
m[nums[i]]=i;
else
return {m[anchor],i};
}
return {};
}
};
| 22.647059 | 68 | 0.446753 | [
"vector"
] |
bbaa4781e51bdddd7a9244df6838be84f2663641 | 34,925 | cpp | C++ | net/config/common/nclan/lancmn.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/config/common/nclan/lancmn.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/config/common/nclan/lancmn.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1997.
//
// File: L A N C M N . C P P
//
// Contents: Implementation of LAN Connection related functions common
// to the shell and netman.
//
// Notes:
//
// Author: danielwe 7 Oct 1997
//
//----------------------------------------------------------------------------
#include <pch.h>
#pragma hdrstop
#include <winsock2.h>
#include <mswsock.h>
#include <iphlpapi.h>
#include "lancmn.h"
#include "ncnetcfg.h"
#include "ncnetcon.h"
#include "ncreg.h"
#include "ncstring.h"
#include "netconp.h"
#include "ndispnp.h"
#include "naming.h"
extern const DECLSPEC_SELECTANY WCHAR c_szConnName[] = L"Name";
extern const DECLSPEC_SELECTANY WCHAR c_szRegKeyConFmt[] = L"System\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\%s\\Connection";
extern const DECLSPEC_SELECTANY WCHAR c_szRegKeyIrdaFmt[] = L"System\\CurrentControlSet\\Control\\Network\\{6BDD1FC5-810F-11D0-BEC7-08002BE2092F}\\%s\\Connection";
extern const DECLSPEC_SELECTANY WCHAR c_szRegKeyHwConFmt[] = L"System\\CurrentControlSet\\Control\\Network\\Connections\\%s";
extern const DECLSPEC_SELECTANY WCHAR c_szRegValuePnpInstanceId[] = L"PnpInstanceID";
extern const DECLSPEC_SELECTANY WCHAR c_szRegKeyNetworkAdapters[] = L"System\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}";
extern const DECLSPEC_SELECTANY WCHAR c_szRegValueNetCfgInstanceId[] = L"NetCfgInstanceId";
extern const DECLSPEC_SELECTANY WCHAR c_szRegValueMediaSubType[] = L"MediaSubType";
//
// Helper functions
//
//+---------------------------------------------------------------------------
//
// Function: HrOpenConnectionKey
//
// Purpose: Opens the "Connection" subkey under the gievn connection
// GUID.
//
// Arguments:
// pguid [in] GUID of net card in use by the connection
// pszGuid [in] String version of GUID of net card in use by
// the connection
// sam [in] SAM desired
// occFlags [in] Flags determining how to open the key
// pszPnpId [in] The Pnp id of the net card in use by the
// connection. This is used if the key is created.
// phkey [out] Returns hkey of connection subkey
//
// Returns: S_OK if success, OLE or Win32 error otherwise.
//
// Author: danielwe 7 Oct 1997
//
// Notes: Only pguid or pszGuid should be specified, not both. Specifying
// both will result in an E_INVALIDARG error
//
//
HRESULT
HrOpenConnectionKey (
IN const GUID* pguid,
IN PCWSTR pszGuid,
IN REGSAM sam,
IN OCC_FLAGS occFlags,
IN PCWSTR pszPnpId,
OUT HKEY *phkey)
{
HRESULT hr = S_OK;
WCHAR szRegPath[256];
WCHAR szGuid[c_cchGuidWithTerm];
Assert(phkey);
Assert(pguid || (pszGuid && *pszGuid));
Assert(!(pguid && pszGuid));
Assert (FImplies (OCCF_CREATE_IF_NOT_EXIST == occFlags, pszPnpId && *pszPnpId));
*phkey = NULL;
if (pguid)
{
StringFromGUID2(*pguid, szGuid, c_cchGuidWithTerm);
pszGuid = szGuid;
}
wsprintfW(szRegPath, c_szRegKeyConFmt, pszGuid);
if (occFlags & OCCF_CREATE_IF_NOT_EXIST)
{
DWORD dwDisp;
hr = HrRegCreateKeyEx(HKEY_LOCAL_MACHINE, szRegPath, 0,
sam, NULL, phkey, &dwDisp);
if ((S_OK == hr))
{
DWORD dwMediaSubType;
// Store the pnp instance id as our back pointer to the pnp tree.
//
hr = HrRegSetSz (*phkey, c_szRegValuePnpInstanceId, pszPnpId);
TraceError("HrRegSetSz in HrOpenConnectionKey failed.", hr);
HRESULT hrT = HrRegQueryDword(*phkey, c_szRegValueMediaSubType, &dwMediaSubType);
if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hrT)
{
CIntelliName inName(NULL, NULL);
NETCON_MEDIATYPE ncMediaType = NCM_NONE;
NETCON_SUBMEDIATYPE ncMediaSubType = NCSM_NONE;
hrT = inName.HrGetPseudoMediaTypes(*pguid, &ncMediaType, &ncMediaSubType);
if (SUCCEEDED(hrT) && (NCSM_LAN != ncMediaSubType) )
{
hrT = HrRegSetDword(*phkey, c_szRegValueMediaSubType, ncMediaSubType);
}
}
TraceError("Could not set media subtype for adapter", hrT);
}
}
else if (occFlags & OCCF_DELETE_IF_EXIST)
{
if (wcslen(szGuid) > 0)
{
wcscpy(szRegPath, c_szRegKeyNetworkAdapters);
wcscat(szRegPath, L"\\");
wcscat(szRegPath, szGuid);
hr = HrRegDeleteKeyTree(HKEY_LOCAL_MACHINE, szRegPath);
}
}
else
{
hr = HrRegOpenKeyEx(HKEY_LOCAL_MACHINE, szRegPath, sam, phkey);
}
TraceErrorOptional("HrOpenConnectionKey", hr,
HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrOpenHwConnectionKey
//
// Purpose: Opens the per-hardware profile registry key for this connection
//
// Arguments:
// refGuid [in] GUID of net card in use by the connection
// sam [in] SAM desired
// occFlags [in] Flags determining how to open the key
// phkey [out] Returns hkey of connection subkey
//
// Returns: S_OK if success, OLE or Win32 error otherwise.
//
// Author: danielwe 9 Oct 1997
//
// Notes:
//
HRESULT
HrOpenHwConnectionKey(
REFGUID refGuid,
REGSAM sam,
OCC_FLAGS occFlags,
HKEY *phkey)
{
HRESULT hr = S_OK;
WCHAR szRegPath[256];
WCHAR szGuid[c_cchGuidWithTerm];
Assert(phkey);
*phkey = NULL;
StringFromGUID2(refGuid, szGuid, c_cchGuidWithTerm);
wsprintfW(szRegPath, c_szRegKeyHwConFmt, szGuid);
if (occFlags & OCCF_CREATE_IF_NOT_EXIST)
{
DWORD dwDisp;
hr = HrRegCreateKeyEx(HKEY_CURRENT_CONFIG, szRegPath, 0,
sam, NULL, phkey, &dwDisp);
}
else
{
hr = HrRegOpenKeyEx(HKEY_CURRENT_CONFIG, szRegPath, sam, phkey);
}
TraceError("HrOpenHwConnectionKey", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrIsConnectionNameUnique
//
// Purpose: Returns whether or not the given connection name is unique.
//
// Arguments:
// guidExclude [in,ref] Device GUID of Connection to exclude from
// consideration (can be {0})
// pszName [in] Name to verify for uniqueness
//
// Returns: S_OK if name is unique, S_FALSE if it is a duplicate, or OLE
// or Win32 error otherwise
//
// Author: danielwe 14 Nov 1997
//
// Notes:
//
HRESULT
HrIsConnectionNameUnique(
REFGUID guidExclude,
PCWSTR pszName)
{
Assert(pszName);
BOOL fDupe = FALSE;
// Iterate all LAN connections
//
INetConnectionManager * pconMan;
HRESULT hr = HrCreateInstance(CLSID_LanConnectionManager,
CLSCTX_SERVER | CLSCTX_NO_CODE_DOWNLOAD, &pconMan);
TraceHr(ttidError, FAL, hr, FALSE, "HrCreateInstance");
if (SUCCEEDED(hr))
{
CIterNetCon ncIter(pconMan, NCME_DEFAULT);
INetConnection * pconn;
while (SUCCEEDED(hr) && !fDupe &&
(S_OK == (ncIter.HrNext(&pconn))))
{
// Exclude if GUID passed in matches this connection's GUID.
//
if (!FPconnEqualGuid(pconn, guidExclude))
{
NETCON_PROPERTIES* pProps;
hr = pconn->GetProperties(&pProps);
if (SUCCEEDED(hr))
{
AssertSz(pProps->pszwName, "NULL pszwName!");
if (!lstrcmpiW(pProps->pszwName, pszName))
{
// Names match.. This is a dupe.
fDupe = TRUE;
}
FreeNetconProperties(pProps);
}
}
ReleaseObj(pconn);
}
ReleaseObj(pconMan);
}
if (SUCCEEDED(hr))
{
hr = fDupe ? S_FALSE : S_OK;
}
TraceErrorOptional("HrIsConnectionNameUnique", hr, (S_FALSE == hr));
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrLanConnectionNameFromGuidOrPath
//
// Purpose: Retrieves the display-name of a LAN connection given its GUID.
//
// Arguments:
// guid [in] GUID of net card in question
// pszPath [in] Bind path that contains the GUID of the net
// card in question
// pszName [out] receives the retrieved name
// pcchMax [inout] indicates the capacity of 'pszName' on input,
// contains the required capacity on output.
//
// Returns: S_OK if success, OLE or Win32 error otherwise.
//
// Author: aboladeg 30 May 1998
//
// Notes: Only pguid or pszGuidPath should be specified, not both.
// Specifying both will result in an E_INVALIDARG error
//
EXTERN_C
HRESULT
WINAPI
HrLanConnectionNameFromGuidOrPath(
const GUID* pguid,
PCWSTR pszPath,
PWSTR pszName,
LPDWORD pcchMax)
{
HRESULT hr = S_OK;
Assert(pcchMax);
// If neither a guid nor a path was specified then return an error.
//
if (!pguid && (!pszPath || !*pszPath))
{
hr = E_INVALIDARG;
}
// If both pguid and a path were specified then return an error.
//
else if (pguid && (pszPath && *pszPath))
{
hr = E_INVALIDARG;
}
else
{
WCHAR szGuid [c_cchGuidWithTerm];
PCWSTR pszGuid = NULL;
// If we don't have pguid, it means we are to parset if from
// pszPath.
//
if (!pguid)
{
Assert(pszPath && *pszPath);
// Search for the beginning brace of the supposed GUID and
// copy the remaining characters into szGuid.
// If no guid is found, return file not found since
// there will be no connection name found.
//
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
for (const WCHAR* pch = pszPath; *pch; pch++)
{
if (*pch == L'{')
{
wcsncpy (szGuid, pch, celems(szGuid)-1);
szGuid[celems(szGuid)-1] = 0;
pszGuid = szGuid;
hr = S_OK;
break;
}
}
}
if (S_OK == hr)
{
HKEY hkey;
hr = HrOpenConnectionKey(pguid, pszGuid, KEY_READ,
OCCF_NONE, NULL, &hkey);
if (S_OK == hr)
{
DWORD dwType;
*pcchMax *= sizeof(WCHAR);
hr = HrRegQueryValueEx(hkey, c_szConnName, &dwType,
(LPBYTE)pszName, pcchMax);
*pcchMax /= sizeof(WCHAR);
RegCloseKey(hkey);
}
}
}
TraceError("HrLanConnectionNameFromGuid",
(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr) ? S_OK : hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrPnccFromGuid
//
// Purpose: Given a GUID of an adapter, returns the INetCfgComponent
// that corresponds to it.
//
// Arguments:
// pnc [in] INetCfg to work with
// refGuid [in] GUID of adapter to look for
// ppncc [out] Returns INetCfgComponent already AddRef'd
//
// Returns: S_OK if found, S_FALSE if not (out param will be NULL), or
// OLE or Win32 error otherwise
//
// Author: danielwe 6 Nov 1997
//
// Notes: Caller should ReleaseObj the returned pointer
//
HRESULT HrPnccFromGuid(INetCfg *pnc, const GUID &refGuid,
INetCfgComponent **ppncc)
{
HRESULT hr = S_OK;
Assert(pnc);
if (!ppncc)
{
hr = E_POINTER;
}
else
{
*ppncc = NULL;
BOOL fFound = FALSE;
CIterNetCfgComponent nccIter(pnc, &GUID_DEVCLASS_NET);
INetCfgComponent * pncc;
while (!fFound && SUCCEEDED(hr) &&
S_OK == (hr = nccIter.HrNext(&pncc)))
{
GUID guidTest;
hr = pncc->GetInstanceGuid(&guidTest);
if (S_OK == hr)
{
if (guidTest == refGuid)
{
// Found our adapter
fFound = TRUE;
// Give another reference so it's not released down below
AddRefObj(pncc);
*ppncc = pncc;
Assert (S_OK == hr);
}
}
ReleaseObj(pncc);
}
if (SUCCEEDED(hr) && !fFound)
{
hr = S_FALSE;
}
}
TraceErrorOptional("HrPnccFromGuid", hr, (S_FALSE == hr));
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrIsConnection
//
// Purpose: Determines whether the given component has an associated
// LAN connection.
//
// Arguments:
// pncc [in] Component to test
//
// Returns: S_OK if it does, S_FALSE if not, otherwise a Win32 error code
//
// Author: danielwe 2 Oct 1997
//
// Notes:
//
HRESULT HrIsConnection(INetCfgComponent *pncc)
{
HRESULT hr = S_FALSE;
GUID guid;
Assert(pncc);
// Get the component instance GUID
//
hr = pncc->GetInstanceGuid(&guid);
if (SUCCEEDED(hr))
{
HKEY hkey;
// Check for the existence of the connection sub-key
hr = HrOpenConnectionKey(&guid, NULL, KEY_READ,
OCCF_NONE, NULL, &hkey);
if (SUCCEEDED(hr))
{
RegCloseKey(hkey);
}
else if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
{
// Key not there, return FALSE
hr = S_FALSE;
}
}
TraceErrorOptional("HrIsConnection", hr, (S_FALSE == hr));
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrGetDeviceGuid
//
// Purpose: Given a LAN connection object, returns the device GUID
// associated with it.
//
// Arguments:
// pconn [in] LAN connection object
// pguid [out] Returns device GUID
//
// Returns: S_OK if success, OLE or Win32 error if failed
//
// Author: danielwe 23 Dec 1997
//
// Notes:
//
HRESULT HrGetDeviceGuid(INetConnection *pconn, GUID *pguid)
{
HRESULT hr = S_OK;
INetLanConnection * plan = NULL;
Assert(pguid);
hr = HrQIAndSetProxyBlanket(pconn, &plan);
if (SUCCEEDED(hr))
{
hr = plan->GetDeviceGuid(pguid);
ReleaseObj(plan);
}
TraceError("HrGetDeviceGuid", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: FPconnEqualGuid
//
// Purpose: Determines if the given connection's device GUID matches the
// guid passed in.
//
// Arguments:
// pconn [in] Connection object to examine (must be a LAN connection)
// guid [in,ref] Guid to compare with
//
// Returns: TRUE if connection's device guid matches passed in guid, FALSE
// if not.
//
// Author: danielwe 23 Dec 1997
//
// Notes:
//
BOOL FPconnEqualGuid(INetConnection *pconn, REFGUID guid)
{
HRESULT hr = S_OK;
GUID guidDev;
BOOL fRet = FALSE;
hr = HrGetDeviceGuid(pconn, &guidDev);
if (SUCCEEDED(hr))
{
fRet = (guidDev == guid);
}
TraceError("FPconnEqualGuid", hr);
return fRet;
}
//+---------------------------------------------------------------------------
//
// Function: HrPnpInstanceIdFromGuid
//
// Purpose: Given a GUID of a network device, returns its PnP Instance ID
//
// Arguments:
// pguid [in] NetCfg instance GUID of device
// pszInstance [out] PnP instance ID (string)
//
// Returns: S_OK if success, Win32 error code otherwise
//
// Author: danielwe 30 Oct 1998
//
// Notes:
//
HRESULT
HrPnpInstanceIdFromGuid(
const GUID* pguid,
PWSTR pszInstance,
UINT cchInstance)
{
HRESULT hr = S_OK;
WCHAR szRegPath[MAX_PATH];
HKEY hkey;
DWORD cb;
WCHAR szGuid[c_cchGuidWithTerm];
StringFromGUID2(*pguid, szGuid, c_cchGuidWithTerm);
wsprintfW(szRegPath, c_szRegKeyConFmt, szGuid);
hr = HrRegOpenKeyEx(HKEY_LOCAL_MACHINE, szRegPath, KEY_READ, &hkey);
if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
{
wsprintfW(szRegPath, c_szRegKeyIrdaFmt, szGuid);
hr = HrRegOpenKeyEx(HKEY_LOCAL_MACHINE, szRegPath, KEY_READ, &hkey);
}
if (S_OK == hr)
{
cb = cchInstance * sizeof(WCHAR);
hr = HrRegQuerySzBuffer(hkey, c_szRegValuePnpInstanceId,
pszInstance, &cb);
RegCloseKey(hkey);
}
#ifdef ENABLETRACE
if (FAILED(hr))
{
TraceHr (ttidError, FAL, hr, IsEqualGUID(*pguid, GUID_NULL), "HrPnpInstanceIdFromGuid "
"failed getting id for %S", szGuid);
}
#endif
TraceHr (ttidError, FAL, hr,
HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr,
"HrPnpInstanceIdFromGuid");
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HrGetPnpDeviceStatus
//
// Purpose: Given a network device GUID, returns its status
//
// Arguments:
// pguid [in] NetCfg instance GUID of network device
// pStatus [out] Status of device
//
// Returns: S_OK if success, Win32 error code otherwise
//
// Author: danielwe 30 Oct 1998
//
// Notes:
//
EXTERN_C
HRESULT
WINAPI
HrGetPnpDeviceStatus(
const GUID* pguid,
NETCON_STATUS *pStatus)
{
HRESULT hr = S_OK;
if (!pStatus || !pguid)
{
hr = E_POINTER;
goto err;
}
WCHAR szInstance[MAX_PATH];
hr = HrPnpInstanceIdFromGuid(pguid, szInstance, celems(szInstance));
if (SUCCEEDED(hr))
{
DEVINST devinst;
CONFIGRET cr;
cr = CM_Locate_DevNode(&devinst, szInstance,
CM_LOCATE_DEVNODE_NORMAL);
if (CR_SUCCESS == cr)
{
hr = HrGetDevInstStatus(devinst, pguid, pStatus);
}
else if (CR_NO_SUCH_DEVNODE == cr)
{
// If the devnode doesn't exist, the hardware is not physically
// present
//
*pStatus = NCS_HARDWARE_NOT_PRESENT;
}
}
err:
TraceError("HrGetPnpDeviceStatus", hr);
return hr;
}
extern const WCHAR c_szDevice[];
//+---------------------------------------------------------------------------
//
// Function: HrQueryLanMediaState
//
// Purpose: Determines as best as can be basically whether the cable is
// plugged in to the network card.
//
// Arguments:
// pguid [in] GUID of device to tes
// pfEnabled [out] Returns TRUE if media is connected, FALSE if not
//
// Returns: S_OK if success, Win32 error otherwise
//
// Author: danielwe 13 Nov 1998
//
// Notes:
//
EXTERN_C
HRESULT
WINAPI
HrQueryLanMediaState(
const GUID* pguid,
BOOL* pfEnabled)
{
HRESULT hr = S_OK;
if (!pfEnabled)
{
hr = E_POINTER;
}
else
{
UINT uiRet = 0;
NIC_STATISTICS nsNewLanStats = {0};
tstring strDevice;
UNICODE_STRING ustrDevice;
WCHAR szGuid[c_cchGuidWithTerm];
// Initialize to TRUE
//
*pfEnabled = TRUE;
StringFromGUID2(*pguid, szGuid, c_cchGuidWithTerm);
strDevice = c_szDevice;
strDevice.append(szGuid);
RtlInitUnicodeString(&ustrDevice, strDevice.c_str());
nsNewLanStats.Size = sizeof(NIC_STATISTICS);
uiRet = NdisQueryStatistics(&ustrDevice, &nsNewLanStats);
if (uiRet)
{
*pfEnabled = (nsNewLanStats.MediaState == MEDIA_STATE_CONNECTED);
}
else
{
hr = HrFromLastWin32Error();
}
}
TraceHr (ttidError, FAL, hr,
HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr,
"HrQueryLanMediaState");
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: FIsMediaPresent
//
// Purpose: Determines as best as can be basically whether the cable is
// plugged in to the network card.
//
// Arguments:
// pGuid [in] GUID of device to test
//
// Returns: TRUE if media is connected, FALSE otherwise
//
// Author: danielwe 30 Oct 1998
//
// Notes:
//
BOOL
FIsMediaPresent(
const GUID *pguid)
{
BOOL fEnabled;
if (SUCCEEDED(HrQueryLanMediaState(pguid, &fEnabled)))
{
return fEnabled;
}
// Assume media is connected on failure
return TRUE;
}
//+---------------------------------------------------------------------------
//
// Function: HrGetDevInstStatus
//
// Purpose: Determines status of the given Pnp device instance
//
// Arguments:
// devinst [in] PnP device instance
// pGuid [in] GUID of said device
// pStatus [out] Status of device
//
// Returns: S_OK if success, Win32 error code otherwise
//
// Author: danielwe 30 Oct 1998
//
// Notes:
//
HRESULT
HrGetDevInstStatus(
DEVINST devinst,
const GUID* pguid,
NETCON_STATUS* pStatus)
{
HRESULT hr = S_OK;
ULONG ulStatus;
ULONG ulProblem;
CONFIGRET cfgRet;
if (!pguid)
{
return E_INVALIDARG;
}
if (!pStatus)
{
return E_POINTER;
}
cfgRet = CM_Get_DevNode_Status_Ex(&ulStatus, &ulProblem,
devinst, 0, NULL);
if (CR_SUCCESS == cfgRet)
{
TraceTag(ttidLanCon, "CM_Get_DevNode_Status_Ex: ulProblem "
"= 0x%08X, ulStatus = 0x%08X.",
ulProblem, ulStatus);
switch (ulProblem)
{
case 0:
// No problem, we're connected
*pStatus = NCS_CONNECTED;
break;
case CM_PROB_DEVICE_NOT_THERE:
case CM_PROB_MOVED:
// Device not present
*pStatus = NCS_HARDWARE_NOT_PRESENT;
break;
case CM_PROB_HARDWARE_DISABLED:
// Device was disabled via Device Manager
*pStatus = NCS_HARDWARE_DISABLED;
break;
case CM_PROB_DISABLED:
// Device was disconnected
*pStatus = NCS_DISCONNECTED;
break;
default:
// All other problems
*pStatus = NCS_HARDWARE_MALFUNCTION;
break;
}
if (*pStatus == NCS_CONNECTED)
{
// Check DeviceState and MediaState from NdisQueryStatistics
UINT uiRet = 0;
NIC_STATISTICS nsNewLanStats = {0};
tstring strDevice;
UNICODE_STRING ustrDevice;
WCHAR szGuid[c_cchGuidWithTerm];
StringFromGUID2(*pguid, szGuid, c_cchGuidWithTerm);
strDevice = c_szDevice;
strDevice.append(szGuid);
RtlInitUnicodeString(&ustrDevice, strDevice.c_str());
nsNewLanStats.Size = sizeof(NIC_STATISTICS);
uiRet = NdisQueryStatistics(&ustrDevice, &nsNewLanStats);
if (uiRet)
{
// Check MediaState
if (nsNewLanStats.MediaState == MEDIA_STATE_DISCONNECTED)
{
TraceTag(ttidLanCon, "NdisQueryStatistics reports MediaState of "
"device %S is disconnected.", szGuid);
*pStatus = NCS_MEDIA_DISCONNECTED;
}
else
{
HRESULT hrTmp;
BOOL fValidAddress = TRUE;
hrTmp = HrGetAddressStatusForAdapter(pguid, &fValidAddress);
if (SUCCEEDED(hrTmp))
{
if (!fValidAddress)
{
*pStatus = NCS_INVALID_ADDRESS;
INetCfg *pNetCfg = NULL;
BOOL fInitCom = TRUE;
HRESULT hrT = CoInitializeEx(NULL, COINIT_DISABLE_OLE1DDE | COINIT_MULTITHREADED);
if (RPC_E_CHANGED_MODE == hrT)
{
hrT = S_OK;
fInitCom = FALSE;
}
if (SUCCEEDED(hrT))
{
HRESULT hrT = HrCreateAndInitializeINetCfg(NULL, &pNetCfg, FALSE, 0, NULL, NULL);
if (SUCCEEDED(hrT))
{
INetCfgComponent *pNetCfgComponent = NULL;
hrT = HrPnccFromGuid(pNetCfg, *pguid, &pNetCfgComponent);
if (S_OK == hrT)
{
DWORD dwCharacteristics = 0;
pNetCfgComponent->GetCharacteristics(&dwCharacteristics);
if (NCF_VIRTUAL & dwCharacteristics)
{
*pStatus = NCS_CONNECTED;
TraceTag(ttidLanCon, "NCS_INVALID_ADDRESS status ignored for NCF_VIRTUAL device: %S", szGuid);
}
pNetCfgComponent->Release();
}
HrUninitializeAndReleaseINetCfg(FALSE, pNetCfg, FALSE);
}
if (fInitCom)
{
CoUninitialize();
}
}
TraceError("Error retrieving adapter Characteristics", hrT);
}
}
}
}
else
{
// $REVIEW(tongl 11/25/98): This is added to display proper state
// for ATM ELAN virtual miniports (Raid #253972, 256355).
//
// If we get here for a physical adapter, this means NdisQueryStatistics
// returned different device state from CM_Get_DevNode_Status_Ex, we may
// have a problem.
hr = HrFromLastWin32Error();
if ((HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr) &&
(nsNewLanStats.DeviceState == DEVICE_STATE_DISCONNECTED))
{
Assert(nsNewLanStats.MediaState == MEDIA_STATE_UNKNOWN);
TraceTag(ttidLanCon, "NdisQueryStatistics reports DeviceState of "
"device %S is disconnected.", szGuid);
*pStatus = NCS_DISCONNECTED;
hr = S_OK;
}
else if (HRESULT_FROM_WIN32(ERROR_NOT_READY) == hr)
{
// This error means that the device went into power
// management induced sleep and so we should report this
// case as media disconnected, not connection disconnected
TraceTag(ttidLanCon, "NdisQueryStatistics reports device"
" %S is asleep. Returning status of media "
"disconnected.", szGuid);
*pStatus = NCS_MEDIA_DISCONNECTED;
hr = S_OK;
}
else if (HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED) == hr)
{
TraceTag(ttidLanCon, "NdisQueryStatistics reports device %S is still connecting.",
szGuid);
*pStatus = NCS_CONNECTING;
hr = S_OK;
}
else
{
// Treat as disconected, if we return failure the folder will
// not display this connection at all.
TraceHr (ttidLanCon, FAL, hr, FALSE, "NdisQueryStatistics reports error on device %S",
szGuid);
*pStatus = NCS_DISCONNECTED;
hr = S_OK;
}
}
}
}
TraceError("HrGetDevInstStatus", hr);
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: HasValidAddress
//
// Purpose: Verifies that the given adapter has a valid address
//
// Arguments:
// IN PIP_ADAPTER_INFO pAdapterInfo - Adapter Info structure
// containing addresses
//
// Returns: True if Valid address, False otherwise
//
// Author: ckotze 11 Jan 2001
//
// Notes:
//
//
//
BOOL HasValidAddress(IN PIP_ADAPTER_INFO pAdapterInfo)
{
PIP_ADDR_STRING pAddrString;
unsigned int addr;
TraceFileFunc(ttidConman);
for(pAddrString = &pAdapterInfo->IpAddressList; pAddrString != NULL; pAddrString = pAddrString->Next)
{
TraceTag(ttidConman, "IP Address: %s", pAddrString->IpAddress.String);
addr = inet_addr(pAddrString->IpAddress.String);
if(!addr)
{
return FALSE;
}
}
return TRUE;
}
//+---------------------------------------------------------------------------
//
// Function: HrGetAddressStatusForAdapter
//
// Purpose: Verifies that the given adapter has a valid address
//
// Arguments:
// IN LPCGUID pguidAdapter - Guid for the adapter
// OUT BOOL* pbValidAddress - BOOL indicating if it has
// has Valid Address
//
// Returns: True if Valid address, False otherwise
//
// Author: ckotze 11 Jan 2001
//
// Notes:
//
//
//
HRESULT HrGetAddressStatusForAdapter(IN LPCGUID pguidAdapter, OUT BOOL* pbValidAddress)
{
HRESULT hr = E_FAIL;
GUID guidId = GUID_NULL;
PIP_ADAPTER_INFO pAdapterInfo = NULL;
PIP_ADAPTER_INFO pAdapters = NULL;
ULONG ulSize = 0;
PIP_ADAPTER_INFO p = NULL;
WCHAR lpszInstanceId[50];
WCHAR szAdapterGUID[MAX_PATH];
WCHAR szAdapterID[MAX_PATH];
if (!pguidAdapter)
{
return E_INVALIDARG;
}
if (!pbValidAddress)
{
return E_POINTER;
}
ZeroMemory(szAdapterGUID, sizeof(WCHAR)*MAX_PATH);
ZeroMemory(szAdapterID, sizeof(WCHAR)*MAX_PATH);
StringFromGUID2(*pguidAdapter, szAdapterGUID, MAX_PATH);
// GetAdaptersInfo returns ERROR_BUFFER_OVERFLOW when it is filling in the size
if ( ERROR_BUFFER_OVERFLOW == GetAdaptersInfo(NULL, &ulSize) )
{
pAdapters = reinterpret_cast<PIP_ADAPTER_INFO>(new BYTE[ulSize]);
if (pAdapters)
{
if(ERROR_SUCCESS == GetAdaptersInfo(pAdapters, &ulSize))
{
for (p = pAdapters; p != NULL; p = p->Next)
{
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, p->AdapterName, strlen(p->AdapterName), szAdapterID, MAX_PATH);
if (wcscmp(szAdapterGUID, szAdapterID) == 0)
{
TraceTag(ttidConman, "Found Adapter: %s", p->AdapterName);
pAdapterInfo = p;
*pbValidAddress = HasValidAddress(pAdapterInfo);
hr = S_OK;
TraceTag(ttidConman, "Valid Address: %s", (*pbValidAddress) ? "Yes" : "No");
TraceTag(ttidConman, "DHCP: %s", (pAdapterInfo->DhcpEnabled) ? "Yes" : "No");
}
}
}
delete[] reinterpret_cast<BYTE*>(pAdapters);
}
else
{
hr = E_OUTOFMEMORY;
}
}
return hr;
}
HRESULT HrGetPseudoMediaTypeFromConnection(IN REFGUID guidConn, OUT NETCON_SUBMEDIATYPE *pncsm)
{
HRESULT hr = S_OK;
HKEY hkeyConnection;
hr = HrOpenConnectionKey(&guidConn, NULL, KEY_READ, OCCF_NONE, NULL, &hkeyConnection);
if (SUCCEEDED(hr))
{
DWORD dwMediaSubType;
hr = HrRegQueryDword(hkeyConnection, c_szRegValueMediaSubType, &dwMediaSubType);
if (SUCCEEDED(hr))
{
*pncsm = static_cast<NETCON_SUBMEDIATYPE>(dwMediaSubType);
}
else
{
*pncsm = NCSM_LAN;
}
RegCloseKey(hkeyConnection);
}
return hr;
}
| 30.133736 | 175 | 0.502362 | [
"object"
] |
bbb63391f638f66ea4d87395b7d12566df9936c4 | 1,855 | cpp | C++ | GeeksForGeeks/C Plus Plus/Top_View_of_a_Binary_Tree.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 4 | 2021-06-19T14:15:34.000Z | 2021-06-21T13:53:53.000Z | GeeksForGeeks/C Plus Plus/Top_View_of_a_Binary_Tree.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 2 | 2021-07-02T12:41:06.000Z | 2021-07-12T09:37:50.000Z | GeeksForGeeks/C Plus Plus/Top_View_of_a_Binary_Tree.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 3 | 2021-06-19T15:19:20.000Z | 2021-07-02T17:24:51.000Z | /*
Problem Statement:
------------------
Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes
visible when the tree is viewed from the top. For the given below tree
1
/ \
2 3
/ \ / \
4 5 6 7
Top view will be: 4 2 1 3 7
Note: Return nodes from leftmost node to rightmost node.
Example 1:
---------
Input:
1
/ \
2 3
Output: 2 1 3
Example 2:
---------
Input:
10
/ \
20 30
/ \ / \
40 60 90 100
Output: 40 20 10 30 100
Your Task: Since this is a function problem. You don't have to take input. Just complete the function topView()
that takes root node as parameter and returns a list of nodes visible from the top view from left to right.
Print endline after end of printing the top view.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N).
*/
// Link --> https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1#
// Code:
class Solution
{
public:
vector <int> topView(Node *root)
{
vector <int> ans;
if(root == NULL)
return ans;
Node *temp = NULL;
queue <pair <Node* , int>> q;
map<int , int> mp;
q.push({root, 0});
while(!q.empty())
{
temp = q.front().first;
int d = q.front().second;
q.pop();
if(mp.find(d) == mp.end())
mp[d] = temp->data;
if(temp->left)
q.push({temp->left, d-1});
if(temp->right)
q.push({temp->right, d+1});
}
for(auto it = mp.begin(); it != mp.end(); it++)
ans.push_back(it->second);
return ans;
}
};
| 20.842697 | 126 | 0.504582 | [
"vector"
] |
bbb70952bb92f45539f85aa3e70ea4d89a787470 | 16,005 | cpp | C++ | plugins/track/head/kinectHeadTracking/3rdParty/kinect/v2.0_1409/Samples/Native/AudioCaptureRaw-Console/WASAPICapture.cpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 158 | 2016-11-17T19:37:51.000Z | 2022-03-21T19:57:55.000Z | plugins/track/head/kinectHeadTracking/3rdParty/kinect/v2.0_1409/Samples/Native/AudioCaptureRaw-Console/WASAPICapture.cpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 94 | 2016-11-18T09:55:57.000Z | 2021-01-14T08:50:40.000Z | plugins/track/head/kinectHeadTracking/3rdParty/kinect/v2.0_1409/Samples/Native/AudioCaptureRaw-Console/WASAPICapture.cpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 51 | 2017-05-24T10:20:25.000Z | 2022-03-17T15:07:02.000Z | //------------------------------------------------------------------------------
// <copyright file="WASAPICapture.cpp" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// This module provides sample code used to demonstrate capturing raw audio streams from
// the Kinect 4-microphone array.
// </summary>
//------------------------------------------------------------------------------
#include "StdAfx.h"
#include <assert.h>
#include <avrt.h>
#include "WASAPICapture.h"
/// <summary>
/// Initializes an instance of CWASAPICapture type.
/// </summary>
CWASAPICapture::CWASAPICapture(IMMDevice *Endpoint) :
_Endpoint(Endpoint),
_AudioClient(NULL),
_CaptureClient(NULL),
_Resampler(NULL),
_CaptureThread(NULL),
_CaptureFile(INVALID_HANDLE_VALUE),
_ShutdownEvent(NULL),
_EngineLatencyInMS(0),
_MixFormat(NULL),
_MixFrameSize(0),
_InputBufferSize(0),
_InputBuffer(NULL),
_InputSample(NULL),
_OutputBufferSize(0),
_OutputBuffer(NULL),
_OutputSample(NULL),
_BytesCaptured(0),
_Gain(1.0f)
{
_Endpoint->AddRef(); // Since we're holding a copy of the endpoint, take a reference to it. It'll be released in Shutdown();
}
/// <summary>
/// Uninitialize an instance of CWASAPICapture type.
/// </summary>
/// <remarks>
/// Shuts down the capture code and frees all the resources.
/// </remarks>
CWASAPICapture::~CWASAPICapture(void)
{
if (NULL != _CaptureThread)
{
SetEvent(_ShutdownEvent);
WaitForSingleObject(_CaptureThread, INFINITE);
CloseHandle(_CaptureThread);
_CaptureThread = NULL;
}
_CaptureFile = INVALID_HANDLE_VALUE;
if (NULL != _ShutdownEvent)
{
CloseHandle(_ShutdownEvent);
_ShutdownEvent = NULL;
}
SafeRelease(_Endpoint);
SafeRelease(_AudioClient);
SafeRelease(_CaptureClient);
SafeRelease(_Resampler);
if (NULL != _MixFormat)
{
CoTaskMemFree(_MixFormat);
_MixFormat = NULL;
}
SafeRelease(_InputBuffer);
SafeRelease(_InputSample);
SafeRelease(_OutputBuffer);
SafeRelease(_OutputSample);
}
/// <summary>
/// Initialize the capturer.
/// </summary>
/// <param name="EngineLatency">
/// Number of milliseconds of acceptable lag between live sound being produced and recording operation.
/// </param>
/// <returns>
/// true if capturer was initialized successfully, false otherwise.
/// </returns>
bool CWASAPICapture::Initialize(UINT32 EngineLatency)
{
//
// Create our shutdown event - we want a manual reset event that starts in the not-signaled state.
//
_ShutdownEvent = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE);
if (NULL == _ShutdownEvent)
{
printf_s("Unable to create shutdown event: %u.\n", GetLastError());
return false;
}
//
// Now activate an IAudioClient object on our preferred endpoint and retrieve the mix format for that endpoint.
//
HRESULT hr = _Endpoint->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, reinterpret_cast<void **>(&_AudioClient));
if (FAILED(hr))
{
printf_s("Unable to activate audio client: %x.\n", hr);
return false;
}
//
// Load the MixFormat. This may differ depending on the shared mode used
//
if (!LoadFormat())
{
printf_s("Failed to load the mix format \n");
return false;
}
//
// Remember our configured latency
//
_EngineLatencyInMS = EngineLatency;
if (!InitializeAudioEngine())
{
return false;
}
_InputBufferSize = _EngineLatencyInMS * _MixFormat->nAvgBytesPerSec / 1000;
_OutputBufferSize = _EngineLatencyInMS * _OutFormat.nAvgBytesPerSec / 1000;
hr = CreateResamplerBuffer(_InputBufferSize, &_InputSample, &_InputBuffer);
if (FAILED(hr))
{
printf_s("Unable to allocate input buffer.");
return false;
}
hr = CreateResamplerBuffer(_OutputBufferSize, &_OutputSample, &_OutputBuffer);
if (FAILED(hr))
{
printf_s("Unable to allocate output buffer.");
return false;
}
// Create resampler object
hr = CreateResampler(_MixFormat, &_OutFormat, &_Resampler);
if (FAILED(hr))
{
printf_s("Unable to create audio resampler\n");
return false;
}
return true;
}
/// <summary>
/// Start capturing audio data.
/// </summary>
/// <param name="waveFile">
/// [in] Handle to wave file where audio data will be written.
/// </param>
/// <returns>
/// true if capturer has successfully started capturing audio data, false otherwise.
/// </returns>
bool CWASAPICapture::Start(HANDLE waveFile)
{
HRESULT hr;
_BytesCaptured = 0;
_CaptureFile = waveFile;
//
// Now create the thread which is going to drive the capture.
//
_CaptureThread = CreateThread(NULL, 0, WASAPICaptureThread, this, 0, NULL);
if (NULL == _CaptureThread)
{
printf_s("Unable to create transport thread: %x.", GetLastError());
return false;
}
//
// We're ready to go, start capturing!
//
hr = _AudioClient->Start();
if (FAILED(hr))
{
printf_s("Unable to start capture client: %x.\n", hr);
return false;
}
return true;
}
/// <summary>
/// Stop the capturer.
/// </summary>
void CWASAPICapture::Stop()
{
HRESULT hr;
//
// Tell the capture thread to shut down, wait for the thread to complete then clean up all the stuff we
// allocated in Start().
//
if (NULL != _ShutdownEvent)
{
SetEvent(_ShutdownEvent);
}
hr = _AudioClient->Stop();
if (FAILED(hr))
{
printf_s("Unable to stop audio client: %x\n", hr);
}
if (NULL != _CaptureThread)
{
WaitForSingleObject(_CaptureThread, INFINITE);
CloseHandle(_CaptureThread);
_CaptureThread = NULL;
}
}
/// <summary>
/// Capture thread - captures audio from WASAPI, processes it with a resampler and writes it to file.
/// </summary>
/// <param name="Context">
/// [in] Thread data, representing an instance of CWASAPICapture type.
/// </param>
/// <returns>
/// Thread return value.
/// </returns>
DWORD CWASAPICapture::WASAPICaptureThread(LPVOID Context)
{
CWASAPICapture *capturer = static_cast<CWASAPICapture *>(Context);
return capturer->DoCaptureThread();
}
/// <summary>
/// Capture thread - captures audio from WASAPI, processes it with a resampler and writes it to file.
/// </summary>
/// <returns>
/// Thread return value.
/// </returns>
DWORD CWASAPICapture::DoCaptureThread()
{
bool stillPlaying = true;
HANDLE mmcssHandle = NULL;
DWORD mmcssTaskIndex = 0;
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
{
printf_s("Unable to initialize COM in render thread: %x\n", hr);
return hr;
}
mmcssHandle = AvSetMmThreadCharacteristics(L"Audio", &mmcssTaskIndex);
if (mmcssHandle == NULL)
{
printf_s("Unable to enable MMCSS on capture thread: %u\n", GetLastError());
}
while (stillPlaying)
{
//
// We want to wait for half the desired latency in milliseconds.
//
// That way we'll wake up half way through the processing period to pull the
// next set of samples from the engine.
//
DWORD waitResult = WaitForSingleObject(_ShutdownEvent, _EngineLatencyInMS / 2);
switch (waitResult)
{
case WAIT_OBJECT_0 + 0:
// If _ShutdownEvent has been set, we're done and should exit the main capture loop.
stillPlaying = false;
break;
case WAIT_TIMEOUT:
// We need to retrieve the next buffer of samples from the audio capturer.
BYTE *pData;
UINT32 framesAvailable;
DWORD flags;
bool isEmpty = false;
// Keep fetching audio in a tight loop as long as audio device still has data.
while (!isEmpty && (WAIT_OBJECT_0 != WaitForSingleObject(_ShutdownEvent, 0)))
{
hr = _CaptureClient->GetBuffer(&pData, &framesAvailable, &flags, NULL, NULL);
if (SUCCEEDED(hr))
{
if ( (AUDCLNT_S_BUFFER_EMPTY == hr) || (0 == framesAvailable) )
{
isEmpty = true;
}
else
{
DWORD bytesAvailable = framesAvailable * _MixFrameSize;
// Process input to resampler
hr = ProcessResamplerInput(pData, bytesAvailable, flags);
if (SUCCEEDED(hr))
{
DWORD bytesWritten;
// Process output from resampler
hr = ProcessResamplerOutput(&bytesWritten);
if (SUCCEEDED(hr))
{
// Audio capture was successful, so bump the capture buffer pointer.
_BytesCaptured += bytesWritten;
}
}
}
hr = _CaptureClient->ReleaseBuffer(framesAvailable);
if (FAILED(hr))
{
printf_s("Unable to release capture buffer: %x!\n", hr);
}
}
}
break;
}
}
if (NULL != mmcssHandle)
{
AvRevertMmThreadCharacteristics(mmcssHandle);
}
CoUninitialize();
return 0;
}
/// <summary>
/// Take audio data captured from WASAPI and feed it as input to audio resampler.
/// </summary>
/// <param name="pBuffer">
/// [in] Buffer holding audio data from WASAPI.
/// </param>
/// <param name="bufferSize">
/// [in] Number of bytes available in pBuffer.
/// </param>
/// <param name="flags">
/// [in] Flags returned from WASAPI capture.
/// </param>
/// <returns>
/// S_OK on success, otherwise failure code.
/// </returns>
HRESULT CWASAPICapture::ProcessResamplerInput(BYTE *pBuffer, DWORD bufferSize, DWORD flags)
{
HRESULT hr = S_OK;
BYTE* pLocked = NULL;
DWORD maxLength;
hr = _InputBuffer->Lock(&pLocked, &maxLength, NULL);
if (SUCCEEDED(hr))
{
DWORD dataToCopy = min(bufferSize, maxLength);
//
// The flags on capture tell us information about the data.
//
// We only really care about the silent flag since we want to put frames of silence into the buffer
// when we receive silence. We rely on the fact that a logical bit 0 is silence for both float and int formats.
//
if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
{
// Fill 0s from the capture buffer to the output buffer.
ZeroMemory(pLocked, dataToCopy);
}
else
{
// Copy data from the audio engine buffer to the output buffer.
memcpy_s(pLocked, maxLength, pBuffer, bufferSize);
// Apply gain on the raw Kinect buffer if needed, before the resampler.
if (_Gain != 1.0f)
{
// When we capture in shared mode the capture mix format is always 32-bit IEEE
// floating point, so we can safely assume float samples in the buffer.
float* pFloatLocked = (float *)pLocked;
for (DWORD i = 0; i < dataToCopy/sizeof(float); i++)
{
pFloatLocked[i] *= _Gain;
}
}
}
hr = _InputBuffer->SetCurrentLength(dataToCopy);
if (SUCCEEDED(hr))
{
hr = _Resampler->ProcessInput(0, _InputSample, 0);
}
_InputBuffer->Unlock();
}
return hr;
}
/// <summary>
/// Get data output from audio resampler and write it to file.
/// </summary>
/// <param name="pBytesWritten">
/// [out] On success, will receive number of bytes written to file.
/// </param>
/// <returns>
/// S_OK on success, otherwise failure code.
/// </returns>
HRESULT CWASAPICapture::ProcessResamplerOutput(DWORD *pBytesWritten)
{
HRESULT hr = S_OK;
MFT_OUTPUT_DATA_BUFFER outBuffer;
DWORD outStatus;
outBuffer.dwStreamID = 0;
outBuffer.pSample = _OutputSample;
outBuffer.dwStatus = 0;
outBuffer.pEvents = 0;
hr = _Resampler->ProcessOutput(0, 1, &outBuffer, &outStatus);
if (SUCCEEDED(hr))
{
BYTE* pLocked = NULL;
hr = _OutputBuffer->Lock(&pLocked, NULL, NULL);
if (SUCCEEDED(hr))
{
DWORD lockedLength;
hr = _OutputBuffer->GetCurrentLength(&lockedLength);
if (SUCCEEDED(hr))
{
if (!WriteFile(_CaptureFile, pLocked, lockedLength, pBytesWritten, NULL))
{
hr = E_FAIL;
}
}
_OutputBuffer->Unlock();
}
}
return hr;
}
/// <summary>
/// Initialize WASAPI in timer driven mode, and retrieve a capture client for the transport.
/// </summary>
/// <returns>
/// S_OK on success, otherwise failure code.
/// </returns>
bool CWASAPICapture::InitializeAudioEngine()
{
HRESULT hr = _AudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_NOPERSIST, _EngineLatencyInMS*10000, 0, _MixFormat, NULL);
if (FAILED(hr))
{
printf_s("Unable to initialize audio client: %x.\n", hr);
return false;
}
hr = _AudioClient->GetService(IID_PPV_ARGS(&_CaptureClient));
if (FAILED(hr))
{
printf_s("Unable to get new capture client: %x.\n", hr);
return false;
}
return true;
}
/// <summary>
/// Retrieve the format we'll use to capture samples and set gain
/// </summary>
/// <returns>
/// true if format was loaded successfully, false otherwise.
/// </returns>
bool CWASAPICapture::LoadFormat()
{
HRESULT hr = _AudioClient->GetMixFormat(&_MixFormat);
if (FAILED(hr))
{
printf_s("Unable to get mix format on audio client: %x.\n", hr);
return false;
}
// Frame size (nBlockAlign) of the audio we will read from WASAPI
_MixFrameSize = (_MixFormat->wBitsPerSample / 8) * _MixFormat->nChannels;
// Set to 0 or 1 to select example outputs
#if 1
// Example one: Use the capture mix format. If Kinect is the only capture device
// running, this will give us Kinect's "raw" 4 microphones (4 channels) of audio
// at 16khz sample rate, 32-bit IEEE float format.
// In this example we do not apply a gain. Note that since Kinect microphones have
// a large dynamic range, audio levels may be very low unless you have a sound
// source close to Kinect. You can select a gain larger than 1.0 to adjust levels.
// Also note that in this example, the Resampler is just a pass-through. It does
// not do any format conversion.
_OutFormat.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
_OutFormat.nChannels = _MixFormat->nChannels;
_OutFormat.nSamplesPerSec = _MixFormat->nSamplesPerSec;
_OutFormat.wBitsPerSample = _MixFormat->wBitsPerSample;
_Gain = 1.0f;
#else
// Example two: Use the resampler to convert sample rate, number of channels
// and sample format of the "raw" Kinect audio. In this example, the output is mono,
// 16-bit signed at 48khz sample rate. We also apply a gain of 10 to compensate for
// low level audio.
_OutFormat.wFormatTag = WAVE_FORMAT_PCM;
_OutFormat.nChannels = 1;
_OutFormat.nSamplesPerSec = 48000;
_OutFormat.wBitsPerSample = 16;
_Gain = 10.0f;
#endif
_OutFormat.nBlockAlign = _OutFormat.nChannels * _OutFormat.wBitsPerSample / 8;
_OutFormat.nAvgBytesPerSec = _OutFormat.nSamplesPerSec * _OutFormat.nBlockAlign;
_OutFormat.cbSize = 0;
return true;
}
| 29.804469 | 146 | 0.60656 | [
"render",
"object"
] |
bbb859205eb482abe05abba35fba7c8e179fbeb2 | 6,523 | cpp | C++ | python/PyAlembic/PyXformSample.cpp | ryu-sw/alembic | 395450bad88f9d5ed6d20612e9201aac93a5eb54 | [
"MIT"
] | 921 | 2015-01-03T11:04:38.000Z | 2022-03-29T06:38:34.000Z | python/PyAlembic/PyXformSample.cpp | ryu-sw/alembic | 395450bad88f9d5ed6d20612e9201aac93a5eb54 | [
"MIT"
] | 264 | 2015-01-05T17:15:45.000Z | 2022-03-28T20:14:51.000Z | python/PyAlembic/PyXformSample.cpp | ryu-sw/alembic | 395450bad88f9d5ed6d20612e9201aac93a5eb54 | [
"MIT"
] | 276 | 2015-01-12T01:34:20.000Z | 2022-03-08T09:19:42.000Z | //-*****************************************************************************
//
// Copyright (c) 2012,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// 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 Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//-*****************************************************************************
#include <Foundation.h>
using namespace boost::python;
//-*****************************************************************************
void register_xformsample()
{
// Overloads for XformSample
//
size_t ( AbcG::XformSample::*addTranslateScaleOp )
( AbcG::XformOp, const Imath::V3d& )
= &AbcG::XformSample::addOp;
size_t ( AbcG::XformSample::*addRotateOp )
( AbcG::XformOp, const Imath::V3d&, double )
= &AbcG::XformSample::addOp;
size_t ( AbcG::XformSample::*addMatrixOp )
( AbcG::XformOp, const Imath::M44d& )
= &AbcG::XformSample::addOp;
size_t ( AbcG::XformSample::*addRotateAxisOp )
( AbcG::XformOp, double )
= &AbcG::XformSample::addOp;
size_t ( AbcG::XformSample::*addPresetOp )
( const AbcG::XformOp& )
= &AbcG::XformSample::addOp;
// Overload for __getitem__
struct Overloads
{
typedef AbcG::XformSample Sample;
static AbcG::XformOp &getOpByIndex( Sample& iSamp, size_t iIndex )
{
return iSamp[iIndex];
}
};
// XformSample
//
class_<AbcG::XformSample>(
"XformSample",
init<>( "Creates an empty XformSample class object." ) )
.def( "__getitem__",
Overloads::getOpByIndex,
( arg( "index" ) ),
return_internal_reference<>() )
.def( "addOp",
addTranslateScaleOp,
( arg( "transOrScaleOp" ), arg( "value" ) ),
"Add translate or scale op. Returns the index of the op in its "
"op-stack." )
.def( "addOp",
addRotateOp,
( arg( "rotateOp" ), arg( "axis" ), arg( "degrees" ) ),
"Add rotate op. Returns the index of the op in its op-stack." )
.def( "addOp",
addMatrixOp,
( arg( "matrixOp" ), arg( "matrix" ) ),
"Add matrix op. Returns the index of the op in its op-stack." )
.def( "addOp",
addRotateAxisOp,
( arg( "axisRotateOp" ), arg( "degrees" ) ),
"Add rotateX, rotateY or rotateZ op." )
.def( "addOp",
addPresetOp,
( arg( "op" ) ),
"Add an op with values already set on the op." )
.def( "getOp",
&AbcG::XformSample::getOp,
( arg( "index" ) ) )
.def( "getNumOps",
&AbcG::XformSample::getNumOps )
.def( "getNumOpChannels",
&AbcG::XformSample::getNumOpChannels )
.def( "setInheritsXforms",
&AbcG::XformSample::setInheritsXforms,
( arg( "inherits" ) ) )
.def( "getInheritsXforms",
&AbcG::XformSample::getInheritsXforms )
.def( "setTranslation",
&AbcG::XformSample::setTranslation,
( arg( "trans" ) ) )
.def( "getTranslation",
&AbcG::XformSample::getTranslation )
.def( "setRotation",
&AbcG::XformSample::setRotation,
( arg( "axis" ), arg( "degrees" ) ) )
.def( "getAxis",
&AbcG::XformSample::getAxis )
.def( "getAngle",
&AbcG::XformSample::getAngle )
.def( "setXRotation",
&AbcG::XformSample::setXRotation,
( arg( "degrees" ) ) )
.def( "getXRotation",
&AbcG::XformSample::getXRotation )
.def( "setYRotation",
&AbcG::XformSample::setYRotation,
( arg( "degrees" ) ) )
.def( "getYRotation",
&AbcG::XformSample::getYRotation )
.def( "setZRotation",
&AbcG::XformSample::setZRotation,
( arg( "degrees" ) ) )
.def( "getZRotation",
&AbcG::XformSample::getZRotation )
.def( "setScale",
&AbcG::XformSample::setScale,
( arg( "scale" ) ) )
.def( "getScale",
&AbcG::XformSample::getScale )
.def( "setMatrix",
&AbcG::XformSample::setMatrix,
( arg( "matrix" ) ) )
.def( "getMatrix",
&AbcG::XformSample::getMatrix )
.def( "isTopologyEqual",
&AbcG::XformSample::isTopologyEqual,
( arg( "sample" ) ),
"Tests whether this sample has the same topology as 'sample'" )
.def( "getIsTopologyFrozen",
&AbcG::XformSample::getIsTopologyFrozen,
"Has this Sample been used in a call to OXformSchema::set()" )
.def( "reset", &AbcG::XformSample::reset )
;
}
| 40.265432 | 80 | 0.555879 | [
"object"
] |
c7e12effebdf2bdec130c9c9253c16a4ee345987 | 32,288 | cpp | C++ | MapGen/CLR Profiler/Source/ProfilerOBJ/ProfilerInfo.cpp | hotdogee/fractal-percolation | b78bc351ea67f8a189f11ab0d2e85b68490d3bd9 | [
"Apache-2.0"
] | null | null | null | MapGen/CLR Profiler/Source/ProfilerOBJ/ProfilerInfo.cpp | hotdogee/fractal-percolation | b78bc351ea67f8a189f11ab0d2e85b68490d3bd9 | [
"Apache-2.0"
] | null | null | null | MapGen/CLR Profiler/Source/ProfilerOBJ/ProfilerInfo.cpp | hotdogee/fractal-percolation | b78bc351ea67f8a189f11ab0d2e85b68490d3bd9 | [
"Apache-2.0"
] | null | null | null | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/****************************************************************************************
* File:
* ProfilerInfo.cpp
*
* Description:
*
*
*
***************************************************************************************/
#include "avlnode.h"
#include "basehlp.h"
#include "ProfilerInfo.h"
/***************************************************************************************
******************** ********************
******************** LStack Implementation ********************
******************** ********************
***************************************************************************************/
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
LStack::LStack( ULONG size ) :
m_Count( 0 ),
m_Size( size ),
m_Array( NULL )
{
m_Array = new ULONG[size];
} // ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
LStack::~LStack()
{
if ( m_Array != NULL )
{
delete[] m_Array;
m_Array = NULL;
}
} // dtor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
LStack::LStack( const LStack &source )
{
m_Size = source.m_Size;
m_Count = source.m_Count;
m_Array = source.m_Array;
} // copy ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
ULONG LStack::Count()
{
return m_Count;
} // LStack::Count
ULONG *GrowStack(ULONG newSize, ULONG currentSize, ULONG *stack)
{
ULONG *newStack = new ULONG[newSize];
if ( newStack != NULL )
{
//
// copy all the elements
//
for (ULONG i =0; i < currentSize; i++ )
{
newStack[i] = stack[i];
}
delete[] stack;
return newStack;
}
else
_THROW_EXCEPTION( "Allocation for m_Array FAILED" )
}
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void LStack::Push( ULONG item )
{
if ( m_Count == m_Size )
m_Array = GrowStack(2*m_Count, m_Count, m_Array);
m_Array[m_Count] = item;
m_Count++;
} // LStack::Push
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
DWORD LStack::Pop()
{
DWORD item = -1;
if ( m_Count !=0 )
{
m_Count--;
item = (DWORD)m_Array[m_Count];
}
return item;
} // LStack::Pop
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
DWORD LStack::Top()
{
if ( m_Count == 0 )
return -1;
else
return m_Array[m_Count-1];
} // LStack::Top
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
BOOL LStack::Empty()
{
return (BOOL)(m_Count == NULL);
} // LStack::Empty
/***************************************************************************************
******************** ********************
******************** BaseInfo Implementation ********************
******************** ********************
***************************************************************************************/
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
BaseInfo::BaseInfo( UINT_PTR id, ULONG internal ) :
m_id( id ),
m_internalID( internal )
{
} // ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public virtual */
BaseInfo::~BaseInfo()
{
} // dtor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
template<typename T>
BOOL BaseInfo::Compare( T in_key )
{
UINT_PTR key = (UINT_PTR)in_key;
return (BOOL)(m_id == key);
} // BaseInfo::Compare
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
template<typename T>
Comparison BaseInfo::CompareEx( T in_key )
{
Comparison res = EQUAL_TO;
UINT_PTR key = (UINT_PTR)in_key;
if ( key > m_id )
res = GREATER_THAN;
else if ( key < m_id )
res = LESS_THAN;
return res;
} // BaseInfo::CompareEx
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void BaseInfo::Dump( )
{} // BaseInfo::Dump
/***************************************************************************************
******************** ********************
******************** ThreadInfo Implementation ********************
******************** ********************
***************************************************************************************/
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
ThreadInfo::ThreadInfo( ThreadID threadID, ULONG internal ) :
BaseInfo( (UINT_PTR)threadID, internal ),
m_win32ThreadID( 0 )
{
m_pThreadCallStack = new LStack( MAX_LENGTH );
m_pLatestUnwoundFunction = new LStack( MAX_LENGTH );
m_pLatestStackTraceInfo = NULL;
} // ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public virtual */
ThreadInfo::~ThreadInfo()
{
if ( m_pThreadCallStack != NULL )
{
delete m_pThreadCallStack;
m_pThreadCallStack = NULL;
}
if ( m_pLatestUnwoundFunction != NULL )
{
delete m_pLatestUnwoundFunction;
m_pLatestUnwoundFunction = NULL;
}
} // dtor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void ThreadInfo::Dump()
{} // ThreadInfo::Dump
/***************************************************************************************
******************** ********************
******************** FunctionInfo Implementation ********************
******************** ********************
***************************************************************************************/
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
FunctionInfo::FunctionInfo( FunctionID functionID, ULONG internal ) :
BaseInfo( (UINT_PTR)functionID, internal )
{
wcscpy( m_functionName, L"UNKNOWN" );
wcscpy( m_functionSig, L"" );
} // ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public virtual */
FunctionInfo::~FunctionInfo()
{
} // dtor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void FunctionInfo::Dump()
{} // FunctionInfo::Dump
/***************************************************************************************
******************** ********************
******************** ModuleInfo Implementation ********************
******************** ********************
***************************************************************************************/
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
ModuleInfo::ModuleInfo( ModuleID moduleID, ULONG internal ) :
BaseInfo( (UINT_PTR)moduleID, internal ),
m_loadAddress( 0 )
{
wcscpy( m_moduleName, L"UNKNOWN" );
} // ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public virtual */
ModuleInfo::~ModuleInfo()
{
} // dtor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void ModuleInfo::Dump()
{} // ModuleInfo::Dump
/***************************************************************************************
******************** ********************
******************** ClassInfo Implementation ********************
******************** ********************
***************************************************************************************/
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
ClassInfo::ClassInfo( ClassID classID, ULONG internal ) :
BaseInfo( (UINT_PTR)classID, internal ),
m_objectsAllocated( 0 )
{
wcscpy( m_className, L"UNKNOWN" );
} // ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public virtual */
ClassInfo::~ClassInfo()
{} // dtor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void ClassInfo::Dump()
{} // ClassInfo::Dump
/***************************************************************************************
******************** ********************
******************** PrfInfo Implementation ********************
******************** ********************
***************************************************************************************/
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
PrfInfo::PrfInfo() :
m_pProfilerInfo( NULL ),
m_dwEventMask( 0 ),
m_pClassTable( NULL ),
m_pThreadTable( NULL ),
m_pFunctionTable( NULL ),
m_pStackTraceTable( NULL )
{
// initialize tables
m_pClassTable = new HashTable<ClassInfo *, ClassID>();
m_pThreadTable = new SList<ThreadInfo *, ThreadID>();
m_pModuleTable = new Table<ModuleInfo *, ModuleID>();
m_pFunctionTable = new Table<FunctionInfo *, FunctionID>();
m_pStackTraceTable = new HashTable<StackTraceInfo *, StackTrace>();
} // ctor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* virtual public */
PrfInfo::~PrfInfo()
{
if ( m_pProfilerInfo != NULL )
m_pProfilerInfo->Release();
// clean up tables
if ( m_pClassTable != NULL )
{
delete m_pClassTable;
m_pClassTable = NULL;
}
if ( m_pThreadTable != NULL )
{
delete m_pThreadTable;
m_pThreadTable = NULL;
}
if ( m_pFunctionTable != NULL )
{
delete m_pFunctionTable;
m_pFunctionTable = NULL;
}
if ( m_pModuleTable != NULL )
{
delete m_pModuleTable;
m_pModuleTable = NULL;
}
} // dtor
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
/* throws BaseException */
void PrfInfo::AddThread( ThreadID threadID )
{
HRESULT hr;
ThreadID myThreadID;
hr = m_pProfilerInfo->GetCurrentThreadID( &myThreadID );
if ( SUCCEEDED( hr ) )
{
if ( threadID == myThreadID )
{
ThreadInfo *pThreadInfo;
pThreadInfo = new ThreadInfo( threadID );
if ( pThreadInfo != NULL )
{
hr = m_pProfilerInfo->GetThreadInfo( pThreadInfo->m_id, &(pThreadInfo->m_win32ThreadID) );
if ( SUCCEEDED( hr ) )
m_pThreadTable->AddEntry( pThreadInfo, threadID );
else
_THROW_EXCEPTION( "ICorProfilerInfo::GetThreadInfo() FAILED" )
}
else
_THROW_EXCEPTION( "Allocation for ThreadInfo Object FAILED" )
}
else
_THROW_EXCEPTION( "Thread ID's do not match FAILED" )
}
else
_THROW_EXCEPTION( "ICorProfilerInfo::GetCurrentThreadID() FAILED" )
} // PrfInfo::AddThread
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
/* throws BaseException */
void PrfInfo::RemoveThread( ThreadID threadID )
{
if ( threadID != NULL )
{
ThreadInfo *pThreadInfo;
pThreadInfo = m_pThreadTable->Lookup( threadID );
if ( pThreadInfo != NULL )
m_pThreadTable->DelEntry( threadID );
else
_THROW_EXCEPTION( "Thread was not found in the Thread Table" )
}
else
_THROW_EXCEPTION( "ThreadID is NULL" )
} // PrfInfo::RemoveThread
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
/* throws BaseException */
void PrfInfo::AddFunction( FunctionID functionID, ULONG internalID )
{
if ( functionID != NULL )
{
FunctionInfo *pFunctionInfo;
pFunctionInfo = m_pFunctionTable->Lookup( functionID );
if ( pFunctionInfo == NULL )
{
pFunctionInfo = new FunctionInfo( functionID, internalID );
if ( pFunctionInfo != NULL )
{
try
{
_GetFunctionSig( &pFunctionInfo );
m_pFunctionTable->AddEntry( pFunctionInfo, functionID );
}
catch ( BaseException *exception )
{
delete pFunctionInfo;
throw;
}
}
else
_THROW_EXCEPTION( "Allocation for FunctionInfo Object FAILED" )
}
}
else
_THROW_EXCEPTION( "FunctionID is NULL" )
} // PrfInfo::AddFunction
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
/* throws BaseException */
void PrfInfo::RemoveFunction( FunctionID functionID )
{
if ( functionID != NULL )
{
FunctionInfo *pFunctionInfo;
pFunctionInfo = m_pFunctionTable->Lookup( functionID );
if ( pFunctionInfo != NULL )
m_pFunctionTable->DelEntry( functionID );
else
_THROW_EXCEPTION( "Function was not found in the Function Table" )
}
else
_THROW_EXCEPTION( "FunctionID is NULL" )
} // PrfInfo::RemoveFunction
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
/* throws BaseException */
void PrfInfo::AddModule( ModuleID moduleID, ULONG internalID )
{
if ( moduleID != NULL )
{
ModuleInfo *pModuleInfo;
pModuleInfo = m_pModuleTable->Lookup( moduleID );
if ( pModuleInfo == NULL )
{
pModuleInfo = new ModuleInfo( moduleID, internalID );
if ( pModuleInfo != NULL )
{
HRESULT hr;
ULONG dummy;
hr = m_pProfilerInfo->GetModuleInfo( moduleID,
&(pModuleInfo->m_loadAddress),
MAX_LENGTH,
&dummy,
pModuleInfo->m_moduleName,
NULL );
if ( SUCCEEDED( hr ) )
{
m_pModuleTable->AddEntry( pModuleInfo, moduleID );
}
else
_THROW_EXCEPTION( "ICorProfilerInfo::GetModuleInfo() FAILED" )
}
else
_THROW_EXCEPTION( "Allocation for ModuleInfo Object FAILED" )
}
}
else
_THROW_EXCEPTION( "ModuleID is NULL" )
} // PrfInfo::AddModule
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
/* throws BaseException */
void PrfInfo::RemoveModule( ModuleID moduleID )
{
if ( moduleID != NULL )
{
ModuleInfo *pModuleInfo;
pModuleInfo = m_pModuleTable->Lookup( moduleID );
if ( pModuleInfo != NULL )
m_pModuleTable->DelEntry( moduleID );
else
_THROW_EXCEPTION( "Module was not found in the Module Table" )
}
else
_THROW_EXCEPTION( "ModuleID is NULL" )
} // PrfInfo::RemoveModule
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void PrfInfo::UpdateOSThreadID( ThreadID managedThreadID, DWORD osThreadID )
{
ThreadInfo *pThreadInfo;
pThreadInfo = m_pThreadTable->Lookup( managedThreadID );
if ( pThreadInfo != NULL )
pThreadInfo->m_win32ThreadID = osThreadID;
else
_THROW_EXCEPTION( "Thread does not exist in the thread table" )
} // PrfInfo::UpdateOSThreadID
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void PrfInfo::UpdateUnwindStack( FunctionID *functionID, StackAction action )
{
HRESULT hr;
ThreadID threadID;
hr = m_pProfilerInfo->GetCurrentThreadID( &threadID );
if ( SUCCEEDED(hr) )
{
ThreadInfo *pThreadInfo = m_pThreadTable->Lookup( threadID );
if ( pThreadInfo == NULL )
{
// Sadly, sometimes we see threads that weren't announced via
// CreateThread. Add them now...
AddThread( threadID );
pThreadInfo = m_pThreadTable->Lookup( threadID );
}
if ( pThreadInfo != NULL )
{
switch ( action )
{
case PUSH:
(pThreadInfo->m_pLatestUnwoundFunction)->Push( (ULONG)*functionID );
break;
case POP:
*functionID = (ULONG)(pThreadInfo->m_pLatestUnwoundFunction)->Pop();
break;
}
}
else
_THROW_EXCEPTION( "Thread Structure was not found in the thread list" )
}
else
_THROW_EXCEPTION( "ICorProfilerInfo::GetCurrentThreadID() FAILED" )
} // PrfInfo::UpdateUnwindStack
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
void PrfInfo::UpdateCallStack( FunctionID functionID, StackAction action )
{
HRESULT hr = S_OK;
ThreadID threadID;
hr = m_pProfilerInfo->GetCurrentThreadID(&threadID);
if ( SUCCEEDED(hr) )
{
ThreadInfo *pThreadInfo = m_pThreadTable->Lookup( threadID );
if ( pThreadInfo == NULL )
{
// Sadly, sometimes we see threads that weren't announced via
// CreateThread. Add them now...
AddThread( threadID );
pThreadInfo = m_pThreadTable->Lookup( threadID );
}
if ( pThreadInfo != NULL )
{
switch ( action )
{
case PUSH:
(pThreadInfo->m_pThreadCallStack)->Push( (ULONG)functionID );
break;
case POP:
(pThreadInfo->m_pThreadCallStack)->Pop();
break;
}
}
else
_THROW_EXCEPTION( "Thread Structure was not found in the thread list" )
}
else
_THROW_EXCEPTION( "ICorProfilerInfo::GetCurrentThreadID() FAILED" )
} // PrfInfo::UpdateCallStack
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* public */
HRESULT PrfInfo::GetNameFromClassID( ClassID classID, WCHAR className[] )
{
HRESULT hr = E_FAIL;
if ( m_pProfilerInfo != NULL )
{
ModuleID moduleID;
mdTypeDef classToken;
hr = m_pProfilerInfo->GetClassIDInfo( classID,
&moduleID,
&classToken );
if ( SUCCEEDED( hr ) )
{
IMetaDataImport *pMDImport = NULL;
hr = m_pProfilerInfo->GetModuleMetaData( moduleID,
(ofRead | ofWrite),
IID_IMetaDataImport,
(IUnknown **)&pMDImport );
if ( SUCCEEDED( hr ) )
{
if ( classToken != mdTypeDefNil )
{
DWORD dwTypeDefFlags = 0;
hr = BASEHELPER::GetClassName(pMDImport, classToken, className);
if ( FAILED( hr ) )
Failure( "_GetClassNameHelper() FAILED" );
}
else
DEBUG_OUT( ("The class token is mdTypeDefNil, class does NOT have MetaData info") );
pMDImport->Release ();
}
else
{
// Failure( "IProfilerInfo::GetModuleMetaData() => IMetaDataImport FAILED" );
wcscpy(className, L"???");
hr = S_OK;
}
}
else
Failure( "ICorProfilerInfo::GetClassIDInfo() FAILED" );
}
else
Failure( "ICorProfilerInfo Interface has NOT been Initialized" );
return hr;
} // PrfHelper::GetNameFromClassID
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
/* private */
/* throws BaseException */
void PrfInfo::_GetFunctionSig( FunctionInfo **ppFunctionInfo )
{
HRESULT hr;
BOOL isStatic;
ULONG argCount;
WCHAR returnType[MAX_LENGTH];
WCHAR functionName[MAX_LENGTH];
WCHAR functionParameters[10 * MAX_LENGTH];
//
// init strings
//
returnType[0] = L'\0';
functionName[0] = L'\0';
functionParameters[0] = L'\0';
(*ppFunctionInfo)->m_functionSig[0] = L'\0';
// get the sig of the function and
// use utilcode to get the parameters you want
BASEHELPER::GetFunctionProperties( m_pProfilerInfo,
(*ppFunctionInfo)->m_id,
&isStatic,
&argCount,
returnType,
ARRAY_LEN(returnType),
functionParameters,
ARRAY_LEN(functionParameters),
functionName,
ARRAY_LEN(functionName));
const size_t sigLen = ARRAY_LEN((*ppFunctionInfo)->m_functionSig);
_snwprintf( (*ppFunctionInfo)->m_functionSig,
sigLen,
L"%s%s (%s)",
(isStatic ? L"static " : L""),
returnType,
functionParameters );
(*ppFunctionInfo)->m_functionSig[sigLen-1] = L'\0';
WCHAR *index = (*ppFunctionInfo)->m_functionSig;
while ( *index != L'\0' )
{
if ( *index == '+' )
*index = ' ';
index++;
}
//
// update the function name if it is not yet set
//
if ( wcsstr( (*ppFunctionInfo)->m_functionName, L"UNKNOWN" ) != NULL ) {
const size_t nameLen = ARRAY_LEN((*ppFunctionInfo)->m_functionName);
wcsncpy((*ppFunctionInfo)->m_functionName, functionName, nameLen );
(*ppFunctionInfo)->m_functionName[nameLen-1] = '\0';
}
} // PrfInfo::_GetFunctionSig
/***************************************************************************************
* Method:
*
*
* Purpose:
*
*
* Parameters:
*
*
* Return value:
*
*
* Notes:
*
***************************************************************************************/
void PrfInfo::Failure( char *message )
{
if ( message == NULL )
message = "**** SEVERE FAILURE: TURNING OFF APPLICABLE PROFILING EVENTS ****";
//
// Display the error message and discontinue monitoring CLR events, except the
// IMMUTABLE ones. Turning off the IMMUTABLE events can cause crashes. The only
// place that we can safely enable or disable immutable events is the Initialize
// callback.
//
TEXT_OUTLN( message )
m_pProfilerInfo->SetEventMask( (m_dwEventMask & (DWORD)COR_PRF_MONITOR_IMMUTABLE) );
} // PrfInfo::Failure
// end of file
| 22.594822 | 202 | 0.345918 | [
"object"
] |
c7e7e4c86cffe69ac058f6d4c9127a65ff149aca | 19,650 | cpp | C++ | src/d3d9/d3d9_presenter.cpp | doitsujin/d9vk | f2e9104a6008d0f121577a42cba41d78874b56c1 | [
"Zlib"
] | 7 | 2019-03-31T15:44:23.000Z | 2021-07-15T23:34:11.000Z | src/d3d9/d3d9_presenter.cpp | doitsujin/d9vk | f2e9104a6008d0f121577a42cba41d78874b56c1 | [
"Zlib"
] | null | null | null | src/d3d9/d3d9_presenter.cpp | doitsujin/d9vk | f2e9104a6008d0f121577a42cba41d78874b56c1 | [
"Zlib"
] | null | null | null | #include "d3d9_presenter.h"
#include "dxgi_presenter_frag.h"
#include "dxgi_presenter_vert.h"
namespace dxvk {
D3D9Presenter::D3D9Presenter(
Direct3DDevice9Ex* parent,
HWND window,
const D3D9PresenterDesc* desc,
DWORD gammaFlags,
const D3DGAMMARAMP* gammaRamp)
: m_parent ( parent )
, m_window ( window )
, m_device ( parent->GetDXVKDevice() )
, m_context ( m_device->createContext() )
, m_desc ( *desc ) {
createPresenter();
createBackBuffer();
createHud();
initRenderState();
initSamplers();
initShaders();
setGammaRamp(gammaFlags, gammaRamp);
}
void D3D9Presenter::setGammaRamp(
DWORD Flags,
const D3DGAMMARAMP* pRamp) {
std::array<D3D9_VK_GAMMA_CP, GammaPointCount> cp;
for (uint32_t i = 0; i < GammaPointCount; i++) {
cp[i].R = pRamp->red[i];
cp[i].G = pRamp->green[i];
cp[i].B = pRamp->blue[i];
cp[i].A = 0;
}
createGammaTexture(cp.data());
}
void D3D9Presenter::createGammaTexture(const D3D9_VK_GAMMA_CP* pControlPoints) {
if (m_gammaTexture == nullptr) {
DxvkImageCreateInfo imgInfo;
imgInfo.type = VK_IMAGE_TYPE_1D;
imgInfo.format = VK_FORMAT_R16G16B16A16_UNORM;
imgInfo.flags = 0;
imgInfo.sampleCount = VK_SAMPLE_COUNT_1_BIT;
imgInfo.extent = { GammaPointCount, 1, 1 };
imgInfo.numLayers = 1;
imgInfo.mipLevels = 1;
imgInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT
| VK_IMAGE_USAGE_SAMPLED_BIT;
imgInfo.stages = VK_PIPELINE_STAGE_TRANSFER_BIT
| VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
imgInfo.access = VK_ACCESS_TRANSFER_WRITE_BIT
| VK_ACCESS_SHADER_READ_BIT;
imgInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imgInfo.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_gammaTexture = m_device->createImage(
imgInfo, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
DxvkImageViewCreateInfo viewInfo;
viewInfo.type = VK_IMAGE_VIEW_TYPE_1D;
viewInfo.format = VK_FORMAT_R16G16B16A16_UNORM;
viewInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
viewInfo.aspect = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.minLevel = 0;
viewInfo.numLevels = 1;
viewInfo.minLayer = 0;
viewInfo.numLayers = 1;
m_gammaTextureView = m_device->createImageView(m_gammaTexture, viewInfo);
}
m_context->beginRecording(
m_device->createCommandList());
m_context->updateImage(m_gammaTexture,
VkImageSubresourceLayers{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
VkOffset3D{ 0, 0, 0 },
VkExtent3D{ GammaPointCount, 1, 1 },
pControlPoints, 0, 0);
m_device->submitCommandList(
m_context->endRecording(),
VK_NULL_HANDLE,
VK_NULL_HANDLE);
}
void D3D9Presenter::createBackBuffer() {
m_swapImage = nullptr;
m_swapImageResolve = nullptr;
m_swapImageView = nullptr;
m_backBuffer = nullptr;
D3D9TextureDesc desc;
desc.Depth = 1;
desc.Discard = FALSE;
desc.Format = m_desc.format;
desc.Height = std::max(1u, m_desc.height);
desc.Lockable = FALSE;
desc.MipLevels = 1;
desc.MultiSample = m_desc.multisample;
desc.MultisampleQuality = 0;
desc.Pool = D3DPOOL_DEFAULT;
desc.Type = D3DRTYPE_SURFACE;
desc.Usage = D3DUSAGE_RENDERTARGET;
desc.Width = std::max(1u, m_desc.width);
desc.Offscreen = FALSE;
m_backBuffer = new Direct3DCommonTexture9{ m_parent, &desc };
m_swapImage = m_backBuffer->GetImage();
// If the image is multisampled, we need to create
// another image which we'll use as a resolve target
if (m_swapImage->info().sampleCount != VK_SAMPLE_COUNT_1_BIT) {
DxvkImageCreateInfo resolveInfo;
resolveInfo.type = VK_IMAGE_TYPE_2D;
resolveInfo.format = m_swapImage->info().format;
resolveInfo.flags = 0;
resolveInfo.sampleCount = VK_SAMPLE_COUNT_1_BIT;
resolveInfo.extent = m_swapImage->info().extent;
resolveInfo.numLayers = 1;
resolveInfo.mipLevels = 1;
resolveInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT;
resolveInfo.stages = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT
| VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
| VK_PIPELINE_STAGE_TRANSFER_BIT;
resolveInfo.access = VK_ACCESS_SHADER_READ_BIT
| VK_ACCESS_TRANSFER_WRITE_BIT
| VK_ACCESS_COLOR_ATTACHMENT_READ_BIT
| VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
resolveInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
resolveInfo.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_swapImageResolve = m_device->createImage(
resolveInfo, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}
// Create an image view that allows the
// image to be bound as a shader resource.
DxvkImageViewCreateInfo viewInfo;
viewInfo.type = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = m_swapImage->info().format;
viewInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
viewInfo.aspect = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.minLevel = 0;
viewInfo.numLevels = 1;
viewInfo.minLayer = 0;
viewInfo.numLayers = 1;
m_swapImageView = m_device->createImageView(
m_swapImageResolve != nullptr
? m_swapImageResolve
: m_swapImage,
viewInfo);
// Initialize the image so that we can use it. Clearing
// to black prevents garbled output for the first frame.
VkImageSubresourceRange subresources;
subresources.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresources.baseMipLevel = 0;
subresources.levelCount = 1;
subresources.baseArrayLayer = 0;
subresources.layerCount = 1;
VkClearColorValue clearColor;
clearColor.float32[0] = 0.0f;
clearColor.float32[1] = 0.0f;
clearColor.float32[2] = 0.0f;
clearColor.float32[3] = 0.0f;
m_context->beginRecording(
m_device->createCommandList());
m_context->clearColorImage(
m_swapImage, clearColor, subresources);
m_device->submitCommandList(
m_context->endRecording(),
VK_NULL_HANDLE,
VK_NULL_HANDLE);
}
void D3D9Presenter::createHud() {
m_hud = hud::Hud::createHud(m_device);
}
void D3D9Presenter::initRenderState() {
m_iaState.primitiveTopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
m_iaState.primitiveRestart = VK_FALSE;
m_iaState.patchVertexCount = 0;
m_rsState.polygonMode = VK_POLYGON_MODE_FILL;
m_rsState.cullMode = VK_CULL_MODE_BACK_BIT;
m_rsState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
m_rsState.depthClipEnable = VK_FALSE;
m_rsState.depthBiasEnable = VK_FALSE;
m_rsState.sampleCount = VK_SAMPLE_COUNT_1_BIT;
m_msState.sampleMask = 0xffffffff;
m_msState.enableAlphaToCoverage = VK_FALSE;
m_msState.enableAlphaToOne = VK_FALSE;
VkStencilOpState stencilOp;
stencilOp.failOp = VK_STENCIL_OP_KEEP;
stencilOp.passOp = VK_STENCIL_OP_KEEP;
stencilOp.depthFailOp = VK_STENCIL_OP_KEEP;
stencilOp.compareOp = VK_COMPARE_OP_ALWAYS;
stencilOp.compareMask = 0xFFFFFFFF;
stencilOp.writeMask = 0xFFFFFFFF;
stencilOp.reference = 0;
m_dsState.enableDepthTest = VK_FALSE;
m_dsState.enableDepthWrite = VK_FALSE;
m_dsState.enableStencilTest = VK_FALSE;
m_dsState.depthCompareOp = VK_COMPARE_OP_ALWAYS;
m_dsState.stencilOpFront = stencilOp;
m_dsState.stencilOpBack = stencilOp;
m_loState.enableLogicOp = VK_FALSE;
m_loState.logicOp = VK_LOGIC_OP_NO_OP;
m_blendMode.enableBlending = VK_FALSE;
m_blendMode.colorSrcFactor = VK_BLEND_FACTOR_ONE;
m_blendMode.colorDstFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
m_blendMode.colorBlendOp = VK_BLEND_OP_ADD;
m_blendMode.alphaSrcFactor = VK_BLEND_FACTOR_ONE;
m_blendMode.alphaDstFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
m_blendMode.alphaBlendOp = VK_BLEND_OP_ADD;
m_blendMode.writeMask = VK_COLOR_COMPONENT_R_BIT
| VK_COLOR_COMPONENT_G_BIT
| VK_COLOR_COMPONENT_B_BIT
| VK_COLOR_COMPONENT_A_BIT;
}
void D3D9Presenter::initSamplers() {
DxvkSamplerCreateInfo samplerInfo;
samplerInfo.magFilter = VK_FILTER_NEAREST;
samplerInfo.minFilter = VK_FILTER_NEAREST;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
samplerInfo.mipmapLodBias = 0.0f;
samplerInfo.mipmapLodMin = 0.0f;
samplerInfo.mipmapLodMax = 0.0f;
samplerInfo.useAnisotropy = VK_FALSE;
samplerInfo.maxAnisotropy = 1.0f;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.compareToDepth = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.borderColor = VkClearColorValue();
samplerInfo.usePixelCoord = VK_FALSE;
m_samplerFitting = m_device->createSampler(samplerInfo);
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
m_samplerScaling = m_device->createSampler(samplerInfo);
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
m_gammaSampler = m_device->createSampler(samplerInfo);
}
void D3D9Presenter::initShaders() {
const SpirvCodeBuffer vsCode(dxgi_presenter_vert);
const SpirvCodeBuffer fsCode(dxgi_presenter_frag);
const std::array<DxvkResourceSlot, 4> fsResourceSlots = { {
{ BindingIds::Sampler, VK_DESCRIPTOR_TYPE_SAMPLER, VK_IMAGE_VIEW_TYPE_MAX_ENUM },
{ BindingIds::Texture, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_IMAGE_VIEW_TYPE_2D },
{ BindingIds::GammaSmp, VK_DESCRIPTOR_TYPE_SAMPLER, VK_IMAGE_VIEW_TYPE_MAX_ENUM },
{ BindingIds::GammaTex, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_IMAGE_VIEW_TYPE_1D },
} };
m_vertShader = m_device->createShader(
VK_SHADER_STAGE_VERTEX_BIT,
0, nullptr, { 0u, 1u },
vsCode);
m_fragShader = m_device->createShader(
VK_SHADER_STAGE_FRAGMENT_BIT,
fsResourceSlots.size(),
fsResourceSlots.data(),
{ 1u, 1u }, fsCode);
}
void D3D9Presenter::recreateSwapChain(const D3D9PresenterDesc* desc) {
m_desc = *desc;
vk::PresenterDesc presenterDesc;
presenterDesc.imageExtent = { m_desc.width, m_desc.height };
presenterDesc.imageCount = pickImageCount(m_desc.bufferCount);
presenterDesc.numFormats = pickFormats(m_desc.format, presenterDesc.formats);
presenterDesc.numPresentModes = pickPresentModes(m_desc.presentInterval != 0, presenterDesc.presentModes);
if (m_presenter->recreateSwapChain(presenterDesc) != VK_SUCCESS)
throw DxvkError("D3D9Presenter: Failed to recreate swap chain");
createRenderTargetViews();
}
void D3D9Presenter::present() {
// Wait for the sync event so that we
// respect the maximum frame latency
Rc<DxvkEvent> syncEvent = m_parent->GetFrameSyncEvent();
syncEvent->wait();
if (m_hud != nullptr)
m_hud->update();
for (uint32_t i = 0; i < m_desc.presentInterval || i < 1; i++) {
m_context->beginRecording(
m_device->createCommandList());
// Resolve back buffer if it is multisampled. We
// only have to do it only for the first frame.
if (m_swapImageResolve != nullptr && i == 0) {
VkImageSubresourceLayers resolveSubresources;
resolveSubresources.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
resolveSubresources.mipLevel = 0;
resolveSubresources.baseArrayLayer = 0;
resolveSubresources.layerCount = 1;
m_context->resolveImage(
m_swapImageResolve, resolveSubresources,
m_swapImage, resolveSubresources,
VK_FORMAT_UNDEFINED);
}
// Presentation semaphores and WSI swap chain image
vk::PresenterInfo info = m_presenter->info();
vk::PresenterSync sync = m_presenter->getSyncSemaphores();
uint32_t imageIndex = 0;
VkResult status = m_presenter->acquireNextImage(
sync.acquire, sync.fence, imageIndex);
while (status != VK_SUCCESS && status != VK_SUBOPTIMAL_KHR) {
recreateSwapChain(&m_desc);
info = m_presenter->info();
sync = m_presenter->getSyncSemaphores();
status = m_presenter->acquireNextImage(
sync.acquire, sync.fence, imageIndex);
}
// Wait for image to become actually available
m_presenter->waitForFence(sync.fence);
// Use an appropriate texture filter depending on whether
// the back buffer size matches the swap image size
bool fitSize = m_swapImage->info().extent.width == info.imageExtent.width
&& m_swapImage->info().extent.height == info.imageExtent.height;
m_context->bindShader(VK_SHADER_STAGE_VERTEX_BIT, m_vertShader);
m_context->bindShader(VK_SHADER_STAGE_FRAGMENT_BIT, m_fragShader);
DxvkRenderTargets renderTargets;
renderTargets.color[0].view = m_imageViews.at(imageIndex);
renderTargets.color[0].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
m_context->bindRenderTargets(renderTargets, false);
VkViewport viewport;
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = float(info.imageExtent.width);
viewport.height = float(info.imageExtent.height);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor;
scissor.offset.x = 0;
scissor.offset.y = 0;
scissor.extent.width = info.imageExtent.width;
scissor.extent.height = info.imageExtent.height;
m_context->setViewports(1, &viewport, &scissor);
m_context->setRasterizerState(m_rsState);
m_context->setMultisampleState(m_msState);
m_context->setDepthStencilState(m_dsState);
m_context->setLogicOpState(m_loState);
m_context->setBlendMode(0, m_blendMode);
m_context->setInputAssemblyState(m_iaState);
m_context->setInputLayout(0, nullptr, 0, nullptr);
m_context->bindResourceSampler(BindingIds::Sampler, fitSize ? m_samplerFitting : m_samplerScaling);
m_context->bindResourceSampler(BindingIds::GammaSmp, m_gammaSampler);
m_context->bindResourceView(BindingIds::Texture, m_swapImageView, nullptr);
m_context->bindResourceView(BindingIds::GammaTex, m_gammaTextureView, nullptr);
m_context->draw(4, 1, 0, 0);
if (m_hud != nullptr)
m_hud->render(m_context, info.imageExtent);
if (i + 1 >= m_desc.presentInterval) {
DxvkEventRevision eventRev;
eventRev.event = syncEvent;
eventRev.revision = syncEvent->reset();
m_context->signalEvent(eventRev);
}
m_device->submitCommandList(
m_context->endRecording(),
sync.acquire, sync.present);
status = m_device->presentImage(
m_presenter, sync.present);
if (status != VK_SUCCESS)
recreateSwapChain(&m_desc);
}
}
VkFormat D3D9Presenter::makeSrgb(VkFormat format) {
switch (format) {
case VK_FORMAT_R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_SRGB;
case VK_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_SRGB;
default: return format; // TODO: make this srgb-ness more correct.
}
}
uint32_t D3D9Presenter::pickFormats(
D3D9Format format,
VkSurfaceFormatKHR* dstFormats) {
uint32_t n = 0;
switch (format) {
default:
Logger::warn(str::format("D3D9Presenter: Unexpected format: ", format));
case D3D9Format::A8R8G8B8:
case D3D9Format::X8R8G8B8:
case D3D9Format::A8B8G8R8:
case D3D9Format::X8B8G8R8: {
dstFormats[n++] = { VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
dstFormats[n++] = { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
} break;
case D3D9Format::A2R10G10B10:
case D3D9Format::A2B10G10R10: {
dstFormats[n++] = { VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
dstFormats[n++] = { VK_FORMAT_A2R10G10B10_UNORM_PACK32, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
} break;
case D3D9Format::X1R5G5B5:
case D3D9Format::A1R5G5B5: {
dstFormats[n++] = { VK_FORMAT_B5G5R5A1_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
dstFormats[n++] = { VK_FORMAT_R5G5B5A1_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
dstFormats[n++] = { VK_FORMAT_A1R5G5B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
}
case D3D9Format::R5G6B5: {
dstFormats[n++] = { VK_FORMAT_B5G6R5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
dstFormats[n++] = { VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
}
}
return n;
}
uint32_t D3D9Presenter::pickPresentModes(
bool vsync,
VkPresentModeKHR* dstModes) {
uint32_t n = 0;
if (vsync) {
dstModes[n++] = VK_PRESENT_MODE_FIFO_KHR;
}
else {
dstModes[n++] = VK_PRESENT_MODE_IMMEDIATE_KHR;
dstModes[n++] = VK_PRESENT_MODE_MAILBOX_KHR;
dstModes[n++] = VK_PRESENT_MODE_FIFO_RELAXED_KHR;
}
return n;
}
uint32_t D3D9Presenter::pickImageCount(
uint32_t preferred) {
return preferred;
}
void D3D9Presenter::createPresenter() {
DxvkDeviceQueue graphicsQueue = m_device->graphicsQueue();
vk::PresenterDevice presenterDevice;
presenterDevice.queueFamily = graphicsQueue.queueFamily;
presenterDevice.queue = graphicsQueue.queueHandle;
presenterDevice.adapter = m_device->adapter()->handle();
vk::PresenterDesc presenterDesc;
presenterDesc.imageExtent = { m_desc.width, m_desc.height };
presenterDesc.imageCount = pickImageCount(m_desc.bufferCount);
presenterDesc.numFormats = pickFormats(m_desc.format, presenterDesc.formats);
presenterDesc.numPresentModes = pickPresentModes(m_desc.presentInterval != 0, presenterDesc.presentModes);
m_presenter = new vk::Presenter(m_window,
m_device->adapter()->vki(),
m_device->vkd(),
presenterDevice,
presenterDesc);
createRenderTargetViews();
}
void D3D9Presenter::createRenderTargetViews() {
vk::PresenterInfo info = m_presenter->info();
m_imageViews.clear();
m_imageViews.resize(info.imageCount);
DxvkImageCreateInfo imageInfo;
imageInfo.type = VK_IMAGE_TYPE_2D;
imageInfo.format = info.format.format;
imageInfo.sampleCount = VK_SAMPLE_COUNT_1_BIT;
imageInfo.extent = { info.imageExtent.width, info.imageExtent.height, 1 };
imageInfo.numLayers = 1;
imageInfo.mipLevels = 1;
imageInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
imageInfo.stages = 0;
imageInfo.access = 0;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
imageInfo.flags = 0;
DxvkImageViewCreateInfo viewInfo;
viewInfo.type = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = info.format.format;
viewInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
viewInfo.aspect = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.minLevel = 0;
viewInfo.numLevels = 1;
viewInfo.minLayer = 0;
viewInfo.numLayers = 1;
for (uint32_t i = 0; i < info.imageCount; i++) {
VkImage imageHandle = m_presenter->getImage(i).image;
Rc<DxvkImage> image = new DxvkImage(
m_device->vkd(), imageInfo, imageHandle);
m_imageViews[i] = new DxvkImageView(
m_device->vkd(), image, viewInfo);
}
}
} | 34.656085 | 110 | 0.707837 | [
"render"
] |
c7e85daeb8d2fa9df1c828005a1255fc408c3745 | 2,484 | cpp | C++ | src/Renderer/CarRenderer.cpp | AmrikSadhra/FCE-To-Obj | a3c928077add2bd5d5f3463daee6008f150a0a54 | [
"MIT"
] | 212 | 2019-08-10T16:57:57.000Z | 2022-03-30T02:21:05.000Z | src/Renderer/CarRenderer.cpp | AmrikSadhra/FCE-To-Obj | a3c928077add2bd5d5f3463daee6008f150a0a54 | [
"MIT"
] | 11 | 2018-07-10T18:01:09.000Z | 2019-06-26T13:41:24.000Z | src/Renderer/CarRenderer.cpp | AmrikSadhra/FCE-to-OBJ | a3c928077add2bd5d5f3463daee6008f150a0a54 | [
"MIT"
] | 20 | 2020-02-09T02:38:35.000Z | 2022-03-23T20:26:28.000Z | #include "CarRenderer.h"
void CarRenderer::Render(const shared_ptr<Car> &car, const std::shared_ptr<BaseCamera> &camera, const std::vector<std::shared_ptr<BaseLight>> &lights)
{
m_carShader.use();
// This shader state doesnt change during a car renderpass
m_carShader.loadProjectionViewMatrices(camera->projectionMatrix, camera->viewMatrix);
m_carShader.setPolyFlagged(car->carBodyModel.hasPolyFlags);
m_carShader.loadCarColor(glm::vec3(1, 1, 1));
m_carShader.loadLights(lights);
m_carShader.loadEnvironmentMapTexture();
// Check if we're texturing the car from multiple textures, if we are, let the shader know with a uniform and bind texture array
m_carShader.setMultiTextured(car->renderInfo.isMultitexturedModel);
if (car->renderInfo.isMultitexturedModel)
{
m_carShader.bindTextureArray(car->renderInfo.textureArrayID);
}
else
{
m_carShader.loadCarTexture(car->renderInfo.textureID);
}
// Render the Car models
for (auto &misc_model : car->miscModels)
{
m_carShader.loadTransformationMatrix(misc_model.ModelMatrix);
m_carShader.loadSpecular(misc_model.specularDamper, 0, 0);
misc_model.render();
}
m_carShader.loadTransformationMatrix(car->leftFrontWheelModel.ModelMatrix);
m_carShader.loadSpecular(car->leftFrontWheelModel.specularDamper, 0, 0);
car->leftFrontWheelModel.render();
m_carShader.loadTransformationMatrix(car->leftRearWheelModel.ModelMatrix);
m_carShader.loadSpecular(car->leftRearWheelModel.specularDamper, 0, 0);
car->leftRearWheelModel.render();
m_carShader.loadTransformationMatrix(car->rightFrontWheelModel.ModelMatrix);
m_carShader.loadSpecular(car->rightFrontWheelModel.specularDamper, 0, 0);
car->rightFrontWheelModel.render();
m_carShader.loadTransformationMatrix(car->rightRearWheelModel.ModelMatrix);
m_carShader.loadSpecular(car->rightRearWheelModel.specularDamper, 0, 0);
car->rightRearWheelModel.render();
m_carShader.loadTransformationMatrix(car->carBodyModel.ModelMatrix);
m_carShader.loadSpecular(car->carBodyModel.specularDamper, car->carBodyModel.specularReflectivity, car->carBodyModel.envReflectivity);
m_carShader.loadCarColor(car->vehicleProperties.colour); // The colour should only apply to the car body
car->carBodyModel.render();
m_carShader.unbind();
}
CarRenderer::~CarRenderer()
{
// Cleanup VBOs and shaders
m_carShader.cleanup();
}
| 40.721311 | 150 | 0.756844 | [
"render",
"vector"
] |
c7ec4a118b24752b87189c9c43c479ccd57f205e | 9,888 | cpp | C++ | pj_adc_fft/Main.cpp | iwatake2222/pico-work | b403521f3ebdfcdb9cf31811dadedde777d44cb7 | [
"Apache-2.0"
] | 12 | 2021-04-01T13:08:14.000Z | 2021-11-27T22:49:53.000Z | pj_adc_fft/Main.cpp | iwatake2222/pico-work | b403521f3ebdfcdb9cf31811dadedde777d44cb7 | [
"Apache-2.0"
] | 2 | 2021-04-03T17:26:38.000Z | 2021-04-10T14:25:26.000Z | pj_adc_fft/Main.cpp | iwatake2222/pico-work | b403521f3ebdfcdb9cf31811dadedde777d44cb7 | [
"Apache-2.0"
] | 3 | 2021-02-20T08:36:23.000Z | 2021-11-15T09:28:24.000Z | #include <cstdint>
#include <cstdio>
#define _USE_MATH_DEFINES
#include <cmath>
#include <cstdlib>
#include <cstring>
#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "LcdIli9341SPI.h"
#include "TpTsc2046SPI.h"
#include "AdcBuffer.h"
#include "RingBuffer.h"
/*** CONST VALUE ***/
static constexpr std::array<uint8_t, 2> COLOR_BG = { 0x00, 0x00 };
static constexpr std::array<uint8_t, 2> COLOR_LINE = { 0xF8, 0x00 };
static constexpr std::array<uint8_t, 2> COLOR_LINE_FFT = { 0x00, 0x1F };
static constexpr int32_t SCALE = 1;
static constexpr int32_t SCALE_FFT = 8;
static constexpr int32_t BUFFER_SIZE = 512; // 2^x
static constexpr int32_t SAMPLING_RATE = 10000;
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
static constexpr int32_t MIN_ADC_BUFFER_SIZE = MIN(4, AdcBuffer::BUFFER_NUM);
/*** MACRO ***/
#ifndef BUILD_ON_PC
#define HALT() do{while(1) sleep_ms(100);}while(0)
#define PRINT_TIME() do{printf("TIME: %d [ms]\n", to_ms_since_boot(get_absolute_time()));}while(0)
#else
#define HALT() do{}while(0)
#define PRINT_TIME() do{}while(0)
#endif
/*** FUNCTION ***/
static void core1_main();
static LcdIli9341SPI& createStaticLcd(void);
static TpTsc2046SPI& createStaticTp(void);
static AdcBuffer& createStaticAdcBuffer(void);
static void reset(LcdIli9341SPI& lcd);
static bool displayWave(AdcBuffer& adcBuffer, LcdIli9341SPI& lcd);
static void displayFft(LcdIli9341SPI& lcd);
static void displayTime(LcdIli9341SPI& lcd, bool isSkipDisplay, uint32_t core0, uint32_t core1);
static void switchMultiCore(TpTsc2046SPI& tp);
/*** GLOBAL VARIABLE ***/
AdcBuffer* g_adcBuffer;
RingBuffer<float> g_fftResultList;
static int32_t g_timeFFT = 0; // [msec]
static bool g_multiCore = true;
int main() {
/*** Initilization ***/
/* Initialize system */
stdio_init_all();
sleep_ms(1000); // wait until UART connected
printf("Hello, world!\n");
/* Initialize device */
LcdIli9341SPI& lcd = createStaticLcd();
TpTsc2046SPI& tp = createStaticTp();
AdcBuffer& adcBuffer = createStaticAdcBuffer();
g_adcBuffer = &adcBuffer;
reset(lcd);
/* Prepare core1 for FFT */
g_fftResultList.initialize(3, BUFFER_SIZE / 2);
if (g_multiCore) {
multicore_launch_core1(core1_main);
}
/*** Main loop ***/
adcBuffer.start();
while(1) {
uint32_t t0 = to_ms_since_boot(get_absolute_time());
bool isSkipDisplay = displayWave(adcBuffer, lcd);
displayFft(lcd);
if (!g_multiCore) {
core1_main();
}
uint32_t t1 = to_ms_since_boot(get_absolute_time());
displayTime(lcd, isSkipDisplay, t1 - t0, g_timeFFT);
switchMultiCore(tp);
}
/*** Finalization ***/
adcBuffer.stop();
adcBuffer.finalize();
lcd.finalize();
tp.finalize();
return 0;
}
static LcdIli9341SPI& createStaticLcd(void)
{
static LcdIli9341SPI lcd;
LcdIli9341SPI::CONFIG lcdConfig;
lcdConfig.spiPortNum = 0;
lcdConfig.pinSck = 2;
lcdConfig.pinMosi = 3;
lcdConfig.pinMiso = 4;
lcdConfig.pinCs = 5;
lcdConfig.pinDc = 7;
lcdConfig.pinReset = 6;
lcd.initialize(lcdConfig);
lcd.test();
return lcd;
}
static TpTsc2046SPI& createStaticTp(void)
{
static TpTsc2046SPI tp;
TpTsc2046SPI::CONFIG tpConfig;
tpConfig.spiPortNum = 1;
tpConfig.pinSck = 10;
tpConfig.pinMosi = 11;
tpConfig.pinMiso = 12;
tpConfig.pinCs = 13;
tpConfig.pinIrq = 14;
tpConfig.callback = nullptr;
tp.initialize(tpConfig);
return tp;
}
static AdcBuffer& createStaticAdcBuffer(void)
{
static AdcBuffer adcBuffer;
AdcBuffer::CONFIG adcConfig;
adcConfig.captureChannel = 0;
// adcConfig.captureDepth = LcdIli9341SPI::WIDTH;
adcConfig.captureDepth = BUFFER_SIZE;
adcConfig.samplingRate = SAMPLING_RATE;
adcBuffer.initialize(adcConfig);
return adcBuffer;
}
static void reset(LcdIli9341SPI& lcd)
{
std::array<uint8_t, 2> colorBg = { 0x00, 0x1F };
lcd.drawRect(0, 0, LcdIli9341SPI::WIDTH, LcdIli9341SPI::HEIGHT, COLOR_BG);
lcd.setCharPos(0, 0);
}
static bool displayWave(AdcBuffer& adcBuffer, LcdIli9341SPI& lcd)
{
/*
n Frame n + 1
buff[0] RP, LINE(PREVIOUS)
buff[1] LINE(NEW) RP LINE(PREVIOUS)
buff[2] ADC is writing to this buff LINE(NEW)
buff[3] WP ADC is writing to this buff(this buff is not valid yet)
buff[4] WP
*/
if (adcBuffer.getBufferSize() >= MIN_ADC_BUFFER_SIZE) {
auto& adcBufferPrevious = adcBuffer.getBuffer(0);
auto& adcBufferLatest = adcBuffer.getBuffer(1);
const float scale = 1 / 256.0 * SCALE * LcdIli9341SPI::HEIGHT;
const float offset = - 0.5 * SCALE * LcdIli9341SPI::HEIGHT + LcdIli9341SPI::HEIGHT / 2 - 50;
/* Delete previous line */
for (int32_t i = 1; i < std::min(LcdIli9341SPI::WIDTH, (int32_t)adcBufferPrevious.size()); i++) {
// lcd.drawRect(i, (adcBufferPrevious[i] / 256.0 - 0.5) * SCALE * LcdIli9341SPI::HEIGHT + LcdIli9341SPI::HEIGHT / 2, 2, 2, COLOR_BG);
lcd.drawLine(
i - 1, adcBufferPrevious[i - 1] * scale + offset,
i, adcBufferPrevious[i] * scale + offset + 1,
2, COLOR_BG);
}
/* Draw new line */
for (int32_t i = 1; i < std::min(LcdIli9341SPI::WIDTH, (int32_t)adcBufferPrevious.size()); i++) {
// lcd.drawRect(i, (adcBufferLatest[i] / 256.0 - 0.5) * SCALE * LcdIli9341SPI::HEIGHT + LcdIli9341SPI::HEIGHT / 2, 2, 2, COLOR_LINE);
lcd.drawLine(
i - 1, adcBufferLatest[i - 1] * scale + offset,
i, adcBufferLatest[i] * scale + offset + 1,
2, COLOR_LINE);
}
adcBuffer.deleteFront();
return false;
} else {
// printf("displayWave: underflow\n");
sleep_ms(1);
return true;
}
}
static void displayFft(LcdIli9341SPI& lcd)
{
if (g_fftResultList.getStoredDataNum() >= 3) {
auto& fftPrevious = g_fftResultList.refer(0);
auto& fftLatest = g_fftResultList.refer(1);
/* Delete previous line */
for (int32_t i = 1; i < fftPrevious.size(); i++) {
// lcd.drawRect(LcdIli9341SPI::WIDTH - i, fftPrevious[i] * LcdIli9341SPI::HEIGHT, 2, 2, COLOR_BG);
lcd.drawLine(
i - 1, LcdIli9341SPI::HEIGHT * (1 - fftPrevious[i - 1]),
i, LcdIli9341SPI::HEIGHT * (1 - fftPrevious[i]) + 1,
2, COLOR_BG);
}
/* Draw new line */
for (int32_t i = 1; i < fftLatest.size(); i++) {
// lcd.drawRect(LcdIli9341SPI::WIDTH - i, fftLatest[i] * LcdIli9341SPI::HEIGHT, 2, 2, COLOR_LINE);
lcd.drawLine(
i - 1, LcdIli9341SPI::HEIGHT * (1 - fftLatest[i - 1]),
i, LcdIli9341SPI::HEIGHT * (1 - fftLatest[i]) + 1,
2, COLOR_LINE_FFT);
}
(void)g_fftResultList.read();
} else {
// printf("displayFft: underflow\n");
}
}
static void displayTime(LcdIli9341SPI& lcd, bool isSkipDisplay, uint32_t core0, uint32_t core1)
{
// printf("Time[ms]: main = %d, FFT = %d [ms]\n", core0, core1);
if (!isSkipDisplay) {
lcd.setCharPos(120, 160);
if (g_multiCore) {
lcd.putText("Dual Core");
} else {
lcd.putText("Single Core");
}
char text[20];
snprintf(text, sizeof(text), "Sa = %d kHz", SAMPLING_RATE / 1000);
lcd.setCharPos(120, 180);
lcd.putText(text);
snprintf(text, sizeof(text), "Main(UI) = %d ms", core0);
lcd.setCharPos(120, 200);
lcd.putText(text);
snprintf(text, sizeof(text), "FFT = %d ms", core1);
lcd.setCharPos(120, 220);
lcd.putText(text);
}
}
static void switchMultiCore(TpTsc2046SPI& tp)
{
float tpX, tpY, tpPressure;
tp.getFromDevice(tpX, tpY, tpPressure);
if (tpPressure > 50) {
static uint32_t s_previousTpCheckTime = 0;
if (to_ms_since_boot(get_absolute_time()) - s_previousTpCheckTime > 1000) {
if (g_multiCore) {
g_multiCore = false;
multicore_reset_core1();
g_fftResultList.initialize(3, BUFFER_SIZE / 2);
} else {
g_multiCore = true;
multicore_launch_core1(core1_main);
}
s_previousTpCheckTime = to_ms_since_boot(get_absolute_time());
}
}
}
extern int fft(int n, float x[], float y[]);
static double hammingWindow(double x)
{
double val = 0.54 - 0.46 * std::cos(2 * M_PI * x);
return val;
}
static void core1_main()
{
if (g_multiCore) {
printf("Hello, core1!\n");
}
#if 0
/* test FFT*/
#define N 256
static float x[N], y[N];
for(int32_t i = 0; i < N; i++){
x[i] = std::sin((1.0 * i * 100) / N * 2 * M_PI);
x[i] *= hammingWindow((double)(i)/N);
y[i] = 0;
}
if (fft(N, x, y)) {
printf("error\n");
}
for (int32_t i = 0; i < N / 2; i++){
double p = sqrt(x[i] * x[i] + y[i] * y[i]);
printf("%d: %.03f %.03f %.03f\n",i, p, x[i], y[i]); // power real-part imaginary-part
}
while(1) {
sleep_ms(100);
}
#else
static std::vector<float> x(BUFFER_SIZE);
static std::vector<float> y(BUFFER_SIZE);
while(1) {
uint32_t t0 = to_ms_since_boot(get_absolute_time());
if (g_adcBuffer->getBufferSize() >= MIN_ADC_BUFFER_SIZE - 1) { // do not use "MIN_ADC_BUFFER_SIZE" because the main thread may pop the buffer
auto& data = g_adcBuffer->getBuffer(1); // do not use RP because the RP may be increased by main thread and overwritten by ADC
for (int32_t i = 0; i < x.size(); i++) {
x[i] = (data[i] / 256.0 - 0.5) * 2; // -1 ~ +1
x[i] *= SCALE_FFT;
x[i] *= hammingWindow((double)(i) / x.size());
}
for (int32_t i = 0; i < y.size(); i++) y[i] = 0;
float* resultBuffer = g_fftResultList.writePtr();
if (!resultBuffer) {
// printf("core1_main: overflow\n");
resultBuffer = g_fftResultList.getLatestWritePtr();
}
(void)fft(x.size(), x.data(), y.data());
for (int32_t i = 0; i < BUFFER_SIZE / 2; i++){
resultBuffer[i] = std::sqrt(x[i] * x[i] + y[i] * y[i]);
}
} else {
sleep_ms(1);
}
uint32_t t1 = to_ms_since_boot(get_absolute_time());
g_timeFFT = t1 - t0;
if (!g_multiCore) {
break;
}
}
#endif
}
| 29.428571 | 145 | 0.638147 | [
"vector"
] |
c7fd41e085da0c05379e97241c67746e07be802e | 3,780 | cc | C++ | vpc/src/model/UnTagResourcesRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | vpc/src/model/UnTagResourcesRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | vpc/src/model/UnTagResourcesRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/vpc/model/UnTagResourcesRequest.h>
using AlibabaCloud::Vpc::Model::UnTagResourcesRequest;
UnTagResourcesRequest::UnTagResourcesRequest() :
RpcServiceRequest("vpc", "2016-04-28", "UnTagResources")
{
setMethod(HttpRequest::Method::Post);
}
UnTagResourcesRequest::~UnTagResourcesRequest()
{}
long UnTagResourcesRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void UnTagResourcesRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string UnTagResourcesRequest::getRegionId()const
{
return regionId_;
}
void UnTagResourcesRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
std::vector<UnTagResourcesRequest::Tag> UnTagResourcesRequest::getTag()const
{
return tag_;
}
void UnTagResourcesRequest::setTag(const std::vector<Tag>& tag)
{
tag_ = tag;
for(int dep1 = 0; dep1!= tag.size(); dep1++) {
auto tagObj = tag.at(dep1);
std::string tagObjStr = "Tag." + std::to_string(dep1 + 1);
setParameter(tagObjStr + ".Value", tagObj.value);
setParameter(tagObjStr + ".Key", tagObj.key);
}
}
bool UnTagResourcesRequest::getAll()const
{
return all_;
}
void UnTagResourcesRequest::setAll(bool all)
{
all_ = all;
setParameter("All", all ? "true" : "false");
}
std::vector<std::string> UnTagResourcesRequest::getResourceId()const
{
return resourceId_;
}
void UnTagResourcesRequest::setResourceId(const std::vector<std::string>& resourceId)
{
resourceId_ = resourceId;
for(int dep1 = 0; dep1!= resourceId.size(); dep1++) {
setParameter("ResourceId."+ std::to_string(dep1), resourceId.at(dep1));
}
}
std::string UnTagResourcesRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void UnTagResourcesRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string UnTagResourcesRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void UnTagResourcesRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
long UnTagResourcesRequest::getOwnerId()const
{
return ownerId_;
}
void UnTagResourcesRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string UnTagResourcesRequest::getResourceType()const
{
return resourceType_;
}
void UnTagResourcesRequest::setResourceType(const std::string& resourceType)
{
resourceType_ = resourceType;
setParameter("ResourceType", resourceType);
}
std::vector<std::string> UnTagResourcesRequest::getTagKey()const
{
return tagKey_;
}
void UnTagResourcesRequest::setTagKey(const std::vector<std::string>& tagKey)
{
tagKey_ = tagKey;
for(int dep1 = 0; dep1!= tagKey.size(); dep1++) {
setParameter("TagKey."+ std::to_string(dep1), tagKey.at(dep1));
}
}
| 25.369128 | 93 | 0.733598 | [
"vector",
"model"
] |
c7fde69ee083bfc33404ab4939ebc0343379a9d9 | 894 | cpp | C++ | Baekjoon/6000~6999/6549.cpp | Lee-Siwon/Problem-Solving | e3414067c848f2c676865ef88d68e408344f439a | [
"Unlicense"
] | null | null | null | Baekjoon/6000~6999/6549.cpp | Lee-Siwon/Problem-Solving | e3414067c848f2c676865ef88d68e408344f439a | [
"Unlicense"
] | null | null | null | Baekjoon/6000~6999/6549.cpp | Lee-Siwon/Problem-Solving | e3414067c848f2c676865ef88d68e408344f439a | [
"Unlicense"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<vector>
#include<cmath>
#include<string>
#include<stack>
#include<stdio.h>
using namespace std;
void init(){
}
void solve(int n){
vector<long long> x;
for(int i=0;i<n;i++){
long long a;
cin>>a;
x.push_back(a);
}
x.push_back(-1);
stack<pair<int,long long> >st;
long long answer=0;
for(int i=0;i<=n;i++){
int num=i;
while(st.size()&&(x[i]<(st.size()?st.top().second:0))){
int a = st.top().first;
num=a;
long long b = st.top().second;
st.pop();
answer = max(answer,(i*1ll-a)*b);
}
st.push({num,x[i]});
}
cout<<answer;
return;
}
int main(){
int t;
ios_base::sync_with_stdio(false);
cin.tie(NULL);
t=100000000;
// cin>>t;
for(int i=0;i<t;i++){
// cout<<"Case #"<<i+1<<"\n";
int n;
cin>>n;
if(n==0)return 0;
solve(n);
cout<<"\n";
}
}
| 16.254545 | 58 | 0.542506 | [
"vector"
] |
2a0addf0838e07aeb1922f77c96968f707192b69 | 32,580 | cpp | C++ | src/server/ServerCommands.cpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | 3 | 2022-01-21T10:38:06.000Z | 2022-02-01T16:44:46.000Z | src/server/ServerCommands.cpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | null | null | null | src/server/ServerCommands.cpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | null | null | null | // automatically converted
#include "ServerCommands.hpp"
#include "BanSystem.hpp"
#include "Server.hpp"
#include "ServerHelper.hpp"
#include "common/misc/PortUtilsSoldat.hpp"
#include "shared/Command.hpp"
#include "shared/Demo.hpp"
#include "shared/Game.hpp"
#include "shared/mechanics/SpriteSystem.hpp"
#include "shared/misc/GlobalSystems.hpp"
#include "shared/network/NetworkServer.hpp"
#include "shared/network/NetworkServerConnection.hpp"
#include "shared/network/NetworkServerFunctions.hpp"
#include "shared/network/NetworkServerGame.hpp"
#include "shared/network/NetworkServerMessages.hpp"
#include "shared/network/NetworkUtils.hpp"
using string = std::string;
namespace
{
/*$PUSH*/
/*$WARN 5024 OFF : Parameter "$1" not used*/
void commandaddbot(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name, tempstr;
std::int32_t teamset;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
if (GS::GetGame().GetPlayersNum() == max_players)
return;
tempstr = args[0];
teamset = strtointdef({tempstr[6], 1}, 1);
addbotplayer(name, teamset);
}
void commandaddbots(std::vector<std::string> &args, std::uint8_t sender)
{
if (length(args) == 1)
return;
if (GS::GetGame().GetPlayersNum() == max_players)
return;
auto amount = strtointdef(args[1], 2);
for (auto i = 0; i < amount; i++)
{
addbotplayer("Terminator", i % 2 + 1);
}
}
void commandnextmap(std::vector<std::string> &args, std::uint8_t sender)
{
nextmap();
}
void commandmap(std::vector<std::string> &args, std::uint8_t sender)
{
tmapinfo status;
if (length(args) == 1)
return;
if (length(args[1]) < 1)
return;
if (getmapinfo(args[1], GS::GetGame().GetUserDirectory(), status))
{
preparemapchange(args[1]);
}
else
{
#ifdef STEAM
if (status.workshopid > 0)
{
mapchangeitemid = status.workshopid;
if (steamapi.ugc.downloaditem(mapchangeitemid, true))
GetServerMainConsole().console(string("[Steam] Workshop map ") + inttostr(mapchangeitemid) +
" not found in cache, downloading.",
warning_message_color, sender);
else
GetServerMainConsole().console(string("[Steam] Workshop map ") + inttostr(mapchangeitemid) +
" is invalid",
warning_message_color, sender);
}
else
#endif
GetServerMainConsole().console(string("Map not found (") + args[1] + ')',
warning_message_color, sender);
}
// if not MapExists(MapChangeName, userdirectory) then
// begin
// GetServerMainConsole().Console('Map not found (' + MapChangeName + ')',
// WARNING_MESSAGE_COLOR, Sender); Exit;
// end;
}
void commandpause(std::vector<std::string> &args, std::uint8_t sender)
{
GS::GetGame().SetMapchangecounter(999999999);
serversyncmsg();
}
void commandunpause(std::vector<std::string> &args, std::uint8_t sender)
{
GS::GetGame().SetMapchangecounter(GS::GetGame().GetMapchangecounter() - 60);
serversyncmsg();
}
void commandrestart(std::vector<std::string> &args, std::uint8_t sender)
{
auto &game = GS::GetGame();
auto &map = game.GetMap();
game.SetMapchangename(map.name);
game.SetMapchangecounter(game.GetMapchangetime());
servermapchange(all_players); // Inform clients of Map Change
#ifdef SCRIPT
scrptdispatcher.onbeforemapchange(mapchangename);
#endif
}
void commandkick(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t i;
tcommandtargets targets;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
targets = commandtarget(name, sender);
for (i = 0; i <= high(targets); i++)
kickplayer(targets[i], false, kick_console, 0);
}
void commandkicklast(std::vector<std::string> &args, std::uint8_t sender)
{
if ((lastplayer > 0) && (lastplayer < max_sprites + 1))
{
if (SpriteSystem::Get().GetSprite(lastplayer).IsActive())
{
kickplayer(lastplayer, false, kick_console, 0);
}
}
}
void commandban(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name, tempstr;
std::int32_t i;
tcommandtargets targets;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
if (sender == 255)
tempstr = "an admin";
else
tempstr = SpriteSystem::Get().GetSprite(sender).player->name;
targets = commandtarget(name, sender);
for (i = 0; i <= high(targets); i++)
kickplayer(targets[i], true, kick_console, (day * 30), std::string("Banned by ") + tempstr);
}
void commandbaniphw(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name, tempstr;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
if (sender == 255)
tempstr = "an admin";
else
tempstr = SpriteSystem::Get().GetSprite(sender).player->name;
if (args[0] == "banhw")
{
addbannedhw(name, string("Banned by ") + tempstr, (day * 30));
GetServerMainConsole().console(string("HWID ") + name + " banned", client_message_color,
sender);
}
else
{
addbannedip(name, string("Banned by ") + tempstr, day * 30);
GetServerMainConsole().console(string("IP number ") + name + " banned", client_message_color,
sender);
}
savetxtlists();
}
void commandunban(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
if (delbannedip(name))
GetServerMainConsole().console(string("IP number ") + name + " unbanned", client_message_color,
sender);
if (delbannedhw(name))
GetServerMainConsole().console(string("HWID ") + name + " unbanned", client_message_color,
sender);
savetxtlists();
}
void commandunbanlast(std::vector<std::string> &args, std::uint8_t sender)
{
if (delbannedip(lastban))
GetServerMainConsole().console(string("IP number ") + lastban + " unbanned",
client_message_color, sender);
if (delbannedhw(lastbanhw))
GetServerMainConsole().console(string("HWID ") + lastbanhw + " unbanned", client_message_color,
sender);
savetxtlists();
}
void commandadm(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t i;
tcommandtargets targets;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
targets = commandtarget(name, sender);
for (i = 0; i <= high(targets); i++)
if (isremoteadminip(SpriteSystem::Get().GetSprite(targets[i]).player->ip))
{
remoteips.add(SpriteSystem::Get().GetSprite(targets[i]).player->ip);
GetServerMainConsole().console(string("IP number ") +
SpriteSystem::Get().GetSprite(targets[i]).player->ip +
" added to Remote Admins",
client_message_color, sender);
savetxtlists();
}
}
void commandadmip(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
if (!isremoteadminip(name))
{
remoteips.add(name);
GetServerMainConsole().console(string("IP number ") + name + " added to Remote Admins",
client_message_color, sender);
savetxtlists();
}
}
void commandunadm(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t j;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
if (isremoteadminip(name))
{
NotImplemented("network");
#if 0
j = remoteips.indexof(name);
remoteips.delete_(j);
#endif
GetServerMainConsole().console(string("IP number ") + name + " removed from Remote Admins",
client_message_color, sender);
savetxtlists();
}
}
void commandsetteam(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name, tempstr;
std::int32_t i;
std::uint8_t teamset;
tcommandtargets targets;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
tempstr = args[0];
NotImplemented();
#if 0
teamset = strtointdef(std::string(tempstr.at(8)), 1);
#endif
targets = commandtarget(name, sender);
for (i = 0; i <= high(targets); i++)
{
SpriteSystem::Get().GetSprite(targets[i]).changeteam(teamset, true);
}
}
void commandsay(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
serversendstringmessage((name), all_players, 255, msgtype_pub);
}
void commandkill(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
tvector2 a;
std::int32_t i;
tcommandtargets targets;
if (length(args) == 1)
return;
name = args[1];
targets = commandtarget(name, sender);
for (i = 0; i <= high(targets); i++)
{
SpriteSystem::Get().GetSprite(targets[i]).vest = 0;
SpriteSystem::Get().GetSprite(targets[i]).healthhit(3430, targets[i], 1, -1, a);
GetServerMainConsole().console(SpriteSystem::Get().GetSprite(targets[i]).player->name +
" killed by admin",
client_message_color, sender);
}
}
void commandloadwep(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
if (length(args) == 1)
{
if (CVar::sv_realisticmode)
name = "weapons_floatistic";
else
name = "weapons";
}
else
name = args[1];
lastwepmod = name;
loadweapons(name);
for (auto &sprite : SpriteSystem::Get().GetActiveSprites())
{
if (sprite.player->controlmethod == human)
{
servervars(sprite.num);
}
}
}
void commandloadcon(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t i;
if (length(args) == 1)
return;
name = args[1];
if (CVar::sv_lockedmode)
{
GetServerMainConsole().console(
std::string("Locked Mode is enabled. Settings can't be changed mid-game."),
server_message_color, sender);
return;
}
GS::GetGame().SetMapchangecounter(GS::GetGame().GetMapchangecounter() - 60);
serverdisconnect();
GS::GetBulletSystem().KillAll();
GS::GetThingSystem().KillAll();
for (auto &sprite : SpriteSystem::Get().GetActiveSprites())
{
sprite.player->team = fixteam(sprite.player->team);
sprite.respawn();
sprite.player->kills = 0;
sprite.player->deaths = 0;
sprite.player->flags = 0;
sprite.player->tkwarnings = 0;
sprite.player->chatwarnings = 0;
sprite.player->knifewarnings = 0;
sprite.player->scorespersecond = 0;
sprite.player->grabspersecond = 0;
}
loadconfig(name);
GetServerMainConsole().console(string("Config reloaded ") + currentconf, client_message_color,
sender);
startserver();
}
void commandloadlist(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t i;
if (length(args) == 0)
{
NotImplemented("missing stringreplace");
#if 0
name = stringreplace(CVar::sv_maplist, ".txt", "", rfreplaceall);
#endif
}
else
name = args[1];
if (fileexists(GS::GetGame().GetUserDirectory() + name + ".txt"))
{
mapslist.loadfromfile(GS::GetGame().GetUserDirectory() + name + ".txt");
i = 1;
mapslist.erase(std::remove(mapslist.begin(), mapslist.end(), ""), mapslist.end());
CVar::sv_maplist = name + ".txt";
GetServerMainConsole().console(string("Mapslist loaded ") + name, client_message_color, sender);
}
}
void commandpm(std::vector<std::string> &args, std::uint8_t sender)
{
std::string pmtoid, pmmessage;
std::int32_t i;
tcommandtargets targets;
if (length(args) <= 2)
return;
pmtoid = args[1];
targets = commandtarget(pmtoid, sender);
for (i = 0; i <= high(targets); i++)
{
pmmessage = args[2];
GetServerMainConsole().console(string("Private Message sent to ") + idtoname(targets[i]),
server_message_color, sender);
GetServerMainConsole().console(string("(PM) To: ") + idtoname(targets[i]) +
" From: " + idtoname(sender) + " Message: " + pmmessage,
server_message_color);
serversendstringmessage(string("(PM) ") + (pmmessage), targets[i], 255, msgtype_pub);
}
}
void commandgmute(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t i, j;
tcommandtargets targets;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
targets = commandtarget(name, sender);
for (i = 0; i <= high(targets); i++)
{
SpriteSystem::Get().GetSprite(targets[i]).player->muted = 1;
for (j = 1; j <= max_players; j++)
if (trim(mutelist[j]) == "")
{
mutelist[j] = SpriteSystem::Get().GetSprite(targets[i]).player->ip;
mutename[j] = SpriteSystem::Get().GetSprite(targets[i]).player->name;
break;
}
GetServerMainConsole().console(SpriteSystem::Get().GetSprite(targets[i]).player->name +
" has been muted.",
client_message_color, sender);
}
}
void commandungmute(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t i, j;
tcommandtargets targets;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
targets = commandtarget(name, sender);
for (i = 0; i <= high(targets); i++)
{
SpriteSystem::Get().GetSprite(targets[i]).player->muted = 0;
for (j = 1; j <= max_players; j++)
if (trim(mutelist[j]) == SpriteSystem::Get().GetSprite(targets[i]).player->ip)
{
mutelist[j] = "";
break;
}
GetServerMainConsole().console(SpriteSystem::Get().GetSprite(targets[i]).player->name +
" has been unmuted.",
client_message_color, sender);
}
}
void commandaddmap(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
// if not (MapExists(Name, userdirectory)) then
// begin
// GetServerMainConsole().Console('Map not found (' + Name + ')',
// SERVER_MESSAGE_COLOR, Sender);
// Exit;
// end;
mapslist.add(name);
GetServerMainConsole().console(name + " has been added to the map list.", server_message_color,
sender);
savemaplist();
}
void commanddelmap(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t tempint;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
for (tempint = 0; tempint <= (mapslist.size() - 1); tempint++)
{
NotImplemented();
#if 0
if (uppercase(mapslist[tempint]) == uppercase(name))
{
GetServerMainConsole().console(name + " has been removed from the map list.", server_message_color,
sender);
mapslist.delete_(tempint);
break;
}
#endif
}
savemaplist();
}
void commandtempban(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name, tempstr;
if (length(args) <= 2)
return;
name = args[1];
if (length(name) < 1)
return;
tempstr = args[2];
// *BAN*
addbannedip(tempstr, "Temporary Ban by an Admin", strtointdef(name, 1) * minute);
GetServerMainConsole().console(string("IP number ") + tempstr + " banned for " + name +
" minutes.",
client_message_color, sender);
savetxtlists();
}
void commandweaponon(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t j;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
for (auto &sprite : SpriteSystem::Get().GetActiveSprites())
{
if (sprite.player->controlmethod == human)
{
j = strtointdef(name, -1);
if ((j > -1) && (j < 15))
setweaponactive(sprite.num, j, true);
}
}
}
void commandweaponoff(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
std::int32_t j;
if (length(args) == 1)
return;
name = args[1];
if (length(name) < 1)
return;
for (auto &sprite : SpriteSystem::Get().GetActiveSprites())
{
if (sprite.player->controlmethod == human)
{
j = strtointdef(name, -1);
if ((j > -1) && (j < 15))
setweaponactive(sprite.num, j, false);
}
}
}
void commandbanlist(std::vector<std::string> &args, std::uint8_t sender)
{
NotImplemented();
#if 0
std::int32_t i;
tdatetime banduration;
std::string bandurationtext;
GetServerMainConsole().console(format("%-15s | %-9s | %s", set::of("HWID", "Duration", "Reason", eos)),
server_message_color, sender);
for (i = 1; i <= high(bannedhwlist); i++)
{
if (bannedhwlist[i].time == permanent)
bandurationtext = "PERMANENT";
else
{
banduration = incsecond(now, bannedhwlist[i].time / 60) - now;
bandurationtext =
format("%dd%s", set::of(trunc(banduration),
formatdatetime("h\"h\"n\"m\"", banduration), eos));
}
GetServerMainConsole().console(format("%-15s | %-9s | %s", set::of(bannedhwlist[i].hw, bandurationtext,
bannedhwlist[i].reason, eos)),
server_message_color, sender);
}
GetServerMainConsole().console(format("%-15s | %-9s | %s", set::of("IP", "Duration", "Reason", eos)),
server_message_color, sender);
for (i = 1; i <= high(bannediplist); i++)
{
if (bannediplist[i].time == permanent)
bandurationtext = "PERMANENT";
else
{
banduration = incsecond(now, bannediplist[i].time / 60) - now;
bandurationtext =
format("%dd%s", set::of(trunc(banduration),
formatdatetime("h\"h\"n\"m\"", banduration), eos));
}
GetServerMainConsole().console(format("%-15s | %-9s | %s", set::of(bannediplist[i].ip, bandurationtext,
bannediplist[i].reason, eos)),
server_message_color, sender);
}
#endif
}
void commandnetstats(std::vector<std::string> &args, std::uint8_t sender)
{
std::array<char, 2048> statstext;
tplayer dstplayer;
if (GetServerNetwork()->NetworkingSocket().GetDetailedConnectionStatus(1, statstext.data(),
2048) == 0)
{
NotImplemented();
#if 0
output << statstext << NL;
#endif
}
for (auto &dstplayer : players)
{
if (GetServerNetwork()->NetworkingSocket().GetDetailedConnectionStatus(
dstplayer->peer, statstext.data(), 2048) == 0)
{
NotImplemented();
#if 0
output << "----------------" << NL;
output << dstplayer.name << NL;
output << dstplayer.peer << NL;
output << statstext << NL;
output << "----------------" << NL;
#endif
}
}
}
void commandplayercommand(std::vector<std::string> &args, std::uint8_t sender)
{
std::string command;
tvector2 a;
command = args[0];
if (command == "tabac")
{
SpriteSystem::Get().GetSprite(sender).idlerandom = 0;
SpriteSystem::Get().GetSprite(sender).idletime = 1;
}
else if (command == "smoke")
{
SpriteSystem::Get().GetSprite(sender).idlerandom = 1;
SpriteSystem::Get().GetSprite(sender).idletime = 1;
}
else if (command == "takeoff")
{
SpriteSystem::Get().GetSprite(sender).idlerandom = 4;
SpriteSystem::Get().GetSprite(sender).idletime = 1;
}
else if (command == "victory")
{
SpriteSystem::Get().GetSprite(sender).idlerandom = 5;
SpriteSystem::Get().GetSprite(sender).idletime = 1;
}
else if (command == "piss")
{
SpriteSystem::Get().GetSprite(sender).idlerandom = 6;
SpriteSystem::Get().GetSprite(sender).idletime = 1;
}
else if (command == "mercy")
{
SpriteSystem::Get().GetSprite(sender).idlerandom = 7;
SpriteSystem::Get().GetSprite(sender).idletime = 1;
if (SpriteSystem::Get().GetSprite(sender).player->kills > 0)
SpriteSystem::Get().GetSprite(sender).player->kills -= 1;
}
else if (command == "pwn")
{
SpriteSystem::Get().GetSprite(sender).idlerandom = 8;
SpriteSystem::Get().GetSprite(sender).idletime = 1;
}
else if (command == "kill")
{
SpriteSystem::Get().GetSprite(sender).vest = 0;
SpriteSystem::Get().GetSprite(sender).healthhit(150, sender, 1, -1, a);
if (SpriteSystem::Get().GetSprite(sender).player->kills > 0)
SpriteSystem::Get().GetSprite(sender).player->kills -= 1;
}
else if (command == "brutalkill")
{
SpriteSystem::Get().GetSprite(sender).vest = 0;
SpriteSystem::Get().GetSprite(sender).healthhit(3423, sender, 1, -1, a);
if (SpriteSystem::Get().GetSprite(sender).player->kills > 0)
SpriteSystem::Get().GetSprite(sender).player->kills -= 1;
}
}
void commandinfo(std::vector<std::string> &args, std::uint8_t sender)
{
std::string gametype = "";
#ifdef SCRIPT
std::int8_t i;
tstringlist scriptlist;
#endif
if (length((std::string)CVar::sv_greeting) > 0)
serversendstringmessage((CVar::sv_greeting), sender, 255, msgtype_pub);
if (length((std::string)CVar::sv_greeting2) > 0)
serversendstringmessage((CVar::sv_greeting2), sender, 255, msgtype_pub);
if (length((std::string)CVar::sv_greeting3) > 0)
serversendstringmessage((CVar::sv_greeting3), sender, 255, msgtype_pub);
serversendstringmessage(string("Server: ") + string(CVar::sv_hostname), sender, 255, msgtype_pub);
serversendstringmessage(string("Address: ") + (serverip) + ':' + (inttostr(serverport)), sender,
255, msgtype_pub);
serversendstringmessage(string("Version: ") + dedversion, sender, 255, msgtype_pub);
switch (CVar::sv_gamemode)
{
case gamestyle_deathmatch:
gametype = "Deathmatch";
break;
case gamestyle_pointmatch:
gametype = "Pointmatch";
break;
case gamestyle_teammatch:
gametype = "Teammatch";
break;
case gamestyle_ctf:
gametype = "Capture the Flag";
break;
case gamestyle_rambo:
gametype = "Rambomatch";
break;
case gamestyle_inf:
gametype = "Infiltration";
break;
case gamestyle_htf:
gametype = "Hold the Flag";
break;
}
serversendstringmessage(string("Gamemode: ") + gametype, sender, 255, msgtype_pub);
serversendstringmessage(string("Timelimit: ") + (inttostr(CVar::sv_timelimit / 3600)), sender,
255, msgtype_pub);
serversendstringmessage(string("Nextmap: ") + (checknextmap()), sender, 255, msgtype_pub);
#ifdef SCRIPT
serversendstringmessage(string("Scripting: ") + iif(CVar::sc_enable, "Enabled", "Disabled"),
sender, 255, msgtype_pub);
if (CVar::sc_enable)
{
gametype = "";
scriptlist = scrptdispatcher.scriptlist;
for (i = 0; i <= scriptlist.count - 1; i++)
gametype = gametype + iif(i != 0, ", ", "") + scriptlist.strings[i];
serversendstringmessage(string("Scripts: ") + gametype, sender, 255, msgtype_pub);
scriptlist.free(0);
}
#endif
if (GS::GetWeaponSystem().GetLoadedWMChecksum() != GS::GetWeaponSystem().GetDefaultWMChecksum())
serversendstringmessage(string("Server uses weapon mod \"") + (wmname) + " v" + (wmversion) +
"\" (checksum " +
(inttostr(GS::GetWeaponSystem().GetLoadedWMChecksum())) + ')',
sender, 255, msgtype_pub);
}
void commandadminlog(std::vector<std::string> &args, std::uint8_t sender)
{
std::string adminlog;
if (length(args) == 1)
return;
adminlog = args[1];
if (length((std::string)CVar::sv_adminpassword) > 0)
{
if (adminlog == CVar::sv_adminpassword)
{
if (!isadminip(SpriteSystem::Get().GetSprite(sender).player->ip))
adminips.add(SpriteSystem::Get().GetSprite(sender).player->ip);
GetServerMainConsole().console(SpriteSystem::Get().GetSprite(sender).player->name +
" added to Game Admins",
server_message_color, sender);
}
else
{
GetServerMainConsole().console(SpriteSystem::Get().GetSprite(sender).player->name +
" tried to login as Game Admin with bad password",
server_message_color, sender);
}
}
}
void commandvotemap(std::vector<std::string> &args, std::uint8_t sender)
{
std::string mapname;
if (length(args) == 1)
return;
mapname = args[1];
if (GS::GetGame().IsVoteActive())
{
// check if the vote target is actually the target
if (GS::GetGame().GetVoteTarget() != string(mapname))
return;
// check if he already voted
if (GS::GetGame().HasVoted(sender))
return;
#ifdef SCRIPT
scrptdispatcher.onvotemap(sender, mapname);
#endif
GS::GetGame().countvote(sender);
}
else
{
if (std::find(mapslist.begin(), mapslist.end(), mapname) !=
mapslist.end()) /*and (MapExists(MapName, userdirectory))*/
{
if (GS::GetGame().CanVote(sender))
{
if (!GS::GetGame().IsVoteActive())
{
#ifdef SCRIPT
if (scrptdispatcher.onvotemapstart(sender, mapname))
return;
#endif
GS::GetGame().startvote(sender, vote_map, mapname, "---");
serversendvoteon(GS::GetGame().GetVoteType(), sender, mapname, "---");
}
}
else
serversendstringmessage("Can't vote for 2:00 minutes after joining game or last vote",
sender, 255, msgtype_pub);
}
else
serversendstringmessage(string("Map not found (") + (mapname) + ')', sender, 255,
msgtype_pub);
}
}
#ifdef SCRIPT
void commandrecompile(std::vector<std::string> &args, std::uint8_t sender)
{
std::string name;
if (length(args) == 1)
{
if (!CVar::sc_enable)
GetServerMainConsole().console("Scripting is currently disabled.", client_message_color,
sender);
else
{
scrptdispatcher.prepare(0);
scrptdispatcher.launch(0);
}
}
else
{
name = args[1];
if (!CVar::sc_enable)
GetServerMainConsole().console("Scripting is currently disabled.", client_message_color,
sender);
else
scrptdispatcher.launch(name);
}
}
#endif
void commandrecord(std::vector<std::string> &args, std::uint8_t sender)
{
std::string str1;
if (length(args) == 2)
str1 = args[1];
else
{
NotImplemented();
#if 0
str1 = formatdatetime("yyyy-mm-dd_hh-nn-ss_", now(0)) + map.name;
#endif
}
GS::GetDemoRecorder().stoprecord();
GS::GetDemoRecorder().startrecord(GS::GetGame().GetUserDirectory() + "demos/" + str1 + ".sdm");
}
void commandstop(std::vector<std::string> &args, std::uint8_t sender)
{
GS::GetDemoRecorder().stoprecord();
}
} // namespace
/*$POP*/
void initservercommands()
{
commandadd("addbot", commandaddbot, "Add specific bot to game", cmd_adminonly);
commandadd("addbot1", commandaddbot, "Add specific bot to alpha team", cmd_adminonly);
commandadd("addbot2", commandaddbot, "Add specific bot to blue team", cmd_adminonly);
commandadd("addbot3", commandaddbot, "Add specific bot to charlie team", cmd_adminonly);
commandadd("addbot4", commandaddbot, "Add specific bot to delta team", cmd_adminonly);
commandadd("addbot5", commandaddbot, "Add specific bot to spectators", cmd_adminonly);
commandadd("addbots", commandaddbots, "Add multiple bots for test", cmd_adminonly);
commandadd("nextmap", commandnextmap, "Change map to next in maplist", cmd_adminonly);
commandadd("map", commandmap, "Change map to specified mapname", cmd_adminonly);
commandadd("pause", commandpause, "Pause game", cmd_adminonly);
commandadd("unpause", commandunpause, "Unpause game", cmd_adminonly);
commandadd("restart", commandrestart, "Restart current map", cmd_adminonly);
commandadd("kick", commandkick, "Kick player with specified nick or id", cmd_adminonly);
commandadd("kicklast", commandkicklast, "Kick last connected player", cmd_adminonly);
commandadd("ban", commandban, "Ban player with specified nick or id", cmd_adminonly);
commandadd("banip", commandbaniphw, "Ban specified IP address", cmd_adminonly);
commandadd("banhw", commandbaniphw, "Ban specified hwid", cmd_adminonly);
commandadd("unban", commandunban, "Unban specified ip or hwid", cmd_adminonly);
commandadd("unbanlast", commandunban, "Unban last player", cmd_adminonly);
commandadd("adm", commandadm, "Give admin to specified nick or id", cmd_adminonly);
commandadd("admip", commandadmip, "add the IP number to the Remote Admins list", cmd_adminonly);
commandadd("unadm", commandunadm, "remove the IP number from the admins list", cmd_adminonly);
commandadd("setteam1", commandsetteam, "move specified id or nick to alpha team", cmd_adminonly);
commandadd("setteam2", commandsetteam, "move specified id or nick to bravo team", cmd_adminonly);
commandadd("setteam3", commandsetteam, "move specified id or nick to charlie team",
cmd_adminonly);
commandadd("setteam4", commandsetteam, "move specified id or nick to delta team", cmd_adminonly);
commandadd("setteam5", commandsetteam, "move specified id or nick to spectators", cmd_adminonly);
commandadd("say", commandsay, "Send chat message", cmd_adminonly);
commandadd("pkill", commandkill, "Kill specified id or nick", cmd_adminonly);
commandadd("loadwep", commandloadwep, "Load weapons config", cmd_adminonly);
commandadd("loadcon", commandloadcon, "Load server config", cmd_adminonly);
commandadd("loadlist", commandloadlist, "Load maplist", cmd_adminonly);
commandadd("pm", commandpm, "Send private message to other player", cmd_adminonly);
commandadd("gmute", commandgmute, "Mute player on server", cmd_adminonly);
commandadd("ungmute", commandungmute, "Unmute player on server", cmd_adminonly);
commandadd("addmap", commandaddmap, "Add map to the maplist", cmd_adminonly);
commandadd("delmap", commanddelmap, "Remove map from the maplist", cmd_adminonly);
commandadd("weaponon", commandweaponon, "Enable specific weapon on the server", cmd_adminonly);
commandadd("weaponoff", commandweaponoff, "Disable specific weapon on the server", cmd_adminonly);
commandadd("banlist", commandbanlist, "Show banlist", cmd_adminonly);
commandadd("net_stats", commandnetstats, "Show network stats", cmd_adminonly);
commandadd("tabac", commandplayercommand, "tabac", cmd_playeronly);
commandadd("smoke", commandplayercommand, "smoke", cmd_playeronly);
commandadd("takeoff", commandplayercommand, "takeoff", cmd_playeronly);
commandadd("victory", commandplayercommand, "victory", cmd_playeronly);
commandadd("piss", commandplayercommand, "piss", cmd_playeronly);
commandadd("mercy", commandplayercommand, "mercy", cmd_playeronly);
commandadd("pwn", commandplayercommand, "pwn", cmd_playeronly);
commandadd("kill", commandplayercommand, "kill", cmd_playeronly);
commandadd("brutalkill", commandplayercommand, "brutalkill", cmd_playeronly);
commandadd("info", commandinfo, "info", cmd_playeronly);
commandadd("adminlog", commandadminlog, "adminlog", cmd_playeronly);
commandadd("votemap", commandvotemap, "votemap", cmd_playeronly);
commandadd("record", commandrecord, "record demo", cmd_adminonly);
commandadd("stop", commandstop, "stop recording demo", cmd_adminonly);
#ifdef SCRIPT
commandadd("recompile", commandrecompile(), "Recompile all or specific script", cmd_adminonly);
#endif
}
| 29.51087 | 111 | 0.62302 | [
"vector"
] |
2a0d5260ba3a74443e4ac4d7c53626d092820ba8 | 3,623 | cpp | C++ | moos-ivp/ivp/src/lib_geometry/XYFormatUtilsCommsPulse.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/lib_geometry/XYFormatUtilsCommsPulse.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/lib_geometry/XYFormatUtilsCommsPulse.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | /*****************************************************************/
/* NAME: Michael Benjamin */
/* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */
/* FILE: XYFormatUtilsRangePulse.cpp */
/* DATE: Feb 5th, 2011 */
/* */
/* This file is part of IvP Helm Core Libs */
/* */
/* IvP Helm Core Libs is free software: you can redistribute it */
/* and/or modify it under the terms of the Lesser GNU General */
/* Public License as published by the Free Software Foundation, */
/* either version 3 of the License, or (at your option) any */
/* later version. */
/* */
/* IvP Helm Core Libs 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 Lesser GNU General Public License for more */
/* details. */
/* */
/* You should have received a copy of the Lesser GNU General */
/* Public License along with MOOS-IvP. If not, see */
/* <http://www.gnu.org/licenses/>. */
/*****************************************************************/
#include <vector>
#include <cstdlib>
#include "XYFormatUtilsCommsPulse.h"
#include "MBUtils.h"
using namespace std;
//---------------------------------------------------------------
// Procedure: string2CommsPulse (Method #0)
// Example: Create a point from a string representation.
XYCommsPulse string2CommsPulse(string str)
{
return(stringStandard2CommsPulse(str));
}
//---------------------------------------------------------------
// Procedure: stringStandard2CommsPulse (Method #1)
// Note: This function is standard because it processes the
// string format used when a string is created from an
// existing XYCommsPulse instance.
// Example: label=one,sx=4,sy=2,tx=44,ty=55,beam_width=10,duration=5,
// fill=0.3,fill_color=yellow,edge_color=green
//
XYCommsPulse stringStandard2CommsPulse(string str)
{
XYCommsPulse null_pulse;
XYCommsPulse new_pulse;
str = stripBlankEnds(str);
vector<string> mvector = parseString(str, ',');
unsigned int i, vsize = mvector.size();
for(i=0; i<vsize; i++) {
mvector[i] = stripBlankEnds(mvector[i]);
string param = tolower(stripBlankEnds(biteString(mvector[i], '=')));
string value = stripBlankEnds(mvector[i]);
double dval = atof(value.c_str());
if((param == "sx") && isNumber(value))
new_pulse.set_sx(dval);
else if((param == "sy") && isNumber(value))
new_pulse.set_sy(dval);
else if((param == "tx") && isNumber(value))
new_pulse.set_tx(dval);
else if((param == "ty") && isNumber(value))
new_pulse.set_ty(dval);
else if((param == "beam_width") && isNumber(value))
new_pulse.set_beam_width(dval);
else if((param == "duration") && isNumber(value))
new_pulse.set_duration(dval);
else if((param == "fill") && isNumber(value))
new_pulse.set_fill(dval);
else
new_pulse.set_param(param, value);
}
if(!new_pulse.valid())
return(null_pulse);
return(new_pulse);
}
| 36.969388 | 72 | 0.515871 | [
"vector"
] |
2a0e767970429ff598542e6adcb1cad21b6ee476 | 1,858 | cpp | C++ | src/StageTimeComputation.cpp | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | src/StageTimeComputation.cpp | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | src/StageTimeComputation.cpp | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | #include "CommonHeader.h"
#include "RobotInfo.h"
static double ReductionMagnitude(double cur_s, double phase_s, double reduction_ratio){
if(cur_s<phase_s) return 1.0;
else{
if(cur_s<=1.0){
return 1.0 - (1.0 - reduction_ratio)/(1.0 - phase_s) * (cur_s - phase_s);
} else return reduction_ratio;
}
}
double StageTimeComputation(const Robot & SimRobot, const Config & CurConfig, const Config & CurVelocity,
const Config & UpdatedConfig, const std::vector<int> & SwingLinkChain,
const double & sCur, const SimPara & SimParaObj,
std::vector<double> & NextConfig,
std::vector<double> & NextVelocity){
// Given Current Configuration, Velocity, and Updated Configuration, calculate the transition time.
double StageTime = 0.0;
double PhaseRatio = SimParaObj.PhaseRatio;
std::vector<double> qMinVec = SimRobot.qMin;
std::vector<double> qMaxVec = SimRobot.qMax;
if(sCur<SimParaObj.PhaseRatio){
StageTime = AccPhaseTimeComputation(CurConfig, CurVelocity,
qMinVec, qMaxVec,
NextConfig, NextVelocity,
SimRobot.velMax, SimRobot.accMax,
SwingLinkChain);
}
else
{
double ReductionMag = ReductionMagnitude(sCur, PhaseRatio, SimParaObj.ReductionRatio);
StageTime = DecPhaseTimeComputation(CurConfig, CurVelocity,
qMinVec, qMaxVec,
NextConfig, NextVelocity,
SimRobot.velMax, SimRobot.accMax,
SwingLinkChain, ReductionMag);
}
return StageTime;
} | 46.45 | 105 | 0.560818 | [
"vector"
] |
2a10ddb92632f2f707cd241f820cf3235e218fe3 | 2,942 | cpp | C++ | wave_vision/tests/viz_tests/descriptor_viz_tests.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 80 | 2017-03-12T18:57:33.000Z | 2022-03-30T11:44:33.000Z | wave_vision/tests/viz_tests/descriptor_viz_tests.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 210 | 2017-03-13T15:01:34.000Z | 2022-01-15T03:19:44.000Z | wave_vision/tests/viz_tests/descriptor_viz_tests.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 31 | 2017-08-14T16:54:52.000Z | 2022-01-21T06:44:16.000Z | #include "wave/wave_test.hpp"
#include "wave/vision/descriptor/brisk_descriptor.hpp"
#include "wave/vision/descriptor/orb_descriptor.hpp"
#include "wave/vision/detector/fast_detector.hpp"
#include "wave/vision/detector/orb_detector.hpp"
namespace wave {
const auto TEST_IMAGE = "tests/data/image_center.png";
TEST(BRISKTests, ComputeFASTBRISKDescriptors) {
cv::Mat descriptors;
cv::Mat image_with_keypoints;
cv::Mat image = cv::imread(TEST_IMAGE);
std::vector<cv::KeyPoint> keypoints;
FASTDetector fast;
BRISKDescriptor brisk;
keypoints = fast.detectFeatures(image);
descriptors = brisk.extractDescriptors(image, keypoints);
ASSERT_FALSE(descriptors.empty());
// Visual test to verify descriptors are being computed properly
cv::drawKeypoints(descriptors, keypoints, image_with_keypoints);
cv::imshow("BRISK Descriptors", image_with_keypoints);
cv::waitKey(0);
cv::destroyAllWindows();
}
TEST(BRISKTESTS, ComputeORBBRISKDescriptors) {
cv::Mat descriptors;
cv::Mat image_with_keypoints;
cv::Mat image = cv::imread(TEST_IMAGE);
std::vector<cv::KeyPoint> keypoints;
ORBDetector orb;
BRISKDescriptor brisk;
keypoints = orb.detectFeatures(image);
descriptors = brisk.extractDescriptors(image, keypoints);
ASSERT_FALSE(descriptors.empty());
// Visual test to verify descriptors are being computed properly
cv::drawKeypoints(descriptors, keypoints, image_with_keypoints);
cv::imshow("BRISK Descriptors", image_with_keypoints);
cv::waitKey(0);
cv::destroyAllWindows();
}
TEST(ORBDescriptorTests, ComputeORBORBDescriptors) {
cv::Mat descriptors;
cv::Mat image_with_keypoints;
cv::Mat image = cv::imread(TEST_IMAGE);
std::vector<cv::KeyPoint> keypoints;
ORBDetector detector;
ORBDescriptor descriptor;
keypoints = detector.detectFeatures(image);
descriptors = descriptor.extractDescriptors(image, keypoints);
ASSERT_FALSE(descriptors.empty());
// Visual test to verify descriptors are being computed properly
cv::drawKeypoints(descriptors, keypoints, image_with_keypoints);
cv::imshow("ORB Descriptors", image_with_keypoints);
cv::waitKey(0);
cv::destroyAllWindows();
}
TEST(FASTORBDescriptorTests, ComputeFASTORBDescriptors) {
cv::Mat descriptors;
cv::Mat image_with_keypoints;
cv::Mat image = cv::imread(TEST_IMAGE);
std::vector<cv::KeyPoint> keypoints;
FASTDetector detector;
ORBDescriptor descriptor;
keypoints = detector.detectFeatures(image);
descriptors = descriptor.extractDescriptors(image, keypoints);
ASSERT_FALSE(descriptors.empty());
// Visual test to verify descriptors are being computed properly
cv::drawKeypoints(descriptors, keypoints, image_with_keypoints);
cv::imshow("ORB Descriptors", image_with_keypoints);
cv::waitKey(0);
cv::destroyAllWindows();
}
} // namespace wave
| 27.495327 | 68 | 0.731815 | [
"vector"
] |
2a13adc2cfb2a3a0e2ac8d0e37eb5deed800cf90 | 581 | cpp | C++ | src/source/util/digest.cpp | mvpwizard/DLA | 5ead2574e61e619ca3a93f1e771e3988fc144928 | [
"MIT"
] | 1 | 2019-03-24T12:07:46.000Z | 2019-03-24T12:07:46.000Z | src/source/util/digest.cpp | nepitdev/DLA | 5ead2574e61e619ca3a93f1e771e3988fc144928 | [
"MIT"
] | 10 | 2019-03-06T20:27:39.000Z | 2019-11-27T08:28:12.000Z | src/source/util/digest.cpp | openepit/DLA | 5ead2574e61e619ca3a93f1e771e3988fc144928 | [
"MIT"
] | null | null | null | #include "digest.hpp"
namespace dla
{
digest::digest(std::vector<uint8_t> data):
data(data) { }
std::vector<uint8_t> digest::execute()
{
uint8_t digest[SHA256_DIGEST_LENGTH];
SHA256(&data[0], data.size(), (uint8_t*) &digest);
data = std::vector<uint8_t>(std::begin(digest), std::end(digest));
return data;
}
uint8_t digest::next()
{
if (buffer.empty()) buffer = execute();
uint8_t val = buffer[0];
buffer.erase(buffer.begin());
return val;
}
digest::~digest() { }
} | 23.24 | 74 | 0.552496 | [
"vector"
] |
2a15a8b0935cbb29204758f724f5857b54973965 | 937 | cpp | C++ | LeetCode/102_Binary_Tree_Level_Order_Traversal/main.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | 1 | 2020-07-08T23:16:19.000Z | 2020-07-08T23:16:19.000Z | LeetCode/102_Binary_Tree_Level_Order_Traversal/main.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | 1 | 2020-05-16T03:12:24.000Z | 2020-05-16T03:14:42.000Z | LeetCode/102_Binary_Tree_Level_Order_Traversal/main.cpp | sungmen/Acmicpc_Solve | 0298a6aec84993a4d8767bd2c00490b7201e06a4 | [
"MIT"
] | 2 | 2020-05-16T03:25:16.000Z | 2021-02-10T16:51:25.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
vector<vector<int>> v;
public:
void dfs(TreeNode* root, int deep) {
int val = root->val;
if (v.size() == deep) {
v.push_back({val});
} else {
v[deep].push_back(val);
}
if (root->left != nullptr) {
dfs(root->left, deep+1);
}
if (root->right != nullptr) {
dfs(root->right, deep+1);
}
}
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr) return {};
dfs(root, 0);
return v;
}
}; | 26.027778 | 93 | 0.502668 | [
"vector"
] |
2a1e9ae0d724e6f97b1597864cb0b2932b566e26 | 1,690 | cpp | C++ | chapter_4/libs/libshading/ProgramUniform.cpp | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 5 | 2017-05-13T20:47:13.000Z | 2020-04-18T18:18:03.000Z | chapter_4/libs/libshading/ProgramUniform.cpp | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | null | null | null | chapter_4/libs/libshading/ProgramUniform.cpp | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 8 | 2016-10-24T16:24:21.000Z | 2021-03-15T11:23:57.000Z | #include "includes/opengl-common.hpp"
#include "includes/glm-common.hpp"
#include "ProgramUniform.h"
CProgramUniform::CProgramUniform(int location)
: m_location(location)
{
}
void CProgramUniform::operator =(int value)
{
if (m_location != -1)
{
glUniform1i(m_location, value);
}
}
void CProgramUniform::operator =(float value)
{
if (m_location != -1)
{
glUniform1f(m_location, value);
}
}
void CProgramUniform::operator =(const glm::vec2 &value)
{
if (m_location != -1)
{
glUniform2fv(m_location, 1, glm::value_ptr(value));
}
}
void CProgramUniform::operator =(const glm::ivec2 &value)
{
if (m_location != -1)
{
glUniform2iv(m_location, 1, glm::value_ptr(value));
}
}
void CProgramUniform::operator =(const glm::vec3 &value)
{
if (m_location != -1)
{
glUniform3fv(m_location, 1, glm::value_ptr(value));
}
}
void CProgramUniform::operator =(const glm::vec4 &value)
{
if (m_location != -1)
{
glUniform4fv(m_location, 1, glm::value_ptr(value));
}
}
void CProgramUniform::operator =(const glm::mat3 &value)
{
if (m_location != -1)
{
glUniformMatrix3fv(m_location, 1, false, glm::value_ptr(value));
}
}
void CProgramUniform::operator =(const glm::mat4 &value)
{
if (m_location != -1)
{
glUniformMatrix4fv(m_location, 1, false, glm::value_ptr(value));
}
}
void CProgramUniform::operator =(const std::vector<glm::mat4> &value)
{
if ((m_location != -1) && !value.empty())
{
const GLsizei count = GLsizei(value.size());
glUniformMatrix4fv(m_location, count, false, glm::value_ptr(value[0]));
}
}
| 20.361446 | 79 | 0.626036 | [
"vector"
] |
2a26ef4626dc5f752210be538a8877cfb8dbd368 | 1,216 | cc | C++ | leetcode/120_triangle.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | leetcode/120_triangle.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | leetcode/120_triangle.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: 120_triangle.cc
*
* Description:
*
* Version: 1.0
* Created: 04/17/2015 08:32:12 PM
* Revision: none
* Compiler: gcc
*
* Author: (Qi Liu), liuqi.edward@gmail.com
* Organization: antq.com
*
* =====================================================================================
*/
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
if(triangle.size() == 0)
return 0;
int i, j, size, ans;
size = triangle.size();
for(i = 1; i != size; ++i){
triangle[i][0] += triangle[i-1][0];
for(j = 1; j != triangle[i].size()-1; ++j){
triangle[i][j] += std::min(triangle[i-1][j-1], triangle[i-1][j]);
}
triangle[i][j] += triangle[i-1][j-1];
}
ans = triangle[i-1][0];
for(auto k : triangle[i-1]){
if(k < ans)
ans = k;
}
return ans;
}
};
int main(){
vector<vector<int> > triangle = {{1}, {3,4}, {6,5,6}, {4,1,8,1}};
Solution sln;
int ans = sln.minimumTotal(triangle);
cout<<ans<<endl;
return 0;
}
| 22.943396 | 88 | 0.467105 | [
"vector"
] |
2a53766de322ec8a554e88ae462b878b11b7b319 | 6,739 | cpp | C++ | code/Core/Source/Resource/T3DTexture.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | 1 | 2021-11-16T15:11:52.000Z | 2021-11-16T15:11:52.000Z | code/Core/Source/Resource/T3DTexture.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | null | null | null | code/Core/Source/Resource/T3DTexture.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | null | null | null | /*******************************************************************************
* This file is part of Tiny3D (Tiny 3D Graphic Rendering Engine)
* Copyright (C) 2015-2020 Answer Wong
* For latest info, see https://github.com/answerear/Tiny3D
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "Resource/T3DTexture.h"
#include "Resource/T3DArchive.h"
#include "Resource/T3DArchiveManager.h"
#include "ImageCodec/T3DImage.h"
#include "Render/T3DHardwareBufferManager.h"
namespace Tiny3D
{
//--------------------------------------------------------------------------
T3D_IMPLEMENT_CLASS_1(Texture, Resource);
//--------------------------------------------------------------------------
TexturePtr Texture::create(const String &name, HardwareBuffer::Usage usage,
uint32_t access, size_t mipmaps, size_t texWidth /* = 0 */,
size_t texHeight /* = 0 */, TexUsage texUsage /* = E_TU_DEFAULT */,
TextureType texType /* = E_TEX_TYPE_2D */,
PixelFormat format /* = PixelFormat::E_PF_A8R8G8B8 */)
{
TexturePtr texture = new Texture(name, usage, access, mipmaps,
texWidth, texHeight, texUsage, texType, format);
texture->release();
return texture;
}
//----------------------------------------------------------------- ---------
Texture::Texture(const String &name, HardwareBuffer::Usage usage,
uint32_t access, size_t mipmaps, size_t texWidth, size_t texHeight,
TexUsage texUsage, TextureType texType, PixelFormat format)
: Resource(name)
, mTexType(texType)
, mTexUsage(texUsage)
, mMipmaps(mipmaps)
, mTexWidth(texWidth)
, mTexHeight(texHeight)
, mImgWidth(texWidth)
, mImgHeight(texHeight)
, mFormat(format)
, mHasAlpha(false)
, mUsage(usage)
, mAccessMode(access)
, mPBO(nullptr)
{
}
//--------------------------------------------------------------------------
Texture::~Texture()
{
mPBO = nullptr;
}
//--------------------------------------------------------------------------
Resource::Type Texture::getType() const
{
return Type::E_RT_TEXTURE;
}
//--------------------------------------------------------------------------
ResourcePtr Texture::clone() const
{
TexturePtr texture = Texture::create(mName, mUsage, mAccessMode,
mMipmaps, mTexWidth, mTexHeight, mTexUsage, mTexType, mFormat);
if (texture != nullptr)
{
TResult ret = texture->load();
if (T3D_FAILED(ret))
{
texture = nullptr;
}
}
return texture;
}
//--------------------------------------------------------------------------
TResult Texture::load()
{
TResult ret = T3D_OK;
do
{
if (E_TU_DEFAULT == mTexUsage)
{
// 加载纹理数据
Image image;
ret = image.load(mName);
if (T3D_FAILED(ret))
{
T3D_LOG_ERROR(LOG_TAG_RESOURCE, "Load image %s failed !",
mName.c_str());
break;
}
if (mTexWidth == 0)
{
mTexWidth = image.getWidth();
}
if (mTexHeight == 0)
{
mTexHeight = image.getHeight();
}
// 创建硬件缓冲区
mPBO = T3D_HARDWARE_BUFFER_MGR.createPixelBuffer(mTexWidth,
mTexHeight, mFormat, image.getData(), mUsage, mAccessMode,
mMipmaps);
if (mPBO == nullptr)
{
ret = T3D_ERR_INVALID_POINTER;
T3D_LOG_ERROR(LOG_TAG_RESOURCE, "Create pixel buffer "
"failed !");
break;
}
}
else
{
// 创建硬件缓冲区
mPBO = T3D_HARDWARE_BUFFER_MGR.createPixelBuffer(mTexWidth,
mTexHeight, mFormat, nullptr, mUsage, mAccessMode, mMipmaps);
if (mPBO == nullptr)
{
ret = T3D_ERR_INVALID_POINTER;
T3D_LOG_ERROR(LOG_TAG_RESOURCE, "Create pixel buffer "
"failed !");
break;
}
}
} while (0);
return ret;
}
//--------------------------------------------------------------------------
TResult Texture::unload()
{
mPBO = nullptr;
return Resource::unload();
}
//--------------------------------------------------------------------------
TResult Texture::saveToFile(const String &path, uint32_t fileType) const
{
TResult ret = T3D_OK;
do
{
if (mPBO == nullptr)
{
ret = T3D_ERR_INVALID_POINTER;
T3D_LOG_ERROR(LOG_TAG_RESOURCE, "Not initialize !");
break;
}
Image image;
ret = mPBO->writeImage(image);
if (T3D_FAILED(ret))
{
T3D_LOG_ERROR(LOG_TAG_RESOURCE, "Write to image failed !");
break;
}
ret = image.save(path, fileType);
if (T3D_FAILED(ret))
{
T3D_LOG_ERROR(LOG_TAG_RESOURCE, "Save to file failed !");
break;
}
} while (0);
return ret;
}
//--------------------------------------------------------------------------
TResult Texture::copyTo(TexturePtr texture, Rect *dstRect /* = nullptr */,
Rect *srcRect /* = nullptr */)
{
if (!texture->isLoaded())
{
texture->load();
}
return mPBO->copyTo(texture->getPixelBuffer(), dstRect, srcRect);
}
}
| 30.493213 | 81 | 0.452293 | [
"render",
"3d"
] |
3980abee191267d016b3fc86acfa6c9e3b5ad391 | 9,789 | cpp | C++ | quick_bench_can.cpp | SzalonyJohny/STM32_CAN_abstraction | 4465c4c9bd8367429db6eed78cce001d294370ff | [
"MIT"
] | null | null | null | quick_bench_can.cpp | SzalonyJohny/STM32_CAN_abstraction | 4465c4c9bd8367429db6eed78cce001d294370ff | [
"MIT"
] | null | null | null | quick_bench_can.cpp | SzalonyJohny/STM32_CAN_abstraction | 4465c4c9bd8367429db6eed78cce001d294370ff | [
"MIT"
] | null | null | null | #include<array>
#include<algorithm>
#include<numeric>
#include<span>
#include<stdio.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <array>
#include <memory>
#include <stdio.h>
typedef struct {
uint32_t StdId; /*!< Specifies the standard identifier.
This parameter must be a number between Min_Data = 0 and
Max_Data = 0x7FF. */
uint32_t ExtId; /*!< Specifies the extended identifier.
This parameter must be a number between Min_Data = 0 and
Max_Data = 0x1FFFFFFF. */
uint32_t IDE; /*!< Specifies the type of identifier for the message that will
be transmitted. This parameter can be a value of @ref
CAN_identifier_type */
uint32_t RTR; /*!< Specifies the type of frame for the message that will be
transmitted. This parameter can be a value of @ref
CAN_remote_transmission_request */
uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted.
This parameter must be a number between Min_Data = 0 and
Max_Data = 8. */
uint32_t Timestamp; /*!< Specifies the timestamp counter value captured on
start of frame reception.
@note: Time Triggered Communication Mode must be
enabled. This parameter must be a number between
Min_Data = 0 and Max_Data = 0xFFFF. */
uint32_t FilterMatchIndex; /*!< Specifies the index of matching acceptance
filter element. This parameter must be a number
between Min_Data = 0 and Max_Data = 0xFF. */
} CAN_RxHeaderTypeDef;
typedef enum { DISABLE = 0, ENABLE = !DISABLE } FunctionalState;
/**
* @brief CAN Tx message header structure definition
*/
typedef struct {
uint32_t StdId; /*!< Specifies the standard identifier.
This parameter must be a number between Min_Data = 0 and
Max_Data = 0x7FF. */
uint32_t ExtId; /*!< Specifies the extended identifier.
This parameter must be a number between Min_Data = 0 and
Max_Data = 0x1FFFFFFF. */
uint32_t IDE; /*!< Specifies the type of identifier for the message that will
be transmitted. This parameter can be a value of @ref
CAN_identifier_type */
uint32_t RTR; /*!< Specifies the type of frame for the message that will be
transmitted. This parameter can be a value of @ref
CAN_remote_transmission_request */
uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted.
This parameter must be a number between Min_Data = 0 and
Max_Data = 8. */
FunctionalState
TransmitGlobalTime; /*!< Specifies whether the timestamp counter value
captured on start of frame transmission, is sent in DATA6 and
DATA7 replacing pData[6] and pData[7].
@note: Time Triggered Communication Mode must be enabled.
@note: DLC must be programmed as 8 bytes, in order these 2 bytes
are sent. This parameter can be set to ENABLE or DISABLE. */
} CAN_TxHeaderTypeDef;
typedef enum {
HAL_OK = 0x00U,
HAL_ERROR = 0x01U,
HAL_BUSY = 0x02U,
HAL_TIMEOUT = 0x03U
} HAL_StatusTypeDef;
typedef struct {
} CAN_HandleTypeDef;
HAL_StatusTypeDef HAL_CAN_GetRxMessage(CAN_HandleTypeDef *hcan, uint32_t RxFifo,
CAN_RxHeaderTypeDef *pHeader,
uint8_t aData[]) {
// test senario
aData[0] = rand()%123;
aData[1] = 2;
aData[2] = rand()%123;
aData[3] = rand()%123;
aData[4] = rand()%123;
aData[5] = rand()%123;
aData[6] = rand()%123;
pHeader->IDE = rand()%5 + 1;
pHeader->DLC = rand()%5 + 1;
return HAL_StatusTypeDef::HAL_OK;
}
HAL_StatusTypeDef HAL_CAN_AddTxMessage(CAN_HandleTypeDef *hcan,
CAN_TxHeaderTypeDef *pHeader,
uint8_t aData[], uint32_t *pTxMailbox) {
return HAL_StatusTypeDef::HAL_OK;
}
#define CAN_RTR_DATA (0x00000000U) /*!< Data frame */
#define CAN_RTR_REMOTE (0x00000002U) /*!< Remote frame */
#define CAN_ID_STD (0x00000000U) /*!< Standard Id */
#define CAN_ID_EXT (0x00000004U)
static const std::size_t max_dlc_size = 8;
struct Can_rx_message {
Can_rx_message(CAN_HandleTypeDef *hcan, uint32_t RxFifo)
: header{0}, data{0} {
this->status =
HAL_CAN_GetRxMessage(hcan, RxFifo, &this->header, this->data);
}
CAN_RxHeaderTypeDef header;
uint8_t data[max_dlc_size];
HAL_StatusTypeDef status;
};
template <typename T> struct Can_tx_message {
Can_tx_message(T data, CAN_TxHeaderTypeDef message_header)
: header{message_header} {
static_assert(std::is_trivially_constructible<T>(),
"Object must by C like struct");
static_assert(std::is_class<T>(), "Object must by C like struct");
std::memcpy(this->buff, &data, sizeof(T));
}
uint8_t buff[max_dlc_size];
CAN_TxHeaderTypeDef header;
HAL_StatusTypeDef send(CAN_HandleTypeDef *hcan, uint32_t *pTxMailbox) {
return HAL_CAN_AddTxMessage(hcan, &this->header, this->buff, pTxMailbox);
}
};
class Device_base {
public:
const uint32_t IDE;
const uint32_t DLC;
constexpr Device_base(uint32_t ide, uint32_t dlc) : IDE{ide}, DLC{dlc} {}
virtual void set_data(Can_rx_message &m) = 0;
};
enum struct apps_status_struct : uint8_t {
ALL_OK,
SENSOR_IMPLOSIBILITY,
SUPPLY_VOLTAGE_INCORECT,
};
struct __attribute__((packed)) Apps_data {
uint16_t apps_value;
int16_t d_apps_dt;
apps_status_struct apps_status;
};
class apps_c : public Device_base {
public:
constexpr apps_c(uint32_t ide, uint32_t dlc)
: Device_base(ide, dlc), data{0} {};
Apps_data data;
void set_data(Can_rx_message &m) override {
std::memcpy(&data, &m.data[0], sizeof(Apps_data));
}
};
namespace apps_const {
const int APPS_CAN_ID = 0x0A;
const int APPS_CAN_DLC = sizeof(Apps_data);
const CAN_TxHeaderTypeDef can_tx_header_apps{
APPS_CAN_ID, 0xFFF, CAN_ID_STD, CAN_RTR_DATA, APPS_CAN_DLC, DISABLE};
}
enum struct Acquisition_card_status_struct : uint8_t {
ALL_OK,
COS_SIE_rozwalilo,
SUPPLY_VOLTAGE_INCORECT,
};
struct __attribute__((packed)) Acquisition_card_data {
uint32_t wheel_time_interval_left;
uint32_t wheel_time_interval_right;
Acquisition_card_status_struct apps_status =
Acquisition_card_status_struct::ALL_OK;
};
class acquisition_card_c : public Device_base {
public:
constexpr acquisition_card_c(uint32_t ide, uint32_t dlc)
: Device_base(ide, dlc), data{0} {};
Acquisition_card_data data;
void set_data(Can_rx_message &m) override {
std::memcpy(&data, &m.data[0], sizeof(Acquisition_card_data));
}
};
namespace new_can {
class can_interface {
apps_c apps{1, 3};
acquisition_card_c ac{2, 4};
apps_c apps2{3, 3};
acquisition_card_c ac2{4, 4};
apps_c apps3{5, 3};
acquisition_card_c ac3{6, 4};
std::array<Device_base *, 8> device_array = {&apps, &ac, &apps2, &ac2, &apps3, &ac3};
public:
void disp() {
printf("Apps IDE: %d \n", (int)apps.IDE);
printf("Apps status: %d \n", (int)apps.data.apps_status);
printf("Apps value: %d \n", apps.data.apps_value);
printf("Apps d_dt: %d \n\n", apps.data.d_apps_dt);
}
void get_message(Can_rx_message &m) {
for (auto &dev : device_array) {
if (dev->IDE == m.header.IDE) {
dev->set_data(m);
return; // to exit void
}
}
}
void get_message_2(Can_rx_message &m) {
if(apps.IDE == m.header.IDE){
apps.set_data(m);
return;
}
else if(ac.IDE == m.header.IDE){
ac.set_data(m);
return;
}
if(apps2.IDE == m.header.IDE){
apps2.set_data(m);
return;
}
else if(ac2.IDE == m.header.IDE){
ac2.set_data(m);
return;
}
if(apps3.IDE == m.header.IDE){
apps3.set_data(m);
return;
}
else if(ac3.IDE == m.header.IDE){
ac3.set_data(m);
return;
}
}
Apps_data get_apps_data() { return apps.data; }
Acquisition_card_data get_acquisition_card_data() { return ac.data; }
};
} // namespace new_can
static void get_message(benchmark::State& state) {
// global HAL CUBE_MX initialized data
CAN_HandleTypeDef hcan1;
// global can interface handle
new_can::can_interface can;
// Code inside this loop is measured repeatedly
for (auto _ : state) {
can_rx_message rx{&hcan1, 1};
if (rx.status == HAL_StatusTypeDef::HAL_OK) {
can.get_message(rx);
} else {
// Error_Handeler("Error in reciving data from can");
}
benchmark::DoNotOptimize(can);
}
}
// Register the function as a benchmark
BENCHMARK(get_message);
static void get_message_2(benchmark::State& state) {
// global HAL CUBE_MX initialized data
CAN_HandleTypeDef hcan1;
// global can interface handle
new_can::can_interface can;
for (auto _ : state) {
can_rx_message rx{&hcan1, 1};
if (rx.status == HAL_StatusTypeDef::HAL_OK) {
can.get_message_2(rx);
} else {
// Error_Handeler("Error in reciving data from can");
}
benchmark::DoNotOptimize(can);
}
}
BENCHMARK(get_message_2);
| 29.396396 | 88 | 0.62039 | [
"object"
] |
3982d12f603656fe7de37a2b70c3863ac26bf7e0 | 26,863 | cpp | C++ | android-11/frameworks/base/tools/aapt2/cmd/Dump.cpp | MrIkso/sdk-tools | 53b34cdaca0b94364446f01b5ac3455773db3029 | [
"Apache-2.0"
] | 5 | 2020-12-19T06:56:06.000Z | 2022-01-09T01:28:42.000Z | android-11/frameworks/base/tools/aapt2/cmd/Dump.cpp | MrIkso/sdk-tools | 53b34cdaca0b94364446f01b5ac3455773db3029 | [
"Apache-2.0"
] | 1 | 2021-09-27T06:00:40.000Z | 2021-09-27T06:00:40.000Z | android-11/frameworks/base/tools/aapt2/cmd/Dump.cpp | MrIkso/sdk-tools | 53b34cdaca0b94364446f01b5ac3455773db3029 | [
"Apache-2.0"
] | 3 | 2020-12-19T06:56:27.000Z | 2021-09-26T18:50:44.000Z | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Dump.h"
#include <cinttypes>
#include <vector>
#include "android-base/stringprintf.h"
#include "androidfw/ConfigDescription.h"
#include "androidfw/StringPiece.h"
#include "Debug.h"
#include "Diagnostics.h"
#include "LoadedApk.h"
#include "Util.h"
#include "format/Container.h"
#include "format/binary/BinaryResourceParser.h"
#include "format/binary/XmlFlattener.h"
#include "format/proto/ProtoDeserialize.h"
#include "io/FileStream.h"
#include "io/ZipArchive.h"
#include "process/IResourceTableConsumer.h"
#include "text/Printer.h"
#include "util/Files.h"
using ::aapt::text::Printer;
using ::android::StringPiece;
using ::android::base::StringPrintf;
namespace aapt {
static const char* ResourceFileTypeToString(const ResourceFile::Type& type) {
switch (type) {
case ResourceFile::Type::kPng:
return "PNG";
case ResourceFile::Type::kBinaryXml:
return "BINARY_XML";
case ResourceFile::Type::kProtoXml:
return "PROTO_XML";
default:
break;
}
return "UNKNOWN";
}
static void DumpCompiledFile(const ResourceFile& file, const Source& source, off64_t offset,
size_t len, Printer* printer) {
printer->Print("Resource: ");
printer->Println(file.name.to_string());
printer->Print("Config: ");
printer->Println(file.config.to_string());
printer->Print("Source: ");
printer->Println(file.source.to_string());
printer->Print("Type: ");
printer->Println(ResourceFileTypeToString(file.type));
printer->Println(StringPrintf("Data: offset=%" PRIi64 " length=%zd", offset, len));
}
namespace {
class DumpContext : public IAaptContext {
public:
PackageType GetPackageType() override {
// Doesn't matter.
return PackageType::kApp;
}
IDiagnostics* GetDiagnostics() override {
return &diagnostics_;
}
NameMangler* GetNameMangler() override {
UNIMPLEMENTED(FATAL);
return nullptr;
}
const std::string& GetCompilationPackage() override {
static std::string empty;
return empty;
}
uint8_t GetPackageId() override {
return 0;
}
SymbolTable* GetExternalSymbols() override {
UNIMPLEMENTED(FATAL);
return nullptr;
}
bool IsVerbose() override {
return verbose_;
}
void SetVerbose(bool val) {
verbose_ = val;
}
int GetMinSdkVersion() override {
return 0;
}
const std::set<std::string>& GetSplitNameDependencies() override {
UNIMPLEMENTED(FATAL) << "Split Name Dependencies should not be necessary";
static std::set<std::string> empty;
return empty;
}
private:
StdErrDiagnostics diagnostics_;
bool verbose_ = false;
};
} // namespace
int DumpAPCCommand::Action(const std::vector<std::string>& args) {
DumpContext context;
DebugPrintTableOptions print_options;
print_options.show_sources = true;
print_options.show_values = !no_values_;
if (args.size() < 1) {
diag_->Error(DiagMessage() << "No dump container specified");
return 1;
}
bool error = false;
for (auto container : args) {
io::FileInputStream input(container);
if (input.HadError()) {
context.GetDiagnostics()->Error(DiagMessage(container)
<< "failed to open file: " << input.GetError());
error = true;
continue;
}
// Try as a compiled file.
ContainerReader reader(&input);
if (reader.HadError()) {
context.GetDiagnostics()->Error(DiagMessage(container)
<< "failed to read container: " << reader.GetError());
error = true;
continue;
}
printer_->Println("AAPT2 Container (APC)");
ContainerReaderEntry* entry;
std::string error;
while ((entry = reader.Next()) != nullptr) {
if (entry->Type() == ContainerEntryType::kResTable) {
printer_->Println("kResTable");
pb::ResourceTable pb_table;
if (!entry->GetResTable(&pb_table)) {
context.GetDiagnostics()->Error(DiagMessage(container)
<< "failed to parse proto table: " << entry->GetError());
error = true;
continue;
}
ResourceTable table;
error.clear();
if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
context.GetDiagnostics()->Error(DiagMessage(container)
<< "failed to parse table: " << error);
error = true;
continue;
}
printer_->Indent();
Debug::PrintTable(table, print_options, printer_);
printer_->Undent();
} else if (entry->Type() == ContainerEntryType::kResFile) {
printer_->Println("kResFile");
pb::internal::CompiledFile pb_compiled_file;
off64_t offset;
size_t length;
if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &length)) {
context.GetDiagnostics()->Error(DiagMessage(container)
<< "failed to parse compiled proto file: "
<< entry->GetError());
error = true;
continue;
}
ResourceFile file;
if (!DeserializeCompiledFileFromPb(pb_compiled_file, &file, &error)) {
context.GetDiagnostics()->Warn(DiagMessage(container)
<< "failed to parse compiled file: " << error);
error = true;
continue;
}
printer_->Indent();
DumpCompiledFile(file, Source(container), offset, length, printer_);
printer_->Undent();
}
}
}
return (error) ? 1 : 0;
}
int DumpBadgerCommand::Action(const std::vector<std::string>& args) {
printer_->Print(StringPrintf("%s", kBadgerData));
printer_->Print("Did you mean \"aapt2 dump badging\"?\n");
return 1;
}
int DumpConfigsCommand::Dump(LoadedApk* apk) {
ResourceTable* table = apk->GetResourceTable();
if (!table) {
GetDiagnostics()->Error(DiagMessage() << "Failed to retrieve resource table");
return 1;
}
// Comparison function used to order configurations
auto compare = [](android::ConfigDescription c1, android::ConfigDescription c2) -> bool {
return c1.compare(c2) < 0;
};
// Insert the configurations into a set in order to keep every configuarion seen
std::set<android::ConfigDescription, decltype(compare)> configs(compare);
for (auto& package : table->packages) {
for (auto& type : package->types) {
for (auto& entry : type->entries) {
for (auto& value : entry->values) {
configs.insert(value->config);
}
}
}
}
// Print the configurations in order
for (auto& config : configs) {
GetPrinter()->Print(StringPrintf("%s\n", config.to_string().data()));
}
return 0;
}
int DumpPackageNameCommand::Dump(LoadedApk* apk) {
Maybe<std::string> package_name = GetPackageName(apk);
if (!package_name) {
return 1;
}
GetPrinter()->Println(package_name.value());
return 0;
}
int DumpStringsCommand::Dump(LoadedApk* apk) {
ResourceTable* table = apk->GetResourceTable();
if (!table) {
GetDiagnostics()->Error(DiagMessage() << "Failed to retrieve resource table");
return 1;
}
// Load the run-time xml string pool using the flattened data
BigBuffer buffer(4096);
StringPool::FlattenUtf8(&buffer, table->string_pool, GetDiagnostics());
auto data = buffer.to_string();
android::ResStringPool pool(data.data(), data.size(), false);
Debug::DumpResStringPool(&pool, GetPrinter());
return 0;
}
int DumpStyleParentCommand::Dump(LoadedApk* apk) {
Maybe<std::string> package_name = GetPackageName(apk);
if (!package_name) {
return 1;
}
const auto target_style = ResourceName(package_name.value(), ResourceType::kStyle, style_);
const auto table = apk->GetResourceTable();
if (!table) {
GetDiagnostics()->Error(DiagMessage() << "Failed to retrieve resource table");
return 1;
}
Maybe<ResourceTable::SearchResult> target = table->FindResource(target_style);
if (!target) {
GetDiagnostics()->Error(
DiagMessage() << "Target style \"" << target_style.entry << "\" does not exist");
return 1;
}
Debug::PrintStyleGraph(table, target_style);
return 0;
}
int DumpTableCommand::Dump(LoadedApk* apk) {
if (apk->GetApkFormat() == ApkFormat::kProto) {
GetPrinter()->Println("Proto APK");
} else {
GetPrinter()->Println("Binary APK");
}
ResourceTable* table = apk->GetResourceTable();
if (!table) {
GetDiagnostics()->Error(DiagMessage() << "Failed to retrieve resource table");
return 1;
}
DebugPrintTableOptions print_options;
print_options.show_sources = true;
print_options.show_values = !no_values_;
Debug::PrintTable(*table, print_options, GetPrinter());
return 0;
}
int DumpXmlStringsCommand::Dump(LoadedApk* apk) {
DumpContext context;
bool error = false;
for (auto xml_file : files_) {
android::ResXMLTree tree;
if (apk->GetApkFormat() == ApkFormat::kProto) {
auto xml = apk->LoadXml(xml_file, GetDiagnostics());
if (!xml) {
error = true;
continue;
}
// Flatten the xml document to get a binary representation of the proto xml file
BigBuffer buffer(4096);
XmlFlattenerOptions options = {};
options.keep_raw_values = true;
XmlFlattener flattener(&buffer, options);
if (!flattener.Consume(&context, xml.get())) {
error = true;
continue;
}
// Load the run-time xml tree using the flattened data
std::string data = buffer.to_string();
tree.setTo(data.data(), data.size(), /** copyData */ true);
} else if (apk->GetApkFormat() == ApkFormat::kBinary) {
io::IFile* file = apk->GetFileCollection()->FindFile(xml_file);
if (!file) {
GetDiagnostics()->Error(DiagMessage(xml_file)
<< "File '" << xml_file << "' not found in APK");
error = true;
continue;
}
std::unique_ptr<io::IData> data = file->OpenAsData();
if (!data) {
GetDiagnostics()->Error(DiagMessage() << "Failed to open " << xml_file);
error = true;
continue;
}
// Load the run-time xml tree from the file data
tree.setTo(data->data(), data->size(), /** copyData */ true);
} else {
GetDiagnostics()->Error(DiagMessage(apk->GetSource()) << "Unknown APK format");
error = true;
continue;
}
Debug::DumpResStringPool(&tree.getStrings(), GetPrinter());
}
return (error) ? 1 : 0;
}
int DumpXmlTreeCommand::Dump(LoadedApk* apk) {
for (auto file : files_) {
auto xml = apk->LoadXml(file, GetDiagnostics());
if (!xml) {
return 1;
}
Debug::DumpXml(*xml, GetPrinter());
}
return 0;
}
int DumpOverlayableCommand::Dump(LoadedApk* apk) {
ResourceTable* table = apk->GetResourceTable();
if (!table) {
GetDiagnostics()->Error(DiagMessage() << "Failed to retrieve resource table");
return 1;
}
Debug::DumpOverlayable(*table, GetPrinter());
return 0;
}
const char DumpBadgerCommand::kBadgerData[2925] = {
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 95, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 61, 63, 86, 35, 40, 46, 46,
95, 95, 95, 95, 97, 97, 44, 32, 46, 124, 42, 33, 83, 62, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 58, 46, 58, 59, 61, 59, 61, 81, 81, 81, 81, 66, 96, 61, 61, 58, 46,
46, 46, 58, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 61, 59, 59, 59, 58, 106, 81, 81,
81, 81, 102, 59, 61, 59, 59, 61, 61, 61, 58, 46, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
61, 59, 59, 59, 58, 109, 81, 81, 81, 81, 61, 59, 59, 59, 59, 59, 58, 59, 59,
46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 46, 61, 59, 59, 59, 60, 81, 81, 81, 81, 87, 58,
59, 59, 59, 59, 59, 59, 61, 119, 44, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 47, 61, 59, 59,
58, 100, 81, 81, 81, 81, 35, 58, 59, 59, 59, 59, 59, 58, 121, 81, 91, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 46, 109, 58, 59, 59, 61, 81, 81, 81, 81, 81, 109, 58, 59, 59, 59,
59, 61, 109, 81, 81, 76, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 41, 87, 59, 61, 59, 41, 81, 81,
81, 81, 81, 81, 59, 61, 59, 59, 58, 109, 81, 81, 87, 39, 46, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
60, 81, 91, 59, 59, 61, 81, 81, 81, 81, 81, 87, 43, 59, 58, 59, 60, 81, 81,
81, 76, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 52, 91, 58, 45, 59, 87, 81, 81, 81, 81,
70, 58, 58, 58, 59, 106, 81, 81, 81, 91, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 93, 40,
32, 46, 59, 100, 81, 81, 81, 81, 40, 58, 46, 46, 58, 100, 81, 81, 68, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 46, 46, 32, 46,
46, 46, 32, 46, 32, 46, 45, 91, 59, 61, 58, 109, 81, 81, 81, 87, 46, 58, 61,
59, 60, 81, 81, 80, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 46,
61, 59, 61, 61, 61, 59, 61, 61, 59, 59, 59, 58, 58, 46, 46, 41, 58, 59, 58,
81, 81, 81, 81, 69, 58, 59, 59, 60, 81, 81, 68, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32,
32, 32, 32, 32, 58, 59, 61, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 61, 61, 46, 61, 59, 93, 81, 81, 81, 81, 107, 58, 59, 58, 109, 87, 68,
96, 32, 32, 32, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 10, 32, 32, 32, 46, 60, 61, 61, 59, 59, 59, 59, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 58, 58, 58, 115, 109, 68, 41, 36,
81, 109, 46, 61, 61, 81, 69, 96, 46, 58, 58, 46, 58, 46, 46, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 46, 32, 95, 81, 67,
61, 61, 58, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 58, 68, 39, 61, 105, 61, 63, 81, 119, 58, 106, 80, 32, 58, 61, 59, 59,
61, 59, 61, 59, 61, 46, 95, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 10, 32, 32, 36, 81, 109, 105, 59, 61, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 46, 58, 37, 73, 108, 108, 62, 52, 81,
109, 34, 32, 61, 59, 59, 59, 59, 59, 59, 59, 59, 59, 61, 59, 61, 61, 46, 46,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 46, 45, 57, 101, 43, 43, 61,
61, 59, 59, 59, 59, 59, 59, 61, 59, 59, 59, 59, 59, 59, 59, 59, 59, 58, 97,
46, 61, 108, 62, 126, 58, 106, 80, 96, 46, 61, 61, 59, 59, 59, 59, 59, 59, 59,
59, 59, 59, 59, 59, 59, 61, 61, 97, 103, 97, 32, 32, 32, 32, 32, 32, 32, 10,
32, 32, 32, 32, 45, 46, 32, 46, 32, 32, 32, 32, 32, 32, 32, 32, 45, 45, 45,
58, 59, 59, 59, 59, 61, 119, 81, 97, 124, 105, 124, 124, 39, 126, 95, 119, 58, 61,
58, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 61, 119, 81, 81,
99, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 58, 59, 59, 58, 106, 81, 81, 81, 109, 119,
119, 119, 109, 109, 81, 81, 122, 58, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 59, 58, 115, 81, 87, 81, 102, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 61, 58,
59, 61, 81, 81, 81, 81, 81, 81, 87, 87, 81, 81, 81, 81, 81, 58, 59, 59, 59,
59, 59, 59, 59, 59, 58, 45, 45, 45, 59, 59, 59, 41, 87, 66, 33, 32, 32, 32,
32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 58, 59, 59, 93, 81, 81, 81, 81, 81, 81, 81, 81, 81,
81, 81, 81, 81, 40, 58, 59, 59, 59, 58, 45, 32, 46, 32, 32, 32, 32, 32, 46,
32, 126, 96, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 58, 61, 59, 58, 81,
81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 40, 58, 59, 59, 59, 58, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 58, 59, 59, 58, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81,
81, 40, 58, 59, 59, 59, 46, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 58, 61, 59, 60, 81, 81, 81, 81,
81, 81, 81, 81, 81, 81, 81, 81, 81, 59, 61, 59, 59, 61, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
58, 59, 59, 93, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 40, 59,
59, 59, 59, 32, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 58, 61, 58, 106, 81, 81, 81, 81, 81, 81, 81,
81, 81, 81, 81, 81, 81, 76, 58, 59, 59, 59, 32, 46, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 61, 58, 58,
81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 87, 58, 59, 59, 59, 59,
32, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 58, 59, 61, 41, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81,
81, 81, 87, 59, 61, 58, 59, 59, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 58, 61, 58, 61, 81, 81,
81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 107, 58, 59, 59, 59, 59, 58, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 58, 59, 59, 58, 51, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 102, 94,
59, 59, 59, 59, 59, 61, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 58, 61, 59, 59, 59, 43, 63, 36, 81,
81, 81, 87, 64, 86, 102, 58, 59, 59, 59, 59, 59, 59, 59, 46, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 61,
59, 59, 59, 59, 59, 59, 59, 43, 33, 58, 126, 126, 58, 59, 59, 59, 59, 59, 59,
59, 59, 59, 59, 32, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 46, 61, 59, 59, 59, 58, 45, 58, 61, 59, 58, 58, 58, 61,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 58, 32, 46, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 61, 59, 59, 59, 59, 59,
58, 95, 32, 45, 61, 59, 61, 59, 59, 59, 59, 59, 59, 59, 45, 58, 59, 59, 59,
59, 61, 58, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 58, 61, 59, 59, 59, 59, 59, 61, 59, 61, 46, 46, 32, 45, 45, 45, 59, 58,
45, 45, 46, 58, 59, 59, 59, 59, 59, 59, 61, 46, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 46, 58, 59, 59, 59, 59, 59, 59, 59, 59, 59,
61, 59, 46, 32, 32, 46, 32, 46, 32, 58, 61, 59, 59, 59, 59, 59, 59, 59, 59,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 45,
59, 59, 59, 59, 59, 59, 59, 59, 58, 32, 32, 32, 32, 32, 32, 32, 32, 32, 61,
59, 59, 59, 59, 59, 59, 59, 58, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 46, 61, 59, 59, 59, 59, 59, 59, 59, 32, 46, 32,
32, 32, 32, 32, 32, 61, 46, 61, 59, 59, 59, 59, 59, 59, 58, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 61, 59, 59, 59,
59, 59, 59, 59, 59, 32, 46, 32, 32, 32, 32, 32, 32, 32, 46, 61, 58, 59, 59,
59, 59, 59, 58, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 58, 59, 59, 59, 59, 59, 59, 59, 59, 46, 46, 32, 32, 32, 32,
32, 32, 32, 61, 59, 59, 59, 59, 59, 59, 59, 45, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 32, 45, 61, 59, 59, 59, 59,
59, 58, 32, 46, 32, 32, 32, 32, 32, 32, 32, 58, 59, 59, 59, 59, 59, 58, 45,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 45, 45, 45, 45, 32, 46, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 45, 61, 59, 58, 45, 45, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 46, 32, 32, 46, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 10};
} // namespace aapt
| 47.545133 | 99 | 0.498827 | [
"vector"
] |
3987aacc938e67b56d3d3d608f4aa3b01dff5dff | 9,688 | hpp | C++ | graphblas/backend/apspie/DenseMatrix.hpp | owensgroup/push-pull | b50b1d1fd07788bcfde9f58bfa58dc6eea2db18a | [
"Apache-2.0"
] | 7 | 2018-08-07T06:37:36.000Z | 2022-02-25T13:17:11.000Z | graphblas/backend/apspie/DenseMatrix.hpp | owensgroup/push-pull | b50b1d1fd07788bcfde9f58bfa58dc6eea2db18a | [
"Apache-2.0"
] | 2 | 2018-08-21T11:55:19.000Z | 2018-12-06T20:22:58.000Z | graphblas/backend/apspie/DenseMatrix.hpp | owensgroup/push-pull | b50b1d1fd07788bcfde9f58bfa58dc6eea2db18a | [
"Apache-2.0"
] | 2 | 2019-04-05T00:14:01.000Z | 2022-01-31T20:21:22.000Z | #ifndef GRB_BACKEND_APSPIE_DENSEMATRIX_HPP
#define GRB_BACKEND_APSPIE_DENSEMATRIX_HPP
#include <vector>
#include <iostream>
#include <typeinfo>
#include "graphblas/types.hpp"
#include "graphblas/backend/apspie/apspie.hpp"
namespace graphblas
{
namespace backend
{
template <typename T>
class SparseMatrix;
template <typename T>
class DenseMatrix
{
public:
DenseMatrix()
: nrows_(0), ncols_(0), nvals_(0),
h_denseVal_(NULL), d_denseVal_(NULL), need_update_(0) {}
DenseMatrix( Index nrows, Index ncols )
: nrows_(nrows), ncols_(ncols), nvals_(nrows*ncols),
h_denseVal_(NULL), d_denseVal_(NULL), need_update_(0) {}
~DenseMatrix() {}
// C API Methods
Info nnew( Index nrows, Index ncols );
Info dup( const DenseMatrix* rhs );
Info clear();
Info nrows( Index* nrows_t ) const;
Info ncols( Index* ncols_t ) const;
Info nvals( Index* nvals_t ) const;
template <typename BinaryOpT>
Info build( const std::vector<Index>* row_indices,
const std::vector<Index>* col_indices,
const std::vector<T>* values,
Index nvals,
BinaryOpT dup );
Info build( const std::vector<T>* values,
Index nvals );
Info setElement( Index row_index,
Index col_index );
Info extractElement( T* val,
Index row_index,
Index col_index );
Info extractTuples( std::vector<Index>* row_indices,
std::vector<Index>* col_indices,
std::vector<T>* values,
Index* n );
Info extractTuples( std::vector<T>* values,
Index* n );
// Handy methods
const T operator[]( Index ind );
Info print( bool force_update);
Info setNrows( Index nrows );
Info setNcols( Index ncols );
Info resize( Index nrows,
Index ncols );
template <typename U>
Info fill( Index axis,
Index nvals,
U start );
template <typename U>
Info fillAscending( Index axis,
Index nvals,
U start );
private:
Info allocate();
Info printDense() const;
Info cpuToGpu();
Info gpuToCpu( bool force_update=false );
private:
Index nrows_;
Index ncols_;
Index nvals_;
// Dense format
T* h_denseVal_;
T* d_denseVal_;
bool need_update_;
/*template <typename c, typename a, typename b>
friend Info spmm( DenseMatrix<c>& C,
const SparseMatrix<a>& A,
const DenseMatrix<b>& B );
// For testing
template <typename c, typename a, typename b>
friend Info spmm( DenseMatrix<c>& C,
const SparseMatrix<a>& A,
const DenseMatrix<b>& B,
const int TA,
const int TB,
const int NT,
const bool ROW_MAJOR );
template <typename c, typename a, typename b>
friend Info cusparse_spmm( DenseMatrix<c>& C,
const SparseMatrix<a>& A,
const DenseMatrix<b>& B );*/
};
template <typename T>
Info DenseMatrix<T>::nnew( Index nrows, Index ncols )
{
nrows_ = nrows;
ncols_ = ncols;
nvals_ = nrows_*ncols_;
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::dup( const DenseMatrix* rhs )
{
if( nrows_ != rhs->nrows_ ) return GrB_DIMENSION_MISMATCH;
if( ncols_ != rhs->ncols_ ) return GrB_DIMENSION_MISMATCH;
nvals_ = rhs->nvals_;
Info err = allocate();
if( err != GrB_SUCCESS ) return err;
//std::cout << "copying " << nrows_+1 << " rows\n";
//std::cout << "copying " << nvals_+1 << " rows\n";
CUDA( cudaMemcpy( d_denseVal_, rhs->d_denseVal_, nvals_*sizeof(T),
cudaMemcpyDeviceToDevice ) );
CUDA( cudaDeviceSynchronize() );
need_update_ = true;
return err;
}
template <typename T>
Info DenseMatrix<T>::clear()
{
if( h_denseVal_ ) free(h_denseVal_);
if( d_denseVal_ ) CUDA( cudaFree(d_denseVal_) );
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::nrows( Index* nrows_t ) const
{
*nrows_t = nrows_;
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::ncols( Index* ncols_t ) const
{
*ncols_t = ncols_;
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::nvals( Index* nvals_t ) const
{
*nvals_t = nvals_;
return GrB_SUCCESS;
}
template <typename T>
template <typename BinaryOpT>
Info DenseMatrix<T>::build( const std::vector<Index>* row_indices,
const std::vector<Index>* col_indices,
const std::vector<T>* values,
Index nvals,
BinaryOpT dup )
{
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::build( const std::vector<T>* values,
Index nvals )
{
if( nvals > nvals_ ) return GrB_DIMENSION_MISMATCH;
Info err = allocate();
if( err != GrB_SUCCESS ) return err;
// Host copy
for( graphblas::Index i=0; i<nvals_; i++ )
h_denseVal_[i] = (*values)[i];
err = cpuToGpu();
return err;
}
template <typename T>
Info DenseMatrix<T>::setElement( Index row_index,
Index col_index )
{
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::extractElement( T* val,
Index row_index,
Index col_index )
{
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::extractTuples( std::vector<Index>* row_indices,
std::vector<Index>* col_indices,
std::vector<T>* values,
Index* n )
{
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::extractTuples( std::vector<T>* values, Index* n )
{
Info err = gpuToCpu();
values->clear();
if( *n>nvals_ )
{
err = GrB_UNINITIALIZED_OBJECT;
*n = nvals_;
}
else if( *n<nvals_ )
err = GrB_INSUFFICIENT_SPACE;
for( Index i=0; i<*n; i++ ) {
values->push_back( h_denseVal_[i] );
}
return err;
}
template <typename T>
const T DenseMatrix<T>::operator[]( Index ind )
{
return T(0);
}
template <typename T>
Info DenseMatrix<T>::print( bool force_update )
{
Info err = gpuToCpu( force_update );
printArray( "denseVal", h_denseVal_, std::min(nvals_,40) );
printDense();
return err;
}
template <typename T>
Info DenseMatrix<T>::setNrows( Index nrows )
{
nrows_ = nrows;
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::setNcols( Index ncols )
{
ncols_ = ncols;
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::resize( Index nrows, Index ncols )
{
return GrB_SUCCESS;
}
template <typename T>
template <typename U>
Info DenseMatrix<T>::fill( Index axis,
Index nvals,
U start )
{
return GrB_SUCCESS;
}
template <typename T>
template <typename U>
Info DenseMatrix<T>::fillAscending( Index axis,
Index nvals,
U start )
{
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::allocate()
{
// Host alloc
if( nvals_!=0 && h_denseVal_ == NULL )
h_denseVal_ = (T*)malloc(nvals_*sizeof(T));
for( Index i=0; i<nvals_; i++ )
h_denseVal_[i] = (T) 0;
if( nvals_!=0 && d_denseVal_ == NULL )
CUDA( cudaMalloc( &d_denseVal_, nvals_*sizeof(T) ) );
if( h_denseVal_==NULL || d_denseVal_==NULL ) return GrB_OUT_OF_MEMORY;
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::printDense() const
{
Index row_length=std::min(20,nrows_);
Index col_length=std::min(20,ncols_);
for( Index row=0; row<row_length; row++ )
{
for( Index col=0; col<col_length; col++ )
{
// Print row major order matrix in row major order by default
//if( major_type_ == GrB_ROWMAJOR )
//{
if( h_denseVal_[row*ncols_+col]!=0.0 ) std::cout << "x ";
else std::cout << "0 ";
// Print column major order matrix in row major order (Transposition)
/*}
else if (major_type_ == GrB_COLMAJOR )
{
if( h_denseVal_[col*nrows_+row]!=0.0 ) std::cout << "x ";
else std::cout << "0 ";
}*/
}
std::cout << std::endl;
}
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::cpuToGpu()
{
CUDA( cudaMemcpy( d_denseVal_, h_denseVal_, nvals_*sizeof(T),
cudaMemcpyHostToDevice ) );
return GrB_SUCCESS;
}
template <typename T>
Info DenseMatrix<T>::gpuToCpu( bool force_update )
{
if( need_update_ || force_update )
CUDA( cudaMemcpy( h_denseVal_, d_denseVal_, nvals_*sizeof(T),
cudaMemcpyDeviceToHost ) );
need_update_ = false;
return GrB_SUCCESS;
}
} // backend
} // graphblas
#endif // GRB_BACKEND_APSPIE_DENSEMATRIX_HPP
| 26.542466 | 77 | 0.553159 | [
"vector"
] |
398d6ced1c925820d5b8171c70b2e8ee080b7a34 | 3,740 | cpp | C++ | src/Game.cpp | Malguzt/TestingBox2d | 408c9c6d94adc27c915946349ff8a7de2ecbdf66 | [
"MIT"
] | null | null | null | src/Game.cpp | Malguzt/TestingBox2d | 408c9c6d94adc27c915946349ff8a7de2ecbdf66 | [
"MIT"
] | null | null | null | src/Game.cpp | Malguzt/TestingBox2d | 408c9c6d94adc27c915946349ff8a7de2ecbdf66 | [
"MIT"
] | null | null | null | #include "Game.h"
Game::Game()
{
pWnd = new RenderWindow(VideoMode(1280, 768), "Testing box2d");
pWnd->setVisible(true);
fps = 60;
pWnd->setFramerateLimit(fps);
frameTime = 1.0f / fps;
setZoom();
initPhysics();
theBarrel = new Barrel(phyWorld, pWnd, 20.0f, 80.0f);
}
Game::~Game()
{
delete phyWorld;
delete pWnd;
}
void Game::Go()
{
Event evt;
while(pWnd->isOpen())
{
while (pWnd->pollEvent(evt))
{
processEvent(evt);
}
pWnd->clear();
updateGame();
drawGame();
pWnd->display();
}
}
void Game::processEvent(Event &evt)
{
switch (evt.type)
{
case Event::Closed:
pWnd->close();
break;
case Event::KeyPressed:
processKey(evt.key.code);
break;
case Event::MouseButtonPressed:
ragdolls.push_back(new Ragdoll(phyWorld, pWnd, theBarrel->body->GetPosition().x + 60, theBarrel->body->GetPosition().y - 60));
ragdolls.back()->applyForce(LONG_MAX, -LONG_MAX);
//board.checkClick(Vector2i(evt.mouseButton.x, evt.mouseButton.y), *pWnd);
break;
}
}
void Game::processKey(int keyCode)
{
switch(keyCode)
{
case Keyboard::Escape:
pWnd->close();
break;
}
}
void Game::updateGame()
{
phyWorld->Step(frameTime,8,8);
// phyWorld->ClearForces();
phyWorld->DrawDebugData();
theBarrel->updatePosition(Mouse::getPosition(*pWnd));
for (std::vector<Ragdoll*>::iterator it = ragdolls.begin(); it != ragdolls.end(); ++it)
{
(*it)->updatePosition();
}
}
void Game::drawGame()
{
for (std::vector<Ragdoll*>::iterator it = ragdolls.begin(); it != ragdolls.end(); ++it)
{
(*it)->draw();
}
theBarrel->draw();
}
void Game::initPhysics(){
//Set the gravity
phyWorld = new b2World(b2Vec2(0.0f, 9.8f));
//Set the debuger
debugRender = new SFMLRenderer(pWnd);
debugRender->SetFlags(UINT_MAX);
phyWorld->SetDebugDraw(debugRender);
//Create floor and walls
b2Body* groundBody = Game::CreateRectangularStaticBody(phyWorld,1000,10);
groundBody->SetTransform(b2Vec2(500.0f,1000.0f),0.0f);
b2Body* leftWallBody = Game::CreateRectangularStaticBody(phyWorld,10,1000);
leftWallBody->SetTransform(b2Vec2(0.0f,500.0f),0.0f);
b2Body* rightWallBody = Game::CreateRectangularStaticBody(phyWorld,10,1000);
rightWallBody->SetTransform(b2Vec2(1000.0f,500.0f),0.0f);
//Create the ceiling
b2Body* topWallBody = Game::CreateRectangularStaticBody(phyWorld,1000,10);
topWallBody->SetTransform(b2Vec2(500.0f,0.0f),0.0f);
}
b2Body* Game::CreateRectangularStaticBody(b2World *phyWorld, float sizeX, float sizeY){
b2Body* body = CreateStaticBody(phyWorld);
b2FixtureDef box = CreateRectangularFixtureDef(sizeX,sizeY,0.0f,0.5f,0.5f);
body->CreateFixture(&box);
return body;
}
b2Body* Game::CreateStaticBody(b2World *phyWorld){
b2Body * body;
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(0.0f, 0.0f);
body = phyWorld->CreateBody(&bodyDef);
return body;
}
b2FixtureDef Game::CreateRectangularFixtureDef(float sizeX, float sizeY, float density, float friction,float restitution){
b2PolygonShape* box= new b2PolygonShape();
box->SetAsBox(sizeX/2.0f, sizeY/2.0f,b2Vec2(0.0f,0.0f),0.0f);
b2FixtureDef fixtureDef;
fixtureDef.shape = box;
fixtureDef.density = density;
fixtureDef.friction = friction;
fixtureDef.restitution=restitution;
return fixtureDef;
}
void Game::setZoom(){
View camara;
camara.setSize(1000.0f, 1000.0f);
camara.setCenter(500.0f, 500.0f);
pWnd->setView(camara);
}
| 23.974359 | 138 | 0.640909 | [
"shape",
"vector"
] |
39902086e9a6bcd493198fbdbea75e7d461c04c7 | 2,613 | cpp | C++ | AtCoder/typical90/026 - Independent Set on a Tree/main.cpp | t-mochizuki/cpp-study | df0409c2e82d154332cb2424c7810370aa9822f9 | [
"MIT"
] | 1 | 2020-05-24T02:27:05.000Z | 2020-05-24T02:27:05.000Z | AtCoder/typical90/026 - Independent Set on a Tree/main.cpp | t-mochizuki/cpp-study | df0409c2e82d154332cb2424c7810370aa9822f9 | [
"MIT"
] | null | null | null | AtCoder/typical90/026 - Independent Set on a Tree/main.cpp | t-mochizuki/cpp-study | df0409c2e82d154332cb2424c7810370aa9822f9 | [
"MIT"
] | null | null | null | // g++ -std=c++14 -DDEV=1 main.cpp
#include <stdio.h>
#include <cassert>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
using std::cin;
using std::cout;
using std::endl;
using std::terminate;
using std::vector;
using std::map;
using std::make_pair;
#define rep(i, a, n) for (int i = (a); i < (n); ++i)
#define bit(n, k) ((n >> k) & 1)
class Problem {
private:
int N;
map<int, vector<int>> E;
vector<bool> visited;
vector<bool> colors;
void debug() {
rep(i, 1, N+1) {
cout << colors[i] << endl;
}
cout << endl;
}
void ans(int stop, bool color) {
bool first = true;
int cnt = 0;
rep(i, 1, N+1) {
if (cnt == stop) break;
if (first) {
first = false;
if (color == colors[i]) {
cout << i;
cnt++;
}
} else {
if (color == colors[i]) {
cout << " " << i;
cnt++;
}
}
}
cout << endl;
}
public:
Problem() {
cin >> N;
assert(N % 2 == 0);
assert(2 <= N);
assert(N <= 100000);
for (int x = 1; x <= N-1; ++x) {
int a, b; cin >> a >> b;
assert(1 <= a);
assert(a <= N);
assert(1 <= b);
assert(b <= N);
assert(a < b);
if (E.find(a) == E.end()) {
E.insert(make_pair(a, vector<int>(1, b)));
} else {
E[a].push_back(b);
}
if (E.find(b) == E.end()) {
E.insert(make_pair(b, vector<int>(1, a)));
} else {
E[b].push_back(a);
}
}
visited.assign(N+1, false);
colors.assign(N+1, false);
}
void visit(int from, bool color) {
if (visited[from]) return ;
visited[from] = true;
for (auto to : E[from]) {
visit(to, !color);
}
colors[from] = color;
}
void solve() {
int from = 1;
visit(from, true);
int cnt = 0;
rep(i, 1, N+1) if (colors[i]) cnt++;
if (cnt < N/2) {
ans(N/2, false);
} else {
ans(N/2, true);
}
}
};
int main() {
#ifdef DEV
std::ifstream in("input");
cin.rdbuf(in.rdbuf());
int t; cin >> t;
for (int x = 1; x <= t; ++x) {
Problem p;
p.solve();
}
#else
Problem p;
p.solve();
#endif
return 0;
}
| 19.355556 | 58 | 0.395714 | [
"vector"
] |
3991f2eed6e56dc3dc432cd4d6eaa32d19659b9b | 4,269 | cxx | C++ | smtk/model/operators/DivideInstance.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 40 | 2015-02-21T19:55:54.000Z | 2022-01-06T13:13:05.000Z | smtk/model/operators/DivideInstance.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 127 | 2015-01-15T20:55:45.000Z | 2021-08-19T17:34:15.000Z | smtk/model/operators/DivideInstance.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 27 | 2015-03-04T14:17:51.000Z | 2021-12-23T01:05:42.000Z | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt 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 "smtk/model/operators/DivideInstance.h"
#include "smtk/model/Entity.h"
#include "smtk/model/Instance.h"
#include "smtk/model/Instance.txx"
#include "smtk/model/Resource.h"
#include "smtk/model/Resource.txx"
#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ComponentItem.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/ModelEntityItem.h"
#include "smtk/attribute/StringItem.h"
#include "smtk/attribute/VoidItem.h"
#include "smtk/model/DivideInstance_xml.h"
using namespace smtk::model;
namespace smtk
{
namespace model
{
bool DivideInstance::ableToOperate()
{
if (!this->Superclass::ableToOperate())
{
return false;
}
// Check that the associated instance is cloned or has cloned children
// that we can use to divide its placements.
Instance parent = this->parentOfClones(this->parameters()->associations());
return parent.isValid();
}
DivideInstance::Result DivideInstance::operateInternal()
{
auto associations = this->parameters()->associations();
Instance instance = this->parentOfClones(associations);
smtk::model::ResourcePtr resource = instance.resource();
if (!resource || !instance.isValid())
{
return this->createResult(smtk::operation::Operation::Outcome::FAILED);
}
Result result = this->createResult(smtk::operation::Operation::Outcome::SUCCEEDED);
auto created = result->findComponent("created");
auto modified = result->findComponent("modified");
auto expunged = result->findComponent("expunged");
// Divide instance.
std::set<smtk::model::Instance> children;
auto divided = instance.divide(/* merge */ false, &children);
if (divided.find(instance) == divided.end())
{
// The output instance is not the input. So it is
// safe to delete the input.
children.insert(children.end(), instance);
}
for (const auto& entry : children)
{
expunged->appendValue(entry.entityRecord());
}
smtk::model::EntityRefArray delExpunged;
smtk::model::EntityRefArray delModified;
resource->deleteEntities(children, delModified, delExpunged, m_debugLevel > 0);
for (const auto& entry : divided)
{
if (entry == instance)
{
continue;
}
created->appendValue(entry.entityRecord());
}
for (const auto& tmp : delExpunged)
{
expunged->appendValue(tmp.entityRecord());
}
for (const auto& tmp : delModified)
{
modified->appendValue(tmp.entityRecord());
}
return result;
}
const char* DivideInstance::xmlDescription() const
{
return DivideInstance_xml;
}
smtk::model::Instance DivideInstance::parentOfClones(
const smtk::attribute::ReferenceItemPtr& item) const
{
auto instances = item->as<Instances>([](smtk::resource::PersistentObjectPtr obj) {
return smtk::model::Instance(std::dynamic_pointer_cast<smtk::model::Entity>(obj));
});
if (instances.empty())
{
smtkErrorMacro(this->log(), "No instances were provided.");
return smtk::model::Instance();
}
Instance result;
for (auto instance : instances)
{
Instance parent;
for (; (parent = instance.memberOf()).isValid();)
{
if (parent.isInstance())
{
instance = parent;
}
else
{
break;
}
}
if (!result.isValid())
{
result = instance;
}
else if (result != instance)
{
smtkErrorMacro(
this->log(),
"The given instance has clones with different parent "
"instances ("
<< result.name() << ", " << instance.name() << ").");
return smtk::model::Instance();
}
}
smtk::model::ResourcePtr resource = result.resource();
if (!resource || !result.isValid())
{
smtkErrorMacro(this->log(), "The given instance is invalid.");
return smtk::model::Instance();
}
return result;
}
} //namespace model
} // namespace smtk
| 27.365385 | 86 | 0.653549 | [
"model"
] |
39932b965d2cc000aa116dd12f49b62b099f1dd6 | 617 | cpp | C++ | nodes/group_regex_node.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | nodes/group_regex_node.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | nodes/group_regex_node.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | #include "group_regex_node.hpp"
using rand_regex::group_regex_node_;
group_regex_node_::group_regex_node_(std::vector<regex_node_*>&& grouped_nodes)
: grouped_nodes_(grouped_nodes)
{
//
}
void group_regex_node_::generate(std::ostream& os, random_generator_base& random_gen, std::vector<std::tuple<int, regex_node_*>>& groups)
{
for(const auto node : grouped_nodes_)
node->generate(os, random_gen, groups);
}
void group_regex_node_::regenerate(std::ostream& os, const std::vector<std::tuple<int, regex_node_*>>& groups) const
{
for(const auto node : grouped_nodes_)
node->regenerate(os, groups);
}
| 28.045455 | 137 | 0.750405 | [
"vector"
] |
3993512904eb37696a20281339e24a70cbb5d517 | 550 | cpp | C++ | Leetcode1760.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | 1 | 2020-06-28T06:29:05.000Z | 2020-06-28T06:29:05.000Z | Leetcode1760.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | null | null | null | Leetcode1760.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
bool check(vector<int>& nums, int op, int v) {
for (int x : nums) {
op -= (x - 1) / v;
if (op < 0) return 0;
}
return op >= 0;
}
int minimumSize(vector<int>& nums, int maxOperations) {
int n = nums.size();
int r = 0, l = 1;
for (int x: nums) r = max(r, x);
while (l < r) {
int mid = l + r >> 1;
if (check(nums, maxOperations, mid)) r = mid;
else l = mid + 1;
}
return l;
}
};
| 23.913043 | 59 | 0.416364 | [
"vector"
] |
3998eb100ed00bf4c2bf7be99581e637a7a9c2f2 | 30,102 | cpp | C++ | automata-1.0.0/Automata.cpp | booherbg/PyAutomata | 432555806dd68ff6a8c05b525fa25ab8ac0a80fe | [
"Apache-2.0"
] | 1 | 2018-09-19T07:27:31.000Z | 2018-09-19T07:27:31.000Z | automata-1.0.0/Automata.cpp | booherbg/PyAutomata | 432555806dd68ff6a8c05b525fa25ab8ac0a80fe | [
"Apache-2.0"
] | null | null | null | automata-1.0.0/Automata.cpp | booherbg/PyAutomata | 432555806dd68ff6a8c05b525fa25ab8ac0a80fe | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2008 Alex Reynolds
*
* 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.
*
* Automata.cpp
* Automata
*
* Notes about this framework.
* Automata has an internal "buffer" that fills up, generation by generation,
* as iterateAutomata() is executed. This means that you set the number of
* generations in the header, and when you "fill" the buffer, you execute
* the iteration until the buffer is full. This gives you the benefit of:
* 1) Pre-allocated size for known number of generations
* 2) Execute one time, get the entire CA history
*
* You can get a single generation by creating a g* = new AutomataGeneration() bitset,
* and passing it into generationAtIndex(*g, int) along with an integer. To get the
* integer of the current index, call getCurrentIndex(). The call to
* currentGeneration(*g) is simply generationAtIndex(*g, getCurrentIndex());
*
* I have taken the liberty of adding specific interfaces for accessing the
* data contained in the "current generation" (ie last generation computed)
* This framework was originally written by the author to compute and display
* arbitrary 2Dimensional CAs; the only necessary output was the 2D structure. The
* main public function originally available for this purpose is Automata.stringFromGeneration(&g,int).
* I have added the trivial Automata.stringFromCurrentGeneration().
* Along with:
* unsigned char *bytes_FromGeneration(AutomataGeneration &, int&)
* unsigned char *bytes_FromCurrentGeneration(int&)
* These create a byte array representation of the given automata
* generation. The generation is broken up into chunks of 8 bits starting
* from the left-most bit. Each chunk is converted into an unsigned char (1-byte).
* The character array is malloc's inside the functions, so the user must
* take care to free() any char* array that is created. The integer
* argument is a second output - it will be set as the length of the byte array.
*
* unsigned char *bStringFromGeneration(AutomataGeneration &)
* bStringFromCurrentGeneration()
* Identical to stringFromGeneration except that the ascii characters
* for '0' and '1' are used instead of the default characters. Useful
* for slow byt guaranteed binary output from the Automata. Could be
* used to output to stdout, for example.
* The reason that *FromCurrentGeneration() exists is that it has no prototype
* dependencies on the AutomataGeneration bitset. This can be easily and
* seamilessly used by the cython compiler for direct access to the buffer,
* returned as a std::string or unsigned char * (easy datatypes to work with
* on the python side). At this point in time I'm not sure how to directly
* access the AutomataGeneration bitset, however it appears that there is no
* immediate need for direct access. These supporting functions are doing just fine.
*
* Possible Bugs:
* Interestingly enough, it appears that the following happens:
* 1) _generations = new AutomataGenerations is initialized to <kAutomataGenerations> rows
* 2) I think each row in AutomataGenerations is created with default constructor (kAutomataGenerationLength)
* 3) Once the true ca width comes through, either the size() is updated to a brand new
* vector (leaving the first vectors hanging in memory) or the print-off
* is restricted to the correct range. Not sure, yet.
* Either way something strange is happening
*
* Seems that a new vector is created every single time, and is either copied
* or replaces the existing vector. Either way a single destructor is called
* with every constructor, there doesn't seem to be any dangling pointers.
* All is good and sane.
*/
#include "Automata.h"
//#pragma mark -
//#pragma mark Constructors
/* I added this as a class so that we can set how large a generation is at run time
* This just isn't possible with bitset - it has to be set at compile time.
*
* set() and reset() are used for compatibility
*/
AutomataGeneration::AutomataGeneration(unsigned int generationLength)
{
this->generationLength = generationLength;
this->_vector = new std::vector<bool>(generationLength);
//cout << "creating AutomataGeneration with size=" << generationLength << "\n";
/*for (unsigned int i=0; i < generationLength; i++)
{
//(*this->_vector).push_back(0);
cout << " " << (*this->_vector).size();
}*/
reset();
}
/* It appears that this is being called the appropriate number of times */
/*
AutomataGeneration::~AutomataGeneration() {
cout << "deleting vector" << endl;
}
*/
void AutomataGeneration::reset()
{
//cout << "AutomataGeneration::reset();size=" << generationLength << "|" << (*this->_vector).size() << "\n";
for (unsigned int i=0; i < generationLength; i++)
{
(*this->_vector)[i] = 0; // shorthand for clearing a bitset
}
}
void AutomataGeneration::clear(unsigned int index){ (*this->_vector)[index] = 0; }
void AutomataGeneration::flip(unsigned int index){ (*this->_vector)[index].flip(); }
void AutomataGeneration::set(unsigned int index){ (*this->_vector)[index] = 1; }
unsigned int AutomataGeneration::size(){ return (*this->_vector).size(); }
/*
AutomataGeneration& AutomataGeneration::operator = (const AutomataGeneration &ref) {
*_vector = *(ref._vector);
generationLength = ref.generationLength;
return *this;
}*/
Automata::Automata(
unsigned int rule,
unsigned int caWidth
/* unsigned int seedIsRandom,
unsigned int seedStartingPosition,
unsigned int generationLength) {
*/ ){
// cout << "Initializing automaton... (rule: " << rule
/* ", generationLength: " << generationLength <<
// ", seedIsRandom: " << seedIsRandom <<
// ", seedStartingPosition: " << seedStartingPosition << ")"
<< ")" << endl; */
this->p_rule=rule;
// this->p_seedIsRandom=seedIsRandom;
// this->p_seedStartingPosition=seedStartingPosition;
this->p_generationLength=caWidth;
try {
_currentIndex = -1;
_overallIndex = -1;
_generations = new AutomataGenerations(kAutomataGenerations); // 150
//typedef std::bitset< kAutomataGenerationLength > AutomataGeneration;
//typedef std::vector< AutomataGeneration > AutomataGenerations;
//typedef std::bitset< 100 > ag;
//void *p = new std::vector< std::bitset< kAutomataGenerationLength > >(10);
setBinaryRuleFromInteger(rule);
}
catch (std::bad_alloc &exc) {
cout << exc.what() << endl;
}
catch (...) {
delete _generations;
}
if (TIME_BASED_SEED)
{ // this was harder than i realized to get a seed not based on seconds
timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);
} else {
srand(SRAND_SEED);
}
//cout << "end init\n";
}
void Automata::init_seed(unsigned int mode, unsigned int value, unsigned int position)
{
/*
* This function is meant to handle everything relating to the seeding of the
* cellular automata. This was moved out of the constructor. I needed the option
* of specifying that the seed is random, a single cell, or a pre-set value.
*
* Throws exception 100 if the mode is invalid.
AutomataGeneration *g_seed = new AutomataGeneration;
if (seedIsRandom)
randomizeSeed(*g_seed);
else
initializeSeedAtPosition(*g_seed, seedStartingPosition);
validateGeneration(*g_seed);
appendGeneration(*g_seed);
delete g_seed;
*/
this->p_seedIsRandom=0;
this->p_seedStartingPosition=kDefaultSeedStartingPosition;
// reset back to the head of the buffer!
this->_currentIndex = -1;
this->_overallIndex = -1;
AutomataGeneration *g_seed=NULL;
//try
//{
g_seed = new AutomataGeneration(p_generationLength);
//(*g_seed).reset(); // or g_seed->reset()
//} catch (std::bad_alloc &exc)
//{
// cout << exc.what() << endl;
//}
//cout << "init_seed()1\n";
if (mode == 0)
{ // single centered cell
initializeSeedAtPosition(*g_seed, p_generationLength/2);
} else if (mode == 1)
{ // random seed
randomizeSeed(*g_seed);
this->p_seedIsRandom=1;
} else if (mode == 2)
{ // pre-specified value, centered
initializeSeedWithValue(*g_seed, value, position);
} else if (mode == 3)
{
// 010101010101 pattern
delete g_seed;
throw(101);
} else {
delete g_seed;
throw(101);
}
//cout << "init_seed()2\n";
validateGeneration(*g_seed);
//cout << "init_seed()2b\n";
appendGeneration(*g_seed); // increments _generationIndex
delete g_seed;
//cout << "init_seed()3\n";
}
void Automata::init_seed(unsigned int values[], unsigned int n)
{
/*
* This function is meant to handle everything relating to the seeding of the
* cellular automata. This was moved out of the constructor. I needed the option
* of specifying that the seed is random, a single cell, or a pre-set value.
*
* This function takes a list of 8-bit unsigned integers and places them
* into the a generation. The seeding is kind of strange but it works, so I'm
* not sure if I'm going to leave it as is or not...
*
* Basically the value in values[0] is mapped onto the generation from the
* left side, but it is "reversed" the bit value. So if the number that is
* seeded is 135, in binary that is 10000111. The seeded value is:
* (left) | 11100001 <second value> <third value> |
* So you can see that the value is seeded but it is seeded in reverse.
* Not a huge deal, but kind of strange.
*
* Let's say the vector looks like this:
* 0 10 20 30 40 50
* | | | | | |
* |____________________________________________________|
*
* If I want to make it look like this:
* 0 10 20 30 40 50
* | | | | | |
* |__________11111100000_______________________________|
* What convention do I use? Do i say I want 1111100000 at 10? Do I say I
* want 0000011111 at 20? Do I say I want 1111100000 at 15?
*
* I'm choosing that I say I want 1111100000 at 10. So you pass in a value
* that has left-most-significant-bit (16-bits) and the left-most index that
* you want to include the number (16-bit).
*
* so init_seed(value=0b1111100000, position=10) should work.
*
* A bug. apparently if the end of the vector is cut off, the number of
* digits remaining in the vector are set by the last two (not first two) of
* the number only. So if there are 10 digits and two 8-bit digits are used,
* like say 255 and 6, the last two will be 10 because 6 in binary ends with
* 10. Weird. Doesn't affect the rest. Cancel that. It simply puts it in
* without regard to what's already there. only sets one bits, ignores the
* rest. so 000100 with an 8 becomes 001100. weird.
*/
unsigned int i;
this->p_seedIsRandom=0;
this->p_seedStartingPosition=kDefaultSeedStartingPosition;
// reset back to the head of the buffer!
this->_currentIndex = -1;
this->_overallIndex = -1;
AutomataGeneration *g_seed=NULL;
try
{
g_seed = new AutomataGeneration(p_generationLength);
//(*g_seed).reset();
} catch (std::bad_alloc &exc)
{
cout << exc.what() << endl;
}
// what does this next line do? I forget. Why is '4' hard coded?
// looks like position is hard coded. That's weird.
// each value is an unsigned int. sizeof(unsigned int) == 4 (bytes) = 4*8=16
// next up: why do we set the position as the center?
// unsigned int position = (unsigned int)((sizeof(unsigned int)*BITS_PER_SEED_VALUE)/2);
unsigned int position = 0; // start at left-most side
// cout << "initial position: " << position << endl;
unsigned int value;
for (i=0; i<n; i++)
{
value = values[i];
initializeSeedWithValue(*g_seed, value, position);
position += sizeof(unsigned int)*BITS_PER_SEED_VALUE;
// cout << "next position: " << position << endl;
}
//cout << g_seed->count() << "------\n";
validateGeneration(*g_seed);
appendGeneration(*g_seed); // increments _generationIndex
delete g_seed;
}
void Automata::initializeSeedWithValue (AutomataGeneration &seed, unsigned int value, unsigned int position)
{
/*
* initializeSeedWithValue
* seed is an AutomataGeneration object to be worked with
* value is what value to seed with. unsigned int, so 16-bit by nature
*
* BITS_PER_SEED_VALUE will determine how many bits we'll use of <value>,
* although all entries in <value> will be packed tightly into the vector
* See Automata.h to set BITS_PER_SEED_VALUE
* 1: Use only the first 4 bits (0-15)
* 2: Use only the first 8 bits (0-255)
* 4: use only the first 16 bits (0-65535)
* 8: use entire range of the unsigned int: (0-4294967295)
*
* in other words, if BITS_PER_SEED_VALUE is 2:
* init_seed((255, 255, 255, 255))
* is the equivalent of the following if BITS_PER_SEED is 4:
* init_seed((65535, 65535))
*/
unsigned int n;
// n = (int)ceil(log2(value)); // number of bits required
n = sizeof(unsigned int)*BITS_PER_SEED_VALUE; // how many bits per chunk (16-bit)
bool bit = 0;
// cout << "position: " << position << endl;
// n is the width of the chunk to write, typically hard coded to be 16-bits
if (n > seed.size())
{
cout << "Warning: truncating seed because it is too large. ";
cout << n << "-bits truncated to " << seed.size() << "-bits\n";
n = seed.size();
}
// if we're trying to center too close to the end of the vector, no good
// should not do this, should skip if it is out of bounds but not adjust
// starting position since it causes overlap.
// if (position > (seed.size() - n))
// position = seed.size() - n;
// cout << "left: " << position << " w:" << w << endl;
// for (unsigned int i=0; i < n; ++i)
for (unsigned int i=(n); i > 0; i--) // weird, if we do >= 0 it wraps around into an infinite loop
{
// for each bit, set it appropriately
bit = value % 2;
if (bit == 1)
{
if ((i+position-1) < seed.size())
{
seed.set((i+position-1));
}
}
// cout << (i-1) << ":" << bit << " ";
value = value / 2;
}
}
Automata::Automata(const Automata& ref, unsigned int seedFromEndOfRef) {
_currentIndex = ref._currentIndex;
_overallIndex = ref._overallIndex;
for (unsigned int i = 0; i < kNumberOfRules; ++i)
_rule[i] = ref._rule[i];
if (seedFromEndOfRef)
_generations->at(0) = ref._generations->at(kAutomataGenerations-1);
else
for (unsigned int i = 0; i < kAutomataGenerations; ++i)
_generations->push_back(ref._generations->at(i));
}
Automata::~Automata()
{
//cout << "Deleting automaton..." << endl;
delete _generations;
}
/*
* C++ Operators
* Definitions for operators like << and =
*/
ostream& operator << (ostream &os, const Automata &ref) {
AutomataGeneration *test = new AutomataGeneration(ref.p_generationLength);
for (unsigned int i = 0; i < kAutomataGenerations; ++i) {
ref.generationAtIndex(*test, i);
os << i << " " << ref.stringFromGeneration(*test) << endl;
}
delete test;
return os;
}
Automata& Automata::operator = (const Automata &ref) {
_currentIndex = ref._currentIndex;
_overallIndex = ref._overallIndex;
_rule = ref._rule;
*_generations = *(ref._generations);
return *this;
}
/*
* Public Functions
* All publicly accessible functions
*/
void Automata::iterateAutomata () {
/* iterateAutomata
* This is the core function responsible for applying the rule to each
* generation in the automata. A single execution of this function:
* 0) If there is no seed, call init_seed() with default parameters
* 1) Create 2 bit generations, <current> and <next>
* 2) current = generationAtIndex(_currentIndex)
* 3) next = getNextGeneration(current)
* 4) Make sure it is a valid generation
* 5) Append the generation to the buffer and increment index
* 6) Delete both <current> and <next>. This might be optimizable
*/
try {
// Q: Why are these created each time?
// A: Because they are copied into the _generations vector and
// subsequently deleted.
AutomataGeneration *current = new AutomataGeneration(p_generationLength);
AutomataGeneration *next = new AutomataGeneration(p_generationLength);
if (_currentIndex == -1)
{
init_seed(0);
}
generationAtIndex(*current, _currentIndex);
getNextGeneration(*current, *next);
validateGeneration(*next);
appendGeneration(*next);
delete next;
delete current;
}
catch (std::bad_alloc &exc) {
cout << exc.what() << endl;
}
}
void Automata::printBuffer () const {
/*
* printBuffer
* prints out the automata 2D Buffer. It does this by creating a bit
* vector (AutomataGenerations) and setting it as each consecutive
* generation present in the buffer. Then that generation is printed
* out as a single line (via stringFromGeneration()).
*/
unsigned int const max_digits = 7;
if (_currentIndex == -1)
{
cout << "*** Warning: Cellular Automata not seeded. Please use init_seeds()\n";
return;
}
unsigned int digits=0;
AutomataGeneration *test = new AutomataGeneration(p_generationLength);
// cout << "test size to start out with is: " << (*test).size() << endl;
for (unsigned int i = 0; i < kAutomataGenerations; ++i) {
generationAtIndex(*test, i);
if (i == 0)
{
digits = 0;
} else {
digits = log10(i); // see how many positions we need
}
if (digits > max_digits)
{
digits = max_digits;
}
if (digits < 0)
{
digits = 0;
}
for (unsigned int j=0; j<(max_digits-digits); j++)
{
cout << " ";
}
// cout << "length: >>" << (*test).size() << " " << p_generationLength << " ";
cout << i << "|" << stringFromGeneration(*test) << "|" << endl;
}
delete test;
}
void Automata::fillBuffer ()
{
/* fillBuffer
* This function calls iterateAutomata() kAutomataGenerations-1 times.
* It appears this function is meant to really only be called one time.
* After it is called once, each consecutive time would continue to generate
* the buffer... but not overwrite it.
*/
for (unsigned int counter = 0; counter < kAutomataGenerations-1; ++counter)
iterateAutomata();
}
int Automata::currentGenerationIndex () const
{
return _currentIndex;
}
std::string Automata::stringFromGeneration (AutomataGeneration &g) const
{
std::string str(g.size(), kOffPixelChar);
for (unsigned int i = 0; i < g.size(); ++i)
{
str[i] = (g[i] == kOffPixel ? kOffPixelChar : kOnPixelChar);
}
return str;
}
std::string Automata::stringFromCurrentGeneration () const
{
std::string s;
AutomataGeneration *g = new AutomataGeneration(p_generationLength);
if (_currentIndex == -1)
{
cout << "*** Warning: Cellular Automata not seeded. Please use init_seeds()\n";
return s;
}
// init_seed();
currentGeneration(*g);
s = stringFromGeneration(*g);
delete g;
return s;
}
std::string Automata::bStringFromGeneration (AutomataGeneration &g) const
{
// const char on = '1';
// const char off = '0';
std::string str(g.size(), kOffPixelChar);
for (unsigned int i = 0; i < g.size(); ++i)
{
str[i] = (g[i] == kOffPixel ? '0' : '1');
}
return str;
}
std::string Automata::bStringFromCurrentGeneration() const
{
std::string s;
AutomataGeneration *g = new AutomataGeneration(p_generationLength);
if (_currentIndex == -1)
{
cout << "*** Warning: Cellular Automata not seeded. Please use init_seeds()\n";
return s;
}
currentGeneration(*g);
s = bStringFromGeneration(*g);
delete g;
return s;
}
// *** Could return void *, cast to appropriate type based on size of <n> ***
unsigned long *Automata::chunks_FromGeneration(AutomataGeneration &g, unsigned int &numchunks_out, unsigned int n) const
/*
* unsigned int *bytes_FromGeneration(AutomataGeneration &g, unsigned int &chunks)
*
* Returns a byte array (on the heap) (unsigned character array). chunks is set
* to the length of the returned byte array. Don't forget to free the princess.
* // for example.
* unsigned int n=0;
* AutomataGeneration *g = new AutomataGeneration()
* currentGeneration(g)
* unsigned char *princess = bytes_FromGeneration(*g, n);
* do_something_like_have_tea_with(princess, n);
* free(princess); // important, otherwise she will run rampant through the
* // memory swamp like a banshee in the night. You don't want that.
*
* @TODO: I think there is a bug here, must check chunks for accurate shit
*/
{
//unsigned char c;
// unsigned int n=6; // Bits per Byte
unsigned int k=0,num=0,i=0,j=0;
/**********'-0__0-'***************************************-0__o-**********\
| |
| MALLOC WARNING - don't forget to free the princess!!!! |
| |
\******************************+~.._/''\_..~+*****************************/
numchunks_out = g.size()/n; // Number of Bytes per Generation
if (n <= 0)
{
cout << "** ERROR **: n <= 0 invalid\n";
return NULL;
}
/*
if (n <= 8)
{
unsigned char *princess = (unsigned char *)malloc(chunks_out*sizeof(unsigned char)); // dependent on arbitrary n=8
} else if (8 < n <= 16)
{
unsigned int *princess = (unsigned int *)malloc(chunks_out*sizeof(unsigned int));
} else if (16 < n <= 32)
{
unsigned long *princess = (unsigned long *)malloc(chunks_out*sizeof(unsigned long));
}
if (princess == NULL)
{
cout << "** ERROR **: Unable to allocate memory for byte array. The princess has been lost.\n";
exit(EXIT_FAILURE);
}
*/
unsigned long *princess = (unsigned long *)malloc(numchunks_out*sizeof(unsigned long));
for (i=0; i<(g.size());)
{
// for some stupid reason, cout << g[i] throws all kinds of garbage out
// it's because i am using pointer math, gar. (*g)[0] not g[0]
num=0;
for (j=0; j<n; j++)
{
if (i >= g.size()) {
break;
}
// cout << i << " < " << g.size() << " < " << numchunks_out << endl;;
num += g[i]*pow(2, (n-1)-j);
//cout << g[i];
i++;
}
//cout << " " << num << " ";
// *** Protect the Princess! ***
if (k >= numchunks_out)
{
//cout << "The princess cannot eat cake; too full. k>=numchunks_out\n";
} else
{
princess[k] = num;
}
k++;
}
return princess;
}
unsigned long *Automata::chunks_FromCurrentGeneration(unsigned int &numchunks_out, unsigned int n) const
/*
* bytes_FromCurrentGeneration
* Creates a byte array representation (binary) of the current generation state.
* Returns a pointer to the byte array of length <n>
* numchunks_out is set (passed by reference) to the length of the returned character array
* n is the number of bits to break the automata into.
*
* The current generation is broken up into groups of 8 bits. Each bit is converted
* into an unsigned number and added to the array. Pretty standard.
*
* Next up - mapping of arbitrary lengths.
*
* *g means "the object pointed to by the pointer g"
*/
{
AutomataGeneration *g = new AutomataGeneration(p_generationLength);
if (_currentIndex == -1)
{
cout << "*** Warning: Cellular Automata not seeded. Please use init_seeds()\n";
return 0;
}
currentGeneration(*g);
//unsigned char *c = bytes_FromGeneration(*g, chunks_out, n);
unsigned long *c = chunks_FromGeneration(*g, numchunks_out, n);
return c;
}
// note: this creates *very large* integers. Duh! Use string instead
//unsigned int Automata::uintFromCurrentGeneration()
/*
* uintFromCurrentGeneration
* a helper class for cython. Gets us an unsigned integer representation
* of the current generation without having to export bitset, AutomataGeneration,
* AutomataGenerations, string, etc.
*/
/*
{
unsigned int i;
unsigned long long int ret=0;
AutomataGeneration *g = new AutomataGeneration();
currentGeneration(*g);
for (i=0; i<(g->size()); i++)
{
ret += ((*g)[i] == kOffPixel ? 0 : 1);
ret = ret << 1;
cout << (*g)[i] << "";
}
cout << " " << ret << "\n";
return ret;
}
*/
/*
* Private / Utility Functions
*/
int Automata::currentIndex () const
{
return _currentIndex;
}
int Automata::overallIndex () const
{
return _overallIndex;
}
void Automata::getGeneration (AutomataGeneration &output, unsigned int index) const
{
//output is a bitmask vector.
//cout << "index: " << index << "\n";
// this has to be a copy operation. we're copying the data from the
// AutomataGeneration in the <vector> _generations into the fresh
// AutomataGeneration &output. A pointer to _generations is not desired
// to protect data integrity (read-only).
// @TODO if output already points at a vector, does it create a dangling pointer?
output = _generations->at(index);
}
void Automata::currentGeneration (AutomataGeneration &output) const
{
// Get the generation we are at based on the index
if (_currentIndex == -1)
{
cout << "*** Warning: Cellular Automata not seeded. Please use init_seeds()\n";
return;
}
getGeneration(output, _currentIndex);
}
void Automata::generationAtIndex (AutomataGeneration &output, unsigned int index) const
{
// Get the generation of an arbitrary index.
getGeneration(output, index);
}
void Automata::appendGeneration (AutomataGeneration &g)
{
//increment indices and append generation to the buffer
_overallIndex++;
if (_currentIndex < 0) {
_currentIndex = -1; // protection
}
_currentIndex = (_currentIndex + 1) % kAutomataGenerations; //wrap-around
_generations->at(_currentIndex) = g; // copy? has to be, g gets deleted()
//_currentGeneration = g;
}
void Automata::randomizeSeed (AutomataGeneration &seed)
{
// generate a random generation bitfield
for (unsigned int i = 0; i < p_generationLength; ++i)
if (random() % 2 == 0)
{
seed.clear(i);
} else
{
seed.set(i);
}
}
void Automata::initializeSeedAtPosition (AutomataGeneration &seed, unsigned int position)
{
// seed is a generation bitfield.
//cout << "initializeSeedAtPosition1\n";
seed.reset(); // reset bitfield to all binary 0's
seed.set(position); // Turn the <position> to binary 1
//cout << "initializeSeedAtPosition2\n";
}
/*
void Automata::initializeCurrentGeneration(unsigned int value)
{
AutomataGeneration *g = new AutomataGeneration();
currentGeneration(*g);
initializeSeedWithValue(*g, value);
delete g;
}*/
/*
* Private Members & Functions
*
*/
void Automata::setBinaryRuleFromInteger (unsigned int numericalCode)
/*
* setBinaryRuleFromInteger
* Takes the given rule, like 110, and computes the computation (0 or 1) that
* each neighborhood permutation would produce. Initializes _rule[]
*/
{
int x, y;
for (y = kNumberOfRules-1; y >= 0; y--) {
x = numericalCode / (1 << y);
numericalCode = numericalCode - x * (1 << y);
_rule[y] = (x == 0 ? kOffPixel : kOnPixel);
}
}
void Automata::getNextGeneration (AutomataGeneration &cg, AutomataGeneration &ng)
/*
* getNextGeneration
* For the given generation, execute the output of each neighborhood and
* assign that value to the corresponding cell in the next generation &ng.
*/
{
unsigned int output, neighborhood;
for (unsigned int position = 0; position < cg.size(); ++position) {
neighborhood = getNeighborhoodForGenerationAtPosition(cg, position);
validateNeighborhood(neighborhood);
output = getOutputForNeighborhood(neighborhood);
validateOutput(output);
//ng[position] = (output == 0 ? kOffPixel : kOnPixel);
if (output == 0)
ng.clear(position);
else
ng.set(position);
}
}
unsigned int Automata::getOutputForNeighborhood (unsigned int neighborhood)
/*
* This function basically looks up the next state of the cell given
* the unsigned integer representation (3-bit) of the neighborhood.
* Returns a lookup into the array _rule[unsigned int[8]]
*/
{
validateNeighborhood(neighborhood);
unsigned int output = _rule[neighborhood];
validateOutput(output);
return output;
}
unsigned int Automata::getNeighborhoodForGenerationAtPosition (AutomataGeneration &cg, unsigned int position)
/*
* getNeighborhoodForGenerationAtPosition
* Creates the neighborhood of generation cg at <position>.
* Also takes care of wrapping around the neighborhood to include neighbors
* on either side of the vector (wrap-around).
*
* This would be the function to modify if wrap-around is not desired. For
* example, each cell to the left of g[0] and to the right of g[-1] can be
* assumed as static value of 0 or 1.
*
*/
{
unsigned int center = (cg[position] == kOffPixel ? kOffPixelInteger : kOnPixelInteger);
unsigned int left;
if (position == 0) {
left = (cg[cg.size()-1] == kOffPixel ? kOffPixelInteger : kOnPixelInteger);
} else {
left = (cg[position-1] == kOffPixel ? kOffPixelInteger : kOnPixelInteger);
}
unsigned int right;
if (position == cg.size()-1) {
right = (cg[0] == kOffPixel ? kOffPixelInteger : kOnPixelInteger);
} else {
right = (cg[position+1] == kOffPixel ? kOffPixelInteger : kOnPixelInteger);
}
unsigned int neighborhood = (1 * right) + (2 * center) + (4 * left);
validateNeighborhood(neighborhood);
return neighborhood;
}
/* Exceptions */
void Automata::validateNeighborhood (unsigned int neighborhood)
{
if ((neighborhood < kLowBoundOnNeighborhood) || (neighborhood > kHighBoundOnNeighborhood))
throw kAutomataBadNeighborhoodBoundsException;
}
void Automata::validateOutput (unsigned int output)
{
if ((output < kLowBoundOnOutput) || (output > kHighBoundOnOutput))
throw kAutomataBadOutputBoundsException;
}
void Automata::validateGeneration (AutomataGeneration &g)
{
//cout << g.size() << " " << p_generationLength << "\n";
if (g.size() > p_generationLength)
throw kAutomataBadStringLengthException;
}
| 32.826609 | 120 | 0.677596 | [
"object",
"vector"
] |
399971e53ff0410e085ca0630165f08a6940ac3e | 2,587 | cpp | C++ | qt_genericclient.cpp | BlivionIaG/ChilyClient | 3f34583024b3932af4d0d5192c4e1b0981ecf5ab | [
"MIT"
] | null | null | null | qt_genericclient.cpp | BlivionIaG/ChilyClient | 3f34583024b3932af4d0d5192c4e1b0981ecf5ab | [
"MIT"
] | null | null | null | qt_genericclient.cpp | BlivionIaG/ChilyClient | 3f34583024b3932af4d0d5192c4e1b0981ecf5ab | [
"MIT"
] | null | null | null | #include "qt_genericclient.hpp"
QT_GenericClient::QT_GenericClient(QString address, quint16 port, QObject *parent) : QObject(parent), alive{true}
{
socket = new QTcpSocket(this);
Connect(address, port);
connect(socket, SIGNAL(connected()), this, SLOT(connectedToServer()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectedFromServer()));
connect(socket, SIGNAL(readyRead()), this, SLOT(receivedFromServer()));
connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(sentToServer(qint64)));
}
void QT_GenericClient::Connect(QString address, quint16 port){
qDebug() << "Connexion au Serveur "+address+" au port "+QString::number(port);
socket->connectToHost(address, port);
if(socket->waitForDisconnected(timeout))
{
qDebug() << "Error: " << socket->errorString();
}
}
std::vector<std::string> QT_GenericClient::receive(){
std::vector<std::string> output;
for(const auto &it : buffer){
output.push_back(it);
}
buffer.clear();
return output;
}
bool QT_GenericClient::send(const std::string &message){
if (message.length() <= 0) {
qDebug() << "No message to send !";
return false;
}
socket->write((message+"\n").c_str());
return socket->waitForBytesWritten(writeWaitTime);;
}
bool QT_GenericClient::action(std::string msg) {
auto cmd = cmdFormat::parseCommand(msg);
if (!cmd.command.compare("quit")) {
socket->close();
alive = false;
} else if (!cmd.command.compare("auth")) {
if (cmd.args.size() < 2) {
send(cmd.id + "@auth:2 error wrong values");
} else {
id = cmd.args[0];
key = cmd.args[1];
qDebug() << "id set to " << QString::fromStdString(id) << " and key is " << QString::fromStdString(key);
}
}else {
return false;
}
return true;
}
void QT_GenericClient::connectedToServer(){
qDebug() << "Connected to Server !";
}
void QT_GenericClient::disconnectedFromServer(){
qDebug() << "Disconnected from server !";
}
void QT_GenericClient::receivedFromServer(){
while (socket->canReadLine()) {
auto tmp = socket->readLine();
QString tmpBuffer = QString(tmp).trimmed();
if (tmpBuffer.size() <= 0) {
qDebug() << "Error: Server Disconnected !";
} else if(!action(tmpBuffer.toStdString())){
buffer.append(tmpBuffer.toStdString());
}
}
}
void QT_GenericClient::sentToServer(qint64 bytes){
qDebug() << "Sent to Server: " << bytes << " bytes";
}
| 27.817204 | 116 | 0.617704 | [
"vector"
] |
399a0a1fe8941588682562fd581e5a9c6aa6abd8 | 3,308 | cpp | C++ | src/bembel/kernel/scene/scene.cpp | JoachimHerber/Bembel-Game-Engine | 5c4e46c5a15356af6e997038a8d76065b0691b50 | [
"MIT"
] | 2 | 2018-01-02T14:07:54.000Z | 2021-07-05T08:05:21.000Z | src/bembel/kernel/scene/scene.cpp | JoachimHerber/Bembel-Game-Engine | 5c4e46c5a15356af6e997038a8d76065b0691b50 | [
"MIT"
] | null | null | null | src/bembel/kernel/scene/scene.cpp | JoachimHerber/Bembel-Game-Engine | 5c4e46c5a15356af6e997038a8d76065b0691b50 | [
"MIT"
] | null | null | null | #include "./scene.hpp"
#include <bembel/base/logging/logger.hpp>
#include "./component-container.hpp"
namespace bembel::kernel {
Scene::Scene(AssetManager& asste_mgr)
: asste_mgr(asste_mgr) {
}
Scene::~Scene() {
for(auto asset_handle : this->assets) { this->asste_mgr.releaseAsset(asset_handle); }
}
Scene::EntityID Scene::createEntity() {
if(this->unused_entity_ids.empty()) {
this->entities.push_back(0);
return this->entities.size() - 1;
} else {
EntityID id = this->unused_entity_ids.top();
this->unused_entity_ids.pop();
return id;
}
}
Scene::EntityID Scene::createEntity(const xml::Element* properties) {
EntityID entity = createEntity();
for(const xml::Element* component : xml::IterateChildElements(properties)) {
auto it = this->component_type_map.find(component->Value());
if(it == this->component_type_map.end()) continue; // unknown component type
if(this->container[it->second]->createComponent(entity, component, this->asste_mgr)) {
this->entities[entity] |= this->container[it->second]->getComponentMask();
}
}
return entity;
}
bool Scene::deleteEntity(EntityID id) {
if(id >= this->entities.size()) return false; // invalid entity id
// delete all components of of the entity
for(auto& container : this->container) {
if((this->entities[id] & container->getComponentMask()) != 0)
container->deleteComponent(id);
}
this->entities[id] = 0;
this->unused_entity_ids.push(id);
return true;
}
bool Scene::loadScene(const std::string& file_name) {
xml::Document doc;
if(doc.LoadFile(file_name.c_str()) != tinyxml2::XML_SUCCESS) {
BEMBEL_LOG_ERROR() << "Failed to lode file '" << file_name << "'\n"
<< doc.ErrorName() << std::endl;
return false;
}
const xml::Element* root = doc.FirstChildElement("Scene");
if(!root) return false;
const xml::Element* assets = root->FirstChildElement("Assets");
for(auto asset : xml::IterateChildElements(assets)) { loadAsset(asset); }
const xml::Element* entities = root->FirstChildElement("Entities");
for(auto entity : xml::IterateChildElements(entities, "Entity")) { createEntity(entity); }
return true;
}
const std::vector<Scene::ComponentMask>& Scene::getEntitys() const {
return this->entities;
}
bool Scene::loadAssets(const std::string& file_name) {
xml::Document doc;
if(doc.LoadFile(file_name.c_str()) != tinyxml2::XML_SUCCESS) {
BEMBEL_LOG_ERROR() << "Failed to load file '" << file_name << "'\n"
<< doc.ErrorName() << std::endl;
return false;
}
const xml::Element* root = doc.FirstChildElement("Assets");
if(!root) {
BEMBEL_LOG_ERROR() << "File '" << file_name << "' has no root element 'GeometryMesh'"
<< std::endl;
return false;
}
for(auto it : xml::IterateChildElements(root)) { loadAsset(it); }
return true;
}
void Scene::loadAsset(const xml::Element* properties) {
AssetHandle hndl = this->asste_mgr.requestAsset(properties->Value(), properties);
if(this->asste_mgr.isHandelValid(hndl)) { this->assets.emplace(hndl); }
}
} // namespace bembel::kernel
| 32.116505 | 94 | 0.636638 | [
"vector"
] |
39b7433c8f5396e39bb90f9efcccb70310422d14 | 7,637 | cc | C++ | components/signin/core/browser/device_activity_fetcher.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | components/signin/core/browser/device_activity_fetcher.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | components/signin/core/browser/device_activity_fetcher.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2015 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 "components/signin/core/browser/device_activity_fetcher.h"
#include "base/strings/stringprintf.h"
#include "components/signin/core/browser/signin_client.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
#include "google_apis/gaia/gaia_constants.h"
#include "google_apis/gaia/gaia_urls.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_fetcher.h"
namespace {
// TODO(mlerman,anthonyvd): Replace the three parameters following with the
// necessary parameters for calling the ListDevices endpoint, once live.
// crbug.com/463611 for details!
const char kSyncListDevicesScope[] =
"https://www.googleapis.com/auth/chromesynclistdevices";
const char kChromeDomain[] = "http://www.chrome.com";
const char kListDevicesEndpoint[] = "http://127.0.0.1";
// Template for optional authorization header when using an OAuth access token.
const char kAuthorizationHeader[] = "Authorization: Bearer %s";
// In case of an error while fetching using the GaiaAuthFetcher, retry with
// exponential backoff. Try up to 9 times within 10 minutes.
const net::BackoffEntry::Policy kBackoffPolicy = {
// Number of initial errors (in sequence) to ignore before applying
// exponential back-off rules.
0,
// Initial delay for exponential backoff in ms.
1000,
// Factor by which the waiting time will be multiplied.
2,
// Fuzzing percentage. ex: 10% will spread requests randomly
// between 90%-100% of the calculated time.
0.1, // 10%
// Maximum amount of time we are willing to delay our request in ms.
1000 * 60 * 15, // 15 minutes.
// Time to keep an entry from being discarded even when it
// has no significant state, -1 to never discard.
-1,
// Don't use initial delay unless the last request was an error.
false,
};
const int kMaxFetcherRetries = 9;
} // namespace
DeviceActivityFetcher::DeviceActivityFetcher(
SigninClient* signin_client,
DeviceActivityFetcher::Observer* observer)
: fetcher_backoff_(&kBackoffPolicy),
fetcher_retries_(0),
signin_client_(signin_client),
observer_(observer) {
}
DeviceActivityFetcher::~DeviceActivityFetcher() {
}
void DeviceActivityFetcher::Start() {
fetcher_retries_ = 0;
login_hint_ = std::string();
StartFetchingListIdpSessions();
}
void DeviceActivityFetcher::Stop() {
if (gaia_auth_fetcher_)
gaia_auth_fetcher_->CancelRequest();
if (url_fetcher_)
url_fetcher_.reset();
}
void DeviceActivityFetcher::StartFetchingListIdpSessions() {
gaia_auth_fetcher_.reset(signin_client_->CreateGaiaAuthFetcher(
this, GaiaConstants::kChromeSource,
signin_client_->GetURLRequestContext()));
gaia_auth_fetcher_->StartListIDPSessions(kSyncListDevicesScope,
kChromeDomain);
}
void DeviceActivityFetcher::StartFetchingGetTokenResponse() {
gaia_auth_fetcher_.reset(signin_client_->CreateGaiaAuthFetcher(
this, GaiaConstants::kChromeSource,
signin_client_->GetURLRequestContext()));
gaia_auth_fetcher_->StartGetTokenResponse(kSyncListDevicesScope,
kChromeDomain, login_hint_);
}
void DeviceActivityFetcher::StartFetchingListDevices() {
// Call the Sync Endpoint.
url_fetcher_ = net::URLFetcher::Create(GURL(kListDevicesEndpoint),
net::URLFetcher::GET, this);
url_fetcher_->SetRequestContext(signin_client_->GetURLRequestContext());
if (!access_token_.empty()) {
url_fetcher_->SetExtraRequestHeaders(
base::StringPrintf(kAuthorizationHeader, access_token_.c_str()));
}
url_fetcher_->Start();
}
void DeviceActivityFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
// TODO(mlerman): Uncomment the code below once we have a working proto.
// Work done under crbug.com/463611
// std::string response_string;
// ListDevices list_devices;
// if (!source->GetStatus().is_success()) {
// VLOG(1) << "Failed to fetch listdevices response. Retrying.";
// if (++fetcher_retries_ < kMaxFetcherRetries) {
// fetcher_backoff_.InformOfRequest(false);
// fetcher_timer_.Start(
// FROM_HERE, fetcher_backoff_.GetTimeUntilRelease(), this,
// &DeviceActivityFetcher::StartFetchingListDevices);
// return;
// } else {
// observer_->OnFetchDeviceActivityFailure();
// return;
// }
// }
// net::HttpStatusCode response_status = static_cast<net::HttpStatusCode>(
// source->GetResponseCode());
// if (response_status == net::HTTP_BAD_REQUEST ||
// response_status == net::HTTP_UNAUTHORIZED) {
// // BAD_REQUEST indicates that the request was malformed.
// // UNAUTHORIZED indicates that security token didn't match the id.
// VLOG(1) << "No point retrying the checkin with status: "
// << response_status << ". Checkin failed.";
// CheckinRequestStatus status = response_status == net::HTTP_BAD_REQUEST ?
// HTTP_BAD_REQUEST : HTTP_UNAUTHORIZED;
// RecordCheckinStatusAndReportUMA(status, recorder_, false);
// callback_.Run(response_proto);
// return;
// }
// if (response_status != net::HTTP_OK ||
// !source->GetResponseAsString(&response_string) ||
// !list_devices.ParseFromString(response_string)) {
// LOG(ERROR) << "Failed to get list devices response. HTTP Status: "
// << response_status;
// if (++fetcher_retries_ < kMaxFetcherRetries) {
// fetcher_backoff_.InformOfRequest(false);
// fetcher_timer_.Start(
// FROM_HERE, fetcher_backoff_.GetTimeUntilRelease(), this,
// &DeviceActivityFetcher::StartFetchingListDevices);
// return;
// } else {
// observer_->OnFetchDeviceActivityFailure();
// return;
// }
// }
std::vector<DeviceActivity> devices;
// TODO(mlerman): Fill |devices| from the proto in |source|.
// Call this last as OnFetchDeviceActivitySuccess will delete |this|.
observer_->OnFetchDeviceActivitySuccess(devices);
}
void DeviceActivityFetcher::OnListIdpSessionsSuccess(
const std::string& login_hint) {
fetcher_backoff_.InformOfRequest(true);
login_hint_ = login_hint;
access_token_ = std::string();
StartFetchingGetTokenResponse();
}
void DeviceActivityFetcher::OnListIdpSessionsError(
const GoogleServiceAuthError& error) {
if (++fetcher_retries_ < kMaxFetcherRetries && error.IsTransientError()) {
fetcher_backoff_.InformOfRequest(false);
fetcher_timer_.Start(FROM_HERE, fetcher_backoff_.GetTimeUntilRelease(),
this,
&DeviceActivityFetcher::StartFetchingListIdpSessions);
return;
}
observer_->OnFetchDeviceActivityFailure();
}
void DeviceActivityFetcher::OnGetTokenResponseSuccess(
const ClientOAuthResult& result) {
fetcher_backoff_.InformOfRequest(true);
access_token_ = result.access_token;
StartFetchingListDevices();
}
void DeviceActivityFetcher::OnGetTokenResponseError(
const GoogleServiceAuthError& error) {
if (++fetcher_retries_ < kMaxFetcherRetries && error.IsTransientError()) {
fetcher_backoff_.InformOfRequest(false);
fetcher_timer_.Start(FROM_HERE, fetcher_backoff_.GetTimeUntilRelease(),
this,
&DeviceActivityFetcher::StartFetchingGetTokenResponse);
return;
}
observer_->OnFetchDeviceActivityFailure();
}
| 37.253659 | 80 | 0.708131 | [
"vector"
] |
39ba25bbd2011fa829638b365245921531f716f4 | 3,253 | cc | C++ | Code/Components/Analysis/simulations/current/apps/tFlux.cc | rtobar/askapsoft | 6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 1 | 2020-06-18T08:37:43.000Z | 2020-06-18T08:37:43.000Z | Code/Components/Analysis/simulations/current/apps/tFlux.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Components/Analysis/simulations/current/apps/tFlux.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | ///
/// @file : Create a FITS file with fake sources and random noise
///
/// Control parameters are passed in from a LOFAR ParameterSet file.
///
/// @copyright (c) 2007 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Matthew Whiting <matthew.whiting@csiro.au>
#include <askap_simulations.h>
#include <FITS/FITSfile.h>
#include <simulationutilities/FluxGenerator.h>
#include <modelcomponents/Continuum.h>
#include <askap/AskapLogging.h>
#include <askap/AskapError.h>
#include <Common/ParameterSet.h>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <stdlib.h>
#include <time.h>
using namespace askap;
using namespace askap::simulations;
using namespace askap::simulations::FITS;
ASKAP_LOGGER(logger, "tFlux.log");
// Move to Askap Util?
std::string getInputs(const std::string& key, const std::string& def, int argc,
const char** argv)
{
if (argc > 2) {
for (int arg = 0; arg < (argc - 1); arg++) {
std::string argument = std::string(argv[arg]);
if (argument == key) {
return std::string(argv[arg + 1]);
}
}
}
return def;
}
// Main function
int main(int argc, const char** argv)
{
ASKAPLOG_INIT("tFlux.log_cfg");
LOFAR::ParameterSet parset("tests/tparset.in");
parset = parset.makeSubset("createFITS.");
FITSfile file(parset);
struct wcsprm *wcs = file.getWCS();
// wcsprt(wcs);
std::vector<int> axes = parset.getInt32Vector("axes");
int nz = axes[wcs->spec];
FluxGenerator fluxes(nz);
ASKAPLOG_DEBUG_STR(logger, "number of channels = " << nz);
Continuum cont(-1., -1., 1.4e9, 1.);
double x = 512., y = 512.;
boost::shared_ptr<Spectrum> spec(&cont);
fluxes.addSpectrum(spec, x, y, wcs);
for (size_t i = 0; i < fluxes.nChan(); i++) {
std::cout << i << " " << fluxes.getFlux(i) << "\n";
}
std::cout << "\n";
FluxGenerator singleFlux(1);
cont = Continuum(0., 0., 1.4e9, 1.);
spec = boost::shared_ptr<Spectrum>(&cont);
singleFlux.addSpectrum(spec, x, y, wcs);
for (size_t i = 0; i < singleFlux.nChan(); i++) {
std::cout << i << " " << singleFlux.getFlux(i) << "\n";
}
}
| 30.12037 | 79 | 0.654165 | [
"vector"
] |
39bca8e46cc37d7c78fe577a10ea163c4f59c17c | 5,666 | hpp | C++ | include/shz/spatial/kd_tree_discriminators.hpp | TraxNet/ShadingZenCpp | 46860da3249900259941bf64f4a46347500b65fb | [
"MIT"
] | 3 | 2015-04-30T15:41:51.000Z | 2018-12-28T05:47:18.000Z | include/shz/spatial/kd_tree_discriminators.hpp | TraxNet/ShadingZenCpp | 46860da3249900259941bf64f4a46347500b65fb | [
"MIT"
] | null | null | null | include/shz/spatial/kd_tree_discriminators.hpp | TraxNet/ShadingZenCpp | 46860da3249900259941bf64f4a46347500b65fb | [
"MIT"
] | null | null | null | #ifndef __SHZ_MATH_KD_TREE_DISCRIMINATORS__
#define __SHZ_MATH_KD_TREE_DISCRIMINATORS__
namespace shz{ namespace spatial{
struct plane_discriminator_tag { };
struct sah_boxplanes_plane_discriminator_tag : public plane_discriminator_tag { };
struct plane_roundrobin_discriminator_tag : public plane_discriminator_tag { };
template<typename KDTreeTraits, typename Tag> struct plane_discriminator_category { };
template<typename KDTreeTraits> struct plane_discriminator_category<KDTreeTraits, sah_boxplanes_plane_discriminator_tag> {
plane_discriminator_category(size_t dimension){ }
/*
template<class InputIterator> std::tuple<size_t, typename KDTreeTraits::discriminator_type>
choose_plane(
InputIterator& first,
InputIterator& last){
std::tuple<size_t, typename KDTreeTraits::discriminator_type> ret;
return ret;
}
bool partition_set(
const std::tuple<size_t, typename KDTreeTraits::discriminator_type>& params,
std::vector<typename KDTreeTraits::pair_type>& left_set,
std::vector<typename KDTreeTraits::pair_type>& right_set) {
return false;
}*/
};
/**
* Round robin discrimintaor partial specialization. The discrinator plane to parition the current set is choosen in
* a round robin secuence. This is the least efficient algorithm to generate a kd-tree.
*/
template<typename KDTreeTraits> struct plane_discriminator_category<KDTreeTraits, plane_roundrobin_discriminator_tag> {
/**
* Constructor
*
* @param depth The current depth of the tree being discriminated
* @return A tuple with information regarding the choosen discrimination
* parameters (dimensio, discriminator value)
*/
plane_discriminator_category(size_t depth)
: current_depth(depth) { }
/**
* Chooses a discriminator plane which partitions the given set in two. For this
* round-robin implementation, the discriminator (axis) is chosen alternatively on
* each depth of the tree.
*
* @return A tuple with information about the discriminating dimension and the exact
* value where the plane has been placed.
*/
template<class InputIterator> inline std::tuple<size_t, typename KDTreeTraits::discriminator_type>
choose_plane(
InputIterator start,
InputIterator end)
{
size_t current_dimension = current_depth%KDTreeTraits::max_dimensions;
std::tuple<size_t, typename KDTreeTraits::discriminator_type> ret;
std::vector<typename KDTreeTraits::pair_type> elements(start, end);
std::sort(
elements.begin(),
elements.end(),
typename KDTreeTraits::less_than_key(current_dimension, KDTreeTraits::lower_bound));
std::get<0>(ret) = current_dimension;
auto median = (end - start)/2;
std::get<1>(ret) = start[median].first[KDTreeTraits::lower_bound][current_dimension];
return ret;
}
/**
* Given an input and information about the discriminator plane, parititions the input set into
* two sub-sets using their median values (for the plane position). If all the items in the input
* set are in both sub-sets, or one of the sub-sets is empty, returns false to point the caller to
* avoid creating two sub-sets
* @return If all items are in both partitions or there is an empty partition we can return false
* so that this is actually not partitioned and a leaf node should be created. Otherwise return true.
*/
inline bool partition_set(
const std::tuple<size_t, typename KDTreeTraits::discriminator_type>& params,
std::vector<typename KDTreeTraits::pair_type>& input_set,
std::vector<typename KDTreeTraits::pair_type>& left_set,
std::vector<typename KDTreeTraits::pair_type>& right_set)
{
typename KDTreeTraits::discriminator_type discriminator;
typename std::vector<typename KDTreeTraits::pair_type>::size_type items_in_both = 0;
size_t dimension = current_depth%KDTreeTraits::max_dimensions;
// sort all items acordding to the current dimension and choose the median. That poin is the
// place where the parition plane is placed.
std::sort(
input_set.begin(),
input_set.end(),
typename KDTreeTraits::less_than_key(dimension, KDTreeTraits::lower_bound));
auto median = (input_set.end() - input_set.begin())/2;
discriminator =
input_set[median].first[KDTreeTraits::lower_bound][dimension];
for(auto& pair : input_set){
if(pair.first[dimension][KDTreeTraits::upper_bound] < discriminator){
left_set.push_back(pair);
} else if(pair.first[dimension][KDTreeTraits::lower_bound] < discriminator
&& pair.first[dimension][KDTreeTraits::upper_bound] > discriminator) {
left_set.push_back(pair);
right_set.push_back(pair);
items_in_both++;
} else{
right_set.push_back(pair);
}
}
// If all items are in both partitions or there is an empty partition
// we can return false so that this is actually not partitioned and
// a leaf node is created.
if(items_in_both == input_set.size() || right_set.empty() || left_set.empty())
return false;
return true;
}
protected:
size_t current_depth;
};
} };
#endif // __SHZ_MATH_KD_TREE_DISCRIMINATORS__ | 41.97037 | 123 | 0.673667 | [
"vector"
] |
39c0ef5ad2cc373958201253eeddb4bc6719e8c1 | 15,569 | cpp | C++ | cpp/SceneChangeDetection/SceneChangeDetection.cpp | openmpf/openmpf-components | acf012aeda0bac902e4678a97338b0aa5ffe38bf | [
"Apache-2.0"
] | 5 | 2017-10-19T12:14:09.000Z | 2022-02-11T15:16:48.000Z | cpp/SceneChangeDetection/SceneChangeDetection.cpp | openmpf/openmpf-components | acf012aeda0bac902e4678a97338b0aa5ffe38bf | [
"Apache-2.0"
] | 126 | 2017-05-05T19:40:32.000Z | 2022-03-08T19:14:00.000Z | cpp/SceneChangeDetection/SceneChangeDetection.cpp | openmpf/openmpf-components | acf012aeda0bac902e4678a97338b0aa5ffe38bf | [
"Apache-2.0"
] | 2 | 2018-06-08T18:32:55.000Z | 2020-08-27T21:25:07.000Z | /******************************************************************************
* NOTICE *
* *
* This software (or technical data) was produced for the U.S. Government *
* under contract, and is subject to the Rights in Data-General Clause *
* 52.227-14, Alt. IV (DEC 2007). *
* *
* Copyright 2021 The MITRE Corporation. All Rights Reserved. *
******************************************************************************/
/******************************************************************************
* Copyright 2021 The MITRE Corporation *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
#include "SceneChangeDetection.h"
#include <algorithm>
#include <fstream>
#include <utility>
#include <opencv2/imgproc.hpp>
#include <detectionComponentUtils.h>
#include <MPFSimpleConfigLoader.h>
#include <MPFVideoCapture.h>
#include <Utils.h>
using namespace MPF::COMPONENT;
using namespace cv;
std::string SceneChangeDetection::GetDetectionType() {
return "SCENE";
}
bool SceneChangeDetection::Init() {
// Determine where the executable is running.
std::string run_dir = GetRunDirectory();
if (run_dir.empty()) {
run_dir = ".";
}
std::string plugin_path = run_dir + "/SceneChangeDetection";
std::string config_path = plugin_path + "/config";
logger_ = log4cxx::Logger::getLogger("SceneChangeDetection");
LOG4CXX_DEBUG(logger_, "Plugin path: " << plugin_path);
LOG4CXX_INFO(logger_, "Initializing SceneChangeDetection");
// Initialize dilateKernel.
dilateKernel = getStructuringElement(MORPH_RECT, Size(11, 11), Point(5, 5));
SetDefaultParameters();
//Once this is done - parameters will be set and SetReadConfigParameters() can be called again to revert back
//to the params read at initialization.
std::string config_params_path = config_path + "/mpfSceneChangeDetection.ini";
int rc = LoadConfig(config_params_path, parameters);
if (rc) {
LOG4CXX_ERROR(logger_, "Could not parse config file: " << config_params_path);
keyframes.clear();
return false;
}
SetReadConfigParameters();
keyframes.clear();
LOG4CXX_INFO(logger_, "INITIALIZED COMPONENT" );
return true;
}
/*
* Called during Init.
* Initializes default parameter values.
*/
void SceneChangeDetection::SetDefaultParameters() {
// Threshold for edge detection.
// Higher values result in less detections (lower sensitivity).
// Range 0-1.
edge_thresh = 0.75;
// Threshold for histogram detection.
// Higher values result in more detections (higher sensitivity).
// Range 0-1.
hist_thresh = 0.25;
// Threshold for content detection.
// Higher values result in less detections (lower sensitivity).
// Range 0-1.
cont_thresh = 0.30;
// Threshold for thrs detection.
// Higher values result in more detections (higher sensitivity).
// Range 0-1? (most likely 0-255).
thrs_thresh = 12.0;
// Second threshold for thrs detection (combines with thrs_thres).
// Higher values decrease sensitivity.
// Range 0-1.
minPercent = 0.95;
// Expected min number of frames between scene changes.
minScene = 15;
// Toggles each type of detection (true = perform detection).
do_hist = true;
do_cont = true;
do_thrs = true;
do_edge = true;
use_middle_frame = true;
}
/*
* Called during Init.
* Sets parameters from .ini file.
*/
void SceneChangeDetection::SetReadConfigParameters() {
if (parameters.contains("DO_HIST")) {
do_hist = (parameters["DO_HIST"].toInt() > 0);
}
if (parameters.contains("DO_CONT")) {
do_cont = (parameters["DO_CONT"].toInt() > 0);
}
if (parameters.contains("DO_THRS")) {
do_thrs = (parameters["DO_THRS"].toInt() > 0);
}
if (parameters.contains("DO_EDGE")) {
do_edge = (parameters["DO_EDGE"].toInt() > 0);
}
if (parameters.contains("USE_MIDDLE_FRAME")) {
use_middle_frame = (parameters["USE_MIDDLE_FRAME"].toInt() > 0);
}
if (parameters.contains("HIST_THRESHOLD")) {
hist_thresh = parameters["HIST_THRESHOLD"].toDouble();
}
if (parameters.contains("CONT_THRESHOLD")) {
cont_thresh = parameters["CONT_THRESHOLD"].toDouble();
}
if (parameters.contains("THRS_THRESHOLD")) {
thrs_thresh = parameters["THRS_THRESHOLD"].toDouble();
}
if (parameters.contains("EDGE_THRESHOLD")) {
edge_thresh = parameters["EDGE_THRESHOLD"].toDouble();
}
if (parameters.contains("MIN_PERCENT")) {
minPercent = parameters["MIN_PERCENT"].toDouble();
}
if (parameters.contains("MIN_SCENECHANGE_LENGTH")) {
minScene = parameters["MIN_SCENECHANGE_LENGTH"].toInt();
}
}
bool SceneChangeDetection::Close() {
return true;
}
/*
* Calculates the difference in edge pixels between the last two frames.
* Returns true when the difference exceeds edge_thresh.
*/
bool SceneChangeDetection::DetectChangeEdges(const cv::Mat &frameGray, cv::Mat &lastFrameEdgeFinal)
{
cv::Mat frameEdges, frameEdgeFinal, edgeDst;
blur(frameGray, frameEdges, Size(3, 3));
Canny(frameEdges, frameEdges, 90, 270, 3);
frameGray.copyTo(frameEdgeFinal, frameEdges);
dilate(frameEdgeFinal, frameEdgeFinal, dilateKernel);
absdiff(frameEdgeFinal, lastFrameEdgeFinal, edgeDst);
double sumEdges = sum(edgeDst).val[0];
int frame_pixels = edgeDst.size().width * edgeDst.size().height;
double deltaEdges = sumEdges / frame_pixels;
frameEdges.copyTo(lastFrameEdgeFinal);
if (deltaEdges > edge_thresh)
{
return true;
}
else
{
return false;
}
}
/*
* Performs histogram comparison between the last two frames.
* Returns true when correlation falls below hist_thresh.
*/
bool SceneChangeDetection::DetectChangeHistogram(const cv::Mat &frame, cv::Mat &lastHist)
{
MatND hist;
const float* ranges[] = { hranges, sranges };
calcHist( &frame, 1, (const int*) &channels[0], Mat(), // Do not use mask.
hist, 2, histSize, ranges,
true, // The histogram is uniform.
false );
double val = compareHist(hist, lastHist, cv::HISTCMP_CORREL);
hist.copyTo(lastHist);
return val < hist_thresh;
}
/*
* Calculates average difference in HSV values between the last two frames.
* Returns true when total average difference exceeds cont_thresh.
*/
bool SceneChangeDetection::DetectChangeContent(const cv::Mat &frame, cv::Mat &lastFrameHSV)
{
Mat frameHSV, dst;
cvtColor(frame, frameHSV, COLOR_BGR2HSV);
absdiff(frameHSV, lastFrameHSV, dst);
auto sum_ = sum(dst).val;
int frame_pixels = dst.size().width * dst.size().height;
double deltaH = sum_[0] / frame_pixels;
double deltaS = sum_[1] / frame_pixels;
double deltaV = sum_[2] / frame_pixels;
double deltaHSVAvg = (deltaH + deltaS + deltaV) / (3.0);
frameHSV.copyTo(lastFrameHSV);
if (deltaHSVAvg > cont_thresh)
{
return true;
}
else return false;
}
/*
* Performs threshold detection for scene fade outs.
* Note: Once threshold is met, fadeOut is set to true
* and all subsequent frames in the scene will be marked as fade outs.
*/
bool SceneChangeDetection::DetectChangeThreshold(const cv::Mat &frame, cv::Mat &lastFrame)
{
bool FUT = frameUnderThreshold(frame, thrs_thresh, numPixels * 3);
if (!fadeOut && FUT)
{
fadeOut = true;
}
else if (fadeOut && FUT)
{
return true;
}
return false;
}
/*
* Counts number of pixels that fall under threshold value.
* If total number of dark pixels exceeds minThreshold, return true.
*/
bool SceneChangeDetection::frameUnderThreshold(const cv::Mat &image, double threshold, double numPixels)
{
int minThreshold = (int)(numPixels * (1.0 - minPercent));
int frameAmount = 0;
std::vector<Mat> channels;
split(image, channels);
for (int y = 0; y < image.rows; y++)
{
cv::Mat dst;
compare(channels[0].row(y), Scalar(threshold), dst, CMP_GT);
frameAmount += countNonZero(dst);
if (frameAmount > minThreshold)
{
return false;
}
}
return true;
}
/*
* Performs up to four different scene change detection protocols.
*/
std::vector<MPFVideoTrack> SceneChangeDetection::GetDetections(const MPFVideoJob &job) {
try {
LOG4CXX_DEBUG(logger_, "[" << job.job_name << "] " << "Job feed_forward_is: " << job.has_feed_forward_track);
if (job.has_feed_forward_track)
{
LOG4CXX_DEBUG(logger_, "[" << job.job_name << "] " << "STARTING FEEDFORWARD GETDETECTIONS" );
}
else
{
LOG4CXX_DEBUG(logger_, "[" << job.job_name << "] " << "STARTING NO FF GETDETECTIONS" );
}
LOG4CXX_DEBUG(logger_, "[" << job.job_name << "] " << "Data URI = " << job.data_uri);
MPFVideoCapture cap(job);
int frame_count = cap.GetFrameCount();
LOG4CXX_DEBUG(logger_, "[" << job.job_name << "] " << "frame count = " << frame_count);
LOG4CXX_DEBUG(logger_, "[" << job.job_name << "] " << "begin frame = " << job.start_frame);
LOG4CXX_DEBUG(logger_, "[" << job.job_name << "] " << "end frame = " << job.stop_frame);
Mat lastFrameEdgeFinal, frameGray, lastFrameHSV, lastFrame;
MatND lastHist;
int frame_index;
const std::vector<cv::Mat> &init_frames = cap.GetInitializationFramesIfAvailable(1);
// Attempt to use the frame before the start of the segment to initialize the foreground.
// If one is not available, use frame 0 and start processing at frame 1.
if (init_frames.empty()) {
frame_index = 1;
bool success = cap.Read(lastFrame);
if (!success){
return { };
}
}
else {
frame_index = 0;
lastFrame = init_frames.at(0);
}
int lastFrameNum = 0;
int rows, cols;
const float* ranges[] = { hranges, sranges };
// Initialize the first frame.
edge_thresh = DetectionComponentUtils::GetProperty<double>(job.job_properties, "EDGE_THRESHOLD", edge_thresh);
hist_thresh = DetectionComponentUtils::GetProperty<double>(job.job_properties, "HIST_THRESHOLD", hist_thresh);
cont_thresh = DetectionComponentUtils::GetProperty<double>(job.job_properties, "CONT_THRESHOLD", cont_thresh);
thrs_thresh = DetectionComponentUtils::GetProperty<double>(job.job_properties, "THRS_THRESHOLD", thrs_thresh);
minPercent = DetectionComponentUtils::GetProperty<double>(job.job_properties, "MIN_PERCENT", minPercent);
minScene = DetectionComponentUtils::GetProperty<int>(job.job_properties, "MIN_SCENECHANGE_LENGTH", minScene);
do_hist = DetectionComponentUtils::GetProperty<bool>(job.job_properties, "DO_HIST", do_hist);
do_cont = DetectionComponentUtils::GetProperty<bool>(job.job_properties, "DO_CONT", do_cont);
do_thrs = DetectionComponentUtils::GetProperty<bool>(job.job_properties, "DO_THRS", do_thrs);
do_edge = DetectionComponentUtils::GetProperty<bool>(job.job_properties, "DO_EDGE", do_edge);
use_middle_frame = DetectionComponentUtils::GetProperty<bool>(job.job_properties, "USE_MIDDLE_FRAME", use_middle_frame);
double msec = cap.GetProperty(CAP_PROP_POS_MSEC);
rows = lastFrame.rows;
cols = lastFrame.cols;
numPixels = rows * cols;
cvtColor(lastFrame, frameGray, COLOR_BGR2GRAY);
cv::Mat frameEdges, frameEdgeFinal;
blur(frameGray, frameEdges, Size(3, 3));
Canny(frameEdges, frameEdges, 90, 270, 3);
frameGray.copyTo(lastFrameEdgeFinal, frameEdges);
dilate(lastFrameEdgeFinal, lastFrameEdgeFinal, dilateKernel);
cvtColor(lastFrame, lastFrameHSV, COLOR_BGR2HSV);
calcHist( &lastFrame, 1, (const int*) &channels[0], Mat(),
lastHist, 2, histSize, ranges,
true,
false );
cv::Mat frame;
while (cap.Read(frame)) {
cvtColor(frame,frameGray,COLOR_BGR2GRAY);
bool edge_result = do_edge && DetectChangeEdges(frameGray, lastFrameEdgeFinal);
bool hist_result = do_hist && DetectChangeHistogram(frame, lastHist);
bool cont_result = do_cont && DetectChangeContent(frame, lastFrameHSV);
bool thrs_result = do_thrs && DetectChangeThreshold(frame, lastFrame);
if (edge_result || hist_result || cont_result || thrs_result)
{
if (frame_index - lastFrameNum >= minScene)
{
keyframes[frame_index] = lastFrameNum;
lastFrameNum = frame_index;
}
}
frame_index++;
}
keyframes[frame_index] = lastFrameNum;
std::vector<MPFVideoTrack> tracks;
for(auto const& kv : keyframes)
{
auto start_frame = kv.second;
auto end_frame = kv.first;
MPFVideoTrack track(start_frame, end_frame - 1);
if (use_middle_frame) {
track.frame_locations.insert(
std::pair<int,MPFImageLocation>(start_frame + (int)((end_frame - start_frame) / 2),
MPFImageLocation(0, 0, cols, rows)
)
);
} else {
for(int i = start_frame; i < end_frame; i++)
{
track.frame_locations.insert(
std::pair<int,MPFImageLocation>(i,
MPFImageLocation(0, 0, cols, rows)
)
);
}
}
cap.ReverseTransform(track);
tracks.push_back(track);
}
keyframes.clear();
LOG4CXX_INFO(logger_, "[" + job.job_name + "] Processing complete. Found " + std::to_string(tracks.size()) + " tracks.");
return tracks;
}
catch (...) {
keyframes.clear();
Utils::LogAndReThrowException(job, logger_);
}
}
MPF_COMPONENT_CREATOR(SceneChangeDetection);
MPF_COMPONENT_DELETER();
| 36.71934 | 129 | 0.596955 | [
"vector"
] |
39c7a93c23180eb8e905b3ef844826edb9a25bbc | 1,009 | cpp | C++ | CC/LC/MinMovesToMakeArrComplementary.cpp | MrRobo24/Codes | 9513f42b61e898577123d5b996e43ba7a067a019 | [
"MIT"
] | 1 | 2020-10-12T08:03:20.000Z | 2020-10-12T08:03:20.000Z | CC/LC/MinMovesToMakeArrComplementary.cpp | MrRobo24/Codes | 9513f42b61e898577123d5b996e43ba7a067a019 | [
"MIT"
] | null | null | null | CC/LC/MinMovesToMakeArrComplementary.cpp | MrRobo24/Codes | 9513f42b61e898577123d5b996e43ba7a067a019 | [
"MIT"
] | null | null | null | https://leetcode.com/problems/minimum-moves-to-make-array-complementary/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minMoves(vector<int>& nums, int lim) {
int n = nums.size();
int change[200001] = {0};
int exact[200001] = {0};
int maxSum = INT_MIN;
for (int i=0;i<n/2;i++) {
int a = nums[i];
int b = nums[n-1-i];
int sum = a + b;
int low = min(a, b) + 1;
int high = max(a,b) + lim;
change[low]-=1;
change[high+1]+=1;
exact[a+b]+=1;
maxSum = max(maxSum, a + b);
}
//cout << "MAX SUM " << maxSum << "\n";
int steps = n, minSteps = INT_MAX;
for (int i=2;i<=maxSum;i++) {
steps += change[i];
minSteps = min(steps - exact[i], minSteps);
//cout << minSteps << "\n";
}
return minSteps;
}
}; | 27.27027 | 72 | 0.437066 | [
"vector"
] |
39d6bd477d74ad2d40750ef77412a042b01f0016 | 1,238 | cpp | C++ | test/test_lua_proxy.cpp | nitrocaster/luabind-deboostified | 72cc6e5e9da61d8ba0cd6835937a827c2cbad652 | [
"BSL-1.0"
] | 3 | 2015-11-23T08:19:40.000Z | 2020-11-03T01:52:37.000Z | test/test_lua_proxy.cpp | nitrocaster/luabind-deboostified | 72cc6e5e9da61d8ba0cd6835937a827c2cbad652 | [
"BSL-1.0"
] | 4 | 2020-10-18T23:11:14.000Z | 2021-01-01T20:54:49.000Z | test/test_lua_proxy.cpp | nitrocaster/luabind-deboostified | 72cc6e5e9da61d8ba0cd6835937a827c2cbad652 | [
"BSL-1.0"
] | 1 | 2020-12-28T18:47:11.000Z | 2020-12-28T18:47:11.000Z | // Boost Software License http://www.boost.org/LICENSE_1_0.txt
// Copyright (c) 2005 The Luabind Authors
#include <luabind/lua_proxy.hpp>
#include <luabind/object.hpp>
struct X_tag;
struct X
{
typedef X_tag lua_proxy_tag;
};
namespace luabind
{
template<>
struct lua_proxy_traits<X>
{
typedef std::true_type is_specialized;
};
} // namespace luabind
#define LUABIND_STATIC_ASSERT(expr) static_assert(expr, #expr)
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_type<X>::value);
LUABIND_STATIC_ASSERT(!luabind::is_lua_proxy_type<X&>::value);
LUABIND_STATIC_ASSERT(!luabind::is_lua_proxy_type<X const&>::value);
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_arg<X>::value);
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_arg<X const>::value);
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_arg<X&>::value);
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_arg<X const&>::value);
LUABIND_STATIC_ASSERT(!luabind::is_lua_proxy_arg<int>::value);
LUABIND_STATIC_ASSERT(!luabind::is_lua_proxy_arg<int[4]>::value);
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_arg<X const&>::value);
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_arg<luabind::object&>::value);
LUABIND_STATIC_ASSERT(luabind::is_lua_proxy_arg<luabind::object const&>::value);
| 31.74359 | 80 | 0.789176 | [
"object"
] |
39d7725392d719429cd695e1ff5bb61c33e5f50f | 382 | cpp | C++ | app/Obstacle.cpp | nuclearczy/mid-test | 9e7bca69fcfa3905179d14ebc81823562d97eea6 | [
"BSD-3-Clause"
] | null | null | null | app/Obstacle.cpp | nuclearczy/mid-test | 9e7bca69fcfa3905179d14ebc81823562d97eea6 | [
"BSD-3-Clause"
] | null | null | null | app/Obstacle.cpp | nuclearczy/mid-test | 9e7bca69fcfa3905179d14ebc81823562d97eea6 | [
"BSD-3-Clause"
] | 1 | 2020-10-18T13:09:19.000Z | 2020-10-18T13:09:19.000Z | /**Copyright (c) 2019 Hao Da (Kevin) Dong, Zuyang Cao, Jing Liang
* @file Obstacle.cpp
* @date 10/13/2019
* @brief The file Obstacle.cpp implements the obstacle class.
* The class will be used in Xingyun class.
* @license This project is released under the BSD-3-Clause License.
*/
#include<iostream>
#include<vector>
#include <Obstacle.hpp>
| 29.384615 | 71 | 0.662304 | [
"vector"
] |
39e55d904e1d715eb3a1133df5f27d7f350e6b67 | 3,160 | cpp | C++ | pose_refinement/SA-LMPE/ba/openMVG/features/mser/mser_test.cpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 90 | 2019-05-19T03:48:23.000Z | 2022-02-02T15:20:49.000Z | pose_refinement/SA-LMPE/ba/openMVG/features/mser/mser_test.cpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 11 | 2019-05-22T07:45:46.000Z | 2021-05-20T01:48:26.000Z | pose_refinement/SA-LMPE/ba/openMVG/features/mser/mser_test.cpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 18 | 2019-05-19T03:48:32.000Z | 2021-05-29T18:19:16.000Z | // This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2015 Romuald PERROT, Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/features/feature.hpp"
#include "openMVG/features/mser/mser.hpp"
#include "openMVG/features/mser/mser_region.hpp"
#include "openMVG/image/image_io.hpp"
#include "testing/testing.h"
using namespace openMVG;
using namespace image;
using namespace features;
using namespace MSER;
TEST( MSER , Extraction )
{
Image<unsigned char> image , outimg;
const std::string png_filename = std::string(THIS_SOURCE_DIR) + "/image_test/lena.png";
EXPECT_TRUE(ReadImage(png_filename.c_str(), &image));
// Inverted image
Image<unsigned char> image4( 255 - image.array() );
std::vector<MSERRegion> regs;
MSERExtractor extr4( 2 , 0.0005, 0.1 , 0.5 , 0.5 , MSERExtractor::MSER_4_CONNECTIVITY );
extr4.Extract( image4 , regs );
MSERExtractor extr8( 2 , 0.0005 , 0.1 , 0.5 , 0.5 , MSERExtractor::MSER_8_CONNECTIVITY );
extr8.Extract( image , regs );
// Export ellipse
outimg = image;
for (size_t i = 0; i < regs.size(); ++i )
{
double ex , ey;
double Mx, My;
double mx , my;
double Ml , ml;
regs[i].FitEllipse( ex , ey , Mx , My , mx , my , Ml , ml );
for (double t = 0; t < 2.0 * 3.141592; t += 0.001 )
{
const int x = ex + ( cos( t ) * Mx * Ml + sin( t ) * mx * ml ) * 2.0 + 0.5;
const int y = ey + ( cos( t ) * My * Ml + sin( t ) * my * ml ) * 2.0 + 0.5;
if (x >= 0 && y >= 0 && x < image.Width() && y < image.Height() )
{
outimg( y , x ) = 255;
}
}
/*
double a, b, c;
regs[i].FitEllipse( a, b, c );
double x, y;
regs[i].FitEllipse( x, y );
const AffinePointFeature fp(x, y, a, b, c);
DrawEllipse(fp.x(), fp.y(), fp.l1(), fp.l2(), 255, &outimg, fp.orientation());
*/
}
WriteImage( "outimg.png" , outimg );
}
TEST( MSER , Extraction_Synthetic )
{
// Dark MSER detection
{
Image<unsigned char> image(40, 40, true, 254);
image.block<10,10>(15,15).setConstant(1);
WriteImage( "in_1.png" , image );
std::vector<MSERRegion> regs;
// Dark regions
MSERExtractor extr( 2 , 0.0005 , 0.1 , 0.5 , 0.5 , MSERExtractor::MSER_4_CONNECTIVITY );
extr.Extract( image , regs );
EXPECT_EQ(1, regs.size());
}
// Bright MSER detection
{
Image<unsigned char> image(40, 40, true, 1);
image.block<10,10>(15,15).setConstant(127);
WriteImage( "in_2.png" , image );
// Dark regions
std::vector<MSERRegion> regs;
MSERExtractor extr( 2 , 0.0005 , 0.1 , 0.5 , 0.5 , MSERExtractor::MSER_4_CONNECTIVITY );
extr.Extract( Image<unsigned char>( 255 - image.array() ) , regs );
EXPECT_EQ(1, regs.size());
}
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
| 29.53271 | 92 | 0.583861 | [
"geometry",
"vector"
] |
39ea31547ad69edd1f6bcaccbaf9e05504677f4d | 7,385 | cpp | C++ | src/atomsciflow/vasp/vasp_poscar.cpp | DeqiTang/build-test-atomsciflow | 6fb65c79e74993e2100fbbca31b910d495076805 | [
"MIT"
] | 1 | 2022-01-25T01:44:32.000Z | 2022-01-25T01:44:32.000Z | src/atomsciflow/vasp/vasp_poscar.cpp | DeqiTang/build-test-atomsciflow | 6fb65c79e74993e2100fbbca31b910d495076805 | [
"MIT"
] | null | null | null | src/atomsciflow/vasp/vasp_poscar.cpp | DeqiTang/build-test-atomsciflow | 6fb65c79e74993e2100fbbca31b910d495076805 | [
"MIT"
] | null | null | null | /************************************************************************
MIT License
Copyright (c) 2021 Deqi Tang
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 "atomsciflow/vasp/vasp_poscar.h"
#include <boost/algorithm/string.hpp>
#include <armadillo>
#include <iostream>
#include <vector>
#include "atomsciflow/utils/structure.h"
#include "atomsciflow/base/element.h"
namespace atomsciflow {
namespace ba = boost::algorithm;
VaspPoscar::VaspPoscar() {
selective_dynamics = false;
}
void VaspPoscar::get_xyz(std::string xyzfile) {
auto element_map = get_element_number_map();
this->xyz.read_xyz_file(xyzfile);
for (const auto& elem : this->xyz.elements_set) {
this->elem_natom_in_number_order.push_back(std::pair<std::string, int>{elem, element_map[elem].number});
}
std::sort(
this->elem_natom_in_number_order.begin(),
this->elem_natom_in_number_order.end(),
[](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) -> bool {
return a.second < b.second;
}
);
for (auto& item : this->elem_natom_in_number_order) {
item.second = 0;
for (const auto& atom : this->xyz.atoms) {
if (item.first == atom.name) {
++item.second;
}
}
}
}
/**
* @brief VaspPoscar::to_string
* @param coordtype
* candidates:
* "direct" | "cartesian", ignoring upper or lower case
* @return The vasp POSCAR as a string
* Note:
* THe order of atoms in the gnerated POSCAR string might be
* different from the input xyz file. Because, the atoms in
* POSCAR is grouped considering the element type.
*/
std::string VaspPoscar::to_string(std::string coordtype = "Cartesian") {
std::string out = "";
auto cell = this->xyz.cell;
out += "general comment\n";
out += "1.0\n";
for (const auto& vec : cell) {
out += std::to_string(vec[0]);
out += "\t";
out += std::to_string(vec[1]);
out += "\t";
out += std::to_string(vec[2]);
out += "\n";
}
for (const auto& item : this->elem_natom_in_number_order) {
out += item.first;
out += " ";
}
out += "\n";
for (const auto& item : this->elem_natom_in_number_order) {
out += std::to_string(item.second);
out += " ";
}
out += "\n";
if (this->selective_dynamics == true) {
out += "Selective dynamics\n";
if (ba::to_lower_copy(coordtype) == "cartesian") {
out += "Cartesian\n";
for (const auto& element_pair : this->elem_natom_in_number_order) {
for (const auto& atom : this->xyz.atoms) {
if (element_pair.first == atom.name) {
out += std::to_string(atom.x);
out += "\t";
out += std::to_string(atom.y);
out += "\t";
out += std::to_string(atom.z);
// for (auto fix : atom.fix) {
// if (fix == true) {
// out += "\tF";
// } else if (fix == False) {
// out += "\tT";
// }
// }
out += "\n";
}
}
}
} else if (ba::to_lower_copy(coordtype) == "direct") {
std::vector<Atom> atoms_frac;
atoms_cart_to_frac(atoms_frac, this->xyz.atoms, this->xyz.cell);
out += "Direct\n";
for (const auto& element_pair : this->elem_natom_in_number_order) {
for (int k = 0; k < this->xyz.atoms.size(); k++) {
if (element_pair.first == this->xyz.atoms[k].name) {
out += std::to_string(atoms_frac[k].x);
out += std::to_string(atoms_frac[k].y);
out += std::to_string(atoms_frac[k].z);
// for (auto fix in this->xyz.atoms[k].fix) {
// if (fix == true) {
// out += "\tF";
// } else if (fix == false) {
// out += "\tT";
// }
// }
out += "\n";
}
}
}
}
} else if (false == this->selective_dynamics) {
if (ba::to_lower_copy(coordtype) == "cartesian") {
out += "Cartesian\n";
for (const auto& item : this->elem_natom_in_number_order) {
for (const auto& atom : this->xyz.atoms) {
if (atom.name == item.first) {
out += std::to_string(atom.x);
out += "\t";
out += std::to_string(atom.y);
out += "\t";
out += std::to_string(atom.z);
out += "\n";
}
}
}
} else if (ba::to_lower_copy(coordtype) == "direct") {
std::vector<Atom> atoms_frac;
atoms_cart_to_frac(atoms_frac, this->xyz.atoms, this->xyz.cell);
out += "Direct\n";
for (const auto& item : this->elem_natom_in_number_order) {
for (int k = 0; k < this->xyz.atoms.size(); k++) {
if (this->xyz.atoms[k].name == item.first) {
out += std::to_string(atoms_frac[k].x);
out += "\t";
out += std::to_string(atoms_frac[k].y);
out += "\t";
out += std::to_string(atoms_frac[k].z);
out += "\n";
}
}
}
}
} else {
std::cout << "------------------------------------------------------------------------" << "\n";
std::cout << "Warning: atomsciflow::Vasp::VaspPoscar\n";
std::cout << "ifstatic could only be true or false\n";
std::cout << "------------------------------------------------------------------------" << "\n";
std::exit(1);
}
out += "\n";
return out;
}
} // namespace atomsciflow
| 38.463542 | 112 | 0.486662 | [
"vector"
] |
39eb46a2a6737b5d82bf2e56a660204122633a8b | 22,130 | cxx | C++ | src/ptclib/speech_aws.cxx | sverdlin/opalvoip-ptlib | f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be | [
"Beerware"
] | null | null | null | src/ptclib/speech_aws.cxx | sverdlin/opalvoip-ptlib | f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be | [
"Beerware"
] | null | null | null | src/ptclib/speech_aws.cxx | sverdlin/opalvoip-ptlib | f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be | [
"Beerware"
] | null | null | null | /*
* speech_aws.cxx
*
* AWS SDK interface wrapper for speech
*
* Portable Windows Library
*
* Copyright (c) 2021 Vox Lucida Pty. Ltd.
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Portable Windows Library.
*
* The Initial Developer of the Original Code is Vox Lucida Pty. Ltd.
*
* Contributor(s): Robert Jongbloed.
*/
#include <ptlib.h>
#if P_AWS_SDK
#include <ptclib/speech.h>
#include <ptclib/pwavfile.h>
#include <ptclib/random.h>
#include <ptclib/url.h>
#include <ptclib/cypher.h>
#include <ptclib/http.h>
#include <ptclib/pjson.h>
#include <ptclib/aws_sdk.h>
#define USE_IMPORT_EXPORT
#include <aws/polly/PollyClient.h>
#include <aws/text-to-speech/PCMOutputDriver.h>
#include <aws/text-to-speech/TextToSpeechManager.h>
#include <aws/transcribe/TranscribeServiceClient.h>
#include <aws/transcribe/model/CreateVocabularyRequest.h>
#include <aws/transcribe/model/DeleteVocabularyRequest.h>
#define PTraceModule() "AWS-Speech"
#ifdef _MSC_VER
#pragma comment(lib, P_AWS_SDK_LIBDIR(polly))
#pragma comment(lib, P_AWS_SDK_LIBDIR(text-to-speech))
#pragma comment(lib, P_AWS_SDK_LIBDIR(transcribe))
#endif
////////////////////////////////////////////////////////////
// Text to speech using AWS
class PTextToSpeech_AWS : public PTextToSpeech, PAwsClient<Aws::Polly::PollyClient>
{
PCLASSINFO(PTextToSpeech_AWS, PTextToSpeech);
std::shared_ptr<Aws::TextToSpeech::TextToSpeechManager> m_manager;
Aws::TextToSpeech::CapabilityInfo m_capability;
struct WAVOutputDriver : Aws::TextToSpeech::PCMOutputDriver, PObject
{
PWAVFile m_wavFile;
virtual bool WriteBufferToDevice(const unsigned char* data, size_t size)
{
return m_wavFile.Write(data, size);
}
virtual Aws::Vector<Aws::TextToSpeech::DeviceInfo> EnumerateDevices() const
{
Aws::TextToSpeech::DeviceInfo deviceInfo;
deviceInfo.deviceName = "*.wav";
return Aws::Vector<Aws::TextToSpeech::DeviceInfo>(1, deviceInfo);
}
virtual void SetActiveDevice(const Aws::TextToSpeech::DeviceInfo & deviceInfo, const Aws::TextToSpeech::CapabilityInfo & capability)
{
if (m_wavFile.Open(deviceInfo.deviceName.c_str(), PFile::WriteOnly) &&
m_wavFile.SetSampleRate(capability.sampleRate) &&
m_wavFile.SetChannels(capability.channels) &&
m_wavFile.SetSampleSize(capability.sampleWidthBits)) {
PTRACE(4, "Opened WAV file " << m_wavFile.GetName());
}
}
virtual const char* GetName() const
{
return m_wavFile.GetName().c_str();
}
};
struct OutputDriverFactory : Aws::TextToSpeech::PCMOutputDriverFactory
{
virtual Aws::Vector<std::shared_ptr<Aws::TextToSpeech::PCMOutputDriver>> LoadDrivers() const
{
Aws::Vector<std::shared_ptr<Aws::TextToSpeech::PCMOutputDriver>> drivers;
drivers.push_back(std::make_shared<WAVOutputDriver>());
return drivers;
}
};
public:
PTextToSpeech_AWS()
{
m_capability.sampleRate = 8000;
m_capability.channels = 1;
m_capability.sampleWidthBits = 16;
}
~PTextToSpeech_AWS()
{
Close();
}
virtual PStringArray GetVoiceList()
{
//Enumerate the available voices
auto mgr = m_manager;
if (!mgr)
mgr = Aws::TextToSpeech::TextToSpeechManager::Create(m_client);
Aws::Vector<std::pair<Aws::String, Aws::String>> awsVoices = mgr->ListAvailableVoices();
PStringArray voiceList(awsVoices.size());
for (size_t i = 0; i < awsVoices.size(); ++i)
voiceList[i] = PSTRSTRM(awsVoices[i].first << ':' << awsVoices[i].second);
PTRACE(3, "Voices: " << setfill(',') << voiceList);
return voiceList;
}
virtual bool InternalSetVoice(const PString & name, const PString & /*language*/)
{
if (!m_manager)
return false;
m_manager->SetActiveVoice(name.c_str());
return true;
}
virtual bool SetSampleRate(unsigned rate)
{
m_capability.sampleRate = rate;
return true;
}
virtual unsigned GetSampleRate() const
{
return m_capability.sampleRate;
}
virtual bool SetChannels(unsigned channels)
{
m_capability.channels = channels;
return true;
}
virtual unsigned GetChannels() const
{
return m_capability.channels;
}
bool SetVolume(unsigned)
{
return false;
}
unsigned GetVolume() const
{
return 100;
}
bool OpenFile(const PFilePath & fn)
{
m_manager = Aws::TextToSpeech::TextToSpeechManager::Create(m_client, std::make_shared<OutputDriverFactory>());
std::shared_ptr<WAVOutputDriver> driver = std::make_shared<WAVOutputDriver>();
PTRACE_CONTEXT_ID_TO(*driver);
Aws::TextToSpeech::DeviceInfo deviceInfo;
deviceInfo.deviceName = fn.c_str();
m_manager->SetActiveDevice(driver, deviceInfo, m_capability);
if (m_voiceName.empty())
SetVoice(PString::Empty());
else
InternalSetVoice(m_voiceName, m_voiceLanguage);
return true;
}
bool OpenChannel(PChannel * /*channel*/)
{
Close();
return false;
}
bool IsOpen() const
{
return !!m_manager;
}
bool Close()
{
m_manager.reset();
return true;
}
bool Speak(const PString & text, TextType /*hint*/)
{
bool success = false;
PSyncPoint done;
Aws::TextToSpeech::SendTextCompletedHandler handler =
[&success, &done]
(const char*, const Aws::Polly::Model::SynthesizeSpeechOutcome&, bool doneGood)
{
success = doneGood;
done.Signal();
};
m_manager->SendTextToOutputDevice(text.c_str(), handler);
done.Wait();
return success;
}
};
PFACTORY_CREATE(PFactory<PTextToSpeech>, PTextToSpeech_AWS, P_TEXT_TO_SPEECH_AWS, false);
////////////////////////////////////////////////////////////
// Speech recognition using Microsoft's Speech API (SAPI)
class PSpeechRecognition_AWS : public PSpeechRecognition, PAwsClient<Aws::TranscribeService::TranscribeServiceClient>
{
PCLASSINFO(PSpeechRecognition_AWS, PSpeechRecognition);
unsigned m_sampleRate;
Aws::TranscribeService::Model::LanguageCode m_language;
PStringSet m_vocabularies;
PWebSocket m_webSocket;
PThread * m_eventThread;
PDECLARE_MUTEX(m_openMutex);
PDECLARE_MUTEX(m_eventMutex);
#pragma pack(1)
struct Prelude
{
PUInt32b m_totalLen;
PUInt32b m_headerLen;
PUInt32b m_preludeCRC;
};
#pragma pack()
bool WriteEvent(const PBYTEArray & contents, const PStringOptions & headers)
{
size_t headerLen = 0;
for (PStringOptions::const_iterator it = headers.begin(); it != headers.end(); ++it)
headerLen += 1 + it->first.length() + 1 + 2 + it->second.length();
PBYTEArray message(sizeof(Prelude) + headerLen + contents.size() + sizeof(PUInt32b));
BYTE * ptr = message.GetPointer();
Prelude & prelude = *reinterpret_cast<Prelude *>(ptr);
ptr += sizeof(Prelude);
prelude.m_headerLen = headerLen;
prelude.m_totalLen = message.size();
prelude.m_preludeCRC = PCRC32::Calculate(&prelude, sizeof(Prelude) - sizeof(prelude.m_preludeCRC));
for (PStringOptions::const_iterator it = headers.begin(); it != headers.end(); ++it) {
PString key = it->first;
PString value = it->second;
*ptr++ = key.length();
memcpy(ptr, key.c_str(), key.length());
ptr += key.length();
*ptr++ = 7; // String
*(PUInt16b *)ptr = value.length();
ptr += 2;
memcpy(ptr, value.c_str(), value.length());
ptr += value.length();
}
memcpy(ptr, contents, contents.size());
ptr += contents.size();
*(PUInt32b *)ptr = PCRC32::Calculate(message, message.size() - sizeof(PUInt32b));
return m_webSocket.Write(message, message.size());
}
bool WriteAudioEvent(const int16_t * samples, size_t sampleCount)
{
PStringOptions headers;
headers.Set(":message-type", "event");
headers.Set(":event-type", "AudioEvent");
headers.Set(":content-type", "application/octet-stream");
return WriteEvent(PBYTEArray((const BYTE *)samples, sampleCount*sizeof(uint16_t), false), headers);
}
bool ReadEvent(PBYTEArray & contents, PStringOptions & headers)
{
PBYTEArray message;
if (!m_webSocket.ReadMessage(message))
return false;
if (message.size() < sizeof(Prelude)) {
PTRACE(2, "Received message ridiculously small");
return false;
}
Prelude prelude = message.GetAs<Prelude>();
if (message.size() < prelude.m_totalLen) {
PTRACE(2, "Received message too small");
return false;
}
uint32_t calculatedCRC = PCRC32::Calculate(message, sizeof(Prelude) - sizeof(prelude.m_preludeCRC));
uint32_t providedCRC = prelude.m_preludeCRC;
if (calculatedCRC != providedCRC) {
PTRACE(2, "Received message header CRC failed: " << calculatedCRC << "!=" << providedCRC);
return false;
}
size_t crcPos = message.size() - sizeof(uint32_t);
calculatedCRC = PCRC32::Calculate(message, crcPos);
providedCRC = message.GetAs<PUInt32b>(crcPos);
if (calculatedCRC != providedCRC) {
PTRACE(2, "Received message CRC failed: " << calculatedCRC << "!=" << providedCRC);
return false;
}
const BYTE * ptr = message.GetPointer() + sizeof(prelude);
const BYTE * endHeaders = ptr + prelude.m_headerLen;
while (ptr < endHeaders) {
PString key(reinterpret_cast<const char *>(ptr)+1, *ptr);
ptr += key.length() + 1;
switch (*ptr++) {
default:
PTRACE(2, "Received message with invalid header");
return false;
case 0:
headers.SetBoolean(key, true);
break;
case 1:
headers.SetBoolean(key, false);
break;
case 2:
headers.SetInteger(key, *ptr++);
break;
case 3:
headers.SetInteger(key, *reinterpret_cast<const PUInt16b *>(ptr));
ptr += sizeof(PUInt16b);
break;
case 4:
headers.SetInteger(key, *reinterpret_cast<const PUInt32b *>(ptr));
ptr += sizeof(PUInt32b);
break;
case 5:
headers.SetVar(key, *reinterpret_cast<const PUInt64b *>(ptr));
ptr += sizeof(PUInt64b);
break;
case 6:
case 7:
case 8:
uint16_t len = *reinterpret_cast<const PUInt16b *>(ptr);
headers.SetString(key, PString(reinterpret_cast<const char *>(ptr)+sizeof(PUInt16b), len));
ptr += len + sizeof(PUInt16b);
break;
}
}
contents = PBYTEArray(ptr, message.size() - sizeof(prelude) - prelude.m_headerLen - sizeof(uint32_t));
return true;
}
void ReadEvents()
{
std::set<Transcript> sentTranscripts;
while (m_webSocket.IsOpen()) {
PBYTEArray data;
PStringOptions headers;
if (ReadEvent(data, headers)) {
PTRACE(5, "Read " << data.size() << " bytes, headers:\n" << headers);
PJSON json(PJSON::e_Null);
if (headers.Get(":content-type") == PMIMEInfo::ApplicationJSON())
json.FromString(data);
PString messageType = headers.Get(":message-type");
if (messageType == "event") {
PString type = headers.Get(":event-type");
if (type == "TranscriptEvent" &&
json.IsType(PJSON::e_Object) &&
json.GetObject().IsType("Transcript", PJSON::e_Object) &&
json.GetObject().GetObject("Transcript").IsType("Results", PJSON::e_Array)) {
PJSON::Array const & results = json.GetObject().GetObject("Transcript").GetArray("Results");
PTRACE_IF(4, !results.empty(), "Received " << type << ":\n" << json.AsString(0, 2));
for (size_t idxResult = 0; idxResult < results.size(); ++idxResult) {
if (results.IsType(idxResult, PJSON::e_Object)) {
PJSON::Object const & result = results.GetObject(idxResult);
if (result.IsType("Alternatives", PJSON::e_Array)) {
PJSON::Array const & alternatives = result.GetArray("Alternatives");
for (size_t idxAlternative = 0; idxAlternative < alternatives.size(); ++idxAlternative) {
if (alternatives.GetObject(idxAlternative).IsType("Items", PJSON::e_Array)) {
PJSON::Array const & items = alternatives.GetObject(idxAlternative).GetArray("Items");
for (size_t idxItem = 0; idxItem < items.size(); ++idxItem) {
if (items.IsType(idxItem, PJSON::e_Object)) {
PJSON::Object const & item = items.GetObject(idxItem);
if (item.GetString("Type") == "pronunciation") {
Transcript transcript(false,
PTimeInterval::Seconds((double)item.GetNumber("StartTime")),
item.GetString("Content"),
(float)item.GetNumber("Confidence"));
if (!transcript.m_content.empty() && sentTranscripts.find(transcript) == sentTranscripts.end()) {
sentTranscripts.insert(transcript);
PTRACE(4, "Sending notification of " << transcript);
m_notifier(*this, transcript);
}
}
}
}
}
}
if (!alternatives.empty() && !result.GetBoolean("IsPartial")) {
Transcript transcript(true,
PTimeInterval::Seconds((double)result.GetNumber("StartTime")),
alternatives.GetObject(0).GetString("Transcript"),
1);
PTRACE(4, "Sending notification of " << transcript);
m_notifier(*this, transcript);
}
}
}
}
}
else {
PTRACE(4, "Received " << type << ":\n" << json.AsString(0, 2));
}
}
#if PTRACING
else if (PTrace::CanTrace(2) && messageType == "exception") {
ostream & log = PTRACE_BEGIN(2);
log << "Received exception " << headers.Get(":exception-type", "Unknown") << ", details:";
if (json.IsType(PJSON::e_Null))
log << '\n' << data;
else {
PString msg;
if (json.IsType(PJSON::e_Object))
msg = json.GetObject().GetString("Message");
else if (json.IsType(PJSON::e_String))
msg = json.GetString();
if (msg.empty())
log << '\n' << json.AsString(0, 2);
else
log << (msg.Find('\n') != P_MAX_INDEX ? '\n' : ' ') << msg;
}
log << PTrace::End;
}
#endif // PTRACING
}
}
}
void DeleteVocabulary(const PString & name)
{
if (name.empty() || !m_vocabularies.Contains(name))
return;
m_client->DeleteVocabulary(Aws::TranscribeService::Model::DeleteVocabularyRequest()
.WithVocabularyName(name.c_str()));
m_vocabularies -= name;
}
public:
PSpeechRecognition_AWS()
: m_sampleRate(8000)
, m_language(Aws::TranscribeService::Model::LanguageCode::en_US)
, m_eventThread(NULL)
{ }
~PSpeechRecognition_AWS()
{
Close();
while (!m_vocabularies.empty())
DeleteVocabulary(*m_vocabularies.begin());
}
virtual bool SetSampleRate(unsigned rate)
{
PWaitAndSignal lock(m_openMutex);
if (IsOpen())
return false;
m_sampleRate = rate;
return true;
}
virtual unsigned GetSampleRate() const
{
return m_sampleRate;
}
virtual bool SetChannels(unsigned channels)
{
return channels == 1;
}
virtual unsigned GetChannels() const
{
return 1;
}
virtual bool SetLanguage(const PString & language)
{
PWaitAndSignal lock(m_openMutex);
if (IsOpen())
return false;
auto code = Aws::TranscribeService::Model::LanguageCodeMapper::GetLanguageCodeForName(language.c_str());
if (code == Aws::TranscribeService::Model::LanguageCode::NOT_SET)
return false;
m_language = code;
return true;
}
virtual PString GetLanguage() const
{
return Aws::TranscribeService::Model::LanguageCodeMapper::GetNameForLanguageCode(m_language);
}
virtual bool SetVocabulary(const PString & name, const PStringArray & words)
{
DeleteVocabulary(name);
if (words.empty())
return true;
Aws::Vector<Aws::String> phrases(words.size());
for (size_t i = 0; i < words.size(); ++i)
phrases[i] = words[i].c_str();
auto outcome = m_client->CreateVocabulary(Aws::TranscribeService::Model::CreateVocabularyRequest()
.WithVocabularyName(name.c_str())
.WithLanguageCode(m_language)
.WithPhrases(phrases));
if (outcome.IsSuccess()) {
m_vocabularies += name;
return true;
}
PTRACE(2, "Could not create vocubulary: " << outcome.GetResult().GetFailureReason());
return false;
}
static void AddSignedHeader(PURL & url, PStringStream & canonical, const char * key, const PString & value, bool first = false)
{
url.SetQueryVar(key, value);
if (!first)
canonical << '&';
canonical << key << '=' << PURL::TranslateString(value, PURL::QueryTranslation);
}
virtual bool Open(const Notifier & notifier, const PString & vocabulary)
{
PWaitAndSignal lock(m_openMutex);
Close();
PTRACE(4, "Opening speech recognition.");
m_notifier = notifier;
PConstString const service("transcribe");
PConstString const operation("aws4_request");
PConstString const algorithm("AWS4-HMAC-SHA256");
PString timestamp = PTime().AsString(PTime::ShortISO8601, PTime::UTC);
PString credentialDatestamp = timestamp.Left(8);
PString credentialScope = PSTRSTRM(credentialDatestamp << '/' << m_region << '/' << service << '/' << operation);
PStringStream canonical;
PURL url;
url.SetScheme("wss");
url.SetHostName(PSTRSTRM("transcribestreaming." << m_region << ".amazonaws.com"));
url.SetPort(8443);
url.SetPathStr("stream-transcription-websocket");
canonical << "GET\n" << url.GetPathStr() << '\n';
// The following must be in ANSI order
AddSignedHeader(url, canonical, "X-Amz-Algorithm", algorithm, true);
AddSignedHeader(url, canonical, "X-Amz-Credential", PSTRSTRM(m_accessKeyId << '/' << credentialScope));
AddSignedHeader(url, canonical, "X-Amz-Date", timestamp);
AddSignedHeader(url, canonical, "X-Amz-Expires", "300");
AddSignedHeader(url, canonical, "X-Amz-SignedHeaders", "host");
AddSignedHeader(url, canonical, "language-code", GetLanguage());
AddSignedHeader(url, canonical, "media-encoding", "pcm");
AddSignedHeader(url, canonical, "sample-rate", PString(GetSampleRate()));
if (!vocabulary.empty())
AddSignedHeader(url, canonical, "vocabulary-name", vocabulary);
canonical << "\nhost:" << url.GetHostPort() << "\n\nhost\n";
PMessageDigest::Result result;
PMessageDigestSHA256::Encode("", result);
canonical << result.AsHex();
PMessageDigestSHA256::Encode(canonical, result);
PString stringToSign = PSTRSTRM(algorithm << '\n' << timestamp << '\n' << credentialScope << '\n' << result.AsHex());
PHMAC_SHA256 signer;
signer.SetKey("AWS4" + m_secretAccessKey); signer.Process(credentialDatestamp, result);
signer.SetKey(result); signer.Process(m_region.c_str(), result);
signer.SetKey(result); signer.Process(service, result);
signer.SetKey(result); signer.Process(operation, result);
signer.SetKey(result); signer.Process(stringToSign, result);
url.SetQueryVar("X-Amz-Signature", result.AsHex());
PTRACE(4, "Execute WebSocket connect: " << url << "\nCanonical string:\n'" << canonical << "'\nStringToSign:\n'" << stringToSign << '\'');
if (!m_webSocket.Connect(url))
return false;
m_webSocket.SetBinaryMode();
m_eventThread = new PThreadObj<PSpeechRecognition_AWS>(*this, &PSpeechRecognition_AWS::ReadEvents);
PTRACE(3, "Opened speech recognition.");
return true;
}
virtual bool IsOpen() const
{
return m_webSocket.IsOpen();
}
virtual bool Close()
{
PWaitAndSignal lock(m_openMutex);
if (!IsOpen())
return false;
PTRACE(3, "Closing speech recognition.");
m_webSocket.Close();
PThread::WaitAndDelete(m_eventThread);
return true;
}
virtual bool Listen(const PFilePath & fn)
{
if (!PAssert(!fn.empty(), PInvalidParameter))
return false;
PWaitAndSignal lock(m_openMutex);
if (!m_webSocket.IsOpen())
return false;
PWAVFile wavFile;
if (!wavFile.Open(fn, PFile::ReadOnly))
return false;
vector<int16_t> buffer(4096);
while (wavFile.Read(buffer.data(), buffer.size()*sizeof(int16_t))) {
if (!WriteAudioEvent(buffer.data(), wavFile.GetLastReadCount()/sizeof(int16_t)))
return false;
}
WriteAudioEvent(NULL, 0); // Empty event ends the stream
PTRACE(4, "Written " << fn);
return wavFile.GetErrorCode() == PChannel::NoError;
}
virtual bool Listen(const int16_t * samples, size_t sampleCount)
{
PWaitAndSignal lock(m_openMutex);
return m_webSocket.IsOpen() && WriteAudioEvent(samples, sampleCount);
}
};
PFACTORY_CREATE(PFactory<PSpeechRecognition>, PSpeechRecognition_AWS, P_SPEECH_RECOGNITION_AWS, false);
#endif // P_AWS_SDK
| 30.994398 | 142 | 0.623678 | [
"object",
"vector",
"model"
] |
39ec9a4250f2cf7f977f5e7dd2328764472681e3 | 3,665 | hpp | C++ | include/VM/Vars.hpp | feral-lang/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"MIT"
] | 131 | 2020-03-19T15:22:37.000Z | 2021-12-19T02:37:01.000Z | include/VM/Vars.hpp | Electrux/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"BSD-3-Clause"
] | 14 | 2020-04-06T05:50:15.000Z | 2021-06-26T06:19:04.000Z | include/VM/Vars.hpp | Electrux/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"BSD-3-Clause"
] | 20 | 2020-04-06T07:28:30.000Z | 2021-09-05T14:46:25.000Z | /*
MIT License
Copyright (c) 2020 Feral Language repositories
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.
*/
#ifndef VM_VARS_HPP
#define VM_VARS_HPP
#include <string>
#include <unordered_map>
#include <vector>
#include "Vars/Base.hpp"
class vars_frame_t
{
std::unordered_map<std::string, var_base_t *> m_vars;
public:
vars_frame_t();
~vars_frame_t();
inline const std::unordered_map<std::string, var_base_t *> &all() const
{
return m_vars;
}
inline bool exists(const std::string &name)
{
return m_vars.find(name) != m_vars.end();
}
var_base_t *get(const std::string &name);
void add(const std::string &name, var_base_t *val, const bool inc_ref);
void rem(const std::string &name, const bool dec_ref);
static void *operator new(size_t sz);
static void operator delete(void *ptr, size_t sz);
vars_frame_t *thread_copy(const size_t &src_id, const size_t &idx);
};
class vars_stack_t
{
std::vector<size_t> m_loops_from;
// each vars_frame_t is a stack frame
// it is a pointer to remove the issue of recreation of object when vector increases size
// since recreation will cause the object to be deleted (and destructor be called) and
// invalidate the variable pointers (since destructor contains var_dref() calls)
std::vector<vars_frame_t *> m_stack;
size_t m_top;
public:
vars_stack_t();
~vars_stack_t();
// checks if a variable exists in CURRENT scope ONLY
bool exists(const std::string &name);
var_base_t *get(const std::string &name);
void inc_top(const size_t &count);
void dec_top(const size_t &count);
void push_loop();
// 'break' also uses this
void pop_loop();
void loop_continue();
void add(const std::string &name, var_base_t *val, const bool inc_ref);
void rem(const std::string &name, const bool dec_ref);
vars_stack_t *thread_copy(const size_t &src_id, const size_t &idx);
};
/*
* vars for each source file
* stash exists to add variables to a function BEFORE the block of function starts
* this is useful for declaring function variables inside the function without extra scope
*
* 0 cannot be a function id as it specifies source level scope and hence is created in constructor
*/
class vars_t
{
size_t m_fn_stack;
std::unordered_map<std::string, var_base_t *> m_stash;
// maps function id to vars_frame_t
std::unordered_map<size_t, vars_stack_t *> m_fn_vars;
public:
vars_t();
~vars_t();
// checks if a variable exists in CURRENT scope ONLY
bool exists(const std::string &name);
var_base_t *get(const std::string &name);
void blk_add(const size_t &count);
void blk_rem(const size_t &count);
void push_fn();
void pop_fn();
void stash(const std::string &name, var_base_t *val, const bool &iref = true);
void unstash();
inline void push_loop()
{
m_fn_vars[m_fn_stack]->push_loop();
}
inline void pop_loop()
{
m_fn_vars[m_fn_stack]->pop_loop();
}
inline void loop_continue()
{
m_fn_vars[m_fn_stack]->loop_continue();
}
void add(const std::string &name, var_base_t *val, const bool inc_ref);
// add variable to module level unconditionally (for vm.register_new_type())
void addm(const std::string &name, var_base_t *val, const bool inc_ref);
void rem(const std::string &name, const bool dec_ref);
vars_t *thread_copy(const size_t &src_id, const size_t &idx);
};
#endif // VM_VARS_HPP
| 26.751825 | 99 | 0.736971 | [
"object",
"vector"
] |
39f833e3cfc5744e72f06f8331afd0c67cd7d8fe | 2,123 | cpp | C++ | src/CalculatorManager.cpp | feng-zhe/ZheQuant-brain-cpp | 3180b7cfcbfc4ca13831dbbbe1fa69821cefb12e | [
"Apache-2.0"
] | null | null | null | src/CalculatorManager.cpp | feng-zhe/ZheQuant-brain-cpp | 3180b7cfcbfc4ca13831dbbbe1fa69821cefb12e | [
"Apache-2.0"
] | null | null | null | src/CalculatorManager.cpp | feng-zhe/ZheQuant-brain-cpp | 3180b7cfcbfc4ca13831dbbbe1fa69821cefb12e | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <new>
#include "MovingAverageCalculator.h"
#include "CompareCalculator.h"
#include "CalculatorManager.h"
#include "Helper.h"
using namespace std;
CalculatorManager::CalculatorManager(){}
CalculatorManager::~CalculatorManager(){}
string CalculatorManager::Calculate(const string& cmd){
const string kStr_dbg = "[CalcMgr]";
// split the cmd
vector<string> cmd_strs = Helper::split_cmd(cmd);
// find the calc type and params
string calc_type, params;
for(size_t i=0; i<cmd_strs.size()-1; ++i){
// check if it is the calc_type or params
if(cmd_strs[i]=="-p"){
params = cmd_strs[i+1];
} else if(cmd_strs[i]=="-t"){
calc_type = cmd_strs[i+1];
}
// break if we find both
if(!params.empty() && !calc_type.empty()) break;
}
// get calculators
auto vec_calc = GetAllCalcOnHeap();
// find the right calculator
Calculator* ptr_calc = NULL;
cout<< kStr_dbg <<" choosing the calculator with type " << calc_type << endl;
for(auto iter=vec_calc.begin(); iter!=vec_calc.end(); ++iter){
auto ptr_temp = *iter;
if(ptr_temp==NULL) continue;
if(ptr_temp->GetCalcType() == calc_type){
ptr_calc = ptr_temp;
cout<< kStr_dbg <<" found the calculator" << endl;
break;
}
}
string str_rst = "{}";
if( ptr_calc == NULL ){
cout<< kStr_dbg <<" no calculator found" << endl;
} else {
str_rst = ptr_calc->Calculate(params);
}
// free calculators
DeleteAllCalcOnHeap(vec_calc);
// return result
return str_rst;
}
vector<Calculator*> CalculatorManager::GetAllCalcOnHeap(){
vector<Calculator*> vec_calc;
// TODO: add other plugins
vec_calc.push_back(new (std::nothrow) MovingAverageCalculator);
vec_calc.push_back(new (std::nothrow) CompareCalculator);
// end of adding plugins
return vec_calc;
}
void CalculatorManager::DeleteAllCalcOnHeap(const vector<Calculator*> & vec_calc){
for(Calculator* ptr_calc : vec_calc){
delete ptr_calc;
}
}
| 30.328571 | 82 | 0.632595 | [
"vector"
] |
39f8ead3b5c98ecd010a690cc7b2192ad15672e6 | 4,112 | cpp | C++ | problems/atcoder/abc205/f---grid-and-tokens/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/atcoder/abc205/f---grid-and-tokens/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/atcoder/abc205/f---grid-and-tokens/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
static_assert(sizeof(int) == 4 && sizeof(long) == 8);
template <typename Flow = long, typename FlowSum = Flow>
struct tidal_flow {
struct Edge {
int node[2];
Flow cap, flow = 0;
};
int V, E = 0;
vector<vector<int>> res;
vector<Edge> edge;
explicit tidal_flow(int V) : V(V), res(V) {}
void add(int u, int v, Flow capacity, bool bothways = false) {
assert(0 <= u && u < V && 0 <= v && v < V && u != v && capacity > 0);
res[u].push_back(E++), edge.push_back({{u, v}, capacity, 0});
res[v].push_back(E++), edge.push_back({{v, u}, bothways ? capacity : 0, 0});
}
vector<int> level, edges, Q;
vector<Flow> p;
vector<FlowSum> h, l;
static constexpr FlowSum flowsuminf = numeric_limits<FlowSum>::max() / 2;
bool bfs(int s, int t) {
level.assign(V, -1);
edges.clear();
level[s] = 0;
Q[0] = s;
int i = 0, S = 1;
while (i < S && level[Q[i]] != level[t]) {
int u = Q[i++];
for (int e : res[u]) {
int v = edge[e].node[1];
if (edge[e].flow < edge[e].cap) {
if (level[v] == -1) {
level[v] = level[u] + 1;
Q[S++] = v;
}
if (level[v] == level[u] + 1) {
edges.push_back(e);
}
}
}
}
return level[t] != -1;
}
FlowSum tide(int s, int t) {
fill(begin(h), end(h), 0);
h[s] = flowsuminf;
for (int e : edges) {
auto [w, v] = edge[e].node;
p[e] = min(FlowSum(edge[e].cap - edge[e].flow), h[w]);
h[v] = h[v] + p[e];
}
if (h[t] == 0) {
return 0;
}
fill(begin(l), end(l), 0);
l[t] = h[t];
for (auto it = edges.rbegin(); it != edges.rend(); it++) {
int e = *it;
auto [w, v] = edge[e].node;
p[e] = min(FlowSum(p[e]), min(h[w] - l[w], l[v]));
l[v] -= p[e];
l[w] += p[e];
}
fill(begin(h), end(h), 0);
h[s] = l[s];
for (auto e : edges) {
auto [w, v] = edge[e].node;
p[e] = min(FlowSum(p[e]), h[w]);
h[w] -= p[e];
h[v] += p[e];
edge[e].flow += p[e];
edge[e ^ 1].flow -= p[e];
}
return h[t];
}
FlowSum maxflow(int s, int t) {
h.assign(V, 0);
l.assign(V, 0);
p.assign(E, 0);
Q.resize(V);
FlowSum max_flow = 0, df;
while (bfs(s, t)) {
do {
df = tide(s, t);
max_flow += df;
} while (df > 0);
}
return max_flow;
}
Flow get_flow(int e) const { return edge[2 * e].flow; }
bool left_of_mincut(int u) const { return level[u] >= 0; }
};
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int R, C, N;
cin >> R >> C >> N;
vector<array<int, 4>> rooks(N);
for (auto &[a, b, c, d] : rooks) {
cin >> a >> c >> b >> d;
a--, b--, c--, d--;
}
// R rows, C column, s, t, 2N internals
int s = R + C + 2 * N, t = s + 1;
tidal_flow<int> mf(R + C + 2 * N + 2);
int ROW = 0, LEFT = R, RIGHT = R + N, COL = R + 2 * N;
// s to rows
for (int r = 0; r < R; r++) {
mf.add(s, r + ROW, 1);
}
// rows to internal first
for (int i = 0; i < N; i++) {
for (int r = rooks[i][0]; r <= rooks[i][1]; r++) {
mf.add(r + ROW, i + LEFT, 1);
}
}
// link internal
for (int i = 0; i < N; i++) {
mf.add(i + LEFT, i + RIGHT, 1);
}
// internal to columns
for (int i = 0; i < N; i++) {
for (int c = rooks[i][2]; c <= rooks[i][3]; c++) {
mf.add(i + RIGHT, c + COL, 1);
}
}
// columns to t
for (int c = 0; c < C; c++) {
mf.add(c + COL, t, 1);
}
cout << mf.maxflow(s, t) << endl;
return 0;
}
| 28.555556 | 84 | 0.401265 | [
"vector"
] |
39fb567486572c62bb2db6d5d44d032e58b0f5b0 | 616 | cpp | C++ | Dataset/Leetcode/test/5/41.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/5/41.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/5/41.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
string XXX(string s) {
int len=s.size();
vector<vector<int>> dp(len,vector<int>(len));
string res;
for(int l=1;l<=len;++l)
for(int i=0;i+l-1<len;++i)
{
if(l==1)
dp[i][i+l-1]=true;
else if(l==2)
dp[i][i+l-1]=s[i]==s[i+l-1];
else
{
dp[i][i+l-1]=dp[i+1][i+l-2]&(s[i]==s[i+l-1]);
}
if(dp[i][i+l-1]==true&&l>res.size())
{
res=s.substr(i,l);
}
}
return res;
}
};
| 22.814815 | 61 | 0.345779 | [
"vector"
] |
39fbdbcd267c0e332f71154d5268e89f0a7a032e | 928 | cxx | C++ | src/external/stl_ext/test/string.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 86 | 2016-05-30T16:08:24.000Z | 2022-03-30T22:57:35.000Z | src/external/stl_ext/test/string.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 41 | 2017-02-02T22:28:17.000Z | 2022-02-22T16:51:14.000Z | src/external/stl_ext/test/string.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 26 | 2016-05-30T16:08:33.000Z | 2021-12-29T03:02:30.000Z | #include "gtest/gtest.h"
#include "iostream.hpp"
#include "string.hpp"
using namespace std;
using namespace stl_ext;
TEST(unit_string, str)
{
EXPECT_EQ("1", str(1));
EXPECT_EQ("1.45", str(1.45));
EXPECT_EQ("[1, 2, 3]", str(vector<int>{1,2,3}));
const char *cs = "hi";
string s = "hi";
EXPECT_STREQ("hi", str("hi"));
EXPECT_STREQ("hi", str(cs));
EXPECT_EQ(cs, str(cs));
EXPECT_EQ("hi", str(s));
EXPECT_EQ(&s, &str(s));
EXPECT_EQ("1 1.45 [1, 2, 3]", str("%d %g %j", 1, 1.45, vector<int>{1,2,3}));
EXPECT_EQ("hoople", translated("booths", "bhst", "hlep"));
EXPECT_EQ("BORK", toupper("Bork"));
EXPECT_EQ("bork", tolower("Bork"));
}
TEST(unit_string, translate)
{
EXPECT_EQ("hoople", translated("booths", "bhst", "hlep"));
}
TEST(unit_string, toupper)
{
EXPECT_EQ("BORK", toupper("Bork"));
}
TEST(unit_string, tolower)
{
EXPECT_EQ("bork", tolower("Bork"));
}
| 22.634146 | 80 | 0.594828 | [
"vector"
] |
2608da04997a13b778d389af21536f118bba1686 | 4,299 | cpp | C++ | src/ofxLSGRuleParametric.cpp | edap/ofxLSystemGrammar | c66d8d48f826f987fab245463b0ae61b39b35002 | [
"MIT"
] | 36 | 2016-04-02T00:40:23.000Z | 2022-01-25T10:08:39.000Z | src/ofxLSGRuleParametric.cpp | edap/ofxLSystemGrammar | c66d8d48f826f987fab245463b0ae61b39b35002 | [
"MIT"
] | null | null | null | src/ofxLSGRuleParametric.cpp | edap/ofxLSystemGrammar | c66d8d48f826f987fab245463b0ae61b39b35002 | [
"MIT"
] | 4 | 2017-02-18T17:42:12.000Z | 2021-11-12T00:42:28.000Z | #include <ofxLSGRuleParametric.h>
ofxLSGRuleParametric::ofxLSGRuleParametric(
string _predecessor,
string _conditions,
string _successor,
map<string,float> _constants){
predecessor = _predecessor;
conditions = setConditions(_conditions);
successor = setSuccessor(_successor, _constants);
predecessorParameters = getPredecessorParameters();
predecessorLetters = getPredecessorLetters();
};
vector<ofxLSGCondition> ofxLSGRuleParametric::getConditions() const{
return conditions;
}
string ofxLSGRuleParametric::getPredecessor() const{
return predecessor;
}
vector<pair<string,vector<ofxLSGOperation>>> ofxLSGRuleParametric::getSuccessor() const{
return successor;
}
vector<string> ofxLSGRuleParametric::getPredecessorParameters() const{
// it puts in a vector x,y from, for example "A(x,y)"
return ofxLSGUtils::matchesInRegex(predecessor, "[a-z]");
}
// it returns a vector containing pairs, example, having a successor
// with first element 'F(s)', it returns a pair, where 'F(s)'
// is the key, and s is in the vector value
vector<pair<string, vector<string>>> ofxLSGRuleParametric::getSuccessorWithParameters() const{
vector<pair<string, vector<string>>> result;
for(auto succ : successor){
auto params = ofxLSGUtils::matchesInRegex(succ.first, "[a-z]");
result.push_back(make_pair(succ.first, params));
}
return result;
}
vector<string> ofxLSGRuleParametric::getPredecessorLetters() const{
// it puts in a vector A,B from, for example "A(x)> B(Y)"
return ofxLSGUtils::matchesInRegex(predecessor, "[A-Z]");
}
vector<ofxLSGCondition> ofxLSGRuleParametric::setConditions(string _conditions) const{
vector<ofxLSGCondition> conditions;
auto parts = ofSplitString(_conditions, "&&");
for(auto part:parts){
conditions.push_back(ofxLSGCondition(part));
}
return conditions;
}
vector<pair<string,vector<ofxLSGOperation>>> ofxLSGRuleParametric::setSuccessor(
string _successor,
map<string,float> _constants
) const{
auto successorWithConstants = replaceConstantsInModules(_successor, _constants);
auto successorModules = ofxLSGUtils::getModulesFromString(successorWithConstants);
// grep operations
// use the grepped kye as value for the operation object
// calculate substitution if necessary. otherwise return
vector<pair<string,vector<ofxLSGOperation>>> successors;
for(auto part:successorModules){
if (part.length() == 0) continue;
auto ops = getOperationsInModule(part);
successors.push_back(make_pair(part, ops));
}
return successors;
}
string ofxLSGRuleParametric::replaceConstantsInModules(string successor, Constants _constants) const{
string result;
result = successor;
for(auto _constant : _constants){
auto key = _constant.first;
auto val = _constant.second;
ofStringReplace(result, key, ofToString(val));
}
return result;
};
//This method take a module like A(x+1), recognize that x+1 is an operation, and returns
// a vector containing the operations, (in this case only one), for that module
vector<ofxLSGOperation> ofxLSGRuleParametric::getOperationsInModule(string module) const{
vector<ofxLSGOperation> operations;
auto textInsideRounBrackets = ofxLSGUtils::matchesInRegex(module, "\\([A-Za-z0-9,\\.\\+\\*\\/-]+\\)");
for(auto stringOp:textInsideRounBrackets){
//remove the first parenthesis
stringOp = ofxLSGUtils::stripFirstAndLastChar(stringOp);
if(ofxLSGUtils::countSubstring(stringOp, "(") > 0){
ofLogError("Currently nested operation are not supported, it is not \
possible to process the string "+stringOp);
}
auto operationsString = ofSplitString(stringOp, ",");
for(auto op:operationsString){
operations.push_back(ofxLSGOperation(op));
}
}
return operations;
}
| 40.556604 | 106 | 0.655734 | [
"object",
"vector"
] |
261fcaae0ce5a22801012e8f0f8e5cf6c83a26b2 | 5,443 | cpp | C++ | src/Socket.cpp | ismart-omari/frnetlib | 11ede8c8df8390f6971ad784841efb0ef593ed54 | [
"MIT"
] | null | null | null | src/Socket.cpp | ismart-omari/frnetlib | 11ede8c8df8390f6971ad784841efb0ef593ed54 | [
"MIT"
] | null | null | null | src/Socket.cpp | ismart-omari/frnetlib | 11ede8c8df8390f6971ad784841efb0ef593ed54 | [
"MIT"
] | null | null | null | //
// Created by fred on 06/12/16.
//
#include <mutex>
#include <csignal>
#include <iostream>
#include <vector>
#ifdef USE_SSL
#include <mbedtls/error.h>
#endif
#include "frnetlib/NetworkEncoding.h"
#include "frnetlib/Socket.h"
#include "frnetlib/Sendable.h"
namespace fr
{
Socket::Socket()
: ai_family(AF_UNSPEC),
max_receive_size(0),
socket_read_timeout(0),
socket_write_timeout(0)
{
init_wsa();
}
Socket::Status Socket::send(const Sendable &obj)
{
if(!connected())
return Socket::Status::Disconnected;
return obj.send(this);
}
Socket::Status Socket::receive(Sendable &obj)
{
return obj.receive(this);
}
Socket::Status Socket::receive_all(void *dest, size_t buffer_size)
{
auto bytes_remaining = (ssize_t) buffer_size;
while(bytes_remaining > 0)
{
size_t received = 0;
Status status = receive_raw((char*)dest + (buffer_size - bytes_remaining), (size_t)bytes_remaining, received);
bytes_remaining -= received;
if(status != Socket::Status::Success)
{
if((ssize_t)buffer_size == bytes_remaining)
return status;
if(status == Socket::Status::WouldBlock)
continue;
return Socket::Status::Disconnected;
}
}
return Socket::Status::Success;
}
void Socket::shutdown()
{
::shutdown(get_socket_descriptor(), SHUT_RDWR);
}
void Socket::set_inet_version(Socket::IP version)
{
switch(version)
{
case Socket::IP::v4:
ai_family = AF_INET;
break;
case Socket::IP::v6:
ai_family = AF_INET6;
break;
case Socket::IP::any:
ai_family = AF_UNSPEC;
break;
default:
throw std::logic_error("Unknown Socket::IP value passed to set_inet_version()");
}
}
std::string Socket::status_to_string(fr::Socket::Status status)
{
#ifdef _WIN32
auto wsa_err_to_str = [](int err) -> std::string {
std::string buff(255, '\0');
auto len = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), &buff[0], buff.size(), NULL);
if(len == 0)
return "Unknown";
buff.resize(len);
return buff;
};
#define ERR_STR wsa_err_to_str(WSAGetLastError())
#else
#define ERR_STR strerror(errno)
#endif
switch(status)
{
case Socket::Status::Unknown:
return "Unknown";
case Socket::Status::Success:
return "Success";
case Socket::Status::ListenFailed:
return std::string("Listen Failed (").append(ERR_STR).append(")");
case Socket::Status::BindFailed:
return std::string("Bind Failed (").append(ERR_STR).append(")");
case Socket::Status::Disconnected:
return "The Socket Is Not Connected";
case Socket::Status::Error:
return "Error";
case Socket::Status::WouldBlock:
return "Would Block";
case Socket::Status::ConnectionFailed:
return "Connection Failed";
case Socket::Status::HandshakeFailed:
return "Handshake Failed";
case Socket::Status::VerificationFailed:
return "Verification Failed";
case Socket::Status::MaxPacketSizeExceeded:
return "Max Packet Size Exceeded";
case Socket::Status::NotEnoughData:
return "Not Enough Data";
case Socket::Status::ParseError:
return "Parse Error";
case Socket::Status::HttpHeaderTooBig:
return "HTTP Header Too Big";
case Socket::Status::HttpBodyTooBig:
return "HTTP Body Too Big";
case Socket::Status::AddressLookupFailure:
#ifdef _WIN32
return std::string("Address Lookup Failure (").append(wsa_err_to_str(WSAGetLastError())).append(")");
#else
return std::string("Address Lookup Failure (").append(gai_strerror(errno)).append(")");
#endif
case Socket::Status::SendError:
return std::string("Send Error (").append(ERR_STR).append(")");
case Socket::Status::ReceiveError:
return std::string("Receive Error (").append(ERR_STR).append(")");
case Socket::Status::AcceptError:
return std::string("Accept Error (").append(ERR_STR).append(")");
case Socket::Status::SSLError:
{
#ifdef USE_SSL
char buff[256] = {0};
// mbedtls_strerror(errno, buff, sizeof(buff));
return std::string("SSL Error (").append(buff).append(")");
#else
return "Generic SSL Error";
#endif
}
case Socket::Status::NoRouteToHost:
return "No Route To Host";
case Socket::Status::Timeout:
return "Timeout";
default:
return "Unknown";
}
return "Internal Error";
}
void Socket::disconnect()
{
close_socket();
}
} | 32.207101 | 178 | 0.552085 | [
"vector"
] |
261feb74afa9478603c36fe919cfedc78bf5ff44 | 1,885 | hpp | C++ | lib/Painless_Mesh/src/painlessmesh/tcp.hpp | ErshovVladislav10M/-Graduate-work-Bachelor- | d525dff87bfad0d42c63d2aca3b4cc57adb53584 | [
"Apache-2.0"
] | null | null | null | lib/Painless_Mesh/src/painlessmesh/tcp.hpp | ErshovVladislav10M/-Graduate-work-Bachelor- | d525dff87bfad0d42c63d2aca3b4cc57adb53584 | [
"Apache-2.0"
] | null | null | null | lib/Painless_Mesh/src/painlessmesh/tcp.hpp | ErshovVladislav10M/-Graduate-work-Bachelor- | d525dff87bfad0d42c63d2aca3b4cc57adb53584 | [
"Apache-2.0"
] | null | null | null | #ifndef _PAINLESS_MESH_TCP_HPP_
#define _PAINLESS_MESH_TCP_HPP_
#include <list>
#include "Arduino.h"
#include "painlessmesh/configuration.hpp"
#include "painlessmesh/logger.hpp"
namespace painlessmesh {
namespace tcp {
inline uint32_t encodeNodeId(const uint8_t *hwaddr) {
using namespace painlessmesh::logger;
Log(GENERAL, "encodeNodeId():\n");
uint32_t value = 0;
value |= hwaddr[2] << 24; // Big endian (aka "network order"):
value |= hwaddr[3] << 16;
value |= hwaddr[4] << 8;
value |= hwaddr[5];
return value;
}
template <class T, class M>
void initServer(AsyncServer &server, M &mesh) {
using namespace logger;
server.setNoDelay(true);
server.onClient(
[&mesh](void *arg, AsyncClient *client) {
if (mesh.semaphoreTake()) {
Log(CONNECTION, "New AP connection incoming\n");
auto conn = std::make_shared<T>(client, &mesh, false);
conn->initTasks();
mesh.subs.push_back(conn);
mesh.semaphoreGive();
}
},
NULL);
server.begin();
}
template <class T, class M>
void connect(AsyncClient &client, IPAddress ip, uint16_t port, M &mesh) {
using namespace logger;
client.onError([&mesh](void *, AsyncClient *client, int8_t err) {
if (mesh.semaphoreTake()) {
Log(CONNECTION, "tcp_err(): error trying to connect %d\n", err);
mesh.droppedConnectionCallbacks.execute(0, true);
mesh.semaphoreGive();
}
});
client.onConnect(
[&mesh](void *, AsyncClient *client) {
if (mesh.semaphoreTake()) {
Log(CONNECTION, "New STA connection incoming\n");
auto conn = std::make_shared<T>(client, &mesh, true);
conn->initTasks();
mesh.subs.push_back(conn);
mesh.semaphoreGive();
}
},
NULL);
client.connect(ip, port);
}
} // namespace tcp
} // namespace painlessmesh
#endif
| 26.180556 | 73 | 0.63183 | [
"mesh"
] |
1c7cc40b4bdaea1158ead09e7e5b983ef2c74f73 | 979 | cpp | C++ | src/nabor.cpp | cran/nabor | 4ae143e67d2ef7ed7900963370f83436ce38021f | [
"BSD-3-Clause"
] | 24 | 2016-04-03T17:31:16.000Z | 2020-12-08T08:40:56.000Z | src/nabor.cpp | cran/nabor | 4ae143e67d2ef7ed7900963370f83436ce38021f | [
"BSD-3-Clause"
] | 9 | 2015-01-28T18:10:39.000Z | 2020-09-22T00:11:31.000Z | src/nabor.cpp | cran/nabor | 4ae143e67d2ef7ed7900963370f83436ce38021f | [
"BSD-3-Clause"
] | null | null | null | #include <Rcpp.h>
#include <RcppEigen.h>
#include "nabo.h"
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppEigen)]]
using namespace Rcpp;
using namespace Nabo;
using namespace Eigen;
#include "WKNN.h"
// [[Rcpp::export]]
List knn_generic(int st, const Eigen::Map<Eigen::MatrixXd> data, const Eigen::Map<Eigen::MatrixXd> query,
const int k, const double eps, const double radius) {
// create WKNND object but don't build tree
WKNND tree = WKNND(data, false);
// establish search type
Nabo::NNSearchD::SearchType nabo_st;
if(st==1L){
// incoming st==1 implies auto, so choose according to value of k
nabo_st = k < 30 ? NNSearchD::KDTREE_LINEAR_HEAP : NNSearchD::KDTREE_TREE_HEAP;
} else {
// if we receive 2L from R => BRUTE_FORCE etc
nabo_st = static_cast<Nabo::NNSearchD::SearchType>(st-2L);
}
// build tree using appropriate search type
tree.build_tree(nabo_st);
return tree.query(query, k, eps, radius);
}
| 27.971429 | 105 | 0.678243 | [
"object"
] |
1c862ed3503c76b92035bc3d7f9855e968519ee7 | 34,489 | cpp | C++ | multiview/multiview_cpp/src/perceive/calibration/position-scene-cameras/manifest-data.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 5 | 2021-09-03T23:12:08.000Z | 2022-03-04T21:43:32.000Z | multiview/multiview_cpp/src/perceive/calibration/position-scene-cameras/manifest-data.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:57:46.000Z | 2022-02-26T05:33:02.000Z | multiview/multiview_cpp/src/perceive/calibration/position-scene-cameras/manifest-data.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 2 | 2021-09-26T03:14:40.000Z | 2022-01-26T06:42:52.000Z |
#include "manifest-data.hpp"
#include <opencv2/opencv.hpp>
#include "config.hpp"
#include "print-helper.hpp"
#include "perceive/io/lazy-s3.hpp"
#include "perceive/io/perceive-assets.hpp"
#include "perceive/optimization/breadth-first-search.hpp"
#include "perceive/utils/create-cv-remap.hpp"
#include "perceive/utils/file-system.hpp"
#define This ManifestData
namespace perceive::calibration::position_scene_cameras
{
// --------------------------------------------------------- lookup-camera-index
//
size_t This::lookup_camera_index(const string_view camera_id) const noexcept
{
auto ii
= std::find_if(cbegin(cam_infos), cend(cam_infos), [&](const auto& o) {
return o.camera_id == camera_id;
});
return (ii == cend(cam_infos))
? cam_infos.size()
: size_t(std::distance(cbegin(cam_infos), ii));
}
// ------------------------------------------------------------- lookup-position
//
size_t This::lookup_position(const string_view position_name) const noexcept
{
auto ii = ranges::find_if(positions, [&](const auto& pos_dat) {
return pos_dat.position_name == position_name;
});
return (ii == cend(positions))
? positions.size()
: size_t(ranges::distance(cbegin(positions), ii));
}
// -------------------------------------------------- lookup-cam-cam-constraints
//
vector<std::pair<int, int>> This::get_cam_cam_constraints() const noexcept
{
vector<std::pair<int, int>> o;
o.reserve(constraints.size());
std::transform(cbegin(constraints),
cend(constraints),
std::back_inserter(o),
[&](const auto ij) {
return std::make_pair(ij.first.x(), ij.first.y());
});
return o;
}
// -------------------------------------------------- calc-paths-to-ref-position
//
static vector<vector<int>> calc_paths_to_ref_position(const ManifestData& mdata)
{
const int n_cameras = mdata.n_cameras();
auto get_cam_id = [&](const int ind) -> const string& {
return mdata.cam_infos.at(size_t(ind)).camera_id;
};
auto lookup_camera_index = [&](const string_view camera_id) -> size_t {
const auto index = mdata.lookup_camera_index(camera_id);
Expects(index < mdata.cam_infos.size());
return index;
};
// Find all the neighbours for all the cameras
auto calc_all_neighbours = [&]() {
auto calc_neighbours = [&](const int u) {
const auto& cinfo = mdata.cam_infos.at(size_t(u));
vector<int> x;
for(auto pos_ind : cinfo.positions)
for(auto cdat_ind : mdata.positions.at(size_t(pos_ind)).cdats)
if(mdata.data.at(size_t(cdat_ind)).cam_index != size_t(u))
x.push_back(int(mdata.data.at(size_t(cdat_ind)).cam_index));
remove_duplicates(x);
return x;
};
vector<vector<int>> o((size_t(n_cameras)));
for(auto i = 0; i < n_cameras; ++i) o[size_t(i)] = calc_neighbours(i);
return o;
};
const vector<vector<int>> cam_neighbours = calc_all_neighbours();
// Which cameras are sink cameras?
// A sink camera is one that can see the default-position-index
auto calc_sink_cameras = [&]() {
vector<bool> o(size_t(n_cameras), false);
for(const auto& cdat : mdata.data) {
if(cdat.position_index == mdata.default_position_index)
o.at(lookup_camera_index(cdat.camera_id)) = true;
}
return o;
};
const vector<bool> sink_cameras = calc_sink_cameras();
auto is_sink = [&sink_cameras](const unsigned u) -> bool {
return sink_cameras.at(u);
};
auto for_each_neighbour
= [&cam_neighbours](const unsigned u,
std::function<void(const unsigned)> f) {
std::for_each(cbegin(cam_neighbours[u]),
cend(cam_neighbours[u]),
[&f](unsigned ind) { f(ind); });
};
auto convert_to_cdat_path = [&](const vector<unsigned>& cam_cam_path) {
vector<int> path;
auto get_cam_id = [&](const unsigned cam_index) -> const string_view {
return mdata.cam_infos.at(cam_index).camera_id;
};
auto find_cdat = [&](const string_view camera_id) {
const auto ii = std::find_if(
cbegin(mdata.data),
cend(mdata.data),
[&](const auto& cdat) -> bool {
return (cdat.camera_id == camera_id)
&& (cdat.position_index == mdata.default_position_index);
});
Expects(ii != cend(mdata.data));
return int(std::distance(cbegin(mdata.data), ii));
};
auto find_cdat_for_position_and_cam
= [&](const size_t pos_index, const size_t cam_index) -> size_t {
auto ii = ranges::find_if(mdata.data, [&](const auto& cdat) {
return cdat.cam_index == cam_index
&& cdat.position_index == pos_index;
});
return (ii == cend(mdata.data))
? mdata.data.size()
: size_t(ranges::distance(cbegin(mdata.data), ii));
};
// Convert a pair of cameras to a pair of cdat-indices
// EXCEPT for the final position
for(size_t i = 0; i + 1 < cam_cam_path.size(); ++i) {
const int cam_0 = int(cam_cam_path[i + 0]);
const int cam_1 = int(cam_cam_path[i + 1]);
size_t ind_0 = 0;
size_t ind_1 = 0;
for(size_t pindex = 0; pindex < mdata.positions.size(); ++pindex) {
ind_0 = find_cdat_for_position_and_cam(pindex, size_t(cam_0));
ind_1 = find_cdat_for_position_and_cam(pindex, size_t(cam_1));
if(ind_0 < mdata.data.size() && ind_1 < mdata.data.size()) break;
}
Expects(ind_0 < mdata.data.size() && ind_1 < mdata.data.size());
path.push_back(int(ind_0));
path.push_back(int(ind_1));
}
if(!cam_cam_path.empty()) { // get the ref view
const auto cam_id = get_cam_id(cam_cam_path.back());
const auto& info = mdata.positions.at(mdata.default_position_index);
auto ii = ranges::find_if(info.cdats, [&](int ind) {
return mdata.data.at(size_t(ind)).camera_id == cam_id;
});
Expects(ii != cend(info.cdats));
path.push_back(*ii);
}
return path;
};
auto make_path_to = [&](const int cam_ind) {
const vector<unsigned> cam_cam_path = breadth_first_search(
unsigned(cam_ind), is_sink, size_t(n_cameras), for_each_neighbour);
const auto cdat_path = convert_to_cdat_path(cam_cam_path);
if(cdat_path.size() == 0) {
LOG_ERR(
format("failed to find path to camera '{}'", get_cam_id(cam_ind)));
} else {
Expects(cdat_path.size() % 2 == 1);
}
return cdat_path;
};
vector<vector<int>> paths((size_t(n_cameras)));
for(auto i = 0; i < n_cameras; ++i) paths[size_t(i)] = make_path_to(i);
return paths;
}
// ----------------------------------------------- calc-scene-consistent-cam-ets
//
static vector<EuclideanTransform>
calc_scene_consistent_cam_ets(const ManifestData& mdata,
const string_view outdir)
{
const int n_cameras = mdata.n_cameras();
auto init_et = [&](int index) -> const EuclideanTransform& {
return mdata.data.at(size_t(index)).init_et;
};
auto calc_et = [&](const auto& cinfo) {
const vector<int>& path = cinfo.cdat_path;
if(path.size() == 0) return EuclideanTransform::nan();
EuclideanTransform e0 = {};
bool is_odd = true;
for(auto ii = rbegin(path); ii != rend(path); ++ii) {
e0 = (is_odd ? init_et(*ii) : init_et(*ii).inverse()) * e0;
is_odd = !is_odd;
}
return e0;
};
vector<EuclideanTransform> ets;
ets.resize(size_t(n_cameras));
std::transform(
cbegin(mdata.cam_infos), cend(mdata.cam_infos), begin(ets), calc_et);
return ets;
}
// ---------------------------------------------- calc-scene-consistent-cube-ets
//
static vector<EuclideanTransform>
calc_scene_consistent_cube_ets(const ManifestData& mdata,
const string_view outdir)
{
const int n_cameras = mdata.n_cameras();
const int n_positions = mdata.n_positions();
const auto cam_ets = calc_scene_consistent_cam_ets(mdata, outdir);
vector<EuclideanTransform> ets;
ets.resize(size_t(n_positions), EuclideanTransform::nan());
ranges::for_each(mdata.data, [&](const auto& cdat) {
const auto& cinfo = mdata.cam_infos.at(cdat.cam_index);
const auto& cam_et = cam_ets.at(cdat.cam_index); // cam->world
const auto& init_et = cdat.init_et;
auto& et = ets.at(cdat.position_index);
if(cinfo.cdat_path.size() > 0 && !et.is_finite())
et = (init_et.inverse() * cam_et).inverse();
});
return ets;
}
// --------------------------------------------------------- parse-manifest-file
//
ManifestData parse_manifest_file(const Config& config) noexcept(false)
{
ManifestData mdata;
ParallelJobSet pjobs;
const string_view outdir = config.outdir;
const string_view manifest_fname = config.manifest_fname;
string raw_manifest_data;
vector<vector<string>> lines;
std::atomic<bool> has_error{false};
{ // ---- Load the aruco cube
try {
if(config.cube_key.empty() and config.cube_filename.empty()) {
mdata.ac = make_kyle_aruco_cube();
print(g_info,
g_default,
format("set aruco cube to default bespoke `kyle-cube`"));
} else if(!config.cube_key.empty()) {
fetch(mdata.ac, config.cube_key);
print(g_info,
g_default,
format("loaded aruco cube `{}`", config.cube_key));
} else if(!config.cube_filename.empty()) {
read(mdata.ac, file_get_contents(config.cube_filename));
print(g_info,
g_default,
format("loaded aruco cube from file `{}`",
config.cube_filename));
} else {
FATAL("logic error");
}
} catch(std::exception& e) {
print(g_skull,
g_error,
format("failed to load the aruco cube: {}", e.what()));
has_error.store(true, std::memory_order_relaxed);
}
Expects(ArucoCube::k_n_faces == mdata.face_ims.size());
for(auto i = 0; i < ArucoCube::k_n_faces; ++i) {
auto f_ind = ArucoCube::face_e(i);
const auto face_size = 800;
mdata.face_ims[size_t(i)]
= mdata.ac.draw_face(f_ind, face_size, false, false);
if(f_ind == ArucoCube::BOTTOM) continue;
const auto fname = format(
"{}/000_{}_{}.png", outdir, i, ArucoCube::face_to_str(f_ind));
cv::imwrite(fname, mdata.ac.draw_face(f_ind, face_size, true, true));
}
}
{ // ---- Set Undistort K
const unsigned uw = 800;
const unsigned uh = 600; // Undistorted width/height
const real vfov = 75.0; // vertical field of view
mdata.undistorted_w = uw;
mdata.undistorted_h = uh;
mdata.K = Matrix3r::Identity();
mdata.K(0, 0) = mdata.K(1, 1)
= 0.5 * real(uh) / tan(0.5 * to_radians(vfov));
mdata.K(0, 2) = uw * 0.5;
mdata.K(1, 2) = uh * 0.5;
}
{ // ---- Load the raw manifest data
try {
print(g_info,
g_default,
format("loading manifest file: {}", manifest_fname));
if(is_s3_uri(manifest_fname))
s3_load(manifest_fname, raw_manifest_data);
else
raw_manifest_data = file_get_contents(manifest_fname);
} catch(std::exception& e) {
print(g_skull, g_error, format("FAILED: {}", e.what()));
return mdata;
}
}
{ // ---- Parse the manifest data into a set of fields
std::istringstream in_data(raw_manifest_data);
auto line_no = 1; // lines in failes are naturally '1'-indexed
for(string line; std::getline(in_data, line); ++line_no) {
trim(line);
if(line.empty() || line[0] == '#') continue;
auto parts = explode(line, " \t", true);
if(parts.size() != 3) {
print(
g_skull,
g_error,
format("parse error at line {}: expected 3 fields, but got {}",
line_no,
parts.size()));
has_error.store(true, std::memory_order_relaxed);
} else {
lines.push_back(std::move(parts));
}
}
}
{ // ---- Read Positions
auto read_position
= [](const string_view pos) -> std::pair<string_view, bool> {
if(pos.empty() || pos.back() != '*') return {pos, false};
return {string_view(&pos[0], pos.size() - 1), true};
};
auto lookup_position = [&](const string_view position) {
auto ret = mdata.lookup_position(position);
Expects(ret < mdata.positions.size());
return ret;
};
// Set up the positions, and the default-position-index
string_view default_position = "";
for(const auto& fields : lines) {
const auto [position, is_default] = read_position(fields[0]);
if(is_default) {
if(default_position == position) {
// all is good... it's just been selected twice or more times
} else if(default_position == ""s) {
default_position = position; // all is good... record the default
} else {
print(g_skull,
g_error,
format("attempted to set '{}' as the default position, "
"however, the default was already set to '{}'!",
position,
default_position));
has_error.store(true, std::memory_order_relaxed);
}
}
PositionInfo pos_info;
pos_info.position_name = string(cbegin(position), cend(position));
if(mdata.lookup_position(position) < mdata.positions.size()) {
// We already have this position
} else {
mdata.positions.push_back(std::move(pos_info));
}
}
// It's just nicer for output messages
// remove_duplicates(mdata.positions);
std::sort(begin(mdata.positions),
end(mdata.positions),
[&](const auto& A, const auto& B) {
return A.position_name < B.position_name;
});
// What was that default position??
if(default_position == "") {
print(g_skull,
g_error,
format("no default position was set! At least one position "
"entry must be marked with a '*' at the end. For "
"example, 'Aruco1*' would mean that the Aruco1 position "
"is the default position."));
has_error.store(true, std::memory_order_relaxed);
} else {
mdata.default_position_index = lookup_position(default_position);
print(g_info,
g_default,
format("setting default position to '{}'", default_position));
}
// Convert lines to cam-image-datas
mdata.data.reserve(lines.size());
std::transform(cbegin(lines),
cend(lines),
std::back_inserter(mdata.data),
[&](const auto& fields) -> CamImageData {
CamImageData cdat;
const auto [position, is_default]
= read_position(fields[0]);
cdat.position_index = lookup_position(position);
cdat.camera_id = fields[1];
cdat.image_fname = fields[2];
cdat.name = format(
"{}-{}",
mdata.positions[cdat.position_index].position_name,
cdat.camera_id);
return cdat;
});
}
{ // ---- Every camera-position must be unique
auto is_duplicate_position_camera
= [](const auto& cdat0, const auto& cdat1) {
return cdat0.position_index == cdat1.position_index
&& cdat0.camera_id == cdat1.camera_id;
};
auto process_duplicate = [&](const auto& cdat0, const auto& cdat1) {
print(g_skull,
g_error,
format("duplicate position-camera pair {}, for "
"images\n\t{}\n\t{}",
cdat0.name,
cdat0.image_fname,
cdat1.image_fname));
has_error.store(true, std::memory_order_relaxed);
};
for(size_t i = 1; i < mdata.data.size(); ++i)
for(size_t j = 0; j < i; ++j)
if(is_duplicate_position_camera(mdata.data[i], mdata.data[j]))
process_duplicate(mdata.data[i], mdata.data[j]);
if(has_error.load(std::memory_order_relaxed))
throw std::runtime_error("aborting due to previous errors");
}
{ // Load the images
auto construct_path
= [](const string_view ref_fname, const string_view fname) {
if(!fname.empty() && (fname[0] == '/' || is_s3_uri(fname)))
return format("{}", fname);
const auto path = format("{}/{}", dirname_sv(ref_fname), fname);
return is_s3_uri(path) ? path : absolute_path(path);
};
vector<char> raw_bytes;
ranges::for_each(mdata.data, [&](auto& cdat) {
string path = ""s;
try {
path = construct_path(manifest_fname, cdat.image_fname);
if(is_s3_uri(path)) {
lazy_load(path, raw_bytes);
} else {
file_get_contents(path, raw_bytes);
}
cdat.raw_image = decode_image_to_cv_mat(raw_bytes);
array<ARGBImage, 2> parts;
hsplit(cv_to_argb(cdat.raw_image), parts[0], parts[1]);
cdat.image = argb_to_cv(parts[0]);
print(g_tick, g_default, format("loaded '{}'", path));
} catch(std::exception& e) {
print(g_skull,
g_error,
format("failed to read image file '{}': {}", path, e.what()));
has_error.store(true, std::memory_order_relaxed);
}
});
}
auto get_unique_camera_ids = [&]() {
vector<string> camera_ids;
camera_ids.reserve(lines.size());
std::transform(cbegin(lines),
cend(lines),
std::back_inserter(camera_ids),
[&](const auto& fields) { return fields.at(1); });
remove_duplicates(camera_ids);
return camera_ids;
};
const auto camera_ids = get_unique_camera_ids();
{ // Sort `cdats` into positions
for(size_t i = 0; i < mdata.data.size(); ++i) {
const auto& cdat = mdata.data[i];
const size_t index = cdat.position_index;
Expects(index < mdata.positions.size());
mdata.positions[index].cdats.push_back(int(i));
}
}
{ // Update cdat camera indices
ranges::for_each(mdata.data, [&](auto& cdat) {
auto ii = ranges::find(camera_ids, cdat.camera_id);
Expects(ii != cend(camera_ids));
cdat.cam_index = size_t(ranges::distance(cbegin(camera_ids), ii));
});
}
{ // Initialize cam-infos
mdata.cam_infos.reserve(camera_ids.size());
std::transform(cbegin(camera_ids),
cend(camera_ids),
std::back_inserter(mdata.cam_infos),
[&](const auto cam_id) {
CamInfo cinfo;
cinfo.camera_id = cam_id;
return cinfo;
});
{ // all the positions for a given camera
ranges::for_each(mdata.data, [&](const auto& cdat) {
auto& cinfo = mdata.cam_infos.at(cdat.cam_index);
cinfo.positions.push_back(int(cdat.position_index));
});
ranges::for_each(mdata.cam_infos, [&](auto& cinfo) {
remove_duplicates(cinfo.positions);
});
}
{ // get the path for each camera
const auto paths = calc_paths_to_ref_position(mdata);
Expects(paths.size() == mdata.cam_infos.size());
for(size_t i = 0; i < paths.size(); ++i)
mdata.cam_infos.at(i).cdat_path = paths.at(i);
{ // What are those paths??
ranges::for_each(mdata.cam_infos, [&](const auto& cinfo) {
const auto path_s = format(
"Path {}: {}",
cinfo.camera_id,
rng::implode(
cinfo.cdat_path, " --> ", [&](const auto& cdat_ind) {
return format("{{{}}}",
mdata.data.at(size_t(cdat_ind)).name);
}));
print(g_info, g_default, path_s);
});
}
}
{ // set the working formats (from cdat images)
ranges::for_each(mdata.data, [&](auto& cdat) {
const int iw = cdat.image.cols;
const int ih = cdat.image.rows;
const auto cdat_fmt = Point2(iw, ih);
Point2& wfmt = mdata.cam_infos.at(cdat.cam_index).working_format;
if(wfmt == Point2{0, 0} || wfmt == cdat_fmt) {
wfmt = cdat_fmt;
} else {
has_error.store(true, std::memory_order_relaxed);
LOG_ERR(
format("camera {} had at least two different image formats!",
cdat.camera_id));
}
});
// We have a format for each camera
Expects(ranges::all_of(mdata.cam_infos, [&](const auto& x) {
return x.working_format.x > 0 && x.working_format.y > 0;
}));
}
{ // Load bcam-infos
for(size_t i = 0; i < camera_ids.size(); ++i) {
pjobs.schedule([i, &mdata, &has_error]() {
auto& cinfo = mdata.cam_infos.at(i);
const auto& cam_id = cinfo.camera_id;
auto& bcam_info = cinfo.bcam_info;
try {
const auto now_i = tick();
fetch(bcam_info, cam_id);
print(g_tick,
g_default,
format("loading camera '{}' - {:5.3f}s",
cam_id,
tock(now_i)));
} catch(std::exception& e) {
print(g_skull,
g_error,
format("failed to load camera '{}': {}",
cam_id,
e.what()));
has_error.store(true, std::memory_order_relaxed);
}
});
}
pjobs.execute();
}
{ // Fetch caching undistort inverses
ranges::for_each(mdata.cam_infos, [&pjobs](auto& cinfo) {
pjobs.schedule([&cinfo]() {
const auto& bcam_info = cinfo.bcam_info;
const auto wfmt = cinfo.working_format;
auto& cu = cinfo.cu;
const auto now_i = tick();
cu.init(bcam_info.M[0]);
cu.set_working_format(wfmt.x, wfmt.y);
print(g_tick,
g_default,
format("loading caching-undistort for {} - {:5.3f}s",
bcam_info.M[0].sensor_id(),
tock(now_i)));
});
});
pjobs.execute();
}
{ // Create undistort maps
const Matrix3r H = Matrix3r::Identity();
const auto uw = mdata.undistorted_w;
const auto uh = mdata.undistorted_h;
const bool use_fast_distort = config.use_fast_distort;
auto now = tick();
print(g_info, g_default, "calculating/loading undistort maps", false);
ranges::for_each(mdata.cam_infos, [&](auto& cinfo) {
auto& mapxys = cinfo.mapxys;
const auto& bcam_info = cinfo.bcam_info;
const auto& cu = cinfo.cu; // working format set
const auto fname = format("{}/mapxys_{}_fast={}.data",
outdir,
cinfo.camera_id,
str(use_fast_distort));
if(is_regular_file(fname)) {
cv::FileStorage file(fname, cv::FileStorage::READ);
file[format("cam_mapx")] >> mapxys[0];
file[format("cam_mapy")] >> mapxys[1];
} else {
std::function<Vector2(const Vector2&)> f
= [&](const Vector2& x) { return cu.fast_distort(x); };
std::function<Vector2(const Vector2&)> g
= [&](const Vector2& x) { return cu.distort(x); };
auto ff = use_fast_distort ? f : g;
create_cv_remap_threaded(
uw, uh, H, ff, mdata.K, mapxys[0], mapxys[1], pjobs);
cv::FileStorage file(fname, cv::FileStorage::WRITE);
file << format("cam_mapx") << mapxys[0];
file << format("cam_mapy") << mapxys[1];
}
});
cout << format(" - {:5.3f}s", tock(now)) << endl;
}
}
{ // Undistort the images
print(g_info, g_default, "undistorting images", false);
const auto now = tick();
auto f = [&](int cdat_ind) {
auto& cdat = mdata.data.at(size_t(cdat_ind));
const auto& cinfo = mdata.cam_infos.at(size_t(cdat.cam_index));
const auto& mapxys = cinfo.mapxys;
cv::remap(cdat.image,
cdat.undistorted,
mapxys[0],
mapxys[1],
cv::INTER_LINEAR,
cv::BORDER_CONSTANT,
cv::Scalar(255, 255, 255));
const auto fname
= format("{}/002_undistorted_{}.png", outdir, cdat.name);
cv::imwrite(fname, cdat.undistorted);
};
for(size_t i = 0; i < mdata.data.size(); ++i)
pjobs.schedule([&f, i]() { f(int(i)); });
pjobs.execute();
cout << format(" - {:5.3f}s", tock(now)) << endl;
}
{ // ArucoCube detections
const auto& ac = mdata.ac;
const auto& K = mdata.K;
auto process_cdat = [&](auto& cdat) {
const auto now = tick();
const auto out_fname
= format("{}/003_{}_detect.png", outdir, cdat.name);
const auto& cinfo = mdata.cam_infos.at(cdat.cam_index);
const auto& cu = cinfo.cu;
cdat.detects = ac.detect_markers(cdat.image, cu, out_fname);
{ // estimate initial et
const auto [et, success]
= estimate_init_et(ac, cdat.detects, cu, cdat.name, false);
ARGBImage argb = cv_to_argb(cdat.image);
ac.render_pointwise(argb, cdat.detects, cu, et, {});
argb.save(format("{}/008_init-et_{}.png", outdir, cdat.name));
cdat.init_et = et.inverse();
if(!success) has_error = true;
}
{ // let's try refine et
const auto [et, success]
= dense_refine_init_et(cdat.init_et.inverse(),
ac,
CachingUndistortInverse(K),
cv_to_LAB_im(cdat.undistorted),
mdata.face_ims,
cdat.detects,
cdat.name,
false);
ARGBImage argb = cv_to_argb(cdat.image);
ac.render_dense(argb, cdat.detects, mdata.face_ims, cu, et, {});
argb.save(format("{}/009_dense-et_{}.png", outdir, cdat.name));
cdat.init_et = et.inverse();
if(!success) has_error = true;
}
const auto err_fn = ac.pointwise_error_fun(cu, cdat.detects);
const auto err0 = err_fn(cdat.init_et.inverse());
{
auto redistort = [&](const Vector2& D) -> Vector2 {
Vector3r N = to_vec3r(homgen_R2_to_P2(cinfo.cu.undistort(D)));
return homgen_P2_to_R2(to_vec3(K * N));
};
auto distorted_quad_to_undistorted
= [&](const array<Vector2, 4>& Q) {
array<Vector2, 4> O;
for(auto&& [q, o] : views::zip(Q, O)) o = redistort(q);
return O;
};
ARGBImage argb = cv_to_argb(cdat.undistorted);
ranges::for_each(cdat.detects, [&](const auto& detect) {
const auto& face = ac.measures.at(size_t(detect.f_ind));
const auto k = face.kolour;
for(const auto& quad : detect.quads)
render_quad_2d(argb, distorted_quad_to_undistorted(quad), k);
});
argb.save(out_fname);
}
const bool success = cdat.detects.size() >= 2;
if(success) {
print(g_info,
g_default,
format("detected {} markers on {}, err = {:5.3f} - {:5.3f}s",
cdat.detects.size(),
cdat.name,
err0,
tock(now)));
} else {
print(
g_skull,
g_error,
format("failed to detected 2 or more markers on {} - {:5.3f}s",
cdat.name,
tock(now)));
has_error.store(true, std::memory_order_relaxed);
}
};
ranges::for_each(mdata.data, [&](auto& cdat) {
pjobs.schedule([&cdat, &process_cdat]() { process_cdat(cdat); });
});
pjobs.execute();
}
{ // get scene-consistent initial estimate for camera position
const auto ets = calc_scene_consistent_cam_ets(mdata, outdir);
Expects(ets.size() == mdata.cam_infos.size());
for(size_t i = 0; i < ets.size(); ++i)
mdata.cam_infos.at(i).init_et = ets.at(i);
}
{ // Scene-consistent Aruco-cube positions
const auto ets = calc_scene_consistent_cube_ets(mdata, outdir);
Expects(ets.size() == mdata.positions.size());
for(size_t i = 0; i < ets.size(); ++i)
mdata.positions.at(i).init_et = ets.at(i);
}
{ // Create constraint graph
auto now = tick();
print(g_info,
g_default,
format("finding camera-camera constraints", tock(now)));
auto lookup_camera = [&](const auto& cam_id) {
auto ii = ranges::find(camera_ids, cam_id);
Expects(ii != cend(camera_ids));
return ranges::distance(cbegin(camera_ids), ii);
};
auto is_pos_fun = [&](size_t pos_ind) {
return [pos_ind](const auto& cdat) {
return cdat.position_index == pos_ind;
};
};
auto get_cdat_index
= [&](const auto& cdat) { return int(&cdat - &mdata.data[0]); };
auto find_it = [&](const size_t pos_ind) {
auto rng = mdata.data | views::filter(is_pos_fun(pos_ind))
| views::transform(get_cdat_index);
vector<int> cdat_inds(begin(rng), end(rng));
for(size_t i = 0; i < cdat_inds.size(); ++i) {
for(size_t j = i + 1; j < cdat_inds.size(); ++j) {
OrderedPair key(
int(lookup_camera(
mdata.data[size_t(cdat_inds[i])].camera_id)),
int(lookup_camera(
mdata.data[size_t(cdat_inds[j])].camera_id)));
auto ii = mdata.constraints.find(key);
if(ii == cend(mdata.constraints)) {
vector<int> indices = {cdat_inds[i], cdat_inds[j]};
CamCamConstraints cc = {key, std::move(indices)};
mdata.constraints.insert(std::make_pair(cc.cam_indices, cc));
} else {
ii->second.cam_image_indices.push_back(cdat_inds[i]);
ii->second.cam_image_indices.push_back(cdat_inds[j]);
}
}
}
};
for(size_t ind = 0; ind < mdata.positions.size(); ++ind) { find_it(ind); }
// Print the output
for(const auto& [key, cc] : mdata.constraints) {
vector<string> poses;
std::transform(cbegin(cc.cam_image_indices),
cend(cc.cam_image_indices),
std::back_inserter(poses),
[&](const int ind) {
return mdata.positions
.at(mdata.data.at(size_t(ind)).position_index)
.position_name;
});
remove_duplicates(poses);
print(g_tick,
g_default,
format("{}-{}: ['{}']",
camera_ids[size_t(key.x())],
camera_ids[size_t(key.y())],
rng::implode(poses, "', '")));
}
print(g_info, g_default, format("done - {:5.3f}s", tock(now)));
}
if(has_error.load(std::memory_order_relaxed)) {
throw std::runtime_error("aborting due to previous errors");
}
{ // Some trailing INFO lines
print(g_info, g_default, "successfully loaded manifest data");
}
return mdata;
}
void cdat_fn_test(const ManifestData& mdata)
{
auto test_cdat = [&](const auto& cdat) {
const auto& cu = mdata.cam_infos.at(cdat.cam_index).cu;
const auto err_fn = mdata.ac.pointwise_error_fun(cu, cdat.detects);
const auto err0 = err_fn(cdat.init_et.inverse());
return err0;
};
ranges::for_each(mdata.data, [&](const auto& cdat) {
INFO(format("{} --> {}", cdat.name, test_cdat(cdat)));
});
}
} // namespace perceive::calibration::position_scene_cameras
| 37.610687 | 80 | 0.520253 | [
"vector",
"transform"
] |
1c8d22cc70768b20e1da63717dc2edb4aade83d9 | 3,477 | cpp | C++ | src/kittireader.cpp | jhultman/continuous-fusion | 1df1cc1488965fd5f101d66d1ca916a430d1dfd6 | [
"MIT"
] | 25 | 2019-06-19T11:55:53.000Z | 2022-02-28T07:56:38.000Z | src/kittireader.cpp | jhultman/continuous-fusion | 1df1cc1488965fd5f101d66d1ca916a430d1dfd6 | [
"MIT"
] | 1 | 2020-11-17T06:46:26.000Z | 2021-11-04T11:49:38.000Z | src/kittireader.cpp | jhultman/continuous-fusion | 1df1cc1488965fd5f101d66d1ca916a430d1dfd6 | [
"MIT"
] | 4 | 2020-07-16T01:59:47.000Z | 2022-02-28T06:41:14.000Z | #include "kittireader.hpp"
#include "calibration.hpp"
#include <vector>
#include <opencv2/opencv.hpp>
#include "pcl_ros/point_cloud.h"
KittiReader::KittiReader(std::string basedir)
{
auto calib = makeCalib(basedir);
auto PRT = calib.getVeloToImage();
}
std::vector<cv::String> KittiReader::globFilesHelper(std::string pattern)
{
std::vector<cv::String> fpaths;
cv::glob(pattern, fpaths, false);
return fpaths;
}
std::vector<cv::Mat> KittiReader::getImages(std::vector<cv::String> fpaths)
{
std::vector<cv::Mat> images;
for(auto const& fpath : fpaths)
{
auto image = cv::imread(fpath, CV_LOAD_IMAGE_COLOR);
images.push_back(image);
}
return images;
}
pcl::PointXYZI PointXYZI_(cv::Vec4f fields)
{
pcl::PointXYZI pt;
pt.x = fields[0];
pt.y = fields[1];
pt.z = fields[2];
pt.intensity = fields[3];
return pt;
}
pcl::PointCloud<pcl::PointXYZI> KittiReader::getPointcloud(cv::String fpath)
{
// Points outside approximate camera viewing frustum filtered.
std::ifstream ifs(fpath.c_str(), std::ios::in | std::ios::binary);
pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);
cloud->is_dense = false;
cv::Vec4f point;
while(ifs.good())
{
ifs.read((char *) &point, 4*sizeof(float));
if (
(point[0] > 0) &
(abs(point[0]) > abs(point[1])) &
(point[0] > 0) &
(point[0] < 48) &
(point[1] > -24) &
(point[1] < 24))
{
cloud->push_back(PointXYZI_(point));
}
}
return *cloud;
}
std::vector<pcl::PointCloud<pcl::PointXYZI>> KittiReader::getPointclouds(std::vector<cv::String> fpaths)
{
pcl::PointCloud<pcl::PointXYZI> cloud;
std::vector<pcl::PointCloud<pcl::PointXYZI>> clouds;
for(auto const& fpath : fpaths)
{
cloud = getPointcloud(fpath);
clouds.push_back(cloud);
}
return clouds;
}
std::vector<float> KittiReader::splitLineByChar(std::string line, char delim)
{
std::string val;
std::vector<float> vals;
std::istringstream iss(line);
while(std::getline(iss, val, delim))
{
vals.push_back(atof(val.c_str()));
}
return vals;
}
void KittiReader::loadImagesAndPoints(std::string basedir)
{
std::string patternImages = basedir +
"2011_09_26_drive_0005_sync/image_02/data/*.png";
std::string patternPoints = basedir +
"2011_09_26_drive_0005_sync/velodyne_points/data/*.bin";
auto imageFpaths = globFilesHelper(patternImages);
auto pointcloudFpaths = globFilesHelper(patternPoints);
auto images = getImages(imageFpaths);
auto points = getPointclouds(pointcloudFpaths);
return;
}
std::map<std::string, std::vector<float>> KittiReader::getCalib(cv::String fpath)
{
std::map<std::string, std::vector<float>> calib;
std::ifstream ifs(fpath.c_str());
std::string key, line;
while(ifs.good())
{
std::getline(ifs, key, ':');
ifs.ignore(1, ' ');
std::getline(ifs, line, '\n');
auto val = splitLineByChar(line, ' ');
calib.insert(std::make_pair(key, val));
}
return calib;
}
Calibration KittiReader::makeCalib(cv::String basedir)
{
auto veloToCam = getCalib(basedir + "calib_velo_to_cam.txt");
auto camToCam = getCalib(basedir + "calib_cam_to_cam.txt");
auto calib = Calibration(veloToCam, camToCam);
return calib;
}
| 27.816 | 104 | 0.630141 | [
"vector"
] |
1c93fdc91e06715e0b50df4adf25285f0851fb71 | 5,057 | cc | C++ | Top Favorite Songs/solution 1/main.cc | kishoredbn/Object-Oriented-Pros | fc69eaeda90776b7e72a39c4f32229cb4fb8729d | [
"MIT"
] | null | null | null | Top Favorite Songs/solution 1/main.cc | kishoredbn/Object-Oriented-Pros | fc69eaeda90776b7e72a39c4f32229cb4fb8729d | [
"MIT"
] | null | null | null | Top Favorite Songs/solution 1/main.cc | kishoredbn/Object-Oriented-Pros | fc69eaeda90776b7e72a39c4f32229cb4fb8729d | [
"MIT"
] | 1 | 2021-03-11T15:40:07.000Z | 2021-03-11T15:40:07.000Z | #include "common.h"
int main()
{
CSimpleMusicManager manager;
// all songs in the store
vvMusicAttribute vsongs = {
{{music::author, {"AR Rehman"}}, {music::name, {"Pray for me Brother"}}, {music::release, {2005}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Mast magan"}}, {music::release, {2019}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Hindustani"}}, {music::release, {2000}}},
{{music::author, {"Rashid Ali"}}, {music::name, {"Nazarlayena"}}, {music::release, {2010}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Jai Ho"}}, {music::release, {2002}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Laal Isqh"}}, {music::release, {2017}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Humse Muqabla"}}, {music::release, {2010}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Kabhi Jo Badal barse"}}, {music::release, {2012}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Chaiya Chiya"}}, {music::release, {1998}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Tum hi ho"}}, {music::release, {2015}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Satrangi rey"}}, {music::release, {1999}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Chana mereya"}}, {music::release, {2012}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Radha kaisey na Jale"}}, {music::release, {2003}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Orey chori"}}, {music::release, {2001}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Raabta"}}, {music::release, {2014}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Dreams on Fire"}}, {music::release, {2012}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Geruya"}}, {music::release, {2006}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Taal sey Taal"}}, {music::release, {2005}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Nahi Samney"}}, {music::release, {2002}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Osana"}}, {music::release, {2010}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Take it easy Urvasi"}}, {music::release, {2013}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Khamoshiya"}}, {music::release, {2011}}},
{{music::author, {"Jubin Nautiyal"}}, {music::name, {"Zindagi Kuch Toh Bata"}}, {music::release, {2018}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Agar Tum Sathe ho"}}, {music::release, {2017}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Gopala Gopala"}}, {music::release, {2002}}},
{{music::author, {"Arijit Singh"}}, {music::name, {"Tujhe Kinta Chahey aur hum"}}, {music::release, {2019}}},
{{music::author, {"Jubin Nautiyal"}}, {music::name, {"Tujhe Kinta Chahey aur hum"}}, {music::release, {2019}}},
{{music::author, {"Rashid Ali"}}, {music::name, {"Kabhi Kabhi Aditi"}}, {music::release, {2004}}},
{{music::author, {"AR Rehman"}}, {music::name, {"Dil se"}}, {music::release, {2008}}}
};
manager.AddSongs(vsongs);
// add songs in the playlist, based on vector of search attributes
vvMusicAttribute vsongs_playlist = {
{{music::author, {"Rashid Ali"}}},
{{music::author, {"Jubin Nautiyal"}}}
};
manager.AddToPlayList(vsongs_playlist);
manager.GetTopSongs(); // Get top 10 fequently played song.
// add songs in the playlist, based on vector of search attributes
vvMusicAttribute vsongs_playlist1 = {
{{music::author, {"Arijit Singh"}}}
};
manager.AddToPlayList(vsongs_playlist1);
manager.GetTopSongs(); // Get top 10 fequently played song.
// add songs in the playlist, based on vector of search attributes
vvMusicAttribute vsongs_playlist2 = {
{{music::name, {"Tujhe Kinta Chahey aur hum"}}}
};
manager.AddToPlayList(vsongs_playlist2);
manager.GetTopSongs(); // Get top 10 fequently played song.
// add songs in the playlist, based on vector of search attributes
vvMusicAttribute vsongs_playlist3 = {
{{music::release, {2012}}}
};
manager.AddToPlayList(vsongs_playlist3);
manager.GetTopSongs(); // Get top 10 fequently played song.
return 0;
}
| 67.426667 | 135 | 0.50267 | [
"vector"
] |
1c9553a1e75e3224301cb2ab85c820f0e82c1396 | 4,176 | cpp | C++ | Source/SystemQOR/MSWindows/WinQL/COM/Server/MMC/WinQLExtendPropertySheetImpl.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/SystemQOR/MSWindows/WinQL/COM/Server/MMC/WinQLExtendPropertySheetImpl.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/SystemQOR/MSWindows/WinQL/COM/Server/MMC/WinQLExtendPropertySheetImpl.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //WinQLExtendPropertySheetImpl.cpp
// Copyright Querysoft Limited 2013, 2015, 2017
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//Base class implementation for MMC snapin ExtendPropertySheetImpl
#include "WinQL/CodeServices/WinQLPolicy.h"
#include "WinQL/Application/Threading/WinQLCriticalSection.h"
#include "WinQL/Application/ErrorSystem/WinQLError.h"
#include "WinQL/COM/Server/MMC/WinQLExtendPropertySheetImpl.h"
#include "WinQAPI/OLE32.h"
//--------------------------------------------------------------------------------
namespace nsWin32
{
using namespace nsWinQAPI;
__QOR_IMPLEMENT_COMCLASS_ID( CExtendPropertySheetImpl, IExtendPropertySheet );
//--------------------------------------------------------------------------------
CExtendPropertySheetImpl::CExtendPropertySheetImpl( CIUnknownImplBase<>* pImpl ) : CInterfaceImplBase< IExtendPropertySheet >( pImpl )
{
_WINQ_FCONTEXT( "CExtendPropertySheetImpl::CExtendPropertySheetImpl" );
RegisterInterface( dynamic_cast< IExtendPropertySheet* >( this ) );
}
//--------------------------------------------------------------------------------
CExtendPropertySheetImpl::~CExtendPropertySheetImpl()
{
_WINQ_FCONTEXT( "CExtendPropertySheetImpl::~CExtendPropertySheetImpl" );
}
//--------------------------------------------------------------------------------
long CExtendPropertySheetImpl::CreatePropertyPages( IPropertySheetCallback* lpProvider, Cmp_long_ptr handle, IDataObject* lpIDataObject )
{
_WINQ_FCONTEXT( "CExtendPropertySheetImpl::CreatePropertyPages" );
return E_NOTIMPL;
}
//--------------------------------------------------------------------------------
long CExtendPropertySheetImpl::QueryPagesFor( IDataObject* lpDataObject )
{
_WINQ_FCONTEXT( "CExtendPropertySheetImpl::QueryPagesFor" );
return E_NOTIMPL;
}
__QOR_IMPLEMENT_COMCLASS_ID( CExtendPropertySheet2Impl, IExtendPropertySheet2 );
//--------------------------------------------------------------------------------
CExtendPropertySheet2Impl::CExtendPropertySheet2Impl( CIUnknownImplBase<>* pImpl ) : CInterfaceImplBase< IExtendPropertySheet2, CExtendPropertySheetImpl >( pImpl )
{
_WINQ_FCONTEXT( "CExtendPropertySheet2Impl::CExtendPropertySheet2Impl" );
RegisterInterface( dynamic_cast< IExtendPropertySheet2* >( this ) );
}
//--------------------------------------------------------------------------------
CExtendPropertySheet2Impl::~CExtendPropertySheet2Impl()
{
_WINQ_FCONTEXT( "CExtendPropertySheet2Impl::~CExtendPropertySheet2Impl" );
}
//--------------------------------------------------------------------------------
long CExtendPropertySheet2Impl::GetWatermarks( IDataObject* lpIDataObject, void** lphWatermark, void** lphHeader, void** lphPalette, int* bStretch)
{
_WINQ_FCONTEXT( "CExtendPropertySheet2Impl::GetWatermarks" );
return E_NOTIMPL;
}
}//nsWin32
| 44.425532 | 164 | 0.665948 | [
"object"
] |
1ca116fd9b94a0ac63fcf8761537be4ecd559478 | 428 | cpp | C++ | components/xtl/tests/stl/ptrbinf2.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/xtl/tests/stl/ptrbinf2.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/xtl/tests/stl/ptrbinf2.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include <stl/algorithm>
#include <stl/functional>
#include <stdio.h>
using namespace stl;
inline int sum (int x,int y) { return x + y; }
int main ()
{
printf ("Results of ptrbinf2_test:\n");
int input1 [4] = {7,2,3,5}, input2 [4] = {1,5,5,8}, output [4];
transform ((int*)input1,(int*)input1+4,(int*)input2,(int*)output,ptr_fun (sum));
for (int i=0;i<4;i++)
printf ("%d\n",output [i]);
return 0;
}
| 19.454545 | 82 | 0.593458 | [
"transform"
] |
1caddd824509aa4f7ec4fa821023096c72ea6ed8 | 655 | cpp | C++ | boboleetcode/Play-Leetcode-master/1207-Unique-Number-of-Occurrences/cpp-1207/main.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/1207-Unique-Number-of-Occurrences/cpp-1207/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/1207-Unique-Number-of-Occurrences/cpp-1207/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/unique-number-of-occurrences/
/// Author : liuyubobobo
/// Time : 2019-09-28
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Using HashMap
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
unordered_map<int, int> freq;
for(int e: arr) freq[e] ++;
unordered_map<int, int> res;
for(const pair<int, int>& p: freq)
if(res.count(p.second)) return false;
else res[p.second] ++;
return true;
}
};
int main() {
return 0;
} | 19.264706 | 72 | 0.603053 | [
"vector"
] |
1cae6bf8cb99f6cf2549074f21ef4ec57c1b8204 | 22,234 | cc | C++ | src/store/strongstore/tests/waitdie-test.cc | princeton-sns/spanner-rss | 6d7bf5ee6487772cd4f93e8458b5f22ae775974a | [
"MIT"
] | 1 | 2021-11-24T01:38:28.000Z | 2021-11-24T01:38:28.000Z | src/store/strongstore/tests/waitdie-test.cc | princeton-sns/spanner-rss | 6d7bf5ee6487772cd4f93e8458b5f22ae775974a | [
"MIT"
] | null | null | null | src/store/strongstore/tests/waitdie-test.cc | princeton-sns/spanner-rss | 6d7bf5ee6487772cd4f93e8458b5f22ae775974a | [
"MIT"
] | null | null | null | #include "store/strongstore/waitdie.h"
#include <gtest/gtest.h>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "store/common/timestamp.h"
namespace strongstore {
TEST(WaitDie, BasicReadLock) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp());
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, BasicWriteLock) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp());
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, BasicReadWriteLock) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp());
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 1, Timestamp());
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiReadLock) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp());
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForRead("lock", 2, Timestamp());
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForRead("lock", 3, Timestamp());
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiWriteLockWait) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiWriteLockDie) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(0));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_FAIL);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiReadWriteLockWait) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForRead("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiReadWriteLockDie) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp(0));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForRead("lock", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_FAIL);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
notify_rws.clear();
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MergeReadWriteWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiReadWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(3));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(2));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 3, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 2);
ASSERT_EQ(notify_rws.count(2), 1);
ASSERT_EQ(notify_rws.count(3), 1);
notify_rws.clear();
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForRead("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiReadWaiterRelease1) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(3));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(2));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 3, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForRead("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MultiReadWaiterRelease2) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(3));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(2));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 3, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForRead("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MergeMultiReadWriteWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(3));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(2));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 3, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 3, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(3), 1);
notify_rws.clear();
wd.ReleaseForRead("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, MergeWriteReadWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, ReleaseReadWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, ReleaseWriteWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, ReleaseMultiWriteWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp(2));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 3, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(3), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, ReleaseReadWriteWaiter1) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, ReleaseReadWriteWaiter2) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, ReleaseReadWriteWaiter3) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForWrite("lock", 1, Timestamp(1));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForRead("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
status = wd.LockForWrite("lock", 2, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForWrite("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForRead("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, Release2WriteWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp(2));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
status = wd.LockForWrite("lock", 3, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(3), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, Release2WriteReadWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp(3));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 2, Timestamp(2));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 3, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForWrite("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
status = wd.LockForRead("lock", 4, Timestamp(0));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(4), 1);
notify_rws.clear();
wd.ReleaseForRead("lock", 4, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, ReleaseWriteReadWaiter) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock", 1, Timestamp(2));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForWrite("lock", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
status = wd.LockForRead("lock", 3, Timestamp(0));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), LOCKED_FOR_READ);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForRead("lock", 3, notify_rws);
ASSERT_EQ(wd.GetLockState("lock"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
TEST(WaitDie, WaitTwoLocks) {
WaitDie wd;
std::unordered_set<uint64_t> notify_rws;
int status = wd.LockForRead("lock1", 1, Timestamp(2));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock1"), LOCKED_FOR_READ);
status = wd.LockForRead("lock2", 1, Timestamp(2));
ASSERT_EQ(status, REPLY_OK);
ASSERT_EQ(wd.GetLockState("lock2"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock1", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock1"), LOCKED_FOR_READ);
status = wd.LockForWrite("lock2", 2, Timestamp(1));
ASSERT_EQ(status, REPLY_WAIT);
ASSERT_EQ(wd.GetLockState("lock2"), LOCKED_FOR_READ);
wd.ReleaseForRead("lock1", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock1"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForRead("lock2", 1, notify_rws);
ASSERT_EQ(wd.GetLockState("lock2"), LOCKED_FOR_WRITE);
ASSERT_EQ(notify_rws.size(), 1);
ASSERT_EQ(notify_rws.count(2), 1);
notify_rws.clear();
wd.ReleaseForWrite("lock1", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock1"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
wd.ReleaseForWrite("lock2", 2, notify_rws);
ASSERT_EQ(wd.GetLockState("lock2"), UNLOCKED);
ASSERT_EQ(notify_rws.size(), 0);
}
}; // namespace strongstore
| 29.566489 | 62 | 0.687955 | [
"vector"
] |
1cbfd5222edf012e02a97aba1dda06aec64c7d31 | 1,368 | cpp | C++ | UICPC/21/nwerc2020all/jointexcavation/submissions/accepted/bjarki.cpp | MilladMuhammadi/Competitive-Programming | 9f84a2d2734a5efe0e1fde0062e51782cd5af2c6 | [
"MIT"
] | null | null | null | UICPC/21/nwerc2020all/jointexcavation/submissions/accepted/bjarki.cpp | MilladMuhammadi/Competitive-Programming | 9f84a2d2734a5efe0e1fde0062e51782cd5af2c6 | [
"MIT"
] | null | null | null | UICPC/21/nwerc2020all/jointexcavation/submissions/accepted/bjarki.cpp | MilladMuhammadi/Competitive-Programming | 9f84a2d2734a5efe0e1fde0062e51782cd5af2c6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for (auto i=(a); i<(b); ++i)
#define iter(it,c) for (auto it = (c).begin(); it != (c).end(); ++it)
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vi> vvi;
typedef long long ll;
const int INF = 2147483647;
vi adj[1000100];
int color[1000100];
vi path;
int a = 0, b = 0;
int n;
void check() {
int c = n - a - b;
if (a == c) {
cout << b << " " << a << endl;
iter(it,path) {
cout << *it+1 << " ";
}
cout << endl;
rep(i,0,n) {
if (color[i] == 0) {
cout << i+1 << " ";
}
}
cout << endl;
rep(i,0,n) {
if (color[i] == 2) {
cout << i+1 << " ";
}
}
cout << endl;
}
}
void dfs(int v) {
if (color[v] != 0) {
return;
}
path.push_back(v);
color[v] = 1;
b++;
check();
iter(it,adj[v]) {
dfs(*it);
}
color[v] = 2;
b--;
a++;
path.pop_back();
check();
}
int main() {
memset(color, 0, sizeof(color));
int m;
cin >> n >> m;
rep(i,0,m) {
int a, b;
cin >> a >> b;
a--, b--;
adj[a].push_back(b);
adj[b].push_back(a);
}
check();
dfs(0);
return 0;
}
| 16.682927 | 69 | 0.406433 | [
"vector"
] |
1ccd67e770c3168dad834a3c2f45c804acb8b6e4 | 4,595 | cpp | C++ | deprecated/perception/navigator_vision/exFAST_SparseStereo/src/sparsestereo/stereorectification.cpp | jaxnb/NaviGator | 2edb85cf5eab38f62132b3f467814516d2bb05f3 | [
"MIT"
] | 27 | 2020-02-17T21:54:09.000Z | 2022-03-18T17:49:23.000Z | deprecated/perception/navigator_vision/exFAST_SparseStereo/src/sparsestereo/stereorectification.cpp | jaxnb/NaviGator | 2edb85cf5eab38f62132b3f467814516d2bb05f3 | [
"MIT"
] | 325 | 2019-09-11T14:13:56.000Z | 2022-03-31T00:38:30.000Z | deprecated/perception/navigator_vision/exFAST_SparseStereo/src/sparsestereo/stereorectification.cpp | ericgorday/NaviGator | cc929a8609d7a416d0b8c9a95059e296f669464a | [
"MIT"
] | 24 | 2019-09-16T00:29:45.000Z | 2022-03-06T10:56:38.000Z | /*
* Author: Konstantin Schauwecker
* Year: 2012
*/
#include "stereorectification.h"
#include <cstring>
#include <climits>
namespace sparsestereo {
using namespace std;
using namespace cv;
using namespace boost;
scoped_array<float> Epiline::dummyLine;
int Epiline::dummyLineLength = -1;
void Epiline::setMaxEpilineLength(int len) {
if(dummyLineLength != len) {
dummyLine.reset(new float[len]);
memset(dummyLine.get(), 0, sizeof(float)*len);
dummyLineLength = len;
}
}
StereoRectification::StereoRectification(const CalibrationResult& calibRes, Interpolation interpolation)
: interpolation(interpolation), calibRes(calibRes)
{
initImageRectMap();
initPointRectMap();
initEpilines();
}
void StereoRectification::initImageRectMap() {
// Create rectification maps for image rectification
initUndistortRectifyMap(calibRes.cameraMatrix[0], calibRes.distCoeffs[0], calibRes.R[0],
calibRes.P[0], calibRes.imageSize, CV_16SC2, imageRectMap[0][0], imageRectMap[0][1]);
initUndistortRectifyMap(calibRes.cameraMatrix[1], calibRes.distCoeffs[1], calibRes.R[1],
calibRes.P[1], calibRes.imageSize, CV_16SC2, imageRectMap[1][0], imageRectMap[1][1]);
}
void StereoRectification::initPointRectMap() {
// Create rectification maps for integer point rectification
// Collect all image point coordinates
vector<Point2f> distortedPoints((calibRes.imageSize.width + 1) * (calibRes.imageSize.height + 1));
for(int y=0; y<=calibRes.imageSize.height; y++)
for(int x=0; x<=calibRes.imageSize.width; x++)
distortedPoints[y * (calibRes.imageSize.width + 1) + x]/*, 0)*/ = Point2f(x, y);
for(int i=0; i<2; i++) {
// Perform rectification
vector<Point2f> undistortedPoints(distortedPoints.size());
undistortPoints(distortedPoints, undistortedPoints, calibRes.cameraMatrix[i], calibRes.distCoeffs[i],
calibRes.R[i], calibRes.P[i]);
// Store results
pointRectMap[i] = Mat_<Point2f>(calibRes.imageSize.height + 1, calibRes.imageSize.width + 1, Point2f(-1, -1));
for(int y=0; y<= calibRes.imageSize.height; y++)
for(int x=0; x<= calibRes.imageSize.width; x++)
pointRectMap[i](y,x) = undistortedPoints[y * (calibRes.imageSize.width + 1) + x];//, 0);
}
}
void StereoRectification::initEpilines() {
for(int i=0; i<2; i++) {
epilines[i] = Mat_<float>(calibRes.imageSize, -1e6);
// First calculate a float undistortion map
Mat_<float> rectMap[2];
initUndistortRectifyMap(calibRes.cameraMatrix[i], calibRes.distCoeffs[i], calibRes.R[i],
calibRes.P[i], calibRes.imageSize, CV_32F, rectMap[0], rectMap[1]);
//Calculate epilines
for(int y=0; y < calibRes.imageSize.height; y++) {
for(int x=0; x<calibRes.imageSize.width - 1; x++) {
// Linearly interpolate between each entry in the undistortion map
double dx = rectMap[0](y, x + 1) - rectMap[0](y, x);
double dy = rectMap[1](y, x + 1) - rectMap[1](y, x);
for(int imgX = (int)round(rectMap[0](y, x)); imgX <= (int)round(rectMap[0](y, x+1)); imgX++) {
if(imgX >=0 && imgX < calibRes.imageSize.width) {
double interpolated = rectMap[1](y, x) + dy / dx * (imgX - rectMap[0](y, x));
if(interpolated >= 0 && interpolated < calibRes.imageSize.height) {
epilines[i](y, imgX) = interpolated;
}
}
}
}
}
// Fill epilines index
epilineIndex[i] = Mat_<int>(calibRes.imageSize, -1);
for(int line = 0; line < calibRes.imageSize.height - 1; line++)
for(int x=0; x<calibRes.imageSize.width; x++) {
for(int imgY = max(0, int(epilines[i](line, x)+0.5)); imgY <= min(calibRes.imageSize.height-1, (int)round(epilines[i](line+1, x))); imgY++)
if(imgY >=0 && imgY < calibRes.imageSize.height) {
if(fabs(imgY - epilines[i](line, x)) < fabs(imgY - epilines[i](line+1, x)))
epilineIndex[i](imgY, x) = line;
else epilineIndex[i](imgY, x) = line + 1;
}
}
}
}
Point2f StereoRectification::highPrecisionRectifyLeftPoint(Point2f inLeft) const {
Mat_<Point2f> inLeftPoint(1, 1, inLeft);
vector<Point2f> outLeftPoint;
undistortPoints(inLeftPoint, outLeftPoint, calibRes.cameraMatrix[0], calibRes.distCoeffs[0],
calibRes.R[0], calibRes.P[0]);
return outLeftPoint[0];
}
Point2f StereoRectification::highPrecisionRectifyRightPoint(Point2f inRight) const {
Mat_<Point2f> inRightPoint(1, 1, inRight);
vector<Point2f> outRightPoint;
undistortPoints(inRightPoint, outRightPoint, calibRes.cameraMatrix[1], calibRes.distCoeffs[1],
calibRes.R[1], calibRes.P[1]);
return outRightPoint[0];
}
}
| 37.663934 | 144 | 0.677911 | [
"vector"
] |
1cd0acedf383e20622302e3f03600fb5af72b42b | 4,282 | cpp | C++ | lib/book.cpp | Bronek/smatch | 5195480b8f2a63ac1c26b4fe813eef62aed339c3 | [
"MIT"
] | null | null | null | lib/book.cpp | Bronek/smatch | 5195480b8f2a63ac1c26b4fe813eef62aed339c3 | [
"MIT"
] | null | null | null | lib/book.cpp | Bronek/smatch | 5195480b8f2a63ac1c26b4fe813eef62aed339c3 | [
"MIT"
] | null | null | null | #include "book.hpp"
#include <algorithm>
namespace smatch {
namespace {
// Special value for Order.match, set at the end of Book::insert(). 0 is not good because the
// purpose of Order.match is to identify index of Match in vector passed to Book::match(), and
// of course first match added to this collection will have index 0
static constexpr size_t unmatched = std::numeric_limits<size_t>::max();
}
Order& Book::insert(const Order& o)
{
// BuySell is what we store in ids_, to allow us to quickly find orders by id
const auto it = ids_.emplace(
o.id , BuySell { buys_.end() , sells_.end() }
);
// Enforce that ids are unique
if (not it.second)
throw bad_order_id("Duplicate order id", o.id);
// A shortcut for storing buy or sell iterator into BuySell we just inserted into ids_
auto& os = it.first->second;
// Build Priority for price and priority of the order. Since on each insert
// we bump serial_, each such constructed Priority will be unique.
const Priority pp { o.price , ++serial_ };
// Store an order (limit or iceberg) in an appropriate collection buys_ or sells_
// and persist the iterator for this element in BuySell created above.
Order* ret = nullptr;
if (o.side == Side::Buy) {
os.buy = buys_.emplace(pp, o).first;
ret = &os.buy->second;
}
else {
os.sell = sells_.emplace(pp, o).first;
ret = &os.sell->second;
}
ret->match = unmatched;
return *ret;
}
void Book::remove(uint id)
{
const auto i = ids_.find(id);
if (i == ids_.end())
throw bad_order_id("Invalid order id", id);
if (i->second.buy != buys_.end())
buys_.erase(i->second.buy);
else // if (i->second.sell != sells_.end() )
sells_.erase(i->second.sell);
ids_.erase(i);
}
template <Side side>
void Book::match(Order& active, std::vector<Match>& matches)
{
// Active order is on "this side" and it will be matched against orders on the "opposite side"
constexpr auto opposite = (side == Side::Buy ? Side::Sell : Side::Buy);
auto& orders = this->orders<opposite>();
size_t count = 0; // Partially matched orders
while (active.size > 0 && not orders.empty())
{
auto& top = orders.begin()->second;
if (side == Side::Buy && active.price < top.price)
break;
else if (side == Side::Sell && active.price > top.price)
break;
const uint size = std::min(active.size, top.size);
if (top.match == unmatched)
{
++count;
Match match;
match.price = top.price;
match.size = 0; // Increased below
match.buyId = (side == Side::Buy ? active.id : top.id);
match.sellId = (side == Side::Sell ? active.id : top.id);
top.match = matches.size();
matches.push_back(match);
}
matches[top.match].size += size;
// Remove liquidity from active order, reset size if it is an iceberg
active.full -= size;
active.size = std::min(active.full, active.peak);
// Remove liquidity from top order
top.size -= size;
top.full -= size;
// This section could be slightly optimized by replacing calls to remove() and insert()
// with custom tailored modifications of both ids_ and orders collections
if (top.size == 0)
{
const Order copy = top;
remove(copy.id);
// Must not use top below this point
if (copy.full > 0)
{
auto& renew = insert(copy);
renew.match = copy.match;
renew.size = std::min(copy.full, copy.peak);
}
else
--count;
}
}
// Clear partial matches collected so far
size_t i = 0;
for (auto& o : orders)
{
if (o.second.match == unmatched)
continue;
o.second.match = unmatched;
if (++i == count)
break;
}
}
// Explicit instantiations of the above, for Engine::handle() to use
template void Book::match<Side::Buy>(Order&, std::vector<Match>& );
template void Book::match<Side::Sell>(Order&, std::vector<Match>& );
}
| 32.195489 | 98 | 0.583372 | [
"vector"
] |
1cdca7627c19ddc80cab1b3218da2d2d58998e46 | 7,981 | cpp | C++ | Cocodrilo/CppWrapper/CppWrapperApp.cpp | CocodriloCAD/Cocodrilo | eca315f31f9341cea758e92ef22c931f2888c882 | [
"MIT"
] | 2 | 2022-01-05T17:10:38.000Z | 2022-01-14T09:33:59.000Z | Cocodrilo/CppWrapper/CppWrapperApp.cpp | CocodriloCAD/Cocodrilo | eca315f31f9341cea758e92ef22c931f2888c882 | [
"MIT"
] | 3 | 2022-01-27T15:42:14.000Z | 2022-02-23T09:11:31.000Z | Cocodrilo/CppWrapper/CppWrapperApp.cpp | CocodriloCAD/Cocodrilo | eca315f31f9341cea758e92ef22c931f2888c882 | [
"MIT"
] | null | null | null | // CppWrapper.cpp : Defines the initialization routines for the DLL.
//
#include "stdafx.h"
#include "rhinoSdkPlugInDeclare.h"
#include "CppWrapperApp.h"
// Rhino plug-in declaration
RHINO_PLUG_IN_DECLARE
// Rhino developer declarations
// TODO: fill in the following developer declarations
// with your company information. When completed,
// delete the following #error directive.
//#error Developer declarations block is incomplete!
RHINO_PLUG_IN_DEVELOPER_ORGANIZATION( L"My Company Name" );
RHINO_PLUG_IN_DEVELOPER_ADDRESS( L"123 Developer Street\r\nCity State 12345-6789" );
RHINO_PLUG_IN_DEVELOPER_COUNTRY( L"My Country" );
RHINO_PLUG_IN_DEVELOPER_PHONE( L"123.456.7890" );
RHINO_PLUG_IN_DEVELOPER_FAX( L"123.456.7891" );
RHINO_PLUG_IN_DEVELOPER_EMAIL( L"support@mycompany.com" );
RHINO_PLUG_IN_DEVELOPER_WEBSITE( L"http://www.mycompany.com" );
RHINO_PLUG_IN_UPDATE_URL( L"http://www.mycompany.com/support" );
//
// Note!
//
// A Rhino Skin DLL is an MFC DLL.
//
// If this DLL is dynamically linked against the MFC
// DLLs, any functions exported from this DLL which
// call into MFC must have the AFX_MANAGE_STATE macro
// added at the very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//
// CCppWrapperApp
BEGIN_MESSAGE_MAP(CCppWrapperApp, CWinApp)
END_MESSAGE_MAP()
// The one and only CCppWrapperApp object
static class CCppWrapperApp theApp;
// CCppWrapperApp initialization
BOOL CCppWrapperApp::InitInstance()
{
CWinApp::InitInstance();
return TRUE;
}
int CCppWrapperApp::ExitInstance()
{
return CWinApp::ExitInstance();
}
// CSplashWnd
IMPLEMENT_DYNAMIC(CSplashWnd, CWnd)
CSplashWnd::CSplashWnd()
{
}
CSplashWnd::~CSplashWnd()
{
}
BEGIN_MESSAGE_MAP(CSplashWnd, CWnd)
ON_WM_PAINT()
ON_WM_CREATE()
END_MESSAGE_MAP()
// CSplashWnd message handlers
void CSplashWnd::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect r;
GetClientRect(r);
if ((HBITMAP)m_splash_bitmap)
{
CDC memDC;
memDC.CreateCompatibleDC(NULL);
memDC.SelectObject(&m_splash_bitmap);
dc.BitBlt(0, 0, r.Width(), r.Height(), &memDC, 0, 0, SRCCOPY);
}
else
{
dc.FillSolidRect(r, ::GetSysColor(COLOR_WINDOW));
COLORREF cr = dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
int iBkMode = dc.SetBkMode( TRANSPARENT );
CString s = L"Sample Splash Screen";
dc.DrawText(s, r, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
dc.SetTextColor(cr);
dc.SetBkMode(iBkMode);
}
}
int CSplashWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
AFX_MANAGE_STATE(::AfxGetStaticModuleState());
m_splash_bitmap.LoadBitmap(IDB_SPLASH);
CRect rW, rC;
GetWindowRect(rW);
GetClientRect(rC);
BITMAP bmp;
m_splash_bitmap.GetBitmap(&bmp);
int cx = bmp.bmWidth + (rW.Width() - rC.Width());
int cy = bmp.bmHeight + (rW.Height() - rC.Height());
SetWindowPos(NULL, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER);
CenterWindow();
return 0;
}
/////////////////////////////////////////////////////////////////////////////
// class CCppWrapperSkinDLL
//
class CCppWrapperSkinDLL : public CRhinoSkinDLL
{
public:
CCppWrapperSkinDLL();
~CCppWrapperSkinDLL();
// Required overrides
HICON MainRhinoIcon() override;
const wchar_t* ApplicationName() override;
UUID SkinPlugInID() override;
void ShowSplash(bool bShow) override;
// Optional overrides
HMENU MainRhinoMenu() override;
private:
HICON m_hIcon; // Used to save the skin icon handle so the destructor can delete it later.
CMenu m_menu; // Used to save the menu handle so the destructor can delete it later.
CSplashWnd m_wndSplash; // Splash window to create and show when ShowSplash(true) is called.
};
// The one and only CCppWrapperSkinDLL object.
// This must be created for the skin to load.
static class CCppWrapperSkinDLL theSkin;
CCppWrapperSkinDLL::CCppWrapperSkinDLL()
: m_hIcon(NULL)
{
}
CCppWrapperSkinDLL::~CCppWrapperSkinDLL()
{
// Make sure the DLL module instance is active since this is a DLL which is being loaded
// by the Rhino executable.
//
// For more information on module states and MFC, see
// "Managing the State Data of MFC Modules" in Creating
// New Documents, Windows, and Views and Technical Note 58.
//
AFX_MANAGE_STATE(::AfxGetStaticModuleState());
// Destroy the splash window if necessary.
if (::IsWindow(m_wndSplash.m_hWnd))
m_wndSplash.DestroyWindow();
// Destroy the applicaion icon if necessary.
if (m_hIcon)
::DestroyIcon(m_hIcon);
m_hIcon = NULL;
}
const wchar_t* CCppWrapperSkinDLL::ApplicationName()
{
// Return application name string used to replace the string "Rhino".
// this must return a non NULL string or the skin DLL will fail to load.
return L"CppWrapper";
}
// Return CSkinPlugInSamplePlugIn::PlugInID()
UUID CCppWrapperSkinDLL::SkinPlugInID()
{
// Returns the UUID of the companion Rhino plug-in that is used
// to manage this DLL's menu and provided other extensions to
// Rhino. If this plug-in is not going to provide a custom menu,
// then is must return ON_nil_uuid.
static const GUID CppWrapperPlugIn_UUID = ON_nil_uuid;
return CppWrapperPlugIn_UUID;
}
void CCppWrapperSkinDLL::ShowSplash( bool bShow )
{
// This method will be called when Rhino wants to display or hide a splash screen
// on startup. If you do not provide a splash screen then none will appear.
// This will not be called if Rhino is started with the "/nosplash" option.
// For more information on module states and MFC, see
// "Managing the State Data of MFC Modules" in Creating
// New Documents, Windows, and Views and Technical Note 58.
AFX_MANAGE_STATE(::AfxGetStaticModuleState());
if (bShow && FALSE == ::IsWindow(m_wndSplash.m_hWnd))
{
CSize size(::GetSystemMetrics(SM_CXFULLSCREEN), ::GetSystemMetrics(SM_CYFULLSCREEN));
CRect r(CPoint(0, 0), size);
r.DeflateRect(r.Width() / 3, r.Height() / 3);
m_wndSplash.CreateEx(WS_EX_TOPMOST, AfxRegisterWndClass(NULL), ApplicationName(), WS_POPUP | WS_VISIBLE | WS_BORDER, r, NULL, 0, NULL);
}
else if (bShow)
{
m_wndSplash.ShowWindow(SW_SHOW);
m_wndSplash.UpdateWindow();
}
else if (!bShow && ::IsWindow(m_wndSplash.m_hWnd))
{
m_wndSplash.DestroyWindow();
}
}
HICON CCppWrapperSkinDLL::MainRhinoIcon()
{
// Return HICON to be used by Rhino main frame and dialog boxes,
// the skin DLL will fail to load if this returns NULL.
// (Extracted from the Platform SDK help file)
// For more information on module states and MFC, see
// "Managing the State Data of MFC Modules" in Creating
// New Documents, Windows, and Views and Technical Note 58.
AFX_MANAGE_STATE(::AfxGetStaticModuleState());
if (NULL == m_hIcon)
m_hIcon = theApp.LoadIcon(IDI_ICON);
return m_hIcon;
}
HMENU CCppWrapperSkinDLL::MainRhinoMenu()
{
// Override this and return a valid HMENU if you want to replace
// the main Rhino menu otherwise Rhino will use its default menu.
// (Extracted from the Platform SDK help file)
// For more information on module states and MFC, see
// "Managing the State Data of MFC Modules" in Creating
// New Documents, Windows, and Views and Technical Note 58.
AFX_MANAGE_STATE(::AfxGetStaticModuleState());
// TODO: load your menu resource here.
// For example:
// if( NULL == m_menu.GetSafeHmenu() )
// m_menu.LoadMenu( IDR_MENU );
return m_menu.GetSafeHmenu();
}
| 28.402135 | 139 | 0.71808 | [
"object"
] |
1cdf17ba3f0e4cbe61f2a05e9f1a5b31ecfee1fa | 3,411 | hpp | C++ | src/utils.hpp | gumigumi4f/sv4d | ca3d334a602001486dcf341d1c98c620ce01e067 | [
"MIT"
] | null | null | null | src/utils.hpp | gumigumi4f/sv4d | ca3d334a602001486dcf341d1c98c620ce01e067 | [
"MIT"
] | null | null | null | src/utils.hpp | gumigumi4f/sv4d | ca3d334a602001486dcf341d1c98c620ce01e067 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include <sstream>
namespace sv4d {
namespace utils {
namespace string {
inline std::string trim(const std::string& s) {
auto left = std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)));
auto right = std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace)));
return (left < right.base()) ? std::string(left, right.base()) : std::string();
}
inline std::vector<std::string> split(const std::string& input, char delimiter) {
std::istringstream stream(input);
std::string field;
std::vector<std::string> result;
while (std::getline(stream, field, delimiter)) {
result.push_back(field);
}
return result;
}
inline std::vector<int> strvec_to_intvec(const std::vector<std::string>& strvec) {
auto intvec = std::vector<int>();
for (auto str : strvec) {
intvec.push_back(std::stoi(str));
}
return intvec;
}
inline std::vector<std::string> intvec_to_strvec(const std::vector<int>& intvec) {
auto strvec = std::vector<std::string>();
for (int num : intvec) {
strvec.push_back(std::to_string(num));
}
return strvec;
}
inline std::vector<float> strvec_to_floatvec(const std::vector<std::string>& strvec) {
auto floatvec = std::vector<float>();
for (auto str : strvec) {
floatvec.push_back(std::stof(str));
}
return floatvec;
}
inline std::vector<std::string> floatvec_to_strvec(const std::vector<float>& intvec) {
auto strvec = std::vector<std::string>();
for (int num : intvec) {
strvec.push_back(std::to_string(num));
}
return strvec;
}
inline std::string join(const std::vector<std::string>& v, char delimiter) {
std::string s;
if (!v.empty()) {
s += v[0];
for (decltype(v.size()) i = 1, c = v.size(); i < c; ++i) {
if (delimiter) {
s += delimiter;
}
s += v[i];
}
}
return s;
}
}
namespace operation {
const int SigmoidTableSize = 1024;
const int MaxSigmoid = 8.0;
std::vector<float> computeSigmoidTable();
const std::vector<float> sigmoidTable = computeSigmoidTable();
inline float sigmoid(float x) {
if (x < -MaxSigmoid) {
return 0.0f;
} else if (x > MaxSigmoid) {
return 1.0f;
} else {
int i = int((x + MaxSigmoid) * SigmoidTableSize / MaxSigmoid / 2);
return sigmoidTable[i];
}
}
}
}
} | 33.116505 | 113 | 0.454999 | [
"vector"
] |
1ce0d7e0048a6ae9a06fdf6cc39d51547e053055 | 2,242 | cxx | C++ | src/DmwMeshActionText3dGenerator.cxx | DmitrySemikin/das-mesh-workbench | 35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6 | [
"Apache-2.0"
] | null | null | null | src/DmwMeshActionText3dGenerator.cxx | DmitrySemikin/das-mesh-workbench | 35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6 | [
"Apache-2.0"
] | null | null | null | src/DmwMeshActionText3dGenerator.cxx | DmitrySemikin/das-mesh-workbench | 35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6 | [
"Apache-2.0"
] | null | null | null | #include <memory>
#include <string>
#include <vtkElevationFilter.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>
#include <vtkVectorText.h>
#include "DmwModel.hxx"
#include "DmwMeshActionText3dGeneratorGui.hxx"
#include "DmwMeshActionText3dGenerator.hxx"
using std::make_unique;
using std::make_shared;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
DmwMeshActionText3dGenerator::DmwMeshActionText3dGenerator(shared_ptr<DmwModel> model)
: model(model),
dialog(nullptr)
{
// Nothing to do here
}
DmwMeshActionText3dGenerator::~DmwMeshActionText3dGenerator() noexcept {
// Nothing to do here
}
vtkSmartPointer<vtkPolyData> DmwMeshActionText3dGenerator::generate3dText(const char *const text) const {
vtkNew<vtkVectorText> vectorText;
vectorText->SetText(text);
// TODO: How to specify coordinates? Or probably we can offset it after creation.
vtkNew<vtkElevationFilter> elevationFilter;
elevationFilter->SetInputConnection(vectorText->GetOutputPort());
elevationFilter->SetLowPoint(0, 0, 0);
elevationFilter->SetHighPoint(10, 0, 0);
elevationFilter->Update();
vtkSmartPointer<vtkDataSet> dataSet = elevationFilter->GetOutput();
// TODO: Find the way to manage stdout with qt (without explicit reference to qt here)
// dataSet->PrintSelf();
vtkSmartPointer<vtkPolyData> polyData = vtkPolyData::SafeDownCast(dataSet);
if (polyData == nullptr) {
// TODO: What to do?
}
return polyData;
}
void DmwMeshActionText3dGenerator::generate3dTextWithGuiAndUpdateModel() {
if (dialog == nullptr) {
dialog = make_unique<DmwMeshActionText3dGeneratorGui>();
dialog->connect(dialog.get(), &QDialog::finished, this, &DmwMeshActionText3dGenerator::onDialogFinished);
dialog->open();
}
}
void DmwMeshActionText3dGenerator::onDialogFinished(int result) {
if (result == (int)QDialog::DialogCode::Accepted && dialog != nullptr) {
const string text = dialog->getText();
vtkSmartPointer<vtkDataSet> textDataSet = generate3dText(text.c_str());
model->setDataSet(textDataSet);
}
dialog.reset();
}
void DmwMeshActionText3dGenerator::call() {
generate3dTextWithGuiAndUpdateModel();
}
| 28.74359 | 113 | 0.732382 | [
"model"
] |
1ce226072b0cb247ac9b0cf828024eec971ce51a | 11,489 | cpp | C++ | src/batterytech/src/batterytech/render/ShaderProgram.cpp | puretekniq/batterytech | cc831b2835b7bf4826948831f0274e3d80921339 | [
"MIT",
"BSD-3-Clause-Clear",
"Zlib",
"BSD-3-Clause"
] | 10 | 2015-04-07T22:23:31.000Z | 2016-03-06T11:48:32.000Z | src/batterytech/src/batterytech/render/ShaderProgram.cpp | robdoesstuff/batterytech | cc831b2835b7bf4826948831f0274e3d80921339 | [
"MIT",
"BSD-3-Clause-Clear",
"Zlib",
"BSD-3-Clause"
] | 3 | 2015-05-17T10:45:48.000Z | 2016-07-29T18:34:53.000Z | src/batterytech/src/batterytech/render/ShaderProgram.cpp | puretekniq/batterytech | cc831b2835b7bf4826948831f0274e3d80921339 | [
"MIT",
"BSD-3-Clause-Clear",
"Zlib",
"BSD-3-Clause"
] | 4 | 2015-05-03T03:00:48.000Z | 2016-03-03T12:49:01.000Z | /*
* BatteryTech
* Copyright (c) 2010 Battery Powered Games LLC.
*
* This code is a component of BatteryTech and is subject to the 'BatteryTech
* End User License Agreement'. Among other important provisions, this
* license prohibits the distribution of source code to anyone other than
* authorized parties. If you have any questions or would like an additional
* copy of the license, please contact: support@batterypoweredgames.com
*/
//============================================================================
// Name : ShaderProgram.cpp
// Description : Models a Shader Program for easy creation, use and management
//============================================================================
#include "ShaderProgram.h"
#include "../Logger.h"
#include "../platform/platformgeneral.h"
#include <string.h>
#include <stdio.h>
#include "../util/strx.h"
#include "../batterytech.h"
#include "../Context.h"
namespace BatteryTech {
int ShaderProgram::binds = 0;
ShaderProgram* ShaderProgram::currentProgram = NULL;
static BOOL32 debugShaders = FALSE;
ShaderProgram::ShaderProgram(const char *tag, const char *vertShaderAssetName, const char *fragShaderAssetName) {
vertShader = fragShader = program = 0;
this->tag = strdup(tag);
this->vertShaderAssetName = strdup(vertShaderAssetName);
this->fragShaderAssetName = strdup(fragShaderAssetName);
attribLocs = new StrHashTable<GLint>((int)(MAX_VERTEX_ATTRIBUTES * 1.3f));
// -1 is special and means not found, unlike 0, which seems only to be right for textures, so we use -2 for "NULL" to show that we've already searched and cached
attribLocs->setNullReturnVal(-2);
uniformLocs = new StrHashTable<GLint>((int)(MAX_UNIFORMS * 1.3f));
uniformLocs->setNullReturnVal(-2);
defines = new ManagedArray<ShaderDefine>(MAX_DEFINES);
vertAttLocsContiguous = FALSE;
contigAttribCount = 0;
}
ShaderProgram::~ShaderProgram() {
free(tag);
free(vertShaderAssetName);
free(fragShaderAssetName);
attribLocs->deleteElements();
delete attribLocs;
uniformLocs->deleteElements();
delete uniformLocs;
defines->deleteElements();
delete defines;
}
void ShaderProgram::invalidateGL() {
program = 0;
vertShader = 0;
fragShader = 0;
uniformLocs->deleteElements();
attribLocs->deleteElements();
}
void ShaderProgram::load(BOOL32 force) {
if (program && !force) {
// already initialized
return;
}
Property *prop = btGetContext()->appProperties->get("debug_shaders");
if (prop) {
debugShaders = prop->getBoolValue();
}
uniformLocs->deleteElements();
attribLocs->deleteElements();
GLint status = 0;
vertShader = loadShaderFromAsset(GL_VERTEX_SHADER, vertShaderAssetName);
fragShader = loadShaderFromAsset(GL_FRAGMENT_SHADER, fragShaderAssetName);
program = glCreateProgram();
glAttachShader(program, vertShader);
glAttachShader(program, fragShader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &status);
if(status == GL_FALSE){
logProgramInfo(program);
} else {
// auto find uniforms and attributes
GLint activeUniforms;
GLint activeAttributes;
glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &activeUniforms);
glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES, &activeAttributes);
if (debugShaders) {
char buf[255];
sprintf(buf, "%s uniforms=%d attribs=%d", tag, activeUniforms, activeAttributes);
logmsg(buf);
}
for (GLuint i = 0; i < (GLuint)activeUniforms; i++) {
char name[255];
GLsizei nameLength;
GLint size;
GLenum type;
glGetActiveUniform(program, i, 255, &nameLength, &size, &type, name);
if (strEndsWith(name, "[0]")) {
// by default we just want the base name to be consistent
name[strlen(name)-3] = '\0';
}
if (debugShaders) {
char buf[1024];
sprintf(buf, "%s uniform %d = %s", tag, i, name);
logmsg(buf);
}
addUniformLoc(name);
}
// we say the attribute locations are contiguous if they are like 0,1,2,3 etc but 0 5 8 30 is not nor is 1,2,3,4, must start at 0.
// this allows for really quick and easy bitwise checks to turn on/off attribute locations when changing shaders.
BOOL32 isContiguous = TRUE;
U32 attLocBits = 0;
S32 maxID = -1;
S32 minID = 1;
for (GLuint i = 0; i < (GLuint)activeAttributes; i++) {
char name[255];
GLsizei nameLength;
GLint size;
GLenum type;
glGetActiveAttrib(program, i, 255, &nameLength, &size, &type, name);
if (debugShaders) {
char buf[1024];
sprintf(buf, "%s attrib %d = %s", tag, i, name);
logmsg(buf);
}
// determine if sequential starting from 0 and mark as contiguous
GLint attLoc = addVertexAttributeLoc(name);
if (attLoc > 32) {
isContiguous = FALSE;
}
if (attLoc > maxID) {
maxID = attLoc;
}
if (attLoc < minID) {
minID = attLoc;
}
attLocBits |= 1 << attLoc;
}
if (minID > 0) {
isContiguous = FALSE;
} else {
for (S32 i = 0; i <= maxID; i++) {
if (!(attLocBits & 1 << i)) {
isContiguous = FALSE;
break;
}
}
}
vertAttLocsContiguous = isContiguous;
if (isContiguous) {
contigAttribCount = maxID + 1;
}
}
}
void ShaderProgram::unload() {
if (program) {
glDetachShader(program, vertShader);
glDetachShader(program, fragShader);
glDeleteShader(vertShader);
glDeleteShader(fragShader);
glDeleteProgram(program);
}
program = 0;
vertShader = 0;
fragShader = 0;
}
/**
* We have a very optimized bind here.
*
* 1) It won't rebind to a shader that's already bound
* 2) It has optimizations for sequentially numbered vertex attribute locations starting at 0
* 2a) In this case, which is either 99 or 100% of the time, this will only unbind/bind to deltas in the attribute counts.
*/
void ShaderProgram::bind() {
if( currentProgram == this ) {
return;
}
ShaderProgram *lastProgram = currentProgram;
currentProgram = this;
if (lastProgram) {
// both programs need contiguous att locs in order to optimize
if (!lastProgram->vertAttLocsContiguous || !vertAttLocsContiguous) {
// be safe - unbind all
for (StrHashTable<GLint>::Iterator i = lastProgram->attribLocs->getIterator(); i.hasNext;) {
GLint loc = attribLocs->getNext(i);
glDisableVertexAttribArray(loc);
}
} else {
// only unbind ones we don't need
for (U32 i = contigAttribCount; i < lastProgram->contigAttribCount; i++) {
glDisableVertexAttribArray(i);
}
}
}
binds++;
glUseProgram(program);
// enable vertex attrib arrays
if (lastProgram && lastProgram->vertAttLocsContiguous && vertAttLocsContiguous) {
// only enable ones beyond what were already enabled
for (U32 i = lastProgram->contigAttribCount; i < contigAttribCount; i++) {
glEnableVertexAttribArray(i);
}
} else {
for (StrHashTable<GLint>::Iterator i = attribLocs->getIterator(); i.hasNext;) {
GLint loc = attribLocs->getNext(i);
glEnableVertexAttribArray(loc);
}
}
}
void ShaderProgram::addDefine(const char *name, const char *value) {
defines->add(new ShaderDefine(name, value));
}
void ShaderProgram::unbind() {
// never actually unbind a shader - instead we optimize on the binding of the next.
// The only caveat is that you must always use this class when dealing with Shaders and Generic Vertex Attributes.
}
GLint ShaderProgram::addVertexAttributeLoc(const char *name) {
GLint loc = glGetAttribLocation(program, name);
if (loc == -1) {
char buf[1024];
sprintf(buf, "%s-%s - add - Vertex Attribute %s not found or is invalid", vertShaderAssetName, fragShaderAssetName, name);
logmsg(buf);
} else {
//char buf[255];
//sprintf(buf, "Added vertex attribute %s at loc %d", name, loc);
//logmsg(buf);
}
attribLocs->put(name, loc);
return loc;
}
GLint ShaderProgram::addUniformLoc(const char *name) {
GLint loc = glGetUniformLocation(program, name);
if (loc == -1) {
char buf[1024];
sprintf(buf, "%s-%s - add - Uniform %s not found or is invalid", vertShaderAssetName, fragShaderAssetName, name);
logmsg(buf);
} else {
//char buf[1024];
//sprintf(buf, "%s-%s - Added uniform %s at loc %d", vertShaderAssetName, fragShaderAssetName, name, loc);
//logmsg(buf);
}
uniformLocs->put(name, loc);
return loc;
}
GLint ShaderProgram::getVertexAttributeLoc(const char *name) {
// array-based lookup ok for such small lists.
GLint loc = attribLocs->get(name);
if (loc != -2) {
return loc;
}
if (debugShaders) {
char buf[1024];
sprintf(buf, "%s-%s - get - Vertex Attribute %s not found, attempting to auto-add", vertShaderAssetName, fragShaderAssetName, name);
logmsg(buf);
}
return addVertexAttributeLoc(name);
}
GLint ShaderProgram::getUniformLoc(const char *name) {
GLint loc = uniformLocs->get(name);
if (loc != -2) {
return loc;
}
if (debugShaders) {
char buf[1024];
sprintf(buf, "%s-%s - get - Uniform %s not found, attempting to auto-add", vertShaderAssetName, fragShaderAssetName, name);
logmsg(buf);
}
return addUniformLoc(name);
}
GLuint ShaderProgram::loadShaderFromAsset(GLenum type, const char *assetName) {
S32 assetSize;
unsigned char *fileData = _platform_load_asset(assetName, &assetSize);
if (fileData) {
char *shaderText = new char[assetSize+1];
strncpy(shaderText, (char*)fileData, assetSize);
shaderText[assetSize] = '\0';
_platform_free_asset(fileData);
//logmsg(shaderText);
GLuint shader = loadShader(type, shaderText, assetName);
delete [] shaderText;
return shader;
} else {
logmsg("No file data loading shader:");
logmsg(assetName);
}
return 0;
}
GLuint ShaderProgram::loadShader(GLenum type, const char *shaderSrc, const char *assetName) {
char buf[255];
if (debugShaders) {
sprintf(buf, "Loading Shader %s", assetName);
logmsg(buf);
}
GLuint shader;
GLint compiled;
// Create the shader object
shader = glCreateShader(type);
if(shader == 0) {
logmsg("Error - could not create shader of specified type");
return 0;
}
const char *shaderSources[2];
char defineText[1024];
defineText[0] = '\0';
for (S32 i = 0; i < defines->getSize(); i++) {
strcat(defineText, "#define ");
strcat(defineText, defines->array[i]->name);
strcat(defineText, " ");
strcat(defineText, defines->array[i]->value);
strcat(defineText, "\n");
}
shaderSources[0] = defineText;
shaderSources[1] = shaderSrc;
// Load the shader source
glShaderSource(shader, 2, shaderSources, NULL);
// Compile the shader
glCompileShader(shader);
// Check the compile status
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if(!compiled) {
sprintf(buf, "Error loading shader %s", assetName);
logmsg(buf);
logShaderInfo(shader);
glDeleteShader(shader);
return 0;
}
return shader;
}
void ShaderProgram::logShaderInfo(GLuint obj) {
GLint infoLen = 0;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infoLen);
if(infoLen > 0) {
char infoLog[1024];
glGetShaderInfoLog(obj, (infoLen > 1024 ? 1024 : infoLen), NULL, infoLog);
logmsg(infoLog);
}
}
void ShaderProgram::logProgramInfo(GLuint obj) {
GLint infoLen = 0;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infoLen);
if(infoLen > 0) {
char infoLog[1024];
glGetProgramInfoLog(obj, (infoLen > 1024 ? 1024 : infoLen), NULL, infoLog);
logmsg(infoLog);
}
}
}
| 31.135501 | 163 | 0.669249 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.