hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
74ce2cd0ca642ef0026a69ec23b6b0bfa2b1a10c | 4,478 | cpp | C++ | examples/LeNet/Main.cpp | huningxin/webnn-native | 11cb275baddeabf6831cb2b4f99d8df3113dbecd | [
"Apache-2.0"
] | null | null | null | examples/LeNet/Main.cpp | huningxin/webnn-native | 11cb275baddeabf6831cb2b4f99d8df3113dbecd | [
"Apache-2.0"
] | null | null | null | examples/LeNet/Main.cpp | huningxin/webnn-native | 11cb275baddeabf6831cb2b4f99d8df3113dbecd | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The WebNN-native Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdlib.h>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <memory>
#include <numeric>
#include <vector>
#include "common/Log.h"
#include "examples/LeNet/LeNet.h"
#include "examples/LeNet/MnistUbyte.h"
#include "examples/SampleUtils.h"
const size_t TOP_NUMBER = 3;
void SelectTopKData(std::vector<float> outputData,
std::vector<size_t>& topKIndex,
std::vector<float>& topKData) {
std::vector<size_t> indexes(outputData.size());
std::iota(std::begin(indexes), std::end(indexes), 0);
std::partial_sort(
std::begin(indexes), std::begin(indexes) + TOP_NUMBER, std::end(indexes),
[&outputData](unsigned l, unsigned r) { return outputData[l] > outputData[r]; });
std::sort(outputData.rbegin(), outputData.rend());
for (size_t i = 0; i < TOP_NUMBER; ++i) {
topKIndex[i] = indexes[i];
topKData[i] = outputData[i];
}
}
void PrintResult(webnn::Result output) {
const float* outputBuffer = static_cast<const float*>(output.Buffer());
std::vector<float> outputData(outputBuffer, outputBuffer + output.BufferSize() / sizeof(float));
std::vector<size_t> topKIndex(TOP_NUMBER);
std::vector<float> topKData(TOP_NUMBER);
SelectTopKData(outputData, topKIndex, topKData);
std::cout << std::endl << "Prediction Result:" << std::endl;
std::cout << "#"
<< " "
<< "Label"
<< " "
<< "Probability" << std::endl;
std::cout.precision(2);
for (size_t i = 0; i < TOP_NUMBER; ++i) {
std::cout << i << " ";
std::cout << std::left << std::setw(5) << std::fixed << topKIndex[i] << " ";
std::cout << std::left << std::fixed << 100 * topKData[i] << "%" << std::endl;
}
std::cout << std::endl;
}
void ShowUsage() {
std::cout << std::endl;
std::cout << "LeNet [OPTIONs]" << std::endl << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " -h "
<< "Print this message." << std::endl;
std::cout << " -i \"<path>\" "
<< "Required. Path to an image." << std::endl;
std::cout << " -m \"<path>\" "
<< "Required. Path to a .bin file with trained weights." << std::endl;
}
int main(int argc, const char* argv[]) {
DumpMemoryLeaks();
std::string imagePath, modelPath;
for (int i = 1; i < argc; ++i) {
if (strcmp("-h", argv[i]) == 0) {
ShowUsage();
return 0;
}
if (strcmp("-i", argv[i]) == 0 && i + 1 < argc) {
imagePath = argv[i + 1];
} else if (strcmp("-m", argv[i]) == 0 && i + 1 < argc) {
modelPath = argv[i + 1];
}
}
if (imagePath.empty() || modelPath.empty()) {
dawn::ErrorLog() << "Invalid options.";
ShowUsage();
return -1;
}
MnistUbyte reader(imagePath);
if (!reader.DataInitialized()) {
dawn::ErrorLog() << "The input image is invalid.";
return -1;
}
if (reader.Size() != 28 * 28) {
dawn::ErrorLog() << "The expected size of the input image is 784 (28 * 28), but got "
<< reader.Size() << ".";
return -1;
}
LeNet lenet;
if (!lenet.Load(modelPath)) {
dawn::ErrorLog() << "Failed to load LeNet.";
return -1;
}
if (!lenet.Compile()) {
dawn::ErrorLog() << "Failed to compile LeNet.";
return -1;
}
std::vector<float> input(reader.GetData().get(), reader.GetData().get() + reader.Size());
webnn::Result result = lenet.Compute(input.data(), input.size() * sizeof(float));
if (!result) {
dawn::ErrorLog() << "Failed to compute LeNet.";
return -1;
}
PrintResult(result);
dawn::InfoLog() << "Done.";
}
| 33.924242 | 100 | 0.561635 | huningxin |
74d129b14afecd892090edb6c46c56e7ae3e5f6d | 298 | cpp | C++ | problems/MapShortcut/tests/generateTest.cpp | biqar/lucid-programming-competition-2021 | 9c61ced7939ce8fe60c9ddbd31447e00e6299d2b | [
"Apache-2.0"
] | 1 | 2021-11-01T18:20:36.000Z | 2021-11-01T18:20:36.000Z | problems/MapShortcut/tests/generateTest.cpp | biqar/lucid-programming-competition-2021 | 9c61ced7939ce8fe60c9ddbd31447e00e6299d2b | [
"Apache-2.0"
] | 1 | 2021-10-30T20:27:38.000Z | 2021-10-30T20:27:38.000Z | problems/MapShortcut/tests/generateTest.cpp | biqar/lucid-programming-competition-2021 | 9c61ced7939ce8fe60c9ddbd31447e00e6299d2b | [
"Apache-2.0"
] | 3 | 2021-10-31T04:35:33.000Z | 2021-12-08T19:33:27.000Z | #include <cmath>
#include <iostream>
using namespace std;
int main()
{
int steps = 10000;
cout << steps << "\n";
for(int i = 0; i < steps; i++){
cout << ((rand() % 2 == 0) ? "Left " : "Right ")<< (rand() % 180) + 1 << " " << (rand() % 100) + 1 << "\n";
}
return 0;
}
| 19.866667 | 115 | 0.442953 | biqar |
74d5eb026312831bbbab69dd622b44f0d18d0129 | 748 | cpp | C++ | data/test/cpp/74d5eb026312831bbbab69dd622b44f0d18d0129loadwindow.cpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/test/cpp/74d5eb026312831bbbab69dd622b44f0d18d0129loadwindow.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/test/cpp/74d5eb026312831bbbab69dd622b44f0d18d0129loadwindow.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | #include "loadwindow.h"
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QLabel>
LoadWindow::LoadWindow(): QWidget()
{
#if DEBUG_CREA_FORET
cout<< "Chargement d'une foret à partir d'un fichier "<< endl;
#endif
#if DEBUG_LOAD
cout<< "Taille : " << largeur<< " en largeur "<< hauteur<< " en hauteur" <<endl;
#endif
resize(400, 30);
QVBoxLayout* layLoad= new QVBoxLayout(this);
QLabel* txtLoad= new QLabel("Chargement de la foret");
PB_load= new QProgressBar();
layLoad->addWidget(txtLoad);
layLoad->addWidget(PB_load);
show();
}
LoadWindow::~LoadWindow()
{
delete PB_load;
}
void LoadWindow::setProgress(int pourcentage)
{
PB_load->setValue(pourcentage);
}
void LoadWindow::closeProgress()
{
hide();
delete PB_load;
} | 18.243902 | 81 | 0.703209 | harshp8l |
74d77cd5445f3d1ecc810e8ecd96103fbe94940e | 5,872 | cpp | C++ | ChainIDE/contractwidget/ContractWidget.cpp | AnyChainIDE/AnyChainIDE | b4f2775a968b5aaa1114f58590f736f356fcf3b3 | [
"MIT"
] | null | null | null | ChainIDE/contractwidget/ContractWidget.cpp | AnyChainIDE/AnyChainIDE | b4f2775a968b5aaa1114f58590f736f356fcf3b3 | [
"MIT"
] | null | null | null | ChainIDE/contractwidget/ContractWidget.cpp | AnyChainIDE/AnyChainIDE | b4f2775a968b5aaa1114f58590f736f356fcf3b3 | [
"MIT"
] | null | null | null | #include "ContractWidget.h"
#include "ui_ContractWidget.h"
#include <QCoreApplication>
#include <QGuiApplication>
#include <QClipboard>
#include <QDir>
#include <QMenu>
#include "ChainIDE.h"
#include "datamanager/DataManagerHX.h"
#include "datamanager/DataManagerUB.h"
#include "datamanager/DataManagerCTC.h"
#include "ConvenientOp.h"
class ContractWidget::DataPrivate
{
public:
DataPrivate()
:contextMenu(new QMenu())
{
}
public:
QMenu *contextMenu;//右键菜单
};
Q_DECLARE_METATYPE(DataManagerStruct::ContractInfoPtr)
Q_DECLARE_METATYPE(DataManagerStruct::AddressContractPtr)
ContractWidget::ContractWidget(QWidget *parent) :
QWidget(parent),
_p(new DataPrivate()),
ui(new Ui::ContractWidget)
{
ui->setupUi(this);
InitWidget();
}
ContractWidget::~ContractWidget()
{
delete _p;
_p = nullptr;
delete ui;
}
void ContractWidget::RefreshTree()
{
ui->functionWidget->Clear();
if(ChainIDE::getInstance()->getChainClass() == DataDefine::HX)
{
DataManagerHX::getInstance()->queryAccount();
}
else if(ChainIDE::getInstance()->getChainClass() == DataDefine::UB)
{
DataManagerUB::getInstance()->queryContract();
}
else if(ChainIDE::getInstance()->getChainClass() == DataDefine::CTC)
{
DataManagerCTC::getInstance()->queryAccount();
}
}
void ContractWidget::ContractClicked(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
if(current && current->parent())
{
ui->functionWidget->RefreshContractAddr(current->text(0));
}
}
void ContractWidget::CopyAddr()
{
if(QTreeWidgetItem *item = ui->treeWidget->currentItem())
{
QApplication::clipboard()->setText(item->data(0,Qt::UserRole).value<DataManagerStruct::ContractInfoPtr>()->GetContractAddr());
}
}
void ContractWidget::InitWidget()
{
//初始化右键菜单
ui->treeWidget->installEventFilter(this);
InitContextMenu();
ui->treeWidget->header()->setVisible(false);
ui->treeWidget->header()->setStretchLastSection(true);
ui->treeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->splitter->setSizes(QList<int>()<<0.66*this->height()<<0.34*this->height());
connect(ui->treeWidget,&QTreeWidget::currentItemChanged,this,&ContractWidget::ContractClicked);
if(ChainIDE::getInstance()->getChainClass() == DataDefine::HX && (ChainIDE::getInstance()->getStartChainTypes() | DataDefine::NONE))
{
connect(DataManagerHX::getInstance(),&DataManagerHX::queryAccountFinish,DataManagerHX::getInstance(),&DataManagerHX::queryContract);
connect(DataManagerHX::getInstance(),&DataManagerHX::queryContractFinish,this,&ContractWidget::InitTree);
}
else if(ChainIDE::getInstance()->getChainClass() == DataDefine::UB && (ChainIDE::getInstance()->getStartChainTypes() | DataDefine::NONE))
{
connect(DataManagerUB::getInstance(),&DataManagerUB::queryContractFinish,this,&ContractWidget::InitTree);
}
else if(ChainIDE::getInstance()->getChainClass() == DataDefine::CTC && (ChainIDE::getInstance()->getStartChainTypes() | DataDefine::NONE))
{
connect(DataManagerCTC::getInstance(),&DataManagerCTC::queryAccountFinish,DataManagerCTC::getInstance(),&DataManagerCTC::queryContract);
connect(DataManagerCTC::getInstance(),&DataManagerCTC::queryContractFinish,this,&ContractWidget::InitTree);
}
}
void ContractWidget::InitTree()
{
ui->treeWidget->clear();
DataManagerStruct::AddressContractDataPtr data = nullptr;
if(ChainIDE::getInstance()->getChainClass() == DataDefine::HX)
{
data = DataManagerHX::getInstance()->getContract();
}
else if(ChainIDE::getInstance()->getChainClass() == DataDefine::UB)
{
data = DataManagerUB::getInstance()->getContract();
}
else if(ChainIDE::getInstance()->getChainClass() == DataDefine::CTC)
{
data = DataManagerCTC::getInstance()->getContract();
}
if(!data) return ;
for(auto it = data->getAllData().begin();it != data->getAllData().end();++it)
{
QTreeWidgetItem *item = new QTreeWidgetItem(QStringList()<<(*it)->GetOwnerAddr()<<tr("合约描述"));
item->setFlags(Qt::ItemIsEnabled);
item->setData(0,Qt::UserRole,QVariant::fromValue<DataManagerStruct::AddressContractPtr>(*it));
item->setTextAlignment(0,Qt::AlignCenter);
ui->treeWidget->addTopLevelItem(item);
for(auto cont = (*it)->GetContracts().begin();cont != (*it)->GetContracts().end();++cont)
{
QTreeWidgetItem *childitem = new QTreeWidgetItem(QStringList()<<((*cont)->GetContractName().isEmpty()?(*cont)->GetContractAddr():(*cont)->GetContractName())<<(*cont)->GetContractDes());
childitem->setData(0,Qt::UserRole,QVariant::fromValue<DataManagerStruct::ContractInfoPtr>(*cont));
childitem->setToolTip(0,(*cont)->GetContractAddr());
childitem->setTextAlignment(0,Qt::AlignCenter);
item->addChild(childitem);
}
}
ui->treeWidget->expandAll();
}
void ContractWidget::InitContextMenu()
{
QAction *copyAction = new QAction(tr("复制地址"),this);
connect(copyAction,&QAction::triggered,this,&ContractWidget::CopyAddr);
_p->contextMenu->addAction(copyAction);
}
bool ContractWidget::eventFilter(QObject *watched, QEvent *event)
{
if(watched == ui->treeWidget && event->type() == QEvent::ContextMenu)
{
if(QTreeWidgetItem *item = ui->treeWidget->currentItem())
{
if(item->parent() && ui->treeWidget->itemAt(ui->treeWidget->viewport()->mapFromGlobal(QCursor::pos())) == item)
{
_p->contextMenu->exec(QCursor::pos());
}
}
}
return QWidget::eventFilter(watched,event);
}
void ContractWidget::retranslator()
{
ui->retranslateUi(this);
ui->functionWidget->retranslator();
}
| 33.747126 | 197 | 0.676771 | AnyChainIDE |
74daa34641282415d5b3e9ba9395c6cd43befc86 | 3,425 | cpp | C++ | hosts/wconvert/xml_skeleton_exporter.cpp | ndoxx/wcore | 8b24519e9a01b0397ba2959507e1e12ea3a3aa44 | [
"Apache-2.0"
] | null | null | null | hosts/wconvert/xml_skeleton_exporter.cpp | ndoxx/wcore | 8b24519e9a01b0397ba2959507e1e12ea3a3aa44 | [
"Apache-2.0"
] | null | null | null | hosts/wconvert/xml_skeleton_exporter.cpp | ndoxx/wcore | 8b24519e9a01b0397ba2959507e1e12ea3a3aa44 | [
"Apache-2.0"
] | null | null | null | #include <stack>
#include <fstream>
#include "xml_skeleton_exporter.h"
#include "vendor/rapidxml/rapidxml_print.hpp"
#include "xml_utils.hpp"
#include "config.h"
#include "logger.h"
using namespace rapidxml;
using namespace wcore;
namespace wconvert
{
static void xml_node_add_attribute(xml_document<>& doc, xml_node<>* node, const char* attr_name, const char* attr_val)
{
char* al_attr_name = doc.allocate_string(attr_name);
char* al_attr_val = doc.allocate_string(attr_val);
xml_attribute<>* attr = doc.allocate_attribute(al_attr_name, al_attr_val);
node->append_attribute(attr);
}
static void xml_node_set_value(xml_document<>& doc, xml_node<>* node, const char* value)
{
node->value(doc.allocate_string(value));
}
XMLSkeletonExporter::XMLSkeletonExporter()
{
wcore::CONFIG.get("root.folders.model"_h, exportdir_);
}
XMLSkeletonExporter::~XMLSkeletonExporter()
{
}
static std::string mat4_to_string(const math::mat4& matrix)
{
std::string matrix_str;
for(int ii=0; ii<16; ++ii)
{
matrix_str += std::to_string(matrix[ii]);
if(ii<15)
matrix_str += " ";
}
return matrix_str;
}
static void make_skeletton_DOM(xml_document<>& doc, rapidxml::xml_node<>* parent_xml_node, const Tree<BoneInfo>::nodeT* bone_node)
{
xml_node<>* current_xml_node = doc.allocate_node(node_element, "bone");
parent_xml_node->append_node(current_xml_node);
// Bone name
xml_node_add_attribute(doc, current_xml_node, "name", bone_node->data.name.c_str());
// Bone offset matrix
const math::mat4& offset_matrix = bone_node->data.offset_matrix;
std::string matrix_str(mat4_to_string(offset_matrix));
xml_node<>* matrix_xml_node = doc.allocate_node(node_element, "offset");
current_xml_node->append_node(matrix_xml_node);
xml_node_set_value(doc, matrix_xml_node, matrix_str.c_str());
for(auto* child = bone_node->first_node(); child; child = child->next_sibling())
{
make_skeletton_DOM(doc, current_xml_node, child);
}
}
bool XMLSkeletonExporter::export_skeleton(const AnimatedModelInfo& model_info)
{
std::string filename(model_info.model_name + ".skel");
DLOGN("<i>Exporting</i> skeletton to:", "wconvert");
DLOGI("<p>" + filename + "</p>", "wconvert");
// * Produce XML representation of model data
// Doctype declaration
xml_document<> doc;
xml_node<>* decl = doc.allocate_node(node_declaration);
decl->append_attribute(doc.allocate_attribute("version", "1.0"));
decl->append_attribute(doc.allocate_attribute("encoding", "UTF-8"));
doc.append_node(decl);
// Root node
xml_node<>* root = doc.allocate_node(node_element, "BoneHierarchy");
doc.append_node(root);
xml_node_add_attribute(doc, root, "name", model_info.model_name.c_str());
// Root transform
std::string matrix_str(mat4_to_string(model_info.root_transform));
xml_node<>* root_transform_xml_node = doc.allocate_node(node_element, "offset");
root->append_node(root_transform_xml_node);
xml_node_set_value(doc, root_transform_xml_node, matrix_str.c_str());
// Depth-first traversal of bone hierarchy
// We want to conserve the hierarchy in XML format
make_skeletton_DOM(doc, root, model_info.bone_hierarchy.get_root());
std::ofstream outfile;
outfile.open(exportdir_ / filename);
outfile << doc;
return true;
}
} // namespace wconvert
| 30.580357 | 130 | 0.71562 | ndoxx |
74dfa06458cbaa03a4b96a72543165cefd0aeba5 | 11,584 | cpp | C++ | tests/apc/minimal-sync-attr/components/sender/hello_sender_exec.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 7 | 2016-04-12T15:09:33.000Z | 2022-01-26T02:28:28.000Z | tests/apc/minimal-sync-attr/components/sender/hello_sender_exec.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 10 | 2019-11-26T15:24:01.000Z | 2022-03-28T11:45:14.000Z | tests/apc/minimal-sync-attr/components/sender/hello_sender_exec.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 5 | 2016-04-12T18:40:44.000Z | 2019-12-18T14:27:52.000Z | // -*- C++ -*-
/**
* @file hello_sender_exec.cpp
* @author Martin Corino
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
//@@{__RIDL_REGEN_MARKER__} - HEADER_END : hello_sender_impl.cpp[Header]
#include "hello_sender_exec.h"
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[user_includes]
#include <thread>
#include "ciaox11/testlib/ciaox11_testlog.h"
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[user_includes]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[user_global_impl]
// Your declarations here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[user_global_impl]
namespace Hello_Sender_Impl
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[user_namespace_impl]
//============================================================
// Worker thread for synchronous invocations for MyFoo
//============================================================
void
synch_foo_generator::set_context(
IDL::traits<Hello::CCM_Sender_Context>::ref_type context)
{
this->ciao_context_ = IDL::traits<Hello::CCM_Sender_Context>::narrow (std::move(context));
}
int
synch_foo_generator::svc ()
{
std::this_thread::sleep_for (std::chrono::seconds (3));
CIAOX11_TEST_INFO << "Sender:\t->get_connection_run_my_foo" << std::endl;
IDL::traits<Hello::MyFoo>::ref_type my_foo =
this->ciao_context_->get_connection_run_my_foo();
if (!my_foo)
{
CIAOX11_TEST_ERROR << "ERROR Sender:\t->get_connection_run_my_foo "
<< "returns null" << std::endl;
return 1;
}
try
{
int32_t answer;
for (uint16_t i = 0; i < 11; ++i)
{
my_foo->hello (answer);
CIAOX11_TEST_INFO << "Sender:\tsynch hello " << answer << std::endl;
}
}
catch (const Hello::InternalError& )
{
CIAOX11_TEST_INFO << "Sender:\tsynch hello get expected exception."
<< std::endl;
}
return 0;
}
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[user_namespace_impl]
/**
* Facet Executor Implementation Class : foo_port_s_foo_prov_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[ctor]
foo_port_s_foo_prov_exec_i::foo_port_s_foo_prov_exec_i (
IDL::traits< ::Hello::CCM_Sender_Context>::ref_type context)
: context_ (std::move (context))
{
}
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[ctor]
foo_port_s_foo_prov_exec_i::~foo_port_s_foo_prov_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i[user_private_ops]
/** Operations and attributes from foo_port_s_foo_prov */
int32_t
foo_port_s_foo_prov_exec_i::hello (
int32_t answer)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i::hello[_answer]
X11_UNUSED_ARG(answer);
return {};
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::foo_port_s_foo_prov_exec_i::hello[_answer]
}
/**
* Component Executor Implementation Class : Sender_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[ctor]
Sender_exec_i::Sender_exec_i ()
{
}
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[ctor]
Sender_exec_i::~Sender_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[user_private_ops]
/** Session component operations */
void Sender_exec_i::configuration_complete ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[configuration_complete]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[configuration_complete]
}
void Sender_exec_i::ccm_activate ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[ccm_activate]
this->synch_foo_gen_.set_context(this->context_);
this->synch_foo_gen_.activate (THR_NEW_LWP | THR_JOINABLE, 1);
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[ccm_activate]
}
void Sender_exec_i::ccm_passivate ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[ccm_passivate]
this->synch_foo_gen_.wait();
if (my_attrib2() != 11 || my_attrib4().foo_long_struct() != 32 ||
my_attribute()[0] != 123)
{
CIAOX11_TEST_ERROR << " ERROR Sender: expexted attribute values 11, 32 and 123, but received "
<< my_attrib2() << "," << my_attrib4().foo_long_struct() << "," << my_attribute()
<< std::endl;
}
else CIAOX11_TEST_INFO << " Sender: attribute values : "
<< my_attrib2() << "," << my_attrib4().foo_long_struct() << "," << my_attribute()
<< std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[ccm_passivate]
}
void Sender_exec_i::ccm_remove ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[ccm_remove]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[ccm_remove]
}
IDL::traits< ::Hello::CCM_PortFooS>::ref_type
Sender_exec_i::get_foo_port_s_foo_prov ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[get_foo_port_s_foo_prov]
if (!this->foo_port_s_foo_prov_)
{
this->foo_port_s_foo_prov_ = CORBA::make_reference <foo_port_s_foo_prov_exec_i> (this->context_);
}
return this->foo_port_s_foo_prov_;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[get_foo_port_s_foo_prov]
}
::Hello::foo_seq
Sender_exec_i::my_attribute ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attribute[getter]
return this->my_attribute_;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attribute[getter]
}
void
Sender_exec_i::my_attribute (
const ::Hello::foo_seq& my_attribute)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attribute[setter]
this->my_attribute_ = my_attribute;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attribute[setter]
}
::Hello::foo_long
Sender_exec_i::my_attrib2 ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib2[getter]
return this->my_attrib2_;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib2[getter]
}
void
Sender_exec_i::my_attrib2 (
::Hello::foo_long my_attrib2)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib2[setter]
this->my_attrib2_ = my_attrib2;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib2[setter]
}
::Hello::bar_seq
Sender_exec_i::my_attrib3 ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib3[getter]
return this->my_attrib3_;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib3[getter]
}
void
Sender_exec_i::my_attrib3 (
const ::Hello::bar_seq& my_attrib3)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib3[setter]
this->my_attrib3_ = my_attrib3;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib3[setter]
}
::Hello::foo_struct
Sender_exec_i::my_attrib4 ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib4[getter]
Hello::foo_struct test {32,"Hi",33};
return test;
//return this->my_attrib4_;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib4[getter]
}
void
Sender_exec_i::my_attrib4 (
const ::Hello::foo_struct& my_attrib4)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib4[setter]
this->my_attrib4_ = my_attrib4;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib4[setter]
}
int32_t
Sender_exec_i::my_attrib5 ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib5[getter]
return this->my_attrib5_;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib5[getter]
}
void
Sender_exec_i::my_attrib5 (
int32_t my_attrib5)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib5[setter]
this->my_attrib5_ = my_attrib5;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib5[setter]
}
::Hello::out_seq
Sender_exec_i::my_attrib6 ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib6[getter]
return this->my_attrib6_;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib6[getter]
}
void
Sender_exec_i::my_attrib6 (
const ::Hello::out_seq& my_attrib6)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i::my_attrib6[setter]
this->my_attrib6_ = my_attrib6;
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i::my_attrib6[setter]
}
/// Operations from Components::SessionComponent
void
Sender_exec_i::set_session_context (
IDL::traits<Components::SessionContext>::ref_type ctx)
{
// Setting the context of this component.
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[set_session_context]
this->context_ = IDL::traits< ::Hello::CCM_Sender_Context >::narrow (std::move(ctx));
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[set_session_context]
}
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[user_namespace_end_impl]
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[user_namespace_end_impl]
} // namespace Hello_Sender_Impl
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[factory]
extern "C" void
create_Hello_Sender_Impl (
IDL::traits<Components::EnterpriseComponent>::ref_type& component)
{
component = CORBA::make_reference <Hello_Sender_Impl::Sender_exec_i> ();
}
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[factory]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : hello_sender_impl.cpp[Footer]
// Your footer (code) here
// -*- END -*-
| 35.975155 | 107 | 0.698636 | jwillemsen |
74e135f01c967a7b4d283e4fac56d360ed812608 | 7,254 | cpp | C++ | bin/sept/ZoomWindow.cpp | vdods/sept | 08ee1faf1af4feb0dc440a3002eb8cc52681f946 | [
"Apache-2.0"
] | null | null | null | bin/sept/ZoomWindow.cpp | vdods/sept | 08ee1faf1af4feb0dc440a3002eb8cc52681f946 | [
"Apache-2.0"
] | null | null | null | bin/sept/ZoomWindow.cpp | vdods/sept | 08ee1faf1af4feb0dc440a3002eb8cc52681f946 | [
"Apache-2.0"
] | null | null | null | // 2020.03.16 - Victor Dods
#include "MainWindow.hpp"
#include <iostream>
#include <QtWidgets>
bool WheelFilter::eventFilter (QObject *obj, QEvent *event)
{
if (event->type() == QEvent::Wheel) {
auto wheel_event = static_cast<QWheelEvent*>(event);
if (wheel_event->modifiers() == Qt::ControlModifier || wheel_event->modifiers() == Qt::ShiftModifier) {
// Returning true filters the event. The idea is to filter it on the QGraphicsView's
// viewport and then let the main window handle the event.
return true;
}
}
return false; // Returning false does not filter the event.
}
MainWindow::MainWindow () {
create_actions();
create_status_bar();
read_settings();
#ifndef QT_NO_SESSIONMANAGER
QGuiApplication::setFallbackSessionManagementEnabled(false);
connect(qApp, &QGuiApplication::commitDataRequest, this, &MainWindow::commit_data);
#endif
setUnifiedTitleAndToolBarOnMac(true);
// Create and populate the scene.
m_scene = new QGraphicsScene(this);
{
auto grid_layout = new QGridLayout();
{
auto label = new QLabel("HIPPO");
label->setTextInteractionFlags(Qt::TextSelectableByMouse);
grid_layout->addWidget(label, 0, 0);
}
grid_layout->addWidget(new QPushButton("THINGY"), 0, 1);
grid_layout->addWidget(new QTextEdit("OSTRICH"), 1, 0);
{
auto subscene = new QGraphicsScene();
{
auto label = new QLabel("TINY HIPPO\nTINY OSTRICH\nTINY DONKEY");
label->setTextInteractionFlags(Qt::TextSelectableByMouse);
subscene->addWidget(label);
}
auto subview = new QGraphicsView();
subview->scale(0.5, 0.5);
subview->setScene(subscene);
grid_layout->addWidget(subview);
}
auto w = new QWidget();
w->setLayout(grid_layout);
m_scene->addWidget(w);
}
// {
// // QWidget *w = new QLabel("HIPPO");
// // QWidget *w = new QPushButton("THINGY");
// QWidget *w = new QTextEdit("OSTRICH");
// m_scene->addWidget(w);
// }
m_view = new QGraphicsView(this);
// NOTE: Rendering of QTextEdit and QPushButton happen incorrectly if the default
// ViewportUpdateMode (which is QGraphicsView::MinimalViewportUpdate) is used.
// Same with SmartViewportUpdate and BoundingRectViewportUpdate. The NoViewportUpdate
// doesn't work because it doesn't update automatically (though perhaps it could work
// if the widgets were manually triggered to re-render).
m_view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); // This works, though there are drop shadows which look weird.
m_view->setScene(m_scene);
// Set the drag mode to hand. Note that the text selection and text entry of QLabel and
// QTextEdit interfere with this, so it's not necessarily easy to do this.
// m_view->setDragMode(QGraphicsView::ScrollHandDrag);
// Install an event filter on the QGraphicsView to override certain behaviors.
auto wheel_filter = new WheelFilter();
m_view->viewport()->installEventFilter(wheel_filter);
this->setCentralWidget(m_view);
}
void MainWindow::closeEvent (QCloseEvent *event) {
// Do stuff, then call event->accept() or event->ignore(). There are probably other
// ways you could respond to the event (see QCloseEvent).
event->accept();
}
// void MainWindow::keyPressEvent (QKeyEvent *event) {
// switch (event->key()) {
// case Qt::Key_Minus:
// m_view->scale(1.0/1.1, 1.0/1.1);
// break;
//
// case Qt::Key_Plus:
// m_view->scale(1.1, 1.1);
// break;
//
// case Qt::Key_BracketLeft:
// m_view->rotate(-15.0);
// break;
//
// case Qt::Key_BracketRight:
// m_view->rotate(15.0);
// break;
// }
// }
void MainWindow::wheelEvent (QWheelEvent *event) {
double constexpr ANGLE_DELTA = 15.0;
double constexpr SCALE_FACTOR = 1.1;
// If only Ctrl button is pressed, zoom.
// If only Shift button is pressed, rotate.
// NOTE: If the modifier is Qt::AltModifier, then the x and y coordinates of angleDelta
// are switched, ostensibly to facilitate horizontal scrolling.
switch (event->modifiers()) {
case Qt::ControlModifier: {
bool wheel_went_up = event->angleDelta().y() >= 0;
if (wheel_went_up)
m_view->scale(SCALE_FACTOR, SCALE_FACTOR);
else
m_view->scale(1.0/SCALE_FACTOR, 1.0/SCALE_FACTOR);
event->accept();
break;
}
case Qt::ShiftModifier: {
bool wheel_went_up = event->angleDelta().y() >= 0;
m_view->rotate((wheel_went_up ? -1.0 : 1.0) * ANGLE_DELTA);
event->accept();
break;
}
}
}
void MainWindow::about () {
QMessageBox::about(
this,
tr("About SEPT Viewer"),
tr("Created 2020.03.16 by Victor Dods")
);
}
void MainWindow::create_actions() {
QMenu *file_menu = menuBar()->addMenu(tr("&File"));
// QToolBar *file_tool_bar = addToolBar(tr("File"));
file_menu->addSeparator();
QAction *exit_action = file_menu->addAction(tr("E&xit"), this, &QWidget::close);
exit_action->setShortcuts(QKeySequence::Quit);
exit_action->setStatusTip(tr("Exit the application"));
QMenu *help_menu = menuBar()->addMenu(tr("&Help"));
QAction *about_action = help_menu->addAction(tr("&About"), this, &MainWindow::about);
about_action->setStatusTip(tr("Show the application's About box"));
QAction *about_qt_action = help_menu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
about_qt_action->setStatusTip(tr("Show the Qt library's About box"));
}
void MainWindow::create_status_bar() {
statusBar()->showMessage(tr("Ready"));
}
void MainWindow::read_settings() {
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
if (geometry.isEmpty()) {
QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
resize(availableGeometry.width(), availableGeometry.height());
move(0, 0);
// resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
// move((availableGeometry.width() - width()) / 2, (availableGeometry.height() - height()) / 2);
} else {
restoreGeometry(geometry);
}
}
void MainWindow::write_settings() {
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
settings.setValue("geometry", saveGeometry());
}
#ifndef QT_NO_SESSIONMANAGER
void MainWindow::commit_data(QSessionManager &manager) {
if (manager.allowsInteraction()) {
// Do stuff, like maybe bring up "are you sure you want to exit?" dialog. If that returns
// with "cancel", then call manager.cancel().
} else {
// Do involuntary backup of state. Could be to an "emergency backup state".
}
}
#endif
| 35.558824 | 132 | 0.633995 | vdods |
74e205cb10d4ec90ec9ffc2ba3b208d12e7fbb4a | 1,249 | cpp | C++ | lambda.cpp | as-xjc/learn_cpp | 238c5fca03956393694436d43833598abb435963 | [
"MIT"
] | null | null | null | lambda.cpp | as-xjc/learn_cpp | 238c5fca03956393694436d43833598abb435963 | [
"MIT"
] | null | null | null | lambda.cpp | as-xjc/learn_cpp | 238c5fca03956393694436d43833598abb435963 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <set>
#include <thread>
#include <vector>
void static_or_local_lambda() {
static auto generator = []() {
return 1;
};
auto generator2 = []() {
return 1;
};
std::printf("generator 1:%p\n", &generator);
std::printf("generator 2:%p\n", &generator2);
}
void print_lambda_point() {
static_or_local_lambda();
static_or_local_lambda();
std::thread test([]() {
static_or_local_lambda();
static_or_local_lambda();
});
test.join();
}
void find_if() {
std::vector<int> vector{1,2,3,4,5,6,7,8,9,10};
std::printf("\nvector:\n\t");
for (auto& i : vector) {
std::printf("%d ", i);
}
std::printf("\n");
/**
* param auto in lambda support start in C++14
* in C++11:
* @code
* auto it = std::find_if(std::begin(vector), vector.end(), [](const int& value) {
* return value == 5;
* });
* @endcode
*/
auto it = std::find_if(std::begin(vector), vector.end(), [](const auto& value) {
return value == 5;
});
if (it == vector.end()) {
std::cout << "find_if not found" << std::endl;
} else {
std::cout << "find_if :" << *it << std::endl;
}
}
int main() {
print_lambda_point();
find_if();
return 0;
} | 18.924242 | 86 | 0.567654 | as-xjc |
74e4118561b35051e39961e4cb1f1beab746cca2 | 9,878 | cpp | C++ | gen/linux/kin/eigen/src/Jvb_VectorNav_to_LeftToeBottom.cpp | UMich-BipedLab/Cassie_StateEstimation | d410ddce0ab342651f5ec0540c2867faf959a3a9 | [
"BSD-3-Clause"
] | 26 | 2018-07-20T15:20:19.000Z | 2022-03-14T07:12:12.000Z | gen/linux/kin/eigen/src/Jvb_VectorNav_to_LeftToeBottom.cpp | UMich-BipedLab/Cassie_StateEstimation | d410ddce0ab342651f5ec0540c2867faf959a3a9 | [
"BSD-3-Clause"
] | 2 | 2019-04-19T22:57:00.000Z | 2022-01-11T12:46:20.000Z | gen/linux/kin/eigen/src/Jvb_VectorNav_to_LeftToeBottom.cpp | UMich-BipedLab/Cassie_StateEstimation | d410ddce0ab342651f5ec0540c2867faf959a3a9 | [
"BSD-3-Clause"
] | 10 | 2018-07-29T08:05:14.000Z | 2022-02-03T08:48:11.000Z | /*
* Automatically Generated from Mathematica.
* Tue 8 Jan 2019 23:21:09 GMT-05:00
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "Jvb_VectorNav_to_LeftToeBottom.h"
#ifdef _MSC_VER
#define INLINE __forceinline /* use __forceinline (VC++ specific) */
#else
#define INLINE static inline /* use standard inline */
#endif
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
INLINE double Power(double x, double y) { return pow(x, y); }
INLINE double Sqrt(double x) { return sqrt(x); }
INLINE double Abs(double x) { return fabs(x); }
INLINE double Exp(double x) { return exp(x); }
INLINE double Log(double x) { return log(x); }
INLINE double Sin(double x) { return sin(x); }
INLINE double Cos(double x) { return cos(x); }
INLINE double Tan(double x) { return tan(x); }
INLINE double Csc(double x) { return 1.0/sin(x); }
INLINE double Sec(double x) { return 1.0/cos(x); }
INLINE double ArcSin(double x) { return asin(x); }
INLINE double ArcCos(double x) { return acos(x); }
/* update ArcTan function to use atan2 instead. */
INLINE double ArcTan(double x, double y) { return atan2(y,x); }
INLINE double Sinh(double x) { return sinh(x); }
INLINE double Cosh(double x) { return cosh(x); }
INLINE double Tanh(double x) { return tanh(x); }
#define E 2.71828182845904523536029
#define Pi 3.14159265358979323846264
#define Degree 0.01745329251994329576924
/*
* Sub functions
*/
static void output1(Eigen::Matrix<double,3,14> &p_output1, const Eigen::Matrix<double,14,1> &var1)
{
double t755;
double t858;
double t1275;
double t836;
double t932;
double t1097;
double t723;
double t1301;
double t1663;
double t1678;
double t1798;
double t1100;
double t1727;
double t1776;
double t717;
double t1833;
double t1850;
double t1895;
double t2188;
double t1783;
double t1954;
double t1974;
double t659;
double t2238;
double t2240;
double t2327;
double t650;
double t2967;
double t2976;
double t3026;
double t2951;
double t3048;
double t3062;
double t3128;
double t3131;
double t3079;
double t3175;
double t3191;
double t3232;
double t3298;
double t3304;
double t2839;
double t3623;
double t3624;
double t3589;
double t3592;
double t3631;
double t3646;
double t3649;
double t3671;
double t3688;
double t3710;
double t3711;
double t3724;
double t3562;
double t3563;
double t3593;
double t3605;
double t3687;
double t3744;
double t3758;
double t3777;
double t3785;
double t3789;
double t3807;
double t3820;
double t3500;
double t3522;
double t3565;
double t3569;
double t3775;
double t3852;
double t3855;
double t3902;
double t3911;
double t3919;
double t3926;
double t3927;
double t260;
double t3382;
double t3383;
double t3401;
double t3231;
double t3335;
double t3344;
double t3445;
double t3474;
double t3963;
double t3973;
double t3978;
double t3988;
double t4019;
double t3535;
double t3550;
double t3890;
double t3931;
double t3938;
double t4157;
double t4072;
double t4075;
double t4081;
double t4124;
double t4137;
double t4163;
double t4169;
double t4173;
double t4174;
double t4176;
double t4099;
double t4108;
double t3480;
double t3941;
double t3961;
double t4020;
double t4036;
double t2482;
double t2626;
double t2792;
double t2020;
double t2410;
double t2422;
double t4147;
double t4162;
double t4179;
double t4195;
double t2438;
double t2905;
double t2906;
double t2915;
double t2928;
double t4224;
double t4230;
double t4239;
double t4241;
double t4252;
double t4285;
double t4290;
double t4293;
double t4384;
double t3349;
double t3417;
double t3428;
double t4215;
double t4219;
double t4409;
double t4412;
double t4307;
double t4335;
double t4065;
double t4294;
t755 = Cos(var1[6]);
t858 = Sin(var1[6]);
t1275 = Cos(var1[5]);
t836 = 0.642788*t755;
t932 = -0.766044*t858;
t1097 = t836 + t932;
t723 = Sin(var1[5]);
t1301 = 0.766044*t755;
t1663 = 0.642788*t858;
t1678 = t1301 + t1663;
t1798 = Cos(var1[4]);
t1100 = t723*t1097;
t1727 = t1275*t1678;
t1776 = 0. + t1100 + t1727;
t717 = Sin(var1[4]);
t1833 = t1275*t1097;
t1850 = -1.*t723*t1678;
t1895 = 0. + t1833 + t1850;
t2188 = Sin(var1[3]);
t1783 = -1.*t717*t1776;
t1954 = t1798*t1895;
t1974 = 0. + t1783 + t1954;
t659 = Cos(var1[3]);
t2238 = t1798*t1776;
t2240 = t717*t1895;
t2327 = 0. + t2238 + t2240;
t650 = Cos(var1[2]);
t2967 = -0.766044*t755;
t2976 = -0.642788*t858;
t3026 = t2967 + t2976;
t2951 = -1.*t723*t1097;
t3048 = t1275*t3026;
t3062 = 0. + t2951 + t3048;
t3128 = t723*t3026;
t3131 = 0. + t1833 + t3128;
t3079 = t717*t3062;
t3175 = t1798*t3131;
t3191 = 0. + t3079 + t3175;
t3232 = t1798*t3062;
t3298 = -1.*t717*t3131;
t3304 = 0. + t3232 + t3298;
t2839 = Sin(var1[2]);
t3623 = -1.*t755;
t3624 = 1. + t3623;
t3589 = -1.*t1275;
t3592 = 1. + t3589;
t3631 = -0.0216*t3624;
t3646 = 0.0306*t755;
t3649 = 0.01770000000000005*t858;
t3671 = 0. + t3631 + t3646 + t3649;
t3688 = -1.1135*t3624;
t3710 = -1.1312*t755;
t3711 = 0.052199999999999996*t858;
t3724 = 0. + t3688 + t3710 + t3711;
t3562 = -1.*t1798;
t3563 = 1. + t3562;
t3593 = -0.7055*t3592;
t3605 = -0.0184*t723;
t3687 = t723*t3671;
t3744 = t1275*t3724;
t3758 = 0. + t3593 + t3605 + t3687 + t3744;
t3777 = 0.0184*t3592;
t3785 = -0.7055*t723;
t3789 = t1275*t3671;
t3807 = -1.*t723*t3724;
t3820 = 0. + t3777 + t3785 + t3789 + t3807;
t3500 = -1.*t659;
t3522 = 1. + t3500;
t3565 = -0.0016*t3563;
t3569 = -0.2707*t717;
t3775 = -1.*t717*t3758;
t3852 = t1798*t3820;
t3855 = 0. + t3565 + t3569 + t3775 + t3852;
t3902 = -0.2707*t3563;
t3911 = 0.0016*t717;
t3919 = t1798*t3758;
t3926 = t717*t3820;
t3927 = 0. + t3902 + t3911 + t3919 + t3926;
t260 = Cos(var1[1]);
t3382 = -1.*t2188*t3191;
t3383 = t659*t3304;
t3401 = 0. + t3382 + t3383;
t3231 = t659*t3191;
t3335 = t2188*t3304;
t3344 = 0. + t3231 + t3335;
t3445 = -1.*t650;
t3474 = 1. + t3445;
t3963 = -0.049*t3522;
t3973 = -0.21*t2188;
t3978 = t659*t3855;
t3988 = -1.*t2188*t3927;
t4019 = 0. + t3963 + t3973 + t3978 + t3988;
t3535 = -0.21*t3522;
t3550 = 0.049*t2188;
t3890 = t2188*t3855;
t3931 = t659*t3927;
t3938 = 0. + t3535 + t3550 + t3890 + t3931;
t4157 = Sin(var1[1]);
t4072 = t650*t3401;
t4075 = -1.*t3344*t2839;
t4081 = 0. + t4072 + t4075;
t4124 = -1.*t260;
t4137 = 1. + t4124;
t4163 = -0.049*t3474;
t4169 = t650*t4019;
t4173 = -0.09*t2839;
t4174 = -1.*t3938*t2839;
t4176 = 0. + t4163 + t4169 + t4173 + t4174;
t4099 = t260*t4081;
t4108 = 0. + t4099;
t3480 = -0.09*t3474;
t3941 = t650*t3938;
t3961 = 0.049*t2839;
t4020 = t4019*t2839;
t4036 = 0. + t3480 + t3941 + t3961 + t4020;
t2482 = t2188*t1974;
t2626 = t659*t2327;
t2792 = 0. + t2482 + t2626;
t2020 = t659*t1974;
t2410 = -1.*t2188*t2327;
t2422 = 0. + t2020 + t2410;
t4147 = -0.049*t4137;
t4162 = 0.004500000000000004*t4157;
t4179 = t260*t4176;
t4195 = 0. + t4147 + t4162 + t4179;
t2438 = t650*t2422;
t2905 = -1.*t2792*t2839;
t2906 = 0. + t2438 + t2905;
t2915 = t260*t2906;
t2928 = 0. + t2915;
t4224 = 0.135*t4137;
t4230 = 0.1305*t260;
t4239 = 0.049*t4157;
t4241 = t4157*t4176;
t4252 = 0. + t4224 + t4230 + t4239 + t4241;
t4285 = t650*t2792;
t4290 = t2422*t2839;
t4293 = 0. + t4285 + t4290;
t4384 = 0. + t4157;
t3349 = t650*t3344;
t3417 = t3401*t2839;
t3428 = 0. + t3349 + t3417;
t4215 = t4157*t4081;
t4219 = 0. + t4215;
t4409 = -1.*t260;
t4412 = 0. + t4409;
t4307 = t4157*t2906;
t4335 = 0. + t4307;
t4065 = t3428*t4036;
t4294 = -1.*t4036*t4293;
p_output1(0)=0. + t2928*(t4065 + t4108*t4195 + t4219*t4252) + t4108*(-1.*t2928*t4195 + t4294 - 1.*t4252*t4335);
p_output1(1)=-0.135*t4293 + (-1.*t3428*t4036 - 1.*t4108*t4195 - 1.*t4219*t4252)*t4384 + t4108*(0. + t4195*t4384 + t4252*t4412);
p_output1(2)=-0.135*t3428 + (t2928*t4195 + t4036*t4293 + t4252*t4335)*t4384 + t2928*(0. - 1.*t4195*t4384 - 1.*t4252*t4412);
p_output1(3)=-0.049 + (0. + t4065 + t4081*t4176)*t4293 + t3428*(0. - 1.*t2906*t4176 + t4294);
p_output1(4)=0. + 0.135*t2906 - 0.1305*t3428;
p_output1(5)=0. + 0.135*t4081 + 0.1305*t4293;
p_output1(6)=0.;
p_output1(7)=0. - 0.09*t2422 + 0.049*t2792 - 1.*t3344*t3938 - 1.*t3401*t4019;
p_output1(8)=0. + 0.049*t3344 - 0.09*t3401 + t2792*t3938 + t2422*t4019;
p_output1(9)=0.;
p_output1(10)=0. - 0.21*t1974 + 0.049*t2327 - 1.*t3304*t3855 - 1.*t3191*t3927;
p_output1(11)=0. + 0.049*t3191 - 0.21*t3304 + t1974*t3855 + t2327*t3927;
p_output1(12)=0.;
p_output1(13)=0. + 0.0016*t1776 - 0.2707*t1895 - 1.*t3131*t3758 - 1.*t3062*t3820;
p_output1(14)=0. - 0.2707*t3062 + 0.0016*t3131 + t1776*t3758 + t1895*t3820;
p_output1(15)=0.;
p_output1(16)=0. - 0.7055*t1097 - 0.0184*t1678 - 1.*t3026*t3671 - 1.*t1097*t3724;
p_output1(17)=0. - 0.0184*t1097 - 0.7055*t3026 + t1097*t3671 + t1678*t3724;
p_output1(18)=0.;
p_output1(19)=0.05136484440000011;
p_output1(20)=0.019994554799999897;
p_output1(21)=0;
p_output1(22)=0;
p_output1(23)=0;
p_output1(24)=0;
p_output1(25)=0;
p_output1(26)=0;
p_output1(27)=0;
p_output1(28)=0;
p_output1(29)=0;
p_output1(30)=0;
p_output1(31)=0;
p_output1(32)=0;
p_output1(33)=0;
p_output1(34)=0;
p_output1(35)=0;
p_output1(36)=0;
p_output1(37)=0;
p_output1(38)=0;
p_output1(39)=0;
p_output1(40)=0;
p_output1(41)=0;
}
Eigen::Matrix<double,3,14> Jvb_VectorNav_to_LeftToeBottom(const Eigen::Matrix<double,14,1> &var1)
{
/* Call Subroutines */
Eigen::Matrix<double,3,14> p_output1;
output1(p_output1, var1);
return p_output1;
}
| 23.80241 | 129 | 0.641324 | UMich-BipedLab |
74e593bb3a6457d26e1def2a3361587ea952c5c9 | 36,360 | cpp | C++ | vegastrike/src/star_system_generic.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/src/star_system_generic.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/src/star_system_generic.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | #include <assert.h>
#include "star_system_generic.h"
#include "gfx/vec.h"
#include "cmd/planet_generic.h"
#include "cmd/unit_generic.h"
#include "cmd/unit_collide.h"
#include "cmd/collection.h"
#include "gfx/cockpit_generic.h"
#include "audiolib.h"
#include "lin_time.h"
#include "cmd/beam.h"
#include "cmd/bolt.h"
#include <expat.h>
#include "cmd/music.h"
#include "configxml.h"
#include "vs_globals.h"
#include "vegastrike.h"
#include "universe_generic.h"
#include "cmd/nebula_generic.h"
#include "galaxy_gen.h"
#include "cmd/script/mission.h"
#include "in_kb.h"
#include "cmd/script/flightgroup.h"
#include "load_mission.h"
#include "lin_time.h"
#include "cmd/unit_util.h"
#include "cmd/unit_factory.h"
#include "cmd/unit_collide.h"
#include "vs_random.h"
#include "savegame.h"
#include "networking/netclient.h"
#include "in_kb_data.h"
#include "universe_util.h" //get galaxy faction, dude
#include <boost/version.hpp>
#if BOOST_VERSION != 102800
#if defined (_MSC_VER) && _MSC_VER <= 1200
#define Vector Vactor
#endif
#include "cs_boostpython.h"
#if defined (_MSC_VER) && _MSC_VER <= 1200
#undef Vector
#endif
#else
#include <boost/python/detail/extension_class.hpp>
#endif
vector< Vector >perplines;
extern std::vector< unorigdest* >pendingjump;
void TentativeJumpTo( StarSystem *ss, Unit *un, Unit *jumppoint, const std::string &system )
{
for (unsigned int i = 0; i < pendingjump.size(); ++i)
if (pendingjump[i]->un.GetUnit() == un)
return;
ss->JumpTo( un, jumppoint, system );
}
float ScaleJumpRadius( float radius )
{
static float jump_radius_scale = parse_float( vs_config->getVariable( "physics", "jump_radius_scale", "2" ) );
static float game_speed = parse_float( vs_config->getVariable( "physics", "game_speed", "1" ) );
//need this because sys scale doesn't affect j-point size
radius *= jump_radius_scale*game_speed;
return radius;
}
StarSystem::StarSystem()
{
stars = NULL;
bolts = NULL;
collidetable = NULL;
collidemap[Unit::UNIT_ONLY] = new CollideMap( Unit::UNIT_ONLY );
collidemap[Unit::UNIT_BOLT] = new CollideMap( Unit::UNIT_BOLT );
no_collision_time = 0; //(int)(1+2.000/SIMULATION_ATOM);
///adds to jumping table;
name = NULL;
current_stage = MISSION_SIMULATION;
time = 0;
zone = 0;
sigIter = drawList.createIterator();
this->current_sim_location = 0;
}
StarSystem::StarSystem( const char *filename, const Vector ¢r, const float timeofyear )
{
no_collision_time = 0; //(int)(1+2.000/SIMULATION_ATOM);
collidemap[Unit::UNIT_ONLY] = new CollideMap( Unit::UNIT_ONLY );
collidemap[Unit::UNIT_BOLT] = new CollideMap( Unit::UNIT_BOLT );
this->current_sim_location = 0;
///adds to jumping table;
name = NULL;
zone = 0;
_Universe->pushActiveStarSystem( this );
bolts = new bolt_draw;
collidetable = new CollideTable( this );
current_stage = MISSION_SIMULATION;
this->filename = filename;
LoadXML( filename, centr, timeofyear );
if (!name)
name = strdup( filename );
sigIter = drawList.createIterator();
AddStarsystemToUniverse( filename );
time = 0;
_Universe->popActiveStarSystem();
}
extern void ClientServerSetLightContext( int lightcontext );
StarSystem::~StarSystem()
{
if ( _Universe->getNumActiveStarSystem() )
_Universe->activeStarSystem()->SwapOut();
_Universe->pushActiveStarSystem( this );
ClientServerSetLightContext( lightcontext );
delete[] name;
Unit *unit;
for (un_iter iter = drawList.createIterator(); (unit = *iter); ++iter)
unit->Kill( false );
//if the next line goes ANYWHERE else Vega Strike will CRASH!!!!!
//DO NOT MOVE THIS LINE! IT MUST STAY
if (collidetable) delete collidetable;
_Universe->popActiveStarSystem();
vector< StarSystem* >activ;
while ( _Universe->getNumActiveStarSystem() ) {
if (_Universe->activeStarSystem() != this)
activ.push_back( _Universe->activeStarSystem() );
else
fprintf( stderr, "Avoided fatal error in deleting star system %s\n", getFileName().c_str() );
_Universe->popActiveStarSystem();
}
while ( activ.size() ) {
_Universe->pushActiveStarSystem( activ.back() );
activ.pop_back();
}
if ( _Universe->getNumActiveStarSystem() )
_Universe->activeStarSystem()->SwapIn();
RemoveStarsystemFromUniverse();
delete collidemap[Unit::UNIT_ONLY];
delete collidemap[Unit::UNIT_BOLT];
}
/********* FROM STAR SYSTEM XML *********/
void setStaticFlightgroup( vector< Flightgroup* > &fg, const std::string &nam, int faction )
{
while ( faction >= (int) fg.size() ) {
fg.push_back( new Flightgroup() );
fg.back()->nr_ships = 0;
}
if (fg[faction]->nr_ships == 0) {
fg[faction]->flightgroup_nr = faction;
fg[faction]->pos.i = fg[faction]->pos.j = fg[faction]->pos.k = 0;
fg[faction]->nr_ships = 0;
fg[faction]->ainame = "default";
fg[faction]->faction = FactionUtil::GetFaction( faction );
fg[faction]->type = "Base";
fg[faction]->nr_waves_left = 0;
fg[faction]->nr_ships_left = 0;
fg[faction]->name = nam;
}
++fg[faction]->nr_ships;
++fg[faction]->nr_ships_left;
}
Flightgroup * getStaticBaseFlightgroup( int faction )
{
//warning mem leak...not big O(num factions)
static vector< Flightgroup* >fg;
setStaticFlightgroup( fg, "Base", faction );
return fg[faction];
}
Flightgroup * getStaticStarFlightgroup( int faction )
{
//warning mem leak...not big O(num factions)
static vector< Flightgroup* >fg;
setStaticFlightgroup( fg, "Base", faction );
return fg[faction];
}
Flightgroup * getStaticNebulaFlightgroup( int faction )
{
static vector< Flightgroup* >fg;
setStaticFlightgroup( fg, "Nebula", faction );
return fg[faction];
}
Flightgroup * getStaticAsteroidFlightgroup( int faction )
{
static vector< Flightgroup* >fg;
setStaticFlightgroup( fg, "Asteroid", faction );
return fg[faction];
}
Flightgroup * getStaticUnknownFlightgroup( int faction )
{
static vector< Flightgroup* >fg;
setStaticFlightgroup( fg, "Unknown", faction );
return fg[faction];
}
void StarSystem::beginElement( void *userData, const XML_Char *name, const XML_Char **atts )
{
( (StarSystem*) userData )->beginElement( name, AttributeList( atts ) );
}
void StarSystem::endElement( void *userData, const XML_Char *name )
{
( (StarSystem*) userData )->endElement( name );
}
extern string RemoveDotSystem( const char *input );
string StarSystem::getFileName() const
{
return getStarSystemSector( filename )+string( "/" )+RemoveDotSystem( getStarSystemName( filename ).c_str() );
}
string StarSystem::getName()
{
return string( name );
}
void StarSystem::AddUnit( Unit *unit )
{
if ( stats.system_faction == FactionUtil::GetNeutralFaction() )
stats.CheckVitals( this );
if (unit->specInterdiction > 0 || unit->isPlanet() || unit->isJumppoint() || unit->isUnit() == ASTEROIDPTR) {
Unit *un;
bool found = false;
for (un_iter i = gravitationalUnits().createIterator();
(un = *i) != NULL;
++i)
if (un == unit) {
found = true;
break;
}
if (!found)
gravitationalUnits().prepend( unit );
}
drawList.prepend( unit );
unit->activeStarSystem = this; //otherwise set at next physics frame...
UnitFactory::broadcastUnit( unit, GetZone() );
unsigned int priority = UnitUtil::getPhysicsPriority( unit );
//Do we need the +1 here or not - need to look at when current_sim_location is changed relative to this function
//and relative to this function, when the bucket is processed...
unsigned int tmp = 1+( (unsigned int) vsrandom.genrand_int32() )%priority;
this->physics_buffer[(this->current_sim_location+tmp)%SIM_QUEUE_SIZE].prepend( unit );
stats.AddUnit( unit );
}
bool StarSystem::RemoveUnit( Unit *un )
{
for (unsigned int locind = 0; locind < Unit::NUM_COLLIDE_MAPS; ++locind)
if ( !is_null( un->location[locind] ) ) {
collidemap[locind]->erase( un->location[locind] );
set_null( un->location[locind] );
}
bool removed2 = false;
Unit *unit;
for (un_iter iter = gravitationalUnits().createIterator(); (unit = *iter); ++iter)
if (unit == un) {
iter.remove();
removed2 = true;
break; //Shouldn't be in there twice
}
//NOTE: not sure why if(1) was here, but safemode removed it
bool removed = false;
if (1) {
for (un_iter iter = drawList.createIterator(); (unit = *iter); ++iter)
if (unit == un) {
iter.remove();
removed = true;
break;
}
}
if (removed) {
for (unsigned int i = 0; i <= SIM_QUEUE_SIZE; ++i) {
Unit *unit;
for (un_iter iter = physics_buffer[i].createIterator(); (unit = *iter); ++iter)
if (unit == un) {
iter.remove();
removed = true;
//terminate outer loop
i = SIM_QUEUE_SIZE+1;
break;
}
}
stats.RemoveUnit( un );
}
return removed;
}
void StarSystem::ExecuteUnitAI()
{
try {
Unit *unit = NULL;
for (un_iter iter = getUnitList().createIterator(); (unit = *iter); ++iter) {
unit->ExecuteAI();
unit->ResetThreatLevel();
}
}
catch (const boost::python::error_already_set) {
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
fflush( stderr );
fflush( stdout );
} throw;
}
}
//sorry boyz...I'm just a tourist with a frag nav console--could you tell me where I am?
Unit * getTopLevelOwner() //returns terrible memory--don't dereference...ever...not even aligned
{
return (Unit*) 0x31337; //FIXME How about telling us a little story behind this function? --chuck_starchaser
}
void CarSimUpdate( Unit *un, float height )
{
un->SetVelocity( Vector( un->GetVelocity().i, 0, un->GetVelocity().k ) );
un->curr_physical_state.position = QVector( un->curr_physical_state.position.i,
height,
un->curr_physical_state.position.k );
}
StarSystem::Statistics::Statistics()
{
system_faction = FactionUtil::GetNeutralFaction();
newfriendlycount = 0;
newenemycount = 0;
newcitizencount = 0;
newneutralcount = 0;
friendlycount = 0;
enemycount = 0;
neutralcount = 0;
citizencount = 0;
checkIter = 0;
navCheckIter = 0;
}
void StarSystem::Statistics::CheckVitals( StarSystem *ss )
{
int faction = FactionUtil::GetFactionIndex( UniverseUtil::GetGalaxyFaction( ss->getFileName() ) );
if (faction != system_faction) {
*this = Statistics(); //invoke copy constructor to clear it
this->system_faction = faction;
Unit *un;
for (un_iter ui = ss->getUnitList().createIterator();
(un = *ui) != NULL;
++ui)
this->AddUnit( un ); //siege will take some time
return; //no need to check vitals now, they're all set
}
size_t iter = navCheckIter;
int k = 0;
if ( iter >= navs[0].size() ) {
iter -= navs[0].size();
k = 1;
}
if ( iter >= navs[1].size() ) {
iter -= navs[1].size();
k = 2;
}
size_t totalnavchecking = 25;
size_t totalsyschecking = 25;
while ( iter < totalnavchecking && iter < navs[k].size() ) {
if (navs[k][iter].GetUnit() == NULL) {
navs[k].erase( navs[k].begin()+iter );
} else {
++iter;
++navCheckIter;
}
}
if ( k == 2 && iter >= navs[k].size() )
navCheckIter = 0; //start over next time
size_t sortedsize = ss->collidemap[Unit::UNIT_ONLY]->sorted.size();
int sysfac = system_faction;
size_t counter = checkIter+totalsyschecking;
for (; checkIter < counter && checkIter < sortedsize; ++checkIter) {
Collidable *collide = &ss->collidemap[Unit::UNIT_ONLY]->sorted[checkIter];
if (collide->radius > 0) {
Unit *un = collide->ref.unit;
float rel = UnitUtil::getRelationFromFaction( un, sysfac );
if ( FactionUtil::isCitizenInt( un->faction ) ) {
++newcitizencount;
} else {
if (rel > 0.05)
++newfriendlycount;
else if (rel < 0.)
++newenemycount;
else
++newneutralcount;
}
}
}
if (checkIter >= sortedsize && sortedsize
> (unsigned int) (enemycount+neutralcount+friendlycount
+citizencount)/4 /*suppose at least 1/4 survive a given frame*/) {
citizencount = newcitizencount;
newcitizencount = 0;
enemycount = newenemycount;
newenemycount = 0;
neutralcount = newneutralcount;
newneutralcount = 0;
friendlycount = newfriendlycount;
newfriendlycount = 0;
checkIter = 0; //start over with list
}
}
void StarSystem::Statistics::AddUnit( Unit *un )
{
float rel = UnitUtil::getRelationFromFaction( un, system_faction );
if ( FactionUtil::isCitizenInt( un->faction ) ) {
++citizencount;
} else {
if (rel > 0.05)
++friendlycount;
else if (rel < 0.)
++enemycount;
else
++neutralcount;
}
if ( un->GetDestinations().size() )
jumpPoints[un->GetDestinations()[0]].SetUnit( un );
if ( UnitUtil::isSignificant( un ) ) {
int k = 0;
if (rel > 0) k = 1; //base
if ( un->isPlanet() && !un->isJumppoint() )
k = 1; //friendly planet
//asteroid field/debris field
if ( UnitUtil::isAsteroid( un ) ) k = 2;
navs[k].push_back( UnitContainer( un ) );
}
}
void StarSystem::Statistics::RemoveUnit( Unit *un )
{
float rel = UnitUtil::getRelationFromFaction( un, system_faction );
if ( FactionUtil::isCitizenInt( un->faction ) ) {
--citizencount;
} else {
if (rel > 0.05)
--friendlycount;
else if (rel < 0.)
--enemycount;
else
--neutralcount;
}
if ( un->GetDestinations().size() ) {
//make sure it is there
jumpPoints[(un->GetDestinations()[0])].SetUnit( NULL );
//kill it--stupid I know--but hardly time critical
jumpPoints.erase( jumpPoints.find( un->GetDestinations()[0] ) );
}
if ( UnitUtil::isSignificant( un ) ) {
for (int k = 0; k < 3; ++k)
for (size_t i = 0; i < navs[k].size();) {
if (navs[k][i].GetUnit() == un)
//slow but who cares
navs[k].erase( navs[k].begin()+i );
else ++i; //only increment if you didn't erase current
}
}
}
//Variables for debugging purposes only - eliminate later
unsigned int physicsframecounter = 1;
unsigned int theunitcounter = 0;
unsigned int totalprocessed = 0;
unsigned int movingavgarray[128] = {0};
unsigned int movingtotal = 0;
double aggfire = 0;
int numprocessed = 0;
double targetpick = 0;
void StarSystem::RequestPhysics( Unit *un, unsigned int queue )
{
Unit *unit = NULL;
un_iter iter = this->physics_buffer[queue].createIterator();
while ( (unit = *iter) && *iter != un )
++iter;
if (unit == un) {
un->predicted_priority = 0;
unsigned int newloc = (current_sim_location+1)%SIM_QUEUE_SIZE;
if (newloc != queue)
iter.moveBefore( this->physics_buffer[newloc] );
}
}
void StarSystem::UpdateUnitPhysics( bool firstframe )
{
static bool phytoggle = true;
static int batchcount = SIM_QUEUE_SIZE-1;
double aitime = 0;
double phytime = 0;
double collidetime = 0;
double flattentime = 0;
double bolttime = 0;
targetpick = 0;
aggfire = 0;
numprocessed = 0;
stats.CheckVitals( this );
if (phytoggle) {
for (++batchcount; batchcount > 0; --batchcount) {
//BELOW COMMENTS ARE NO LONGER IN SYNCH
//NOTE: Randomization is necessary to preserve scattering - otherwise, whenever a
//unit goes from low-priority to high-priority and back to low-priority, they
//get synchronized and start producing peaks.
//NOTE2: But... randomization must come only on priority changes. Otherwise, it may
//interfere with subunit scheduling. Luckily, all units that make use of subunit
//scheduling also require a constant base priority, since otherwise priority changes
//will wreak havoc with subunit interpolation. Luckily again, we only need
//randomization on priority changes, so we're fine.
try {
Unit *unit = NULL;
for (un_iter iter = physics_buffer[current_sim_location].createIterator(); (unit = *iter); ++iter) {
int priority = UnitUtil::getPhysicsPriority( unit );
//Doing spreading here and only on priority changes, so as to make AI easier
int predprior = unit->predicted_priority;
//If the priority has really changed (not an initial scattering, because prediction doesn't match)
if (priority != predprior) {
if (predprior == 0)
//Validate snapshot of current interpolated state (this is a reschedule)
unit->curr_physical_state = unit->cumulative_transformation;
//Save priority value as prediction for next scheduling, but don't overwrite yet.
predprior = priority;
//Scatter, so as to achieve uniform distribution
priority = 1+( ( (unsigned int) vsrandom.genrand_int32() )%priority );
}
float backup = SIMULATION_ATOM;
theunitcounter = theunitcounter+1;
SIMULATION_ATOM *= priority;
unit->sim_atom_multiplier = priority;
double aa = queryTime();
unit->ExecuteAI();
double bb = queryTime();
unit->ResetThreatLevel();
//FIXME "firstframe"-- assume no more than 2 physics updates per frame.
unit->UpdatePhysics( identity_transformation, identity_matrix, Vector( 0,
0,
0 ), priority
== 1 ? firstframe : true, &this->gravitationalUnits(), unit );
double cc = queryTime();
aitime += bb-aa;
phytime += cc-bb;
SIMULATION_ATOM = backup;
unit->predicted_priority = predprior;
}
}
catch (const boost::python::error_already_set) {
if ( PyErr_Occurred() ) {
PyErr_Print();
PyErr_Clear();
fflush( stderr );
fflush( stdout );
} throw;
}
double c0 = queryTime();
Bolt::UpdatePhysics( this );
double cc = queryTime();
last_collisions.clear();
double fl0 = queryTime();
collidemap[Unit::UNIT_BOLT]->flatten();
if (Unit::NUM_COLLIDE_MAPS > 1)
collidemap[Unit::UNIT_ONLY]->flatten( *collidemap[Unit::UNIT_BOLT] );
flattentime = queryTime()-fl0;
Unit *unit;
for (un_iter iter = physics_buffer[current_sim_location].createIterator(); (unit = *iter);) {
int priority = unit->sim_atom_multiplier;
float backup = SIMULATION_ATOM;
SIMULATION_ATOM *= priority;
unsigned int newloc = (current_sim_location+priority)%SIM_QUEUE_SIZE;
unit->CollideAll();
SIMULATION_ATOM = backup;
if (newloc == current_sim_location)
++iter;
else
iter.moveBefore( physics_buffer[newloc] );
}
double dd = queryTime();
collidetime += dd-cc;
bolttime += cc-c0;
current_sim_location = (current_sim_location+1)%SIM_QUEUE_SIZE;
++physicsframecounter;
totalprocessed += theunitcounter;
theunitcounter = 0;
}
} else {
Unit *unit = NULL;
for (un_iter iter = getUnitList().createIterator(); (unit = *iter); ++iter) {
unit->ExecuteAI();
last_collisions.clear();
unit->UpdatePhysics( identity_transformation, identity_matrix, Vector( 0,
0,
0 ), firstframe,
&this->gravitationalUnits(), unit );
unit->CollideAll();
}
}
}
extern void TerrainCollide();
extern void UpdateAnimatedTexture();
extern void UpdateCameraSnds();
extern float getTimeCompression();
//server
void ExecuteDirector()
{
unsigned int curcockpit = _Universe->CurrentCockpit();
{
for (unsigned int i = 0; i < active_missions.size(); ++i)
if (active_missions[i]) {
_Universe->SetActiveCockpit( active_missions[i]->player_num );
StarSystem *ss = _Universe->AccessCockpit()->activeStarSystem;
if (ss) _Universe->pushActiveStarSystem( ss );
mission = active_missions[i];
active_missions[i]->DirectorLoop();
if (ss) _Universe->popActiveStarSystem();
}
}
_Universe->SetActiveCockpit( curcockpit );
mission = active_missions[0];
processDelayedMissions();
{
for (unsigned int i = 1; i < active_missions.size();) {
if (active_missions[i]) {
if (active_missions[i]->runtime.pymissions) {
++i;
} else {
unsigned int w = active_missions.size();
active_missions[i]->terminateMission();
if ( w == active_missions.size() ) {
printf( "MISSION NOT ERASED\n" );
break;
}
}
} else {
active_missions.Get()->erase( active_missions.Get()->begin()+i );
}
}
}
}
Unit* StarSystem::nextSignificantUnit()
{
return(*sigIter);
}
void StarSystem::Update( float priority )
{
Unit *unit;
bool firstframe = true;
//No time compression here
float normal_simulation_atom = SIMULATION_ATOM;
time += GetElapsedTime();
_Universe->pushActiveStarSystem( this );
if ( time/SIMULATION_ATOM >= (1./PHY_NUM) ) {
while ( time/SIMULATION_ATOM >= (1.) ) {
//Chew up all SIMULATION_ATOMs that have elapsed since last update
ExecuteDirector();
TerrainCollide();
Unit::ProcessDeleteQueue();
current_stage = MISSION_SIMULATION;
collidetable->Update();
for (un_iter iter = drawList.createIterator(); (unit = *iter); ++iter)
unit->SetNebula( NULL );
UpdateMissiles(); //do explosions
UpdateUnitPhysics( firstframe );
firstframe = false;
}
time -= SIMULATION_ATOM;
}
SIMULATION_ATOM = normal_simulation_atom;
_Universe->popActiveStarSystem();
}
//client
void StarSystem::Update( float priority, bool executeDirector )
{
bool firstframe = true;
double pythontime = 0;
///this makes it so systems without players may be simulated less accurately
for (unsigned int k = 0; k < _Universe->numPlayers(); ++k)
if (_Universe->AccessCockpit( k )->activeStarSystem == this)
priority = 1;
float normal_simulation_atom = SIMULATION_ATOM;
SIMULATION_ATOM /= ( priority/getTimeCompression() );
///just be sure to restore this at the end
time += GetElapsedTime();
_Universe->pushActiveStarSystem( this );
//WARNING PERFORMANCE HACK!!!!!
if (time > 2*SIMULATION_ATOM)
time = 2*SIMULATION_ATOM;
double bolttime = 0;
if ( time/SIMULATION_ATOM >= (1./PHY_NUM) ) {
//Chew up all SIMULATION_ATOMs that have elapsed since last update
while ( time/SIMULATION_ATOM >= (1./PHY_NUM) ) {
if (current_stage == MISSION_SIMULATION) {
TerrainCollide();
UpdateAnimatedTexture();
Unit::ProcessDeleteQueue();
double pythonidea = queryTime();
if ( (run_only_player_starsystem
&& _Universe->getActiveStarSystem( 0 ) == this) || !run_only_player_starsystem )
if (executeDirector)
ExecuteDirector();
pythontime = queryTime()-pythonidea;
static int dothis = 0;
if ( this == _Universe->getActiveStarSystem( 0 ) )
if ( (++dothis)%2 == 0 )
AUDRefreshSounds();
for (unsigned int i = 0; i < active_missions.size(); ++i)
//waste of farkin time
active_missions[i]->BriefingUpdate();
current_stage = PROCESS_UNIT;
} else if (current_stage == PROCESS_UNIT) {
UpdateUnitPhysics( firstframe );
UpdateMissiles(); //do explosions
collidetable->Update();
if ( this == _Universe->getActiveStarSystem( 0 ) )
UpdateCameraSnds();
bolttime = queryTime();
bolttime = queryTime()-bolttime;
current_stage = MISSION_SIMULATION;
firstframe = false;
}
time -= (1./PHY_NUM)*SIMULATION_ATOM;
}
unsigned int i = _Universe->CurrentCockpit();
for (unsigned int j = 0; j < _Universe->numPlayers(); ++j)
if (_Universe->AccessCockpit( j )->activeStarSystem == this) {
_Universe->SetActiveCockpit( j );
_Universe->AccessCockpit( j )->updateAttackers();
if ( _Universe->AccessCockpit( j )->Update() ) {
SIMULATION_ATOM = normal_simulation_atom;
_Universe->SetActiveCockpit( i );
_Universe->popActiveStarSystem();
return;
}
}
_Universe->SetActiveCockpit( i );
}
if ( sigIter.isDone() )
sigIter = drawList.createIterator();
else
++sigIter;
while ( !sigIter.isDone() && !UnitUtil::isSignificant( *sigIter) )
++sigIter;
//If it is done, leave it NULL for this frame then.
//WARNING cockpit does not get here...
SIMULATION_ATOM = normal_simulation_atom;
//WARNING cockpit does not get here...
_Universe->popActiveStarSystem();
}
/*
**************************************************************************************
*** STAR SYSTEM JUMP STUFF **
**************************************************************************************
*/
Hashtable< std::string, StarSystem, 127 >star_system_table;
void StarSystem::AddStarsystemToUniverse( const string &mname )
{
star_system_table.Put( mname, this );
}
void StarSystem::RemoveStarsystemFromUniverse()
{
if ( star_system_table.Get( filename ) )
star_system_table.Delete( filename );
}
StarSystem * GetLoadedStarSystem( const char *system )
{
StarSystem *ss = star_system_table.Get( string( system ) );
std::string ssys( string( system )+string( ".system" ) );
if (!ss)
ss = star_system_table.Get( ssys );
return ss;
}
std::vector< unorigdest* >pendingjump;
bool PendingJumpsEmpty()
{
return pendingjump.empty();
}
extern void SetShieldZero( Unit* );
void StarSystem::ProcessPendingJumps()
{
for (unsigned int kk = 0; kk < pendingjump.size(); ++kk) {
Unit *un = pendingjump[kk]->un.GetUnit();
if (pendingjump[kk]->delay >= 0) {
Unit *jp = pendingjump[kk]->jumppoint.GetUnit();
if (un && jp) {
QVector delta = ( jp->LocalPosition()-un->LocalPosition() );
float dist = delta.Magnitude();
if (pendingjump[kk]->delay > 0) {
float speed = dist/pendingjump[kk]->delay;
bool player = (_Universe->isPlayerStarship( un ) != NULL);
if (dist > 10 && player) {
if (un->activeStarSystem == pendingjump[kk]->orig)
un->SetCurPosition( un->LocalPosition()+SIMULATION_ATOM*delta*(speed/dist) );
} else if (!player) {
un->SetVelocity( Vector( 0, 0, 0 ) );
}
static bool setshieldzero =
XMLSupport::parse_bool( vs_config->getVariable( "physics", "jump_disables_shields", "true" ) );
if (setshieldzero)
SetShieldZero( un );
}
}
double time = GetElapsedTime();
if (time > 1)
time = 1;
pendingjump[kk]->delay -= time;
continue;
} else {
#ifdef JUMP_DEBUG
VSFileSystem::vs_fprintf( stderr, "Volitalizing pending jump animation.\n" );
#endif
_Universe->activeStarSystem()->VolitalizeJumpAnimation( pendingjump[kk]->animation );
}
int playernum = _Universe->whichPlayerStarship( un );
//In non-networking mode or in networking mode or a netplayer wants to jump and is ready or a non-player jump
if ( Network == NULL || playernum < 0 || ( Network != NULL && playernum >= 0 && Network[playernum].readyToJump() ) ) {
Unit *un = pendingjump[kk]->un.GetUnit();
StarSystem *savedStarSystem = _Universe->activeStarSystem();
//Download client descriptions of the new zone (has to be blocking)
if (Network != NULL)
Network[playernum].downloadZoneInfo();
if ( un == NULL || !_Universe->StillExists( pendingjump[kk]->dest )
|| !_Universe->StillExists( pendingjump[kk]->orig ) ) {
#ifdef JUMP_DEBUG
VSFileSystem::vs_fprintf( stderr, "Adez Mon! Unit destroyed during jump!\n" );
#endif
delete pendingjump[kk];
pendingjump.erase( pendingjump.begin()+kk );
--kk;
continue;
}
bool dosightandsound = ( (pendingjump[kk]->dest == savedStarSystem) || _Universe->isPlayerStarship( un ) );
_Universe->setActiveStarSystem( pendingjump[kk]->orig );
if ( un->TransferUnitToSystem( kk, savedStarSystem, dosightandsound ) )
un->DecreaseWarpEnergy( false, 1.0f );
if (dosightandsound)
_Universe->activeStarSystem()->DoJumpingComeSightAndSound( un );
_Universe->AccessCockpit()->OnJumpEnd(un);
delete pendingjump[kk];
pendingjump.erase( pendingjump.begin()+kk );
--kk;
_Universe->setActiveStarSystem( savedStarSystem );
//In networking mode we tell the server we want to go back in game
if (Network != NULL) {
//Find the corresponding networked player
if (playernum >= 0) {
Network[playernum].inGame();
Network[playernum].unreadyToJump();
}
}
}
}
}
double calc_blend_factor( double frac, int priority, unsigned int when_it_will_be_simulated, int cur_simulation_frame )
{
if (when_it_will_be_simulated == SIM_QUEUE_SIZE) {
return 1;
} else {
int relwas = when_it_will_be_simulated-priority;
if (relwas < 0) relwas += SIM_QUEUE_SIZE;
int relcur = cur_simulation_frame-relwas-1;
if (relcur < 0) relcur += SIM_QUEUE_SIZE;
return (relcur+frac)/(double) priority;
}
}
void ActivateAnimation( Unit *jumppoint )
{
jumppoint->graphicOptions.Animating = 1;
Unit *un;
for (un_iter i = jumppoint->getSubUnits(); NULL != (un = *i); ++i)
ActivateAnimation( un );
}
static bool isJumping( const vector< unorigdest* > &pending, Unit *un )
{
for (size_t i = 0; i < pending.size(); ++i)
if (pending[i]->un == un)
return true;
return false;
}
QVector SystemLocation( std::string system );
double howFarToJump();
QVector ComputeJumpPointArrival( QVector pos, std::string origin, std::string destination )
{
QVector finish = SystemLocation( destination );
QVector start = SystemLocation( origin );
QVector dir = finish-start;
if ( dir.MagnitudeSquared() ) {
dir.Normalize();
dir = -dir;
pos = -pos;
pos.Normalize();
if ( pos.MagnitudeSquared() ) pos.Normalize();
return (dir*.5+pos*.125)*howFarToJump();
}
return QVector( 0, 0, 0 );
}
bool StarSystem::JumpTo( Unit *un, Unit *jumppoint, const std::string &system, bool force, bool save_coordinates )
{
if ( ( un->DockedOrDocking()&(~Unit::DOCKING_UNITS) ) != 0 )
return false;
if (Network == NULL || force) {
if (un->jump.drive >= 0)
un->jump.drive = -1;
#ifdef JUMP_DEBUG
VSFileSystem::vs_fprintf( stderr, "jumping to %s. ", system.c_str() );
#endif
StarSystem *ss = star_system_table.Get( system );
std::string ssys( system+".system" );
if (!ss)
ss = star_system_table.Get( ssys );
bool justloaded = false;
if (!ss) {
justloaded = true;
ss = _Universe->GenerateStarSystem( ssys.c_str(), filename.c_str(), Vector( 0, 0, 0 ) );
//NETFIXME: Do we want to generate the system if an AI unit jumps?
}
if ( ss && !isJumping( pendingjump, un ) ) {
#ifdef JUMP_DEBUG
VSFileSystem::vs_fprintf( stderr, "Pushing back to pending queue!\n" );
#endif
bool dosightandsound = ( ( this == _Universe->getActiveStarSystem( 0 ) ) || _Universe->isPlayerStarship( un ) );
int ani = -1;
if (dosightandsound)
ani = _Universe->activeStarSystem()->DoJumpingLeaveSightAndSound( un );
_Universe->AccessCockpit()->OnJumpBegin(un);
pendingjump.push_back( new unorigdest( un, jumppoint, this, ss, un->GetJumpStatus().delay, ani, justloaded,
save_coordinates ? ComputeJumpPointArrival( un->Position(), this->getFileName(),
system ) : QVector( 0, 0, 0 ) ) );
} else {
#ifdef JUMP_DEBUG
VSFileSystem::vs_fprintf( stderr, "Failed to retrieve!\n" );
#endif
return false;
}
if (jumppoint)
ActivateAnimation( jumppoint );
} else
//Networking mode
if (jumppoint) {
Network->jumpRequest( system, jumppoint->GetSerial() );
}
return true;
}
| 37.292308 | 130 | 0.561304 | Ezeer |
74e6ab1cb3afd798480ad9862f87c14473e2e6fd | 5,313 | hpp | C++ | include/as/multithread_task/parallel_for.hpp | asmith-git/multithread-task | 4b09b854aff2cf24651fd75bbed8d3019f8be379 | [
"Apache-2.0"
] | null | null | null | include/as/multithread_task/parallel_for.hpp | asmith-git/multithread-task | 4b09b854aff2cf24651fd75bbed8d3019f8be379 | [
"Apache-2.0"
] | null | null | null | include/as/multithread_task/parallel_for.hpp | asmith-git/multithread-task | 4b09b854aff2cf24651fd75bbed8d3019f8be379 | [
"Apache-2.0"
] | null | null | null | #ifndef ASMITH_PARALLEL_FOR_TASK_HPP
#define ASMITH_PARALLEL_FOR_TASK_HPP
// Copyright 2017 Adam Smith
//
// 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 "task_dispatcher.hpp"
#include "task.hpp"
namespace as {
template<class T, class F, class L1, class L2>
class parallel_for_task : public task<void> {
private:
const L1 mCondition;
const L2 mIncrement;
const F mFunction;
const T mBegin;
const T mEnd;
T mIndex;
public:
parallel_for_task(const T aBegin, const T aEnd, const F aFunction, const L1 aCondition, const L2 aIncrement) :
mCondition(aCondition),
mIncrement(aIncrement),
mFunction(aFunction),
mBegin(aBegin),
mEnd(aEnd),
mIndex(aBegin)
{}
void on_execute(as::task_controller& aController) override {
mIndex = mBegin;
on_resume(aController, 0);
}
void on_resume(as::task_controller& aController, uint8_t aLocation) override {
while(mCondition(mIndex, mEnd)) {
#ifndef ASMITH_DISABLE_PARALLEL_FOR_PAUSE
if(is_pause_requested()) pause(aController, aLocation);
#endif
mFunction(mIndex);
mIncrement(mIndex);
}
set_return();
}
};
namespace implementation {
template<class V, class F, class I, class I2, class L1, class L2>
void parallel_for(task_dispatcher& aDispatcher, V aMin, V aMax, F aFunction, size_t aBlocks, task_dispatcher::priority aPriority, I aMinFn, I2 aMaxFn, L1 aCondition, L2 aIncrement) {
std::future<void>* const futures = new std::future<void>[aBlocks];
try{
for(size_t i = 0; i < aBlocks; ++i) {
task_dispatcher::task_ptr task(new parallel_for_task<V,F,L1,L2>(aMinFn(i), aMaxFn(i), aFunction, aCondition, aIncrement));
futures[i] = aDispatcher.schedule<void>(task, aPriority);
}
for(size_t i = 0; i < aBlocks; ++i) futures[i].get();
}catch (std::exception& e) {
delete[] futures;
throw e;
}
delete[] futures;
}
}
template<class I, class F>
void parallel_for_less_than(task_dispatcher& aDispatcher, I aMin, I aMax, F aFunction, uint8_t aBlocks = 4, task_dispatcher::priority aPriority = task_dispatcher::priority::PRIORITY_MEDIUM) {
implementation::parallel_for<I, F>(
aDispatcher,
aMin,
aMax,
aFunction,
aBlocks,
aPriority,
[=](I i)->I {
const I range = aMax - aMin;
const I sub_range = range / aBlocks;
return aMin + (sub_range * i);
},
[=](I i)->I {
const I range = aMax - aMin;
const I sub_range = range / aBlocks;
return i + 1 == aBlocks ? aMax : sub_range * (i + 1);
},
[](const I a, const I b)->bool{ return a < b; },
[](I& i)->void { ++i; }
);
}
template<class I, class F>
void parallel_for_less_than_equals(task_dispatcher& aDispatcher, I aMin, I aMax, F aFunction, uint8_t aBlocks = 4, task_dispatcher::priority aPriority = task_dispatcher::priority::PRIORITY_MEDIUM) {
implementation::parallel_for<I, F>(
aDispatcher,
aMin,
aMax,
aFunction,
aBlocks,
aPriority,
[=](I i)->I {
const I range = aMax - aMin;
const I sub_range = range / aBlocks;
return i == 0 ? aMin : aMin + (sub_range * i) + 1;
},
[=](int i)->I {
const I range = aMax - aMin;
const I sub_range = range / aBlocks;
return i + 1 == aBlocks ? aMax : sub_range * (i + 1);
},
[](const I a, const I b)->bool{ return a <= b; },
[](I& i)->void { ++i; }
);
}
template<class I, class F>
void parallel_for_greater_than(task_dispatcher& aDispatcher, I aMin, I aMax, F aFunction, uint8_t aBlocks = 4, task_dispatcher::priority aPriority = task_dispatcher::priority::PRIORITY_MEDIUM) {
implementation::parallel_for<I, F>(
aDispatcher,
aMin,
aMax,
aFunction,
aBlocks,
aPriority,
[=](I i)->I {
const I range = aMin - aMax;
const I sub_range = range / aBlocks;
return aMin -(sub_range * i);
},
[=](I i)->I {
const I range = aMin - aMax;
const I sub_range = range / aBlocks;
return i + 1 == aBlocks ? aMax : aMin - (sub_range * (i + 1));
},
[](const I a, const I b)->bool{ return a > b; },
[](I& i)->void { --i; }
);
}
template<class I, class F>
void parallel_for_greater_than_equals(task_dispatcher& aDispatcher, I aMin, I aMax, F aFunction, uint8_t aBlocks = 4, task_dispatcher::priority aPriority = task_dispatcher::priority::PRIORITY_MEDIUM) {
implementation::parallel_for<I, F>(
aDispatcher,
aMin,
aMax,
aFunction,
aBlocks,
aPriority,
[=](I i)->I {
const I range = aMin - aMax;
const I sub_range = range / aBlocks;
return i == 0 ? aMin : aMin - (sub_range * i) - 1;
},
[=](I i)->I {
const I range = aMin - aMax;
const I sub_range = range / aBlocks;
return i + 1 == aBlocks ? aMax : aMin - (sub_range * (i + 1));
},
[](const I a, const I b)->bool{ return a >= b; },
[](I& i)->void { --i; }
);
}
}
#endif | 30.36 | 202 | 0.654056 | asmith-git |
d55cab678c4665883553fd2ed1be29a834df8216 | 4,402 | cpp | C++ | libs/SysmelCompiler/Environment/ASTNode.cpp | ronsaldo/sysmel-beta | 14237d780527c6ca1bb34f74195838f78f0c6acc | [
"MIT"
] | 2 | 2021-10-30T15:31:43.000Z | 2021-11-08T09:45:15.000Z | libs/SysmelCompiler/Environment/ASTNode.cpp | ronsaldo/sysmel-beta | 14237d780527c6ca1bb34f74195838f78f0c6acc | [
"MIT"
] | null | null | null | libs/SysmelCompiler/Environment/ASTNode.cpp | ronsaldo/sysmel-beta | 14237d780527c6ca1bb34f74195838f78f0c6acc | [
"MIT"
] | null | null | null | #include "Environment/ASTNode.hpp"
#include "Environment/ASTSemanticAnalyzer.hpp"
#include "Environment/ASTSourcePosition.hpp"
#include "Environment/ASTLiteralValueNode.hpp"
#include "Environment/ASTValuePatternNode.hpp"
#include "Environment/LiteralString.hpp"
#include "Environment/SubclassResponsibility.hpp"
#include "Environment/MacroInvocationContext.hpp"
#include "Environment/BootstrapMethod.hpp"
#include "Environment/BootstrapTypeRegistration.hpp"
namespace Sysmel
{
namespace Environment
{
static BootstrapTypeRegistration<ASTNode> ASTNodeTypeRegistration;
MethodCategories ASTNode::__instanceMethods__()
{
return MethodCategories{
{"accessing", {
makeMethodBinding<ASTSourcePositionPtr (ASTNodePtr)> ("sourcePosition", [](const ASTNodePtr &self) {
return self->sourcePosition;
}, MethodFlags::Pure),
}},
{"converting", {
makeMethodBinding<ASTSourcePositionPtr (ASTNodePtr)> ("parseAsPatternNode", [](const ASTNodePtr &self) {
return self->parseAsPatternNode();
}, MethodFlags::Pure),
}},
};
}
ASTNode::ASTNode()
{
sourcePosition = ASTSourcePosition::empty();
}
AnyValuePtr ASTNode::accept(const ASTVisitorPtr &)
{
SysmelSelfSubclassResponsibility();
}
ASTNodePtr ASTNode::parseAsPatternNode()
{
auto result = basicMakeObject<ASTValuePatternNode> ();
result->sourcePosition = sourcePosition;
result->expectedValue = selfFromThis();
return result;
}
ASTNodePtr ASTNode::parseAsBindingPatternNode()
{
return parseAsPatternNode();
}
ASTNodePtr ASTNode::optimizePatternNodeForExpectedTypeWith(const TypePtr &, const ASTSemanticAnalyzerPtr &semanticAnalyzer)
{
return semanticAnalyzer->recordSemanticErrorInNode(selfFromThis(), "Not a pattern node that can be optimized.");
}
ASTNodePtr ASTNode::expandPatternNodeForExpectedTypeWith(const TypePtr &, const ASTNodePtr &, const ASTSemanticAnalyzerPtr &semanticAnalyzer)
{
return semanticAnalyzer->recordSemanticErrorInNode(selfFromThis(), "Not a pattern node that can be expanded.");
}
bool ASTNode::isASTNode() const
{
return true;
}
bool ASTNode::isASTLiteralSymbolValue() const
{
return false;
}
bool ASTNode::isPureCompileTimeLiteralValueNode() const
{
return false;
}
bool ASTNode::isPureCompileTimeEvaluableNode() const
{
return false;
}
ASTNodePtr ASTNode::asASTNodeRequiredInPosition(const ASTSourcePositionPtr &requiredSourcePosition)
{
(void)requiredSourcePosition;
return selfFromThis();
}
ASTNodePtr ASTNode::asInlinedBlockBodyNode()
{
return selfFromThis();
}
bool ASTNode::isASTIdentifierSymbolValue() const
{
return false;
}
bool ASTNode::isASTLiteralTypeNode() const
{
return false;
}
bool ASTNode::isAlwaysMatchingPattern() const
{
return false;
}
bool ASTNode::isNeverMatchingPattern() const
{
return false;
}
bool ASTNode::isValidForCachingTypeConversionRules() const
{
return true;
}
bool ASTNode::isSuperReference() const
{
return false;
}
ASTNodePtr ASTNode::parseAsArgumentNodeWith(const ASTSemanticAnalyzerPtr &semanticAnalyzer)
{
return semanticAnalyzer->recordSemanticErrorInNode(selfFromThis(), "This is not a valid argument argument specification.");
}
ASTNodePtr ASTNode::parseAsPatternMatchingCaseWith(const ASTSemanticAnalyzerPtr &semanticAnalyzer)
{
return semanticAnalyzer->recordSemanticErrorInNode(selfFromThis(), "Not a valid pattern matching case.");
}
std::string ASTNode::printString() const
{
return sexpressionToPrettyString(asSExpression());
}
ASTNodePtrList ASTNode::children()
{
ASTNodePtrList result;
childrenDo([&](const ASTNodePtr &child) {
if(child)
result.push_back(child);
});
return result;
}
void ASTNode::childrenDo(const ASTIterationBlock &aBlock)
{
(void)aBlock;
}
void ASTNode::allChildrenDo(const ASTIterationBlock &aBlock)
{
ASTIterationBlock recursiveBlock = [&](const ASTNodePtr &child) {
aBlock(child);
child->childrenDo(recursiveBlock);
};
childrenDo(recursiveBlock);
}
void ASTNode::withAllChildrenDo(const ASTIterationBlock &aBlock)
{
aBlock(selfFromThis());
allChildrenDo(aBlock);
}
ASTPragmaNodePtr ASTNode::getPragmaNamed(const AnyValuePtr &requestedPragmaSelector)
{
return nullptr;
}
} // End of namespace Environment
} // End of namespace Sysmel | 24.054645 | 141 | 0.745797 | ronsaldo |
d55ea0d25a858f78f95d565d282a464cbb4f0605 | 2,416 | cpp | C++ | cpp/custrings/tests/test_url.cpp | JohnZed/cudf | 403d2571e5fcde66b7768b2213f6c142cc8b63db | [
"Apache-2.0"
] | null | null | null | cpp/custrings/tests/test_url.cpp | JohnZed/cudf | 403d2571e5fcde66b7768b2213f6c142cc8b63db | [
"Apache-2.0"
] | null | null | null | cpp/custrings/tests/test_url.cpp | JohnZed/cudf | 403d2571e5fcde66b7768b2213f6c142cc8b63db | [
"Apache-2.0"
] | null | null | null | #include <gtest/gtest.h>
#include "nvstrings/NVStrings.h"
#include "./utils.h"
struct TestURL : public GdfTest {
};
TEST_F(TestURL, UrlEncode)
{
std::vector<const char*> hstrs{"www.nvidia.com/rapids?p=é",
"/_file-7.txt",
"a b+c~d",
"e\tfgh\\jklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789",
" \t\f\n",
nullptr,
""};
NVStrings* strs = NVStrings::create_from_array(hstrs.data(), hstrs.size());
NVStrings* got = strs->url_encode();
const char* expected[] = {"www.nvidia.com%2Frapids%3Fp%3D%C3%A9",
"%2F_file-7.txt",
"a%20b%2Bc~d",
"e%09fgh%5Cjklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789",
"%20%09%0C%0A",
nullptr,
""};
EXPECT_TRUE(verify_strings(got, expected));
NVStrings::destroy(got);
NVStrings::destroy(strs);
}
TEST_F(TestURL, UrlDecode)
{
std::vector<const char*> hstrs{"www.nvidia.com/rapids/%3Fp%3D%C3%A9",
"/_file-1234567890.txt",
"a%20b%2Bc~defghijklmnopqrstuvwxyz",
"%25-accent%c3%a9d",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"01234567890",
nullptr,
""};
NVStrings* strs = NVStrings::create_from_array(hstrs.data(), hstrs.size());
NVStrings* got = strs->url_decode();
const char* expected[] = {"www.nvidia.com/rapids/?p=é",
"/_file-1234567890.txt",
"a b+c~defghijklmnopqrstuvwxyz",
"%-accentéd",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"01234567890",
nullptr,
""};
EXPECT_TRUE(verify_strings(got, expected));
NVStrings::destroy(got);
NVStrings::destroy(strs);
}
| 36.606061 | 78 | 0.412252 | JohnZed |
d55f8de827a5b2a68185b3d9d9d3c2bb3658bf6a | 17,143 | cpp | C++ | wpn.cpp | commandus/wpn | 7064b4effd1d1e502daf6bddcdf126165706ca32 | [
"MIT"
] | 2 | 2020-11-22T23:45:19.000Z | 2020-12-14T06:54:31.000Z | wpn.cpp | commandus/wpn | 7064b4effd1d1e502daf6bddcdf126165706ca32 | [
"MIT"
] | null | null | null | wpn.cpp | commandus/wpn | 7064b4effd1d1e502daf6bddcdf126165706ca32 | [
"MIT"
] | 1 | 2021-05-13T12:23:19.000Z | 2021-05-13T12:23:19.000Z | /**
* Copyright (c) 2018 Andrei Ivanov <andrei.i.ivanov@commandus.com>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* @file wpn.cpp
*
*/
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <signal.h>
#include <argtable3/argtable3.h>
#include <curl/curl.h>
#include "platform.h"
#include "wpn.h"
#include "wp-storage-file.h"
#include "wp-subscribe.h"
#include "wp-push.h"
#include "sslfactory.h"
#include "mcs/mcsclient.h"
#include "utilqr.h"
#include "utilstring.h"
#include "utilvapid.h"
#include "utilrecv.h"
#include "sslfactory.h"
#include "errlist.h"
#define PROMPT_STARTED "Enter q or press Ctrl+C to quit, p to ping"
#define LINK_SUREPHONE_D "https://surephone.commandus.com/?d="
#define LINK_SUREPHONE_QR "https://surephone.commandus.com/qr/?id="
#define DEF_EMAIL_TEMPLATE "<html><body>$subject<br/>Hi, $name<br/>Click the link below on the phone, tablet or other device on which surephone is installed.\
If the program is not already installed, \
<a href=\"https://play.google.com/store/apps/details?id=com.commandus.surephone\">install it</a>.\
<br/>$body</body></html>"
static int quitFlag = 0;
void signalHandler(int signal)
{
switch(signal)
{
case SIGHUP:
std::cerr << MSG_RELOAD_CONFIG_REQUEST << std::endl;
quitFlag = 2;
fclose(0);
break;
case SIGINT:
std::cerr << MSG_INTERRUPTED << std::endl;
quitFlag = 1;
break;
default:
break;
}
}
#ifdef _MSC_VER
// TODO
void setSignalHandler()
{
}
#else
void setSignalHandler()
{
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = &signalHandler;
sigaction(SIGINT, &action, NULL);
sigaction(SIGHUP, &action, NULL);
}
#endif
#ifdef _MSC_VER
void initWindows()
{
// Initialize Winsock
WSADATA wsaData;
int r = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (r)
{
std::cerr << "WSAStartup error %d" << r << std::endl;
exit(ERR_WSA);
}
}
#endif
void onLog
(
void *env,
int severity,
const char *message
)
{
WpnConfig *c = (WpnConfig *) env;
if (c && c->config && c->config->clientOptions->getVerbosity() >= severity)
{
std::cerr << message;
}
}
/**
* Call dynamically loaded functions to notify user
*/
void onNotify(
void *env,
const char *persistent_id,
const char *from,
const char *appName,
const char *appId,
int64_t sent,
const NotifyMessageC *notification
)
{
WpnConfig *c = (WpnConfig *) env;
if (c && c->config && c->config->clientOptions->getVerbosity() > 2)
{
if (notification)
{
std::cerr << "Body:" << notification->body << std::endl;
}
}
for (std::vector <OnNotifyC>::const_iterator it(((WpnConfig*) env)->onNotifyList.begin()); it != ((WpnConfig*)env)->onNotifyList.end(); ++it)
{
(*it) (env, persistent_id, from, appName, appId, sent, notification);
}
}
void readCommand(
int *quitFlag,
std::istream &strm,
MCSClient *client
)
{
std::string s;
while ((*quitFlag == 0) && (!strm.eof()))
{
strm >> s;
if (s.find_first_of("qQ") == 0)
{
*quitFlag = 1;
break;
}
if (s.find_first_of("pP") == 0)
{
client->ping();
}
}
}
int main(int argc, char** argv)
{
// Signal handler
setSignalHandler();
#ifdef _MSC_VER
initWindows();
#endif
// In windows, this will init the winsock stuff
curl_global_init(CURL_GLOBAL_ALL);
initSSL();
WpnConfig config(argc, argv);
if (config.error())
exit(config.error());
switch (config.cmd)
{
case CMD_LIST:
{
if ((config.outputFormat == 0) && (config.config->clientOptions->getVerbosity() > 0))
std::cout << "subscribeUrl\tsubscribe mode\tendpoint\tauthorized entity\tFCM token\tpushSet" << std::endl;
config.config->subscriptions->write(std::cout, "\t", config.outputFormat);
}
break;
case CMD_LIST_QRCODE:
{
if ((config.outputFormat == 0) && (config.config->clientOptions->getVerbosity() > 0))
std::cout << "FCM QRCodes:" << std::endl;
std::stringstream ss;
std::string foreground = u8"\u2588\u2588";
std::string background = " ";
std::string v = config.config->wpnKeys->getPublicKey();
if (config.invert_qrcode)
v = qr2string(v, foreground, background);
else
v = qr2string(v, background, foreground);
std::cout
<< config.config->wpnKeys->id << "\t"
<< config.config->clientOptions->name << std::endl
<< v << std::endl;
long r = 0;
if (config.config->clientOptions->getVerbosity() > 0) {
for (std::vector<Subscription>::const_iterator it(config.config->subscriptions->list.begin()); it != config.config->subscriptions->list.end(); ++it)
{
std::string v = it->getWpnKeys().getPublicKey();
if (config.invert_qrcode)
v = qr2string(v, foreground, background);
else
v = qr2string(v, background, foreground);
std::cout
<< it->getWpnKeys().id << "\t"
<< it->getName() << std::endl
<< v << std::endl;
}
}
}
break;
case CMD_LIST_LINK:
{
std::stringstream ssBody;
for (std::vector<Subscription>::const_iterator it(config.config->subscriptions->list.begin()); it != config.config->subscriptions->list.end(); ++it)
{
std::stringstream ss;
ss
<< it->getName() << ","
<< it->getAuthorizedEntity() << ","
<< it->getServerKey() << ","
<< it->getToken();
ssBody << LINK_SUREPHONE_D << escapeURLString(ss.str()) << std::endl;
}
std::cout << ssBody.str();
}
break;
case CMD_LIST_EMAIL:
{
if (config.subject.empty()) {
config.subject = "Connect device to wpn";
}
if (config.email_template.empty()) {
config.email_template = DEF_EMAIL_TEMPLATE;
}
std::string m = config.email_template;
size_t p = m.find("$name");
if (p != std::string::npos)
{
m.replace(p, 5, config.cn);
}
p = m.find("$subject");
if (p != std::string::npos)
{
m.replace(p, 8, config.subject);
}
std::stringstream ssBody;
for (std::vector<Subscription>::const_iterator it(config.config->subscriptions->list.begin()); it != config.config->subscriptions->list.end(); ++it)
{
std::stringstream ss;
ss
<< it->getName() << ","
<< it->getAuthorizedEntity() << ","
<< it->getServerKey() << ","
<< it->getToken();
std::string u = escapeURLString(ss.str());
ssBody
<< "<p>"
<< "<a href=\"" << LINK_SUREPHONE_D << u << "\">Connect to "
<< it->getName()
<< "</a>"
<< "</p>"
<< std::endl;
}
p = m.find("$body");
if (p != std::string::npos)
{
m.replace(p, 5, ssBody.str());
}
std::cout << m << std::endl;
}
break;
case CMD_CREDENTIALS:
{
if ((config.outputFormat == 0) && (config.config->clientOptions->getVerbosity() > 0))
std::cout << "application\tandroid\ttoken\tGCM" << std::endl;
config.config->androidCredentials->write(std::cout, "\t", config.outputFormat);
std::cout << std::endl;
}
break;
case CMD_KEYS:
{
if ((config.outputFormat == 0) && (config.config->clientOptions->getVerbosity() > 0))
std::cout << "private\tpublic\tsecret" << std::endl;
config.config->wpnKeys->write(std::cout, "\t", config.outputFormat);
std::cout << std::endl;
}
break;
case CMD_SUBSCRIBE_FCM:
{
std::string d;
std::string headers;
std::string token;
std::string pushset;
int r = subscribeFCM(&d, &headers, token, pushset,
config.config->wpnKeys->getPublicKey(),
config.config->wpnKeys->getAuthSecret(),
config.subscribeUrl, config.getDefaultFCMEndPoint(), config.authorizedEntity,
config.config->clientOptions->getVerbosity());
if ((r < 200) || (r >= 300))
{
std::cerr << "Error " << r << ": " << d << std::endl;
}
else
{
Subscription subscription;
subscription.setToken(token);
subscription.setPushSet(pushset);
subscription.setServerKey(config.serverKey);
subscription.setSubscribeUrl(config.subscribeUrl);
subscription.setSubscribeMode(SUBSCRIBE_FORCE_FIREBASE);
subscription.setEndpoint(config.getDefaultFCMEndPoint());
subscription.setAuthorizedEntity(config.authorizedEntity);
config.config->subscriptions->list.push_back(subscription);
if (config.config->clientOptions->getVerbosity() > 0)
{
subscription.write(std::cout, "\t", config.outputFormat);
}
}
}
break;
case CMD_SUBSCRIBE_VAPID:
{
// TODO
Subscription subscription;
config.config->subscriptions->list.push_back(subscription);
if (config.config->clientOptions->getVerbosity() > 0)
{
subscription.write(std::cout, "\t", config.outputFormat);
}
}
break;
case CMD_UNSUBSCRIBE:
{
if (config.authorizedEntity.empty())
{
// delete all
Subscription f(config.fcm_endpoint, config.authorizedEntity);
for (std::vector<Subscription>::iterator it(config.config->subscriptions->list.begin()); it != config.config->subscriptions->list.end(); ++it)
{
// TODO
}
config.config->subscriptions->list.clear();
}
else
{
Subscription f(config.fcm_endpoint, config.authorizedEntity);
std::vector<Subscription>::iterator it = std::find(config.config->subscriptions->list.begin(),
config.config->subscriptions->list.end(), f);
if (it != config.config->subscriptions->list.end())
config.config->subscriptions->list.erase(it);
}
}
break;
case CMD_PUSH:
{
std::string retval;
std::string token = "";
std::string serverKey;
WpnKeys wpnKeys;
if (!config.private_key.empty()) {
// override Wpn keys
wpnKeys.init(0, 0, config.private_key, config.public_key, config.auth_secret);
}
switch (config.subscriptionMode) {
case SUBSCRIBE_FORCE_FIREBASE:
serverKey = config.serverKey;
break;
case SUBSCRIBE_FORCE_VAPID:
break;
default:
// Load server key from the subscription, by the name
const Subscription *subscription = config.getSubscription(config.name);
if (subscription) {
switch (subscription->getSubscribeMode()) {
case SUBSCRIBE_FORCE_FIREBASE:
config.subscriptionMode = SUBSCRIBE_FORCE_FIREBASE;
serverKey = subscription->getServerKey();
token = subscription->getToken();
break;
case SUBSCRIBE_FORCE_VAPID:
{
config.subscriptionMode = SUBSCRIBE_FORCE_VAPID;
// subscription MUST keep wpn keys
WpnKeys wpnkeys = subscription->getWpnKeys();
wpnKeys.init(subscription->getWpnKeys());
}
break;
default:
break;
}
}
break;
}
std::string body = jsClientNotification("", config.subject, config.body, config.icon, config.link, config.data);
// for VAPID only one endpoint not many
for (std::vector<std::string>::const_iterator it(config.recipientTokens.begin()); it != config.recipientTokens.end(); ++it)
{
int r;
if (config.command.empty())
{
if (config.config->clientOptions->getVerbosity() > 1)
std::cout << "Sending notification to " << *it << std::endl;
switch (config.subscriptionMode) {
case SUBSCRIBE_FORCE_FIREBASE:
r = push2ClientNotificationFCM(&retval, serverKey, *it,
config.subject, config.body, config.icon, config.link, config.data, config.config->clientOptions->getVerbosity());
break;
case SUBSCRIBE_FORCE_VAPID:
if (config.config->clientOptions->getVerbosity() > 3) {
std::cerr << "sender public key: " << wpnKeys.getPublicKey() << std::endl
<< "sender private key: " << wpnKeys.getPrivateKey() << std::endl
<< "endpoint: " << *it << std::endl
<< "public key: " << config.vapid_recipient_p256dh << std::endl
<< "auth secret: " << config.auth_secret << std::endl
<< "body: " << body << std::endl
<< "sub: " << config.sub << std::endl;
}
r = webpushVapid(NULL, retval, wpnKeys.getPublicKey(), wpnKeys.getPrivateKey(), *it, config.vapid_recipient_p256dh, config.auth_secret,
body, config.sub, config.aesgcm ? AESGCM : AES128GCM);
if (config.config->clientOptions->getVerbosity() > 3) {
std::string filename = "aesgcm.bin";
retval = webpushVapidCmd(wpnKeys.getPublicKey(), wpnKeys.getPrivateKey(), filename, *it, config.vapid_recipient_p256dh, config.auth_secret,
body, config.sub, config.aesgcm ? AESGCM : AES128GCM);
}
break;
}
}
else
{
if (config.config->clientOptions->getVerbosity() > 1)
std::cout << "Execute command " << config.command << " on " << *it << std::endl;
switch (config.subscriptionMode) {
case SUBSCRIBE_FORCE_FIREBASE:
r = push2ClientDataFCM(&retval, serverKey, token, *it, "", config.command, 0, "", config.config->clientOptions->getVerbosity());
break;
case SUBSCRIBE_FORCE_VAPID:
r = webpushVapid(NULL, retval, wpnKeys.getPublicKey(), wpnKeys.getPrivateKey(), *it, config.vapid_recipient_p256dh, config.vapid_recipient_auth,
body, config.sub, config.aesgcm ? AESGCM : AES128GCM);
break;
}
}
if (r >= 200 && r < 300)
std::cout << retval << std::endl;
else
std::cerr << "Error " << r << ": " << retval << std::endl;
}
}
break;
case CMD_PRINT_VERSION:
{
std::cout << config.versionString() << std::endl;
break;
}
case CMD_GENERATE_VAPID_KEYS:
{
Subscription subscription;
std::string d;
std::string headers;
config.config->wpnKeys->generate();
/*
int r = subscribe(subscription, SUBSCRIBE_VAPID, *config.wpnKeys,
config.subscribeUrl, config.getDefaultEndPoint(), config.authorizedEntity,
config.serverKey, &d, &headers, config.verbosity);
if ((r < 200) || (r >= 300))
{
std::cerr << "Error " << r << ": " << d << std::endl;
}
else
{
config.subscriptions->list.push_back(subscription);
}
if (config.verbosity > 0)
{
subscription.write(std::cout, "\t", config.outputFormat);
}
*/
std::cout << config.config->wpnKeys->toJsonString() << std::endl;
}
break;
default:
{
do {
quitFlag = 0;
config.loadNotifyFuncs();
MCSClient client(
config.config->subscriptions,
config.config->wpnKeys->getPrivateKey(),
config.config->wpnKeys->getAuthSecret(),
config.config->androidCredentials->getAndroidId(),
config.config->androidCredentials->getSecurityToken(),
onNotify, &config, onLog, &config,
config.config->clientOptions->getVerbosity()
);
// check in
if (config.config->androidCredentials->getAndroidId() == 0)
{
uint64_t androidId = config.config->androidCredentials->getAndroidId();
uint64_t securityToken = config.config->androidCredentials->getSecurityToken();
int r = checkIn(&androidId, &securityToken, config.config->clientOptions->getVerbosity());
if (r < 200 || r >= 300)
{
return ERR_NO_ANDROID_ID_N_TOKEN;
}
config.config->androidCredentials->setAndroidId(androidId);
config.config->androidCredentials->setSecurityToken(securityToken);
}
// register
if (config.config->androidCredentials->getGCMToken().empty())
{
int r;
for (int i = 0; i < 5; i++)
{
std::string gcmToken;
r = registerDevice(&gcmToken,
config.config->androidCredentials->getAndroidId(),
config.config->androidCredentials->getSecurityToken(),
config.config->androidCredentials->getAppId(),
config.config->clientOptions->getVerbosity()
);
if (r >= 200 && r < 300)
{
config.config->androidCredentials->setGCMToken(gcmToken);
break;
}
sleep(1);
}
if (r < 200 || r >= 300)
{
return ERR_NO_FCM_TOKEN;
}
}
client.connect();
std::cerr << PROMPT_STARTED << std::endl;
readCommand(&quitFlag, std::cin, &client);
client.disconnect();
config.unloadNotifyFuncs();
} while (quitFlag == 2);
}
}
config.config->save();
return 0;
}
| 29.97028 | 158 | 0.635186 | commandus |
d5609174e85033a4e5396ecac711ecec863cc658 | 3,788 | cpp | C++ | CyberSoftMedicine/main.cpp | snowdence/ContestScience_DetectCancer | a50a1bf0130ce0fd099f3424ce4c9c9a8bfaf137 | [
"MIT"
] | null | null | null | CyberSoftMedicine/main.cpp | snowdence/ContestScience_DetectCancer | a50a1bf0130ce0fd099f3424ce4c9c9a8bfaf137 | [
"MIT"
] | null | null | null | CyberSoftMedicine/main.cpp | snowdence/ContestScience_DetectCancer | a50a1bf0130ce0fd099f3424ce4c9c9a8bfaf137 | [
"MIT"
] | null | null | null | /******************************************************************************************/
/*********** Author : Tran Minh Duc (Snowdence) *******************/
/*********** Email : Snowdence2911@gmail.com *******************/
/*********** Phone : 0982 259 245 *******************
/*********** Project: CyberSoftMedicine - CyberCorp Inc. *******************/
/*********** Date : 9:51 09/04/2017 *******************/
/*********** Compile: Visual Studio 2017 *******************/
/******************************************************************************************/
#include <iostream>
#include <ctime>
#include <string>
#include "SupportFile.h"
#include "NeuralLayer.h"
#include "NeuralProcess.h"
using namespace std;
SupportFile sf;
/// <summary> Admin </summary>
/// <param name="inputNeurons">Số nơ ron đầu vào.</param>
/// <param name="hiddenNeurons">Số nơ ron lớp ẩn.</param>
/// <param name="outputNeurons">Số nơ ron đầu ra.</param>
/// <param name="learningRate">Tốc độ học .</param>
/// <param name="momentum">Hằng số momen mặc định 0.9 .</param>
void trainExperience(int inputNeurons, int hiddenNeurons, int outputNeurons, float learningRate, float momentum, int epochs, char* fileTraining, char* saveWeights)
{
sf.initFileData(inputNeurons, outputNeurons);
if(sf.loadFileData(fileTraining) == false)
{
cout << "Co loi xay ra voi file dao tao. " << endl;
return;
}
NeuralLayer nn(inputNeurons, hiddenNeurons, outputNeurons);
NeuralProcess nT(&nn);
nT.setTrainingParameters(learningRate, momentum, false);
nT.setStoppingConditions(epochs, 95);
nT.trainNetwork(sf.getTrainingDataSet());
nn.saveWeights(saveWeights);
}
void useExperience(int inputNeurons, int hiddenNeurons, int outputNeurons, char* fileTest, char* fileWeights)
{
sf.initFileData(inputNeurons, outputNeurons);
sf.loadFileData(fileTest);
NeuralLayer nn(inputNeurons, hiddenNeurons, outputNeurons);
if (!nn.loadWeights(fileWeights))
{
cout << "Co Loi Xay Ra Voi File Kinh Nghiem " << endl;
return;
}
NeuralProcess nT(&nn);
cout << "\n\n\n" << endl;
cout << "Ket qua tinh toan duoc la : [" << ((*nn.feedForwardPattern(sf.getTrainingDataSet()->trainingSet[0]->pattern) == 0) ? "Lanh tinh" : "Ac tinh") << "]" << endl;
}
void display()
{
cout << "************************************* " << endl;
cout << "------------------------------------- " << endl;
cout << "1. Dao tao mang neuron" << endl;
cout << "2. Su dung kinh nghiem da dao tao " << endl;
cout << "3. Thoat chuong trinh " << endl;
cout << "------------------------------------- " << endl;
cout << "************************************* " << endl;
cout << "" << endl;
cout << "Nhap lua chon cua ban : ";
}
void train()
{
string file = "";
string w = "";
int thehe = 1000;
cout << "Nhap file dao tao: ";
cin >> file;
cout << "Nhap ten file de luu kinh nghiem sau khi dao tao: ";
cin >> w;
char tab1[1024];
char tab2[1024];
trainExperience(9, 16, 1, 0.001, 0.9, thehe, strcpy(tab1, file.c_str()), strcpy(tab2, w.c_str()) );
}
void use() {
string file = "";
string exp = "";
cout << "Nhap ten file can de du doan: ";
cin >> file;
cout << "Nhap ten file kinh nghiem da luu: ";
cin >> exp;
char temp[1024];
char tempp[1024];
useExperience(9, 16, 1,strcpy(temp, file.c_str()) , strcpy(tempp, exp.c_str()) );
}
void main()
{
int option = 0;
LABEL:
display();
cin >> option;
switch (option)
{
case 1:
train();
break;
case 2:
use();
break;
case 3:
goto END;
break;
default:
cout << "Gia tri ban vua nhap khong dung" << endl;
break;
}
cout << "\n\n\n" << endl;
goto LABEL;
//trainExperience(9, 16, 1, 0.001, 0.9, 100, "cancer.txt", "weights.txt");
//useExperience(9, 16, 1, "test.txt", "weights.txt");
END:
system("exit");
} | 31.04918 | 167 | 0.558342 | snowdence |
d563068ad87208151ba4618b1b8ed063349fe979 | 2,640 | cpp | C++ | Engine/source/sfx/sfxResource.cpp | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 2,113 | 2015-01-01T11:23:01.000Z | 2022-03-28T04:51:46.000Z | Engine/source/sfx/sfxResource.cpp | Ashry00/Torque3D | 33e3e41c8b7eb41c743a589558bc21302207ef97 | [
"MIT"
] | 948 | 2015-01-02T01:50:00.000Z | 2022-02-27T05:56:40.000Z | Engine/source/sfx/sfxResource.cpp | Ashry00/Torque3D | 33e3e41c8b7eb41c743a589558bc21302207ef97 | [
"MIT"
] | 944 | 2015-01-01T09:33:53.000Z | 2022-03-15T22:23:03.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "sfx/sfxResource.h"
#include "sfx/sfxFileStream.h"
#include "core/util/fourcc.h"
#include "core/resourceManager.h"
// Ugly workaround to keep the constructor protected.
struct SFXResource::_NewHelper
{
static SFXResource* New( String fileName, const ThreadSafeRef< SFXStream >& stream )
{
return new SFXResource( fileName, stream );
}
};
template<>
void* Resource< SFXResource >::create( const Torque::Path& path )
{
String fullPath = path.getFullPath();
// Try to open the stream.
ThreadSafeRef< SFXStream > stream = SFXFileStream::create( fullPath );
if( !stream )
return NULL;
// We have a valid stream... create the resource.
SFXResource* res = SFXResource::_NewHelper::New( fullPath, stream );
return res;
}
template<>
ResourceBase::Signature Resource< SFXResource >::signature()
{
return MakeFourCC( 's', 'f', 'x', 'r' );
}
Resource< SFXResource > SFXResource::load( String filename )
{
return ResourceManager::get().load( filename );
}
SFXResource::SFXResource( String fileName, SFXStream *stream )
: mFileName( fileName ),
mFormat( stream->getFormat() ),
mDuration( stream->getDuration() )
{
}
bool SFXResource::exists( String filename )
{
return SFXFileStream::exists( filename );
}
SFXStream* SFXResource::openStream()
{
return SFXFileStream::create( mFileName );
}
| 31.807229 | 87 | 0.682197 | vbillet |
d56d520ca31a1a0d4e01db3fd7025bab7c717764 | 3,133 | cpp | C++ | lib/spdk/SpdkIoBuf.cpp | janlt/daqdb | 04ff602fe0a6c199a782b877203b8b8b9d3fec66 | [
"Apache-2.0"
] | 22 | 2019-02-08T17:23:12.000Z | 2021-10-12T06:35:37.000Z | lib/spdk/SpdkIoBuf.cpp | janlt/daqdb | 04ff602fe0a6c199a782b877203b8b8b9d3fec66 | [
"Apache-2.0"
] | 8 | 2019-02-11T06:30:47.000Z | 2020-04-22T09:49:44.000Z | lib/spdk/SpdkIoBuf.cpp | daq-db/daqdb | e30afe8a9a4727e60d0c1122d28679a4ce326844 | [
"Apache-2.0"
] | 10 | 2019-02-11T10:26:52.000Z | 2019-09-16T20:49:25.000Z | /**
* Copyright (c) 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "spdk/env.h"
#include "SpdkIoBuf.h"
namespace DaqDB {
SpdkIoBufMgr::~SpdkIoBufMgr() {}
SpdkIoBuf *SpdkIoBufMgr::getIoWriteBuf(uint32_t ioSize, uint32_t align) {
SpdkIoBuf *buf = 0;
uint32_t bufIdx = ioSize / 4096;
if (bufIdx < 8) {
buf = block[bufIdx]->getWriteBuf();
if (!buf->getSpdkDmaBuf())
buf->setSpdkDmaBuf(
spdk_dma_zmalloc(static_cast<size_t>(ioSize), align, NULL));
} else {
buf = new SpdkIoSizedBuf<1 << 16>(1 << 16, -1);
buf->setSpdkDmaBuf(
spdk_dma_zmalloc(static_cast<size_t>(ioSize), align, NULL));
}
return buf;
}
void SpdkIoBufMgr::putIoWriteBuf(SpdkIoBuf *ioBuf) {
if (ioBuf->getIdx() != -1)
ioBuf->putWriteBuf(ioBuf);
else {
delete ioBuf;
}
}
SpdkIoBuf *SpdkIoBufMgr::getIoReadBuf(uint32_t ioSize, uint32_t align) {
SpdkIoBuf *buf = 0;
uint32_t bufIdx = ioSize / 4096;
if (bufIdx < 8) {
buf = block[bufIdx]->getReadBuf();
buf->setIdx(bufIdx);
if (!buf->getSpdkDmaBuf())
buf->setSpdkDmaBuf(
spdk_dma_zmalloc(static_cast<size_t>(ioSize), align, NULL));
} else {
buf = new SpdkIoSizedBuf<1 << 16>(1 << 16, -1);
buf->setSpdkDmaBuf(
spdk_dma_zmalloc(static_cast<size_t>(ioSize), align, NULL));
}
return buf;
}
void SpdkIoBufMgr::putIoReadBuf(SpdkIoBuf *ioBuf) {
if (ioBuf->getIdx() != -1)
ioBuf->putReadBuf(ioBuf);
else
delete ioBuf;
}
Lock SpdkIoBufMgr::instanceMutex;
SpdkIoBufMgr *SpdkIoBufMgr::instance = 0;
SpdkIoBufMgr *SpdkIoBufMgr::getSpdkIoBufMgr() {
if (!SpdkIoBufMgr::instance) {
WriteLock r_lock(instanceMutex);
SpdkIoBufMgr::instance = new SpdkIoBufMgr();
}
return SpdkIoBufMgr::instance;
}
void SpdkIoBufMgr::putSpdkIoBufMgr() {
if (SpdkIoBufMgr::instance) {
WriteLock r_lock(instanceMutex);
delete SpdkIoBufMgr::instance;
SpdkIoBufMgr::instance = 0;
}
}
SpdkIoBufMgr::SpdkIoBufMgr() {
block[0] = new SpdkIoSizedBuf<4096>(4096, 0);
block[1] = new SpdkIoSizedBuf<2 * 4096>(2 * 4096, 1);
block[2] = new SpdkIoSizedBuf<3 * 4096>(3 * 4096, 2);
block[3] = new SpdkIoSizedBuf<4 * 4096>(4 * 4096, 3);
block[4] = new SpdkIoSizedBuf<5 * 4096>(5 * 4096, 4);
block[5] = new SpdkIoSizedBuf<6 * 4096>(6 * 4096, 5);
block[6] = new SpdkIoSizedBuf<7 * 4096>(7 * 4096, 6);
block[7] = new SpdkIoSizedBuf<8 * 4096>(8 * 4096, 7);
}
} // namespace DaqDB
| 30.125 | 76 | 0.637408 | janlt |
d56e4c51124dd3c3861735a8feefa5847b625f24 | 1,830 | cpp | C++ | core/jni/android_app_ActivityThread.cpp | Y-D-Lu/rr_frameworks_base | c5a298fb78e662bb3775016a6ad5ff7c423ec8a9 | [
"Apache-2.0"
] | null | null | null | core/jni/android_app_ActivityThread.cpp | Y-D-Lu/rr_frameworks_base | c5a298fb78e662bb3775016a6ad5ff7c423ec8a9 | [
"Apache-2.0"
] | null | null | null | core/jni/android_app_ActivityThread.cpp | Y-D-Lu/rr_frameworks_base | c5a298fb78e662bb3775016a6ad5ff7c423ec8a9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 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 "jni.h"
#include "GraphicsJNI.h"
#include <nativehelper/JNIHelp.h>
#include <minikin/Layout.h>
#include <renderthread/RenderProxy.h>
#include "core_jni_helpers.h"
#include <unistd.h>
namespace android {
static void android_app_ActivityThread_purgePendingResources(JNIEnv* env, jobject clazz) {
// Don't care about return values.
mallopt(M_PURGE, 0);
}
static void
android_app_ActivityThread_dumpGraphics(JNIEnv* env, jobject clazz, jobject javaFileDescriptor) {
int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor);
android::uirenderer::renderthread::RenderProxy::dumpGraphicsMemory(fd);
minikin::Layout::dumpMinikinStats(fd);
}
static JNINativeMethod gActivityThreadMethods[] = {
// ------------ Regular JNI ------------------
{ "nPurgePendingResources", "()V",
(void*) android_app_ActivityThread_purgePendingResources },
{ "nDumpGraphicsInfo", "(Ljava/io/FileDescriptor;)V",
(void*) android_app_ActivityThread_dumpGraphics }
};
int register_android_app_ActivityThread(JNIEnv* env) {
return RegisterMethodsOrDie(env, "android/app/ActivityThread",
gActivityThreadMethods, NELEM(gActivityThreadMethods));
}
};
| 32.678571 | 97 | 0.730055 | Y-D-Lu |
d570b489b19f2331a163a6fb31ebaebd8e1f7d88 | 803 | cpp | C++ | chp5-while-guess/chp5-while-guess/chp5-while-guess.cpp | cmacdougald/2020SPRING-ITSE1307 | c7d941deace980fd99dfadcd55518f75b3d20684 | [
"MIT"
] | null | null | null | chp5-while-guess/chp5-while-guess/chp5-while-guess.cpp | cmacdougald/2020SPRING-ITSE1307 | c7d941deace980fd99dfadcd55518f75b3d20684 | [
"MIT"
] | null | null | null | chp5-while-guess/chp5-while-guess/chp5-while-guess.cpp | cmacdougald/2020SPRING-ITSE1307 | c7d941deace980fd99dfadcd55518f75b3d20684 | [
"MIT"
] | null | null | null | // chp5-while-guess.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <cstdlib>
int main()
{
srand(time(0));
int intMAXNUMBER = 100;
int intRandomNumber = rand() % intMAXNUMBER + 1;
int intGuess = 0;
do {
std::cerr << "N: " << intRandomNumber << std::endl;
std::cout << "Please enter a number between 1 and " << intMAXNUMBER << ": ";
std::cin >> intGuess;
if (intGuess > intRandomNumber) {
std::cout << "You guessed too high..." << std::endl;
}
else if (intGuess < intRandomNumber) {
std::cout << "You guessed too low..." << std::endl;
}
else {
std::cout << "Congrats!" << std::endl;
}
} while (intGuess != intRandomNumber);
return 0;
}
| 20.589744 | 79 | 0.582814 | cmacdougald |
d571bea53f21a1864f150d1350f703b8d1890b7e | 504 | cpp | C++ | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex05-jmurkijanian | f0d5c8a60227cb4eef10241e97e949dc6c9790a2 | [
"MIT"
] | null | null | null | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex05-jmurkijanian | f0d5c8a60227cb4eef10241e97e949dc6c9790a2 | [
"MIT"
] | null | null | null | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex05-jmurkijanian | f0d5c8a60227cb4eef10241e97e949dc6c9790a2 | [
"MIT"
] | null | null | null | // Random Rectangle
#include <iostream>
#include <string>
#include <cstdlib>
int main()
{
//Constants, and assigned values
const int MAXHEIGHT = 3;
const int MAX = 40;
unsigned seed = time(0);
srand(seed);
int length = rand();
//Gives length its max value
//the 1 prevents it from outputing nothing
length = rand() % MAX + 1;
//outputs the # rectangle
std::string max;
max.assign(length,'#');
std::cout << max << std::endl;
std::cout << max << std::endl;
std::cout << max << std::endl;
return 0;
}
| 16.8 | 42 | 0.662698 | CSUF-CPSC120-2019F23-24 |
d574a6258fc4c241df7507f6a7598c163eb9dc68 | 8,416 | cc | C++ | src/QSS/path.cc | NREL/SOEP-QSS | 354df458f6eaf13e9f0271eccd747047ab4f0f71 | [
"BSD-3-Clause"
] | 13 | 2017-08-04T15:15:59.000Z | 2022-03-24T06:02:22.000Z | src/QSS/path.cc | NREL/SOEP-QSS | 354df458f6eaf13e9f0271eccd747047ab4f0f71 | [
"BSD-3-Clause"
] | 4 | 2021-08-19T01:56:30.000Z | 2021-08-23T01:41:36.000Z | src/QSS/path.cc | NREL/SOEP-QSS | 354df458f6eaf13e9f0271eccd747047ab4f0f71 | [
"BSD-3-Clause"
] | 1 | 2017-09-15T17:14:57.000Z | 2017-09-15T17:14:57.000Z | // QSS Solver Path Functions
//
// Project: QSS Solver
//
// Developed by Objexx Engineering, Inc. (https://objexx.com) under contract to
// the National Renewable Energy Laboratory of the U.S. Department of Energy
//
// Copyright (c) 2017-2021 Objexx Engineering, Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES
// GOVERNMENT, 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.
// QSS Headers
#include <QSS/path.hh>
#include <QSS/string.hh>
// C++ Headers
#include <cctype>
#include <regex>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
#include <direct.h>
#include <errno.h>
#else
#include <sys/errno.h>
#endif
#ifdef _WIN32
#ifndef S_ISREG
#define S_ISREG(mode) (((mode)&S_IFMT)==S_IFREG)
#endif
#ifdef _WIN64
#define stat _stat64
#else
#define stat _stat
#endif
#endif
namespace QSS {
namespace path {
// Globals
#ifdef _WIN32
char const sep( '\\' );
std::string const tmp( std::getenv( "TEMP" ) != nullptr ? std::getenv( "TEMP" ) : "." );
#else
char const sep( '/' );
std::string const tmp( "/tmp" );
#endif
// Is Name a File?
bool
is_file( std::string const & name )
{
if ( name.empty() ) return false;
struct stat stat_buf;
#ifdef _WIN32
return ( ( stat( name.c_str(), &stat_buf ) == 0 ) && S_ISREG( stat_buf.st_mode ) && ( stat_buf.st_mode & _S_IREAD ) );
#else
return ( ( stat( name.c_str(), &stat_buf ) == 0 ) && S_ISREG( stat_buf.st_mode ) && ( stat_buf.st_mode & S_IRUSR ) );
#endif
}
// Base Name
std::string
base( std::string const & path )
{
std::size_t ibeg( path.rfind( sep ) );
if ( ibeg == std::string::npos ) {
ibeg = 0;
} else {
++ibeg;
}
std::string const name( path, ibeg, path.length() - ibeg );
std::size_t const idot( name.rfind( '.' ) );
if ( idot == std::string::npos ) {
return name;
} else {
return name.substr( 0u, idot );
}
}
// Directory Name
std::string
dir( std::string const & path )
{
std::size_t l( path.length() ); // Length to search up to
while ( ( l > 0u ) && ( path[ l - 1 ] == sep ) ) --l; // Skip trailing path separators
while ( ( l > 0u ) && ( path[ l - 1 ] != sep ) ) --l; // Skip dir/file name
if ( ( l > 0u ) && ( path[ l - 1 ] == sep ) ) --l; // Skip trailing path separator
if ( l > 0u ) {
return path.substr( 0u, l );
} else {
return std::string( "." );
}
}
// Make a Directory
bool
make_dir( std::string const & dir )
{
#ifdef _WIN32
#ifdef __MINGW32__
return ( ( mkdir( dir.c_str() ) == 0 ) || ( errno == EEXIST ) );
#else
return ( ( _mkdir( dir.c_str() ) == 0 ) || ( errno == EEXIST ) );
#endif
#else
return ( ( mkdir( dir.c_str(), S_IRWXU ) == 0 ) || ( errno == EEXIST ) );
#endif
}
// Make a Path
bool
make_path( std::string const & path )
{
#ifdef _WIN32
// Find the starting position
if ( path.empty() ) return false;
std::string::size_type i( 0 );
std::string::size_type const path_len( path.length() );
if ( path_len >= 2 ) {
if ( ( isalpha( path[ 0 ] ) ) && ( path[ 1 ] == ':' ) ) { // X:
i = 2;
}
}
if ( i < path_len ) i = path.find_first_not_of( ".\\/", i );
// Create the directories of the path
if ( ( i < path_len ) && ( i != std::string::npos ) ) {
while ( ( i = path.find_first_of( "\\/", i ) ) != std::string::npos ) {
if ( i + 1 == path.length() ) { // Last directory
return make_dir( path.substr( 0u, i ) );
} else if ( ! make_dir( path.substr( 0u, i ) ) ) { // Failed
return false;
}
++i;
}
return make_dir( path ); // One more directory
} else { // Nothing to do
return true;
}
#else
// Find the starting position
if ( path.empty() ) return false;
std::string::size_type i( path.find_first_not_of( "./" ) );
std::string::size_type const path_len( path.length() );
// Create the directories of the path
if ( ( i < path_len ) && ( i != std::string::npos ) ) {
while ( ( i = path.find_first_of( "/", i ) ) != std::string::npos ) {
if ( i + 1 == path.length() ) { // Last directory
return make_dir( path.substr( 0u, i ) );
} else if ( ! make_dir( path.substr( 0u, i ) ) ) { // Failed
return false;
}
++i;
}
return make_dir( path ); // One more directory
} else { // Nothing to do
return true;
}
#endif
}
// URI of a Path
std::string
uri( std::string const & path )
{
std::string uri;
for ( char c : path ) {
switch ( c ) {
case '%':
uri += "%25";
break;
case ' ':
uri += "%20";
break;
case '!':
uri += "%21";
break;
case '#':
uri += "%23";
break;
case '$':
uri += "%24";
break;
case '&':
uri += "%26";
break;
case '\'':
uri += "%27";
break;
case '(':
uri += "%28";
break;
case ')':
uri += "%29";
break;
case '*':
uri += "%2A";
break;
case '+':
uri += "%2B";
break;
case ',':
uri += "%2C";
break;
case ':':
uri += "%3A";
break;
case ';':
uri += "%3B";
break;
case '=':
uri += "%3D";
break;
case '?':
uri += "%3F";
break;
case '@':
uri += "%40";
break;
case '[':
uri += "%5B";
break;
case ']':
uri += "%5D";
break;
case '^':
uri += "%5E";
break;
case '`':
uri += "%60";
break;
case '{':
uri += "%7B";
break;
case '}':
uri += "%7D";
break;
#ifdef _WIN32
case '\\':
uri += '/';
break;
#endif
default:
uri += c;
break;
}
}
return uri;
}
// Path of a URI
std::string
un_uri( std::string const & uri )
{
std::string path( uri );
if ( has_prefix( path, "file://" ) ) path.erase( 0, 7 );
path = std::regex_replace( path, std::regex( "%20" ), " " );
path = std::regex_replace( path, std::regex( "%21" ), "!" );
path = std::regex_replace( path, std::regex( "%23" ), "#" );
path = std::regex_replace( path, std::regex( "%24" ), "$" );
path = std::regex_replace( path, std::regex( "%26" ), "&" );
path = std::regex_replace( path, std::regex( "%27" ), "'" );
path = std::regex_replace( path, std::regex( "%28" ), "(" );
path = std::regex_replace( path, std::regex( "%29" ), ")" );
path = std::regex_replace( path, std::regex( "%2A" ), "*" );
path = std::regex_replace( path, std::regex( "%2B" ), "+" );
path = std::regex_replace( path, std::regex( "%2C" ), "," );
path = std::regex_replace( path, std::regex( "%3A" ), ":" );
path = std::regex_replace( path, std::regex( "%3B" ), ";" );
path = std::regex_replace( path, std::regex( "%3D" ), "=" );
path = std::regex_replace( path, std::regex( "%3F" ), "?" );
path = std::regex_replace( path, std::regex( "%40" ), "@" );
path = std::regex_replace( path, std::regex( "%5B" ), "[" );
path = std::regex_replace( path, std::regex( "%5D" ), "]" );
path = std::regex_replace( path, std::regex( "%5E" ), "^" );
path = std::regex_replace( path, std::regex( "%60" ), "`" );
path = std::regex_replace( path, std::regex( "%7B" ), "{" );
path = std::regex_replace( path, std::regex( "%7D" ), "}" );
#ifdef _WIN32
path = std::regex_replace( path, std::regex( "/" ), "\\" );
#endif
path = std::regex_replace( path, std::regex( "%25" ), "%" );
return path;
}
} // path
} // QSS
| 26.71746 | 119 | 0.591492 | NREL |
d57679da5d03f5b03da8d7023103602798dd54cb | 3,242 | cpp | C++ | CP-Algorithms/Algebra/2_Prime numbers/1_spoj_BSPRIME - Binary Sequence of Prime Number.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | 5 | 2021-02-14T17:48:21.000Z | 2022-01-24T14:29:44.000Z | CP-Algorithms/Algebra/2_Prime numbers/1_spoj_BSPRIME - Binary Sequence of Prime Number.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | CP-Algorithms/Algebra/2_Prime numbers/1_spoj_BSPRIME - Binary Sequence of Prime Number.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
/// Segmented Sieve
/// Description: Simple sieve of Eratosthenes with few optimizations.
/// It generates primes below 10^9
/// Tutorial Link: https://github.com/kimwalisch/primesieve/wiki/Segmented-sieve-of-Eratosthenes
///set your CPU's L1 cache size(in bytes)
const int64_t L1D_CACHE_SIZE = 32768;
//to store primes
int64_t ppprimes[9000000], nPrime;
int64_t binary[150000009];
///Generate primes using the segmented sieve of Eratosthenes.
///This algorithm uses O(n log log n) operations and O(sqrt(n)) space.
///@param limit Sieve primes <= limit.
void segmented_sieve(int64_t limit){
int64_t sqrtt = (int64_t) sqrt(limit);
int64_t segment_size = max(sqrtt, L1D_CACHE_SIZE);
int64_t count = (limit<2) ? 0 : 1;
///we sieve primes >= 3
int64_t i = 3;
int64_t n = 3;
int64_t s = 3;
vector<char> sieve(segment_size);
vector<char> is_prime(sqrtt + 1, true);
vector<int64_t> primes;
vector<int64_t> multiples;
ppprimes[nPrime++] = 2;
for(int64_t low = 0; low<=limit; low+=segment_size) {
fill(sieve.begin(), sieve.end(), true);
///current segment = [low, high]
int64_t high = low + segment_size - 1;
high = min(high, limit);
///generate sieving primes using simple sieve of Eratosthenes
for(; i*i<=high; i+=2){
if(is_prime[i]){
for(int64_t j = i*i; j<=sqrtt; j+=i){
is_prime[j] = false;
}
}
}
///initialize sieving primes for segmented sieve
for(; s*s<=high; s+=2){
if(is_prime[s]){
primes.push_back(s);
multiples.push_back(s*s - low);
}
}
///sieve the current segment
for(size_t i=0;i<primes.size();i++){
int64_t j = multiples[i];
for(int64_t k = primes[i]*2; j<segment_size; j+=k){
sieve[j] = false;
}
multiples[i] = j - segment_size;
}
for(; n<=high; n+=2){
if(sieve[n-low]) {/// n is prime
ppprimes[nPrime++] = n;
//pprimes.emplace_back(n);
count++;
//if(count%500==1) printf("%ld\n", n);
}
}
}
//printf("%ld primes found.\n", count);
}
int64_t cnt =0;
void preCalculate(){
int64_t idx=1;
for(int64_t i=0;i<nPrime;i++){
int x = ppprimes[i];
//cout<<x<<" ";
/*
while(x>0){ ///this will count 2->01
int y = x&1 ///3->11
//cout<<y; ///5->101 7->111 11->1011 which is worng
if(y==1) cnt++;
binary[idx++] = cnt;
x = x>>1;
}
//cout<<endl;
*/
int flag = 0;
for(int j=0;j<32;j++){ ///Here is the main ninja techinque
if(x<0){
cnt++;
binary[idx++] = cnt;
flag = 1;
}
else if(flag) {
binary[idx++] = cnt;
}
//cout<<x;
x = x<<1;
}
//cout<<endl;
//cout<<binary[1]<<endl;
//cout<<binary[2]<<endl;
//cout<<binary[3]<<endl;
//cout<<binary[4]<<endl;
//printf("%lld ",cnt);
}
//printf("idx = %ld\n nPrime=%lld\ncnt=%d", idx, nPrime, cnt);
}
int main(int argc, char** argv){
if(argc>=2) {
segmented_sieve(atoll(argv[1]));
}
else {
segmented_sieve(101865020);
}
//cout<<"Completed"<<endl;
preCalculate();
//cout<<"Completed2"<<endl;
unsigned t, n;
cin>>t;
while(t--){
cin>>n;
if(n==0) printf("0\n");
else if(n==1) printf("1\n");
else printf("%u\n", binary[n]);
}
return 0;
}
| 19.768293 | 96 | 0.592535 | Sowmik23 |
d5775ec94f6960c8745c9549f9b4bf7147d02b6e | 730 | hpp | C++ | libs/gui/impl/include/sge/gui/impl/make_container_pair.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/gui/impl/include/sge/gui/impl/make_container_pair.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/gui/impl/include/sge/gui/impl/make_container_pair.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_GUI_IMPL_MAKE_CONTAINER_PAIR_HPP_INCLUDED
#define SGE_GUI_IMPL_MAKE_CONTAINER_PAIR_HPP_INCLUDED
#include <sge/gui/impl/swap_pair.hpp>
#include <sge/gui/widget/reference_alignment_pair.hpp>
#include <sge/gui/widget/reference_alignment_vector.hpp>
namespace sge::gui::impl
{
sge::gui::widget::reference_alignment_vector make_container_pair(
sge::gui::widget::reference_alignment_pair const &,
sge::gui::widget::reference_alignment_pair const &,
sge::gui::impl::swap_pair);
}
#endif
| 30.416667 | 65 | 0.761644 | cpreh |
d57b2e18c1af91ea67aa92a11bb3c0f1c6580aa9 | 3,416 | cpp | C++ | src/graphics/vulkan/descriptor_init.cpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | src/graphics/vulkan/descriptor_init.cpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | src/graphics/vulkan/descriptor_init.cpp | InspectorSolaris/nd-engine | a8d63fe4bc0e57a96317adf015534d2e779ffcbb | [
"WTFPL"
] | null | null | null | #include "descriptor_init.hpp"
#include "tools_runtime.hpp"
namespace nd::src::graphics::vulkan
{
using namespace nd::src::tools;
DescriptorPool
createDescriptorPool(opt<const DescriptorPoolCfg>::ref cfg, const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
const auto createInfo = VkDescriptorPoolCreateInfo {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = cfg.next,
.flags = cfg.flags,
.maxSets = cfg.maxSets,
.poolSizeCount = static_cast<u32>(cfg.sizes.size()),
.pPoolSizes = cfg.sizes.data()};
VkDescriptorPool descriptorPool;
ND_VK_ASSERT(vkCreateDescriptorPool(device, &createInfo, ND_VK_ALLOCATION_CALLBACKS, &descriptorPool));
return descriptorPool;
}
DescriptorSetLayout
createDescriptorSetLayout(opt<const DescriptorSetLayoutCfg>::ref cfg, const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
const auto createInfo = VkDescriptorSetLayoutCreateInfo {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = cfg.next,
.flags = cfg.flags,
.bindingCount = static_cast<u32>(cfg.bindings.size()),
.pBindings = cfg.bindings.data()};
VkDescriptorSetLayout descriptorSetLayout;
ND_VK_ASSERT(vkCreateDescriptorSetLayout(device, &createInfo, ND_VK_ALLOCATION_CALLBACKS, &descriptorSetLayout));
return descriptorSetLayout;
}
DescriptorSetLayoutObjects
createDescriptorSetLayoutObjects(opt<const DescriptorSetLayoutObjectsCfg>::ref cfg, const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
return {.mesh = createDescriptorSetLayout(cfg.mesh, device)};
}
vec<DescriptorSet>
allocateDescriptorSets(opt<const DescriptorSetCfg>::ref cfg,
opt<const DescriptorPool>::ref descriptorPool,
const VkDevice device) noexcept(ND_VK_ASSERT_NOTHROW)
{
ND_SET_SCOPE();
const auto allocateInfo = VkDescriptorSetAllocateInfo {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = cfg.next,
.descriptorPool = descriptorPool,
.descriptorSetCount = static_cast<u32>(cfg.layouts.size()),
.pSetLayouts = cfg.layouts.data()};
auto descriptorSets = vec<DescriptorSet>(cfg.layouts.size());
ND_VK_ASSERT(vkAllocateDescriptorSets(device, &allocateInfo, descriptorSets.data()));
return descriptorSets;
}
} // namespace nd::src::graphics::vulkan
| 46.794521 | 141 | 0.53103 | InspectorSolaris |
d57e24cab5c502dd7faa514aa18dac25dd49dce5 | 4,651 | hh | C++ | include/click/statvector.hh | MassimoGirondi/fastclick | 71b9a3392c2e847a22de3c354be1d9f61216cb5b | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | include/click/statvector.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | include/click/statvector.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | // -*- c-basic-offset: 4 -*-
#ifndef CLICK_STATVECTOR_HH
#define CLICK_STATVECTOR_HH
#include <click/batchelement.hh>
#include <click/multithread.hh>
#include <click/vector.hh>
#include <click/straccum.hh>
#include <click/statvector.hh>
CLICK_DECLS
template <typename T>
class StatVector {
enum{H_MEDIAN,H_AVERAGE,H_DUMP,H_MAX_OBS,H_N_OBS,H_NZ,H_MAX,H_MAX_OBS_VAL};
static String read_handler(Element *e, void *thunk)
{
StatVector *fd = (StatVector*)e->cast("StatVector");
switch ((intptr_t)thunk) {
case H_MAX:
case H_NZ:
case H_MAX_OBS: {
Vector<T> sums(fd->stats.get_value(0).size(),0);
T max_batch_v = -1;
int max_batch_index = -1;
int max_nz = -1;
int nz=0;
for (unsigned j = 0; j < sums.size(); j++) {
for (unsigned i = 0; i < fd->stats.weight(); i++) {
sums[j] += fd->stats.get_value(i)[j];
}
if (sums[j] > max_batch_v) {
max_batch_v = sums[j];
max_batch_index = j;
}
if (sums[j] > 0) {
max_nz = j;
nz++;
}
}
if ((intptr_t)thunk == H_MAX) {
return String(max_nz);
} else if ((intptr_t)thunk == H_NZ) {
return String(nz);
} else
return String(max_batch_index);
}
case H_N_OBS:
case H_MEDIAN: {
Vector<T> sums(fd->stats.get_value(0).size(),0);
T total = 0;
for (unsigned j = 0; j < sums.size(); j++) {
for (unsigned i = 0; i < fd->stats.weight(); i++) {
sums[j] += fd->stats.get_value(i)[j];
}
total += sums[j];
}
if ((intptr_t)thunk == H_N_OBS)
return String(total);
T val = 0;
for (int i = 0; i < sums.size(); i++) {
val += sums[i];
if (val > total/2)
return String(i);
}
return "0";
}
case H_AVERAGE: {
int count = 0;
int total = 0;
for (unsigned i = 0; i < fd->stats.weight(); i++) {
for (unsigned j = 0; j < (unsigned)fd->stats.get_value(i).size(); j++) {
total += fd->stats.get_value(i)[j] * j;
count += fd->stats.get_value(i)[j];
}
}
if (count > 0)
return String((double)total/(double)count);
else
return String(0);
}
case H_DUMP: {
StringAccum s;
Vector<T> sums(fd->stats.get_value(0).size(),0);
for (unsigned i = 0; i < fd->stats.weight(); i++) {
for (unsigned j = 0; j < (unsigned)fd->stats.get_value(i).size(); j++) {
sums[j] += fd->stats.get_value(i)[j];
if (i == fd->stats.weight() - 1 && sums[j] != 0)
s << j << ": " << sums[j] << "\n";
}
}
return s.take_string();
}
default:
return "<error>";
}
}
protected:
per_thread<Vector<T>> stats;
StatVector() {
}
StatVector(Vector<T> v) : stats(v) {
}
void add_stat_handler(Element* e) {
//Value the most seen (gives the value)
e->add_read_handler("most_seen", read_handler, H_MAX_OBS, Handler::f_expensive);
//Value the most seen (gives the frequency of the value)
e->add_read_handler("most_seen_freq", read_handler, H_MAX_OBS_VAL, Handler::f_expensive);
//Maximum value seen
e->add_read_handler("max", read_handler, H_MAX, Handler::f_expensive);
//Number of observations
e->add_read_handler("count", read_handler, H_N_OBS, Handler::f_expensive);
//Number of values that had at least one observations
e->add_read_handler("nval", read_handler, H_NZ, Handler::f_expensive);
//Value for the median number of observations
e->add_read_handler("median", read_handler, H_MEDIAN, Handler::f_expensive);
//Average of value*frequency
e->add_read_handler("average", read_handler, H_AVERAGE, Handler::f_expensive);
e->add_read_handler("avg", read_handler, H_AVERAGE, Handler::f_expensive);
//Dump all value: frequency
e->add_read_handler("dump", read_handler, H_DUMP, Handler::f_expensive);
}
};
CLICK_ENDDECLS
#endif //CLICK_STATVECTOR_HH
| 34.198529 | 97 | 0.500538 | MassimoGirondi |
d584b2a3b2b7bd95119bdae50d731d8a1e083a75 | 1,175 | cpp | C++ | solutions/LeetCode/C++/908.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/908.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/908.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 8 ms submission
class Solution {
public:
int smallestRangeI(vector<int>& A, int K) {
const int mx = *max_element(A.begin(), A.end());
const int mn = *min_element(A.begin(), A.end());
if (mx - K <= mn + K)
return 0;
return mx - K - (mn + K);
}
};
auto ___ = []() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
__________________________________________________________________________________________________
sample 9864 kb submission
class Solution {
public:
int smallestRangeI(vector<int>& A, int K) {
if(A.size()<2)
return 0;
int min = INT_MAX;
int max = INT_MIN;
for(int i = 0;i<A.size();i++){
if(min>A[i])
min = A[i];
if(max<A[i])
max = A[i];
}
if((max-K)<=(min+K))
return 0;
else
return (max-K)-(min+K);
}
};
__________________________________________________________________________________________________
| 27.325581 | 98 | 0.593191 | timxor |
d58ac31b2fb6c9ddee3b02c404d400ba910ffed0 | 369 | cpp | C++ | regression/esbmc-cpp/qt/QList/list_contains/main.cpp | vanderson-rocha/esbmc | 45768923a0fe79226feca5581b4d75b0a9f5f741 | [
"BSD-3-Clause"
] | 1 | 2021-02-26T22:03:18.000Z | 2021-02-26T22:03:18.000Z | regression/esbmc-cpp/qt/QList/list_contains/main.cpp | vanderson-rocha/esbmc | 45768923a0fe79226feca5581b4d75b0a9f5f741 | [
"BSD-3-Clause"
] | null | null | null | regression/esbmc-cpp/qt/QList/list_contains/main.cpp | vanderson-rocha/esbmc | 45768923a0fe79226feca5581b4d75b0a9f5f741 | [
"BSD-3-Clause"
] | 1 | 2021-04-15T14:14:27.000Z | 2021-04-15T14:14:27.000Z | #include <iostream>
#include <QList>
#include <QString>
#include <cassert>
using namespace std;
int main ()
{
QList<QString> list;
list << "A" << "B" << "C" << "B" << "A";
assert(list.contains("B"));
assert(list.contains("A"));
assert(list.contains("C"));
//assert(list.indexOf("X") == -1); // returns -1
return 0;
}
| 21.705882 | 62 | 0.528455 | vanderson-rocha |
d58b83add753a6374f7748174e813bee36758f80 | 2,092 | cpp | C++ | StarLight/filewriter.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StarLight/filewriter.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | StarLight/filewriter.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////
//
// Copyright 2010
//
// This file is part of starlight.
//
// starlight 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.
//
// starlight 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 starlight. If not, see <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////////
//
// File and Version Information:
// $Rev:: $: revision of last commit
// $Author: jwebb $: author of last commit
// $Date: 2012/11/27 22:27:31 $: date of last commit
//
// Description:
//
//
//
///////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <exception>
#include <cstdlib>
#include "filewriter.h"
using namespace std;
fileWriter::fileWriter()
: _fileName(""),
_fileStream()
{ }
fileWriter::fileWriter(const string& fileName) :
_fileName(fileName)
,_fileStream(fileName.c_str())
{ }
fileWriter::~fileWriter()
{ }
int fileWriter::open()
{
try
{
_fileStream.open(_fileName.c_str());
}
catch (const ios::failure & error)
{
cerr << "I/O exception: " << error.what() << endl;
return EXIT_FAILURE;
}
return 0;
}
int fileWriter::open(const string& fileName)
{
_fileName = fileName;
return open();
}
int fileWriter::close()
{
try
{
_fileStream.close();
}
catch (const ios::failure & error)
{
cerr << "I/O exception: " << error.what() << endl;
return EXIT_FAILURE;
}
return 0;
}
| 22.021053 | 75 | 0.556883 | klendathu2k |
d58cf4d6b06e06529868f891053a04653fe15275 | 9,457 | hpp | C++ | include/fe/math/Vector3.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | 1 | 2018-06-15T23:49:37.000Z | 2018-06-15T23:49:37.000Z | include/fe/math/Vector3.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | 5 | 2017-04-23T03:25:10.000Z | 2018-02-23T07:48:16.000Z | include/fe/math/Vector3.hpp | TheCandianVendingMachine/TCVM_Flat_Engine | 13797b91f6f4199d569f80baa29e2584652fc4b5 | [
"MIT"
] | null | null | null | // Vector3.hpp
// A 3d vector class used for defining coordinates in space
#pragma once
#include <cmath>
#include <SFML/System/Vector3.hpp>
namespace fe
{
template <typename dataType>
struct Vector3;
template <typename T>
struct lightVector3;
template<typename dataType, typename vectorType>
Vector3<dataType> operator*(const dataType &lhs, Vector3<vectorType> &rhs);
template<typename dataType, typename vectorType>
Vector3<dataType> operator/(const dataType &lhs, Vector3<vectorType> &rhs);
template<typename dataType, typename vectorType>
void operator*=(const dataType &lhs, Vector3<vectorType> &rhs);
template<typename dataType, typename vectorType>
void operator/=(const dataType &lhs, Vector3<vectorType> &rhs);
template <typename dataType>
struct Vector3
{
dataType x;
dataType y;
dataType z;
Vector3() : x(0), y(0), z(0) {}
Vector3(dataType X, dataType Y, dataType Z) : x(X), y(Y), z(Z) {}
Vector3(const Vector3<dataType> ©) : x(copy.x), y(copy.y), z(copy.z) {}
Vector3(const lightVector3<dataType> ©) : x(copy.x), y(copy.y), z(copy.z) {}
Vector3(const sf::Vector3<dataType> ©) : x(copy.x), y(copy.y), z(copy.z) {}
template <typename otherDataType>
Vector3(const Vector3<otherDataType> ©) : x(static_cast<dataType>(copy.x)), y(static_cast<dataType>(copy.y)), z(static_cast<dataType>(copy.z)) {}
template <typename otherDataType>
Vector3(const lightVector3<otherDataType> ©) : x(static_cast<dataType>(copy.x)), y(static_cast<dataType>(copy.y)), z(static_cast<dataType>(copy.z)) {}
template <typename otherDataType>
Vector3(const sf::Vector3<otherDataType> ©) : x(static_cast<dataType>(copy.x)), y(static_cast<dataType>(copy.y)), z(static_cast<dataType>(copy.z)) {}
Vector3 &operator=(const Vector3<dataType> ©) { if (© != this) { x = copy.x; y = copy.y; z = copy.z; } return *this; }
bool operator==(const Vector3<dataType> &rhs) const { return rhs.x == x && rhs.y == y && rhs.y == y; }
Vector3<dataType> operator+(const Vector3<dataType> &rhs) const { return Vector3<dataType>(rhs.x + x, rhs.y + y, rhs.z + z); }
Vector3<dataType> operator-(const Vector3<dataType> &rhs) const { return Vector3<dataType>(x - rhs.x, y - rhs.y, z - rhs.z); }
Vector3<dataType> operator*(const dataType &rhs) const { return Vector3<dataType>(rhs * x, rhs * y, rhs * z); }
Vector3<dataType> operator/(const dataType &rhs) const { return Vector3<dataType>(x / rhs, y / rhs, z / rhs); }
Vector3<dataType> operator-() const { return Vector3<dataType>(-x, -y, -z); }
template<typename T> Vector3<dataType> operator+(const Vector3<T> &rhs) const { return Vector3<dataType>(static_cast<dataType>(rhs.x) + x, static_cast<dataType>(rhs.y) + y, static_cast<dataType>(rhs.z) + z); }
template<typename T> Vector3<dataType> operator-(const Vector3<T> &rhs) const { return Vector3<dataType>(x - static_cast<dataType>(rhs.x), y - static_cast<dataType>(rhs.y), z - static_cast<dataType>(rhs.z)); }
template<typename T> Vector3<dataType> operator*(const T &rhs) const { return Vector3<dataType>(static_cast<dataType>(rhs) * x, static_cast<dataType>(rhs) * y, static_cast<dataType>(rhs) * z); }
template<typename T> Vector3<dataType> operator/(const T &rhs) const { return Vector3<dataType>(x / static_cast<dataType>(rhs), y / static_cast<dataType>(rhs), z / static_cast<dataType>(rhs)); }
// A way to get the x/y coordinate based on the index provided. Useful in incrementing loops
dataType operator[](const size_t &index) const { if (index == 0) return x; if (index == 1) return y; if (index == 2) return z; return 0.f; }
// A way to get the x/y coordinate based on the index provided. Useful in incrementing loops
dataType operator[](const int &index) const { if (index == 0) return x; if (index == 1) return y; if (index == 2) return z; return 0.f; }
void operator+=(const Vector3 &rhs) { x += rhs.x; y += rhs.y; z += rhs.z; }
void operator-=(const Vector3 &rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; }
void operator*=(const dataType &rhs){ x *= rhs; y *= rhs; z *= rhs; }
void operator/=(const dataType &rhs){ x /= rhs; y /= rhs; z /= rhs; }
friend Vector3<dataType> operator*(const dataType &lhs, Vector3<dataType> &rhs);
friend Vector3<dataType> operator/(const dataType &lhs, Vector3<dataType> &rhs);
friend void operator*=(const dataType &lhs, Vector3<dataType> &rhs);
friend void operator/=(const dataType &lhs, Vector3<dataType> &rhs);
float magnitude() const { return std::sqrt(x * x + y * y + z * z); }
float magnitudeSqr() const { return x * x + y * y + z * z; }
Vector3<dataType> normalize() const
{
float mag = magnitude();
if (mag != 0.f)
{
return Vector3<dataType>(x / mag, y / mag, z / mag);
}
return Vector3<dataType>();
}
Vector3<dataType> clamp(float max)
{
// max^3 / (x^3 + y^3) = 3 * Modifier
if (max * max > x * x + y * y + z * z) return *this;
float modifier = std::sqrt((max * max) / (x * x + y * y + z * z));
return modifier < 1.f ? fe::Vector3d(x * modifier, y * modifier, z * modifier) : *this;
}
Vector3<dataType> abs() const { return Vector3(std::abs(x), std::abs(y), std::abs(z)); }
Vector3<dataType> normal() const { return Vector3(-y, x, z); }
float dot(const Vector3<dataType> &other) const { return x * other.x + y * other.y + z * other.z; }
Vector3<dataType> cross(const Vector3<dataType> &other) const { return Vector3<dataType>(y * other.y - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x); }
Vector3<dataType> project(Vector3<dataType> &other) const
{
float mag = other.magnitudeSqr();
if (mag != 0)
{
return Vector3<dataType>(other * (dot(other) / other.magnitudeSqr()));
}
return Vector3();
}
};
// External functions that are useful for Vector operations
template<typename dataType>
Vector3<dataType> lerp(const Vector3<dataType> &a, const Vector3<dataType> &b, const float &percent)
{
return Vector3<dataType>((dataType(1) - percent) * a + (percent * b));
}
template<typename dataType, typename vectorType>
Vector3<dataType> fe::operator*(const dataType &lhs, Vector3<vectorType> &rhs)
{
return rhs * lhs;
}
template<typename dataType, typename vectorType>
Vector3<dataType> fe::operator/(const dataType &lhs, Vector3<vectorType> &rhs)
{
return rhs / lhs;
}
template<typename dataType, typename vectorType>
void fe::operator*=(const dataType &lhs, Vector3<vectorType> &rhs)
{
rhs *= lhs;
}
template<typename dataType, typename vectorType>
void fe::operator/=(const dataType &lhs, Vector3<vectorType> &rhs)
{
rhs /= lhs;
}
template<typename T>
struct lightVector3
{
T x;
T y;
T z;
lightVector3() : x(T()), y(T()), z(T()) {}
lightVector3(T x, T y, T z) : x(x), y(y), z(z) {}
lightVector3(const fe::Vector3<T> ©) : x(copy.x), y(copy.y), z(copy.z) {}
lightVector3<T> operator-(const lightVector3<T> &rhs) { return fe::lightVector3<T>(x - rhs.x, y - rhs.y, z - rhs.z); }
lightVector3<T> operator+(const lightVector3<T> &rhs) { return fe::lightVector3<T>(x + rhs.x, y + rhs.y, z + rhs.z); }
lightVector3<T> operator-(const fe::Vector3<T> &rhs) { return fe::lightVector3<T>(x - rhs.x, y - rhs.y, z - rhs.z); }
lightVector3<T> operator+(const fe::Vector3<T> &rhs) { return fe::lightVector3<T>(x + rhs.x, y + rhs.y, z + rhs.z); }
lightVector2<T> operator*(T rhs) { return fe::lightVector2<T>(x * rhs, y * rhs, z * rhs); }
lightVector2<T> operator/(T rhs) { return fe::lightVector2<T>(x / rhs, y / rhs, z / rhs); }
};
typedef lightVector3<float> lightVector3d;
typedef Vector3<float> Vector3d;
}
| 55.629412 | 227 | 0.538754 | TheCandianVendingMachine |
d58d16e90aea0760422135219f8e4764a4605170 | 6,152 | hh | C++ | include/psp/libos/su/DispatchSu.hh | maxdml/Pers-phone | 510833b934e9df916d2f9f5b243d7e530a353840 | [
"Apache-2.0"
] | 2 | 2021-11-13T03:31:33.000Z | 2022-02-20T16:08:50.000Z | include/psp/libos/su/DispatchSu.hh | maxdml/psp | 510833b934e9df916d2f9f5b243d7e530a353840 | [
"Apache-2.0"
] | null | null | null | include/psp/libos/su/DispatchSu.hh | maxdml/psp | 510833b934e9df916d2f9f5b243d7e530a353840 | [
"Apache-2.0"
] | null | null | null | #ifndef DISPATCH_SU_H_
#define DISPATCH_SU_H_
#include <arpa/inet.h>
#include <psp/libos/persephone.hh>
#include <psp/libos/Request.hh>
#include <fstream>
#define MAX_CLIENTS 64
#define RESA_SAMPLES_NEEDED 5e4
#define UPDATE_PERIOD 5 * 1e3 //5 usec
#define MAX_WINDOWS 8192
struct profiling_windows {
uint64_t tsc_start;
uint64_t tsc_end;
uint64_t count;
double mean_ns;
uint64_t qlen[MAX_TYPES];
uint64_t counts[MAX_TYPES];
uint32_t group_res[MAX_TYPES];
uint32_t group_steal[MAX_TYPES];
bool do_update;
};
class Dispatcher : public Worker {
/* Dispatch mode */
public: enum dispatch_mode {
DFCFS = 0,
CFCFS,
SJF,
DARC,
EDF,
UNKNOWN
};
public: const char *dp_str[6] = {
"DFCFS",
"CFCFS",
"SJF",
"DARC",
"EDF",
"UNKNOWN"
};
public: static enum dispatch_mode str_to_dp(std::string const &dp) {
if (dp == "CFCFS") {
return dispatch_mode::CFCFS;
} else if (dp == "DFCFS") {
return dispatch_mode::DFCFS;
} else if (dp == "SJF") {
return dispatch_mode::SJF;
} else if (dp == "DARC") {
return dispatch_mode::DARC;
} else if (dp == "EDF") {
return dispatch_mode::EDF;
}
return dispatch_mode::UNKNOWN;
}
public: enum dispatch_mode dp;
// peer ID -> number of "compute slot" available (max= max batch size)
public: uint32_t free_peers = 0; // a bitmask of free workers
private: uint8_t last_peer = 0;
public: RequestType *rtypes[static_cast<int>(ReqType::LAST)];
public: uint32_t n_rtypes;
public: uint32_t type_to_nsorder[static_cast<int>(ReqType::LAST)];
public: uint64_t num_rcvd = 0; /** < Total number of received requests */
private: uint32_t n_drops = 0;
private: uint32_t num_dped = 0;
private: uint64_t peer_dpt_tsc[MAX_WORKERS]; // Record last time we dispatched to a peer
public: uint32_t n_workers = 0;
// DARC parameters
public: uint32_t n_resas;
public: uint32_t n_groups = 0;
public: TypeGroups groups[MAX_TYPES];
private: float delta = 0.2; // Similarity factor
public: bool first_resa_done;
public: bool dynamic;
public: uint32_t update_frequency;
public: profiling_windows windows[MAX_WINDOWS];
private: uint32_t prev_active;
private: uint32_t n_windows = 0;
public: uint32_t spillway = 0;
public: int set_darc();
private: int update_darc();
private: int drain_queue(RequestType *&rtype);
private: int dyn_resa_drain_queue(RequestType *&rtype);
private: int dequeue(unsigned long *payload);
private: int setup() override;
private: int work(int status, unsigned long payload) override;
private: int process_request(unsigned long req) override;
public: int signal_free_worker(int peer_id, unsigned long type);
public: int enqueue(unsigned long req, uint64_t cur_tsc);
public: int dispatch();
private: inline int push_to_rqueue(unsigned long req, RequestType *&rtype, uint64_t cur_tsc);
public: void set_dp(std::string &policy) {
dp = Dispatcher::str_to_dp(policy);
}
public: Dispatcher() : Worker(WorkerType::DISPATCH) {
if (cycles_per_ns == 0)
PSP_WARN("Dispatcher set before system TSC was calibrated. DARC update frequency likely 0.");
update_frequency = UPDATE_PERIOD * cycles_per_ns;
}
public: Dispatcher(int worker_id) : Worker(WorkerType::DISPATCH, worker_id) {
if (cycles_per_ns == 0)
PSP_WARN("Dispatcher set before system TSC was calibrated. DARC update frequency likely 0.");
update_frequency = UPDATE_PERIOD * cycles_per_ns;
}
public: ~Dispatcher() {
PSP_INFO(
"Nested dispatcher received " << num_rcvd << " (" << n_batchs_rcvd << " batches)"
<< " dispatched " << num_dped << " but dropped " << n_drops << " requests"
);
PSP_INFO("Latest windows count: " << windows[n_windows].count << ". Performed " << n_windows << " updates.");
for (uint32_t i = 0; i < n_rtypes; ++i) {
PSP_INFO(
"[" << req_type_str[static_cast<int>(rtypes[i]->type)] << "] has "
<< rtypes[i]->rqueue_head - rtypes[i]->rqueue_tail << " pending items"
);
PSP_INFO(
"[" << req_type_str[static_cast<int>(rtypes[i]->type)] << "] average ns: "
<< rtypes[i]->windows_mean_ns / cycles_per_ns
);
delete rtypes[i];
}
PSP_INFO(
"[" << req_type_str[static_cast<int>(rtypes[type_to_nsorder[0]]->type)] << "] has "
<< rtypes[type_to_nsorder[0]]->rqueue_head - rtypes[type_to_nsorder[0]]->rqueue_tail
<< " pending items"
);
delete rtypes[type_to_nsorder[0]];
if (dp == DARC) {
// Record windows statistics
std::string path = generate_log_file_path(label, "server/windows");
std::cout << "dpt log at " << path << std::endl;
std::ofstream output(path);
if (not output.is_open()) {
PSP_ERROR("COULD NOT OPEN " << path);
} else {
output << "ID\tSTART\tEND\tGID\tRES\tSTEAL\tCOUNT\tUPDATED\tQLEN" << std::endl;
for (size_t i = 0; i < n_windows; ++i) {
auto &w = windows[i];
for (size_t j = 0; j < n_rtypes; ++j) {
output << i << "\t" << std::fixed << w.tsc_start / cycles_per_ns
<< "\t" << std::fixed << w.tsc_end / cycles_per_ns
<< "\t" << j
<< "\t" << w.group_res[j] << "\t" << w.group_steal[j]
<< "\t" << w.counts[j] << "\t" << w.do_update
<< "\t" << w.qlen[j]
<< std::endl;
}
}
output.close();
}
}
}
};
#endif //DISPATCH_SU_H_
| 36.402367 | 117 | 0.569083 | maxdml |
d58dd7f3a1204eb9d22da7e5177c8675650ed515 | 25,637 | cc | C++ | chromeos/services/assistant/assistant_manager_service_impl_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/services/assistant/assistant_manager_service_impl_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/services/assistant/assistant_manager_service_impl_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/assistant/assistant_manager_service_impl.h"
#include <utility>
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/test/bind_test_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/values.h"
#include "chromeos/assistant/internal/internal_util.h"
#include "chromeos/assistant/internal/test_support/fake_alarm_timer_manager.h"
#include "chromeos/assistant/internal/test_support/fake_assistant_manager.h"
#include "chromeos/assistant/internal/test_support/fake_assistant_manager_internal.h"
#include "chromeos/dbus/power/fake_power_manager_client.h"
#include "chromeos/services/assistant/assistant_manager_service.h"
#include "chromeos/services/assistant/public/cpp/features.h"
#include "chromeos/services/assistant/public/mojom/assistant.mojom.h"
#include "chromeos/services/assistant/service_context.h"
#include "chromeos/services/assistant/test_support/fake_assistant_manager_service_delegate.h"
#include "chromeos/services/assistant/test_support/fake_client.h"
#include "chromeos/services/assistant/test_support/fake_service_context.h"
#include "chromeos/services/assistant/test_support/fully_initialized_assistant_state.h"
#include "chromeos/services/assistant/test_support/mock_assistant_interaction_subscriber.h"
#include "chromeos/services/assistant/test_support/mock_media_manager.h"
#include "libassistant/shared/internal_api/assistant_manager_internal.h"
#include "libassistant/shared/public/assistant_manager.h"
#include "services/media_session/public/mojom/media_session.mojom-shared.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace assistant {
using media_session::mojom::MediaSessionAction;
using testing::ElementsAre;
using testing::StrictMock;
using CommunicationErrorType = AssistantManagerService::CommunicationErrorType;
using UserInfo = AssistantManagerService::UserInfo;
namespace {
const char* kNoValue = FakeAssistantManager::kNoValue;
// Action CloneArg<k>(pointer) clones the k-th (0-based) argument of the mock
// function to *pointer. This is analogous to testing::SaveArg<k> except it uses
// mojo::Clone to support mojo types.
//
// Example usage:
// std::vector<MyMojoPtr> ptrs;
// EXPECT_CALL(my_mock, MyMethod(_)).WillOnce(CloneArg<0>(&ptrs));
ACTION_TEMPLATE(CloneArg,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(pointer)) {
*pointer = mojo::Clone(::std::get<k>(args));
}
#define EXPECT_STATE(_state) \
EXPECT_EQ(_state, assistant_manager_service()->GetState());
// Adds an AlarmTimerEvent of the given |type| to |events|.
static void AddAlarmTimerEvent(
std::vector<assistant_client::AlarmTimerEvent>& events,
assistant_client::AlarmTimerEvent::Type type) {
events.push_back(assistant_client::AlarmTimerEvent());
events.back().type = type;
}
// Adds an AlarmTimerEvent of type TIMER with the given |state| to |events|.
static void AddTimerEvent(
std::vector<assistant_client::AlarmTimerEvent>& events,
assistant_client::Timer::State state) {
AddAlarmTimerEvent(events, assistant_client::AlarmTimerEvent::TIMER);
events.back().timer_data.state = state;
}
// Return the list of all libassistant error codes that are considered to be
// authentication errors. This list is created on demand as there is no clear
// enum that defines these, and we don't want to hard code this list in the
// test.
static std::vector<int> GetAuthenticationErrorCodes() {
const int kMinErrorCode = GetLowestErrorCode();
const int kMaxErrorCode = GetHighestErrorCode();
std::vector<int> result;
for (int code = kMinErrorCode; code <= kMaxErrorCode; ++code) {
if (IsAuthError(code))
result.push_back(code);
}
return result;
}
// Return a list of some libassistant error codes that are not considered to be
// authentication errors. Note we do not return all such codes as there are
// simply too many and testing them all significantly slows down the tests.
static std::vector<int> GetNonAuthenticationErrorCodes() {
return {-99999, 0, 1};
}
class FakeAssistantClient : public FakeClient {
public:
FakeAssistantClient() = default;
void RequestBatteryMonitor(
mojo::PendingReceiver<device::mojom::BatteryMonitor> receiver) override {}
private:
DISALLOW_COPY_AND_ASSIGN(FakeAssistantClient);
};
class AssistantAlarmTimerControllerMock
: public ash::mojom::AssistantAlarmTimerController {
public:
AssistantAlarmTimerControllerMock() = default;
AssistantAlarmTimerControllerMock(const AssistantAlarmTimerControllerMock&) =
delete;
AssistantAlarmTimerControllerMock& operator=(
const AssistantAlarmTimerControllerMock&) = delete;
~AssistantAlarmTimerControllerMock() override = default;
// ash::mojom::AssistantAlarmTimerController:
MOCK_METHOD(void,
OnTimerStateChanged,
(std::vector<ash::mojom::AssistantTimerPtr>),
(override));
};
class CommunicationErrorObserverMock
: public AssistantManagerService::CommunicationErrorObserver {
public:
CommunicationErrorObserverMock() = default;
~CommunicationErrorObserverMock() override = default;
MOCK_METHOD(void,
OnCommunicationError,
(AssistantManagerService::CommunicationErrorType error));
private:
DISALLOW_COPY_AND_ASSIGN(CommunicationErrorObserverMock);
};
class StateObserverMock : public AssistantManagerService::StateObserver {
public:
StateObserverMock() = default;
~StateObserverMock() override = default;
MOCK_METHOD(void, OnStateChanged, (AssistantManagerService::State new_state));
private:
DISALLOW_COPY_AND_ASSIGN(StateObserverMock);
};
class AssistantManagerServiceImplTest : public testing::Test {
public:
AssistantManagerServiceImplTest() = default;
~AssistantManagerServiceImplTest() override = default;
void SetUp() override {
PowerManagerClient::InitializeFake();
FakePowerManagerClient::Get()->SetTabletMode(
PowerManagerClient::TabletMode::OFF, base::TimeTicks());
mojo::PendingRemote<device::mojom::BatteryMonitor> battery_monitor;
assistant_client_.RequestBatteryMonitor(
battery_monitor.InitWithNewPipeAndPassReceiver());
shared_url_loader_factory_ =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&url_loader_factory_);
service_context_ = std::make_unique<FakeServiceContext>();
service_context_
->set_main_task_runner(task_environment.GetMainThreadTaskRunner())
.set_power_manager_client(PowerManagerClient::Get())
.set_assistant_state(&assistant_state_);
CreateAssistantManagerServiceImpl(/*libassistant_config=*/{});
}
void CreateAssistantManagerServiceImpl(
base::Optional<std::string> s3_server_uri_override = base::nullopt) {
auto delegate = std::make_unique<FakeAssistantManagerServiceDelegate>();
delegate_ = delegate.get();
assistant_manager_service_ = std::make_unique<AssistantManagerServiceImpl>(
&assistant_client_, service_context_.get(), std::move(delegate),
shared_url_loader_factory_->Clone(), s3_server_uri_override);
}
void TearDown() override {
assistant_manager_service_.reset();
PowerManagerClient::Shutdown();
}
AssistantManagerServiceImpl* assistant_manager_service() {
return assistant_manager_service_.get();
}
ash::AssistantState* assistant_state() { return &assistant_state_; }
FakeAssistantManagerServiceDelegate* delegate() { return delegate_; }
FakeAssistantManager* fake_assistant_manager() {
return delegate_->assistant_manager();
}
FakeAssistantManagerInternal* fake_assistant_manager_internal() {
return delegate_->assistant_manager_internal();
}
FakeAlarmTimerManager* fake_alarm_timer_manager() {
return static_cast<FakeAlarmTimerManager*>(
fake_assistant_manager_internal()->GetAlarmTimerManager());
}
FakeServiceContext* fake_service_context() { return service_context_.get(); }
action::CrosActionModule* action_module() {
return assistant_manager_service_->action_module_for_testing();
}
void Start() {
assistant_manager_service()->Start(UserInfo("<user-id>", "<access-token>"),
/*enable_hotword=*/false);
}
void RunUntilIdle() { base::RunLoop().RunUntilIdle(); }
// Adds a state observer mock, and add the expectation for the fact that it
// auto-fires the observer.
void AddStateObserver(StateObserverMock* observer) {
EXPECT_CALL(*observer,
OnStateChanged(assistant_manager_service()->GetState()));
assistant_manager_service()->AddAndFireStateObserver(observer);
}
void WaitUntilStartIsFinished() {
assistant_manager_service()->WaitUntilStartIsFinishedForTesting();
}
// Raise all the |libassistant_error_codes| as communication errors from
// libassistant, and check that they are reported to our
// |AssistantCommunicationErrorObserver| as errors of type |expected_type|.
void TestCommunicationErrors(const std::vector<int>& libassistant_error_codes,
CommunicationErrorType expected_error) {
Start();
WaitUntilStartIsFinished();
auto* delegate =
fake_assistant_manager_internal()->assistant_manager_delegate();
for (int code : libassistant_error_codes) {
CommunicationErrorObserverMock observer;
assistant_manager_service()->AddCommunicationErrorObserver(&observer);
EXPECT_CALL(observer, OnCommunicationError(expected_error));
delegate->OnCommunicationError(code);
RunUntilIdle();
assistant_manager_service()->RemoveCommunicationErrorObserver(&observer);
ASSERT_TRUE(testing::Mock::VerifyAndClearExpectations(&observer))
<< "Failure for error code " << code;
}
}
private:
base::test::SingleThreadTaskEnvironment task_environment;
FakeAssistantClient assistant_client_{};
FullyInitializedAssistantState assistant_state_;
std::unique_ptr<FakeServiceContext> service_context_;
network::TestURLLoaderFactory url_loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_;
FakeAssistantManagerServiceDelegate* delegate_;
std::unique_ptr<AssistantManagerServiceImpl> assistant_manager_service_;
DISALLOW_COPY_AND_ASSIGN(AssistantManagerServiceImplTest);
};
// Tests if the JSON string contains the given path with the given value
#define EXPECT_HAS_PATH_WITH_VALUE(config_string, path, expected_value) \
({ \
base::Optional<base::Value> config = \
base::JSONReader::Read(config_string); \
ASSERT_TRUE(config.has_value()); \
const base::Value* actual = config->FindPath(path); \
base::Value expected = base::Value(expected_value); \
ASSERT_NE(actual, nullptr) \
<< "Path '" << path << "' not found in config: " << config_string; \
EXPECT_EQ(*actual, expected); \
})
} // namespace
TEST_F(AssistantManagerServiceImplTest, StateShouldStartAsStopped) {
EXPECT_STATE(AssistantManagerService::STOPPED);
}
TEST_F(AssistantManagerServiceImplTest,
StateShouldChangeToStartingAfterCallingStart) {
Start();
EXPECT_STATE(AssistantManagerService::STARTING);
}
TEST_F(AssistantManagerServiceImplTest,
StateShouldRemainStartingUntilLibassistantIsStarted) {
Start();
fake_assistant_manager()->BlockStartCalls();
RunUntilIdle();
EXPECT_STATE(AssistantManagerService::STARTING);
fake_assistant_manager()->UnblockStartCalls();
WaitUntilStartIsFinished();
EXPECT_STATE(AssistantManagerService::STARTED);
}
TEST_F(AssistantManagerServiceImplTest,
StateShouldBecomeRunningAfterLibassistantSignalsOnStartFinished) {
Start();
WaitUntilStartIsFinished();
fake_assistant_manager()->device_state_listener()->OnStartFinished();
EXPECT_STATE(AssistantManagerService::RUNNING);
}
TEST_F(AssistantManagerServiceImplTest, ShouldSetStateToStoppedAfterStopping) {
Start();
WaitUntilStartIsFinished();
EXPECT_STATE(AssistantManagerService::STARTED);
assistant_manager_service()->Stop();
EXPECT_STATE(AssistantManagerService::STOPPED);
}
TEST_F(AssistantManagerServiceImplTest,
ShouldReportAuthenticationErrorsToCommunicationErrorObservers) {
TestCommunicationErrors(GetAuthenticationErrorCodes(),
CommunicationErrorType::AuthenticationError);
}
TEST_F(AssistantManagerServiceImplTest,
ShouldReportNonAuthenticationErrorsToCommunicationErrorObservers) {
std::vector<int> non_authentication_errors = GetNonAuthenticationErrorCodes();
// check to ensure these are not authentication errors.
for (int code : non_authentication_errors)
ASSERT_FALSE(IsAuthError(code));
// Run the actual unittest
TestCommunicationErrors(non_authentication_errors,
CommunicationErrorType::Other);
}
TEST_F(AssistantManagerServiceImplTest,
ShouldPassUserInfoToAssistantManagerWhenStarting) {
assistant_manager_service()->Start(UserInfo("<user-id>", "<access-token>"),
/*enable_hotword=*/false);
WaitUntilStartIsFinished();
EXPECT_EQ("<user-id>", fake_assistant_manager()->user_id());
EXPECT_EQ("<access-token>", fake_assistant_manager()->access_token());
}
TEST_F(AssistantManagerServiceImplTest, ShouldPassUserInfoToAssistantManager) {
Start();
WaitUntilStartIsFinished();
assistant_manager_service()->SetUser(
UserInfo("<new-user-id>", "<new-access-token>"));
EXPECT_EQ("<new-user-id>", fake_assistant_manager()->user_id());
EXPECT_EQ("<new-access-token>", fake_assistant_manager()->access_token());
}
TEST_F(AssistantManagerServiceImplTest,
ShouldPassEmptyUserInfoToAssistantManager) {
Start();
WaitUntilStartIsFinished();
assistant_manager_service()->SetUser(base::nullopt);
EXPECT_EQ(kNoValue, fake_assistant_manager()->user_id());
EXPECT_EQ(kNoValue, fake_assistant_manager()->access_token());
}
TEST_F(AssistantManagerServiceImplTest,
ShouldNotCrashWhenSettingUserInfoBeforeStartIsFinished) {
EXPECT_STATE(AssistantManagerService::STOPPED);
assistant_manager_service()->SetUser(UserInfo("<user-id>", "<access-token>"));
Start();
EXPECT_STATE(AssistantManagerService::STARTING);
assistant_manager_service()->SetUser(UserInfo("<user-id>", "<access-token>"));
}
TEST_F(AssistantManagerServiceImplTest,
ShouldPassS3ServerUriOverrideToAssistantManager) {
CreateAssistantManagerServiceImpl("the-uri-override");
Start();
WaitUntilStartIsFinished();
EXPECT_HAS_PATH_WITH_VALUE(delegate()->libassistant_config(),
"testing.s3_grpc_server_uri", "the-uri-override");
}
TEST_F(AssistantManagerServiceImplTest, ShouldPauseMediaManagerOnPause) {
StrictMock<MockMediaManager> mock;
fake_assistant_manager()->SetMediaManager(&mock);
Start();
WaitUntilStartIsFinished();
EXPECT_CALL(mock, Pause);
assistant_manager_service()->UpdateInternalMediaPlayerStatus(
MediaSessionAction::kPause);
}
TEST_F(AssistantManagerServiceImplTest, ShouldResumeMediaManagerOnPlay) {
StrictMock<MockMediaManager> mock;
fake_assistant_manager()->SetMediaManager(&mock);
Start();
WaitUntilStartIsFinished();
EXPECT_CALL(mock, Resume);
assistant_manager_service()->UpdateInternalMediaPlayerStatus(
MediaSessionAction::kPlay);
}
TEST_F(AssistantManagerServiceImplTest, ShouldIgnoreOtherMediaManagerActions) {
const auto unsupported_media_session_actions = {
MediaSessionAction::kPreviousTrack, MediaSessionAction::kNextTrack,
MediaSessionAction::kSeekBackward, MediaSessionAction::kSeekForward,
MediaSessionAction::kSkipAd, MediaSessionAction::kStop,
MediaSessionAction::kSeekTo, MediaSessionAction::kScrubTo,
};
StrictMock<MockMediaManager> mock;
fake_assistant_manager()->SetMediaManager(&mock);
Start();
WaitUntilStartIsFinished();
for (auto action : unsupported_media_session_actions) {
// If this is not ignored, |mock| will complain about an uninterested call.
assistant_manager_service()->UpdateInternalMediaPlayerStatus(action);
}
}
TEST_F(AssistantManagerServiceImplTest,
ShouldNotCrashWhenMediaManagerIsAbsent) {
Start();
WaitUntilStartIsFinished();
assistant_manager_service()->UpdateInternalMediaPlayerStatus(
media_session::mojom::MediaSessionAction::kPlay);
}
TEST_F(AssistantManagerServiceImplTest, ShouldFireStateObserverWhenAddingIt) {
StrictMock<StateObserverMock> observer;
EXPECT_CALL(observer,
OnStateChanged(AssistantManagerService::State::STOPPED));
assistant_manager_service()->AddAndFireStateObserver(&observer);
assistant_manager_service()->RemoveStateObserver(&observer);
}
TEST_F(AssistantManagerServiceImplTest, ShouldFireStateObserverWhenStarting) {
StrictMock<StateObserverMock> observer;
AddStateObserver(&observer);
fake_assistant_manager()->BlockStartCalls();
EXPECT_CALL(observer,
OnStateChanged(AssistantManagerService::State::STARTING));
Start();
assistant_manager_service()->RemoveStateObserver(&observer);
fake_assistant_manager()->UnblockStartCalls();
}
TEST_F(AssistantManagerServiceImplTest, ShouldFireStateObserverWhenStarted) {
StrictMock<StateObserverMock> observer;
AddStateObserver(&observer);
EXPECT_CALL(observer,
OnStateChanged(AssistantManagerService::State::STARTING));
EXPECT_CALL(observer,
OnStateChanged(AssistantManagerService::State::STARTED));
Start();
WaitUntilStartIsFinished();
assistant_manager_service()->RemoveStateObserver(&observer);
}
TEST_F(AssistantManagerServiceImplTest,
ShouldFireStateObserverWhenLibAssistantSignalsOnStartFinished) {
Start();
WaitUntilStartIsFinished();
StrictMock<StateObserverMock> observer;
AddStateObserver(&observer);
EXPECT_CALL(observer,
OnStateChanged(AssistantManagerService::State::RUNNING));
fake_assistant_manager()->device_state_listener()->OnStartFinished();
assistant_manager_service()->RemoveStateObserver(&observer);
}
TEST_F(AssistantManagerServiceImplTest, ShouldFireStateObserverWhenStopping) {
Start();
WaitUntilStartIsFinished();
StrictMock<StateObserverMock> observer;
AddStateObserver(&observer);
EXPECT_CALL(observer,
OnStateChanged(AssistantManagerService::State::STOPPED));
assistant_manager_service()->Stop();
assistant_manager_service()->RemoveStateObserver(&observer);
}
TEST_F(AssistantManagerServiceImplTest,
ShouldNotFireStateObserverAfterItIsRemoved) {
StrictMock<StateObserverMock> observer;
AddStateObserver(&observer);
assistant_manager_service()->RemoveStateObserver(&observer);
EXPECT_CALL(observer, OnStateChanged).Times(0);
Start();
}
TEST_F(AssistantManagerServiceImplTest,
ShouldUpdateActionModuleWhenAmbientModeStateChanged) {
EXPECT_FALSE(action_module()->IsAmbientModeEnabledForTesting());
assistant_manager_service()->EnableAmbientMode(true);
EXPECT_TRUE(action_module()->IsAmbientModeEnabledForTesting());
assistant_manager_service()->EnableAmbientMode(false);
EXPECT_FALSE(action_module()->IsAmbientModeEnabledForTesting());
}
// OnTimersResponse() is only supported when features::kAssistantTimersV2 is
// enabled. By default it is disabled, should we expect no subscribers to be
// notified of OnTimersResponse() events.
TEST_F(AssistantManagerServiceImplTest,
ShouldNotNotifyIteractionSubscribersOfTimersResponse) {
StrictMock<MockAssistantInteractionSubscriber> subscriber;
mojo::Receiver<mojom::AssistantInteractionSubscriber> receiver(&subscriber);
assistant_manager_service()->AddAssistantInteractionSubscriber(
receiver.BindNewPipeAndPassRemote());
EXPECT_CALL(subscriber, OnTimersResponse).Times(0);
assistant_manager_service()->OnShowTimers({});
base::RunLoop().RunUntilIdle();
}
TEST_F(AssistantManagerServiceImplTest,
ShouldNotifyInteractionSubscribersOfTimersResponseInV2) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(features::kAssistantTimersV2);
StrictMock<MockAssistantInteractionSubscriber> subscriber;
mojo::Receiver<mojom::AssistantInteractionSubscriber> receiver(&subscriber);
assistant_manager_service()->AddAssistantInteractionSubscriber(
receiver.BindNewPipeAndPassRemote());
EXPECT_CALL(subscriber, OnTimersResponse(ElementsAre("1", "2"))).Times(1);
assistant_manager_service()->OnShowTimers({"1", "2"});
base::RunLoop().RunUntilIdle();
}
TEST_F(AssistantManagerServiceImplTest,
ShouldNotifyAlarmTimerControllerOfOnlyRingingTimers) {
Start();
WaitUntilStartIsFinished();
assistant_manager_service()->OnStartFinished();
StrictMock<AssistantAlarmTimerControllerMock> alarm_timer_controller;
fake_service_context()->set_assistant_alarm_timer_controller(
&alarm_timer_controller);
std::vector<ash::mojom::AssistantTimerPtr> timers;
EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged)
.WillOnce(CloneArg<0>(&timers));
std::vector<assistant_client::AlarmTimerEvent> events;
// Ignore NONE, ALARMs, and SCHEDULED/PAUSED timers.
AddAlarmTimerEvent(events, assistant_client::AlarmTimerEvent::Type::NONE);
AddAlarmTimerEvent(events, assistant_client::AlarmTimerEvent::Type::ALARM);
AddTimerEvent(events, assistant_client::Timer::State::SCHEDULED);
AddTimerEvent(events, assistant_client::Timer::State::PAUSED);
// Accept FIRED timers.
AddTimerEvent(events, assistant_client::Timer::State::FIRED);
fake_alarm_timer_manager()->SetAllEvents(std::move(events));
fake_alarm_timer_manager()->NotifyRingingStateListeners();
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, timers.size());
EXPECT_EQ(ash::mojom::AssistantTimerState::kFired, timers[0]->state);
}
TEST_F(AssistantManagerServiceImplTest,
ShouldNotifyAlarmTimerControllerOfAnyTimersInV2) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(features::kAssistantTimersV2);
StrictMock<AssistantAlarmTimerControllerMock> alarm_timer_controller;
fake_service_context()->set_assistant_alarm_timer_controller(
&alarm_timer_controller);
// We expect OnTimerStateChanged() to be invoked when starting LibAssistant.
EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged).Times(1);
Start();
WaitUntilStartIsFinished();
assistant_manager_service()->OnStartFinished();
testing::Mock::VerifyAndClearExpectations(&alarm_timer_controller);
std::vector<ash::mojom::AssistantTimerPtr> timers;
EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged)
.WillOnce(CloneArg<0>(&timers));
std::vector<assistant_client::AlarmTimerEvent> events;
// Ignore NONE and ALARMs.
AddAlarmTimerEvent(events, assistant_client::AlarmTimerEvent::Type::NONE);
AddAlarmTimerEvent(events, assistant_client::AlarmTimerEvent::Type::ALARM);
// Accept SCHEDULED/PAUSED/FIRED timers.
AddTimerEvent(events, assistant_client::Timer::State::SCHEDULED);
AddTimerEvent(events, assistant_client::Timer::State::PAUSED);
AddTimerEvent(events, assistant_client::Timer::State::FIRED);
fake_alarm_timer_manager()->SetAllEvents(std::move(events));
fake_alarm_timer_manager()->NotifyRingingStateListeners();
base::RunLoop().RunUntilIdle();
ASSERT_EQ(3u, timers.size());
EXPECT_EQ(ash::mojom::AssistantTimerState::kScheduled, timers[0]->state);
EXPECT_EQ(ash::mojom::AssistantTimerState::kPaused, timers[1]->state);
EXPECT_EQ(ash::mojom::AssistantTimerState::kFired, timers[2]->state);
}
TEST_F(AssistantManagerServiceImplTest,
ShouldNotifyAlarmTimerControllerOfTimersWhenStartingLibAssistantInV2) {
// Enable timers V2.
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(features::kAssistantTimersV2);
// Pre-populate the AlarmTimerManager with a single scheduled timer.
std::vector<assistant_client::AlarmTimerEvent> events;
AddTimerEvent(events, assistant_client::Timer::State::SCHEDULED);
fake_alarm_timer_manager()->SetAllEvents(std::move(events));
// Bind AssistantAlarmTimerController.
StrictMock<AssistantAlarmTimerControllerMock> alarm_timer_controller;
fake_service_context()->set_assistant_alarm_timer_controller(
&alarm_timer_controller);
// Expect (and capture) |timers| to be sent to AssistantAlarmTimerController.
std::vector<ash::mojom::AssistantTimerPtr> timers;
EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged)
.WillOnce(CloneArg<0>(&timers));
// Start LibAssistant.
Start();
WaitUntilStartIsFinished();
assistant_manager_service()->OnStartFinished();
// Verify AssistantAlarmTimerController is notified of the scheduled timer.
ASSERT_EQ(1u, timers.size());
EXPECT_EQ(ash::mojom::AssistantTimerState::kScheduled, timers[0]->state);
}
} // namespace assistant
} // namespace chromeos
| 36.057665 | 93 | 0.764754 | sarang-apps |
d58eca98fde583fda59e7f1026eea07bac324555 | 4,134 | cpp | C++ | active16/src/libalf/libalf/testsuites/NLstar_count_eq_queries/count_eq_queries_random.cpp | adiojha629/JIRP_LRM | a06e3725a8f4f406a100d2a4c2c69d4e9450a2d3 | [
"MIT"
] | 2 | 2021-09-22T13:02:55.000Z | 2021-11-08T19:16:55.000Z | active16/src/libalf/libalf/testsuites/NLstar_count_eq_queries/count_eq_queries_random.cpp | adiojha629/JIRP_LRM | a06e3725a8f4f406a100d2a4c2c69d4e9450a2d3 | [
"MIT"
] | null | null | null | active16/src/libalf/libalf/testsuites/NLstar_count_eq_queries/count_eq_queries_random.cpp | adiojha629/JIRP_LRM | a06e3725a8f4f406a100d2a4c2c69d4e9450a2d3 | [
"MIT"
] | null | null | null | /* $Id: count_eq_queries_random.cpp 1386 2010-10-12 16:59:18Z davidpiegdon $
* vim: fdm=marker
*
* This file is part of libalf.
*
* libalf 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.
*
* libalf 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 libalf. If not, see <http://www.gnu.org/licenses/>.
*
* (c) 2008,2009 Lehrstuhl Softwaremodellierung und Verifikation (I2), RWTH Aachen University
* and Lehrstuhl Logik und Theorie diskreter Systeme (I7), RWTH Aachen University
* Author: David R. Piegdon <david-i2@piegdon.de>
*
*/
#include <iostream>
#include <ostream>
#include <iterator>
#include <fstream>
#include <algorithm>
#include <libalf/alf.h>
#include <libalf/algorithm_NLstar.h>
#include <amore++/nondeterministic_finite_automaton.h>
#include <amore++/deterministic_finite_automaton.h>
#include <liblangen/dfa_randomgenerator.h>
#include "amore_alf_glue.h"
using namespace std;
using namespace libalf;
using namespace liblangen;
ostream_logger my_logger(&cout, LOGGER_DEBUG);
int learn_via_NLstar(int asize, amore::finite_automaton * model)
{{{
statistics stats;
knowledgebase<bool> knowledge;
int iteration;
bool success = false;
// create NLstar table and teach it the automaton
NLstar_table<bool> ot(&knowledge, &my_logger, asize);
for(iteration = 1; iteration <= 100; iteration++) {
conjecture *cj;
while( NULL == (cj = ot.advance()) ) {
// resolve missing knowledge:
stats.queries.uniq_membership += amore_alf_glue::automaton_answer_knowledgebase(*model, knowledge);
}
list<int> counterexample;
stats.queries.equivalence++;
if(amore_alf_glue::automaton_equivalence_query(*model, cj, counterexample)) {
// equivalent
cout << "success.\n";
success = true;
break;
}
delete cj;
ot.add_counterexample(counterexample);
}
if(success) {
// cout << "success.\n";
return stats.queries.equivalence;
} else {
cout << "failed!\n";
return -1;
}
}}}
int main(int argc, char**argv)
{{{
bool f_is_dfa;
int f_asize, f_state_count;
set<int> f_initial, f_final;
map<int, map<int, set<int> > > f_transitions;
int num = 0;
if(argc != 3) {
printf("give asize and state-count as parameter\n");
return -1;
}
int asize = atoi(argv[1]);
unsigned int size = atoi(argv[2]);
int checked = 0;
int skipped = 0;
int found = 0;
int print_skipper = 0;
dfa_randomgenerator drng;
while(1) {
drng.generate(asize, size, f_is_dfa, f_asize, f_state_count, f_initial, f_final, f_transitions);
amore::finite_automaton *model = amore::construct_amore_automaton(f_is_dfa, f_asize, f_state_count, f_initial, f_final, f_transitions);
model->minimize();
if(model->get_state_count() < size) {
skipped++;
} else {
checked++;
unsigned int eq_queries = learn_via_NLstar(asize, model);
if(eq_queries > size) {
found++;
char filename[128];
ofstream file;
snprintf(filename, 128, "hit-a%d-s%d-%02d.dot", asize, size, num);
basic_string<int32_t> serialized = model->serialize();
file.open(filename); file << model->visualize(); file.close();
snprintf(filename, 128, "hit-a%d-s%d-%02d.atm", asize, size, num);
basic_string_to_file(serialized, filename);
my_logger(LOGGER_WARN, "\nmatch found with asize %d, state count %d, eq queries %d. saved as %s.\n",
asize, size, eq_queries, filename);
num++;
}
}
delete model;
if(checked > 0) {
print_skipper++;
print_skipper %= 10;
if(print_skipper == 0) {
printf("asize %d, states %d; %d, checked %d, found %d (%f%% of checked) \r",
asize, size,
skipped+checked, checked, found, ((double)found) / checked * 100);
}
}
}
}}}
| 27.019608 | 137 | 0.694485 | adiojha629 |
d58f93c1ba82427fc731279cc053a0ad36790def | 91 | cpp | C++ | contracts/test.inline/test.inline.cpp | ETAIO/eta | cdf2427f5b955ba2cde9b3978cf1f268053306ef | [
"MIT"
] | null | null | null | contracts/test.inline/test.inline.cpp | ETAIO/eta | cdf2427f5b955ba2cde9b3978cf1f268053306ef | [
"MIT"
] | null | null | null | contracts/test.inline/test.inline.cpp | ETAIO/eta | cdf2427f5b955ba2cde9b3978cf1f268053306ef | [
"MIT"
] | null | null | null | #include <test.inline/test.inline.hpp>
ETAIO_ABI( ETAio::testinline, (reqauth)(forward) )
| 22.75 | 50 | 0.747253 | ETAIO |
d58fba1c1f02154fdefdf22d4e656da6e9a640e8 | 432 | cpp | C++ | tests/compile_fail/unique_ptr_a_copy_assignment.cpp | rockdreamer/throwing_ptr | cd28490ebf9be803497a9fff733de62295d8288e | [
"BSL-1.0"
] | 2 | 2020-12-11T15:46:26.000Z | 2021-02-02T05:26:11.000Z | tests/compile_fail/unique_ptr_a_copy_assignment.cpp | rockdreamer/throwing_ptr | cd28490ebf9be803497a9fff733de62295d8288e | [
"BSL-1.0"
] | null | null | null | tests/compile_fail/unique_ptr_a_copy_assignment.cpp | rockdreamer/throwing_ptr | cd28490ebf9be803497a9fff733de62295d8288e | [
"BSL-1.0"
] | null | null | null | // Copyright Claudio Bantaloukas 2017-2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <throwing/unique_ptr.hpp>
int main() {
// cannot assign from unique_ptr to another (array version)
throwing::unique_ptr<int[]> from;
throwing::unique_ptr<int[]> to;
to = from;
return 0;
}
| 28.8 | 63 | 0.668981 | rockdreamer |
d592ded8329d50b76c2ce483998f827b7b09db20 | 19,087 | cpp | C++ | libminifi/test/integration/StateTransactionalityTests.cpp | rustammendel/nifi-minifi-cpp | 3a3615debb9129e7b954827debccaecc68b66006 | [
"Apache-2.0"
] | 113 | 2016-04-30T15:00:13.000Z | 2022-03-26T20:42:58.000Z | libminifi/test/integration/StateTransactionalityTests.cpp | rustammendel/nifi-minifi-cpp | 3a3615debb9129e7b954827debccaecc68b66006 | [
"Apache-2.0"
] | 688 | 2016-04-28T17:52:38.000Z | 2022-03-29T07:58:05.000Z | libminifi/test/integration/StateTransactionalityTests.cpp | rustammendel/nifi-minifi-cpp | 3a3615debb9129e7b954827debccaecc68b66006 | [
"Apache-2.0"
] | 104 | 2016-04-28T15:20:51.000Z | 2022-03-01T13:39:20.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#undef NDEBUG
#include <iostream>
#include "IntegrationBase.h"
#include "../StatefulProcessor.h"
#include "../TestBase.h"
#include "utils/IntegrationTestUtils.h"
#include "core/state/ProcessorController.h"
using org::apache::nifi::minifi::processors::StatefulProcessor;
using org::apache::nifi::minifi::state::ProcessorController;
namespace {
using LogChecker = std::function<bool()>;
struct HookCollection {
StatefulProcessor::HookType on_schedule_hook_;
std::vector<StatefulProcessor::HookType> on_trigger_hooks_;
LogChecker log_checker_;
};
class StatefulIntegrationTest : public IntegrationBase {
public:
explicit StatefulIntegrationTest(std::string testCase, HookCollection hookCollection)
: on_schedule_hook_(std::move(hookCollection.on_schedule_hook_))
, on_trigger_hooks_(std::move(hookCollection.on_trigger_hooks_))
, log_checker_(hookCollection.log_checker_)
, test_case_(std::move(testCase)) {
}
void testSetup() override {
LogTestController::getInstance().reset();
LogTestController::getInstance().setDebug<core::ProcessGroup>();
LogTestController::getInstance().setDebug<core::Processor>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<StatefulIntegrationTest>();
logger_->log_info("Running test case \"%s\"", test_case_);
}
void updateProperties(std::shared_ptr<minifi::FlowController> fc) override {
const auto controllerVec = fc->getAllComponents();
/* This tests depends on a configuration that contains only one StatefulProcessor named statefulProcessor
* (See TestStateTransactionality.yml)
* In this case there are two components in the flowcontroller: first is the controller itself,
* second is the processor that the test uses.
* Added here some assertions to make it clear. In case any of these fail without changing the corresponding yml file,
* that most probably means a breaking change. */
assert(controllerVec.size() == 2);
assert(controllerVec[0]->getComponentName() == "FlowController");
assert(controllerVec[1]->getComponentName() == "statefulProcessor");
// set hooks
const auto processController = std::dynamic_pointer_cast<ProcessorController>(controllerVec[1]);
assert(processController != nullptr);
stateful_processor_ = std::dynamic_pointer_cast<StatefulProcessor>(processController->getProcessor());
assert(stateful_processor_ != nullptr);
stateful_processor_->setHooks(on_schedule_hook_, on_trigger_hooks_);
}
void runAssertions() override {
using org::apache::nifi::minifi::utils::verifyEventHappenedInPollTime;
assert(verifyEventHappenedInPollTime(std::chrono::milliseconds(wait_time_), [&] {
return stateful_processor_->hasFinishedHooks() && log_checker_();
}));
}
private:
const StatefulProcessor::HookType on_schedule_hook_;
const std::vector<StatefulProcessor::HookType> on_trigger_hooks_;
const LogChecker log_checker_;
const std::string test_case_;
std::shared_ptr<StatefulProcessor> stateful_processor_;
std::shared_ptr<logging::Logger> logger_{logging::LoggerFactory<StatefulIntegrationTest>::getLogger()};
};
const std::unordered_map<std::string, std::string> exampleState{{"key1", "value1"}, {"key2", "value2"}};
const std::unordered_map<std::string, std::string> exampleState2{{"key3", "value3"}, {"key4", "value4"}};
auto standardLogChecker = [] {
const std::string logs = LogTestController::getInstance().log_output.str();
const auto errorResult = utils::StringUtils::countOccurrences(logs, "[error]");
const auto warningResult = utils::StringUtils::countOccurrences(logs, "[warning]");
return errorResult.second == 0 && warningResult.second == 0;
};
auto commitAndRollbackWarnings = [] {
const std::string logs = LogTestController::getInstance().log_output.str();
const auto errorResult = utils::StringUtils::countOccurrences(logs, "[error]");
const auto commitWarningResult = utils::StringUtils::countOccurrences(logs, "[warning] Caught \"Process Session Operation: State manager commit failed.\"");
const auto rollbackWarningResult = utils::StringUtils::countOccurrences(logs,
"[warning] Caught Exception during process session rollback: Process Session Operation: State manager rollback failed.");
return errorResult.second == 0 && commitWarningResult.second == 1 && rollbackWarningResult.second == 1;
};
auto exceptionRollbackWarnings = [] {
const std::string logs = LogTestController::getInstance().log_output.str();
const auto errorResult = utils::StringUtils::countOccurrences(logs, "[error]");
const auto exceptionWarningResult = utils::StringUtils::countOccurrences(logs, "[warning] Caught \"Triggering rollback\"");
const auto rollbackWarningResult = utils::StringUtils::countOccurrences(logs, "[warning] ProcessSession rollback for statefulProcessor executed");
return errorResult.second == 0 && exceptionWarningResult.second == 1 && rollbackWarningResult.second == 1;
};
const std::unordered_map<std::string, HookCollection> testCasesToHookLists {
{"State_is_recorded_after_committing", {
{},
{
[] (core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[] (core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
}},
{"State_is_discarded_after_rolling_back", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState2));
throw std::runtime_error("Triggering rollback");
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
exceptionRollbackWarnings
}},
{
"Get_in_onSchedule_without_previous_state", {
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
},
{},
standardLogChecker
}
},
{
"Set_in_onSchedule", {
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
{
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
}
},
{
"Clear_in_onSchedule", {
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.clear());
assert(stateManager.set(exampleState));
assert(stateManager.clear());
},
{
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
}
},
standardLogChecker
},
},
{
"Persist_in_onSchedule", {
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
}
},
{},
standardLogChecker
}
},
{
"Manual_beginTransaction", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.beginTransaction());
}
},
standardLogChecker
},
},
{
"Manual_commit", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(stateManager.commit());
}
},
commitAndRollbackWarnings
},
},
{
"Manual_rollback", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.rollback());
}
},
commitAndRollbackWarnings
},
},
{
"Get_without_previous_state", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
}
},
standardLogChecker
},
},
{
"(set),(get,get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
},
},
{
"(set),(get,set)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.set(exampleState));
}
},
standardLogChecker
},
},
{
"(set),(get,clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.clear());
}
},
standardLogChecker
},
},
{
"(set),(get,persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.persist());
}
},
standardLogChecker
},
},
{
"(set,!get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
},
},
standardLogChecker
},
},
{
"(set,set)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(stateManager.set(exampleState));
},
},
standardLogChecker
},
},
{
"(set,!clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(!stateManager.clear());
},
},
standardLogChecker
},
},
{
"(set,persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(stateManager.persist());
},
},
standardLogChecker
},
},
{
"(set),(clear,!get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
}
},
standardLogChecker
},
},
{
"(set),(clear),(!get),(set),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
},
},
{
"(set),(clear,set)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
assert(stateManager.set(exampleState));
},
},
standardLogChecker
},
},
{
"(set),(clear),(!clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.clear());
},
},
standardLogChecker
},
},
{
"(set),(clear),(persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
},
standardLogChecker
},
},
{
"(persist),(set),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
},
},
standardLogChecker
},
},
{
"(persist),(set),(clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
},
standardLogChecker
},
},
{
"(persist),(persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
},
standardLogChecker
},
},
{
"No_change_2_rounds", {
{},
{
[](core::CoreComponentStateManager&) {},
[](core::CoreComponentStateManager&) {},
},
standardLogChecker
},
},
{
"(!clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.clear());
},
},
standardLogChecker
},
},
{
"(set),(get,throw)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
throw std::runtime_error("Triggering rollback");
},
},
exceptionRollbackWarnings
}
},
{
"(set),(clear,throw),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
throw std::runtime_error("Triggering rollback");
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
},
},
exceptionRollbackWarnings
}
},
{
"(set),(clear,throw),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
throw std::runtime_error("Triggering rollback");
},
},
exceptionRollbackWarnings
}
}
};
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::cerr << "A test file (*.yml) argument is mandatory, a second argument for test case name is optional\n";
return EXIT_FAILURE;
}
const std::string testFile = argv[1];
if (argc == 2) {
// run all tests
for (const auto& test : testCasesToHookLists) {
StatefulIntegrationTest statefulIntegrationTest(test.first, test.second);
statefulIntegrationTest.run(testFile);
}
} else if (argc == 3) {
// run specified test case
const std::string testCase = argv[2];
auto iter = testCasesToHookLists.find(testCase);
if (iter == testCasesToHookLists.end()) {
std::cerr << "Test case \"" << testCase << "\" cannot be found\n";
return EXIT_FAILURE;
}
StatefulIntegrationTest statefulIntegrationTest(iter->first, iter->second);
statefulIntegrationTest.run(testFile);
} else {
std::cerr << "Too many arguments\n";
return EXIT_FAILURE;
}
}
| 30.835218 | 158 | 0.615864 | rustammendel |
d5933b6a37ae2ebf4b37174990b1abdcd3f6cebd | 476 | cpp | C++ | Engine/Source/Developer/StandaloneRenderer/Private/ios/SlateOpenGLContext.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Developer/StandaloneRenderer/Private/ios/SlateOpenGLContext.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Developer/StandaloneRenderer/Private/ios/SlateOpenGLContext.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "StandaloneRendererPrivate.h"
#include "OpenGL/SlateOpenGLRenderer.h"
FSlateOpenGLContext::FSlateOpenGLContext()
: WindowHandle(NULL)
, Context(NULL)
{
}
FSlateOpenGLContext::~FSlateOpenGLContext()
{
Destroy();
}
void FSlateOpenGLContext::Initialize( void* InWindow, const FSlateOpenGLContext* SharedContext )
{
}
void FSlateOpenGLContext::Destroy()
{
}
void FSlateOpenGLContext::MakeCurrent()
{
}
| 16.413793 | 96 | 0.773109 | PopCap |
d593acf738b3cfb817b771b1122d7b155f37a0ea | 17,597 | cpp | C++ | test/testEpoll.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | test/testEpoll.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | test/testEpoll.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | //MIT License
//Copyright (c) 2020 bexoft GmbH (mail@bexoft.de)
//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.
#if !defined(WIN32)
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "finalmq/poller/PollerImplEpoll.h"
#include "finalmq/helpers/OperatingSystem.h"
#include "MockIOperatingSystem.h"
using ::testing::_;
using ::testing::Return;
using ::testing::InSequence;
using ::testing::DoAll;
using namespace finalmq;
static const std::string BUFFER = "Hello";
static const int EPOLL_FD = 3;
static const int CONTROLSOCKET_READ = 4;
static const int CONTROLSOCKET_WRITE = 5;
static const int TESTSOCKET = 7;
static const int NUMBER_OF_BYTES_TO_READ = 20;
static const int TIMEOUT = 10;
MATCHER_P(Event, event, "")
{
return (arg->events == event->events &&
arg->data.fd == event->data.fd);
}
class TestEpoll: public testing::Test
{
protected:
virtual void SetUp()
{
m_mockMockOperatingSystem = new MockIOperatingSystem;
OperatingSystem::setInstance(std::unique_ptr<IOperatingSystem>(m_mockMockOperatingSystem));
m_select = std::make_unique<PollerImplEpoll>();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_create1(EPOLL_CLOEXEC)).Times(1)
.WillRepeatedly(Return(EPOLL_FD));
SocketDescriptorPtr sd1 = std::make_shared<SocketDescriptor>(CONTROLSOCKET_READ);
SocketDescriptorPtr sd2 = std::make_shared<SocketDescriptor>(CONTROLSOCKET_WRITE);
EXPECT_CALL(*m_mockMockOperatingSystem, makeSocketPair(_, _)).Times(1)
.WillRepeatedly(DoAll(testing::SetArgReferee<0>(sd1), testing::SetArgReferee<1>(sd2), Return(0)));
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = CONTROLSOCKET_READ;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, CONTROLSOCKET_READ, Event(&evCtl))).Times(1);
m_select->init();
testing::Mock::VerifyAndClearExpectations(m_mockMockOperatingSystem);
}
virtual void TearDown()
{
EXPECT_CALL(*m_mockMockOperatingSystem, close(EPOLL_FD)).Times(1).WillRepeatedly(Return(0));
EXPECT_CALL(*m_mockMockOperatingSystem, closeSocket(_)).WillRepeatedly(Return(0));
m_select = nullptr;
OperatingSystem::setInstance({});
}
MockIOperatingSystem* m_mockMockOperatingSystem = nullptr;
std::unique_ptr<IPoller> m_select;
};
TEST_F(TestEpoll, timeout)
{
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(10);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, true);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
TEST_F(TestEpoll, testAddSocketReadableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(_, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketReadableEINTR)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
{
InSequence seq;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(_, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(-1));
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(_, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
}
EXPECT_CALL(*m_mockMockOperatingSystem, getLastError()).Times(1)
.WillOnce(Return(SOCKETERROR(EINTR)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketReadableError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(-1));
EXPECT_CALL(*m_mockMockOperatingSystem, getLastError()).Times(1)
.WillOnce(Return(SOCKETERROR(EACCES)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, true);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
TEST_F(TestEpoll, testAddSocketReadableWaitSocketDescriptorsChanged)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
epoll_event evCtlRemove;
evCtlRemove.events = 0;
evCtlRemove.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_DEL, socket->getDescriptor(), Event(&evCtlRemove))).Times(1);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(
testing::DoAll(
testing::Invoke([this, &socket](int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t* sigmask){
m_select->removeSocket(socket);
}),
testing::SetArgPointee<1>(events),
Return(1)
)
);
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
EXPECT_CALL(*m_mockMockOperatingSystem, closeSocket(socket->getDescriptor())).WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketDisconnectRead)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(0), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketDisconnectEpollError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLERR;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, true);
EXPECT_EQ(result.descriptorInfos[0].readable, false);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketIoCtlError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(0), Return(-1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketWritableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
epoll_event evCtlWrite;
evCtlWrite.events = EPOLLIN | EPOLLOUT;
evCtlWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlWrite))).Times(1);
m_select->enableWrite(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLOUT;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, false);
EXPECT_EQ(result.descriptorInfos[0].writable, true);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketDisableWritableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
epoll_event evCtlWrite;
evCtlWrite.events = EPOLLIN | EPOLLOUT;
evCtlWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlWrite))).Times(1);
m_select->enableWrite(socket);
epoll_event evCtlDisableWrite;
evCtlDisableWrite.events = EPOLLIN;
evCtlDisableWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlDisableWrite))).Times(1);
m_select->disableWrite(socket);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, true);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
#endif
| 39.455157 | 151 | 0.697278 | mnaveedb |
d59528abc769a6352fba83bf91ce430152d70e5e | 665 | hpp | C++ | libs/fnd/iterator/include/bksge/fnd/iterator/default_sentinel.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/iterator/include/bksge/fnd/iterator/default_sentinel.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/iterator/include/bksge/fnd/iterator/default_sentinel.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file default_sentinel.hpp
*
* @brief default_sentinel の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
#define BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
#include <bksge/fnd/iterator/config.hpp>
#if defined(BKSGE_USE_STD_RANGES_ITERATOR)
namespace bksge
{
using std::default_sentinel_t;
using std::default_sentinel;
} // namespace bksge
#else
#include <bksge/fnd/config.hpp>
namespace bksge
{
struct default_sentinel_t {};
BKSGE_INLINE_VAR BKSGE_CONSTEXPR
default_sentinel_t default_sentinel{};
} // namespace bksge
#endif
#endif // BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
| 16.219512 | 50 | 0.741353 | myoukaku |
d5980d8a757aad45a69ab4414bf4ff972fc9efab | 2,140 | cc | C++ | RecoLocalCalo/EcalRecAlgos/src/EcalGainRatiosGPU.cc | swiedenb/cmssw | f91490fd5861333c9be8b8a0ce74eb7816cb2d11 | [
"Apache-2.0"
] | 4 | 2020-06-27T23:27:21.000Z | 2020-11-19T09:17:01.000Z | RecoLocalCalo/EcalRecAlgos/src/EcalGainRatiosGPU.cc | swiedenb/cmssw | f91490fd5861333c9be8b8a0ce74eb7816cb2d11 | [
"Apache-2.0"
] | 524 | 2018-01-29T15:50:45.000Z | 2021-08-04T14:03:21.000Z | RecoLocalCalo/EcalRecAlgos/src/EcalGainRatiosGPU.cc | swiedenb/cmssw | f91490fd5861333c9be8b8a0ce74eb7816cb2d11 | [
"Apache-2.0"
] | 7 | 2018-02-19T11:17:13.000Z | 2020-10-12T21:57:00.000Z | #include "RecoLocalCalo/EcalRecAlgos/interface/EcalGainRatiosGPU.h"
#include "FWCore/Utilities/interface/typelookup.h"
#include "HeterogeneousCore/CUDAUtilities/interface/cudaCheck.h"
EcalGainRatiosGPU::EcalGainRatiosGPU(EcalGainRatios const& values)
: gain12Over6_(values.size()), gain6Over1_(values.size()) {
// fill in eb
auto const& barrelValues = values.barrelItems();
for (unsigned int i = 0; i < barrelValues.size(); i++) {
gain12Over6_[i] = barrelValues[i].gain12Over6();
gain6Over1_[i] = barrelValues[i].gain6Over1();
}
// fill in ee
auto const& endcapValues = values.endcapItems();
auto const offset = barrelValues.size();
for (unsigned int i = 0; i < endcapValues.size(); i++) {
gain12Over6_[offset + i] = endcapValues[i].gain12Over6();
gain6Over1_[offset + i] = endcapValues[i].gain6Over1();
}
}
EcalGainRatiosGPU::Product::~Product() {
// deallocation
cudaCheck(cudaFree(gain12Over6));
cudaCheck(cudaFree(gain6Over1));
}
EcalGainRatiosGPU::Product const& EcalGainRatiosGPU::getProduct(cudaStream_t cudaStream) const {
auto const& product = product_.dataForCurrentDeviceAsync(
cudaStream, [this](EcalGainRatiosGPU::Product& product, cudaStream_t cudaStream) {
// malloc
cudaCheck(cudaMalloc((void**)&product.gain12Over6, this->gain12Over6_.size() * sizeof(float)));
cudaCheck(cudaMalloc((void**)&product.gain6Over1, this->gain6Over1_.size() * sizeof(float)));
// transfer
cudaCheck(cudaMemcpyAsync(product.gain12Over6,
this->gain12Over6_.data(),
this->gain12Over6_.size() * sizeof(float),
cudaMemcpyHostToDevice,
cudaStream));
cudaCheck(cudaMemcpyAsync(product.gain6Over1,
this->gain6Over1_.data(),
this->gain6Over1_.size() * sizeof(float),
cudaMemcpyHostToDevice,
cudaStream));
});
return product;
}
TYPELOOKUP_DATA_REG(EcalGainRatiosGPU);
| 40.377358 | 103 | 0.633178 | swiedenb |
d59e02bcb06319d174002a7a7c0b41db85531c6f | 1,992 | cpp | C++ | src/RaZor/Interface/Component/RigidBodyGroup.cpp | Razakhel/RaZor | e3cc7942f168a0df6cd08d8874e6390fd24e5b10 | [
"MIT"
] | null | null | null | src/RaZor/Interface/Component/RigidBodyGroup.cpp | Razakhel/RaZor | e3cc7942f168a0df6cd08d8874e6390fd24e5b10 | [
"MIT"
] | 1 | 2021-01-13T01:35:45.000Z | 2021-05-04T15:43:56.000Z | src/RaZor/Interface/Component/RigidBodyGroup.cpp | Razakhel/RaZor | e3cc7942f168a0df6cd08d8874e6390fd24e5b10 | [
"MIT"
] | 2 | 2021-01-13T01:36:02.000Z | 2021-08-08T10:17:53.000Z | #include "RaZor/Interface/Component/RigidBodyGroup.hpp"
#include "ui_RigidBodyComp.h"
#include <RaZ/Entity.hpp>
#include <RaZ/Physics/RigidBody.hpp>
RigidBodyGroup::RigidBodyGroup(Raz::Entity& entity, AppWindow& appWindow) : ComponentGroup(entity, appWindow) {
Ui::RigidBodyComp rigidBodyComp {};
rigidBodyComp.setupUi(this);
auto& rigidBody = entity.getComponent<Raz::RigidBody>();
// Mass
rigidBodyComp.mass->setValue(static_cast<double>(rigidBody.getMass()));
connect(rigidBodyComp.mass, QOverload<double>::of(&ValuePicker::valueChanged), [&rigidBody] (double val) {
rigidBody.setMass(static_cast<float>(val));
});
// Bounciness
rigidBodyComp.bounciness->setValue(static_cast<double>(rigidBody.getBounciness()));
connect(rigidBodyComp.bounciness, QOverload<double>::of(&ValuePicker::valueChanged), [&rigidBody] (double val) {
rigidBody.setBounciness(static_cast<float>(val));
});
// Velocity
rigidBodyComp.velocityX->setValue(static_cast<double>(rigidBody.getVelocity().x()));
rigidBodyComp.velocityY->setValue(static_cast<double>(rigidBody.getVelocity().y()));
rigidBodyComp.velocityZ->setValue(static_cast<double>(rigidBody.getVelocity().z()));
const auto updateVelocity = [rigidBodyComp, &rigidBody] (double) {
const auto velocityX = static_cast<float>(rigidBodyComp.velocityX->value());
const auto velocityY = static_cast<float>(rigidBodyComp.velocityY->value());
const auto velocityZ = static_cast<float>(rigidBodyComp.velocityZ->value());
rigidBody.setVelocity(Raz::Vec3f(velocityX, velocityY, velocityZ));
};
connect(rigidBodyComp.velocityX, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
connect(rigidBodyComp.velocityY, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
connect(rigidBodyComp.velocityZ, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
}
void RigidBodyGroup::removeComponent() {
m_entity.removeComponent<Raz::RigidBody>();
}
| 39.058824 | 114 | 0.758032 | Razakhel |
d59e39d3b691fc245b55e0f03fe0dd7d165981b4 | 1,240 | cpp | C++ | StiGame/gui/TabItem.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | 8 | 2015-02-03T20:23:49.000Z | 2022-02-15T07:51:05.000Z | StiGame/gui/TabItem.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | null | null | null | StiGame/gui/TabItem.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | 2 | 2017-02-13T18:04:00.000Z | 2020-08-24T03:21:37.000Z | #include "TabItem.h"
namespace StiGame
{
namespace Gui
{
TabItem::TabItem() : Item("TabItem")
{
tabName = "Untitled";
}
TabItem::TabItem(std::string m_tabName) : Item("TabItem")
{
tabName = m_tabName;
}
TabItem::~TabItem()
{
}
std::string TabItem::getTabName(void)
{
return tabName;
}
void TabItem::onClick(Point *relpt)
{
container.iterator().publishOnClick(relpt);
}
void TabItem::onMouseMotion(Point *relpt)
{
container.iterator().publishOnMouseMotion(relpt);
}
void TabItem::setMouseOver(bool m_mouseOver)
{
if(!m_mouseOver)
{
for(ItemIterator it = container.iterator(); it.next();)
{
it.item()->setMouseOver(false);
}
}
}
Surface* TabItem::render(void)
{
Surface *buffer = new Surface(width, height);
buffer->fill(background);
SDL_Rect src = SDL_Rect();
SDL_Rect dst = SDL_Rect();
for(ItemIterator it = container.iterator(); it.next();)
{
Item *item = it.item();
src.w = item->getWidth();
src.h = item->getHeight();
dst.w = src.w;
dst.h = src.h;
dst.x = item->getX();
dst.y = item->getY();
Surface *ibuf = item->render();
buffer->blit(ibuf, &src, &dst);
delete ibuf;
}
return buffer;
}
}
}
| 15.308642 | 63 | 0.612097 | jordsti |
d59e579eb0548c18a88c8e802a4a642410d7988b | 379 | hpp | C++ | include/SSVOpenHexagon/Utils/FontHeight.hpp | duck-37/SSVOpenHexagon | f4af15149de5c9d3b843cbfe2abcd9b68a9876d1 | [
"AFL-3.0"
] | 409 | 2015-01-03T00:08:16.000Z | 2021-11-29T05:42:06.000Z | include/SSVOpenHexagon/Utils/FontHeight.hpp | duck-37/SSVOpenHexagon | f4af15149de5c9d3b843cbfe2abcd9b68a9876d1 | [
"AFL-3.0"
] | 185 | 2015-01-03T14:52:31.000Z | 2021-11-19T20:58:48.000Z | include/SSVOpenHexagon/Utils/FontHeight.hpp | duck-37/SSVOpenHexagon | f4af15149de5c9d3b843cbfe2abcd9b68a9876d1 | [
"AFL-3.0"
] | 74 | 2015-01-12T19:08:54.000Z | 2021-11-22T23:43:59.000Z | // Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: https://opensource.org/licenses/AFL-3.0
#pragma once
namespace sf {
class Text;
}
namespace hg::Utils {
[[nodiscard]] float getFontHeight(sf::Text& font);
[[nodiscard]] float getFontHeight(sf::Text& font, const unsigned int charSize);
} // namespace hg::Utils
| 19.947368 | 79 | 0.707124 | duck-37 |
d59fec959c24f6f6ab2cdad16e0476c01013e662 | 3,306 | cpp | C++ | Snakeware/features/bullet-manipulation/bullet-event.cpp | d3dx9tex/InsightCSGO | 6c218e243e165ec2d171db8bf5f006f00c4a95c8 | [
"Apache-2.0"
] | null | null | null | Snakeware/features/bullet-manipulation/bullet-event.cpp | d3dx9tex/InsightCSGO | 6c218e243e165ec2d171db8bf5f006f00c4a95c8 | [
"Apache-2.0"
] | null | null | null | Snakeware/features/bullet-manipulation/bullet-event.cpp | d3dx9tex/InsightCSGO | 6c218e243e165ec2d171db8bf5f006f00c4a95c8 | [
"Apache-2.0"
] | 2 | 2021-06-29T14:28:21.000Z | 2022-01-31T16:45:42.000Z | #include "bullet-event.h"
#include "../../valve_sdk/interfaces/IVRenderBeams.h"
#include "../../features/ragebot/ragebot.h"
#include "../../features/ragebot/resolver/resolver.h"
void BulletImpactEvent::FireGameEvent(IGameEvent *event) {
if (!g_LocalPlayer || !event) return;
static ConVar* sv_showimpacts = g_CVar->FindVar("sv_showimpacts");
if (g_Options.misc_bullet_impacts)
sv_showimpacts->SetValue(1);
else
sv_showimpacts->SetValue(0);
if (g_Options.misc_bullet_tracer) {
if (g_EngineClient->GetPlayerForUserID(event->GetInt("userid")) == g_EngineClient->GetLocalPlayer() && g_LocalPlayer && g_LocalPlayer->IsAlive())
{
float x = event->GetFloat("x"), y = event->GetFloat("y"), z = event->GetFloat("z");
bulletImpactInfo.push_back({ g_GlobalVars->curtime, Vector(x, y, z) });
}
}
int32_t userid = g_EngineClient->GetPlayerForUserID(event->GetInt("userid"));
if (userid == g_EngineClient->GetLocalPlayer()) {
if (RageBot::Get().iTargetID != NULL) {
auto player = C_BasePlayer::GetPlayerByIndex(RageBot::Get().iTargetID);
if (!player) return;
int32_t idx = player->EntIndex();
auto &player_recs = Resolver::Get().ResolveRecord[idx];
if (!player->IsDormant())
{
int32_t tickcount = g_GlobalVars->tickcount;
if (tickcount != tickHitWall)
{
tickHitWall = tickcount;
originalShotsMissed = player_recs.iMissedShots;
if (tickcount != tickHitPlayer) {
tickHitWall = tickcount;
++player_recs.iMissedShots;
}
}
}
}
}
}
int BulletImpactEvent::GetEventDebugID(void)
{
return EVENT_DEBUG_ID_INIT;
}
void BulletImpactEvent::RegisterSelf()
{
g_GameEvents->AddListener(this, "bullet_impact", false);
}
void BulletImpactEvent::UnregisterSelf()
{
g_GameEvents->RemoveListener(this);
}
void BulletImpactEvent::Paint(void)
{
if (!g_Options.misc_bullet_tracer) return;
if (!g_EngineClient->IsInGame() || !g_LocalPlayer || !g_LocalPlayer->IsAlive()) {
bulletImpactInfo.clear();
return;
}
std::vector<BulletImpactInfo> &impacts = bulletImpactInfo;
if (impacts.empty()) return;
Color current_color(g_Options.color_bullet_tracer);
for (size_t i = 0; i < impacts.size(); i++)
{
auto current_impact = impacts.at(i);
BeamInfo_t beamInfo;
beamInfo.m_nType = TE_BEAMPOINTS;
beamInfo.m_pszModelName = "sprites/purplelaser1.vmt";
beamInfo.m_nModelIndex = -1;
beamInfo.m_flHaloScale = 0.0f;
beamInfo.m_flLife = 3.3f;
beamInfo.m_flWidth = 4.f;
beamInfo.m_flEndWidth = 4.f;
beamInfo.m_flFadeLength = 0.0f;
beamInfo.m_flAmplitude = 2.0f;
beamInfo.m_flBrightness = 255.f;
beamInfo.m_flSpeed = 0.2f;
beamInfo.m_nStartFrame = 0;
beamInfo.m_flFrameRate = 0.f;
beamInfo.m_flRed = current_color.r();
beamInfo.m_flGreen = current_color.g();
beamInfo.m_flBlue = current_color.b();
beamInfo.m_nSegments = 2;
beamInfo.m_bRenderable = true;
beamInfo.m_nFlags = FBEAM_ONLYNOISEONCE | FBEAM_NOTILE | FBEAM_HALOBEAM | FBEAM_FADEIN;
beamInfo.m_vecStart = g_LocalPlayer->GetEyePos();
beamInfo.m_vecEnd = current_impact.m_vecHitPos;
auto beam = g_RenderBeam->CreateBeamPoints(beamInfo);
if (beam) g_RenderBeam->DrawBeam(beam);
impacts.erase(impacts.begin() + i);
}
}
void BulletImpactEvent::AddSound(C_BasePlayer *p) {
} | 26.031496 | 147 | 0.705687 | d3dx9tex |
d5a0f6c285e13541ba7d921041ca19929c4d822a | 8,697 | cpp | C++ | wrappers/glcaps.cpp | moonlinux/apitrace | 764c9786b2312b656ce0918dff73001c6a85f46f | [
"MIT"
] | 1,723 | 2015-01-08T19:10:21.000Z | 2022-03-31T16:41:40.000Z | wrappers/glcaps.cpp | moonlinux/apitrace | 764c9786b2312b656ce0918dff73001c6a85f46f | [
"MIT"
] | 471 | 2015-01-02T15:02:34.000Z | 2022-03-26T17:54:10.000Z | wrappers/glcaps.cpp | moonlinux/apitrace | 764c9786b2312b656ce0918dff73001c6a85f46f | [
"MIT"
] | 380 | 2015-01-22T19:06:32.000Z | 2022-03-25T02:20:39.000Z | /**************************************************************************
*
* Copyright 2011 Jose Fonseca
* 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.
*
**************************************************************************/
/*
* Manipulation of GL extensions.
*
* So far we insert GREMEDY extensions, but in the future we could also clamp
* the GL extensions to core GL versions here.
*/
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <map>
#include "glproc.hpp"
#include "gltrace.hpp"
#include "os.hpp"
#include "config.hpp"
namespace gltrace {
typedef std::map<std::string, const char *> ExtensionsMap;
// Cache of the translated extensions strings
static ExtensionsMap extensionsMap;
// Additional extensions to be advertised
static const char *
extraExtension_stringsFull[] = {
"GL_GREMEDY_string_marker",
"GL_GREMEDY_frame_terminator",
"GL_ARB_debug_output",
"GL_AMD_debug_output",
"GL_KHR_debug",
"GL_EXT_debug_marker",
"GL_EXT_debug_label",
"GL_VMWX_map_buffer_debug",
};
static const char *
extraExtension_stringsES[] = {
"GL_KHR_debug",
"GL_EXT_debug_marker",
"GL_EXT_debug_label",
};
// Description of additional extensions we want to advertise
struct ExtensionsDesc
{
unsigned numStrings;
const char **strings;
};
#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
const struct ExtensionsDesc
extraExtensionsFull = {
ARRAY_SIZE(extraExtension_stringsFull),
extraExtension_stringsFull
};
const struct ExtensionsDesc
extraExtensionsES = {
ARRAY_SIZE(extraExtension_stringsES),
extraExtension_stringsES
};
const struct ExtensionsDesc *
getExtraExtensions(const Context *ctx)
{
switch (ctx->profile.api) {
case glfeatures::API_GL:
return &extraExtensionsFull;
case glfeatures::API_GLES:
return &extraExtensionsES;
default:
assert(0);
return &extraExtensionsFull;
}
}
/**
* Translate the GL extensions string, adding new extensions.
*/
static const char *
overrideExtensionsString(const char *extensions)
{
const Context *ctx = getContext();
const ExtensionsDesc *desc = getExtraExtensions(ctx);
size_t i;
ExtensionsMap::const_iterator it = extensionsMap.find(extensions);
if (it != extensionsMap.end()) {
return it->second;
}
size_t extensionsLen = strlen(extensions);
size_t extraExtensionsLen = 0;
for (i = 0; i < desc->numStrings; ++i) {
const char * extraExtension = desc->strings[i];
size_t extraExtensionLen = strlen(extraExtension);
extraExtensionsLen += extraExtensionLen + 1;
}
// We use malloc memory instead of a std::string because we need to ensure
// that extensions strings will not move in memory as the extensionsMap is
// updated.
size_t newExtensionsLen = extensionsLen + 1 + extraExtensionsLen + 1;
char *newExtensions = (char *)malloc(newExtensionsLen);
if (!newExtensions) {
return extensions;
}
if (extensionsLen) {
memcpy(newExtensions, extensions, extensionsLen);
// Add space separator if necessary
if (newExtensions[extensionsLen - 1] != ' ') {
newExtensions[extensionsLen++] = ' ';
}
}
for (i = 0; i < desc->numStrings; ++i) {
const char * extraExtension = desc->strings[i];
size_t extraExtensionLen = strlen(extraExtension);
memcpy(newExtensions + extensionsLen, extraExtension, extraExtensionLen);
extensionsLen += extraExtensionLen;
newExtensions[extensionsLen++] = ' ';
}
newExtensions[extensionsLen++] = '\0';
assert(extensionsLen <= newExtensionsLen);
extensionsMap[extensions] = newExtensions;
return newExtensions;
}
const GLubyte *
_glGetString_override(GLenum name)
{
const configuration *config = getConfig();
const GLubyte *result;
// Try getting the override string value first
result = getConfigString(config, name);
if (!result) {
// Ask the real GL library
result = _glGetString(name);
}
if (result) {
switch (name) {
case GL_EXTENSIONS:
result = (const GLubyte *)overrideExtensionsString((const char *)result);
break;
default:
break;
}
}
return result;
}
static void
getInteger(const configuration *config,
GLenum pname, GLint *params)
{
// Disable ARB_get_program_binary
switch (pname) {
case GL_NUM_PROGRAM_BINARY_FORMATS:
if (params) {
GLint numProgramBinaryFormats = 0;
_glGetIntegerv(pname, &numProgramBinaryFormats);
if (numProgramBinaryFormats > 0) {
os::log("apitrace: warning: hiding program binary formats (https://git.io/JOM0m)\n");
}
params[0] = 0;
}
return;
case GL_PROGRAM_BINARY_FORMATS:
// params might be NULL here, as we returned 0 for
// GL_NUM_PROGRAM_BINARY_FORMATS.
return;
}
if (params) {
*params = getConfigInteger(config, pname);
if (*params != 0) {
return;
}
}
// Ask the real GL library
_glGetIntegerv(pname, params);
}
/**
* TODO: To be thorough, we should override all glGet*v.
*/
void
_glGetIntegerv_override(GLenum pname, GLint *params)
{
const configuration *config = getConfig();
/*
* It's important to handle params==NULL correctly here, which can and does
* happen, particularly when pname is GL_COMPRESSED_TEXTURE_FORMATS or
* GL_PROGRAM_BINARY_FORMATS and the implementation returns 0 for
* GL_NUM_COMPRESSED_TEXTURE_FORMATS or GL_NUM_PROGRAM_BINARY_FORMATS, as
* the application ends up calling `params = malloc(0)` or `param = new
* GLint[0]` which can yield NULL.
*/
getInteger(config, pname, params);
if (params) {
const Context *ctx;
switch (pname) {
case GL_NUM_EXTENSIONS:
ctx = getContext();
if (ctx->profile.major >= 3) {
const ExtensionsDesc *desc = getExtraExtensions(ctx);
*params += desc->numStrings;
}
break;
case GL_MAX_LABEL_LENGTH:
/* We provide our default implementation of KHR_debug when the
* driver does not. So return something sensible here.
*/
if (params[0] == 0) {
params[0] = 256;
}
break;
case GL_MAX_DEBUG_MESSAGE_LENGTH:
if (params[0] == 0) {
params[0] = 4096;
}
break;
}
}
}
const GLubyte *
_glGetStringi_override(GLenum name, GLuint index)
{
const configuration *config = getConfig();
const Context *ctx = getContext();
const GLubyte *retVal;
if (ctx->profile.major >= 3) {
switch (name) {
case GL_EXTENSIONS:
{
const ExtensionsDesc *desc = getExtraExtensions(ctx);
GLint numExtensions = 0;
getInteger(config, GL_NUM_EXTENSIONS, &numExtensions);
if ((GLuint)numExtensions <= index && index < (GLuint)numExtensions + desc->numStrings) {
return (const GLubyte *)desc->strings[index - (GLuint)numExtensions];
}
}
break;
default:
break;
}
}
retVal = getConfigStringi(config, name, index);
if (retVal)
return retVal;
return _glGetStringi(name, index);
}
} /* namespace gltrace */
| 27.609524 | 105 | 0.634012 | moonlinux |
d5a29ee1fc53aa30517ae804164995c2b4aec658 | 503 | cpp | C++ | UVa Online Judge/10699 - Count the factors.cpp | SamanKhamesian/ACM-ICPC-Problems | c68c04bee4de9ba9f30e665cd108484e0fcae4d7 | [
"Apache-2.0"
] | 2 | 2019-03-19T23:59:48.000Z | 2019-03-21T20:13:12.000Z | UVa Online Judge/10699 - Count the factors.cpp | SamanKhamesian/ACM-ICPC-Problems | c68c04bee4de9ba9f30e665cd108484e0fcae4d7 | [
"Apache-2.0"
] | null | null | null | UVa Online Judge/10699 - Count the factors.cpp | SamanKhamesian/ACM-ICPC-Problems | c68c04bee4de9ba9f30e665cd108484e0fcae4d7 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
#define MAX 1000001
vector <int> numDiff(MAX, 0);
void numDif()
{
for (int i = 2; i < MAX ; ++i)
{
if (numDiff[i] == 0)
{
for (int j = i; j < MAX; j += i)
{
numDiff[j]++;
}
}
}
}
int main()
{
numDif();
int n;
while (cin >> n && n != 0)
{
cout << n << " : " << numDiff[n] << endl;
}
} | 13.972222 | 49 | 0.417495 | SamanKhamesian |
d5a4593ad9a110c8963cfd8b84d10826582b06fe | 81,624 | cpp | C++ | src/mbgl/shaders/source.cpp | ebe-forks/qtlocation-mapboxgl | 952c4131e6a46fd0fab2208379dc340fb02924e3 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/shaders/source.cpp | ebe-forks/qtlocation-mapboxgl | 952c4131e6a46fd0fab2208379dc340fb02924e3 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/shaders/source.cpp | ebe-forks/qtlocation-mapboxgl | 952c4131e6a46fd0fab2208379dc340fb02924e3 | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2019-09-02T19:04:19.000Z | 2019-09-02T19:04:19.000Z | // NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED.
#include <mbgl/shaders/source.hpp>
#include <mbgl/util/compression.hpp>
#include <cstdint>
namespace mbgl {
namespace shaders {
const char* source() {
static const uint8_t compressed[] = {
0x78, 0xda, 0xed, 0x7d, 0x6b, 0x73, 0x1b, 0x37,
0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, 0xde, 0x6c, 0x3c, 0xd4, 0x6d, 0x8a,
0x29, 0xca, 0x26, 0xfc, 0x12, 0xea, 0xd4, 0x66,
0xc7, 0x7d, 0xd1, 0x32, 0x9d, 0xee, 0xb9, 0xbb,
0x42, 0x1e, 0x0c, 0xf6, 0xd3, 0xc7, 0xf5, 0x6c,
0x86, 0x9e, 0xd8, 0xa3, 0xc3, 0xa7, 0xf4, 0x60,
0x9f, 0xe3, 0x8a, 0x00, 0x62, 0xf8, 0xb7, 0x2d,
0x8c, 0x4b, 0xe6, 0x5d, 0xf2, 0xba, 0x87, 0xc6,
0x36, 0xed, 0xa9, 0x32, 0x85, 0x58, 0xcb, 0x2c,
0xd6, 0x1e, 0x1c, 0xf4, 0xc3, 0xe7, 0x00, 0x5b,
0x1e, 0x27, 0x4f, 0x2c, 0xac, 0xdb, 0xdb, 0xa0,
0x4d, 0x51, 0x8c, 0x24, 0xbe, 0x8c, 0xad, 0x45,
0x5f, 0x7d, 0x4b, 0xae, 0xd0, 0x7d, 0x38, 0x52,
0xa1, 0x35, 0x6a, 0xf9, 0x56, 0xad, 0xf2, 0xa2,
0x19, 0xaf, 0x99, 0xd5, 0x7b, 0x81, 0xd2, 0x54,
0x33, 0x3e, 0x53, 0x0a, 0xa5, 0x81, 0x03, 0xdc,
0x13, 0xa5, 0xb7, 0x7d, 0x8e, 0xe8, 0x28, 0xaf,
0xbf, 0xad, 0x57, 0x6e, 0x34, 0x80, 0xae, 0x03,
0xad, 0xc3, 0xa3, 0x7a, 0x52, 0xf8, 0x78, 0x83,
0xe7, 0x6c, 0x28, 0x5d, 0xb9, 0xa7, 0xf8, 0x2d,
0x5c, 0x93, 0xff, 0x7f, 0xc9, 0x73, 0xe5, 0xd5
};
static std::string decompressed = util::decompress(std::string(reinterpret_cast<const char*>(compressed), sizeof(compressed)));
return decompressed.c_str();
};
} // namespace shaders
} // namespace mbgl
| 55.564329 | 131 | 0.572283 | ebe-forks |
d5a94e747658932f35f740260bd43d6bb43d329c | 10,282 | cpp | C++ | tcs/csp_solver_tou_block_schedules.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 61 | 2017-08-09T15:10:59.000Z | 2022-02-15T21:45:31.000Z | tcs/csp_solver_tou_block_schedules.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 462 | 2017-07-31T21:26:46.000Z | 2022-03-30T22:53:50.000Z | tcs/csp_solver_tou_block_schedules.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 73 | 2017-08-24T17:39:31.000Z | 2022-03-28T08:37:47.000Z | /**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "csp_solver_tou_block_schedules.h"
#include "csp_solver_util.h"
#include <algorithm>
void C_block_schedule::check_dimensions()
{
// Check that each schedule is a 12x24 matrix
// If not, throw exception
if (mc_weekdays.nrows() != mc_weekends.nrows()
|| mc_weekdays.nrows() != 12
|| mc_weekdays.ncols() != mc_weekends.ncols()
|| mc_weekdays.ncols() != 24 )
{
m_error_msg = "TOU schedules must have 12 rows and 24 columns";
throw C_csp_exception( m_error_msg, "TOU block schedule init" );
}
/*
if( mc_weekdays.nrows() != mstatic_n_rows )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekday schedule has %d rows.", (int)mc_weekdays.nrows());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekdays.ncols() != mstatic_n_cols )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekday schedule has %d columns.", (int)mc_weekdays.ncols());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekends.nrows() != mstatic_n_rows )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekend schedule has %d rows.",(int) mc_weekends.nrows());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekends.ncols() != mstatic_n_cols )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekend schedule has %d columns.", (int)mc_weekends.ncols());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
*/
return;
}
void C_block_schedule::size_vv(int n_arrays)
{
mvv_tou_arrays.resize(n_arrays, std::vector<double>(0, std::numeric_limits<double>::quiet_NaN()));
}
void C_block_schedule::check_arrays_for_tous(int n_arrays)
{
// Check that all TOU periods represented in the schedules are available in the tou arrays
int i_tou_min = 1;
int i_tou_max = 1;
int i_tou_day = -1;
int i_tou_end = -1;
int i_temp_max = -1;
int i_temp_min = -1;
for( int i = 0; i < 12; i++ )
{
for( int j = 0; j < 24; j++ )
{
i_tou_day = (int) mc_weekdays(i, j) - 1;
i_tou_end = (int) mc_weekends(i, j) - 1;
i_temp_max = std::max(i_tou_day, i_tou_end);
i_temp_min = std::min(i_tou_day, i_tou_end);
if( i_temp_max > i_tou_max )
i_tou_max = i_temp_max;
if( i_temp_min < i_tou_min )
i_tou_min = i_temp_min;
}
}
if( i_tou_min < 0 )
{
throw(C_csp_exception("Smallest TOU period cannot be less than 1", "TOU block schedule initialization"));
}
for( int k = 0; k < n_arrays; k++ )
{
if( i_tou_max + 1 > (int)mvv_tou_arrays[k].size() )
{
m_error_msg = util::format("TOU schedule contains TOU period = %d, while the %s array contains %d elements", (int)i_temp_max, mv_labels[k].c_str(), mvv_tou_arrays[k].size());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
}
void C_block_schedule::set_hr_tou(bool is_leapyear)
{
/*
This method sets the TOU schedule month by hour for an entire year, so only makes sense in the context of an annual simulation.
*/
if( m_hr_tou != 0 )
delete [] m_hr_tou;
int nhrann = 8760+(is_leapyear?24:0);
m_hr_tou = new double[nhrann];
int nday[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if( is_leapyear )
nday[1] ++;
int wday = 5, i = 0;
for( int m = 0; m<12; m++ )
{
for( int d = 0; d<nday[m]; d++ )
{
bool bWeekend = (wday <= 0);
if( wday >= 0 ) wday--;
else wday = 5;
for( int h = 0; h<24 && i<nhrann && m * 24 + h<288; h++ )
{
if( bWeekend )
m_hr_tou[i] = mc_weekends(m, h); // weekends[m * 24 + h];
else
m_hr_tou[i] = mc_weekdays(m, h); // weekdays[m * 24 + h];
i++;
}
}
}
}
void C_block_schedule::init(int n_arrays, bool is_leapyear)
{
check_dimensions();
check_arrays_for_tous(n_arrays);
set_hr_tou(is_leapyear);
}
C_block_schedule_csp_ops::C_block_schedule_csp_ops()
{
// Initializie temporary output 2D vector
size_vv(N_END);
mv_labels.resize(N_END);
mv_labels[0] = "Turbine Fraction";
mv_is_diurnal = true;
}
C_block_schedule_pricing::C_block_schedule_pricing()
{
// Initializie temporary output 2D vector
size_vv(N_END);
mv_labels.resize(N_END);
mv_labels[0] = "Price Multiplier";
mv_is_diurnal = true;
}
void C_csp_tou_block_schedules::init()
{
try
{
ms_params.mc_csp_ops.init(C_block_schedule_csp_ops::N_END, mc_dispatch_params.m_isleapyear);
}
catch( C_csp_exception &csp_exception )
{
m_error_msg = "The CSP ops " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
// time step initialization of actual price multipliers done in calling compute modules.
// mv_is_diurnal is set to true in constructor
if (ms_params.mc_pricing.mv_is_diurnal)
{
try
{
ms_params.mc_pricing.init(C_block_schedule_pricing::N_END, mc_dispatch_params.m_isleapyear);
}
catch (C_csp_exception &csp_exception)
{
m_error_msg = "The CSP pricing " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
if (ms_params.mc_csp_ops.mv_is_diurnal)
{
try
{
ms_params.mc_csp_ops.init(C_block_schedule_csp_ops::N_END, mc_dispatch_params.m_isleapyear);
}
catch (C_csp_exception& csp_exception)
{
m_error_msg = "The CSP ops " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
return;
}
// TODO: move this into dispatch some how
void C_csp_tou_block_schedules::call(double time_s, C_csp_tou::S_csp_tou_outputs & tou_outputs)
{
int i_hour = (int)(ceil(time_s/3600.0 - 1.e-6) - 1);
if( i_hour > 8760 - 1 + (mc_dispatch_params.m_isleapyear ? 24 : 0) || i_hour<0 )
{
m_error_msg = util::format("The hour input to the TOU schedule must be from 1 to 8760. The input hour was %d.", i_hour+1);
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
size_t csp_op_tou = (size_t)ms_params.mc_csp_ops.m_hr_tou[i_hour]; // an 8760-size array of the 1-9 turbine output fraction for the timestep
tou_outputs.m_csp_op_tou = (int)csp_op_tou; // needed for hybrid cooling regardless of turbine output fraction schedule type
if (ms_params.mc_csp_ops.mv_is_diurnal) {
tou_outputs.m_f_turbine = ms_params.mc_csp_ops.mvv_tou_arrays[C_block_schedule_csp_ops::TURB_FRAC][csp_op_tou-1]; // an array of size 9 of the different turbine output fractions
}
else {
tou_outputs.m_f_turbine = ms_params.mc_csp_ops.timestep_load_fractions.at(i_hour);
}
if (ms_params.mc_pricing.mv_is_diurnal)
{
int pricing_tou = (int)ms_params.mc_pricing.m_hr_tou[i_hour];
tou_outputs.m_pricing_tou = pricing_tou;
tou_outputs.m_price_mult = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][pricing_tou - 1];
}
else // note limited to hour but can be extended to timestep using size
{
// these can be set in initialize and we may want to include time series inputs for other multipliers and fractions
size_t nrecs = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE].size();
if (nrecs <= 0)
{
m_error_msg = util::format("The timestep price multiplier array was empty.");
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
size_t nrecs_per_hour = nrecs / 8760;
int ndx = (int)((ceil(time_s / 3600.0 - 1.e-6) - 1) * nrecs_per_hour);
if (ndx > (int)nrecs - 1 + (mc_dispatch_params.m_isleapyear ? 24 : 0) || ndx<0)
{
m_error_msg = util::format("The index input to the TOU schedule must be from 1 to %d. The input timestep index was %d.", (int)nrecs, ndx + 1);
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
tou_outputs.m_price_mult = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][ndx];
}
}
void C_csp_tou_block_schedules::setup_block_uniform_tod()
{
int nrows = ms_params.mc_csp_ops.mstatic_n_rows;
int ncols = ms_params.mc_csp_ops.mstatic_n_cols;
for( int i = 0; i < ms_params.mc_csp_ops.N_END; i++ )
ms_params.mc_csp_ops.mvv_tou_arrays[i].resize(2, 1.0);
for( int i = 0; i < ms_params.mc_pricing.N_END; i++ )
ms_params.mc_pricing.mvv_tou_arrays[i].resize(2, 1.0);
ms_params.mc_csp_ops.mc_weekdays.resize_fill(nrows, ncols, 1.0);
ms_params.mc_csp_ops.mc_weekends.resize_fill(nrows, ncols, 1.0);
ms_params.mc_pricing.mc_weekdays.resize_fill(nrows, ncols, 1.0);
ms_params.mc_pricing.mc_weekends.resize_fill(nrows, ncols, 1.0);
}
| 34.619529 | 188 | 0.71844 | JordanMalan |
d5a9ae7c2b9029df289fdd0f8063e3db2eee9cd7 | 360 | hpp | C++ | include/turbo/DebugImgui.hpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | 2 | 2021-02-12T13:05:02.000Z | 2021-02-22T14:25:00.000Z | include/turbo/DebugImgui.hpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | null | null | null | include/turbo/DebugImgui.hpp | mariusvn/turbo-engine | 63cc2b76bc1aff7de9655916553a03bd768f5879 | [
"MIT"
] | null | null | null |
#ifndef __TURBO_ENGINE_DEBUGIMGUI_HPP__
#define __TURBO_ENGINE_DEBUGIMGUI_HPP__
#ifdef __TURBO_USE_IMGUI__
#include <imgui/imgui.h>
#include <imgui/imgui_impl_allegro5.h>
#include "debug_menus/EngineDebug.hpp"
#include "debug_menus/SceneManagerDebug.hpp"
#define ONLYIMGUI(expr) expr;
#else
#define ONLYIMGUI(expr)
#endif
#endif
| 18 | 48 | 0.761111 | mariusvn |
d5adfdc3e9422b4f86b3634a34be5d519d6a6b9f | 1,973 | cpp | C++ | lib/build_tree.cpp | LC-John/Py-CParser | c9a0b7b06a5058e0b223f170aa3b8e540f0c0228 | [
"MIT"
] | 3 | 2019-09-20T09:01:32.000Z | 2021-08-12T06:02:34.000Z | lib/build_tree.cpp | LC-John/Py-CParser | c9a0b7b06a5058e0b223f170aa3b8e540f0c0228 | [
"MIT"
] | null | null | null | lib/build_tree.cpp | LC-John/Py-CParser | c9a0b7b06a5058e0b223f170aa3b8e540f0c0228 | [
"MIT"
] | 1 | 2021-08-12T06:02:41.000Z | 2021-08-12T06:02:41.000Z | #include "y.tab.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include "tree.h"
using namespace std;
extern FILE* yyin;
extern FILE* yyout;
typedef struct yy_buffer_state * YY_BUFFER_STATE;
extern YY_BUFFER_STATE yy_scan_string(const char * str);
extern void yy_delete_buffer(YY_BUFFER_STATE buffer);
extern void yy_switch_to_buffer(YY_BUFFER_STATE buffer);
TreeNode* root;
TreeNode* curr;
void deleteTree(TreeNode* root)
{
for (int i = 0; i < root->children.size(); i++)
if (root->children[i] != NULL)
deleteTree(root->children[i]);
delete root;
}
void deleteChain(TreeNode* root)
{
TreeNode* tmp;
while(root != NULL)
{
tmp = root->next;
delete root;
root = tmp;
}
}
extern "C"
{
char* getStructuredParsingTree(char* input)
{
YY_BUFFER_STATE buffer = yy_scan_string(input);
yy_switch_to_buffer(buffer);
root = new TreeNode(Non, "<translation_unit>", NULL);
curr = root;
if (yyparse() == 0)
{
yy_delete_buffer(buffer);
char* ret = strdup((root->structuredTree("")).c_str());
deleteTree(root);
return ret;
}
else
{
yy_delete_buffer(buffer);
deleteChain(curr);
return strdup("");
}
}
}
extern "C"
{
void freeCharPtr(char* str)
{
if (str != NULL)
free(str);
}
}
extern "C"
{
void printParsingTree(char* input)
{
YY_BUFFER_STATE buffer = yy_scan_string(input);
yy_switch_to_buffer(buffer);
root = new TreeNode(Non, "<translation_unit>", NULL);
curr = root;
if (yyparse() == 0)
{
root->printTree(0, yyout);
deleteTree(root);
}
else
{
fprintf(stderr, "Syntax Error!\n");
deleteChain(curr);
}
yy_delete_buffer(buffer);
return;
}
} | 21.922222 | 67 | 0.563102 | LC-John |
d5ae2e33fe3b711ff11ff074a86d07ac27f21c7b | 630 | cpp | C++ | CSP-Training/1/18-rectangle.cpp | cyp0633/homework | c4a134aa0c2e38e1a24fab178b42a7a1a0f3cd25 | [
"MIT"
] | null | null | null | CSP-Training/1/18-rectangle.cpp | cyp0633/homework | c4a134aa0c2e38e1a24fab178b42a7a1a0f3cd25 | [
"MIT"
] | null | null | null | CSP-Training/1/18-rectangle.cpp | cyp0633/homework | c4a134aa0c2e38e1a24fab178b42a7a1a0f3cd25 | [
"MIT"
] | 1 | 2020-12-14T08:52:40.000Z | 2020-12-14T08:52:40.000Z | //三角形的面积
#include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
double x1, y1, x2, y2, x3, y3, s, a, b, c, A;
while (scanf("%lf%lf%lf%lf%lf%lf", &x1, &y1, &x2, &y2, &x3, &y3))
{
if (x1 == 0 && y1 == 0 && x2 == 0 && y2 == 0 && x3 == 0 && y3 == 0)
{
break;
}
a = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
b = sqrt(pow(x3 - x2, 2) + pow(y3 - y2, 2));
c = sqrt(pow(x3 - x1, 2) + pow(y3 - y1, 2));
s = (a + b + c) / 2;
A = sqrt(s * (s - a) * (s - b) * (s - c));
printf("%.6lf\n", A);
}
return 0;
} | 26.25 | 75 | 0.396825 | cyp0633 |
d5b125ff62b3d5f93770de5b5a77f848ee97b388 | 7,383 | cpp | C++ | Competitive Programming/avl insertion.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | Competitive Programming/avl insertion.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | Competitive Programming/avl insertion.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | // C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// AVL tree node
struct AVLwithparent {
struct AVLwithparent* left;
struct AVLwithparent* right;
int key;
struct AVLwithparent* par;
int height;
};
// Function to update the height of
// a node according to its children's
// node's heights
void Updateheight(
struct AVLwithparent* root)
{
if (root != NULL) {
// Store the height of the
// current node
int val = 1;
// Store the height of the left
// and right substree
if (root->left != NULL)
val = root->left->height + 1;
if (root->right != NULL)
val = max(
val, root->right->height + 1);
// Update the height of the
// current node
root->height = val;
}
}
// Function to handle Left Left Case
struct AVLwithparent* LLR(
struct AVLwithparent* root)
{
// Create a reference to the
// left child
struct AVLwithparent* tmpnode = root->left;
// Update the left child of the
// root to the right child of the
// current left child of the root
root->left = tmpnode->right;
// Update parent pointer of the
// left child of the root node
if (tmpnode->right != NULL)
tmpnode->right->par = root;
// Update the right child of
// tmpnode to root
tmpnode->right = root;
// Update parent pointer of
// the tmpnode
tmpnode->par = root->par;
// Update the parent pointer
// of the root
root->par = tmpnode;
// Update tmpnode as the left or the
// right child of its parent pointer
// according to its key value
if (tmpnode->par != NULL
&& root->key < tmpnode->par->key) {
tmpnode->par->left = tmpnode;
}
else {
if (tmpnode->par != NULL)
tmpnode->par->right = tmpnode;
}
// Make tmpnode as the new root
root = tmpnode;
// Update the heights
Updateheight(root->left);
Updateheight(root->right);
Updateheight(root);
Updateheight(root->par);
// Return the root node
return root;
}
// Function to handle Right Right Case
struct AVLwithparent* RRR(
struct AVLwithparent* root)
{
// Create a reference to the
// right child
struct AVLwithparent* tmpnode = root->right;
// Update the right child of the
// root as the left child of the
// current right child of the root
root->right = tmpnode->left;
// Update parent pointer of the
// right child of the root node
if (tmpnode->left != NULL)
tmpnode->left->par = root;
// Update the left child of the
// tmpnode to root
tmpnode->left = root;
// Update parent pointer of
// the tmpnode
tmpnode->par = root->par;
// Update the parent pointer
// of the root
root->par = tmpnode;
// Update tmpnode as the left or
// the right child of its parent
// pointer according to its key value
if (tmpnode->par != NULL
&& root->key < tmpnode->par->key) {
tmpnode->par->left = tmpnode;
}
else {
if (tmpnode->par != NULL)
tmpnode->par->right = tmpnode;
}
// Make tmpnode as the new root
root = tmpnode;
// Update the heights
Updateheight(root->left);
Updateheight(root->right);
Updateheight(root);
Updateheight(root->par);
// Return the root node
return root;
}
// Function to handle Left Right Case
struct AVLwithparent* LRR(
struct AVLwithparent* root)
{
root->left = RRR(root->left);
return LLR(root);
}
// Function to handle right left case
struct AVLwithparent* RLR(
struct AVLwithparent* root)
{
root->right = LLR(root->right);
return RRR(root);
}
// Function to insert a node in
// the AVL tree
struct AVLwithparent* Insert(
struct AVLwithparent* root,
struct AVLwithparent* parent,
int key)
{
if (root == NULL) {
// Create and assign values
// to a new node
root = new struct AVLwithparent;
// If the root is NULL
if (root == NULL) {
cout << "Error in memory"
<< endl;
}
// Otherwise
else {
root->height = 1;
root->left = NULL;
root->right = NULL;
root->par = parent;
root->key = key;
}
}
else if (root->key > key) {
// Recur to the left subtree
// to insert the node
root->left = Insert(root->left,
root, key);
// Store the heights of the
// left and right subtree
int firstheight = 0;
int secondheight = 0;
if (root->left != NULL)
firstheight = root->left->height;
if (root->right != NULL)
secondheight = root->right->height;
// Balance the tree if the
// current node is not balanced
if (abs(firstheight
- secondheight)
== 2) {
if (root->left != NULL
&& key < root->left->key) {
// Left Left Case
root = LLR(root);
}
else {
// Left Right Case
root = LRR(root);
}
}
}
else if (root->key < key) {
// Recur to the right subtree
// to insert the node
root->right = Insert(root->right,
root, key);
// Store the heights of the
// left and right subtree
int firstheight = 0;
int secondheight = 0;
if (root->left != NULL)
firstheight
= root->left->height;
if (root->right != NULL)
secondheight = root->right->height;
// Balance the tree if the
// current node is not balanced
if (abs(firstheight - secondheight) == 2) {
if (root->right != NULL
&& key < root->right->key) {
// Right Left Case
root = RLR(root);
}
else {
// Right Right Case
root = RRR(root);
}
}
}
// Case when given key is already
// in the tree
else {
}
// Update the height of the
// root node
Updateheight(root);
// Return the root node
return root;
}
// Function to print the preorder
// traversal of the AVL tree
void printpreorder(
struct AVLwithparent* root)
{
// Print the node's value along
// with its parent value
cout << "Node: " << root->key
<< ", Parent Node: ";
if (root->par != NULL)
cout << root->par->key << endl;
else
cout << "NULL" << endl;
// Recur to the left subtree
if (root->left != NULL) {
printpreorder(root->left);
}
// Recur to the right subtree
if (root->right != NULL) {
printpreorder(root->right);
}
}
// Driver Code
int main()
{
struct AVLwithparent* root;
root = NULL;
// Function Call to insert nodes
root = Insert(root, NULL, 10);
root = Insert(root, NULL, 20);
root = Insert(root, NULL, 30);
root = Insert(root, NULL, 40);
root = Insert(root, NULL, 50);
root = Insert(root, NULL, 25);
// Function call to print the tree
printpreorder(root);
} | 22.647239 | 51 | 0.54165 | shreejitverma |
d5b1c2b770abf1b77670507f804e134221f9eeb4 | 2,538 | cc | C++ | content/browser/compute_pressure/cpuid_base_frequency_parser.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | content/browser/compute_pressure/cpuid_base_frequency_parser.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | content/browser/compute_pressure/cpuid_base_frequency_parser.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2021 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 "content/browser/compute_pressure/cpuid_base_frequency_parser.h"
#include <stdint.h>
#include <limits>
#include "base/check_op.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece_forward.h"
#include "third_party/re2/src/re2/re2.h"
#include "third_party/re2/src/re2/stringpiece.h"
namespace content {
int64_t ParseBaseFrequencyFromCpuid(base::StringPiece brand_string) {
// A perfectly accurate number pattern would be quite a bit more complex, as
// we want to capture both integers (1133Mhz) and decimal fractions (1.20Ghz).
// The current pattern is preferred as base::StringToDouble() can catch the
// false positives.
//
// The unit pattern matches the strings "MHz" and "GHz" case-insensitively.
re2::RE2 frequency_re("([0-9.]+)\\s*([GgMm][Hh][Zz])");
// As matches are consumed, `input` will be mutated to reflect the
// non-consumed string.
re2::StringPiece input(brand_string.data(), brand_string.size());
re2::StringPiece number_string; // The frequency number.
re2::StringPiece unit; // MHz or GHz (case-insensitive)
while (
re2::RE2::FindAndConsume(&input, frequency_re, &number_string, &unit)) {
DCHECK_GT(number_string.size(), 0u)
<< "The number pattern should only match non-empty strings";
DCHECK_EQ(unit.size(), 3u)
<< "The unit pattern should match exactly 3 characters";
double number;
if (!base::StringToDouble(
base::StringPiece(number_string.data(), number_string.size()),
&number)) {
continue;
}
DCHECK_GE(number, 0);
double unit_multiplier =
(unit[0] == 'G' || unit[0] == 'g') ? 1'000'000'000 : 1'000'000;
double frequency = number * unit_multiplier;
// Avoid conversion overflows. double can (imprecisely) store larger numbers
// than int64_t.
if (!base::IsValueInRangeForNumericType<int64_t>(frequency))
continue;
int64_t frequency_int = static_cast<int64_t>(frequency);
// It's unlikely that Chrome can run on CPUs with clock speeds below 100MHz.
// This cutoff can catch some bad parses.
static constexpr int64_t kMinimumFrequency = 100'000'000;
if (frequency_int < kMinimumFrequency)
continue;
return frequency_int;
}
return -1;
}
} // namespace content
| 33.84 | 80 | 0.69937 | zealoussnow |
d5b3721c4eac2e2bdb250f4de4c4da0c83f3ff3b | 520 | cpp | C++ | native/graphics/opengl/desktop/linux/platform_graphics.cpp | 49View/event_horizon | 9b78c9318e1a785384ab01eb4d90e79f0192c6ad | [
"BSD-3-Clause"
] | null | null | null | native/graphics/opengl/desktop/linux/platform_graphics.cpp | 49View/event_horizon | 9b78c9318e1a785384ab01eb4d90e79f0192c6ad | [
"BSD-3-Clause"
] | 7 | 2021-09-02T05:58:24.000Z | 2022-02-27T07:06:43.000Z | native/graphics/opengl/desktop/linux/platform_graphics.cpp | 49View/event_horizon | 9b78c9318e1a785384ab01eb4d90e79f0192c6ad | [
"BSD-3-Clause"
] | 2 | 2020-02-06T02:05:15.000Z | 2021-11-25T11:35:14.000Z | #include "../../../platform_graphics.hpp"
#include "../../gl_headers.hpp"
#include "core/util.h"
void initGraphics() {
// glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
// glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
// glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
}
void initGraphicsExtensions() {
// start GLEW extension handler
// glewExperimental = GL_TRUE;
//
if ( glewInit() != GLEW_OK ) {
LOGE( "Failed to initialize GLEW" );
}
} | 26 | 65 | 0.734615 | 49View |
d5b546d2d04fed03d0c5ab9d67fdeffe41ffb07f | 3,279 | cpp | C++ | source/rendercore-examples/source/GltfExampleRenderer.cpp | sbusch42/rendercore | 8d0bd316ff23f8f6596a07d8a3ce568049ad08d2 | [
"MIT"
] | 1 | 2019-02-12T16:00:45.000Z | 2019-02-12T16:00:45.000Z | source/rendercore-examples/source/GltfExampleRenderer.cpp | sbusch42/rendercore | 8d0bd316ff23f8f6596a07d8a3ce568049ad08d2 | [
"MIT"
] | null | null | null | source/rendercore-examples/source/GltfExampleRenderer.cpp | sbusch42/rendercore | 8d0bd316ff23f8f6596a07d8a3ce568049ad08d2 | [
"MIT"
] | null | null | null |
#include <rendercore-examples/GltfExampleRenderer.h>
#include <cppassist/memory/make_unique.h>
#include <glbinding/gl/gl.h>
#include <rendercore/rendercore.h>
#include <rendercore-gltf/GltfConverter.h>
#include <rendercore-gltf/GltfLoader.h>
#include <rendercore-gltf/Asset.h>
using namespace rendercore::opengl;
using namespace rendercore::gltf;
namespace rendercore
{
namespace examples
{
GltfExampleRenderer::GltfExampleRenderer(GpuContainer * container)
: Renderer(container)
, m_counter(0)
, m_angle(0.0f)
{
// Initialize object transformation
m_transform.setTranslation({ 0.0f, 0.0f, 0.0f });
m_transform.setScale ({ 1.0f, 1.0f, 1.0f });
m_transform.setRotation (glm::angleAxis(0.0f, glm::vec3(0.0f, 1.0f, 0.0f)));
// Create camera
m_camera = cppassist::make_unique<Camera>();
// Load GLTF asset
GltfLoader loader;
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/BoxAnimated/BoxAnimated.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/TextureCoordinateTest/TextureCoordinateTest.gltf");
auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/BoomBox/BoomBox.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/PbrTest/PbrTest.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/Taxi/Taxi.gltf");
// Transfer data from GLTF
GltfConverter converter;
converter.convert(*asset.get());
auto & textures = converter.textures();
for (auto & texture : textures) {
texture->setContainer(this);
m_textures.push_back(std::move(texture));
}
auto & materials = converter.materials();
for (auto & material : materials) {
material->setContainer(this);
m_materials.push_back(std::move(material));
}
auto & meshes = converter.meshes();
for (auto & mesh : meshes) {
mesh->setContainer(this);
m_meshes.push_back(std::move(mesh));
}
auto & scenes = converter.scenes();
for (auto & scene : scenes) {
m_scenes.push_back(std::move(scene));
}
// Create mesh renderer
m_sceneRenderer = cppassist::make_unique<SceneRenderer>(this);
}
GltfExampleRenderer::~GltfExampleRenderer()
{
}
void GltfExampleRenderer::onUpdate()
{
// Advance counter
m_counter++;
// Rotate model
m_angle += m_timeDelta * 1.0f;
m_transform.setRotation(glm::angleAxis(m_angle, glm::vec3(0.0f, 1.0f, 0.0f)));
// Animation has been updated, redraw the scene (will also issue another update)
scheduleRedraw();
}
void GltfExampleRenderer::onRender()
{
// Update viewport
gl::glViewport(m_viewport.x, m_viewport.y, m_viewport.z, m_viewport.w);
// Clear screen
gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);
// Update camera
m_camera->lookAt(glm::vec3(0.0f, 0.0, 9.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
m_camera->perspective(glm::radians(40.0f), glm::ivec2(m_viewport.z, m_viewport.w), 0.1f, 64.0f);
// Render scenes
for (auto & scene : m_scenes) {
m_sceneRenderer->render(*scene.get(), m_transform.transform(), m_camera.get());
}
}
} // namespace examples
} // namespace rendercore
| 28.513043 | 126 | 0.676426 | sbusch42 |
d5b8088798fa7de545854f74e24636c75d645472 | 3,536 | cpp | C++ | evaporative_air_cooler/evaporative_air_cooler_code/src/main.cpp | hhk7734/avr_proj | cb0c5c53af7eb8a0924f8c483a1a010be4b92636 | [
"MIT"
] | null | null | null | evaporative_air_cooler/evaporative_air_cooler_code/src/main.cpp | hhk7734/avr_proj | cb0c5c53af7eb8a0924f8c483a1a010be4b92636 | [
"MIT"
] | null | null | null | evaporative_air_cooler/evaporative_air_cooler_code/src/main.cpp | hhk7734/avr_proj | cb0c5c53af7eb8a0924f8c483a1a010be4b92636 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <BlynkSimpleSerialBLE.h>
#include "LOT_adc.h"
#include "LOT_ntc103f397.h"
#define SYSTEM_STATE_VIRTUAL_PIN V0
#define FORCED_FAN_ON_OFF_VIRTUAL_PIN V1
#define NTC103F397_VIRTUAL_PIN V2
#define THRESHOLD_TEMPERATURE_VIRTUAL_PIN V3
#define MOTION_STATE_VIRTUAL_PIN V4
#define MAX_PUSH_TIME_MS 500
#define PARALLEL_RESISTOR 9.85f
#define THRESHOLD_TEMPERATURE_SAFETY_ZONE 0.3f
// AT+BAUD6
// AT+NAMEevaporative
// AT+PIN0000
#define HC_O6_BAUDRATE 38400
char auth[] = "3993b1f88d9e4607b04007cd3ebe8876";
BlynkTimer timer;
volatile uint32_t pushtime = 0;
volatile uint8_t system_state = 0;
uint8_t forced_fan_on_off = 0;
float temperature;
float threshold_temperature = 25.0f;
volatile uint8_t motion_state = 0;
volatile uint32_t motion_capture_time = 0;
void fast_timer( void );
void slow_timer( void );
// app -> nano
BLYNK_WRITE( SYSTEM_STATE_VIRTUAL_PIN )
{
system_state = param.asInt();
}
BLYNK_WRITE( FORCED_FAN_ON_OFF_VIRTUAL_PIN )
{
forced_fan_on_off = param.asInt();
}
BLYNK_WRITE( THRESHOLD_TEMPERATURE_VIRTUAL_PIN )
{
threshold_temperature = param.asFloat();
}
void setup()
{
Serial.begin( HC_O6_BAUDRATE );
Blynk.config( Serial, auth );
// Blynk.begin(Serial, auth);
DDRB |= _BV( DDB5 );
MCUCR &= ~_BV( PUD ); // PULL-UP activate
DDRD &= ~_BV( DDD2 ); // INPUT
PORTD |= _BV( PD2 ); // PULL-UP
EIMSK |= _BV( INT0 ); // interrupt enable
EICRA |= _BV( ISC00 ); // any logical change
LOT_adc_setup();
DDRD &= ~_BV( DDD3 ); // INPUT
PORTD |= _BV( PD3 ); // PULL-UP
EIMSK |= _BV( INT1 ); // interrupt enable
EICRA |= _BV( ISC10 ); // any logical change
DDRD |= _BV( DDD5 ) | _BV( DDD4 ); // OUTPUT
timer.setInterval( 450, fast_timer );
timer.setInterval( 2050, slow_timer );
}
void loop()
{
Blynk.run();
timer.run();
if ( system_state )
{
PORTD |= _BV( PD4 );
if ( forced_fan_on_off )
{
PORTD |= _BV( PD5 );
}
else
{
if ( motion_state && ( temperature > threshold_temperature ) )
{
PORTD |= _BV( PD5 );
}
else if ( ( motion_state && ( temperature < threshold_temperature - THRESHOLD_TEMPERATURE_SAFETY_ZONE ) )
|| ( !motion_state ) )
{
PORTD &= ~_BV( PD5 );
}
}
}
else
{
PORTD &= ~( _BV( PD5 ) | _BV( PD4 ) );
}
float thermistor_R = LOT_adc_read( 0 );
thermistor_R = ( PARALLEL_RESISTOR * thermistor_R ) / ( 1024.0 - thermistor_R );
temperature = LOT_ntc_temperature( thermistor_R );
}
void fast_timer( void )
{
Blynk.virtualWrite( SYSTEM_STATE_VIRTUAL_PIN, system_state );
Blynk.virtualWrite( FORCED_FAN_ON_OFF_VIRTUAL_PIN, forced_fan_on_off );
Blynk.virtualWrite( NTC103F397_VIRTUAL_PIN, temperature );
Blynk.virtualWrite( MOTION_STATE_VIRTUAL_PIN, motion_state );
}
void slow_timer( void )
{
Blynk.virtualWrite( THRESHOLD_TEMPERATURE_VIRTUAL_PIN, threshold_temperature );
}
ISR( INT0_vect )
{
if ( PIND & _BV( PIND2 ) )
{
pushtime = millis();
}
else
{
if ( millis() - pushtime > MAX_PUSH_TIME_MS )
{
system_state ^= 1;
}
}
}
ISR( INT1_vect )
{
if ( PIND & _BV( PIND3 ) )
{
motion_state = 1;
}
else
{
motion_state = 0;
}
} | 23.417219 | 117 | 0.606335 | hhk7734 |
d5bdc08023633e1ad70c97907b5e60dfe585edb3 | 18,848 | cpp | C++ | src/mlapack/Rlaed4.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rlaed4.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rlaed4.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2008-2010
* Nakata, Maho
* All rights reserved.
*
* $Id: Rlaed4.cpp,v 1.7 2010/08/07 04:48:32 nakatamaho Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/*
Copyright (c) 1992-2007 The University of Tennessee. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
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 listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <mblas.h>
#include <mlapack.h>
#define MTRUE 0
#define MFALSE 1
void Rlaed4(INTEGER n, INTEGER i, REAL * d, REAL * z, REAL * delta, REAL rho, REAL * dlam, INTEGER * info)
{
REAL a, b, c;
INTEGER j;
REAL w;
INTEGER ii;
REAL dw, zz[3];
INTEGER ip1;
REAL del, eta, phi, eps, tau, psi;
INTEGER iim1, iip1;
REAL dphi, dpsi;
INTEGER iter;
REAL temp, prew, temp1, dltlb, dltub, midpt;
INTEGER niter;
INTEGER swtch, swtch3;
INTEGER orgati;
REAL erretm, rhoinv;
REAL Two = 2.0, Three = 3.0, Four = 4.0, One = 1.0, Zero = 0.0, Eight = 8.0, Ten = 10.0;
//Since this routine is called in an inner loop, we do no argument
//checking.
//Quick return for N=1 and 2
*info = 0;
if (n == 1) {
//Presumably, I=1 upon entry
*dlam = d[1] + rho * z[1] * z[1];
delta[1] = One;
return;
}
if (n == 2) {
Rlaed5(i, &d[0], &z[1], &delta[1], rho, dlam);
return;
}
//Compute machine epsilon
eps = Rlamch("Epsilon");
rhoinv = One / rho;
//The case I = N
if (i == n) {
//Initialize some basic variables
ii = n - 1;
niter = 1;
//Calculate initial guess
midpt = rho / Two;
//If ||Z||_2 is not one, then TEMP should be set to
//RHO * ||Z||_2^2 / TWO
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - midpt;
}
psi = Zero;
for (j = 0; j < n - 2; j++) {
psi += z[j] * z[j] / delta[j];
}
c = rhoinv + psi;
w = c + z[ii] * z[ii] / delta[ii] + z[n] * z[n] / delta[n];
if (w <= Zero) {
temp = z[n - 1] * z[n - 1] / (d[n] - d[n - 1] + rho)
+ z[n] * z[n] / rho;
if (c <= temp) {
tau = rho;
} else {
del = d[n] - d[n - 1];
a = -c * del + z[n - 1] * z[n - 1] + z[n] * z[n];
b = z[n] * z[n] * del;
if (a < Zero) {
tau = b * Two / (sqrt(a * a + b * Four * c) - a);
} else {
tau = (a + sqrt(a * a + b * Four * c)) / (c * Two);
}
}
//It can be proved that
//D(N)+RHO/2 <= LAMBDA(N) < D(N)+TAU <= D(N)+RHO
dltlb = midpt;
dltub = rho;
} else {
del = d[n] - d[n - 1];
a = -c * del + z[n - 1] * z[n - 1] + z[n] * z[n];
b = z[n] * z[n] * del;
if (a < Zero) {
tau = b * Two / (sqrt(a * a + b * Four * c) - a);
} else {
tau = (a + sqrt(a * a + b * Four * c)) / (c * Two);
}
//It can be proved that
//D(N) < D(N)+TAU < LAMBDA(N) < D(N)+RHO/2
dltlb = Zero;
dltub = midpt;
}
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - tau;
}
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * Eight + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
//Test for convergence
if (abs(w) <= eps * erretm) {
*dlam = d[i] + tau;
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
++niter;
c = w - delta[n - 1] * dpsi - delta[n] * dphi;
a = (delta[n - 1] + delta[n]) * w - delta[n - 1] * delta[n] * (dpsi + dphi);
b = delta[n - 1] * delta[n] * w;
if (c < Zero) {
c = abs(c);
}
if (c == Zero) {
//ETA = B/A
//ETA = RHO - TAU
eta = dltub - tau;
} else if (a >= Zero) {
eta = (a + sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a - sqrt((abs(a * a - b * Four * c))));
}
//Note, eta should be positive if w is negative, and
//eta should be negative otherwise. However,
//for some reason caused by roundoff, eta*w > 0,
//we simply use one Newton step instead. This way
//will guarantee eta*w < Zero
if (w * eta > Zero) {
eta = -w / (dpsi + dphi);
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * Eight + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
//Main loop to update the values of the array DELTA
iter = niter + 1;
for (niter = iter; niter <= 30; ++niter) {
//Test for convergence
if (abs(w) <= eps * erretm) {
*dlam = d[i] + tau;
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
c = w - delta[n - 1] * dpsi - delta[n] * dphi;
a = (delta[n - 1] + delta[n]) * w - delta[n - 1] * delta[n] * (dpsi + dphi);
b = delta[n - 1] * delta[n] * w;
if (a >= Zero) {
eta = (a + sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a - sqrt(abs(a * a - b * Four * c)));
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta > Zero) {
eta = -w / (dpsi + dphi);
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
}
//Return with INFO = 1, NITER = MAXIT and not converged
*info = 1;
*dlam = d[i] + tau;
goto L250;
//End for the case I = N
} else {
//The case for I < N
niter = 1;
ip1 = i + 1;
//Calculate initial guess
del = d[ip1] - d[i];
midpt = del / Two;
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - midpt;
}
psi = Zero;
for (j = 0; j < i - 1; j++) {
psi += z[j] * z[j] / delta[j];
}
phi = Zero;
for (j = n; j >= i + 2; j--) {
phi += z[j] * z[j] / delta[j];
}
c = rhoinv + psi + phi;
w = c + z[i] * z[i] / delta[i] + z[ip1] * z[ip1] / delta[ip1];
if (w > Zero) {
//d(i)< the ith eigenvalue < (d(i)+d(i+1))/2
//We choose d(i) as origin.
orgati = MTRUE;
a = c * del + z[i] * z[i] + z[ip1] * z[ip1];
b = z[i] * z[i] * del;
if (a > Zero) {
tau = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
} else {
tau = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
}
dltlb = Zero;
dltub = midpt;
} else {
//(d(i)+d(i+1))/2 <= the ith eigenvalue < d(i+1)
//We choose d(i+1) as origin.
orgati = MFALSE;
a = c * del - z[i] * z[i] - z[ip1] * z[ip1];
b = z[ip1] * z[ip1] * del;
if (a < Zero) {
tau = b * Two / (a - sqrt(abs(a * a + b * Four * c)));
} else {
tau = -(a + sqrt(abs(a * a + b * Four * c))) / (c * Two);
}
dltlb = -midpt;
dltub = Zero;
}
if (orgati) {
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - tau;
}
} else {
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[ip1] - tau;
}
}
if (orgati) {
ii = i;
} else {
ii = i + 1;
}
iim1 = ii - 1;
iip1 = ii + 1;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
w = rhoinv + phi + psi;
//W is the value of the secular function with
//its ii-th element removed.
swtch3 = MFALSE;
if (orgati) {
if (w < Zero) {
swtch3 = MTRUE;
}
} else {
if (w > Zero) {
swtch3 = MTRUE;
}
}
if (ii == 1 || ii == n) {
swtch3 = MFALSE;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w += temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau) * dw;
//Test for convergence
if (abs(w) <= eps * erretm) {
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
++niter;
if (!swtch3) {
if (orgati) {
c = w - delta[ip1] * dw - (d[i] - d[ip1]) * (z[i] / delta[i] * z[i] / delta[i]);
} else {
c = w - delta[i] * dw - (d[ip1] - d[i]) * (z[ip1] / delta[ip1] * z[ip1] / delta[ip1]);
}
a = (delta[i] + delta[ip1]) * w - delta[i] * delta[ip1] * dw;
b = delta[i] * delta[ip1] * w;
if (c == Zero) {
if (a == Zero) {
if (orgati) {
a = z[i] * z[i] + delta[ip1] * delta[ip1] * (dpsi + dphi);
} else {
a = z[ip1] * z[ip1] + delta[i] * delta[i] * (dpsi + dphi);
}
}
eta = b / a;
} else if (a <= Zero) {
eta = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
}
} else {
/* Interpolation using THREE most relevant poles */
temp = rhoinv + psi + phi;
if (orgati) {
temp1 = z[iim1] / delta[iim1];
temp1 *= temp1;
c = temp - delta[iip1] * (dpsi + dphi) - (d[iim1] - d[iip1]) * temp1;
zz[0] = z[iim1] * z[iim1];
zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi);
} else {
temp1 = z[iip1] / delta[iip1];
temp1 *= temp1;
c = temp - delta[iim1] * (dpsi + dphi) - (d[iip1] - d[iim1]) * temp1;
zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1));
zz[2] = z[iip1] * z[iip1];
}
zz[1] = z[ii] * z[ii];
Rlaed6(niter, orgati, c, &delta[iim1], zz, &w, &eta, info);
if (*info != 0) {
goto L250;
}
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta >= Zero) {
eta = -w / dw;
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
prew = w;
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w = rhoinv + phi + psi + temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau + eta) * dw;
swtch = MFALSE;
if (orgati) {
if (-w > abs(prew) / Ten) {
swtch = MTRUE;
}
} else {
if (w > abs(prew) / Ten) {
swtch = MTRUE;
}
}
tau += eta;
//Main loop to update the values of the array DELTA
iter = niter + 1;
for (niter = iter; niter <= 30; ++niter) {
//Test for convergence
if (abs(w) <= eps * erretm) {
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
if (!swtch3) {
if (!swtch) {
if (orgati) {
c = w - delta[ip1] * dw - (d[i] - d[ip1]) * ((z[i] / delta[i]) * (z[i] / delta[i]));
} else {
c = w - delta[i] * dw - (d[ip1] - d[i]) * ((z[ip1] / delta[ip1]) * (z[ip1] / delta[ip1]));
}
} else {
temp = z[ii] / delta[ii];
if (orgati) {
dpsi += temp * temp;
} else {
dphi += temp * temp;
}
c = w - delta[i] * dpsi - delta[ip1] * dphi;
}
a = (delta[i] + delta[ip1]) * w - delta[i] * delta[ip1]
* dw;
b = delta[i] * delta[ip1] * w;
if (c == Zero) {
if (a == Zero) {
if (!swtch) {
if (orgati) {
a = z[i] * z[i] + delta[ip1] * delta[ip1] * (dpsi + dphi);
} else {
a = z[ip1] * z[ip1] + delta[i] * delta[i] * (dpsi + dphi);
}
} else {
a = delta[i] * delta[i] * dpsi + delta[ip1]
* delta[ip1] * dphi;
}
}
eta = b / a;
} else if (a <= Zero) {
eta = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
}
} else {
//Interpolation using THREE most relevant poles
temp = rhoinv + psi + phi;
if (swtch) {
c = temp - delta[iim1] * dpsi - delta[iip1] * dphi;
zz[0] = delta[iim1] * delta[iim1] * dpsi;
zz[2] = delta[iip1] * delta[iip1] * dphi;
} else {
if (orgati) {
temp1 = z[iim1] / delta[iim1];
temp1 *= temp1;
c = temp - delta[iip1] * (dpsi + dphi) - (d[iim1]
- d[iip1]) * temp1;
zz[0] = z[iim1] * z[iim1];
zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi);
} else {
temp1 = z[iip1] / delta[iip1];
temp1 *= temp1;
c = temp - delta[iim1] * (dpsi + dphi) - (d[iip1]
- d[iim1]) * temp1;
zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1));
zz[2] = z[iip1] * z[iip1];
}
}
Rlaed6(niter, orgati, c, &delta[iim1], zz, &w, &eta, info);
if (*info != 0) {
goto L250;
}
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta >= Zero) {
eta = -w / dw;
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
prew = w;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w = rhoinv + phi + psi + temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau) * dw;
if (w * prew > Zero && abs(w) > abs(prew) / Ten) {
swtch = !swtch;
}
}
//Return with INFO = 1, NITER = MAXIT and not converged
*info = 1;
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
}
L250:
return;
}
| 26.887304 | 106 | 0.524194 | JaegerP |
d5c082e3fe50e130b11d22dbe777878e19d46a82 | 2,098 | cpp | C++ | Source/MLApp/MLReporter.cpp | afofo/madronalib | 14816a124c8d3a225540ffb408e602aa024fdb4b | [
"MIT"
] | null | null | null | Source/MLApp/MLReporter.cpp | afofo/madronalib | 14816a124c8d3a225540ffb408e602aa024fdb4b | [
"MIT"
] | null | null | null | Source/MLApp/MLReporter.cpp | afofo/madronalib | 14816a124c8d3a225540ffb408e602aa024fdb4b | [
"MIT"
] | null | null | null |
// MadronaLib: a C++ framework for DSP applications.
// Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com
// Distributed under the MIT license: http://madrona-labs.mit-license.org/
#include "MLReporter.h"
// --------------------------------------------------------------------------------
#pragma mark param viewing
MLPropertyView::MLPropertyView(MLWidget* w, MLSymbol a) :
mpWidget(w),
mAttr(a)
{
}
MLPropertyView::~MLPropertyView()
{
}
void MLPropertyView::view(const MLProperty& p) const
{
mpWidget->setPropertyImmediate(mAttr, p);
/*
// with Widget properties we can remove switch! TODO
switch(p.getType())
{
case MLProperty::kUndefinedProperty:
break;
case MLProperty::kFloatProperty:
mpWidget->setAttribute(mAttr, p.getFloatValue());
break;
case MLProperty::kStringProperty:
mpWidget->setStringAttribute(mAttr, *p.getStringValue());
break;
case MLProperty::kSignalProperty:
mpWidget->setSignalAttribute(mAttr, *p.getSignalValue());
break;
}
*/
}
// --------------------------------------------------------------------------------
#pragma mark MLReporter
MLReporter::MLReporter(MLPropertySet* m) :
MLPropertyListener(m)
{
}
MLReporter::~MLReporter()
{
}
// ----------------------------------------------------------------
// parameter viewing
// add a parameter view.
// when param p changes, attribute attr of Widget w will be set to the param's value.
//
void MLReporter::addPropertyViewToMap(MLSymbol p, MLWidget* w, MLSymbol attr)
{
mPropertyViewsMap[p].push_back(MLPropertyViewPtr(new MLPropertyView(w, attr)));
}
void MLReporter::doPropertyChangeAction(MLSymbol prop, const MLProperty& newVal)
{
// do we have viewers for this parameter?
MLPropertyViewListMap::iterator look = mPropertyViewsMap.find(prop);
if (look != mPropertyViewsMap.end())
{
// run viewers
MLPropertyViewList viewers = look->second;
for(MLPropertyViewList::iterator vit = viewers.begin(); vit != viewers.end(); vit++)
{
MLPropertyViewPtr pv = (*vit);
const MLPropertyView& v = (*pv);
v.view(newVal);
}
}
}
| 24.114943 | 86 | 0.638227 | afofo |
d5c25e539cbb9f6f38b23b843fb68da4f6c5dfe7 | 68,739 | cpp | C++ | src/louischessx/chessboard_eval.cpp | louishobson/louischessx | cc97e4ef4b716bfa9d83435f1f0cb8512bd1c4f4 | [
"MIT"
] | null | null | null | src/louischessx/chessboard_eval.cpp | louishobson/louischessx | cc97e4ef4b716bfa9d83435f1f0cb8512bd1c4f4 | [
"MIT"
] | null | null | null | src/louischessx/chessboard_eval.cpp | louishobson/louischessx | cc97e4ef4b716bfa9d83435f1f0cb8512bd1c4f4 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Louis Hobson <louis-hobson@hotmail.co.uk>. All Rights Reserved.
*
* Distributed under MIT licence as a part of the Chess C++ library.
* For details, see: https://github.com/louishobson/Chess/blob/master/LICENSE
*
* src/chess/chessboard_eval.cpp
*
* Implementation of evaluation methods in include/chess/chessboard.h
*
*/
/* INCLUDES */
#include <louischessx/chessboard.h>
/* BOARD EVALUATION */
/** @name get_check_info
*
* @brief Get information about the check state of a color's king
* @param pc: The color who's king we will look at
* @return check_info_t
*/
chess::chessboard::check_info_t chess::chessboard::get_check_info ( pcolor pc ) const chess_validate_throw
{
/* SETUP */
/* The output check info */
check_info_t check_info;
/* Get the other color */
const pcolor npc = other_color ( pc );
/* Get the friendly and opposing pieces */
const bitboard friendly = bb ( pc );
const bitboard opposing = bb ( npc );
/* Get the king and position of the colored king */
const bitboard king = bb ( pc, ptype::king );
const int king_pos = king.trailing_zeros ();
/* Get the positions of the opposing straight and diagonal pieces */
const bitboard op_straight = bb ( npc, ptype::queen ) | bb ( npc, ptype::rook );
const bitboard op_diagonal = bb ( npc, ptype::queen ) | bb ( npc, ptype::bishop );
/* Get the primary propagator.
* Primary propagator of not opposing means that spans will overlook friendly pieces.
* The secondary propagator will be universe.
*/
const bitboard pp = ~opposing;
const bitboard sp = ~bitboard {};
/* KING, KNIGHTS AND PAWNS */
/* Throw if kings are adjacent (this should never occur) */
#if CHESS_VALIDATE
if ( bitboard::king_attack_lookup ( king_pos ) & bb ( npc, ptype::king ) ) throw std::runtime_error { "Adjacent king found in check_info ()." };
#endif
/* Add checking knights */
check_info.check_vectors |= bitboard::knight_attack_lookup ( king_pos ) & bb ( npc, ptype::knight );
/* Switch depending on pc and add checking pawns */
if ( pc == pcolor::white )
check_info.check_vectors |= king.pawn_any_attack_n () & bb ( pcolor::black, ptype::pawn );
else
check_info.check_vectors |= king.pawn_any_attack_s () & bb ( pcolor::white, ptype::pawn );
/* SLIDING PIECES */
/* Iterate through the straight compass to see if those sliding pieces could be attacking */
if ( bitboard::straight_attack_lookup ( king_pos ) & op_straight )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), king_pos ) & op_straight )
{
/* Span the king in the current direction */
const bitboard king_span = king.rook_attack ( dir, pp, sp );
/* Get the checking and blocking pieces */
const bitboard checking = king_span & op_straight;
const bitboard blocking = king_span & friendly;
/* Add check info */
check_info.check_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_empty () );
check_info.pin_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_singleton () );
}
}
/* Iterate through the diagonal compass to see if those sliding pieces could be attacking */
if ( bitboard::diagonal_attack_lookup ( king_pos ) & op_diagonal )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), king_pos ) & op_diagonal )
{
/* Span the king in the current direction */
const bitboard king_span = king.bishop_attack ( dir, pp, sp );
/* Get the checking and blocking pieces */
const bitboard checking = king_span & op_diagonal;
const bitboard blocking = king_span & friendly;
/* Add check info */
check_info.check_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_empty () );
check_info.pin_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_singleton () );
}
}
/* SET REMAINING VARIABLES AND RETURN */
/* Get the check count */
check_info.check_count = ( check_info.check_vectors & bb ( npc ) ).popcount ();
/* Set the check vectors along straight and diagonal paths */
check_info.straight_check_vectors = check_info.check_vectors & bitboard::straight_attack_lookup ( king_pos );
check_info.diagonal_check_vectors = check_info.check_vectors & bitboard::diagonal_attack_lookup ( king_pos );
/* Set the pin vectors along straight and diagonal paths */
check_info.straight_pin_vectors = check_info.pin_vectors & bitboard::straight_attack_lookup ( king_pos );
check_info.diagonal_pin_vectors = check_info.pin_vectors & bitboard::diagonal_attack_lookup ( king_pos );
/* Set check_vectors_dep_check_count */
check_info.check_vectors_dep_check_count = check_info.check_vectors.all_if ( check_info.check_count == 0 ).only_if ( check_info.check_count < 2 );
/* Return the info */
return check_info;
}
/** @name is_protected
*
* @brief Returns true if the board position is protected by the player specified.
* There is no restriction on what piece is at the position, since any piece in the position is ignored.
* @param pc: The color who is defending.
* @param pos: The position of the cell to check the defence of.
* @return boolean
*/
bool chess::chessboard::is_protected ( pcolor pc, int pos ) const chess_validate_throw
{
/* SETUP */
/* Get a bitboard from pos */
const bitboard pos_bb = singleton_bitboard ( pos );
/* Get the positions of the friendly straight and diagonal pieces */
const bitboard fr_straight = bb ( pc, ptype::queen ) | bb ( pc, ptype::rook );
const bitboard fr_diagonal = bb ( pc, ptype::queen ) | bb ( pc, ptype::bishop );
/* Get the propagators.
* Primary propagator of not non-occupied will mean the span will stop at the first piece.
* The secondary propagator of friendly pieces means the span will include a friendly piece if found.
*/
const bitboard pp = ~bb ();
const bitboard sp = bb ( pc );
/* Get the adjacent open cells. These are the cells which don't contain an enemy piece or a friendly pawn, knight or king (and protection from a sliding piece could be blocked) */
const bitboard adj_open_cells = bitboard::king_attack_lookup ( pos ) & ~bb ( other_color ( pc ) ) & ~bb ( pc, ptype::pawn ) & ~bb ( pc, ptype::knight ) & ~bb ( pc, ptype::king );
/* KING, KNIGHTS AND PAWNS */
/* Look for an adjacent king */
if ( bitboard::king_attack_lookup ( pos ) & bb ( pc, ptype::king ) ) return true;
/* Look for defending knights */
if ( bitboard::knight_attack_lookup ( pos ) & bb ( pc, ptype::knight ) ) return true;
/* Switch depending on pc and look for defending pawns */
if ( pc == pcolor::white )
{ if ( pos_bb.pawn_any_attack_s () & bb ( pcolor::white, ptype::pawn ) ) return true; }
else
{ if ( pos_bb.pawn_any_attack_n () & bb ( pcolor::black, ptype::pawn ) ) return true; }
/* SLIDING PIECES */
/* Iterate through the straight compass to see if those sliding pieces could be defending */
if ( bitboard::straight_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::straight_attack_lookup ( pos ).has_common ( fr_straight ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_straight ) )
if ( pos_bb.rook_attack ( dir, pp, sp ) & fr_straight ) return true;
}
/* Iterate through the diagonal compass to see if those sliding pieces could be defending */
if ( bitboard::diagonal_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::diagonal_attack_lookup ( pos ).has_common ( fr_diagonal ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_diagonal ) )
if ( pos_bb.bishop_attack ( dir, pp, sp ) & fr_diagonal ) return true;
}
/* Return false */
return false;
}
/** @name get_least_valuable_attacker
*
* @brief Takes a color and position and finds the least valuable piece attacking that color.
* @param pc: The color attacking.
* @param pos: The position being attacked.
* @return A pair of ptype and position, no_piece and -1 if no attacker is found.
*/
std::pair<chess::ptype, int> chess::chessboard::get_least_valuable_attacker ( pcolor pc, int pos ) const chess_validate_throw
{
/* SETUP */
/* Get the check info */
const check_info_t check_info = get_check_info ( pc );
/* If pos is not part of check_vectors_dep_check_count, then no move will leave the king not in check, so no move is possible */
if ( !check_info.check_vectors_dep_check_count.test ( pos ) ) return { ptype::no_piece, 0 };
/* Get a bitboard from pos */
const bitboard pos_bb = singleton_bitboard ( pos );
/* Get the positions of the friendly straight and diagonal pieces. Disregard straight pieces on diagonal pin vectors and vice versa. */
const bitboard fr_straight = ( bb ( pc, ptype::queen ) | bb ( pc, ptype::rook ) ) & ~check_info.diagonal_pin_vectors;
const bitboard fr_diagonal = ( bb ( pc, ptype::queen ) | bb ( pc, ptype::bishop ) ) & ~check_info.straight_pin_vectors;
/* Get the propagators.
* Primary propagator of not non-occupied will mean the span will stop at the first piece.
* The secondary propagator of friendly pieces means the span will include a friendly piece if found.
*/
const bitboard pp = ~bb ();
const bitboard sp = bb ( pc );
/* Get the adjacent open cells. These are the cells which don't contain an enemy piece or a friendly pawn, knight or king (and protection from a sliding piece could be blocked) */
const bitboard adj_open_cells = bitboard::king_attack_lookup ( pos ) & ~bb ( other_color ( pc ) ) & ~bb ( pc, ptype::pawn ) & ~bb ( pc, ptype::knight ) & ~bb ( pc, ptype::king );
/* PAWNS */
{
/* Switch depending on pc and look for attacking pawns */
bitboard attackers = ( pc == pcolor::white ? pos_bb.pawn_any_attack_s () : pos_bb.pawn_any_attack_n () ) & bb ( pc, ptype::pawn );
/* Remove pawns on straight pin vectors */
attackers &= ~check_info.straight_pin_vectors;
/* Remove the pawns on diagonal pin vectors, if they move off of their pin vector */
attackers &= ~( attackers & check_info.diagonal_pin_vectors ).only_if_not ( check_info.diagonal_pin_vectors.test ( pos ) );
/* If there are any pawns left, return one of them */
if ( attackers ) return { ptype::pawn, attackers.trailing_zeros () };
}
/* KNIGHTS */
{
/* Get the attacking knights */
bitboard attackers = bitboard::knight_attack_lookup ( pos ) & bb ( pc, ptype::knight );
/* Remove those which are on pin vectors */
attackers &= ~check_info.pin_vectors;
/* If there are any knights left, return one of them */
if ( attackers ) return { ptype::knight, attackers.trailing_zeros () };
}
/* SLIDING PIECES */
/* If an attacking queen is found, the rest of the directions must be checked for lower value pieces.
* Hence keep a variable storing the position of a queen, if found.
*/
int attacking_queen_pos = -1;
/* Iterate through diagonal sliding pieces first, since this way finding a bishop or rook can cause immediate return */
/* Iterate through the diagonal compass to see if those sliding pieces could be defending */
if ( bitboard::diagonal_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::diagonal_attack_lookup ( pos ).has_common ( fr_diagonal ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_diagonal ) )
{
/* Get the attacker */
bitboard attacker = pos_bb.bishop_attack ( dir, pp, sp ) & fr_diagonal;
/* Get if there is an attacker, and it does not move off of a pin vector */
if ( attacker && !( attacker.contains ( check_info.diagonal_pin_vectors ) && !check_info.diagonal_pin_vectors.test ( pos ) ) )
{
/* Get the position */
const int attacker_pos = attacker.trailing_zeros ();
/* If is a bishop, return now, else set attacking_queen_pos */
if ( bb ( pc, ptype::bishop ).test ( attacker_pos ) ) return { ptype::bishop, attacker_pos }; else attacking_queen_pos = attacker_pos;
}
}
}
/* Iterate through the straight compass to see if those sliding pieces could be attacking */
if ( bitboard::straight_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::straight_attack_lookup ( pos ).has_common ( fr_straight ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_straight ) )
{
/* Get the attackers */
bitboard attacker = pos_bb.rook_attack ( dir, pp, sp ) & fr_straight;
/* Get if there is an attacker, and it does not move off of a pin vector */
if ( attacker && !( attacker.contains ( check_info.straight_pin_vectors ) && !check_info.straight_pin_vectors.test ( pos ) ) )
{
/* Get the position */
const int attacker_pos = attacker.trailing_zeros ();
/* If is a rook, return now, else set attacking_queen_pos */
if ( bb ( pc, ptype::rook ).test ( attacker_pos ) ) return { ptype::rook, attacker_pos }; else attacking_queen_pos = attacker_pos;
}
}
}
/* If an attacking queen was found, return that */
if ( attacking_queen_pos != -1 ) return { ptype::queen, attacking_queen_pos };
/* KING */
/* Get if there is an adjacent king */
if ( bitboard::king_attack_lookup ( pos ) & bb ( pc, ptype::king ) )
{
/* If pos is not protected by the other color, return the king as attacking */
if ( !is_protected ( other_color ( pc ), pos ) ) return { ptype::king, bb ( pc, ptype::king ).trailing_zeros () };
}
/* NO PIECE */
/* Return no_piece */
return { ptype::no_piece, -1 };
}
/** @name static_exchange_evaluation
*
* @brief Takes a color and position, and returns the possible material gain from the color attacking that position.
* @param pc: The color attacking.
* @param attacked_pos: The position being attacked.
* @param attacked_pt: The piece type to assume that's occupying pos. If no_piece, will be calculated.
* @param attacker_pos: The position of the first piece to attack attacked_pos.
* @param attacker_pt: The piece type that's first attacking attacked_pos. If no_piece, will be set to the least valuable attacker.
* @param prev_gain: A the gain from previous calls. Used internally, should be 0 initially.
* @return An integer, 0 meaning no matierial gain, +/- meaning material gain or loss respectively.
*/
int chess::chessboard::static_exchange_evaluation ( pcolor pc, int attacked_pos, ptype attacked_pt, int attacker_pos, ptype attacker_pt, int prev_gain ) chess_validate_throw
{
/* Create an array of material values for each ptype */
constexpr std::array<int, 7> material_values { 100, 400, 400, 600, 1100, 10000, 0 };
/* Get the attacked type, if required. Return prev_gain if there is no attacked piece. */
if ( attacked_pt == ptype::no_piece ) attacked_pt = find_type ( other_color ( pc ), attacked_pos );
if ( attacked_pt == ptype::no_piece ) return prev_gain;
/* Get the speculative gain */
const int spec_gain = prev_gain + material_values [ cast_penum ( attacked_pt ) ];
/* Possibly cutoff */
if ( std::max ( prev_gain, spec_gain ) < 0 ) return prev_gain;
/* Get the least value piece of this color attacking pos.
* If attacker_pos is set, then find the piece type at that position. Otherwise chose the least valuable attacker.
* Return prev_gain if there is no such piece.
*/
if ( attacker_pt == ptype::no_piece ) if ( attacked_pos != -1 ) attacker_pt = find_type ( pc, attacker_pos ); else
std::tie ( attacker_pt, attacker_pos ) = get_least_valuable_attacker ( pc, attacked_pos );
if ( attacker_pt == ptype::no_piece ) return prev_gain;
/* Make the capture */
get_bb ( pc ).reset ( attacker_pos );
get_bb ( pc, attacker_pt ).reset ( attacker_pos );
get_bb ( pc ).set ( attacked_pos );
get_bb ( pc, attacker_pt ).set ( attacked_pos );
get_bb ( other_color ( pc ) ).reset ( attacked_pos );
get_bb ( other_color ( pc ), attacked_pt ).reset ( attacked_pos );
/* Get the gain from see */
const int gain = std::max ( prev_gain, -static_exchange_evaluation ( other_color ( pc ), attacked_pos, attacker_pt, -1, ptype::no_piece, -spec_gain ) );
/* Unmake the capture */
get_bb ( other_color ( pc ) ).set ( attacked_pos );
get_bb ( other_color ( pc ), attacked_pt ).set ( attacked_pos );
get_bb ( pc ).reset ( attacked_pos );
get_bb ( pc, attacker_pt ).reset ( attacked_pos );
get_bb ( pc ).set ( attacker_pos );
get_bb ( pc, attacker_pt ).set ( attacker_pos );
/* Return the gain */
return gain;
}
/** @name evaluate
*
* @brief Symmetrically evaluate the board state.
* Note that although is non-const, a call to this function will leave the board unmodified.
* @param pc: The color who's move it is next
* @return Integer value, positive for pc, negative for not pc
*/
int chess::chessboard::evaluate ( pcolor pc )
{
/* TERMINOLOGY */
/* Here, a piece refers to any chessman, including pawns and kings.
* Restricted pieces, or restrictives, do not include pawns or kings.
*
* It's important to note the difference between general attacks and legal attacks.
*
* An attack is any position a piece could end up in and potentially capture, regardless of if A) it leaves the king in check, or B) if a friendly piece is in the attack set.
* Legal attacks must be currently possible moves, including A) not leaving the king in check, and B) not attacking friendly pieces, and C) pawns not attacking empty cells.
* Note that a pawn push is not an attack, since a pawn cannot capture by pushing.
*
* A capture is a legal attack on an enemy piece.
* A restricted capture is a legal attack on a restricted enemy piece.
*
* Mobility is the number of distinct strictly legal moves. If a mobility is zero, that means that color is in checkmate.
*/
/* CONSTANTS */
/* Masks */
constexpr bitboard white_center { 0x0000181818000000 }, black_center { 0x0000001818180000 };
constexpr bitboard white_bishop_initial_cells { 0x0000000000000024 }, black_bishop_initial_cells { 0x2400000000000000 };
constexpr bitboard white_knight_initial_cells { 0x0000000000000042 }, black_knight_initial_cells { 0x4200000000000000 };
/* Material values */
constexpr int QUEEN { 1100 }; // 19
constexpr int ROOK { 600 }; // 10
constexpr int BISHOP { 400 }; // 7
constexpr int KNIGHT { 400 }; // 7
constexpr int PAWN { 100 }; // 2
/* Pawns */
constexpr int PAWN_GENERAL_ATTACKS { 1 }; // For every generally attacked cell
constexpr int CENTER_PAWNS { 20 }; // For every pawn
constexpr int PAWN_CENTER_GENERAL_ATTACKS { 10 }; // For every generally attacked cell (in the center)
constexpr int ISOLATED_PAWNS { -10 }; // For every pawn
constexpr int ISOLATED_PAWNS_ON_SEMIOPEN_FILES { -10 }; // For every pawn
constexpr int DOUBLED_PAWNS { -5 }; // Tripled pawns counts as -10 etc.
constexpr int PAWN_GENERAL_ATTACKS_ADJ_OP_KING { 20 }; // For every generally attacked cell
constexpr int PHALANGA { 20 }; // Tripple pawn counts as 40 etc.
constexpr int BLOCKED_PASSED_PAWNS { -15 }; // For each blocked passed pawn
constexpr int STRONG_SQUARES { 20 }; // For each strong square (one attacked by a friendly pawn and not an enemy pawn)
constexpr int BACKWARD_PAWNS { 10 }; // For each pawn behind a strong square (see above)
constexpr int PASSED_PAWNS_DISTANCE { 5 }; // For each passed pawn, for every square away from the 1st rank (since may be queened)
constexpr int LEGAL_ATTACKS_ON_PASSED_PAWN_TRAJECTORIES { 5 }; // For each attack
/* Sliding pieces */
constexpr int STRAIGHT_PIECES_ON_7TH_RANK { 30 }; // For each piece
constexpr int DOUBLE_BISHOP { 20 }; // If true
constexpr int STRAIGHT_PIECES_ON_OPEN_FILE { 35 }; // For each piece
constexpr int STRAIGHT_PIECES_ON_SEMIOPEN_FILE { 25 }; // For each piece
constexpr int STRAIGHT_PIECE_LEGAL_ATTACKS_ON_OPEN_FILES { 10 }; // For every legal attack
constexpr int STRAIGHT_PIECE_LEGAL_ATTACKS_ON_SEMIOPEN_FILES { 5 }; // For every legal attack
constexpr int STRAIGHT_PIECES_BEHIND_PASSED_PAWNS { 20 }; // For every piece
constexpr int DIAGONAL_PIECE_RESTRICTED_CAPTURES { 15 }; // For every restricted capture on enemy pieces (not including pawns or kings)
constexpr int RESTRICTIVES_LEGALLY_ATTACKED_BY_DIAGONAL_PIECES { 15 }; // For every restrictive, white and black (pieces not including pawns or kings)
/* Knights */
constexpr int CENTER_KNIGHTS { 20 }; // For every knight
/* Bishops and knights */
constexpr int BISHOP_OR_KNIGHT_INITIAL_CELL { -15 }; // For every bishop/knight
constexpr int DIAGONAL_OR_KNIGHT_CAPTURE_ON_STRAIGHT_PIECES { 10 }; // For every capture
constexpr int BISHOP_OR_KNIGHT_ON_STRONG_SQUARE { 20 }; // For each piece
/* Mobility and king queen mobility, for every move */
constexpr int MOBILITY { 1 }; // For every legal move
constexpr int KING_QUEEN_MOBILITY { -2 }; // For every non-capture attack, pretending the king is a queen
/* Castling */
constexpr int CASTLE_MADE { 30 }; // If true
constexpr int CASTLE_LOST { -60 }; // If true
/* Other values */
constexpr int KNIGHT_AND_QUEEN_EXIST { 10 }; // If true
constexpr int CENTER_LEGAL_ATTACKS_BY_RESTRICTIVES { 10 }; // For every attack (not including pawns or kings)
constexpr int PINNED_PIECES { -20 }; // For each (friendly) piece
/* Non-symmetrical values */
constexpr int CHECKMATE { 10000 }; // If on the enemy, -10000 if on self
constexpr int KINGS_IN_OPPOSITION { 15 }; // If the kings are one off adjacent
/* SETUP */
/* Get the check info */
const check_info_t white_check_info = get_check_info ( pcolor::white );
const check_info_t black_check_info = get_check_info ( pcolor::black );
/* Get king positions */
const int white_king_pos = bb ( pcolor::white, ptype::king ).trailing_zeros ();
const int black_king_pos = bb ( pcolor::black, ptype::king ).trailing_zeros ();
/* Get the king spans */
const bitboard white_king_span = bitboard::king_attack_lookup ( white_king_pos );
const bitboard black_king_span = bitboard::king_attack_lookup ( black_king_pos );
/* Set legalize_attacks. This is the intersection of not friendly pieces, not the enemy king, and check_vectors_dep_check_count. */
const bitboard white_legalize_attacks = ~bb ( pcolor::white ) & ~bb ( pcolor::black, ptype::king ) & white_check_info.check_vectors_dep_check_count;
const bitboard black_legalize_attacks = ~bb ( pcolor::black ) & ~bb ( pcolor::white, ptype::king ) & black_check_info.check_vectors_dep_check_count;
/* Get the restrictives */
const bitboard white_restrictives = bb ( pcolor::white, ptype::bishop ) | bb ( pcolor::white, ptype::rook ) | bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::knight );
const bitboard black_restrictives = bb ( pcolor::black, ptype::bishop ) | bb ( pcolor::black, ptype::rook ) | bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::knight );
const bitboard restrictives = white_restrictives | black_restrictives;
/* Set the primary propagator such that all empty cells are set */
const bitboard pp = ~bb ();
/* Get the white pawn rear span */
const bitboard white_pawn_rear_span = bb ( pcolor::white, ptype::pawn ).span ( compass::s );
const bitboard black_pawn_rear_span = bb ( pcolor::black, ptype::pawn ).span ( compass::n );
/* Get the pawn file fills (from the rear span and forwards fill) */
const bitboard white_pawn_file_fill = white_pawn_rear_span | bb ( pcolor::white, ptype::pawn ).fill ( compass::n );
const bitboard black_pawn_file_fill = black_pawn_rear_span | bb ( pcolor::black, ptype::pawn ).fill ( compass::s );
/* Get the open and semiopen files. White semiopen files contain no white pawns. */
const bitboard open_files = ~( white_pawn_file_fill | black_pawn_file_fill );
const bitboard white_semiopen_files = ~white_pawn_file_fill & black_pawn_file_fill;
const bitboard black_semiopen_files = ~black_pawn_file_fill & white_pawn_file_fill;
/* Get the passed pawns */
const bitboard white_passed_pawns = bb ( pcolor::white, ptype::pawn ) & ~white_pawn_rear_span & black_semiopen_files & black_semiopen_files.shift ( compass::e ) & black_semiopen_files.shift ( compass::w );
const bitboard black_passed_pawns = bb ( pcolor::black, ptype::pawn ) & ~black_pawn_rear_span & white_semiopen_files & white_semiopen_files.shift ( compass::e ) & white_semiopen_files.shift ( compass::w );
/* Get the cells behind passed pawns.
* This is the span between the passed pawns and the next piece back, including the next piece back but not the pawn.
*/
const bitboard white_behind_passed_pawns = white_passed_pawns.span ( compass::s, pp, ~bitboard {} );
const bitboard black_behind_passed_pawns = black_passed_pawns.span ( compass::n, pp, ~bitboard {} );
/* Get the cells in front of passed pawns.
* This is the span between the passed pawns and the opposite end of the board, not including the pawn.
*/
const bitboard white_passed_pawn_trajectories = white_passed_pawns.span ( compass::n );
const bitboard black_passed_pawn_trajectories = black_passed_pawns.span ( compass::s );
/* ACCUMULATORS */
/* The value of the evaluation function */
int value = 0;
/* Mobilities */
int white_mobility = 0, black_mobility = 0;
/* Partial defence unions. Gives cells which are protected by friendly pieces.
* This is found from the union of all general attacks and can be used to determine opposing king's possible moves.
* However, pinned sliding pieces' general attacks are not included in this union (due to complexity to calculate), hence 'partial'.
*/
bitboard white_partial_defence_union, black_partial_defence_union;
/* Accumulate the difference between white and black's straight piece legal attacks on open and semiopen files */
int straight_legal_attacks_open_diff = 0, straight_legal_attacks_semiopen_diff = 0;
/* Accumulate the difference between white and black's attacks the center by restrictives */
int center_legal_attacks_by_restrictives_diff = 0;
/* Accumulate the difference between white and black's number of restricted captures by diagonal pieces */
int diagonal_restricted_captures_diff = 0;
/* Accumulate the restricted pieces attacked by diagonal pieces */
bitboard restrictives_legally_attacked_by_white_diagonal_pieces, restrictives_legally_attacked_by_black_diagonal_pieces;
/* Accumulate bishop or knight captures on enemy straight pieces */
int diagonal_or_knight_captures_on_straight_diff = 0;
/* Accumulate attacks on passed pawn trajectories */
int legal_attacks_on_passed_pawn_trajectories_diff = 0;
/* NON-PINNED SLIDING PIECES */
/* Deal with non-pinned sliding pieces of both colors in one go.
* If in double check, check_vectors_dep_check_count will remove all attacks the attacks.
*/
/* Scope new bitboards */
{
/* Set straight and diagonal pieces */
const bitboard white_straight_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) & ~white_check_info.pin_vectors;
const bitboard white_diagonal_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::bishop ) ) & ~white_check_info.pin_vectors;
const bitboard black_straight_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) & ~black_check_info.pin_vectors;
const bitboard black_diagonal_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::bishop ) ) & ~black_check_info.pin_vectors;
/* Start compasses */
straight_compass straight_dir;
diagonal_compass diagonal_dir;
/* Iterate through the compass to get all queen, rook and bishop attacks */
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( int i = 0; i < 4; ++i )
{
/* Get the compasses */
straight_dir = straight_compass_array [ i ];
diagonal_dir = diagonal_compass_array [ i ];
/* Apply all shifts to get straight and diagonal general attacks (note that sp is universe to get general attacks)
* This allows us to union to the defence set first.
*/
bitboard white_straight_attacks = white_straight_pieces.rook_attack ( straight_dir, pp, ~bitboard {} );
bitboard white_diagonal_attacks = white_diagonal_pieces.bishop_attack ( diagonal_dir, pp, ~bitboard {} );
bitboard black_straight_attacks = black_straight_pieces.rook_attack ( straight_dir, pp, ~bitboard {} );
bitboard black_diagonal_attacks = black_diagonal_pieces.bishop_attack ( diagonal_dir, pp, ~bitboard {} );
/* Union defence */
white_partial_defence_union |= white_straight_attacks | white_diagonal_attacks;
black_partial_defence_union |= black_straight_attacks | black_diagonal_attacks;
/* Legalize the attacks */
white_straight_attacks &= white_legalize_attacks;
white_diagonal_attacks &= white_legalize_attacks;
black_straight_attacks &= black_legalize_attacks;
black_diagonal_attacks &= black_legalize_attacks;
/* Sum mobility */
white_mobility += white_straight_attacks.popcount () + white_diagonal_attacks.popcount ();
black_mobility += black_straight_attacks.popcount () + black_diagonal_attacks.popcount ();
/* Sum rook attacks on open files */
straight_legal_attacks_open_diff += ( white_straight_attacks & open_files ).popcount ();
straight_legal_attacks_open_diff -= ( black_straight_attacks & open_files ).popcount ();
/* Sum rook attacks on semiopen files */
straight_legal_attacks_semiopen_diff += ( white_straight_attacks & white_semiopen_files ).popcount ();
straight_legal_attacks_semiopen_diff -= ( black_straight_attacks & black_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( white_straight_attacks & white_center ).popcount () + ( white_diagonal_attacks & white_center ).popcount ();
center_legal_attacks_by_restrictives_diff -= ( black_straight_attacks & black_center ).popcount () + ( black_diagonal_attacks & black_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_white_diagonal_pieces |= restrictives & white_diagonal_attacks;
restrictives_legally_attacked_by_black_diagonal_pieces |= restrictives & black_diagonal_attacks;
/* Sum the restricted captures by diagonal pieces */
diagonal_restricted_captures_diff += ( white_diagonal_attacks & black_restrictives ).popcount ();
diagonal_restricted_captures_diff -= ( black_diagonal_attacks & white_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff += ( white_diagonal_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
diagonal_or_knight_captures_on_straight_diff -= ( black_diagonal_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( white_straight_attacks & black_passed_pawn_trajectories ).popcount () + ( white_diagonal_attacks & black_passed_pawn_trajectories ).popcount ();
legal_attacks_on_passed_pawn_trajectories_diff -= ( black_straight_attacks & white_passed_pawn_trajectories ).popcount () + ( black_diagonal_attacks & white_passed_pawn_trajectories ).popcount ();
}
}
/* PINNED SLIDING PIECES */
/* Pinned pieces are handelled separately for each color.
* Only if that color is not in check will they be considered.
* The flood spans must be calculated separately for straight and diagonal, since otherwise the flood could spill onto adjacent pin vectors.
*/
/* White pinned pieces */
if ( white_check_info.pin_vectors.is_nonempty () & white_check_info.check_count == 0 )
{
/* Get the straight and diagonal pinned pieces which can move.
* Hence the straight pinned pieces are all on straight pin vectors, and diagonal pinned pieces are all on diagonal pin vectors.
*/
const bitboard straight_pinned_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) & white_check_info.straight_pin_vectors;
const bitboard diagonal_pinned_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::bishop ) ) & white_check_info.diagonal_pin_vectors;
/* Initially set pinned attacks to empty */
bitboard straight_pinned_attacks, diagonal_pinned_attacks;
/* Flood span straight and diagonal (but only if there are pieces to flood) */
if ( straight_pinned_pieces ) straight_pinned_attacks = straight_pinned_pieces.straight_flood_span ( white_check_info.straight_pin_vectors );
if ( diagonal_pinned_pieces ) diagonal_pinned_attacks = diagonal_pinned_pieces.diagonal_flood_span ( white_check_info.diagonal_pin_vectors );
/* Get the union of pinned attacks */
const bitboard pinned_attacks = straight_pinned_attacks | diagonal_pinned_attacks;
/* Only continue if there were appropriate pinned attacks */
if ( pinned_attacks )
{
/* Union defence (at this point the defence union becomes partial) */
white_partial_defence_union |= pinned_attacks | bb ( pcolor::white, ptype::king );
/* Sum mobility */
white_mobility += pinned_attacks.popcount ();
/* Sum rook attacks on open and semiopen files */
straight_legal_attacks_open_diff += ( straight_pinned_attacks & open_files ).popcount ();
straight_legal_attacks_semiopen_diff += ( straight_pinned_attacks & white_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( pinned_attacks & white_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_white_diagonal_pieces |= restrictives & diagonal_pinned_attacks;
/* Get the number of diagonal restricted captures */
diagonal_restricted_captures_diff += ( diagonal_pinned_attacks & black_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff += ( diagonal_pinned_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( pinned_attacks & black_passed_pawn_trajectories ).popcount ();
}
}
/* Black pinned pieces */
if ( black_check_info.pin_vectors.is_nonempty () & black_check_info.check_count == 0 )
{
/* Get the straight and diagonal pinned pieces which can move.
* Hence the straight pinned pieces are all on straight pin vectors, and diagonal pinned pieces are all on diagonal pin vectors.
*/
const bitboard straight_pinned_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) & black_check_info.straight_pin_vectors;
const bitboard diagonal_pinned_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::bishop ) ) & black_check_info.diagonal_pin_vectors;
/* Initially set pinned attacks to empty */
bitboard straight_pinned_attacks, diagonal_pinned_attacks;
/* Flood span straight and diagonal (but only if there are pieces to flood) */
if ( straight_pinned_pieces ) straight_pinned_attacks = straight_pinned_pieces.straight_flood_span ( black_check_info.straight_pin_vectors );
if ( diagonal_pinned_pieces ) diagonal_pinned_attacks = diagonal_pinned_pieces.diagonal_flood_span ( black_check_info.diagonal_pin_vectors );
/* Get the union of pinned attacks */
const bitboard pinned_attacks = straight_pinned_attacks | diagonal_pinned_attacks;
/* Only continue if there were appropriate pinned attacks */
if ( pinned_attacks )
{
/* Union defence (at this point the defence union becomes partial) */
black_partial_defence_union |= pinned_attacks | bb ( pcolor::black, ptype::king );
/* Sum mobility */
black_mobility += pinned_attacks.popcount ();
/* Sum rook attacks on open and semiopen files */
straight_legal_attacks_open_diff -= ( straight_pinned_attacks & open_files ).popcount ();
straight_legal_attacks_semiopen_diff -= ( straight_pinned_attacks & black_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff -= ( pinned_attacks & black_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_black_diagonal_pieces |= restrictives & diagonal_pinned_attacks;
/* Get the number of diagonal restricted captures */
diagonal_restricted_captures_diff -= ( diagonal_pinned_attacks & white_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff -= ( diagonal_pinned_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff -= ( pinned_attacks & white_passed_pawn_trajectories ).popcount ();
}
}
/* GENERAL SLIDING PIECES */
/* Scope new bitboards */
{
/* Get straight pieces */
const bitboard white_straight_pieces = bb ( pcolor::white, ptype::rook ) | bb ( pcolor::white, ptype::queen );
const bitboard black_straight_pieces = bb ( pcolor::black, ptype::rook ) | bb ( pcolor::black, ptype::queen );
/* Incorperate the material cost into value */
value += BISHOP * ( bb ( pcolor::white, ptype::bishop ).popcount () - bb ( pcolor::black, ptype::bishop ).popcount () );
value += ROOK * ( bb ( pcolor::white, ptype::rook ).popcount () - bb ( pcolor::black, ptype::rook ).popcount () );
value += QUEEN * ( bb ( pcolor::white, ptype::queen ).popcount () - bb ( pcolor::black, ptype::queen ).popcount () );
/* Incorporate straight pieces on 7th (or 2nd) rank into value */
{
const bitboard white_straight_pieces_7th_rank = white_straight_pieces & bitboard { bitboard::masks::rank_7 };
const bitboard black_straight_pieces_2nd_rank = black_straight_pieces & bitboard { bitboard::masks::rank_2 };
value += STRAIGHT_PIECES_ON_7TH_RANK * ( white_straight_pieces_7th_rank.popcount () - black_straight_pieces_2nd_rank.popcount () );
}
/* Incorporate bishops on initial cells into value */
{
const bitboard white_initial_bishops = bb ( pcolor::white, ptype::bishop ) & white_bishop_initial_cells;
const bitboard black_initial_bishops = bb ( pcolor::black, ptype::bishop ) & black_bishop_initial_cells;
value += BISHOP_OR_KNIGHT_INITIAL_CELL * ( white_initial_bishops.popcount () - black_initial_bishops.popcount () );
}
/* Incorporate double bishops into value */
value += DOUBLE_BISHOP * ( ( bb ( pcolor::white, ptype::bishop ).popcount () == 2 ) - ( bb ( pcolor::black, ptype::bishop ).popcount () == 2 ) );
/* Incorporate straight pieces and attacks on open/semiopen files into value */
value += STRAIGHT_PIECES_ON_OPEN_FILE * ( ( white_straight_pieces & open_files ).popcount () - ( black_straight_pieces & open_files ).popcount () );
value += STRAIGHT_PIECES_ON_SEMIOPEN_FILE * ( ( white_straight_pieces & white_semiopen_files ).popcount () - ( black_straight_pieces & black_semiopen_files ).popcount () );
value += STRAIGHT_PIECE_LEGAL_ATTACKS_ON_OPEN_FILES * straight_legal_attacks_open_diff;
value += STRAIGHT_PIECE_LEGAL_ATTACKS_ON_SEMIOPEN_FILES * straight_legal_attacks_semiopen_diff;
/* Incorporate straight pieces behind passed pawns into value */
value += STRAIGHT_PIECES_BEHIND_PASSED_PAWNS * ( ( white_straight_pieces & white_behind_passed_pawns ).popcount () - ( black_straight_pieces & black_behind_passed_pawns ).popcount () );
/* Incorporate restrictives attacked by diagonal pieces */
value += RESTRICTIVES_LEGALLY_ATTACKED_BY_DIAGONAL_PIECES * ( restrictives_legally_attacked_by_white_diagonal_pieces.popcount () - restrictives_legally_attacked_by_black_diagonal_pieces.popcount () );
/* Incorporate diagonal pieces restricted captures into value */
value += DIAGONAL_PIECE_RESTRICTED_CAPTURES * diagonal_restricted_captures_diff;
}
/* KNIGHTS */
/* Each color is considered separately in loops */
/* Scope new bitboards */
{
/* Iterate through white knights to get attacks.
* If in double check, white_check_info.check_vectors_dep_check_count will remove all moves.
*/
for ( bitboard white_knights = bb ( pcolor::white, ptype::knight ); white_knights; )
{
/* Get the position of the next knight and its general attacks */
const int pos = white_knights.trailing_zeros (); white_knights.reset ( pos );
bitboard knight_attacks = bitboard::knight_attack_lookup ( pos );
/* Union defence */
white_partial_defence_union |= knight_attacks;
/* Find legal knight attacks. Note that a pinned knight cannot move along its pin vector, hence cannot move at all. */
knight_attacks = knight_attacks.only_if ( !white_check_info.pin_vectors.test ( pos ) ) & white_legalize_attacks;
/* Sum mobility */
white_mobility += knight_attacks.popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( knight_attacks & white_center ).popcount ();
/* Sum the legal captures on enemy straight pieces by knights */
diagonal_or_knight_captures_on_straight_diff += ( knight_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( knight_attacks & black_passed_pawn_trajectories ).popcount ();
}
/* Iterate through black knights to get attacks */
for ( bitboard black_knights = bb ( pcolor::black, ptype::knight ); black_knights; )
{
/* Get the position of the next knight and its general attacks */
const int pos = black_knights.trailing_zeros (); black_knights.reset ( pos );
bitboard knight_attacks = bitboard::knight_attack_lookup ( pos );
/* Union defence */
black_partial_defence_union |= knight_attacks;
/* Find legal knight attacks. Note that a pinned knight cannot move along its pin vector, hence cannot move at all. */
knight_attacks = knight_attacks.only_if ( !black_check_info.pin_vectors.test ( pos ) ) & black_legalize_attacks;
/* Sum mobility */
black_mobility += knight_attacks.popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff -= ( knight_attacks & black_center ).popcount ();
/* Sum the legal captures on enemy straight pieces by knights */
diagonal_or_knight_captures_on_straight_diff -= ( knight_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff -= ( knight_attacks & white_passed_pawn_trajectories ).popcount ();
}
/* Incorperate the number of knights into value */
value += KNIGHT * ( bb ( pcolor::white, ptype::knight ).popcount () - bb ( pcolor::black, ptype::knight ).popcount () );
/* Incorporate knights on initial cells into value */
{
const bitboard white_initial_knights = bb ( pcolor::white, ptype::knight ) & white_knight_initial_cells;
const bitboard black_initial_knights = bb ( pcolor::black, ptype::knight ) & black_knight_initial_cells;
value += BISHOP_OR_KNIGHT_INITIAL_CELL * ( white_initial_knights.popcount () - black_initial_knights.popcount () );
}
/* Incorporate knights in the venter into value */
{
const bitboard white_center_knights = bb ( pcolor::white, ptype::knight ) & white_center;
const bitboard black_center_knights = bb ( pcolor::black, ptype::knight ) & black_center;
value += CENTER_KNIGHTS * ( white_center_knights.popcount () - black_center_knights.popcount () );
}
}
/* PAWN MOVES */
/* We can handle both colors, pinned and non-pinned pawns simultaneously, since pawn moves are more simple than sliding pieces and knights.
* Non-pinned pawns can have their moves calculated normally, but pinned pawns must first be checked as to whether they will move along their pin vector.
* There is no if-statement for double check, only check_vectors_dep_check_count is used to mask out all moves if in double check.
* This is because double check is quite unlikely, and pawn move calculations are quite cheap anyway.
*/
/* Scope the new bitboards */
{
/* Get the non-pinned pawns */
const bitboard white_non_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & ~white_check_info.pin_vectors;
const bitboard black_non_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & ~black_check_info.pin_vectors;
/* Get the straight and diagonal pinned pawns */
const bitboard white_straight_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & white_check_info.straight_pin_vectors;
const bitboard white_diagonal_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & white_check_info.diagonal_pin_vectors;
const bitboard black_straight_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & black_check_info.straight_pin_vectors;
const bitboard black_diagonal_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & black_check_info.diagonal_pin_vectors;
/* Calculations for pawn pushes.
* Non-pinned pawns can push without restriction.
* Pinned pawns can push only if they started and ended within a straight pin vector.
* If in check, ensure that the movements protected the king.
*/
const bitboard white_pawn_pushes = ( white_non_pinned_pawns.pawn_push_n ( pp ) | ( white_straight_pinned_pawns.pawn_push_n ( pp ) & white_check_info.straight_pin_vectors ) ) & white_check_info.check_vectors_dep_check_count;
const bitboard black_pawn_pushes = ( black_non_pinned_pawns.pawn_push_s ( pp ) | ( black_straight_pinned_pawns.pawn_push_s ( pp ) & black_check_info.straight_pin_vectors ) ) & black_check_info.check_vectors_dep_check_count;
/* Get general pawn attacks */
const bitboard white_pawn_attacks = bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::ne ) | bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::nw );
const bitboard black_pawn_attacks = bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::se ) | bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::sw );
/* Get the strong squares.
* These are the squares attacked by a friendly pawn, but not by an enemy pawn.
*/
const bitboard white_strong_squares = white_pawn_attacks & ~black_pawn_attacks;
const bitboard black_strong_squares = black_pawn_attacks & ~white_pawn_attacks;
/* Get pawn captures (legal pawn attacks).
* Non-pinned pawns can attack without restriction.
* Pinned pawns can attack only if they started and ended within a diagonal pin vector.
* If in check, ensure that the movements protected the king.
* En passant will be added later
*/
bitboard white_pawn_captures_e = ( white_non_pinned_pawns.pawn_attack ( diagonal_compass::ne ) | ( white_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::ne ) & white_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::black ) & white_legalize_attacks;
bitboard white_pawn_captures_w = ( white_non_pinned_pawns.pawn_attack ( diagonal_compass::nw ) | ( white_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::nw ) & white_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::black ) & white_legalize_attacks;
bitboard black_pawn_captures_e = ( black_non_pinned_pawns.pawn_attack ( diagonal_compass::se ) | ( black_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::se ) & black_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::white ) & black_legalize_attacks;
bitboard black_pawn_captures_w = ( black_non_pinned_pawns.pawn_attack ( diagonal_compass::sw ) | ( black_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::sw ) & black_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::white ) & black_legalize_attacks;
/* Save the en passant target square */
const int en_passant_target = aux_info.en_passant_target;
/* Add white en passant captures if they don't lead to check */
if ( bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::ne ).only_if ( aux_info.en_passant_color == pcolor::white ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::white, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target - 9, en_passant_target } );
if ( !is_in_check ( pc ) ) white_pawn_captures_e.set ( en_passant_target );
unmake_move_internal ();
} if ( bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::nw ).only_if ( aux_info.en_passant_color == pcolor::white ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::white, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target - 7, en_passant_target } );
if ( !is_in_check ( pc ) ) white_pawn_captures_w.set ( en_passant_target );
unmake_move_internal ();
}
/* Add black en passant captures if they don't lead to check */
if ( bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::se ).only_if ( aux_info.en_passant_color == pcolor::black ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::black, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target + 7, en_passant_target } );
if ( !is_in_check ( pc ) ) black_pawn_captures_e.set ( en_passant_target );
unmake_move_internal ();
} if ( bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::sw ).only_if ( aux_info.en_passant_color == pcolor::black ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::black, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target + 9, en_passant_target } );
if ( !is_in_check ( pc ) ) black_pawn_captures_w.set ( en_passant_target );
unmake_move_internal ();
}
/* Union defence */
white_partial_defence_union |= white_pawn_attacks;
black_partial_defence_union |= black_pawn_attacks;
/* Sum mobility */
white_mobility += white_pawn_pushes.popcount () + white_pawn_captures_e.popcount () + white_pawn_captures_w.popcount ();
black_mobility += black_pawn_pushes.popcount () + black_pawn_captures_e.popcount () + black_pawn_captures_w.popcount ();
/* Incorporate the number of pawns into value */
value += PAWN * ( bb ( pcolor::white, ptype::pawn ).popcount () - bb ( pcolor::black, ptype::pawn ).popcount () );
/* Incorporate the number of cells generally attacked by pawns into value */
value += PAWN_GENERAL_ATTACKS * ( white_pawn_attacks.popcount () - black_pawn_attacks.popcount () );
/* Incorporate strong squares into value */
value += STRONG_SQUARES * ( white_strong_squares.popcount () - black_strong_squares.popcount () );
/* Sum the legal attacks on passed pawn trajectories.
* Use pawn general attacks, since legal captures require there to be a piece present.
*/
legal_attacks_on_passed_pawn_trajectories_diff += ( white_pawn_attacks & black_passed_pawn_trajectories ).popcount () - ( black_pawn_attacks & white_passed_pawn_trajectories ).popcount ();
/* Incorperate the number of pawns in the center to value */
{
const bitboard white_center_pawns = bb ( pcolor::white, ptype::pawn ) & white_center;
const bitboard black_center_pawns = bb ( pcolor::black, ptype::pawn ) & black_center;
value += CENTER_PAWNS * ( white_center_pawns.popcount () - black_center_pawns.popcount () );
}
/* Incororate the number of center cells generally attacked by pawns into value */
{
const bitboard white_center_defence = white_pawn_attacks & white_center;
const bitboard black_center_defence = black_pawn_attacks & black_center;
value += PAWN_CENTER_GENERAL_ATTACKS * ( white_center_defence.popcount () - black_center_defence.popcount () );
}
/* Incorporate isolated pawns, and those on semiopen files, into value */
{
const bitboard white_isolated_pawns = bb ( pcolor::white, ptype::pawn ) & ~( white_pawn_file_fill.shift ( compass::e ) | white_pawn_file_fill.shift ( compass::w ) );
const bitboard black_isolated_pawns = bb ( pcolor::black, ptype::pawn ) & ~( black_pawn_file_fill.shift ( compass::e ) | black_pawn_file_fill.shift ( compass::w ) );
value += ISOLATED_PAWNS * ( white_isolated_pawns.popcount () - black_isolated_pawns.popcount () );
value += ISOLATED_PAWNS_ON_SEMIOPEN_FILES * ( ( white_isolated_pawns & white_semiopen_files ).popcount () - ( black_isolated_pawns & black_semiopen_files ).popcount () );
}
/* Incorporate the number of doubled pawns into value */
{
const bitboard white_doubled_pawns = bb ( pcolor::white, ptype::pawn ) & white_pawn_rear_span;
const bitboard black_doubled_pawns = bb ( pcolor::black, ptype::pawn ) & black_pawn_rear_span;
value += DOUBLED_PAWNS * ( white_doubled_pawns.popcount () - black_doubled_pawns.popcount () );
}
/* Incorporate the number of cells adjacent to enemy king, which are generally attacked by pawns, into value */
{
const bitboard white_pawn_defence_adj_op_king = white_pawn_attacks & black_king_span;
const bitboard black_pawn_defence_adj_op_king = black_pawn_attacks & white_king_span;
value += PAWN_GENERAL_ATTACKS_ADJ_OP_KING * ( white_pawn_defence_adj_op_king.popcount () - black_pawn_defence_adj_op_king.popcount () );
}
/* Incorporate phalanga into value */
{
const bitboard white_phalanga = bb ( pcolor::white, ptype::pawn ) & bb ( pcolor::white, ptype::pawn ).shift ( compass::e );
const bitboard black_phalanga = bb ( pcolor::black, ptype::pawn ) & bb ( pcolor::black, ptype::pawn ).shift ( compass::e );
value += PHALANGA * ( white_phalanga.popcount () - black_phalanga.popcount () );
}
/* Incorporate blocked passed pawns into value */
{
const bitboard white_blocked_passed_pawns = white_behind_passed_pawns.shift ( compass::n ).shift ( compass::n ) & bb ( pcolor::black );
const bitboard black_blocked_passed_pawns = black_behind_passed_pawns.shift ( compass::s ).shift ( compass::s ) & bb ( pcolor::white );
value += BLOCKED_PASSED_PAWNS * ( white_blocked_passed_pawns.popcount () - black_blocked_passed_pawns.popcount () );
}
/* Incorporate backwards pawns into value */
{
const bitboard white_backward_pawns = white_strong_squares.shift ( compass::s ) & bb ( pcolor::white, ptype::pawn );
const bitboard black_backward_pawns = black_strong_squares.shift ( compass::n ) & bb ( pcolor::black, ptype::pawn );
value += BACKWARD_PAWNS * ( white_backward_pawns.popcount () - black_backward_pawns.popcount () );
}
/* Incorporate bishops or knights on strong squares into value */
{
const bitboard white_bishop_or_knight_strong_squares = white_strong_squares & ( bb ( pcolor::white, ptype::bishop ) | bb ( pcolor::white, ptype::knight ) );
const bitboard black_bishop_or_knight_strong_squares = black_strong_squares & ( bb ( pcolor::black, ptype::bishop ) | bb ( pcolor::black, ptype::knight ) );
value += BISHOP_OR_KNIGHT_ON_STRONG_SQUARE * ( white_bishop_or_knight_strong_squares.popcount () - black_bishop_or_knight_strong_squares.popcount () );
}
/* Incorporate passed pawns into value */
{
const bitboard white_passed_pawns_distance = white_passed_pawns.fill ( compass::s );
const bitboard black_passed_pawns_distance = black_passed_pawns.fill ( compass::n );
value += PASSED_PAWNS_DISTANCE * ( white_passed_pawns_distance.popcount () - black_passed_pawns_distance.popcount () );
}
}
/* KING ATTACKS */
/* Use the king position to look for possible attacks.
* As well as using the partial defence union, check any left over king moves for check.
*/
/* Scope the new bitboards */
{
/* Get all the king legal attacks (into empty space or an opposing piece).
* The empty space must not be protected by the opponent, and the kings must not be left adjacent.
* Note that some illegal attacks may be included here, if there are any opposing pinned sliding pieces.
*/
bitboard white_king_attacks = white_king_span & ~black_king_span & ~bb ( pcolor::white ) & ~black_partial_defence_union;
bitboard black_king_attacks = black_king_span & ~white_king_span & ~bb ( pcolor::black ) & ~white_partial_defence_union;
/* Validate the remaining white king moves */
if ( white_king_attacks )
{
/* Temporarily unset the king */
get_bb ( pcolor::white ).reset ( white_king_pos );
get_bb ( pcolor::white, ptype::king ).reset ( white_king_pos );
/* Loop through the white king attacks to validate they don't lead to check */
for ( bitboard white_king_attacks_temp = white_king_attacks; white_king_attacks_temp; )
{
/* Get the position of the next king attack then use the position to determine if it is defended by the opponent */
int pos = white_king_attacks_temp.trailing_zeros ();
white_king_attacks.reset_if ( pos, is_protected ( pcolor::black, pos ) );
white_king_attacks_temp.reset ( pos );
}
/* Reset the king */
get_bb ( pcolor::white ).set ( white_king_pos );
get_bb ( pcolor::white, ptype::king ).set ( white_king_pos );
}
/* Validate the remaining black king moves */
if ( black_king_attacks )
{
/* Temporarily unset the king */
get_bb ( pcolor::black ).reset ( black_king_pos );
get_bb ( pcolor::black, ptype::king ).reset ( black_king_pos );
/* Loop through the white king attacks to validate they don't lead to check */
for ( bitboard black_king_attacks_temp = black_king_attacks; black_king_attacks_temp; )
{
/* Get the position of the next king attack then use the position to determine if it is defended by the opponent */
int pos = black_king_attacks_temp.trailing_zeros ();
black_king_attacks.reset_if ( pos, is_protected ( pcolor::white, pos ) );
black_king_attacks_temp.reset ( pos );
}
/* Reset the king */
get_bb ( pcolor::black ).set ( black_king_pos );
get_bb ( pcolor::black, ptype::king ).set ( black_king_pos );
}
/* Calculate king queen fill. Flood fill using pp and queen attack lookup as a propagator. */
const bitboard white_king_queen_fill = bb ( pcolor::white, ptype::king ).straight_flood_fill ( bitboard::straight_attack_lookup ( white_king_pos ) & pp )
| bb ( pcolor::white, ptype::king ).diagonal_flood_fill ( bitboard::diagonal_attack_lookup ( white_king_pos ) & pp );
const bitboard black_king_queen_fill = bb ( pcolor::black, ptype::king ).straight_flood_fill ( bitboard::straight_attack_lookup ( black_king_pos ) & pp )
| bb ( pcolor::black, ptype::king ).diagonal_flood_fill ( bitboard::diagonal_attack_lookup ( black_king_pos ) & pp );
/* Sum mobility */
white_mobility += white_king_attacks.popcount () + can_kingside_castle ( pcolor::white, white_check_info ) + can_queenside_castle ( pcolor::white, white_check_info );
black_mobility += black_king_attacks.popcount () + can_kingside_castle ( pcolor::black, black_check_info ) + can_queenside_castle ( pcolor::black, black_check_info );
/* Incorporate the king queen mobility into value.
* It does not matter that we are using the fills instead of spans, since the fact both the fills include their kings will cancel out.
*/
value += KING_QUEEN_MOBILITY * ( white_king_queen_fill.popcount () - black_king_queen_fill.popcount () );
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( white_king_span & black_passed_pawn_trajectories ).popcount () - ( black_king_span & white_passed_pawn_trajectories ).popcount ();
}
/* CHECKMATE AND STALEMATE */
/* If one color has no mobility and the other does, return maxima/minima or 0, depending on check count */
if ( ( white_mobility == 0 ) & ( black_mobility != 0 ) ) if ( white_check_info.check_count ) return ( pc == pcolor::white ? -CHECKMATE : CHECKMATE ); else return 0;
if ( ( black_mobility == 0 ) & ( white_mobility != 0 ) ) if ( black_check_info.check_count ) return ( pc == pcolor::white ? CHECKMATE : -CHECKMATE ); else return 0;
/* If neither color has any mobility, return 0 */
if ( white_mobility == 0 && black_mobility == 0 ) return 0;
/* FINISH ADDING TO VALUE */
/* Mobility */
value += MOBILITY * ( white_mobility - black_mobility );
/* Attacks by restrictives on center */
value += CENTER_LEGAL_ATTACKS_BY_RESTRICTIVES * center_legal_attacks_by_restrictives_diff;
/* Captures on straight pieces by diagonal pieces and knights */
value += DIAGONAL_OR_KNIGHT_CAPTURE_ON_STRAIGHT_PIECES * diagonal_or_knight_captures_on_straight_diff;
/* Knight and queen exist */
{
const bool white_knight_and_queen_exist = bb ( pcolor::white, ptype::knight ).is_nonempty () & bb ( pcolor::white, ptype::queen ).is_nonempty ();
const bool black_knight_and_queen_exist = bb ( pcolor::black, ptype::knight ).is_nonempty () & bb ( pcolor::black, ptype::queen ).is_nonempty ();
value += KNIGHT_AND_QUEEN_EXIST * ( white_knight_and_queen_exist - black_knight_and_queen_exist );
}
/* Castling */
value += CASTLE_MADE * ( castle_made ( pcolor::white ) - castle_made ( pcolor::black ) );
value += CASTLE_LOST * ( castle_lost ( pcolor::white ) - castle_lost ( pcolor::black ) );
/* Pinned pieces */
{
const bitboard white_pinned_pieces = white_check_info.pin_vectors & bb ( pcolor::white );
const bitboard black_pinned_pieces = black_check_info.pin_vectors & bb ( pcolor::black );
value += PINNED_PIECES * ( white_pinned_pieces.popcount () - black_pinned_pieces.popcount () );
}
/* Attacks on passed pawn trajectories */
value += LEGAL_ATTACKS_ON_PASSED_PAWN_TRAJECTORIES * legal_attacks_on_passed_pawn_trajectories_diff;
/* Kings in opposition */
value += KINGS_IN_OPPOSITION * ( white_king_span & black_king_span ).is_nonempty () * ( pc == pcolor::white ? +1 : -1 );
/* Return the value */
return ( pc == pcolor::white ? value : -value );
} | 55.079327 | 264 | 0.672704 | louishobson |
d5c3c99bc81144bd23911bae5e557daedfe7d844 | 1,125 | cpp | C++ | src/bt-box2ddemo/app-src/level/LevelIO.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/bt-box2ddemo/app-src/level/LevelIO.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/bt-box2ddemo/app-src/level/LevelIO.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 | /*
* LevelIO.cpp
*
* Created on: Dec 1, 2010
* Author: rgreen
*/
#include "LevelIO.h"
#include <batterytech/platform/platformgeneral.h>
#include <batterytech/Logger.h>
#include "../gameobject/GameObjectFactory.h"
#include <batterytech/util/TextFileUtil.h>
#include <string.h>
LevelIO::LevelIO(GameContext *context) {
this->context = context;
}
LevelIO::~LevelIO() {
context = NULL;
}
void LevelIO::getDataDirPath(char* path) {
_platform_get_external_storage_dir_name(path, 255);
strcat(path, _platform_get_path_separator());
strcat(path, "demo-app-data");
}
void LevelIO::checkDataDir() {
logmsg("External Storage Directory:");
char dir[255];
getDataDirPath(dir);
logmsg(dir);
if (!_platform_path_exists(dir)) {
logmsg("Path does not exist. Attempting to create");
if (!_platform_path_create(dir)) {
logmsg("Unable to create dir!");
}
} else {
logmsg("Path exists.");
}
if (_platform_path_can_read(dir)) {
logmsg("Can read from dir.");
}
if (_platform_path_can_write(dir)) {
logmsg("Can write to dir.");
}
logmsg(dir);
}
| 21.226415 | 56 | 0.664 | puretekniq |
d5c3dd1fc316a4c692342e0c989d405ab58e66af | 536 | hpp | C++ | src/core/primitives/mc-loader/QuadMaterial.hpp | chaosink/tungsten | 88ea02044dbaf20472a8173b6752460b50c096d8 | [
"Apache-2.0",
"Unlicense"
] | 1,655 | 2015-01-12T13:05:37.000Z | 2022-03-31T13:37:57.000Z | src/core/primitives/mc-loader/QuadMaterial.hpp | chaosink/tungsten | 88ea02044dbaf20472a8173b6752460b50c096d8 | [
"Apache-2.0",
"Unlicense"
] | 65 | 2015-01-13T08:34:28.000Z | 2021-06-08T05:07:58.000Z | src/core/primitives/mc-loader/QuadMaterial.hpp | chaosink/tungsten | 88ea02044dbaf20472a8173b6752460b50c096d8 | [
"Apache-2.0",
"Unlicense"
] | 190 | 2015-01-12T14:53:05.000Z | 2022-03-30T17:30:00.000Z | #ifndef QUADMATERIAL_HPP_
#define QUADMATERIAL_HPP_
#include "textures/BitmapTexture.hpp"
#include "bsdfs/Bsdf.hpp"
#include "math/Box.hpp"
#include "math/Vec.hpp"
#include <memory>
namespace Tungsten {
namespace MinecraftLoader {
struct QuadMaterial
{
std::shared_ptr<Bsdf> bsdf;
std::shared_ptr<Bsdf> emitterBsdf;
Box2f opaqueBounds;
Box2f emitterOpaqueBounds;
std::shared_ptr<BitmapTexture> emission;
float primaryScale, secondaryScale;
float sampleWeight;
};
}
}
#endif /* QUADMATERIAL_HPP_ */
| 16.242424 | 44 | 0.738806 | chaosink |
d5c43d44aad51a86cfa64c77c46376a790c7b0f5 | 371 | cpp | C++ | infer/tests/codetoanalyze/c_cpp/pulse/caller_in_cpp.cpp | livinlife6751/infer | 8a234f1e9fa9ef247f101e452e68cc2c99c91c98 | [
"MIT"
] | 14,499 | 2015-06-11T16:00:28.000Z | 2022-03-31T23:43:54.000Z | infer/tests/codetoanalyze/c_cpp/pulse/caller_in_cpp.cpp | cottamz/infer | 859d69c8bd30e3fc02a9394b2da9da1fe5368993 | [
"MIT"
] | 1,529 | 2015-06-11T16:55:30.000Z | 2022-03-27T15:59:46.000Z | infer/tests/codetoanalyze/c_cpp/pulse/caller_in_cpp.cpp | cottamz/infer | 859d69c8bd30e3fc02a9394b2da9da1fe5368993 | [
"MIT"
] | 2,225 | 2015-06-11T16:36:10.000Z | 2022-03-31T05:16:59.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <stdlib.h>
#include "callee_in_c.h"
void call_set_field_three_Ok(int* p) {
struct s x;
x.a = 5;
set_field_three(&x);
if (x.a == 5) {
free(p);
*p = 3;
}
}
| 18.55 | 66 | 0.638814 | livinlife6751 |
d5c613037da92a42adefc3e03b2cf4a88879e4d2 | 16,129 | cpp | C++ | fs/fat32/tests/fat32_test/main.cpp | kms1212/OpenFSL | 476bb59bce6b451ef39b2dbfef85a814218bce80 | [
"BSD-3-Clause"
] | 3 | 2021-05-27T13:12:28.000Z | 2022-03-08T19:04:49.000Z | fs/fat32/tests/fat32_test/main.cpp | kms1212/OpenFSL | 476bb59bce6b451ef39b2dbfef85a814218bce80 | [
"BSD-3-Clause"
] | 3 | 2021-06-15T14:11:11.000Z | 2021-08-17T02:03:07.000Z | fs/fat32/tests/fat32_test/main.cpp | kms1212/OpenFSL | 476bb59bce6b451ef39b2dbfef85a814218bce80 | [
"BSD-3-Clause"
] | 3 | 2021-06-15T14:05:08.000Z | 2022-02-22T08:13:10.000Z | /* Copyright (c) 2021. kms1212(Minsu Kwon)
This file is part of OpenFSL.
OpenFSL and its source code is published over BSD 3-Clause License.
See the BSD-3-Clause for more details.
<https://raw.githubusercontent.com/kms1212/OpenFSL/main/LICENSE>
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <codecvt>
#include <bitset>
#include "openfsl/fslutils.h"
#include "openfsl/fileblockdevice.h"
#include "openfsl/sector.h"
#include "openfsl/fat32/fs_fat32.h"
int readCount = 0;
int writeCount = 0;
size_t split(const std::string &txt, std::vector<std::string>* strs, char ch);
void hexdump(uint8_t* p, size_t offset, size_t len);
std::fstream disk;
int main(int argc, char** argv) {
if (argc != 3) {
std::cout << "usage: " << argv[0] << " [image_file] [test_name]";
return 1;
}
std::string imageFileName = std::string(argv[1]);
std::string testName = std::string(argv[2]);
disk.open(imageFileName, std::ios::in | std::ios::out | std::ios::binary);
openfsl::FileBlockDevice bd;
std::cout << "Reading image file parameter...\n";
std::fstream diskInfo;
diskInfo.open(imageFileName + ".info", std::ios::in);
if (!diskInfo.fail()) {
std::string line;
openfsl::BlockDevice::DiskParameter parameter;
while (getline(diskInfo, line)) {
std::cout << line << "\n";
std::vector<std::string> value;
split(line, &value, ' ');
if (value[0] == "SectorPerTrack") {
parameter.sectorPerTrack = stoi(value[1]);
} else if (value[0] == "HeadPerCylinder") {
parameter.headPerCylinder = stoi(value[1]);
} else if (value[0] == "BytesPerSector") {
parameter.bytesPerSector = stoi(value[1]);
}
}
bd.setDiskParameter(parameter);
diskInfo.close();
} else {
std::cout << "Fail to read disk parameter file. ";
std::cout << "Default values are will be used.\n";
}
bd.initialize(imageFileName, openfsl::FileBlockDevice::OpenMode::RW);
openfsl::FAT32 fat32(&bd, "", "\\/");
error_t result = fat32.initialize();
if (result) {
disk.close();
return result;
}
fat32.enableCache(512);
/////////////////////////////////////////////
// CHDIR TEST
/////////////////////////////////////////////
std::cout << "===========================\n";
std::cout << " CHDIR TEST\n";
std::cout << "===========================\n";
std::vector<std::string> chdirChecklist; // Checklist
chdirChecklist.push_back("::/.");
chdirChecklist.push_back("::/..");
chdirChecklist.push_back("::/directory1");
chdirChecklist.push_back("subdir1");
chdirChecklist.push_back("::");
chdirChecklist.push_back("directory1/subdir2");
chdirChecklist.push_back("../..");
chdirChecklist.push_back("directory9");
for (size_t i = 0; i < chdirChecklist.size(); i++) {
fat32.changeDirectory(chdirChecklist.at(i));
std::cout << "chdir(\"" << chdirChecklist.at(i) << "\") -> "
<< fat32.getPath() << "\n";
}
/////////////////////////////////////////////
// GETDIRLIST TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " GETDIRLIST TEST\n";
std::cout << "===========================\n";
std::vector<std::string> listDirChecklistDir; // Checklist directories
std::vector<std::vector<std::string>> listDirChecklist; // Checklist
std::vector<std::string> listDirChecklistChilds; // Checklist childs list
listDirChecklistDir.push_back("::"); // Directory ::
listDirChecklistChilds.push_back("DIRECTORY1");
listDirChecklistChilds.push_back("DIRECTORY2");
listDirChecklistChilds.push_back("DIRECTORY3");
listDirChecklistChilds.push_back("DIRECTORY4");
listDirChecklistChilds.push_back("DIRECTORY5");
listDirChecklistChilds.push_back("DIRECTORY6");
listDirChecklistChilds.push_back("DIRECTORY7");
listDirChecklistChilds.push_back("DIRECTORY8");
listDirChecklistChilds.push_back("FILE1.TXT");
listDirChecklistChilds.push_back("FILE2.TXT");
listDirChecklistChilds.push_back("FILE3.TXT");
listDirChecklistChilds.push_back("FILE4.TXT");
listDirChecklistChilds.push_back("FILE5.TXT");
listDirChecklistChilds.push_back("FILE6.TXT");
listDirChecklistChilds.push_back("FILE7.TXT");
listDirChecklistChilds.push_back("FILE8.TXT");
listDirChecklistChilds.push_back("LFNFILENAME1.TXT");
listDirChecklistChilds.push_back("LFNFILENAME2.TXT");
listDirChecklistChilds.push_back("LFNFILENAME3.TXT");
listDirChecklistChilds.push_back("LFNFILENAME4.TXT");
listDirChecklistChilds.push_back("DIRECTORY9");
listDirChecklist.push_back(listDirChecklistChilds);
listDirChecklistChilds.clear();
listDirChecklistDir.push_back("::/directory1"); // Directory ::/directory1
listDirChecklistChilds.push_back(".");
listDirChecklistChilds.push_back("..");
listDirChecklistChilds.push_back("SUBDIR1");
listDirChecklistChilds.push_back("SUBDIR2");
listDirChecklistChilds.push_back("SUBDIR3");
listDirChecklistChilds.push_back("SUBDIR4");
listDirChecklist.push_back(listDirChecklistChilds);
for (size_t j = 0; j < listDirChecklist.size(); j++) {
int result_temp;
fat32.changeDirectory(listDirChecklistDir.at(j));
std::vector<openfsl::FAT32::FileInfo> buf;
fat32.listDirectory(&buf);
result_temp = buf.size() != listDirChecklist.at(j).size();
result += result_temp;
std::cout << "(dirList.size() = " << buf.size()
<< ") != (dirChild.size() = " << listDirChecklist.at(j).size()
<< ") Returns : " << result_temp << "\n";
std::string filename;
for (uint32_t i = 0; i < buf.size(); i++) {
std::cout << buf[i].fileName << ": ";
filename = buf[i].fileName;
for (auto& c : filename) c = static_cast<char>(toupper(c));
if (find(listDirChecklist.at(j).begin(),
listDirChecklist.at(j).end(), filename) ==
listDirChecklist.at(j).end()) {
std::cout << "not found\n";
result++;
} else {
std::cout << "found\n";
}
}
}
/////////////////////////////////////////////
// GETFILEINFORMATION TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " GETFILEINFORMATION TEST\n";
std::cout << "===========================\n";
std::vector<std::string> finfoChecklist; // Checklist
finfoChecklist.push_back("::/file1.txt");
finfoChecklist.push_back("::/file2.txt");
finfoChecklist.push_back("::/file3.txt");
finfoChecklist.push_back("::/file4.txt");
finfoChecklist.push_back("::/file5.txt");
finfoChecklist.push_back("::/file6.txt");
finfoChecklist.push_back("::/file7.txt");
finfoChecklist.push_back("::/file8.txt");
finfoChecklist.push_back("::/lfnfilename1.txt");
finfoChecklist.push_back("::/lfnfilename2.txt");
finfoChecklist.push_back("::/lfnfilename3.txt");
finfoChecklist.push_back("::/lfnfilename4.txt");
for (size_t i = 0; i < finfoChecklist.size(); i++) {
std::pair<error_t, openfsl::FAT32::FileInfo> fileInfo =
fat32.getEntryInfo(finfoChecklist.at(i));
if (fileInfo.first) {
result++;
break;
}
std::cout << "getFileInformation(\"" << finfoChecklist.at(i)
<< "\") Returns : \n";
std::cout << " File Name: " << fileInfo.second.fileName << "\n";
std::cout << " File Created Time: "
<< fileInfo.second.fileCreateTime.time_month << "/"
<< fileInfo.second.fileCreateTime.time_day << "/"
<< fileInfo.second.fileCreateTime.time_year << " "
<< fileInfo.second.fileCreateTime.time_hour << ":"
<< fileInfo.second.fileCreateTime.time_min << ":"
<< fileInfo.second.fileCreateTime.time_sec << "."
<< fileInfo.second.fileCreateTime.time_millis << "\n";
std::cout << " File Access Time: "
<< fileInfo.second.fileAccessTime.time_month << "/"
<< fileInfo.second.fileAccessTime.time_day << "/"
<< fileInfo.second.fileAccessTime.time_year << " "
<< fileInfo.second.fileAccessTime.time_hour << ":"
<< fileInfo.second.fileAccessTime.time_min << ":"
<< fileInfo.second.fileAccessTime.time_sec << "."
<< fileInfo.second.fileAccessTime.time_millis << "\n";
std::cout << " File Mod Time: "
<< fileInfo.second.fileModTime.time_month << "/"
<< fileInfo.second.fileModTime.time_day << "/"
<< fileInfo.second.fileModTime.time_year << " "
<< fileInfo.second.fileModTime.time_hour << ":"
<< fileInfo.second.fileModTime.time_min << ":"
<< fileInfo.second.fileModTime.time_sec << "."
<< fileInfo.second.fileModTime.time_millis << "\n";
std::cout << " File Location: " << fileInfo.second.fileLocation << "\n";
std::cout << " File Size: " << fileInfo.second.fileSize << "\n";
std::stringstream ss;
ss << std::hex << (unsigned int)fileInfo.second.fileAttr;
std::cout << " File Attribute: 0x" << ss.str() << "\n";
}
/////////////////////////////////////////////
// FILE TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " FILE TEST\n";
std::cout << "===========================\n";
std::vector<std::string> fileChecklist; // Checklist
fileChecklist.push_back("::/file1.txt");
fileChecklist.push_back("::/file2.txt");
fileChecklist.push_back("::/file3.txt");
fileChecklist.push_back("::/file4.txt");
fileChecklist.push_back("::/file5.txt");
fileChecklist.push_back("::/file6.txt");
fileChecklist.push_back("::/file7.txt");
fileChecklist.push_back("::/file8.txt");
fileChecklist.push_back("::/lfnfilename1.txt");
fileChecklist.push_back("::/lfnfilename2.txt");
fileChecklist.push_back("::/lfnfilename3.txt");
fileChecklist.push_back("::/lfnfilename4.txt");
for (size_t i = 0; i < fileChecklist.size(); i++) {
std::cout << "Filename: " << finfoChecklist.at(i) << "\n";
openfsl::FAT32::FILE file(&fat32);
if (file.open(fileChecklist.at(i), openfsl::FSL_OpenMode::Read)) {
result++;
continue;
}
std::cout << "openFile(\"" << finfoChecklist.at(i) << "\")\n";
file.seekg(0, openfsl::FSL_SeekMode::SeekEnd);
size_t fileSize = file.tellg();
file.seekg(0, openfsl::FSL_SeekMode::SeekSet);
char* buf = new char[fileSize + 1]();
memset(buf, 0, fileSize + 1);
file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize);
buf[fileSize] = 0;
std::string buf_s(buf);
std::string comp_s("Hello, World!\nOpenFSL\n");
std::cout << "file.read() :\n";
std::cout << " Read: \n<" << buf_s << ">\n";
hexdump(reinterpret_cast<uint8_t*>(buf), 0, fileSize);
std::cout << "\n";
if (buf_s != comp_s) {
result++;
}
// Try to read file with seek
memset(buf, 0, fileSize + 1);
file.seekg(14, openfsl::FSL_SeekMode::SeekSet);
file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize - 14);
buf_s = std::string(buf);
comp_s = "OpenFSL\n";
std::cout << "file.seek(14) file.read() :\n";
std::cout << " Read: \n<" << buf_s << ">\n";
hexdump(reinterpret_cast<uint8_t*>(buf), 0, fileSize - 14);
if (buf_s != comp_s) {
result++;
}
// Try to read more than the size of file.
memset(buf, 0, fileSize + 1);
file.seekg(14, openfsl::FSL_SeekMode::SeekSet);
size_t ret = file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize);
if (ret != fileSize - 14)
result++;
std::cout << "file.seek(14) file.read() :\n";
std::cout << " Returned: " << ret << "\n";
file.close();
std::cout << "------------------------------\n";
}
/////////////////////////////////////////////
// MAKE DIRECTORY TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " MAKE DIRECTORY TEST\n";
std::cout << "===========================\n";
std::vector<std::string> mkDirChecklist; // Checklist
fileChecklist.push_back("::/mkdirtest1");
fileChecklist.push_back("::/mkdirtest2");
fileChecklist.push_back("::/SFNMKDIR.1");
fileChecklist.push_back("::/SFNMKDIR.2");
for (std::string dirname : mkDirChecklist) {
result += fat32.makeDirectory(dirname);
result += fat32.changeDirectory(dirname);
result += fat32.changeDirectory("..");
}
/////////////////////////////////////////////
// REMOVE DIRECTORY TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " REMOVE DIRECTORY TEST\n";
std::cout << "===========================\n";
std::vector<std::string> rmDirChecklist; // Checklist
fileChecklist.push_back("::/mkdirtest1");
fileChecklist.push_back("::/mkdirtest2");
fileChecklist.push_back("::/SFNMKDIR.1");
fileChecklist.push_back("::/SFNMKDIR.2");
for (std::string dirname : rmDirChecklist) {
result += fat32.remove(dirname,
openfsl::FAT32::FileAttribute::Directory);
if (!fat32.changeDirectory(dirname))
result++;
}
std::cout << "Total read count: " << readCount << std::endl;
std::cout << "Total write count: " << writeCount << std::endl;
disk.close();
return result;
}
size_t split(const std::string &txt,
std::vector<std::string>* strs, char ch) {
std::string temp = txt;
size_t pos = temp.find(ch);
size_t initialPos = 0;
strs->clear();
// Decompose statement
while (pos != std::string::npos) {
if (temp.at(pos - 1) != '\\') {
strs->push_back(temp.substr(initialPos, pos - initialPos));
initialPos = pos + 1;
} else {
temp.erase(temp.begin() + pos - 1);
}
pos = temp.find(ch, pos + 1);
}
// Add the last one
strs->push_back(temp.substr(initialPos,
std::min(pos, temp.size()) - initialPos + 1));
return strs->size();
}
void hexdump(uint8_t* p, size_t offset, size_t len) {
std::ios init(nullptr);
init.copyfmt(std::cout);
size_t address = 0;
size_t row = 0;
std::cout << std::hex << std::setfill('0');
while (1) {
if (address >= len) break;
size_t nread = ((len - address) > 16) ? 16 : (len - address);
// Show the address
std::cout << std::setw(8) << address + offset;
// Show the hex codes
for (size_t i = 0; i < 16; i++) {
if (i % 8 == 0) std::cout << ' ';
if (i < nread)
std::cout << ' ' << std::setw(2)
<< static_cast<int>(p[16 * row + i + offset]);
else
std::cout << " ";
}
// Show printable characters
std::cout << " ";
for (size_t i = 0; i < nread; i++) {
uint8_t ch = p[16 * row + i + offset];
if (ch < 32 || ch > 125) std::cout << '.';
else
std::cout << ch;
}
std::cout << "\n";
address += 16;
row++;
}
std::cout.copyfmt(init);
}
| 35.139434 | 83 | 0.545601 | kms1212 |
d5cac4189391d3a5ab3edbd8333094c6bd8426bf | 320 | hpp | C++ | include/game/texture.hpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | include/game/texture.hpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | include/game/texture.hpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "file.hpp"
#include "types.hpp"
namespace gold {
struct texture : public file {
protected:
static object& getPrototype();
public:
texture();
texture(file copy);
texture(path fpath);
texture(binary data);
var load(list args = {});
var bind(list args);
};
} // namespace gold | 16 | 32 | 0.6625 | CoryNull |
d5cdf8882529fd5bc4327631f446d7997755b886 | 959 | hh | C++ | gneis-geant4/private-include/isnp/facility/component/SpallationTargetMessenger.hh | andrey-nakin/gneis-geant4 | 6def0304b5664a5dafdcfd58344ad2006ef44d62 | [
"MIT"
] | null | null | null | gneis-geant4/private-include/isnp/facility/component/SpallationTargetMessenger.hh | andrey-nakin/gneis-geant4 | 6def0304b5664a5dafdcfd58344ad2006ef44d62 | [
"MIT"
] | null | null | null | gneis-geant4/private-include/isnp/facility/component/SpallationTargetMessenger.hh | andrey-nakin/gneis-geant4 | 6def0304b5664a5dafdcfd58344ad2006ef44d62 | [
"MIT"
] | null | null | null | #ifndef isnp_facility_component_SpallationTargetMessenger_hh
#define isnp_facility_component_SpallationTargetMessenger_hh
#include <memory>
#include <G4UImessenger.hh>
#include <G4UIdirectory.hh>
#include <G4UIcmdWithABool.hh>
#include <G4UIcmdWith3VectorAndUnit.hh>
#include "isnp/facility/component/SpallationTarget.hh"
namespace isnp {
namespace facility {
namespace component {
class SpallationTargetMessenger: public G4UImessenger {
public:
SpallationTargetMessenger(SpallationTarget& component);
~SpallationTargetMessenger() override;
G4String GetCurrentValue(G4UIcommand* command) override;
void SetNewValue(G4UIcommand*, G4String) override;
private:
SpallationTarget& component;
std::unique_ptr<G4UIdirectory> const directory;
std::unique_ptr<G4UIcmdWithABool> const hasCoolerCmd;
std::unique_ptr<G4UIcmdWith3VectorAndUnit> const rotationCmd, positionCmd;
};
}
}
}
#endif // isnp_facility_component_SpallationTargetMessenger_hh
| 22.302326 | 75 | 0.828989 | andrey-nakin |
d5cff4d5527fecb5bd854b98d73ceae25be84698 | 136 | cpp | C++ | main.cpp | Hiro-KE/RayTracer | d30b3ef794df3d31c42e8d6e99dea640b413c417 | [
"MIT"
] | null | null | null | main.cpp | Hiro-KE/RayTracer | d30b3ef794df3d31c42e8d6e99dea640b413c417 | [
"MIT"
] | null | null | null | main.cpp | Hiro-KE/RayTracer | d30b3ef794df3d31c42e8d6e99dea640b413c417 | [
"MIT"
] | null | null | null | #include <RayTracer/render.h>
int main(int, char**) {
render Render;
Render.init();
Render.process();
return 0;
}
| 13.6 | 29 | 0.580882 | Hiro-KE |
d5d1d7e8647555dec0c3e34673499e7488585d15 | 4,024 | cpp | C++ | Medusa/Medusa/Graphics/Buffer/IGraphicsBuffer.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2019-04-22T09:09:50.000Z | 2019-04-22T09:09:50.000Z | Medusa/Medusa/Graphics/Buffer/IGraphicsBuffer.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | null | null | null | Medusa/Medusa/Graphics/Buffer/IGraphicsBuffer.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2021-06-30T14:08:03.000Z | 2021-06-30T14:08:03.000Z | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "Graphics/Buffer/IGraphicsBuffer.h"
#include "Graphics/Render/Render.h"
#include "Graphics/State/ArrayBufferRenderState.h"
#include "Graphics/State/ElementArrayBufferRenderState.h"
#include "Graphics/State/RenderStateMachine.h"
#include "Graphics/Render/Render.h"
#include "Core/Log/Log.h"
#include "Rendering/RenderingStatics.h"
MEDUSA_BEGIN;
IGraphicsBuffer::IGraphicsBuffer(GraphicsBufferType bufferType,GraphicsBufferUsage usageType,GraphicsDataType dataType,uint componentCount,bool isNormlized/*=false*/)
:mUsageType(usageType),
mDataType(dataType),mComponentCount(componentCount),mIsNormlized(isNormlized)
{
mIsDataLoaded=false;
mBufferSize=0;
if (bufferType==GraphicsBufferType::Array)
{
mRenderState=new ArrayBufferRenderState();
}
else
{
mRenderState=new ElementArrayBufferRenderState();
}
}
IGraphicsBuffer::~IGraphicsBuffer(void)
{
DeleteObject();
SAFE_RELEASE(mRenderState);
}
bool IGraphicsBuffer::Initialize()
{
//GenObjcet();
return true;
}
bool IGraphicsBuffer::Uninitialize()
{
//DeleteObjcet();
return true;
}
void IGraphicsBuffer::GenObject()
{
if (mRenderState->Buffer() == 0)
{
uint buffer = Render::Instance().GenBuffer();
RenderingStatics::Instance().IncreaseBuffer();
mRenderState->SetBuffer(buffer);
}
}
void IGraphicsBuffer::DeleteObject()
{
if (mRenderState->Buffer() != 0)
{
Render::Instance().DeleteBuffer(mRenderState->Buffer());
RenderingStatics::Instance().DecreaseBuffer();
mRenderState->SetBuffer(0);
}
}
void IGraphicsBuffer::Bind( bool val )
{
if (val)
{
GenObject();
RenderStateMachine::Instance().Push(mRenderState);
//Render::Instance().BindBuffer(GetType(),renderState.GetBuffer());
}
else
{
RenderStateMachine::Instance().Pop(mRenderState);
//Render::Instance().BindBuffer(GetType(),0);
}
}
void IGraphicsBuffer::LoadBufferData( size_t size,void* data)
{
Render::Instance().LoadBufferData(GetType(),static_cast<uint>(size),data,UsageType());
RenderingStatics::Instance().CountGPUUploadSize(size);
mIsDataLoaded=true;
mBufferSize=size;
}
void IGraphicsBuffer::ModifyBufferSubData( size_t offset, size_t size, const void* data )
{
Log::AssertFormat(offset+size<=mBufferSize,"offset:{}+size:{}={} > buffer size:{}",(uint)offset,(uint)size,(uint)(offset+size),(uint)mBufferSize);
GenObject();
Render::Instance().ModifyBufferSubData(GetType(),static_cast<uint>(offset),static_cast<uint>(size),data);
RenderingStatics::Instance().CountGPUUploadSize(size);
}
void IGraphicsBuffer::SetDirtyRange( size_t minIndex,size_t maxIndex,size_t maxLimit )
{
mDirtyRange.ExpandRange(minIndex,maxIndex);
mDirtyRange.ShrinkMax(maxLimit);
}
void IGraphicsBuffer::LimitDirtyRange(size_t maxLimit)
{
mDirtyRange.ExpandMin(maxLimit);
mDirtyRange.ShrinkMax((uint)maxLimit);
}
void IGraphicsBuffer::CleanDirty()
{
mDirtyRange.Reset();
}
void IGraphicsBuffer::Apply()
{
Bind(true);
RETURN_IF_FALSE(IsDirty());
UpdateBufferData();
CleanDirty();
}
void IGraphicsBuffer::Restore()
{
Bind(false);
}
void IGraphicsBuffer::DrawArray( GraphicsDrawMode drawMode/*=GraphicsDrawMode::Triangles*/ ) const
{
DrawArray(drawMode,0,Count());
}
void IGraphicsBuffer::DrawArray( GraphicsDrawMode drawMode,int first,uint count ) const
{
Render::Instance().DrawArrays(drawMode,first,count);
}
void IGraphicsBuffer::DrawElements( GraphicsDrawMode drawMode/*=GraphicsDrawMode::Triangles*/ ) const
{
DrawElements(drawMode,Count(),mDataType,nullptr);
}
void IGraphicsBuffer::DrawElements( GraphicsDrawMode drawMode,uint count,GraphicsDataType dataType,const void* indices ) const
{
Render::Instance().DrawIndices(drawMode,count,dataType,indices);
}
MEDUSA_END; | 24.095808 | 167 | 0.730119 | JamesLinus |
d5d24a29410f8602d9b09664fa30cb7009576dcf | 869 | hpp | C++ | week4/Person/Person.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | 1 | 2019-01-06T22:36:01.000Z | 2019-01-06T22:36:01.000Z | week4/Person/Person.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | week4/Person/Person.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | /*********************************************************************
** Author: Wei-Chien Hsu
** Date: 04/24/18
** Description: A class called Person that has two data members
- a string variable called name and a double variable called age.
It should have a constructor that takes two values and uses them to
initialize the data members.
It should have get methods for both data members (getName and getAge),
but doesn't need any set methods.
*********************************************************************/
#ifndef PERSON_HPP
#define PERSON_HPP
#include <string>
class Person {
private:
std::string name;
double age;
public:
Person();
Person(std::string, double);
std::string getName();
double getAge();
};
#endif | 31.035714 | 89 | 0.50748 | WeiChienHsu |
d5d2b1114c1f6d5a35f3e3d7962cc2699fb8e67c | 473 | cpp | C++ | src/Commands/SelVertexCmd.cpp | PlayMe-Martin/XiMapper | 1926cbd1d13c771d9d60d0d5eb343e059067e0f0 | [
"MIT"
] | 410 | 2015-02-04T22:26:32.000Z | 2022-03-29T00:00:13.000Z | src/Commands/SelVertexCmd.cpp | victorscaff/ofxPiMapper | e79e88e21891abded8388520d4e7f5e6868bfbb7 | [
"MIT"
] | 162 | 2015-01-11T16:09:39.000Z | 2022-03-14T11:24:48.000Z | src/Commands/SelVertexCmd.cpp | victorscaff/ofxPiMapper | e79e88e21891abded8388520d4e7f5e6868bfbb7 | [
"MIT"
] | 100 | 2015-02-09T06:42:31.000Z | 2022-01-01T01:40:36.000Z | #include "SelVertexCmd.h"
namespace ofx {
namespace piMapper {
SelVertexCmd::SelVertexCmd(SurfaceManager * sm, int i){
_surfaceManager = sm;
_newVertexIndex = i;
}
void SelVertexCmd::exec(){
_prevVertexIndex = _surfaceManager->getSelectedVertexIndex();
_surfaceManager->selectVertex(_newVertexIndex);
}
void SelVertexCmd::undo(){
ofLogNotice("SelVertexCmd", "undo");
_surfaceManager->selectVertex(_prevVertexIndex);
}
} // namespace piMapper
} // namespace ofx
| 19.708333 | 62 | 0.761099 | PlayMe-Martin |
d5d498f2c2979ef8d9a980b037d10cf6b0d1031e | 4,323 | cpp | C++ | demo/sireen_example/src/coding_image_demo.cpp | Jetpie/SiReen | 00365023117bec88391bfb37d9549fdca75ac10b | [
"BSD-2-Clause"
] | 4 | 2015-03-18T15:00:38.000Z | 2016-01-04T13:09:59.000Z | demo/sireen_example/src/coding_image_demo.cpp | Jetpie/SiReen | 00365023117bec88391bfb37d9549fdca75ac10b | [
"BSD-2-Clause"
] | null | null | null | demo/sireen_example/src/coding_image_demo.cpp | Jetpie/SiReen | 00365023117bec88391bfb37d9549fdca75ac10b | [
"BSD-2-Clause"
] | null | null | null | #include <unistd.h>
#include <ctime>
#include <vector>
#include "sireen/file_utility.hpp"
#include "sireen/image_feature_extract.hpp"
/*
* Main
*/
int main(int argc, char * argv[]) {
/*********************************************
* Step 0 - optget to receive input option
*********************************************/
char result_buf[256]= "res/llc/caltech101.txt";
char codebook_buf[256]= "res/codebooks/caltech101/cbcaltech101.txt";
char image_dir_buf[256]= "res/images/caltech101";
/* CHECK THE INPUT OPTIONS */
//initialize the arg options
int opt;
while ((opt = getopt(argc, argv, "r:c:i:")) != -1) {
switch (opt) {
case 'r':
sprintf(result_buf, "%s", optarg);
break;
case 'c':
sprintf(codebook_buf, "%s", optarg);
break;
case 'i':
sprintf(image_dir_buf, "%s", optarg);
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [options]\n", argv[0]);
fprintf(stderr, " -i :PATH to image directory\n");
fprintf(stderr, " -r :PATH to result\n");
fprintf(stderr, " -c :PATH to codebook\n");
return -1;
}
}
/* CHECK END */
/*--------------------------------------------
* Path
--------------------------------------------*/
string result_path = string(result_buf);
string image_dir = string(image_dir_buf);
string codebook_path = string(codebook_buf);
/*--------------------------------------------
* PARAMETERS
--------------------------------------------*/
const int CB_SIZE = 500;
/*--------------------------------------------
* VARIABLE READ & WRITE CACHE
--------------------------------------------*/
FILE * outfile;
float *codebook = new float[128 * CB_SIZE];
//counter for reading lines;
unsigned int done=0;
// Initiation
ImageCoder icoder;
/*********************************************
* Step 1 - Loading & Check everything
*********************************************/
// 1. codebook validation
if (access(codebook_path.c_str(), 0)){
cerr << "codebook not found!" << endl;
return -1;
}
char delim[2] = ",";
futil::file_to_pointer(codebook_path.c_str(), codebook,delim);
if (codebook == NULL) {
cerr << "codebook error!" << endl;
return -1;
}
// 1. write file validation
outfile = fopen(result_path.c_str(), "wt+");
//if no file, error report
if ( NULL == outfile) {
cerr << "result file initialize problem!" << endl;
return -1;
}
vector<string> all_images;
string imgfile;
string llcstr;
futil::get_files_in_dir(all_images,image_dir);
/*********************************************
* Step 2 - Traverse the image directory
*********************************************/
clock_t start = clock();
for(unsigned int n = 0; n < all_images.size(); ++n)
{
// load image source to Mat format(opencv2.4.9)
// using the simple llcDescripter interface from
// ImageCoder
imgfile = all_images[n];
try
{
Mat src_image = imread(imgfile,0);
if(!src_image.data)
{
cout << "\tinvalid source image! --> " << imgfile << endl;
continue;
}
llcstr = icoder.llc_sift(src_image, codebook, CB_SIZE, 5);
// cout << llcstr << endl;
}
catch(...)
{
cout << "\tbroken image! --> " << imgfile << endl;
continue;
}
/*********************************************
* Step 4 - write result to file
*********************************************/
// correct file
fprintf(outfile, "%s\t", imgfile.c_str());
fprintf(outfile, "%s\n", llcstr.c_str());
// succeed count
done++;
// print info
if(done % 10== 0){
cout << "\t" << done << " Processed..." << endl;
}
}
cout << "\t" << done << " Processed...(done)"
<< " <Elasped Time: " << float(clock() -start)/CLOCKS_PER_SEC
<< "s>"<< endl;
delete codebook;
fclose(outfile);
}
| 30.020833 | 74 | 0.442979 | Jetpie |
d5d607bcc74262633493aea149afe1accf9e6af5 | 4,854 | cpp | C++ | ZeroLibraries/Common/String/StringUtility.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1 | 2022-03-26T21:08:19.000Z | 2022-03-26T21:08:19.000Z | ZeroLibraries/Common/String/StringUtility.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ZeroLibraries/Common/String/StringUtility.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// \file StringUtility.cpp
///
///
/// Authors: Chris Peters
/// Copyright 2013, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
//---------------------------------------------------------------------- Strings
bool CaseInsensitiveStringLess(StringParam a, StringParam b)
{
StringRange achars = a.All();
StringRange bchars = b.All();
while(!achars.Empty() && !bchars.Empty())
{
Rune aChar = UTF8::ToLower(achars.Front());
Rune bChar = UTF8::ToLower(bchars.Front());
if(aChar < bChar)
return true;
if(aChar > bChar)
return false;
achars.PopFront();
bchars.PopFront();
}
if(achars.Empty() && !bchars.Empty())
return true;
return false;
}
Pair<StringRange,StringRange> SplitOnLast(StringRange input, Rune delimiter)
{
//With empty just return empty String
if(input.Empty())
return Pair<StringRange,StringRange>(input, input);
size_t numRunes = input.ComputeRuneCount();
StringRange lastOf = input.FindLastOf(delimiter);
// Delim found return string and empty
if(lastOf.Empty())
return Pair<StringRange,StringRange>(input, StringRange());
if(lastOf.SizeInBytes() == 0)
return Pair<StringRange, StringRange>(StringRange(), input.SubString(input.Begin(), input.End()));
if(lastOf.SizeInBytes() == numRunes - 1)
return Pair<StringRange, StringRange>(input.SubString(input.Begin(), input.End()), StringRange());
return Pair<StringRange, StringRange>(input.SubString(input.Begin(), lastOf.End()), input.SubString(lastOf.Begin() + 1, lastOf.End()));
}
Pair<StringRange,StringRange> SplitOnFirst(StringRange input, Rune delimiter)
{
StringTokenRange tokenRange(input, delimiter);
StringRange left = tokenRange.Front();
StringRange right = StringRange(left.End(), input.End());
return Pair<StringRange, StringRange>(left, right);
}
StringRange StripBeforeLast(StringRange input, Rune delimiter)
{
Pair<StringRange, StringRange> split = SplitOnLast(input, delimiter);
// If the delimiter was not found the second will be empty
if(split.second.Empty())
return input;
else
return split.second;
}
String JoinStrings(const Array<String>& strings, StringParam delimiter)
{
StringBuilder builder;
for (size_t i = 0; i < strings.Size(); ++i)
{
const String& string = strings[i];
builder.Append(string);
bool isNotLast = (i + 1 != strings.Size());
if (isNotLast)
{
builder.Append(delimiter);
}
}
return builder.ToString();
}
char OnlyAlphaNumeric(char c)
{
if (!isalnum(c))
return '_';
else
return c;
}
//******************************************************************************
// Recursive helper for global string Permute below
static void PermuteRecursive(char *src, size_t start, size_t end, Array<String>& perms)
{
// finished a permutation, add it to the list
if (start == end)
{
perms.PushBack(src);
return;
}
for (size_t i = start; i < end; ++i)
{
// swap to get new head
Swap(src[start], src[i]);
// permute
PermuteRecursive(src, start + 1, end, perms);
// backtrack
Swap(src[start], src[i]);
}
}
//******************************************************************************
void Permute(StringParam src, Array<String>& perms)
{
// convert to std string which is char writable
size_t srclen = src.SizeInBytes();
// create a temp buffer on the stack to manipulate src
char *buf = (char *)alloca(srclen + 1);
memset(buf, 0, srclen + 1);
// recursively calculate permutations
PermuteRecursive(buf, 0, srclen, perms);
}
//******************************************************************************
void SuperPermute(StringParam src, Array<String>& perms)
{
// convert to std string which is char writable
size_t srclen = src.SizeInBytes();
const char *csrc = src.c_str();
// create a temp buffer on the stack to manipulate src
char *buf = (char *)alloca(srclen + 1);
memset(buf, 0, srclen + 1);
// push the individual elements of the source
StringRange srcRange = src;
for (; !srcRange.Empty(); srcRange.PopFront())
perms.PushBack(String(srcRange.Front()));
for (uint l = 1; l < srclen; ++l)
{
for (uint i = 0; i + l < srclen; ++i)
{
// initialize buffer
memcpy(buf, csrc + i, l);
for (uint j = i + l; j < srclen; ++j)
{
buf[l] = csrc[j];
PermuteRecursive(buf, 0, l + 1, perms);
buf[l] = '\0';
}
}
}
}
}//namespace Zero
| 26.380435 | 138 | 0.568809 | jodavis42 |
d5d6f4da384be88e5094adaa636d8ce75426255a | 8,745 | cc | C++ | Geometry/GEMGeometry/test/ME0GeometryAnalyzer10EtaPart.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Geometry/GEMGeometry/test/ME0GeometryAnalyzer10EtaPart.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Geometry/GEMGeometry/test/ME0GeometryAnalyzer10EtaPart.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | /** Derived from DTGeometryAnalyzer by Nicola Amapane
*
* \author M. Maggi - INFN Bari
*/
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "Geometry/GEMGeometry/interface/ME0Geometry.h"
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "Geometry/GEMGeometry/interface/ME0EtaPartitionSpecs.h"
#include "Geometry/CommonTopologies/interface/StripTopology.h"
#include "DataFormats/Math/interface/deltaPhi.h"
#include <memory>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <iomanip>
#include <set>
class ME0GeometryAnalyzer10EtaPart : public edm::one::EDAnalyzer<>
{
public:
ME0GeometryAnalyzer10EtaPart( const edm::ParameterSet& pset);
~ME0GeometryAnalyzer10EtaPart() override;
void beginJob() override {}
void analyze(edm::Event const& iEvent, edm::EventSetup const&) override;
void endJob() override {}
private:
const std::string& myName() { return myName_;}
const int dashedLineWidth_;
const std::string dashedLine_;
const std::string myName_;
std::ofstream ofos;
};
using namespace std;
ME0GeometryAnalyzer10EtaPart::ME0GeometryAnalyzer10EtaPart( const edm::ParameterSet& /*iConfig*/ )
: dashedLineWidth_(104), dashedLine_( string(dashedLineWidth_, '-') ),
myName_( "ME0GeometryAnalyzer10EtaPart" )
{
ofos.open("ME0testOutput10EtaPart.out");
ofos <<"======================== Opening output file"<< endl;
}
ME0GeometryAnalyzer10EtaPart::~ME0GeometryAnalyzer10EtaPart()
{
ofos.close();
ofos <<"======================== Closing output file"<< endl;
}
void
ME0GeometryAnalyzer10EtaPart::analyze( const edm::Event& /*iEvent*/, const edm::EventSetup& iSetup )
{
edm::ESHandle<ME0Geometry> pDD;
iSetup.get<MuonGeometryRecord>().get(pDD);
ofos << myName() << ": Analyzer..." << endl;
ofos << "start " << dashedLine_ << endl;
ofos << " Geometry node for ME0Geom is " << &(*pDD) << endl;
ofos << " detTypes \t" <<pDD->detTypes().size() << endl;
ofos << " GeomDetUnit \t" <<pDD->detUnits().size() << endl;
ofos << " GeomDet \t" <<pDD->dets().size() << endl;
ofos << " GeomDetUnit DetIds\t" <<pDD->detUnitIds().size() << endl;
ofos << " eta partitions \t" <<pDD->etaPartitions().size() << endl;
ofos << " layers \t" <<pDD->layers().size() << endl;
ofos << " chambers \t" <<pDD->chambers().size() << endl;
// ofos << " regions \t" <<pDD->regions().size() << endl;
// checking uniqueness of roll detIds
bool flagNonUniqueRollID = false;
bool flagNonUniqueRollRawID = false;
int nstrips = 0;
int npads = 0;
for (auto roll1 : pDD->etaPartitions()){
nstrips += roll1->nstrips();
npads += roll1->npads();
for (auto roll2 : pDD->etaPartitions()){
if (roll1 != roll2){
if (roll1->id() == roll2->id()) flagNonUniqueRollID = true;
if (roll1->id().rawId() == roll2->id().rawId()) flagNonUniqueRollRawID = true;
}
}
}
if (flagNonUniqueRollID or flagNonUniqueRollRawID)
ofos << " -- WARNING: non unique roll Ids!!!" << endl;
// checking uniqueness of layer detIds
bool flagNonUniqueLaID = false;
bool flagNonUniqueLaRawID = false;
for (auto la1 : pDD->layers()){
for (auto la2 : pDD->layers()){
if (la1 != la2){
if (la1->id() == la2->id()) flagNonUniqueLaID = true;
if (la1->id().rawId() == la2->id().rawId()) flagNonUniqueLaRawID = true;
}
}
}
if (flagNonUniqueLaID or flagNonUniqueLaRawID)
ofos << " -- WARNING: non unique layer Ids!!!" << endl;
// checking uniqueness of chamber detIds
bool flagNonUniqueChID = false;
bool flagNonUniqueChRawID = false;
for (auto ch1 : pDD->chambers()){
for (auto ch2 : pDD->chambers()){
if (ch1 != ch2){
if (ch1->id() == ch2->id()) flagNonUniqueChID = true;
if (ch1->id().rawId() == ch2->id().rawId()) flagNonUniqueChRawID = true;
}
}
}
if (flagNonUniqueChID or flagNonUniqueChRawID)
ofos << " -- WARNING: non unique chamber Ids!!!" << endl;
// print out number of strips and pads
ofos << " total number of strips\t"<<nstrips << endl;
ofos << " total number of pads \t"<<npads << endl;
ofos << myName() << ": Begin iteration over geometry..." << endl;
ofos << "iter " << dashedLine_ << endl;
ofos << myName() << "Begin ME0Geometry TEST" << endl;
/*
* possible checklist for an eta partition:
* base_bottom, base_top, height, strips, pads
* cx, cy, cz, ceta, cphi
* tx, ty, tz, teta, tphi
* bx, by, bz, beta, bphi
* pitch center, pitch bottom, pitch top
* deta, dphi
* gap thicess
* sum of all dx + gap = chamber height
*/
int i = 1;
for (auto ch : pDD->chambers()){
ME0DetId chId(ch->id());
int nLayers(ch->nLayers());
ofos << "\tME0Chamber " << i << ", ME0DetId = " << chId.rawId() << ", " << chId << " has " << nLayers << " layers." << endl;
int j = 1;
for (auto la : ch->layers()){
ME0DetId laId(la->id());
int nRolls(la->nEtaPartitions());
ofos << "\t\tME0Layer " << j << ", ME0DetId = " << laId.rawId() << ", " << laId << " has " << nRolls << " eta partitions." << endl;
int k = 1;
auto& rolls(la->etaPartitions());
for (auto roll : rolls){
// for (auto roll : pDD->etaPartitions()){
ME0DetId rId(roll->id());
ofos<<"\t\t\tME0EtaPartition " << k << " , ME0DetId = " << rId.rawId() << ", " << rId << endl;
const BoundPlane& bSurface(roll->surface());
const StripTopology* topology(&(roll->specificTopology()));
// base_bottom, base_top, height, strips, pads (all half length)
auto& parameters(roll->specs()->parameters());
float bottomEdge(parameters[0]);
float topEdge(parameters[1]);
float height(parameters[2]);
float nStrips(parameters[3]);
float nPads(parameters[4]);
LocalPoint lCentre( 0., 0., 0. );
GlobalPoint gCentre(bSurface.toGlobal(lCentre));
LocalPoint lTop( 0., height, 0.);
GlobalPoint gTop(bSurface.toGlobal(lTop));
LocalPoint lBottom( 0., -height, 0.);
GlobalPoint gBottom(bSurface.toGlobal(lBottom));
// gx, gy, gz, geta, gphi (center)
double cx(gCentre.x());
double cy(gCentre.y());
double cz(gCentre.z());
double ceta(gCentre.eta());
int cphi(static_cast<int>(gCentre.phi().degrees()));
if (cphi < 0) cphi += 360;
double tx(gTop.x());
double ty(gTop.y());
double tz(gTop.z());
double teta(gTop.eta());
int tphi(static_cast<int>(gTop.phi().degrees()));
if (tphi < 0) tphi += 360;
double bx(gBottom.x());
double by(gBottom.y());
double bz(gBottom.z());
double beta(gBottom.eta());
int bphi(static_cast<int>(gBottom.phi().degrees()));
if (bphi < 0) bphi += 360;
// pitch bottom, pitch top, pitch centre
float pitch(roll->pitch());
float topPitch(roll->localPitch(lTop));
float bottomPitch(roll->localPitch(lBottom));
// Type - should be GHA0[1-nRolls]
string type(roll->type().name());
// print info about edges
LocalPoint lEdge1(topology->localPosition(0.));
LocalPoint lEdgeN(topology->localPosition((float)nStrips));
double cstrip1(roll->toGlobal(lEdge1).phi().degrees());
double cstripN(roll->toGlobal(lEdgeN).phi().degrees());
double dphi(cstripN - cstrip1);
if (dphi < 0.) dphi += 360.;
double deta(abs(beta - teta));
const bool printDetails(true);
if (printDetails)
ofos << "\t\t\t\tType: " << type << endl
<< "\t\t\t\tDimensions[cm]: b = " << bottomEdge*2 << ", B = " << topEdge*2 << ", H = " << height*2 << endl
<< "\t\t\t\tnStrips = " << nStrips << ", nPads = " << nPads << endl
<< "\t\t\t\ttop(x,y,z)[cm] = (" << tx << ", " << ty << ", " << tz << "), top (eta,phi) = (" << teta << ", " << tphi << ")" << endl
<< "\t\t\t\tcenter(x,y,z) = (" << cx << ", " << cy << ", " << cz << "), center(eta,phi) = (" << ceta << ", " << cphi << ")" << endl
<< "\t\t\t\tbottom(x,y,z) = (" << bx << ", " << by << ", " << bz << "), bottom(eta,phi) = (" << beta << ", " << bphi << ")" << endl
<< "\t\t\t\tpitch (top,center,bottom) = " << topPitch << " " << pitch << " " << bottomPitch << ", dEta = " << deta << ", dPhi = " << dphi << endl
<< "\t\t\t\tlocal pos at strip 1 " << lEdge1 << " strip N " << lEdgeN << endl;
++k;
} ++j;
} ++i;
}
ofos << dashedLine_ << " end" << endl;
}
//define this as a plug-in
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(ME0GeometryAnalyzer10EtaPart);
| 34.565217 | 153 | 0.605718 | pasmuss |
d5d8e7be9d5306c7eb0f2aef9fba0c635d0935ca | 628 | cpp | C++ | Polymorphism/player.cpp | LegendaryyDoc/Constructors-and-Decuns | d3469ad46ff88a7d33dee1f50a5f49ee4b99f208 | [
"MIT"
] | null | null | null | Polymorphism/player.cpp | LegendaryyDoc/Constructors-and-Decuns | d3469ad46ff88a7d33dee1f50a5f49ee4b99f208 | [
"MIT"
] | null | null | null | Polymorphism/player.cpp | LegendaryyDoc/Constructors-and-Decuns | d3469ad46ff88a7d33dee1f50a5f49ee4b99f208 | [
"MIT"
] | null | null | null | #include "player.h"
#include "raylib.h"
#include <iostream>
bool player::moveTo(const Vector2 & dest)
{
std::cout << "player moving" << std::endl;
return false;
}
void player::takeDamage(int damage)
{
if (health >= 0)
{
health -= damage;
death = false;
}
else
{
death = true;
}
}
player::player(const std::string & fileName)
{
std::cout << "Creating sprite!" << std::endl;
mySprite = LoadTexture(fileName.c_str());
}
player::player()
{
}
player::~player()
{
std::cout << "Destroying sprite!" << std::endl;
UnloadTexture(mySprite);
}
void player::draw(Color h)
{
DrawTexture(mySprite, 375, 225, h);
}
| 13.361702 | 48 | 0.636943 | LegendaryyDoc |
d5daa1639a8aecc7956364b0221bddbdf2321648 | 527 | cpp | C++ | BOJ_CPP/10269.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/10269.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/10269.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
int main() {
fastio;
int C, n, a, b, c, i;
long long m = 0;
cin >> C >> n;
for (i = 1; i <= n; ++i) {
cin >> a >> b >> c;
if (m < a) {
break;
}
m += b - a;
if (m > C) {
break;
}
if (c > 0 && m != C) {
break;
}
}
cout << (i == n + 1 && m == 0 ? "possible" : "impossible");
return 0;
} | 20.269231 | 63 | 0.371917 | tnsgh9603 |
d5e13c87da2f8607dae0800dc215083e9e513939 | 3,386 | cpp | C++ | catkin_ws/src/srrg2_core/srrg2_core/src/misc_tests/test_platform_synthetic_joints.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | 5 | 2020-03-11T14:36:13.000Z | 2021-09-09T09:01:15.000Z | catkin_ws/src/srrg2_core/srrg2_core/src/misc_tests/test_platform_synthetic_joints.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | 1 | 2020-06-07T17:25:04.000Z | 2020-07-15T07:36:10.000Z | catkin_ws/src/srrg2_core/srrg2_core/src/misc_tests/test_platform_synthetic_joints.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | 2 | 2020-11-30T08:17:53.000Z | 2021-06-19T05:07:07.000Z | #include <iostream>
#include "../srrg_data_structures/platform.h"
#include "srrg_geometry/geometry3d.h"
using namespace srrg2_core;
int32_t main() {
//ds check events
JointEventPtr event_t0(new JointEvent(0, "j0", 0));
JointEventPtr event_t1(new JointEvent(1, "j0", 100));
JointEventPtr event_t2(new JointEvent(2, "j0", 103));
if (event_t0 < event_t1) {
std::cerr << "event t=0 is earlier than event t=1" << std::endl;
} else {
std::cerr << "event t=1 is earlier than event t=0" << std::endl;
}
if (event_t2 > event_t1) {
std::cerr << "event t=2 is older than event t=1" << std::endl;
} else {
std::cerr << "event t=1 is older than event t=2" << std::endl;
}
std::cerr << "copying event_t1 into event_t3: fields" << std::endl;
JointEventPtr event_t3 = event_t1;
std::cerr << "event_t3: " << event_t3->timeSeconds() << " = " << event_t1->timeSeconds() << std::endl;
std::cerr << "event_t3: " << event_t3->position() << " = " << event_t1->position() << std::endl;
std::cerr << "copying event_t2 into event_t3: fields" << std::endl;
event_t3 = event_t2;
std::cerr << "event_t3: " << event_t3->timeSeconds() << " = " << event_t2->timeSeconds() << std::endl;
std::cerr << "event_t3: " << event_t3->position() << " = " << event_t2->position() << std::endl;
LinkWithJointPrismatic* prismatic_joint = new LinkWithJointPrismatic("jp0", Vector3f(1, 0, 0));
prismatic_joint->addEvent(event_t0);
prismatic_joint->addEvent(event_t1);
prismatic_joint->addEvent(event_t2);
std::cerr << "number of events in joint jp0: " << prismatic_joint->numberOfEvents() << std::endl;
std::cerr << "sampling" << std::endl;
prismatic_joint->sample(0);
std::cerr << "sampled distance (LinkWithJointPrismatic) at t=0s: " << prismatic_joint->sampledPosition() << std::endl;
prismatic_joint->sample(1.5);
std::cerr << "sampled distance (LinkWithJointPrismatic) at t=1.5s: " << prismatic_joint->sampledPosition() << std::endl;
prismatic_joint->sample(0.5);
std::cerr << "sampled distance (LinkWithJointPrismatic) at t=0.5s: " << prismatic_joint->sampledPosition() << std::endl;
LinkWithJointRotational* rotational_joint = new LinkWithJointRotational("jr0", Vector3f(0, 0, 1));
JointEventPtr event_rotational_t0(new JointEvent(0, "jr0", 0));
JointEventPtr event_rotational_t1(new JointEvent(1, "jr0", 1));
rotational_joint->addEvent(event_rotational_t0);
rotational_joint->addEvent(event_rotational_t1);
std::cerr << "number of events in joint jp0: " << rotational_joint->numberOfEvents() << std::endl;
rotational_joint->sample(0.5);
std::cerr << "sampled orientation (LinkWithJointRotational) at t=0.5s: "
<< rotational_joint->sampledPosition().w()
<< " " << rotational_joint->sampledPosition().x()
<< " " << rotational_joint->sampledPosition().y()
<< " " << rotational_joint->sampledPosition().z()
<< std::endl;
rotational_joint->sample(0.75);
std::cerr << "sampled orientation (LinkWithJointRotational) at t=0.75s: "
<< rotational_joint->sampledPosition().w()
<< " " << rotational_joint->sampledPosition().x()
<< " " << rotational_joint->sampledPosition().y()
<< " " << rotational_joint->sampledPosition().z()
<< std::endl;
delete prismatic_joint;
delete rotational_joint;
return 0;
}
| 44.552632 | 122 | 0.65446 | laaners |
d5e1ecf6caa304a4c100ccf67141b1d65b14af47 | 3,259 | cpp | C++ | back-end/user_manage_rest_9098/user_manage/user_manage/src/user_manage.cpp | marklion/poker_game | 1efad6ac3da333df714c88bee7e4a261ac594f5a | [
"BSD-2-Clause"
] | 3 | 2020-07-09T11:31:46.000Z | 2020-12-15T03:02:12.000Z | back-end/user_manage_rest_9098/user_manage/user_manage/src/user_manage.cpp | marklion/poker_game | 1efad6ac3da333df714c88bee7e4a261ac594f5a | [
"BSD-2-Clause"
] | 2 | 2022-02-19T06:08:20.000Z | 2022-02-27T09:46:31.000Z | back-end/user_manage_rest_9098/user_manage/user_manage/src/user_manage.cpp | marklion/poker_game | 1efad6ac3da333df714c88bee7e4a261ac594f5a | [
"BSD-2-Clause"
] | null | null | null | // This file generated by ngrestcg
// For more information, please visit: https://github.com/loentar/ngrest
#include "user_manage.h"
#include "random_user.h"
#include "db_sqlite_user.h"
#include "Base64.h"
#include "picosha2.h"
#include <hiredis/hiredis.h>
register_resp user_manage::proc_register(const register_req &text)
{
register_resp ret;
std::string reg_name;
std::string hash_pwd;
picosha2::hash256_hex_string(text.reg_password, hash_pwd);
if (true == Base64::Decode(text.reg_name, ®_name))
{
auto db_ret = db_sqlite_insert_user(text.reg_number, hash_pwd, reg_name);
if (0 == db_ret)
ret = "success";
else if (1 == db_ret)
ret = "exit";
else
ret = "fail";
}
return ret;
}
login_resp user_manage::proc_login(const login_req& text)
{
login_resp ret = {"fail", ""};
std::string hash_pwd;
picosha2::hash256_hex_string(text.login_pwd, hash_pwd);
if (db_sqlite_query_user(text.login_id, hash_pwd))
{
auto ssid = db_sqlite_logon_user(text.login_id);
if (ssid.length() == 32)
{
ret.status = "success";
ret.ssid = ssid;
}
}
return ret;
}
hello_resp user_manage::proc_get_hello()
{
hello_resp ret = {"hello mvc"};
return ret;
}
login_random_resp user_manage::proc_login_random()
{
login_random_resp ret;
auto random_user_ssid = RandomUserGenerat();
if (random_user_ssid.length() >= 0)
{
ret.status = "success";
ret.type = "response";
ret.ssid = random_user_ssid;
}
return ret;
}
std::string get_string_from_redis(redisContext *_predis, std::string _command)
{
std::string ret = "";
auto preply = redisCommand(_predis, _command.c_str());
if (NULL != preply)
{
redisReply *stdreply = (redisReply *)preply;
if (REDIS_REPLY_STRING == stdreply->type)
{
ret.assign(stdreply->str, stdreply->len);
}
freeReplyObject(preply);
}
return ret;
}
get_user_info_resp user_manage::proc_get_user_info(std::string ssid)
{
get_user_info_resp ret = {"fail", "", ""};
redisContext *predis = redisConnect("localhost", 6379);
if (NULL != predis)
{
std::string command;
command = std::string("HGET user_ssid:") + ssid + " name";
Base64::Encode(get_string_from_redis(predis, command), &ret.name) ;
command = std::string("HGET user_ssid:") + ssid + " cash";
ret.cash = get_string_from_redis(predis, command);
if (ret.name.length() > 0 && ret.cash.length() > 0)
{
ret.status = "success";
}
redisFree(predis);
}
return ret;
}
std::string user_manage::proc_logoff(std::string ssid)
{
std::string ret = "fail";
redisContext *predis = redisConnect("localhost", 6379);
if (NULL != predis)
{
auto user_id = get_string_from_redis(predis, std::string("HGET user_ssid:") + ssid + " id");
freeReplyObject(redisCommand(predis, "DEL user_ssid:%s", ssid.c_str()));
freeReplyObject(redisCommand(predis, "DEL id:%s", user_id.c_str()));
redisFree(predis);
ret = "success";
}
return ret;
} | 24.689394 | 100 | 0.614299 | marklion |
d5e289349d1dce2bd1ec9e1733740d6b97b0be47 | 3,339 | cpp | C++ | applications/DEMApplication/custom_processes/automatic_dt_process.cpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | applications/DEMApplication/custom_processes/automatic_dt_process.cpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | applications/DEMApplication/custom_processes/automatic_dt_process.cpp | ma6yu/Kratos | 02380412f8a833a2cdda6791e1c7f9c32e088530 | [
"BSD-4-Clause"
] | null | null | null | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Ignasi de Pouplana
//
// Application includes
#include "custom_processes/automatic_dt_process.hpp"
namespace Kratos
{
/// this function is designed for being called at the beginning of the computations
/// right after reading the model and the groups
void AutomaticDTProcess::ExecuteBeforeSolutionLoop()
{
KRATOS_TRY;
ModelPart::ElementsContainerType& rElements = mrModelPart.GetCommunicator().LocalMesh().Elements();
const int NElems = static_cast<int>(rElements.size());
ModelPart::ElementsContainerType::ptr_iterator ptr_itElem_begin = rElements.ptr_begin();
// Find smallest particle
double min_radius = std::numeric_limits<double>::infinity();
SphericContinuumParticle* pSmallestDemElem = dynamic_cast<SphericContinuumParticle*>(ptr_itElem_begin->get());
for (int i = 0; i < NElems; i++) {
ModelPart::ElementsContainerType::ptr_iterator ptr_itElem = ptr_itElem_begin + i;
Element* p_element = ptr_itElem->get();
SphericContinuumParticle* pDemElem = dynamic_cast<SphericContinuumParticle*>(p_element);
const double radius = pDemElem->GetRadius();
if (radius < min_radius) {
pSmallestDemElem = pDemElem;
min_radius = radius;
}
}
// Calculate stiffness of the smallest particle with itself
double initial_dist = 2.0*min_radius;
double myYoung = pSmallestDemElem->GetYoung();
double myPoisson = pSmallestDemElem->GetPoisson();
double calculation_area = 0.0;
double kn_el = 0.0;
double kt_el = 0.0;
DEMContinuumConstitutiveLaw::Pointer NewContinuumConstitutiveLaw = pSmallestDemElem->GetProperties()[DEM_CONTINUUM_CONSTITUTIVE_LAW_POINTER]->Clone();
NewContinuumConstitutiveLaw->CalculateContactArea(min_radius, min_radius, calculation_area);
NewContinuumConstitutiveLaw->CalculateElasticConstants(kn_el, kt_el, initial_dist, myYoung, myPoisson, calculation_area, pSmallestDemElem, pSmallestDemElem);
// Calculate mass of the smallest particle
const double particle_density = pSmallestDemElem->GetDensity();
const double particle_volume = pSmallestDemElem->CalculateVolume();
const double min_mass = particle_volume * particle_density;
// Calculate critical delta time
const double critical_delta_time = std::sqrt(min_mass/kn_el);
mrModelPart.GetProcessInfo().SetValue(DELTA_TIME,mCorrectionFactor*critical_delta_time);
KRATOS_INFO("Automatic DT process") << "Calculated critical time step: " << critical_delta_time << " seconds." << std::endl;
KRATOS_INFO("Automatic DT process") << "Using a correction factor of: " << mCorrectionFactor << ", the resulting time step is: " << mCorrectionFactor*critical_delta_time << " seconds." << std::endl;
KRATOS_CATCH("");
}
///------------------------------------------------------------------------------------
} // namespace Kratos.
| 45.121622 | 206 | 0.649596 | ma6yu |
d5e45ed1fc68deebb20f0162226cd4018ecb3438 | 4,593 | hxx | C++ | admin/netui/common/h/bltdlgxp.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/common/h/bltdlgxp.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/common/h/bltdlgxp.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
bltdlgxp.hxx
Expandable dialog class declaration.
This class represents a standard BLT DIALOG_WINDOW which can
be expanded once to reveal new controls. All other operations
are common between EXPANDABLE_DIALOG and DIALOG_WINDOW.
To construct, provide the control ID of two controls: a "boundary"
static text control (SLT) and an "expand" button.
The "boundary" control is declared in the resource file as 2x2
units in size, containing no text, and has only the WS_CHILD style.
Its location marks the lower right corner of the reduced (initial)
size of the dialog. Controls lower and/or to the right of this
boundary "point" are disabled until the dialog is expanded.
The "expand" button is a normal two-state button which usually has
a title like "Options >>" to indicate that it changes the dialog.
EXPANDABLE_DIALOG handles the state transition entirely, and the
"expand" button is permanently disabled after the transition. In
other words, it's a one way street.
The virtual method OnExpand() is called when expansion takes place;
this can be overridden to initialize controls which have been
heretofor invisible. It's usually necessary to override the default
version of OnExpand() to set focus on whichever control you want,
since the control which had focus (the expand button) is now disabled.
There is one optional parameter to the constructor. It specifies a
distance, in dialog units. If the ShowArea() member finds that the
"boundary" control is within this distance of the real (.RC file)
border of the dialog, it will use the original border. This prevents
small (3-10 unit) errors caused by the inability to place a control
immediately against the dialog border.
FILE HISTORY:
DavidHov 11/1/91 Created
*/
#ifndef _BLTDLGXP_HXX_
#define _BLTDLGXP_HXX_
/*************************************************************************
NAME: EXPANDABLE_DIALOG
SYNOPSIS: A dialog whose initial state is small, and then expands
to reveal more controls. Two controls are special:
a "boundary" control which demarcates the
limits of the smaller initial state, and
an "expand" button which causes the dialog
to grow to its full size; the button is then
permanently disabled.
About the "cPxBoundary" parameter: if the distance from
the end of the boundary control to the edge of the dialog
is LESS than this value, the size of the original dialog
will be used for that dimension.
INTERFACE:
EXPANDABLE_DIALOG() -- constructor
~EXPANDABLE_DIALOG() -- destructor
Process() -- run the dialog
OnExpand() -- optional virtual routine
called when the dialog is
expanded. Default routine
just sets focus on OK button.
PARENT: DIALOG_WINDOW
USES: PUSH_BUTTON, SLT
CAVEATS: The expansion process is one-way; that is, the dialog
cannot be shrunk. The controlling button is permanently
disabled after the expansion.
NOTES:
HISTORY:
DavidHov 10/30/91 Created
**************************************************************************/
DLL_CLASS EXPANDABLE_DIALOG ;
#define EXP_MIN_USE_BOUNDARY 20
DLL_CLASS EXPANDABLE_DIALOG : public DIALOG_WINDOW
{
public:
EXPANDABLE_DIALOG
( const TCHAR * pszResourceName,
HWND hwndOwner,
CID cidBoundary,
CID cidExpandButn,
INT cPxBoundary = EXP_MIN_USE_BOUNDARY ) ;
~ EXPANDABLE_DIALOG () ;
// Overloaded 'Process' members for reducing initial dialog extent
APIERR Process ( UINT * pnRetVal = NULL ) ;
APIERR Process ( BOOL * pfRetVal ) ;
protected:
PUSH_BUTTON _butnExpand ; // The button which bloats
SLT _sltBoundary ; // The "point" marker
BOOL OnCommand ( const CONTROL_EVENT & event ) ;
// Virtual called when dialog is to be expanded.
virtual VOID OnExpand () ;
VOID ShowArea ( BOOL fFull ) ; // Change dialog size
private:
XYDIMENSION _xyOriginal ; // Original dlg box dimensions
INT _cPxBoundary ; // Limit to force original boundary
BOOL _fExpanded ; // Dialog is expanded
};
#endif // _BLTDLGXP_HXX_
| 34.533835 | 76 | 0.645548 | npocmaka |
d5e4eaa1f195ed86fbbc103d55e4b37d79d2df24 | 5,015 | hpp | C++ | Sources/Models/Model.hpp | LukePrzyb/Acid | ba7da3ffcc08791f047ec0f15317b3e0ba971850 | [
"MIT"
] | null | null | null | Sources/Models/Model.hpp | LukePrzyb/Acid | ba7da3ffcc08791f047ec0f15317b3e0ba971850 | [
"MIT"
] | null | null | null | Sources/Models/Model.hpp | LukePrzyb/Acid | ba7da3ffcc08791f047ec0f15317b3e0ba971850 | [
"MIT"
] | null | null | null | #pragma once
#include "Maths/Vector3.hpp"
#include "Graphics/Buffers/Buffer.hpp"
#include "Resources/Resource.hpp"
namespace acid {
template<typename Base>
class ModelFactory {
public:
using TCreateReturn = std::shared_ptr<Base>;
using TCreateMethodNode = std::function<TCreateReturn(const Node &)>;
using TRegistryMapNode = std::unordered_map<std::string, TCreateMethodNode>;
using TCreateMethodFilename = std::function<TCreateReturn(const std::filesystem::path &)>;
using TRegistryMapFilename = std::unordered_map<std::string, TCreateMethodFilename>;
virtual ~ModelFactory() = default;
/**
* Creates a new model, or finds one with the same values.
* @param node The node to decode values from.
* @return The model with the requested values.
*/
static TCreateReturn Create(const Node &node) {
auto typeName = node["type"].Get<std::string>();
auto it = RegistryNode().find(typeName);
return it == RegistryNode().end() ? nullptr : it->second(node);
}
/**
* Creates a new model, or finds one with the same values.
* @param filename The file to load the model from.
* @return The model loaded from the filename.
*/
static TCreateReturn Create(const std::filesystem::path &filename) {
auto fileExt = filename.extension().string();
auto it = RegistryFilename().find(fileExt);
return it == RegistryFilename().end() ? nullptr : it->second(filename);
}
static TRegistryMapNode &RegistryNode() {
static TRegistryMapNode impl;
return impl;
}
static TRegistryMapFilename &RegistryFilename() {
static TRegistryMapFilename impl;
return impl;
}
/**
* A class used to help register subclasses of Model to the factory.
* Your subclass should have a static Create function taking a Node, or path.
* @tparam T The type that will extend Model.
*/
template<typename T>
class Registrar : public Base {
protected:
template<int Dummy = 0>
static bool Register(const std::string &typeName) {
Registrar::name = typeName;
ModelFactory::RegistryNode()[typeName] = [](const Node &node) -> TCreateReturn {
return T::Create(node);
};
return true;
}
template<int Dummy = 0>
static bool Register(const std::string &typeName, const std::string &extension) {
Register(typeName);
ModelFactory::RegistryFilename()[extension] = [](const std::filesystem::path &filename) -> TCreateReturn {
return T::Create(filename);
};
return true;
}
const Node &Load(const Node &node) override {
return node >> *dynamic_cast<T *>(this);
}
Node &Write(Node &node) const override {
node["type"].Set(name);
return node << *dynamic_cast<const T *>(this);
}
inline static std::string name;
};
friend const Node &operator>>(const Node &node, Base &base) {
return base.Load(node);
}
friend Node &operator<<(Node &node, const Base &base) {
return base.Write(node);
}
protected:
virtual const Node &Load(const Node &node) { return node; }
virtual Node &Write(Node &node) const { return node; }
};
/**
* @brief Resource that represents a model vertex and index buffer.
*/
class ACID_EXPORT Model : public ModelFactory<Model>, public Resource {
public:
/**
* Creates a new empty model.
*/
Model() = default;
/**
* Creates a new model.
* @tparam T The vertex type.
* @param vertices The model vertices.
* @param indices The model indices.
*/
template<typename T>
explicit Model(const std::vector<T> &vertices, const std::vector<uint32_t> &indices = {}) :
Model() {
Initialize(vertices, indices);
}
bool CmdRender(const CommandBuffer &commandBuffer, uint32_t instances = 1) const;
template<typename T>
std::vector<T> GetVertices(std::size_t offset = 0) const;
template<typename T>
void SetVertices(const std::vector<T> &vertices);
std::vector<uint32_t> GetIndices(std::size_t offset = 0) const;
void SetIndices(const std::vector<uint32_t> &indices);
std::vector<float> GetPointCloud() const;
const Vector3f &GetMinExtents() const { return m_minExtents; }
const Vector3f &GetMaxExtents() const { return m_maxExtents; }
float GetWidth() const { return m_maxExtents.m_x - m_minExtents.m_x; }
float GetHeight() const { return m_maxExtents.m_y - m_minExtents.m_y; }
float GetDepth() const { return m_maxExtents.m_z - m_minExtents.m_z; }
float GetRadius() const { return m_radius; }
const Buffer *GetVertexBuffer() const { return m_vertexBuffer.get(); }
const Buffer *GetIndexBuffer() const { return m_indexBuffer.get(); }
uint32_t GetVertexCount() const { return m_vertexCount; }
uint32_t GetIndexCount() const { return m_indexCount; }
static VkIndexType GetIndexType() { return VK_INDEX_TYPE_UINT32; }
protected:
template<typename T>
void Initialize(const std::vector<T> &vertices, const std::vector<uint32_t> &indices = {});
private:
std::unique_ptr<Buffer> m_vertexBuffer;
std::unique_ptr<Buffer> m_indexBuffer;
uint32_t m_vertexCount = 0;
uint32_t m_indexCount = 0;
Vector3f m_minExtents;
Vector3f m_maxExtents;
float m_radius = 0.0f;
};
}
#include "Model.inl"
| 30.210843 | 109 | 0.714656 | LukePrzyb |
d5e988104d12cb3eb25053a7b6090f42e28be3d8 | 26,239 | cc | C++ | src/GraphTraverser.cc | berselius/tycho2 | b57f0aeeb861f34139577d386f18e59070ea2eca | [
"Unlicense"
] | 11 | 2017-07-26T16:08:58.000Z | 2021-03-02T14:49:32.000Z | src/GraphTraverser.cc | berselius/tycho2 | b57f0aeeb861f34139577d386f18e59070ea2eca | [
"Unlicense"
] | 3 | 2017-07-31T15:51:31.000Z | 2021-06-08T21:16:25.000Z | src/GraphTraverser.cc | berselius/tycho2 | b57f0aeeb861f34139577d386f18e59070ea2eca | [
"Unlicense"
] | 14 | 2017-06-21T20:27:21.000Z | 2021-06-24T18:53:11.000Z | /*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced
under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
Laboratory (LANL), which is operated by Los Alamos National Security, LLC for
the U.S. Department of Energy. The U.S. Government has rights to use,
reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
to produce derivative works, such modified software should be clearly marked,
so as not to confuse it with the version available from LANL.
Additionally, redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Los Alamos National Security, LLC, Los Alamos
National Laboratory, LANL, the U.S. Government, nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL
SECURITY, LLC 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 "GraphTraverser.hh"
#include "Mat.hh"
#include "Global.hh"
#include "TychoMesh.hh"
#include "Comm.hh"
#include "Timer.hh"
#include <vector>
#include <set>
#include <queue>
#include <utility>
#include <omp.h>
#include <limits.h>
#include <string.h>
using namespace std;
/*
Tuple class
*/
namespace {
class Tuple
{
private:
UINT c_cell;
UINT c_angle;
UINT c_priority;
public:
Tuple(UINT cell, UINT angle, UINT priority)
: c_cell(cell), c_angle(angle), c_priority(priority) {}
UINT getCell() const { return c_cell; }
UINT getAngle() const { return c_angle; }
// Comparison operator to determine relative priorities
// Needed for priority_queue
bool operator<(const Tuple &rhs) const
{
return c_priority < rhs.c_priority;
}
};}
/*
splitPacket
Packet is (global side, angle, data)
*/
static
void splitPacket(char *packet, UINT &globalSide, UINT &angle, char **data)
{
memcpy(&globalSide, packet, sizeof(UINT));
packet += sizeof(UINT);
memcpy(&angle, packet, sizeof(UINT));
packet += sizeof(UINT);
*data = packet;
}
/*
createPacket
Packet is (global side, angle, data)
*/
static
void createPacket(vector<char> &packet, UINT globalSide, UINT angle,
UINT dataSize, const char *data)
{
packet.resize(2 * sizeof(UINT) + dataSize);
char *p = packet.data();
memcpy(p, &globalSide, sizeof(UINT));
p += sizeof(UINT);
memcpy(p, &angle, sizeof(UINT));
p += sizeof(UINT);
memcpy(p, data, dataSize);
}
/*
isIncoming
Determines whether data is incoming to the cell
depending on sweep direction.
*/
static
bool isIncoming(UINT angle, UINT cell, UINT face, Direction direction)
{
if (direction == Direction_Forward)
return g_tychoMesh->isIncoming(angle, cell, face);
else if (direction == Direction_Backward)
return g_tychoMesh->isOutgoing(angle, cell, face);
// Should never get here
Assert(false);
return false;
}
/*
angleGroupIndex
Gets angle groups for angle index.
e.g. 20 angles numbered 0...19 with 3 threads.
Split into 3 angle chunks of size 7,7,6: 0...6 7...13 14...19
If angle in 0...6, return 0
If angle in 7...13, return 1
If angle in 14...19, return 2
*/
UINT angleGroupIndex(UINT angle)
{
UINT numAngles = g_nAngles;
UINT chunkSize = numAngles / g_nThreads;
UINT numChunksBigger = numAngles % g_nThreads;
UINT lowIndex = 0;
// Find angleGroup
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
UINT nextLowIndex = lowIndex + chunkSize;
if (angleGroup < numChunksBigger)
nextLowIndex++;
if (angle < nextLowIndex)
return angleGroup;
lowIndex = nextLowIndex;
}
// Should never get here
Assert(false);
return 0;
}
/*
sendData2Sided
Implements two-sided MPI for sending data.
*/
void GraphTraverser::sendData2Sided(
const vector<vector<char>> &sendBuffers) const
{
vector<MPI_Request> mpiSendRequests;
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
// Send the data
for (UINT index = 0; index < numAdjRanks; index++) {
const vector<char> &sendBuffer = sendBuffers[index];
if (sendBuffer.size() > 0) {
MPI_Request request;
const int adjRank = c_adjRankIndexToRank[index];
const int tag = 0;
mpiError = MPI_Isend(const_cast<char*>(sendBuffer.data()),
sendBuffer.size(),
MPI_BYTE, adjRank, tag,
MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
}
}
// Make sure all sends are done
if (mpiSendRequests.size() > 0) {
mpiError = MPI_Waitall(mpiSendRequests.size(), mpiSendRequests.data(),
MPI_STATUSES_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
/*
recvData2Sided
Implements two-sided MPI for receiving data.
*/
void GraphTraverser::recvData2Sided(vector<char> &dataPackets) const
{
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
for (UINT index = 0; index < numAdjRanks; index++) {
const int adjRank = c_adjRankIndexToRank[index];
const int tag = 0;
int flag = 0;
MPI_Status mpiStatus;
int recvCount;
// Probe for new message
mpiError = MPI_Iprobe(adjRank, tag, MPI_COMM_WORLD, &flag, &mpiStatus);
Insist(mpiError == MPI_SUCCESS, "");
mpiError = MPI_Get_count(&mpiStatus, MPI_BYTE, &recvCount);
Insist(mpiError == MPI_SUCCESS, "");
// Recv message if there is one
if (flag) {
UINT originalSize = dataPackets.size();
dataPackets.resize(originalSize + recvCount);
mpiError = MPI_Recv(&dataPackets[originalSize], recvCount,
MPI_BYTE, adjRank, tag, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
}
/*
sendAndRecvData()
The algorithm is
- Irecv data size for all adjacent ranks
- ISend data size and then data (if any)
- Wait on recv of data size, then blocking recv for data if there is any.
Data is sent in two steps to each adjacent rank.
First is the number of bytes of data that will be sent.
Second is the raw data in bytes.
The tag for the first send is 0.
The tag for the second send is 1.
The raw data is made of data packets containing:
globalSide, angle, and data to send.
The data can have different meanings depending on the TraverseData
subclass.
When done traversing local graph, you want to stop all communication.
This is done by setting killComm to true.
To mark killing communication, sendSize is set to UINT64_MAX.
In this event, commDark[rank] is set to true on the receiving rank
so we no longer look for communication from this rank.
*/
void GraphTraverser::sendAndRecvData(const vector<vector<char>> &sendBuffers,
vector<char> &dataPackets,
vector<bool> &commDark,
const bool killComm) const
{
// Check input
Assert(c_adjRankIndexToRank.size() == sendBuffers.size());
Assert(c_adjRankIndexToRank.size() == commDark.size());
// Variables
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
vector<UINT> recvSizes(numAdjRanks);
vector<UINT> sendSizes(numAdjRanks);
vector<MPI_Request> mpiRecvRequests(numAdjRanks);
vector<MPI_Request> mpiSendRequests;
UINT numRecv = numAdjRanks;
// Setup recv of data size
for (UINT index = 0; index < numAdjRanks; index++) {
// No recv if adjRank is no longer communicating
if (commDark[index]) {
mpiRecvRequests[index] = MPI_REQUEST_NULL;
numRecv--;
continue;
}
// Irecv data size
int numDataToRecv = 1;
int adjRank = c_adjRankIndexToRank[index];
int tag0 = 0;
mpiError = MPI_Irecv(&recvSizes[index], numDataToRecv, MPI_UINT64_T,
adjRank, tag0, MPI_COMM_WORLD,
&mpiRecvRequests[index]);
Insist(mpiError == MPI_SUCCESS, "");
}
// Send data size and data
for (UINT index = 0; index < numAdjRanks; index++) {
// Don't send if adjRank is no longer communicating
if (commDark[index])
continue;
const vector<char> &sendBuffer = sendBuffers[index];
int numDataToSend = 1;
int adjRank = c_adjRankIndexToRank[index];
int tag0 = 0;
int tag1 = 1;
// Send data size
MPI_Request request;
sendSizes[index] = sendBuffer.size();
if (killComm)
sendSizes[index] = UINT64_MAX;
mpiError = MPI_Isend(&sendSizes[index], numDataToSend, MPI_UINT64_T,
adjRank, tag0, MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
// Send data
if (sendSizes[index] > 0 && sendSizes[index] != UINT64_MAX) {
MPI_Request request;
Assert(sendBuffer.size() < INT_MAX);
mpiError = MPI_Isend(const_cast<char*>(sendBuffer.data()),
sendBuffer.size(),
MPI_BYTE, adjRank, tag1,
MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
}
}
// Recv data size and data
for (UINT numWaits = 0; numWaits < numRecv; numWaits++) {
// Wait for a data size to arrive
int index;
mpiError = MPI_Waitany(mpiRecvRequests.size(), mpiRecvRequests.data(),
&index, MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
// Recv data
if (recvSizes[index] > 0 && recvSizes[index] != UINT64_MAX) {
int adjRank = c_adjRankIndexToRank[index];
int tag1 = 1;
UINT originalSize = dataPackets.size();
dataPackets.resize(originalSize + recvSizes[index]);
mpiError = MPI_Recv(&dataPackets[originalSize], recvSizes[index],
MPI_BYTE, adjRank, tag1, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
// Stop communication with this rank
if (recvSizes[index] == UINT64_MAX) {
commDark[index] = true;
}
}
// Make sure all sends are done
if (mpiSendRequests.size() > 0) {
mpiError = MPI_Waitall(mpiSendRequests.size(), mpiSendRequests.data(),
MPI_STATUSES_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
/*
GraphTraverser
If doComm is true, graph traversal is global.
If doComm is false, each mesh partition is traversed locally with no
consideration for boundaries between partitions.
*/
GraphTraverser::GraphTraverser(Direction direction, bool doComm,
UINT dataSizeInBytes)
: c_direction(direction), c_doComm(doComm),
c_dataSizeInBytes(dataSizeInBytes)
{
// Get adjacent ranks
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT face = 0; face < g_nFacePerCell; face++) {
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK &&
c_adjRankToRankIndex.count(adjRank) == 0)
{
UINT rankIndex = c_adjRankIndexToRank.size();
c_adjRankToRankIndex.insert(make_pair(adjRank, rankIndex));
c_adjRankIndexToRank.push_back(adjRank);
}
}}
// Calc num dependencies for each (cell, angle) pair
c_initNumDependencies.resize(g_nAngles, g_nCells);
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
c_initNumDependencies(angle, cell) = 0;
for (UINT face = 0; face < g_nFacePerCell; face++) {
bool incoming = isIncoming(angle, cell, face, c_direction);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
if (c_doComm && incoming && adjRank != TychoMesh::BAD_RANK) {
c_initNumDependencies(angle, cell)++;
}
else if (!c_doComm && incoming && adjCell != TychoMesh::BOUNDARY_FACE) {
c_initNumDependencies(angle, cell)++;
}
}
}}
}
/*
traverse
Traverses g_tychoMesh.
*/
void GraphTraverser::traverse(const UINT maxComputePerStep,
TraverseData &traverseData)
{
vector<priority_queue<Tuple>> canCompute(g_nThreads);
Mat2<UINT> numDependencies(g_nAngles, g_nCells);
UINT numCellAnglePairsToCalculate = g_nAngles * g_nCells;
Mat2<vector<char>> sendBuffers;
vector<vector<char>> sendBuffers1;
vector<bool> commDark;
Timer totalTimer;
Timer setupTimer;
Timer commTimer;
Timer sendTimer;
Timer recvTimer;
// Start total timer
totalTimer.start();
setupTimer.start();
// Calc num dependencies for each (cell, angle) pair
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
numDependencies(angle, cell) = c_initNumDependencies(angle, cell);
}}
// Set size of sendBuffers and commDark
UINT numAdjRanks = c_adjRankIndexToRank.size();
sendBuffers.resize(g_nThreads, numAdjRanks);
sendBuffers1.resize(numAdjRanks);
commDark.resize(numAdjRanks, false);
// Initialize canCompute queue
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
if (numDependencies(angle, cell) == 0) {
UINT priority = traverseData.getPriority(cell, angle);
UINT angleGroup = angleGroupIndex(angle);
canCompute[angleGroup].push(Tuple(cell, angle, priority));
}
}}
// End setup timer
setupTimer.stop();
// Traverse the graph
while (numCellAnglePairsToCalculate > 0) {
// Do local traversal
#pragma omp parallel
{
UINT stepsTaken = 0;
UINT angleGroup = omp_get_thread_num();
while (canCompute[angleGroup].size() > 0 &&
stepsTaken < maxComputePerStep)
{
// Get cell/angle pair to compute
Tuple cellAnglePair = canCompute[angleGroup].top();
canCompute[angleGroup].pop();
UINT cell = cellAnglePair.getCell();
UINT angle = cellAnglePair.getAngle();
stepsTaken++;
#pragma omp atomic
numCellAnglePairsToCalculate--;
// Get boundary type and adjacent cell/side data for each face
BoundaryType bdryType[g_nFacePerCell];
UINT adjCellsSides[g_nFacePerCell];
bool isOutgoingWrtDirection[g_nFacePerCell];
for (UINT face = 0; face < g_nFacePerCell; face++) {
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
adjCellsSides[face] = adjCell;
if (g_tychoMesh->isOutgoing(angle, cell, face)) {
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_OutIntBdry;
adjCellsSides[face] =
g_tychoMesh->getSide(cell, face);
}
else if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank == TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_OutExtBdry;
}
else {
bdryType[face] = BoundaryType_OutInt;
}
if (c_direction == Direction_Forward) {
isOutgoingWrtDirection[face] = true;
}
else {
isOutgoingWrtDirection[face] = false;
}
}
else {
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_InIntBdry;
adjCellsSides[face] =
g_tychoMesh->getSide(cell, face);
}
else if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank == TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_InExtBdry;
}
else {
bdryType[face] = BoundaryType_InInt;
}
if (c_direction == Direction_Forward) {
isOutgoingWrtDirection[face] = false;
}
else {
isOutgoingWrtDirection[face] = true;
}
}
}
// Update data for this cell-angle pair
traverseData.update(cell, angle, adjCellsSides, bdryType);
// Update dependency for children
for (UINT face = 0; face < g_nFacePerCell; face++) {
if (isOutgoingWrtDirection[face]) {
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
if (adjCell != TychoMesh::BOUNDARY_FACE) {
numDependencies(angle, adjCell)--;
if (numDependencies(angle, adjCell) == 0) {
UINT priority =
traverseData.getPriority(adjCell, angle);
Tuple tuple(adjCell, angle, priority);
canCompute[angleGroup].push(tuple);
}
}
else if (c_doComm && adjRank != TychoMesh::BAD_RANK) {
UINT rankIndex = c_adjRankToRankIndex.at(adjRank);
UINT side = g_tychoMesh->getSide(cell, face);
UINT globalSide = g_tychoMesh->getLGSide(side);
vector<char> packet;
createPacket(packet, globalSide, angle,
c_dataSizeInBytes,
traverseData.getData(cell, face, angle));
sendBuffers(angleGroup, rankIndex).insert(
sendBuffers(angleGroup, rankIndex).end(),
packet.begin(), packet.end());
}
}
}
}
}
// Put together sendBuffers from different angleGroups
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers1[rankIndex].insert(
sendBuffers1[rankIndex].end(),
sendBuffers(angleGroup, rankIndex).begin(),
sendBuffers(angleGroup, rankIndex).end());
}}
// Do communication
commTimer.start();
if (c_doComm) {
// Send/Recv
UINT packetSizeInBytes = 2 * sizeof(UINT) + c_dataSizeInBytes;
vector<char> dataPackets;
if (g_mpiType == MPIType_TychoTwoSided) {
const bool killComm = false;
sendAndRecvData(sendBuffers1, dataPackets, commDark, killComm);
}
else if (g_mpiType == MPIType_CapsaicinTwoSided) {
sendTimer.start();
sendData2Sided(sendBuffers1);
sendTimer.stop();
recvTimer.start();
recvData2Sided(dataPackets);
recvTimer.stop();
}
else {
Insist(false, "MPI type not recognized.");
}
// Clear send buffers for next iteration
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers(angleGroup, rankIndex).clear();
}}
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers1[rankIndex].clear();
}
// Unpack packets
UINT numPackets = dataPackets.size() / packetSizeInBytes;
Assert(dataPackets.size() % packetSizeInBytes == 0);
for (UINT i = 0; i < numPackets; i++) {
char *packet = &dataPackets[i * packetSizeInBytes];
UINT globalSide;
UINT angle;
char *packetData;
splitPacket(packet, globalSide, angle, &packetData);
UINT localSide = g_tychoMesh->getGLSide(globalSide);
traverseData.setSideData(localSide, angle, packetData);
UINT cell = g_tychoMesh->getSideCell(localSide);
numDependencies(angle, cell)--;
if (numDependencies(angle, cell) == 0) {
UINT priority = traverseData.getPriority(cell, angle);
Tuple tuple(cell, angle, priority);
canCompute[angleGroupIndex(angle)].push(tuple);
}
}
}
commTimer.stop();
}
// Send kill comm signal to adjacent ranks
if (g_mpiType == MPIType_TychoTwoSided) {
commTimer.start();
if (c_doComm) {
vector<char> dataPackets;
const bool killComm = true;
sendAndRecvData(sendBuffers1, dataPackets, commDark, killComm);
}
commTimer.stop();
}
// Print times
totalTimer.stop();
double totalTime = totalTimer.wall_clock();
Comm::gmax(totalTime);
double setupTime = setupTimer.wall_clock();
Comm::gmax(setupTime);
double commTime = commTimer.sum_wall_clock();
Comm::gmax(commTime);
double sendTime = sendTimer.sum_wall_clock();
Comm::gmax(sendTime);
double recvTime = recvTimer.sum_wall_clock();
Comm::gmax(recvTime);
if (Comm::rank() == 0) {
printf(" Traverse Timer (comm): %fs\n", commTime);
printf(" Traverse Timer (send): %fs\n", sendTime);
printf(" Traverse Timer (recv): %fs\n", recvTime);
printf(" Traverse Timer (setup): %fs\n", setupTime);
printf(" Traverse Timer (total): %fs\n", totalTime);
}
}
| 34.389253 | 84 | 0.548725 | berselius |
d5e9f464b23a5a84da88b2d7b6ac621cb6f56c51 | 5,131 | hpp | C++ | expected.hpp | KholdStare/plumbingplusplus | cced5c76e6d9e8a1b3467b45c3bf36e14e57734c | [
"BSL-1.0"
] | 10 | 2015-01-26T16:30:04.000Z | 2022-03-16T14:37:31.000Z | expected.hpp | KholdStare/plumbingplusplus | cced5c76e6d9e8a1b3467b45c3bf36e14e57734c | [
"BSL-1.0"
] | null | null | null | expected.hpp | KholdStare/plumbingplusplus | cced5c76e6d9e8a1b3467b45c3bf36e14e57734c | [
"BSL-1.0"
] | null | null | null | // This code is put in the public domain by Andrei Alexandrescu
// See http://www.reddit.com/r/programming/comments/14m1tc/andrei_alexandrescu_systematic_error_handling_in/c7etk47
// Some edits by Alexander Kondratskiy.
#ifndef EXPECTED_HPP_TN6DJT51
#define EXPECTED_HPP_TN6DJT51
#include <stdexcept>
#include <algorithm>
template <class T>
class Expected {
union {
std::exception_ptr spam;
T ham;
};
bool gotHam;
Expected() {
// used by fromException below
}
public:
Expected(const T& rhs) : ham(rhs), gotHam(true) {}
Expected(T&& rhs) : ham(std::move(rhs)), gotHam(true) {}
Expected(const Expected& rhs) : gotHam(rhs.gotHam) {
if (gotHam) new(&ham) T(rhs.ham);
else new(&spam) std::exception_ptr(rhs.spam);
}
Expected(Expected&& rhs) : gotHam(rhs.gotHam) {
if (gotHam) new(&ham) T(std::move(rhs.ham));
else new(&spam) std::exception_ptr(std::move(rhs.spam));
}
void swap(Expected& rhs) {
if (gotHam) {
if (rhs.gotHam) {
using std::swap;
swap(ham, rhs.ham);
} else {
auto t = std::move(rhs.spam);
new(&rhs.ham) T(std::move(ham));
new(&spam) std::exception_ptr(t);
std::swap(gotHam, rhs.gotHam);
}
} else {
if (rhs.gotHam) {
rhs.swap(*this);
} else {
spam.swap(rhs.spam);
std::swap(gotHam, rhs.gotHam);
}
}
}
Expected& operator=(Expected<T> rhs) {
swap(rhs);
return *this;
}
~Expected() {
//using std::exception_ptr;
if (gotHam) ham.~T();
else spam.~exception_ptr();
}
static Expected<T> fromException(std::exception_ptr p) {
Expected<T> result;
result.gotHam = false;
new(&result.spam) std::exception_ptr(std::move(p));
return result;
}
template <class E>
static Expected<T> fromException(const E& exception) {
if (typeid(exception) != typeid(E)) {
throw std::invalid_argument(
"Expected<T>::fromException: slicing detected.");
}
return fromException(std::make_exception_ptr(exception));
}
static Expected<T> fromException() {
return fromException(std::current_exception());
}
template <class U>
static Expected<T> transferException(Expected<U> const& other) {
if (other.valid()) {
throw std::invalid_argument(
"Expected<T>::transferException: other Expected<U> does not contain an exception.");
}
return fromException(other.spam);
}
bool valid() const {
return gotHam;
}
/**
* implicit conversion may throw if spam
*/
operator T&() {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
T& get() {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
const T& get() const {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
template <class E>
bool hasException() const {
try {
if (!gotHam) std::rethrow_exception(spam);
} catch (const E& object) {
return true;
} catch (...) {
}
return false;
}
template <class F>
static Expected fromCode(F fun) {
try {
return Expected(fun());
} catch (...) {
return fromException();
}
}
};
// TODO: clean this up
template <>
class Expected<void> {
std::exception_ptr spam;
bool gotHam;
public:
Expected() : gotHam(true) { }
void swap(Expected& rhs) {
if (gotHam) {
if (!rhs.gotHam) {
auto t = std::move(rhs.spam);
new(&spam) std::exception_ptr(t);
std::swap(gotHam, rhs.gotHam);
}
} else {
if (rhs.gotHam) {
rhs.swap(*this);
} else {
spam.swap(rhs.spam);
std::swap(gotHam, rhs.gotHam);
}
}
}
Expected& operator=(Expected<void> rhs) {
swap(rhs);
return *this;
}
~Expected() {
//using std::exception_ptr;
if (!gotHam) spam.~exception_ptr();
}
static Expected<void> fromException(std::exception_ptr p) {
Expected<void> result;
result.gotHam = false;
new(&result.spam) std::exception_ptr(std::move(p));
return result;
}
template <class E>
static Expected<void> fromException(const E& exception) {
if (typeid(exception) != typeid(E)) {
throw std::invalid_argument(
"Expected<void>::fromException: slicing detected.");
}
return fromException(std::make_exception_ptr(exception));
}
static Expected<void> fromException() {
return fromException(std::current_exception());
}
bool valid() const {
return gotHam;
}
/**
* implicit conversion may throw if spam
*/
operator void() {
if (!gotHam) std::rethrow_exception(spam);
}
void get() const {
if (!gotHam) std::rethrow_exception(spam);
}
template <class E>
bool hasException() const {
try {
if (!gotHam) std::rethrow_exception(spam);
} catch (const E& object) {
return true;
} catch (...) {
}
return false;
}
template <class F>
static Expected fromCode(F fun) {
try {
fun();
return Expected();
} catch (...) {
return fromException();
}
}
};
#endif /* end of include guard: EXPECTED_HPP_TN6DJT51 */
| 21.834043 | 115 | 0.603391 | KholdStare |
d5eb345505ba75f1c5e48d9d375bb67bc53df562 | 666 | cpp | C++ | 05. Searching/05 Count 1s in Sorted Binary Array/05b count 1s in sorted binary array.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 190 | 2021-02-10T17:01:01.000Z | 2022-03-20T00:21:43.000Z | 05. Searching/05 Count 1s in Sorted Binary Array/05b count 1s in sorted binary array.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | null | null | null | 05. Searching/05 Count 1s in Sorted Binary Array/05b count 1s in sorted binary array.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 27 | 2021-03-26T11:35:15.000Z | 2022-03-06T07:34:54.000Z | #include<bits/stdc++.h>
using namespace std;
/*
problem is similar as finding first occurrence
because array is binary and sorted so,
if we find first occurrence of 1, then subtract it from
last index to find count.
*/
int count1s(int a[], int n)//time comp. O(logn)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] == 0)
{
low = mid + 1;
}
else
{
if (mid == 0 or a[mid - 1] != a[mid])
{
return (n - mid);
}
else
{
high = mid - 1;
}
}
}
return 0;
}
int main()
{
int a[] = {0, 0, 0, 0, 1, 1, 1};
int n = sizeof(a) / sizeof(int);
cout << count1s(a, n);
return 0;
} | 14.478261 | 55 | 0.545045 | VivekYadav105 |
d5ed8afbb7ae6ba5c91700484eaab897dc2e03ee | 1,040 | cpp | C++ | 10591 Happy Number.cpp | zihadboss/UVA-Solutions | 020fdcb09da79dc0a0411b04026ce3617c09cd27 | [
"Apache-2.0"
] | 86 | 2016-01-20T11:36:50.000Z | 2022-03-06T19:43:14.000Z | 10591 Happy Number.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | null | null | null | 10591 Happy Number.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | 113 | 2015-12-04T06:40:57.000Z | 2022-02-11T02:14:28.000Z | #include <iostream>
using namespace std;
enum Status {Unchecked, Checking, IsHappy, NotHappy };
const int HIGHEST = 1000;
Status numbers[HIGHEST];
inline int nextNum(int num)
{
int ret = 0;
while (num)
{
ret += (num % 10) * (num % 10);
num /= 10;
}
return ret;
}
bool isHappy(int num)
{
num = nextNum(num);
if (numbers[num] == Unchecked)
{
numbers[num] = Checking;
bool is = isHappy(num);
numbers[num] = (is ? IsHappy : NotHappy);
}
else if (numbers[num] == Checking)
return false;
return numbers[num] == IsHappy;
}
int main()
{
for (int i = 0; i < HIGHEST; ++i)
numbers[i] = Unchecked;
numbers[1] = IsHappy;
int T;
cin >> T;
for (int t = 1; t <= T; ++t)
{
int num;
cin >> num;
if (isHappy(num))
cout << "Case #" << t << ": " << num << " is a Happy number.\n";
else
cout << "Case #" << t << ": " << num << " is an Unhappy number.\n";
}
}
| 17.333333 | 79 | 0.4875 | zihadboss |
d5f10b52a30c096b9f003eb11609a265900325f0 | 3,183 | cpp | C++ | tests/bin2llvmir/utils/simplifycfg_tests.cpp | mehrdad-shokri/retdec | a82f16e97b163afe789876e0a819489c5b9b358e | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | 4,816 | 2017-12-12T18:07:09.000Z | 2019-04-17T02:01:04.000Z | tests/bin2llvmir/utils/simplifycfg_tests.cpp | mehrdad-shokri/retdec | a82f16e97b163afe789876e0a819489c5b9b358e | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | 514 | 2017-12-12T18:22:52.000Z | 2019-04-16T16:07:11.000Z | tests/bin2llvmir/utils/simplifycfg_tests.cpp | mehrdad-shokri/retdec | a82f16e97b163afe789876e0a819489c5b9b358e | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | 579 | 2017-12-12T18:38:02.000Z | 2019-04-11T13:32:53.000Z | /**
* @file tests/bin2llvmir/utils/tests/simplifycfg_tests.cpp
* @brief Tests for the @c CFGSimplifyPass pass.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*
* This is checking that LLVM's -simplifycfg is behaving as expected.
* If this fails, something in LLVM changed and we need to react, because
* otherwise it will start to screw up our code.
*/
#include "../lib/Transforms/Scalar/SimplifyCFGPass.cpp"
#include "retdec/bin2llvmir/optimizations/unreachable_funcs/unreachable_funcs.h"
#include "bin2llvmir/utils/llvmir_tests.h"
using namespace ::testing;
using namespace llvm;
namespace retdec {
namespace bin2llvmir {
namespace tests {
/**
* @brief Tests for the @c UnreachableFuncs pass.
*/
class CFGSimplifyPassTests: public LlvmIrTests
{
protected:
void runOnModule()
{
LlvmIrTests::runOnModule<CFGSimplifyPass>();
}
};
TEST_F(CFGSimplifyPassTests, unreachableBasicBlocksKeep)
{
parseInput(R"(
; Instructions in unreachable BBs are *NOT* removed if metadata named
; 'llvmToAsmGlobalVariableName' exits.
@llvm2asm = global i64 0
define void @fnc() {
store volatile i64 123, i64* @llvm2asm, !asm !1
ret void
store volatile i64 456, i64* @llvm2asm, !asm !2
ret void
store volatile i64 789, i64* @llvm2asm, !asm !3
ret void
}
!llvmToAsmGlobalVariableName = !{!0}
!0 = !{!"llvm2asm"}
!1 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
!2 = !{!"name", i64 456, i64 10, !"asm", !"annotation"}
!3 = !{!"name", i64 789, i64 10, !"asm", !"annotation"}
)");
runOnModule();
std::string exp = R"(
@llvm2asm = global i64 0
define void @fnc() {
; 7b
store volatile i64 123, i64* @llvm2asm, !asm !1
ret void
; No predecessors!
; 1c8
store volatile i64 456, i64* @llvm2asm, !asm !2
ret void
; No predecessors!
; 315
store volatile i64 789, i64* @llvm2asm, !asm !3
ret void
}
!llvmToAsmGlobalVariableName = !{!0}
!0 = !{!"llvm2asm"}
!1 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
!2 = !{!"name", i64 456, i64 10, !"asm", !"annotation"}
!3 = !{!"name", i64 789, i64 10, !"asm", !"annotation"}
)";
checkModuleAgainstExpectedIr(exp);
}
TEST_F(CFGSimplifyPassTests, unreachableBasicBlocksRemove)
{
parseInput(R"(
; Instructions in unreachable BBs are removed if metadata named
; 'llvmToAsmGlobalVariableName' does not exit.
@llvm2asm = global i64 0
define void @fnc() {
store volatile i64 123, i64* @llvm2asm, !asm !0
ret void
store volatile i64 456, i64* @llvm2asm, !asm !1
ret void
store volatile i64 789, i64* @llvm2asm, !asm !2
ret void
}
!0 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
!1 = !{!"name", i64 456, i64 10, !"asm", !"annotation"}
!2 = !{!"name", i64 789, i64 10, !"asm", !"annotation"}
)");
runOnModule();
std::string exp = R"(
@llvm2asm = global i64 0
define void @fnc() {
; 7b
store volatile i64 123, i64* @llvm2asm, !asm !0
ret void
}
!0 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
)";
checkModuleAgainstExpectedIr(exp);
}
} // namespace tests
} // namespace bin2llvmir
} // namespace retdec
| 23.932331 | 80 | 0.647817 | mehrdad-shokri |
d5f2a4b8dd5f721a7cd9705db193fe2302c6188b | 5,060 | cpp | C++ | thirdparty/ULib/src/ulib/debug/error_simulation.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/debug/error_simulation.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/debug/error_simulation.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // ============================================================================
//
// = LIBRARY
// ULib - c++ library
//
// = FILENAME
// error_simulation.cpp
//
// = AUTHOR
// Stefano Casazza
//
// ============================================================================
/*
#define DEBUG_DEBUG
*/
#include <ulib/base/utility.h>
#include <ulib/debug/error_simulation.h>
bool USimulationError::flag_init;
char* USimulationError::file_mem;
uint32_t USimulationError::file_size;
union uuvararg USimulationError::var_arg;
/**
* #if defined(HAVE_STRTOF) && !defined(strtof)
* extern "C" { float strtof(const char* nptr, char** endptr); }
* #endif
* #if defined(HAVE_STRTOLD) && !defined(strtold)
* extern "C" { long double strtold(const char* nptr, char** endptr); }
* #endif
*/
void USimulationError::init()
{
U_INTERNAL_TRACE("USimulationError::init()")
int fd = 0;
char* env = getenv("USIMERR");
char file[MAX_FILENAME_LEN];
if ( env &&
*env)
{
flag_init = true;
// format: <file_error_simulation>
// error.sim
(void) sscanf(env, "%254s", file);
fd = open(file, O_RDONLY | O_BINARY, 0666);
if (fd != -1)
{
struct stat st;
if (fstat(fd, &st) == 0)
{
file_size = st.st_size;
if (file_size)
{
file_mem = (char*) mmap(0, file_size, PROT_READ, MAP_SHARED, fd, 0);
if (file_mem == MAP_FAILED) file_size = 0;
}
}
(void) close(fd);
}
}
if (fd <= 0)
{
U_MESSAGE("SIMERR%W<%Woff%W>%W", YELLOW, RED, YELLOW, RESET);
}
else
{
U_MESSAGE("SIMERR%W<%Won%W>: File<%W%s%W>%W", YELLOW, GREEN, YELLOW, CYAN, file, YELLOW, RESET);
}
}
void* USimulationError::checkForMatch(const char* call_name)
{
U_INTERNAL_TRACE("USimulationError::checkForMatch(%s)", call_name);
if (flag_init &&
file_size)
{
const char* ptr = call_name;
while (*ptr && *ptr != '(') ++ptr;
if (*ptr == '(')
{
int len = ptr - call_name;
char* limit = file_mem + file_size - len;
char* file_ptr = file_mem;
// format: <classname>::method <random range> <return type> <return value> <errno value>
// ::lstat 10 i -1 13
bool match = false;
for (; file_ptr <= limit; ++file_ptr)
{
while (u__isspace(*file_ptr)) ++file_ptr;
if (*file_ptr != '#')
{
while (u__isspace(*file_ptr)) ++file_ptr;
U_INTERNAL_PRINT("file_ptr = %.*s", len, file_ptr);
if (u__isspace(file_ptr[len]) &&
memcmp(file_ptr, call_name, len) == 0)
{
match = true;
file_ptr += len;
// manage random testing
uint32_t range = (uint32_t) strtol(file_ptr, &file_ptr, 10);
if (range > 0) match = (u_get_num_random(range) == (range / 2));
break;
}
}
while (*file_ptr != '\n') ++file_ptr;
}
if (match)
{
while (u__isspace(*file_ptr)) ++file_ptr;
char type = *file_ptr++;
switch (type)
{
case 'p': // pointer
{
var_arg.p = (void*) strtol(file_ptr, &file_ptr, 16);
}
break;
case 'l': // long
{
var_arg.l = strtol(file_ptr, &file_ptr, 10);
}
break;
case 'L': // long long
{
# ifdef HAVE_STRTOULL
var_arg.ll = (long long) strtoull(file_ptr, &file_ptr, 10);
# endif
}
break;
case 'f': // float
{
# ifdef HAVE_STRTOF
var_arg.f = strtof(file_ptr, &file_ptr);
# endif
}
break;
case 'd': // double
{
var_arg.d = strtod(file_ptr, &file_ptr);
}
break;
case 'D': // long double
{
# ifdef HAVE_STRTOLD
var_arg.ld = strtold(file_ptr, &file_ptr);
# endif
}
break;
case 'i': // word-size (int)
default:
{
var_arg.i = (int) strtol(file_ptr, &file_ptr, 10);
}
break;
}
errno = atoi(file_ptr);
U_INTERNAL_PRINT("errno = %d var_arg = %d", errno, var_arg.i);
return &var_arg;
}
}
}
return 0;
}
| 24.444444 | 102 | 0.422925 | liftchampion |
d5f32cfc4a4d34a9dc80d0f34ca42ccf7406100e | 8,457 | cpp | C++ | Scene.cpp | MikuAuahDark/lovewrap | 1c0b7d8419f83cd1ef437a5c3b27ab96ac9a6b15 | [
"Zlib"
] | 1 | 2019-05-29T23:24:59.000Z | 2019-05-29T23:24:59.000Z | Scene.cpp | MikuAuahDark/lovewrap | 1c0b7d8419f83cd1ef437a5c3b27ab96ac9a6b15 | [
"Zlib"
] | null | null | null | Scene.cpp | MikuAuahDark/lovewrap | 1c0b7d8419f83cd1ef437a5c3b27ab96ac9a6b15 | [
"Zlib"
] | null | null | null | /**
* Copyright (c) 2040 Dark Energy Processor
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
// STL
#include <map>
#include <string>
#include <vector>
// Lua
extern "C" {
#include "lua.h"
#include "lauxlib.h"
}
// lovewrap
#include "LOVEWrap.h"
#include "Scene.h"
// Current scene
lovewrap::Scene *currentScene = nullptr;
static int loveLoad(lua_State *L)
{
// args
std::vector<std::string> args;
int argLen = lua_objlen(L, 1);
for (int i = 1; i <= argLen; i++)
{
lua_pushinteger(L, (lua_Integer) i);
lua_rawget(L, 1);
size_t strSize;
const char *str = lua_tolstring(L, -1, &strSize);
args.push_back(std::string(str, strSize));
lua_pop(L, 1);
}
currentScene->load(args);
return 0;
}
static int loveUpdate(lua_State *L)
{
currentScene->update(luaL_checknumber(L, 1));
return 0;
}
static int loveDraw(lua_State *L)
{
currentScene->draw();
return 0;
}
static int loveQuit(lua_State *L)
{
lua_pushboolean(L, (int) currentScene->quit());
return 1;
}
typedef void(*EventHandlerFunc)(const std::vector<love::Variant> &);
inline ptrdiff_t getIntegerFromVariant(const std::vector<love::Variant> &arg, size_t index)
{
if (index > arg.size())
throw love::Exception("index %u is out of range", (uint32_t) index);
const love::Variant &var = arg[index - 1];
if (var.getType() != love::Variant::NUMBER)
throw love::Exception("index %u is not a number", (uint32_t) index);
return var.getData().number;
}
inline bool getBooleanFromVariant(const std::vector<love::Variant> &arg, size_t index, bool implicitConversion = false)
{
if (index > arg.size())
throw love::Exception("index %u is out of range", (uint32_t) index);
const love::Variant &var = arg[index - 1];
const love::Variant::Data &data = var.getData();
love::Variant::Type varType = var.getType();
if (implicitConversion)
{
if (varType == love::Variant::BOOLEAN)
return data.boolean;
else if (varType == love::Variant::NUMBER)
return abs(data.number) <= 0.000001;
else if (varType == love::Variant::NIL)
return false;
else
throw love::Exception("index %u is not a boolean", (uint32_t) index);
}
else if (varType != var.BOOLEAN)
throw love::Exception("index %u is not a boolean", (uint32_t) index);
return var.getData().boolean;
}
inline std::string getStringFromVariant(const std::vector<love::Variant> &arg, size_t index)
{
if (index > arg.size())
throw love::Exception("index %u is out of range", (uint32_t) index);
const love::Variant &var = arg[index - 1];
const love::Variant::Data &data = var.getData();
love::Variant::Type varType = var.getType();
switch(varType)
{
case love::Variant::SMALLSTRING:
{
return std::string(data.smallstring.str, data.smallstring.len);
}
case love::Variant::STRING:
{
return std::string(data.string->str, data.string->len);
}
default:
throw love::Exception("index %u is not a string", (uint32_t) index);
}
}
template<typename T> inline T getConstantFromVariant(
const std::vector<love::Variant> &arg,
size_t index,
bool (*func)(const char*, T&)
)
{
std::string str = getStringFromVariant(arg, index);
T outVal;
if (func(str.c_str(), outVal))
return outVal;
else
throw love::Exception("index %u invalid constant value '%s'", (uint32_t) index, str.c_str());
}
static void loveEventKeyPressed(const std::vector<love::Variant> &arg)
{
using namespace love::keyboard;
currentScene->keyPressed(
getConstantFromVariant<Keyboard::Key>(arg, 1, &Keyboard::getConstant),
getConstantFromVariant<Keyboard::Scancode>(arg, 2, &Keyboard::getConstant),
getBooleanFromVariant(arg, 3)
);
}
static void loveEventKeyReleased(const std::vector<love::Variant> &arg)
{
using namespace love::keyboard;
currentScene->keyReleased(
getConstantFromVariant<Keyboard::Key>(arg, 1, &Keyboard::getConstant),
getConstantFromVariant<Keyboard::Scancode>(arg, 2, &Keyboard::getConstant)
);
}
static int loveGameLoop(lua_State *L)
{
static bool eventHandlerInitialized = false;
static std::map<std::string, EventHandlerFunc> eventHandler;
if (!eventHandlerInitialized)
{
eventHandler["keypressed"] = &loveEventKeyPressed;
eventHandler["keyreleased"] = &loveEventKeyReleased;
eventHandlerInitialized = true;
}
double dt = 0;
if (lovewrap::event::isLoaded())
{
auto inst = lovewrap::event::getInstance();
love::event::Message *msg = nullptr;
inst->pump();
while (inst->poll(msg))
{
if (msg->name.compare("quit") == 0 && currentScene->quit() == false)
{
if (msg->args.size() > 0)
msg->args[0].toLua(L);
else
lua_pushinteger(L, 0);
return 1;
}
else
{
auto iter = eventHandler.find(msg->name);
if (iter != eventHandler.end())
{
try
{
iter->second(msg->args);
}
catch (love::Exception &e)
{
fprintf(stderr, "Exception '%s': %s\n", msg->name.c_str(), e.what());
return luaL_error(L, "%s", e.what());
}
}
else
fprintf(stderr, "Missing event handler: %s\n", msg->name.c_str());
}
}
}
if (lovewrap::timer::isLoaded())
dt = lovewrap::timer::step();
try
{
currentScene->update(dt);
}
catch (love::Exception &e)
{
lua_pushstring(L, e.what());
lua_error(L);
}
if (lovewrap::graphics::isLoaded() && lovewrap::graphics::isActive())
{
lovewrap::graphics::origin();
lovewrap::graphics::clear(lovewrap::graphics::getBackgroundColor());
try
{
currentScene->draw();
}
catch (love::Exception &e)
{
lua_pushstring(L, e.what());
lua_error(L);
}
lua_gc(L, LUA_GCCOLLECT, 0);
lovewrap::graphics::present();
}
return 0;
}
static int loveRun(lua_State *L)
{
// args
std::vector<std::string> args;
lua_getglobal(L, "arg");
int argLen = lua_objlen(L, 1);
size_t strSize;
const char *str = nullptr;
// index -2 = argv[0]
lua_pushinteger(L, -2);
lua_rawget(L, 1);
str = lua_tolstring(L, -1, &strSize);
args.push_back(std::string(str, strSize));
for (int i = 1; i <= argLen; i++)
{
lua_pushinteger(L, (lua_Integer) i);
lua_rawget(L, 1);
str = lua_tolstring(L, -1, &strSize);
if (str != nullptr)
args.push_back(std::string(str, strSize));
lua_pop(L, 1);
}
lua_pop(L, 1);
try
{
currentScene->load(args);
}
catch (love::Exception &e)
{
lua_pushstring(L, e.what());
lua_error(L);
}
lua_pushcfunction(L, &loveGameLoop);
return 1;
}
int baseMain(lua_State *L)
{
lua_getglobal(L, "love");
// love.load
lua_pushcfunction(L, &loveLoad);
lua_setfield(L, -2, "load");
// love.update
lua_pushcfunction(L, &loveUpdate);
lua_setfield(L, -2, "update");
// love.draw
lua_pushcfunction(L, &loveDraw);
lua_setfield(L, -2, "draw");
// love.quit
lua_pushcfunction(L, &loveQuit);
lua_setfield(L, -2, "quit");
// love.run
lua_pushcfunction(L, &loveRun);
lua_setfield(L, -2, "run");
lua_pop(L, 1);
lua_pushboolean(L, 1);
return 1;
}
namespace lovewrap
{
lua_CFunction initializeScene(Scene *scene)
{
currentScene = scene;
return &baseMain;
}
Scene::Scene() {}
Scene::~Scene() {}
void Scene::load(std::vector<std::string>) {}
void Scene::update(double) {}
void Scene::draw() {}
bool Scene::quit() {return false;}
void Scene::visible(bool) {}
void Scene::focus(bool) {}
void Scene::resize(int, int) {}
void Scene::keyPressed(love::keyboard::Keyboard::Key, love::keyboard::Keyboard::Scancode, bool) {}
void Scene::keyReleased(love::keyboard::Keyboard::Key, love::keyboard::Keyboard::Scancode) {}
void Scene::textInput(std::string) {}
void Scene::mousePressed(int, int, int, bool) {}
void Scene::mouseReleased(int, int, int, bool) {}
void Scene::mouseMoved(int, int, int, int, bool) {}
void Scene::mouseFocus(bool) {}
}
| 23.622905 | 119 | 0.675653 | MikuAuahDark |
d5f3557e2fdaab5141eaa5f83dc185801c3a2a1c | 5,393 | cpp | C++ | Blaze/logger.cpp | Star-Athenaeum/Blaze | 73f26316e4146596aeb82f77d054cf4e472a2d3d | [
"MIT"
] | 1 | 2021-09-29T21:54:54.000Z | 2021-09-29T21:54:54.000Z | Blaze/logger.cpp | Star-Athenaeum/Blaze | 73f26316e4146596aeb82f77d054cf4e472a2d3d | [
"MIT"
] | 44 | 2020-04-17T14:39:36.000Z | 2020-10-14T04:15:48.000Z | Blaze/logger.cpp | Stryxus/Blaze | 73f26316e4146596aeb82f77d054cf4e472a2d3d | [
"MIT"
] | 1 | 2020-09-30T22:56:48.000Z | 2020-09-30T22:56:48.000Z | #include "pch.hpp"
#include "logger.hpp"
bool Logger::is_using_custom_color = false;
Logger::COLOR Logger::global_foregronnd_color = COLOR::BRIGHT_WHITE_FOREGROUND;
void Logger::log_info(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::BRIGHT_WHITE_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[INFO]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_warn(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::YELLOW_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[WARN]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_error(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::RED_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[ERROR]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_info(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::BRIGHT_WHITE_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[INFO]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_warn(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::YELLOW_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[WARN]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_error(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::RED_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[ERROR]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_nl(int amount)
{
if (amount < 1) amount = 1;
for (int i = 0; i < amount; i++) printf("\n");
}
void Logger::log_divide()
{
string divide = "";
for (int i = 0; i < get_console_buffer_width() - 1; i++) divide += "-";
printf(string("\n" + divide).c_str());
}
void Logger::set_global_foreground_color(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
global_foregronnd_color = color;
}
/*
void Logger::set_global_background_color(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
*/
void Logger::set_console_color(COLOR color)
{
is_using_custom_color = true;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
void Logger::clear_console_color()
{
is_using_custom_color = false;
}
void Logger::set_console_color_internal(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
void Logger::flush_log_buffer()
{
COORD tl = { 0,0 };
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &s);
DWORD written = 0;
DWORD cells = s.dwSize.X * s.dwSize.Y;
FillConsoleOutputCharacter(console, ' ', cells, tl, &written);
FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);
SetConsoleCursorPosition(console, tl);
}
void Logger::log_last_error()
{
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
string message(messageBuffer, size);
LocalFree(messageBuffer);
Logger::log_error(message);
}
void Logger::wait()
{
char c;
cin >> std::noskipws;
while (cin >> c) cout << c << std::endl;
}
string Logger::get_date_time_string()
{
time_t now = cr::system_clock::to_time_t(cr::system_clock::now());
tm current_time{};
localtime_s(¤t_time, &now);
string year = to_string(1900 + current_time.tm_year);
string month = current_time.tm_mon > 8 ? to_string(1 + current_time.tm_mon) : "0" + to_string(1 + current_time.tm_mon);
string day = current_time.tm_mday > 8 ? to_string(1 + current_time.tm_mday) : "0" + to_string(1 + current_time.tm_mday);
string hour = current_time.tm_hour != 60 ? current_time.tm_hour > 8 ? to_string(1 + current_time.tm_hour) : "0" + to_string(1 + current_time.tm_hour) : "00";
string minute = current_time.tm_min != 60 ? current_time.tm_min > 8 ? to_string(1 + current_time.tm_min) : "0" + to_string(1 + current_time.tm_min) : "00";
string second = current_time.tm_sec != 60 ? current_time.tm_sec > 8 ? to_string(1 + current_time.tm_sec) : "0" + to_string(1 + current_time.tm_sec) : "00";
string millisecond = to_string((cr::duration_cast<cr::milliseconds>(cr::system_clock::now().time_since_epoch())).count()).substr(10);
return "[" + year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second + "." + millisecond + "]";
}
wstring Logger::get_date_time_wstring()
{
return string_to_wstring_copy(get_date_time_string());
}
int Logger::get_console_buffer_width()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
} | 36.194631 | 220 | 0.749676 | Star-Athenaeum |
d5f5e196a84df4f4c368f0cf8496d86ca8c3b2c4 | 9,294 | cpp | C++ | tests/unit/utils_test.cpp | wedataintelligence/sdk | b7064239ca82a53485a8913788be67e07d412971 | [
"BSD-2-Clause"
] | null | null | null | tests/unit/utils_test.cpp | wedataintelligence/sdk | b7064239ca82a53485a8913788be67e07d412971 | [
"BSD-2-Clause"
] | null | null | null | tests/unit/utils_test.cpp | wedataintelligence/sdk | b7064239ca82a53485a8913788be67e07d412971 | [
"BSD-2-Clause"
] | null | null | null | /**
* (c) 2019 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include <array>
#include <tuple>
#include <gtest/gtest.h>
#include <mega/base64.h>
#include <mega/filesystem.h>
#include <mega/utils.h>
#include "megafs.h"
TEST(utils, hashCombine_integer)
{
size_t hash = 0;
mega::hashCombine(hash, 42);
#ifdef _WIN32
// MSVC's std::hash gives different values than that of gcc/clang
ASSERT_EQ(sizeof(hash) == 4 ? 286246808ul : 10203658983813110072ull, hash);
#else
ASSERT_EQ(2654435811ull, hash);
#endif
}
TEST(CharacterSet, IterateUtf8)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator("abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'a');
EXPECT_EQ(it.get(), 'b');
EXPECT_EQ(it.get(), 'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator("q\xf0\x90\x80\x80r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), 'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
}
TEST(CharacterSet, IterateUtf16)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator(L"abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'a');
EXPECT_EQ(it.get(), L'b');
EXPECT_EQ(it.get(), L'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator(L"q\xd800\xdc00r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), L'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
}
using namespace mega;
using namespace std;
// Disambiguate between Microsoft's FileSystemType.
using ::mega::FileSystemType;
class ComparatorTest
: public ::testing::Test
{
public:
ComparatorTest()
: mFSAccess()
{
}
template<typename T, typename U>
int compare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, false);
}
template<typename T, typename U>
int ciCompare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, true);
}
LocalPath fromPath(const string& s)
{
return LocalPath::fromPath(s, mFSAccess);
}
template<typename T, typename U>
int fsCompare(const T& lhs, const U& rhs, const FileSystemType type) const
{
const auto caseInsensitive = isCaseInsensitive(type);
return compareUtf(lhs, true, rhs, true, caseInsensitive);
}
private:
FSACCESS_CLASS mFSAccess;
}; // ComparatorTest
TEST_F(ComparatorTest, CompareLocalPaths)
{
LocalPath lhs;
LocalPath rhs;
// Case insensitive
{
// Make sure basic characters are uppercased.
lhs = fromPath("abc");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("ABCD");
EXPECT_LT(ciCompare(lhs, rhs), 0);
EXPECT_GT(ciCompare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("A0B");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure decoded characters are uppercased.
lhs = fromPath("%61%62%63");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = fromPath("A%qB%");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
}
// Case sensitive
{
// Basic comparison.
lhs = fromPath("abc");
EXPECT_EQ(compare(lhs, lhs), 0);
// Make sure characters are not uppercased.
rhs = fromPath("ABC");
EXPECT_NE(compare(lhs, rhs), 0);
EXPECT_NE(compare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("abcd");
EXPECT_LT(compare(lhs, rhs), 0);
EXPECT_GT(compare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("a0b");
EXPECT_EQ(compare(lhs, rhs), 0);
EXPECT_EQ(compare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
EXPECT_EQ(compare(lhs, lhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = fromPath("A%070B1C");
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = fromPath("a%070b1c");
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST_F(ComparatorTest, CompareLocalPathAgainstString)
{
LocalPath lhs;
string rhs;
// Case insensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invariants.
lhs = fromPath("abc");
rhs = "abcd";
EXPECT_LT(ciCompare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(ciCompare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "A0b1C";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Escapes are uppercased.
lhs = fromPath("%61%62%63");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = "A%QB%";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
}
// Case sensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "abc";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invariants.
rhs = "abcd";
EXPECT_LT(compare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(compare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "a0b1c";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invalid escapes left as-is.
lhs = fromPath("a%qb%r");
rhs = "a%qb%r";
EXPECT_EQ(compare(lhs, rhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = "A%070B1C";
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = "a%070b1c";
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST(Conversion, HexVal)
{
// Decimal [0-9]
for (int i = 0x30; i < 0x3a; ++i)
{
EXPECT_EQ(hexval(i), i - 0x30);
}
// Lowercase hexadecimal [a-f]
for (int i = 0x41; i < 0x47; ++i)
{
EXPECT_EQ(hexval(i), i - 0x37);
}
// Uppercase hexadeimcal [A-F]
for (int i = 0x61; i < 0x67; ++i)
{
EXPECT_EQ(hexval(i), i - 0x57);
}
}
TEST(URLCodec, Unescape)
{
string input = "a%4a%4Bc";
string output;
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "aJKc");
}
TEST(URLCodec, UnescapeInvalidEscape)
{
string input;
string output;
// First character is invalid.
input = "a%qbc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%qbc");
// Second character is invalid.
input = "a%bqc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%bqc");
}
TEST(URLCodec, UnescapeShortEscape)
{
string input;
string output;
// No hex digits.
input = "a%";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%");
// Single hex digit.
input = "a%a";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%a");
}
| 23.410579 | 79 | 0.574026 | wedataintelligence |
d5f6b1df4d2d5e8912048e47a6cefa406da9812f | 511 | hpp | C++ | section 4 codes/PacWoman.hpp | PacktPublishing/Building-Games-with-SFML | d79d787ea4e580fe158b92c57a97853f4bf8a656 | [
"MIT"
] | 7 | 2020-01-07T10:32:39.000Z | 2021-12-16T19:48:32.000Z | section 4 codes/PacWoman.hpp | PacktPublishing/Building-Games-with-SFML | d79d787ea4e580fe158b92c57a97853f4bf8a656 | [
"MIT"
] | null | null | null | section 4 codes/PacWoman.hpp | PacktPublishing/Building-Games-with-SFML | d79d787ea4e580fe158b92c57a97853f4bf8a656 | [
"MIT"
] | 2 | 2020-01-05T04:33:43.000Z | 2020-01-07T10:32:40.000Z | #ifndef PACWOMAN_PACWOMAN_HPP
#define PACWOMAN_PACWOMAN_HPP
#include "Animator.hpp"
#include "Character.hpp"
class PacWoman : public Character
{
public:
PacWoman(sf::Texture& texture);
void die();
bool isDying() const;
bool isDead() const;
void update(sf::Time delta);
private:
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
bool m_isDying;
bool m_isDead;
sf::Sprite m_visual;
Animator m_runAnimator;
Animator m_dieAnimator;
};
#endif // PACWOMAN_PACWOMAN_HPP
| 16.483871 | 68 | 0.737769 | PacktPublishing |
d5f768d56116729a556b5839d1d28f8b9b2272dd | 27,082 | cpp | C++ | dbghlpr/emulator_exts.cpp | ntauth/dbghlpr | a47e540b4be7d7a99ed74eb7597140265461e244 | [
"BSD-2-Clause"
] | 3 | 2019-04-02T21:57:13.000Z | 2020-07-14T09:34:08.000Z | dbghlpr/emulator_exts.cpp | ntauth/dbghlpr | a47e540b4be7d7a99ed74eb7597140265461e244 | [
"BSD-2-Clause"
] | null | null | null | dbghlpr/emulator_exts.cpp | ntauth/dbghlpr | a47e540b4be7d7a99ed74eb7597140265461e244 | [
"BSD-2-Clause"
] | 2 | 2019-04-02T21:57:14.000Z | 2019-11-20T08:30:26.000Z | #define _CRT_SECURE_NO_WARNINGS
#include <unicorn/unicorn.h>
#include <engextcpp.hpp>
#include <windows.h>
#include <TlHelp32.h>
#include <stdio.h>
#include <list>
#include <memory>
#include <strsafe.h>
#include <interface.h>
#include <engine.h>
#include <capstone.h>
#include <engine_linker.h>
#include <helper.h>
#include <emulator.h>
static void hook_code(uc_engine *uc, uint64_t address, uint32_t size, void *user_data)
{
dprintf("run %I64x\n", address);
}
static void hook_unmap_memory(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data)
{
if (type == UC_MEM_WRITE_UNMAPPED || type == UC_MEM_READ_UNMAPPED)
{
dprintf("unmaped memory.. %I64x\n", address);
}
}
static void hook_fetch_memory(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data)
{
if (type == UC_MEM_FETCH_UNMAPPED)
{
dprintf("fetch memory.. %I64x\n", address);
}
}
unsigned long long __stdcall alignment(unsigned long long region_size, unsigned long image_aligin)
{
unsigned long mod = region_size % image_aligin;
region_size -= mod;
return region_size + image_aligin;
}
//
//
//
uc_engine *_uc = nullptr;
bool __stdcall query(unsigned long long address, unsigned long long *base, unsigned long long *size)
{
uc_mem_region *um = nullptr;
uint32_t count = 0;
if (uc_mem_regions(_uc, &um, &count) != 0)
return false;
std::shared_ptr<void> uc_memory_closer(um, free);
for (unsigned int i = 0; i < count; ++i)
{
if (address >= um[i].begin && address <= um[i].end)
{
*base = um[i].begin;
*size = um[i].end - um[i].begin;
return true;
}
}
return false;
}
void set_global_descriptor(SegmentDescriptor *desc, uint32_t base, uint32_t limit, uint8_t is_code)
{
desc->descriptor = 0;
desc->base_low = base & 0xffff;
desc->base_mid = (base >> 16) & 0xff;
desc->base_hi = base >> 24;
if (limit > 0xfffff)
{
limit >>= 12;
desc->granularity = 1;
}
desc->limit_low = limit & 0xffff;
desc->limit_hi = limit >> 16;
desc->dpl = 3;
desc->present = 1;
desc->db = 1;
desc->type = is_code ? 0xb : 3;
desc->system = 1;
}
bool __stdcall read_x86_cpu_context(cpu_context_type *context)
{
int x86_register[] = { UC_X86_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long *read_register = nullptr;
void **read_ptr = nullptr;
read_register = (unsigned long *)malloc(sizeof(unsigned long)*size);
if (!read_register)
return false;
std::shared_ptr<void> read_register_closer(read_register, free);
memset(read_register, 0, sizeof(unsigned long)*size);
read_ptr = (void **)malloc(sizeof(void **)*size);
if (!read_ptr)
return false;
std::shared_ptr<void> read_ptr_closer(read_ptr, free);
memset(read_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
read_ptr[i] = &read_register[i];
if (uc_reg_read_batch(_uc, x86_register, read_ptr, size) != 0)
return false;
context->rax = read_register[PR_RAX];
context->rbx = read_register[PR_RBX];
context->rcx = read_register[PR_RCX];
context->rdx = read_register[PR_RDX];
context->rsi = read_register[PR_RSI];
context->rdi = read_register[PR_RDI];
context->rsp = read_register[PR_RSP];
context->rbp = read_register[PR_RBP];
context->rip = read_register[PR_RIP];
context->xmm0 = read_register[PR_XMM0];
context->xmm1 = read_register[PR_XMM1];
context->xmm2 = read_register[PR_XMM2];
context->xmm3 = read_register[PR_XMM3];
context->xmm4 = read_register[PR_XMM4];
context->xmm5 = read_register[PR_XMM5];
context->xmm6 = read_register[PR_XMM6];
context->xmm7 = read_register[PR_XMM7];
context->ymm0 = read_register[PR_YMM0];
context->ymm1 = read_register[PR_YMM1];
context->ymm2 = read_register[PR_YMM2];
context->ymm3 = read_register[PR_YMM3];
context->ymm4 = read_register[PR_YMM4];
context->ymm5 = read_register[PR_YMM5];
context->ymm6 = read_register[PR_YMM6];
context->ymm7 = read_register[PR_YMM7];
context->efl = read_register[PR_EFLAGS];
context->cs = (unsigned short)read_register[PR_REG_CS];
context->ds = (unsigned short)read_register[PR_REG_DS];
context->es = (unsigned short)read_register[PR_REG_ES];
context->fs = (unsigned short)read_register[PR_REG_FS];
context->gs = (unsigned short)read_register[PR_REG_GS];
context->ss = (unsigned short)read_register[PR_REG_SS];
return true;
}
bool __stdcall write_x86_cpu_context(cpu_context_type context)
{
int x86_register[] = { UC_X86_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long *write_register = nullptr;
void **write_ptr = nullptr;
write_register = (unsigned long *)malloc(sizeof(unsigned long)*size);
if (!write_register)
return false;
std::shared_ptr<void> write_register_closer(write_register, free);
memset(write_register, 0, sizeof(unsigned long)*size);
write_ptr = (void **)malloc(sizeof(void **)*size);
if (!write_ptr)
return false;
std::shared_ptr<void> write_ptr_closer(write_ptr, free);
memset(write_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
write_ptr[i] = &write_register[i];
write_register[PR_RAX] = (unsigned long)context.rax;
write_register[PR_RBX] = (unsigned long)context.rbx;
write_register[PR_RCX] = (unsigned long)context.rcx;
write_register[PR_RDX] = (unsigned long)context.rdx;
write_register[PR_RSI] = (unsigned long)context.rsi;
write_register[PR_RDI] = (unsigned long)context.rdi;
write_register[PR_RSP] = (unsigned long)context.rsp;
write_register[PR_RBP] = (unsigned long)context.rbp;
write_register[PR_RIP] = (unsigned long)context.rip;
write_register[PR_EFLAGS] = (unsigned long)context.efl;
write_register[PR_XMM0] = (unsigned long)context.xmm0;
write_register[PR_XMM1] = (unsigned long)context.xmm1;
write_register[PR_XMM2] = (unsigned long)context.xmm2;
write_register[PR_XMM3] = (unsigned long)context.xmm3;
write_register[PR_XMM4] = (unsigned long)context.xmm4;
write_register[PR_XMM5] = (unsigned long)context.xmm5;
write_register[PR_XMM6] = (unsigned long)context.xmm6;
write_register[PR_XMM7] = (unsigned long)context.xmm7;
write_register[PR_YMM0] = (unsigned long)context.ymm0;
write_register[PR_YMM1] = (unsigned long)context.ymm1;
write_register[PR_YMM2] = (unsigned long)context.ymm2;
write_register[PR_YMM3] = (unsigned long)context.ymm3;
write_register[PR_YMM4] = (unsigned long)context.ymm4;
write_register[PR_YMM5] = (unsigned long)context.ymm5;
write_register[PR_YMM6] = (unsigned long)context.ymm6;
write_register[PR_YMM7] = (unsigned long)context.ymm7;
write_register[PR_REG_CS] = context.cs;
write_register[PR_REG_DS] = context.ds;
write_register[PR_REG_ES] = context.es;
write_register[PR_REG_FS] = context.fs;
write_register[PR_REG_GS] = context.gs;
write_register[PR_REG_SS] = context.ss;
if (uc_reg_write_batch(_uc, x86_register, write_ptr, size) != 0)
return false;
return true;
}
bool __stdcall write_x64_cpu_context(cpu_context_type context)
{
#ifdef _WIN64
int x86_register[] = { UC_X64_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long long *write_register = nullptr;
void **write_ptr = nullptr;
write_register = (unsigned long long *)malloc(sizeof(unsigned long long)*size);
if (!write_register)
return false;
std::shared_ptr<void> write_register_closer(write_register, free);
memset(write_register, 0, sizeof(unsigned long long)*size);
write_ptr = (void **)malloc(sizeof(void **)*size);
if (!write_ptr)
return false;
std::shared_ptr<void> write_ptr_closer(write_ptr, free);
memset(write_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
write_ptr[i] = &write_register[i];
write_register[PR_RAX] = context.rax;
write_register[PR_RBX] = context.rbx;
write_register[PR_RCX] = context.rcx;
write_register[PR_RDX] = context.rdx;
write_register[PR_RSI] = context.rsi;
write_register[PR_RDI] = context.rdi;
write_register[PR_RSP] = context.rsp;
write_register[PR_RBP] = context.rbp;
write_register[PR_RIP] = context.rip;
write_register[PR_R8] = context.r8;
write_register[PR_R9] = context.r9;
write_register[PR_R10] = context.r10;
write_register[PR_R11] = context.r11;
write_register[PR_R12] = context.r12;
write_register[PR_R13] = context.r13;
write_register[PR_R14] = context.r14;
write_register[PR_R15] = context.r15;
write_register[PR_EFLAGS] = (unsigned long)context.efl;
write_register[PR_XMM0] = context.xmm0;
write_register[PR_XMM1] = context.xmm1;
write_register[PR_XMM2] = context.xmm2;
write_register[PR_XMM3] = context.xmm3;
write_register[PR_XMM4] = context.xmm4;
write_register[PR_XMM5] = context.xmm5;
write_register[PR_XMM6] = context.xmm6;
write_register[PR_XMM7] = context.xmm7;
write_register[PR_XMM8] = context.xmm8;
write_register[PR_XMM9] = context.xmm9;
write_register[PR_XMM10] = context.xmm10;
write_register[PR_XMM11] = context.xmm11;
write_register[PR_XMM12] = context.xmm12;
write_register[PR_XMM13] = context.xmm13;
write_register[PR_XMM14] = context.xmm14;
write_register[PR_XMM15] = context.xmm15;
write_register[PR_YMM0] = context.ymm0;
write_register[PR_YMM1] = context.ymm1;
write_register[PR_YMM2] = context.ymm2;
write_register[PR_YMM3] = context.ymm3;
write_register[PR_YMM4] = context.ymm4;
write_register[PR_YMM5] = context.ymm5;
write_register[PR_YMM6] = context.ymm6;
write_register[PR_YMM7] = context.ymm7;
write_register[PR_YMM8] = context.ymm8;
write_register[PR_YMM9] = context.ymm9;
write_register[PR_YMM10] = context.ymm10;
write_register[PR_YMM11] = context.ymm11;
write_register[PR_YMM12] = context.ymm12;
write_register[PR_YMM13] = context.ymm13;
write_register[PR_YMM14] = context.ymm14;
write_register[PR_YMM15] = context.ymm15;
write_register[PR_REG_CS] = context.cs;
write_register[PR_REG_DS] = context.ds;
write_register[PR_REG_ES] = context.es;
write_register[PR_REG_FS] = context.fs;
write_register[PR_REG_GS] = context.gs;
write_register[PR_REG_SS] = context.ss;
if (uc_reg_write_batch(_uc, x86_register, write_ptr, size) != 0)
return false;
#endif
return true;
}
bool __stdcall read_x64_cpu_context(cpu_context_type *context)
{
#ifdef _WIN64
int x86_register[] = { UC_X64_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long long *read_register = nullptr;
void **read_ptr = nullptr;
read_register = (unsigned long long *)malloc(sizeof(unsigned long long)*size);
if (!read_register)
return false;
std::shared_ptr<void> read_register_closer(read_register, free);
memset(read_register, 0, sizeof(unsigned long long)*size);
read_ptr = (void **)malloc(sizeof(void **)*size);
if (!read_ptr)
return false;
std::shared_ptr<void> read_ptr_closer(read_ptr, free);
memset(read_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
read_ptr[i] = &read_register[i];
if (uc_reg_read_batch(_uc, x86_register, read_ptr, size) != 0)
return false;
context->rax = read_register[PR_RAX];
context->rbx = read_register[PR_RBX];
context->rcx = read_register[PR_RCX];
context->rdx = read_register[PR_RDX];
context->rsi = read_register[PR_RSI];
context->rdi = read_register[PR_RDI];
context->rsp = read_register[PR_RSP];
context->rbp = read_register[PR_RBP];
context->rip = read_register[PR_RIP];
context->r8 = read_register[PR_R8];
context->r9 = read_register[PR_R9];
context->r10 = read_register[PR_R10];
context->r11 = read_register[PR_R11];
context->r12 = read_register[PR_R12];
context->r13 = read_register[PR_R13];
context->r14 = read_register[PR_R14];
context->r15 = read_register[PR_R15];
context->efl = (unsigned long)read_register[PR_EFLAGS];
context->xmm0 = read_register[PR_XMM0];
context->xmm1 = read_register[PR_XMM1];
context->xmm2 = read_register[PR_XMM2];
context->xmm3 = read_register[PR_XMM3];
context->xmm4 = read_register[PR_XMM4];
context->xmm5 = read_register[PR_XMM5];
context->xmm6 = read_register[PR_XMM6];
context->xmm7 = read_register[PR_XMM7];
context->xmm8 = read_register[PR_XMM8];
context->xmm9 = read_register[PR_XMM9];
context->xmm10 = read_register[PR_XMM10];
context->xmm11 = read_register[PR_XMM11];
context->xmm12 = read_register[PR_XMM12];
context->xmm13 = read_register[PR_XMM13];
context->xmm14 = read_register[PR_XMM14];
context->xmm15 = read_register[PR_XMM15];
context->ymm0 = read_register[PR_YMM0];
context->ymm1 = read_register[PR_YMM1];
context->ymm2 = read_register[PR_YMM2];
context->ymm3 = read_register[PR_YMM3];
context->ymm4 = read_register[PR_YMM4];
context->ymm5 = read_register[PR_YMM5];
context->ymm6 = read_register[PR_YMM6];
context->ymm7 = read_register[PR_YMM7];
context->ymm8 = read_register[PR_YMM8];
context->ymm9 = read_register[PR_YMM9];
context->ymm10 = read_register[PR_YMM10];
context->ymm11 = read_register[PR_YMM11];
context->ymm12 = read_register[PR_YMM12];
context->ymm13 = read_register[PR_YMM13];
context->ymm14 = read_register[PR_YMM14];
context->ymm15 = read_register[PR_YMM15];
context->cs = (unsigned short)read_register[PR_REG_CS];
context->ds = (unsigned short)read_register[PR_REG_DS];
context->es = (unsigned short)read_register[PR_REG_ES];
context->fs = (unsigned short)read_register[PR_REG_FS];
context->gs = (unsigned short)read_register[PR_REG_GS];
context->ss = (unsigned short)read_register[PR_REG_SS];
#endif
return true;
}
void __stdcall print_reg_64(unsigned long long c, unsigned long long b)
{
if (c != b)
g_Ext->Dml("<b><col fg=\"changed\">%0*I64x</col></b>", 16, c);
else
dprintf("%0*I64x", 16, c);
}
void __stdcall print_reg_32(unsigned long long c, unsigned long long b)
{
if (c != b)
g_Ext->Dml("<b><col fg=\"changed\">%08x</col></b>", c);
else
dprintf("%08x", c);
}
void __stdcall view_cpu_context()
{
cpu_context_type context;
#ifdef _WIN64
read_x64_cpu_context(&context);
dprintf(" rax=%0*I64x rbx=%0*I64x rcx=%0*I64x rdx=%0*I64x rsi=%0*I64x rdi=%0*I64x\n", 16, context.rax, 16, context.rbx, 16, context.rcx, 16, context.rdx, 16, context.rsi, 16, context.rdi);
dprintf(" rip=%0*I64x rsp=%0*I64x rbp=%0*I64x efl=%0*I64x\n", 16, context.rip, 16, context.rsp, 16, context.rbp, context.efl);
dprintf(" r8=%0*I64x r9=%0*I64x r10=%0*I64x r11=%0*I64x r12=%0*I64x r13=%0*I64x r14=%0*I64x r15=%0*I64x\n", 16, context.r8, 16, context.r9, 16, context.r10, 16, context.r11, 16, context.r12, 16, context.r13, 16, context.r14, 16, context.r15);
dprintf(" cs=%x ds=%x es=%x fs=%x gs=%x %ss\n", context.cs, context.ds, context.es, context.fs, context.gs, context.ss);
#else
read_x86_cpu_context(&context);
dprintf(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n", (unsigned long)context.rax, (unsigned long)context.rbx, (unsigned long)context.rcx, (unsigned long)context.rdx, (unsigned long)context.rsi, (unsigned long)context.rdi);
dprintf(" eip=%08x esp=%08x ebp=%08x efl=%08x\n", (unsigned long)context.rip, (unsigned long)context.rsp, (unsigned long)context.rbp, (unsigned long)context.efl);
dprintf(" cs=%x ds=%x es=%x fs=%x gs=%x %ss\n", context.cs, context.ds, context.es, context.fs, context.gs, context.ss);
#endif
dprintf("\n");
char str[1024] = { 0, };
Disasm(&context.rip, str, false);
dprintf(" %s", str);
dprintf("\n");
}
bool __stdcall create_global_descriptor_table(cpu_context_type context, unsigned long mode)
{
SegmentDescriptor global_descriptor[31];
memset(global_descriptor, 0, sizeof(global_descriptor));
context.ss = 0x88; // rpl = 0
context.gs = 0x63;
set_global_descriptor(&global_descriptor[0x33 >> 3], 0, 0xfffff000, 1); // 64 code
set_global_descriptor(&global_descriptor[context.cs >> 3], 0, 0xfffff000, 1);
set_global_descriptor(&global_descriptor[context.ds >> 3], 0, 0xfffff000, 0);
set_global_descriptor(&global_descriptor[context.fs >> 3], 0, 0xfff, 0);
set_global_descriptor(&global_descriptor[context.gs >> 3], 0, 0xfffff000, 0);
set_global_descriptor(&global_descriptor[context.ss >> 3], 0, 0xfffff000, 0);
global_descriptor[context.ss >> 3].dpl = 0; // dpl = 0, cpl = 0
unsigned long long gdt_base = 0xc0000000;
uc_x86_mmr gdtr;
gdtr.base = gdt_base;
gdtr.limit = (sizeof(SegmentDescriptor) * 31) - 1;
if (uc_reg_write(_uc, UC_X86_REG_GDTR, &gdtr) != 0)
return false;
if (uc_mem_map(_uc, gdt_base, (size_t)0x10000, UC_PROT_ALL) == 0)
{
if (uc_mem_write(_uc, gdt_base, global_descriptor, sizeof(global_descriptor)) == 0)
{
#ifdef _WIN64
write_x64_cpu_context(context);
#else
write_x86_cpu_context(context);
#endif
}
}
return true;
}
//
//
//
EXT_CLASS_COMMAND(WindbgEngine, open, "", "{bit;ed,o;bit;;}")
{
if (!HasArg("bit"))
{
return;
}
if (_uc)
{
uc_close(_uc);
}
uc_mode mode;
unsigned long long bit = GetArgU64("bit", false);
if (bit == 0x32)
{
mode = UC_MODE_32;
}
else if (bit == 0x64)
{
mode = UC_MODE_64;
}
else
{
dprintf("unsupported mode\n");
return;
}
if (uc_open(UC_ARCH_X86, mode, &_uc) == 0)
{
cpu_context_type context;
engine_linker linker;
linker.get_thread_context(&context);
cpu_context_type segment_context = { 0, };
segment_context.cs = context.cs;
segment_context.ds = context.ds;
segment_context.es = context.es;
segment_context.fs = 0x88;
segment_context.gs = 0x63;
if (create_global_descriptor_table(segment_context, mode))
{
dprintf("emulator:: open success\n");
view_cpu_context();
}
}
}
EXT_CLASS_COMMAND(WindbgEngine, alloc, "", "{em;ed,o;em;;}" "{size;ed,o;size;;}" "{copy;b,o;copy;;}")
{
if (!HasArg("em") || !HasArg("size"))
{
return;
}
unsigned long long em = GetArgU64("em", false);
unsigned long long size = GetArgU64("size", false);
unsigned long long base = alignment(em, 0x1000) - 0x1000;
unsigned long long base_size = alignment(size, 0x1000);
if (uc_mem_map(_uc, base, (size_t)base_size, UC_PROT_ALL) == 0)
{
dprintf("emulator:: alloc success\n");
dprintf(" [-] %I64x-%I64x\n", base, base+base_size);
if (HasArg("copy"))
{
unsigned char *dump = (unsigned char *)malloc((size_t)size);
if (!dump)
{
dprintf("emulator:: copy fail\n");
}
std::shared_ptr<void> dump_closer(dump, free);
engine_linker linker;
unsigned long readn = linker.read_virtual_memory(em, dump, (unsigned long)size);
if (uc_mem_write(_uc, em, dump, readn) == 0)
{
dprintf("emulator:: copy success\n");
}
}
}
else
{
dprintf("emulator:: copy fail\n");
}
}
EXT_CLASS_COMMAND(WindbgEngine, write, "", "{em;ed,o;em;;}" "{hex;x,o;hex;;}")
{
if (!HasArg("em") || !HasArg("hex"))
{
return;
}
unsigned long long em = GetArgU64("em", false);
PCSTR hex = GetArgStr("hex", true);
size_t size_of_hex = strlen(hex);
unsigned char *hex_dump = (unsigned char *)malloc(size_of_hex);
if (!hex_dump)
{
return;
}
std::shared_ptr<void> pattern_closer(hex_dump, free);
memset(hex_dump, 0, size_of_hex);
unsigned long long j = 0;
for (unsigned long long i = 0; i < size_of_hex; ++i)
{
if (hex[i] != ' ')
{
char *end = nullptr;
hex_dump[j++] = (unsigned char)strtol(&hex[i], &end, 16);
i = end - hex;
}
}
if (uc_mem_write(_uc, em, hex_dump, size_of_hex) == 0)
{
dprintf("emulator:: write success\n");
}
}
EXT_CLASS_COMMAND(WindbgEngine, read, "", "{em;ed,o;em;;}" "{size;ed,o;size;;}")
{
if (!HasArg("em") || !HasArg("size"))
{
return;
}
unsigned long long em = GetArgU64("em", false);
unsigned long long size = GetArgU64("size", false);
unsigned char *dump = (unsigned char *)malloc((size_t)size);
if (!dump)
return;
std::shared_ptr<void> dump_closer(dump, free);
memset(dump, 0, (size_t)size);
if (uc_mem_read(_uc, em, dump, (size_t)size) != 0)
{
dprintf("emulator:: read fail\n");
return;
}
unsigned int i = 0, j = 0;
for (i; i < size; ++i)
{
if (i == 0)
{
dprintf("%08x ", em);
}
else if (i % 16 == 0)
{
/*-- ascii --*/
for (j; j < i; ++j)
{
if (helper::is_ascii(dump, (size_t)size))
dprintf("%c", dump[j]);
else
dprintf(".");
}
/*-- next line --*/
dprintf("\n");
em += 16;
dprintf("%08x ", em);
}
dprintf("%02x ", dump[i]);
}
if (i % 16)
{
for (unsigned k = 0; k < i % 16; ++i)
dprintf(" ");
}
for (j; j < i; ++j)
{
if (helper::is_ascii(dump, (size_t)size))
dprintf("%c", dump[j]);
else
dprintf(".");
}
dprintf("\n");
}
EXT_CLASS_COMMAND(WindbgEngine, query, "", "{em;ed,o;em;;}")
{
if (!HasArg("em"))
return;
unsigned long long em = GetArgU64("em", false);
unsigned long long base = 0;
unsigned long long size = 0;
if (::query(em, &base, &size))
{
dprintf(" %I64x-%I64x\n", base, base + size + 1);
}
}
EXT_CLASS_COMMAND(WindbgEngine, trace, "", "{em;ed,o;em;;}" "{step;ed,o;step;;}")
{
if (!HasArg("em") || !HasArg("step"))
return;
cpu_context_type backup;
read_x86_cpu_context(&backup);
unsigned long long em = GetArgU64("em", false);
unsigned long long step = GetArgU64("step", false);
unsigned long long base = 0;
unsigned long long size = 0;
if (::query(em, &base, &size))
{
dprintf(" %I64x:: %I64x-%I64x\n", em, base, base + size + 1);
}
else
{
dprintf(" %I64x:: not found emulator memory..\n");
}
uc_err err = uc_emu_start(_uc, em, em+size, 0, (size_t)step);
if (err)
{
dprintf("emulator:: %d\n", err);
}
else
{
cpu_context_type context;
#ifdef _WIN64
read_x64_cpu_context(&context);
#else
read_x86_cpu_context(&context);
#endif
#ifdef _WIN64
view_cpu_context();
#else
view_cpu_context();
#endif
}
}
EXT_CLASS_COMMAND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ed,o;ymm14;;}" "{ymm15;ed,o;ymm15;;}"
"{view;b,o;view;;}")
{
if (HasArg("view"))
{
view_cpu_context();
}
else
{
cpu_context_type context;
#ifdef _WIN64
read_x64_cpu_context(&context);
#else
read_x86_cpu_context(&context);
#endif
if (HasArg("rax"))
context.rax = GetArgU64("rax", false);
if(HasArg("rbx"))
context.rbx = GetArgU64("rbx", false);
if (HasArg("rcx"))
context.rcx = GetArgU64("rcx", false);
if (HasArg("rdx"))
context.rdx = GetArgU64("rdx", false);
if (HasArg("rdi"))
context.rdi = GetArgU64("rdi", false);
if (HasArg("rsi"))
context.rsi = GetArgU64("rsi", false);
if (HasArg("rbp"))
context.rbp = GetArgU64("rbp", false);
if (HasArg("rsp"))
context.rsp = GetArgU64("rsp", false);
if (HasArg("rip"))
context.rsp = GetArgU64("rip", false);
if (HasArg("r8"))
context.r8 = GetArgU64("r8", false);
if (HasArg("r9"))
context.r9 = GetArgU64("r9", false);
if (HasArg("r10"))
context.r10 = GetArgU64("r10", false);
if (HasArg("r11"))
context.r11 = GetArgU64("r11", false);
if (HasArg("r12"))
context.r12 = GetArgU64("r12", false);
if (HasArg("r13"))
context.r13 = GetArgU64("r13", false);
if (HasArg("r14"))
context.r14 = GetArgU64("r14", false);
if (HasArg("r15"))
context.r15 = GetArgU64("r15", false);
if (HasArg("xmm0"))
context.xmm0 = GetArgU64("xmm0", false);
if (HasArg("xmm1"))
context.xmm1 = GetArgU64("xmm1", false);
if (HasArg("xmm2"))
context.xmm2 = GetArgU64("xmm2", false);
if (HasArg("xmm3"))
context.xmm3 = GetArgU64("xmm3", false);
if (HasArg("xmm4"))
context.xmm4 = GetArgU64("xmm4", false);
if (HasArg("xmm5"))
context.xmm5 = GetArgU64("xmm5", false);
if (HasArg("xmm6"))
context.xmm6 = GetArgU64("xmm6", false);
if (HasArg("xmm7"))
context.xmm7 = GetArgU64("xmm7", false);
if (HasArg("xmm8"))
context.xmm8 = GetArgU64("xmm8", false);
if (HasArg("xmm9"))
context.xmm9 = GetArgU64("xmm9", false);
if (HasArg("xmm10"))
context.xmm10 = GetArgU64("xmm10", false);
if (HasArg("xmm11"))
context.xmm11 = GetArgU64("xmm11", false);
if (HasArg("xmm12"))
context.xmm12 = GetArgU64("xmm12", false);
if (HasArg("xmm13"))
context.xmm13 = GetArgU64("xmm13", false);
if (HasArg("xmm14"))
context.xmm14 = GetArgU64("xmm14", false);
if (HasArg("xmm15"))
context.xmm15 = GetArgU64("xmm15", false);
if (HasArg("ymm0"))
context.ymm0 = GetArgU64("ymm0", false);
if (HasArg("ymm1"))
context.ymm1 = GetArgU64("ymm1", false);
if (HasArg("ymm2"))
context.ymm2 = GetArgU64("ymm2", false);
if (HasArg("ymm3"))
context.ymm3 = GetArgU64("ymm3", false);
if (HasArg("ymm4"))
context.ymm4 = GetArgU64("ymm4", false);
if (HasArg("ymm5"))
context.ymm5 = GetArgU64("ymm5", false);
if (HasArg("ymm6"))
context.ymm6 = GetArgU64("ymm6", false);
if (HasArg("ymm7"))
context.ymm7 = GetArgU64("ymm7", false);
if (HasArg("ymm8"))
context.ymm8 = GetArgU64("ymm8", false);
if (HasArg("ymm9"))
context.ymm9 = GetArgU64("ymm9", false);
if (HasArg("ymm10"))
context.ymm10 = GetArgU64("ymm10", false);
if (HasArg("ymm11"))
context.ymm11 = GetArgU64("ymm11", false);
if (HasArg("ymm12"))
context.ymm12 = GetArgU64("ymm12", false);
if (HasArg("ymm13"))
context.ymm13 = GetArgU64("ymm13", false);
if (HasArg("ymm14"))
context.ymm14 = GetArgU64("ymm14", false);
if (HasArg("ymm15"))
context.ymm15 = GetArgU64("ymm15", false);
if (HasArg("copy"))
{
engine_linker linker;
cpu_context_type current_context = { 0, };
if (linker.get_thread_context(¤t_context))
{
context.rax = current_context.rax;
context.rbx = current_context.rbx;
context.rcx = current_context.rcx;
context.rdx = current_context.rdx;
context.rdi = current_context.rdi;
context.rsi = current_context.rsi;
context.rsp = current_context.rsp;
context.rbp = current_context.rbp;
context.rip = current_context.rip;
context.efl = current_context.efl;
context.r8 = current_context.r8;
context.r9 = current_context.r9;
context.r10 = current_context.r10;
context.r11 = current_context.r11;
context.r12 = current_context.r12;
context.r13 = current_context.r13;
context.r14 = current_context.r14;
context.r15 = current_context.r15;
}
}
#ifdef _WIN64
write_x64_cpu_context(context);
#else
write_x86_cpu_context(context);
#endif
view_cpu_context();
}
}
| 28.387841 | 243 | 0.681781 | ntauth |
d5f7b9bc02d182192c18faf987c2f68cf1eeb6df | 20,947 | cpp | C++ | core/src/main.cpp | qualk/Vega.wtf | 8e0966d5d490f73d405433154daa5b2d9a50f9b6 | [
"MIT"
] | 6 | 2021-09-17T01:33:23.000Z | 2022-03-19T05:13:21.000Z | core/src/main.cpp | qualk/Vega.wtf | 8e0966d5d490f73d405433154daa5b2d9a50f9b6 | [
"MIT"
] | 1 | 2021-09-17T02:03:02.000Z | 2021-09-17T02:03:02.000Z | core/src/main.cpp | qualk/Vega.wtf | 8e0966d5d490f73d405433154daa5b2d9a50f9b6 | [
"MIT"
] | 4 | 2021-09-17T01:33:32.000Z | 2021-09-29T05:12:23.000Z | #include "includes.h"
#define OBF_BEGIN try { obf::next_step __crv = obf::next_step::ns_done; std::shared_ptr<obf::base_rvholder> __rvlocal;
// Data
static LPDIRECT3D9 g_pD3D = NULL;
static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
static D3DPRESENT_PARAMETERS g_d3dpp = {};
// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void ResetDevice();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
bool frameRounding = true;
float GUI_Color[4] = { 1.000f, 0.137f, 1.000f, 1.000f };
bool otherBG = true;
namespace features {
int window_key = 45; // insert
bool hideWindow = false;
}
namespace helpers {
// Keymap
const char* keys[256] = {
"",
"",
"",
"",
"",
"MOUSE4",
"MOUSE5",
"",
"BACKSPACE",
"TAB",
"",
"",
"CLEAR",
"ENTER",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"SPACE",
"PGUP",
"PGDOWN",
"END",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"INSERT",
"DELETE",
"",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"",
"",
"",
"",
"",
"",
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"",
"",
"",
"",
"",
"NUM0",
"NUM1",
"NUM2",
"NUM3",
"NUM4",
"NUM5",
"NUM6",
"NUM7",
"NUM8",
"NUM9",
"MULTIPLY",
"ADD",
"SEPARATOR",
"SUBTRACT",
"DECIMAL",
"DIVIDE",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"F13",
"F14",
"F15",
"F16",
"F17",
"F18",
"F19",
"F20",
"F21",
"F22",
"F23",
"F24",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"LSHIFT",
"RSHIFT",
"LCONTROL",
"RCONTROL",
"LMENU",
"RMENU",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"COMMA",
"MINUS",
"PERIOD",
"SLASH",
"TILDA",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"[",
"|",
"]",
"QUOTE",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
};
//
// Gets current key down and returns it
//
int getKeybind()
{
int i = 0;
int n = 0;
while (n == 0) {
for (i = 3; i < 256; i++)
{
if (GetAsyncKeyState((i)))
{
if (i < 256) {
if (!(*keys[i] == 0)) {
n = 1;
return i;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
//
// check if the key is down.
//
bool keyCheck(int key)
{
for (int t = 3; t < 256; t++)
{
if (GetAsyncKeyState(t))
{
if ((keys[key] == keys[t]) & (keys[key] != 0 & keys[t] != 0))
{
return true;
//std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
}
return false;
}
static auto generate_random_float = [](float min, float max) {
float random = ((float)rand()) / (float)RAND_MAX;
float diff = max - min;
float r = random * diff;
return min + r;
};
//
// Implement this as a thread
// takes in a key and a reference to a bool to toggle on or off
// if they key you put in is true it toggles the bool you passed in.
//
void checkThread(int key, bool& toggle)
{
auto future = std::async(helpers::keyCheck, key);
if (future.get()) {
toggle = !toggle;
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
}
// Side Panel State
int sidePanel = 0;
// Main code
int main(int, char**)
{
// Create application window
//ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T(" "), NULL };
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T(" "), WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, 500, 335, NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.Fonts->AddFontFromMemoryCompressedTTF(Ubuntu_Light_compressed_data, Ubuntu_Light_compressed_size, 20);
io.Fonts->AddFontFromMemoryCompressedTTF(Ubuntu_Regular_compressed_data, Ubuntu_Regular_compressed_size, 18);
std::thread clickerThread(features::clickerThread);
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX9_Init(g_pd3dDevice);
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
// Start the Dear ImGui frame
ImGui_ImplDX9_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
if (!features::hideWindow) {
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
::ShowWindow(GetConsoleWindow(), SW_HIDE);
}
else {
// Show the window
::ShowWindow(hwnd, SW_HIDE);
::ShowWindow(GetConsoleWindow(), SW_HIDE);
}
{
// press the - on Visual Studio to Ignore
{
ImColor mainColor = ImColor(GUI_Color[0], GUI_Color[1], GUI_Color[2], GUI_Color[3]);
ImColor bodyColor = ImColor(int(24), int(24), int(24), 255);
ImColor fontColor = ImColor(int(255), int(255), int(255), 255);
ImGuiStyle& style = ImGui::GetStyle();
ImVec4 mainColorHovered = ImVec4(mainColor.Value.x + 0.1f, mainColor.Value.y + 0.1f, mainColor.Value.z + 0.1f, mainColor.Value.w);
ImVec4 mainColorActive = ImVec4(mainColor.Value.x + 0.2f, mainColor.Value.y + 0.2f, mainColor.Value.z + 0.2f, mainColor.Value.w);
ImVec4 menubarColor = ImVec4(bodyColor.Value.x, bodyColor.Value.y, bodyColor.Value.z, bodyColor.Value.w - 0.8f);
ImVec4 frameBgColor = ImVec4(bodyColor.Value.x + 0.1f, bodyColor.Value.y + 0.1f, bodyColor.Value.z + 0.1f, bodyColor.Value.w + .1f);
ImVec4 tooltipBgColor = ImVec4(bodyColor.Value.x, bodyColor.Value.y, bodyColor.Value.z, bodyColor.Value.w + .05f);
style.Alpha = 1.0f;
style.WindowPadding = ImVec2(8, 8);
style.WindowMinSize = ImVec2(32, 32);
style.WindowRounding = 0.0f;
style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
style.ChildRounding = 0.0f;
style.FramePadding = ImVec2(4, 3);
style.FrameRounding = 0.0f;
style.ItemSpacing = ImVec2(4, 3);
style.ItemInnerSpacing = ImVec2(4, 4);
style.TouchExtraPadding = ImVec2(0, 0);
style.IndentSpacing = 21.0f;
style.ColumnsMinSpacing = 3.0f;
style.ScrollbarSize = 8.f;
style.ScrollbarRounding = 0.0f;
style.GrabMinSize = 1.0f;
style.GrabRounding = 0.0f;
style.ButtonTextAlign = ImVec2(0.5f, 0.5f);
style.DisplayWindowPadding = ImVec2(22, 22);
style.DisplaySafeAreaPadding = ImVec2(4, 4);
style.AntiAliasedLines = true;
style.CurveTessellationTol = 1.25f;
style.Colors[ImGuiCol_Text] = fontColor;
style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f);
style.Colors[ImGuiCol_WindowBg] = bodyColor;
style.Colors[ImGuiCol_ChildBg] = ImVec4(.0f, .0f, .0f, .0f);
style.Colors[ImGuiCol_PopupBg] = tooltipBgColor;
style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f);
style.Colors[ImGuiCol_FrameBg] = frameBgColor;
style.Colors[ImGuiCol_FrameBgHovered] = mainColorHovered;
style.Colors[ImGuiCol_FrameBgActive] = mainColorActive;
style.Colors[ImGuiCol_TitleBg] = mainColor;
style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 0.98f, 0.95f, 0.75f);
style.Colors[ImGuiCol_TitleBgActive] = mainColor;
style.Colors[ImGuiCol_MenuBarBg] = menubarColor;
style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(frameBgColor.x + .05f, frameBgColor.y + .05f, frameBgColor.z + .05f, frameBgColor.w);
style.Colors[ImGuiCol_ScrollbarGrab] = mainColor;
style.Colors[ImGuiCol_ScrollbarGrabHovered] = mainColorHovered;
style.Colors[ImGuiCol_ScrollbarGrabActive] = mainColorActive;
style.Colors[ImGuiCol_CheckMark] = mainColor;
style.Colors[ImGuiCol_SliderGrab] = mainColorHovered;
style.Colors[ImGuiCol_SliderGrabActive] = mainColorActive;
style.Colors[ImGuiCol_Button] = mainColor;
style.Colors[ImGuiCol_ButtonHovered] = mainColorHovered;
style.Colors[ImGuiCol_ButtonActive] = mainColorActive;
style.Colors[ImGuiCol_Header] = mainColor;
style.Colors[ImGuiCol_HeaderHovered] = mainColorHovered;
style.Colors[ImGuiCol_HeaderActive] = mainColorActive;
style.Colors[ImGuiCol_ResizeGrip] = mainColor;
style.Colors[ImGuiCol_ResizeGripHovered] = mainColorHovered;
style.Colors[ImGuiCol_ResizeGripActive] = mainColorActive;
style.Colors[ImGuiCol_PlotLines] = mainColor;
style.Colors[ImGuiCol_PlotLinesHovered] = mainColorHovered;
style.Colors[ImGuiCol_PlotHistogram] = mainColor;
style.Colors[ImGuiCol_PlotHistogramHovered] = mainColorHovered;
style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f);
}
// check if the keys down for keybinds
helpers::checkThread(features::left_key, features::CLICKER_TOGGLED);
helpers::checkThread(features::right_key, features::rCLICKER_TOGGLED);
helpers::checkThread(features::window_key, features::hideWindow);
// check for frame rounding
if (frameRounding) {
ImGui::GetStyle().FrameRounding = 4.0f;
ImGui::GetStyle().GrabRounding = 3.0f;
}
else { // we do da java
ImGui::GetStyle().FrameRounding = 0.0f;
ImGui::GetStyle().GrabRounding = 0.0f;
}
// Actuall stuff
// Setup tings
ImGui::Begin(xorstr_(" "), NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoInputs);
ImGui::SetWindowSize({ 500, 0 });
ImGui::SetWindowPos({ 0, 0 });
ImGui::End();
// Left Shit
ImGui::Begin(xorstr_("SidePanel"), NULL, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDecoration); {
ImGui::SetWindowPos({ -5, -5 });
ImGui::SetWindowSize({ 125, 515 });
ImGui::Text(xorstr_("Vega - Clicker"));
if (ImGui::Button(xorstr_("Clicker"), { 100, 50 })) sidePanel = 0;
if (ImGui::Button(xorstr_("Misc"), { 100, 50 })) sidePanel = 1;
//if (ImGui::Button(xorstr_("Config"), { 100, 50 })) sidePanel = 2;
if (ImGui::Button(xorstr_("Settings"), { 100, 50 })) sidePanel = 3;
ImGui::End();
}
// For drawing the gui
ImGui::Begin(xorstr_("Canvas"), NULL, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDecoration); {
ImGui::SetWindowPos({ 115, 5 });
ImGui::SetWindowSize({ 450, 350 });
if (sidePanel == 0) {
// Left
ImGui::Checkbox(xorstr_("Left Toggle"), &features::CLICKER_TOGGLED); ImGui::SameLine(); if (ImGui::Button(xorstr_("Left Bind"))) { features::left_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::left_key]);
// drag clicker not done
//if (!features::lDrag) {
// ImGui::SliderFloat(xorstr_("L CPS"), &features::CPS, 10.0f, 20.0f, "%.1f");
// ImGui::Checkbox(xorstr_("Extra Rand"), &features::lExtraRand); ImGui::SameLine();
//}
// ImGui::Checkbox(xorstr_("Drag Click"), &features::lDrag);
ImGui::SliderFloat(xorstr_("L CPS"), &features::CPS, 10.0f, 20.0f, "%.1f");
ImGui::Checkbox(xorstr_("Extra Rand"), &features::lExtraRand);
ImGui::NewLine();
// Right
ImGui::Checkbox(xorstr_("Right Toggle"), &features::rCLICKER_TOGGLED); ImGui::SameLine(); if (ImGui::Button(xorstr_("Right Bind"))) { features::right_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::right_key]);
ImGui::SliderFloat(xorstr_("R CPS"), &features::rCPS, 10.0f, 20.0f, "%.1f");
ImGui::Checkbox(xorstr_("Extra Rand "), &features::rExtraRand);
}
if (sidePanel == 1) {
ImGui::Checkbox(xorstr_("Block Hit"), &features::BLOCKHIT); ImGui::SameLine(); ImGui::BulletText(xorstr_("Note: This is only for Left Click"));
ImGui::SliderInt(xorstr_(" "), &features::BLOCK_CHANCE, 1, 25, "%d Chance");
}
if (sidePanel == 2) {
ImGui::Text(xorstr_("NOTHING YET - Configs"));
}
// Settings Tab
if (sidePanel == 3) {
ImGui::ColorEdit4(xorstr_(" "), GUI_Color, ImGuiColorEditFlags_NoBorder | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoPicker);
ImGui::Checkbox(xorstr_("Other Background"), &otherBG); ImGui::SameLine(); ImGui::Checkbox(xorstr_("Rounding"), &frameRounding);
ImGui::Text(xorstr_("Application average %.3f ms/frame (%.1f FPS)"),
1000.0 / double(ImGui::GetIO().Framerate), double(ImGui::GetIO().Framerate));
ImGui::Text(xorstr_("Hide Window: ")); ImGui::SameLine();
if (ImGui::Button(xorstr_("Bind"))) { features::window_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::window_key]);
ImGui::NewLine();
ImGui::Text(xorstr_("Vega - Clicker V2.5\nLGBTQHIV+-123456789 Edition"));
}
ImGui::End();
}
ImGui::Begin(xorstr_("DrawList"), NULL, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs);
ImGui::SetWindowPos({ 0, 0 });
ImGui::SetWindowSize({ 800, 800 });
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DrawList->AddLine({ 107, 0 }, { 107, 400 }, ImGui::GetColorU32(ImVec4{ GUI_Color[0], GUI_Color[1], GUI_Color[2], GUI_Color[3] }), 3);
ImGui::End();
}
// Rendering (dont touch)
ImGui::EndFrame();
g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
D3DCOLOR clear_col_dx;
if (otherBG) clear_col_dx = D3DCOLOR_RGBA((int)(12), (int)(22), (int)(28), (int)(255));
else clear_col_dx = D3DCOLOR_RGBA((int)(27), (int)(22), (int)(22), (int)(255));
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
if (g_pd3dDevice->BeginScene() >= 0)
{
ImGui::Render();
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
g_pd3dDevice->EndScene();
}
HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
// Handle loss of D3D9 device
if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
ResetDevice();
}
clickerThread.detach();
ImGui_ImplDX9_Shutdown();
ImGui_ImplWin32_Shutdown();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
// Helper functions
bool CreateDeviceD3D(HWND hWnd)
{
if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL)
return false;
// Create the D3DDevice
ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
g_d3dpp.Windowed = TRUE;
g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
g_d3dpp.EnableAutoDepthStencil = TRUE;
g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync
//g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate
if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
return false;
return true;
}
void CleanupDeviceD3D()
{
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
if (g_pD3D) { g_pD3D->Release(); g_pD3D = NULL; }
}
void ResetDevice()
{
ImGui_ImplDX9_InvalidateDeviceObjects();
HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
if (hr == D3DERR_INVALIDCALL)
IM_ASSERT(0);
ImGui_ImplDX9_CreateDeviceObjects();
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
{
g_d3dpp.BackBufferWidth = LOWORD(lParam);
g_d3dpp.BackBufferHeight = HIWORD(lParam);
ResetDevice();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
#define OBF_END } catch(std::shared_ptr<obf::base_rvholder>& r) { return *r; } catch (...) {throw;}
| 29.881598 | 263 | 0.532009 | qualk |
d5fa1d60b0d0efac056ab516c51fc4448961e201 | 4,555 | cpp | C++ | A2020/Module12_4Digits/Demo4Digits/src/Affichage4DigitsBase.cpp | monkTrapist/420-W48-SF | d1c2b64dcc3054c054a29040eedf05fbdcbfeece | [
"CC0-1.0"
] | 1 | 2021-01-28T18:36:35.000Z | 2021-01-28T18:36:35.000Z | A2020/Module12_4Digits/Demo4Digits/src/Affichage4DigitsBase.cpp | monkTrapist/420-W48-SF | d1c2b64dcc3054c054a29040eedf05fbdcbfeece | [
"CC0-1.0"
] | 2 | 2020-12-09T19:52:34.000Z | 2022-03-21T12:11:08.000Z | A2020/Module12_4Digits/Demo4Digits/src/Affichage4DigitsBase.cpp | monkTrapist/420-W48-SF | d1c2b64dcc3054c054a29040eedf05fbdcbfeece | [
"CC0-1.0"
] | 11 | 2020-11-11T16:55:57.000Z | 2022-03-28T13:46:57.000Z | #include "Affichage4DigitsBase.h"
#include "OptimiserEntreesSorties.h"
static const byte valeurSegments[] = {
// Segements ABCDEFGP
0b11111100, // 0 '0' AAA
0b01100000, // 1 '1' F B
0b11011010, // 2 '2' F B
0b11110010, // 3 '3' GGG
0b01100110, // 4 '4' E C
0b10110110, // 5 '5' E C
0b10111110, // 6 '6' DDD P
0b11100000, // 7 '7'
0b11111110, // 8 '8'
0b11110110, // 9 '9'
0b11101110, // 10 'A'
0b00111110, // 11 'b'
0b10011100, // 12 'C'
0b01111010, // 13 'd'
0b10011110, // 14 'E'
0b10001110, // 15 'F'
0b00000010, // 16 '-'
0b00000000, // 17 ' '
0b10000000, // 18 '¨' Trop grand
0b00010000, // 19 '_' Trop petit
};
static const int nombreConfigurations = sizeof(valeurSegments);
static const int blanc = 17;
static const int tropGrand = 18;
static const int tropPetit = 19;
static const int moins = 16;
Affichage4DigitsBase::Affichage4DigitsBase(const int &p_pinD1, const int &p_pinD2, const int &p_pinD3, const int &p_pinD4, const bool &p_cathodeCommune)
: m_pinD{p_pinD1, p_pinD2, p_pinD3, p_pinD4}
{
if (p_cathodeCommune)
{
this->m_digitOff = HIGH;
this->m_digitOn = LOW;
this->m_segmentOff = LOW;
this->m_segmentOn = HIGH;
}
else
{
this->m_digitOff = LOW;
this->m_digitOn = HIGH;
this->m_segmentOff = HIGH;
this->m_segmentOn = LOW;
}
for (size_t digitIndex = 0; digitIndex < 4; digitIndex++)
{
pinMode(this->m_pinD[digitIndex], OUTPUT);
}
}
const byte valeurSegmentTropGrand = valeurSegments[tropGrand];
const byte valeurSegmentTropPetit = valeurSegments[tropPetit];
const byte valeurSegmentBlanc = valeurSegments[blanc];
const byte valeurSegmentMoins = valeurSegments[moins];
// Affichage des 4 digits en 4 cycle d'appel et utilisation d'une cache
// Idées cache et afficher digit / digit prises de la très bonne vidéo de Cyrob : https://www.youtube.com/watch?v=CS4t0j1yzH0
void Affichage4DigitsBase::Afficher(const int &p_valeur, const int &p_base) const
{
if (p_valeur != this->m_valeurCache || p_base != this->m_baseCache)
{
this->m_valeurCache = p_valeur;
this->m_baseCache = p_base;
if (p_base == DEC && p_valeur > 9999)
{
this->m_cache[0] = valeurSegmentTropGrand;
this->m_cache[1] = valeurSegmentTropGrand;
this->m_cache[2] = valeurSegmentTropGrand;
this->m_cache[3] = valeurSegmentTropGrand;
}
else if (p_base == DEC && p_valeur < -999)
{
this->m_cache[0] = valeurSegmentTropPetit;
this->m_cache[1] = valeurSegmentTropPetit;
this->m_cache[2] = valeurSegmentTropPetit;
this->m_cache[3] = valeurSegmentTropPetit;
}
else
{
switch (p_base)
{
case HEX:
this->m_cache[0] = valeurSegments[(byte)(p_valeur >> 12 & 0x0F)];
this->m_cache[1] = valeurSegments[(byte)((p_valeur >> 8) & 0x0F)];
this->m_cache[2] = valeurSegments[(byte)((p_valeur >> 4) & 0x0F)];
this->m_cache[3] = valeurSegments[(byte)(p_valeur & 0x0F)];
break;
case DEC: // par défault décimale. Autres bases non gérées.
default:
{
int valeur = p_valeur < 0 ? -p_valeur : p_valeur;
int index = 3;
while (valeur != 0 && index >= 0)
{
this->m_cache[index] = valeurSegments[valeur % 10];
valeur /= 10;
--index;
}
while (index >= 0)
{
this->m_cache[index] = valeurSegmentBlanc;
--index;
}
if (p_valeur < 0)
{
this->m_cache[0] = valeurSegmentMoins;
}
}
break;
}
}
}
}
void Affichage4DigitsBase::Executer() const
{
monDigitalWrite(this->m_pinD[this->m_digitCourant], this->m_digitOff);
++this->m_digitCourant;
#if !OPTIMISE_MODULO
this->m_digitCourant %= 4;
#else
if (this->m_digitCourant > 3)
{
this->m_digitCourant = 0;
}
#endif
this->EnvoyerValeur(this->m_cache[this->m_digitCourant]);
monDigitalWrite(this->m_pinD[this->m_digitCourant], this->m_digitOn);
}
| 31.19863 | 152 | 0.554336 | monkTrapist |
d5fe4c6eca40732deeea391dda8eb4c5e233dea6 | 4,169 | cpp | C++ | java/jcl/src/native/harmony/JniConstants.cpp | webos21/xi | 496d636232183c4cc4ec25ab45f6ee25d5eeaf43 | [
"Apache-2.0"
] | 1 | 2018-09-25T10:56:25.000Z | 2018-09-25T10:56:25.000Z | java/jcl/src/native/harmony/JniConstants.cpp | webos21/xi | 496d636232183c4cc4ec25ab45f6ee25d5eeaf43 | [
"Apache-2.0"
] | 2 | 2021-04-07T00:18:48.000Z | 2021-04-07T00:20:08.000Z | java/jcl/src/native/harmony/JniConstants.cpp | webos21/xi | 496d636232183c4cc4ec25ab45f6ee25d5eeaf43 | [
"Apache-2.0"
] | 1 | 2017-10-26T23:20:32.000Z | 2017-10-26T23:20:32.000Z | /*
* Copyright (C) 2010 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 "JniConstants.h"
// by cmjo
//#include <stdlib.h>
#include "xi/xi_process.h"
// by jshwang
//#define LOGE printf
#if 0
jclass JniConstants::bidiRunClass;
jclass JniConstants::bigDecimalClass;
jclass JniConstants::booleanClass;
jclass JniConstants::byteClass;
jclass JniConstants::byteArrayClass;
jclass JniConstants::charsetICUClass;
jclass JniConstants::constructorClass;
jclass JniConstants::datagramPacketClass;
jclass JniConstants::deflaterClass;
jclass JniConstants::doubleClass;
jclass JniConstants::fieldClass;
jclass JniConstants::fieldPositionIteratorClass;
jclass JniConstants::multicastGroupRequestClass;
jclass JniConstants::inetAddressClass;
jclass JniConstants::inflaterClass;
jclass JniConstants::integerClass;
jclass JniConstants::interfaceAddressClass;
jclass JniConstants::localeDataClass;
jclass JniConstants::longClass;
jclass JniConstants::methodClass;
jclass JniConstants::parsePositionClass;
jclass JniConstants::patternSyntaxExceptionClass;
jclass JniConstants::realToStringClass;
jclass JniConstants::socketClass;
jclass JniConstants::socketImplClass;
jclass JniConstants::stringClass;
//jclass JniConstants::vmRuntimeClass;
static jclass findClass(JNIEnv* env, const char* name) {
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(env->FindClass(name)));
if (result == NULL) {
log_error(XDLOG, "failed to find class '%s'\n", name);
xi_proc_abort();
}
return result;
}
#endif // 0
void JniConstants::init(JNIEnv*) {
#if 0
bidiRunClass = findClass(env, "org/apache/harmony/text/BidiRun");
bigDecimalClass = findClass(env, "java/math/BigDecimal");
booleanClass = findClass(env, "java/lang/Boolean");
byteClass = findClass(env, "java/lang/Byte");
byteArrayClass = findClass(env, "[B");
charsetICUClass = findClass(env, "com/ibm/icu4jni/charset/CharsetICU");
constructorClass = findClass(env, "java/lang/reflect/Constructor");
datagramPacketClass = findClass(env, "java/net/DatagramPacket");
deflaterClass = findClass(env, "java/util/zip/Deflater");
doubleClass = findClass(env, "java/lang/Double");
fieldClass = findClass(env, "java/lang/reflect/Field");
fieldPositionIteratorClass = findClass(env, "com/ibm/icu4jni/text/NativeDecimalFormat$FieldPositionIterator");
inetAddressClass = findClass(env, "java/net/InetAddress");
inflaterClass = findClass(env, "java/util/zip/Inflater");
integerClass = findClass(env, "java/lang/Integer");
interfaceAddressClass = findClass(env, "java/net/InterfaceAddress");
localeDataClass = findClass(env, "com/ibm/icu4jni/util/LocaleData");
longClass = findClass(env, "java/lang/Long");
methodClass = findClass(env, "java/lang/reflect/Method");
multicastGroupRequestClass = findClass(env, "java/net/MulticastGroupRequest");
parsePositionClass = findClass(env, "java/text/ParsePosition");
patternSyntaxExceptionClass = findClass(env, "java/util/regex/PatternSyntaxException");
realToStringClass = findClass(env, "java/lang/RealToString");
socketClass = findClass(env, "java/net/Socket");
socketImplClass = findClass(env, "java/net/SocketImpl");
stringClass = findClass(env, "java/lang/String");
// vmRuntimeClass = findClass(env, "dalvik/system/VMRuntime");
#else
// deflaterClass = findClass(env, "java/util/zip/Deflater");
// inflaterClass = findClass(env, "java/util/zip/Inflater");
// stringClass = findClass(env, "java/lang/String");
// charsetICUClass = findClass(env, "com/ibm/icu4jni/charset/CharsetICU");
#endif
}
| 40.872549 | 114 | 0.753898 | webos21 |
91067fa19469909ffe22bf89389e71dae6d1be7e | 2,372 | hpp | C++ | boost/numeric/itl/krylov/async_executor.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | null | null | null | boost/numeric/itl/krylov/async_executor.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | null | null | null | boost/numeric/itl/krylov/async_executor.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | null | null | null | // Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
// 2008 Dresden University of Technology and the Trustees of Indiana University.
// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.
#ifndef ITL_ASYNC_EXECUTOR_INCLUDE
#define ITL_ASYNC_EXECUTOR_INCLUDE
#include <thread>
#include <boost/numeric/itl/iteration/interruptible_iteration.hpp>
namespace itl {
template <typename Solver>
class async_executor
{
public:
async_executor(const Solver& solver) : my_solver(solver), my_iter(), my_thread() {}
/// Solve linear system approximately as specified by \p iter
template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >
void start_solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const
{
my_iter.set_iter(iter);
// my_thread= std::thread(&Solver::solve, &my_solver, b, x, my_iter);
my_thread= std::thread([this, &x, &b]() { my_solver.solve(x, b, my_iter);});
}
/// Solve linear system approximately as specified by \p iter
template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >
int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const
{
start_solve(x, b, iter);
return wait();
}
/// Perform one iteration on linear system
template < typename HilbertSpaceX, typename HilbertSpaceB >
int solve(HilbertSpaceX& x, const HilbertSpaceB& b) const
{
itl::basic_iteration<double> iter(x, 1, 0, 0);
return solve(x, b, iter);
}
int wait()
{
my_thread.join();
return my_iter.error_code();
}
bool is_finished() const { return !my_thread.joinable(); }
int interrupt() { my_iter.interrupt(); return wait(); }
private:
Solver my_solver;
mutable interruptible_iteration my_iter;
mutable std::thread my_thread;
};
template <typename Solver>
inline async_executor<Solver> make_async_executor(const Solver& solver)
{
return async_executor<Solver>(solver);
}
} // namespace itl
#endif // ITL_ASYNC_EXECUTOR_INCLUDE
| 30.025316 | 94 | 0.677487 | lit-uriy |
5103455a2ad81cf0f3ed55dad96c5de5ed3414f1 | 18,644 | cpp | C++ | Inkpad-develop-framework-project/Inkpad-Core/livarot/ShapeSweepUtils.cpp | manjukiran/MKImageMarkup | be4046e2d5c9a4f6b69d2c6e928af5e70093144d | [
"Apache-2.0"
] | 1 | 2021-06-14T15:35:13.000Z | 2021-06-14T15:35:13.000Z | Inkpad-develop-framework-project/Inkpad-Core/livarot/ShapeSweepUtils.cpp | manjukiran/MKImageMarkup | be4046e2d5c9a4f6b69d2c6e928af5e70093144d | [
"Apache-2.0"
] | null | null | null | Inkpad-develop-framework-project/Inkpad-Core/livarot/ShapeSweepUtils.cpp | manjukiran/MKImageMarkup | be4046e2d5c9a4f6b69d2c6e928af5e70093144d | [
"Apache-2.0"
] | null | null | null | /*
* ShapeSweepUtils.cpp
* nlivarot
*
* Created by fred on Wed Jun 18 2003.
*
*/
#include "Shape.h"
#include "MyMath.h"
SweepEvent::SweepEvent()
{
MakeNew(NULL,NULL,0,0,0,0);
}
SweepEvent::~SweepEvent(void)
{
MakeDelete();
}
void
SweepEvent::MakeNew(SweepTree* iLeft,SweepTree* iRight,float px,float py,float itl,float itr)
{
ind=-1;
posx=px;
posy=py;
tl=itl;
tr=itr;
leftSweep=iLeft;
rightSweep=iRight;
leftSweep->rightEvt=this;
rightSweep->leftEvt=this;
}
void
SweepEvent::MakeDelete(void)
{
if ( leftSweep ) {
if ( leftSweep->src->aretes[leftSweep->bord].st < leftSweep->src->aretes[leftSweep->bord].en ) {
leftSweep->src->pData[leftSweep->src->aretes[leftSweep->bord].en].pending--;
} else {
leftSweep->src->pData[leftSweep->src->aretes[leftSweep->bord].st].pending--;
}
leftSweep->rightEvt=NULL;
}
if ( rightSweep ) {
if ( rightSweep->src->aretes[rightSweep->bord].st < rightSweep->src->aretes[rightSweep->bord].en ) {
rightSweep->src->pData[rightSweep->src->aretes[rightSweep->bord].en].pending--;
} else {
rightSweep->src->pData[rightSweep->src->aretes[rightSweep->bord].st].pending--;
}
rightSweep->leftEvt=NULL;
}
leftSweep=rightSweep=NULL;
}
void SweepEvent::CreateQueue(SweepEventQueue &queue,int size)
{
queue.nbEvt=0;
queue.maxEvt=size;
queue.events=(SweepEvent*)malloc(queue.maxEvt*sizeof(SweepEvent));
queue.inds=(int*)malloc(queue.maxEvt*sizeof(int));
}
void SweepEvent::DestroyQueue(SweepEventQueue &queue)
{
if ( queue.events ) free(queue.events);
if ( queue.inds ) free(queue.inds);
queue.nbEvt=queue.maxEvt=0;
queue.inds=NULL;
queue.events=NULL;
}
SweepEvent* SweepEvent::AddInQueue(SweepTree* iLeft,SweepTree* iRight,float px,float py,float itl,float itr,SweepEventQueue &queue)
{
if ( queue.nbEvt >= queue.maxEvt ) return NULL;
int n=queue.nbEvt++;
queue.events[n].MakeNew(iLeft,iRight,px,py,itl,itr);
if ( iLeft->src->aretes[iLeft->bord].st < iLeft->src->aretes[iLeft->bord].en ) {
iLeft->src->pData[iLeft->src->aretes[iLeft->bord].en].pending++;
} else {
iLeft->src->pData[iLeft->src->aretes[iLeft->bord].st].pending++;
}
if ( iRight->src->aretes[iRight->bord].st < iRight->src->aretes[iRight->bord].en ) {
iRight->src->pData[iRight->src->aretes[iRight->bord].en].pending++;
} else {
iRight->src->pData[iRight->src->aretes[iRight->bord].st].pending++;
}
queue.events[n].ind=n;
queue.inds[n]=n;
int curInd=n;
while ( curInd > 0 ) {
int half=(curInd-1)/2;
int no=queue.inds[half];
if ( py < queue.events[no].posy || ( py == queue.events[no].posy && px < queue.events[no].posx ) ) {
queue.events[n].ind=half;
queue.events[no].ind=curInd;
queue.inds[half]=n;
queue.inds[curInd]=no;
} else {
break;
}
curInd=half;
}
return queue.events+n;
}
void SweepEvent::SupprFromQueue(SweepEventQueue &queue)
{
if ( queue.nbEvt <= 1 ) {
MakeDelete();
queue.nbEvt=0;
return;
}
int n=ind;
int to=queue.inds[n];
MakeDelete();
queue.events[--queue.nbEvt].Relocate(queue,to);
int moveInd=queue.nbEvt;
if ( moveInd == n ) return;
to=queue.inds[moveInd];
queue.events[to].ind=n;
queue.inds[n]=to;
int curInd=n;
float px=queue.events[to].posx;
float py=queue.events[to].posy;
bool didClimb=false;
while ( curInd > 0 ) {
int half=(curInd-1)/2;
int no=queue.inds[half];
if ( py < queue.events[no].posy || ( py == queue.events[no].posy && px < queue.events[no].posx ) ) {
queue.events[to].ind=half;
queue.events[no].ind=curInd;
queue.inds[half]=to;
queue.inds[curInd]=no;
didClimb=true;
} else {
break;
}
curInd=half;
}
if ( didClimb ) return;
while ( 2*curInd+1 < queue.nbEvt ) {
int son1=2*curInd+1;
int son2=son1+1;
int no1=queue.inds[son1];
int no2=queue.inds[son2];
if ( son2 < queue.nbEvt ) {
if ( py > queue.events[no1].posy || ( py == queue.events[no1].posy && px > queue.events[no1].posx ) ) {
if ( queue.events[no2].posy > queue.events[no1].posy || ( queue.events[no2].posy == queue.events[no1].posy && queue.events[no2].posx > queue.events[no1].posx ) ) {
queue.events[to].ind=son1;
queue.events[no1].ind=curInd;
queue.inds[son1]=to;
queue.inds[curInd]=no1;
curInd=son1;
} else {
queue.events[to].ind=son2;
queue.events[no2].ind=curInd;
queue.inds[son2]=to;
queue.inds[curInd]=no2;
curInd=son2;
}
} else {
if ( py > queue.events[no2].posy || ( py == queue.events[no2].posy && px > queue.events[no2].posx ) ) {
queue.events[to].ind=son2;
queue.events[no2].ind=curInd;
queue.inds[son2]=to;
queue.inds[curInd]=no2;
curInd=son2;
} else {
break;
}
}
} else {
if ( py > queue.events[no1].posy || ( py == queue.events[no1].posy && px > queue.events[no1].posx ) ) {
queue.events[to].ind=son1;
queue.events[no1].ind=curInd;
queue.inds[son1]=to;
queue.inds[curInd]=no1;
}
break;
}
}
}
bool SweepEvent::PeekInQueue(SweepTree* &iLeft,SweepTree* &iRight,float &px,float &py,float &itl,float &itr,SweepEventQueue &queue)
{
if ( queue.nbEvt <= 0 ) return false;
iLeft=queue.events[queue.inds[0]].leftSweep;
iRight=queue.events[queue.inds[0]].rightSweep;
px=queue.events[queue.inds[0]].posx;
py=queue.events[queue.inds[0]].posy;
itl=queue.events[queue.inds[0]].tl;
itr=queue.events[queue.inds[0]].tr;
return true;
}
bool SweepEvent::ExtractFromQueue(SweepTree* &iLeft,SweepTree* &iRight,float &px,float &py,float &itl,float &itr,SweepEventQueue &queue)
{
if ( queue.nbEvt <= 0 ) return false;
iLeft=queue.events[queue.inds[0]].leftSweep;
iRight=queue.events[queue.inds[0]].rightSweep;
px=queue.events[queue.inds[0]].posx;
py=queue.events[queue.inds[0]].posy;
itl=queue.events[queue.inds[0]].tl;
itr=queue.events[queue.inds[0]].tr;
queue.events[queue.inds[0]].SupprFromQueue(queue);
return true;
}
void SweepEvent::Relocate(SweepEventQueue &queue,int to)
{
if ( queue.inds[ind] == to ) return; // j'y suis deja
queue.events[to].posx=posx;
queue.events[to].posy=posy;
queue.events[to].tl=tl;
queue.events[to].tr=tr;
queue.events[to].leftSweep=leftSweep;
queue.events[to].rightSweep=rightSweep;
leftSweep->rightEvt=queue.events+to;
rightSweep->leftEvt=queue.events+to;
queue.events[to].ind=ind;
queue.inds[ind]=to;
}
/*
*
*/
SweepTree::SweepTree(void)
{
src=NULL;
bord=-1;
startPoint=-1;
leftEvt=rightEvt=NULL;
sens=true;
// invDirLength=1;
}
SweepTree::~SweepTree(void)
{
MakeDelete();
}
void
SweepTree::MakeNew(Shape* iSrc,int iBord,int iWeight,int iStartPoint)
{
AVLTree::MakeNew();
ConvertTo(iSrc,iBord,iWeight,iStartPoint);
}
void
SweepTree::ConvertTo(Shape* iSrc,int iBord,int iWeight,int iStartPoint)
{
src=iSrc;
bord=iBord;
leftEvt=rightEvt=NULL;
startPoint=iStartPoint;
if ( src->aretes[bord].st < src->aretes[bord].en ) {
if ( iWeight >= 0 ) sens=true; else sens=false;
} else {
if ( iWeight >= 0 ) sens=false; else sens=true;
}
// invDirLength=src->eData[bord].isqlength;
// invDirLength=1/sqrt(src->aretes[bord].dx*src->aretes[bord].dx+src->aretes[bord].dy*src->aretes[bord].dy);
}
void
SweepTree::MakeDelete(void)
{
if ( leftEvt ) {
leftEvt->rightSweep=NULL;
}
if ( rightEvt ) {
rightEvt->leftSweep=NULL;
}
leftEvt=rightEvt=NULL;
AVLTree::MakeDelete();
}
void SweepTree::CreateList(SweepTreeList &list,int size)
{
list.nbTree=0;
list.maxTree=size;
list.trees=(SweepTree*)malloc(list.maxTree*sizeof(SweepTree));
list.racine=NULL;
}
void SweepTree::DestroyList(SweepTreeList &list)
{
if ( list.trees ) free(list.trees);
list.trees=NULL;
list.nbTree=list.maxTree=0;
list.racine=NULL;
}
SweepTree* SweepTree::AddInList(Shape* iSrc,int iBord,int iWeight,int iStartPoint,SweepTreeList &list,Shape* iDst)
{
if ( list.nbTree >= list.maxTree ) return NULL;
int n=list.nbTree++;
list.trees[n].MakeNew(iSrc,iBord,iWeight,iStartPoint);
return list.trees+n;
}
int SweepTree::Find(float px,float py,SweepTree* newOne,SweepTree* &insertL,SweepTree* &insertR,bool sweepSens)
{
vec2d bOrig,bNorm;
bOrig.x=src->pData[src->aretes[bord].st].rx;
bOrig.y=src->pData[src->aretes[bord].st].ry;
bNorm.x=src->eData[bord].rdx;
bNorm.y=src->eData[bord].rdy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
RotCCW(bNorm);
vec2d diff;
diff.x=px-bOrig.x;
diff.y=py-bOrig.y;
double y=0;
// if ( startPoint == newOne->startPoint ) {
// y=0;
// } else {
y=Cross(bNorm,diff);
// }
// y*=invDirLength;
if ( fabs(y) < 0.000001 ) {
// prendre en compte les directions
vec2d nNorm;
nNorm.x=newOne->src->eData[newOne->bord].rdx;
nNorm.y=newOne->src->eData[newOne->bord].rdy;
if ( newOne->src->aretes[newOne->bord].st > newOne->src->aretes[newOne->bord].en ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
RotCCW(nNorm);
if ( sweepSens ) {
y=Dot(bNorm,nNorm);
} else {
y=Dot(nNorm,bNorm);
}
if ( y == 0 ) {
y=Cross(bNorm,nNorm);
if ( y == 0 ) {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
return found_exact;
}
}
}
if ( y < 0 ) {
if ( sonL ) {
return (static_cast <SweepTree*> (sonL))->Find(px,py,newOne,insertL,insertR,sweepSens);
} else {
insertR=this;
insertL=static_cast <SweepTree*> (leftElem);
if ( insertL ) {
return found_between;
} else {
return found_on_left;
}
}
} else {
if ( sonR ) {
return (static_cast <SweepTree*> (sonR))->Find(px,py,newOne,insertL,insertR,sweepSens);
} else {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
if ( insertR ) {
return found_between;
} else {
return found_on_right;
}
}
}
return not_found;
}
int SweepTree::Find(float px,float py,SweepTree* &insertL,SweepTree* &insertR)
{
vec2d bOrig,bNorm;
bOrig.x=src->pData[src->aretes[bord].st].rx;
bOrig.y=src->pData[src->aretes[bord].st].ry;
bNorm.x=src->eData[bord].rdx;
bNorm.y=src->eData[bord].rdy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
RotCCW(bNorm);
vec2d diff;
diff.x=px-bOrig.x;
diff.y=py-bOrig.y;
double y=0;
y=Cross(bNorm,diff);
if ( fabs(y) < 0.000001 ) {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
return found_exact;
}
if ( y < 0 ) {
if ( sonL ) {
return (static_cast <SweepTree*> (sonL))->Find(px,py,insertL,insertR);
} else {
insertR=this;
insertL=static_cast <SweepTree*> (leftElem);
if ( insertL ) {
return found_between;
} else {
return found_on_left;
}
}
} else {
if ( sonR ) {
return (static_cast <SweepTree*> (sonR))->Find(px,py,insertL,insertR);
} else {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
if ( insertR ) {
return found_between;
} else {
return found_on_right;
}
}
}
return not_found;
}
void SweepTree::RemoveEvents(SweepEventQueue &queue)
{
RemoveEvent(queue,true);
RemoveEvent(queue,false);
}
void SweepTree::RemoveEvent(SweepEventQueue &queue,bool onLeft)
{
if ( onLeft ) {
if ( leftEvt ) {
leftEvt->SupprFromQueue(queue);
// leftEvt->MakeDelete(); // fait dans SupprFromQueue
}
leftEvt=NULL;
} else {
if ( rightEvt ) {
rightEvt->SupprFromQueue(queue);
// rightEvt->MakeDelete(); // fait dans SupprFromQueue
}
rightEvt=NULL;
}
}
int SweepTree::Remove(SweepTreeList &list,SweepEventQueue &queue,bool rebalance)
{
RemoveEvents(queue);
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Remove(tempR,rebalance);
list.racine=static_cast <SweepTree*> (tempR);
MakeDelete();
if ( list.nbTree <= 1 ) {
list.nbTree=0;
list.racine=NULL;
} else {
if ( list.racine == list.trees+(list.nbTree-1) ) list.racine=this;
list.trees[--list.nbTree].Relocate(this);
}
return err;
}
int SweepTree::Insert(SweepTreeList &list,SweepEventQueue &queue,Shape* iDst,int iAtPoint,bool rebalance,bool sweepSens)
{
if ( list.racine == NULL ) {
list.racine=this;
return avl_no_err;
}
SweepTree* insertL=NULL;
SweepTree* insertR=NULL;
int insertion=list.racine->Find(iDst->pts[iAtPoint].x,iDst->pts[iAtPoint].y,this,insertL,insertR,sweepSens);
if ( insertion == found_on_left ) {
} else if ( insertion == found_on_right ) {
} else if ( insertion == found_exact ) {
if ( insertR ) insertR->RemoveEvent(queue,true);
if ( insertL ) insertL->RemoveEvent(queue,false);
// insertL->startPoint=startPoint;
} else if ( insertion == found_between ) {
insertR->RemoveEvent(queue,true);
insertL->RemoveEvent(queue,false);
}
// if ( insertL ) cout << insertL->bord; else cout << "-1";
// cout << " < ";
// cout << bord;
// cout << " < ";
// if ( insertR ) cout << insertR->bord; else cout << "-1";
// cout << endl;
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Insert(tempR,insertion,static_cast <AVLTree*> (insertL),static_cast <AVLTree*> (insertR),rebalance);
list.racine=static_cast <SweepTree*> (tempR);
return err;
}
int SweepTree::InsertAt(SweepTreeList &list,SweepEventQueue &queue,Shape* iDst,SweepTree* insNode,int fromPt,bool rebalance,bool sweepSens)
{
if ( list.racine == NULL ) {
list.racine=this;
return avl_no_err;
}
vec2 fromP;
fromP.x=src->pData[fromPt].rx;
fromP.y=src->pData[fromPt].ry;
vec2d nNorm;
nNorm.x=src->aretes[bord].dx;
nNorm.y=src->aretes[bord].dy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
if ( sweepSens == false ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
vec2d bNorm;
bNorm.x=insNode->src->aretes[insNode->bord].dx;
bNorm.y=insNode->src->aretes[insNode->bord].dy;
if ( insNode->src->aretes[insNode->bord].st > insNode->src->aretes[insNode->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
SweepTree* insertL=NULL;
SweepTree* insertR=NULL;
double ang=Dot(bNorm,nNorm);
if ( ang == 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
} else if ( ang > 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
while ( insertL ) {
if ( insertL->src == src ) {
if ( insertL->src->aretes[insertL->bord].st != fromPt && insertL->src->aretes[insertL->bord].en != fromPt ) {
break;
}
} else {
int ils=insertL->src->aretes[insertL->bord].st;
int ile=insertL->src->aretes[insertL->bord].en;
if ( ( insertL->src->pData[ils].rx != fromP.x || insertL->src->pData[ils].ry != fromP.y ) &&
( insertL->src->pData[ile].rx != fromP.x || insertL->src->pData[ile].ry != fromP.y ) ) {
break;
}
}
bNorm.x=insertL->src->aretes[insertL->bord].dx;
bNorm.y=insertL->src->aretes[insertL->bord].dy;
if ( insertL->src->aretes[insertL->bord].st > insertL->src->aretes[insertL->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
ang=Dot(bNorm,nNorm);
if ( ang <= 0 ) {
break;
}
insertR=insertL;
insertL=static_cast <SweepTree*> (insertR->leftElem);
}
} else if ( ang < 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
while ( insertR ) {
if ( insertR->src == src ) {
if ( insertR->src->aretes[insertR->bord].st != fromPt && insertR->src->aretes[insertR->bord].en != fromPt ) {
break;
}
} else {
int ils=insertR->src->aretes[insertR->bord].st;
int ile=insertR->src->aretes[insertR->bord].en;
if ( ( insertR->src->pData[ils].rx != fromP.x || insertR->src->pData[ils].ry != fromP.y ) &&
( insertR->src->pData[ile].rx != fromP.x || insertR->src->pData[ile].ry != fromP.y ) ) {
break;
}
}
bNorm.x=insertR->src->aretes[insertR->bord].dx;
bNorm.y=insertR->src->aretes[insertR->bord].dy;
if ( insertR->src->aretes[insertR->bord].st > insertR->src->aretes[insertR->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
ang=Dot(bNorm,nNorm);
if ( ang > 0 ) {
break;
}
insertL=insertR;
insertR=static_cast <SweepTree*> (insertL->rightElem);
}
}
int insertion=found_between;
if ( insertL == NULL ) insertion=found_on_left;
if ( insertR == NULL ) insertion=found_on_right;
if ( insertion == found_on_left ) {
} else if ( insertion == found_on_right ) {
} else if ( insertion == found_exact ) {
if ( insertR ) insertR->RemoveEvent(queue,true);
if ( insertL ) insertL->RemoveEvent(queue,false);
// insertL->startPoint=startPoint;
} else if ( insertion == found_between ) {
insertR->RemoveEvent(queue,true);
insertL->RemoveEvent(queue,false);
}
// if ( insertL ) cout << insertL->bord; else cout << "-1";
// cout << " < ";
// cout << bord;
// cout << " < ";
// if ( insertR ) cout << insertR->bord; else cout << "-1";
// cout << endl;
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Insert(tempR,insertion,static_cast <AVLTree*> (insertL),static_cast <AVLTree*> (insertR),rebalance);
list.racine=static_cast <SweepTree*> (tempR);
return err;
}
void SweepTree::Relocate(SweepTree* to)
{
if ( this == to ) return;
AVLTree::Relocate(to);
to->src=src;
to->bord=bord;
to->sens=sens;
to->leftEvt=leftEvt;
to->rightEvt=rightEvt;
to->startPoint=startPoint;
if ( src->swsData ) src->swsData[bord].misc=to;
if ( src->swrData ) src->swrData[bord].misc=to;
if ( leftEvt ) leftEvt->rightSweep=to;
if ( rightEvt ) rightEvt->leftSweep=to;
}
void SweepTree::SwapWithRight(SweepTreeList &list,SweepEventQueue &queue)
{
SweepTree* tL=this;
SweepTree* tR=static_cast <SweepTree*> (rightElem);
tL->src->swsData[tL->bord].misc=tR;
tR->src->swsData[tR->bord].misc=tL;
{Shape* swap=tL->src;tL->src=tR->src;tR->src=swap;}
{int swap=tL->bord;tL->bord=tR->bord;tR->bord=swap;}
{int swap=tL->startPoint;tL->startPoint=tR->startPoint;tR->startPoint=swap;}
// {float swap=tL->invDirLength;tL->invDirLength=tR->invDirLength;tR->invDirLength=swap;}
{bool swap=tL->sens;tL->sens=tR->sens;tR->sens=swap;}
}
void SweepTree::Avance(Shape* dstPts,int curPoint,Shape* a,Shape* b)
{
return;
/* if ( curPoint != startPoint ) {
int nb=-1;
if ( sens ) {
// nb=dstPts->AddEdge(startPoint,curPoint);
} else {
// nb=dstPts->AddEdge(curPoint,startPoint);
}
if ( nb >= 0 ) {
dstPts->swsData[nb].misc=(void*)((src==b)?1:0);
int wp=waitingPoint;
dstPts->eData[nb].firstLinkedPoint=waitingPoint;
waitingPoint=-1;
while ( wp >= 0 ) {
dstPts->pData[wp].edgeOnLeft=nb;
wp=dstPts->pData[wp].nextLinkedPoint;
}
}
startPoint=curPoint;
}*/
}
| 27.744048 | 167 | 0.64734 | manjukiran |
5103d51bff7740df534c6bcf7d516e9c5fd1b3b2 | 4,873 | cpp | C++ | main.cpp | nabetani/dcast_time | a54351fb23fcbf4c87b482468b79ba07209a2ad6 | [
"MIT"
] | null | null | null | main.cpp | nabetani/dcast_time | a54351fb23fcbf4c87b482468b79ba07209a2ad6 | [
"MIT"
] | null | null | null | main.cpp | nabetani/dcast_time | a54351fb23fcbf4c87b482468b79ba07209a2ad6 | [
"MIT"
] | null | null | null | #include <array>
#include <chrono>
#include <functional>
#include <iostream>
#include <random>
#include <type_traits>
using namespace std;
using namespace std::chrono;
// define class
#define DERIVE(base, derived, num) \
class derived : public base { \
int derived_##member; \
\
public: \
static inline constexpr int tid = num; \
derived() : derived_##member(0) {} \
int m() const { return derived_##member; } \
int derived##_proc() const { return num; }; \
bool is_a(int t) const override { return t == tid || base::is_a(t); } \
};
class root {
public:
virtual ~root() {}
virtual bool is_a(int t) const { return false; }
};
DERIVE(root, vertebrate, __LINE__)
DERIVE(vertebrate, fish, __LINE__)
DERIVE(fish, amphibian, __LINE__)
DERIVE(fish, shark, __LINE__)
DERIVE(fish, tuna, __LINE__)
DERIVE(amphibian, reptile, __LINE__)
DERIVE(amphibian, newt, __LINE__)
DERIVE(amphibian, frog, __LINE__)
DERIVE(reptile, mammal, __LINE__)
DERIVE(reptile, crocodile, __LINE__)
DERIVE(reptile, snake, __LINE__)
DERIVE(mammal, monkey, __LINE__)
DERIVE(monkey, aye_aye, __LINE__)
DERIVE(monkey, tamarin, __LINE__)
DERIVE(monkey, hominidae, __LINE__)
DERIVE(hominidae, gorilla, __LINE__)
DERIVE(hominidae, human, __LINE__)
DERIVE(mammal, whale, __LINE__)
DERIVE(whale, blue_whale, __LINE__)
DERIVE(whale, narwhal, __LINE__)
DERIVE(whale, sperm_whale, __LINE__)
DERIVE(reptile, bird, __LINE__)
DERIVE(bird, penguin, __LINE__)
DERIVE(penguin, king_penguin, __LINE__)
DERIVE(penguin, magellanic_penguin, __LINE__)
DERIVE(penguin, galapagos_penguin, __LINE__)
DERIVE(bird, sparrow, __LINE__)
constexpr size_t COUNT = 1'000'000;
std::function<root *()> newAnimals[] = {
[]() -> root * { return new shark(); },
[]() -> root * { return new tuna(); },
[]() -> root * { return new newt(); },
[]() -> root * { return new frog(); },
[]() -> root * { return new crocodile(); },
[]() -> root * { return new snake(); },
[]() -> root * { return new aye_aye(); },
[]() -> root * { return new tamarin(); },
[]() -> root * { return new gorilla(); },
[]() -> root * { return new human(); },
[]() -> root * { return new blue_whale(); },
[]() -> root * { return new narwhal(); },
[]() -> root * { return new sperm_whale(); },
[]() -> root * { return new king_penguin(); },
[]() -> root * { return new magellanic_penguin(); },
[]() -> root * { return new galapagos_penguin(); },
[]() -> root * { return new sparrow(); },
};
constexpr size_t newAnimalsCount = sizeof(newAnimals) / sizeof(*newAnimals);
int dynamic_run(std::array<root *, COUNT> const &m) {
int sum = 0;
for (auto const &e : m) {
if (auto p = dynamic_cast<mammal const *>(e)) {
sum += p->mammal_proc();
}
if (auto p = dynamic_cast<bird const *>(e)) {
sum += p->bird_proc();
}
}
return sum;
}
template <typename cast> //
inline cast animal_cast(root *p) {
if (p->is_a(std::remove_pointer<cast>::type::tid)) {
return static_cast<cast>(p);
}
return nullptr;
}
template <typename cast> //
inline cast animal_cast(root const *p) {
if (p->is_a(std::remove_pointer<cast>::type::tid)) {
return static_cast<cast>(p);
}
return nullptr;
}
int static_run(std::array<root *, COUNT> const &m) {
int sum = 0;
for (auto const &e : m) {
if (auto p = animal_cast<mammal const *>(e)) {
sum += p->mammal_proc();
}
if (auto p = animal_cast<bird const *>(e)) {
sum += p->bird_proc();
}
}
return sum;
}
void run(char const *title, decltype(dynamic_run) runner,
std::array<root *, COUNT> const &m, bool production) {
auto start = high_resolution_clock::now();
auto r = runner(m);
auto end = high_resolution_clock::now();
if (production) {
std::cout << title
<< "\n"
" res="
<< r
<< "\n"
" "
<< duration_cast<microseconds>(end - start).count() * 1e-3
<< "ms\n";
}
}
void test(int num) {
std::array<root *, COUNT> m = {0};
std::mt19937_64 rng(num);
std::uniform_int_distribution<size_t> dist(0, newAnimalsCount - 1);
for (auto &e : m) {
e = newAnimals[dist(rng)]();
}
for (int i = 0; i < 3; ++i) {
run("dynamic_cast", dynamic_run, m, 2 <= i);
run("animal_cast", static_run, m, 2 <= i);
}
}
int main(int argc, char const *argv[]) {
test(argc < 2 ? 0 : std::atoi(argv[1]));
}
| 31.237179 | 80 | 0.55038 | nabetani |
51071105c0b31071a09f45a2f9cb28b159477bd2 | 8,457 | cxx | C++ | dev/ese/src/checksum/checksum.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | 1 | 2021-02-02T07:04:07.000Z | 2021-02-02T07:04:07.000Z | dev/ese/src/checksum/checksum.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | dev/ese/src/checksum/checksum.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "checksumstd.hxx"
#ifdef _IA64_
extern "C" {
void __lfetch( INT Level,void const *Address );
#pragma intrinsic( __lfetch )
}
#define MD_LFHINT_NONE 0x00
#define MD_LFHINT_NT1 0x01
#define MD_LFHINT_NT2 0x02
#define MD_LFHINT_NTA 0x03
#endif
typedef ULONG( *PFNCHECKSUMOLDFORMAT )( const unsigned char * const, const ULONG );
ULONG ChecksumSelectOldFormat( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormatSlowly( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormat64Bit( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormatSSE( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormatSSE2( const unsigned char * const pb, const ULONG cb );
static PFNCHECKSUMOLDFORMAT pfnChecksumOldFormat = ChecksumSelectOldFormat;
ULONG ChecksumOldFormat( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormat;
Unused( pfn );
return pfnChecksumOldFormat( pb, cb );
}
typedef XECHECKSUM( *PFNCHECKSUMNEWFORMAT )( const unsigned char * const, const ULONG, const ULONG, BOOL );
XECHECKSUM ChecksumSelectNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
enum ChecksumParityMaskFunc
{
ParityMaskFuncDefault = 0,
ParityMaskFuncPopcnt,
};
XECHECKSUM ChecksumNewFormatSlowly( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
XECHECKSUM ChecksumNewFormat64Bit( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
XECHECKSUM ChecksumNewFormatSSE( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
template <ChecksumParityMaskFunc TParityMaskFunc> XECHECKSUM ChecksumNewFormatSSE2( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue);
XECHECKSUM ChecksumNewFormatAVX( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
PFNCHECKSUMNEWFORMAT pfnChecksumNewFormat = ChecksumSelectNewFormat;
XECHECKSUM ChecksumNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
{
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormat;
Unused( pfn );
return pfnChecksumNewFormat( pb, cb, pgno, fHeaderBlock );
}
ULONG ChecksumSelectOldFormat( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumSelectOldFormat;
#if defined _X86_ && defined _CHPE_X86_ARM64_
pfn = ChecksumOldFormatSlowly;
#else
if( FSSEInstructionsAvailable() )
{
if( FSSE2InstructionsAvailable() )
{
pfn = ChecksumOldFormatSSE2;
}
else
{
pfn = ChecksumOldFormatSSE;
}
}
else if( sizeof( void * ) == sizeof( ULONG ) * 2 )
{
pfn = ChecksumOldFormat64Bit;
}
else
{
pfn = ChecksumOldFormatSlowly;
}
#endif
pfnChecksumOldFormat = pfn;
return (*pfn)( pb, cb );
}
ULONG ChecksumOldFormatSlowly( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormatSlowly;
Unused( pfn );
const ULONG * pdw = (ULONG *)pb;
const INT cDWords = 8;
const INT cbStep = cDWords * sizeof( ULONG );
__int64 cbT = cb;
Assert( 0 == ( cbT % cbStep ) );
ULONG dwChecksum = 0x89abcdef ^ pdw[0];
while ( ( cbT -= cbStep ) >= 0 )
{
dwChecksum ^= pdw[0]
^ pdw[1]
^ pdw[2]
^ pdw[3]
^ pdw[4]
^ pdw[5]
^ pdw[6]
^ pdw[7];
pdw += cDWords;
}
return dwChecksum;
}
ULONG ChecksumOldFormat64Bit( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormat64Bit;
Unused( pfn );
const unsigned __int64* pqw = (unsigned __int64 *)pb;
unsigned __int64 qwChecksum = 0;
const INT cQWords = 4;
const INT cbStep = cQWords * sizeof( unsigned __int64 );
__int64 cbT = cb;
Assert( 0 == ( cbT % cbStep ) );
qwChecksum ^= pqw[0] & 0x00000000FFFFFFFF;
while ( ( cbT -= cbStep ) >= 0 )
{
#ifdef _IA64_
__lfetch( MD_LFHINT_NTA, (unsigned char *)(pqw + 4) );
#endif
qwChecksum ^= pqw[0];
qwChecksum ^= pqw[1];
qwChecksum ^= pqw[2];
qwChecksum ^= pqw[3];
pqw += cQWords;
}
const unsigned __int64 qwUpper = ( qwChecksum >> ( sizeof( ULONG ) * 8 ) );
const unsigned __int64 qwLower = qwChecksum & 0x00000000FFFFFFFF;
qwChecksum = qwUpper ^ qwLower;
const ULONG ulChecksum = static_cast<ULONG>( qwChecksum ) ^ 0x89abcdef;
return ulChecksum;
}
XECHECKSUM ChecksumSelectNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
{
PFNCHECKSUMNEWFORMAT pfn = ChecksumSelectNewFormat;
#if defined _X86_ && defined _CHPE_X86_ARM64_
pfn = ChecksumNewFormatSlowly;
#else
if( FAVXEnabled() && FPopcntAvailable() )
{
pfn = ChecksumNewFormatAVX;
}
else if( FSSEInstructionsAvailable() )
{
if( FSSE2InstructionsAvailable() )
{
if( FPopcntAvailable() )
{
pfn = ChecksumNewFormatSSE2<ParityMaskFuncPopcnt>;
}
else
{
pfn = ChecksumNewFormatSSE2<ParityMaskFuncDefault>;
}
}
else
{
pfn = ChecksumNewFormatSSE;
}
}
else if( sizeof( DWORD_PTR ) == sizeof( ULONG ) * 2 )
{
pfn = ChecksumNewFormat64Bit;
}
else
{
pfn = ChecksumNewFormatSlowly;
}
#endif
pfnChecksumNewFormat = pfn;
return (*pfn)( pb, cb, pgno, fHeaderBlock );
}
ULONG DwECCChecksumFromXEChecksum( const XECHECKSUM checksum )
{
return (ULONG)( checksum >> 32 );
}
ULONG DwXORChecksumFromXEChecksum( const XECHECKSUM checksum )
{
return (ULONG)( checksum & 0xffffffff );
}
INT CbitSet( const ULONG dw )
{
INT cbit = 0;
for( INT ibit = 0; ibit < 32; ++ibit )
{
if( dw & ( 1 << ibit ) )
{
++cbit;
}
}
return cbit;
}
BOOL FECCErrorIsCorrectable( const UINT cb, const XECHECKSUM xeChecksumExpected, const XECHECKSUM xeChecksumActual )
{
Assert( xeChecksumActual != xeChecksumExpected );
const DWORD dwECCChecksumExpected = DwECCChecksumFromXEChecksum( xeChecksumExpected );
const DWORD dwECCChecksumActual = DwECCChecksumFromXEChecksum( xeChecksumActual );
if ( FECCErrorIsCorrectable( cb, dwECCChecksumExpected, dwECCChecksumActual ) )
{
const ULONG dwXor = DwXORChecksumFromXEChecksum( xeChecksumActual ) ^ DwXORChecksumFromXEChecksum( xeChecksumExpected );
if ( 1 == CbitSet( dwXor ) )
{
return fTrue;
}
}
return fFalse;
}
UINT IbitCorrupted( const UINT cb, const XECHECKSUM xeChecksumExpected, const XECHECKSUM xeChecksumActual )
{
Assert( xeChecksumExpected != xeChecksumActual );
Assert( FECCErrorIsCorrectable( cb, xeChecksumExpected, xeChecksumActual ) );
const DWORD dwECCChecksumExpected = DwECCChecksumFromXEChecksum( xeChecksumExpected );
const DWORD dwECCChecksumActual = DwECCChecksumFromXEChecksum( xeChecksumActual );
Assert( dwECCChecksumExpected != dwECCChecksumActual );
return IbitCorrupted( cb, dwECCChecksumExpected, dwECCChecksumActual );
}
BOOL FECCErrorIsCorrectable( const UINT cb, const ULONG dwECCChecksumExpected, const ULONG dwECCChecksumActual )
{
const ULONG dwEcc = dwECCChecksumActual ^ dwECCChecksumExpected;
const ULONG ulMask = ( ( cb << 3 ) - 1 );
const ULONG ulX = ( ( dwEcc >> 16 ) ^ dwEcc ) & ulMask;
return ulMask == ulX;
}
UINT IbitCorrupted( const UINT cb, const ULONG dwECCChecksumExpected, const ULONG dwECCChecksumActual )
{
const ULONG dwEcc = dwECCChecksumActual ^ dwECCChecksumExpected;
if ( dwEcc == 0 )
{
return ulMax;
}
const UINT ibitCorrupted = (UINT)( dwEcc & 0xffff );
const UINT ibCorrupted = ibitCorrupted / 8;
if ( ibCorrupted >= cb )
{
return ulMax;
}
return ibitCorrupted;
}
| 27.368932 | 177 | 0.656261 | augustoproiete-forks |
5107892e5a1d972fb443ea1ce54bf6e01ae87b6c | 3,235 | cc | C++ | Frontend/timer.cc | TongLing916/ICE-BA | b8febd35af821e3bbb5909c66a485b9e234a80fe | [
"Apache-2.0"
] | null | null | null | Frontend/timer.cc | TongLing916/ICE-BA | b8febd35af821e3bbb5909c66a485b9e234a80fe | [
"Apache-2.0"
] | null | null | null | Frontend/timer.cc | TongLing916/ICE-BA | b8febd35af821e3bbb5909c66a485b9e234a80fe | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2017-2018 Baidu Robotic Vision Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "timer.h"
#include <glog/logging.h>
#ifndef __DEVELOPMENT_DEBUG_MODE__
#define __HELPER_TIMER_NO_DEBUG__
#endif
namespace XP {
ScopedMicrosecondTimer::ScopedMicrosecondTimer(const std::string& text_id,
int vlog_level)
: text_id_(text_id),
vlog_level_(vlog_level),
t_start_(std::chrono::steady_clock::now()) {}
ScopedMicrosecondTimer::~ScopedMicrosecondTimer() {
#ifndef __HELPER_TIMER_NO_DEBUG__
VLOG(vlog_level_) << "ScopedTimer " << text_id_ << "=["
<< std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t_start_)
.count()
<< "] microseconds";
#endif
}
ScopedLoopProfilingTimer::ScopedLoopProfilingTimer(const std::string& text_id,
int vlog_level)
: text_id_(text_id),
vlog_level_(vlog_level),
t_start_(std::chrono::steady_clock::now()) {}
ScopedLoopProfilingTimer::~ScopedLoopProfilingTimer() {
using namespace std::chrono;
// print timing info even if in release mode
if (VLOG_IS_ON(vlog_level_)) {
VLOG(vlog_level_)
<< "ScopedLoopProfilingTimer " << text_id_ << " start_end=["
<< duration_cast<microseconds>(t_start_.time_since_epoch()).count()
<< " "
<< duration_cast<microseconds>(steady_clock::now().time_since_epoch())
.count()
<< "]";
}
}
MicrosecondTimer::MicrosecondTimer(const std::string& text_id, int vlog_level)
: has_ended_(false), text_id_(text_id), vlog_level_(vlog_level) {
t_start_ = std::chrono::steady_clock::now();
}
MicrosecondTimer::MicrosecondTimer()
: has_ended_(false), text_id_(""), vlog_level_(99) {
t_start_ = std::chrono::steady_clock::now();
}
int MicrosecondTimer::end() {
CHECK(!has_ended_);
has_ended_ = true;
int micro_sec_passed = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t_start_)
.count();
#ifndef __HELPER_TIMER_NO_DEBUG__
VLOG(vlog_level_) << "Timer " << text_id_ << "=[" << micro_sec_passed
<< "] microseconds";
#endif
return micro_sec_passed;
}
MicrosecondTimer::~MicrosecondTimer() {
if (!has_ended_) {
VLOG(vlog_level_) << "MicrosecondTimer " << text_id_ << " is not used";
}
}
} // namespace XP
| 38.058824 | 79 | 0.619165 | TongLing916 |
5108c7a420e43b5a63cae1c04ef7103795d2fffc | 13,996 | cpp | C++ | geonames/WktGeometry.cpp | fmidev/smartmet-engine-geonames | 4f135e026a55363d6cf9a08cc83c5710074439c1 | [
"MIT"
] | null | null | null | geonames/WktGeometry.cpp | fmidev/smartmet-engine-geonames | 4f135e026a55363d6cf9a08cc83c5710074439c1 | [
"MIT"
] | 1 | 2017-04-25T08:46:12.000Z | 2017-04-25T08:46:12.000Z | geonames/WktGeometry.cpp | fmidev/smartmet-engine-geonames | 4f135e026a55363d6cf9a08cc83c5710074439c1 | [
"MIT"
] | 1 | 2017-09-10T17:40:46.000Z | 2017-09-10T17:40:46.000Z | #include "WktGeometry.h"
#include "Engine.h"
#include <gis/Box.h>
#include <macgyver/Exception.h>
#include <ogr_geometry.h>
namespace SmartMet
{
namespace Engine
{
namespace Geonames
{
namespace
{
// ----------------------------------------------------------------------
/*!
* \brief Get location name from location:radius
*/
// ----------------------------------------------------------------------
std::string get_name_base(const std::string& theName)
{
try
{
std::string place = theName;
// remove radius if exists
if (place.find(':') != std::string::npos)
place = place.substr(0, place.find(':'));
return place;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::unique_ptr<OGRGeometry> get_ogr_geometry(const std::string wktString, double radius /*= 0.0*/)
{
std::unique_ptr<OGRGeometry> ret;
std::string wkt = get_name_base(wktString);
OGRGeometry* geom = Fmi::OGR::createFromWkt(wkt, 4326);
if (geom)
{
if (radius > 0.0)
{
std::unique_ptr<OGRGeometry> poly;
poly.reset(Fmi::OGR::expandGeometry(geom, radius * 1000));
OGRGeometryFactory::destroyGeometry(geom);
geom = poly.release();
}
ret.reset(geom);
}
return ret;
}
std::list<const OGRGeometry*> get_geometry_list(const OGRGeometry* geom)
{
std::list<const OGRGeometry*> ret;
switch (geom->getGeometryType())
{
case wkbMultiPoint:
{
// OGRMultiPoint geometry -> extract OGRPoints
const auto* mpGeom = static_cast<const OGRMultiPoint*>(geom);
int numGeoms = mpGeom->getNumGeometries();
for (int i = 0; i < numGeoms; i++)
ret.push_back(mpGeom->getGeometryRef(i));
}
break;
case wkbMultiLineString:
{
// OGRMultiLineString geometry -> extract OGRLineStrings
const auto* mlsGeom = static_cast<const OGRMultiLineString*>(geom);
int numGeoms = mlsGeom->getNumGeometries();
for (int i = 0; i < numGeoms; i++)
ret.push_back(mlsGeom->getGeometryRef(i));
}
break;
case wkbMultiPolygon:
{
// OGRMultiLineString geometry -> extract OGRLineStrings
const auto* mpolGeom = static_cast<const OGRMultiPolygon*>(geom);
int numGeoms = mpolGeom->getNumGeometries();
for (int i = 0; i < numGeoms; i++)
ret.push_back(mpolGeom->getGeometryRef(i));
}
break;
case wkbPoint:
case wkbLineString:
case wkbPolygon:
ret.push_back(geom);
break;
default:
// no other geometries are supported
break;
}
return ret;
}
NFmiSvgPath get_svg_path(const OGRGeometry& geom)
{
try
{
NFmiSvgPath ret;
// Get SVG-path
Fmi::Box box = Fmi::Box::identity();
std::string svgString = Fmi::OGR::exportToSvg(geom, box, 6);
svgString.insert(0, " \"\n");
svgString.append(" \"\n");
std::stringstream svgStringStream(svgString);
ret.Read(svgStringStream);
return ret;
}
catch (...)
{
throw Fmi::Exception(BCP, "Failed to create NFmiSvgPath from OGRGeometry");
}
}
bool is_multi_geometry(const OGRGeometry& geom)
{
bool ret = false;
switch (geom.getGeometryType())
{
case wkbMultiPoint:
case wkbMultiLineString:
case wkbMultiPolygon:
{
ret = true;
}
break;
default:
break;
}
return ret;
}
} // namespace
// ----------------------------------------------------------------------
/*!
* \brief Initialize the WktGeometry object
*/
// ----------------------------------------------------------------------
void WktGeometry::init(const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
try
{
// Create OGRGeometry
geometryFromWkt(loc->name, loc->radius);
// Get SVG-path
svgPathsFromGeometry();
// Get locations from OGRGeometry; OGRMulti* geometries may contain many locations
locationsFromGeometry(loc, language, geoengine);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Create OGRGeometry from wkt-string
*/
// ----------------------------------------------------------------------
void WktGeometry::geometryFromWkt(const std::string& wktString, double radius)
{
if (wktString.find(" as") != std::string::npos)
itsName = wktString.substr(wktString.find(" as") + 3);
else
{
itsName = wktString;
if (itsName.size() > 60)
{
itsName = wktString.substr(0, 30);
itsName += " ...";
}
}
itsGeom = get_ogr_geometry(wktString, radius).release();
}
// ----------------------------------------------------------------------
/*!
* \brief Create NFmiSvgPath object(s) from OGRGeometry
*/
// ----------------------------------------------------------------------
void WktGeometry::svgPathsFromGeometry()
{
itsSvgPath = get_svg_path(*itsGeom);
if (is_multi_geometry(*itsGeom))
{
std::list<const OGRGeometry*> glist = get_geometry_list(itsGeom);
for (const auto* g : glist)
itsSvgPaths.push_back(get_svg_path(*g));
}
}
// ----------------------------------------------------------------------
/*!
* \brief Create Spine::LocationPtr objects from OGRGeometry
*/
// ----------------------------------------------------------------------
void WktGeometry::locationsFromGeometry(const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
itsLocation = locationFromGeometry(itsGeom, loc, language, geoengine);
if (is_multi_geometry(*itsGeom))
{
std::list<const OGRGeometry*> glist = get_geometry_list(itsGeom);
for (const auto* g : glist)
itsLocations.push_back(locationFromGeometry(g, loc, language, geoengine));
}
}
// ----------------------------------------------------------------------
/*!
* \brief Create Spine::LocationPtr OGRGeometry
*/
// ----------------------------------------------------------------------
Spine::LocationPtr WktGeometry::locationFromGeometry(
const OGRGeometry* geom,
const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
OGREnvelope envelope;
geom->getEnvelope(&envelope);
double top = envelope.MaxY;
double bottom = envelope.MinY;
double left = envelope.MinX;
double right = envelope.MaxX;
double lon = (right + left) / 2.0;
double lat = (top + bottom) / 2.0;
Spine::LocationPtr geoloc = geoengine.lonlatSearch(lon, lat, language);
std::unique_ptr<Spine::Location> tmp(new Spine::Location(geoloc->geoid,
"", // tloc.tag,
geoloc->iso2,
geoloc->municipality,
geoloc->area,
geoloc->feature,
geoloc->country,
geoloc->longitude,
geoloc->latitude,
geoloc->timezone,
geoloc->population,
geoloc->elevation));
tmp->radius = loc->radius;
tmp->type = loc->type;
tmp->name = itsName;
OGRwkbGeometryType type = geom->getGeometryType();
switch (type)
{
case wkbPoint:
{
tmp->type = Spine::Location::CoordinatePoint;
}
break;
case wkbPolygon:
case wkbMultiPolygon:
{
tmp->type = Spine::Location::Area;
}
break;
case wkbLineString:
case wkbMultiLineString:
case wkbMultiPoint:
{
// LINESTRING, MULTILINESTRING and MULTIPOINT are handled in a similar fashion
tmp->type = Spine::Location::Path;
}
break;
default:
break;
};
Spine::LocationPtr ret(tmp.release());
return ret;
}
// ----------------------------------------------------------------------
/*!
* \brief Initialize the WktGeometry object
*/
// ----------------------------------------------------------------------
WktGeometry::WktGeometry(const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
init(loc, language, geoengine);
}
// ----------------------------------------------------------------------
/*!
* \brief Destroy OGRGeometry object
*/
// ----------------------------------------------------------------------
WktGeometry::~WktGeometry()
{
if (itsGeom)
{
OGRGeometryFactory::destroyGeometry(itsGeom);
itsGeom = nullptr;
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get Spine::LocationPtr
*/
// ----------------------------------------------------------------------
Spine::LocationPtr WktGeometry::getLocation() const
{
return itsLocation;
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of Spine::LocationPtr objects
*
* For multipart geometry this returns list of Spine::LocationPtr objects,
* that has been created from geometiry primitives inside multipart geometry.
*
* For geometry primitives this returns empty list.
*/
// ----------------------------------------------------------------------
Spine::LocationList WktGeometry::getLocations() const
{
return itsLocations;
}
// ----------------------------------------------------------------------
/*!
* \brief Get NFmiSvgPath object
*/
// ----------------------------------------------------------------------
NFmiSvgPath WktGeometry::getSvgPath() const
{
return itsSvgPath;
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of NFmiSvgPath objects
*
* For multipart geometry this returns list of NFmiSvgPath objects,
* that has been created from geometiry primitives inside multipart geometry.
*
* For geometry primitives this returns empty list.
*/
// ----------------------------------------------------------------------
std::list<NFmiSvgPath> WktGeometry::getSvgPaths() const
{
return itsSvgPaths;
}
// ----------------------------------------------------------------------
/*!
* \brief Get OGRGeometry object
*/
// ----------------------------------------------------------------------
const OGRGeometry* WktGeometry::getGeometry() const
{
return itsGeom;
}
// ----------------------------------------------------------------------
/*!
* \brief Get name of geometry
*/
// ----------------------------------------------------------------------
const std::string& WktGeometry::getName() const
{
return itsName;
}
// ----------------------------------------------------------------------
/*!
* \brief Adds new geometry into container
*/
// ----------------------------------------------------------------------
void WktGeometries::addWktGeometry(const std::string& id, WktGeometryPtr wktGeometry)
{
itsWktGeometries.insert(std::make_pair(id, wktGeometry));
}
Spine::LocationPtr WktGeometries::getLocation(const std::string& id) const
{
Spine::LocationPtr ret = nullptr;
if (itsWktGeometries.find(id) != itsWktGeometries.end())
{
WktGeometryPtr wktGeom = itsWktGeometries.at(id);
ret = wktGeom->getLocation();
}
return ret;
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of Spine::LocationPtr objects of specified geometry
*/
// ----------------------------------------------------------------------
Spine::LocationList WktGeometries::getLocations(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getLocations();
return Spine::LocationList();
}
// ----------------------------------------------------------------------
/*!
* \brief Get NFmiSvgPath object of specified geometry
*/
// ----------------------------------------------------------------------
NFmiSvgPath WktGeometries::getSvgPath(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getSvgPath();
return NFmiSvgPath();
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of NFmiSvgPath objects of specified geometry
*/
// ----------------------------------------------------------------------
std::list<NFmiSvgPath> WktGeometries::getSvgPaths(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getSvgPaths();
return std::list<NFmiSvgPath>();
}
// ----------------------------------------------------------------------
/*!
* \brief Get OGRGeometry object of specified geometry
*/
// ----------------------------------------------------------------------
const OGRGeometry* WktGeometries::getGeometry(const std::string& id) const
{
const OGRGeometry* ret = nullptr;
if (itsWktGeometries.find(id) != itsWktGeometries.end())
{
WktGeometryPtr wktGeom = itsWktGeometries.at(id);
ret = wktGeom->getGeometry();
}
return ret;
}
// ----------------------------------------------------------------------
/*!
* \brief Get name of specified geometry
*/
// ----------------------------------------------------------------------
std::string WktGeometries::getName(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getName();
return std::string();
}
} // namespace Geonames
} // namespace Engine
} // namespace SmartMet
| 27.229572 | 99 | 0.495284 | fmidev |
510c52aaeb3ff95cdb61f442a869f2d5cc10769a | 1,972 | cpp | C++ | test/environmentTest5.cpp | Preponderous-Software/SDL-Environment | 2d03160330d16da52996a8344ff47fe11cbdfe43 | [
"MIT"
] | null | null | null | test/environmentTest5.cpp | Preponderous-Software/SDL-Environment | 2d03160330d16da52996a8344ff47fe11cbdfe43 | [
"MIT"
] | null | null | null | test/environmentTest5.cpp | Preponderous-Software/SDL-Environment | 2d03160330d16da52996a8344ff47fe11cbdfe43 | [
"MIT"
] | null | null | null | #include "Environment.h"
#include <cstdlib>
// create environment
Environment environment;
int xpos = environment.getW()/2 - 50;
int ypos = environment.getH()/2 - 50;
int xvel = 0;
int yvel = 0;
int xtarget = 0;
int ytarget = 0;
drawRects() {
// render black square
environment.setRenderColor(0x00, 0x00, 0x00, 0xFF);
environment.drawRectangle(xpos, ypos, 100, 100);
// render green square
environment.setRenderColor(0x00, 200, 0x00, 0xFF);
environment.drawRectangle(xtarget - 5, ytarget - 5, 10, 10);
}
int chooseRandomX() {
return rand() % environment.getW();
}
int chooseRandomY() {
return rand() % environment.getH();
}
changeRectVel() {
// if left, go right
if (xpos < xtarget) {
xvel = 1;
}
// if right, go left
if (xpos > xtarget) {
xvel = -1;
}
// if up, go down
if (ypos < ytarget) {
yvel = 1;
}
// if down, go up
if (ypos > ytarget) {
yvel = -1;
}
// if reached, stop
if (xpos == xtarget) {
xvel = 0;
}
if (ypos == ytarget) {
yvel = 0;
}
if (xpos == xtarget && ypos == ytarget) {
xtarget = chooseRandomX();
ytarget = chooseRandomY();
}
}
changeRectPos() {
xpos += xvel;
ypos += yvel;
}
int main(int argc, char* args[]) {
// set title
environment.setTitle("Environment Test 5");
// set width and height of the screen
environment.setScreenWidth(700);
environment.setScreenHeight(700);
// initialize
environment.init();
// load media
environment.loadMedia();
// main loop
while (environment.isRunning()) {
while (environment.pollEvent() != 0) {
if (environment.getEvent()->type == SDL_QUIT) {
environment.setRunning(false);
}
}
// clear environment
environment.setRenderColor(0xFF, 0xFF, 0xFF, 0XFF);
environment.clear();
// draw rectangle
drawRects();
// change velocity
changeRectVel();
// change x and y
changeRectPos();
// present environment
environment.present();
}
// clean up environment
environment.cleanUp();
} | 17 | 61 | 0.639452 | Preponderous-Software |
510fa8b52b24bb8c9fd6df0eb31fdab90e79b353 | 11,216 | cpp | C++ | Code/Engine/Foundation/Threading/Implementation/TaskSystemGroups.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/Engine/Foundation/Threading/Implementation/TaskSystemGroups.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/Engine/Foundation/Threading/Implementation/TaskSystemGroups.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | #include <Foundation/FoundationPCH.h>
#include <Foundation/Logging/Log.h>
#include <Foundation/Profiling/Profiling.h>
#include <Foundation/Threading/Implementation/TaskGroup.h>
#include <Foundation/Threading/Implementation/TaskSystemState.h>
#include <Foundation/Threading/Implementation/TaskWorkerThread.h>
#include <Foundation/Threading/Lock.h>
#include <Foundation/Threading/TaskSystem.h>
ezTaskGroupID ezTaskSystem::CreateTaskGroup(ezTaskPriority::Enum Priority, ezOnTaskGroupFinishedCallback callback)
{
EZ_LOCK(s_TaskSystemMutex);
ezUInt32 i = 0;
// this search could be speed up with a stack of free groups
for (; i < s_State->m_TaskGroups.GetCount(); ++i)
{
if (!s_State->m_TaskGroups[i].m_bInUse)
{
goto foundtaskgroup;
}
}
// no free group found, create a new one
s_State->m_TaskGroups.ExpandAndGetRef();
s_State->m_TaskGroups[i].m_uiTaskGroupIndex = static_cast<ezUInt16>(i);
foundtaskgroup:
s_State->m_TaskGroups[i].Reuse(Priority, callback);
ezTaskGroupID id;
id.m_pTaskGroup = &s_State->m_TaskGroups[i];
id.m_uiGroupCounter = s_State->m_TaskGroups[i].m_uiGroupCounter;
return id;
}
void ezTaskSystem::AddTaskToGroup(ezTaskGroupID groupID, const ezSharedPtr<ezTask>& pTask)
{
EZ_ASSERT_DEBUG(pTask != nullptr, "Cannot add nullptr tasks.");
EZ_ASSERT_DEV(pTask->IsTaskFinished(), "The given task is not finished! Cannot reuse a task before it is done.");
EZ_ASSERT_DEBUG(!pTask->m_sTaskName.IsEmpty(), "Every task should have a name");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
pTask->Reset();
pTask->m_BelongsToGroup = groupID;
groupID.m_pTaskGroup->m_Tasks.PushBack(pTask);
}
void ezTaskSystem::AddTaskGroupDependency(ezTaskGroupID groupID, ezTaskGroupID DependsOn)
{
EZ_ASSERT_DEBUG(DependsOn.IsValid(), "Invalid dependency");
EZ_ASSERT_DEBUG(groupID.m_pTaskGroup != DependsOn.m_pTaskGroup || groupID.m_uiGroupCounter != DependsOn.m_uiGroupCounter, "Group cannot depend on itselfs");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
groupID.m_pTaskGroup->m_DependsOnGroups.PushBack(DependsOn);
}
void ezTaskSystem::AddTaskGroupDependencyBatch(ezArrayPtr<const ezTaskGroupDependency> batch)
{
#if EZ_ENABLED(EZ_COMPILE_FOR_DEBUG)
// lock here once to reduce the overhead of ezTaskGroup::DebugCheckTaskGroup inside AddTaskGroupDependency
EZ_LOCK(s_TaskSystemMutex);
#endif
for (const ezTaskGroupDependency& dep : batch)
{
AddTaskGroupDependency(dep.m_TaskGroup, dep.m_DependsOn);
}
}
void ezTaskSystem::StartTaskGroup(ezTaskGroupID groupID)
{
EZ_ASSERT_DEV(s_ThreadState->m_Workers[ezWorkerThreadType::ShortTasks].GetCount() > 0, "No worker threads started.");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
ezInt32 iActiveDependencies = 0;
{
EZ_LOCK(s_TaskSystemMutex);
ezTaskGroup& tg = *groupID.m_pTaskGroup;
tg.m_bStartedByUser = true;
for (ezUInt32 i = 0; i < tg.m_DependsOnGroups.GetCount(); ++i)
{
if (!IsTaskGroupFinished(tg.m_DependsOnGroups[i]))
{
ezTaskGroup& Dependency = *tg.m_DependsOnGroups[i].m_pTaskGroup;
// add this task group to the list of dependencies, such that when that group finishes, this task group can get woken up
Dependency.m_OthersDependingOnMe.PushBack(groupID);
// count how many other groups need to finish before this task group can be executed
++iActiveDependencies;
}
}
if (iActiveDependencies != 0)
{
// atomic integers are quite slow, so do not use them in the loop, where they are not yet needed
tg.m_iNumActiveDependencies = iActiveDependencies;
}
}
if (iActiveDependencies == 0)
{
ScheduleGroupTasks(groupID.m_pTaskGroup, false);
}
}
void ezTaskSystem::StartTaskGroupBatch(ezArrayPtr<const ezTaskGroupID> batch)
{
EZ_LOCK(s_TaskSystemMutex);
for (const ezTaskGroupID& group : batch)
{
StartTaskGroup(group);
}
}
bool ezTaskSystem::IsTaskGroupFinished(ezTaskGroupID Group)
{
// if the counters differ, the task group has been reused since the GroupID was created, so that group has finished
return (Group.m_pTaskGroup == nullptr) || (Group.m_pTaskGroup->m_uiGroupCounter != Group.m_uiGroupCounter);
}
void ezTaskSystem::ScheduleGroupTasks(ezTaskGroup* pGroup, bool bHighPriority)
{
if (pGroup->m_Tasks.IsEmpty())
{
pGroup->m_iNumRemainingTasks = 1;
// "finish" one task -> will finish the task group and kick off dependent groups
TaskHasFinished(nullptr, pGroup);
return;
}
ezInt32 iRemainingTasks = 0;
// add all the tasks to the task list, so that they will be processed
{
EZ_LOCK(s_TaskSystemMutex);
// store how many tasks from this groups still need to be processed
for (auto pTask : pGroup->m_Tasks)
{
iRemainingTasks += ezMath::Max(1u, pTask->m_uiMultiplicity);
pTask->m_iRemainingRuns = ezMath::Max(1u, pTask->m_uiMultiplicity);
}
pGroup->m_iNumRemainingTasks = iRemainingTasks;
for (ezUInt32 task = 0; task < pGroup->m_Tasks.GetCount(); ++task)
{
auto& pTask = pGroup->m_Tasks[task];
for (ezUInt32 mult = 0; mult < ezMath::Max(1u, pTask->m_uiMultiplicity); ++mult)
{
TaskData td;
td.m_pBelongsToGroup = pGroup;
td.m_pTask = pTask;
td.m_pTask->m_bTaskIsScheduled = true;
td.m_uiInvocation = mult;
if (bHighPriority)
s_State->m_Tasks[pGroup->m_Priority].PushFront(td);
else
s_State->m_Tasks[pGroup->m_Priority].PushBack(td);
}
}
// send the proper thread signal, to make sure one of the correct worker threads is awake
switch (pGroup->m_Priority)
{
case ezTaskPriority::EarlyThisFrame:
case ezTaskPriority::ThisFrame:
case ezTaskPriority::LateThisFrame:
case ezTaskPriority::EarlyNextFrame:
case ezTaskPriority::NextFrame:
case ezTaskPriority::LateNextFrame:
case ezTaskPriority::In2Frames:
case ezTaskPriority::In3Frames:
case ezTaskPriority::In4Frames:
case ezTaskPriority::In5Frames:
case ezTaskPriority::In6Frames:
case ezTaskPriority::In7Frames:
case ezTaskPriority::In8Frames:
case ezTaskPriority::In9Frames:
{
WakeUpThreads(ezWorkerThreadType::ShortTasks, iRemainingTasks);
break;
}
case ezTaskPriority::LongRunning:
case ezTaskPriority::LongRunningHighPriority:
{
WakeUpThreads(ezWorkerThreadType::LongTasks, iRemainingTasks);
break;
}
case ezTaskPriority::FileAccess:
case ezTaskPriority::FileAccessHighPriority:
{
WakeUpThreads(ezWorkerThreadType::FileAccess, iRemainingTasks);
break;
}
case ezTaskPriority::SomeFrameMainThread:
case ezTaskPriority::ThisFrameMainThread:
case ezTaskPriority::ENUM_COUNT:
// nothing to do for these enum values
break;
}
}
}
void ezTaskSystem::DependencyHasFinished(ezTaskGroup* pGroup)
{
// remove one dependency from the group
if (pGroup->m_iNumActiveDependencies.Decrement() == 0)
{
// if there are no remaining dependencies, kick off all tasks in this group
ScheduleGroupTasks(pGroup, true);
}
}
ezResult ezTaskSystem::CancelGroup(ezTaskGroupID Group, ezOnTaskRunning::Enum OnTaskRunning)
{
if (ezTaskSystem::IsTaskGroupFinished(Group))
return EZ_SUCCESS;
EZ_PROFILE_SCOPE("CancelGroup");
EZ_LOCK(s_TaskSystemMutex);
ezResult res = EZ_SUCCESS;
auto TasksCopy = Group.m_pTaskGroup->m_Tasks;
// first cancel ALL the tasks in the group, without waiting for anything
for (ezUInt32 task = 0; task < TasksCopy.GetCount(); ++task)
{
if (CancelTask(TasksCopy[task], ezOnTaskRunning::ReturnWithoutBlocking) == EZ_FAILURE)
{
res = EZ_FAILURE;
}
}
// if all tasks could be removed without problems, we do not need to try it again with blocking
if (OnTaskRunning == ezOnTaskRunning::WaitTillFinished && res == EZ_FAILURE)
{
// now cancel the tasks in the group again, this time wait for those that are already running
for (ezUInt32 task = 0; task < TasksCopy.GetCount(); ++task)
{
CancelTask(TasksCopy[task], ezOnTaskRunning::WaitTillFinished).IgnoreResult();
}
}
return res;
}
void ezTaskSystem::WaitForGroup(ezTaskGroupID Group)
{
EZ_PROFILE_SCOPE("WaitForGroup");
EZ_ASSERT_DEV(tl_TaskWorkerInfo.m_bAllowNestedTasks, "The executing task '{}' is flagged to never wait for other tasks but does so anyway. Remove the flag or remove the wait-dependency.", tl_TaskWorkerInfo.m_szTaskName);
const auto ThreadTaskType = tl_TaskWorkerInfo.m_WorkerType;
const bool bAllowSleep = ThreadTaskType != ezWorkerThreadType::MainThread;
while (!ezTaskSystem::IsTaskGroupFinished(Group))
{
if (!HelpExecutingTasks(Group))
{
if (bAllowSleep)
{
const ezWorkerThreadType::Enum typeToWakeUp = (ThreadTaskType == ezWorkerThreadType::Unknown) ? ezWorkerThreadType::ShortTasks : ThreadTaskType;
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Blocked) == (int)ezTaskWorkerState::Active, "Corrupt worker state");
}
WakeUpThreads(typeToWakeUp, 1);
Group.m_pTaskGroup->WaitForFinish(Group);
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Active) == (int)ezTaskWorkerState::Blocked, "Corrupt worker state");
}
break;
}
else
{
ezThreadUtils::YieldTimeSlice();
}
}
}
}
void ezTaskSystem::WaitForCondition(ezDelegate<bool()> condition)
{
EZ_PROFILE_SCOPE("WaitForCondition");
EZ_ASSERT_DEV(tl_TaskWorkerInfo.m_bAllowNestedTasks, "The executing task '{}' is flagged to never wait for other tasks but does so anyway. Remove the flag or remove the wait-dependency.", tl_TaskWorkerInfo.m_szTaskName);
const auto ThreadTaskType = tl_TaskWorkerInfo.m_WorkerType;
const bool bAllowSleep = ThreadTaskType != ezWorkerThreadType::MainThread;
while (!condition())
{
if (!HelpExecutingTasks(ezTaskGroupID()))
{
if (bAllowSleep)
{
const ezWorkerThreadType::Enum typeToWakeUp = (ThreadTaskType == ezWorkerThreadType::Unknown) ? ezWorkerThreadType::ShortTasks : ThreadTaskType;
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Blocked) == (int)ezTaskWorkerState::Active, "Corrupt worker state");
}
WakeUpThreads(typeToWakeUp, 1);
while (!condition())
{
// TODO: busy loop for now
ezThreadUtils::YieldTimeSlice();
}
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Active) == (int)ezTaskWorkerState::Blocked, "Corrupt worker state");
}
break;
}
else
{
ezThreadUtils::YieldTimeSlice();
}
}
}
}
EZ_STATICLINK_FILE(Foundation, Foundation_Threading_Implementation_TaskSystemGroups);
| 31.069252 | 222 | 0.711751 | Tekh-ops |