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 float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 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 float64 1 77k ⌀ | 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 float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c6e0f7afc9d0a35fffd5410e137c10c3a38b07e | 9,863 | cpp | C++ | src/opencv_ingestor.cpp | open-edge-insights/video-ingestion | 189f50c73df6a2879de278f1232f14f291c8e6cf | [
"MIT"
] | 7 | 2021-05-11T04:28:28.000Z | 2022-03-29T00:39:39.000Z | src/opencv_ingestor.cpp | open-edge-insights/video-ingestion | 189f50c73df6a2879de278f1232f14f291c8e6cf | [
"MIT"
] | 1 | 2022-02-10T03:38:58.000Z | 2022-02-10T03:38:58.000Z | src/opencv_ingestor.cpp | open-edge-insights/video-ingestion | 189f50c73df6a2879de278f1232f14f291c8e6cf | [
"MIT"
] | 6 | 2021-09-19T17:48:37.000Z | 2022-03-22T04:22:48.000Z | // Copyright (c) 2019 Intel Corporation.
//
// 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
* @brief OpenCV Ingestor implementation
*/
#include <string>
#include <vector>
#include <cerrno>
#include <unistd.h>
#include <eii/msgbus/msgbus.h>
#include <eii/utils/logger.h>
#include <eii/utils/json_config.h>
#include "eii/vi/opencv_ingestor.h"
using namespace eii::vi;
using namespace eii::utils;
using namespace eii::udf;
#define PIPELINE "pipeline"
#define LOOP_VIDEO "loop_video"
#define UUID_LENGTH 5
OpenCvIngestor::OpenCvIngestor(config_t* config, FrameQueue* frame_queue, std::string service_name, std::condition_variable& snapshot_cv, EncodeType enc_type, int enc_lvl):
Ingestor(config, frame_queue, service_name, snapshot_cv, enc_type, enc_lvl) {
m_width = 0;
m_height = 0;
m_cap = NULL;
m_encoding = false;
m_loop_video = false;
m_double_frames = false;
m_initialized.store(true);
config_value_t* cvt_double = config_get(config, "double_frames");
if (cvt_double != NULL) {
LOG_DEBUG_0("DOUBLING FRAMES");
if (cvt_double->type != CVT_BOOLEAN) {
config_value_destroy(cvt_double);
LOG_ERROR_0("double_frames must be a boolean");
throw "ERROR";
}
m_double_frames = cvt_double->body.boolean;
config_value_destroy(cvt_double);
}
config_value_t* cvt_pipeline = config->get_config_value(config->cfg, PIPELINE);
LOG_INFO("cvt_pipeline initialized");
if(cvt_pipeline == NULL) {
const char* err = "JSON missing key";
LOG_ERROR("%s \'%s\'", err, PIPELINE);
throw(err);
} else if(cvt_pipeline->type != CVT_STRING) {
config_value_destroy(cvt_pipeline);
const char* err = "JSON value must be a string";
LOG_ERROR("%s for \'%s\'", err, PIPELINE);
throw(err);
}
m_pipeline = std::string(cvt_pipeline->body.string);
LOG_INFO("Pipeline: %s", m_pipeline.c_str());
config_value_destroy(cvt_pipeline);
config_value_t* cvt_loop_video = config->get_config_value(
config->cfg, LOOP_VIDEO);
if(cvt_loop_video != NULL) {
if(cvt_loop_video->type != CVT_BOOLEAN) {
LOG_ERROR_0("Loop video must be a boolean");
config_value_destroy(cvt_loop_video);
}
if(cvt_loop_video->body.boolean) {
m_loop_video = true;
}
config_value_destroy(cvt_loop_video);
}
m_cap = new cv::VideoCapture(m_pipeline);
if(!m_cap->isOpened()) {
LOG_ERROR("Failed to open gstreamer pipeline: %s", m_pipeline.c_str());
}
}
OpenCvIngestor::~OpenCvIngestor() {
LOG_DEBUG_0("OpenCV ingestor destructor");
if(m_cap != NULL) {
m_cap->release();
LOG_DEBUG_0("Cap deleted");
}
}
void free_cv_frame(void* obj) {
cv::Mat* frame = (cv::Mat*) obj;
frame->release();
delete frame;
}
void OpenCvIngestor::run(bool snapshot_mode) {
// indicate that the run() function corresponding to the m_th thread has started
m_running.store(true);
LOG_INFO_0("Ingestor thread running publishing on stream");
Frame* frame = NULL;
int64_t frame_count = 0;
msg_envelope_elem_body_t* elem = NULL;
try {
while (!m_stop.load()) {
this->read(frame);
msg_envelope_t* meta_data = frame->get_meta_data();
// Profiling start
DO_PROFILING(this->m_profile, meta_data, "ts_Ingestor_entry")
// Profiling end
msgbus_ret_t ret;
if(frame_count == INT64_MAX) {
LOG_WARN_0("frame count has reached INT64_MAX, so resetting \
it back to zero");
frame_count = 0;
}
frame_count++;
elem = msgbus_msg_envelope_new_integer(frame_count);
if (elem == NULL) {
delete frame;
const char* err = "Failed to create frame_number element";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(meta_data, "frame_number", elem);
if(ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to put frame_number in meta-data";
LOG_ERROR("%s", err);
throw err;
}
elem = NULL;
LOG_DEBUG("Frame number: %ld", frame_count);
// Profiling start
DO_PROFILING(this->m_profile, meta_data, "ts_filterQ_entry")
// Profiling end
// Set encding type and level
try {
frame->set_encoding(m_enc_type, m_enc_lvl);
} catch(const char *err) {
LOG_ERROR("Exception: %s", err);
} catch(...) {
LOG_ERROR("Exception occurred in set_encoding()");
}
QueueRetCode ret_queue = m_udf_input_queue->push(frame);
if(ret_queue == QueueRetCode::QUEUE_FULL) {
if(m_udf_input_queue->push_wait(frame) != QueueRetCode::SUCCESS) {
LOG_ERROR_0("Failed to enqueue message, "
"message dropped");
}
// Add timestamp which acts as a marker if queue if blocked
DO_PROFILING(this->m_profile, meta_data, m_ingestor_block_key.c_str());
}
frame = NULL;
if(snapshot_mode) {
m_stop.store(true);
m_snapshot_cv.notify_all();
}
}
} catch(const char* err) {
LOG_ERROR("Exception: %s", err);
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
throw err;
} catch(...) {
LOG_ERROR("Exception occured in opencv ingestor run()");
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
throw;
}
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
LOG_INFO_0("Ingestor thread stopped");
if(snapshot_mode)
m_running.store(false);
}
void OpenCvIngestor::read(Frame*& frame) {
cv::Mat* cv_frame = new cv::Mat();
cv::Mat* frame_copy = NULL;
if (m_cap == NULL) {
m_cap = new cv::VideoCapture(m_pipeline);
if(!m_cap->isOpened()) {
LOG_ERROR("Failed to open gstreamer pipeline: %s", m_pipeline.c_str());
}
}
if(!m_cap->read(*cv_frame)) {
if(cv_frame->empty()) {
// cv_frame->empty signifies video has ended
if(m_loop_video == true) {
// Re-opening the video capture
LOG_WARN_0("Video ended. Looping...");
m_cap->release();
delete m_cap;
m_cap = new cv::VideoCapture(m_pipeline);
} else {
const char* err = "Video ended...";
LOG_WARN("%s", err);
// Sleeping indefinitely to avoid restart
while(true) {
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
m_cap->read(*cv_frame);
} else {
// Error due to malformed frame
const char* err = "Failed to read frame from OpenCV video capture";
LOG_ERROR("%s", err);
}
}
LOG_DEBUG_0("Frame read successfully");
frame = new Frame(
(void*) cv_frame, free_cv_frame, (void*) cv_frame->data,
cv_frame->cols, cv_frame->rows, cv_frame->channels());
if (m_double_frames) {
frame_copy = new cv::Mat();
*frame_copy = cv_frame->clone();
frame->add_frame(
(void*) frame_copy, free_cv_frame, (void*) frame_copy->data,
frame_copy->cols, frame_copy->rows, frame_copy->channels(),
EncodeType::NONE, 0);
}
if(m_poll_interval > 0) {
usleep(m_poll_interval * 1000 * 1000);
}
}
void OpenCvIngestor::stop() {
if(m_initialized.load()) {
if(!m_stop.load()) {
m_stop.store(true);
// wait for the ingestor thread function run() to finish its execution.
if(m_th != NULL) {
m_th->join();
}
}
// After its made sure that the Ingestor run() function has been stopped (as in m_th-> join() above), m_stop flag is reset
// so that the ingestor is ready for the next ingestion.
m_running.store(false);
m_stop.store(false);
LOG_INFO_0("Releasing video capture object");
if(m_cap != NULL) {
m_cap->release();
delete m_cap;
m_cap = NULL;
LOG_DEBUG_0("Capture object deleted");
}
}
}
| 33.433898 | 172 | 0.590794 |
cc5ef918995bb2503c2ab1edca88ecdb0e110f70 | 22,520 | cpp | C++ | ing10_DAC/src/dac.cpp | Ging-H/DAC | f97efd32e6e8601990bd1af815a0bd82be99beb7 | [
"MIT"
] | null | null | null | ing10_DAC/src/dac.cpp | Ging-H/DAC | f97efd32e6e8601990bd1af815a0bd82be99beb7 | [
"MIT"
] | null | null | null | ing10_DAC/src/dac.cpp | Ging-H/DAC | f97efd32e6e8601990bd1af815a0bd82be99beb7 | [
"MIT"
] | null | null | null | #include "dac.h"
#include "ui_dac.h"
#include <QStyleFactory>
#include <QDesktopServices>
#include <QUrl>
#include "protocoldialog.h"
/* DAC——WinForm */
DAC::DAC(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::DAC)
{
ui->setupUi(this);
currentPort = new BaseSerialComm();
this->initComboBox_Config();
/* 串口错误信息处理 */
connect(currentPort,SIGNAL(errorOccurred(QSerialPort::SerialPortError)),this, SLOT(slots_errorHandler(QSerialPort::SerialPortError) ));
this->setWindowTitle("硬石电子-DAC模块控制工具 v1.0");
QString styleName;
styleName = loadStyle();
if(styleName != NULL)
this->configStyle(styleName);
this->Master = new MBSerialMaster();
tim = new QTimer();
}
DAC::~DAC()
{
delete ui;
}
/* 初始化了串口设置当中的下拉列表(ComboBox) */
void DAC::initComboBox_Config()
{
/* 更新下拉列表 */
BaseSerialComm::listBaudRate( ui->cbbBaud, 0);
BaseSerialComm::listDataBit ( ui->cbbDataBit, 0);
BaseSerialComm::listVerify ( ui->cbbVerify , 0 );
BaseSerialComm::listStopBit ( ui->cbbStopBit);
BaseSerialComm::listPortNum ( ui->cbbPortNum);
BaseSerialComm::listBaudRate( ui->cbbNewBaud, 0);
BaseSerialComm::listVerify ( ui->cbbNewVerify, 0);
}
/* updata stop bits 槽函数 */
void DAC::on_cbbVerify_currentIndexChanged(int index)
{
QVariant tmpVariant;
switch(index){
case 0:
ui -> cbbStopBit->setCurrentText("2");
break;
default :
ui -> cbbStopBit->setCurrentText("1");
break;
}
if(currentPort->isOpen()){
tmpVariant = ui->cbbStopBit->currentData();// 某些情况不支持1.5停止位
currentPort->setStopBits (tmpVariant.value < BaseSerialComm::StopBits > ());
}
}
/* updata baudRate 槽函数 */
void DAC::on_cbbBaud_currentIndexChanged(int index)
{
Q_UNUSED(index)
if(currentPort->isOpen()){
QVariant tmpVariant;
/* 设置波特率 */
tmpVariant = ui->cbbBaud->currentData(); // 读取控件的当前项的值
currentPort->setBaudRate(tmpVariant.value < BaseSerialComm::BaudRate > () );
}
}
/* 刷新按钮点击 槽函数 */
void DAC::on_btnRefresh_clicked()
{
if( !currentPort->isOpen()){ // 关闭串口才能刷新端口号
ui -> cbbPortNum ->clear();
BaseSerialComm::listPortNum ( ui -> cbbPortNum );
}
}
/* 打开串口 槽函数*/
void DAC::on_btnOpenPort_clicked(bool checked)
{
QString tmp = ui->cbbPortNum->currentText();
tmp = tmp.split(" ").first();// Item的 text 由 <COM1 "描述"> 组成,使用空格作为分隔符取第一段就是端口名
if(checked){
// 当前串口处于关闭状态
currentPort->setPortName( tmp ); // 设置端口号
if( currentPort->open(QIODevice::ReadWrite)){ // 打开串口
currentPort -> setDTRState(false);
currentPort -> setRTSState(false);
/* 配置端口的波特率等参数 */
this->configPort();
this->Master->configMaster(currentPort, ui->txtCurrentAddr->text().toInt() );
ui->btnOpenPort->setText(tr("关闭端口"));
}else{
ui->btnOpenPort->setChecked(false);
}
}
else{
currentPort->close();
ui->btnOpenPort->setText(tr("打开端口"));
}
}
/* 配置端口的波特率\数据位\奇偶校验\停止位 */
void DAC::configPort()
{
QVariant tmpVariant;
/* 设置波特率 */
tmpVariant = ui->cbbBaud->currentData(); // 读取控件的当前项的值
currentPort->setBaudRate(tmpVariant.value < BaseSerialComm::BaudRate > () );
/* 设置数据位 */
tmpVariant = ui->cbbDataBit->currentData();
currentPort->setDataBits( tmpVariant.value <BaseSerialComm::DataBits > () );
/* 设置校验位 */
tmpVariant = ui->cbbVerify->currentData();
currentPort->setParity (tmpVariant.value < BaseSerialComm::Parity > () );
/* 设置停止位 */
tmpVariant = ui->cbbStopBit->currentData();// 某些情况不支持1.5停止位
if(currentPort->setStopBits (tmpVariant.value < BaseSerialComm::StopBits > () ) == false ){
ui -> cbbStopBit->clear();
BaseSerialComm::listStopBit ( ui -> cbbStopBit );
QMessageBox::information(NULL, tr("不支持的设置"), tr("该串口设备不支持当前停止位设置,已修改为默认的设置"), 0, 0);
}
}
/* 串口错误信息处理 */
void DAC::slots_errorHandler(QSerialPort::SerialPortError error)
{
switch(error){
case QSerialPort::DeviceNotFoundError:QMessageBox::information(NULL, tr("未找到设备"), tr("检查设备是否已经连接,或者是否正常供电"), 0, 0);
break;
case QSerialPort::OpenError:
case QSerialPort::PermissionError:QMessageBox::information(NULL, tr("打开失败"), tr("检查设备是否已被其他软件占用"), 0, 0);
break;
default:
break;
}
}
/* 读设备信息 */
void DAC::on_btnDeviceMsg_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
ui->statusBar->showMessage(tr("读取设备ID和控制模式"));
this->readAll();
}
void DAC::readAll()
{
ui->statusBar->clearMessage();
/* 连续读10个寄存器 */
QByteArray txbuf;
QByteArray rxbuf;
if(Master->readHoldingRegisters(RegDeviceID, 10, txbuf, rxbuf) == MBSerialMaster::ErrNone){
QByteArray deviceID = rxbuf.mid(3,2).toHex().toUpper();// 设备ID:MD+0x1040
deviceID.prepend("MD");
ui->lblDeviceID->setText(deviceID);
quint16 deviceAddress = (rxbuf.at(5)<<8) | rxbuf.at(6); // 通信参数1,从地址
ui->txtNewAddr->setText(tr("%01").arg(deviceAddress)); // 显示从机地址
// quint16 deviceDataWidth = (rxbuf.at(7)<<8) | rxbuf.at(8); // 通信参数2,数据长度,停止位
quint16 deviceVerify = (rxbuf.at(9)<<8) | rxbuf.at(10); // 通信参数3,校验位
ui->cbbNewVerify->setCurrentIndex(deviceVerify);
quint16 deviceBaud = (rxbuf.at(11)<<8) | rxbuf.at(12); // 通信参数4,波特率
ui->cbbNewBaud->setCurrentIndex(deviceBaud);
quint16 deviceSys = (rxbuf.at(13)<<8) | rxbuf.at(14); // 系统寄存器,控制模式
if( 0 != deviceSys ){
ui->lblCtrlMode->setText("PWM");
}else{
ui->lblCtrlMode->setText("Modbus");
}
quint16 deviceCHAOutput = ((quint8)(rxbuf.at(15))<<8) | (quint8)rxbuf.at(16); // 通道A输出电压值
double Output = (double)deviceCHAOutput/(double)1000;
ui->spbVoltChA->setValue(Output);
quint16 deviceCHBOutput = ((quint8)rxbuf.at(17)<<8) | (quint8)rxbuf.at(18); // 通道A输出电压值
Output = (double)deviceCHBOutput/(double)1000;
ui->spbVoltChB->setValue(Output);
quint16 deviceCHACalibration = ((quint8)rxbuf.at(19)<<8) | (quint8)rxbuf.at(20); // 通道A输出校准比例
Output = (double)deviceCHACalibration /(double)10000;
ui->spbVoltCaliA->setValue(Output);
quint16 deviceCHBCalibration = ((quint8)rxbuf.at(21)<<8) | (quint8)rxbuf.at(22); // 通道B输出校准比例
Output = (double)deviceCHBCalibration /(double)10000;
ui->spbVoltCaliB->setValue(Output);
}
ui->txtTx->setText( txbuf.toHex(' ').toUpper());
ui->txtRx->setText( rxbuf.toHex(' ').toUpper());
ui->statusBar->showMessage(tr("成功读取所有数据"));
}
/* 读取设备ID */
void DAC::readDeviceID()
{
QByteArray txbuf;
QByteArray rxbuf;
ui->statusBar->clearMessage();
if(Master->readHoldingRegisters(RegDeviceID, 1, txbuf, rxbuf) == MBSerialMaster::ErrNone){
QByteArray tmp = rxbuf.mid(3,2).toHex().toUpper();
tmp.prepend("MD");
ui->lblDeviceID->setText(tmp);
}else{
ui->statusBar->showMessage(tr("读取ID失败"));
}
ui->txtTx->setText( txbuf.toHex(' ').toUpper());
ui->txtRx->setText( rxbuf.toHex(' ').toUpper());
}
/* 读取控制模式 */
void DAC::readCtrlMode()
{
QByteArray txbuf;
QByteArray rxbuf;
ui->statusBar->clearMessage();
if(Master->readHoldingRegisters(RegSys, 1, txbuf, rxbuf) == MBSerialMaster::ErrNone){
if( 0 != rxbuf.at(4) ){
ui->lblCtrlMode->setText("PWM");
}else{
ui->lblCtrlMode->setText("Modbus");
}
ui->statusBar->showMessage(tr("读取设备所有寄存器值"));
}else{
ui->statusBar->showMessage(tr("读取控制模式失败"));
}
ui->txtTx->setText( txbuf.toHex(' ').toUpper());
ui->txtRx->setText( rxbuf.toHex(' ').toUpper());
}
/* 修改电压值 */
void DAC::writeOutputVolt(quint16 CHx, quint16 Volt)
{
QByteArray txbuf;
QByteArray rxbuf;
ui->statusBar->clearMessage();
if(Master->writeHoldingRegister(CHx, Volt, txbuf, rxbuf) == MBSerialMaster::ErrNone){
ui->statusBar->showMessage(tr("成功写入"));
}else{
ui->statusBar->showMessage(tr("配置通道输出电压失败"));
}
ui->txtTx->setText( txbuf.toHex(' ').toUpper());
ui->txtRx->setText( rxbuf.toHex(' ').toUpper());
}
/* 修改A通道输出电压值 */
void DAC::on_btnOutA_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
quint16 volt = (ui->spbVoltChA->value()*1000);
this->writeOutputVolt(RegOutputA, volt);
}
/* 修改B通道输出电压值 */
void DAC::on_btnOutB_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
quint16 volt = (ui->spbVoltChB->value()*1000);
this->writeOutputVolt(RegOutputB, volt);
}
/* 修改所有通道输出电压值 */
void DAC::on_btnOutAll_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
emit ui->btnOutA->click();
emit ui->btnOutB->click();
}
/* 修改比例值 */
void DAC::writeCalibrationRate(quint16 CHx, quint16 Rate)
{
QByteArray txbuf;
QByteArray rxbuf;
ui->statusBar->clearMessage();
if(Master->writeHoldingRegister(CHx, Rate, txbuf, rxbuf) == MBSerialMaster::ErrNone){
ui->statusBar->showMessage(tr("成功写入"));
}else{
ui->statusBar->showMessage(tr("配置通道校准比例值失败"));
}
ui->txtTx->setText( txbuf.toHex(' ').toUpper());
ui->txtRx->setText( rxbuf.toHex(' ').toUpper());
}
/* 修改A通道比例值 */
void DAC::on_btnCaliA_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
quint16 Rate = (ui->spbVoltCaliA->value()*10000);
writeCalibrationRate(RegCalibrationA, Rate);
}
/* 修改B通道比例值 */
void DAC::on_btnCaliB_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
quint16 Rate = (ui->spbVoltCaliB->value()*10000);
writeCalibrationRate(RegCalibrationB, Rate);
}
/* 修改所有比例值 */
void DAC::on_btnCaliAll_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
emit ui->btnCaliA->click();
emit ui->btnCaliB->click();
}
/* 修改从机地址 */
bool DAC::modifyDeviceAddress(quint16 newAddress)
{
QByteArray txbuf;
QByteArray rxbuf;
bool ok = true;
ui->statusBar->clearMessage();
if(Master->writeHoldingRegister(RegCommAddress, newAddress, txbuf, rxbuf) == MBSerialMaster::ErrNone){
ui->statusBar->showMessage(tr("成功更新从机地址,设备重启之后生效"));
ok = true;
}else{
ui->statusBar->showMessage(tr("配置通道输出电压失败"));
ok = false;
}
ui->txtTx->setText( txbuf.toHex(' ').toUpper());
ui->txtRx->setText( rxbuf.toHex(' ').toUpper());
return ok;
}
/* 修改通信参数 */
void DAC::on_btnConfig_clicked()
{
if(!currentPort->isOpen()){
ui->statusBar->showMessage(tr("未打开串口"));
return;
}
quint16 newAddress = ui->txtNewAddr->text().toInt();
if( 100 < newAddress )
{
ui->statusBar->showMessage(tr("从机地址范围是1~100,设置通信参数失败"));
return;
}
if(this->modifyDeviceAddress(newAddress) == false){
ui->statusBar->showMessage(tr("设置通信参数失败,通信错误"));
return;
}
QByteArray txbuf;
QByteArray rxbuf;
QByteArray data;
data[0] = 0;
data[1] = ui->cbbNewVerify->currentIndex();
data[2] = 0;
data[3] = ui->cbbNewBaud->currentIndex();
ui->statusBar->clearMessage();
if(Master->writeHoldingRegister(RegCommVerify,data,txbuf,rxbuf) == MBSerialMaster::ErrNone){
ui->statusBar->showMessage(tr("成功写入通信参数,重启DAC模块之后生效"));
}else{
ui->statusBar->showMessage(tr("配置通信参数失败,但是从机地址已经更新")); // 从机地址更新成功才能配置通信参数
}
ui->txtTx->setText( txbuf.toHex(' ').toUpper());
ui->txtRx->setText( rxbuf.toHex(' ').toUpper());
}
/* 实时更新从机地址 */
void DAC::on_txtCurrentAddr_editingFinished()
{
if(currentPort->isOpen())
Master->setDeviceAddr(ui->txtCurrentAddr->text().toInt());
}
/* 保存文件 */
void DAC::on_actionSave_triggered()
{
QString filePath = QFileDialog::getSaveFileName(this,"Save FIle", qApp->applicationDirPath(), "Xml(*.xml)") ;
if(NULL != filePath ){
QFile *file = new QFile(filePath);
if(file->open(QIODevice::WriteOnly | QIODevice::WriteOnly)){
QXmlStreamWriter xml(file);
xml.setAutoFormatting(true);
xml.writeStartDocument(); //
xml.writeStartElement("DAC");
xml.writeStartElement("Communication");
xml.writeTextElement("Address",ui->txtCurrentAddr->text());// 从机地址
xml.writeTextElement("Baudrate",tr("%1").arg(ui->cbbBaud->currentIndex()));// 波特率
xml.writeTextElement("Verify",tr("%1").arg(ui->cbbVerify->currentIndex()));// 校验位
xml.writeEndElement();
xml.writeStartElement("New");
xml.writeTextElement("Address",ui->txtNewAddr->text());// 从机地址
xml.writeTextElement("Baudrate",tr("%1").arg(ui->cbbNewBaud->currentIndex()));// 波特率
xml.writeTextElement("Verify",tr("%1").arg(ui->cbbNewVerify->currentIndex()));// 校验位
xml.writeEndElement();
xml.writeStartElement("Voltage");
xml.writeTextElement("CHA",tr("%1").arg(ui->spbVoltChA->value()));
xml.writeTextElement("CHB",tr("%1").arg(ui->spbVoltChB->value()));
xml.writeEndElement();
xml.writeStartElement("Calibration");
xml.writeTextElement("CHA",tr("%1").arg(ui->spbVoltCaliA->value()));
xml.writeTextElement("CHB",tr("%1").arg(ui->spbVoltCaliB->value()));
xml.writeEndElement();
xml.writeEndElement();
xml.writeEndDocument();
file->close();
}
delete file;
}
}
/* 打开文件 */
void DAC::on_actionOpen_triggered()
{
QString filePath = QFileDialog::getOpenFileName(this,"OpenFIle", qApp->applicationDirPath(), "Xml(*.xml)") ;
if(NULL != filePath ){
QFile *file = new QFile(filePath);
if(file->open(QIODevice::ReadOnly | QIODevice::ReadOnly)){
QXmlStreamReader xml(file);
quint32 currentElement = 0;
while(!xml.atEnd()){
xml.readNextStartElement();
QString name = xml.name().toString();
if(name.contains("Communication")){
currentElement = 1; // 第一个元素
}else if(name.contains("New")){
currentElement = 2; // 第二个元素
}
else if(name.contains("Voltage")){
currentElement = 3; // 第三个元素
}else if(name.contains("Calibration")){
currentElement = 4; // 第四个元素
}
switch(currentElement){
case 1:
if(name.contains("Address")){
ui->txtCurrentAddr->setText( xml.readElementText() );
}else if(name.contains("Baudrate")){
ui->cbbBaud->setCurrentIndex(xml.readElementText().toInt());
}else if(name.contains("Verify")){
ui->cbbVerify->setCurrentIndex(xml.readElementText().toInt());
}
break;
case 2:
if(name.contains("Address")){
ui->txtNewAddr->setText( xml.readElementText() );
}else if(name.contains("Baudrate")){
ui->cbbNewBaud->setCurrentIndex(xml.readElementText().toInt());
}else if(name.contains("Verify")){
ui->cbbNewVerify->setCurrentIndex(xml.readElementText().toInt());
}
break;
case 3:
if(name.contains("CHA")){
ui->spbVoltChA->setValue( xml.readElementText().toDouble() );
}else if(name.contains("CHB")){
ui->spbVoltChB->setValue( xml.readElementText().toDouble() );
}
break;
case 4:
if(name.contains("CHA")){
ui->spbVoltCaliA->setValue( xml.readElementText().toDouble() );
}else if(name.contains("CHB")){
ui->spbVoltCaliB->setValue( xml.readElementText().toDouble() );
}
break;
}
}
file->close();
}
}
}
/* 打开说明文档 */
void DAC::on_actionHelp_triggered()
{
QString path = QDir::currentPath();
path += "/helpFile.pdf";
ui->statusBar->showMessage(tr("打开使用说明文件"));
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}
/* 应用皮肤Fusion */
void DAC::on_actionFusion_triggered()
{
QString styleName =ui->actionFusion->text();
this->configStyle(styleName);
this->saveStyle(styleName);
}
/* 应用皮肤Windows */
void DAC::on_actionWindows_triggered()
{
QString styleName =ui->actionWindows->text();
this->configStyle(styleName);
this->saveStyle(styleName);
}
/* 皮肤WindowsXP */
void DAC::on_actionWindoeXP_triggered()
{
QString styleName =ui->actionWindoeXP->text();
this->configStyle(styleName);
this->saveStyle(styleName);
}
/* 皮肤WindowsVista */
void DAC::on_actionWindowVista_triggered()
{
QString styleName =ui->actionWindowVista->text();
this->configStyle(styleName);
this->saveStyle(styleName);
}
/* 皮肤Dark */
void DAC::on_actionDark_triggered()
{
QString styleName =ui->actionDark->text();
this->configStyle(styleName);
this->saveStyle(styleName);
}
/* 皮肤BlackOrange */
void DAC::on_actionBlackO_triggered()
{
QString styleName =ui->actionBlackO->text();
this->configStyle(styleName);
this->saveStyle(styleName);
}
// 设置皮肤样式
//styleName = {1.Fusion, 2.Windows,...}
void DAC::configStyle(QString styleName)
{
qint32 index = styleName.section('.',0,0).toInt();
QString style = styleName.section('.',1,1);
switch(index){
case 1:
case 2:
case 3:
case 4:
qApp->setStyleSheet(" ");
QApplication::setStyle(QStyleFactory::create(style));//Qt自带皮肤风格 可选 Windows,WindowsXP,WindowsVista,Fusion
return;
break;
default:
QFile file(QString(":/theme/%1.css").arg(style)); //两种自定义的皮肤风格,dark和blackOrange
if(file.exists() ){
qApp->setStyleSheet(" ");
file.open(QFile::ReadOnly | QFile::Text);
QTextStream ts(&file);
qApp->setStyleSheet(ts.readAll());
file.close();
}
break;
}
}
/* 保存为.ini文件 */
void DAC::saveStyle(QString styleName)
{
/* 读取文件名字 */
QSettings settings("Style.ini", QSettings::IniFormat);
settings.beginGroup("Skins");
settings.setValue("Style", styleName);
settings.endGroup();
}
/* 加载.ini文件 */
QString DAC::loadStyle()
{
QSettings settings("Style.ini", QSettings::IniFormat);
settings.beginGroup("Skins");
QString styleName = settings.value("Style").toString();
return styleName;
}
/* 显示寄存器列表 */
void DAC::on_actionRegList_triggered()
{
ui->statusBar->showMessage(tr("显示寄存器列表"));
pDialog = new protocolDialog();
pDialog->setAttribute(Qt::WA_DeleteOnClose); // 关闭的时候delete
pDialog->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMinMaxButtonsHint);// 自定义按钮
pDialog->setWindowTitle("DAC模块寄存器列表");
pDialog->show();
}
/* 打开Modbus协议文档 */
void DAC::on_actionModbus_triggered()
{
QString path = QDir::currentPath();
path += "/Modbus.pdf";
ui->statusBar->showMessage(tr("Modbus协议"));
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}
/**
* @brief DAC::slots_readVolt 定时器处理函数,读取电压值
*/
void DAC::slots_readVolt()
{
if(currentPort->isBusy()){
return;
}else{
if(currentPort->isOpen() ){
QByteArray txbuf;
QByteArray rxbuf;
if(Master->readHoldingRegisters(RegOutputA, 4, txbuf, rxbuf) == MBSerialMaster::ErrNone){
quint16 deviceCHAOutput = ((quint8)(rxbuf.at(3))<<8) | (quint8)rxbuf.at(4); // 通道A输出电压值
double Output = (double)deviceCHAOutput/(double)1000;
ui->spbVoltChA->setValue(Output);
quint16 deviceCHBOutput = ((quint8)rxbuf.at(5)<<8) | (quint8)rxbuf.at(6); // 通道A输出电压值
Output = (double)deviceCHBOutput/(double)1000;
ui->spbVoltChB->setValue(Output);
quint16 deviceCHACalibration = ((quint8)rxbuf.at(7)<<8) | (quint8)rxbuf.at(8); // 通道A输出校准比例
Output = (double)deviceCHACalibration /(double)10000;
ui->spbVoltCaliA->setValue(Output);
quint16 deviceCHBCalibration = ((quint8)rxbuf.at(9)<<8) | (quint8)rxbuf.at(10); // 通道B输出校准比例
Output = (double)deviceCHBCalibration /(double)10000;
ui->spbVoltCaliB->setValue(Output);
}
if(ui->ckbReadVolt->isChecked() && (currentPort->isOpen()) ){
quint32 time = this->time;
tim->singleShot(time ,this, SLOT(slots_readVolt()));
}
}
}
}
/**
* @brief DAC::on_ckbReadVolt_clicked 读取电压值
* @param checked checkedBox状态
*/
void DAC::on_ckbReadVolt_clicked(bool checked)
{
if(checked){
if(!currentPort->isOpen()){
QMessageBox::information(this,"未打开串口","未打开串口");
ui->ckbReadVolt->setChecked(false);
return ;
}
this->time = ui->spbTime->value();
quint32 time = this->time;
tim->singleShot( time, this, SLOT(slots_readVolt()));
}
}
| 33.215339 | 141 | 0.575044 |
cc6033dfeeb05bcadef587cf2cd59cd5542fc7f6 | 117,939 | cpp | C++ | Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 1 | 2022-01-31T06:24:24.000Z | 2022-01-31T06:24:24.000Z | Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-04-11T15:50:42.000Z | 2021-06-05T08:23:04.000Z | Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-01-08T00:55:18.000Z | 2022-01-31T06:24:18.000Z | /****************************************************************************
* ==> PSS_ProcedureSymbolBP -----------------------------------------------*
****************************************************************************
* Description : Provides a procedure symbol for banking process *
* Developer : Processsoft *
****************************************************************************/
#include "stdafx.h"
#include "PSS_ProcedureSymbolBP.h"
// processsoft
#include "zBaseLib\PSS_Tokenizer.h"
#include "zBaseLib\PSS_Global.h"
#include "zBaseLib\PSS_ToolbarObserverMsg.h"
#include "zBaseLib\PSS_MsgBox.h"
#include "zBaseLib\PSS_DrawFunctions.h"
#include "zBaseSym\zBaseSymRes.h"
#include "zModel\PSS_ModelGlobal.h"
#include "zModel\PSS_UserGroupEntity.h"
#include "zModel\PSS_ProcessGraphModelDoc.h"
#include "zModel\PSS_SelectUserGroupDlg.h"
#include "zModel\PSS_ODSymbolManipulator.h"
#define _ZMODELEXPORT
#include "zModel\PSS_BasicProperties.h"
#undef _ZMODELEXPORT
#include "zProperty\PSS_PropertyAttributes.h"
#include "zProperty\PSS_PropertyObserverMsg.h"
#include "PSS_DeliverableLinkSymbolBP.h"
#include "PSS_RuleListPropertiesBP.h"
#include "PSS_TaskListPropertiesBP.h"
#include "PSS_DecisionListPropertiesBP.h"
#include "PSS_CostPropertiesProcedureBP_Beta1.h"
#include "PSS_UnitPropertiesBP_Beta1.h"
#include "PSS_CombinationPropertiesBP.h"
#include "PSS_SimPropertiesProcedureBP.h"
#include "PSS_AddRemoveCombinationDeliverableDlg.h"
#include "PSS_SelectMasterDeliverableDlg.h"
#include "PSS_ProcessGraphModelControllerBP.h"
#include "PSS_RiskOptionsDlg.h"
// resources
#include "zModelBPRes.h"
#include "PSS_ModelResIDs.h"
#include "zModel\zModelRes.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
//---------------------------------------------------------------------------
// Global constants
//---------------------------------------------------------------------------
const std::size_t g_MaxRuleListSize = 20;
const std::size_t g_MaxTaskListSize = 20;
const std::size_t g_MaxDecisionListSize = 20;
const std::size_t g_MaxCombinationListSize = 20;
const std::size_t g_MaxRulesSize = 20;
const std::size_t g_MaxRisksSize = 20;
//---------------------------------------------------------------------------
// Static variables
//---------------------------------------------------------------------------
static CMenu g_CombinationMenu;
static CMenu g_RulesMenu;
static CMenu g_RiskMenu;
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_ProcedureSymbolBP, PSS_Symbol, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_ProcedureSymbolBP
//---------------------------------------------------------------------------
PSS_ProcedureSymbolBP::PSS_ProcedureSymbolBP(const CString& name) :
PSS_Symbol(),
m_Combinations(this)
{
ShowAttributeArea(true);
PSS_Symbol::SetSymbolName(name);
CreateSymbolProperties();
}
//---------------------------------------------------------------------------
PSS_ProcedureSymbolBP::PSS_ProcedureSymbolBP(const PSS_ProcedureSymbolBP& other)
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_ProcedureSymbolBP::~PSS_ProcedureSymbolBP()
{}
//---------------------------------------------------------------------------
PSS_ProcedureSymbolBP& PSS_ProcedureSymbolBP::operator = (const PSS_ProcedureSymbolBP& other)
{
PSS_Symbol::operator = ((const PSS_Symbol&)other);
m_Combinations = other.m_Combinations;
m_Rules = other.m_Rules;
m_Risks = other.m_Risks;
return *this;
}
//---------------------------------------------------------------------------
BOOL PSS_ProcedureSymbolBP::Create(const CString& name)
{
BOOL result = FALSE;
try
{
m_IsInCreationProcess = true;
result = PSS_Symbol::Create(IDR_BP_PROCEDURE,
::AfxFindResourceHandle(MAKEINTRESOURCE(IDR_PACKAGE_SYM),
_T("Symbol")),
name);
if (!CreateSymbolProperties())
result = FALSE;
}
catch (...)
{
m_IsInCreationProcess = false;
throw;
}
m_IsInCreationProcess = false;
return result;
}
//---------------------------------------------------------------------------
CODComponent* PSS_ProcedureSymbolBP::Dup() const
{
return new PSS_ProcedureSymbolBP(*this);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::CopySymbolDefinitionFrom(const CODSymbolComponent& src)
{
PSS_Symbol::CopySymbolDefinitionFrom(src);
const PSS_ProcedureSymbolBP* pProcedure = dynamic_cast<const PSS_ProcedureSymbolBP*>(&src);
if (pProcedure)
{
m_Combinations = pProcedure->m_Combinations;
m_Combinations.SetParent(this);
m_SimulationProperties = pProcedure->m_SimulationProperties;
m_UnitProp = pProcedure->m_UnitProp;
m_CostProcedureProp = pProcedure->m_CostProcedureProp;
m_Rules = pProcedure->m_Rules;
m_Risks = pProcedure->m_Risks;
m_CommentRect = pProcedure->m_CommentRect;
// fill the unit double validation type array
m_UnitDoubleValidationTypeArray.RemoveAll();
GetUnitDoubleValidationTypeStringArray(m_UnitDoubleValidationTypeArray);
}
}
//---------------------------------------------------------------------------
BOOL PSS_ProcedureSymbolBP::SetSymbolName(const CString& value)
{
return PSS_Symbol::SetSymbolName(value);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::AcceptDropItem(CObject* pObj, const CPoint& point)
{
// don't allow the drop if the symbol isn't local
if (!IsLocal())
return false;
// is an user entity?
if (pObj && ISA(pObj, PSS_UserGroupEntity))
return true;
// is a rule?
if (pObj && ISA(pObj, PSS_LogicalRulesEntity))
return true;
return PSS_Symbol::AcceptDropItem(pObj, point);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::DropItem(CObject* pObj, const CPoint& point)
{
PSS_UserGroupEntity* pUserGroupEntity = dynamic_cast<PSS_UserGroupEntity*>(pObj);
if (pUserGroupEntity)
{
PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel());
// is the user group valid?
if (pModel && !pModel->MainUserGroupIsValid())
{
PSS_MsgBox mBox;
mBox.Show(IDS_CANNOTDROP_USERGROUPNOTINLINE, MB_OK);
return false;
}
SetUnitGUID(pUserGroupEntity->GetGUID());
SetUnitName(pUserGroupEntity->GetEntityName());
// change the unit cost
SetUnitCost(pUserGroupEntity->GetEntityCost());
// set flag for modification
SetModifiedFlag(TRUE);
// refresh the attribute area and redraw the symbol
RefreshAttributeTextArea(true);
return true;
}
PSS_LogicalRulesEntity* pLogicalRulesEntity = dynamic_cast<PSS_LogicalRulesEntity*>(pObj);
if (pLogicalRulesEntity)
{
PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel());
// is the rule valid?
if (pModel && !pModel->MainLogicalRulesIsValid())
{
PSS_MsgBox mBox;
mBox.Show(IDS_CANNOTDROP_RULENOTINLINE, MB_OK);
return false;
}
std::unique_ptr<PSS_RulesPropertiesBP> pRuleProps(new PSS_RulesPropertiesBP());
pRuleProps->SetRuleName(pLogicalRulesEntity->GetEntityName());
pRuleProps->SetRuleDescription(pLogicalRulesEntity->GetEntityDescription());
pRuleProps->SetRuleGUID(pLogicalRulesEntity->GetGUID());
m_Rules.AddRule(pRuleProps.get());
pRuleProps.release();
// set the procedure symbol as modified
SetModifiedFlag(TRUE);
// refresh the attribute area and redraw the symbol
RefreshAttributeTextArea(true);
return true;
}
return PSS_Symbol::DropItem(pObj, point);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::AcceptExtApp() const
{
return true;
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::AcceptExtFile() const
{
return true;
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::CreateSymbolProperties()
{
if (!PSS_Symbol::CreateSymbolProperties())
return false;
PSS_RuleListPropertiesBP propRules;
AddProperty(propRules);
PSS_TaskListPropertiesBP propTasks;
AddProperty(propTasks);
PSS_DecisionListPropertiesBP propDecisions;
AddProperty(propDecisions);
PSS_CostPropertiesProcedureBP_Beta1 propCost;
AddProperty(propCost);
PSS_UnitPropertiesBP_Beta1 propUnit;
AddProperty(propUnit);
// create at least one combination property
m_Combinations.CreateInitialProperties();
// fill the unit double validation type array
m_UnitDoubleValidationTypeArray.RemoveAll();
GetUnitDoubleValidationTypeStringArray(m_UnitDoubleValidationTypeArray);
// create at least one risk property
m_Risks.CreateInitialProperties();
return true;
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::FillProperties(PSS_Properties::IPropertySet& propSet, bool numericValues, bool groupValues)
{
// if no file, add a new one
if (!GetExtFileCount())
AddNewExtFile();
// if no application, add a new one
if (!GetExtAppCount())
AddNewExtApp();
// the "Name", "Description" and "Reference" properties of the "General" group can be found in the base class.
// The "External Files" and "External Apps" properties are also available from there
if (!PSS_Symbol::FillProperties(propSet, numericValues, groupValues))
return false;
// only local symbol may access to properties
if (!IsLocal())
return true;
PSS_ProcessGraphModelMdl* pProcessGraphModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel());
PSS_ProcessGraphModelDoc* pProcessGraphMdlDoc = pProcessGraphModel ? dynamic_cast<PSS_ProcessGraphModelDoc*>(pProcessGraphModel->GetDocument()) : NULL;
// initialize the currency symbol with the user local currency symbol defined in the control panel
CString currencySymbol = PSS_Global::GetLocaleCurrency();
// update the currency symbol according to the user selection
if (pProcessGraphMdlDoc)
currencySymbol = pProcessGraphMdlDoc->GetCurrencySymbol();
bool groupEnabled = true;
if (pProcessGraphModel && !pProcessGraphModel->MainUserGroupIsValid())
groupEnabled = false;
std::unique_ptr<PSS_Property> pProp;
// if the rule menu isn't loaded, load it
if (!g_RulesMenu.GetSafeHmenu())
g_RulesMenu.LoadMenu(IDR_RULES_MENU);
const int ruleCount = m_Rules.GetRulesCount();
// fill the rule properties
if (ruleCount)
{
CString ruleSectionTitle;
ruleSectionTitle.LoadString(IDS_Z_RULES_TITLE);
CString ruleDesc;
ruleDesc.LoadString(IDS_Z_RULES_DESC);
PSS_ProcessGraphModelMdlBP* pOwnerModel = dynamic_cast<PSS_ProcessGraphModelMdlBP*>(GetOwnerModel());
PSS_LogicalRulesEntity* pMainRule = NULL;
// get the main rule
if (pOwnerModel)
{
PSS_ProcessGraphModelControllerBP* pModelCtrl =
dynamic_cast<PSS_ProcessGraphModelControllerBP*>(pOwnerModel->GetController());
if (pModelCtrl)
{
PSS_ProcessGraphModelDoc* pDoc = dynamic_cast<PSS_ProcessGraphModelDoc*>(pModelCtrl->GetDocument());
if (pDoc)
pMainRule = pDoc->GetMainLogicalRules();
}
}
// iterate through the rules and add their properties
for (int i = 0; i < ruleCount; ++i)
{
// the rule check can only be performed if the rules are synchronized with the referential
if (pProcessGraphModel && pProcessGraphModel->MainLogicalRulesIsValid())
{
const CString safeName = GetRuleNameByGUID(pMainRule, m_Rules.GetRuleGUID(i));
if (!safeName.IsEmpty() && safeName != m_Rules.GetRuleName(i))
m_Rules.SetRuleName(i, safeName);
}
CString ruleName;
ruleName.Format(IDS_Z_RULES_NAME, i + 1);
// the "Rule x" property of the "Rules" group
pProp.reset(new PSS_Property(ruleSectionTitle,
ZS_BP_PROP_RULES,
ruleName,
M_Rule_Name_ID + (i * g_MaxRulesSize),
ruleDesc,
m_Rules.GetRuleName(i),
PSS_Property::IE_T_EditMenu,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
NULL,
&g_RulesMenu));
pProp->EnableDragNDrop();
propSet.Add(pProp.get());
pProp.release();
}
}
// NOTE BE CAREFUL the previous rules architecture below has now changed, and is designed as controls, because
// they became obsolete after the new rules system was implemented since November 2006. But as the two architectures
// are too different one from the other, and the both needed to cohabit together, for compatibility reasons with the
// previous serialization process, the texts referencing to the previous architecture were modified, and the "Rules"
// words were replaced by "Controls" in the text resources, however the code side was not updated, due to a too huge
// work to apply the changes. So if a new modification should be applied in the code, please be aware about this point
PSS_RuleListPropertiesBP* pRulesProps;
// add the rule
if ((pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST))) == NULL)
{
PSS_RuleListPropertiesBP propRules;
AddProperty(propRules);
// get it back
pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST));
if (!pRulesProps)
return false;
}
CString propTitle;
propTitle.LoadString(IDS_ZS_BP_PROP_RULELST_TITLE);
CStringArray* pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle);
CString propName;
propName.LoadString(IDS_Z_RULE_LIST_NAME);
CString propDesc;
propDesc.LoadString(IDS_Z_RULE_LIST_DESC);
CString finalPropName;
int count = GetRuleCount() + 1;
// iterate through all control properties, and define at least one control
for (int i = 0; i < g_MaxRuleListSize; ++i)
{
finalPropName.Format(_T("%s %d"), propName, i + 1);
// add control, if count is reached continue to add empty control until reaching the maximum size
if (i < count)
// the "Control x" property of the "Controls" group
pProp.reset(new PSS_Property(propTitle,
ZS_BP_PROP_RULELIST,
finalPropName,
M_Rule_List_ID + (i * g_MaxRuleListSize),
propDesc,
GetRuleAt(i),
PSS_Property::IE_T_EditIntelli,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
pValueArray));
else
// the "Control X" of the "Controls" group, but it is empty and not shown
pProp.reset(new PSS_Property(propTitle,
ZS_BP_PROP_RULELIST,
finalPropName,
M_Rule_List_ID + (i * g_MaxRuleListSize),
propDesc,
_T(""),
PSS_Property::IE_T_EditIntelli,
false,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
pValueArray));
pProp->EnableDragNDrop();
propSet.Add(pProp.get());
pProp.release();
}
// load the risk menu if still not exists
if (!g_RiskMenu.GetSafeHmenu())
g_RiskMenu.LoadMenu(IDR_RISK_MENU);
CString riskTitle;
riskTitle.LoadString(IDS_ZS_BP_PROP_RISK_TITLE);
// iterate through the risks and add their properties
for (int i = 0; i < GetRiskCount(); ++i)
{
CString finalRiskTitle;
finalRiskTitle.Format(_T("%s (%d)"), riskTitle, i + 1);
CString riskName;
riskName.LoadString(IDS_Z_RISK_NAME_NAME);
CString riskDesc;
riskDesc.LoadString(IDS_Z_RISK_NAME_DESC);
CString finalRiskName;
// the "Risk title" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_Name_ID : (M_Risk_Name_ID + (i * g_MaxRisksSize)),
riskDesc,
GetRiskName(i),
PSS_Property::IE_T_EditMenu,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
NULL,
&g_RiskMenu));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_DESC_NAME);
riskDesc.LoadString(IDS_Z_RISK_DESC_DESC);
// the "Description" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_Desc_ID : (M_Risk_Desc_ID + (i * g_MaxRisksSize)),
riskDesc,
GetRiskDesc(i),
PSS_Property::IE_T_EditExtended));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_TYPE_NAME);
riskDesc.LoadString(IDS_Z_RISK_TYPE_DESC);
CString sNoRiskType = _T("");
sNoRiskType.LoadString(IDS_NO_RISK_TYPE);
// the "Type" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_Type_ID : (M_Risk_Type_ID + (i * g_MaxRisksSize)),
riskDesc,
GetRiskType(i).IsEmpty() ? sNoRiskType : GetRiskType(i),
PSS_Property::IE_T_EditExtendedReadOnly));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_IMPACT_NAME);
riskDesc.LoadString(IDS_Z_RISK_IMPACT_DESC);
PSS_Application* pApplication = PSS_Application::Instance();
PSS_MainForm* pMainForm = NULL;
CString riskImpact;
// get the risk impact string
if (pApplication)
{
pMainForm = pApplication->GetMainForm();
if (pMainForm)
{
PSS_RiskImpactContainer* pContainer = pMainForm->GetRiskImpactContainer();
if (pContainer)
riskImpact = pContainer->GetElementAt(GetRiskImpact(i));
}
}
// the "Impact" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_Impact_ID : (M_Risk_Impact_ID + (i * g_MaxRisksSize)),
riskDesc,
riskImpact,
PSS_Property::IE_T_EditExtendedReadOnly));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_PROBABILITY_NAME);
riskDesc.LoadString(IDS_Z_RISK_PROBABILITY_DESC);
CString riskProbability;
if (pMainForm)
{
PSS_RiskProbabilityContainer* pContainer = pMainForm->GetRiskProbabilityContainer();
if (pContainer)
riskProbability = pContainer->GetElementAt(GetRiskProbability(i));
}
// the "Probability" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_Probability_ID : (M_Risk_Probability_ID + (i * g_MaxRisksSize)),
riskDesc,
riskProbability,
PSS_Property::IE_T_EditExtendedReadOnly));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_SEVERITY_NAME);
riskDesc.LoadString(IDS_Z_RISK_SEVERITY_DESC);
// the "Severity" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_Severity_ID : (M_Risk_Severity_ID + (i * g_MaxRisksSize)),
riskDesc,
double(GetRiskSeverity(i)),
PSS_Property::IE_T_EditNumberReadOnly));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_UE_NAME);
riskDesc.LoadString(IDS_Z_RISK_UE_DESC);
// the "Unit. est." property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_UE_ID : (M_Risk_UE_ID + (i * g_MaxRisksSize)),
riskDesc,
GetRiskUE(i),
PSS_Property::IE_T_EditNumber,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol)));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_POA_NAME);
riskDesc.LoadString(IDS_Z_RISK_POA_DESC);
// the "POA" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_POA_ID : (M_Risk_POA_ID + (i * g_MaxRisksSize)),
riskDesc,
GetRiskPOA(i),
PSS_Property::IE_T_EditNumber,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol)));
propSet.Add(pProp.get());
pProp.release();
riskName.LoadString(IDS_Z_RISK_ACTION_NAME);
riskDesc.LoadString(IDS_Z_RISK_ACTION_DESC);
// the "Action" property of the "Risk (x)" group
pProp.reset(new PSS_Property(finalRiskTitle,
groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i),
riskName,
groupValues ? M_Risk_Action_ID : (M_Risk_Action_ID + (i * g_MaxRisksSize)),
riskDesc,
GetRiskAction(i) ? PSS_Global::GetYesFromArrayYesNo() : PSS_Global::GetNoFromArrayYesNo(),
PSS_Property::IE_T_ComboStringReadOnly,
TRUE,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
PSS_Global::GetArrayYesNo()));
propSet.Add(pProp.get());
pProp.release();
}
// add tasks
PSS_TaskListPropertiesBP* pTasksProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST));
if (!pTasksProps)
return false;
count = GetTaskCount() + 1;
propTitle.LoadString(IDS_ZS_BP_PROP_PROCEDURE_TSKLST_TITLE);
pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle);
propName.LoadString(IDS_Z_TASK_LIST_NAME);
propDesc.LoadString(IDS_Z_TASK_LIST_DESC);
// iterate through all task properties, and define at least one task
for (int i = 0; i < g_MaxTaskListSize; ++i)
{
finalPropName.Format(_T("%s %d"), propName, i + 1);
// add task, if count is reached continue to add empty task until reaching the maximum size
if (i < count)
// the "Task x" property of the "Tasks" group
pProp.reset(new PSS_Property(propTitle,
ZS_BP_PROP_TASKLIST,
finalPropName,
M_Task_List_ID + (i * g_MaxTaskListSize),
propDesc,
GetTaskAt(i),
PSS_Property::IE_T_EditIntelli,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
pValueArray));
else
// the "Task x" property of the "Tasks" group, but empty and not shown
pProp.reset(new PSS_Property(propTitle,
ZS_BP_PROP_TASKLIST,
finalPropName,
M_Task_List_ID + (i * g_MaxTaskListSize),
propDesc,
_T(""),
PSS_Property::IE_T_EditIntelli,
false,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
pValueArray));
pProp->EnableDragNDrop();
propSet.Add(pProp.get());
pProp.release();
}
// get the decisions
PSS_DecisionListPropertiesBP* pDecisionsProps =
static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST));
if (!pDecisionsProps)
return false;
count = GetDecisionCount() + 1;
propTitle.LoadString(IDS_ZS_BP_PROP_PROCEDURE_DECLST_TITLE);
pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle);
propName.LoadString(IDS_Z_DECISION_LIST_NAME);
propDesc.LoadString(IDS_Z_DECISION_LIST_DESC);
// iterate through all decision properties, and define at least one decision
for (int i = 0; i < g_MaxDecisionListSize; ++i)
{
finalPropName.Format(_T("%s %d"), propName, i + 1);
// add decision, if count is reached continue to add empty decision until reaching the maximum size
if (i < count)
// the "Decision x" property of the "Decisions" group
pProp.reset(new PSS_Property(propTitle,
ZS_BP_PROP_DECISIONLIST,
finalPropName,
M_Decision_List_ID + (i * g_MaxDecisionListSize),
propDesc,
GetDecisionAt(i),
PSS_Property::IE_T_EditIntelli,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
pValueArray));
else
// the "Decision x" property of the "Decisions" group, but it is empty and not shown
pProp.reset(new PSS_Property(propTitle,
ZS_BP_PROP_DECISIONLIST,
finalPropName,
M_Decision_List_ID + (i * g_MaxDecisionListSize),
propDesc,
_T(""),
PSS_Property::IE_T_EditIntelli,
false,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
pValueArray));
pProp->EnableDragNDrop();
propSet.Add(pProp.get());
pProp.release();
}
int hourPerDay = -1;
int dayPerWeek = -1;
int dayPerMonth = -1;
int dayPerYear = -1;
// get the standard time
if (pProcessGraphMdlDoc)
{
hourPerDay = pProcessGraphMdlDoc->GetHourPerDay();
dayPerWeek = pProcessGraphMdlDoc->GetDayPerWeek();
dayPerMonth = pProcessGraphMdlDoc->GetDayPerMonth();
dayPerYear = pProcessGraphMdlDoc->GetDayPerYear();
}
bool error;
// do add the procedure and processing unit properties?
if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation())
{
// the "Multiplier" property of the "Procedure" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_MULTIPLIER_NAME,
M_Cost_Proc_Multiplier_ID,
IDS_Z_COST_MULTIPLIER_DESC,
GetMultiplier(),
PSS_Property::IE_T_EditNumber,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Accounting, true, -1)));
propSet.Add(pProp.get());
pProp.release();
// the "Standard time" property of the "Procedure" group
if (numericValues)
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_PROCESSING_TIME_NAME,
M_Cost_Proc_Processing_Time_ID,
IDS_Z_COST_PROCESSING_TIME_DESC,
GetProcessingTime(),
PSS_Property::IE_T_EditNumber));
else
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_PROCESSING_TIME_NAME,
M_Cost_Proc_Processing_Time_ID,
IDS_Z_COST_PROCESSING_TIME_DESC,
PSS_Duration(GetProcessingTime(),
hourPerDay,
dayPerWeek,
dayPerMonth,
dayPerYear),
PSS_Property::IE_T_EditDuration,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7)));
propSet.Add(pProp.get());
pProp.release();
// the "Unitary cost" property of the "Procedure" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_UNITARY_COST_NAME,
M_Cost_Proc_Unitary_Cost_ID,
IDS_Z_COST_UNITARY_COST_DESC,
GetUnitaryCost(),
PSS_Property::IE_T_EditNumber,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Currency,
true,
2,
currencySymbol)));
propSet.Add(pProp.get());
pProp.release();
// the "Average duration (weighted)" property of the "Procedure" group
if (numericValues)
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_PROCESSING_DURATION_NAME,
M_Cost_Proc_Processing_Duration_ID,
IDS_Z_COST_PROCESSING_DURATION_DESC,
GetProcessingDuration(),
PSS_Property::IE_T_EditNumber));
else
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_PROCESSING_DURATION_NAME,
M_Cost_Proc_Processing_Duration_ID,
IDS_Z_COST_PROCESSING_DURATION_DESC,
PSS_Duration(GetProcessingDuration(),
hourPerDay,
dayPerWeek,
dayPerMonth,
dayPerYear),
PSS_Property::IE_T_EditDurationReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7)));
propSet.Add(pProp.get());
pProp.release();
// the "Average duration (max)" property of the "Procedure" group
if (numericValues)
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_PROCESSING_DURATIONMAX_NAME,
M_Cost_Proc_Processing_Duration_Max_ID,
IDS_Z_COST_PROCESSING_DURATIONMAX_DESC,
GetProcessingDurationMax(),
PSS_Property::IE_T_EditNumber));
else
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE,
ZS_BP_PROP_PROCEDURE_COST,
IDS_Z_COST_PROCESSING_DURATIONMAX_NAME,
M_Cost_Proc_Processing_Duration_Max_ID,
IDS_Z_COST_PROCESSING_DURATIONMAX_DESC,
PSS_Duration(GetProcessingDurationMax(),
hourPerDay,
dayPerWeek,
dayPerMonth,
dayPerYear),
PSS_Property::IE_T_EditDurationReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7)));
propSet.Add(pProp.get());
pProp.release();
// get the unit cost
const float unitCost = RetrieveUnitCost(GetUnitGUID(), error);
// the "Cost" property of the "Processing unit" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE,
ZS_BP_PROP_UNIT,
IDS_Z_UNIT_COST_NAME,
M_Unit_Cost_ID,
IDS_Z_UNIT_COST_DESC,
unitCost,
PSS_Property::IE_T_EditNumberReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Currency,
true,
2,
currencySymbol)));
propSet.Add(pProp.get());
pProp.release();
// the "Double validation" property of the "Processing unit" group
if (numericValues)
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE,
ZS_BP_PROP_UNIT,
IDS_Z_UNIT_DOUBLE_VALIDATION_NAME,
M_Unit_Double_Validation_ID,
IDS_Z_UNIT_DOUBLE_VALIDATION_DESC,
double(GetUnitDoubleValidationType()),
PSS_Property::IE_T_EditNumber,
false,
PSS_StringFormat(PSS_StringFormat::IE_FT_General)));
else
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE,
ZS_BP_PROP_UNIT,
IDS_Z_UNIT_DOUBLE_VALIDATION_NAME,
M_Unit_Double_Validation_ID,
IDS_Z_UNIT_DOUBLE_VALIDATION_DESC,
GetUnitDoubleValidationTypeString(GetUnitDoubleValidationType()),
PSS_Property::IE_T_ComboStringReadOnly,
false,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
&m_UnitDoubleValidationTypeArray));
propSet.Add(pProp.get());
pProp.release();
}
// the "Guid" property of the "Processing unit" group. This property isn't enabled, just used for write the unit GUID.
// NOTE "GUID" and "Name" properties should appear in Conceptor
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE,
ZS_BP_PROP_UNIT,
IDS_Z_UNIT_GUID_NAME,
M_Unit_GUID_ID,
IDS_Z_UNIT_GUID_DESC,
GetUnitGUID(),
PSS_Property::IE_T_EditExtendedReadOnly,
false));
propSet.Add(pProp.get());
pProp.release();
// get the unit name
const CString unitName = RetrieveUnitName(GetUnitGUID(), error);
// the "Unit" property of the "Processing unit" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE,
ZS_BP_PROP_UNIT,
IDS_Z_UNIT_NAME_NAME,
M_Unit_Name_ID,
IDS_Z_UNIT_NAME_DESC,
unitName,
groupEnabled ? PSS_Property::IE_T_EditExtendedReadOnly : PSS_Property::IE_T_EditStringReadOnly));
propSet.Add(pProp.get());
pProp.release();
// if the combination menu is not loaded, load it
if (!g_CombinationMenu.GetSafeHmenu())
g_CombinationMenu.LoadMenu(IDR_COMBINATION_MENU);
// the combination properties should appear only in Messenger
if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation())
{
CString finalPropTitle;
count = GetCombinationCount();
propTitle.LoadString(IDS_ZS_BP_PROP_COMBINATION_TITLE);
// necessary to check if the initial combination is correct
CheckInitialCombination();
// iterate through all combination properties
for (int i = 0; i < count; ++i)
{
finalPropTitle.Format(_T("%s (%d)"), propTitle, i + 1);
propName.LoadString(IDS_Z_COMBINATION_NAME_NAME);
propDesc.LoadString(IDS_Z_COMBINATION_NAME_DESC);
// the "Combination title" property of the "Combination x" group
pProp.reset(new PSS_Property(finalPropTitle,
groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i),
propName,
groupValues ? M_Combination_Name_ID : (M_Combination_Name_ID + (i * g_MaxCombinationListSize)),
propDesc,
GetCombinationName(i),
PSS_Property::IE_T_EditMenu,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_General),
NULL,
&g_CombinationMenu));
propSet.Add(pProp.get());
pProp.release();
propName.LoadString(IDS_Z_COMBINATION_DELIVERABLES_NAME);
propDesc.LoadString(IDS_Z_COMBINATION_DELIVERABLES_DESC);
// the "Deliverables" property of the "Combination x" group
pProp.reset(new PSS_Property(finalPropTitle,
groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i),
propName,
groupValues ? M_Combination_Deliverables_ID : (M_Combination_Deliverables_ID + (i * g_MaxCombinationListSize)),
propDesc,
GetCombinationDeliverables(i),
PSS_Property::IE_T_EditExtendedReadOnly));
propSet.Add(pProp.get());
pProp.release();
propName.LoadString(IDS_Z_COMBINATION_ACTIVATION_PERC_NAME);
propDesc.LoadString(IDS_Z_COMBINATION_ACTIVATION_PERC_DESC);
// get the percentage
const float maxPercent = GetMaxActivationPerc(GetCombinationMaster(i));
// the "Percentage" property of the "Combination x" group
pProp.reset(new PSS_Property(finalPropTitle,
groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i),
propName,
groupValues ? M_Combination_Activation_Perc_ID : (M_Combination_Activation_Perc_ID + (i * g_MaxCombinationListSize)),
propDesc,
maxPercent,
PSS_Property::IE_T_EditNumberReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Percentage)));
propSet.Add(pProp.get());
pProp.release();
propName.LoadString(IDS_Z_COMBINATION_MASTER_NAME);
propDesc.LoadString(IDS_Z_COMBINATION_MASTER_DESC);
// the "Master" property of the "Combination x" group
pProp.reset(new PSS_Property(finalPropTitle,
groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i),
propName,
groupValues ? M_Combination_Master_ID : (M_Combination_Master_ID + (i * g_MaxCombinationListSize)),
propDesc,
GetCombinationMaster(i),
PSS_Property::IE_T_EditExtendedReadOnly));
propSet.Add(pProp.get());
pProp.release();
}
}
if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation())
{
// get the procedure activation value
const double value = double(CalculateProcedureActivation());
// the "Activation" property of the "Calculations and forecasts" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_ACTIVATION_NAME,
M_Sim_Procedure_Activation_ID,
IDS_Z_SIM_PROCEDURE_ACTIVATION_DESC,
value,
PSS_Property::IE_T_EditNumberReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Accounting, true, 0)));
propSet.Add(pProp.get());
pProp.release();
// the "HMO cost" property of the "Calculations and forecasts" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_COST_NAME,
M_Sim_Procedure_Cost_ID,
IDS_Z_SIM_PROCEDURE_COST_DESC,
double(GetProcedureCost()),
PSS_Property::IE_T_EditNumberReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol)));
propSet.Add(pProp.get());
pProp.release();
// the "Charge" property of the "Calculations and forecasts" group
if (numericValues)
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_NAME,
M_Sim_Procedure_Workload_Forecast_ID,
IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_DESC,
double(GetProcedureWorkloadForecast()),
PSS_Property::IE_T_EditNumber));
else
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_NAME,
M_Sim_Procedure_Workload_Forecast_ID,
IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_DESC,
PSS_Duration(double(GetProcedureWorkloadForecast()),
hourPerDay,
dayPerWeek,
dayPerMonth,
dayPerYear),
PSS_Property::IE_T_EditDurationReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7)));
propSet.Add(pProp.get());
pProp.release();
// the "Cost" property of the "Calculations and forecasts" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_COST_FORECAST_NAME,
M_Sim_Procedure_Cost_Forecast_ID,
IDS_Z_SIM_PROCEDURE_COST_FORECAST_DESC,
double(GetProcedureCostForecast()),
PSS_Property::IE_T_EditNumberReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol)));
propSet.Add(pProp.get());
pProp.release();
// the "Charge / activation" property of the "Calculations and forecasts" group
if (numericValues)
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_NAME,
M_Sim_Procedure_Workload_Per_Activ_ID,
IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_DESC,
double(GetProcedureWorkloadPerActivity()),
PSS_Property::IE_T_EditNumber));
else
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_NAME,
M_Sim_Procedure_Workload_Per_Activ_ID,
IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_DESC,
PSS_Duration(double(GetProcedureWorkloadPerActivity()),
hourPerDay,
dayPerWeek,
dayPerMonth,
dayPerYear),
PSS_Property::IE_T_EditDurationReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7)));
propSet.Add(pProp.get());
pProp.release();
// the "Cost / activation" property of the "Calculations and forecasts" group
pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE,
ZS_BP_PROP_SIM_PROCEDURE,
IDS_Z_SIM_PROCEDURE_COST_P_ACTIV_NAME,
M_Sim_Procedure_Cost_Per_Activ_ID,
IDS_Z_SIM_PROCEDURE_COST_P_ACTIV_DESC,
GetProcedureCostPerActivity(),
PSS_Property::IE_T_EditNumberReadOnly,
true,
PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol)));
propSet.Add(pProp.get());
pProp.release();
}
return true;
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::SaveProperties(PSS_Properties::IPropertySet& propSet)
{
if (!PSS_Symbol::SaveProperties(propSet))
return false;
// only local symbol may access to properties
if (!IsLocal())
return true;
// save the rules
PSS_RuleListPropertiesBP* pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST));
if (!pRulesProps)
return false;
PSS_Properties::IPropertyIterator it(&propSet);
// empty the task list
SetRuleList(_T(""));
// iterate through the data list and fill the property set
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_RULELIST)
switch (pProp->GetValueType())
{
case PSS_Property::IE_VT_String:
// if not empty, add this new task
if (!pProp->GetValueString().IsEmpty())
AddRule(pProp->GetValueString());
break;
}
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
{
const int categoryID = pProp->GetCategoryID();
if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount())
{
const int itemID = pProp->GetItemID();
const int i = categoryID - ZS_BP_PROP_RISK;
if (itemID == M_Risk_Name_ID + (i * g_MaxRisksSize))
SetRiskName(i, pProp->GetValueString());
if (itemID == M_Risk_Desc_ID + (i * g_MaxRisksSize))
SetRiskDesc(i, pProp->GetValueString());
if (itemID == M_Risk_UE_ID + (i * g_MaxRisksSize))
SetRiskUE(i, pProp->GetValueFloat());
if (itemID == M_Risk_POA_ID + (i * g_MaxRisksSize))
SetRiskPOA(i, pProp->GetValueFloat());
if (itemID == M_Risk_Action_ID + (i * g_MaxRisksSize))
SetRiskAction(i, (pProp->GetValueString() == PSS_Global::GetYesFromArrayYesNo() ? 1 : 0));
}
}
// save the tasks
PSS_TaskListPropertiesBP* pTasksProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST));
if (!pTasksProps)
return false;
// empty the task list
SetTaskList(_T(""));
// iterate through the data list and fill the property set
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_TASKLIST)
switch (pProp->GetValueType())
{
case PSS_Property::IE_VT_String:
// if not empty, add this new task
if (!pProp->GetValueString().IsEmpty())
AddTask(pProp->GetValueString());
break;
}
// save the decisions. Because the AddTask() function is called, it's not necessary to call SetProperty()
PSS_DecisionListPropertiesBP* pDecisionsProps =
static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST));
if (!pDecisionsProps)
return false;
// empty the decision list
SetDecisionList(_T(""));
// iterate through the data list and fill the property set
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_DECISIONLIST)
switch (pProp->GetValueType())
{
case PSS_Property::IE_VT_String:
// if not empty, add this new decision
if (!pProp->GetValueString().IsEmpty())
AddDecision(pProp->GetValueString());
break;
}
// iterate through the data list and fill the property set. Because the AddDecision() function is called,
// it's not necessary to call SetProperty()
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_PROCEDURE_COST)
{
const int itemID = pProp->GetItemID();
switch (pProp->GetValueType())
{
case PSS_Property::IE_VT_String: m_CostProcedureProp.SetValue(itemID, pProp->GetValueString()); break;
case PSS_Property::IE_VT_Double: m_CostProcedureProp.SetValue(itemID, float( pProp->GetValueDouble())); break;
case PSS_Property::IE_VT_Float: m_CostProcedureProp.SetValue(itemID, pProp->GetValueFloat()); break;
case PSS_Property::IE_VT_Date: m_CostProcedureProp.SetValue(itemID, float(DATE(pProp->GetValueDate()))); break;
case PSS_Property::IE_VT_TimeSpan: m_CostProcedureProp.SetValue(itemID, double( pProp->GetValueTimeSpan())); break;
case PSS_Property::IE_VT_Duration: m_CostProcedureProp.SetValue(itemID, double( pProp->GetValueDuration())); break;
}
}
// iterate through the data list and fill the property set
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT)
if (pProp->GetItemID() == M_Unit_Double_Validation_ID)
m_UnitProp.SetValue(pProp->GetItemID(),
ConvertUnitDoubleValidationString2Type(pProp->GetValueString()));
else
{
const int itemID = pProp->GetItemID();
switch (pProp->GetValueType())
{
case PSS_Property::IE_VT_Double: m_UnitProp.SetValue(itemID, float(pProp->GetValueDouble())); break;
case PSS_Property::IE_VT_Float: m_UnitProp.SetValue(itemID, pProp->GetValueFloat()); break;
case PSS_Property::IE_VT_String: m_UnitProp.SetValue(itemID, pProp->GetValueString()); break;
}
}
// iterate through the data list and fill the property set of combination
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
{
const int categoryID = pProp->GetCategoryID();
if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount())
{
const int i = categoryID - ZS_BP_PROP_COMBINATION;
PSS_CombinationPropertiesBP* pCombProps = GetCombinationProperty(i);
if (!pCombProps)
return false;
const int itemID = pProp->GetItemID();
switch (pProp->GetValueType())
{
case PSS_Property::IE_VT_String: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), pProp->GetValueString()); break;
case PSS_Property::IE_VT_Double: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), float( pProp->GetValueDouble())); break;
case PSS_Property::IE_VT_Float: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), pProp->GetValueFloat()); break;
case PSS_Property::IE_VT_Date: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), float(DATE(pProp->GetValueDate()))); break;
case PSS_Property::IE_VT_TimeSpan:
case PSS_Property::IE_VT_Duration: THROW("Unsupported value");
}
}
}
// iterate through the data list and fill the property set
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_SIM_PROCEDURE)
{
const int itemID = pProp->GetItemID();
switch (pProp->GetValueType())
{
case PSS_Property::IE_VT_String: m_SimulationProperties.SetValue(itemID, pProp->GetValueString()); break;
case PSS_Property::IE_VT_Double: m_SimulationProperties.SetValue(itemID, pProp->GetValueDouble()); break;
case PSS_Property::IE_VT_Float: m_SimulationProperties.SetValue(itemID, pProp->GetValueFloat()); break;
case PSS_Property::IE_VT_Date: m_SimulationProperties.SetValue(itemID, float(DATE(pProp->GetValueDate()))); break;
case PSS_Property::IE_VT_TimeSpan: m_SimulationProperties.SetValue(itemID, double( pProp->GetValueTimeSpan())); break;
case PSS_Property::IE_VT_Duration: m_SimulationProperties.SetValue(itemID, double( pProp->GetValueDuration())); break;
}
}
RefreshAttributeTextArea(true);
return true;
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::SaveProperty(PSS_Property& prop)
{
if (!PSS_Symbol::SaveProperty(prop))
return false;
// only local symbol may access to properties
if (!IsLocal())
return true;
const int categoryID = prop.GetCategoryID();
if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount())
{
const int itemID = prop.GetItemID();
const int i = categoryID - ZS_BP_PROP_RISK;
if (itemID == M_Risk_Name_ID + (i * g_MaxRisksSize))
SetRiskName(i, prop.GetValueString());
if (itemID == M_Risk_Desc_ID + (i * g_MaxRisksSize))
SetRiskDesc(i, prop.GetValueString());
if (itemID == M_Risk_UE_ID + (i * g_MaxRisksSize))
SetRiskUE(i, prop.GetValueFloat());
if (itemID == M_Risk_POA_ID + (i * g_MaxRisksSize))
SetRiskPOA(i, prop.GetValueFloat());
if (itemID == M_Risk_Action_ID + (i * g_MaxRisksSize))
SetRiskAction(i, (prop.GetValueString() == PSS_Global::GetYesFromArrayYesNo() ? 1 : 0));
}
// check if the user tried to rename a rule, if yes revert to previous name
if (categoryID == ZS_BP_PROP_RULES)
{
const int index = (prop.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize;
if (m_Rules.GetRuleName(index) != prop.GetValueString())
prop.SetValueString(m_Rules.GetRuleName(index));
}
if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount())
{
const int i = categoryID - ZS_BP_PROP_COMBINATION;
switch (prop.GetItemID() - (i * g_MaxCombinationListSize))
{
case M_Combination_Name_ID: SetCombinationName (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break;
case M_Combination_Deliverables_ID: SetCombinationDeliverables (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break;
case M_Combination_Activation_Perc_ID: SetCombinationActivationPerc(prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueFloat()); break;
case M_Combination_Master_ID: SetCombinationMaster (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break;
}
}
if (categoryID == ZS_BP_PROP_RULELIST)
// if not empty, add this new rule
if (!prop.GetValueString().IsEmpty())
AddRule(prop.GetValueString());
if (categoryID == ZS_BP_PROP_TASKLIST)
// if not empty, add this new task
if (!prop.GetValueString().IsEmpty())
AddTask(prop.GetValueString());
if (categoryID == ZS_BP_PROP_DECISIONLIST)
// if not empty, add this new task
if (!prop.GetValueString().IsEmpty())
AddDecision(prop.GetValueString());
// set the symbol as modified. Do nothing else, the values will be saved by the save properties method
SetModifiedFlag();
return true;
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::CheckPropertyValue(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props)
{
return PSS_Symbol::CheckPropertyValue(prop, value, props);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::ProcessExtendedInput(PSS_Property& prop,
CString& value,
PSS_Properties::IPropertySet& props,
bool& refresh)
{
const int categoryID = prop.GetCategoryID();
if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount())
{
const int i = categoryID - ZS_BP_PROP_RISK;
PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel());
CString currencySymbol = PSS_Global::GetLocaleCurrency();
// get the model currency symbol
if (pModel)
{
PSS_ProcessGraphModelDoc* pDoc = dynamic_cast<PSS_ProcessGraphModelDoc*>(pModel->GetDocument());
if (pDoc)
currencySymbol = pDoc->GetCurrencySymbol();
}
CString noRiskType;
noRiskType.LoadString(IDS_NO_RISK_TYPE);
PSS_RiskOptionsDlg riskOptions(GetRiskName(i),
GetRiskDesc(i),
GetRiskType(i).IsEmpty() ? noRiskType : GetRiskType(i),
GetRiskImpact(i),
GetRiskProbability(i),
GetRiskUE(i),
GetRiskPOA(i),
GetRiskAction(i),
currencySymbol);
if (riskOptions.DoModal() == IDOK)
{
SetRiskName (i, riskOptions.GetRiskTitle());
SetRiskDesc (i, riskOptions.GetRiskDescription());
SetRiskType (i, riskOptions.GetRiskType());
SetRiskImpact (i, riskOptions.GetRiskImpact());
SetRiskProbability(i, riskOptions.GetRiskProbability());
SetRiskSeverity (i, riskOptions.GetRiskSeverity());
SetRiskUE (i, riskOptions.GetRiskUE());
SetRiskPOA (i, riskOptions.GetRiskPOA());
SetRiskAction (i, riskOptions.GetRiskAction());
SetModifiedFlag(TRUE);
refresh = true;
return true;
}
}
if (categoryID == ZS_BP_PROP_UNIT && prop.GetItemID() == M_Unit_Name_ID)
{
PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetOwnerModel());
if (pModel)
{
PSS_SelectUserGroupDlg dlg(IDS_SELECTAGROUP_T, pModel->GetMainUserGroup(), true, false);
if (dlg.DoModal() == IDOK)
{
PSS_UserEntity* pUserEntity = dlg.GetSelectedUserEntity();
if (pUserEntity)
{
value = pUserEntity->GetEntityName();
// change the disabled property unit GUID
PSS_Properties::IPropertyIterator it(&props);
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_GUID_ID)
{
pProp->SetValueString(pUserEntity->GetGUID());
break;
}
return true;
}
}
}
}
else
if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount())
{
const int i = categoryID - ZS_BP_PROP_COMBINATION;
switch (prop.GetItemID() - (i * g_MaxCombinationListSize))
{
case M_Combination_Deliverables_ID:
{
// get the deliverables
CString enteringDeliverables;
GetEnteringUpDeliverable(enteringDeliverables);
CString availableDeliverables = GetAvailableDeliverables(enteringDeliverables);
// show the dialog
PSS_AddRemoveCombinationDeliverableDlg dlg(availableDeliverables, value);
if (dlg.DoModal() == IDOK)
{
value = dlg.GetDeliverables();
return true;
}
break;
}
case M_Combination_Master_ID:
{
PSS_SelectMasterDeliverableDlg dlg(GetCombinationDeliverables(i), value);
if (dlg.DoModal() == IDOK)
{
value = dlg.GetMaster();
return true;
}
break;
}
}
}
return PSS_Symbol::ProcessExtendedInput(prop, value, props, refresh);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::ProcessMenuCommand(int menuCmdID,
PSS_Property& prop,
CString& value,
PSS_Properties::IPropertySet& props,
bool& refresh)
{
const int categoryID = prop.GetCategoryID();
if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount())
{
switch (menuCmdID)
{
case ID_ADD_NEWRISK: OnAddNewRisk (prop, value, props, refresh); break;
case ID_DEL_CURRENTRISK: OnDelCurrentRisk(prop, value, props, refresh); break;
default: break;
}
return true;
}
if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount())
{
switch (menuCmdID)
{
case ID_ADD_NEWCOMBINATION: OnAddNewCombination (prop, value, props, refresh); break;
case ID_DEL_CURRENTCOMBINATION: OnDelCurrentCombination (prop, value, props, refresh); break;
case ID_ADD_DELIVERABLE_COMBINATION: OnAddDeliverableCombination(prop, value, props, refresh); break;
case ID_DEL_DELIVERABLE_COMBINATION: OnDelDeliverableCombination(prop, value, props, refresh); break;
default: break;
}
return true;
}
if (categoryID == ZS_BP_PROP_RULES)
switch (menuCmdID)
{
case ID_DEL_CURRENTRULE:
{
const int index = (prop.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize;
m_Rules.DeleteRule(index);
refresh = true;
break;
}
default:
break;
}
return PSS_Symbol::ProcessMenuCommand(menuCmdID, prop, value, props, refresh);
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetAttributeString(PSS_PropertyAttributes* pAttributes) const
{
return PSS_Symbol::GetAttributeString(pAttributes);
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetEnteringUpDeliverable(CString& deliverables)
{
int counter = 0;
CODEdgeArray edges;
// keep only deliverable symbols
if (GetEnteringUpDeliverable(edges) > 0)
{
// initialize the token with ; as separator
PSS_Tokenizer token;
const int edgeCount = edges.GetSize();
for (int i = 0; i < edgeCount; ++i)
{
IODEdge* pIEdge = edges.GetAt(i);
PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge);
if (pComp)
{
token.AddToken(pComp->GetSymbolName());
++counter;
}
}
// assign the resulting string
deliverables = token.GetString();
}
return counter;
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetEnteringUpDeliverable(CODEdgeArray& edges)
{
// get all procedure entering up edges
GetEdgesEntering_Up(edges);
CODComponentSet* pSet = GetReferenceSymbols();
CODComponentSet internalSet;
// get all edges from referenced procedures and local symbol if a referenced symbol is defined
if (!IsLocal())
{
if (!pSet)
pSet = &internalSet;
CODComponent* pLocalSymbol = GetLocalSymbol();
if (pLocalSymbol)
pSet->Add(pLocalSymbol);
}
if (pSet)
{
const int setCount = pSet->GetSize();
for (int i = 0; i < setCount; ++i)
{
PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i));
if (pComp)
{
CODEdgeArray additionalEdges;
pComp->GetEdgesEntering_Up(additionalEdges);
const int edgeCount = additionalEdges.GetSize();
// copy additional edges to the main edges
for (int j = 0; j < edgeCount; ++j)
// get the link
edges.AddEdge(additionalEdges.GetAt(j));
}
}
}
// keep only deliverable symbols
return int(PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP)));
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetLeavingDownDeliverable(CString& deliverables)
{
int counter = 0;
CODEdgeArray edges;
if (GetLeavingDownDeliverable(edges) > 0)
{
// initialize the token with ; as separator
PSS_Tokenizer token;
const int edgeCount = edges.GetSize();
for (int i = 0; i < edgeCount; ++i)
{
IODEdge* pIEdge = edges.GetAt(i);
PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge);
if (pComp)
{
token.AddToken(pComp->GetSymbolName());
++counter;
}
}
// assign the resulting string
deliverables = token.GetString();
}
return counter;
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetLeavingDownDeliverable(CODEdgeArray& edges)
{
// get all leaving down edges
GetEdgesLeaving_Down(edges);
CODComponentSet* pSet = GetReferenceSymbols();
CODComponentSet internalSet;
// get all edges from referenced procedures and local symbol if a referenced symbol is defined
if (!IsLocal())
{
if (!pSet)
pSet = &internalSet;
CODComponent* pLocalSymbol = GetLocalSymbol();
if (pLocalSymbol)
pSet->Add(pLocalSymbol);
}
if (pSet)
{
const int setCount = pSet->GetSize();
for (int i = 0; i < setCount; ++i)
{
PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i));
if (pComp)
{
CODEdgeArray additionalEdges;
pComp->GetEdgesLeaving_Down(additionalEdges);
const int edgeCount = additionalEdges.GetSize();
// copy additional edges to the main edges
for (int j = 0; j < edgeCount; ++j)
// get the link
edges.AddEdge(additionalEdges.GetAt(j));
}
}
}
// keep only deliverable symbols
return int(PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP)));
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetLeavingLeftDeliverable(CString& deliverables)
{
int counter = 0;
CODEdgeArray edges;
if (GetLeavingLeftDeliverable(edges) > 0)
{
// initialize the token with ; as separator
PSS_Tokenizer token;
const int edgeCount = edges.GetSize();
for (int i = 0; i < edgeCount; ++i)
{
IODEdge* pIEdge = edges.GetAt(i);
PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge);
if (pComp)
{
token.AddToken(pComp->GetSymbolName());
++counter;
}
}
// assign the resulting string
deliverables = token.GetString();
}
return counter;
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetLeavingLeftDeliverable(CODEdgeArray& edges)
{
// get all leaving left edges
GetEdgesLeaving_Left(edges);
CODComponentSet* pSet = GetReferenceSymbols();
CODComponentSet internalSet;
// get all edges from referenced procedures and local symbol if a referenced symbol is defined
if (!IsLocal())
{
if (!pSet)
pSet = &internalSet;
CODComponent* pLocalSymbol = GetLocalSymbol();
if (pLocalSymbol)
pSet->Add(pLocalSymbol);
}
if (pSet)
{
const int setCount = pSet->GetSize();
for (int i = 0; i < setCount; ++i)
{
PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i));
if (pComp)
{
CODEdgeArray additionalEdges;
pComp->GetEdgesLeaving_Left(additionalEdges);
const int edgeCount = additionalEdges.GetSize();
// copy additional edges to the main edges
for (int j = 0; j < edgeCount; ++j)
// get the link
edges.AddEdge(additionalEdges.GetAt(j));
}
}
}
// keep only deliverable symbols
return (int)PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP));
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetLeavingRightDeliverable(CString& deliverables)
{
int counter = 0;
CODEdgeArray edges;
if (GetLeavingRightDeliverable(edges) > 0)
{
// initialize the token with ; as separator
PSS_Tokenizer token;
const int edgeCount = edges.GetSize();
for (int i = 0; i < edgeCount; ++i)
{
IODEdge* pIEdge = edges.GetAt(i);
PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge);
if (pComp)
{
token.AddToken(pComp->GetSymbolName());
++counter;
}
}
// assign the resulting string
deliverables = token.GetString();
}
return counter;
}
//---------------------------------------------------------------------------
int PSS_ProcedureSymbolBP::GetLeavingRightDeliverable(CODEdgeArray& edges)
{
// get all leaving right edges
GetEdgesLeaving_Right(edges);
// get all edges from referenced procedures and local symbol if a referenced symbol is defined
CODComponentSet* pSet = GetReferenceSymbols();
CODComponentSet internalSet;
if (!IsLocal())
{
if (!pSet)
pSet = &internalSet;
CODComponent* pLocalSymbol = GetLocalSymbol();
if (pLocalSymbol)
pSet->Add(pLocalSymbol);
}
if (pSet)
{
const int setCount = pSet->GetSize();
for (int i = 0; i < setCount; ++i)
{
PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i));
if (pComp)
{
CODEdgeArray additionalEdges;
pComp->GetEdgesLeaving_Right(additionalEdges);
const int edgeCount = additionalEdges.GetSize();
// copy additional edges to the main edges
for (int j = 0; j < edgeCount; ++j)
// get the link
edges.AddEdge(additionalEdges.GetAt(j));
}
}
}
// keep only deliverable symbols
return (int)PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP));
}
//---------------------------------------------------------------------------
PSS_AnnualNumberPropertiesBP PSS_ProcedureSymbolBP::CalculateProcedureActivation()
{
// get all entering deliverables
CODEdgeArray edges;
// get all entering up edges
if (!GetEnteringUpDeliverable(edges))
return 0;
PSS_AnnualNumberPropertiesBP ProcedureActivation(0);
// for each deliverables, calculate the max procedure activation
for (int i = 0; i < edges.GetSize(); ++i)
{
IODEdge* pIEdge = edges.GetAt(i);
PSS_DeliverableLinkSymbolBP* pDeliverable = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge);
if (!pDeliverable)
continue;
// check if it's a local symbol
if (!pDeliverable->IsLocal())
{
// get the local symbol
pDeliverable = dynamic_cast<PSS_DeliverableLinkSymbolBP*>(pDeliverable->GetLocalSymbol());
if (!pDeliverable)
return false;
}
const int count = GetCombinationCount();
// iterate through combination and check if this deliverable is defined as a master. If yes,
// add it to the procedure activation
for (int j = 0; j < count; ++j)
{
TRACE1("Master = %s\n", GetCombinationMaster(j));
TRACE1("Livrable = %s\n", pDeliverable->GetSymbolName());
// found a master?
if (!GetCombinationMaster(j).IsEmpty() && GetCombinationMaster(j) == pDeliverable->GetSymbolName())
ProcedureActivation += pDeliverable->GetQuantity();
}
}
return ProcedureActivation;
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetRuleList() const
{
PSS_RuleListPropertiesBP* pProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST));
if (!pProps)
return _T("");
return pProps->GetRuleList();
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::SetRuleList(const CString& value)
{
PSS_RuleListPropertiesBP* pProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST));
if (pProps)
{
PSS_RuleListPropertiesBP props(*pProps);
props.SetRuleList(value);
SetProperty(&props);
}
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::RuleExist(const CString& value)
{
// initialize the token with the rule list and with the default ; as separator
PSS_Tokenizer token(GetRuleList());
return token.TokenExist(value);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::AddRule(const CString& value)
{
// initialize the token with the rule list and with the default ; as separator
PSS_Tokenizer token(GetRuleList());
// if the new rule was added successfully, update the rule list
if (token.AddUniqueToken(value))
{
// add the value to the history
CString key;
key.LoadString(IDS_ZS_BP_PROP_RULELST_TITLE);
PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value);
// set the new rule string
SetRuleList(token.GetString());
}
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::RemoveRule(const CString& value)
{
// initialize the token with the rule list and with the default ; as separator
PSS_Tokenizer token(GetRuleList());
// if the rule was removed successfully, update the rule list
if (token.RemoveToken(value))
SetRuleList(token.GetString());
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetRuleAt(std::size_t index)
{
// initialize the token with the rule list and with the default ; as separator
PSS_Tokenizer token(GetRuleList());
CString value;
// get the token at index
if (token.GetTokenAt(index, value))
return value;
return _T("");
}
//---------------------------------------------------------------------------
std::size_t PSS_ProcedureSymbolBP::GetRuleCount() const
{
// initialize the token with the rule list and with the default ; as separator
PSS_Tokenizer token(GetRuleList());
return token.GetTokenCount();
}
//---------------------------------------------------------------------------
BOOL PSS_ProcedureSymbolBP::ContainsRule(const CString& ruleName) const
{
const int ruleCount = m_Rules.GetRulesCount();
for (int i = 0; i < ruleCount; ++i)
if (m_Rules.GetRuleName(i) == ruleName)
return TRUE;
return FALSE;
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::CheckRulesSync(CStringArray& rulesList)
{
CODModel* pModel = GetRootModel();
if (pModel)
return;
if (m_Rules.GetRulesCount() > 0)
{
PSS_ProcessGraphModelMdlBP* pOwnerModel = dynamic_cast<PSS_ProcessGraphModelMdlBP*>(GetOwnerModel());
PSS_LogicalRulesEntity* pMainRule = NULL;
if (pOwnerModel)
pMainRule = pOwnerModel->GetMainLogicalRules();
if (!pMainRule)
return;
const int ruleCount = m_Rules.GetRulesCount();
for (int i = 0; i < ruleCount; ++i)
{
const CString safeName = GetRuleNameByGUID(pMainRule, m_Rules.GetRuleGUID(i));
if (safeName.IsEmpty())
rulesList.Add(m_Rules.GetRuleName(i));
}
}
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetTaskList() const
{
PSS_TaskListPropertiesBP* pProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST));
if (!pProps)
return _T("");
return pProps->GetTaskList();
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::SetTaskList(const CString& value)
{
PSS_TaskListPropertiesBP* pProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST));
if (pProps)
{
PSS_TaskListPropertiesBP props(*pProps);
props.SetTaskList(value);
SetProperty(&props);
}
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::TaskExist(const CString& value)
{
// initialize the token with the task list and with the default ; as separator
PSS_Tokenizer token(GetTaskList());
return token.TokenExist(value);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::AddTask(const CString& value)
{
// initialize the token with the task list and with the default ; as separator
PSS_Tokenizer token(GetTaskList());
// if the new task was added successfully, update the task list
if (token.AddUniqueToken(value))
{
// add the value to the history
CString key;
key.LoadString(IDS_ZS_BP_PROP_PROCEDURE_TSKLST_TITLE);
PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value);
// set the new task string
SetTaskList(token.GetString());
}
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::RemoveTask(const CString& value)
{
// initialize the token with the task list and with the default ; as separator
PSS_Tokenizer token(GetTaskList());
// if the new task was removed successfully, update the task list
if (token.RemoveToken(value))
SetTaskList(token.GetString());
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetTaskAt(std::size_t index)
{
// Initialize the token with the task list and with the default ; as separator
PSS_Tokenizer token(GetTaskList());
CString value;
// get the token at index
if (token.GetTokenAt(index, value))
return value;
return _T("");
}
//---------------------------------------------------------------------------
std::size_t PSS_ProcedureSymbolBP::GetTaskCount() const
{
// initialize the token with the task list and with the default ; as separator
PSS_Tokenizer token(GetTaskList());
return token.GetTokenCount();
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetDecisionList() const
{
PSS_DecisionListPropertiesBP* pProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST));
if (!pProps)
return _T("");
return pProps->GetDecisionList();
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::SetDecisionList(const CString& value)
{
PSS_DecisionListPropertiesBP* pProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST));
if (pProps)
{
PSS_DecisionListPropertiesBP props(*pProps);
props.SetDecisionList(value);
SetProperty(&props);
}
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::DecisionExist(const CString& value)
{
// initialize the token with the decision list and with the default ; as separator
PSS_Tokenizer token(GetDecisionList());
return token.TokenExist(value);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::AddDecision(const CString& value)
{
// initialize the token with the decision list and with the default ; as separator
PSS_Tokenizer token(GetDecisionList());
// if the new decision was added successfully, update the decision list
if (token.AddUniqueToken(value))
{
// add the value to the history
CString key;
key.LoadString(IDS_ZS_BP_PROP_PROCEDURE_DECLST_TITLE);
PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value);
// set the new decision string
SetDecisionList(token.GetString());
}
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::RemoveDecision(const CString& value)
{
// initialize the token with the decision list and with the default ; as separator
PSS_Tokenizer token(GetDecisionList());
// if the new decision was removed successfully, update the decision list
if (token.RemoveToken(value))
SetDecisionList(token.GetString());
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetDecisionAt(std::size_t index)
{
// initialize the token with the decision list and with the default ; as separator
PSS_Tokenizer token(GetDecisionList());
CString value;
// get the decision at index
if (token.GetTokenAt(index, value))
return value;
return _T("");
}
//---------------------------------------------------------------------------
std::size_t PSS_ProcedureSymbolBP::GetDecisionCount() const
{
// initialize the token with the decision list and with the default ; as separator
PSS_Tokenizer token(GetDecisionList());
return token.GetTokenCount();
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetRiskType(std::size_t index) const
{
PSS_Application* pApp = PSS_Application::Instance();
if (!pApp)
return _T("");
PSS_MainForm* pMainForm = pApp->GetMainForm();
if (!pMainForm)
return _T("");
PSS_RiskTypeContainer* pContainer = pMainForm->GetRiskTypeContainer();
if (!pContainer)
return _T("");
const int count = pContainer->GetElementCount();
const CString riskType = m_Risks.GetRiskType(index);
for (int i = 0; i < count; ++i)
if (riskType == pContainer->GetElementAt(i))
return m_Risks.GetRiskType(index);
return _T("");
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::Serialize(CArchive& ar)
{
PSS_Symbol::Serialize(ar);
// only if the object is serialized from or to a document
if (ar.m_pDocument)
{
// serialize the combinations
m_Combinations.Serialize(ar);
m_SimulationProperties.Serialize(ar);
PSS_BaseDocument* pDocument = dynamic_cast<PSS_BaseDocument*>(ar.m_pDocument);
// serialize the risks
if (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 27)
m_Risks.Serialize(ar);
// serialize the rules
if (ar.IsStoring())
m_Rules.Serialize(ar);
else
if (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 26)
m_Rules.Serialize(ar);
if (ar.IsStoring() || (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 19))
{
m_UnitProp.Serialize(ar);
m_CostProcedureProp.Serialize(ar);
}
else
{
TRACE("PSS_ProcedureSymbolBP::Serialize - Start read\n");
// transfer the properties to new format
PSS_CostPropertiesProcedureBP_Beta1* pCostProps =
static_cast<PSS_CostPropertiesProcedureBP_Beta1*>(GetProperty(ZS_BP_PROP_PROCEDURE_COST));
if (pCostProps)
{
SetMultiplier(pCostProps->GetMultiplier());
SetProcessingTime(pCostProps->GetProcessingTime());
SetUnitaryCost(pCostProps->GetUnitaryCost());
}
PSS_UnitPropertiesBP_Beta1* pUnitProps = static_cast<PSS_UnitPropertiesBP_Beta1*>(GetProperty(ZS_BP_PROP_UNIT));
if (pUnitProps)
{
SetUnitName(pUnitProps->GetUnitName());
SetUnitCost(pUnitProps->GetUnitCost());
}
// set the master if only one deliverable was found for the combination
const int count = GetCombinationCount();
for (int i = 0; i < count; ++i)
{
const CString deliverables = GetCombinationDeliverables(i);
// if no separator, only one deliverable, so set this deliverable as the master one
if (deliverables.Find(';') == -1)
SetCombinationMaster(i, deliverables);
}
TRACE("PSS_ProcedureSymbolBP::Serialize - End read\n");
}
}
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnSymbolNameChanged(CODComponent& comp, const CString& oldName)
{
PSS_LinkSymbol* pSymbol = dynamic_cast<PSS_LinkSymbol*>(&comp);
if (pSymbol)
ReplaceDeliverable(oldName, pSymbol->GetSymbolName());
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::OnPostPropertyChanged(PSS_Property& prop, PSS_Properties::IPropertySet& props, bool& refresh)
{
// only local symbol may access to properties
if (!IsLocal())
return false;
bool result = false;
if (prop.GetCategoryID() >= ZS_BP_PROP_COMBINATION &&
prop.GetCategoryID() <= ZS_BP_PROP_COMBINATION + GetCombinationCount())
{
const int i = prop.GetCategoryID() - ZS_BP_PROP_COMBINATION;
switch (prop.GetItemID() - (i * g_MaxCombinationListSize))
{
case M_Combination_Deliverables_ID:
{
const float maxPercent =
GetMaxActivationPerc(GetCombinationMaster(prop.GetCategoryID() - ZS_BP_PROP_COMBINATION));
PSS_Properties::IPropertyIterator it(&props);
bool found = false;
// set the value to the property
for (PSS_Property* pProp = it.GetFirst(); pProp && !found; pProp = it.GetNext())
{
if (!pProp || ((pProp->GetCategoryID() - ZS_BP_PROP_COMBINATION) != i))
continue;
if (pProp->GetItemID() - (i * g_MaxCombinationListSize) == M_Combination_Activation_Perc_ID)
{
pProp->SetValueFloat(maxPercent);
found = true;
}
}
// change the return value if found
if (found)
result = true;
break;
}
default:
break;
}
}
else
if (prop.GetCategoryID() == ZS_BP_PROP_UNIT && prop.GetItemID() == M_Unit_Name_ID)
{
PSS_Properties::IPropertyIterator it(&props);
CString guid;
// iterate through the properties and change the unit cost to the property value
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_GUID_ID)
{
guid = pProp->GetValueString();
break;
}
if (!guid.IsEmpty())
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_Cost_ID)
{
bool error;
float unitCost = RetrieveUnitCost(guid, error);
if (!error)
{
pProp->SetValueFloat(unitCost);
result = true;
}
break;
}
}
else
if (prop.GetCategoryID() == ZS_BP_PROP_RULELIST)
{
// change the return value to reload the properties. Need to reload since the rule list has an empty rule.
// If the user fills it, need to enable a new empty one. And if the user remove one rule, need also to
// disable one from the property list
PSS_Properties::IPropertyIterator it(&props);
std::size_t counterEnableEmpty = 0;
// iterate through the properties and change their enabled flag. To change it, need to check if it is a new
// property that need to be enabled or not, then need to ensure that only an empty property is enable
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_RULELIST)
{
// if the string is not empty, set its enabled flag to true
if (!pProp->GetValueString().IsEmpty())
pProp->SetEnabled(true);
// if the string is empty, check if its enabled flag is set and add it to the counter.
// Enable or disable it according to if the counter is equal or not to 1
if (pProp->GetValueString().IsEmpty())
{
if (pProp->GetEnabled())
++counterEnableEmpty;
else
// if not at least one empty element
if (counterEnableEmpty < 1)
{
pProp->SetEnabled(true);
++counterEnableEmpty;
}
// if the counter is greater than 1, need to disable the empty element
if (counterEnableEmpty > 1)
{
--counterEnableEmpty;
pProp->SetEnabled(false);
}
}
}
result = true;
}
else
if (prop.GetCategoryID() == ZS_BP_PROP_TASKLIST)
{
// change the return value to reload the properties. Need to reload since the rule list has an empty task.
// If the user fills it, need to enable a new empty one. And if the user remove one task, need also to
// disable one from the property list
PSS_Properties::IPropertyIterator it(&props);
std::size_t counterEnableEmpty = 0;
// iterate through the properties and change their enabled flag. To change it, need to check if it is a new
// property that need to be enabled or not, then need to ensure that only an empty property is enable
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_TASKLIST)
{
// if the string is not empty, set the enabled flag to true
if (!pProp->GetValueString().IsEmpty())
pProp->SetEnabled(true);
// if the string is empty, check if its enabled flag is set and add it to the counter.
// Enable or disable it according to if the counter is equal or not to 1
if (pProp->GetValueString().IsEmpty())
{
if (pProp->GetEnabled())
++counterEnableEmpty;
else
// if not at least one empty element
if (counterEnableEmpty < 1)
{
pProp->SetEnabled(true);
++counterEnableEmpty;
}
// if the counter is greater than 1, need to disable the empty element
if (counterEnableEmpty > 1)
{
--counterEnableEmpty;
pProp->SetEnabled(false);
}
}
}
result = true;
}
else
if (prop.GetCategoryID() == ZS_BP_PROP_DECISIONLIST)
{
// change the return value to reload the properties. Need to reload since the decision list has an empty decision.
// If the user fills it, need to enable a new empty one. And if the user remove one decision, need also to
// disable one from the property list
PSS_Properties::IPropertyIterator it(&props);
std::size_t counterEnableEmpty = 0;
// iterate through the properties and change their enabled flag. To change it, need to check if it is a new
// property that need to be enabled or not, then need to ensure that only an empty property is enable
for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext())
if (pProp->GetCategoryID() == ZS_BP_PROP_DECISIONLIST)
{
// if the string is not empty, set its enabled flag to true
if (!pProp->GetValueString().IsEmpty())
pProp->SetEnabled(true);
// if the string is empty, check if its enabled flag is set and add it to the counter.
// Enable or disable it according to if the counter is equal or not to 1
if (pProp->GetValueString().IsEmpty())
{
if (pProp->GetEnabled() == true)
++counterEnableEmpty;
else
// if not at least one empty element
if (counterEnableEmpty < 1)
{
pProp->SetEnabled(true);
++counterEnableEmpty;
}
// if the counter is greater than 1, need to disable the empty element
if (counterEnableEmpty > 1)
{
--counterEnableEmpty;
pProp->SetEnabled(false);
}
}
}
result = true;
}
if (!result)
return PSS_Symbol::OnPostPropertyChanged(prop, props, refresh);
return result;
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::OnDropInternalPropertyItem(PSS_Property& srcProperty,
PSS_Property& dstProperty,
bool top2Down,
PSS_Properties::IPropertySet& props)
{
bool result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_TASKLIST);
if (result)
return true;
result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_RULELIST);
if (result)
return true;
result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_RULES);
if (result)
{
const int srcIndex = (srcProperty.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize;
const int dstIndex = (dstProperty.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize;
const CString srcRuleName = m_Rules.GetRuleName(srcIndex);
const CString srcRuleDesc = m_Rules.GetRuleDescription(srcIndex);
const CString srcRuleGUID = m_Rules.GetRuleGUID(srcIndex);
const CString dstRuleName = m_Rules.GetRuleName(dstIndex);
const CString dstRuleDesc = m_Rules.GetRuleDescription(dstIndex);
const CString dstRuleGUID = m_Rules.GetRuleGUID(dstIndex);
m_Rules.SetRuleName(srcIndex, dstRuleName);
m_Rules.SetRuleDescription(srcIndex, dstRuleDesc);
m_Rules.SetRuleGUID(srcIndex, dstRuleGUID);
m_Rules.SetRuleName(dstIndex, srcRuleName);
m_Rules.SetRuleDescription(dstIndex, srcRuleDesc);
m_Rules.SetRuleGUID(dstIndex, srcRuleGUID);
return true;
}
// otherwise, do it for decisions
return ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_DECISIONLIST);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::OnFillDefaultAttributes(PSS_PropertyAttributes* pAttributes)
{
if (!pAttributes)
return false;
PSS_PropertyAttributes& attributes = PSS_ModelGlobal::GetGlobalPropertyAttributes(GetObjectTypeID());
// if global attributes were defined, copy them
if (attributes.GetAttributeCount() > 0)
*pAttributes = attributes;
else
{
// add the reference number
pAttributes->AddAttribute(ZS_BP_PROP_BASIC, M_Symbol_Number_ID);
// add the unit name
pAttributes->AddAttribute(ZS_BP_PROP_UNIT, M_Unit_Name_ID);
// no item labels
pAttributes->SetShowTitleText(false);
}
return PSS_Symbol::OnFillDefaultAttributes(pAttributes);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::OnChangeAttributes(PSS_PropertyAttributes* pAttributes)
{
return PSS_Symbol::OnChangeAttributes(pAttributes);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnConnect(CODConnection* pConnection)
{
PSS_Symbol::OnConnect(pConnection);
CheckInitialCombination();
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnDisconnect(CODConnection* pConnection)
{
PSS_Symbol::OnDisconnect(pConnection);
CheckInitialCombination();
}
//---------------------------------------------------------------------------
BOOL PSS_ProcedureSymbolBP::OnConnectionMove(CODConnection* pConnection)
{
return PSS_Symbol::OnConnectionMove(pConnection);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnLinkDisconnect(CODLinkComponent* pLink)
{
PSS_LinkSymbol* pLinkSymbol = dynamic_cast<PSS_LinkSymbol*>(pLink);
if (pLinkSymbol)
DeleteDeliverableFromAllCombinations(pLinkSymbol->GetSymbolName());
}
//---------------------------------------------------------------------------
BOOL PSS_ProcedureSymbolBP::OnDoubleClick()
{
return FALSE;
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnUpdate(PSS_Subject* pSubject, PSS_ObserverMsg* pMsg)
{
PSS_Symbol::OnUpdate(pSubject, pMsg);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnDraw(CDC* pDC)
{
PSS_Symbol::OnDraw(pDC);
}
//---------------------------------------------------------------------------
bool PSS_ProcedureSymbolBP::OnToolTip(CString& toolTipText, const CPoint& point, PSS_ToolTip::IEToolTipMode mode)
{
toolTipText.Format(IDS_FS_BPPROCEDURE_TOOLTIP,
(const char*)GetSymbolName(),
(const char*)GetSymbolComment(),
(const char*)GetSymbolReferenceNumberStr());
if (mode == PSS_Symbol::IE_TT_Design)
{
// todo -cFeature -oJean: need to implement the result of the control checking
}
return true;
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::AdjustElementPosition()
{
PSS_Symbol::AdjustElementPosition();
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::CheckInitialCombination()
{
// check if only one combination. If it's the case, set all deliverables to the combination
if (GetCombinationCount() == 1)
{
// get all deliverables
CString enteringDeliverables;
GetEnteringUpDeliverable(enteringDeliverables);
// set it
SetCombinationDeliverables(0, enteringDeliverables);
// if no entering deliverables, remove the master
if (enteringDeliverables.IsEmpty())
SetCombinationMaster(0, enteringDeliverables);
else
{
// if there is only one deliverable, it's the master
PSS_Tokenizer token(enteringDeliverables);
if (token.GetTokenCount() == 1)
{
CString value;
// get the token at index
if (token.GetTokenAt(0, value))
SetCombinationMaster(0, value);
}
}
SetCombinationActivationPerc(0, GetMaxActivationPerc(GetCombinationMaster(0)));
}
}
//---------------------------------------------------------------------------
float PSS_ProcedureSymbolBP::GetMaxActivationPerc(const CString& master)
{
if (master.IsEmpty())
return 0.0f;
double sum = 0;
double masterQuantity = 0;
CODEdgeArray edges;
// get all procedures entering up edges
if (GetEnteringUpDeliverable(edges) > 0)
{
const int edgeCount = edges.GetSize();
for (int i = 0; i < edgeCount; ++i)
{
IODEdge* pIEdge = edges.GetAt(i);
PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge);
// check if it's a local symbol
if (!pComp->IsLocal())
// get the local symbol
pComp = dynamic_cast<PSS_DeliverableLinkSymbolBP*>(pComp->GetLocalSymbol());
if (pComp)
{
// check if the component is the master
if (pComp->GetSymbolName() == master)
masterQuantity = (double)pComp->GetQuantity();
// iterate through combinations and check if the component is the combination master,
// add its quantity to the sum
const int combinationCount = GetCombinationCount();
for (int i = 0; i < combinationCount; ++i)
if (pComp->GetSymbolName() == GetCombinationMaster(i))
sum += (double)pComp->GetQuantity();
}
}
}
if (!sum)
return 0.0f;
return float(masterQuantity / sum);
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnAddNewCombination(PSS_Property& prop,
CString& value,
PSS_Properties::IPropertySet& props,
bool& refresh)
{
// add a new combination
if (AddNewCombination() >= 0)
{
// set the refresh flag to true
refresh = true;
SetModifiedFlag(TRUE);
}
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnDelCurrentCombination(PSS_Property& prop,
CString& value,
PSS_Properties::IPropertySet& props,
bool& refresh)
{
const int count = GetCombinationCount();
if (count <= 1)
{
// cannot delete all combinations
PSS_MsgBox mBox;
mBox.Show(IDS_CANNOTDELETE_ALLCOMBINATIONS, MB_OK);
return;
}
// otherwise, delete the currently selected combination
const int index = prop.GetCategoryID() - ZS_BP_PROP_COMBINATION;
if (DeleteCombination(index))
{
// set the refresh flag to true
refresh = true;
SetModifiedFlag(TRUE);
}
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnAddDeliverableCombination(PSS_Property& prop,
CString& value,
PSS_Properties::IPropertySet& props,
bool& refresh)
{}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnDelDeliverableCombination(PSS_Property& prop,
CString& value,
PSS_Properties::IPropertySet& props,
bool& refresh)
{}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnAddNewRisk(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh)
{
// sdd a new risk
if (AddNewRisk() >= 0)
{
// set the refresh flag to true
refresh = true;
SetModifiedFlag(TRUE);
}
}
//---------------------------------------------------------------------------
void PSS_ProcedureSymbolBP::OnDelCurrentRisk(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh)
{
const int count = GetRiskCount();
if (count <= 1)
{
// cannot delete all risks
PSS_MsgBox mBox;
mBox.Show(IDS_CANNOTDELETE_ALLRISKS, MB_OK);
return;
}
// otherwise, delete the currently selected risk
const int index = prop.GetCategoryID() - ZS_BP_PROP_RISK;
if (DeleteRisk(index))
{
// set the refresh flag to true
refresh = true;
SetModifiedFlag(TRUE);
}
}
//---------------------------------------------------------------------------
CString PSS_ProcedureSymbolBP::GetRuleNameByGUID(PSS_LogicalRulesEntity* pRule, const CString& ruleGUID)
{
if (!pRule)
return _T("");
if (pRule->GetGUID() == ruleGUID)
return pRule->GetEntityName();
if (pRule->ContainEntity())
{
const int count = pRule->GetEntityCount();
for (int i = 0; i < count; ++i)
{
PSS_LogicalRulesEntity* pEntity = dynamic_cast<PSS_LogicalRulesEntity*>(pRule->GetEntityAt(i));
if (!pEntity)
continue;
const CString name = GetRuleNameByGUID(pEntity, ruleGUID);
if (!name.IsEmpty())
return name;
}
}
return _T("");
}
//---------------------------------------------------------------------------
| 40.514943 | 158 | 0.526679 |
cc6570a655cda878517b2a27b4e4526d8a979028 | 3,614 | cc | C++ | o3d/compiler/puritan/main.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | o3d/compiler/puritan/main.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | o3d/compiler/puritan/main.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | /*
* Copyright 2009, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This program demonstrates how to get test case information out of Puritan.
#include <iostream>
#include "test_gen.h"
#include "knobs.h"
static std::string name_of_size(Salem::Puritan::OutputInfo::ArgSize x) {
switch (x) {
case Salem::Puritan::OutputInfo::Float1:
return "float";
case Salem::Puritan::OutputInfo::Float2:
return "float2";
case Salem::Puritan::OutputInfo::Float4:
return "float4";
default:
break;
}
return "Impossible";
}
static std::string comma(bool * need_comma) {
if (*need_comma) {
return ", ";
} else {
*need_comma = true;
return "";
}
}
int main (int argc, char * const argv[]) {
int j = 0;
if (argc > 1) {
sscanf(argv[1], "%d", &j);
}
Salem::Puritan::Knobs options;
// Set up some options just the way we like
options.block_count.set(2, 3);
options.for_count.set(2, 3);
options.for_nesting.set(2, 3);
options.array_in_for_use.set(false);
options.seed.set(j);
Salem::Puritan::OutputInfo info;
// Build a test case
std::string test_case =
Salem::Puritan::generate(&info, options);
// Dump out the test information
std::cout << "(Seed " << options.seed.get() << "), "
<< "(Samplers (";
bool need_comma = false;
for (unsigned i = 0; i < info.n_samplers; i++) {
std::cout << comma(&need_comma) << "in" << i;
}
std::cout << ")),"
<< "(Uniforms (";
need_comma = false;
for (std::list <
std::pair <
Salem::Puritan::OutputInfo::ArgSize,
std::string > >::const_iterator
i = info.uniforms.begin();
i != info.uniforms.end();
i++) {
std::cout << comma(&need_comma)
<< name_of_size(i->first)
<< " "
<< i->second;
}
std::cout << ")), "
<< "(return struct {";
need_comma = false;
for (std::list <Salem::Puritan::OutputInfo::ArgSize>::const_iterator
i = info.returns.begin();
i != info.returns.end();
i++) {
std::cout << comma(&need_comma) << name_of_size(*i);
}
std::cout << "})\n";
std::cout << test_case;
return 1;
}
| 27.8 | 77 | 0.666574 |
cc678fb574dfe265aadd588c689b0d1efdba0f13 | 231 | hpp | C++ | Spiel/src/Graveyard/rendering/RenderBuffer.hpp | Ipotrick/CPP-2D-Game-Engine | 9cd87c369d813904d76668fe6153c7c4e8686023 | [
"MIT"
] | null | null | null | Spiel/src/Graveyard/rendering/RenderBuffer.hpp | Ipotrick/CPP-2D-Game-Engine | 9cd87c369d813904d76668fe6153c7c4e8686023 | [
"MIT"
] | null | null | null | Spiel/src/Graveyard/rendering/RenderBuffer.hpp | Ipotrick/CPP-2D-Game-Engine | 9cd87c369d813904d76668fe6153c7c4e8686023 | [
"MIT"
] | null | null | null | #pragma once
#include "Layer.hpp"
#include "Camera.hpp"
struct RenderBuffer {
std::vector<std::unique_ptr<RenderScript>> scriptDestructQueue;
bool resetTextureCache{ false };
Camera camera;
std::vector<RenderLayer> layers;
}; | 21 | 64 | 0.761905 |
cc68b57f65e3eda864d9e3ad0d92c028d9c624f7 | 1,900 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CMediaFileType.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CMediaFileType.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CMediaFileType.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos 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 "elastos/droid/media/CMediaFileType.h"
namespace Elastos {
namespace Droid {
namespace Media {
CAR_INTERFACE_IMPL(CMediaFileType, Object, IMediaFileType)
CAR_OBJECT_IMPL(CMediaFileType)
CMediaFileType::CMediaFileType()
: mFileType(0)
{
}
CMediaFileType::~CMediaFileType()
{
}
ECode CMediaFileType::constructor()
{
return NOERROR;
}
ECode CMediaFileType::constructor(
/* [in] */ Int32 fileType,
/* [in] */ const String& mimeType)
{
mFileType = fileType;
mMimeType = mimeType;
return NOERROR;
}
ECode CMediaFileType::SetFileType(
/* [in] */ Int32 result)
{
mFileType = result;
return NOERROR;
}
ECode CMediaFileType::SetMimeType(
/* [in] */ const String& result)
{
mMimeType = result;
return NOERROR;
}
ECode CMediaFileType::GetFileType(
/* [out] */ Int32* result)
{
VALIDATE_NOT_NULL(result);
*result = mFileType;
return NOERROR;
}
ECode CMediaFileType::GetMimeType(
/* [out] */ String* result)
{
VALIDATE_NOT_NULL(result);
*result = mMimeType;
return NOERROR;
}
} // namespace Media
} // namepsace Droid
} // namespace Elastos
| 22.352941 | 75 | 0.645263 |
cc7097e3531cba3b13fb012eca8cbc5cc6a126fa | 708 | cpp | C++ | CodeForces/Complete/700-799/791C-BearAndDifferentNames.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/700-799/791C-BearAndDifferentNames.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/700-799/791C-BearAndDifferentNames.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <iostream>
#include <vector>
int main(){
const int L = 26;
const int N = 100;
std::ios_base::sync_with_stdio(false);
std::vector<std::string> a(N);
for(long p = 0; p < N; p++){a[p] = ('A' + (p / L)); a[p] += ('a' + (p % L));}
int n, k; std::cin >> n >> k;
std::vector<bool> eff(n - k + 1, 0);
for(long p = 0; p < n - k + 1; p++){std::string s; std::cin >> s; eff[p] = (s == "YES");}
std::vector<std::string> v;
for(long p = 0; p < k - 1; p++){v.push_back(a[p]);}
for(long p = k - 1; p < n; p++){v.push_back(eff[p - k + 1] ? a[p] : v[p - k + 1]);}
for(long p = 0; p < n; p++){std::cout << v[p] << " ";}
std::cout << std::endl;
return 0;
}
| 29.5 | 93 | 0.457627 |
cc731400e0ed1b202dead5e6b892b09477c244ca | 2,843 | hpp | C++ | behavior_system/IBehavior.hpp | draghan/behavior_tree | e890c29f009e11e8120a861aa5515797a52d656a | [
"MIT"
] | 7 | 2018-08-27T20:31:21.000Z | 2021-11-22T05:57:18.000Z | behavior_system/IBehavior.hpp | draghan/behavior_tree | e890c29f009e11e8120a861aa5515797a52d656a | [
"MIT"
] | null | null | null | behavior_system/IBehavior.hpp | draghan/behavior_tree | e890c29f009e11e8120a861aa5515797a52d656a | [
"MIT"
] | null | null | null | /*
This file is distributed under MIT License.
Copyright (c) 2018 draghan
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.
*/
//
// Created by draghan on 2017-10-14.
//
#pragma once
#include <string>
#include <vector>
#ifndef __arm__
#include <ostream>
#endif
enum class BehaviorState: uint8_t
{
undefined,
success,
failure,
running
};
class IBehavior
{
public:
using ptr = IBehavior *;
using id_t = uint32_t;
const static id_t undefined_id;
#ifndef __arm__
// Decided to disable printing to the streams on ARM processors
// in order to keep some bytes of compiled result file.
// With stream library included, result files were unacceptable
// oversized for Cortex M.
void print_family(std::string indent, bool last, std::ostream &stream);
void introduce_yourself(std::ostream &stream);
#endif
id_t get_id() const;
void set_id(id_t id);
bool add_child(ptr child);
size_t get_number_of_children() const;
ptr get_child(size_t index) const;
ptr get_last_child() const;
ptr get_parent() const;
explicit IBehavior(ptr parent, uint32_t id = 0);
IBehavior(const IBehavior&) = delete;
void operator=(const IBehavior&) = delete;
virtual ~IBehavior() = default;
BehaviorState evaluate();
BehaviorState get_status() const;
bool operator==(const IBehavior &);
virtual std::string get_glyph() const;
virtual bool can_have_children() const = 0;
protected:
std::vector<ptr> children;
ptr parent;
id_t id;
BehaviorState status;
id_t last_evaluated_child;
ptr get_child_for_eval(id_t id);
id_t get_last_evaluated_child_id();
virtual BehaviorState internal_evaluate(id_t id_child_for_evaluation) = 0;
BehaviorState internal_evaluate();
};
| 26.820755 | 82 | 0.719311 |
cc733829dd43fe861230df5866fe3587e4342e0a | 1,670 | hh | C++ | src/cpu/vpred/fcmvp.hh | surya00060/ece-565-course-project | cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd | [
"BSD-3-Clause"
] | null | null | null | src/cpu/vpred/fcmvp.hh | surya00060/ece-565-course-project | cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd | [
"BSD-3-Clause"
] | null | null | null | src/cpu/vpred/fcmvp.hh | surya00060/ece-565-course-project | cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd | [
"BSD-3-Clause"
] | 1 | 2020-12-15T20:53:56.000Z | 2020-12-15T20:53:56.000Z | #ifndef __CPU_VPRED_LVP_PRED_HH__
#define __CPU_VPRED_LVP_PRED_HH__
#include "cpu/vpred/vpred_unit.hh"
#include <vector>
#include "base/statistics.hh"
#include "base/sat_counter.hh"
#include "base/types.hh"
#include "cpu/inst_seq.hh"
#include "cpu/static_inst.hh"
#include "params/FCMVP.hh"
#include "sim/sim_object.hh"
class FCMVP : public VPredUnit
{
public:
FCMVP(const FCMVPParams *params);
bool lookup(Addr inst_addr, RegVal &value);
float getconf(Addr inst_addr, RegVal &value);
void updateTable(Addr inst_addr, bool isValuePredicted, bool isValueTaken, RegVal &trueValue);
static inline RegVal computeHash(RegVal data)
{
RegVal hash = 0;
RegVal bits = 0;
for (int i = 0; i < 8; ++i)
{
bits = ((1 << 8) - 1) & (data >> (8*i));
hash = hash ^ bits;
}
return hash;
}
private:
/*Number of history values to track*/
const unsigned historyLength;
/** Number of History Table Entries*/
const unsigned historyTableSize;
/** Number of History Table Entries*/
const unsigned valuePredictorTableSize;
/** Number of bits to control*/
const unsigned ctrBits;
/*Array of counters*/
std::vector<SatCounter> classificationTable;
/*Array of value predictions*/
std::vector<std::vector<RegVal>> valueHistoryTable;
std::vector<RegVal> valuePredictionTable;
/*Array of tag value*/
std::vector<Addr> tagTable;
};
#endif // __CPU_VPRED_LVP_PRED_HH__
| 25.30303 | 102 | 0.601796 |
cc73743ace3ec7c1299f05c623eb9e78e65b18a8 | 2,732 | hpp | C++ | test/estest/graphics/LibPngDecoderTest.hpp | eaglesakura/protoground | 2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6 | [
"MIT"
] | null | null | null | test/estest/graphics/LibPngDecoderTest.hpp | eaglesakura/protoground | 2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6 | [
"MIT"
] | 1 | 2016-10-25T02:09:00.000Z | 2016-11-10T02:07:59.000Z | test/estest/graphics/LibPngDecoderTest.hpp | eaglesakura/protoground | 2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6 | [
"MIT"
] | null | null | null | #pragma once
#include "estest/protoground-test.hpp"
#include "es/graphics/image/png/PngFileDecoder.h"
#include "es/graphics/image/IImageDecodeCallback.hpp"
namespace es {
namespace test {
namespace internal {
std::shared_ptr<IImageDecodeCallback> newSimpleImageListener() {
class PngImageListener : public IImageDecodeCallback {
ImageInfo info;
bool infoReceived = false;
int readedLines = 0;
public:
PngImageListener() { }
virtual ~PngImageListener() { }
/**
* 画像情報を読み込んだ
*/
virtual void onImageInfoDecoded(const ImageInfo *info) {
ASSERT_NE(info, nullptr);
ASSERT_TRUE(info->srcWidth > 0);
ASSERT_TRUE(info->srcHeight > 0);
this->info = *info;
infoReceived = true;
}
/**
* 画像を指定行読み込んだ
*
* 引数lineは使いまわされる可能性があるため、内部的にテクスチャコピー等を行うこと。
*/
virtual void onImageLineDecoded(const ImageInfo *info, const unsafe_array<uint8_t> pixels, const unsigned height) {
ASSERT_TRUE(pixels.length > 0);
ASSERT_TRUE(height > 0);
ASSERT_TRUE(infoReceived);
readedLines += height;
ASSERT_TRUE(readedLines <= (int) info->srcHeight);
}
/**
* 画像のデコードをキャンセルする場合はtrue
*/
virtual bool isImageDecodeCancel() {
return false;
}
/**
* デコードが完了した
*/
virtual void onImageDecodeFinished(const ImageInfo *info, const ImageDecodeResult_e result) {
ASSERT_EQ(result, ImageDecodeResult_Success);
ASSERT_EQ(info->srcHeight, readedLines);
}
};
sp<IImageDecodeCallback> result(new PngImageListener());
return result;
}
}
/**
* 正方形PowerOfTwo PNG画像を読み込む
*/
TEST(LibPngDecoderTest, DecodeSquarePot_dstRGB8) {
sp<IAsset> asset = IProcessContext::getInstance()->getAssetManager()->load("png/square-pot.png");
ASSERT_TRUE((bool) asset);
PngFileDecoder decoder;
decoder.setOnceReadHeight(25);
decoder.setConvertPixelFormat(PixelFormat_RGB888);
ASSERT_TRUE(decoder.load(asset, internal::newSimpleImageListener()));
}
/**
* 正方形PowerOfTwo PNG画像を読み込む
*/
TEST(LibPngDecoderTest, DecodeSquarePot_dstRGBA8) {
sp<IAsset> asset = IProcessContext::getInstance()->getAssetManager()->load("png/square-pot.png");
ASSERT_TRUE((bool) asset);
PngFileDecoder decoder;
decoder.setOnceReadHeight(25);
decoder.setConvertPixelFormat(PixelFormat_RGBA8888);
ASSERT_TRUE(decoder.load(asset, internal::newSimpleImageListener()));
}
}
} | 27.877551 | 124 | 0.61896 |
cc7424858b6c72272f73481c941b9e55475c869c | 1,032 | cpp | C++ | uva/507.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | uva/507.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | uva/507.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 1 | 2020-08-13T18:07:35.000Z | 2020-08-13T18:07:35.000Z | #include <bits/stdc++.h>
using namespace std;
vector<int> v;
int main(){
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int t, co = 0, len, a;
for(scanf("%d", &t); t--; ){
scanf("%d", &len);
for(int i = 0; i < len - 1; scanf("%d", &a), v.push_back(a), i++);
int g = v[0], m = v[0], sum = v[0];
pair<int, int> p = make_pair(1, 2);
pair<int, int> q = make_pair(1, 2);
for(int i = 1; i < v.size(); i++){
if(sum + v[i] >= v[i]){
sum += v[i];
q.second = i + 2;
}
else{
sum = v[i];
q = make_pair(i + 1, i + 2);
}
if(sum >= g){
if(sum > g) p = make_pair(q.first, q.second);
else if(sum == g && (q.second - q.first) > (p.second - p.first)) p = make_pair(q.first, q.second);
g = sum;
}
}
if(g > 0) printf("The nicest part of route %d is between stops %d and %d\n", ++co, p.first, p.second, g);
else printf("Route %d has no nice parts\n", ++co);
v.clear();
}
return 0;
}
| 29.485714 | 109 | 0.471899 |
cc789143c50ca56072bd50c685f65f77ede4ed74 | 413 | cpp | C++ | Projects/AnalizadorLexico/AnalizadorLexico/Est.cpp | JoaquinRMtz/Escuela | bdd0e902c1a836880c018845b7cac2cccbaa1bed | [
"MIT"
] | null | null | null | Projects/AnalizadorLexico/AnalizadorLexico/Est.cpp | JoaquinRMtz/Escuela | bdd0e902c1a836880c018845b7cac2cccbaa1bed | [
"MIT"
] | null | null | null | Projects/AnalizadorLexico/AnalizadorLexico/Est.cpp | JoaquinRMtz/Escuela | bdd0e902c1a836880c018845b7cac2cccbaa1bed | [
"MIT"
] | null | null | null | #include "Est.h"
Est::Est(Id^ i, Expr^ x)
{
id = i; expr = x;
if (comprobar(id->tipo, expr->tipo) == nullptr) error("Error de tipo");
}
Tipo^ Est::comprobar(Tipo^ p1, Tipo^ p2){
if (Tipo::numerico(p1) && Tipo::numerico(p2))return p2;
else if (p1 == Tipo::Bool && p2 == Tipo::Bool) return p2;
else return nullptr;
}
void Est::gen(int b, int a){
emitir(id->toString() + " = " + expr->gen()->toString());
} | 22.944444 | 72 | 0.598063 |
cc79f3ef2c2041b41a4897dd9196dab1851b8bfb | 6,268 | hpp | C++ | cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_REV_MAT_FUNCTOR_ODE_SYSTEM_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_ODE_SYSTEM_HPP
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/arr/fun/value_of.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace stan {
namespace math {
/**
* Internal representation of an ODE model object which provides
* convenient Jacobian functions to obtain gradients wrt to states
* and parameters. Can be used to provide analytic Jacobians via
* partial template specialisation.
*
* @tparam F type of functor for the base ode system.
*/
template <typename F>
class ode_system {
private:
const F& f_;
const std::vector<double> theta_;
const std::vector<double>& x_;
const std::vector<int>& x_int_;
std::ostream* msgs_;
std::string error_msg(size_t y_size, size_t dy_dt_size) const {
std::stringstream msg;
msg << "ode_system: size of state vector y (" << y_size << ")"
<< " and derivative vector dy_dt (" << dy_dt_size << ")"
<< " in the ODE functor do not match in size.";
return msg.str();
}
public:
/**
* Construct an ODE model with the specified base ODE system,
* parameters, data, and a message stream.
*
* @param[in] f the base ODE system functor.
* @param[in] theta parameters of the ode.
* @param[in] x real data.
* @param[in] x_int integer data.
* @param[in] msgs stream to which messages are printed.
*/
ode_system(const F& f, const std::vector<double> theta,
const std::vector<double>& x, const std::vector<int>& x_int,
std::ostream* msgs)
: f_(f), theta_(theta), x_(x), x_int_(x_int), msgs_(msgs) { }
/**
* Calculate the RHS of the ODE
*
* @param[in] t time.
* @param[in] y state of the ode system at time t.
* @param[out] dy_dt ODE RHS
*/
template <typename Derived1>
inline void operator()(double t, const std::vector<double>& y,
Eigen::MatrixBase<Derived1>& dy_dt) const {
const std::vector<double> dy_dt_vec = f_(t, y, theta_, x_, x_int_,
msgs_);
if (unlikely(y.size() != dy_dt_vec.size()))
throw std::runtime_error(error_msg(y.size(), dy_dt_vec.size()));
dy_dt = Eigen::Map<const Eigen::VectorXd>(&dy_dt_vec[0], y.size());
}
/**
* Calculate the Jacobian of the ODE RHS wrt to states y. The
* function expects the output objects to have correct sizes,
* i.e. dy_dt must be length N and Jy a NxN matrix (N states).
*
* @param[in] t time.
* @param[in] y state of the ode system at time t.
* @param[out] dy_dt ODE RHS
* @param[out] Jy Jacobian of ODE RHS wrt to y.
*/
template <typename Derived1, typename Derived2>
inline void jacobian(double t, const std::vector<double>& y,
Eigen::MatrixBase<Derived1>& dy_dt,
Eigen::MatrixBase<Derived2>& Jy) const {
using Eigen::Matrix;
using Eigen::Map;
using Eigen::RowVectorXd;
using std::vector;
vector<double> grad(y.size());
Map<RowVectorXd> grad_eig(&grad[0], y.size());
try {
start_nested();
vector<var> y_var(y.begin(), y.end());
vector<var> dy_dt_var = f_(t, y_var, theta_, x_, x_int_, msgs_);
if (unlikely(y.size() != dy_dt_var.size()))
throw std::runtime_error(error_msg(y.size(), dy_dt_var.size()));
for (size_t i = 0; i < dy_dt_var.size(); ++i) {
dy_dt(i) = dy_dt_var[i].val();
set_zero_all_adjoints_nested();
dy_dt_var[i].grad(y_var, grad);
Jy.row(i) = grad_eig;
}
} catch (const std::exception& e) {
recover_memory_nested();
throw;
}
recover_memory_nested();
}
/**
* Calculate the Jacobian of the ODE RHS wrt to states y and
* parameters theta. The function expects the output objects to
* have correct sizes, i.e. dy_dt must be length N, Jy a NxN
* matrix and Jtheta a NxM matrix (N states, M parameters).
*
* @param[in] t time.
* @param[in] y state of the ode system at time t.
* @param[out] dy_dt ODE RHS
* @param[out] Jy Jacobian of ODE RHS wrt to y.
* @param[out] Jtheta Jacobian of ODE RHS wrt to theta.
*/
template <typename Derived1, typename Derived2>
inline void jacobian(double t, const std::vector<double>& y,
Eigen::MatrixBase<Derived1>& dy_dt,
Eigen::MatrixBase<Derived2>& Jy,
Eigen::MatrixBase<Derived2>& Jtheta) const {
using Eigen::Dynamic;
using Eigen::Map;
using Eigen::Matrix;
using Eigen::RowVectorXd;
using std::vector;
vector<double> grad(y.size() + theta_.size());
Map<RowVectorXd> grad_eig(&grad[0], y.size() + theta_.size());
try {
start_nested();
vector<var> y_var(y.begin(), y.end());
vector<var> theta_var(theta_.begin(), theta_.end());
vector<var> z_var;
z_var.reserve(y.size() + theta_.size());
z_var.insert(z_var.end(), y_var.begin(), y_var.end());
z_var.insert(z_var.end(), theta_var.begin(), theta_var.end());
vector<var> dy_dt_var = f_(t, y_var, theta_var, x_, x_int_, msgs_);
if (unlikely(y.size() != dy_dt_var.size()))
throw std::runtime_error(error_msg(y.size(), dy_dt_var.size()));
for (size_t i = 0; i < dy_dt_var.size(); ++i) {
dy_dt(i) = dy_dt_var[i].val();
set_zero_all_adjoints_nested();
dy_dt_var[i].grad(z_var, grad);
Jy.row(i) = grad_eig.leftCols(y.size());
Jtheta.row(i) = grad_eig.rightCols(theta_.size());
}
} catch (const std::exception& e) {
recover_memory_nested();
throw;
}
recover_memory_nested();
}
};
}
}
#endif
| 38.219512 | 77 | 0.565571 |
cc7fbe6860a7b75ff0ae6877e7a2427095c20a03 | 3,570 | hpp | C++ | Source/GameComponents/PhysicsObject.hpp | storm20200/WaterEngine | 537910bc03e6d4016c9b22cf616d25afe40f77af | [
"MIT"
] | null | null | null | Source/GameComponents/PhysicsObject.hpp | storm20200/WaterEngine | 537910bc03e6d4016c9b22cf616d25afe40f77af | [
"MIT"
] | 2 | 2015-03-17T01:32:10.000Z | 2015-03-19T18:58:28.000Z | Source/GameComponents/PhysicsObject.hpp | storm20200/WaterEngine | 537910bc03e6d4016c9b22cf616d25afe40f77af | [
"MIT"
] | null | null | null | #if !defined WATER_PHYSICS_OBJECT_INCLUDED
#define WATER_PHYSICS_OBJECT_INCLUDED
// Engine headers.
#include <GameComponents/Collider.hpp>
#include <GameComponents/GameObject.hpp>
// Engine namespace.
namespace water
{
/// <summary>
/// An abstract class for physics objects. Any object which the physics system manages must inherit from this class.
/// PhysicsObject's can be added to a GameState's collection of managed objects which will be given to the physics
/// system every physicUpdate(), this will apply collision detection as well as other features of the system.
/// </summary>
class PhysicsObject : public GameObject
{
public:
///////////////////////////////////
/// Constructors and destructor ///
///////////////////////////////////
PhysicsObject() = default;
PhysicsObject (const PhysicsObject& copy) = default;
PhysicsObject& operator= (const PhysicsObject& copy) = default;
PhysicsObject (PhysicsObject&& move);
PhysicsObject& operator= (PhysicsObject&& move);
// Ensure destructor is virtual.
virtual ~PhysicsObject() override {}
/////////////////
/// Collision ///
/////////////////
/// <summary>
/// This function is called every time two collision objects intersect. This will be called AFTER the objects have been moved
/// by the physics system and will be called on both objects.
/// </summary>
/// <param name="collision"> The object being collided with. </param>
virtual void onCollision (PhysicsObject* const collision) = 0;
/// <summary>
/// The function called on trigger objects when either another trigger object or a collision object intersects the trigger zone.
/// This will be called every frame until the object leaves.
/// </summary>
/// <param name="collision"> The object intersecting the trigger zone. </param>
virtual void onTrigger (PhysicsObject* const collision) = 0;
///////////////////////////
/// Getters and setters ///
///////////////////////////
/// <summary> Indicates whether the PhysicsObject is static or not. </summary>
bool isStatic() const { return m_isStatic; }
/// <summary>
/// Obtain a reference to the collider of the physics object. This contains information relating to how the physics
/// object should be handled by the engine.
/// </summary>
/// <returns> A reference to the collider. </returns>
const Collider& getCollider() const { return m_collider; }
/// <summary> Sets whether the PhysicsObject is static. If they're static they will not be moved by the physics system. </summary>
/// <param name="isStatic"> Whether it should be static. </param>
void setStatic (const bool isStatic) { m_isStatic = isStatic; }
protected:
///////////////////////////
/// Implementation data ///
///////////////////////////
Collider m_collider { }; //!< The collision information of the PhysicsObject.
bool m_isStatic { true }; //!< Determines whether collision should cause this object to move or not.
};
}
#endif
| 41.511628 | 142 | 0.557983 |
cc82da22e8b2c843ea0f15028e5f447aa29db572 | 49,995 | cpp | C++ | unalz-0.65/UnAlz.cpp | kippler/unalz | 457884d21962caa12085bfb6ec5bd12f3eb93c00 | [
"Zlib"
] | 1 | 2021-04-13T04:49:58.000Z | 2021-04-13T04:49:58.000Z | unalz-0.65/UnAlz.cpp | kippler/unalz | 457884d21962caa12085bfb6ec5bd12f3eb93c00 | [
"Zlib"
] | null | null | null | unalz-0.65/UnAlz.cpp | kippler/unalz | 457884d21962caa12085bfb6ec5bd12f3eb93c00 | [
"Zlib"
] | null | null | null |
#ifdef _WIN32
# include "zlib/zlib.h"
# include "bzip2/bzlib.h"
#else
# include <zlib.h>
# include <bzlib.h>
#endif
#include "UnAlz.h"
#ifdef _WIN32
# pragma warning( disable : 4996 ) // crt secure warning
#endif
// utime 함수 처리
#if defined(_WIN32) || defined(__CYGWIN__)
# include <time.h>
# include <sys/utime.h>
#endif
#ifdef __GNUC__
# include <time.h>
# include <utime.h>
#endif
// mkdir
#ifdef _WIN32
# include <direct.h>
#else
# include <sys/stat.h>
#endif
#ifdef _UNALZ_ICONV // code page support
# include <iconv.h>
#endif
#if defined(__linux__) || defined(__GLIBC__) || defined(__GNU__) || defined(__APPLE__)
# include <errno.h>
#endif
#if defined(__NetBSD__)
# include <sys/param.h> // __NetBSD_Version__
# include <errno.h> // iconv.h 때문에 필요
#endif
#ifdef _WIN32 // safe string 처리
# include <strsafe.h>
#endif
// ENDIAN 처리
#ifdef _WIN32 // (L)
# define swapint64(a) (UINT64) ( (((a)&0x00000000000000FFL) << 56) | (((a)&0x000000000000FF00L) << 40) | (((a)&0x0000000000FF0000L) << 24) | (((a)&0x00000000FF000000L) << 8) | (((a)&0x000000FF00000000L) >> 8) | (((a)&0x0000FF0000000000L) >> 24) | (((a)&0x00FF000000000000L) >> 40) | (((a)&0xFF00000000000000L) >> 56) )
#else // (LL)
# define swapint64(a) (UINT64) ( (((a)&0x00000000000000FFLL) << 56) | (((a)&0x000000000000FF00LL) << 40) | (((a)&0x0000000000FF0000LL) << 24) | (((a)&0x00000000FF000000LL) << 8) | (((a)&0x000000FF00000000LL) >> 8) | (((a)&0x0000FF0000000000LL) >> 24) | (((a)&0x00FF000000000000LL) >> 40) | (((a)&0xFF00000000000000LL) >> 56) )
#endif
#define swapint32(a) ((((a)&0xff)<<24)+(((a>>8)&0xff)<<16)+(((a>>16)&0xff)<<8)+(((a>>24)&0xff)))
#define swapint16(a) (((a)&0xff)<<8)+(((a>>8)&0xff))
typedef UINT16 (*_unalz_le16toh)(UINT16 a);
typedef UINT32 (*_unalz_le32toh)(UINT32 a);
typedef UINT64 (*_unalz_le64toh)(UINT64 a);
static _unalz_le16toh unalz_le16toh=NULL;
static _unalz_le32toh unalz_le32toh=NULL;
static _unalz_le64toh unalz_le64toh=NULL;
static UINT16 le16tole(UINT16 a){return a;}
static UINT32 le32tole(UINT32 a){return a;}
static UINT64 le64tole(UINT64 a){return a;}
static UINT16 le16tobe(UINT16 a){return swapint16(a);}
static UINT32 le32tobe(UINT32 a){return swapint32(a);}
static UINT64 le64tobe(UINT64 a){return swapint64(a);}
#ifndef MAX_PATH
# define MAX_PATH 260*6 // 그냥 .. 충분히..
#endif
#ifdef _WIN32
# define PATHSEP "\\"
# define PATHSEPC '\\'
#else
# define PATHSEP "/"
# define PATHSEPC '/'
#endif
static time_t dosTime2TimeT(UINT32 dostime) // from INFO-ZIP src
{
struct tm t;
t.tm_isdst = -1;
t.tm_sec = (((int)dostime) << 1) & 0x3e;
t.tm_min = (((int)dostime) >> 5) & 0x3f;
t.tm_hour = (((int)dostime) >> 11) & 0x1f;
t.tm_mday = (int)(dostime >> 16) & 0x1f;
t.tm_mon = ((int)(dostime >> 21) & 0x0f) - 1;
t.tm_year = ((int)(dostime >> 25) & 0x7f) + 80;
return mktime(&t);
}
static BOOL IsBigEndian(void)
{
union {
short a;
char b[2];
} endian;
endian.a = 0x0102;
if(endian.b[0] == 0x02) return FALSE;
return TRUE;
}
#ifdef _WIN32
# define safe_sprintf StringCbPrintfA
#else
# define safe_sprintf snprintf
#endif
// 64bit file handling support
#if (_FILE_OFFSET_BITS==64)
# define unalz_fseek fseeko
# define unalz_ftell ftello
#else
# define unalz_fseek fseek
# define unalz_ftell ftell
#endif
// error string table <- CUnAlz::ERR 의 번역
static const char* errorstrtable[]=
{
"no error", // ERR_NOERR
"general error", // ERR_GENERAL
"can't open archive file", // ERR_CANT_OPEN_FILE
"can't open dest file or path", // ERR_CANT_OPEN_DEST_FILE
// "can't create dest path", // ERR_CANT_CREATE_DEST_PATH
"corrupted file", // ERR_CORRUPTED_FILE
"not alz file", // ERR_NOT_ALZ_FILE
"can't read signature", // ERR_CANT_READ_SIG
"can't read file", // ERR_CANT_READ_FILE
"error at read header", // ERR_AT_READ_HEADER
"invalid filename length", // ERR_INVALID_FILENAME_LENGTH
"invalid extrafield length", // ERR_INVALID_EXTRAFIELD_LENGTH,
"can't read central directory structure head", // ERR_CANT_READ_CENTRAL_DIRECTORY_STRUCTURE_HEAD,
"invalid filename size", // ERR_INVALID_FILENAME_SIZE,
"invalid extrafield size", // ERR_INVALID_EXTRAFIELD_SIZE,
"invalid filecomment size", // ERR_INVALID_FILECOMMENT_SIZE,
"cant' read header", // ERR_CANT_READ_HEADER,
"memory allocation failed", // ERR_MEM_ALLOC_FAILED,
"file read error", // ERR_FILE_READ_ERROR,
"inflate failed", // ERR_INFLATE_FAILED,
"bzip2 decompress failed", // ERR_BZIP2_FAILED,
"invalid file CRC", // ERR_INVALID_FILE_CRC
"unknown compression method", // ERR_UNKNOWN_COMPRESSION_METHOD
"iconv-can't open iconv", // ERR_ICONV_CANT_OPEN,
"iconv-invalid multisequence of characters", // ERR_ICONV_INVALID_MULTISEQUENCE_OF_CHARACTERS,
"iconv-incomplete multibyte sequence", // ERR_ICONV_INCOMPLETE_MULTIBYTE_SEQUENCE,
"iconv-not enough space of buffer to convert", // ERR_ICONV_NOT_ENOUGH_SPACE_OF_BUFFER_TO_CONVERT,
"iconv-etc", // ERR_ICONV_ETC,
"password was not set", // ERR_PASSWD_NOT_SET,
"invalid password", // ERR_INVALID_PASSWD,
"user aborted",
};
////////////////////////////////////////////////////////////////////////////////////////////////////
/// ctor
/// @date 2004-03-06 오후 11:19:49
////////////////////////////////////////////////////////////////////////////////////////////////////
CUnAlz::CUnAlz()
{
memset(m_files, 0, sizeof(m_files));
m_nErr = ERR_NOERR;
m_posCur = m_fileList.end();//(FileList::iterator)NULL;
m_pFuncCallBack = NULL;
m_pCallbackParam = NULL;
m_bHalt = FALSE;
m_nFileCount = 0;
m_nCurFile = -1;
m_nVirtualFilePos = 0;
m_nCurFilePos = 0;
m_bIsEOF = FALSE;
m_bIsEncrypted = FALSE;
m_bIsDataDescr = FALSE;
m_bPipeMode = FALSE;
#ifdef _UNALZ_ICONV
#ifdef _UNALZ_UTF8
safe_strcpy(m_szToCodepage, "UTF-8",UNALZ_LEN_CODEPAGE) ; // 기본적으로 utf-8
#else
safe_strcpy(m_szToCodepage, "CP949",UNALZ_LEN_CODEPAGE) ; // 기본적으로 CP949
#endif // _UNALZ_UTF8
safe_strcpy(m_szFromCodepage, "CP949",UNALZ_LEN_CODEPAGE); // alz 는 949 만 지원
#endif // _UNALZ_ICONV
// check endian
if(unalz_le16toh==NULL)
{
if(IsBigEndian())
{
unalz_le16toh = le16tobe;
unalz_le32toh = le32tobe;
unalz_le64toh = le64tobe;
}
else
{
unalz_le16toh = le16tole;
unalz_le32toh = le32tole;
unalz_le64toh = le64tole;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// dtor
/// @date 2004-03-06 오후 11:19:52
////////////////////////////////////////////////////////////////////////////////////////////////////
CUnAlz::~CUnAlz()
{
Close();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// progress callback func setting
/// @date 2004-03-01 오전 6:02:05
////////////////////////////////////////////////////////////////////////////////////////////////////
void CUnAlz::SetCallback(_UnAlzCallback* pFunc, void* param)
{
m_pFuncCallBack = pFunc;
m_pCallbackParam = param;
}
#ifdef _WIN32
#if !defined(__GNUWIN32__) && !defined(__GNUC__)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 파일 열기
/// @param szPathName
/// @return
/// @date 2004-03-06 오후 11:03:59
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::Open(LPCWSTR szPathName)
{
char szPathNameA[MAX_PATH];
::WideCharToMultiByte(CP_ACP, 0, szPathName, -1, szPathNameA, MAX_PATH, NULL, NULL);
return Open(szPathNameA);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 대상 파일 세팅하기.
/// @param szFileName
/// @return
/// @date 2004-03-06 오후 11:06:20
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::SetCurrentFile(LPCWSTR szFileName)
{
char szFileNameA[MAX_PATH];
::WideCharToMultiByte(CP_ACP, 0, szFileName, -1, szFileNameA, MAX_PATH, NULL, NULL);
return SetCurrentFile(szFileNameA);
}
BOOL CUnAlz::IsFolder(LPCWSTR szPathName)
{
UINT32 dwRet;
dwRet = GetFileAttributesW(szPathName);
if(dwRet==0xffffffff) return FALSE;
if(dwRet & FILE_ATTRIBUTE_DIRECTORY) return TRUE;
return FALSE;
}
#endif // __GNUWIN32__
#endif // _WIN32
BOOL CUnAlz::Open(const char* szPathName)
{
if(FOpen(szPathName)==FALSE)
{
m_nErr = ERR_CANT_OPEN_FILE;
return FALSE;
}
BOOL bValidAlzHeader = FALSE;
// file 분석시작..
for(;;)
{
SIGNATURE sig;
BOOL ret;
if(FEof()) break;
//int pos = unalz_ftell(m_fp);
sig = ReadSignature();
if(sig==SIG_EOF)
{
break;
}
if(sig==SIG_ERROR)
{
if(bValidAlzHeader)
m_nErr = ERR_CORRUPTED_FILE; // 손상된 파일
else
m_nErr = ERR_NOT_ALZ_FILE; // alz 파일이 아니다.
return FALSE; // 깨진 파일..
}
if(sig==SIG_ALZ_FILE_HEADER)
{
ret = ReadAlzFileHeader();
bValidAlzHeader = TRUE; // alz 파일은 맞다.
}
else if(sig==SIG_LOCAL_FILE_HEADER) ret = ReadLocalFileheader();
else if(sig==SIG_CENTRAL_DIRECTORY_STRUCTURE) ret = ReadCentralDirectoryStructure();
else if(sig==SIG_ENDOF_CENTRAL_DIRECTORY_RECORD) ret = ReadEndofCentralDirectoryRecord();
else
{
// 미구현된 signature ? 깨진 파일 ?
ASSERT(0);
m_nErr = ERR_CORRUPTED_FILE;
return FALSE;
}
if(ret==FALSE)
{
return FALSE;
}
if(FEof()) break;
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 파일 닫기..
/// @return
/// @date 2004-03-06 오후 11:04:21
////////////////////////////////////////////////////////////////////////////////////////////////////
void CUnAlz::Close()
{
FClose();
// 목록 날리기..
FileList::iterator i;
for(i=m_fileList.begin(); i<m_fileList.end(); i++)
{
i->Clear();
}
m_posCur = m_fileList.end();//(FileList::iterator)NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// FILE 내의 SIGNATURE 읽기
/// @return
/// @date 2004-03-06 오후 11:04:47
////////////////////////////////////////////////////////////////////////////////////////////////////
CUnAlz::SIGNATURE CUnAlz::ReadSignature()
{
UINT32 dwSig;
if(FRead(&dwSig, sizeof(dwSig))==FALSE)
{
if(FEof())
return SIG_EOF;
m_nErr = ERR_CANT_READ_SIG;
return SIG_ERROR;
}
return (SIGNATURE)unalz_le32toh(dwSig); // little to host;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// ALZ HEADER SIGNATURE 읽기
/// @return
/// @date 2004-03-06 오후 11:05:11
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::ReadAlzFileHeader()
{
SAlzHeader header;
if(FRead(&header, sizeof(header))==FALSE)
{
ASSERT(0);
m_nErr = ERR_CANT_READ_FILE;
return FALSE;
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 각각의 파일 헤더 읽기
/// @return
/// @date 2004-03-06 오후 11:05:18
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::ReadLocalFileheader()
{
SAlzLocalFileHeader zipHeader;
int ret;
ret = FRead(&(zipHeader.head), sizeof(zipHeader.head));
if(ret==FALSE)
{
m_nErr = ERR_AT_READ_HEADER;
return FALSE;
}
// ALZ 확장..
if( (zipHeader.head.fileDescriptor & (SHORT)1) != 0){
m_bIsEncrypted = TRUE; // 하나라도 암호 걸렸으면 세팅한다.
}
if( (zipHeader.head.fileDescriptor & (SHORT)8) != 0){
m_bIsDataDescr = TRUE;
}
int byteLen = zipHeader.head.fileDescriptor/0x10;
if(byteLen)
{
FRead(&(zipHeader.compressionMethod), sizeof(zipHeader.compressionMethod));
FRead(&(zipHeader.unknown), sizeof(zipHeader.unknown));
FRead(&(zipHeader.fileCRC), sizeof(zipHeader.fileCRC));
FRead(&(zipHeader.compressedSize), byteLen);
FRead(&(zipHeader.uncompressedSize), byteLen); // 압축 사이즈가 없다.
}
// little to system
zipHeader.fileCRC = unalz_le32toh(zipHeader.fileCRC);
zipHeader.head.fileNameLength = unalz_le16toh(zipHeader.head.fileNameLength);
zipHeader.compressedSize = unalz_le64toh(zipHeader.compressedSize);
zipHeader.uncompressedSize = unalz_le64toh(zipHeader.uncompressedSize);
// FILE NAME
zipHeader.fileName = (char*)malloc(zipHeader.head.fileNameLength+sizeof(char));
if(zipHeader.fileName==NULL)
{
m_nErr = ERR_INVALID_FILENAME_LENGTH;
return FALSE;
}
FRead(zipHeader.fileName, zipHeader.head.fileNameLength);
if(zipHeader.head.fileNameLength > MAX_PATH - 5)
zipHeader.head.fileNameLength = MAX_PATH - 5;
zipHeader.fileName[zipHeader.head.fileNameLength] = (CHAR)NULL;
#ifdef _UNALZ_ICONV // codepage convert
if(strlen(m_szToCodepage))
{
#define ICONV_BUF_SIZE (260*6) // utf8 은 최대 6byte
size_t ileft, oleft;
iconv_t cd;
size_t iconv_result;
size_t size;
char inbuf[ICONV_BUF_SIZE];
char outbuf[ICONV_BUF_SIZE];
#if defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__NetBSD__)
const char *inptr = inbuf;
#else
char *inptr = inbuf;
#endif
char *outptr = outbuf;
size = strlen(zipHeader.fileName)+1;
strncpy(inbuf, zipHeader.fileName, size);
ileft = size;
oleft = sizeof(outbuf);
cd = iconv_open(m_szToCodepage, m_szFromCodepage); // 보통 "CP949" 에서 "UTF-8" 로
iconv(cd, NULL, NULL, NULL, NULL);
if( cd == (iconv_t)(-1))
{
m_nErr = ERR_ICONV_CANT_OPEN; // printf("Converting Error : Cannot open iconv");
return FALSE;
}
else
{
iconv_result = iconv(cd, &inptr, &ileft, &outptr, &oleft);
if(iconv_result== (size_t)(-1)) // iconv 실패..
{
if (errno == EILSEQ)
m_nErr = ERR_ICONV_INVALID_MULTISEQUENCE_OF_CHARACTERS; // printf("Invalid Multibyte Sequence of Characters");
else if (errno == EINVAL)
m_nErr = ERR_ICONV_INCOMPLETE_MULTIBYTE_SEQUENCE; //printf("Incomplete multibyte sequence");
else if (errno != E2BIG)
m_nErr = ERR_ICONV_NOT_ENOUGH_SPACE_OF_BUFFER_TO_CONVERT; // printf("Not enough space of buffer to convert");
else
m_nErr = ERR_ICONV_ETC;
iconv_close(cd);
return FALSE;
}
else
{
outbuf[ICONV_BUF_SIZE-oleft] = 0;
if(zipHeader.fileName) free(zipHeader.fileName);
zipHeader.fileName = strdup(outbuf);
if (zipHeader.fileName == NULL)
{
m_nErr = ERR_ICONV_ETC;
iconv_close(cd);
return FALSE;
}
// printf("\n Converted File Name : %s", outbuf);
}
iconv_close(cd);
}
}
#endif
/*
// EXTRA FIELD LENGTH
if(zipHeader.head.extraFieldLength)
{
zipHeader.extraField = (BYTE*)malloc(zipHeader.head.extraFieldLength);
if(zipHeader.extraField==NULL)
{
m_nErr = ERR_INVALID_EXTRAFIELD_LENGTH;
return FALSE;
}
FRead(zipHeader.extraField, 1, zipHeader.head.extraFieldLength);
}
*/
if(IsEncryptedFile(zipHeader.head.fileDescriptor))
FRead(zipHeader.encChk, ALZ_ENCR_HEADER_LEN); // xf86
// SKIP FILE DATA
zipHeader.dwFileDataPos = FTell(); // data 의 위치 저장하기..
FSeek(FTell()+zipHeader.compressedSize);
// DATA DESCRIPTOR
/*
if(zipHeader.head.generalPurposeBitFlag.bit1)
{
FRead(zipHeader.extraField, 1, sizeof(zipHeader.extraField),);
}
*/
/*
#ifdef _DEBUG
printf("NAME:%s COMPRESSED SIZE:%d UNCOMPRESSED SIZE:%d COMP METHOD:%d\n",
zipHeader.fileName,
zipHeader.compressedSize,
zipHeader.uncompressedSize,
zipHeader.compressionMethod
);
#endif
*/
// 파일을 목록에 추가한다..
m_fileList.push_back(zipHeader);
return TRUE;
}
BOOL CUnAlz::ReadCentralDirectoryStructure()
{
SCentralDirectoryStructure header;
if(FRead(&header, sizeof(header.head))==FALSE)
{
m_nErr = ERR_CANT_READ_CENTRAL_DIRECTORY_STRUCTURE_HEAD;
return FALSE;
}
/*
// read file name
if(header.head.fileNameLength)
{
header.fileName = (char*)malloc(header.head.fileNameLength+1);
if(header.fileName==NULL)
{
m_nErr = ERR_INVALID_FILENAME_SIZE;
return FALSE;
}
FRead(header.fileName, 1, header.head.fileNameLength, m_fp);
header.fileName[header.head.fileNameLength] = NULL;
}
// extra field;
if(header.head.extraFieldLength)
{
header.extraField = (BYTE*)malloc(header.head.extraFieldLength);
if(header.extraField==NULL)
{
m_nErr = ERR_INVALID_EXTRAFIELD_SIZE;
return FALSE;
}
FRead(header.extraField, 1, header.head.extraFieldLength, m_fp);
}
// file comment;
if(header.head.fileCommentLength)
{
header.fileComment = (char*)malloc(header.head.fileCommentLength+1);
if(header.fileComment==NULL)
{
m_nErr = ERR_INVALID_FILECOMMENT_SIZE;
return FALSE;
}
FRead(header.fileComment, 1, header.head.fileCommentLength, m_fp);
header.fileComment[header.head.fileCommentLength] = NULL;
}
*/
return TRUE;
}
BOOL CUnAlz::ReadEndofCentralDirectoryRecord()
{
/*
SEndOfCentralDirectoryRecord header;
if(FRead(&header, sizeof(header.head), 1, m_fp)!=1)
{
m_nErr = ERR_CANT_READ_HEADER;
return FALSE;
}
if(header.head.zipFileCommentLength)
{
header.fileComment = (char*)malloc(header.head.zipFileCommentLength+1);
if(header.fileComment==NULL)
{
m_nErr = ERR_INVALID_FILECOMMENT_SIZE;
return FALSE;
}
FRead(header.fileComment, 1, header.head.zipFileCommentLength, m_fp);
header.fileComment[header.head.zipFileCommentLength] = NULL;
}
*/
return TRUE;
}
BOOL CUnAlz::SetCurrentFile(const char* szFileName)
{
FileList::iterator i;
// 순차적으로 찾는다.
for(i=m_fileList.begin(); i<m_fileList.end(); i++)
{
#ifdef _WIN32
if(stricmp(i->fileName, szFileName)==0)
#else
if(strcmp(i->fileName, szFileName)==0)
#endif
{
m_posCur = i;
return TRUE;
}
}
m_posCur = m_fileList.end();//(FileList::iterator)NULL;
return FALSE;
}
void CUnAlz::SetCurrentFile(FileList::iterator newPos)
{
m_posCur = newPos;
}
#ifndef MAX_WBITS
# define MAX_WBITS 15 /* 32K LZ77 window */
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 버퍼에 압축 풀기. 버퍼는 당근 충분한 크기가 준비되어 있어야 한다.
/// @param pDestBuf
/// @return
/// @date 2004-03-07 오전 12:26:13
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::ExtractCurrentFileToBuf(BYTE* pDestBuf, int nBufSize)
{
SExtractDest dest;
dest.nType = ET_MEM;
dest.buf = pDestBuf;
dest.bufpos = 0;
dest.bufsize = nBufSize;
return ExtractTo(&dest);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 현재 파일 (SetCurrentFile로 지)을 대상 경로에 대상 파일로 푼다.
/// @param szDestPathName - 대상 경로
/// @param szDestFileName - 대상 파일명, NULL 이면 원래 파일명 사용
/// @return
/// @date 2004-03-06 오후 11:06:59
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::ExtractCurrentFile(const char* szDestPathName, const char* szDestFileName)
{
if(m_posCur==m_fileList.end()/*(FileList::iterator)NULL*/) {ASSERT(0); return FALSE;}
BOOL ret=FALSE;
SExtractDest dest;
char szDestPathFileName[MAX_PATH];
if(chkValidPassword() == FALSE)
{
return FALSE;
}
if( szDestPathName==NULL||
strlen(szDestPathName) + (szDestFileName?strlen(szDestFileName):strlen(m_posCur->fileName))+1 > MAX_PATH
) // check buffer overflow
{
ASSERT(0);
m_nErr = ERR_GENERAL;
return FALSE;
}
// 경로명
safe_strcpy(szDestPathFileName, szDestPathName, MAX_PATH);
if(szDestPathFileName[strlen(szDestPathFileName)]!=PATHSEPC)
safe_strcat(szDestPathFileName, PATHSEP, MAX_PATH);
// 파일명
if(szDestFileName) safe_strcat(szDestPathFileName, szDestFileName, MAX_PATH);
else safe_strcat(szDestPathFileName, m_posCur->fileName, MAX_PATH);
// ../../ 형식의 보안 버그 확인
if( strstr(szDestPathFileName, "../")||
strstr(szDestPathFileName, "..\\"))
{
ASSERT(0);
m_nErr = ERR_GENERAL;
return FALSE;
}
#ifndef _WIN32
{
char* p = szDestPathFileName; // 경로 delimiter 바꾸기
while(*p)
{
if(*p=='\\') *p='/';
p++;
}
}
#endif
// 압축풀 대상 ( 파일 )
dest.nType = ET_FILE;
if(m_bPipeMode)
dest.fp = stdout; // pipe mode 일 경우 stdout 출력
else
dest.fp = fopen(szDestPathFileName, "wb");
// 타입이 폴더일 경우..
if(m_bPipeMode==FALSE && (m_posCur->head.fileAttribute) & ALZ_FILEATTR_DIRECTORY )
{
//printf("digpath:%s\n", szDestPathFileName);
// 경로파기
DigPath(szDestPathFileName);
return TRUE;
// m_nErr = ERR_CANT_CREATE_DEST_PATH;
// return FALSE;
}
// 파일 열기 실패시 - 경로를 파본다
if(dest.fp==NULL)
{
DigPath(szDestPathFileName);
dest.fp = fopen(szDestPathFileName, "wb");
}
// 그래도 파일열기 실패시.
if(dest.fp==NULL)
{
// 대상 파일 열기 실패
m_nErr = ERR_CANT_OPEN_DEST_FILE;
//printf("dest pathfilename:%s\n",szDestPathFileName);
if(m_pFuncCallBack)
{
// CHAR buf[1024];
// sprintf(buf, "파일 열기 실패 : %s", szDestPathFileName);
// m_pFuncCallBack(buf, 0,0,m_pCallbackParam, NULL);
}
return FALSE;
}
//#endif
// CALLBACK 세팅
if(m_pFuncCallBack) m_pFuncCallBack(m_posCur->fileName, 0,m_posCur->uncompressedSize,m_pCallbackParam, NULL);
ret = ExtractTo(&dest);
if(dest.fp!=NULL)
{
fclose(dest.fp);
// file time setting - from unalz_wcx_01i.zip
utimbuf tmp;
tmp.actime = 0; // 마지막 엑세스 타임
tmp.modtime = dosTime2TimeT(m_posCur->head.fileTimeDate); // 마지막 수정일자만 변경(만든 날자는 어떻게 바꾸지?)
utime(m_posCur->fileName, &tmp);
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 대상에 압축 풀기..
/// @param dest
/// @return
/// @date 2004-03-07 오전 12:44:36
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::ExtractTo(SExtractDest* dest)
{
BOOL ret = FALSE;
// 압축 방법에 따라서 압축 풀기
if(m_posCur->compressionMethod==COMP_NOCOMP)
{
ret = ExtractRawfile(dest, *m_posCur);
}
else if(m_posCur->compressionMethod==COMP_BZIP2)
{
ret = ExtractBzip2(dest, *m_posCur); // bzip2
}
else if(m_posCur->compressionMethod==COMP_DEFLATE)
{
ret = ExtractDeflate2(dest, *m_posCur); // deflate
}
else // COMP_UNKNOWN
{
// alzip 5.6 부터 추가된 포맷(5.5 에서는 풀지 못한다. 영문 5.51 은 푼다 )
// 하지만 어떤 버전에서 이 포맷을 만들어 내는지 정확히 알 수 없다.
// 공식으로 릴리즈된 알집은 이 포맷을 만들어내지 않는다. 비공식(베타?)으로 배포된 버전에서만 이 포맷을 만들어낸다.
m_nErr = ERR_UNKNOWN_COMPRESSION_METHOD;
ASSERT(0);
ret = FALSE;
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// DEFLATE 로 풀기 - 테스트용 함수. 모든 파일을 한꺼번에 읽어서 푼다. 실제 사용 안함.
/// @param fp - 대상 파일
/// @param file - 소스 파일 정보
/// @return
/// @date 2004-03-06 오후 11:09:17
////////////////////////////////////////////////////////////////////////////////////////////////////
/*
BOOL CUnAlz::ExtractDeflate(FILE* fp, SAlzLocalFileHeader& file)
{
z_stream stream;
BYTE* pInBuf=NULL;
BYTE* pOutBuf=NULL;
int nInBufSize = file.compressedSize;
int nOutBufSize = file.uncompressedSize;
int err;
int flush=Z_SYNC_FLUSH;
BOOL ret = FALSE;
memset(&stream, 0, sizeof(stream));
pInBuf = (BYTE*)malloc(nInBufSize);
if(pInBuf==NULL)
{
m_nErr = ERR_MEM_ALLOC_FAILED;
goto END;
}
pOutBuf = (BYTE*)malloc(nOutBufSize);
if(pOutBuf==NULL)
{
m_nErr = ERR_MEM_ALLOC_FAILED;
goto END;
}
// 한번에 읽어서
fseek(m_fp, file.dwFileDataPos, SEEK_SET);
if(FRead(pInBuf, nInBufSize, 1, m_fp)!=1)
{
m_nErr = ERR_FILE_READ_ERROR;
goto END;
}
// 초기화..
inflateInit2(&stream, -MAX_WBITS);
stream.next_out = pOutBuf;
stream.avail_out = nOutBufSize;
stream.next_in = pInBuf;
stream.avail_in = nInBufSize;
err = inflate(&stream, flush);
if(err!=Z_OK && err!=Z_STREAM_END )
{
m_nErr = ERR_INFLATE_FAILED;
goto END;
}
fwrite(pOutBuf, 1, nOutBufSize, fp);
ret = TRUE;
END :
inflateEnd(&stream);
if(pInBuf) free(pInBuf);
if(pOutBuf) free(pOutBuf);
return ret;
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 대상 폴더에 현재 압축파일을 전부 풀기
/// @param szDestPathName - 대상 경로
/// @return
/// @date 2004-03-06 오후 11:09:49
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::ExtractAll(const char* szDestPathName)
{
FileList::iterator i;
for(i=m_fileList.begin(); i<m_fileList.end(); i++)
{
m_posCur = i;
if(ExtractCurrentFile(szDestPathName)==FALSE) return FALSE;
if(m_bHalt)
break; // 멈추기..
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 대상 경로 파기 - 압축 파일 내에 폴더 정보가 있을 경우, 다중 폴더를 판다(dig)
/// @param szPathName
/// @return
/// @date 2004-03-06 오후 11:10:12
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::DigPath(const char* szPathName)
{
char* dup = strdup(szPathName);
char seps[] = "/\\";
char* token;
char path[MAX_PATH] = {0};
char* last;
// 경로만 뽑기.
last = dup + strlen(dup);
while(last!=dup)
{
if(*last=='/' || *last=='\\')
{
*last = (char)NULL;
break;
}
last --;
}
token = strtok( dup, seps );
while( token != NULL )
{
if(strlen(path)==0)
{
if(szPathName[0]=='/') // is absolute path ?
safe_strcpy(path,"/", MAX_PATH);
else if(szPathName[0]=='\\' && szPathName[1]=='\\') // network drive ?
safe_strcpy(path,"\\\\", MAX_PATH);
safe_strcat(path, token, MAX_PATH);
}
else
{
safe_strcat(path, PATHSEP,MAX_PATH);
safe_strcat(path, token,MAX_PATH);
}
if(IsFolder(path)==FALSE)
#ifdef _WIN32
_mkdir(path);
#else
mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
#endif
//printf("path:%s\n", path);
token = strtok( NULL, seps );
}
free(dup);
if(IsFolder(szPathName)) return TRUE;
return FALSE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 제대로된 폴더 인가?
/// @param szPathName
/// @return
/// @date 2004-03-06 오후 11:03:26
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::IsFolder(const CHAR* szPathName)
{
#ifdef _WIN32
UINT32 dwRet;
dwRet = GetFileAttributesA(szPathName);
if(dwRet==0xffffffff) return FALSE;
if(dwRet & FILE_ATTRIBUTE_DIRECTORY) return TRUE;
return FALSE;
#else
struct stat buf;
int result;
result = stat(szPathName, &buf);
if(result!=0) return FALSE;
//printf("isfolder:%s, %d,%d,%d\n", szPathName, buf.st_mode, S_IFDIR, buf.st_mode & S_IFDIR);
if(buf.st_mode & S_IFDIR) return TRUE;
return FALSE;
#endif
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 압축을 풀 대상에 압축을 푼다.
/// @param dest - 대상 OBJECT
/// @param buf - 풀린 데이타
/// @param nSize - 데이타의 크기
/// @return 쓴 바이트수. 에러시 -1 리턴
/// @date 2004-03-07 오전 12:37:41
////////////////////////////////////////////////////////////////////////////////////////////////////
int CUnAlz::WriteToDest(SExtractDest* dest, BYTE* buf, int nSize)
{
if(dest->nType==ET_FILE)
{
return fwrite(buf, 1, nSize, dest->fp);
}
else if(dest->nType==ET_MEM)
{
if(dest->buf==NULL) return nSize; // 대상이 NULL 이다... 압축푸는 시늉만 한다..
if(dest->bufpos+nSize >dest->bufsize) // 에러.. 버퍼가 넘쳤다.
{
ASSERT(0);
return -1;
}
// memcpy
memcpy(dest->buf + dest->bufpos, buf, nSize);
dest->bufpos += nSize;
return nSize;
}
else
{
ASSERT(0);
}
return -1;
}
/* 실패한 방법.. 고생한게 아까워서 못지움.
#define ALZDLZ_HEADER_SIZE 4 // alz 파일의 bzip2 헤더 크기
#define BZIP2_HEADER_SIZE 10 // bzip 파일의 헤더 크기
#define BZIP2_CRC_SIZE 4 // bzip2 의 crc
#define BZIP2_TAIL_SIZE 10 // 대충 4+5 정도.?
BYTE bzip2Header[BZIP2_HEADER_SIZE] = {0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59};
BOOL CUnAlz::ExtractBzip2_bak(FILE* fp, SAlzLocalFileHeader& file)
{
bz_stream stream;
BYTE* pInBuf=NULL;
BYTE* pOutBuf=NULL;
int nInBufSize = file.compressedSize;
int nOutBufSize = file.uncompressedSize;
//int err;
int flush=Z_SYNC_FLUSH;
BOOL ret = FALSE;
UINT32 crc = 0xffffffff;
//BYTE temp[100];
memset(&stream, 0, sizeof(stream));
pInBuf = (BYTE*)malloc(nInBufSize + BZIP2_HEADER_SIZE + BZIP2_CRC_SIZE - ALZDLZ_HEADER_SIZE + BZIP2_TAIL_SIZE);
if(pInBuf==NULL)
{
m_nErr = ERR_MEM_ALLOC_FAILED;
goto END;
}
pOutBuf = (BYTE*)malloc(nOutBufSize);
if(pOutBuf==NULL)
{
m_nErr = ERR_MEM_ALLOC_FAILED;
goto END;
}
// ALZ 의 BZIP 헤더 ("DLZ.") 스킵하기.
fseek(m_fp, ALZDLZ_HEADER_SIZE, SEEK_CUR);
// BZIP2 헤더 삽입
memcpy(pInBuf, bzip2Header, BZIP2_HEADER_SIZE);
// BZIP2 CRC
memcpy(pInBuf+BZIP2_HEADER_SIZE, &(crc), BZIP2_CRC_SIZE);
// 진짜 압축된 데이타를 한번에 읽어서
fseek(m_fp, file.dwFileDataPos+ALZDLZ_HEADER_SIZE, SEEK_SET);
if(FRead(pInBuf+BZIP2_HEADER_SIZE+BZIP2_CRC_SIZE, nInBufSize-ALZDLZ_HEADER_SIZE, 1, m_fp)!=1)
{
m_nErr = ERR_FILE_READ_ERROR;
goto END;
}
// 초기화..
stream.bzalloc = NULL;
stream.bzfree = NULL;
stream.opaque = NULL;
ret = BZ2_bzDecompressInit ( &stream, 3,0 );
if (ret != BZ_OK) goto END;
//memcpy(temp, pInBuf, 100);
stream.next_in = (char*)pInBuf;
stream.next_out = (char*)pOutBuf;
stream.avail_in = nInBufSize+BZIP2_HEADER_SIZE+BZIP2_CRC_SIZE+BZIP2_TAIL_SIZE;
stream.avail_out = nOutBufSize;
ret = BZ2_bzDecompress ( &stream );
// BZ_DATA_ERROR 가 리턴될 수 있다..
//if (ret == BZ_OK) goto END;
//if (ret != BZ_STREAM_END) goto END;
BZ2_bzDecompressEnd(&stream);
fwrite(pOutBuf, 1, nOutBufSize, fp);
ret = TRUE;
END :
if(pInBuf) free(pInBuf);
if(pOutBuf) free(pOutBuf);
if(ret==FALSE) BZ2_bzDecompressEnd(&stream);
return ret;
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
/// RAW 로 압축된 파일 풀기
/// @param fp - 대상 파일
/// @param file - 소스 파일
/// @return
/// @date 2004-03-06 오후 11:10:53
////////////////////////////////////////////////////////////////////////////////////////////////////
#define BUF_LEN (4096*2)
BOOL CUnAlz::ExtractRawfile(SExtractDest* dest, SAlzLocalFileHeader& file)
{
BOOL ret = FALSE;
BYTE buf[BUF_LEN];
INT64 read;
INT64 sizeToRead;
INT64 bufLen = BUF_LEN;
INT64 nWritten = 0;
BOOL bHalt = FALSE;
BOOL bIsEncrypted = IsEncryptedFile(); // 암호걸린 파일인가?
UINT32 dwCRC32= 0;
// 위치 잡고.
FSeek(file.dwFileDataPos);
sizeToRead = file.compressedSize; // 읽을 크기.
m_nErr = ERR_NOERR;
while(sizeToRead)
{
read = min(sizeToRead, bufLen);
if(FRead(buf, (int)read)==FALSE)
{
break;
}
if(bIsEncrypted)
DecryptingData((int)read, buf); // xf86
dwCRC32 = crc32(dwCRC32, buf, (UINT)(read));
WriteToDest(dest, buf, (int)read);
//fwrite(buf, read, 1, fp);
sizeToRead -= read;
nWritten+=read;
// progress callback
if(m_pFuncCallBack)
{
m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt);
if(bHalt)
{
break;
}
}
}
m_bHalt = bHalt;
if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기..
{
if(file.fileCRC==dwCRC32)
{
ret = TRUE;
}
else
{
m_nErr = ERR_INVALID_FILE_CRC;
}
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// BZIP2 압축 풀기..
/// @param fp_w - 대상 파일
/// @param file - 소스 파일 정보
/// @return
/// @date 2004-03-01 오전 5:47:36
////////////////////////////////////////////////////////////////////////////////////////////////////
#define BZIP2_EXTRACT_BUF_SIZE 0x2000
BOOL CUnAlz::ExtractBzip2(SExtractDest* dest, SAlzLocalFileHeader& file)
{
BZFILE *bzfp = NULL;
int smallMode = 0;
int verbosity = 1;
int bzerr;
INT64 len;
BYTE buff[BZIP2_EXTRACT_BUF_SIZE];
INT64 nWritten = 0;
BOOL bHalt = FALSE;
UINT32 dwCRC32= 0;
BOOL ret = FALSE;
FSeek(file.dwFileDataPos);
bzfp = BZ2_bzReadOpen(&bzerr,this,verbosity,smallMode,0,0);
if(bzfp==NULL){ASSERT(0); return FALSE;}
m_nErr = ERR_NOERR;
while((len=BZ2_bzread(bzfp,buff,BZIP2_EXTRACT_BUF_SIZE))>0)
{
WriteToDest(dest, (BYTE*)buff, (int)len);
//fwrite(buff,1,len,fp_w);
dwCRC32 = crc32(dwCRC32,buff, (UINT)(len));
nWritten+=len;
// progress callback
if(m_pFuncCallBack)
{
m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt);
if(bHalt)
{
break;
}
}
}
if(len<0) // 에러 상황..
{
m_nErr = ERR_INFLATE_FAILED;
}
BZ2_bzReadClose( &bzerr, bzfp);
m_bHalt = bHalt;
if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기..
{
if(file.fileCRC==dwCRC32)
{
ret = TRUE;
}
else
{
m_nErr = ERR_INVALID_FILE_CRC;
}
}
/*
// FILE* 를 사용할경우 사용하던 코드. - 멀티 볼륨 지원 안함..
BZFILE *bzfp = NULL;
int smallMode = 0;
int verbosity = 1;
int bzerr;
int len;
char buff[BZIP2_EXTRACT_BUF_SIZE];
INT64 nWritten = 0;
BOOL bHalt = FALSE;
FSeek(file.dwFileDataPos, SEEK_SET);
bzfp = BZ2_bzReadOpen(&bzerr,m_fp,verbosity,smallMode,0,0);
while((len=BZ2_bzread(bzfp,buff,BZIP2_EXTRACT_BUF_SIZE))>0)
{
WriteToDest(dest, (BYTE*)buff, len);
//fwrite(buff,1,len,fp_w);
nWritten+=len;
// progress callback
if(m_pFuncCallBack)
{
m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt);
if(bHalt)
{
break;
}
}
}
BZ2_bzReadClose( &bzerr, bzfp);
m_bHalt = bHalt;
*/
return ret;
}
#ifndef UNZ_BUFSIZE
#define UNZ_BUFSIZE 0x1000 // (16384)
#endif
#define IN_BUF_SIZE UNZ_BUFSIZE
#define OUT_BUF_SIZE 0x1000 //IN_BUF_SIZE
////////////////////////////////////////////////////////////////////////////////////////////////////
/// deflate 로 압축 풀기. ExtractDeflate() 와 달리 조금씩 읽어서 푼다.
/// @param fp
/// @param file
/// @return
/// @date 2004-03-06 오후 11:11:36
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::ExtractDeflate2(SExtractDest* dest, SAlzLocalFileHeader& file)
{
z_stream stream;
BYTE pInBuf[IN_BUF_SIZE];
BYTE pOutBuf[OUT_BUF_SIZE];
int nInBufSize = IN_BUF_SIZE;
int nOutBufSize = OUT_BUF_SIZE;
int err;
int flush=Z_SYNC_FLUSH;
BOOL ret = FALSE;
INT64 nRestReadCompressed;
UINT32 dwCRC32= 0;
INT64 rest_read_uncompressed;
UINT iRead = 0;
INT64 nWritten = 0;
BOOL bHalt = FALSE;
BOOL bIsEncrypted = IsEncryptedFile(); // 암호걸린 파일인가?
memset(&stream, 0, sizeof(stream));
FSeek(file.dwFileDataPos);
inflateInit2(&stream, -MAX_WBITS);
nRestReadCompressed = file.compressedSize;
rest_read_uncompressed = file.uncompressedSize;
// 출력 부분.
stream.next_out = pOutBuf;
stream.avail_out = OUT_BUF_SIZE;
m_nErr = ERR_NOERR;
while(stream.avail_out>0)
{
if(stream.avail_in==0 && nRestReadCompressed>0)
{
UINT uReadThis = UNZ_BUFSIZE;
if (nRestReadCompressed<(int)uReadThis)
uReadThis = (UINT)nRestReadCompressed; // 읽을 크기.
if (uReadThis == 0)
break; // 중지
if(FRead(pInBuf, uReadThis)==FALSE)
{
m_nErr = ERR_CANT_READ_FILE;
goto END;
}
if(bIsEncrypted)
DecryptingData(uReadThis, pInBuf); // xf86
// dwCRC32 = crc32(dwCRC32,pInBuf, (UINT)(uReadThis));
nRestReadCompressed -= uReadThis;
stream.next_in = pInBuf;
stream.avail_in = uReadThis;
}
UINT uTotalOutBefore,uTotalOutAfter;
const BYTE *bufBefore;
UINT uOutThis;
int flush=Z_SYNC_FLUSH;
uTotalOutBefore = stream.total_out;
bufBefore = stream.next_out;
err=inflate(&stream,flush);
uTotalOutAfter = stream.total_out;
uOutThis = uTotalOutAfter-uTotalOutBefore;
dwCRC32 = crc32(dwCRC32,bufBefore, (UINT)(uOutThis));
rest_read_uncompressed -= uOutThis;
iRead += (UINT)(uTotalOutAfter - uTotalOutBefore);
WriteToDest(dest, pOutBuf, uOutThis);
//fwrite(pOutBuf, uOutThis, 1, fp); // file 에 쓰기.
stream.next_out = pOutBuf;
stream.avail_out = OUT_BUF_SIZE;
nWritten+=uOutThis;
// progress callback
if(m_pFuncCallBack)
{
m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt);
if(bHalt)
{
m_nErr = ERR_USER_ABORTED;
break;
}
}
if (err==Z_STREAM_END)
break;
//if(iRead==0) break; // UNZ_EOF;
if (err!=Z_OK)
{
m_nErr = ERR_INFLATE_FAILED;
goto END;
}
}
m_bHalt = bHalt;
if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기..
{
if(file.fileCRC==dwCRC32)
{
ret = TRUE;
}
else
{
m_nErr = ERR_INVALID_FILE_CRC;
}
}
END :
inflateEnd(&stream);
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 파일 열기
/// @param szPathName
/// @return
/// @date 2004-10-02 오후 11:47:14
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::FOpen(const char* szPathName)
{
char* temp = strdup(szPathName); // 파일명 복사..
int i;
int nLen = strlen(szPathName);
UINT64 nFileSizeLow;
UINT32 dwFileSizeHigh;
m_nFileCount = 0;
m_nCurFile = 0;
m_nVirtualFilePos = 0;
m_nCurFilePos = 0;
m_bIsEOF = FALSE;
for(i=0;i<MAX_FILES;i++) // aa.alz 파일명을 가지고 aa.a00 aa.a01 aa.a02 .. 만들기
{
if(i>0)
safe_sprintf(temp+nLen-3, 4, "%c%02d", (i-1)/100+'a', (i-1)%100);
#ifdef _WIN32
m_files[i].fp = CreateFileA(temp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if(m_files[i].fp==INVALID_HANDLE_VALUE) break;
nFileSizeLow = GetFileSize(m_files[i].fp, (DWORD*)&dwFileSizeHigh);
#else
m_files[i].fp = fopen(temp, "rb");
if(m_files[i].fp==NULL) break;
dwFileSizeHigh=0;
unalz_fseek(m_files[i].fp,0,SEEK_END);
nFileSizeLow=unalz_ftell(m_files[i].fp);
unalz_fseek(m_files[i].fp,0,SEEK_SET);
#endif
m_nFileCount++;
m_files[i].nFileSize = ((INT64)nFileSizeLow) + (((INT64)dwFileSizeHigh)<<32);
if(i==0) m_files[i].nMultivolHeaderSize = 0;
else m_files[i].nMultivolHeaderSize = MULTIVOL_HEAD_SIZE;
m_files[i].nMultivolTailSize = MULTIVOL_TAIL_SIZE;
}
free(temp);
if(m_nFileCount==0) return FALSE;
m_files[m_nFileCount-1].nMultivolTailSize = 0; // 마지막 파일은 꼴랑지가 없다..
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 파일 닫기
/// @return
/// @date 2004-10-02 오후 11:48:53
////////////////////////////////////////////////////////////////////////////////////////////////////
void CUnAlz::FClose()
{
int i;
#ifdef _WIN32
for(i=0;i<m_nFileCount;i++) CloseHandle(m_files[i].fp);
#else
for(i=0;i<m_nFileCount;i++) fclose(m_files[i].fp);
#endif
memset(m_files, 0, sizeof(m_files));
m_nFileCount = 0;
m_nCurFile = -1;
m_nVirtualFilePos = 0;
m_nCurFilePos = 0;
m_bIsEOF = FALSE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 파일의 끝인가?
/// @return
/// @date 2004-10-02 오후 11:48:21
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::FEof()
{
return m_bIsEOF;
/*
if(m_fp==NULL){ASSERT(0); return TRUE;}
if(feof(m_fp)) return TRUE;
return FALSE;
*/
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 현재 파일 위치
/// @return
/// @date 2004-10-02 오후 11:50:50
////////////////////////////////////////////////////////////////////////////////////////////////////
INT64 CUnAlz::FTell()
{
return m_nVirtualFilePos; // return ftell(m_fp);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 파일 위치 세팅
/// @param offset
/// @param origin
/// @return
/// @date 2004-10-02 오후 11:51:53
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::FSeek(INT64 offset)
{
m_nVirtualFilePos = offset;
int i;
INT64 remain=offset;
LONG remainHigh;
m_bIsEOF = FALSE;
for(i=0;i<m_nFileCount;i++) // 앞에서 루프를 돌면서 위치 선정하기..
{
if(remain<=m_files[i].nFileSize-m_files[i].nMultivolHeaderSize-m_files[i].nMultivolTailSize)
{
m_nCurFile = i;
m_nCurFilePos = remain+m_files[i].nMultivolHeaderSize; // 물리적 위치.
remainHigh = (LONG)((m_nCurFilePos>>32)&0xffffffff);
#ifdef _WIN32
SetFilePointer(m_files[i].fp, LONG(m_nCurFilePos), &remainHigh, FILE_BEGIN);
#else
unalz_fseek(m_files[i].fp, m_nCurFilePos, SEEK_SET);
#endif
return TRUE;
}
remain -= (m_files[i].nFileSize-m_files[i].nMultivolHeaderSize-m_files[i].nMultivolTailSize);
}
// 실패..?
ASSERT(0);
return FALSE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 파일 읽기
/// @param buffer
/// @param size
/// @param count
/// @return
/// @date 2004-10-02 오후 11:44:05
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::FRead(void* buffer, UINT32 nBytesToRead, int* pTotRead )
{
BOOL ret;
UINT32 nNumOfBytesRead;
INT64 dwRemain;
UINT32 dwRead;
UINT32 dwTotRead;
dwRemain = nBytesToRead;
dwTotRead = 0;
if(pTotRead) *pTotRead=0;
while(dwRemain)
{
dwRead = (UINT32)min(dwRemain, (m_files[m_nCurFile].nFileSize-m_nCurFilePos-m_files[m_nCurFile].nMultivolTailSize));
if(dwRead==0) {
m_bIsEOF = TRUE;return FALSE;
}
#ifdef _WIN32
ret = ReadFile(m_files[m_nCurFile].fp, ((BYTE*)buffer)+dwTotRead, dwRead, (DWORD*)&nNumOfBytesRead, NULL);
if(ret==FALSE && GetLastError()==ERROR_HANDLE_EOF)
{
m_bIsEOF = TRUE;return FALSE;
}
#else
nNumOfBytesRead = fread(((BYTE*)buffer)+dwTotRead, 1,dwRead ,m_files[m_nCurFile].fp);
if(nNumOfBytesRead<=0)
{
m_bIsEOF = TRUE;return FALSE;
}
ret=TRUE;
#endif
if(dwRead!=nNumOfBytesRead) // 발생하면 안된다..
{
ASSERT(0); return FALSE;
}
m_nVirtualFilePos += nNumOfBytesRead; // virtual 파일 위치..
m_nCurFilePos+=nNumOfBytesRead; // 물리적 파일 위치.
dwRemain-=nNumOfBytesRead;
dwTotRead+=nNumOfBytesRead;
if(pTotRead) *pTotRead=dwTotRead;
if(m_nCurFilePos==m_files[m_nCurFile].nFileSize-m_files[m_nCurFile].nMultivolTailSize) // overflow
{
m_nCurFile++;
#ifdef _WIN32
if(m_files[m_nCurFile].fp==INVALID_HANDLE_VALUE)
#else
if(m_files[m_nCurFile].fp==NULL)
#endif
{
m_bIsEOF = TRUE;
if(dwRemain==0) return TRUE; // 완전히 끝까지 읽었다..
return FALSE;
}
m_nCurFilePos = m_files[m_nCurFile].nMultivolHeaderSize; // header skip
#ifdef _WIN32
SetFilePointer(m_files[m_nCurFile].fp, (int)m_nCurFilePos, NULL, FILE_BEGIN);
#else
unalz_fseek(m_files[m_nCurFile].fp, m_nCurFilePos, SEEK_SET);
#endif
}
else
if(m_nCurFilePos>m_files[m_nCurFile].nFileSize-m_files[m_nCurFile].nMultivolTailSize) ASSERT(0);
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// error code 를 스트링으로 바꿔 준다.
/// @param nERR
/// @return
/// @date 2004-10-24 오후 3:28:39
////////////////////////////////////////////////////////////////////////////////////////////////////
const char* CUnAlz::LastErrToStr(ERR nERR)
{
if(nERR>= sizeof(errorstrtable)/sizeof(errorstrtable[0])) {ASSERT(0); return NULL; }
return errorstrtable[nERR];
}
// by xf86
BOOL CUnAlz::chkValidPassword()
{
if(IsEncryptedFile()==FALSE) {return TRUE;}
if (getPasswordLen() == 0){
m_nErr = ERR_PASSWD_NOT_SET;
return FALSE;
}
InitCryptKeys(m_szPasswd);
if(CryptCheck(m_posCur->encChk) == FALSE){
m_nErr = ERR_INVALID_PASSWD;
return FALSE;
}
return TRUE;
}
/*
////////////////////////////////////////////////////////////////////////////////////////////////////
// from CZipArchive
// Copyright (C) 2000 - 2004 Tadeusz Dracz
//
// http://www.artpol-software.com
//
// it's under GPL.
////////////////////////////////////////////////////////////////////////////////////////////////////
void CUnAlz::CryptDecodeBuffer(UINT32 uCount, CHAR *buf)
{
if (IsEncrypted())
for (UINT32 i = 0; i < uCount; i++)
CryptDecode(buf[i]);
}
void CUnAlz::CryptInitKeys()
{
m_keys[0] = 305419896L;
m_keys[1] = 591751049L;
m_keys[2] = 878082192L;
for (int i = 0; i < strlen(m_szPasswd); i++)
CryptUpdateKeys(m_szPasswd[i]);
}
void CUnAlz::CryptUpdateKeys(CHAR c)
{
m_keys[0] = CryptCRC32(m_keys[0], c);
m_keys[1] += m_keys[0] & 0xff;
m_keys[1] = m_keys[1] * 134775813L + 1;
c = CHAR(m_keys[1] >> 24);
m_keys[2] = CryptCRC32(m_keys[2], c);
}
BOOL CUnAlz::CryptCheck(CHAR *buf)
{
CHAR b = 0;
for (int i = 0; i < ALZ_ENCR_HEADER_LEN; i++)
{
b = buf[i];
CryptDecode((CHAR&)b);
}
if (IsDataDescr()) // Data descriptor present
return CHAR(m_posCur->head.fileTimeDate >> 8) == b;
else
return CHAR(m_posCur->maybeCRC >> 24) == b;
}
CHAR CUnAlz::CryptDecryptCHAR()
{
int temp = (m_keys[2] & 0xffff) | 2;
return (CHAR)(((temp * (temp ^ 1)) >> 8) & 0xff);
}
void CUnAlz::CryptDecode(CHAR &c)
{
c ^= CryptDecryptCHAR();
CryptUpdateKeys(c);
}
UINT32 CUnAlz::CryptCRC32(UINT32 l, CHAR c)
{
const ULONG *CRC_TABLE = get_crc_table();
return CRC_TABLE[(l ^ c) & 0xff] ^ (l >> 8);
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 암호걸린 파일인지 여부
/// @param fileDescriptor
/// @return
/// @date 2004-11-27 오후 11:25:32
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::IsEncryptedFile(BYTE fileDescriptor)
{
return fileDescriptor&0x01;
}
BOOL CUnAlz::IsEncryptedFile()
{
return m_posCur->head.fileDescriptor&0x01;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 암호로 키 초기화
/// @param szPassword
/// @return
/// @date 2004-11-27 오후 11:04:01
////////////////////////////////////////////////////////////////////////////////////////////////////
void CUnAlz::InitCryptKeys(const CHAR* szPassword)
{
m_key[0] = 305419896;
m_key[1] = 591751049;
m_key[2] = 878082192;
int i;
for(i=0;i<(int)strlen(szPassword);i++)
{
UpdateKeys(szPassword[i]);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 데이타로 키 업데이트하기
/// @param c
/// @return
/// @date 2004-11-27 오후 11:04:09
////////////////////////////////////////////////////////////////////////////////////////////////////
void CUnAlz::UpdateKeys(BYTE c)
{
m_key[0] = CRC32(m_key[0], c);
m_key[1] = m_key[1]+(m_key[0]&0x000000ff);
m_key[1] = m_key[1]*134775813+1;
m_key[2] = CRC32(m_key[2],m_key[1]>>24);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 암호가 맞는지 헤더 체크하기
/// @param buf
/// @return
/// @date 2004-11-27 오후 11:04:24
////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CUnAlz::CryptCheck(const BYTE* buf)
{
int i;
BYTE c;
BYTE temp[ALZ_ENCR_HEADER_LEN];
memcpy(temp, buf, ALZ_ENCR_HEADER_LEN); // 임시 복사.
for(i=0;i<ALZ_ENCR_HEADER_LEN;i++)
{
c = temp[i] ^ DecryptByte();
UpdateKeys(c);
temp[i] = c;
}
if (IsDataDescr()) // Data descriptor present
return (m_posCur->head.fileTimeDate >> 8) == c;
else
return ( ((m_posCur->fileCRC)>>24) ) == c; // 파일 crc 의 최상위 byte
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 키에서 데이타 추출
/// @return
/// @date 2004-11-27 오후 11:05:36
////////////////////////////////////////////////////////////////////////////////////////////////////
BYTE CUnAlz::DecryptByte()
{
UINT16 temp;
temp = m_key[2] | 2;
return (temp * (temp^1))>>8;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 데이타 압축 풀기
/// @param nSize
/// @param data
/// @return
/// @date 2004-11-27 오후 11:03:30
////////////////////////////////////////////////////////////////////////////////////////////////////
void CUnAlz::DecryptingData(int nSize, BYTE* data)
{
BYTE* p = data;
BYTE temp;
while(nSize)
{
temp = *p ^ DecryptByte();
UpdateKeys(temp);
*p = temp;
nSize--;
p++;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// CRC 테이블 참조
/// @param l
/// @param c
/// @return
/// @date 2004-11-27 오후 11:14:16
////////////////////////////////////////////////////////////////////////////////////////////////////
UINT32 CUnAlz::CRC32(UINT32 l, BYTE c)
{
const z_crc_t *CRC_TABLE = get_crc_table();
return CRC_TABLE[(l ^ c) & 0xff] ^ (l >> 8);
}
void CUnAlz::SetPassword(char *passwd)
{
if(strlen(passwd) == 0) return;
safe_strcpy(m_szPasswd, passwd, UNALZ_LEN_PASSWORD);
}
#ifdef _UNALZ_ICONV
void CUnAlz::SetDestCodepage(const char* szToCodepage)
{
safe_strcpy(m_szToCodepage, szToCodepage, UNALZ_LEN_CODEPAGE);
}
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
/// 문자열 처리 함수들
/// @param l
/// @param c
/// @return
/// @date 2007-02
////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int CUnAlz::_strlcpy (char *dest, const char *src, unsigned int size)
{
register unsigned int i = 0;
if (size > 0) {
size--;
for (i=0; size > 0 && src[i] != '\0'; ++i, size--)
dest[i] = src[i];
dest[i] = '\0';
}
while (src[i++]);
return i;
}
unsigned int CUnAlz::_strlcat (char *dest, const char *src, unsigned int size)
{
register char *d = dest;
for (; size > 0 && *d != '\0'; size--, d++);
return (d - dest) + _strlcpy(d, src, size);
}
// 안전한 strcpy
void CUnAlz::safe_strcpy(char* dst, const char* src, size_t dst_size)
{
#ifdef _WIN32
lstrcpynA(dst, src, dst_size);
#else
_strlcpy(dst, src, dst_size);
#endif
}
void CUnAlz::safe_strcat(char* dst, const char* src, size_t dst_size)
{
#ifdef _WIN32
StringCchCatExA(dst, dst_size, src, NULL, NULL, STRSAFE_FILL_BEHIND_NULL);
//lstrcatA(dst, src); // not safe!!
#else
_strlcat(dst, src, dst_size);
#endif
}
| 25.288316 | 328 | 0.566417 |
cc845d41a4cda951e0c2a35a8a448fb72c79ac7d | 2,767 | cpp | C++ | popcnt-harley-seal.cpp | kimwalisch/sse-popcount | 8f7441afb60847088aac9566d711969c48a03387 | [
"BSD-2-Clause"
] | 275 | 2015-04-06T19:49:18.000Z | 2022-03-19T06:23:47.000Z | popcnt-harley-seal.cpp | kimwalisch/sse-popcount | 8f7441afb60847088aac9566d711969c48a03387 | [
"BSD-2-Clause"
] | 20 | 2015-09-02T04:41:15.000Z | 2021-02-24T17:48:51.000Z | popcnt-harley-seal.cpp | kimwalisch/sse-popcount | 8f7441afb60847088aac9566d711969c48a03387 | [
"BSD-2-Clause"
] | 57 | 2015-06-01T01:08:02.000Z | 2022-01-02T12:49:43.000Z | namespace {
/// This uses fewer arithmetic operations than any other known
/// implementation on machines with fast multiplication.
/// It uses 12 arithmetic operations, one of which is a multiply.
/// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
///
uint64_t popcount_mul(uint64_t x)
{
const uint64_t m1 = UINT64_C(0x5555555555555555);
const uint64_t m2 = UINT64_C(0x3333333333333333);
const uint64_t m4 = UINT64_C(0x0F0F0F0F0F0F0F0F);
const uint64_t h01 = UINT64_C(0x0101010101010101);
x -= (x >> 1) & m1;
x = (x & m2) + ((x >> 2) & m2);
x = (x + (x >> 4)) & m4;
return (x * h01) >> 56;
}
/// Carry-save adder (CSA).
/// @see Chapter 5 in "Hacker's Delight".
///
void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c)
{
uint64_t u = a ^ b;
h = (a & b) | (u & c);
l = u ^ c;
}
/// Harley-Seal popcount (4th iteration).
/// The Harley-Seal popcount algorithm is one of the fastest algorithms
/// for counting 1 bits in an array using only integer operations.
/// This implementation uses only 5.69 instructions per 64-bit word.
/// @see Chapter 5 in "Hacker's Delight" 2nd edition.
///
uint64_t popcnt_harley_seal_64bit(const uint64_t* data, const uint64_t size)
{
uint64_t total = 0;
uint64_t ones = 0, twos = 0, fours = 0, eights = 0, sixteens = 0;
uint64_t twosA, twosB, foursA, foursB, eightsA, eightsB;
uint64_t limit = size - size % 16;
uint64_t i = 0;
for(; i < limit; i += 16)
{
CSA(twosA, ones, ones, data[i+0], data[i+1]);
CSA(twosB, ones, ones, data[i+2], data[i+3]);
CSA(foursA, twos, twos, twosA, twosB);
CSA(twosA, ones, ones, data[i+4], data[i+5]);
CSA(twosB, ones, ones, data[i+6], data[i+7]);
CSA(foursB, twos, twos, twosA, twosB);
CSA(eightsA,fours, fours, foursA, foursB);
CSA(twosA, ones, ones, data[i+8], data[i+9]);
CSA(twosB, ones, ones, data[i+10], data[i+11]);
CSA(foursA, twos, twos, twosA, twosB);
CSA(twosA, ones, ones, data[i+12], data[i+13]);
CSA(twosB, ones, ones, data[i+14], data[i+15]);
CSA(foursB, twos, twos, twosA, twosB);
CSA(eightsB, fours, fours, foursA, foursB);
CSA(sixteens, eights, eights, eightsA, eightsB);
total += popcount_mul(sixteens);
}
total *= 16;
total += 8 * popcount_mul(eights);
total += 4 * popcount_mul(fours);
total += 2 * popcount_mul(twos);
total += 1 * popcount_mul(ones);
for(; i < size; i++)
total += popcount_mul(data[i]);
return total;
}
} // namespace
uint64_t popcnt_harley_seal(const uint8_t* data, const size_t size)
{
uint64_t total = popcnt_harley_seal_64bit((const uint64_t*) data, size / 8);
for (size_t i = size - size % 8; i < size; i++)
total += lookup8bit[data[i]];
return total;
}
| 31.089888 | 78 | 0.64185 |
cc8f25f095ffc1960712df69e506be135c3cfb4c | 10,244 | cpp | C++ | Libs/Visualization/VTK/Widgets/ctkVTKSurfaceMaterialPropertyWidget.cpp | ebrahimebrahim/CTK | c506a0227777b55fc06dd22d74a11c5a9d4247b1 | [
"Apache-2.0"
] | null | null | null | Libs/Visualization/VTK/Widgets/ctkVTKSurfaceMaterialPropertyWidget.cpp | ebrahimebrahim/CTK | c506a0227777b55fc06dd22d74a11c5a9d4247b1 | [
"Apache-2.0"
] | null | null | null | Libs/Visualization/VTK/Widgets/ctkVTKSurfaceMaterialPropertyWidget.cpp | ebrahimebrahim/CTK | c506a0227777b55fc06dd22d74a11c5a9d4247b1 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
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.
=========================================================================*/
// Qt includes
#include <QDebug>
// CTK includes
#include "ctkVTKSurfaceMaterialPropertyWidget.h"
// VTK includes
#include <vtkSmartPointer.h>
#include <vtkProperty.h>
//-----------------------------------------------------------------------------
class ctkVTKSurfaceMaterialPropertyWidgetPrivate
{
Q_DECLARE_PUBLIC(ctkVTKSurfaceMaterialPropertyWidget);
protected:
ctkVTKSurfaceMaterialPropertyWidget* const q_ptr;
public:
ctkVTKSurfaceMaterialPropertyWidgetPrivate(ctkVTKSurfaceMaterialPropertyWidget& object);
vtkSmartPointer<vtkProperty> Property;
double SettingColor;
// Flag that indicates that the GUI is being updated from the VTK property,
// therefore GUI changes should not trigger VTK property update.
bool IsUpdatingGUI;
};
//-----------------------------------------------------------------------------
ctkVTKSurfaceMaterialPropertyWidgetPrivate::ctkVTKSurfaceMaterialPropertyWidgetPrivate(ctkVTKSurfaceMaterialPropertyWidget& object)
:q_ptr(&object)
{
this->SettingColor = false;
this->IsUpdatingGUI = false;
}
//-----------------------------------------------------------------------------
ctkVTKSurfaceMaterialPropertyWidget::~ctkVTKSurfaceMaterialPropertyWidget()
{
}
//-----------------------------------------------------------------------------
ctkVTKSurfaceMaterialPropertyWidget::ctkVTKSurfaceMaterialPropertyWidget(QWidget* parentWidget)
: Superclass(parentWidget)
, d_ptr(new ctkVTKSurfaceMaterialPropertyWidgetPrivate(*this))
{
this->updateFromProperty();
}
//-----------------------------------------------------------------------------
ctkVTKSurfaceMaterialPropertyWidget::ctkVTKSurfaceMaterialPropertyWidget(vtkProperty* property, QWidget* parentWidget)
: Superclass(parentWidget)
, d_ptr(new ctkVTKSurfaceMaterialPropertyWidgetPrivate(*this))
{
this->setProperty(property);
}
//-----------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::setProperty(vtkProperty* property)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
if (d->Property.GetPointer() == property)
{
return;
}
qvtkReconnect(d->Property, property, vtkCommand::ModifiedEvent,
this, SLOT(updateFromProperty()));
d->Property = property;
this->updateFromProperty();
}
//-----------------------------------------------------------------------------
vtkProperty* ctkVTKSurfaceMaterialPropertyWidget::property()const
{
Q_D(const ctkVTKSurfaceMaterialPropertyWidget);
return d->Property.GetPointer();
}
//-----------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::updateFromProperty()
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->setEnabled(d->Property.GetPointer() != 0);
if (d->Property.GetPointer() == 0 || d->SettingColor)
{
return;
}
if (d->IsUpdatingGUI)
{
// Update is already in progress
return;
}
d->IsUpdatingGUI = true;
double* c = d->Property->GetColor();
this->setColor(QColor::fromRgbF(qMin(c[0],1.), qMin(c[1], 1.), qMin(c[2],1.)));
this->setOpacity(d->Property->GetOpacity());
switch (d->Property->GetInterpolation())
{
case VTK_FLAT: this->setInterpolationMode(InterpolationFlat); break;
case VTK_GOURAUD: this->setInterpolationMode(InterpolationGouraud); break;
case VTK_PHONG: this->setInterpolationMode(InterpolationPhong); break;
case VTK_PBR: this->setInterpolationMode(InterpolationPBR); break;
}
this->setAmbient(d->Property->GetAmbient());
this->setDiffuse(d->Property->GetDiffuse());
this->setSpecular(d->Property->GetSpecular());
this->setSpecularPower(d->Property->GetSpecularPower());
this->setMetallic(d->Property->GetMetallic());
this->setRoughness(d->Property->GetRoughness());
d->IsUpdatingGUI = false;
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onColorChanged(const QColor& newColor)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onColorChanged(newColor);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
const QColor c = this->color();
// Need to work around a VTK bug of SetColor() that fires event
// in an unstable state:
// d->Property->SetColor(c.redF(), c.greenF(), c.blueF());
d->SettingColor = true;
d->Property->SetAmbientColor(c.redF(), c.greenF(), c.blueF());
d->Property->SetDiffuseColor(c.redF(), c.greenF(), c.blueF());
d->Property->SetSpecularColor(c.redF(), c.greenF(), c.blueF());
d->SettingColor = false;
// update just in case something connected to the modified event of the
// vtkProperty modified any attribute
this->updateFromProperty();
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onOpacityChanged(double newOpacity)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onOpacityChanged(newOpacity);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetOpacity(this->opacity());
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onInterpolationModeChanged(
ctkMaterialPropertyWidget::InterpolationMode newInterpolationMode)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onInterpolationModeChanged(newInterpolationMode);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
switch (this->interpolationMode())
{
case InterpolationFlat: d->Property->SetInterpolationToFlat(); break;
case InterpolationGouraud: d->Property->SetInterpolationToGouraud(); break;
case InterpolationPhong: d->Property->SetInterpolationToPhong(); break;
case InterpolationPBR: d->Property->SetInterpolationToPBR(); break;
}
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onAmbientChanged(double newAmbient)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onAmbientChanged(newAmbient);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetAmbient(this->ambient());
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onDiffuseChanged(double newDiffuse)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onDiffuseChanged(newDiffuse);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetDiffuse(this->diffuse());
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onSpecularChanged(double newSpecular)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onSpecularChanged(newSpecular);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetSpecular(this->specular());
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onSpecularPowerChanged(double newSpecularPower)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onSpecularPowerChanged(newSpecularPower);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetSpecularPower(this->specularPower());
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onMetallicChanged(double newMetallic)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onMetallicChanged(newMetallic);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetMetallic(this->metallic());
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onRoughnessChanged(double newRoughness)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onRoughnessChanged(newRoughness);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetRoughness(this->roughness());
}
}
// --------------------------------------------------------------------------
void ctkVTKSurfaceMaterialPropertyWidget::onBackfaceCullingChanged(bool newBackfaceCulling)
{
Q_D(ctkVTKSurfaceMaterialPropertyWidget);
this->Superclass::onBackfaceCullingChanged(newBackfaceCulling);
if (d->Property.GetPointer() != 0)
{
// the value might have changed since we fired the signal, use the current
// up-to-date value then.
d->Property->SetBackfaceCulling(this->backfaceCulling());
}
}
| 36.455516 | 131 | 0.625439 |
cc92133cf6216aed3081d7ee820e775f80d84589 | 814 | cpp | C++ | HackerRank/Algorithms/Easy/E0088.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | HackerRank/Algorithms/Easy/E0088.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | HackerRank/Algorithms/Easy/E0088.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | /*
Problem Statement: https://www.hackerrank.com/challenges/acm-icpc-team/problem
*/
#include <iostream>
#include <string>
#include <vector>
#include <bitset>
#define M 500
using namespace std;
vector<int> acmTeam(vector<string> topic) {
int known;
vector<int> ans(2);
for (int i = 0; i < topic.size() - 1; i++) {
bitset<M> b1(topic[i]);
for (int j = i + 1; j < topic.size(); j++) {
bitset<M> b2(topic[j]);
known = (b1 | b2).count();
if (known > ans[0]) {
ans[0] = known;
ans[1] = 1;
}
else if (known == ans[0])
ans[1]++;
}
}
return ans;
}
int main() {
int n, m;
cin >> n >> m;
vector<int> ans;
vector<string> topic(n);
for (int i = 0; i < n; i++)
cin >> topic[i];
ans = acmTeam(topic);
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << endl;
return 0;
} | 18.930233 | 78 | 0.558968 |
cc92e631f99cd32b1e9c3eee1a2ee8e50332cb88 | 1,867 | cpp | C++ | Controller/FileController.cpp | SAarronB/Vector | 225342800beff75e19513bbb6d68a0dcd3eab1e2 | [
"MIT"
] | null | null | null | Controller/FileController.cpp | SAarronB/Vector | 225342800beff75e19513bbb6d68a0dcd3eab1e2 | [
"MIT"
] | null | null | null | Controller/FileController.cpp | SAarronB/Vector | 225342800beff75e19513bbb6d68a0dcd3eab1e2 | [
"MIT"
] | null | null | null | //
// FileController.cpp
// Vector
//
// Created by Bonilla, Sean on 2/5/19.
// Copyright © 2019 CTEC. All rights reserved.
//
#include "FileController.hpp"
using namespace std;
vector<CrimeData> FileController :: readCrimeDataToVector(string filename){
vector<CrimeData> crimes;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//if the file exists at that path.
if(dataFile.is_open()){
//Keep Reading Until you are at the end of the file
while(!dataFile.eof()){
//Grab each line from the VSV separated by the carriage return character.
getline(dataFile, currentCSVLine, '\r');
if(rowCount != 0){
//Create a CrimeData instace forom the line. exclude a black line (usually if opened separeately
if(currentCSVLine.length() != 0){
CrimeData row(currentCSVLine);
crimes.push_back(row);
}
}
rowCount++;
}
dataFile.close();
}else{
cerr << "No File" << endl;
}
return crimes;
}
vector<Music> FileController :: musicDataToVector(string fileName){
vector<Music> musicList;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(fileName);
//if the file exists at that path
if(dataFile.is_open()){
//keepreading until you are tat the end of the file
while(!dataFile.eof()){
getline(dataFile, currentCSVLine, '\r');
if(rowCount != 0){
if(currentCSVLine.length() !=0){
Music row(currentCSVLine);
musicList.push_back(row);
}
}
rowCount++;
}
dataFile.close();
}else{
cerr <<"No File"<< endl;
}
return musicList;
}
| 28.723077 | 112 | 0.561864 |
cc9408e406624a2b5f1b2851338c337524978330 | 827 | cpp | C++ | nfcd/src/main/jni/src/hook/IHook.cpp | malexmave/nfcgate | 8f9c8330d5507aedbb61803538b4d01a93fc7169 | [
"Apache-2.0"
] | 569 | 2015-08-14T14:27:45.000Z | 2022-03-31T17:07:39.000Z | nfcd/src/main/jni/src/hook/IHook.cpp | malexmave/nfcgate | 8f9c8330d5507aedbb61803538b4d01a93fc7169 | [
"Apache-2.0"
] | 45 | 2015-06-01T09:59:22.000Z | 2022-03-24T06:28:40.000Z | nfcd/src/main/jni/src/hook/IHook.cpp | malexmave/nfcgate | 8f9c8330d5507aedbb61803538b4d01a93fc7169 | [
"Apache-2.0"
] | 89 | 2016-03-20T01:33:19.000Z | 2022-03-17T16:53:38.000Z | extern "C" {
#include <xhook.h>
}
#include <nfcd/hook/IHook.h>
#include <nfcd/hook/impl/XHook.h>
#include <nfcd/hook/impl/ADBIHook.h>
#include <nfcd/helper/System.h>
/* static */ bool IHook::useXHook = false;
void IHook::init() {
// Pie = 28
IHook::useXHook = System::sdkInt() >= System::P;
}
IHook *IHook::hook(const std::string &name, void *hook, void *libraryHandle,
const std::string &reLibrary) {
if (useXHook)
return new XHook(name, hook, libraryHandle, reLibrary);
else
return new ADBIHook(name, hook, libraryHandle);
}
void IHook::finish() {
if (useXHook)
LOG_ASSERT_X(xhook_refresh(0) == 0, "xhook_refresh failed");
}
IHook::IHook(const std::string &name, void *hookFn, void *libraryHandle) :
Symbol(name, libraryHandle), mHookFn(hookFn) {}
| 25.84375 | 76 | 0.645707 |
cc94c1ed84af0a8037617af724c7a2a7fa0f4d9d | 728 | hpp | C++ | source/tm/evaluate/move_scores.hpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 7 | 2021-03-05T16:50:19.000Z | 2022-02-02T04:30:07.000Z | source/tm/evaluate/move_scores.hpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 47 | 2021-02-01T18:54:23.000Z | 2022-03-06T19:06:16.000Z | source/tm/evaluate/move_scores.hpp | davidstone/technical-machine | fea3306e58cd026846b8f6c71d51ffe7bab05034 | [
"BSL-1.0"
] | 1 | 2021-01-28T13:10:41.000Z | 2021-01-28T13:10:41.000Z | // Copyright David Stone 2020.
// 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)
#pragma once
#include <tm/move/max_moves_per_pokemon.hpp>
#include <containers/static_vector.hpp>
#include <tm/generation.hpp>
namespace technicalmachine {
struct MoveScores {
MoveScores(Generation, StaticVectorMove legal_selections, bool ai);
void set(Moves move_name, double score);
auto ordered_moves(bool ai) const -> StaticVectorMove;
private:
struct value_type {
Moves move_name;
double score;
};
containers::static_vector<value_type, bounded::builtin_max_value<MoveSize>> m_scores;
};
} // namespace technicalmachine
| 25.103448 | 86 | 0.774725 |
cc99ab560d85ebc58e9b118b30a650a1cbbb73fe | 18,447 | cc | C++ | project4/mariadb/server/storage/tokudb/PerconaFT/src/tests/recovery_fileops_unit.cc | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | 11 | 2017-10-28T08:41:08.000Z | 2021-06-24T07:24:21.000Z | project4/mariadb/server/storage/tokudb/PerconaFT/src/tests/recovery_fileops_unit.cc | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | null | null | null | project4/mariadb/server/storage/tokudb/PerconaFT/src/tests/recovery_fileops_unit.cc | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | 4 | 2017-09-07T09:33:26.000Z | 2021-02-19T07:45:08.000Z | /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*======
This file is part of PerconaFT.
Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2,
as published by the Free Software Foundation.
PerconaFT 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 PerconaFT. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License, version 3,
as published by the Free Software Foundation.
PerconaFT 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with PerconaFT. If not, see <http://www.gnu.org/licenses/>.
======= */
#ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved."
#include <db.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "ft/logger/logger.h"
#include "test.h"
#include "toku_pthread.h"
static int do_recover;
static int do_crash;
static char fileop;
static int choices['J' - 'A' + 1];
const int num_choices = sizeof(choices)/sizeof(choices[0]);
static DB_TXN *txn;
const char *oldname = "oldfoo";
const char *newname = "newfoo";
DB_ENV *env;
DB *db;
static int crash_during_checkpoint;
static char *cmd;
static void
usage(void) {
fprintf(stderr,
"Usage:\n%s [-v|-q]* [-h] (-c|-r) -O fileop -A# -B# -C# -D# -E# "
"-F# -G# [-H# -I# -J#]\n"
" fileop = c/r/d (create/rename/delete)\n"
" Where # is a single digit number > 0.\n"
" A-G are required for fileop=create\n"
" A-I are required for fileop=delete, fileop=rename\n",
cmd);
exit(1);
}
enum { CLOSE_TXN_COMMIT, CLOSE_TXN_ABORT, CLOSE_TXN_NONE };
enum {CREATE_CREATE, CREATE_CHECKPOINT, CREATE_COMMIT_NEW,
CREATE_COMMIT_NEW_CHECKPOINT, CREATE_COMMIT_CHECKPOINT_NEW,
CREATE_CHECKPOINT_COMMIT_NEW};
static int fileop_did_commit(void);
static void close_txn(int type);
static int
get_x_choice(char c, int possibilities) {
assert(c < 'A' + num_choices);
assert(c >= 'A');
int choice = choices[c-'A'];
if (choice >= possibilities)
usage();
return choice;
}
//return 0 or 1
static int
get_bool_choice(char c) {
return get_x_choice(c, 2);
}
static int
get_choice_first_create_unrelated_txn(void) {
return get_bool_choice('A');
}
static int
get_choice_do_checkpoint_after_fileop(void) {
return get_bool_choice('B');
}
static int
get_choice_txn_close_type(void) {
return get_x_choice('C', 3);
}
static int
get_choice_close_txn_before_checkpoint(void) {
int choice = get_bool_choice('D');
//Can't do checkpoint related thing without checkpoint
if (choice)
assert(get_choice_do_checkpoint_after_fileop());
return choice;
}
static int
get_choice_crash_checkpoint_in_callback(void) {
int choice = get_bool_choice('E');
//Can't do checkpoint related thing without checkpoint
if (choice)
assert(get_choice_do_checkpoint_after_fileop());
return choice;
}
static int
get_choice_flush_log_before_crash(void) {
return get_bool_choice('F');
}
static int get_choice_dir_per_db(void) { return get_bool_choice('G'); }
static int get_choice_create_type(void) { return get_x_choice('H', 6); }
static int
get_choice_txn_does_open_close_before_fileop(void) {
return get_bool_choice('I');
}
static int
get_choice_lock_table_split_fcreate(void) {
int choice = get_bool_choice('J');
if (choice)
assert(fileop_did_commit());
return choice;
}
static void
do_args(int argc, char * const argv[]) {
cmd = argv[0];
int i;
//Clear
for (i = 0; i < num_choices; i++) {
choices[i] = -1;
}
char c;
while ((c = getopt(argc, argv, "vqhcrO:A:B:C:D:E:F:G:H:I:J:X:")) != -1) {
switch (c) {
case 'v':
verbose++;
break;
case 'q':
verbose--;
if (verbose < 0)
verbose = 0;
break;
case 'h':
case '?':
usage();
break;
case 'c':
do_crash = 1;
break;
case 'r':
do_recover = 1;
break;
case 'O':
if (fileop != '\0')
usage();
fileop = optarg[0];
switch (fileop) {
case 'c':
case 'r':
case 'd':
break;
default:
usage();
break;
}
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
if (fileop == '\0')
usage();
int num;
num = atoi(optarg);
if (num < 0 || num > 9)
usage();
choices[c - 'A'] = num;
break;
case 'X':
if (strcmp(optarg, "novalgrind") == 0) {
// provide a way for the shell script runner to pass an
// arg that suppresses valgrind on this child process
break;
}
// otherwise, fall through to an error
default:
usage();
break;
}
}
if (argc!=optind) { usage(); exit(1); }
for (i = 0; i < num_choices; i++) {
if (i >= 'H' - 'A' && fileop == 'c')
break;
if (choices[i] == -1)
usage();
}
assert(!do_recover || !do_crash);
assert(do_recover || do_crash);
}
static void UU() crash_it(void) {
int r;
if (get_choice_flush_log_before_crash()) {
r = env->log_flush(env, NULL); //TODO: USe a real DB_LSN* instead of NULL
CKERR(r);
}
fprintf(stderr, "HAPPY CRASH\n");
fflush(stdout);
fflush(stderr);
toku_hard_crash_on_purpose();
printf("This line should never be printed\n");
fflush(stdout);
}
static void checkpoint_callback_maybe_crash(void * UU(extra)) {
if (crash_during_checkpoint)
crash_it();
}
static void env_startup(void) {
int r;
int recover_flag = do_crash ? 0 : DB_RECOVER;
if (do_crash) {
db_env_set_checkpoint_callback(checkpoint_callback_maybe_crash, NULL);
toku_os_recursive_delete(TOKU_TEST_FILENAME);
r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r);
}
int envflags = DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_CREATE | DB_PRIVATE | recover_flag;
r = db_env_create(&env, 0);
CKERR(r);
r = env->set_dir_per_db(env, get_choice_dir_per_db());
CKERR(r);
env->set_errfile(env, stderr);
r = env->open(env, TOKU_TEST_FILENAME, envflags, S_IRWXU+S_IRWXG+S_IRWXO);
CKERR(r);
//Disable auto-checkpointing.
r = env->checkpointing_set_period(env, 0);
CKERR(r);
}
static void
env_shutdown(void) {
int r;
r = env->close(env, 0);
CKERR(r);
toku_os_recursive_delete(TOKU_TEST_FILENAME);
}
static void
checkpoint(void) {
int r;
r = env->txn_checkpoint(env, 0, 0, 0);
CKERR(r);
}
static void
maybe_make_oldest_living_txn(void) {
if (get_choice_first_create_unrelated_txn()) {
// create a txn that never closes, forcing recovery to run from the beginning of the log
DB_TXN *oldest_living_txn;
int r;
r = env->txn_begin(env, NULL, &oldest_living_txn, 0);
CKERR(r);
checkpoint();
}
}
static void
make_txn(void) {
int r;
assert(!txn);
r = env->txn_begin(env, NULL, &txn, 0);
CKERR(r);
}
static void
fcreate(void) {
int r;
r = db_create(&db, env, 0);
CKERR(r);
r = db->open(db, txn, oldname, NULL, DB_BTREE, DB_CREATE|DB_EXCL, 0666);
CKERR(r);
if (fileop!='c' && get_choice_lock_table_split_fcreate()) {
r = db->close(db, 0);
CKERR(r);
close_txn(CLOSE_TXN_COMMIT);
make_txn();
r = db_create(&db, env, 0);
CKERR(r);
r = db->open(db, txn, oldname, NULL, DB_BTREE, 0, 0666);
CKERR(r);
r = db->pre_acquire_table_lock(db, txn);
CKERR(r);
}
DBT key, val;
dbt_init(&key, choices, sizeof(choices));
dbt_init(&val, NULL, 0);
r = db->put(db, txn, &key, &val, 0);
CKERR(r);
dbt_init(&key, "name", sizeof("name"));
dbt_init(&val, (void*)oldname, strlen(oldname)+1);
r = db->put(db, txn, &key, &val, 0);
CKERR(r);
dbt_init(&key, "to_delete", sizeof("to_delete"));
dbt_init(&val, "delete_me", sizeof("delete_me"));
r = db->put(db, txn, &key, &val, 0);
CKERR(r);
r = db->del(db, txn, &key, DB_DELETE_ANY);
CKERR(r);
dbt_init(&key, "to_delete2", sizeof("to_delete2"));
dbt_init(&val, "delete_me2", sizeof("delete_me2"));
r = db->put(db, txn, &key, &val, 0);
CKERR(r);
r = db->del(db, txn, &key, 0);
CKERR(r);
r = db->close(db, 0);
CKERR(r);
}
static void
fdelete(void) {
int r;
r = env->dbremove(env, txn, oldname, NULL, 0);
CKERR(r);
}
static void
frename(void) {
int r;
{
//Rename in 'key/val' pair.
DBT key,val;
r = db_create(&db, env, 0);
CKERR(r);
r = db->open(db, txn, oldname, NULL, DB_BTREE, 0, 0666);
CKERR(r);
dbt_init(&key, "name", sizeof("name"));
dbt_init(&val, (void*)newname, strlen(newname)+1);
r = db->put(db, txn, &key, &val, 0);
CKERR(r);
r = db->close(db, 0);
CKERR(r);
}
r = env->dbrename(env, txn, oldname, NULL, newname, 0);
CKERR(r);
}
static void
close_txn(int type) {
int r;
assert(txn);
if (type==CLOSE_TXN_COMMIT) {
//commit
r = txn->commit(txn, 0);
CKERR(r);
txn = NULL;
}
else if (type == CLOSE_TXN_ABORT) {
//abort
r = txn->abort(txn);
CKERR(r);
txn = NULL;
}
else
assert(type == CLOSE_TXN_NONE);
}
static void
create_and_crash(void) {
//Make txn
make_txn();
//fcreate
fcreate();
if (get_choice_do_checkpoint_after_fileop()) {
crash_during_checkpoint = get_choice_crash_checkpoint_in_callback();
if (get_choice_close_txn_before_checkpoint())
close_txn(get_choice_txn_close_type());
checkpoint();
if (!get_choice_close_txn_before_checkpoint())
close_txn(get_choice_txn_close_type());
}
else {
crash_during_checkpoint = get_choice_crash_checkpoint_in_callback();
assert(!crash_during_checkpoint);
close_txn(get_choice_txn_close_type());
}
}
static void
create_and_maybe_checkpoint_and_or_close_after_create(void) {
fcreate();
switch (get_choice_create_type()) {
case (CREATE_CREATE): //Just create
break;
case (CREATE_CHECKPOINT): //Create then checkpoint
checkpoint();
break;
case (CREATE_COMMIT_NEW): //Create then commit
close_txn(CLOSE_TXN_COMMIT);
make_txn();
break;
case (CREATE_COMMIT_NEW_CHECKPOINT): //Create then commit then create new txn then checkpoint
close_txn(CLOSE_TXN_COMMIT);
make_txn();
checkpoint();
break;
case (CREATE_COMMIT_CHECKPOINT_NEW): //Create then commit then checkpoint then create new txn
close_txn(CLOSE_TXN_COMMIT);
checkpoint();
make_txn();
break;
case (CREATE_CHECKPOINT_COMMIT_NEW): //Create then checkpoint then commit then create new txn
checkpoint();
close_txn(CLOSE_TXN_COMMIT);
make_txn();
break;
default:
assert(false);
break;
}
}
static void
maybe_open_and_close_file_again_before_fileop(void) {
if (get_choice_txn_does_open_close_before_fileop()) {
int r;
r = db_create(&db, env, 0);
CKERR(r);
r = db->open(db, txn, oldname, NULL, DB_BTREE, 0, 0666);
CKERR(r);
r = db->close(db, 0);
CKERR(r);
}
}
static void
delete_and_crash(void) {
//Make txn
make_txn();
//fcreate
create_and_maybe_checkpoint_and_or_close_after_create();
maybe_open_and_close_file_again_before_fileop();
fdelete();
if (get_choice_do_checkpoint_after_fileop()) {
crash_during_checkpoint = get_choice_crash_checkpoint_in_callback();
if (get_choice_close_txn_before_checkpoint())
close_txn(get_choice_txn_close_type());
checkpoint();
if (!get_choice_close_txn_before_checkpoint())
close_txn(get_choice_txn_close_type());
}
else {
crash_during_checkpoint = get_choice_crash_checkpoint_in_callback();
assert(!crash_during_checkpoint);
close_txn(get_choice_txn_close_type());
}
}
static void
rename_and_crash(void) {
//Make txn
make_txn();
//fcreate
create_and_maybe_checkpoint_and_or_close_after_create();
maybe_open_and_close_file_again_before_fileop();
frename();
if (get_choice_do_checkpoint_after_fileop()) {
crash_during_checkpoint = get_choice_crash_checkpoint_in_callback();
if (get_choice_close_txn_before_checkpoint())
close_txn(get_choice_txn_close_type());
checkpoint();
if (!get_choice_close_txn_before_checkpoint())
close_txn(get_choice_txn_close_type());
}
else {
crash_during_checkpoint = get_choice_crash_checkpoint_in_callback();
assert(!crash_during_checkpoint);
close_txn(get_choice_txn_close_type());
}
}
static void
execute_and_crash(void) {
maybe_make_oldest_living_txn();
//split into create/delete/rename
if (fileop=='c')
create_and_crash();
else if (fileop == 'd')
delete_and_crash();
else {
assert(fileop == 'r');
rename_and_crash();
}
crash_it();
}
static int
did_create_commit_early(void) {
int r;
switch (get_choice_create_type()) {
case (CREATE_CREATE): //Just create
case (CREATE_CHECKPOINT): //Create then checkpoint
r = 0;
break;
case (CREATE_COMMIT_NEW): //Create then commit
case (CREATE_COMMIT_NEW_CHECKPOINT): //Create then commit then create new txn then checkpoint
case (CREATE_COMMIT_CHECKPOINT_NEW): //Create then commit then checkpoint then create new txn
case (CREATE_CHECKPOINT_COMMIT_NEW): //Create then checkpoint then commit then create new txn
r = 1;
break;
default:
assert(false);
}
return r;
}
static int
getf_do_nothing(DBT const* UU(key), DBT const* UU(val), void* UU(extra)) {
return 0;
}
static void
verify_file_exists(const char *name, int should_exist) {
int r;
make_txn();
r = db_create(&db, env, 0);
CKERR(r);
r = db->open(db, txn, name, NULL, DB_BTREE, 0, 0666);
if (should_exist) {
CKERR(r);
DBT key, val;
dbt_init(&key, choices, sizeof(choices));
dbt_init(&val, NULL, 0);
r = db->get(db, txn, &key, &val, 0);
r = db->getf_set(db, txn, 0, &key, getf_do_nothing, NULL);
CKERR(r);
dbt_init(&key, "name", sizeof("name"));
dbt_init(&val, (void*)name, strlen(name)+1);
r = db->getf_set(db, txn, 0, &key, getf_do_nothing, NULL);
CKERR(r);
DBC *c;
r = db->cursor(db, txn, &c, 0);
CKERR(r);
int num_found = 0;
while ((r = c->c_getf_next(c, 0, getf_do_nothing, NULL)) == 0) {
num_found++;
}
CKERR2(r, DB_NOTFOUND);
assert(num_found == 2); //name and choices array.
r = c->c_close(c);
CKERR(r);
}
else
CKERR2(r, ENOENT);
r = db->close(db, 0);
CKERR(r);
close_txn(CLOSE_TXN_COMMIT);
}
static int
fileop_did_commit(void) {
return get_choice_txn_close_type() == CLOSE_TXN_COMMIT &&
(!get_choice_do_checkpoint_after_fileop() ||
!get_choice_crash_checkpoint_in_callback() ||
get_choice_close_txn_before_checkpoint());
}
static void
recover_and_verify(void) {
//Recovery was done during env_startup
int expect_old_name = 0;
int expect_new_name = 0;
if (fileop=='c') {
expect_old_name = fileop_did_commit();
}
else if (fileop == 'd') {
expect_old_name = did_create_commit_early() && !fileop_did_commit();
}
else {
//Wrong? if checkpoint AND crash during checkpoint
if (fileop_did_commit())
expect_new_name = 1;
else if (did_create_commit_early())
expect_old_name = 1;
}
// We can't expect files existence until recovery log was not flushed
if ((get_choice_flush_log_before_crash())) {
verify_file_exists(oldname, expect_old_name);
verify_file_exists(newname, expect_new_name);
}
env_shutdown();
}
int
test_main(int argc, char * const argv[]) {
crash_during_checkpoint = 0; //Do not crash during checkpoint (possibly during recovery).
do_args(argc, argv);
env_startup();
if (do_crash)
execute_and_crash();
else
recover_and_verify();
return 0;
}
| 28.249617 | 127 | 0.587521 |
cc9b313ca44aac7dbcd9df1dcb229f9587977680 | 10,473 | cc | C++ | hwy/tests/float_test.cc | clayne/highway | af2cd99390a5bdfeb3fe7b2acc59acbe413943e9 | [
"Apache-2.0"
] | null | null | null | hwy/tests/float_test.cc | clayne/highway | af2cd99390a5bdfeb3fe7b2acc59acbe413943e9 | [
"Apache-2.0"
] | null | null | null | hwy/tests/float_test.cc | clayne/highway | af2cd99390a5bdfeb3fe7b2acc59acbe413943e9 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests some ops specific to floating-point types (Div, Round etc.)
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <limits>
#undef HWY_TARGET_INCLUDE
#define HWY_TARGET_INCLUDE "tests/float_test.cc"
#include "hwy/foreach_target.h"
#include "hwy/highway.h"
#include "hwy/tests/test_util-inl.h"
HWY_BEFORE_NAMESPACE();
namespace hwy {
namespace HWY_NAMESPACE {
struct TestDiv {
template <typename T, class D>
HWY_NOINLINE void operator()(T /*unused*/, D d) {
const auto v = Iota(d, T(-2));
const auto v1 = Set(d, T(1));
// Unchanged after division by 1.
HWY_ASSERT_VEC_EQ(d, v, Div(v, v1));
const size_t N = Lanes(d);
auto expected = AllocateAligned<T>(N);
for (size_t i = 0; i < N; ++i) {
expected[i] = (T(i) - 2) / T(2);
}
HWY_ASSERT_VEC_EQ(d, expected.get(), Div(v, Set(d, T(2))));
}
};
HWY_NOINLINE void TestAllDiv() { ForFloatTypes(ForPartialVectors<TestDiv>()); }
struct TestApproximateReciprocal {
template <typename T, class D>
HWY_NOINLINE void operator()(T /*unused*/, D d) {
const auto v = Iota(d, T(-2));
const auto nonzero = IfThenElse(Eq(v, Zero(d)), Set(d, T(1)), v);
const size_t N = Lanes(d);
auto input = AllocateAligned<T>(N);
Store(nonzero, d, input.get());
auto actual = AllocateAligned<T>(N);
Store(ApproximateReciprocal(nonzero), d, actual.get());
double max_l1 = 0.0;
double worst_expected = 0.0;
double worst_actual = 0.0;
for (size_t i = 0; i < N; ++i) {
const double expected = 1.0 / input[i];
const double l1 = std::abs(expected - actual[i]);
if (l1 > max_l1) {
max_l1 = l1;
worst_expected = expected;
worst_actual = actual[i];
}
}
const double abs_worst_expected = std::abs(worst_expected);
if (abs_worst_expected > 1E-5) {
const double max_rel = max_l1 / abs_worst_expected;
fprintf(stderr, "max l1 %f rel %f (%f vs %f)\n", max_l1, max_rel,
worst_expected, worst_actual);
HWY_ASSERT(max_rel < 0.004);
}
}
};
HWY_NOINLINE void TestAllApproximateReciprocal() {
ForPartialVectors<TestApproximateReciprocal>()(float());
}
struct TestSquareRoot {
template <typename T, class D>
HWY_NOINLINE void operator()(T /*unused*/, D d) {
const auto vi = Iota(d, 0);
HWY_ASSERT_VEC_EQ(d, vi, Sqrt(Mul(vi, vi)));
}
};
HWY_NOINLINE void TestAllSquareRoot() {
ForFloatTypes(ForPartialVectors<TestSquareRoot>());
}
struct TestReciprocalSquareRoot {
template <typename T, class D>
HWY_NOINLINE void operator()(T /*unused*/, D d) {
const auto v = Set(d, 123.0f);
const size_t N = Lanes(d);
auto lanes = AllocateAligned<T>(N);
Store(ApproximateReciprocalSqrt(v), d, lanes.get());
for (size_t i = 0; i < N; ++i) {
float err = lanes[i] - 0.090166f;
if (err < 0.0f) err = -err;
if (err >= 4E-4f) {
HWY_ABORT("Lane %" PRIu64 "(%" PRIu64 "): actual %f err %f\n",
static_cast<uint64_t>(i), static_cast<uint64_t>(N), lanes[i],
err);
}
}
}
};
HWY_NOINLINE void TestAllReciprocalSquareRoot() {
ForPartialVectors<TestReciprocalSquareRoot>()(float());
}
template <typename T, class D>
AlignedFreeUniquePtr<T[]> RoundTestCases(T /*unused*/, D d, size_t& padded) {
const T eps = std::numeric_limits<T>::epsilon();
const T test_cases[] = {
// +/- 1
T(1),
T(-1),
// +/- 0
T(0),
T(-0),
// near 0
T(0.4),
T(-0.4),
// +/- integer
T(4),
T(-32),
// positive near limit
MantissaEnd<T>() - T(1.5),
MantissaEnd<T>() + T(1.5),
// negative near limit
-MantissaEnd<T>() - T(1.5),
-MantissaEnd<T>() + T(1.5),
// positive tiebreak
T(1.5),
T(2.5),
// negative tiebreak
T(-1.5),
T(-2.5),
// positive +/- delta
T(2.0001),
T(3.9999),
// negative +/- delta
T(-999.9999),
T(-998.0001),
// positive +/- epsilon
T(1) + eps,
T(1) - eps,
// negative +/- epsilon
T(-1) + eps,
T(-1) - eps,
// +/- huge (but still fits in float)
T(1E34),
T(-1E35),
// +/- infinity
std::numeric_limits<T>::infinity(),
-std::numeric_limits<T>::infinity(),
// qNaN
GetLane(NaN(d))
};
const size_t kNumTestCases = sizeof(test_cases) / sizeof(test_cases[0]);
const size_t N = Lanes(d);
padded = RoundUpTo(kNumTestCases, N); // allow loading whole vectors
auto in = AllocateAligned<T>(padded);
auto expected = AllocateAligned<T>(padded);
std::copy(test_cases, test_cases + kNumTestCases, in.get());
std::fill(in.get() + kNumTestCases, in.get() + padded, T(0));
return in;
}
struct TestRound {
template <typename T, class D>
HWY_NOINLINE void operator()(T t, D d) {
size_t padded;
auto in = RoundTestCases(t, d, padded);
auto expected = AllocateAligned<T>(padded);
for (size_t i = 0; i < padded; ++i) {
// Avoid [std::]round, which does not round to nearest *even*.
// NOTE: std:: version from C++11 cmath is not defined in RVV GCC, see
// https://lists.freebsd.org/pipermail/freebsd-current/2014-January/048130.html
expected[i] = static_cast<T>(nearbyint(in[i]));
}
for (size_t i = 0; i < padded; i += Lanes(d)) {
HWY_ASSERT_VEC_EQ(d, &expected[i], Round(Load(d, &in[i])));
}
}
};
HWY_NOINLINE void TestAllRound() {
ForFloatTypes(ForPartialVectors<TestRound>());
}
struct TestNearestInt {
template <typename TF, class DF>
HWY_NOINLINE void operator()(TF tf, const DF df) {
using TI = MakeSigned<TF>;
const RebindToSigned<DF> di;
size_t padded;
auto in = RoundTestCases(tf, df, padded);
auto expected = AllocateAligned<TI>(padded);
constexpr double max = static_cast<double>(LimitsMax<TI>());
for (size_t i = 0; i < padded; ++i) {
if (std::isnan(in[i])) {
// We replace NaN with 0 below (no_nan)
expected[i] = 0;
} else if (std::isinf(in[i]) || double(std::abs(in[i])) >= max) {
// Avoid undefined result for lrintf
expected[i] = std::signbit(in[i]) ? LimitsMin<TI>() : LimitsMax<TI>();
} else {
expected[i] = static_cast<TI>(lrintf(in[i]));
}
}
for (size_t i = 0; i < padded; i += Lanes(df)) {
const auto v = Load(df, &in[i]);
const auto no_nan = IfThenElse(Eq(v, v), v, Zero(df));
HWY_ASSERT_VEC_EQ(di, &expected[i], NearestInt(no_nan));
}
}
};
HWY_NOINLINE void TestAllNearestInt() {
ForPartialVectors<TestNearestInt>()(float());
}
struct TestTrunc {
template <typename T, class D>
HWY_NOINLINE void operator()(T t, D d) {
size_t padded;
auto in = RoundTestCases(t, d, padded);
auto expected = AllocateAligned<T>(padded);
for (size_t i = 0; i < padded; ++i) {
// NOTE: std:: version from C++11 cmath is not defined in RVV GCC, see
// https://lists.freebsd.org/pipermail/freebsd-current/2014-January/048130.html
expected[i] = static_cast<T>(trunc(in[i]));
}
for (size_t i = 0; i < padded; i += Lanes(d)) {
HWY_ASSERT_VEC_EQ(d, &expected[i], Trunc(Load(d, &in[i])));
}
}
};
HWY_NOINLINE void TestAllTrunc() {
ForFloatTypes(ForPartialVectors<TestTrunc>());
}
struct TestCeil {
template <typename T, class D>
HWY_NOINLINE void operator()(T t, D d) {
size_t padded;
auto in = RoundTestCases(t, d, padded);
auto expected = AllocateAligned<T>(padded);
for (size_t i = 0; i < padded; ++i) {
expected[i] = std::ceil(in[i]);
}
for (size_t i = 0; i < padded; i += Lanes(d)) {
HWY_ASSERT_VEC_EQ(d, &expected[i], Ceil(Load(d, &in[i])));
}
}
};
HWY_NOINLINE void TestAllCeil() {
ForFloatTypes(ForPartialVectors<TestCeil>());
}
struct TestFloor {
template <typename T, class D>
HWY_NOINLINE void operator()(T t, D d) {
size_t padded;
auto in = RoundTestCases(t, d, padded);
auto expected = AllocateAligned<T>(padded);
for (size_t i = 0; i < padded; ++i) {
expected[i] = std::floor(in[i]);
}
for (size_t i = 0; i < padded; i += Lanes(d)) {
HWY_ASSERT_VEC_EQ(d, &expected[i], Floor(Load(d, &in[i])));
}
}
};
HWY_NOINLINE void TestAllFloor() {
ForFloatTypes(ForPartialVectors<TestFloor>());
}
struct TestAbsDiff {
template <typename T, class D>
HWY_NOINLINE void operator()(T /*unused*/, D d) {
const size_t N = Lanes(d);
auto in_lanes_a = AllocateAligned<T>(N);
auto in_lanes_b = AllocateAligned<T>(N);
auto out_lanes = AllocateAligned<T>(N);
for (size_t i = 0; i < N; ++i) {
in_lanes_a[i] = static_cast<T>((i ^ 1u) << i);
in_lanes_b[i] = static_cast<T>(i << i);
out_lanes[i] = std::abs(in_lanes_a[i] - in_lanes_b[i]);
}
const auto a = Load(d, in_lanes_a.get());
const auto b = Load(d, in_lanes_b.get());
const auto expected = Load(d, out_lanes.get());
HWY_ASSERT_VEC_EQ(d, expected, AbsDiff(a, b));
HWY_ASSERT_VEC_EQ(d, expected, AbsDiff(b, a));
}
};
HWY_NOINLINE void TestAllAbsDiff() {
ForPartialVectors<TestAbsDiff>()(float());
}
// NOLINTNEXTLINE(google-readability-namespace-comments)
} // namespace HWY_NAMESPACE
} // namespace hwy
HWY_AFTER_NAMESPACE();
#if HWY_ONCE
namespace hwy {
HWY_BEFORE_TEST(HwyFloatTest);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllDiv);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllApproximateReciprocal);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllSquareRoot);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllReciprocalSquareRoot);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllRound);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllNearestInt);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllTrunc);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllCeil);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllFloor);
HWY_EXPORT_AND_TEST_P(HwyFloatTest, TestAllAbsDiff);
} // namespace hwy
#endif
| 29.752841 | 85 | 0.634107 |
cca07433d59940f7b8172a0a5d80ae06fa005e53 | 22 | cpp | C++ | src/DlibDotNet.Native.Dnn/dlib/dnn/loss/loss_mmod.cpp | valerysntx/DlibDotNet | 00f8f71834fd4239f2d5c9bc072aa02efaa1a39f | [
"MIT"
] | 1 | 2019-05-07T07:02:17.000Z | 2019-05-07T07:02:17.000Z | src/DlibDotNet.Native.Dnn/dlib/dnn/loss/loss_mmod.cpp | valerysntx/DlibDotNet | 00f8f71834fd4239f2d5c9bc072aa02efaa1a39f | [
"MIT"
] | null | null | null | src/DlibDotNet.Native.Dnn/dlib/dnn/loss/loss_mmod.cpp | valerysntx/DlibDotNet | 00f8f71834fd4239f2d5c9bc072aa02efaa1a39f | [
"MIT"
] | 1 | 2019-04-24T02:15:03.000Z | 2019-04-24T02:15:03.000Z | #include "loss_mmod.h" | 22 | 22 | 0.772727 |
cca1994074eed5734a9fbc22fbe4099d5f9fc42f | 2,075 | hpp | C++ | src/Module/Modem/SCMA/Modem_SCMA.hpp | OlivierHartmann/aff3ct | 58c66228b24e09463bd43ea6453ef18bcacd4d8f | [
"MIT"
] | null | null | null | src/Module/Modem/SCMA/Modem_SCMA.hpp | OlivierHartmann/aff3ct | 58c66228b24e09463bd43ea6453ef18bcacd4d8f | [
"MIT"
] | 4 | 2018-09-27T16:46:31.000Z | 2018-11-22T11:10:41.000Z | src/Module/Modem/SCMA/Modem_SCMA.hpp | OlivierHartmann/aff3ct | 58c66228b24e09463bd43ea6453ef18bcacd4d8f | [
"MIT"
] | null | null | null | #ifndef MODEM_SCMA_HPP_
#define MODEM_SCMA_HPP_
#include <complex>
#include <vector>
#include "Tools/Code/SCMA/modem_SCMA_functions.hpp"
#include "../Modem.hpp"
namespace aff3ct
{
namespace module
{
template <typename B = int, typename R = float, typename Q = R, tools::proto_psi<Q> PSI = tools::psi_0>
class Modem_SCMA : public Modem<B,R,Q>
{
private:
const static std::complex<float> CB[6][4][4];
const int re_user[4][3] = {{1,2,4},{0,2,5},{1,3,5},{0,3,4}};
Q arr_phi[4][4][4][4] = {}; // probability functions
const bool disable_sig2;
R n0; // 1 / n0 = 179.856115108
const int n_ite;
public:
Modem_SCMA(const int N, const tools::Noise<R>& noise = tools::Sigma<R>(), const int bps = 3, const bool disable_sig2 = false,
const int n_ite = 1, const int n_frames = 6);
virtual ~Modem_SCMA() = default;
virtual void set_noise(const tools::Noise<R>& noise);
virtual void modulate ( const B* X_N1, R *X_N2, const int frame_id = -1); using Modem<B,R,Q>::modulate;
virtual void demodulate ( const Q *Y_N1, Q *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::demodulate;
virtual void demodulate_wg(const R *H_N, const Q *Y_N1, Q *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::demodulate_wg;
virtual void filter ( const R *Y_N1, R *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::filter;
static bool is_complex_mod()
{
return true;
}
static bool is_complex_fil()
{
return true;
}
static int size_mod(const int N, const int bps)
{
return ((int)std::pow(2,bps) * ((N +1) / 2));
}
static int size_fil(const int N, const int bps)
{
return size_mod(N, bps);
}
private:
Q phi(const Q* Y_N1, int i, int j, int k, int re, int batch);
Q phi(const Q* Y_N1, int i, int j, int k, int re, int batch, const R* H_N);
void demodulate_batch(const Q* Y_N1, Q* Y_N2, int batch);
};
}
}
#include "Modem_SCMA.hxx"
#endif /* MODEM_SCMA_HPP_ */
| 30.072464 | 126 | 0.61012 |
cca36cc4b702dcbc13369012d2af07499411556b | 1,180 | cpp | C++ | core/optimization/Variable.cpp | metalicn20/charge | 038bbfa14d8f08ffc359d877419b6b984c60ab85 | [
"MIT"
] | null | null | null | core/optimization/Variable.cpp | metalicn20/charge | 038bbfa14d8f08ffc359d877419b6b984c60ab85 | [
"MIT"
] | null | null | null | core/optimization/Variable.cpp | metalicn20/charge | 038bbfa14d8f08ffc359d877419b6b984c60ab85 | [
"MIT"
] | null | null | null | #include "Variable.h"
using namespace std;
Variable::Variable(Alloymaker &alloymaker)
{
setAlloymaker(alloymaker);
}
void Variable::setAlloymaker(Alloymaker &value)
{
alloymaker = &value;
}
Alloymaker &Variable::getAlloymaker()
{
return *alloymaker;
}
double Variable::composition(Standard &std)
{
vector<string> &symbols = std.getSymbols();
size_t length = symbols.size();
double sum = 0;
for (size_t i = 0; i < length; i++)
{
string element = symbols[i];
auto &cmp = getAlloymaker().getCompositions().get(element);
sum += cmp.getPercentage();
}
return sum * amount();
}
double Variable::goal()
{
return alloymaker->getPrice();
}
double Variable::amount()
{
return 1 - alloymaker->getLossPercentage() / 100;
}
double Variable::capacity()
{
return 1;
}
double Variable::lowerBound()
{
return alloymaker->getLowerBound();
}
double Variable::upperBound()
{
return alloymaker->getUpperBound();
}
bool Variable::isInteger()
{
return alloymaker->getIsQuantified();
}
void Variable::setAnswer(double value)
{
answer = value;
}
double Variable::getAnswer()
{
return answer;
}
| 15.733333 | 67 | 0.659322 |
ccb2eda4b66331f8b88bdf846cb6e661b814ea75 | 1,107 | hpp | C++ | include/service_log.hpp | magicmoremagic/bengine-core | fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19 | [
"MIT"
] | null | null | null | include/service_log.hpp | magicmoremagic/bengine-core | fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19 | [
"MIT"
] | null | null | null | include/service_log.hpp | magicmoremagic/bengine-core | fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19 | [
"MIT"
] | null | null | null | #pragma once
#ifndef BE_CORE_SERVICE_LOG_HPP_
#define BE_CORE_SERVICE_LOG_HPP_
#include "service.hpp"
#include "service_ids.hpp"
#include "console_log_sink.hpp"
#include "log.hpp"
namespace be {
///////////////////////////////////////////////////////////////////////////////
template <>
struct SuppressUndefinedService<Log> : True { };
///////////////////////////////////////////////////////////////////////////////
template <>
struct ServiceTraits<Log> : ServiceTraits<> {
using lazy_ids = yes;
};
///////////////////////////////////////////////////////////////////////////////
template <>
struct ServiceName<Log> {
const char* operator()() {
return "Log";
}
};
///////////////////////////////////////////////////////////////////////////////
template <>
struct ServiceFactory<Log> {
std::unique_ptr<Log> operator()(Id id) {
std::unique_ptr<Log> ptr = std::make_unique<Log>();
if (id == Id()) {
ptr->sink(ConsoleLogSink());
} else if (id == ids::core_service_log_void) {
ptr->verbosity_mask(0);
}
return ptr;
}
};
} // be
#endif
| 23.0625 | 79 | 0.455285 |
ccb46faba940aeba89adb75ed17c2ba62fc87e42 | 365 | cpp | C++ | src/messages/CountMessage.cpp | Wolkabout/offset-printing-machine-simulator-lib | 673c45692b7f12c189e7d6d6007d01913bf868b7 | [
"Apache-2.0"
] | null | null | null | src/messages/CountMessage.cpp | Wolkabout/offset-printing-machine-simulator-lib | 673c45692b7f12c189e7d6d6007d01913bf868b7 | [
"Apache-2.0"
] | null | null | null | src/messages/CountMessage.cpp | Wolkabout/offset-printing-machine-simulator-lib | 673c45692b7f12c189e7d6d6007d01913bf868b7 | [
"Apache-2.0"
] | null | null | null | //
// Created by nvuletic on 8.8.19..
//
#include "CountMessage.h"
namespace simulator
{
CountMessage::CountMessage(int count, double percentage) : m_count(count), m_percentage(percentage) {}
int CountMessage::getCount() const
{
return m_count;
}
double CountMessage::getPercentage() const
{
return m_percentage;
}
}
| 17.380952 | 106 | 0.652055 |
ccb9df76d6dfaf384b37dd43a57b8e7429c39983 | 4,862 | cpp | C++ | src/IFTTTWebhook.cpp | Onset/IFTTTWebhook | 1b23992a5cac55cba787f0187e8f74986aa8a752 | [
"MIT"
] | 30 | 2018-05-20T12:59:03.000Z | 2022-03-16T00:26:16.000Z | src/IFTTTWebhook.cpp | Onset/IFTTTWebhook | 1b23992a5cac55cba787f0187e8f74986aa8a752 | [
"MIT"
] | 9 | 2018-04-11T01:30:21.000Z | 2019-10-03T14:55:14.000Z | src/IFTTTWebhook.cpp | Onset/IFTTTWebhook | 1b23992a5cac55cba787f0187e8f74986aa8a752 | [
"MIT"
] | 16 | 2018-03-31T04:40:16.000Z | 2021-12-03T18:55:41.000Z | /*
IFTTTWebhook.cpp
Created by John Romkey - https://romkey.com/
March 24, 2018
*/
#ifndef ESP32
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#endif
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#endif
#include "IFTTTWebhook.h"
IFTTTWebhook::IFTTTWebhook(const char* api_key, const char* event_name) : IFTTTWebhook::IFTTTWebhook(api_key, event_name, DEFAULT_IFTTT_FINGERPRINT) {
}
IFTTTWebhook::IFTTTWebhook(const char* api_key, const char* event_name, const char* ifttt_fingerprint) {
_api_key = api_key;
_event_name = event_name;
_ifttt_fingerprint = ifttt_fingerprint;
}
int IFTTTWebhook::trigger() {
return IFTTTWebhook::trigger(NULL, NULL, NULL);
}
int IFTTTWebhook::trigger(const char* value1) {
return IFTTTWebhook::trigger(value1, NULL, NULL);
}
int IFTTTWebhook::trigger(const char* value1, const char* value2) {
return IFTTTWebhook::trigger(value1, value2, NULL);
}
#ifdef ESP32
const char* _ifttt_root_certificate = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIE0DCCA7igAwIBAgIBBzANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx" \
"EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT" \
"EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp" \
"ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTExMDUwMzA3MDAwMFoXDTMxMDUwMzA3" \
"MDAwMFowgbQxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH" \
"EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjEtMCsGA1UE" \
"CxMkaHR0cDovL2NlcnRzLmdvZGFkZHkuY29tL3JlcG9zaXRvcnkvMTMwMQYDVQQD" \
"EypHbyBEYWRkeSBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IC0gRzIwggEi" \
"MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC54MsQ1K92vdSTYuswZLiBCGzD" \
"BNliF44v/z5lz4/OYuY8UhzaFkVLVat4a2ODYpDOD2lsmcgaFItMzEUz6ojcnqOv" \
"K/6AYZ15V8TPLvQ/MDxdR/yaFrzDN5ZBUY4RS1T4KL7QjL7wMDge87Am+GZHY23e" \
"cSZHjzhHU9FGHbTj3ADqRay9vHHZqm8A29vNMDp5T19MR/gd71vCxJ1gO7GyQ5HY" \
"pDNO6rPWJ0+tJYqlxvTV0KaudAVkV4i1RFXULSo6Pvi4vekyCgKUZMQWOlDxSq7n" \
"eTOvDCAHf+jfBDnCaQJsY1L6d8EbyHSHyLmTGFBUNUtpTrw700kuH9zB0lL7AgMB" \
"AAGjggEaMIIBFjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV" \
"HQ4EFgQUQMK9J47MNIMwojPX+2yz8LQsgM4wHwYDVR0jBBgwFoAUOpqFBxBnKLbv" \
"9r0FQW4gwZTaD94wNAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8v" \
"b2NzcC5nb2RhZGR5LmNvbS8wNQYDVR0fBC4wLDAqoCigJoYkaHR0cDovL2NybC5n" \
"b2RhZGR5LmNvbS9nZHJvb3QtZzIuY3JsMEYGA1UdIAQ/MD0wOwYEVR0gADAzMDEG" \
"CCsGAQUFBwIBFiVodHRwczovL2NlcnRzLmdvZGFkZHkuY29tL3JlcG9zaXRvcnkv" \
"MA0GCSqGSIb3DQEBCwUAA4IBAQAIfmyTEMg4uJapkEv/oV9PBO9sPpyIBslQj6Zz" \
"91cxG7685C/b+LrTW+C05+Z5Yg4MotdqY3MxtfWoSKQ7CC2iXZDXtHwlTxFWMMS2" \
"RJ17LJ3lXubvDGGqv+QqG+6EnriDfcFDzkSnE3ANkR/0yBOtg2DZ2HKocyQetawi" \
"DsoXiWJYRBuriSUBAA/NxBti21G00w9RKpv0vHP8ds42pM3Z2Czqrpv1KrKQ0U11" \
"GIo/ikGQI31bS/6kA1ibRrLDYGCD+H1QQc7CoZDDu+8CL9IVVO5EFdkKrqeKM+2x" \
"LXY2JtwE65/3YR8V3Idv7kaWKK2hJn0KCacuBKONvPi8BDAB" \
"-----END CERTIFICATE-----\n";
#endif
int IFTTTWebhook::trigger(const char* value1, const char* value2, const char* value3) {
HTTPClient http;
const char* ifttt_base = "https://maker.ifttt.com/trigger";
int url_length = strlen(ifttt_base) + strlen("/") + strlen(_event_name) + strlen("/with/key/") + strlen(_api_key) + strlen("?") + (strlen("&valuex=")*3);
url_length += (value1 ? strlen(value1) : 0) + (value2 ? strlen(value2) : 0) + (value3 ? strlen(value3) : 0);
url_length += 5;
char ifttt_url[url_length];
#ifdef IFTTT_WEBHOOK_DEBUG
Serial.print("URL length: ");
Serial.println(url_length);
#endif
snprintf(ifttt_url, url_length, "%s/%s/with/key/%s", ifttt_base, _event_name, _api_key);
if(value1 || value2 || value3) {
strcat(ifttt_url, "?");
}
if(value1) {
strcat(ifttt_url, "value1=\"");
strcat(ifttt_url, value1);
strcat(ifttt_url, "\"");
if(value2 || value3) {
strcat(ifttt_url, "&");
}
}
if(value2) {
strcat(ifttt_url, "value2=\"");
strcat(ifttt_url, value2);
strcat(ifttt_url, "\"");
if(value3) {
strcat(ifttt_url, "&");
}
}
if(value3) {
strcat(ifttt_url, "value3=\"");
strcat(ifttt_url, value3);
strcat(ifttt_url, "\"");
}
#ifdef IFTTT_WEBHOOK_DEBUG
Serial.println(ifttt_url);
#endif
#ifdef ESP32
// certificate: openssl s_client -showcerts -connect maker.ifttt.com:443 < /dev/null
http.begin(ifttt_url, _ifttt_root_certificate);
#else
// fingerprint: openssl s_client -connect maker.ifttt.com:443 < /dev/null 2>/dev/null | openssl x509 -fingerprint -noout | cut -d'=' -f2
http.begin(ifttt_url, _ifttt_fingerprint);
#endif
int httpCode = http.GET();
#ifdef IFTTT_WEBHOOK_DEBUG
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if(httpCode == HTTP_CODE_OK) {
Serial.println(http.getString());
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
#endif
http.end();
return httpCode != HTTP_CODE_OK;
}
| 33.763889 | 155 | 0.757507 |
ccbb82240f83480c1dff283a2e241ccafbe73505 | 2,169 | cc | C++ | 2015/day16.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | 2015/day16.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | 2015/day16.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <unordered_map>
#include "string_utils.h"
bool Check(std::unordered_map<std::string_view, int> const &known_facts,
std::vector<std::string_view> const &tokens) {
for (int i = 2; i < tokens.size(); i += 2) {
auto const thing = Trim(tokens[i], ":,");
auto const it = known_facts.find(thing);
if (it == known_facts.end()) {
continue;
}
auto const count = sv2number<int>(Trim(tokens[i + 1], ":,"));
if (it->second != count) {
return false;
}
}
return true;
}
bool Check2(std::unordered_map<std::string_view, int> const &known_facts,
std::vector<std::string_view> const &tokens) {
for (int i = 2; i < tokens.size(); i += 2) {
auto const thing = Trim(tokens[i], ":,");
auto const it = known_facts.find(thing);
if (it == known_facts.end()) {
continue;
}
auto const count = sv2number<int>(Trim(tokens[i + 1], ":,"));
if (thing == "cats" || thing == "trees") {
if (it->second >= count) {
return false;
}
continue;
}
if (thing == "pomeranians" || thing == "goldfish") {
if (it->second <= count) {
return false;
}
continue;
}
if (it->second != count) {
return false;
}
}
return true;
}
int main() {
std::unordered_map<std::string_view, int> known_facts;
known_facts.emplace("children", 3);
known_facts.emplace("cats", 7);
known_facts.emplace("samoyeds", 2);
known_facts.emplace("pomeranians", 3);
known_facts.emplace("akitas", 0);
known_facts.emplace("vizslas", 0);
known_facts.emplace("goldfish", 5);
known_facts.emplace("trees", 3);
known_facts.emplace("cars", 2);
known_facts.emplace("perfumes", 1);
int idx1 = 0;
int idx2 = 0;
std::string line;
while (std::getline(std::cin, line)) {
auto const t = SplitString(line);
if (Check(known_facts, t)) {
assert(idx1 == 0);
idx1 = sv2number<int>(Trim(t[1], ":,"));
}
if (Check2(known_facts, t)) {
assert(idx2 == 0);
idx2 = sv2number<int>(Trim(t[1], ":,"));
}
}
std::cout << idx1 << "\n" << idx2 << "\n";
return 0;
}
| 25.821429 | 73 | 0.573997 |
ccbf07113c9d9e04ac7ea016896648451d095958 | 404 | cpp | C++ | libi3/path_exists.cpp | andreatulimiero/i3pp | 3e1268ec690bce1821d47df11a985145c289573c | [
"BSD-3-Clause"
] | null | null | null | libi3/path_exists.cpp | andreatulimiero/i3pp | 3e1268ec690bce1821d47df11a985145c289573c | [
"BSD-3-Clause"
] | null | null | null | libi3/path_exists.cpp | andreatulimiero/i3pp | 3e1268ec690bce1821d47df11a985145c289573c | [
"BSD-3-Clause"
] | null | null | null | /*
* vim:ts=4:sw=4:expandtab
*
* i3 - an improved dynamic tiling window manager
* © 2009 Michael Stapelberg and contributors (see also: LICENSE)
*
*/
#include "libi3.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
/*
* Checks if the given path exists by calling stat().
*
*/
bool path_exists(const char *path) {
struct stat buf;
return (stat(path, &buf) == 0);
}
| 18.363636 | 65 | 0.653465 |
ccbfb66b552f44a9321a1a584ac12c9fcc48c154 | 1,590 | cpp | C++ | aws-cpp-sdk-iotsitewise/source/model/CreateAccessPolicyRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-iotsitewise/source/model/CreateAccessPolicyRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-iotsitewise/source/model/CreateAccessPolicyRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iotsitewise/model/CreateAccessPolicyRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::IoTSiteWise::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateAccessPolicyRequest::CreateAccessPolicyRequest() :
m_accessPolicyIdentityHasBeenSet(false),
m_accessPolicyResourceHasBeenSet(false),
m_accessPolicyPermission(Permission::NOT_SET),
m_accessPolicyPermissionHasBeenSet(false),
m_clientToken(Aws::Utils::UUID::RandomUUID()),
m_clientTokenHasBeenSet(true),
m_tagsHasBeenSet(false)
{
}
Aws::String CreateAccessPolicyRequest::SerializePayload() const
{
JsonValue payload;
if(m_accessPolicyIdentityHasBeenSet)
{
payload.WithObject("accessPolicyIdentity", m_accessPolicyIdentity.Jsonize());
}
if(m_accessPolicyResourceHasBeenSet)
{
payload.WithObject("accessPolicyResource", m_accessPolicyResource.Jsonize());
}
if(m_accessPolicyPermissionHasBeenSet)
{
payload.WithString("accessPolicyPermission", PermissionMapper::GetNameForPermission(m_accessPolicyPermission));
}
if(m_clientTokenHasBeenSet)
{
payload.WithString("clientToken", m_clientToken);
}
if(m_tagsHasBeenSet)
{
JsonValue tagsJsonMap;
for(auto& tagsItem : m_tags)
{
tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
}
payload.WithObject("tags", std::move(tagsJsonMap));
}
return payload.View().WriteReadable();
}
| 22.714286 | 114 | 0.755975 |
ccbff3113c7f71866afd884399212a87286ec115 | 875 | hpp | C++ | src/ofxSwizzle/detail/functional/increment_decrement.hpp | t6tn4k/ofxSwizzle | 7d5841e738d0f08cb5456b040c5f827be7775131 | [
"MIT"
] | null | null | null | src/ofxSwizzle/detail/functional/increment_decrement.hpp | t6tn4k/ofxSwizzle | 7d5841e738d0f08cb5456b040c5f827be7775131 | [
"MIT"
] | null | null | null | src/ofxSwizzle/detail/functional/increment_decrement.hpp | t6tn4k/ofxSwizzle | 7d5841e738d0f08cb5456b040c5f827be7775131 | [
"MIT"
] | null | null | null | #ifndef OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP
#define OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP
#include <utility>
namespace ofxSwizzle { namespace detail {
struct pre_increment
{
template <typename T>
constexpr auto operator()(T& t) const -> decltype(++t)
{
return ++t;
}
};
struct post_increment
{
template <typename T>
constexpr auto operator()(T& t) const -> decltype(t++)
{
return t++;
}
};
struct pre_decrement
{
template <typename T>
constexpr auto operator()(T& t) const -> decltype(--t)
{
return --t;
}
};
struct post_decrement
{
template <typename T>
constexpr auto operator()(T& t) const -> decltype(t--)
{
return t--;
}
};
} } // namespace ofxSwizzle::detail
#endif // #ifndef OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP
| 18.617021 | 71 | 0.659429 |
ccc12c1372e0e0c2f549742135a4899726092225 | 1,172 | cpp | C++ | bench/bench_message.cpp | motion-workshop/shadowmocap-sdk-cpp | 2df32936bbfb82b17401734ee850a7b710aa3806 | [
"BSD-2-Clause"
] | null | null | null | bench/bench_message.cpp | motion-workshop/shadowmocap-sdk-cpp | 2df32936bbfb82b17401734ee850a7b710aa3806 | [
"BSD-2-Clause"
] | null | null | null | bench/bench_message.cpp | motion-workshop/shadowmocap-sdk-cpp | 2df32936bbfb82b17401734ee850a7b710aa3806 | [
"BSD-2-Clause"
] | null | null | null | #include <benchmark/benchmark.h>
#include <shadowmocap/message.hpp>
#include <algorithm>
#include <random>
#include <vector>
std::vector<char> make_random_bytes(std::size_t n)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(-128, 127);
std::vector<char> buf(n);
std::generate(std::begin(buf), std::end(buf), [&]() { return dis(gen); });
return buf;
}
template <int N>
void BM_MessageViewCreation(benchmark::State &state)
{
using namespace shadowmocap;
using item_type = message_view_item<N>;
auto data = make_random_bytes(state.range(0) * sizeof(item_type));
for (auto _ : state) {
auto v = make_message_view<N>(data);
benchmark::DoNotOptimize(v);
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations()) * state.range(0) *
sizeof(item_type));
}
BENCHMARK_TEMPLATE(BM_MessageViewCreation, 8)->Range(1 << 3, 1 << 7);
BENCHMARK_TEMPLATE(BM_MessageViewCreation, 16)->Range(1 << 2, 1 << 8);
BENCHMARK_TEMPLATE(BM_MessageViewCreation, 32)->Range(1 << 1, 1 << 9);
BENCHMARK_TEMPLATE(BM_MessageViewCreation, 64)->Range(1 << 0, 1 << 10);
| 26.636364 | 78 | 0.674061 |
ccc7cd504f578562c05f68a24fb31a246c31de29 | 1,221 | cpp | C++ | algorithms/cpp/632.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | 3 | 2016-10-01T10:15:09.000Z | 2017-07-09T02:53:36.000Z | algorithms/cpp/632.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | algorithms/cpp/632.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
private:
struct Element {
int val;
int idx;
int row;
Element(int val, int idx, int row): val(val), idx(idx), row(row) {}
bool operator <(const Element &a) const {
return val > a.val;
}
};
public:
vector<int> smallestRange(vector<vector<int>> &nums) {
int maxVal = INT_MIN;
priority_queue<Element> pq;
for (int i = 0; i < nums.size(); i++) {
maxVal = max(maxVal, nums[i][0]);
pq.push(Element(nums[i][0], 0, i));
}
int range = INT_MAX;
vector<int> result(2);
while (pq.size() == nums.size()) {
Element e = pq.top();
pq.pop();
if (maxVal - e.val < range) {
range = maxVal - e.val;
result[0] = e.val;
result[1] = maxVal;
}
if (e.idx+1 < nums[e.row].size()) {
pq.emplace(nums[e.row][e.idx+1], e.idx+1, e.row);
maxVal = max(maxVal, nums[e.row][e.idx+1]);
}
}
return result;
}
};
int main() {
return 0;
}
| 25.978723 | 75 | 0.465192 |
cccb113e383cab85bb0427179ecb4cbe2936ba12 | 1,485 | cpp | C++ | dvdinfo/detect.cpp | XULPlayer/XULPlayer-legacy | 1ab0ad2a196373d81d350bf45c03f690a0bfb8a2 | [
"MIT"
] | 3 | 2017-11-29T07:11:24.000Z | 2020-03-03T19:23:33.000Z | dvdinfo/detect.cpp | XULPlayer/XULPlayer-legacy | 1ab0ad2a196373d81d350bf45c03f690a0bfb8a2 | [
"MIT"
] | null | null | null | dvdinfo/detect.cpp | XULPlayer/XULPlayer-legacy | 1ab0ad2a196373d81d350bf45c03f690a0bfb8a2 | [
"MIT"
] | 1 | 2018-07-12T12:48:52.000Z | 2018-07-12T12:48:52.000Z | #include "dvd_reader.h"
#include "ifo_types.h"
#include "ifo_read.h"
#include "nav_read.h"
#include "cdrom.h"
#include "dvdinfo.h"
int detect_media_type(const char *psz_path)
{
int i_type;
char *psz_dup;
char psz_tmp[20];
dvd_reader_t *dvd;
vcddev_t* p_cddev;
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
if (psz_path == NULL) return TYPE_UNKNOWN;
psz_dup = _strdup(psz_path);
if( psz_path[0] && psz_path[1] == ':' &&
psz_path[2] == '\\' && psz_path[3] == '\0' ) {
psz_dup[2] = '\0';
}
sprintf(psz_tmp, "%c:\\*", psz_path[0]);
hFind = FindFirstFile(psz_tmp, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
free(psz_dup);
return TYPE_NOMEDIA;
}
do {
/*CD?*/
sprintf(psz_tmp, "%c:\\Track*.cda", psz_path[0]);
hFind = FindFirstFile(psz_tmp, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE) {
i_type = TYPE_CD;
}
else {
/*VCD?*/
sprintf(psz_tmp, "%c:\\MPEGAV", psz_path[0]);
hFind = FindFirstFile(psz_tmp, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) break;
i_type = TYPE_VCD;
}
/*go deeper*/
p_cddev = ioctl_Open(psz_dup);
if(p_cddev == NULL) break;
ioctl_Close(p_cddev);
free(psz_dup);
return i_type;
} while (0);
i_type = TYPE_UNKNOWN;
/*DVD?*/
dvd = DVDOpen(psz_dup);
if(dvd != NULL) {
/*go deeper*/
ifo_handle_t *vmg_file;
vmg_file = ifoOpen(dvd, 0);
if(vmg_file != NULL) {
ifoClose(vmg_file);
i_type = TYPE_DVD;
}
DVDClose(dvd);
}
free(psz_dup);
return i_type;
}
| 19.038462 | 51 | 0.642424 |
ccce06e6b4fdbb371e2d9d97416f8c732c9fff2c | 1,540 | cpp | C++ | Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp | KondoA9/OpenSiv3d-GUIKit | 355b2e7940bf00a8ef5fc3001243e450dccdeab9 | [
"MIT"
] | null | null | null | Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp | KondoA9/OpenSiv3d-GUIKit | 355b2e7940bf00a8ef5fc3001243e450dccdeab9 | [
"MIT"
] | 32 | 2021-10-09T10:04:11.000Z | 2022-02-25T06:10:13.000Z | Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp | athnomedical/Aoba | 355b2e7940bf00a8ef5fc3001243e450dccdeab9 | [
"MIT"
] | null | null | null | #include "TimeoutTaskManager.hpp"
namespace s3d::aoba {
size_t TimeoutTaskManager::addTask(const std::function<void()>& task, double ms, bool threading) {
m_timeouts.emplace_back(task, ms, threading);
return m_timeouts[m_timeouts.size() - 1].id();
}
bool TimeoutTaskManager::isAlive(size_t id) const {
for (const auto& timeout : m_timeouts) {
if (timeout.id() == id) {
return timeout.isAlive();
}
}
return false;
}
bool TimeoutTaskManager::isRunning(size_t id) const {
for (const auto& timeout : m_timeouts) {
if (timeout.id() == id) {
return timeout.isRunning();
}
}
return false;
}
void TimeoutTaskManager::update() {
bool timeoutDeletable = true;
for (auto& timeout : m_timeouts) {
timeout.update();
timeoutDeletable &= !timeout.isAlive();
}
if (timeoutDeletable) {
m_timeouts.clear();
m_timeouts.shrink_to_fit();
}
}
bool TimeoutTaskManager::stop(size_t id) {
for (auto& timeout : m_timeouts) {
if (timeout.id() == id) {
return timeout.stop();
}
}
return false;
}
bool TimeoutTaskManager::restart(size_t id) {
for (auto& timeout : m_timeouts) {
if (timeout.id() == id) {
return timeout.restart();
}
}
return false;
}
}
| 26.101695 | 102 | 0.521429 |
ccceb823ea5512a19cbef0aea09a9ecb142d1b44 | 1,577 | cpp | C++ | src/main/cpp/autonomous/AutoRightSideIntake.cpp | calcmogul/Robot-2020 | b416c202794fb7deea0081beff2f986de7001ed9 | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/autonomous/AutoRightSideIntake.cpp | calcmogul/Robot-2020 | b416c202794fb7deea0081beff2f986de7001ed9 | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/autonomous/AutoRightSideIntake.cpp | calcmogul/Robot-2020 | b416c202794fb7deea0081beff2f986de7001ed9 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) FRC Team 3512. All Rights Reserved.
#include <frc/trajectory/constraint/MaxVelocityConstraint.h>
#include <frc/trajectory/constraint/RectangularRegionConstraint.h>
#include <wpi/numbers>
#include "Robot.hpp"
namespace frc3512 {
void Robot::AutoRightSideIntake() {
// Initial Pose - Right in line with the three balls in the Trench Run
const frc::Pose2d kInitialPose{12_m, 1.05_m,
units::radian_t{wpi::numbers::pi}};
// End Pose - Second ball in the Trench Run
const frc::Pose2d kEndPose{7.95_m, 1.05_m,
units::radian_t{wpi::numbers::pi}};
drivetrain.Reset(kInitialPose);
// Add a constraint to slow down the drivetrain while it's
// approaching the balls
frc::RectangularRegionConstraint regionConstraint{
frc::Translation2d{kEndPose.X(),
kEndPose.Y() - 0.5 * Drivetrain::kLength},
// X: First/Closest ball in the trench run
frc::Translation2d{9.82_m + 0.5 * Drivetrain::kLength,
kInitialPose.Y() + 0.5 * Drivetrain::kLength},
frc::MaxVelocityConstraint{1_mps}};
auto config = Drivetrain::MakeTrajectoryConfig();
config.AddConstraint(regionConstraint);
drivetrain.AddTrajectory(kInitialPose, {}, kEndPose, config);
// Intake Balls x2
intake.Deploy();
intake.Start();
if (!m_autonChooser.Suspend([=] { return drivetrain.AtGoal(); })) {
return;
}
intake.Stop();
EXPECT_TRUE(turret.AtGoal());
}
} // namespace frc3512
| 32.183673 | 74 | 0.638554 |
cccebc6745a7bd1add73efc60d91d7422cab2683 | 3,915 | cpp | C++ | Testing/TestEnumConversions.cpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 2 | 2021-01-19T02:21:48.000Z | 2022-03-26T23:05:49.000Z | Testing/TestEnumConversions.cpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 3 | 2020-07-26T18:48:21.000Z | 2020-10-28T00:45:42.000Z | Testing/TestEnumConversions.cpp | pothosware/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T06:22:20.000Z | 2022-03-24T06:22:20.000Z | // Copyright (c) 2019-2020 Nicholas Corgan
// SPDX-License-Identifier: BSD-3-Clause
#include "Utility.hpp"
#include <Pothos/Framework.hpp>
#include <Pothos/Object.hpp>
#include <Pothos/Testing.hpp>
#include <arrayfire.h>
#include <string>
#include <typeinfo>
namespace GPUTests
{
template <typename Type1, typename Type2>
static void testTypesCanConvert()
{
POTHOS_TEST_TRUE(Pothos::Object::canConvert(
typeid(Type1),
typeid(Type2)));
POTHOS_TEST_TRUE(Pothos::Object::canConvert(
typeid(Type2),
typeid(Type1)));
}
template <typename EnumType>
static void testEnumValueConversion(
const std::string& stringVal,
EnumType enumVal)
{
POTHOS_TEST_EQUAL(
enumVal,
Pothos::Object(stringVal).convert<EnumType>());
POTHOS_TEST_EQUAL(
stringVal,
Pothos::Object(enumVal).convert<std::string>());
}
static void testDTypeEnumUsage(
const std::string& dtypeName,
af::dtype afDType)
{
Pothos::DType dtype(dtypeName);
POTHOS_TEST_EQUAL(
afDType,
Pothos::Object(dtype).convert<af::dtype>());
POTHOS_TEST_EQUAL(dtype.size(), af::getSizeOf(afDType));
auto dtypeFromAF = Pothos::Object(afDType).convert<Pothos::DType>();
POTHOS_TEST_EQUAL(dtypeName, dtypeFromAF.name());
testEnumValueConversion(dtypeName, afDType);
}
}
POTHOS_TEST_BLOCK("/gpu/tests", test_af_backend_conversion)
{
GPUTests::testTypesCanConvert<std::string, af::Backend>();
GPUTests::testEnumValueConversion("CPU", ::AF_BACKEND_CPU);
GPUTests::testEnumValueConversion("CUDA", ::AF_BACKEND_CUDA);
GPUTests::testEnumValueConversion("OpenCL", ::AF_BACKEND_OPENCL);
}
POTHOS_TEST_BLOCK("/gpu/tests", test_af_convmode_conversion)
{
GPUTests::testTypesCanConvert<std::string, af::convMode>();
GPUTests::testEnumValueConversion("Default", ::AF_CONV_DEFAULT);
GPUTests::testEnumValueConversion("Expand", ::AF_CONV_EXPAND);
}
POTHOS_TEST_BLOCK("/gpu/tests", test_af_convdomain_conversion)
{
GPUTests::testTypesCanConvert<std::string, af::convDomain>();
GPUTests::testEnumValueConversion("Auto", ::AF_CONV_AUTO);
GPUTests::testEnumValueConversion("Spatial", ::AF_CONV_SPATIAL);
GPUTests::testEnumValueConversion("Freq", ::AF_CONV_FREQ);
}
POTHOS_TEST_BLOCK("/gpu/tests", test_af_randomenginetype_conversion)
{
GPUTests::testTypesCanConvert<std::string, af::randomEngineType>();
GPUTests::testEnumValueConversion("Philox", ::AF_RANDOM_ENGINE_PHILOX);
GPUTests::testEnumValueConversion("Threefry", ::AF_RANDOM_ENGINE_THREEFRY);
GPUTests::testEnumValueConversion("Mersenne", ::AF_RANDOM_ENGINE_MERSENNE);
}
POTHOS_TEST_BLOCK("/gpu/tests", test_af_topkfunction_conversion)
{
GPUTests::testTypesCanConvert<std::string, af::topkFunction>();
GPUTests::testEnumValueConversion("Min", ::AF_TOPK_MIN);
GPUTests::testEnumValueConversion("Max", ::AF_TOPK_MAX);
GPUTests::testEnumValueConversion("Default", ::AF_TOPK_DEFAULT);
}
POTHOS_TEST_BLOCK("/gpu/tests", test_af_dtype_conversion)
{
GPUTests::testTypesCanConvert<Pothos::DType, af::dtype>();
GPUTests::testDTypeEnumUsage("int8", ::b8);
GPUTests::testDTypeEnumUsage("int16", ::s16);
GPUTests::testDTypeEnumUsage("int32", ::s32);
GPUTests::testDTypeEnumUsage("int64", ::s64);
GPUTests::testDTypeEnumUsage("uint8", ::u8);
GPUTests::testDTypeEnumUsage("uint16", ::u16);
GPUTests::testDTypeEnumUsage("uint32", ::u32);
GPUTests::testDTypeEnumUsage("uint64", ::u64);
GPUTests::testDTypeEnumUsage("float32", ::f32);
GPUTests::testDTypeEnumUsage("float64", ::f64);
GPUTests::testDTypeEnumUsage("complex_float32", ::c32);
GPUTests::testDTypeEnumUsage("complex_float64", ::c64);
}
| 34.043478 | 79 | 0.691699 |
ccd4bed9e0c88af04342ae363205dfd1b611a34a | 4,064 | cpp | C++ | algorithm.cpp | sscerr/DRAGONCELLO | 1dfa2a9bf4d6359d5a9257c10f9adf825edd4594 | [
"MIT"
] | 5 | 2020-11-25T22:05:46.000Z | 2021-02-25T07:12:12.000Z | algorithm.cpp | sscerr/DRAGONCELLO | 1dfa2a9bf4d6359d5a9257c10f9adf825edd4594 | [
"MIT"
] | null | null | null | algorithm.cpp | sscerr/DRAGONCELLO | 1dfa2a9bf4d6359d5a9257c10f9adf825edd4594 | [
"MIT"
] | 1 | 2020-11-26T02:21:41.000Z | 2020-11-26T02:21:41.000Z | #include "dragoncello.h"
void DRAGONCELLO::solveTridiagonalSystem(vector<double>& a, vector<double>& b, vector<double>& c, vector<double>& r, vector<double>& u, int n) {
int j = 0;
double bet = 0.0;
vector<double> gam(n,0.); //double gam[n];
// One vector of workspace, gam, is needed.
if (b[0] == 0.0) cerr << "Error 1 in tridag: the first diagonal term is 0!! " << endl;
//If this happens, then you should rewrite your equations as a set of order N-1, with u1 trivially eliminated.
bet = b[0];
u[0] = r[0] / bet;
for (j = 1; j < n; j++) { //Decomposition and forward substitution.
//double* gm = gam+j;
//(*gm) = c[j-1]/bet;
gam[j] = c[j-1]/bet;
//bet = b[j] - a[j]*(*gm);
bet = b[j] - a[j]*gam[j];
if (bet == 0.0){
cout << "j = 0 " << " --> diagonal term b[0] = " << b[0] << " off diagonal term a[0] = " << a[0] << " c[0] = " << c[0] << " u[0] = " << u[0] << " bet = b[0] " << endl;
cout << "j = " << j << " --> diagonal term b[j] = " << b[j] << " off diagonal term a[j] = " << a[j] << " gam[j] = " << gam[j] << " bet = b[j] - a[j]*c[j-1]/bet " << bet << endl;
cerr << "Error 2 in tridag: bet = 0!" << endl;
}
u[j] = (r[j] - a[j]*u[j-1])/bet;
}
for (j = (n-2); j >= 0; j--)
u[j] -= gam[j+1]*u[j+1]; //Backsubstitution.
return ;
}
int DRAGONCELLO::gsl_linalg_solve_tridiag(const vector<double> & diag,
const vector<double> & abovediag,
const vector<double> & belowdiag,
const vector<double> & rhs,
vector<double> & solution)
{
if(diag.size() != rhs.size())
{
cout << "size of diag must match rhs" << endl;
exit(GSL_EBADLEN);
}
else if (abovediag.size() != rhs.size()-1)
{
cout << "size of abovediag must match rhs-1" << endl;
exit(GSL_EBADLEN);
}
else if (belowdiag.size() != rhs.size()-1)
{
cout << "size of belowdiag must match rhs-1" << endl;
exit(GSL_EBADLEN);
}
else if (solution.size() != rhs.size())
{
cout << "size of solution must match rhs" << endl;
exit(GSL_EBADLEN);
}
else
{
return solve_tridiag_nonsym(diag, abovediag, belowdiag, rhs, solution, diag.size());
}
return 0;
}
/* plain gauss elimination, only not bothering with the zeroes
*
* diag[0] abovediag[0] 0 .....
* belowdiag[0] diag[1] abovediag[1] .....
* 0 belowdiag[1] diag[2]
* 0 0 belowdiag[2] .....
*/
int DRAGONCELLO::solve_tridiag_nonsym(const vector<double> & diag,
const vector<double> & abovediag,
const vector<double> & belowdiag,
const vector<double> & rhs,
vector<double> & x,
size_t N)
{
int status = GSL_SUCCESS;
vector<double> alpha(N);
vector<double> z(N);
size_t i, j;
/* Bidiagonalization (eliminating belowdiag)
& rhs update
diag' = alpha
rhs' = z
*/
alpha[0] = diag.at(0);
z[0] = rhs.at(0);
if (alpha[0] == 0) {
status = GSL_EZERODIV;
}
for (i = 1; i < N; i++)
{
const double t = belowdiag.at(i - 1) / alpha[i-1];
alpha[i] = diag.at(i) - t * abovediag.at(i - 1);
z[i] = rhs.at(i) - t * z[i-1];
if (alpha[i] == 0) {
status = GSL_EZERODIV;
}
}
/* backsubstitution */
x.at(N - 1) = z[N - 1] / alpha[N - 1];
if (N >= 2)
{
for (i = N - 2, j = 0; j <= N - 2; j++, i--)
{
x.at(i) = (z[i] - abovediag.at(i) * x.at(i + 1)) / alpha[i];
}
}
if (status == GSL_EZERODIV) {
cout << "Error : matrix must be positive definite!" << "\n";
}
//delete alpha;
//delete z;
return status;
} | 32.512 | 183 | 0.462352 |
ccd778c92e2ae07f2ba0502f88351f5c392bddca | 28,491 | hpp | C++ | boost/graph/r_c_shortest_paths.hpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | boost/graph/r_c_shortest_paths.hpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | boost/graph/r_c_shortest_paths.hpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // r_c_shortest_paths.hpp header file
// Copyright Michael Drexl 2005, 2006.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP
#define BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP
#include <map>
#include <queue>
#include <vector>
#include <list>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/property_map/property_map.hpp>
namespace boost {
// r_c_shortest_paths_label struct
template<class Graph, class Resource_Container>
struct r_c_shortest_paths_label : public boost::enable_shared_from_this<r_c_shortest_paths_label<Graph, Resource_Container> >
{
r_c_shortest_paths_label
( const unsigned long n,
const Resource_Container& rc = Resource_Container(),
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > pl = boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> >(),
const typename graph_traits<Graph>::edge_descriptor& ed = graph_traits<Graph>::edge_descriptor(),
const typename graph_traits<Graph>::vertex_descriptor& vd = graph_traits<Graph>::vertex_descriptor() )
: num( n ),
cumulated_resource_consumption( rc ),
p_pred_label( pl ),
pred_edge( ed ),
resident_vertex( vd ),
b_is_dominated( false ),
b_is_processed( false )
{}
r_c_shortest_paths_label& operator=( const r_c_shortest_paths_label& other )
{
if( this == &other )
return *this;
this->~r_c_shortest_paths_label();
new( this ) r_c_shortest_paths_label( other );
return *this;
}
const unsigned long num;
Resource_Container cumulated_resource_consumption;
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > p_pred_label;
const typename graph_traits<Graph>::edge_descriptor pred_edge;
const typename graph_traits<Graph>::vertex_descriptor resident_vertex;
bool b_is_dominated;
bool b_is_processed;
}; // r_c_shortest_paths_label
template<class Graph, class Resource_Container>
inline bool operator==
( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,
const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )
{
return
l1.cumulated_resource_consumption == l2.cumulated_resource_consumption;
}
template<class Graph, class Resource_Container>
inline bool operator!=
( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,
const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )
{
return
!( l1 == l2 );
}
template<class Graph, class Resource_Container>
inline bool operator<
( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,
const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )
{
return
l1.cumulated_resource_consumption < l2.cumulated_resource_consumption;
}
template<class Graph, class Resource_Container>
inline bool operator>
( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,
const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )
{
return
l2.cumulated_resource_consumption < l1.cumulated_resource_consumption;
}
template<class Graph, class Resource_Container>
inline bool operator<=
( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,
const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )
{
return
l1 < l2 || l1 == l2;
}
template<class Graph, class Resource_Container>
inline bool operator>=
( const r_c_shortest_paths_label<Graph, Resource_Container>& l1,
const r_c_shortest_paths_label<Graph, Resource_Container>& l2 )
{
return l2 < l1 || l1 == l2;
}
template<typename Graph, typename Resource_Container>
inline bool operator<
( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u) {
return *t < *u;
}
template<typename Graph, typename Resource_Container>
inline bool operator<=( const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u ) {
return *t <= *u;
}
template<typename Graph, typename Resource_Container>
inline bool operator>
(
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u ) {
return *t > *u;
}
template<typename Graph, typename Resource_Container>
inline bool operator>=
(
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &t,
const boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > &u) {
return *t >= *u;
}
namespace detail {
// r_c_shortest_paths_dispatch function (body/implementation)
template<class Graph,
class VertexIndexMap,
class EdgeIndexMap,
class Resource_Container,
class Resource_Extension_Function,
class Dominance_Function,
class Label_Allocator,
class Visitor>
void r_c_shortest_paths_dispatch
( const Graph& g,
const VertexIndexMap& vertex_index_map,
const EdgeIndexMap& /*edge_index_map*/,
typename graph_traits<Graph>::vertex_descriptor s,
typename graph_traits<Graph>::vertex_descriptor t,
// each inner vector corresponds to a pareto-optimal path
std::vector
<std::vector
<typename graph_traits
<Graph>::edge_descriptor> >& pareto_optimal_solutions,
std::vector
<Resource_Container>& pareto_optimal_resource_containers,
bool b_all_pareto_optimal_solutions,
// to initialize the first label/resource container
// and to carry the type information
const Resource_Container& rc,
Resource_Extension_Function& ref,
Dominance_Function& dominance,
// to specify the memory management strategy for the labels
Label_Allocator /*la*/,
Visitor vis )
{
pareto_optimal_resource_containers.clear();
pareto_optimal_solutions.clear();
size_t i_label_num = 0;
#if defined(BOOST_NO_CXX11_ALLOCATOR)
typedef
typename
Label_Allocator::template rebind
<r_c_shortest_paths_label
<Graph, Resource_Container> >::other LAlloc;
#else
typedef
typename
std::allocator_traits<Label_Allocator>::template rebind_alloc
<r_c_shortest_paths_label
<Graph, Resource_Container> > LAlloc;
typedef std::allocator_traits<LAlloc> LTraits;
#endif
LAlloc l_alloc;
typedef
boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > Splabel;
std::priority_queue<Splabel, std::vector<Splabel>, std::greater<Splabel> >
unprocessed_labels;
bool b_feasible = true;
Splabel splabel_first_label = boost::allocate_shared<r_c_shortest_paths_label<Graph, Resource_Container> >(
l_alloc,
i_label_num++,
rc,
boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> >(),
typename graph_traits<Graph>::edge_descriptor(),
s );
unprocessed_labels.push( splabel_first_label );
std::vector<std::list<Splabel> > vec_vertex_labels_data( num_vertices( g ) );
iterator_property_map<typename std::vector<std::list<Splabel> >::iterator,
VertexIndexMap>
vec_vertex_labels(vec_vertex_labels_data.begin(), vertex_index_map);
vec_vertex_labels[s].push_back( splabel_first_label );
typedef
std::vector<typename std::list<Splabel>::iterator>
vec_last_valid_positions_for_dominance_data_type;
vec_last_valid_positions_for_dominance_data_type
vec_last_valid_positions_for_dominance_data( num_vertices( g ) );
iterator_property_map<
typename vec_last_valid_positions_for_dominance_data_type::iterator,
VertexIndexMap>
vec_last_valid_positions_for_dominance
(vec_last_valid_positions_for_dominance_data.begin(),
vertex_index_map);
BGL_FORALL_VERTICES_T(v, g, Graph) {
put(vec_last_valid_positions_for_dominance, v, vec_vertex_labels[v].begin());
}
std::vector<size_t> vec_last_valid_index_for_dominance_data( num_vertices( g ), 0 );
iterator_property_map<std::vector<size_t>::iterator, VertexIndexMap>
vec_last_valid_index_for_dominance
(vec_last_valid_index_for_dominance_data.begin(), vertex_index_map);
std::vector<bool>
b_vec_vertex_already_checked_for_dominance_data( num_vertices( g ), false );
iterator_property_map<std::vector<bool>::iterator, VertexIndexMap>
b_vec_vertex_already_checked_for_dominance
(b_vec_vertex_already_checked_for_dominance_data.begin(),
vertex_index_map);
while( !unprocessed_labels.empty() && vis.on_enter_loop(unprocessed_labels, g) )
{
Splabel cur_label = unprocessed_labels.top();
unprocessed_labels.pop();
vis.on_label_popped( *cur_label, g );
// an Splabel object in unprocessed_labels and the respective Splabel
// object in the respective list<Splabel> of vec_vertex_labels share their
// embedded r_c_shortest_paths_label object
// to avoid memory leaks, dominated
// r_c_shortest_paths_label objects are marked and deleted when popped
// from unprocessed_labels, as they can no longer be deleted at the end of
// the function; only the Splabel object in unprocessed_labels still
// references the r_c_shortest_paths_label object
// this is also for efficiency, because the else branch is executed only
// if there is a chance that extending the
// label leads to new undominated labels, which in turn is possible only
// if the label to be extended is undominated
if( !cur_label->b_is_dominated )
{
typename boost::graph_traits<Graph>::vertex_descriptor
i_cur_resident_vertex = cur_label->resident_vertex;
std::list<Splabel>& list_labels_cur_vertex =
get(vec_vertex_labels, i_cur_resident_vertex);
if( list_labels_cur_vertex.size() >= 2
&& vec_last_valid_index_for_dominance[i_cur_resident_vertex]
< list_labels_cur_vertex.size() )
{
typename std::list<Splabel>::iterator outer_iter =
list_labels_cur_vertex.begin();
bool b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = false;
while( outer_iter != list_labels_cur_vertex.end() )
{
Splabel cur_outer_splabel = *outer_iter;
typename std::list<Splabel>::iterator inner_iter = outer_iter;
if( !b_outer_iter_at_or_beyond_last_valid_pos_for_dominance
&& outer_iter ==
get(vec_last_valid_positions_for_dominance,
i_cur_resident_vertex) )
b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = true;
if( !get(b_vec_vertex_already_checked_for_dominance, i_cur_resident_vertex)
|| b_outer_iter_at_or_beyond_last_valid_pos_for_dominance )
{
++inner_iter;
}
else
{
inner_iter =
get(vec_last_valid_positions_for_dominance,
i_cur_resident_vertex);
++inner_iter;
}
bool b_outer_iter_erased = false;
while( inner_iter != list_labels_cur_vertex.end() )
{
Splabel cur_inner_splabel = *inner_iter;
if( dominance( cur_outer_splabel->
cumulated_resource_consumption,
cur_inner_splabel->
cumulated_resource_consumption ) )
{
typename std::list<Splabel>::iterator buf = inner_iter;
++inner_iter;
list_labels_cur_vertex.erase( buf );
if( cur_inner_splabel->b_is_processed )
{
cur_inner_splabel.reset();
}
else
cur_inner_splabel->b_is_dominated = true;
continue;
}
else
++inner_iter;
if( dominance( cur_inner_splabel->
cumulated_resource_consumption,
cur_outer_splabel->
cumulated_resource_consumption ) )
{
typename std::list<Splabel>::iterator buf = outer_iter;
++outer_iter;
list_labels_cur_vertex.erase( buf );
b_outer_iter_erased = true;
if( cur_outer_splabel->b_is_processed )
{
cur_outer_splabel.reset();
}
else
cur_outer_splabel->b_is_dominated = true;
break;
}
}
if( !b_outer_iter_erased )
++outer_iter;
}
if( list_labels_cur_vertex.size() > 1 )
put(vec_last_valid_positions_for_dominance, i_cur_resident_vertex,
(--(list_labels_cur_vertex.end())));
else
put(vec_last_valid_positions_for_dominance, i_cur_resident_vertex,
list_labels_cur_vertex.begin());
put(b_vec_vertex_already_checked_for_dominance,
i_cur_resident_vertex, true);
put(vec_last_valid_index_for_dominance, i_cur_resident_vertex,
list_labels_cur_vertex.size() - 1);
}
}
if( !b_all_pareto_optimal_solutions && cur_label->resident_vertex == t )
{
// the devil don't sleep
if( cur_label->b_is_dominated )
{
cur_label.reset();
}
while( unprocessed_labels.size() )
{
Splabel l = unprocessed_labels.top();
unprocessed_labels.pop();
// delete only dominated labels, because nondominated labels are
// deleted at the end of the function
if( l->b_is_dominated )
{
l.reset();
}
}
break;
}
if( !cur_label->b_is_dominated )
{
cur_label->b_is_processed = true;
vis.on_label_not_dominated( *cur_label, g );
typename graph_traits<Graph>::vertex_descriptor cur_vertex =
cur_label->resident_vertex;
typename graph_traits<Graph>::out_edge_iterator oei, oei_end;
for( boost::tie( oei, oei_end ) = out_edges( cur_vertex, g );
oei != oei_end;
++oei )
{
b_feasible = true;
Splabel new_label = boost::allocate_shared<r_c_shortest_paths_label<Graph, Resource_Container> >(
l_alloc,
i_label_num++,
cur_label->cumulated_resource_consumption,
cur_label,
*oei,
target( *oei, g ) );
b_feasible =
ref( g,
new_label->cumulated_resource_consumption,
new_label->p_pred_label->cumulated_resource_consumption,
new_label->pred_edge );
if( !b_feasible )
{
vis.on_label_not_feasible( *new_label, g );
new_label.reset();
}
else
{
vis.on_label_feasible( *new_label, g );
vec_vertex_labels[new_label->resident_vertex].
push_back( new_label );
unprocessed_labels.push( new_label );
}
}
}
else
{
vis.on_label_dominated( *cur_label, g );
cur_label.reset();
}
}
std::list<Splabel> dsplabels = get(vec_vertex_labels, t);
typename std::list<Splabel>::const_iterator csi = dsplabels.begin();
typename std::list<Splabel>::const_iterator csi_end = dsplabels.end();
// if d could be reached from o
if( !dsplabels.empty() )
{
for( ; csi != csi_end; ++csi )
{
std::vector<typename graph_traits<Graph>::edge_descriptor>
cur_pareto_optimal_path;
boost::shared_ptr<r_c_shortest_paths_label<Graph, Resource_Container> > p_cur_label = *csi;
pareto_optimal_resource_containers.
push_back( p_cur_label->cumulated_resource_consumption );
while( p_cur_label->num != 0 )
{
cur_pareto_optimal_path.push_back( p_cur_label->pred_edge );
p_cur_label = p_cur_label->p_pred_label;
// assertion b_is_valid beyond this point is not correct if the domination function
// requires resource levels to be strictly greater than existing values
//
// Example
// Customers
// id min_arrival max_departure
// 2 0 974
// 3 0 972
// 4 0 964
// 5 678 801
//
// Path A: 2-3-4-5 (times: 0-16-49-84-678)
// Path B: 3-2-4-5 (times: 0-18-51-62-678)
// The partial path 3-2-4 dominates the other partial path 2-3-4,
// though the path 3-2-4-5 does not strictly dominate the path 2-3-4-5
}
pareto_optimal_solutions.push_back( cur_pareto_optimal_path );
if( !b_all_pareto_optimal_solutions )
break;
}
}
BGL_FORALL_VERTICES_T(i, g, Graph) {
std::list<Splabel>& list_labels_cur_vertex = vec_vertex_labels[i];
typename std::list<Splabel>::iterator si = list_labels_cur_vertex.begin();
const typename std::list<Splabel>::iterator si_end = list_labels_cur_vertex.end();
for(; si != si_end; ++si )
{
(*si).reset();
}
}
} // r_c_shortest_paths_dispatch
} // detail
// default_r_c_shortest_paths_visitor struct
struct default_r_c_shortest_paths_visitor
{
template<class Label, class Graph>
void on_label_popped( const Label&, const Graph& ) {}
template<class Label, class Graph>
void on_label_feasible( const Label&, const Graph& ) {}
template<class Label, class Graph>
void on_label_not_feasible( const Label&, const Graph& ) {}
template<class Label, class Graph>
void on_label_dominated( const Label&, const Graph& ) {}
template<class Label, class Graph>
void on_label_not_dominated( const Label&, const Graph& ) {}
template<class Queue, class Graph>
bool on_enter_loop(const Queue& queue, const Graph& graph) {return true;}
}; // default_r_c_shortest_paths_visitor
// default_r_c_shortest_paths_allocator
typedef
std::allocator<int> default_r_c_shortest_paths_allocator;
// default_r_c_shortest_paths_allocator
// r_c_shortest_paths functions (handle/interface)
// first overload:
// - return all pareto-optimal solutions
// - specify Label_Allocator and Visitor arguments
template<class Graph,
class VertexIndexMap,
class EdgeIndexMap,
class Resource_Container,
class Resource_Extension_Function,
class Dominance_Function,
class Label_Allocator,
class Visitor>
void r_c_shortest_paths
( const Graph& g,
const VertexIndexMap& vertex_index_map,
const EdgeIndexMap& edge_index_map,
typename graph_traits<Graph>::vertex_descriptor s,
typename graph_traits<Graph>::vertex_descriptor t,
// each inner vector corresponds to a pareto-optimal path
std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >&
pareto_optimal_solutions,
std::vector<Resource_Container>& pareto_optimal_resource_containers,
// to initialize the first label/resource container
// and to carry the type information
const Resource_Container& rc,
const Resource_Extension_Function& ref,
const Dominance_Function& dominance,
// to specify the memory management strategy for the labels
Label_Allocator la,
Visitor vis )
{
r_c_shortest_paths_dispatch( g,
vertex_index_map,
edge_index_map,
s,
t,
pareto_optimal_solutions,
pareto_optimal_resource_containers,
true,
rc,
ref,
dominance,
la,
vis );
}
// second overload:
// - return only one pareto-optimal solution
// - specify Label_Allocator and Visitor arguments
template<class Graph,
class VertexIndexMap,
class EdgeIndexMap,
class Resource_Container,
class Resource_Extension_Function,
class Dominance_Function,
class Label_Allocator,
class Visitor>
void r_c_shortest_paths
( const Graph& g,
const VertexIndexMap& vertex_index_map,
const EdgeIndexMap& edge_index_map,
typename graph_traits<Graph>::vertex_descriptor s,
typename graph_traits<Graph>::vertex_descriptor t,
std::vector<typename graph_traits<Graph>::edge_descriptor>&
pareto_optimal_solution,
Resource_Container& pareto_optimal_resource_container,
// to initialize the first label/resource container
// and to carry the type information
const Resource_Container& rc,
const Resource_Extension_Function& ref,
const Dominance_Function& dominance,
// to specify the memory management strategy for the labels
Label_Allocator la,
Visitor vis )
{
// each inner vector corresponds to a pareto-optimal path
std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >
pareto_optimal_solutions;
std::vector<Resource_Container> pareto_optimal_resource_containers;
r_c_shortest_paths_dispatch( g,
vertex_index_map,
edge_index_map,
s,
t,
pareto_optimal_solutions,
pareto_optimal_resource_containers,
false,
rc,
ref,
dominance,
la,
vis );
if (!pareto_optimal_solutions.empty()) {
pareto_optimal_solution = pareto_optimal_solutions[0];
pareto_optimal_resource_container = pareto_optimal_resource_containers[0];
}
}
// third overload:
// - return all pareto-optimal solutions
// - use default Label_Allocator and Visitor
template<class Graph,
class VertexIndexMap,
class EdgeIndexMap,
class Resource_Container,
class Resource_Extension_Function,
class Dominance_Function>
void r_c_shortest_paths
( const Graph& g,
const VertexIndexMap& vertex_index_map,
const EdgeIndexMap& edge_index_map,
typename graph_traits<Graph>::vertex_descriptor s,
typename graph_traits<Graph>::vertex_descriptor t,
// each inner vector corresponds to a pareto-optimal path
std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >&
pareto_optimal_solutions,
std::vector<Resource_Container>& pareto_optimal_resource_containers,
// to initialize the first label/resource container
// and to carry the type information
const Resource_Container& rc,
const Resource_Extension_Function& ref,
const Dominance_Function& dominance )
{
r_c_shortest_paths_dispatch( g,
vertex_index_map,
edge_index_map,
s,
t,
pareto_optimal_solutions,
pareto_optimal_resource_containers,
true,
rc,
ref,
dominance,
default_r_c_shortest_paths_allocator(),
default_r_c_shortest_paths_visitor() );
}
// fourth overload:
// - return only one pareto-optimal solution
// - use default Label_Allocator and Visitor
template<class Graph,
class VertexIndexMap,
class EdgeIndexMap,
class Resource_Container,
class Resource_Extension_Function,
class Dominance_Function>
void r_c_shortest_paths
( const Graph& g,
const VertexIndexMap& vertex_index_map,
const EdgeIndexMap& edge_index_map,
typename graph_traits<Graph>::vertex_descriptor s,
typename graph_traits<Graph>::vertex_descriptor t,
std::vector<typename graph_traits<Graph>::edge_descriptor>&
pareto_optimal_solution,
Resource_Container& pareto_optimal_resource_container,
// to initialize the first label/resource container
// and to carry the type information
const Resource_Container& rc,
const Resource_Extension_Function& ref,
const Dominance_Function& dominance )
{
// each inner vector corresponds to a pareto-optimal path
std::vector<std::vector<typename graph_traits<Graph>::edge_descriptor> >
pareto_optimal_solutions;
std::vector<Resource_Container> pareto_optimal_resource_containers;
r_c_shortest_paths_dispatch( g,
vertex_index_map,
edge_index_map,
s,
t,
pareto_optimal_solutions,
pareto_optimal_resource_containers,
false,
rc,
ref,
dominance,
default_r_c_shortest_paths_allocator(),
default_r_c_shortest_paths_visitor() );
if (!pareto_optimal_solutions.empty()) {
pareto_optimal_solution = pareto_optimal_solutions[0];
pareto_optimal_resource_container = pareto_optimal_resource_containers[0];
}
}
// r_c_shortest_paths
// check_r_c_path function
template<class Graph,
class Resource_Container,
class Resource_Extension_Function>
void check_r_c_path( const Graph& g,
const std::vector
<typename graph_traits
<Graph>::edge_descriptor>& ed_vec_path,
const Resource_Container& initial_resource_levels,
// if true, computed accumulated final resource levels must
// be equal to desired_final_resource_levels
// if false, computed accumulated final resource levels must
// be less than or equal to desired_final_resource_levels
bool b_result_must_be_equal_to_desired_final_resource_levels,
const Resource_Container& desired_final_resource_levels,
Resource_Container& actual_final_resource_levels,
const Resource_Extension_Function& ref,
bool& b_is_a_path_at_all,
bool& b_feasible,
bool& b_correctly_extended,
typename graph_traits<Graph>::edge_descriptor&
ed_last_extended_arc )
{
size_t i_size_ed_vec_path = ed_vec_path.size();
std::vector<typename graph_traits<Graph>::edge_descriptor> buf_path;
if( i_size_ed_vec_path == 0 )
b_feasible = true;
else
{
if( i_size_ed_vec_path == 1
|| target( ed_vec_path[0], g ) == source( ed_vec_path[1], g ) )
buf_path = ed_vec_path;
else
for( size_t i = i_size_ed_vec_path ; i > 0; --i )
buf_path.push_back( ed_vec_path[i - 1] );
for( size_t i = 0; i < i_size_ed_vec_path - 1; ++i )
{
if( target( buf_path[i], g ) != source( buf_path[i + 1], g ) )
{
b_is_a_path_at_all = false;
b_feasible = false;
b_correctly_extended = false;
return;
}
}
}
b_is_a_path_at_all = true;
b_feasible = true;
b_correctly_extended = false;
Resource_Container current_resource_levels = initial_resource_levels;
actual_final_resource_levels = current_resource_levels;
for( size_t i = 0; i < i_size_ed_vec_path; ++i )
{
ed_last_extended_arc = buf_path[i];
b_feasible = ref( g,
actual_final_resource_levels,
current_resource_levels,
buf_path[i] );
current_resource_levels = actual_final_resource_levels;
if( !b_feasible )
return;
}
if( b_result_must_be_equal_to_desired_final_resource_levels )
b_correctly_extended =
actual_final_resource_levels == desired_final_resource_levels ?
true : false;
else
{
if( actual_final_resource_levels < desired_final_resource_levels
|| actual_final_resource_levels == desired_final_resource_levels )
b_correctly_extended = true;
}
} // check_path
} // namespace
#endif // BOOST_GRAPH_R_C_SHORTEST_PATHS_HPP
| 37.886968 | 161 | 0.661226 |
ccd893a9826c4837bd402bf73b06c52f897cfd8d | 35,559 | cpp | C++ | kernel/src/kernelimpl.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | kernel/src/kernelimpl.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | kernel/src/kernelimpl.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | #include "ep/cpp/platform.h"
#include "ep/cpp/plugin.h"
#include "kernelimpl.h"
#include "components/stdiostream.h"
#include "components/lua.h"
#include "components/logger.h"
#include "components/timerimpl.h"
#include "components/pluginmanager.h"
#include "components/pluginloader.h"
#include "components/nativepluginloader.h"
#include "ep/cpp/component/resource/kvpstore.h"
#include "components/datasources/imagesource.h"
#include "components/datasources/geomsource.h"
#include "components/datasources/udsource.h"
#include "components/console.h"
// Components that do the Impl dance
#include "components/componentimpl.h"
#include "components/viewimpl.h"
#include "components/commandmanagerimpl.h"
#include "components/resourcemanagerimpl.h"
#include "components/activityimpl.h"
#include "components/resources/metadataimpl.h"
#include "components/resources/resourceimpl.h"
#include "components/resources/udmodelimpl.h"
#include "components/resources/bufferimpl.h"
#include "components/resources/arraybufferimpl.h"
#include "components/resources/materialimpl.h"
#include "components/resources/shaderimpl.h"
#include "components/resources/menuimpl.h"
#include "components/resources/modelimpl.h"
#include "components/resources/textimpl.h"
#include "components/nodes/nodeimpl.h"
#include "components/nodes/scenenodeimpl.h"
#include "components/nodes/udnodeimpl.h"
#include "components/nodes/cameraimpl.h"
#include "components/nodes/simplecameraimpl.h"
#include "components/nodes/geomnodeimpl.h"
#include "components/nodes/textnodeimpl.h"
#include "components/sceneimpl.h"
#include "components/datasources/datasourceimpl.h"
#include "components/broadcasterimpl.h"
#include "components/streamimpl.h"
#include "components/regeximpl.h"
#include "components/primitivegeneratorimpl.h"
#include "components/projectimpl.h"
#include "components/settingsimpl.h"
#include "components/freetype.h"
#include "components/datasources/fontsource.h"
#include "components/resources/fontimpl.h"
#include "components/fileimpl.h"
#include "components/memstreamimpl.h"
#include "components/socketimpl.h"
#include "components/dynamiccomponent.h"
#include "components/varcomponent.h"
#include "components/glue/componentglue.h"
#include "renderscene.h"
#include "eplua.h"
#include "stdcapture.h"
#include "hal/hal.h"
#include "hal/directory.h"
#include "udPlatformUtil.h"
#include "helpers.h"
#include "ep/cpp/filesystem.h"
namespace ep {
Array<const PropertyInfo> Kernel::getProperties() const
{
return Array<const PropertyInfo>{
EP_MAKE_PROPERTY_RO("resourceManager", getResourceManager, "Resource manager", nullptr, 0),
EP_MAKE_PROPERTY_RO("commandManager", getCommandManager, "Command manager", nullptr, 0),
EP_MAKE_PROPERTY_RO("stdOutBroadcaster", getStdOutBroadcaster, "stdout broadcaster", nullptr, 0),
EP_MAKE_PROPERTY_RO("stdErrBroadcaster", getStdErrBroadcaster, "stderr broadcaster", nullptr, 0),
};
}
Array<const MethodInfo> Kernel::getMethods() const
{
return Array<const MethodInfo>{
EP_MAKE_METHOD(exec, "Execute Lua script")
};
}
Array<const EventInfo> Kernel::getEvents() const
{
return Array<const EventInfo>{
EP_MAKE_EVENT(updatePulse, "Periodic update signal")
};
}
Array<const StaticFuncInfo> Kernel::getStaticFuncs() const
{
return Array<const StaticFuncInfo>{
EP_MAKE_STATICFUNC(getEnvironmentVar, "Get an environment variable"),
EP_MAKE_STATICFUNC(setEnvironmentVar, "Set an environment variable")
};
}
ComponentDescInl *Kernel::makeKernelDescriptor(ComponentDescInl *pType)
{
ComponentDescInl *pDesc = epNew(ComponentDescInl);
EPTHROW_IF_NULL(pDesc, Result::AllocFailure, "Memory allocation failed");
pDesc->info = Kernel::componentInfo();
pDesc->info.flags = ComponentInfoFlags::Unregistered;
pDesc->baseClass = Component::componentID();
pDesc->pInit = nullptr;
pDesc->pCreateInstance = nullptr;
pDesc->pCreateImpl = nullptr;
pDesc->pSuperDesc = nullptr;
// build search trees
for (auto &p : Kernel::getPropertiesImpl())
pDesc->propertyTree.insert(p.id, { p, p.pGetterMethod, p.pSetterMethod });
for (auto &m : Kernel::getMethodsImpl())
pDesc->methodTree.insert(m.id, { m, m.pMethod });
for (auto &e : Kernel::getEventsImpl())
pDesc->eventTree.insert(e.id, { e, e.pSubscribe });
for (auto &f : Kernel::getStaticFuncsImpl())
pDesc->staticFuncTree.insert(f.id, { f, (void*)f.pCall });
if (pType)
{
pType->pSuperDesc = pDesc;
// populate the derived kernel from the base
pType->PopulateFromDesc(pDesc);
pDesc = pType;
}
return pDesc;
}
Kernel::Kernel(ComponentDescInl *_pType, Variant::VarMap commandLine)
: Component(Kernel::makeKernelDescriptor(_pType), nullptr, "ep.Kernel0", commandLine)
{
// alloc impl
pImpl = UniquePtr<Impl>(epNew(KernelImpl, this, commandLine));
getImpl()->StartInit(commandLine);
}
Kernel::~Kernel()
{
// HACK: undo chicken/egg hacks
Component::pImpl = nullptr;
(Kernel*&)pKernel = nullptr;
// Unhook the registered components from our stack before they get deleted
const ComponentDesc *pDesc = pType;
while (pDesc)
{
if (pDesc->pSuperDesc && !(pDesc->pSuperDesc->info.flags & ComponentInfoFlags::Unregistered))
{
(const ComponentDesc*&)pDesc->pSuperDesc = nullptr;
break;
}
pDesc = pDesc->pSuperDesc;
}
}
// HACK !!! (GCC and Clang)
// For the implementation of epInternalInit defined in globalinitialisers to override
// the weak version in epplatform.cpp at least one symbol from that file must
// be referenced externally. This has been implemented in below inside
// createInstance().
namespace internal { void *getStaticImplRegistry(); }
Kernel* Kernel::createInstance(Variant::VarMap commandLine, int renderThreadCount)
{
// HACK: create the KernelImplStatic instance here!
((HashMap<SharedString, UniquePtr<RefCounted>>*)internal::getStaticImplRegistry())->insert(componentID(), UniquePtr<KernelImplStatic>::create());
// set $(AppPath) to argv[0]
String exe = commandLine[0].asString();
#if defined(EP_WINDOWS)
Kernel::setEnvironmentVar("AppPath", exe.getLeftAtLast('\\', true));
#else
Kernel::setEnvironmentVar("AppPath", exe.getLeftAtLast('/', true));
#endif
if (!commandLine.get("renderThreadCount"))
{
auto map = commandLine.clone();
map.insert("renderThreadCount", renderThreadCount);
commandLine = std::move(map);
}
return createInstanceInternal(commandLine);
}
KernelImpl::VarAVLTreeAllocator* KernelImpl::s_pVarAVLAllocator;
KernelImpl::WeakRefRegistryMap* KernelImpl::s_pWeakRefRegistry;
KernelImpl::StaticImplRegistryMap* KernelImpl::s_pStaticImplRegistry;
KernelImpl::KernelImpl(Kernel *pInstance, Variant::VarMap initParams)
: ImplSuper(pInstance)
, componentRegistry(256)
, glueRegistry(64)
, instanceRegistry(8192)
, namedInstanceRegistry(4096)
, foreignInstanceRegistry(4096)
, messageHandlers(64)
, commandLineArgs(initParams)
{
s_pInstance->pKernelInstance = pInstance;
}
void KernelImpl::StartInit(Variant::VarMap initParams)
{
// init the kernel
epscope(fail) { DebugFormat("Error creating Kernel\n"); };
renderThreadCount = initParams["renderThreadCount"].as<int>();
// register global environment vars
WrangleEnvironmentVariables();
// register the base Component type
pInstance->registerComponentType<Component, ComponentImpl, ComponentGlue>();
// HACK: update the descriptor with the base class (bootup chicken/egg)
const ComponentDescInl *pComponentBase = componentRegistry.get(Component::componentID())->pDesc;
ComponentDescInl *pDesc = (ComponentDescInl*)pInstance->pType;
while (pDesc->pSuperDesc)
{
// make sure each component in the kernel hierarchy get all the component meta
pDesc->PopulateFromDesc(pComponentBase);
pDesc = (ComponentDescInl*)pDesc->pSuperDesc;
}
pDesc->pSuperDesc = pComponentBase;
// HACK: fix up the base class since we have a kernel instance (bootup chicken/egg)
(Kernel*&)pInstance->pKernel = pInstance;
pInstance->Component::pImpl = pInstance->Component::createImpl(initParams);
// register all the builtin component types
pInstance->registerComponentType<DataSource, DataSourceImpl>();
pInstance->registerComponentType<Broadcaster, BroadcasterImpl>();
pInstance->registerComponentType<Stream, StreamImpl>();
pInstance->registerComponentType<File, FileImpl, void, FileImplStatic>();
pInstance->registerComponentType<StdIOStream>();
pInstance->registerComponentType<MemStream, MemStreamImpl>();
pInstance->registerComponentType<Socket, SocketImpl>();
pInstance->registerComponentType<Regex, RegexImpl>();
pInstance->registerComponentType<Logger>();
pInstance->registerComponentType<PluginManager>();
pInstance->registerComponentType<PluginLoader>();
pInstance->registerComponentType<NativePluginLoader>();
pInstance->registerComponentType<ResourceManager, ResourceManagerImpl>();
pInstance->registerComponentType<CommandManager, CommandManagerImpl>();
pInstance->registerComponentType<Project, ProjectImpl>();
pInstance->registerComponentType<Timer, TimerImpl>();
pInstance->registerComponentType<Settings, SettingsImpl>();
pInstance->registerComponentType<FreeType>();
pInstance->registerComponentType<Lua>();
pInstance->registerComponentType<View, ViewImpl>();
pInstance->registerComponentType<Activity, ActivityImpl>();
pInstance->registerComponentType<Console>();
pInstance->registerComponentType<PrimitiveGenerator, PrimitiveGeneratorImpl, void, PrimitiveGeneratorImplStatic>();
// resources
pInstance->registerComponentType<Resource, ResourceImpl>();
pInstance->registerComponentType<Buffer, BufferImpl>();
pInstance->registerComponentType<ArrayBuffer, ArrayBufferImpl>();
pInstance->registerComponentType<UDModel, UDModelImpl>();
pInstance->registerComponentType<Shader, ShaderImpl>();
pInstance->registerComponentType<Material, MaterialImpl>();
pInstance->registerComponentType<Model, ModelImpl>();
pInstance->registerComponentType<Text, TextImpl, void, TextImplStatic>();
pInstance->registerComponentType<Menu, MenuImpl>();
pInstance->registerComponentType<KVPStore>();
pInstance->registerComponentType<Metadata, MetadataImpl>();
pInstance->registerComponentType<Scene, SceneImpl>();
pInstance->registerComponentType<Font, FontImpl>();
// nodes
pInstance->registerComponentType<Node, NodeImpl>();
pInstance->registerComponentType<SceneNode, SceneImpl>();
pInstance->registerComponentType<Camera, CameraImpl>();
pInstance->registerComponentType<SimpleCamera, SimpleCameraImpl>();
pInstance->registerComponentType<GeomNode, GeomNodeImpl>();
pInstance->registerComponentType<UDNode, UDNodeImpl>();
pInstance->registerComponentType<TextNode, TextNodeImpl>();
// data sources
pInstance->registerComponentType<ImageSource>();
pInstance->registerComponentType<GeomSource>();
pInstance->registerComponentType<UDSource>();
pInstance->registerComponentType<FontSource>();
// dynamic components
pInstance->registerComponentType<DynamicComponent>();
pInstance->registerComponentType<VarComponent>();
// init the HAL
EPTHROW_RESULT(epHAL_Init(), "epHAL_Init() failed");
// create logger and default streams
spLogger = pInstance->createComponent<Logger>();
spLogger->disableCategory(LogCategories::Trace);
try
{
StreamRef spDebugFile = pInstance->createComponent<File>({ { "name", "logfile" }, { "path", "epKernel.log" }, { "flags", FileOpenFlags::Append | FileOpenFlags::Read | FileOpenFlags::Write | FileOpenFlags::Create | FileOpenFlags::Text } });
spLogger->addStream(spDebugFile);
spDebugFile->writeLn("\n*** Logging started ***");
}
catch (...) {}
#if EP_DEBUG
StreamRef spStdIOStream = pInstance->createComponent<StdIOStream>({ { "output", StdIOStreamOutputs::StdDbg }, {"name", "debugout"} });
spLogger->addStream(spStdIOStream);
#endif
// resource manager
spResourceManager = pInstance->createComponent<ResourceManager>({ { "name", "resourcemanager" } });
// command manager
spCommandManager = pInstance->createComponent<CommandManager>({ { "name", "commandmanager" } });
// settings
spSettings = pInstance->createComponent<Settings>({ { "name", "settings" }, { "src", "settings.epset" } });
// plugin manager
spPluginManager = pInstance->createComponent<PluginManager>({ { "name", "pluginmanager" } });
spPluginManager->registerPluginLoader(pInstance->createComponent<NativePluginLoader>());
// Init capture and broadcast of stdout/stderr
spStdOutBC = pInstance->createComponent<Broadcaster>({ { "name", "stdoutbc" } });
stdOutCapture = epNew(StdCapture, stdout);
epscope(fail) { epDelete(stdOutCapture); };
spStdErrBC = pInstance->createComponent<Broadcaster>({ { "name", "stderrbc" } });
stdErrCapture = epNew(StdCapture, stderr);
epscope(fail) { epDelete(stdErrCapture); };
// create lua VM
spLua = pInstance->createComponent<Lua>();
bKernelCreated = true; // TODO: remove this?
}
void KernelImpl::FinishInit()
{
// create the renderer
spRenderer = SharedPtr<Renderer>::create(pInstance, renderThreadCount);
// init the components
InitComponents();
// call application register
if (HasMessageHandler("register"))
{
// TODO: Crash handler?
if (!sendMessage("$register", "#", "register", nullptr))
{
pInstance->onFatal("Fatal error encountered during application register phase.\nSee epKernel.log for details.\n\nExiting...");
pInstance->quit();
}
}
// load the plugins...
Array<const String> pluginPaths;
// search env vars for extra plugin paths
SharedString pluginPathsVar = Kernel::getEnvironmentVar("PluginDirs");
#if defined(EP_WINDOWS)
String delimiters = ";";
#else
String delimiters = ";:";
#endif
pluginPathsVar.tokenise([&](String token, size_t) {
pluginPaths.pushBack(token);
}, delimiters);
// search global settings for extra plugin paths
//...
// default search paths have lower precedence
pluginPaths.concat(Slice<const String>{
"bin/plugins", // *relative path* used during dev
#if defined(EP_LINUX)
"$(HOME)/.local/share/Euclideon/plugins",
#endif
"$(AppPath)plugins",
#if defined(EP_LINUX)
"/usr/local/share/Euclideon/plugins",
"/usr/share/Euclideon/plugins"
#endif
});
LoadAllPlugins(pluginPaths);
// make the kernel timers
spStreamerTimer = pInstance->createComponent<Timer>({ { "interval", 0.033 } });
spStreamerTimer->elapsed.subscribe(FastDelegate<void()>(this, &KernelImpl::StreamerUpdate));
spUpdateTimer = pInstance->createComponent<Timer>({ { "interval", 0.016 } });
spUpdateTimer->elapsed.subscribe(FastDelegate<void()>(this, &KernelImpl::Update));
// call application init
if (HasMessageHandler("init"))
{
// TODO: Crash handler?
if (!sendMessage("$init", "#", "init", commandLineArgs))
{
pInstance->onFatal("Fatal error encountered during application init phase.\nSee epKernel.log for details.\n\nExiting...");
pInstance->quit();
}
}
}
KernelImpl::~KernelImpl()
{
spLua = nullptr;
spResourceManager = nullptr;
spCommandManager = nullptr;
epDelete (stdOutCapture);
epDelete (stdErrCapture);
stdOutCapture = nullptr;
stdErrCapture = nullptr;
spStdErrBC = nullptr;
spStdOutBC = nullptr;
spLogger = nullptr;
spSettings = nullptr;
if (instanceRegistry.begin() != instanceRegistry.end())
{
int count = 0;
DebugFormat("!!!WARNING: Some Components have not been freed\n");
for (const auto &c : instanceRegistry)
{
++count;
DebugFormat("Unfreed Component: {0} ({1}) refCount {2} \n", c.key, c.value->getName(), c.value->use_count());
}
DebugFormat("{0} Unfreed Component(s)\n", count);
}
epHAL_Deinit();
for (const auto &c : componentRegistry)
epDelete(c.value.pDesc);
}
void KernelImpl::Shutdown()
{
// TODO: Consider whether or not to catch exceptions and then continuing the deinit path or just do nothing.
if (spStreamerTimer)
spStreamerTimer->elapsed.unsubscribe(FastDelegate<void()>(this, &KernelImpl::StreamerUpdate));
if (spUpdateTimer)
spUpdateTimer->elapsed.unsubscribe(FastDelegate<void()>(this, &KernelImpl::Update));
// call application deinit
if (HasMessageHandler("deinit"))
sendMessage("$deinit", "#", "deinit", nullptr);
pInstance->setFocusView(nullptr);
spUpdateTimer = nullptr;
spStreamerTimer = nullptr;
spPluginManager = nullptr;
spRenderer = nullptr;
}
void KernelImpl::WrangleEnvironmentVariables()
{
// TODO: ...
}
Array<SharedString> KernelImpl::ScanPluginFolder(String folderPath, Slice<const String> extFilter)
{
EPFindData findData;
EPFind find;
Array<SharedString> pluginFilenames;
SharedString path = Kernel::resolveString(folderPath);
if (!HalDirectory_FindFirst(&find, path.toStringz(), &findData))
return nullptr;
do
{
if (findData.attributes & EPFA_Directory)
{
MutableString<260> childFolderPath(Format, "{0}/{1}", path, String((const char*)findData.pFilename));
Array<SharedString> childNames = ScanPluginFolder(childFolderPath, extFilter);
for (SharedString &cName : childNames)
pluginFilenames.pushBack(std::move(cName));
}
else
{
bool valid = true;
MutableString<260> filename(Format, "{0}/{1}", path, String((const char*)findData.pFilename));
for (auto &ext : extFilter)
{
valid = (filename.endsWithIC(ext));
if (valid)
break;
}
if (valid)
{
pInstance->logInfo(2, " Found {0}", filename);
pluginFilenames.pushBack(filename);
}
}
} while (HalDirectory_FindNext(&find, &findData));
HalDirectory_FindClose(&find);
return pluginFilenames;
}
void KernelImpl::LoadAllPlugins(Slice<const String> folderPaths)
{
for (auto path : folderPaths)
{
pInstance->logInfo(2, "Scanning {0} for plugins...", path);
Array<SharedString> pluginFilenames = ScanPluginFolder(path);
LoadPlugins(pluginFilenames);
}
}
void KernelImpl::LoadPlugins(Slice<SharedString> files)
{
size_t numRemaining = files.length;
size_t lastTry;
do
{
// since plugins may depend on other plugins, we'll keep trying to reload plugins while loads are succeeding
lastTry = numRemaining;
for (auto &filename : files)
{
if (!filename)
continue;
if (spPluginManager->loadPlugin(filename))
{
pInstance->logInfo(2, "Loaded plugin {0}", filename);
filename = nullptr;
--numRemaining;
}
}
} while (numRemaining && numRemaining < lastTry);
// output a warning if any plugins could not be loaded
for (auto &filename : files)
{
if (filename)
logWarning(2, "Could not load plugin '{0}'", filename);
}
}
void KernelImpl::Update()
{
static uint64_t last = udPerfCounterStart();
uint64_t now = udPerfCounterStart();
double sec = (double)udPerfCounterMilliseconds(last, now) / 1000.0;
last = now;
RelayStdIO();
pInstance->updatePulse.signal(sec);
}
void KernelImpl::RelayStdIO()
{
if (stdOutCapture)
{
String str = stdOutCapture->getCapture();
if (!str.empty())
spStdOutBC->write(str);
}
if (stdErrCapture)
{
String str = stdErrCapture->getCapture();
if (!str.empty())
spStdErrBC->write(str);
}
}
void KernelImpl::StreamerUpdate()
{
udStreamerStatus streamerStatus = { 0 };
udOctree_Update(&streamerStatus);
// TODO: Find a cleaner way of doing this. We have to keep rendering while the streamer is active.
// We need more than just a global active , we need an active per view.
if (streamerStatus.active)
{
SceneRef spScene = spFocusView->getScene();
if (spScene)
spScene->makeDirty();
}
}
Array<const ComponentDesc *> KernelImpl::GetDerivedComponentDescsFromString(String id, bool bIncludeBase)
{
ComponentType *compType = componentRegistry.get(id);
if (compType)
return GetDerivedComponentDescs(compType->pDesc, bIncludeBase);
else
return nullptr;
}
Array<const ComponentDesc *> KernelImpl::GetDerivedComponentDescs(const ComponentDesc *pBase, bool bIncludeBase)
{
Array<const ComponentDesc *> derivedDescs;
for (auto ct : componentRegistry)
{
const ComponentDesc *pDesc = ct.value.pDesc;
if(!bIncludeBase)
pDesc = pDesc->pSuperDesc;
while (pDesc)
{
if (pDesc == pBase)
{
derivedDescs.concat(ct.value.pDesc);
break;
}
pDesc = pDesc->pSuperDesc;
}
}
return derivedDescs;
}
bool KernelImpl::sendMessage(String target, String sender, String message, const Variant &data)
{
EPASSERT_THROW(!target.empty(), Result::InvalidArgument, "target was empty");
char targetType = target.popFront();
if (targetType == '@')
{
// component message
Component **ppComponent = instanceRegistry.get(target);
if (ppComponent)
{
ComponentRef spComponent(*ppComponent);
try {
spComponent->receiveMessage(message, sender, data);
} catch (std::exception &e) {
logError("Message Handler {0} failed: {1}", target, e.what());
return false;
} catch (...) {
logError("Message Handler {0} failed: C++ exception", target);
return false;
}
}
else
{
// TODO: check if it's in the foreign component registry and send it there
EPTHROW_ERROR(Result::Failure, "Target component not found");
}
}
else if (targetType == '#')
{
// kernel message
if (target.eq(uid))
{
// it's for me!
try {
ReceiveMessage(sender, message, data);
} catch (std::exception &e) {
logError("Message Handler {0} failed: {1}", target, e.what());
return false;
} catch (...) {
logError("Message Handler {0} failed: C++ exception", target);
return false;
}
}
else
{
// TODO: foreign kernels?!
EPTHROW_ERROR(Result::Failure, "Invalid Kernel");
}
}
else if (targetType == '$')
{
// registered message
MessageCallback *pHandler = messageHandlers.get(target);
if (pHandler)
{
try {
pHandler->callback(sender, message, data);
} catch (std::exception &e) {
logError("Message Handler {0} failed: {1}", target, e.what());
return false;
} catch (...) {
logError("Message Handler {0} failed: C++ exception", target);
return false;
}
}
else
{
EPTHROW_ERROR(Result::Failure, "No Message Handler");
}
}
else
{
EPTHROW_ERROR(Result::Failure, "Invalid target");
}
return true;
}
// ---------------------------------------------------------------------------------------
void KernelImpl::DispatchToMainThread(MainThreadCallback callback)
{
EPASSERT(false, "!!shouldn't be here!!");
}
// ---------------------------------------------------------------------------------------
void KernelImpl::DispatchToMainThreadAndWait(MainThreadCallback callback)
{
EPASSERT(false, "!!shouldn't be here!!");
}
// TODO: Take this hack out once RecieveMessage's body is implemented
#if defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE)
#pragma optimize("", off)
#endif // defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE)
void KernelImpl::ReceiveMessage(String sender, String message, const Variant &data)
{
}
#if defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE)
#pragma optimize("", on)
#endif // defined(EP_COMPILER_VISUALC) && defined(EP_RELEASE)
void KernelImpl::RegisterMessageHandler(SharedString _name, MessageHandler messageHandler)
{
messageHandlers.replace(_name, MessageCallback{ _name, messageHandler });
}
const ComponentDesc* KernelImpl::RegisterComponentType(ComponentDescInl *pDesc)
{
if (pDesc->info.identifier.exists('@') || pDesc->info.identifier.exists('$') || pDesc->info.identifier.exists('#'))
EPTHROW_ERROR(Result::InvalidArgument, "Invalid component id");
// disallow duplicates
if (componentRegistry.get(pDesc->info.identifier))
EPTHROW_ERROR(Result::InvalidArgument, "Component of type id '{0}' has already been registered", pDesc->info.identifier);
// add to registry
componentRegistry.insert(pDesc->info.identifier, ComponentType{ pDesc, 0 });
if (bKernelCreated && pDesc->pInit)
pDesc->pInit(pInstance);
return pDesc;
}
const ComponentDesc* KernelImpl::RegisterComponentTypeFromMap(Variant::VarMap typeDesc)
{
DynamicComponentDesc *pDesc = epNew(DynamicComponentDesc);
pDesc->info.identifier = typeDesc["identifier"].asSharedString();
size_t offset = pDesc->info.identifier.findLast('.');
EPTHROW_IF(offset == (size_t)-1, Result::InvalidArgument, "Component identifier {0} has no namespace. Use form: namespace.componentname", pDesc->info.identifier);
pDesc->info.nameSpace = pDesc->info.identifier.slice(0, offset);
pDesc->info.name = pDesc->info.identifier.slice(offset+1, pDesc->info.identifier.length);
// pDesc->info.displayName = typeDesc["name"].asSharedString(); // TODO: add this back at some point?
pDesc->info.description = typeDesc["description"].asSharedString();
pDesc->info.epVersion = EP_APIVERSION;
Variant *pVar = typeDesc.get("version");
pDesc->info.pluginVersion = pVar ? pVar->asSharedString() : EPKERNEL_PLUGINVERSION;
pVar = typeDesc.get("flags");
pDesc->info.flags = pVar ? pVar->as<ComponentInfoFlags>() : ComponentInfoFlags();
pDesc->baseClass = typeDesc["super"].asSharedString();
pDesc->pInit = nullptr;
pDesc->pCreateImpl = nullptr;
pDesc->pCreateInstance = [](const ComponentDesc *_pType, Kernel *_pKernel, SharedString _uid, Variant::VarMap initParams) -> ComponentRef {
MutableString128 t(Format, "New (From VarMap): {0} - {1}", _pType->info.identifier, _uid);
_pKernel->logDebug(4, t);
const DynamicComponentDesc *pDesc = (const DynamicComponentDesc*)_pType;
DynamicComponentRef spInstance = pDesc->newInstance(KernelRef(_pKernel), initParams);
ComponentRef spC = _pKernel->createGlue(pDesc->baseClass, _pType, _uid, spInstance, initParams);
spInstance->attachToGlue(spC.get(), initParams);
spC->pUserData = spInstance->getUserData();
return spC;
};
pDesc->newInstance = typeDesc["new"].as<DynamicComponentDesc::NewInstanceFunc>();
pDesc->userData = typeDesc["userdata"].asSharedPtr();
// TODO: populate trees from stuff in dynamic descriptor
// pDesc->desc.Get
/*
// build search trees
for (auto &p : CreateHelper<_ComponentType>::GetProperties())
pDesc->propertyTree.insert(p.id, { p, p.pGetterMethod, p.pSetterMethod });
for (auto &m : CreateHelper<_ComponentType>::GetMethods())
pDesc->methodTree.insert(m.id, { m, m.pMethod });
for (auto &e : CreateHelper<_ComponentType>::GetEvents())
pDesc->eventTree.insert(e.id, { e, e.pSubscribe });
for (auto &f : CreateHelper<_ComponentType>::GetStaticFuncs())
pDesc->staticFuncTree.insert(f.id, { f, (void*)f.pCall });
*/
// setup the super class and populate from its meta
pDesc->pSuperDesc = GetComponentDesc(pDesc->baseClass);
EPTHROW_IF(!pDesc->pSuperDesc, Result::InvalidType, "Base Component '{0}' not registered", pDesc->baseClass);
pDesc->PopulateFromDesc((ComponentDescInl*)pDesc->pSuperDesc);
return RegisterComponentType(pDesc);
}
void KernelImpl::RegisterGlueType(String name, CreateGlueFunc *pCreateFunc)
{
glueRegistry.insert(name, pCreateFunc);
}
void* KernelImpl::CreateImpl(String componentType, Component *_pInstance, Variant::VarMap initParams)
{
ComponentDescInl *pDesc = (ComponentDescInl*)GetComponentDesc(componentType);
if (pDesc->pCreateImpl)
return pDesc->pCreateImpl(_pInstance, initParams);
return nullptr;
}
const ComponentDesc* KernelImpl::GetComponentDesc(String id)
{
ComponentType *pCT = componentRegistry.get(id);
if (!pCT)
return nullptr;
return pCT->pDesc;
}
ComponentRef KernelImpl::CreateComponent(String typeId, Variant::VarMap initParams)
{
ComponentType *_pType = componentRegistry.get(typeId);
EPASSERT_THROW(_pType, Result::InvalidArgument, "Unknown component type {0}", typeId);
EPTHROW_IF(_pType->pDesc->info.flags & ComponentInfoFlags::Abstract, Result::InvalidType, "Cannot create component of abstract type '{0}'", typeId);
try
{
const ComponentDescInl *pDesc = _pType->pDesc;
// TODO: should we have a better uid generator than this?
MutableString64 newUid(Concat, pDesc->info.identifier, _pType->createCount++);
// attempt to create an instance
ComponentRef spComponent(pDesc->pCreateInstance(pDesc, pInstance, newUid, initParams));
// add to the component registry
instanceRegistry.insert(spComponent->uid, spComponent.get());
// TODO: inform partner kernels that I created a component
//...
return spComponent;
}
catch (std::exception &e)
{
logWarning(3, "Create component failed: {0}", String(e.what()));
throw;
}
catch (...)
{
logWarning(3, "Create component failed!");
throw;
}
}
ComponentRef KernelImpl::CreateGlue(String typeId, const ComponentDesc *_pType, SharedString _uid, ComponentRef spInstance, Variant::VarMap initParams)
{
CreateGlueFunc **ppCreate = glueRegistry.get(typeId);
EPTHROW_IF_NULL(ppCreate, Result::InvalidType, "No glue type {0}", typeId);
return (*ppCreate)(pInstance, _pType, _uid, spInstance, initParams);
}
void KernelImpl::DestroyComponent(Component *_pInstance)
{
if (_pInstance->name)
namedInstanceRegistry.remove(_pInstance->name);
instanceRegistry.remove(_pInstance->uid);
// TODO: inform partners that I destroyed a component
//...
}
ComponentRef KernelImpl::FindComponent(String _name) const
{
if (_name.empty() || _name[0] == '$' || _name[0] == '#')
return nullptr;
if (_name[0] == '@')
_name.popFront();
Component * const * ppComponent = namedInstanceRegistry.get(_name);
if (!ppComponent)
ppComponent = instanceRegistry.get(_name);
return ppComponent ? ComponentRef(*ppComponent) : nullptr;
}
void KernelImpl::InitComponents()
{
for (auto i : componentRegistry)
{
if (i.value.pDesc->pInit)
i.value.pDesc->pInit(pInstance);
}
}
void KernelImpl::InitRender()
{
Result result = epHAL_InitRender();
EPASSERT_THROW(result == Result::Success, result, "epHAL_InitRender() Failed");
}
void KernelImpl::DeinitRender()
{
epHAL_DeinitRender();
}
void KernelImpl::Exec(String code)
{
spLua->execute(code);
}
void KernelImpl::Log(int kind, int level, String text, String component) const
{
if (spLogger)
spLogger->log(level, text, (LogCategories)kind, component);
}
const AVLTree<String, const ComponentDesc *> &KernelImpl::GetExtensionsRegistry() const
{
return extensionsRegistry;
}
void KernelImpl::RegisterExtensions(const ComponentDesc *pDesc, const Slice<const String> exts)
{
for (const String &e : exts)
extensionsRegistry.insert(e, pDesc);
}
DataSourceRef KernelImpl::CreateDataSourceFromExtension(String ext, Variant::VarMap initParams)
{
const ComponentDesc **ppDesc = extensionsRegistry.get(ext);
EPASSERT_THROW(ppDesc, Result::Failure, "No datasource for extension {0}", ext);
return component_cast<DataSource>(CreateComponent((*ppDesc)->info.identifier, initParams));
}
SharedPtr<Renderer> KernelImpl::GetRenderer() const
{
return spRenderer;
}
CommandManagerRef KernelImpl::GetCommandManager() const
{
return spCommandManager;
}
SettingsRef KernelImpl::GetSettings() const
{
return spSettings;
}
ResourceManagerRef KernelImpl::GetResourceManager() const
{
return spResourceManager;
}
BroadcasterRef KernelImpl::GetStdOutBroadcaster() const
{
return spStdOutBC;
}
BroadcasterRef KernelImpl::GetStdErrBroadcaster() const
{
return spStdErrBC;
}
ViewRef KernelImpl::GetFocusView() const
{
return spFocusView;
}
ViewRef KernelImpl::SetFocusView(ViewRef spView)
{
ViewRef spOld = spFocusView;
spFocusView = spView;
return spOld;
}
void KernelImplStatic::SetEnvironmentVar(String name, String value)
{
#if defined(EP_WINDOWS)
_putenv_s(name.toStringz(), value.toStringz());
#else
setenv(name.toStringz(), value.toStringz(), 1);
#endif
}
MutableString<0> KernelImplStatic::GetEnvironmentVar(String name)
{
#if defined(EP_WINDOWS)
MutableString<0> r;
auto sz = name.toStringz();
size_t size;
getenv_s(&size, nullptr, 0, sz);
if (size)
{
r.reserve(size);
getenv_s(&size, r.ptr, size, sz);
r.length = size-1;
}
return r;
#else
return getenv(name.toStringz());
#endif
}
MutableString<0> KernelImplStatic::ResolveString(String string, bool bRecursive)
{
// TODO: do this loop in blocks rather than one byte at a time!
MutableString<0> r(Reserve, string.length);
for (size_t i = 0; i < string.length; ++i)
{
if (string[i] == '$' && string.length > i+1 && string[i+1] == '$')
{
++i;
r.pushBack(string[i]);
}
else if (string[i] == '$' && string.length > i+2 && string[i+1] == '(')
{
size_t end = i + 2;
while (end < string.length && string[end] != ')')
++end;
String var = string.slice(i+2, end);
auto val = GetEnvironmentVar(var);
if (val)
{
if (bRecursive)
val = ResolveString(val, true);
r.append(val);
}
i = end;
}
else
r.pushBack(string[i]);
}
return r;
}
} // namespace ep
#if __EP_MEMORY_DEBUG__
#if defined(EP_WINDOWS)
namespace ep {
namespace internal {
int reportingHook(int reportType, char* userMessage, int* retVal)
{
static bool filter = true;
static int debugMsgCount = 3;
static int leakCount = 0;
if (strcmp(userMessage, "Object dump complete.\n") == 0)
filter = false;
if (filter)
{
// Debug messages from our program should consist of 4 parts :
// File (line) | AllocID | Block Descriptor | Memory Data
if (!strstr(userMessage, ") : "))
{
++debugMsgCount;
}
else
{
if (leakCount == 0)
OutputDebugStringA("Detected memory leaks!\nDumping objects ->\n");
debugMsgCount = 0;
++leakCount;
}
// Filter the output if it's not from our program
return (debugMsgCount > 3);
}
return (leakCount == 0);
}
} // namespace internal
} // namespace ep
#endif // defined(EP_WINDOWS)
# if defined (epInitMemoryTracking)
# undef epInitMemoryTracking
# endif // epInitMemoryTracking
void epInitMemoryTracking()
{
#if defined(EP_WINDOWS)
const wchar_t *pFilename = L"MemoryReport_"
#if EP_DEBUG
"Debug_"
#else
"Release_"
#endif // EP_DEBUG
#if defined(EP_ARCH_X64)
"x64"
#elif defined(EP_ARCH_X86)
"x86"
#else
# error "Couldn't detect target architecture"
#endif // defined (EP_ARCH_X64)
".txt";
HANDLE hCrtWarnReport = CreateFileW(pFilename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hCrtWarnReport == INVALID_HANDLE_VALUE) OutputDebugStringA("Error creating CrtWarnReport.txt\n");
errno = 0;
int warnMode = _CrtSetReportMode(_CRT_WARN, _CRTDBG_REPORT_MODE);
_CrtSetReportMode(_CRT_WARN, warnMode | _CRTDBG_MODE_FILE);
if (errno == EINVAL) OutputDebugStringA("Error calling _CrtSetReportMode() warnings\n");
errno = 0;
_CrtSetReportFile(_CRT_WARN, hCrtWarnReport);
if (errno == EINVAL)OutputDebugStringA("Error calling _CrtSetReportFile() warnings\n");
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
//change the report function to only report memory leaks from program code
_CrtSetReportHook(ep::internal::reportingHook);
#endif
}
#endif // __EP_MEMORY_DEBUG__
| 31.083042 | 243 | 0.708344 |
ccdd2555f82ecda3316f35a445dd812b38ff13e3 | 193 | hpp | C++ | Classes/GameScene.hpp | InversePalindrome/Apophis | c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8 | [
"MIT"
] | 7 | 2018-08-20T17:28:29.000Z | 2020-09-05T15:19:31.000Z | Classes/GameScene.hpp | InversePalindrome/JATR66 | c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8 | [
"MIT"
] | null | null | null | Classes/GameScene.hpp | InversePalindrome/JATR66 | c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8 | [
"MIT"
] | 1 | 2019-12-25T12:02:03.000Z | 2019-12-25T12:02:03.000Z | /*
Copyright (c) 2018 Inverse Palindrome
Apophis - GameScene.hpp
InversePalindrome.com
*/
#pragma once
#include <cocos/2d/CCScene.h>
cocos2d::Scene* getGameScene(const std::string& level); | 14.846154 | 55 | 0.751295 |
ef9adb4af0ba3756488f6a0f2409d695b815528d | 1,875 | cpp | C++ | src/flapGame/flapGame/LoadPNG.cpp | KnyazQasan/First-Game-c- | 417d312bb57bb2373d6d0a89892a55718bc597dc | [
"MIT"
] | 239 | 2020-11-26T12:53:51.000Z | 2022-03-24T01:02:49.000Z | src/flapGame/flapGame/LoadPNG.cpp | KnyazQasan/First-Game-c- | 417d312bb57bb2373d6d0a89892a55718bc597dc | [
"MIT"
] | 6 | 2020-11-27T04:00:44.000Z | 2021-07-07T03:02:57.000Z | src/flapGame/flapGame/LoadPNG.cpp | KnyazQasan/First-Game-c- | 417d312bb57bb2373d6d0a89892a55718bc597dc | [
"MIT"
] | 24 | 2020-11-26T22:59:27.000Z | 2022-02-06T04:02:50.000Z | #include <flapGame/Core.h>
#include <flapGame/GLHelpers.h>
// clang-format off
#define STBI_MALLOC(sz) PLY_HEAP.alloc(sz)
#define STBI_REALLOC(p, newsz) PLY_HEAP.realloc(p, newsz)
#define STBI_FREE(p) PLY_HEAP.free(p)
// clang-format om
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "stb/stb_image.h"
namespace flap {
void premultiplySRGB(image::Image& dst) {
PLY_ASSERT(dst.stride >= dst.width * 4);
char* dstRow = dst.data;
char* dstRowEnd = dstRow + dst.stride * dst.height;
while (dstRow < dstRowEnd) {
u32* d = (u32*) dstRow;
u32* dEnd = d + dst.width;
while (d < dEnd) {
Float4 orig = ((Int4<u8>*) d)->to<Float4>() * (1.f / 255.f);
Float3 linearPremultipliedColor = fromSRGB(orig.asFloat3()) * orig.a();
Float4 result = {toSRGB(linearPremultipliedColor), 1.f - orig.a()};
*(Int4<u8>*) d = (result * 255.f + 0.5f).to<Int4<u8>>();
d++;
}
dstRow += dst.stride;
}
}
image::OwnImage loadPNG(StringView src, bool premultiply) {
s32 w = 0;
s32 h = 0;
s32 numChannels = 0;
stbi_set_flip_vertically_on_load(true);
u8* data = stbi_load_from_memory((const stbi_uc*) src.bytes, src.numBytes, &w, &h, &numChannels, 0);
if (!data)
return {};
image::Format fmt = image::Format::Byte;
if (numChannels == 4) {
fmt = image::Format::RGBA;
} else if (numChannels != 1) {
PLY_ASSERT(0);
}
u8 bytespp = image::Image::FormatToBPP[(u32) fmt];
image::OwnImage result;
result.data = (char*) data;
result.stride = w * bytespp;
result.width = w;
result.height = h;
result.bytespp = bytespp;
result.format = fmt;
if (premultiply && numChannels == 4) {
premultiplySRGB(result);
}
return result;
}
} // namespace ply
| 28.409091 | 104 | 0.597333 |
ef9f57549e1dd00801d74e754e07ec188ad918e1 | 973 | cpp | C++ | Strings/Longest-Prefix-Suffix.cpp | Bhannasa/CP-DSA | 395dbdb6b5eb5896cc4182711ff086e1fb76ef7a | [
"MIT"
] | 22 | 2021-10-01T20:14:15.000Z | 2022-02-22T15:27:20.000Z | Strings/Longest-Prefix-Suffix.cpp | Bhannasa/CP-DSA | 395dbdb6b5eb5896cc4182711ff086e1fb76ef7a | [
"MIT"
] | 15 | 2021-10-01T20:24:55.000Z | 2021-10-31T05:55:14.000Z | Strings/Longest-Prefix-Suffix.cpp | Bhannasa/CP-DSA | 395dbdb6b5eb5896cc4182711ff086e1fb76ef7a | [
"MIT"
] | 76 | 2021-10-01T20:01:06.000Z | 2022-03-02T16:15:24.000Z | // https://practice.geeksforgeeks.org/viewSol.php?subId=58bdb4aa62394291d57f659e2c839932&pid=703402&user=tomarshiv51
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
int lps(string s) {
// Your code goes here
int n=s.size(),j=0; int a[n]; a[0]=0;
int i=1;
while(i<n){
if(s[i]==s[j]){
a[i]=j+1; j++; i++;
}
else{
if(j==0){
a[i]=0; i++;
}
else{
j=a[j-1];
}
}
}
return a[n-1];
}
};
// { Driver Code Starts.
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while(t--)
{
string str;
cin >> str;
Solution ob;
cout << ob.lps(str) << "\n";
}
return 0;
}
// } Driver Code Ends
| 15.693548 | 116 | 0.463515 |
efa401af672bc08b39212830123acadded6ac823 | 1,764 | cpp | C++ | mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp | allen7575/The-CPUID-Explorer | 77d0feef70482b2e36cff300ea24271384329f60 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 9 | 2017-08-31T06:03:18.000Z | 2019-01-06T05:07:26.000Z | mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp | allen7575/The-CPUID-Explorer | 77d0feef70482b2e36cff300ea24271384329f60 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp | allen7575/The-CPUID-Explorer | 77d0feef70482b2e36cff300ea24271384329f60 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 8 | 2017-08-31T06:23:22.000Z | 2022-01-24T06:47:19.000Z | // ExtendedCPU5Intel.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "ExtendedCPU5Intel.h"
#include "CPUIDx86.h"
#include "ReportRegs.h"
// CExtendedCPU5Intel dialog
IMPLEMENT_DYNCREATE(CExtendedCPU5Intel, CLeaves)
CExtendedCPU5Intel::CExtendedCPU5Intel()
: CLeaves(CExtendedCPU5Intel::IDD)
{
}
CExtendedCPU5Intel::~CExtendedCPU5Intel()
{
}
void CExtendedCPU5Intel::DoDataExchange(CDataExchange* pDX)
{
CLeaves::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EAX, c_EAX);
DDX_Control(pDX, IDC_EBX, c_EBX);
DDX_Control(pDX, IDC_ECX, c_ECX);
DDX_Control(pDX, IDC_EDX, c_EDX);
}
BEGIN_MESSAGE_MAP(CExtendedCPU5Intel, CLeaves)
END_MESSAGE_MAP()
// CExtendedCPU5Intel message handlers
/****************************************************************************
* CExtendedCPU5Intel::OnSetActive
* Result: BOOL
*
* Effect:
* Reports the registers
****************************************************************************/
BOOL CExtendedCPU5Intel::OnSetActive()
{
CPUregs regs;
GetAndReport(0x80000005, regs);
return CLeaves::OnSetActive();
}
/****************************************************************************
* CExtendedCPU5Intel::OnInitDialog
* Result: BOOL
* TRUE, always
* Effect:
* Initializes the dialog
****************************************************************************/
BOOL CExtendedCPU5Intel::OnInitDialog()
{
CLeaves::OnInitDialog();
SetFixedFont(c_EAX);
SetFixedFont(c_EBX);
SetFixedFont(c_ECX);
SetFixedFont(c_EDX);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| 23.837838 | 77 | 0.573696 |
efa44fa587e0b8ee43b264ca89fcd327d505a17d | 20,926 | cpp | C++ | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8Path2D.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8Path2D.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8Path2D.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8Path2D.h"
#include "bindings/core/v8/V8Path2D.h"
#include "bindings/core/v8/V8SVGMatrix.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/LocalDOMWindow.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(Path2D* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8Path2D::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::Path2D* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8Path2D::wrapperTypeInfo = { gin::kEmbedderBlink, V8Path2D::domTemplate, V8Path2D::derefObject, 0, 0, 0, V8Path2D::installPerContextEnabledMethods, 0, WrapperTypeObjectPrototype, RefCountedObject };
namespace Path2DV8Internal {
template <typename T> void V8_USE(T) { }
static void addPathMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeErrorForMethod("addPath", "Path2D", 1, info.Length(), info.GetIsolate());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
Path2D* path;
SVGMatrixTearOff* transform;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (info.Length() > 0 && !V8Path2D::hasInstance(info[0], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("addPath", "Path2D", "parameter 1 is not of type 'Path2D'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(path, V8Path2D::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
if (UNLIKELY(info.Length() <= 1)) {
impl->addPath(path);
return;
}
if (info.Length() > 1 && !isUndefinedOrNull(info[1]) && !V8SVGMatrix::hasInstance(info[1], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("addPath", "Path2D", "parameter 2 is not of type 'SVGMatrix'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(transform, V8SVGMatrix::toNativeWithTypeCheck(info.GetIsolate(), info[1]));
}
impl->addPath(path, transform);
}
static void addPathMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::addPathMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void closePathMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
Path2D* impl = V8Path2D::toNative(info.Holder());
impl->closePath();
}
static void closePathMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::closePathMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void moveToMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeErrorForMethod("moveTo", "Path2D", 2, info.Length(), info.GetIsolate());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float x;
float y;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue()));
}
impl->moveTo(x, y);
}
static void moveToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::moveToMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void lineToMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeErrorForMethod("lineTo", "Path2D", 2, info.Length(), info.GetIsolate());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float x;
float y;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue()));
}
impl->lineTo(x, y);
}
static void lineToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::lineToMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void quadraticCurveToMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 4)) {
throwMinimumArityTypeErrorForMethod("quadraticCurveTo", "Path2D", 4, info.Length(), info.GetIsolate());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float cpx;
float cpy;
float x;
float y;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(cpx, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(cpy, static_cast<float>(info[1]->NumberValue()));
TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[2]->NumberValue()));
TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[3]->NumberValue()));
}
impl->quadraticCurveTo(cpx, cpy, x, y);
}
static void quadraticCurveToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::quadraticCurveToMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void bezierCurveToMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 6)) {
throwMinimumArityTypeErrorForMethod("bezierCurveTo", "Path2D", 6, info.Length(), info.GetIsolate());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float cp1x;
float cp1y;
float cp2x;
float cp2y;
float x;
float y;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(cp1x, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(cp1y, static_cast<float>(info[1]->NumberValue()));
TONATIVE_VOID_INTERNAL(cp2x, static_cast<float>(info[2]->NumberValue()));
TONATIVE_VOID_INTERNAL(cp2y, static_cast<float>(info[3]->NumberValue()));
TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[4]->NumberValue()));
TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[5]->NumberValue()));
}
impl->bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
}
static void bezierCurveToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::bezierCurveToMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void arcToMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "arcTo", "Path2D", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 5)) {
throwMinimumArityTypeError(exceptionState, 5, info.Length());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float x1;
float y1;
float x2;
float y2;
float radius;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(x1, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(y1, static_cast<float>(info[1]->NumberValue()));
TONATIVE_VOID_INTERNAL(x2, static_cast<float>(info[2]->NumberValue()));
TONATIVE_VOID_INTERNAL(y2, static_cast<float>(info[3]->NumberValue()));
TONATIVE_VOID_INTERNAL(radius, static_cast<float>(info[4]->NumberValue()));
}
impl->arcTo(x1, y1, x2, y2, radius, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void arcToMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::arcToMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void rectMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 4)) {
throwMinimumArityTypeErrorForMethod("rect", "Path2D", 4, info.Length(), info.GetIsolate());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float x;
float y;
float width;
float height;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue()));
TONATIVE_VOID_INTERNAL(width, static_cast<float>(info[2]->NumberValue()));
TONATIVE_VOID_INTERNAL(height, static_cast<float>(info[3]->NumberValue()));
}
impl->rect(x, y, width, height);
}
static void rectMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::rectMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void arcMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "arc", "Path2D", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 5)) {
throwMinimumArityTypeError(exceptionState, 5, info.Length());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float x;
float y;
float radius;
float startAngle;
float endAngle;
bool anticlockwise;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue()));
TONATIVE_VOID_INTERNAL(radius, static_cast<float>(info[2]->NumberValue()));
TONATIVE_VOID_INTERNAL(startAngle, static_cast<float>(info[3]->NumberValue()));
TONATIVE_VOID_INTERNAL(endAngle, static_cast<float>(info[4]->NumberValue()));
TONATIVE_VOID_INTERNAL(anticlockwise, info[5]->BooleanValue());
}
impl->arc(x, y, radius, startAngle, endAngle, anticlockwise, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void arcMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::arcMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void ellipseMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "ellipse", "Path2D", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 7)) {
throwMinimumArityTypeError(exceptionState, 7, info.Length());
return;
}
Path2D* impl = V8Path2D::toNative(info.Holder());
float x;
float y;
float radiusX;
float radiusY;
float rotation;
float startAngle;
float endAngle;
bool anticlockwise;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(x, static_cast<float>(info[0]->NumberValue()));
TONATIVE_VOID_INTERNAL(y, static_cast<float>(info[1]->NumberValue()));
TONATIVE_VOID_INTERNAL(radiusX, static_cast<float>(info[2]->NumberValue()));
TONATIVE_VOID_INTERNAL(radiusY, static_cast<float>(info[3]->NumberValue()));
TONATIVE_VOID_INTERNAL(rotation, static_cast<float>(info[4]->NumberValue()));
TONATIVE_VOID_INTERNAL(startAngle, static_cast<float>(info[5]->NumberValue()));
TONATIVE_VOID_INTERNAL(endAngle, static_cast<float>(info[6]->NumberValue()));
TONATIVE_VOID_INTERNAL(anticlockwise, info[7]->BooleanValue());
}
impl->ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void ellipseMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
Path2DV8Internal::ellipseMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void constructor1(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
RefPtr<Path2D> impl = Path2D::create();
v8::Handle<v8::Object> wrapper = info.Holder();
V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl.release(), &V8Path2D::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
v8SetReturnValue(info, wrapper);
}
static void constructor2(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
Path2D* path;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(path, V8Path2D::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
}
RefPtr<Path2D> impl = Path2D::create(path);
v8::Handle<v8::Object> wrapper = info.Holder();
V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl.release(), &V8Path2D::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
v8SetReturnValue(info, wrapper);
}
static void constructor3(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8StringResource<> text;
{
TOSTRING_VOID_INTERNAL(text, info[0]);
}
RefPtr<Path2D> impl = Path2D::create(text);
v8::Handle<v8::Object> wrapper = info.Holder();
V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl.release(), &V8Path2D::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
v8SetReturnValue(info, wrapper);
}
static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
ExceptionState exceptionState(ExceptionState::ConstructionContext, "Path2D", info.Holder(), isolate);
switch (std::min(1, info.Length())) {
case 0:
if (true) {
Path2DV8Internal::constructor1(info);
return;
}
break;
case 1:
if (V8Path2D::hasInstance(info[0], isolate)) {
Path2DV8Internal::constructor2(info);
return;
}
if (true) {
Path2DV8Internal::constructor3(info);
return;
}
break;
default:
exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(0, info.Length()));
exceptionState.throwIfNeeded();
return;
}
exceptionState.throwTypeError("No matching constructor signature.");
exceptionState.throwIfNeeded();
}
} // namespace Path2DV8Internal
static const V8DOMConfiguration::MethodConfiguration V8Path2DMethods[] = {
{"closePath", Path2DV8Internal::closePathMethodCallback, 0, 0},
{"moveTo", Path2DV8Internal::moveToMethodCallback, 0, 2},
{"lineTo", Path2DV8Internal::lineToMethodCallback, 0, 2},
{"quadraticCurveTo", Path2DV8Internal::quadraticCurveToMethodCallback, 0, 4},
{"bezierCurveTo", Path2DV8Internal::bezierCurveToMethodCallback, 0, 6},
{"arcTo", Path2DV8Internal::arcToMethodCallback, 0, 5},
{"rect", Path2DV8Internal::rectMethodCallback, 0, 4},
{"arc", Path2DV8Internal::arcMethodCallback, 0, 5},
{"ellipse", Path2DV8Internal::ellipseMethodCallback, 0, 7},
};
void V8Path2D::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "DOMConstructor");
if (!info.IsConstructCall()) {
throwTypeError(ExceptionMessages::constructorNotCallableAsFunction("Path2D"), info.GetIsolate());
return;
}
if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
v8SetReturnValue(info, info.Holder());
return;
}
Path2DV8Internal::constructor(info);
}
static void configureV8Path2DTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
if (!RuntimeEnabledFeatures::path2DEnabled())
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "", v8::Local<v8::FunctionTemplate>(), V8Path2D::internalFieldCount, 0, 0, 0, 0, 0, 0, isolate);
else
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "Path2D", v8::Local<v8::FunctionTemplate>(), V8Path2D::internalFieldCount,
0, 0,
0, 0,
V8Path2DMethods, WTF_ARRAY_LENGTH(V8Path2DMethods),
isolate);
functionTemplate->SetCallHandler(V8Path2D::constructorCallback);
functionTemplate->SetLength(0);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
if (RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled()) {
prototypeTemplate->Set(v8AtomicString(isolate, "addPath"), v8::FunctionTemplate::New(isolate, Path2DV8Internal::addPathMethodCallback, v8Undefined(), defaultSignature, 1));
}
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8Path2D::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8Path2DTemplate);
}
bool V8Path2D::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8Path2D::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
Path2D* V8Path2D::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
v8::Handle<v8::Object> wrap(Path2D* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8Path2D>(impl, isolate));
return V8Path2D::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8Path2D::createWrapper(PassRefPtr<Path2D> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8Path2D>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8Path2D>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
return wrapper;
}
void V8Path2D::derefObject(void* object)
{
fromInternalPointer(object)->deref();
}
template<>
v8::Handle<v8::Value> toV8NoInline(Path2D* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
| 38.823748 | 221 | 0.704721 |
efaa95e67d306944eeea043d8368c7cea94e20aa | 5,430 | cc | C++ | chrome/browser/media/router/discovery/media_sink_service_base_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/media/router/discovery/media_sink_service_base_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/media/router/discovery/media_sink_service_base_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 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 "chrome/browser/media/router/discovery/media_sink_service_base.h"
#include "base/test/mock_callback.h"
#include "base/timer/mock_timer.h"
#include "chrome/browser/media/router/test_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::Return;
namespace {
media_router::DialSinkExtraData CreateDialSinkExtraData(
const std::string& model_name,
const std::string& ip_address,
const std::string& app_url) {
media_router::DialSinkExtraData dial_extra_data;
EXPECT_TRUE(dial_extra_data.ip_address.AssignFromIPLiteral(ip_address));
dial_extra_data.model_name = model_name;
dial_extra_data.app_url = GURL(app_url);
return dial_extra_data;
}
std::vector<media_router::MediaSinkInternal> CreateDialMediaSinks() {
media_router::MediaSink sink1("sink1", "sink_name_1",
media_router::SinkIconType::CAST);
media_router::DialSinkExtraData extra_data1 = CreateDialSinkExtraData(
"model_name1", "192.168.1.1", "https://example1.com");
media_router::MediaSink sink2("sink2", "sink_name_2",
media_router::SinkIconType::CAST);
media_router::DialSinkExtraData extra_data2 = CreateDialSinkExtraData(
"model_name2", "192.168.1.2", "https://example2.com");
std::vector<media_router::MediaSinkInternal> sinks;
sinks.push_back(media_router::MediaSinkInternal(sink1, extra_data1));
sinks.push_back(media_router::MediaSinkInternal(sink2, extra_data2));
return sinks;
}
} // namespace
namespace media_router {
class TestMediaSinkServiceBase : public MediaSinkServiceBase {
public:
explicit TestMediaSinkServiceBase(const OnSinksDiscoveredCallback& callback)
: MediaSinkServiceBase(callback) {}
void Start() override {}
void Stop() override {}
};
class MediaSinkServiceBaseTest : public ::testing::Test {
public:
MediaSinkServiceBaseTest()
: // thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
media_sink_service_(
new TestMediaSinkServiceBase(mock_sink_discovered_cb_.Get())) {}
void SetUp() override {
mock_timer_ =
new base::MockTimer(true /*retain_user_task*/, false /*is_repeating*/);
media_sink_service_->SetTimerForTest(base::WrapUnique(mock_timer_));
}
void TestFetchCompleted(const std::vector<MediaSinkInternal>& old_sinks,
const std::vector<MediaSinkInternal>& new_sinks) {
media_sink_service_->mrp_sinks_ =
std::set<MediaSinkInternal>(old_sinks.begin(), old_sinks.end());
media_sink_service_->current_sinks_ =
std::set<MediaSinkInternal>(new_sinks.begin(), new_sinks.end());
EXPECT_CALL(mock_sink_discovered_cb_, Run(new_sinks));
media_sink_service_->OnFetchCompleted();
}
protected:
base::MockCallback<MediaSinkService::OnSinksDiscoveredCallback>
mock_sink_discovered_cb_;
base::MockTimer* mock_timer_;
std::unique_ptr<TestMediaSinkServiceBase> media_sink_service_;
DISALLOW_COPY_AND_ASSIGN(MediaSinkServiceBaseTest);
};
TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_SameSink) {
std::vector<MediaSinkInternal> old_sinks;
std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks();
TestFetchCompleted(old_sinks, new_sinks);
// Same sink
EXPECT_CALL(mock_sink_discovered_cb_, Run(new_sinks)).Times(0);
media_sink_service_->OnFetchCompleted();
}
TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_OneNewSink) {
std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks();
std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks();
MediaSink sink3("sink3", "sink_name_3", SinkIconType::CAST);
DialSinkExtraData extra_data3 = CreateDialSinkExtraData(
"model_name3", "192.168.1.3", "https://example3.com");
new_sinks.push_back(MediaSinkInternal(sink3, extra_data3));
TestFetchCompleted(old_sinks, new_sinks);
}
TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_RemovedOneSink) {
std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks();
std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks();
new_sinks.erase(new_sinks.begin());
TestFetchCompleted(old_sinks, new_sinks);
}
TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_UpdatedOneSink) {
std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks();
std::vector<MediaSinkInternal> new_sinks = CreateDialMediaSinks();
new_sinks[0].set_name("sink_name_4");
TestFetchCompleted(old_sinks, new_sinks);
}
TEST_F(MediaSinkServiceBaseTest, TestFetchCompleted_Mixed) {
std::vector<MediaSinkInternal> old_sinks = CreateDialMediaSinks();
MediaSink sink1("sink1", "sink_name_1", SinkIconType::CAST);
DialSinkExtraData extra_data2 = CreateDialSinkExtraData(
"model_name2", "192.168.1.2", "https://example2.com");
MediaSink sink3("sink3", "sink_name_3", SinkIconType::CAST);
DialSinkExtraData extra_data3 = CreateDialSinkExtraData(
"model_name3", "192.168.1.3", "https://example3.com");
std::vector<MediaSinkInternal> new_sinks;
new_sinks.push_back(MediaSinkInternal(sink1, extra_data2));
new_sinks.push_back(MediaSinkInternal(sink3, extra_data3));
TestFetchCompleted(old_sinks, new_sinks);
}
} // namespace media_router
| 37.708333 | 79 | 0.759484 |
efac67313dd9bd9f69caae66d56b1ffaf67e9911 | 1,591 | hpp | C++ | internal/o80_internal/controllers_manager.hpp | luator/o80 | 65fe75bc6d375db0e4a2fe075c097a54dde7b571 | [
"BSD-3-Clause"
] | null | null | null | internal/o80_internal/controllers_manager.hpp | luator/o80 | 65fe75bc6d375db0e4a2fe075c097a54dde7b571 | [
"BSD-3-Clause"
] | null | null | null | internal/o80_internal/controllers_manager.hpp | luator/o80 | 65fe75bc6d375db0e4a2fe075c097a54dde7b571 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2019 Max Planck Gesellschaft
// Author : Vincent Berenz
#pragma once
#include <memory>
#include "command.hpp"
#include "controller.hpp"
#include "o80/states.hpp"
#include "time_series/multiprocess_time_series.hpp"
namespace o80
{
template <int NB_ACTUATORS, int QUEUE_SIZE, class STATE>
class ControllersManager
{
public:
typedef std::array<Controller<STATE>, NB_ACTUATORS> Controllers;
typedef time_series::MultiprocessTimeSeries<Command<STATE>>
CommandsTimeSeries;
typedef time_series::MultiprocessTimeSeries<int>
CompletedCommandsTimeSeries;
public:
ControllersManager(std::string segment_id);
void process_commands(long int current_iteration);
STATE get_desired_state(int dof,
long int current_iteration,
const TimePoint &time_now,
const STATE ¤t_state);
int get_current_command_id(int dof) const;
void get_newly_executed_commands(std::queue<int> &get);
bool reapplied_desired_states() const;
CommandsTimeSeries &get_commands_time_series();
CompletedCommandsTimeSeries &get_completed_commands_time_series();
private:
std::string segment_id_;
CommandsTimeSeries commands_;
long int pulse_id_;
time_series::Index commands_index_;
CompletedCommandsTimeSeries completed_commands_;
Controllers controllers_;
States<NB_ACTUATORS, STATE> previous_desired_states_;
std::array<bool, NB_ACTUATORS> initialized_;
long int relative_iteration_;
};
}
#include "controllers_manager.hxx"
| 27.912281 | 70 | 0.733501 |
eface07d49cd2d31155cbaf2a0de6163d32bde90 | 5,470 | cc | C++ | nacl/net/rtp/rtp_sender.cc | maxsong11/nacld | c4802cc7d9bda03487bde566a3003e8bc0f574d3 | [
"BSD-3-Clause"
] | 9 | 2015-12-23T21:18:28.000Z | 2018-11-25T10:10:12.000Z | nacl/net/rtp/rtp_sender.cc | maxsong11/nacld | c4802cc7d9bda03487bde566a3003e8bc0f574d3 | [
"BSD-3-Clause"
] | 1 | 2016-01-08T20:56:21.000Z | 2016-01-08T20:56:21.000Z | nacl/net/rtp/rtp_sender.cc | maxsong11/nacld | c4802cc7d9bda03487bde566a3003e8bc0f574d3 | [
"BSD-3-Clause"
] | 6 | 2015-12-04T18:23:49.000Z | 2018-11-06T03:52:58.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Copyright 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/rtp/rtp_sender.h"
#include "base/big_endian.h"
#include "base/logger.h"
#include "base/ptr_utils.h"
#include "base/rand_util.h"
#include "sharer_defines.h"
namespace sharer {
namespace {
// If there is only one reference to the packet then copy the
// reference and return.
// Otherwise return a deep copy of the packet.
PacketRef FastCopyPacket(const PacketRef& packet) {
if (packet.unique()) return packet;
return std::make_shared<Packet>(*packet);
}
} // namespace
RtpSender::RtpSender(PacedSender* const transport) : transport_(transport) {
// Randomly set sequence number start value.
config_.sequence_number = base::RandInt(0, 65535);
}
RtpSender::~RtpSender() {}
bool RtpSender::Initialize(const SharerTransportRtpConfig& config) {
config_.ssrc = config.ssrc;
config_.payload_type = config.rtp_payload_type;
packetizer_ = make_unique<RtpPacketizer>(transport_, &storage_, config_);
return true;
}
void RtpSender::SendFrame(const EncodedFrame& frame) {
PP_DCHECK(packetizer_);
packetizer_->SendFrameAsPackets(frame);
if (storage_.GetNumberOfStoredFrames() > kMaxUnackedFrames) {
// TODO: Change to LOG_IF
DERR()
<< "Possible bug: Frames are not being actively released from storage.";
}
}
void RtpSender::ResendPackets(
const std::string& addr,
const MissingFramesAndPacketsMap& missing_frames_and_packets,
bool cancel_rtx_if_not_in_list, const DedupInfo& dedup_info) {
// Iterate over all frames in the list.
for (MissingFramesAndPacketsMap::const_iterator it =
missing_frames_and_packets.begin();
it != missing_frames_and_packets.end(); ++it) {
SendPacketVector packets_to_resend;
uint32_t frame_id = it->first;
// Set of packets that the receiver wants us to re-send.
// If empty, we need to re-send all packets for this frame.
const PacketIdSet& missing_packet_set = it->second;
bool resend_all = missing_packet_set.find(kRtcpSharerAllPacketsLost) !=
missing_packet_set.end();
bool resend_last = missing_packet_set.find(kRtcpSharerLastPacket) !=
missing_packet_set.end();
const SendPacketVector* stored_packets = storage_.GetFrame32(frame_id);
if (!stored_packets) {
DERR() << "Can't resend " << missing_packet_set.size()
<< " packets for frame:" << frame_id;
continue;
}
for (SendPacketVector::const_iterator it = stored_packets->begin();
it != stored_packets->end(); ++it) {
const PacketKey& packet_key = it->first;
const uint16_t packet_id = packet_key.second.second;
// Should we resend the packet?
bool resend = resend_all;
// Should we resend it because it's in the missing_packet_set?
if (!resend &&
missing_packet_set.find(packet_id) != missing_packet_set.end()) {
resend = true;
}
// If we were asked to resend the last packet, check if it's the
// last packet.
if (!resend && resend_last && (it + 1) == stored_packets->end()) {
resend = true;
}
if (resend) {
// Resend packet to the network.
DINF() << "Resend " << static_cast<int>(frame_id) << ":" << packet_id
<< ", dest: " << addr;
// Set a unique incremental sequence number for every packet.
PacketRef packet_copy = FastCopyPacket(it->second);
UpdateSequenceNumber(packet_copy);
packets_to_resend.push_back(std::make_pair(packet_key, packet_copy));
} else if (cancel_rtx_if_not_in_list) {
transport_->CancelSendingPacket(addr, it->first);
}
}
transport_->ResendPackets(addr, packets_to_resend, dedup_info);
}
}
void RtpSender::ResendFrameForKickstart(uint32_t frame_id,
base::TimeDelta dedupe_window) {
// Send the last packet of the encoded frame to kick start
// retransmission. This gives enough information to the receiver what
// packets and frames are missing.
MissingFramesAndPacketsMap missing_frames_and_packets;
PacketIdSet missing;
missing.insert(kRtcpSharerLastPacket);
missing_frames_and_packets.insert(std::make_pair(frame_id, missing));
// Sending this extra packet is to kick-start the session. There is
// no need to optimize re-transmission for this case.
DedupInfo dedup_info;
dedup_info.resend_interval = dedupe_window;
// ResendPackets(missing_frames_and_packets, false, dedup_info);
}
void RtpSender::UpdateSequenceNumber(PacketRef packet) {
// TODO(miu): This is an abstraction violation. This needs to be a part of
// the overall packet (de)serialization consolidation.
static const int kByteOffsetToSequenceNumber = 2;
BigEndianWriter big_endian_writer(
reinterpret_cast<char*>((packet->data()) + kByteOffsetToSequenceNumber),
sizeof(uint16_t));
big_endian_writer.WriteU16(packetizer_->NextSequenceNumber());
}
int64_t RtpSender::GetLastByteSentForFrame(uint32_t frame_id) {
const SendPacketVector* stored_packets = storage_.GetFrame32(frame_id);
if (!stored_packets) return 0;
PacketKey last_packet_key = stored_packets->rbegin()->first;
return transport_->GetLastByteSentForPacket(last_packet_key);
}
} // namespace sharer
| 36.711409 | 80 | 0.706399 |
efae40771253fa3bfb27b1ee80c55f32c9e089be | 3,140 | cpp | C++ | minesweeper_v1/Instructions.cpp | sangpham2710/CS161-Project | 7051cc17bc64bdcb128884ef02ec70e1552c982e | [
"MIT"
] | 6 | 2021-12-28T08:07:16.000Z | 2022-03-13T06:17:45.000Z | minesweeper_v1/Instructions.cpp | sangpham2710/CS161-Project | 7051cc17bc64bdcb128884ef02ec70e1552c982e | [
"MIT"
] | null | null | null | minesweeper_v1/Instructions.cpp | sangpham2710/CS161-Project | 7051cc17bc64bdcb128884ef02ec70e1552c982e | [
"MIT"
] | 1 | 2021-12-24T07:19:16.000Z | 2021-12-24T07:19:16.000Z | #include "instructions.h"
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "cmanip.h"
#include "game_model.h"
#include "global.h"
#include "main_utils.h"
#include "scene_manager.h"
#include "windows.h"
const long long MAX_TIME = (long long)1e18;
int PADDING_INSTRUCTIONS_X, PADDING_INSTRUCTIONS_Y;
// 3 che do
// 0 0 0 0 0 0 0 0 0 0
// 0 0 0 0 0 0 0 0 0 0
// 0 0 0 0 0 0 0 0 0 0
const std::vector<std::string> instructions = {
R"([WASD]/[Arrow keys])",
"Move Cursor",
"[J]/[Enter]",
"Select | Open A Cell",
"[K]",
"Open Neighboring Cells",
"[L]",
"Flag A Cell",
"[O]",
"Save Game",
"[R]",
"Replay Game",
"[Y]",
"Yes",
"[N]",
"No",
R"([Escape])",
R"(Quit Game | Back to Menu)",
};
int instructionsWidth =
strlen(R"( [Escape]: Quit Game | Back to Menu)");
int instructionsHeight = instructions.size() / 2;
std::vector<std::string> getInstructionHeaderText() {
return {
R"( _ _ ___ __ __ _____ ___ ___ _ _ __ __)",
R"(| || | / _ \\ \ / / |_ _|/ _ \ | _ \| | /_\\ \ / /)",
R"(| __ || (_) |\ \/\/ / | | | (_) | | _/| |__ / _ \\ V / )",
R"(|_||_| \___/ \_/\_/ |_| \___/ |_| |____|/_/ \_\|_| )",
};
}
int getInstructionsPosition() { return PADDING_INSTRUCTIONS_Y + 1; }
void displayInstructionsHeaderAndFooter() {
std::vector<std::string> headerText = getInstructionHeaderText();
const int spacing = 1;
for (int i = 0; i < headerText.size(); i++)
printCenteredText(headerText[i], 3 + i);
printCenteredText(R"([J] Back to Menu)", getWindowHeight() - 2);
}
int Instructions() {
setupInstructionsDisplay();
displayInstructions();
while (true) {
int action = getUserAction();
if (action == MOUSE1 || action == ESCAPE) return WELCOME;
}
}
void displayInstructions() {
resetConsoleScreen();
int cellWidth = instructions[0].size();
displayInstructionsHeaderAndFooter();
for (int i = 0; i < instructions.size(); i++) {
setConsoleCursorPosition(
PADDING_INSTRUCTIONS_X + (cellWidth - instructions[i].size()) / 2 - 5,
PADDING_INSTRUCTIONS_Y + i / 2 + 2);
std::cout << instructions[i];
setConsoleCursorPosition(PADDING_INSTRUCTIONS_X + cellWidth - 2,
PADDING_INSTRUCTIONS_Y + i / 2 + 2);
std::cout << " : " << instructions[i + 1];
// printCenteredText(std::string((cellWidth - instruction[i].size()) / 2, '
// ') + instruction[i] + std::string((cellWidth - instruction[i].size()) /
// 2, ' ') + std::string(instructionWidth - cellWidth, ' '),
// PADDING_INSTRUCTION_Y + i / 2 + 2);
// printCenteredText(std::string(instruction[i].size(), ' ') + instruction[i
// + 1] + std::string(instructionWidth - instruction[i].size() -
// instruction[i + 1].size(), ' '), PADDING_INSTRUCTION_Y + i / 2 + 2);
i++;
}
}
void setupInstructionsDisplay() {
PADDING_INSTRUCTIONS_X = (getWindowWidth() - instructionsWidth) / 2;
PADDING_INSTRUCTIONS_Y = (getWindowHeight() - instructionsHeight) / 2;
}
| 28.545455 | 80 | 0.58758 |
efafcec13c75a40f7bfe2a3549a569f79f732878 | 83,097 | cc | C++ | protobufs/c_peer2peer_netmessages.pb.cc | devilesk/dota-replay-parser | e83b96ee513a7193e6703615df4f676e27b1b8a0 | [
"0BSD"
] | 2 | 2017-02-03T16:57:17.000Z | 2020-10-28T21:13:12.000Z | protobufs/c_peer2peer_netmessages.pb.cc | invokr/dota-replay-parser | 6260aa834fb47f0f1a8c713f4edada6baeb9dcfa | [
"0BSD"
] | 1 | 2017-02-03T22:44:17.000Z | 2017-02-04T08:58:13.000Z | protobufs/c_peer2peer_netmessages.pb.cc | invokr/dota-replay-parser | 6260aa834fb47f0f1a8c713f4edada6baeb9dcfa | [
"0BSD"
] | 2 | 2017-02-03T17:51:57.000Z | 2021-05-22T02:40:00.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: c_peer2peer_netmessages.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "c_peer2peer_netmessages.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace {
const ::google::protobuf::Descriptor* CP2P_TextMessage_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CP2P_TextMessage_reflection_ = NULL;
const ::google::protobuf::Descriptor* CSteam_Voice_Encoding_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CSteam_Voice_Encoding_reflection_ = NULL;
const ::google::protobuf::Descriptor* CP2P_Voice_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CP2P_Voice_reflection_ = NULL;
const ::google::protobuf::EnumDescriptor* CP2P_Voice_Handler_Flags_descriptor_ = NULL;
const ::google::protobuf::Descriptor* CP2P_Ping_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CP2P_Ping_reflection_ = NULL;
const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CP2P_VRAvatarPosition_reflection_ = NULL;
const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition_COrientation_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CP2P_VRAvatarPosition_COrientation_reflection_ = NULL;
const ::google::protobuf::Descriptor* CP2P_WatchSynchronization_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CP2P_WatchSynchronization_reflection_ = NULL;
const ::google::protobuf::EnumDescriptor* P2P_Messages_descriptor_ = NULL;
} // namespace
void protobuf_AssignDesc_c_5fpeer2peer_5fnetmessages_2eproto() {
protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"c_peer2peer_netmessages.proto");
GOOGLE_CHECK(file != NULL);
CP2P_TextMessage_descriptor_ = file->message_type(0);
static const int CP2P_TextMessage_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_TextMessage, text_),
};
CP2P_TextMessage_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
CP2P_TextMessage_descriptor_,
CP2P_TextMessage::default_instance_,
CP2P_TextMessage_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_TextMessage, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_TextMessage, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(CP2P_TextMessage));
CSteam_Voice_Encoding_descriptor_ = file->message_type(1);
static const int CSteam_Voice_Encoding_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CSteam_Voice_Encoding, voice_data_),
};
CSteam_Voice_Encoding_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
CSteam_Voice_Encoding_descriptor_,
CSteam_Voice_Encoding::default_instance_,
CSteam_Voice_Encoding_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CSteam_Voice_Encoding, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CSteam_Voice_Encoding, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(CSteam_Voice_Encoding));
CP2P_Voice_descriptor_ = file->message_type(2);
static const int CP2P_Voice_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, audio_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, broadcast_group_),
};
CP2P_Voice_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
CP2P_Voice_descriptor_,
CP2P_Voice::default_instance_,
CP2P_Voice_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Voice, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(CP2P_Voice));
CP2P_Voice_Handler_Flags_descriptor_ = CP2P_Voice_descriptor_->enum_type(0);
CP2P_Ping_descriptor_ = file->message_type(3);
static const int CP2P_Ping_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, send_time_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, is_reply_),
};
CP2P_Ping_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
CP2P_Ping_descriptor_,
CP2P_Ping::default_instance_,
CP2P_Ping_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_Ping, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(CP2P_Ping));
CP2P_VRAvatarPosition_descriptor_ = file->message_type(4);
static const int CP2P_VRAvatarPosition_offsets_[4] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, body_parts_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, hat_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, scene_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, world_scale_),
};
CP2P_VRAvatarPosition_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
CP2P_VRAvatarPosition_descriptor_,
CP2P_VRAvatarPosition::default_instance_,
CP2P_VRAvatarPosition_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(CP2P_VRAvatarPosition));
CP2P_VRAvatarPosition_COrientation_descriptor_ = CP2P_VRAvatarPosition_descriptor_->nested_type(0);
static const int CP2P_VRAvatarPosition_COrientation_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, pos_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, ang_),
};
CP2P_VRAvatarPosition_COrientation_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
CP2P_VRAvatarPosition_COrientation_descriptor_,
CP2P_VRAvatarPosition_COrientation::default_instance_,
CP2P_VRAvatarPosition_COrientation_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_VRAvatarPosition_COrientation, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(CP2P_VRAvatarPosition_COrientation));
CP2P_WatchSynchronization_descriptor_ = file->message_type(5);
static const int CP2P_WatchSynchronization_offsets_[8] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, demo_tick_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, paused_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, tv_listen_voice_indices_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_mode_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_watching_broadcaster_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_hero_index_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_spectator_autospeed_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, dota_replay_speed_),
};
CP2P_WatchSynchronization_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
CP2P_WatchSynchronization_descriptor_,
CP2P_WatchSynchronization::default_instance_,
CP2P_WatchSynchronization_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CP2P_WatchSynchronization, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(CP2P_WatchSynchronization));
P2P_Messages_descriptor_ = file->enum_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_c_5fpeer2peer_5fnetmessages_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CP2P_TextMessage_descriptor_, &CP2P_TextMessage::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CSteam_Voice_Encoding_descriptor_, &CSteam_Voice_Encoding::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CP2P_Voice_descriptor_, &CP2P_Voice::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CP2P_Ping_descriptor_, &CP2P_Ping::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CP2P_VRAvatarPosition_descriptor_, &CP2P_VRAvatarPosition::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CP2P_VRAvatarPosition_COrientation_descriptor_, &CP2P_VRAvatarPosition_COrientation::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CP2P_WatchSynchronization_descriptor_, &CP2P_WatchSynchronization::default_instance());
}
} // namespace
void protobuf_ShutdownFile_c_5fpeer2peer_5fnetmessages_2eproto() {
delete CP2P_TextMessage::default_instance_;
delete CP2P_TextMessage_reflection_;
delete CSteam_Voice_Encoding::default_instance_;
delete CSteam_Voice_Encoding_reflection_;
delete CP2P_Voice::default_instance_;
delete CP2P_Voice_reflection_;
delete CP2P_Ping::default_instance_;
delete CP2P_Ping_reflection_;
delete CP2P_VRAvatarPosition::default_instance_;
delete CP2P_VRAvatarPosition_reflection_;
delete CP2P_VRAvatarPosition_COrientation::default_instance_;
delete CP2P_VRAvatarPosition_COrientation_reflection_;
delete CP2P_WatchSynchronization::default_instance_;
delete CP2P_WatchSynchronization_reflection_;
}
void protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::protobuf_AddDesc_netmessages_2eproto();
::protobuf_AddDesc_networkbasetypes_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\035c_peer2peer_netmessages.proto\032\021netmess"
"ages.proto\032\026networkbasetypes.proto\" \n\020CP"
"2P_TextMessage\022\014\n\004text\030\001 \001(\014\"+\n\025CSteam_V"
"oice_Encoding\022\022\n\nvoice_data\030\001 \001(\014\"h\n\nCP2"
"P_Voice\022\036\n\005audio\030\001 \001(\0132\017.CMsgVoiceAudio\022"
"\027\n\017broadcast_group\030\002 \001(\r\"!\n\rHandler_Flag"
"s\022\020\n\014Played_Audio\020\001\"0\n\tCP2P_Ping\022\021\n\tsend"
"_time\030\001 \002(\004\022\020\n\010is_reply\030\002 \002(\010\"\313\001\n\025CP2P_V"
"RAvatarPosition\0227\n\nbody_parts\030\001 \003(\0132#.CP"
"2P_VRAvatarPosition.COrientation\022\016\n\006hat_"
"id\030\002 \001(\005\022\020\n\010scene_id\030\003 \001(\005\022\023\n\013world_scal"
"e\030\004 \001(\005\032B\n\014COrientation\022\030\n\003pos\030\001 \001(\0132\013.C"
"MsgVector\022\030\n\003ang\030\002 \001(\0132\013.CMsgQAngle\"\211\002\n\031"
"CP2P_WatchSynchronization\022\021\n\tdemo_tick\030\001"
" \001(\005\022\016\n\006paused\030\002 \001(\010\022\037\n\027tv_listen_voice_"
"indices\030\003 \001(\005\022\033\n\023dota_spectator_mode\030\004 \001"
"(\005\022+\n#dota_spectator_watching_broadcaste"
"r\030\005 \001(\005\022!\n\031dota_spectator_hero_index\030\006 \001"
"(\005\022 \n\030dota_spectator_autospeed\030\007 \001(\005\022\031\n\021"
"dota_replay_speed\030\010 \001(\005*}\n\014P2P_Messages\022"
"\024\n\017p2p_TextMessage\020\200\002\022\016\n\tp2p_Voice\020\201\002\022\r\n"
"\010p2p_Ping\020\202\002\022\031\n\024p2p_VRAvatarPosition\020\203\002\022"
"\035\n\030p2p_WatchSynchronization\020\204\002B\003\200\001\000", 915);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"c_peer2peer_netmessages.proto", &protobuf_RegisterTypes);
CP2P_TextMessage::default_instance_ = new CP2P_TextMessage();
CSteam_Voice_Encoding::default_instance_ = new CSteam_Voice_Encoding();
CP2P_Voice::default_instance_ = new CP2P_Voice();
CP2P_Ping::default_instance_ = new CP2P_Ping();
CP2P_VRAvatarPosition::default_instance_ = new CP2P_VRAvatarPosition();
CP2P_VRAvatarPosition_COrientation::default_instance_ = new CP2P_VRAvatarPosition_COrientation();
CP2P_WatchSynchronization::default_instance_ = new CP2P_WatchSynchronization();
CP2P_TextMessage::default_instance_->InitAsDefaultInstance();
CSteam_Voice_Encoding::default_instance_->InitAsDefaultInstance();
CP2P_Voice::default_instance_->InitAsDefaultInstance();
CP2P_Ping::default_instance_->InitAsDefaultInstance();
CP2P_VRAvatarPosition::default_instance_->InitAsDefaultInstance();
CP2P_VRAvatarPosition_COrientation::default_instance_->InitAsDefaultInstance();
CP2P_WatchSynchronization::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_c_5fpeer2peer_5fnetmessages_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_c_5fpeer2peer_5fnetmessages_2eproto {
StaticDescriptorInitializer_c_5fpeer2peer_5fnetmessages_2eproto() {
protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
}
} static_descriptor_initializer_c_5fpeer2peer_5fnetmessages_2eproto_;
const ::google::protobuf::EnumDescriptor* P2P_Messages_descriptor() {
protobuf_AssignDescriptorsOnce();
return P2P_Messages_descriptor_;
}
bool P2P_Messages_IsValid(int value) {
switch(value) {
case 256:
case 257:
case 258:
case 259:
case 260:
return true;
default:
return false;
}
}
// ===================================================================
#ifndef _MSC_VER
const int CP2P_TextMessage::kTextFieldNumber;
#endif // !_MSC_VER
CP2P_TextMessage::CP2P_TextMessage()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:CP2P_TextMessage)
}
void CP2P_TextMessage::InitAsDefaultInstance() {
}
CP2P_TextMessage::CP2P_TextMessage(const CP2P_TextMessage& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:CP2P_TextMessage)
}
void CP2P_TextMessage::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
text_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CP2P_TextMessage::~CP2P_TextMessage() {
// @@protoc_insertion_point(destructor:CP2P_TextMessage)
SharedDtor();
}
void CP2P_TextMessage::SharedDtor() {
if (text_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete text_;
}
if (this != default_instance_) {
}
}
void CP2P_TextMessage::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CP2P_TextMessage::descriptor() {
protobuf_AssignDescriptorsOnce();
return CP2P_TextMessage_descriptor_;
}
const CP2P_TextMessage& CP2P_TextMessage::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
return *default_instance_;
}
CP2P_TextMessage* CP2P_TextMessage::default_instance_ = NULL;
CP2P_TextMessage* CP2P_TextMessage::New() const {
return new CP2P_TextMessage;
}
void CP2P_TextMessage::Clear() {
if (has_text()) {
if (text_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
text_->clear();
}
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool CP2P_TextMessage::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CP2P_TextMessage)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bytes text = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_text()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CP2P_TextMessage)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CP2P_TextMessage)
return false;
#undef DO_
}
void CP2P_TextMessage::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CP2P_TextMessage)
// optional bytes text = 1;
if (has_text()) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->text(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:CP2P_TextMessage)
}
::google::protobuf::uint8* CP2P_TextMessage::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:CP2P_TextMessage)
// optional bytes text = 1;
if (has_text()) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->text(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CP2P_TextMessage)
return target;
}
int CP2P_TextMessage::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional bytes text = 1;
if (has_text()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->text());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CP2P_TextMessage::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const CP2P_TextMessage* source =
::google::protobuf::internal::dynamic_cast_if_available<const CP2P_TextMessage*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void CP2P_TextMessage::MergeFrom(const CP2P_TextMessage& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_text()) {
set_text(from.text());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void CP2P_TextMessage::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CP2P_TextMessage::CopyFrom(const CP2P_TextMessage& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CP2P_TextMessage::IsInitialized() const {
return true;
}
void CP2P_TextMessage::Swap(CP2P_TextMessage* other) {
if (other != this) {
std::swap(text_, other->text_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata CP2P_TextMessage::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CP2P_TextMessage_descriptor_;
metadata.reflection = CP2P_TextMessage_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int CSteam_Voice_Encoding::kVoiceDataFieldNumber;
#endif // !_MSC_VER
CSteam_Voice_Encoding::CSteam_Voice_Encoding()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:CSteam_Voice_Encoding)
}
void CSteam_Voice_Encoding::InitAsDefaultInstance() {
}
CSteam_Voice_Encoding::CSteam_Voice_Encoding(const CSteam_Voice_Encoding& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:CSteam_Voice_Encoding)
}
void CSteam_Voice_Encoding::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
voice_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CSteam_Voice_Encoding::~CSteam_Voice_Encoding() {
// @@protoc_insertion_point(destructor:CSteam_Voice_Encoding)
SharedDtor();
}
void CSteam_Voice_Encoding::SharedDtor() {
if (voice_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete voice_data_;
}
if (this != default_instance_) {
}
}
void CSteam_Voice_Encoding::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CSteam_Voice_Encoding::descriptor() {
protobuf_AssignDescriptorsOnce();
return CSteam_Voice_Encoding_descriptor_;
}
const CSteam_Voice_Encoding& CSteam_Voice_Encoding::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
return *default_instance_;
}
CSteam_Voice_Encoding* CSteam_Voice_Encoding::default_instance_ = NULL;
CSteam_Voice_Encoding* CSteam_Voice_Encoding::New() const {
return new CSteam_Voice_Encoding;
}
void CSteam_Voice_Encoding::Clear() {
if (has_voice_data()) {
if (voice_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
voice_data_->clear();
}
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool CSteam_Voice_Encoding::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CSteam_Voice_Encoding)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bytes voice_data = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_voice_data()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CSteam_Voice_Encoding)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CSteam_Voice_Encoding)
return false;
#undef DO_
}
void CSteam_Voice_Encoding::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CSteam_Voice_Encoding)
// optional bytes voice_data = 1;
if (has_voice_data()) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->voice_data(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:CSteam_Voice_Encoding)
}
::google::protobuf::uint8* CSteam_Voice_Encoding::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:CSteam_Voice_Encoding)
// optional bytes voice_data = 1;
if (has_voice_data()) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->voice_data(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CSteam_Voice_Encoding)
return target;
}
int CSteam_Voice_Encoding::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional bytes voice_data = 1;
if (has_voice_data()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->voice_data());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CSteam_Voice_Encoding::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const CSteam_Voice_Encoding* source =
::google::protobuf::internal::dynamic_cast_if_available<const CSteam_Voice_Encoding*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void CSteam_Voice_Encoding::MergeFrom(const CSteam_Voice_Encoding& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_voice_data()) {
set_voice_data(from.voice_data());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void CSteam_Voice_Encoding::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CSteam_Voice_Encoding::CopyFrom(const CSteam_Voice_Encoding& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CSteam_Voice_Encoding::IsInitialized() const {
return true;
}
void CSteam_Voice_Encoding::Swap(CSteam_Voice_Encoding* other) {
if (other != this) {
std::swap(voice_data_, other->voice_data_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata CSteam_Voice_Encoding::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CSteam_Voice_Encoding_descriptor_;
metadata.reflection = CSteam_Voice_Encoding_reflection_;
return metadata;
}
// ===================================================================
const ::google::protobuf::EnumDescriptor* CP2P_Voice_Handler_Flags_descriptor() {
protobuf_AssignDescriptorsOnce();
return CP2P_Voice_Handler_Flags_descriptor_;
}
bool CP2P_Voice_Handler_Flags_IsValid(int value) {
switch(value) {
case 1:
return true;
default:
return false;
}
}
#ifndef _MSC_VER
const CP2P_Voice_Handler_Flags CP2P_Voice::Played_Audio;
const CP2P_Voice_Handler_Flags CP2P_Voice::Handler_Flags_MIN;
const CP2P_Voice_Handler_Flags CP2P_Voice::Handler_Flags_MAX;
const int CP2P_Voice::Handler_Flags_ARRAYSIZE;
#endif // _MSC_VER
#ifndef _MSC_VER
const int CP2P_Voice::kAudioFieldNumber;
const int CP2P_Voice::kBroadcastGroupFieldNumber;
#endif // !_MSC_VER
CP2P_Voice::CP2P_Voice()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:CP2P_Voice)
}
void CP2P_Voice::InitAsDefaultInstance() {
audio_ = const_cast< ::CMsgVoiceAudio*>(&::CMsgVoiceAudio::default_instance());
}
CP2P_Voice::CP2P_Voice(const CP2P_Voice& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:CP2P_Voice)
}
void CP2P_Voice::SharedCtor() {
_cached_size_ = 0;
audio_ = NULL;
broadcast_group_ = 0u;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CP2P_Voice::~CP2P_Voice() {
// @@protoc_insertion_point(destructor:CP2P_Voice)
SharedDtor();
}
void CP2P_Voice::SharedDtor() {
if (this != default_instance_) {
delete audio_;
}
}
void CP2P_Voice::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CP2P_Voice::descriptor() {
protobuf_AssignDescriptorsOnce();
return CP2P_Voice_descriptor_;
}
const CP2P_Voice& CP2P_Voice::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
return *default_instance_;
}
CP2P_Voice* CP2P_Voice::default_instance_ = NULL;
CP2P_Voice* CP2P_Voice::New() const {
return new CP2P_Voice;
}
void CP2P_Voice::Clear() {
if (_has_bits_[0 / 32] & 3) {
if (has_audio()) {
if (audio_ != NULL) audio_->::CMsgVoiceAudio::Clear();
}
broadcast_group_ = 0u;
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool CP2P_Voice::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CP2P_Voice)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .CMsgVoiceAudio audio = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_audio()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(16)) goto parse_broadcast_group;
break;
}
// optional uint32 broadcast_group = 2;
case 2: {
if (tag == 16) {
parse_broadcast_group:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &broadcast_group_)));
set_has_broadcast_group();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CP2P_Voice)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CP2P_Voice)
return false;
#undef DO_
}
void CP2P_Voice::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CP2P_Voice)
// optional .CMsgVoiceAudio audio = 1;
if (has_audio()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->audio(), output);
}
// optional uint32 broadcast_group = 2;
if (has_broadcast_group()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->broadcast_group(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:CP2P_Voice)
}
::google::protobuf::uint8* CP2P_Voice::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:CP2P_Voice)
// optional .CMsgVoiceAudio audio = 1;
if (has_audio()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, this->audio(), target);
}
// optional uint32 broadcast_group = 2;
if (has_broadcast_group()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->broadcast_group(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CP2P_Voice)
return target;
}
int CP2P_Voice::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional .CMsgVoiceAudio audio = 1;
if (has_audio()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->audio());
}
// optional uint32 broadcast_group = 2;
if (has_broadcast_group()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->broadcast_group());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CP2P_Voice::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const CP2P_Voice* source =
::google::protobuf::internal::dynamic_cast_if_available<const CP2P_Voice*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void CP2P_Voice::MergeFrom(const CP2P_Voice& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_audio()) {
mutable_audio()->::CMsgVoiceAudio::MergeFrom(from.audio());
}
if (from.has_broadcast_group()) {
set_broadcast_group(from.broadcast_group());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void CP2P_Voice::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CP2P_Voice::CopyFrom(const CP2P_Voice& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CP2P_Voice::IsInitialized() const {
return true;
}
void CP2P_Voice::Swap(CP2P_Voice* other) {
if (other != this) {
std::swap(audio_, other->audio_);
std::swap(broadcast_group_, other->broadcast_group_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata CP2P_Voice::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CP2P_Voice_descriptor_;
metadata.reflection = CP2P_Voice_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int CP2P_Ping::kSendTimeFieldNumber;
const int CP2P_Ping::kIsReplyFieldNumber;
#endif // !_MSC_VER
CP2P_Ping::CP2P_Ping()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:CP2P_Ping)
}
void CP2P_Ping::InitAsDefaultInstance() {
}
CP2P_Ping::CP2P_Ping(const CP2P_Ping& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:CP2P_Ping)
}
void CP2P_Ping::SharedCtor() {
_cached_size_ = 0;
send_time_ = GOOGLE_ULONGLONG(0);
is_reply_ = false;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CP2P_Ping::~CP2P_Ping() {
// @@protoc_insertion_point(destructor:CP2P_Ping)
SharedDtor();
}
void CP2P_Ping::SharedDtor() {
if (this != default_instance_) {
}
}
void CP2P_Ping::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CP2P_Ping::descriptor() {
protobuf_AssignDescriptorsOnce();
return CP2P_Ping_descriptor_;
}
const CP2P_Ping& CP2P_Ping::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
return *default_instance_;
}
CP2P_Ping* CP2P_Ping::default_instance_ = NULL;
CP2P_Ping* CP2P_Ping::New() const {
return new CP2P_Ping;
}
void CP2P_Ping::Clear() {
#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \
&reinterpret_cast<CP2P_Ping*>(16)->f) - \
reinterpret_cast<char*>(16))
#define ZR_(first, last) do { \
size_t f = OFFSET_OF_FIELD_(first); \
size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
::memset(&first, 0, n); \
} while (0)
ZR_(send_time_, is_reply_);
#undef OFFSET_OF_FIELD_
#undef ZR_
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool CP2P_Ping::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CP2P_Ping)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required uint64 send_time = 1;
case 1: {
if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &send_time_)));
set_has_send_time();
} else {
goto handle_unusual;
}
if (input->ExpectTag(16)) goto parse_is_reply;
break;
}
// required bool is_reply = 2;
case 2: {
if (tag == 16) {
parse_is_reply:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &is_reply_)));
set_has_is_reply();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CP2P_Ping)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CP2P_Ping)
return false;
#undef DO_
}
void CP2P_Ping::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CP2P_Ping)
// required uint64 send_time = 1;
if (has_send_time()) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->send_time(), output);
}
// required bool is_reply = 2;
if (has_is_reply()) {
::google::protobuf::internal::WireFormatLite::WriteBool(2, this->is_reply(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:CP2P_Ping)
}
::google::protobuf::uint8* CP2P_Ping::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:CP2P_Ping)
// required uint64 send_time = 1;
if (has_send_time()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->send_time(), target);
}
// required bool is_reply = 2;
if (has_is_reply()) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->is_reply(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CP2P_Ping)
return target;
}
int CP2P_Ping::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// required uint64 send_time = 1;
if (has_send_time()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->send_time());
}
// required bool is_reply = 2;
if (has_is_reply()) {
total_size += 1 + 1;
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CP2P_Ping::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const CP2P_Ping* source =
::google::protobuf::internal::dynamic_cast_if_available<const CP2P_Ping*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void CP2P_Ping::MergeFrom(const CP2P_Ping& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_send_time()) {
set_send_time(from.send_time());
}
if (from.has_is_reply()) {
set_is_reply(from.is_reply());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void CP2P_Ping::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CP2P_Ping::CopyFrom(const CP2P_Ping& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CP2P_Ping::IsInitialized() const {
if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
return true;
}
void CP2P_Ping::Swap(CP2P_Ping* other) {
if (other != this) {
std::swap(send_time_, other->send_time_);
std::swap(is_reply_, other->is_reply_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata CP2P_Ping::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CP2P_Ping_descriptor_;
metadata.reflection = CP2P_Ping_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int CP2P_VRAvatarPosition_COrientation::kPosFieldNumber;
const int CP2P_VRAvatarPosition_COrientation::kAngFieldNumber;
#endif // !_MSC_VER
CP2P_VRAvatarPosition_COrientation::CP2P_VRAvatarPosition_COrientation()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:CP2P_VRAvatarPosition.COrientation)
}
void CP2P_VRAvatarPosition_COrientation::InitAsDefaultInstance() {
pos_ = const_cast< ::CMsgVector*>(&::CMsgVector::default_instance());
ang_ = const_cast< ::CMsgQAngle*>(&::CMsgQAngle::default_instance());
}
CP2P_VRAvatarPosition_COrientation::CP2P_VRAvatarPosition_COrientation(const CP2P_VRAvatarPosition_COrientation& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:CP2P_VRAvatarPosition.COrientation)
}
void CP2P_VRAvatarPosition_COrientation::SharedCtor() {
_cached_size_ = 0;
pos_ = NULL;
ang_ = NULL;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CP2P_VRAvatarPosition_COrientation::~CP2P_VRAvatarPosition_COrientation() {
// @@protoc_insertion_point(destructor:CP2P_VRAvatarPosition.COrientation)
SharedDtor();
}
void CP2P_VRAvatarPosition_COrientation::SharedDtor() {
if (this != default_instance_) {
delete pos_;
delete ang_;
}
}
void CP2P_VRAvatarPosition_COrientation::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition_COrientation::descriptor() {
protobuf_AssignDescriptorsOnce();
return CP2P_VRAvatarPosition_COrientation_descriptor_;
}
const CP2P_VRAvatarPosition_COrientation& CP2P_VRAvatarPosition_COrientation::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
return *default_instance_;
}
CP2P_VRAvatarPosition_COrientation* CP2P_VRAvatarPosition_COrientation::default_instance_ = NULL;
CP2P_VRAvatarPosition_COrientation* CP2P_VRAvatarPosition_COrientation::New() const {
return new CP2P_VRAvatarPosition_COrientation;
}
void CP2P_VRAvatarPosition_COrientation::Clear() {
if (_has_bits_[0 / 32] & 3) {
if (has_pos()) {
if (pos_ != NULL) pos_->::CMsgVector::Clear();
}
if (has_ang()) {
if (ang_ != NULL) ang_->::CMsgQAngle::Clear();
}
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool CP2P_VRAvatarPosition_COrientation::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CP2P_VRAvatarPosition.COrientation)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .CMsgVector pos = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_pos()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_ang;
break;
}
// optional .CMsgQAngle ang = 2;
case 2: {
if (tag == 18) {
parse_ang:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_ang()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CP2P_VRAvatarPosition.COrientation)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CP2P_VRAvatarPosition.COrientation)
return false;
#undef DO_
}
void CP2P_VRAvatarPosition_COrientation::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CP2P_VRAvatarPosition.COrientation)
// optional .CMsgVector pos = 1;
if (has_pos()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->pos(), output);
}
// optional .CMsgQAngle ang = 2;
if (has_ang()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->ang(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:CP2P_VRAvatarPosition.COrientation)
}
::google::protobuf::uint8* CP2P_VRAvatarPosition_COrientation::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:CP2P_VRAvatarPosition.COrientation)
// optional .CMsgVector pos = 1;
if (has_pos()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, this->pos(), target);
}
// optional .CMsgQAngle ang = 2;
if (has_ang()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
2, this->ang(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CP2P_VRAvatarPosition.COrientation)
return target;
}
int CP2P_VRAvatarPosition_COrientation::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional .CMsgVector pos = 1;
if (has_pos()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->pos());
}
// optional .CMsgQAngle ang = 2;
if (has_ang()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->ang());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CP2P_VRAvatarPosition_COrientation::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const CP2P_VRAvatarPosition_COrientation* source =
::google::protobuf::internal::dynamic_cast_if_available<const CP2P_VRAvatarPosition_COrientation*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void CP2P_VRAvatarPosition_COrientation::MergeFrom(const CP2P_VRAvatarPosition_COrientation& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_pos()) {
mutable_pos()->::CMsgVector::MergeFrom(from.pos());
}
if (from.has_ang()) {
mutable_ang()->::CMsgQAngle::MergeFrom(from.ang());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void CP2P_VRAvatarPosition_COrientation::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CP2P_VRAvatarPosition_COrientation::CopyFrom(const CP2P_VRAvatarPosition_COrientation& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CP2P_VRAvatarPosition_COrientation::IsInitialized() const {
return true;
}
void CP2P_VRAvatarPosition_COrientation::Swap(CP2P_VRAvatarPosition_COrientation* other) {
if (other != this) {
std::swap(pos_, other->pos_);
std::swap(ang_, other->ang_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata CP2P_VRAvatarPosition_COrientation::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CP2P_VRAvatarPosition_COrientation_descriptor_;
metadata.reflection = CP2P_VRAvatarPosition_COrientation_reflection_;
return metadata;
}
// -------------------------------------------------------------------
#ifndef _MSC_VER
const int CP2P_VRAvatarPosition::kBodyPartsFieldNumber;
const int CP2P_VRAvatarPosition::kHatIdFieldNumber;
const int CP2P_VRAvatarPosition::kSceneIdFieldNumber;
const int CP2P_VRAvatarPosition::kWorldScaleFieldNumber;
#endif // !_MSC_VER
CP2P_VRAvatarPosition::CP2P_VRAvatarPosition()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:CP2P_VRAvatarPosition)
}
void CP2P_VRAvatarPosition::InitAsDefaultInstance() {
}
CP2P_VRAvatarPosition::CP2P_VRAvatarPosition(const CP2P_VRAvatarPosition& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:CP2P_VRAvatarPosition)
}
void CP2P_VRAvatarPosition::SharedCtor() {
_cached_size_ = 0;
hat_id_ = 0;
scene_id_ = 0;
world_scale_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CP2P_VRAvatarPosition::~CP2P_VRAvatarPosition() {
// @@protoc_insertion_point(destructor:CP2P_VRAvatarPosition)
SharedDtor();
}
void CP2P_VRAvatarPosition::SharedDtor() {
if (this != default_instance_) {
}
}
void CP2P_VRAvatarPosition::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CP2P_VRAvatarPosition::descriptor() {
protobuf_AssignDescriptorsOnce();
return CP2P_VRAvatarPosition_descriptor_;
}
const CP2P_VRAvatarPosition& CP2P_VRAvatarPosition::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
return *default_instance_;
}
CP2P_VRAvatarPosition* CP2P_VRAvatarPosition::default_instance_ = NULL;
CP2P_VRAvatarPosition* CP2P_VRAvatarPosition::New() const {
return new CP2P_VRAvatarPosition;
}
void CP2P_VRAvatarPosition::Clear() {
#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \
&reinterpret_cast<CP2P_VRAvatarPosition*>(16)->f) - \
reinterpret_cast<char*>(16))
#define ZR_(first, last) do { \
size_t f = OFFSET_OF_FIELD_(first); \
size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
::memset(&first, 0, n); \
} while (0)
ZR_(hat_id_, world_scale_);
#undef OFFSET_OF_FIELD_
#undef ZR_
body_parts_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool CP2P_VRAvatarPosition::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CP2P_VRAvatarPosition)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1;
case 1: {
if (tag == 10) {
parse_body_parts:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, add_body_parts()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_body_parts;
if (input->ExpectTag(16)) goto parse_hat_id;
break;
}
// optional int32 hat_id = 2;
case 2: {
if (tag == 16) {
parse_hat_id:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &hat_id_)));
set_has_hat_id();
} else {
goto handle_unusual;
}
if (input->ExpectTag(24)) goto parse_scene_id;
break;
}
// optional int32 scene_id = 3;
case 3: {
if (tag == 24) {
parse_scene_id:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &scene_id_)));
set_has_scene_id();
} else {
goto handle_unusual;
}
if (input->ExpectTag(32)) goto parse_world_scale;
break;
}
// optional int32 world_scale = 4;
case 4: {
if (tag == 32) {
parse_world_scale:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &world_scale_)));
set_has_world_scale();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CP2P_VRAvatarPosition)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CP2P_VRAvatarPosition)
return false;
#undef DO_
}
void CP2P_VRAvatarPosition::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CP2P_VRAvatarPosition)
// repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1;
for (int i = 0; i < this->body_parts_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->body_parts(i), output);
}
// optional int32 hat_id = 2;
if (has_hat_id()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->hat_id(), output);
}
// optional int32 scene_id = 3;
if (has_scene_id()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->scene_id(), output);
}
// optional int32 world_scale = 4;
if (has_world_scale()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->world_scale(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:CP2P_VRAvatarPosition)
}
::google::protobuf::uint8* CP2P_VRAvatarPosition::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:CP2P_VRAvatarPosition)
// repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1;
for (int i = 0; i < this->body_parts_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, this->body_parts(i), target);
}
// optional int32 hat_id = 2;
if (has_hat_id()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->hat_id(), target);
}
// optional int32 scene_id = 3;
if (has_scene_id()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->scene_id(), target);
}
// optional int32 world_scale = 4;
if (has_world_scale()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->world_scale(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CP2P_VRAvatarPosition)
return target;
}
int CP2P_VRAvatarPosition::ByteSize() const {
int total_size = 0;
if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) {
// optional int32 hat_id = 2;
if (has_hat_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->hat_id());
}
// optional int32 scene_id = 3;
if (has_scene_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->scene_id());
}
// optional int32 world_scale = 4;
if (has_world_scale()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->world_scale());
}
}
// repeated .CP2P_VRAvatarPosition.COrientation body_parts = 1;
total_size += 1 * this->body_parts_size();
for (int i = 0; i < this->body_parts_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->body_parts(i));
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CP2P_VRAvatarPosition::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const CP2P_VRAvatarPosition* source =
::google::protobuf::internal::dynamic_cast_if_available<const CP2P_VRAvatarPosition*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void CP2P_VRAvatarPosition::MergeFrom(const CP2P_VRAvatarPosition& from) {
GOOGLE_CHECK_NE(&from, this);
body_parts_.MergeFrom(from.body_parts_);
if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) {
if (from.has_hat_id()) {
set_hat_id(from.hat_id());
}
if (from.has_scene_id()) {
set_scene_id(from.scene_id());
}
if (from.has_world_scale()) {
set_world_scale(from.world_scale());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void CP2P_VRAvatarPosition::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CP2P_VRAvatarPosition::CopyFrom(const CP2P_VRAvatarPosition& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CP2P_VRAvatarPosition::IsInitialized() const {
return true;
}
void CP2P_VRAvatarPosition::Swap(CP2P_VRAvatarPosition* other) {
if (other != this) {
body_parts_.Swap(&other->body_parts_);
std::swap(hat_id_, other->hat_id_);
std::swap(scene_id_, other->scene_id_);
std::swap(world_scale_, other->world_scale_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata CP2P_VRAvatarPosition::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CP2P_VRAvatarPosition_descriptor_;
metadata.reflection = CP2P_VRAvatarPosition_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int CP2P_WatchSynchronization::kDemoTickFieldNumber;
const int CP2P_WatchSynchronization::kPausedFieldNumber;
const int CP2P_WatchSynchronization::kTvListenVoiceIndicesFieldNumber;
const int CP2P_WatchSynchronization::kDotaSpectatorModeFieldNumber;
const int CP2P_WatchSynchronization::kDotaSpectatorWatchingBroadcasterFieldNumber;
const int CP2P_WatchSynchronization::kDotaSpectatorHeroIndexFieldNumber;
const int CP2P_WatchSynchronization::kDotaSpectatorAutospeedFieldNumber;
const int CP2P_WatchSynchronization::kDotaReplaySpeedFieldNumber;
#endif // !_MSC_VER
CP2P_WatchSynchronization::CP2P_WatchSynchronization()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:CP2P_WatchSynchronization)
}
void CP2P_WatchSynchronization::InitAsDefaultInstance() {
}
CP2P_WatchSynchronization::CP2P_WatchSynchronization(const CP2P_WatchSynchronization& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:CP2P_WatchSynchronization)
}
void CP2P_WatchSynchronization::SharedCtor() {
_cached_size_ = 0;
demo_tick_ = 0;
paused_ = false;
tv_listen_voice_indices_ = 0;
dota_spectator_mode_ = 0;
dota_spectator_watching_broadcaster_ = 0;
dota_spectator_hero_index_ = 0;
dota_spectator_autospeed_ = 0;
dota_replay_speed_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CP2P_WatchSynchronization::~CP2P_WatchSynchronization() {
// @@protoc_insertion_point(destructor:CP2P_WatchSynchronization)
SharedDtor();
}
void CP2P_WatchSynchronization::SharedDtor() {
if (this != default_instance_) {
}
}
void CP2P_WatchSynchronization::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CP2P_WatchSynchronization::descriptor() {
protobuf_AssignDescriptorsOnce();
return CP2P_WatchSynchronization_descriptor_;
}
const CP2P_WatchSynchronization& CP2P_WatchSynchronization::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_c_5fpeer2peer_5fnetmessages_2eproto();
return *default_instance_;
}
CP2P_WatchSynchronization* CP2P_WatchSynchronization::default_instance_ = NULL;
CP2P_WatchSynchronization* CP2P_WatchSynchronization::New() const {
return new CP2P_WatchSynchronization;
}
void CP2P_WatchSynchronization::Clear() {
#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \
&reinterpret_cast<CP2P_WatchSynchronization*>(16)->f) - \
reinterpret_cast<char*>(16))
#define ZR_(first, last) do { \
size_t f = OFFSET_OF_FIELD_(first); \
size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
::memset(&first, 0, n); \
} while (0)
if (_has_bits_[0 / 32] & 255) {
ZR_(demo_tick_, dota_replay_speed_);
}
#undef OFFSET_OF_FIELD_
#undef ZR_
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool CP2P_WatchSynchronization::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:CP2P_WatchSynchronization)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 demo_tick = 1;
case 1: {
if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &demo_tick_)));
set_has_demo_tick();
} else {
goto handle_unusual;
}
if (input->ExpectTag(16)) goto parse_paused;
break;
}
// optional bool paused = 2;
case 2: {
if (tag == 16) {
parse_paused:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &paused_)));
set_has_paused();
} else {
goto handle_unusual;
}
if (input->ExpectTag(24)) goto parse_tv_listen_voice_indices;
break;
}
// optional int32 tv_listen_voice_indices = 3;
case 3: {
if (tag == 24) {
parse_tv_listen_voice_indices:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &tv_listen_voice_indices_)));
set_has_tv_listen_voice_indices();
} else {
goto handle_unusual;
}
if (input->ExpectTag(32)) goto parse_dota_spectator_mode;
break;
}
// optional int32 dota_spectator_mode = 4;
case 4: {
if (tag == 32) {
parse_dota_spectator_mode:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &dota_spectator_mode_)));
set_has_dota_spectator_mode();
} else {
goto handle_unusual;
}
if (input->ExpectTag(40)) goto parse_dota_spectator_watching_broadcaster;
break;
}
// optional int32 dota_spectator_watching_broadcaster = 5;
case 5: {
if (tag == 40) {
parse_dota_spectator_watching_broadcaster:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &dota_spectator_watching_broadcaster_)));
set_has_dota_spectator_watching_broadcaster();
} else {
goto handle_unusual;
}
if (input->ExpectTag(48)) goto parse_dota_spectator_hero_index;
break;
}
// optional int32 dota_spectator_hero_index = 6;
case 6: {
if (tag == 48) {
parse_dota_spectator_hero_index:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &dota_spectator_hero_index_)));
set_has_dota_spectator_hero_index();
} else {
goto handle_unusual;
}
if (input->ExpectTag(56)) goto parse_dota_spectator_autospeed;
break;
}
// optional int32 dota_spectator_autospeed = 7;
case 7: {
if (tag == 56) {
parse_dota_spectator_autospeed:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &dota_spectator_autospeed_)));
set_has_dota_spectator_autospeed();
} else {
goto handle_unusual;
}
if (input->ExpectTag(64)) goto parse_dota_replay_speed;
break;
}
// optional int32 dota_replay_speed = 8;
case 8: {
if (tag == 64) {
parse_dota_replay_speed:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &dota_replay_speed_)));
set_has_dota_replay_speed();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:CP2P_WatchSynchronization)
return true;
failure:
// @@protoc_insertion_point(parse_failure:CP2P_WatchSynchronization)
return false;
#undef DO_
}
void CP2P_WatchSynchronization::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:CP2P_WatchSynchronization)
// optional int32 demo_tick = 1;
if (has_demo_tick()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->demo_tick(), output);
}
// optional bool paused = 2;
if (has_paused()) {
::google::protobuf::internal::WireFormatLite::WriteBool(2, this->paused(), output);
}
// optional int32 tv_listen_voice_indices = 3;
if (has_tv_listen_voice_indices()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->tv_listen_voice_indices(), output);
}
// optional int32 dota_spectator_mode = 4;
if (has_dota_spectator_mode()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->dota_spectator_mode(), output);
}
// optional int32 dota_spectator_watching_broadcaster = 5;
if (has_dota_spectator_watching_broadcaster()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->dota_spectator_watching_broadcaster(), output);
}
// optional int32 dota_spectator_hero_index = 6;
if (has_dota_spectator_hero_index()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->dota_spectator_hero_index(), output);
}
// optional int32 dota_spectator_autospeed = 7;
if (has_dota_spectator_autospeed()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(7, this->dota_spectator_autospeed(), output);
}
// optional int32 dota_replay_speed = 8;
if (has_dota_replay_speed()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(8, this->dota_replay_speed(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:CP2P_WatchSynchronization)
}
::google::protobuf::uint8* CP2P_WatchSynchronization::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:CP2P_WatchSynchronization)
// optional int32 demo_tick = 1;
if (has_demo_tick()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->demo_tick(), target);
}
// optional bool paused = 2;
if (has_paused()) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->paused(), target);
}
// optional int32 tv_listen_voice_indices = 3;
if (has_tv_listen_voice_indices()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->tv_listen_voice_indices(), target);
}
// optional int32 dota_spectator_mode = 4;
if (has_dota_spectator_mode()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->dota_spectator_mode(), target);
}
// optional int32 dota_spectator_watching_broadcaster = 5;
if (has_dota_spectator_watching_broadcaster()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->dota_spectator_watching_broadcaster(), target);
}
// optional int32 dota_spectator_hero_index = 6;
if (has_dota_spectator_hero_index()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->dota_spectator_hero_index(), target);
}
// optional int32 dota_spectator_autospeed = 7;
if (has_dota_spectator_autospeed()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(7, this->dota_spectator_autospeed(), target);
}
// optional int32 dota_replay_speed = 8;
if (has_dota_replay_speed()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(8, this->dota_replay_speed(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CP2P_WatchSynchronization)
return target;
}
int CP2P_WatchSynchronization::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional int32 demo_tick = 1;
if (has_demo_tick()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->demo_tick());
}
// optional bool paused = 2;
if (has_paused()) {
total_size += 1 + 1;
}
// optional int32 tv_listen_voice_indices = 3;
if (has_tv_listen_voice_indices()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->tv_listen_voice_indices());
}
// optional int32 dota_spectator_mode = 4;
if (has_dota_spectator_mode()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->dota_spectator_mode());
}
// optional int32 dota_spectator_watching_broadcaster = 5;
if (has_dota_spectator_watching_broadcaster()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->dota_spectator_watching_broadcaster());
}
// optional int32 dota_spectator_hero_index = 6;
if (has_dota_spectator_hero_index()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->dota_spectator_hero_index());
}
// optional int32 dota_spectator_autospeed = 7;
if (has_dota_spectator_autospeed()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->dota_spectator_autospeed());
}
// optional int32 dota_replay_speed = 8;
if (has_dota_replay_speed()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->dota_replay_speed());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CP2P_WatchSynchronization::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const CP2P_WatchSynchronization* source =
::google::protobuf::internal::dynamic_cast_if_available<const CP2P_WatchSynchronization*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void CP2P_WatchSynchronization::MergeFrom(const CP2P_WatchSynchronization& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_demo_tick()) {
set_demo_tick(from.demo_tick());
}
if (from.has_paused()) {
set_paused(from.paused());
}
if (from.has_tv_listen_voice_indices()) {
set_tv_listen_voice_indices(from.tv_listen_voice_indices());
}
if (from.has_dota_spectator_mode()) {
set_dota_spectator_mode(from.dota_spectator_mode());
}
if (from.has_dota_spectator_watching_broadcaster()) {
set_dota_spectator_watching_broadcaster(from.dota_spectator_watching_broadcaster());
}
if (from.has_dota_spectator_hero_index()) {
set_dota_spectator_hero_index(from.dota_spectator_hero_index());
}
if (from.has_dota_spectator_autospeed()) {
set_dota_spectator_autospeed(from.dota_spectator_autospeed());
}
if (from.has_dota_replay_speed()) {
set_dota_replay_speed(from.dota_replay_speed());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void CP2P_WatchSynchronization::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CP2P_WatchSynchronization::CopyFrom(const CP2P_WatchSynchronization& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CP2P_WatchSynchronization::IsInitialized() const {
return true;
}
void CP2P_WatchSynchronization::Swap(CP2P_WatchSynchronization* other) {
if (other != this) {
std::swap(demo_tick_, other->demo_tick_);
std::swap(paused_, other->paused_);
std::swap(tv_listen_voice_indices_, other->tv_listen_voice_indices_);
std::swap(dota_spectator_mode_, other->dota_spectator_mode_);
std::swap(dota_spectator_watching_broadcaster_, other->dota_spectator_watching_broadcaster_);
std::swap(dota_spectator_hero_index_, other->dota_spectator_hero_index_);
std::swap(dota_spectator_autospeed_, other->dota_spectator_autospeed_);
std::swap(dota_replay_speed_, other->dota_replay_speed_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata CP2P_WatchSynchronization::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CP2P_WatchSynchronization_descriptor_;
metadata.reflection = CP2P_WatchSynchronization_reflection_;
return metadata;
}
// @@protoc_insertion_point(namespace_scope)
// @@protoc_insertion_point(global_scope)
| 33.944853 | 133 | 0.703118 |
efb2eb3e96f6020c3d91536886f463811a9693f3 | 36 | cpp | C++ | Chapter-3-Tree/Homework/Chapter-3-Tree-Homework-1/main.cpp | jubgjf/DataStructuresAndAlgorithms | 48c7fa62e618ddbefa760229ce677cdfc822b53f | [
"MIT"
] | 2 | 2020-10-18T07:36:25.000Z | 2021-07-31T23:34:49.000Z | Chapter-3-Tree/Homework/Chapter-3-Tree-Homework-1/main.cpp | jubgjf/DataStructuresAndAlgorithms | 48c7fa62e618ddbefa760229ce677cdfc822b53f | [
"MIT"
] | null | null | null | Chapter-3-Tree/Homework/Chapter-3-Tree-Homework-1/main.cpp | jubgjf/DataStructuresAndAlgorithms | 48c7fa62e618ddbefa760229ce677cdfc822b53f | [
"MIT"
] | null | null | null | #include "header.h"
int main()
{
}
| 6 | 19 | 0.583333 |
efb31ec19a89d05b2cd8ef548b6d6278a3862f1c | 3,163 | cpp | C++ | day05/ex05/CentralBureaucracy.cpp | psprawka/Cpp_Piscine | 73fdb50d654c49587d7d3a2d475b1c57033c8dd4 | [
"MIT"
] | 1 | 2019-09-15T08:29:00.000Z | 2019-09-15T08:29:00.000Z | day05/ex05/CentralBureaucracy.cpp | psprawka/Cpp_Piscine | 73fdb50d654c49587d7d3a2d475b1c57033c8dd4 | [
"MIT"
] | 1 | 2019-09-15T08:28:48.000Z | 2019-09-15T08:28:48.000Z | day05/ex05/CentralBureaucracy.cpp | psprawka/Cpp_Piscine | 73fdb50d654c49587d7d3a2d475b1c57033c8dd4 | [
"MIT"
] | 1 | 2020-03-04T16:14:40.000Z | 2020-03-04T16:14:40.000Z | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* CentralBureaucracy.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: psprawka <psprawka@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/02 22:25:42 by psprawka #+# #+# */
/* Updated: 2018/07/03 13:24:10 by psprawka ### ########.fr */
/* */
/* ************************************************************************** */
#include "CentralBureaucracy.hpp"
#include "Bureaucrat.hpp"
#include "Intern.hpp"
#include "Form.hpp"
#include "OfficeBlock.hpp"
#include <iostream>
#define YELLOW "\x1B[33m"
#define NORMAL "\x1B[0m"
int CentralBureaucracy::_nb_targets = 0;
int CentralBureaucracy::_nb_signers = 0;
int CentralBureaucracy::_nb_executers = 0;
CentralBureaucracy::CentralBureaucracy(void)
{
Intern intern;
for (int i = 0; i < 20; i++)
this->_blocks[i].setIntern(intern);
}
CentralBureaucracy::CentralBureaucracy(CentralBureaucracy const &obj) {
*this = obj;
}
CentralBureaucracy::~CentralBureaucracy(void) {}
CentralBureaucracy &CentralBureaucracy::operator=(CentralBureaucracy const &obj)
{
for (int i = 0; i < 20; i++)
{
this->_blocks[i].setExecutor(*(obj._blocks[i].getExecutor()));
this->_blocks[i].setSigner(*(obj._blocks[i].getSigner()));
this->_target[i] = obj._target[i];
}
return (*this);
}
void CentralBureaucracy::feedSigner(Bureaucrat &obj)
{
if (this->_nb_signers < 20)
this->_blocks[this->_nb_signers++].setSigner(obj);
else
std::cout << "No more spots for Bureaucrats [feedSigner]." << std::endl;
}
void CentralBureaucracy::feedExecuter(Bureaucrat &obj)
{
if (this->_nb_executers < 20)
this->_blocks[this->_nb_executers++].setExecutor(obj);
else
std::cout << "No more spots for Bureaucrats [feedSigner]." << std::endl;
}
void CentralBureaucracy::doBureaucracy(void)
{
std::string interns[3] = {"shrubbery creation", "robotomy request", "presidential pardon"};
int random_person = rand () % 20;
if (this->_nb_targets == 0)
std::cout << "No targets in queue." << std::endl;
for (int i = 0; i < this->_nb_targets; i++)
{
if (!this->_blocks[random_person].getExecutor() || !this->_blocks[random_person].getSigner())
std::cout << "No worker in the office for \"" << this->_target[i] << "\".\n\n";
else
{
std::cout << YELLOW;
this->_blocks[random_person].doBureaucracy(interns[rand () % 3], this->_target[i]);
std::cout << NORMAL << std::endl;
}
random_person = rand () % 20;
}
}
void CentralBureaucracy::queueUp(std::string target)
{
if (this->_nb_targets < 20)
this->_target[this->_nb_targets++] = target;
else
std::cout << "No more targets allowed to queueUp." << std::endl;
}
| 30.12381 | 95 | 0.523554 |
efb9f6507df42e6e4b450ae84d187d9bfc4a6c6c | 818 | cpp | C++ | Problem Solving/Algorithms/Strings/Making Anagrams/making anagrams.cpp | IsaacAsante/hackerrank | 76c430b341ce1e2ab427eda57508eb309d3b215b | [
"MIT"
] | 108 | 2021-03-29T05:04:16.000Z | 2022-03-19T15:11:52.000Z | Problem Solving/Algorithms/Strings/Making Anagrams/making anagrams.cpp | IsaacAsante/hackerrank | 76c430b341ce1e2ab427eda57508eb309d3b215b | [
"MIT"
] | null | null | null | Problem Solving/Algorithms/Strings/Making Anagrams/making anagrams.cpp | IsaacAsante/hackerrank | 76c430b341ce1e2ab427eda57508eb309d3b215b | [
"MIT"
] | 32 | 2021-03-30T03:56:54.000Z | 2022-03-27T14:41:32.000Z | /* Author: Isaac Asante
* HackerRank URL for this exercise: https://www.hackerrank.com/challenges/making-anagrams/problem
* Original video explanation: https://www.youtube.com/watch?v=05mznZNMjvY
* Last verified on: May 19, 2021
*/
/* IMPORTANT:
* This code is meant to be used as a solution on HackerRank (link above).
* It is not meant to be executed as a standalone program.
*/
int makingAnagrams(string s1, string s2) {
int alphabet[26] = { 0 }; // All counts initialized to zero
int sum = 0;
for (int i = 0; i < s1.size(); i++)
--alphabet[s1[i] - 'a']; // Decrease for s1
for (int i = 0; i < s2.size(); i++)
++alphabet[s2[i] - 'a']; // Increase for s2
for (int i = 0; i < 26; i++)
sum += abs(alphabet[i]); // Get the sum of abs values
return sum;
}
| 31.461538 | 98 | 0.617359 |
efba45131a5dbe76ca0d3941a4f10c01cb4946a8 | 8,133 | cpp | C++ | data.cpp | wsaczawa/Mochawk | 8dde3f8303325f489d087dc2877056cd26ee64c3 | [
"MIT"
] | null | null | null | data.cpp | wsaczawa/Mochawk | 8dde3f8303325f489d087dc2877056cd26ee64c3 | [
"MIT"
] | null | null | null | data.cpp | wsaczawa/Mochawk | 8dde3f8303325f489d087dc2877056cd26ee64c3 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "dataFTP.h"
struct older_file {
bool operator()(const fs::directory_entry& p, const fs::directory_entry& p2)
{
return p.last_write_time() > p2.last_write_time();
}
};
std::string value(std::string line) {
return line.substr(line.find(',') + 1, line.length() - line.find(','));
}
folders::folders() {
signals.clear();
std::wifstream f;
std::wstring line;
f.open("./signals.csv");
while (std::getline(f, line)) {
std::pair<std::wstring, std::wstring> signal;
signal.first = getcell(line, 1);
signal.second = getcell(line, 2);
signals.push_back(signal);
}
}
void folders::manage(std::string file) {
fs::remove(New / file);
std::this_thread::sleep_for(std::chrono::seconds(1));
if (fs::exists(file)) {
std::this_thread::sleep_for(std::chrono::seconds(1));
fs::copy_file(file, Summed / file, fs::copy_options::update_existing);
std::this_thread::sleep_for(std::chrono::seconds(1));
fs::remove(file);
}
}
void folders::upgrade(fs::path from, fs::path to) {
try
{
std::this_thread::sleep_for(std::chrono::seconds(1));
fs::copy(from, to, fs::copy_options::update_existing);
}
catch (std::exception& e)
{
std::cout << e.what();
}
}
void folders::send(ftp exp) {
for (auto& p : fs::directory_iterator("./export/")) {
if (exp.put(L"./export/" + p.path().wstring(), p.path().wstring())) {
fs::remove(p.path());
}
}
}
void folders::flush(fs::path d) {
try
{
fs::remove_all(d);
std::this_thread::sleep_for(std::chrono::seconds(1));
fs::copy(Flush, d, fs::copy_options::overwrite_existing);
}
catch (std::exception& e)
{
std::cout << e.what();
}
}
void folders::clear(fs::path d, int last) {
std::priority_queue<fs::directory_entry, pathvec, older_file> newest;
for (auto entry : fs::directory_iterator(d))
{
newest.push(entry);
if (newest.size() > last)
{
fs::remove_all(newest.top());
newest.pop();
}
}
}
std::size_t folders::count(fs::path d) {
using fs::directory_iterator;
return std::distance(directory_iterator(d), directory_iterator{});
}
spectrum::spectrum() {
duration = 0.0;
start = 0.0;
time = 0.0;
preset = 0.0;
vol = 0.0;
}
bool spectrum::operator<(const spectrum& a) const {
return time < a.time;
}
CNFset::CNFset() {
spectra.clear();
downLimit = 0.0;
spectraTime = 0.0;
spectraLimit = 0;
plus = 0;
minus = 0;
}
void CNFset::getConst(fs::path csv) {
std::ifstream f;
f.open(csv);
std::string s;
std::getline(f, s);
downLimit = stod(value(s));
std::getline(f, s);
spectraTime = stod(value(s));
std::getline(f, s);
spectraLimit = stoi(value(s));
std::getline(f, s);
asf = value(s);
std::getline(f, s);
f.close();
}
void CNFset::getSpectra(fs::path folder) {
spectra.clear();
for (auto& p : fs::directory_iterator(folder)) {
spectrum s;
s.name = p.path().filename().string();
s.getData(fs::absolute(p).string());
if(s.time > 0)
spectra.push_back(s);
}
}
void CNFset::load(fs::path backup) {
try {
fs::remove_all("./Buffer/");
fs::copy("./Flush/", "./Buffer/", fs::copy_options::overwrite_existing);
}
catch (std::exception& e)
{
std::cout << e.what();
}
std::ifstream f;
std::string p;
f.open(backup);
while (std::getline(f, p)) {
try {
fs::copy("./Archive/" + p, "./Buffer/" + p, fs::copy_options::overwrite_existing);
}
catch (std::exception& e)
{
std::cout << e.what();
}
}
f.close();
}
void CNFset::save(fs::path backup) {
std::ofstream f(backup);
if (f.is_open())
{
for (unsigned i = 0; i < spectra.size(); i++) {
f << spectra[i].name << std::endl;
}
f.close();
}
}
void CNFset::append(spectrum s) {
spectra.push_back(s);
std::rotate(spectra.rbegin(), spectra.rbegin() + 1, spectra.rend());
if (spectra.size() > spectraLimit + 1) spectra.pop_back();
}
bool CNFset::check(spectrum s) {
if (spectra.empty()) return TRUE;
if (s.time - spectra[0].time < downLimit) {
return FALSE;
}
else {
return TRUE;
}
}
nuclide::nuclide() {
mean = 0.0;
error = 0.0;
mda = 0.0;
}
analysis::analysis(CNFset set) {
unsigned i;
int plus = 0,
minus = 0;
for (i = 1; i < set.spectra.size(); i++) {
if (set.spectra[0].duration < set.spectra[i].duration) {
if (set.spectra[0].time - set.spectra[i].time < set.spectraTime * ((long long)set.spectraLimit + 0.5)) {
plus = i;
}
break;
}
}
for (i = set.spectra.size() - 1; i >= plus; i--) {
if (set.spectra[0].time - set.spectra[i].time < set.spectraTime * ((long long)set.spectraLimit + 0.5)) {
minus = i;
break;
}
}
if (set.spectra[0].duration < set.spectraTime * ((long long)set.spectraLimit + 0.5) && plus == 0) {
minus = 0;
}
fs::copy_file("./New/" + set.spectra[0].name, set.spectra[0].name, fs::copy_options::overwrite_existing);
s = set.spectra[0];
if (minus != 0 && plus != minus) {
if (plus != 0) {
strip(set.spectra[0].name, set.spectra[plus].name, -1);
s.duration = +set.spectra[plus].duration;
s.preset = +set.spectra[plus].preset;
}
strip(set.spectra[0].name, set.spectra[minus].name, 1);
s.duration = -set.spectra[minus].duration;
s.preset = -set.spectra[plus].preset;
}
}
void analysis::strip(std::string sumFile, std::string addFile, int f) {
std::string here = fs::current_path().string() + "/";
std::string command = "strip.exe \"" + here + sumFile + "\" \"" + here + "Archive\\" + addFile + "\" /FACTOR=" + std::to_string(f);
std::system(command.c_str());
}
void analysis::getTimestamp() {
time_t epoch = s.time - 3506716800u;
struct tm localTime = *gmtime(&epoch);
std::wostringstream strTime;
strTime << std::put_time(&localTime, L"%Y-%m-%d %H:%M:%S");
tsDisp = strTime.str();
strTime.str(std::wstring());
strTime << std::put_time(&localTime, L"%Y%m%d%H%M%S");
tsExp = strTime.str();
}
void analysis::process() {
nuclide t;
t.name = L"total";
for (unsigned i = 0; i < nuclides.size(); i++) {
t.mean = t.mean + nuclides[i].mean;
t.mda = t.mda + nuclides[i].mda;
t.error = t.error + nuclides[i].error * nuclides[i].error;
}
t.error = sqrt(t.error);
nuclides.push_back(t);
}
void analysis::writeFTP(std::vector<std::pair<std::wstring, std::wstring>> signals) {
std::wofstream f;
f.open(L"./export/" + tsExp + L".txt");
std::string det = s.name.substr(0, s.name.find("_"));
std::wstring detector(det.begin(), det.end()); //it works only for ASCII!
f << tsExp << std::endl;
for (unsigned i = 0; i < signals.size(); i++) {
std::wstring signal = signals[i].second;
auto that_nuclide = [signal](const nuclide& n) {return n.name == signal; };
int code = 1;
double value = 0.0;
auto it = std::find_if(nuclides.begin(), nuclides.end(), that_nuclide);
if (it != nuclides.end()) {
code = 0;
value = it->mean;
if (it->mean < it->mda) {
code = 1;
}
}
f << detector << "_" << signals[i].first << "\t" << value << "\t" << code << std::endl;
}
f.close();
}
void analysis::writeHTML() {
std::wofstream f;
f.open("./display.html");
f << L"<!DOCTYPE html><html><head><style> table, th, td{ border: 1px solid black; text - align: center; } h2{ text - align: center; }</style></head><body><h2> ";
f << tsDisp;
f << L" </h2><table align = \"center\"><tr><th>Nuclide</th><th>Activity [kBq/m3]</th><th>Error [kBq/m3]</th><th>MDA [kBq/m3]</th></tr>";
for (unsigned i = 0; i < nuclides.size(); i++) {
f << L"<tr>";
f << L"<td>" << nuclides[i].name << L"</td>";
if (nuclides[i].mean < nuclides[i].mda) {
f << L"<td><MDA</td>";
}
else {
f << L"<td>" << nuclides[i].mean << L"</td>";
}
f << L"<td>" << nuclides[i].error << L"</td>";
f << L"<td>" << nuclides[i].mda << L"</td>";
f << L"</tr>";
}
f << L"</table></body></html>";
f.close();
} | 26.067308 | 164 | 0.572728 |
efbb5ba8d03dba10a5d87893ddf82b2ff52cb452 | 1,396 | hpp | C++ | include/jules/array/math.hpp | verri/jules | 5370c533a68bb670ae937967e024428c705215f8 | [
"Zlib"
] | 8 | 2016-12-07T21:47:48.000Z | 2019-11-25T14:26:27.000Z | include/jules/array/math.hpp | verri/jules | 5370c533a68bb670ae937967e024428c705215f8 | [
"Zlib"
] | 23 | 2016-12-07T21:22:24.000Z | 2019-09-02T13:58:42.000Z | include/jules/array/math.hpp | verri/jules | 5370c533a68bb670ae937967e024428c705215f8 | [
"Zlib"
] | 3 | 2017-01-18T02:11:32.000Z | 2018-04-16T01:40:36.000Z | // Copyright (c) 2017-2019 Filipe Verri <filipeverri@gmail.com>
#ifndef JULES_ARRAY_MATH_H
#define JULES_ARRAY_MATH_H
#include <jules/array/functional.hpp>
#include <jules/base/math.hpp>
#include <cmath>
namespace jules
{
template <typename Array>
auto normal_pdf(const common_array_base<Array>& array, typename Array::value_type mu, typename Array::value_type sigma)
{
return apply(array, [mu = std::move(mu), sigma = std::move(sigma)](const auto& x) { return normal_pdf(x, mu, sigma); });
}
template <typename Array> auto abs(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return abs(v); });
}
template <typename Array> auto sqrt(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return sqrt(v); });
}
template <typename Array> auto log(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return log(v); });
}
template <typename Array> auto sin(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return sin(v); });
}
template <typename Array> auto cos(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return cos(v); });
}
template <typename Array> auto tanh(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return tanh(v); });
}
} // namespace jules
#endif // JULES_ARRAY_MATH_H
| 26.339623 | 122 | 0.709169 |
efbec57643023dcd2ec04d45642affda4c24fc9e | 1,114 | cpp | C++ | TicTacToeBoardTest.cpp | tchane24/x06 | 22c331ec4ea87cfb8b5b5b6da287145c0a502fe9 | [
"MIT"
] | null | null | null | TicTacToeBoardTest.cpp | tchane24/x06 | 22c331ec4ea87cfb8b5b5b6da287145c0a502fe9 | [
"MIT"
] | null | null | null | TicTacToeBoardTest.cpp | tchane24/x06 | 22c331ec4ea87cfb8b5b5b6da287145c0a502fe9 | [
"MIT"
] | null | null | null | /**
* Unit Tests for TicTacToeBoard
**/
#include <gtest/gtest.h>
#include "TicTacToeBoard.h"
class TicTacToeBoardTest : public ::testing::Test
{
protected:
TicTacToeBoardTest(){} //constructor runs before each test
virtual ~TicTacToeBoardTest(){} //destructor cleans up after tests
virtual void SetUp(){} //sets up before each test (after constructor)
virtual void TearDown(){} //clean up after each test, (before destructor)
};
TEST(TicTacToeBoardTest, sanityCheck)
{
ASSERT_TRUE(true);
}
TEST(TicTacToeBoardTest, TogglesCorrectly)
{
TicTacToeBoard t;
//Placed toggleTurn() in placePiece()
ASSERT_EQ(t.placePiece(1,2), O);
}
TEST(TicTacToeBoardTest, TogglesCorrectlyx2)
{
TicTacToeBoard t;
t.placePiece(1,2);
ASSERT_EQ(t.placePiece(1,0), X);
}
TEST(TicTacToeBoardTest, BoardIsClear)
{
TicTacToeBoard t;
t.clearBoard();
ASSERT_EQ(t.getPiece(0,0) , Blank);
}
TEST(TicTacToeBoardTest, BoardIsClear2)
{
TicTacToeBoard t;
t.clearBoard();
ASSERT_EQ(t.getPiece(1,1) , Blank);
}
TEST(TicTacToeBoardTest, placePieceOutOfBounds)
{
TicTacToeBoard t;
ASSERT_EQ(t.placePiece(3,0), Invalid);
}
| 21.018868 | 76 | 0.738779 |
efc2ce4052624ade50273969756c0e36c8e72291 | 7,686 | cpp | C++ | src/kiwi/vesKiwiImagePlaneDataRepresentation.cpp | aashish24/ves | 7a73d0d5f76fecc776950ba8ae45458df406c591 | [
"Apache-2.0"
] | 10 | 2015-11-16T02:38:48.000Z | 2021-11-17T11:19:25.000Z | src/kiwi/vesKiwiImagePlaneDataRepresentation.cpp | aashish24/ves | 7a73d0d5f76fecc776950ba8ae45458df406c591 | [
"Apache-2.0"
] | 1 | 2015-10-28T01:22:51.000Z | 2016-09-26T09:41:34.000Z | src/kiwi/vesKiwiImagePlaneDataRepresentation.cpp | aashish24/ves | 7a73d0d5f76fecc776950ba8ae45458df406c591 | [
"Apache-2.0"
] | 3 | 2016-03-18T06:06:42.000Z | 2017-05-10T09:29:54.000Z | /*========================================================================
VES --- VTK OpenGL ES Rendering Toolkit
http://www.kitware.com/ves
Copyright 2011 Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
========================================================================*/
#include "vesKiwiImagePlaneDataRepresentation.h"
#include "vesKiwiDataConversionTools.h"
#include "vesSetGet.h"
#include "vesTexture.h"
#include <vtkScalarsToColors.h>
#include <vtkImageData.h>
#include <vtkFloatArray.h>
#include <vtkLookupTable.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkNew.h>
#include <vtkQuad.h>
#include <cassert>
//----------------------------------------------------------------------------
class vesKiwiImagePlaneDataRepresentation::vesInternal
{
public:
vesInternal()
{
}
~vesInternal()
{
}
vtkSmartPointer<vtkScalarsToColors> ColorMap;
vtkSmartPointer<vtkUnsignedCharArray> TextureData;
vtkSmartPointer<vtkPolyData> ImagePlane;
};
//----------------------------------------------------------------------------
vesKiwiImagePlaneDataRepresentation::vesKiwiImagePlaneDataRepresentation()
{
this->Internal = new vesInternal();
}
//----------------------------------------------------------------------------
vesKiwiImagePlaneDataRepresentation::~vesKiwiImagePlaneDataRepresentation()
{
delete this->Internal;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setImageData(vtkImageData* imageData)
{
vtkSmartPointer<vtkPolyData> imagePlane = this->polyDataForImagePlane(imageData);
this->setPolyData(imagePlane);
this->Internal->ImagePlane = imagePlane;
vesSharedPtr<vesTexture> texture = this->texture();
if (!texture) {
this->setTexture(vesSharedPtr<vesTexture>(new vesTexture()));
}
this->setTextureFromImage(this->texture(), imageData);
}
//----------------------------------------------------------------------------
vesVector2f vesKiwiImagePlaneDataRepresentation::textureSize() const
{
assert(this->texture());
vesImage::Ptr image = this->texture()->image();
return vesVector2f(image->width(), image->height());
}
//----------------------------------------------------------------------------
vtkPolyData* vesKiwiImagePlaneDataRepresentation::imagePlanePolyData()
{
return this->Internal->ImagePlane;
}
//----------------------------------------------------------------------------
vtkScalarsToColors* vesKiwiImagePlaneDataRepresentation::colorMap()
{
return this->Internal->ColorMap;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setColorMap(vtkScalarsToColors* map)
{
this->Internal->ColorMap = map;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setGrayscaleColorMap(double scalarRange[2])
{
this->setColorMap(vesKiwiDataConversionTools::GetGrayscaleLookupTable(scalarRange));
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setShaderProgram(
vesSharedPtr<vesShaderProgram> shaderProgram)
{
// Do nothing.
vesNotUsed(shaderProgram);
}
//----------------------------------------------------------------------------
vesSharedPtr<vesTexture>
vesKiwiImagePlaneDataRepresentation::newTextureFromImage(vtkImageData* image)
{
vesSharedPtr<vesTexture> texture (new vesTexture());
this->setTextureFromImage(texture, image);
return texture;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setTextureFromImage(
vesSharedPtr<vesTexture> texture, vtkImageData* image)
{
assert(image);
assert(image->GetDataDimension() == 2);
assert(image->GetPointData()->GetScalars());
vtkSmartPointer<vtkUnsignedCharArray> pixels = vtkUnsignedCharArray::SafeDownCast(image->GetPointData()->GetScalars());
if (!pixels) {
vtkScalarsToColors* map = this->colorMap();
assert(map);
pixels = vesKiwiDataConversionTools::MapScalars(image->GetPointData()->GetScalars(), map);
}
int dimensions[3];
image->GetDimensions(dimensions);
const int flatDimension = this->imageFlatDimension(image);
int width;
int height;
if (flatDimension == 2) {
// XY plane
width = image->GetDimensions()[0];
height = image->GetDimensions()[1];
}
else if (flatDimension == 1) {
// XZ plane
width = image->GetDimensions()[0];
height = image->GetDimensions()[2];
}
else {
// YZ plane
width = image->GetDimensions()[1];
height = image->GetDimensions()[2];
}
vesKiwiDataConversionTools::SetTextureData(pixels, texture, width, height);
this->Internal->TextureData = pixels;
}
//----------------------------------------------------------------------------
int vesKiwiImagePlaneDataRepresentation::imageFlatDimension(vtkImageData* image)
{
int dimensions[3];
image->GetDimensions(dimensions);
for (int i = 0; i < 3; ++i) {
if (dimensions[i] == 1) {
return i;
}
}
return -1;
}
//----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> vesKiwiImagePlaneDataRepresentation::polyDataForImagePlane(vtkImageData* image)
{
double bounds[6];
image->GetBounds(bounds);
vtkNew<vtkPoints> quadPoints;
quadPoints->SetNumberOfPoints(4);
const int flatDimension = vesKiwiImagePlaneDataRepresentation::imageFlatDimension(image);
if (flatDimension == 2) {
// XY plane
quadPoints->SetPoint(0, bounds[0],bounds[2],bounds[4]);
quadPoints->SetPoint(1, bounds[1],bounds[2],bounds[4]);
quadPoints->SetPoint(2, bounds[1],bounds[3],bounds[4]);
quadPoints->SetPoint(3, bounds[0],bounds[3],bounds[4]);
}
else if (flatDimension == 1) {
// XZ plane
quadPoints->SetPoint(0, bounds[0],bounds[2],bounds[4]);
quadPoints->SetPoint(1, bounds[1],bounds[2],bounds[4]);
quadPoints->SetPoint(2, bounds[1],bounds[2],bounds[5]);
quadPoints->SetPoint(3, bounds[0],bounds[2],bounds[5]);
}
else {
// YZ plane
quadPoints->SetPoint(0, bounds[0],bounds[2],bounds[4]);
quadPoints->SetPoint(1, bounds[0],bounds[3],bounds[4]);
quadPoints->SetPoint(2, bounds[0],bounds[3],bounds[5]);
quadPoints->SetPoint(3, bounds[0],bounds[2],bounds[5]);
}
vtkNew<vtkQuad> quad;
quad->GetPointIds()->SetId(0, 0);
quad->GetPointIds()->SetId(1, 1);
quad->GetPointIds()->SetId(2, 2);
quad->GetPointIds()->SetId(3, 3);
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->Allocate(1, 1);
polyData->InsertNextCell(quad->GetCellType(), quad->GetPointIds());
polyData->SetPoints(quadPoints.GetPointer());
// add texture coordinates
vtkNew<vtkFloatArray> tcoords;
tcoords->SetName("tcoords");
tcoords->SetNumberOfComponents(2);
tcoords->SetNumberOfTuples(4);
tcoords->SetTuple2(0, 0,0);
tcoords->SetTuple2(1, 1,0);
tcoords->SetTuple2(2, 1,1);
tcoords->SetTuple2(3, 0,1);
polyData->GetPointData()->SetScalars(tcoords.GetPointer());
return polyData;
}
| 31.5 | 121 | 0.611371 |
efc35cabfe9d8082842d0bb0d67189eec5730142 | 33,561 | cpp | C++ | src/lib/safe_storage.cpp | imaginatho/safestorage | a2581a1ec4e2e52b39f1f8f7f08afa9c566ee127 | [
"MIT"
] | 8 | 2015-07-04T04:06:15.000Z | 2015-07-10T07:43:41.000Z | src/lib/safe_storage.cpp | imaginatho/safestorage | a2581a1ec4e2e52b39f1f8f7f08afa9c566ee127 | [
"MIT"
] | null | null | null | src/lib/safe_storage.cpp | imaginatho/safestorage | a2581a1ec4e2e52b39f1f8f7f08afa9c566ee127 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <syslog.h>
#include <iostream>
#include <sstream>
#include <string>
#include <exception>
using namespace std;
#include <log.h>
#include <safe_storage_imp.h>
#include <safe_storage_listener.h>
static const char *__safe_storage_extensions [] = {"", ".idx", ".rlg", ".st"};
#define CSTORAGE_SIGNATURE 0x51213298
#define CSTORAGE_SIGNATURE_MASK 0x00000007
#define DECLARE_STRUCT(X,Y) X Y; memset(&Y, 0, sizeof(Y));
#define DECLARE_DEFAULT_STRUCT(X,Y) X __##Y; if (!Y) { memset(&__##Y, 0, sizeof(__##Y)); Y=&__##Y; };
#define CSTORAGE_MODE_STANDARD 0
#define CSTORAGE_MODE_REBUILD 1
template <class R>
bool cmp_struct_field(R st1, R st2, const char *st1_name, const char *st2_name, const char *fieldname, int32_t pos )
{
if (st1 == st2) return true;
std::stringstream msg;
msg << "Field " << fieldname << "of structures " << st1_name;
if (pos >= 0) {
msg << "[" << pos << "]";
}
msg << "(" << st1 << ") and " << st2_name;
if (pos >= 0) {
msg << "[" << pos << "]";
}
msg << "(" << st2 << ") are different";
C_LOG_ERR(msg.str().c_str());
return false;
}
#define CMP_STRUCT_FIELD(ST1,ST2,FIELD,R)\
R |= cmp_struct_field<__typeof__(ST1.FIELD)>(ST1.FIELD,ST2.FIELD,#ST1,#ST2,#FIELD,-1);
#define CMP_STRUCT_ARRAY_FIELD(ST1,ST2,FIELD,R)\
for (int32_t __##FIELD##__index__=0; __##FIELD##__index__ < (int32_t)(sizeof(ST1.FIELD)/sizeof(ST1.FIELD[0])); ++__##FIELD##__index__ ) {\
R |= cmp_struct_field<__typeof__(ST1.FIELD[0])>(\
ST1.FIELD[__##FIELD##__index__],\
ST2.FIELD[__##FIELD##__index__],\
#ST1,#ST2,#FIELD,__##FIELD##__index__);\
}\
typedef union
{
CSafeStorageIndexReg index;
CSafeStorageDataReg data;
CSafeStorageLogReg log;
uint32_t hash_key;
} CSafeStorageHashReg;
/*
* Constructor class CSafeStorage, this method initialize structures, and create list of
* safe files managed with object. These files are added in list files.
*/
CSafeStorage::CSafeStorage ( void )
: findex(0, D_CSTORAGE_INDEX_CACHE),
flog(0, D_CSTORAGE_LOG_CACHE),
fdata(0,0, D_CSTORAGE_DATA_INIT_SIZE, D_CSTORAGE_DATA_DELTA_SIZE /*, 16*/),
fstate(0,0)
{
cursor = -1;
rdwr = false;
dirtySerials = NULL;
dirtySerialSize = 0;
dirtySerialIndex = 0;
mode = CSTORAGE_MODE_STANDARD;
memset(&state, 0, sizeof(state));
files.push_back(&fdata);
files.push_back(&findex);
files.push_back(&flog);
files.push_back(&fstate);
}
/*
* Destructor, that close all files.
*/
CSafeStorage::~CSafeStorage ()
{
close();
if (dirtySerials) free(dirtySerials);
}
/*
* Method that close all file, using list file, close each file.
*/
int32_t CSafeStorage::close ( uint32_t flags )
{
CBaseSafeFileList::iterator it = files.begin();
saveState(true);
while (it != files.end())
{
(*it)->close();
++it;
}
clearDirtySerials();
if (rdwr) sync(true);
fauto_commit = false;
return E_CSTORAGE_OK;
}
/*
* Open a new environment, a list of files in one directory.
*
* @param filename prefix, filename without extension
* @param flags flags that applies to this operation. Current, no flags defined for this operation.
*
* @return 0 if no errors, error code if error occurs.
*/
int32_t CSafeStorage::open ( const string &filename, uint32_t flags, uint32_t hash_key )
{
string _filename;
fauto_commit = false;
try
{
flags |= F_CSFILE_EXCEPTIONS;
int32_t index = 0;
// Check if all file exists
string basename = normalizeFilename(filename);
rdwr = (flags & F_CSTORAGE_WR);
int32_t count = checkFilesPresent(basename, (flags & F_CSTORAGE_WR) ? (R_OK|W_OK):R_OK);
if (count > 0) {
if (count == (int32_t)files.size() && (flags & F_CSTORAGE_CREATE)) return create(basename, flags, hash_key);
return E_CSTORAGE_OPEN_FILE_NO_ACCESS;
}
CBaseSafeFileList::iterator it = files.begin();
// for each file open file
while (it != files.end())
{
_filename = basename + __safe_storage_extensions[index++];
(*it)->open(_filename, flags);
++it;
}
loadState();
// check if hash of all files it's the same.
int32_t result = checkHashKey();
if (result != E_CSTORAGE_OK)
CEXP_CODE(result);
if (flags & F_CSTORAGE_AUTO_COMMIT) {
C_LOG_INFO("Setting autocommit on (flgs:%08X)", flags);
fauto_commit = true;
}
}
catch (const CException &e)
{
// if error found, all files must be closed
C_LOG_ERR("e.getResult()=%d", e.getResult());
close();
return e.getResult();
}
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::setFlags ( uint32_t flags )
{
string _filename;
CBaseSafeFileList::iterator it = files.begin();
for (int _loop = 0; _loop < 2; ++_loop) {
while (it != files.end())
{
_filename = (*it)->getFilename();
// _filename += __safe_storage_extensions[index++];
int result = (*it)->setFlags(flags | (_loop == 0 ? F_CSFILE_CHECK_FLAGS : 0));
if (_loop == 0 && result < 0) {
return E_CSTORAGE_ERROR;
}
++it;
}
}
return 0;
}
string CSafeStorage::normalizeFilename ( const string &filename )
{
int extlen = strlen(__safe_storage_extensions[0]);
if (filename.compare(filename.size() - extlen, extlen, __safe_storage_extensions[0]) == 0) {
return filename.substr(0, filename.size() - extlen);
}
return filename;
}
/*
* Method to create all files
*
* @param filename prefix, filename without extension
* @param flags flags that applies to this operation. Current, no flags defined for this operation.
*
* @return 0 if no errors, error code if error occurs.
*/
int32_t CSafeStorage::create ( const string &filename, uint32_t flags, uint32_t hash_key )
{
C_LOG_DEBUG("create(%s, %04X)", filename.c_str(), flags);
fauto_commit = false;
string basename = normalizeFilename(filename);
if (mode != CSTORAGE_MODE_REBUILD) {
// Check if any file is created
if (checkAnyFilePresent(basename)) {
C_LOG_ERR("FileExists");
return E_CSTORAGE_CREATE_FILE_EXISTS;
}
}
string _filename;
try
{
CBaseSafeFileList::iterator it = files.begin();
int32_t index = 0;
uint32_t nflags = flags | (F_CSFILE_EXCEPTIONS|F_CSFILE_CREATE|F_CSFILE_WR|F_CSFILE_TRUNCATE);
// list of files is created on constructor, array _safe_storage_extensions
// contains extension for each type of file
while (it != files.end())
{
_filename = basename + __safe_storage_extensions[index++];
(*it)->open(_filename, ((*it) == &fdata && (mode == CSTORAGE_MODE_REBUILD)) ? flags : nflags);
++it;
}
// to link all files and avoid that one of them was replaced, renamed, etc.. generate
// a hash key and this key is stored in all files.
if (mode == CSTORAGE_MODE_REBUILD) {
getHashKey(hash_key);
}
else if ((flags & F_CSTORAGE_SET_HASH_KEY) == 0) {
hash_key = generateHashKey();
}
writeHashKey(hash_key, flags);
if (flags & F_CSTORAGE_AUTO_COMMIT) {
C_LOG_INFO("Setting autocommit on (flgs:%08X)", flags);
fauto_commit = true;
}
}
catch (CException &e)
{
// if error found, all files must be closed
C_LOG_ERR("CException %d on %s:%d", e.getResult(), e.getFile(), e.getLine());
close();
return e.getResult();
}
return 0;
}
int32_t CSafeStorage::rebuild ( const string &filename, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageDataReg, r_data)
// donde tenemos guardaa
C_LOG_DEBUG("rebuild(%s, %04X)", filename.c_str(), flags);
mode = CSTORAGE_MODE_REBUILD;
int32_t result = CSafeStorage::create(filename, flags);
if (result != E_CSTORAGE_OK) {
return result;
}
DECLARE_STRUCT(CSafeStorageState, _state)
DECLARE_STRUCT(CSafeStorageHashReg, h)
uint8_t *data = (uint8_t *)malloc(1024*1024);
result = fdata.read(0, h.data);
if (result < 0)
{
C_LOG_ERR("Internal error %d reading data 0", result);
return E_CSTORAGE_DATA_READ;
}
// TODO: Rebuild, gestion del rebuild
while ((result = fdata.read(C_CSFILE_CURRPOS, r_data, data, 1024*1024)) > 0)
{
printf("%08X %8d %8d %6d %02X\n", r_data.signature, r_data.serial, r_data.sequence, r_data.len, r_data.flags);
writeFiles(r_data, data, r_data.len);
}
printf("end rebuild (%d)\n", result);
mode = CSTORAGE_MODE_STANDARD;
saveState(false);
sync(true);
return result;
}
/*
* Check if any file is accessible
*
* @param filename prefix of files, name without extension
* @param mode mode for access check.
*
* @return number of files accessible. If returns 0 means files no exists.
*/
int32_t CSafeStorage::checkFilesPresent ( const string &filename, int32_t mode )
{
string _filename;
int32_t index = 0;
int32_t result = 0;
// for each file
while (index < (int32_t)files.size())
{
// generate filename of each file
_filename = filename + __safe_storage_extensions[index++];
// if file is accessible increment counter result.
if (access(_filename.c_str(), mode)!= 0)
{
C_LOG_DEBUG("checking file %s (not found)", _filename.c_str());
++result;
}
else {
C_LOG_DEBUG("checking file %s (found)", _filename.c_str());
}
}
C_LOG_DEBUG("result=%d", result);
return result;
}
int32_t CSafeStorage::checkAnyFilePresent ( const string &filename )
{
return (files.size() - checkFilesPresent(filename, R_OK));
}
/*
* Sync of all files
*/
void CSafeStorage::sync ( bool full )
{
if (mode == CSTORAGE_MODE_REBUILD) return;
fdata.sync();
if (!full) return;
findex.sync();
flog.sync();
fstate.sync();
}
/*
* Method to make a commit of all made from last commit or rollback. This method
* add commit as data (to recover), as commit as log, and updated status
*
* @return 0 means Ok, otherwise means error.
*/
int32_t CSafeStorage::commit ( void )
{
DECLARE_STRUCT(CSafeStorageDataReg,r_data)
if (fauto_commit)
{
C_LOG_DEBUG("Ignore commit because we are in auto-commit mode");
return E_CSTORAGE_OK;
}
C_LOG_DEBUG("CSafeStorage::commit()");
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_COMMIT;
r_data.sequence = state.last_sequence + 1;
int32_t result = writeFiles(r_data);
// TO-DO: open transactions, make a rollback?
clearDirtySerials();
sync();
return result;
}
void CSafeStorage::clearDirtySerials ( void )
{
dirtySerialIndex = 0;
}
void CSafeStorage::addDirtySerial ( tserial_t serial )
{
if (dirtySerialIndex >= dirtySerialSize) {
dirtySerialSize += C_DIRTY_SERIAL_SIZE;
if (!dirtySerials) dirtySerials = (tserial_t *)malloc(dirtySerialSize * sizeof(tserial_t));
else dirtySerials = (tserial_t *)realloc(dirtySerials, dirtySerialSize * sizeof(tserial_t));
}
dirtySerials[dirtySerialIndex++] = serial;
}
/*
* Method to make a rollback of all write made from last commit or rollback. This method make following steps:
* 1) add rollback (begin) as data
* 2) add rollback (begin) as log
* 3) save state and synchronize all data, log, and state
* 4) update all index of rollback, setting offset -1.
* 5) synchronize index
* 6) add rollback (end) as data linked to last index updated
* 7) add rollback (end) as log linked to last index updated
* 8) save state and synchronize all data, log, and state
*
* @return 0 means Ok, otherwise means error.
*/
int32_t CSafeStorage::rollback ( void )
{
C_LOG_INFO("rollback");
DECLARE_STRUCT(CSafeStorageDataReg,r_data)
int32_t result = E_CSTORAGE_OK;
if (fauto_commit)
{
C_LOG_DEBUG("Rollback disabled in auto-commit mode");
return E_CSTORAGE_NO_ROLLBACK_IN_AUTOCOMMIT;
}
C_LOG_DEBUG("CSafeStorage::rollback()");
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_ROLLBACK_BEGIN;
r_data.sequence = state.last_sequence + 1;
int32_t dlen = (dirtySerialIndex+1) * sizeof(tserial_t);
tserial_t *serials = (tserial_t *)malloc(dlen);
serials[0] = dirtySerialIndex;
for (uint32_t index = 0; index < dirtySerialIndex; ++index ) serials[index+1] = dirtySerials[index];
result = writeFiles(r_data, serials, dlen);
free(serials);
// asociated to rollback_end stored last index modified, todo a check integrity
// beetween index and data.
memset(&r_data, 0, sizeof(r_data));
r_data.sequence = state.last_sequence + 1;
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_ROLLBACK_END;
result = writeFiles(r_data);
clearDirtySerials();
return result;
}
/*
* Method used to verify content of data, recalculate all information and check it with index
* state, and log files
*
* @return 0 means verify was ok, error in otherwise.
*/
int32_t CSafeStorage::verify ( uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageDataReg, r_data)
DECLARE_STRUCT(CSafeStorageState, _state)
int32_t result = fdata.read(0, r_data);
if (result > 0)
{
C_LOG_ERR("Internal error %d reading data 0", result);
return E_CSTORAGE_DATA_READ;
}
while ((result = fdata.read(C_CSFILE_CURRPOS, r_data)) > 0)
{
uint32_t type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
switch(type)
{
// _state.last_offset_index;
// _state.last_offsets;
case T_CSTORAGE_COMMIT:
{
_state.last_close_sequence = r_data.sequence;
_state.last_close_offset = fdata.lastOffset();
_state.last_commit_sequence = r_data.sequence;
++_state.commit_count;
break;
}
case T_CSTORAGE_WRITE:
{
++_state.data_count;
break;
}
case T_CSTORAGE_ROLLBACK_BEGIN:
{
++_state.rollback_begin_count;
break;
}
case T_CSTORAGE_ROLLBACK_END:
{
_state.last_close_sequence = r_data.sequence;
_state.last_close_offset = fdata.lastOffset();
++_state.rollback_end_count;
break;
}
case T_CSTORAGE_STATUS:
{
break;
}
default:
{
C_LOG_ERR("Internal error: Non expected data type (0x%08X) was found", type);
return E_CSTORAGE_DATA_READ;
}
}
_state.last_sequence = r_data.sequence;
++_state.count;
}
CMP_STRUCT_FIELD(state,_state,count,result);
CMP_STRUCT_FIELD(state,_state,data_count,result);
CMP_STRUCT_FIELD(state,_state,commit_count,result);
CMP_STRUCT_FIELD(state,_state,rollback_begin_count,result);
CMP_STRUCT_FIELD(state,_state,rollback_end_count,result);
CMP_STRUCT_FIELD(state,_state,last_offset_index,result);
CMP_STRUCT_FIELD(state,_state,last_commit_sequence,result);
CMP_STRUCT_FIELD(state,_state,last_rollback_sequence,result);
CMP_STRUCT_FIELD(state,_state,last_close_sequence,result);
CMP_STRUCT_FIELD(state,_state,last_sequence,result);
CMP_STRUCT_ARRAY_FIELD(state,_state,last_offsets,result);
return result;
}
int32_t CSafeStorage::recoverDirtySerials ( void )
{
DECLARE_STRUCT(CSafeStorageDataReg ,r_data)
uint64_t offset = state.last_close_offset;
clearDirtySerials();
int32_t result = fdata.read(offset, r_data);
if (result > 0)
{
C_LOG_ERR("Internal error %d reading data on offset %lld", result, offset);
return E_CSTORAGE_DATA_READ;
}
uint32_t type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
if (type != T_CSTORAGE_COMMIT && type != T_CSTORAGE_ROLLBACK_BEGIN && type != T_CSTORAGE_ROLLBACK_END)
{
C_LOG_ERR("Internal error: On offset %llld non expected data type (0x%08X) was found", offset, type);
return E_CSTORAGE_DATA_READ;
}
while ((result = fdata.read(C_CSFILE_CURRPOS, r_data)) > 0)
{
type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
if (type != T_CSTORAGE_WRITE)
{
C_LOG_ERR("Internal error: Non expected data type (0x%08X) was found", offset, type);
return E_CSTORAGE_DATA_READ;
}
if ((r_data.flags & F_CSTORAGE_DF_AUTO_COMMIT) == 0)
addDirtySerial(r_data.serial);
}
return result;
}
int32_t CSafeStorage::read ( tserial_t &serial, void *data, uint32_t dlen, uint32_t flags )
{
C_LOG_DEBUG("read(%ld, %p, %d, %08X)", serial, data, dlen, flags);
DECLARE_STRUCT(CSafeStorageIndexReg ,r_index)
DECLARE_STRUCT(CSafeStorageDataReg ,r_data)
cursor = serial;
if (!rdwr) loadState();
int32_t result = findex.readIndex(serial, r_index);
if (result == E_CSFILE_EMPTY_DATA)
return E_CSTORAGE_SERIAL_NOT_FOUND;
if (result < 0)
return result;
/* verify if offset error, or offset not initialized (=0) or deleted (=-1) */
last_offset = getLastOffset(r_index, serial, flags);
if (last_offset <= 0)
return E_CSTORAGE_SERIAL_NOT_FOUND;
C_LOG_DEBUG("try to read %d bytes on offset %lld", dlen, last_offset);
result = fdata.read(last_offset, r_data, data, dlen);
if (result < 0)
return result;
if (C_LOG_DEBUG_ENABLED) {
if (result > 1024) { C_LOG_DEBUG("data(%p): %s...%s", data, c_log_data2hex(data, 0, 256), c_log_data2hex(data, result - 256, 256)); }
else { C_LOG_DEBUG("data(%p): %s", data, c_log_data2hex(data, 0, result)); };
}
result = result - sizeof(r_data);
C_LOG_DEBUG("state.last_commit_sequence:%d r_data.sequence:%d autocommit:%s", state.last_commit_sequence, r_data.sequence,
(r_data.flags & F_CSTORAGE_DF_AUTO_COMMIT)? "true":"false");
if (C_LOG_DEBUG_ENABLED) {
if (result > 1024) { C_LOG_DEBUG("data(%p): %s...%s", data, c_log_data2hex(data, 0, 256), c_log_data2hex(data, result - 256, 256)); }
else { C_LOG_DEBUG("data(%p): %s", data, c_log_data2hex(data, 0, result)); };
}
return result;
}
int32_t CSafeStorage::readLog ( tseq_t seq, void *data, uint32_t dlen, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageLogReg ,r_log)
if (!rdwr) loadState();
int32_t result = flog.readIndex(seq, r_log);
if (result < 0) return result;
if (result == E_CSFILE_EMPTY_DATA)
return E_CSTORAGE_SEQUENCE_NOT_FOUND;
if (result < 0)
return result;
int64_t offset = r_log.offset;
if (offset < 0)
return E_CSTORAGE_SEQUENCE_NOT_FOUND;
if (dlen < sizeof(CSafeStorageDataReg))
return E_CSTORAGE_NOT_ENOUGH_DATA;
uint8_t *d_data = ((uint8_t *)data) + sizeof(CSafeStorageDataReg);
result = fdata.read(offset, *((CSafeStorageDataReg *)data), d_data, dlen - sizeof(CSafeStorageDataReg));
if (result < 0)
return result;
return result;
}
/*
* Method to access to log
*
* @param seq sequence of log to read
* @param serial out parameter, if it isn't null was stored serial number of this sequence
* @param type out parameter, if it isn't null was stored type of action of this sequence
* (write, commit, rollback-begin, rollback-end)
*
* @return 0 Ok, error in otherwise.
*/
int32_t CSafeStorage::readLogReg ( tseq_t seq, tserial_t &serial, uint8_t &type, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageLogReg ,r_log)
int32_t result = flog.readIndex(seq, r_log);
if (result < 0) return result;
serial = r_log.serial;
type = r_log.type;
return 0;
}
/*
* Write a hash (mark) in all files, to link them, to avoid that
* one of files was replaced with another.
*/
int32_t CSafeStorage::writeHashKey ( uint32_t hash_key, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageHashReg, h)
C_LOG_TRACE("writeHashKey %08X", hash_key);
// store hash in structure
h.hash_key = hash_key;
// write hash in files
if (mode != CSTORAGE_MODE_REBUILD) {
fdata.write(0, h.data);
}
flog.write(0, h.log);
findex.write(0, h.index);
// set hash in state structure, and save it.
state.hash_key = hash_key;
saveState(false);
sync();
return 0;
}
/*
* Check that all files are liked, when files was created an random hash of 4 bytes was generated
* and copy in all files. With this feature it's possible detect when files was replace by other
* incorrect or old file. Data hash is considered how master hash. This information about hash is
* stored in first record.
*
* @return if checks is passed return 0, if not return value that was an OR of all hash that fails.
*/
int32_t CSafeStorage::checkHashKey ( void )
{
DECLARE_STRUCT(CSafeStorageHashReg, h)
uint32_t hash_key;
int32_t result = E_CSTORAGE_OK;
fdata.read(0, h.data);
hash_key = h.hash_key;
C_LOG_DEBUG("CheckHashKey %08X", hash_key);
flog.read(0, h.log);
if (h.hash_key != hash_key) {
C_LOG_ERR("CheckHashKey Log [FAILS] (Data: %08X / Log: %08X)", hash_key, h.hash_key);
result |= E_CSTORAGE_FAIL_HK_LOG;
}
findex.read(0, h.index);
if (h.hash_key != hash_key) {
C_LOG_ERR("CheckHashKey Index [FAILS] (Data: %08X / Index: %08X)", hash_key, h.hash_key);
result |= E_CSTORAGE_FAIL_HK_INDEX;
}
if (!rdwr) loadState();
if (state.hash_key != hash_key) {
C_LOG_ERR("CheckHashKey State [FAILS] (Data: %08X / State: %08X)", hash_key, state.hash_key);
result |= E_CSTORAGE_FAIL_HK_STATE;
}
C_LOG_DEBUG("CheckHashKey [%s] result = %08X", result == E_CSTORAGE_OK ? "OK":"FAILS", result);
return result;
}
int32_t CSafeStorage::write ( tserial_t serial, const void *data, uint32_t dlen, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageDataReg ,r_data)
C_LOG_DEBUG("CSafeStorage::write(%d, %p, %d) lseq:%d", serial, data, dlen, state.last_sequence);
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_WRITE;
r_data.serial = serial;
r_data.sequence = state.last_sequence + 1;
r_data.len = dlen;
if (fauto_commit)
r_data.flags |= F_CSTORAGE_DF_AUTO_COMMIT;
return writeFiles(r_data, data, dlen);
}
int32_t CSafeStorage::applyLog ( const void *data, uint32_t dlen, uint32_t flags )
{
if (dlen < sizeof(CSafeStorageDataReg))
return E_CSTORAGE_NOT_ENOUGH_DATA;
uint8_t *d_data = ((uint8_t *)data) + sizeof(CSafeStorageDataReg);
return writeFiles(*((CSafeStorageDataReg *)data), d_data, dlen - sizeof(CSafeStorageDataReg));
}
int32_t CSafeStorage::writeFiles ( CSafeStorageDataReg &r_data, const void *data, uint32_t dlen )
{
DECLARE_STRUCT(CSafeStorageIndexReg ,r_index)
DECLARE_STRUCT(CSafeStorageLogReg ,r_log)
int32_t result = E_CSTORAGE_OK;
int32_t type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
++state.count;
state.last_sequence = r_data.sequence;
r_log.serial = r_data.serial;
r_log.type = type;
C_LOG_DEBUG("type:%08X dlen:%d", type, dlen);
switch (type)
{
case T_CSTORAGE_WRITE:
{
// prepare log register related to write
r_log.offset = writeData(r_data, data, dlen);
++state.data_count;
// prepare index related to write
setOldestOffset(r_index, r_data.serial, r_log.offset, r_data.sequence, r_data.flags, findex.readIndex(r_data.serial, r_index) < 0);
// if error in data write, abort this write and returns error
if (r_log.offset < 0LL) {
return -1;
}
if (!fauto_commit)
addDirtySerial(r_data.serial);
// save state with information
saveState();
flog.writeIndex(r_data.sequence, r_log);
findex.writeIndex(r_data.serial, r_index);
result = dlen;
break;
}
case T_CSTORAGE_ROLLBACK_BEGIN:
{
writeData(r_data, data, dlen);
writeSyncStateLogSync(r_log);
// mark offset of all indexes as -1
tserial_t *serials = (tserial_t *) data;
int32_t count = serials[0];
// must: dlen / sizeof(tserial_t) == serials[0]+1
int32_t index = 1;
while (index <= count)
{
findex.readIndex(serials[index], r_index);
setNewestOffset(r_index, serials[index], -1, 0, 0);
int32_t result = findex.writeIndex(serials[index], r_index);
if (result < 0)
C_LOG_ERR("CSafeStorage::rollBack Error saving index %d of rollback", serials[index]);
++index;
}
if (count > 0 && mode != CSTORAGE_MODE_REBUILD)
{
findex.sync();
}
break;
}
case T_CSTORAGE_ROLLBACK_END:
{
writeData(r_data);
writeSyncStateLogSync(r_log);
break;
}
case T_CSTORAGE_COMMIT:
{
r_log.offset = writeData(r_data);
++state.commit_count;
state.last_commit_sequence = r_data.sequence;
writeSyncStateLogSync(r_log);
break;
}
}
// check if store a status snapshot
if (state.count % C_STORAGE_STATUS_FREQ == (C_STORAGE_STATUS_FREQ - 1)) {
DECLARE_STRUCT(CSafeStorageDataReg,r_state_data)
r_state_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_STATUS;
r_state_data.sequence = state.last_sequence + 1;
memset(&r_log, 0, sizeof(r_log));
++state.count;
state.last_sequence = r_state_data.sequence;
r_log.serial = r_state_data.serial;
r_log.type = T_CSTORAGE_STATUS;
r_log.offset = writeData(r_state_data);
flog.writeIndex(state.last_sequence, r_log);
saveState();
}
return result;
}
void CSafeStorage::writeSyncStateLogSync ( CSafeStorageLogReg &r_log )
{
flog.writeIndex(state.last_sequence, r_log);
/*
if (mode != CSTORAGE_MODE_REBUILD) fdata.sync();
saveState();
if (mode != CSTORAGE_MODE_REBUILD) flog.sync();*/
}
void CSafeStorage::saveState ( bool sync )
{
if (mode == CSTORAGE_MODE_REBUILD || !rdwr) return;
fstate.write(0, state);
/* if (sync)
fstate.sync();*/
}
void CSafeStorage::loadState ( void)
{
fstate.read(0, state);
}
uint32_t CSafeStorage::generateHashKey ( void )
{
int32_t fd;
uint32_t result = 0;
fd = ::open("/dev/random", O_RDONLY);
if (fd >= 0)
{
if (::read(fd, &result, sizeof(result)) != sizeof(result))
fd = -1;
::close(fd);
}
if (fd < 0) {
srand ( time(NULL) );
result = rand();
}
return result;
}
int32_t CSafeStorage::getInfo ( CSafeStorageInfo &info )
{
info.hash_key = state.hash_key;
info.last_updated = state.last_updated;
info.version = 0;
info.count = state.count;
info.commit_count = state.commit_count;
info.rollback_begin_count = state.rollback_begin_count;
info.rollback_end_count = state.rollback_end_count;
info.last_commit_sequence = state.last_commit_sequence;
info.last_rollback_sequence = state.last_rollback_sequence;
info.last_sequence = state.last_sequence;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::getHashKey ( uint32_t &hash_key )
{
DECLARE_STRUCT(CSafeStorageHashReg, h)
int32_t result = fdata.read(0, h.data);
if (result == sizeof(h.data)) {
result = E_CSTORAGE_OK;
hash_key = h.hash_key;
}
return result;
}
void CSafeStorage::dumpState ( void )
{
int32_t index;
printf("[state]\n");
printf("hash_key: %08X\n", state.hash_key);
printf("last_updated: %d\n", state.last_updated);
printf("count: %d\n", state.count);
printf("commit_count: %d\n", state.commit_count);
printf("rollback_begin_count: %d\n", state.rollback_begin_count);
printf("rollback_end_count: %d\n", state.rollback_end_count);
printf("last_offset_index: %d\n", state.last_offset_index);
printf("last_commit_sequence: %u\n", state.last_commit_sequence);
printf("last_rollback_sequence: %u\n", state.last_rollback_sequence);
printf("last_close_sequence: %d\n", state.last_close_sequence);
printf("last_sequence: %d\n", state.last_sequence);
printf("last_close_offset: %lld\n", state.last_close_offset);
printf("last_offsets[%d]:", sizeof(state.last_offsets)/sizeof(state.last_offsets[0]));
for (index = 0; index < (int32_t)(sizeof(state.last_offsets)/sizeof(state.last_offsets[0])); ++index) {
printf("%s%lld", index?",":"", state.last_offsets[index]);
}
printf("\n");
}
int64_t CSafeStorage::writeData ( CSafeStorageDataReg &r_data, const void *data, uint32_t dlen )
{
if (mode != CSTORAGE_MODE_REBUILD) {
int64_t result = fdata.write(r_data, data, dlen);
if (result < 0) {
C_LOG_ERR("Error writting data (%p,%p,%d) result %d", &r_data, data, dlen, (int32_t)result);
return result;
}
}
state.last_offset_index = (state.last_offset_index + 1) % (sizeof(state.last_offsets)/sizeof(state.last_offsets[0]));
state.last_offsets[state.last_offset_index] = fdata.lastOffset();
return state.last_offsets[state.last_offset_index];
}
int32_t CSafeStorage::removeFiles ( const string &filename )
{
string _filename;
int32_t index = 0;
int32_t result = 0;
int32_t count = sizeof(__safe_storage_extensions)/sizeof(char *);
// for each file
while (index < count)
{
// generate filename of each file
_filename = filename + __safe_storage_extensions[index++];
C_LOG_DEBUG("deleting file %s", _filename.c_str());
if (unlink(_filename.c_str()))
--result;
}
return result;
}
void CSafeStorage::setOldestOffset ( CSafeStorageIndexReg &index, tserial_t serial, int64_t offset, tseq_t sequence, uint32_t flags, bool init )
{
C_LOG_TRACE("In #:%ld off:%lld seq:%d flgs:%08X init:%d 0:[%d,%lld] 1:[%d,%lld]", serial, offset, sequence, flags, init?1:0, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
if (init) {
memset(&index, 0, sizeof(index));
index.offsets[0] = offset;
index.sequences[0] = sequence;
index.flags[0] = flags;
index.offsets[1] = -1;
index.sequences[1] = 0;
index.flags[1] = 0;
}
else {
int32_t pos = (index.sequences[1] > index.sequences[0] ? 0 : 1);
index.offsets[pos] = offset;
index.sequences[pos] = sequence;
index.flags[pos] = flags;
}
C_LOG_TRACE("Out #:%ld 0:[%d,%lld] 1:[%d,%lld]", serial, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
}
void CSafeStorage::setNewestOffset ( CSafeStorageIndexReg &index, tserial_t serial, int64_t offset, tseq_t sequence, uint32_t flags )
{
C_LOG_TRACE("In #:%ld off:%lld seq:%d flgs:%08X 0:[%d,%lld] 1:[%d,%lld]", serial, offset, sequence, flags, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
int32_t pos = (index.sequences[1] > index.sequences[0] ? 1 : 0);
index.offsets[pos] = offset;
index.sequences[pos] = offset;
index.flags[pos] = flags;
C_LOG_TRACE("Out #:%ld 0:[%d,%lld] 1:[%d,%lld]", serial, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
}
int64_t CSafeStorage::getLastOffset ( CSafeStorageIndexReg &index, tserial_t serial, uint32_t flags )
{
int64_t result = -1;
tseq_t lastseq = 0;
uint32_t dirtyRead = (flags & F_CSTORAGE_READ_MODE_MASK) || rdwr;
for ( int32_t i = 0; i < 2; ++i ) {
// check if current position is autocommited if not, check that index is commited, current sequence is lower or equal
// last transaccion commited, if not, check if read in dirty read. Compare with lastseq to avoid read a old register.
if (index.sequences[i] >= lastseq && ((index.flags[i] & F_CSTORAGE_DF_AUTO_COMMIT) ||
index.sequences[i] <= state.last_commit_sequence || dirtyRead)) {
result = index.offsets[i];
lastseq = index.sequences[i];
}
}
C_LOG_INFO("0:[%02X, %d,%lld] 1:[%02X, %d,%lld] S:%u FLGS:%08X R:%lld LCS:%u RDWR:%d",
index.flags[0], index.sequences[0], index.offsets[0], index.flags[1], index.sequences[1], index.offsets[1],
serial, flags, result, state.last_commit_sequence, rdwr);
return result;
}
int64_t CSafeStorage::getLastOffset ( void )
{
return last_offset;
}
int32_t CSafeStorage::goTop ( uint32_t flags )
{
cursor = -1;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::goPos ( tserial_t serial, uint32_t flags )
{
cursor = serial < 0 ? -1 : serial-1;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::getParam ( const string &name )
{
if (name == "index_cache_size") return findex.getCacheSize();
else if (name == "log_cache_size") return flog.getCacheSize();
return -1;
}
int32_t CSafeStorage::setParam ( const string &name, int32_t value )
{
if (name == "index_cache_size") findex.setCacheSize(value);
else if (name == "log_cache_size") flog.setCacheSize(value);
else if (name == "c_log_level") c_log_set_level(value);
else return -1;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::createListener ( const string ¶ms, ISafeStorageListener **ltn )
{
// syslog(LOG_ERR | LOG_USER, "createListener(%s)", params.c_str());
CSafeStorageListener *listener = new CSafeStorageListener(params);
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::createReplica ( const string ¶ms, ISafeStorageReplica **rpl )
{
// syslog(LOG_ERR | LOG_USER, "createReplica(%s)", params.c_str());
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::setCallback ( tsafestorage_callback_t cb )
{
// syslog(LOG_ERR | LOG_USER, "setCallback");
cb(E_CB_REPLICA_FAIL, NULL);
return E_CSTORAGE_OK;
}
void CSafeStorage::findLastSignatureReg ( int32_t max_size )
{
fdata.findLastSignatureReg(max_size, CSTORAGE_SIGNATURE, CSTORAGE_SIGNATURE_SIGN_MASK, sizeof(uint32_t));
}
int32_t ISafeStorage::getLogReg ( const void *data, uint32_t dlen, CSafeStorageLogInfo &linfo )
{
if (sizeof(CSafeStorageDataReg) > dlen) {
return E_CSTORAGE_NOT_VALID_DATA;
}
const CSafeStorageDataReg *dreg = (const CSafeStorageDataReg *)data;
if ((dreg->signature & CSTORAGE_SIGNATURE_SIGN_MASK) != CSTORAGE_SIGNATURE) {
return E_CSTORAGE_NOT_VALID_DATA;
}
memset(&linfo, 0, sizeof(linfo));
linfo.sequence = dreg->sequence;
linfo.serial = dreg->serial;
linfo.type = (dreg->signature & CSTORAGE_SIGNATURE_TYPE_MASK);
linfo.len = dreg->len;
linfo.flags = dreg->flags;
return E_CSTORAGE_OK;
}
| 29.491213 | 201 | 0.678615 |
efc3a216bf2f72dbbbc86f4644ef0f02ab9552b3 | 2,540 | cpp | C++ | src/components/UIElement.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 399 | 2019-01-06T17:55:18.000Z | 2022-03-21T17:41:18.000Z | src/components/UIElement.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 101 | 2019-04-18T21:03:53.000Z | 2022-01-08T13:27:01.000Z | src/components/UIElement.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 56 | 2019-04-10T10:18:27.000Z | 2022-02-08T01:23:31.000Z | #include "UIElement.hpp"
#include <GUI/BsCGUIWidget.h>
#include <GUI/BsGUIPanel.h>
#include <Image/BsSpriteTexture.h>
#include <RTTI/RTTI_UIElement.hpp>
#include <exception/Throw.hpp>
#include <gui/skin_gothic.hpp>
#include <log/logging.hpp>
#include <original-content/OriginalGameResources.hpp>
namespace REGoth
{
UIElement::UIElement(const bs::HSceneObject& parent, bs::HCamera camera)
: bs::Component(parent)
{
setName("UIElement");
auto guiWidget = SO()->addComponent<bs::CGUIWidget>(camera);
guiWidget->setSkin(REGoth::GUI::getGothicStyleSkin());
mGuiLayout = guiWidget->getPanel();
}
UIElement::UIElement(const bs::HSceneObject& parent, HUIElement parentUiElement,
bs::GUILayout* layout)
: bs::Component(parent)
, mParentUiElement(parentUiElement)
, mGuiLayout(layout)
{
setName("UIElement");
if (parentUiElement->SO() != parent->getParent())
{
REGOTH_THROW(InvalidParametersException, "Parent UIElement must be attached to parent SO");
}
parentLayout().addElement(mGuiLayout);
}
UIElement::~UIElement()
{
}
void UIElement::show()
{
layout().setVisible(true);
}
void UIElement::hide()
{
layout().setVisible(false);
}
bs::HSceneObject UIElement::addChildSceneObject(const bs::String& name)
{
auto so = bs::SceneObject::create(name);
so->setParent(SO());
return so;
}
bs::GUILayout& UIElement::layout() const
{
if (!mGuiLayout)
{
REGOTH_THROW(InvalidStateException, "No Layout available?");
}
return *mGuiLayout;
}
bs::GUILayout& UIElement::parentLayout() const
{
if (!mParentUiElement)
{
REGOTH_THROW(InvalidStateException, "No parent available?");
}
return mParentUiElement->layout();
}
bs::Camera& UIElement::camera() const
{
if (!layout()._getParentWidget())
{
REGOTH_THROW(InvalidStateException, "No parent widget available?");
}
auto camera = layout()._getParentWidget()->getCamera();
if (!camera)
{
REGOTH_THROW(InvalidStateException, "No camera available?");
}
return *camera;
}
bs::HSpriteTexture UIElement::loadSprite(const bs::String& texture)
{
bs::HTexture t = gOriginalGameResources().texture(texture);
if (!t)
{
REGOTH_LOG(Warning, Uncategorized, "[UIElement] Failed to load texture: {0}", texture);
return {};
}
return bs::SpriteTexture::create(t);
}
REGOTH_DEFINE_RTTI(UIElement)
} // namespace REGoth
| 21.896552 | 97 | 0.658268 |
efc5a1c2c7fcaafaa0c019bac69c79e662831cad | 354 | cc | C++ | poj/1/1401.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/1/1401.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/1/1401.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(void)
{
int T;
cin >> T;
while (T-- > 0) {
int N;
cin >> N;
int n2 = 0;
for (int base = 2; base <= N; base *= 2) {
n2 += N/base;
}
int n5 = 0;
for (int base = 5; base <= N; base *= 5) {
n5 += N/base;
}
cout << min(n2, n5) << endl;
}
return 0;
}
| 15.391304 | 46 | 0.440678 |
efc6f35430fffde57adff0d36b3155817d6d4ba5 | 379 | hpp | C++ | src/lib/common/Utility.hpp | genome/diagnose_dups | 17f63ed3d07c63f9b55dc7431f6528707d30709f | [
"MIT"
] | 8 | 2015-05-13T12:40:44.000Z | 2018-03-09T15:10:21.000Z | src/lib/common/Utility.hpp | genome/diagnose_dups | 17f63ed3d07c63f9b55dc7431f6528707d30709f | [
"MIT"
] | 5 | 2015-03-22T00:58:44.000Z | 2017-12-08T18:21:49.000Z | src/lib/common/Utility.hpp | genome/diagnose_dups | 17f63ed3d07c63f9b55dc7431f6528707d30709f | [
"MIT"
] | 4 | 2015-08-04T01:11:54.000Z | 2017-04-11T10:27:42.000Z | #pragma once
#include <sam.h>
#include <stdint.h>
#include <vector>
namespace cigar {
std::vector<uint32_t> parse_string_to_cigar_vector(char const* cigar_string);
int32_t calculate_right_offset(bam1_t const* record);
int32_t calculate_right_offset(char const* cigar);
int32_t calculate_left_offset(bam1_t const* record);
int32_t calculate_left_offset(char const* cigar);
}
| 22.294118 | 77 | 0.802111 |
efcb3c623f09b27de5e5af4d73f99e82b6b7561c | 2,181 | cpp | C++ | src/kernel/io/KPrintf.cpp | jameskingstonclarke/arctic | 6fec04809d6175689477abfe21416f33e63cb177 | [
"MIT"
] | 1 | 2021-02-01T19:28:02.000Z | 2021-02-01T19:28:02.000Z | src/kernel/io/KPrintf.cpp | jameskingstonclarke/arctic | 6fec04809d6175689477abfe21416f33e63cb177 | [
"MIT"
] | 9 | 2021-02-07T15:46:11.000Z | 2021-02-18T08:25:42.000Z | src/kernel/io/KPrintf.cpp | jameskingstonclarke/arctic | 6fec04809d6175689477abfe21416f33e63cb177 | [
"MIT"
] | null | null | null | #include "KPrintf.h"
#include "../utils/Math.h"
#include "../Types.h"
#include "../driver/VGAGraphics.h"
#include "Serial.h"
namespace IO{
void kinfo(const char * info){
Driver::VGAGraphics::vga_driver.colour(Driver::VGAGraphics::vga_green);
kprintf("[INFO] ");
kprintf(info);
}
void kwarn(const char * warn){
Driver::VGAGraphics::vga_driver.colour(Driver::VGAGraphics::vga_red);
kprintf("[WARNING] ");
kprintf(warn);
}
void kerr(const char * err){
Driver::VGAGraphics::vga_driver.colour(Driver::VGAGraphics::vga_red);
kprintf("[ERROR] ");
kprintf(err);
}
void kprintf(const char * msg){
unsigned int j = 0;
/* this loop writes the string to video memory */
while(msg[j] != '\0') {
switch(msg[j]){
case '%':
{
switch(msg[j+1]){
case 'd': {
// print a decimal
}
default: {
kprint_c(msg[j]);
++j;
break;
};
}
}
default: {
kprint_c(msg[j]);
++j;
break;
}
}
}
}
void kprintf(String msg){
kprintf(msg.cstr());
}
void kprint_c(const char c){
switch(c){
default:{
Driver::VGAGraphics::vga_driver.putc(c);
}
}
}
void kprint_int(int i){
char buffer[50];
if(i==0){
buffer[0]='0';
buffer[1]='\0';
IO::kprint_str(buffer);
}
bool is_neg = i<0;
if(is_neg)i*=-1;
//!@TODO for integers larger than 10
int j =0;
while(i>0){
buffer[j]=(i%10)+'0';
i/=10;
j++;
}
if(is_neg) buffer[j++]='-';
buffer[j]='\0';
int start = 0;
int end = j-1;
while(start<end){
char a, b;
a = *(buffer+start);
b = *(buffer+end);
*(buffer+start)=b;
*(buffer+end)=a;
start++;
end--;
}
kprint_str(buffer);
}
void kprint_f(float f, int prescision){
// extract integer part
volatile s32 i_part = (s32)f;
// extraft float part
//float f_part = (float)f;
//kprint_int(i_part);
//kprint_c('.');
//kprint_int((int)(f_part*Utils::Math::pow(f_part, prescision)));
}
void kprint_str(const char * str){
for(int i = 0;str[i];i++)
kprint_c(str[i]);
}
} | 19.300885 | 74 | 0.538285 |
efd1f73832af8201c5c3a93fc34f1c6446bfe8ce | 752 | hpp | C++ | include/RED4ext/Types/generated/community/CommunityEntryPhaseTimePeriodData.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/community/CommunityEntryPhaseTimePeriodData.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/community/CommunityEntryPhaseTimePeriodData.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Types/generated/world/GlobalNodeID.hpp>
namespace RED4ext
{
namespace community {
struct CommunityEntryPhaseTimePeriodData
{
static constexpr const char* NAME = "communityCommunityEntryPhaseTimePeriodData";
static constexpr const char* ALIAS = NAME;
CName periodName; // 00
DynArray<world::GlobalNodeID> spotNodeIds; // 08
bool isSequence; // 18
uint8_t unk19[0x20 - 0x19]; // 19
};
RED4EXT_ASSERT_SIZE(CommunityEntryPhaseTimePeriodData, 0x20);
} // namespace community
} // namespace RED4ext
| 26.857143 | 85 | 0.757979 |
efd27baa76ce20bbacdcda74479534b6e862c749 | 2,587 | cpp | C++ | source/mdb/mdbclt/mdbclt_example/src/mdbclt_example.m.cpp | jan-kelemen/melinda | 308e6262bc0cab7f6253062e8abda11452490bb4 | [
"BSD-3-Clause"
] | 3 | 2021-03-25T08:44:38.000Z | 2022-01-06T11:05:42.000Z | source/mdb/mdbclt/mdbclt_example/src/mdbclt_example.m.cpp | jan-kelemen/melinda | 308e6262bc0cab7f6253062e8abda11452490bb4 | [
"BSD-3-Clause"
] | 6 | 2019-07-13T17:11:50.000Z | 2022-03-07T19:22:09.000Z | source/mdb/mdbclt/mdbclt_example/src/mdbclt_example.m.cpp | jan-kelemen/melinda | 308e6262bc0cab7f6253062e8abda11452490bb4 | [
"BSD-3-Clause"
] | null | null | null | #include <array>
#include <chrono>
#include <iostream>
#include <thread>
#include <unistd.h>
#include <vector>
#include <mblcxx_scope_exit.h>
#include <mbltrc_trace.h>
#include <mdbnet_client.h>
#include <mdbnet_serialization.h>
int main()
{
melinda::mbltrc::trace_options trace_config(std::filesystem::path("../log"),
std::filesystem::path("example_client"));
trace_config.level = melinda::mbltrc::trace_level::info;
melinda::mbltrc::initialize_process_trace_handle(
melinda::mbltrc::create_trace_handle(trace_config));
zmq::context_t ctx;
constexpr char const* const address = "tcp://localhost:22365";
melinda::mblcxx::result<zmq::socket_t> connect_result =
melinda::mdbnet::client::connect(ctx, address);
if (!connect_result)
{
MBLTRC_TRACE_FATAL("Can't connect to {}", address);
std::terminate();
}
// TODO-JK allow taking values out of result
zmq::socket_t& socket = connect_result.ok();
MBLCXX_ON_SCOPE_EXIT(socket.disconnect(address));
std::string const identity = socket.get(zmq::sockopt::routing_id, 256);
flatbuffers::FlatBufferBuilder const query =
melinda::mdbnet::serialization::query(identity, "SELECT * FROM v$sql");
while (true)
{
melinda::mdbnet::result<zmq::send_result_t> const send_result =
melinda::mdbnet::client::send(socket,
{reinterpret_cast<std::byte*>(query.GetBufferPointer()),
query.GetSize()});
if (!send_result || !send_result.ok())
{
continue;
}
melinda::mdbnet::result<melinda::mdbnet::recv_response<zmq::message_t>>
recv_result = melinda::mdbnet::client::recv(
socket); // TODO-JK: This is blocking indefinately
if (recv_result)
{
melinda::mdbnet::recv_response<zmq::message_t> const& success =
recv_result.ok();
if (success.received)
{
melinda::mdbnet::Message const* message =
flatbuffers::GetRoot<melinda::mdbnet::root_type>(
success.message.value().data());
if (message->content_type() ==
melinda::mdbnet::MessageContent_result)
{
melinda::mdbnet::QueryResult const* query_result =
message->content_as_result();
MBLTRC_TRACE_INFO("Returned {} rows.",
query_result->length());
}
}
}
}
}
| 31.54878 | 80 | 0.591032 |
efd409501cd105af4876885427bae9752ac9f537 | 2,329 | cpp | C++ | src/Crane.cpp | ithamsteri/towerblocks | 584c37e43dea91ffb789883e873884b9279e7dcb | [
"MIT"
] | null | null | null | src/Crane.cpp | ithamsteri/towerblocks | 584c37e43dea91ffb789883e873884b9279e7dcb | [
"MIT"
] | null | null | null | src/Crane.cpp | ithamsteri/towerblocks | 584c37e43dea91ffb789883e873884b9279e7dcb | [
"MIT"
] | null | null | null | #include "Crane.h"
#include "Resource.h"
#include <cmath>
spSprite
Crane::doThrowBlock()
{
if (_state != States::Working) {
return nullptr;
}
_block->detach();
_block->setPosition(_view->getPosition());
// return crane to base
auto t = _view->addTween(TweenDummy(), 50);
t->addEventListener(TweenEvent::DONE, [this](Event*) { moveToBase(); });
return _block;
}
void
Crane::start()
{
_state = States::FromBase;
_block = getNewBlock();
_block->attachTo(_view);
// reset all parameters for pendulum
_velocity = 0.0f;
_acceleration = 0.0f;
_angle = -0.5f * pi;
// TODO: "Don't Repeat Yourself (DRY)"
float x = _basePosition.x + std::sin(_angle) * _length;
float y = std::cos(_angle) * 0.5f * _length;
auto t = _view->addTween(Actor::TweenPosition(x, y), speedAnimation);
t->addEventListener(TweenEvent::DONE, [this](Event*) { _state = States::Working; });
}
void
Crane::stop()
{
_state = States::Stopped;
auto t = _view->addTween(Actor::TweenPosition(_basePosition), speedAnimation);
}
void
Crane::_init()
{
spSprite magnit = new Sprite;
magnit->setResAnim(res::ui.getResAnim("Game_CraneMagnet"));
magnit->setAnchor(0.5f, 1.0f);
magnit->attachTo(_view);
magnit->setPriority(50);
// save base position for crane
_basePosition = _view->getPosition();
// set length rope of crane
_length = _basePosition.x - _basePosition.x * 2 * 0.20f;
start();
}
void
Crane::_update(const UpdateState& us)
{
if (_state != States::Working) {
return;
}
// TODO: Make Oxygine Tween for pendulum move
_acceleration = gravity / _length * std::sin(_angle);
_velocity += _acceleration / us.dt * _speed;
_angle += _velocity / us.dt * _speed;
float x = _basePosition.x + std::sin(_angle) * _length;
float y = std::cos(_angle) * 0.5f * _length;
_view->setPosition(x, y);
}
void
Crane::moveToBase()
{
_state = States::ToBase;
auto t = _view->addTween(Actor::TweenPosition(_basePosition), speedAnimation);
t->addEventListener(TweenEvent::DONE, [this](Event*) { this->start(); });
}
spSprite
Crane::getNewBlock() const
{
int blockNum = static_cast<int>(scalar::randFloat(0.0f, 7.0f)) + 1;
auto block = new Sprite;
block->setResAnim(res::ui.getResAnim("Block" + std::to_string(blockNum)));
block->setAnchor(0.5f, 0.25f);
return block;
} | 22.180952 | 86 | 0.668957 |
efd502b3ded485b3ba8eb91a2671450db283faa4 | 3,520 | cpp | C++ | tests/altium_crap/Soft Designs/C++/NB3000 C++ Tetris/Embedded/input.cpp | hanun2999/Altium-Schematic-Parser | a9bd5b1a865f92f2e3f749433fb29107af528498 | [
"MIT"
] | 1 | 2020-06-08T11:17:46.000Z | 2020-06-08T11:17:46.000Z | tests/altium_crap/Soft Designs/C++/NB3000 C++ Tetris/Embedded/input.cpp | hanun2999/Altium-Schematic-Parser | a9bd5b1a865f92f2e3f749433fb29107af528498 | [
"MIT"
] | null | null | null | tests/altium_crap/Soft Designs/C++/NB3000 C++ Tetris/Embedded/input.cpp | hanun2999/Altium-Schematic-Parser | a9bd5b1a865f92f2e3f749433fb29107af528498 | [
"MIT"
] | null | null | null | // Logger thread
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <mqueue.h>
#include "devices.h"
#include "drv_ioport.h"
#include "tetris.h"
Buttons::Buttons(const int id)
{
_port = ioport_open(BUTTONS);
for (int i = 0; i < BUTTON_COUNT; ++i)
{
_switchIsUp[i] = true;
_switchUpCount[i] = 0;
}
}
Buttons::button_kind_t Buttons::GetValue()
{
char buttons;
int i;
char button_value;
char result = 0;
buttons = ioport_get_value(_port, 0);
buttons = ~buttons & 0x1F;
for (i = 0; i < BUTTON_COUNT; i++)
{
// for each button, it registers an event when it first goes down,
// as long as it has been up DEBOUNCE times
button_value = (buttons >> i) & 0x01;
if (!button_value)
{
// button is up
_switchUpCount[i]++;
if (_switchUpCount[i] >= DEBOUNCE)
{
_switchIsUp[i] = true;
}
}
else
{
// button is down
_switchUpCount[i] = 0;
if (_switchIsUp[i])
{
result = result | (1 << i);
_switchIsUp[i] = false;
}
}
}
switch (result)
{
case 0x01: return BTN_LEFT;
case 0x02: return BTN_RIGHT;
case 0x04: return BTN_ROTATE;
case 0x08: return BTN_DROP;
case 0x10: return BTN_PAUSE;
}
return BTN_NONE;
}
InputThread::InputThread() : ThreadBase()
{
}
void InputThread::Setup()
{
struct sched_param schedparam;
// base setup function
ThreadBase::Setup();
// initialize pthread attributes
pthread_attr_init(& _attr);
pthread_attr_setinheritsched(& _attr, PTHREAD_EXPLICIT_SCHED);
// initialize scheduling priority
schedparam.sched_priority = INPUT_THREAD_PRIORITY;
pthread_attr_setschedparam(& _attr, & schedparam);
// initialize thread stack
pthread_attr_setstackaddr(& _attr, (void *) & _stack[0]);
pthread_attr_setstacksize(& _attr, sizeof(_stack));
}
void * InputThread::Execute(void * arg)
{
Buttons buttons(BUTTONS);
volatile int stop = 0;
TetrisGame * theGame;
mqd_t mq;
Buttons::button_kind_t kind;
theGame = (TetrisGame *) arg;
mq = theGame->GetSendQueue();
while (!stop)
{
kind = buttons.GetValue();
// stroke actions
if (StrokeAction(theGame, kind) == false)
{
// send exit msg to logger
#define ENDED_BY_USER "\n ended by user"
mq_send(mq, ENDED_BY_USER, sizeof(ENDED_BY_USER) - 1, MSG_EXIT);
}
}
return NULL;
}
bool InputThread::StrokeAction(TetrisGame * theGame, Buttons::button_kind_t kind)
{
switch (kind)
{
case Buttons::BTN_LEFT:
theGame->GetTetrisThread().Kill(SIGBUTTON1);
break;
case Buttons::BTN_RIGHT:
theGame->GetTetrisThread().Kill(SIGBUTTON2);
break;
case Buttons::BTN_ROTATE:
theGame->GetTetrisThread().Kill(SIGBUTTON3);
break;
case Buttons::BTN_DROP:
theGame->GetTetrisThread().Kill(SIGBUTTON4);
break;
case Buttons::BTN_PAUSE:
theGame->GetTetrisThread().Kill(SIGBUTTON5);
break;
default:
break;
}
return true;
}
| 22.709677 | 81 | 0.552841 |
efda4cdf0fedf7671b9917eebe1c9b9a769eaf95 | 3,543 | cpp | C++ | external/webkit/Source/WebKit2/UIProcess/WebPreferences.cpp | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | WebKit/Source/WebKit2/UIProcess/WebPreferences.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | WebKit/Source/WebKit2/UIProcess/WebPreferences.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /*
* Copyright (C) 2010, 2011 Apple 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "WebPreferences.h"
#include "WebPageGroup.h"
namespace WebKit {
WebPreferences::WebPreferences()
{
platformInitializeStore();
}
WebPreferences::WebPreferences(const String& identifier)
: m_identifier(identifier)
{
platformInitializeStore();
}
WebPreferences::~WebPreferences()
{
}
void WebPreferences::addPageGroup(WebPageGroup* pageGroup)
{
m_pageGroups.add(pageGroup);
}
void WebPreferences::removePageGroup(WebPageGroup* pageGroup)
{
m_pageGroups.remove(pageGroup);
}
void WebPreferences::update()
{
for (HashSet<WebPageGroup*>::iterator it = m_pageGroups.begin(), end = m_pageGroups.end(); it != end; ++it)
(*it)->preferencesDidChange();
}
void WebPreferences::updateStringValueForKey(const String& key, const String& value)
{
platformUpdateStringValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
void WebPreferences::updateBoolValueForKey(const String& key, bool value)
{
platformUpdateBoolValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
void WebPreferences::updateUInt32ValueForKey(const String& key, uint32_t value)
{
platformUpdateUInt32ValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
void WebPreferences::updateDoubleValueForKey(const String& key, double value)
{
platformUpdateDoubleValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
#define DEFINE_PREFERENCE_GETTER_AND_SETTERS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) \
void WebPreferences::set##KeyUpper(const Type& value) \
{ \
if (!m_store.set##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key(), value)) \
return; \
update##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key(), value); \
\
} \
\
Type WebPreferences::KeyLower() const \
{ \
return m_store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()); \
} \
FOR_EACH_WEBKIT_PREFERENCE(DEFINE_PREFERENCE_GETTER_AND_SETTERS)
#undef DEFINE_PREFERENCE_GETTER_AND_SETTERS
} // namespace WebKit
| 33.11215 | 111 | 0.740051 |
efdaffa8672f649e8c82c426d322ed9fcb08f56c | 1,359 | hpp | C++ | Seer_Sim/utils/log.hpp | lanl/Seer | 9fb38d5a0fdb5e4dfcd5ee6fdafd9df6078d5f5b | [
"BSD-3-Clause"
] | 1 | 2020-03-19T07:01:35.000Z | 2020-03-19T07:01:35.000Z | Seer_Sim/utils/log.hpp | lanl/Seer | 9fb38d5a0fdb5e4dfcd5ee6fdafd9df6078d5f5b | [
"BSD-3-Clause"
] | null | null | null | Seer_Sim/utils/log.hpp | lanl/Seer | 9fb38d5a0fdb5e4dfcd5ee6fdafd9df6078d5f5b | [
"BSD-3-Clause"
] | 1 | 2020-03-19T07:01:36.000Z | 2020-03-19T07:01:36.000Z | #pragma once
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
namespace Seer
{
class Log
{
std::string outputFilename;
public:
std::stringstream log;
Log(){ outputFilename = "untitled.log"; }
Log(std::string _outputFilename): outputFilename(_outputFilename){ }
~Log();
void setOutputFilename(std::string _outputFilename){ outputFilename = _outputFilename; }
void clear(){ log.str(""); }
void writeToDisk();
};
inline Log::~Log()
{
outputFilename = "";
log.str("");
}
inline void Log::writeToDisk()
{
std::ofstream outputFile( outputFilename.c_str(), std::ios::out);
outputFile << log.str();
outputFile.close();
}
///////////////////////////////////////////////////////////////////////////////////
///////////// Simple Logging
inline void writeLog(std::string filename, std::string log)
{
std::ofstream outputFile( (filename+ ".log").c_str(), std::ios::out);
outputFile << log;
outputFile.close();
}
inline void writeLogApp(std::string filename, std::string log)
{
std::ofstream outputFile( (filename+ ".log").c_str(), std::ios::out | std::ios::app);
outputFile << log;
outputFile.close();
}
inline void writeLogNew(std::string filename, std::string log)
{
std::ofstream outputFile( (filename+ ".log").c_str(), std::ios::out);
outputFile << log;
outputFile.close();
}
} // namespace Seer | 19.414286 | 89 | 0.636497 |
efdcd15d96899c50a32173b6c3761e27d4a3bf75 | 8,702 | hpp | C++ | src/Providers/UNIXProviders/BlockStatisticsManifest/UNIX_BlockStatisticsManifest_AIX.hpp | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/BlockStatisticsManifest/UNIX_BlockStatisticsManifest_ZOS.hpp | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/BlockStatisticsManifest/UNIX_BlockStatisticsManifest_ZOS.hpp | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
UNIX_BlockStatisticsManifest::UNIX_BlockStatisticsManifest(void)
{
}
UNIX_BlockStatisticsManifest::~UNIX_BlockStatisticsManifest(void)
{
}
Boolean UNIX_BlockStatisticsManifest::getInstanceID(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
return true;
}
String UNIX_BlockStatisticsManifest::getInstanceID() const
{
return String ("");
}
Boolean UNIX_BlockStatisticsManifest::getCaption(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CAPTION, getCaption());
return true;
}
String UNIX_BlockStatisticsManifest::getCaption() const
{
return String ("");
}
Boolean UNIX_BlockStatisticsManifest::getDescription(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
return true;
}
String UNIX_BlockStatisticsManifest::getDescription() const
{
return String ("");
}
Boolean UNIX_BlockStatisticsManifest::getElementName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
return true;
}
String UNIX_BlockStatisticsManifest::getElementName() const
{
return String("BlockStatisticsManifest");
}
Boolean UNIX_BlockStatisticsManifest::getElementType(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_TYPE, getElementType());
return true;
}
Uint16 UNIX_BlockStatisticsManifest::getElementType() const
{
return Uint16(0);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStartStatisticTime(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_START_STATISTIC_TIME, getIncludeStartStatisticTime());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStartStatisticTime() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStatisticTime(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_STATISTIC_TIME, getIncludeStatisticTime());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStatisticTime() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeTotalIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_TOTAL_I_OS, getIncludeTotalIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeTotalIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesTransferred(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_K_BYTES_TRANSFERRED, getIncludeKBytesTransferred());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesTransferred() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_I_O_TIME_COUNTER, getIncludeIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_I_OS, getIncludeReadIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_HIT_I_OS, getIncludeReadHitIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_I_O_TIME_COUNTER, getIncludeReadIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_HIT_I_O_TIME_COUNTER, getIncludeReadHitIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesRead(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_K_BYTES_READ, getIncludeKBytesRead());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesRead() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_I_OS, getIncludeWriteIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_HIT_I_OS, getIncludeWriteHitIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_I_O_TIME_COUNTER, getIncludeWriteIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_HIT_I_O_TIME_COUNTER, getIncludeWriteHitIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesWritten(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_K_BYTES_WRITTEN, getIncludeKBytesWritten());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesWritten() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIdleTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_IDLE_TIME_COUNTER, getIncludeIdleTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIdleTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintOp(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_MAINT_OP, getIncludeMaintOp());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintOp() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_MAINT_TIME_COUNTER, getIncludeMaintTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::initialize()
{
return false;
}
Boolean UNIX_BlockStatisticsManifest::load(int &pIndex)
{
return false;
}
Boolean UNIX_BlockStatisticsManifest::finalize()
{
return false;
}
Boolean UNIX_BlockStatisticsManifest::find(Array<CIMKeyBinding> &kbArray)
{
CIMKeyBinding kb;
String instanceIDKey;
for(Uint32 i = 0; i < kbArray.size(); i++)
{
kb = kbArray[i];
CIMName keyName = kb.getName();
if (keyName.equal(PROPERTY_INSTANCE_ID)) instanceIDKey = kb.getValue();
}
/* EXecute find with extracted keys */
return false;
}
| 26.29003 | 97 | 0.78729 |
efe0371b0fc4ddd4c1bde0c167444d0d3a5643d1 | 1,589 | hpp | C++ | kernel/include/Sigma/types/hash_map.hpp | thomtl/Sigma | 30da9446a1f1b5cae4eff77bf9917fae1446ce85 | [
"BSD-2-Clause"
] | 46 | 2019-09-30T18:40:06.000Z | 2022-02-20T12:54:59.000Z | kernel/include/Sigma/types/hash_map.hpp | thomtl/Sigma | 30da9446a1f1b5cae4eff77bf9917fae1446ce85 | [
"BSD-2-Clause"
] | 11 | 2019-08-18T18:31:11.000Z | 2021-09-14T22:34:16.000Z | kernel/include/Sigma/types/hash_map.hpp | thomtl/Sigma | 30da9446a1f1b5cae4eff77bf9917fae1446ce85 | [
"BSD-2-Clause"
] | 1 | 2020-01-20T16:55:13.000Z | 2020-01-20T16:55:13.000Z | #ifndef SIGMA_TYPES_HASH_MAP_H
#define SIGMA_TYPES_HASH_MAP_H
#include <Sigma/common.h>
#include <Sigma/types/linked_list.h>
#include <klibcxx/utility.hpp>
#include <Sigma/arch/x86_64/misc/spinlock.h>
namespace types
{
template<typename T>
struct nop_hasher {
using hash_result = T;
hash_result operator()(T item){
return item;
}
};
// TODO: Seriously, this is the best hash_map you can think of, just, make something doable, not this monstrosity
template<typename Key, typename Value, typename Hasher>
class hash_map {
public:
hash_map() = default;
hash_map(hash_map&& other){
this->list = std::move(other.list);
this->hasher = std::move(other.hasher);
}
hash_map& operator=(hash_map&& other){
this->list = std::move(other.list);
this->hasher = std::move(other.hasher);
return *this;
}
void push_back(Key key, Value value){
auto hash = this->hasher(key);
this->list.push_back({hash, value});
}
Value& operator[](Key key){
auto hash = this->hasher(key);
for(auto& entry : list)
if(entry.first == hash)
return entry.second;
PANIC("Hash not in map");
while(1)
;
}
private:
using entry = std::pair<typename Hasher::hash_result, Value>;
types::linked_list<entry> list;
Hasher hasher;
};
} // namespace types
#endif | 24.446154 | 117 | 0.56073 |
efe16d7cfa75b0fb9545eab906506513fb6c1f5f | 19,369 | cpp | C++ | src/drivers/common/driver_base.cpp | Dwedit/sdlretro | 521c5558cb55d4028210529e336d8a8622037358 | [
"MIT"
] | null | null | null | src/drivers/common/driver_base.cpp | Dwedit/sdlretro | 521c5558cb55d4028210529e336d8a8622037358 | [
"MIT"
] | null | null | null | src/drivers/common/driver_base.cpp | Dwedit/sdlretro | 521c5558cb55d4028210529e336d8a8622037358 | [
"MIT"
] | null | null | null | #include "driver_base.h"
#include "logger.h"
#include "cfg.h"
#include "video_base.h"
#include "buffered_audio.h"
#include "input_base.h"
#include "throttle.h"
#include "util.h"
#include <variables.h>
#include <core.h>
#include <cstring>
#include <cmath>
#include <memory>
#include <fstream>
namespace libretro {
extern struct retro_vfs_interface vfs_interface;
}
namespace drivers {
#ifdef _WIN32
#define PATH_SEPARATOR_CHAR "\\"
#else
#define PATH_SEPARATOR_CHAR "/"
#endif
inline void lowered_string(std::string &s) {
for (char &c: s) {
if (c <= ' ' || c == '\\' || c == '/' || c == ':' || c == '*' || c == '"' || c == '<' || c == '>' || c == '|')
c = '_';
else
c = std::tolower(c);
}
}
inline std::string get_base_name(const std::string &path) {
std::string basename = path;
auto pos = basename.find_last_of("/\\");
if (pos != std::string::npos) {
basename = basename.substr(pos + 1);
}
pos = basename.find_last_of('.');
if (pos != std::string::npos)
basename.erase(pos);
return basename;
}
driver_base *current_driver = nullptr;
driver_base::driver_base() {
frame_throttle = std::make_shared<throttle>();
variables = std::make_unique<libretro::retro_variables>();
}
driver_base::~driver_base() {
deinit_internal();
if (core) {
core_unload(core);
core = nullptr;
}
current_driver = nullptr;
}
void driver_base::set_dirs(const std::string &static_root, const std::string &config_root) {
static_dir = static_root;
config_dir = config_root;
system_dir = config_root + PATH_SEPARATOR_CHAR "system";
util_mkdir(system_dir.c_str());
save_dir = config_root + PATH_SEPARATOR_CHAR "saves";
util_mkdir(save_dir.c_str());
}
void driver_base::run(std::function<void()> in_game_menu_cb) {
while (!shutdown_driver && run_frame(in_game_menu_cb, video->frame_drawn())) {
auto check = g_cfg.get_save_check();
if (check) {
if (!save_check_countdown) {
check_save_ram();
save_check_countdown = lround(check * fps);
} else {
save_check_countdown--;
}
}
core->retro_run();
video->message_frame_pass();
}
}
bool RETRO_CALLCONV retro_environment_cb(unsigned cmd, void *data) {
if (!current_driver) return false;
return current_driver->env_callback(cmd, data);
}
void RETRO_CALLCONV log_printf(enum retro_log_level level, const char *fmt, ...) {
#if defined(NDEBUG) || !defined(LIBRETRO_DEBUG_LOG)
if (level >= RETRO_LOG_DEBUG)
return;
#endif
va_list l;
va_start(l, fmt);
log_vprintf((int)level, fmt, l);
va_end(l);
}
static void RETRO_CALLCONV retro_video_refresh_cb(const void *data, unsigned width, unsigned height, size_t pitch) {
if (!data) return;
current_driver->get_video()->render(data, width, height, pitch);
}
static void RETRO_CALLCONV retro_audio_sample_cb(int16_t left, int16_t right) {
int16_t samples[2] = {left, right};
current_driver->get_audio()->write_samples(samples, 2);
}
static size_t RETRO_CALLCONV retro_audio_sample_batch_cb(const int16_t *data, size_t frames) {
current_driver->get_audio()->write_samples(data, frames * 2);
return frames;
}
static void RETRO_CALLCONV retro_input_poll_cb() {
current_driver->get_input()->input_poll();
}
static int16_t RETRO_CALLCONV retro_input_state_cb(unsigned port, unsigned device, unsigned index, unsigned id) {
return current_driver->get_input()->input_state(port, device, index, id);
}
static bool RETRO_CALLCONV retro_set_rumble_state_cb(unsigned port, enum retro_rumble_effect effect, uint16_t strength) {
return false;
}
inline bool read_file(const std::string filename, std::vector<uint8_t> &data) {
std::ifstream ifs(filename, std::ios_base::binary | std::ios_base::in);
if (!ifs.good()) return false;
ifs.seekg(0, std::ios_base::end);
size_t sz = ifs.tellg();
if (!sz) {
ifs.close();
return false;
}
data.resize(sz);
ifs.seekg(0, std::ios_base::beg);
ifs.read((char *)data.data(), sz);
ifs.close();
return true;
}
bool driver_base::load_game(const std::string &path) {
retro_game_info info = {};
info.path = path.c_str();
if (!need_fullpath) {
std::ifstream ifs(path, std::ios_base::binary | std::ios_base::in);
if (!ifs.good()) {
logger(LOG_ERROR) << "Unable to load " << path << std::endl;
return false;
}
ifs.seekg(0, std::ios_base::end);
game_data.resize(ifs.tellg());
ifs.seekg(0, std::ios_base::beg);
ifs.read(&game_data[0], game_data.size());
ifs.close();
info.data = &game_data[0];
info.size = game_data.size();
}
if (!core->retro_load_game(&info)) {
logger(LOG_ERROR) << "Unable to load " << path << std::endl;
return false;
}
game_path = path;
post_load();
return true;
}
bool driver_base::load_game_from_mem(const std::string &path, const std::string ext, const std::vector<uint8_t> &data) {
retro_game_info info = {};
if (!need_fullpath) {
game_data.assign(data.begin(), data.end());
info.path = path.c_str();
info.data = &game_data[0];
info.size = game_data.size();
} else {
std::string basename = get_base_name(path);
temp_file = config_dir + PATH_SEPARATOR_CHAR "tmp";
util_mkdir(temp_file.c_str());
temp_file = temp_file + PATH_SEPARATOR_CHAR + basename + "." + ext;
std::ofstream ofs(temp_file, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
if (!ofs.good()) return false;
ofs.write((const char*)&data[0], data.size());
if (ofs.bad()) {
ofs.close();
remove(temp_file.c_str());
return false;
}
ofs.close();
info.path = temp_file.c_str();
}
if (!core->retro_load_game(&info)) {
logger(LOG_ERROR) << "Unable to load " << path << std::endl;
return false;
}
game_path = path;
post_load();
return true;
}
void driver_base::unload_game() {
shutdown_driver = false;
check_save_ram();
game_path.clear();
game_base_name.clear();
game_save_path.clear();
game_rtc_path.clear();
save_data.clear();
rtc_data.clear();
core->retro_unload_game();
audio->stop();
unload();
if (!temp_file.empty()) {
remove(temp_file.c_str());
temp_file.clear();
}
}
void driver_base::reset() {
core->retro_reset();
}
bool driver_base::env_callback(unsigned cmd, void *data) {
switch (cmd) {
case RETRO_ENVIRONMENT_SET_ROTATION:
break;
case RETRO_ENVIRONMENT_GET_OVERSCAN:
*(bool*)data = false;
return true;
case RETRO_ENVIRONMENT_GET_CAN_DUPE:
*(bool*)data = true;
return true;
case RETRO_ENVIRONMENT_SET_MESSAGE: {
const auto *msg = (const retro_message*)data;
video->set_message(msg->msg, msg->frames);
return true;
}
case RETRO_ENVIRONMENT_SHUTDOWN:
shutdown_driver = true;
return true;
case RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL:
return true;
case RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY:
*(const char**)data = system_dir.c_str();
return true;
case RETRO_ENVIRONMENT_SET_PIXEL_FORMAT: {
auto new_format = (unsigned)*(const enum retro_pixel_format *)data;
if (new_format != pixel_format) {
pixel_format = new_format;
video->resolution_changed(base_width, base_height, pixel_format == RETRO_PIXEL_FORMAT_XRGB8888 ? 32 : 16);
}
return true;
}
case RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS: {
const auto *inp = (const retro_input_descriptor*)data;
while (inp->description != nullptr) {
input->add_button(inp->port, inp->device, inp->index, inp->id, inp->description);
++inp;
}
return true;
}
case RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK:
case RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE:
case RETRO_ENVIRONMENT_SET_HW_RENDER:
break;
case RETRO_ENVIRONMENT_GET_VARIABLE: {
variables->set_variables_updated(false);
auto *var = (retro_variable *)data;
auto *vari = variables->get_variable(var->key);
if (vari) {
var->value = vari->options[vari->curr_index].first.c_str();
return true;
}
return false;
}
case RETRO_ENVIRONMENT_SET_VARIABLES: {
const auto *vars = (const retro_variable*)data;
variables->load_variables(vars);
variables->load_variables_from_cfg(core_cfg_path);
return true;
}
case RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE:
*(bool*)data = variables->get_variables_updated();
return true;
case RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME:
support_no_game = *(bool*)data;
return true;
case RETRO_ENVIRONMENT_GET_LIBRETRO_PATH:
*(const char**)data = nullptr;
return true;
case RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK:
case RETRO_ENVIRONMENT_SET_AUDIO_CALLBACK:
break;
case RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE: {
auto *ri = (retro_rumble_interface*)data;
ri->set_rumble_state = retro_set_rumble_state_cb;
return true;
}
case RETRO_ENVIRONMENT_GET_INPUT_DEVICE_CAPABILITIES:
*(uint64_t*)data = (1ULL << RETRO_DEVICE_JOYPAD) | (1ULL << RETRO_DEVICE_ANALOG);
return true;
case RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE:
case RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE:
break;
case RETRO_ENVIRONMENT_GET_LOG_INTERFACE: {
((retro_log_callback*)data)->log = log_printf;
return true;
}
case RETRO_ENVIRONMENT_GET_PERF_INTERFACE:
case RETRO_ENVIRONMENT_GET_LOCATION_INTERFACE:
case RETRO_ENVIRONMENT_GET_CORE_ASSETS_DIRECTORY:
break;
case RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY:
*(const char**)data = core_save_dir.empty() ? nullptr : core_save_dir.c_str();
return true;
case RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO:
case RETRO_ENVIRONMENT_SET_PROC_ADDRESS_CALLBACK:
case RETRO_ENVIRONMENT_SET_SUBSYSTEM_INFO:
break;
case RETRO_ENVIRONMENT_SET_CONTROLLER_INFO: {
const auto *info = (const retro_controller_info*)data;
return true;
}
case RETRO_ENVIRONMENT_SET_MEMORY_MAPS: {
const auto *memmap = (const retro_memory_map*)data;
for (unsigned i = 0; i < memmap->num_descriptors; ++i) {
/* TODO: store info of memory map for future use */
}
return true;
}
case RETRO_ENVIRONMENT_SET_GEOMETRY: {
const auto *geometry = (const retro_game_geometry*)data;
base_width = geometry->base_width;
base_height = geometry->base_height;
max_width = geometry->max_width;
max_height = geometry->max_height;
aspect_ratio = geometry->aspect_ratio;
video->resolution_changed(base_width, base_height, pixel_format == RETRO_PIXEL_FORMAT_XRGB8888 ? 32 : 16);
return true;
}
case RETRO_ENVIRONMENT_GET_USERNAME:
*(const char**)data = "sdlretro";
return true;
case RETRO_ENVIRONMENT_GET_LANGUAGE:
*(unsigned*)data = RETRO_LANGUAGE_ENGLISH;
return true;
case RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER:
/*
{
auto *fb = (retro_framebuffer*)data;
fb->data = video->get_framebuffer(&fb->width, &fb->height, &fb->pitch, (int*)&fb->format);
if (fb->data)
return true;
}
*/
return false;
case RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE:
break;
case RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS:
support_achivements = data ? *(bool*)data : true;
return true;
case RETRO_ENVIRONMENT_SET_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE:
case RETRO_ENVIRONMENT_SET_SERIALIZATION_QUIRKS:
case RETRO_ENVIRONMENT_SET_HW_SHARED_CONTEXT:
break;
case RETRO_ENVIRONMENT_GET_VFS_INTERFACE: {
auto *info = (struct retro_vfs_interface_info *)data;
if (info->required_interface_version > 3) return false;
info->iface = &libretro::vfs_interface;
return true;
}
case RETRO_ENVIRONMENT_GET_LED_INTERFACE:
case RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE:
case RETRO_ENVIRONMENT_GET_MIDI_INTERFACE:
case RETRO_ENVIRONMENT_GET_FASTFORWARDING:
case RETRO_ENVIRONMENT_GET_TARGET_REFRESH_RATE:
break;
case RETRO_ENVIRONMENT_GET_INPUT_BITMASKS:
if (data) *(bool*)data = true;
return true;
case RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION:
*(unsigned*)data = RETRO_API_VERSION;
return true;
case RETRO_ENVIRONMENT_SET_CORE_OPTIONS: {
variables->load_variables((const retro_core_option_definition*)data);
variables->load_variables_from_cfg(core_cfg_path);
return true;
}
case RETRO_ENVIRONMENT_SET_CORE_OPTIONS_INTL: {
variables->load_variables(((const retro_core_options_intl*)data)->us);
variables->load_variables_from_cfg(core_cfg_path);
return true;
}
case RETRO_ENVIRONMENT_SET_CORE_OPTIONS_DISPLAY: {
const auto *opt = (const retro_core_option_display*)data;
variables->set_variable_visible(opt->key, opt->visible);
return true;
}
case RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER:
default:
break;
}
if (cmd & RETRO_ENVIRONMENT_EXPERIMENTAL) {
logger(LOG_INFO) << "Unhandled env: " << (cmd & 0xFFFFU) << "(EXPERIMENTAL)" << std::endl;
} else {
logger(LOG_INFO) << "Unhandled env: " << cmd << std::endl;
}
return false;
}
void driver_base::save_variables_to_cfg() {
variables->save_variables_to_cfg(core_cfg_path);
}
bool driver_base::load_core(const std::string &path) {
core = core_load(path.c_str());
if (!core) return false;
current_driver = this;
core_cfg_path = config_dir + PATH_SEPARATOR_CHAR + "cfg";
util_mkdir(core_cfg_path.c_str());
retro_system_info sysinfo = {};
core->retro_get_system_info(&sysinfo);
library_name = sysinfo.library_name;
library_version = sysinfo.library_version;
need_fullpath = sysinfo.need_fullpath;
std::string name = sysinfo.library_name;
lowered_string(name);
core_cfg_path = core_cfg_path + PATH_SEPARATOR_CHAR + name + ".cfg";
core_save_dir = save_dir + PATH_SEPARATOR_CHAR + name;
util_mkdir(core_save_dir.c_str());
init_internal();
return true;
}
bool driver_base::init_internal() {
if (inited) return true;
if (!init()) {
return false;
}
shutdown_driver = false;
core->retro_set_environment(retro_environment_cb);
core->retro_init();
core->retro_set_video_refresh(retro_video_refresh_cb);
core->retro_set_audio_sample(retro_audio_sample_cb);
core->retro_set_audio_sample_batch(retro_audio_sample_batch_cb);
core->retro_set_input_poll(retro_input_poll_cb);
core->retro_set_input_state(retro_input_state_cb);
inited = true;
return true;
}
void driver_base::deinit_internal() {
if (!inited) return;
core->retro_deinit();
/* reset all variables to default value */
library_name.clear();
library_version.clear();
need_fullpath = false;
pixel_format = 0;
support_no_game = false;
base_width = 0;
base_height = 0;
max_width = 0;
max_height = 0;
aspect_ratio = 0.f;
game_data.clear();
variables->reset();
inited = false;
}
void driver_base::check_save_ram() {
// TODO: use progressive check for large sram?
size_t sram_size = core->retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
if (sram_size) {
void *sram = core->retro_get_memory_data(RETRO_MEMORY_SAVE_RAM);
if (sram_size != save_data.size() || memcmp(sram, save_data.data(), sram_size) != 0) {
std::ofstream ofs(game_save_path, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
ofs.write((const char*)sram, sram_size);
ofs.close();
save_data.assign((uint8_t*)sram, (uint8_t*)sram + sram_size);
}
}
size_t rtc_size = core->retro_get_memory_size(RETRO_MEMORY_RTC);
if (rtc_size) {
void *rtc = core->retro_get_memory_data(RETRO_MEMORY_RTC);
if (rtc_size != rtc_data.size() || memcmp(rtc, rtc_data.data(), rtc_size) != 0) {
std::ofstream ofs(game_rtc_path, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
ofs.write((const char*)rtc, rtc_size);
ofs.close();
rtc_data.assign((uint8_t*)rtc, (uint8_t*)rtc + rtc_size);
}
}
}
void driver_base::post_load() {
game_base_name = get_base_name(game_path);
game_save_path = (core_save_dir.empty() ? "" : (core_save_dir + PATH_SEPARATOR_CHAR)) + game_base_name + ".sav";
game_rtc_path = (core_save_dir.empty() ? "" : (core_save_dir + PATH_SEPARATOR_CHAR)) + game_base_name + ".rtc";
read_file(game_save_path, save_data);
read_file(game_rtc_path, rtc_data);
if (!save_data.empty()) {
size_t sz = core->retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
if (sz > save_data.size()) sz = save_data.size();
if (sz) memcpy(core->retro_get_memory_data(RETRO_MEMORY_SAVE_RAM), save_data.data(), sz);
}
if (!rtc_data.empty()) {
size_t sz = core->retro_get_memory_size(RETRO_MEMORY_RTC);
if (sz > rtc_data.size()) sz = rtc_data.size();
if (sz) memcpy(core->retro_get_memory_data(RETRO_MEMORY_RTC), rtc_data.data(), sz);
}
retro_system_av_info av_info = {};
core->retro_get_system_av_info(&av_info);
base_width = av_info.geometry.base_width;
base_height = av_info.geometry.base_height;
max_width = av_info.geometry.max_width;
max_height = av_info.geometry.max_height;
aspect_ratio = av_info.geometry.aspect_ratio;
fps = av_info.timing.fps;
audio->start(g_cfg.get_mono_audio(), av_info.timing.sample_rate, g_cfg.get_sample_rate(), av_info.timing.fps);
frame_throttle->reset(fps);
core->retro_set_controller_port_device(0, RETRO_DEVICE_JOYPAD);
video->resolution_changed(base_width, base_height, pixel_format == RETRO_PIXEL_FORMAT_XRGB8888 ? 32 : 16);
char library_message[256];
snprintf(library_message, 256, "Loaded core: %s", library_name.c_str());
video->set_message(library_message, lround(fps * 5));
}
}
| 34.403197 | 122 | 0.634674 |
efe23776cdeb4c1b4199c11404b11748f3439077 | 4,835 | cpp | C++ | libs/evolvo/test/tests.cpp | rufus-stone/genetic-algo-cpp | 5e31f080d30ffc204fa7891883703183302b2954 | [
"MIT"
] | null | null | null | libs/evolvo/test/tests.cpp | rufus-stone/genetic-algo-cpp | 5e31f080d30ffc204fa7891883703183302b2954 | [
"MIT"
] | null | null | null | libs/evolvo/test/tests.cpp | rufus-stone/genetic-algo-cpp | 5e31f080d30ffc204fa7891883703183302b2954 | [
"MIT"
] | null | null | null | #include "evolvo/chromosome.hpp"
#include "evolvo/crossover.hpp"
#include "evolvo/individual.hpp"
#include "evolvo/population.hpp"
#include "evolvo/selection.hpp"
#define CATCH_CONFIG_MAIN // This tells the Catch2 header to generate a main
#include "catch.hpp"
#include <random>
#include <vector>
#include <map>
#include <spdlog/spdlog.h>
#include <evolvo/ga.hpp>
////////////////////////////////////////////////////////////////
TEST_CASE("Chromosome", "[ga][chromosome]")
{
auto const chromo = ga::Chromosome{{1.1, 2.0, -3.3, 4.6}};
REQUIRE_THAT(chromo, Catch::Matchers::Approx(std::vector<double>{1.1, 2.0, -3.3, 4.6}));
REQUIRE(chromo[0] == Approx(1.1));
REQUIRE(chromo.size() == 4);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Individual", "[ga][individual]")
{
// Create a Chromosome and a fitness
auto const chromo = ga::Chromosome{{1.1, 2.0, -3.3, 4.6}};
double const fitness = 1.0;
// Create a new Individual from the Chromosome
auto const individual1 = ga::Individual{chromo};
// Check that it was created correctly
REQUIRE(individual1.chromosome() == chromo);
REQUIRE_THAT(individual1.chromosome(), Catch::Matchers::Approx(std::vector<double>{1.1, 2.0, -3.3, 4.6}));
REQUIRE(individual1.fitness() == 0.0);
// Create a new Individual from the fitness
auto const individual2 = ga::Individual{fitness};
// Check that it was created correctly
REQUIRE(individual2.chromosome().empty() == true);
REQUIRE(individual2.fitness() == 1.0);
// Create a new Individual from the Chromosome and the fitness
auto const individual3 = ga::Individual{chromo, fitness};
// Check that it was created correctly
REQUIRE(individual3.chromosome() == chromo);
REQUIRE_THAT(individual3.chromosome(), Catch::Matchers::Approx(std::vector<double>{1.1, 2.0, -3.3, 4.6}));
REQUIRE(individual3.fitness() == 1.0);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Selection", "[ga][individual]")
{
// Seed an mt19937 prng for a predictable "random" number to use for testing
auto prng = std::mt19937{42};
// Create a RouletteWheelSelection SelectionMethod
auto roulette_wheel = ga::RouletteWheelSelection{};
// Create a new Population from a collection of Individuals with the specified fitnesses to ride the wheel
auto const population = ga::Population{{ga::Individual{2.0}, ga::Individual{1.0}, ga::Individual{4.0}, ga::Individual{3.0}}};
// Spin the wheel 1000 times and see how many times each individual is chosen
auto results = std::map<int, int>{};
constexpr std::size_t spins = 1000;
for (std::size_t i = 0; i < spins; ++i)
{
std::size_t const choice = roulette_wheel.select(prng, population);
// Make a note of the fitness that was chosen
auto fitness = static_cast<std::size_t>(population[choice].fitness());
results[fitness] += 1;
}
for (auto const &[fitness, times_chosen] : results)
{
spdlog::info("Individual with fitness score {} chosen {} of 1000 times ({:.2f}%)", fitness, times_chosen, (static_cast<double>(times_chosen) / spins) * 100);
}
// Given the specified Population and their fitness scores, after 1000 spins of the wheel we expect the each Individual to have been selected the following number of times based on their fitness scores
auto const expected = std::map<int, int>{{1, 104}, {2, 176}, {3, 294}, {4, 426}};
// Check that the results matched what we expected
REQUIRE(results == expected);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Crossover", "[ga][crossover]")
{
// Seed an mt19937 prng for a predictable "random" number to use for testing
auto prng = std::mt19937{42};
// Create a UniformCrossover CrossoverMethod
auto uniform_crossover = ga::UniformCrossover{};
// Create a pair of Chromosomes to use as parents
auto parent_a = ga::Chromosome{{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}};
auto parent_b = ga::Chromosome{{-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0, -10.0}};
// Create a child by using the UniformCrossover method
auto child = uniform_crossover.crossover(prng, parent_a, parent_b);
// A UniformCrossover has an even 50/50 chance that a gene will come from either parent
auto const expected = ga::Chromosome{{-1.0, 2.0, 3.0, -4.0, 5.0, 6.0, 7.0, 8.0, -9.0, -10.0}};
// Check that the results matched what we expected
REQUIRE(child == expected);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Genetic Algorithm", "[ga][genetic_algorithm]")
{
auto selection_method = std::make_unique<ga::RouletteWheelSelection>();
auto crossover_method = std::make_unique<ga::UniformCrossover>();
auto ga = ga::GeneticAlgorithm{std::move(selection_method), std::move(crossover_method)};
REQUIRE(1 == 1);
}
| 36.908397 | 203 | 0.64757 |
efe522521a9e3e7e53b2f14ea3e49ff2c8753433 | 2,690 | cpp | C++ | implementations/ugene/src/plugins/external_tool_support/src/trimmomatic/steps/TrailingStep.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/external_tool_support/src/trimmomatic/steps/TrailingStep.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/external_tool_support/src/trimmomatic/steps/TrailingStep.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "TrailingStep.h"
#include <U2Core/U2SafePoints.h>
#include "trimmomatic/util/QualitySettingsWidget.h"
namespace U2 {
namespace LocalWorkflow {
const QString TrailingStepFactory::ID = "TRAILING";
TrailingStep::TrailingStep()
: TrimmomaticStep(TrailingStepFactory::ID) {
name = "TRAILING";
description = tr("<html><head></head><body>"
"<h4>TRAILING</h4>"
"<p>This step removes low quality bases from the end. As long as a base has "
"a value below this threshold the base is removed and the next base "
"(i.e. the preceding one) will be investigated. This approach can be "
"used removing the special Illumina \"low quality segment\" regions "
"(which are marked with quality score of 2), but SLIDINGWINDOW or MAXINFO "
"are recommended instead.</p>"
"<p>Input the following values:</p>"
"<ul>"
"<li><b>Quality threshold</b>: the minimum quality required to keep a base.</li>"
"</ul>"
"</body></html>");
}
TrimmomaticStepSettingsWidget *TrailingStep::createWidget() const {
return new QualitySettingsWidget(tr("The minimum quality required to keep a base."));
}
QString TrailingStep::serializeState(const QVariantMap &widgetState) const {
return QualitySettingsWidget::serializeState(widgetState);
}
QVariantMap TrailingStep::parseState(const QString &command) const {
return QualitySettingsWidget::parseState(command, id);
}
TrailingStepFactory::TrailingStepFactory()
: TrimmomaticStepFactory(ID) {
}
TrailingStep *TrailingStepFactory::createStep() const {
return new TrailingStep();
}
} // namespace LocalWorkflow
} // namespace U2
| 36.849315 | 102 | 0.67026 |
efe5281be27fba8ce55da7b1321e1d3fdd27f082 | 9,860 | hpp | C++ | naos/includes/kernel/util/str.hpp | kadds/NaOS | ea5eeed6f777b8f62acf3400b185c94131b6e1f0 | [
"BSD-3-Clause"
] | 14 | 2020-02-12T11:07:58.000Z | 2022-02-02T00:05:08.000Z | naos/includes/kernel/util/str.hpp | kadds/NaOS | ea5eeed6f777b8f62acf3400b185c94131b6e1f0 | [
"BSD-3-Clause"
] | null | null | null | naos/includes/kernel/util/str.hpp | kadds/NaOS | ea5eeed6f777b8f62acf3400b185c94131b6e1f0 | [
"BSD-3-Clause"
] | 4 | 2020-02-27T09:53:53.000Z | 2021-11-07T17:43:44.000Z | #pragma once
#include "array.hpp"
#include "assert.hpp"
#include "common.hpp"
#include "hash.hpp"
#include "iterator.hpp"
#include "kernel/mm/allocator.hpp"
#include "formatter.hpp"
#include "memory.hpp"
#include <utility>
namespace util
{
/// \brief compair two string
/// \return 0 if equal
int strcmp(const char *str1, const char *str2);
/// \brief copy src to dst (include \\0) same as 'strcopy(char *, const char *)'
i64 strcopy(char *dst, const char *src, i64 max_len);
/// \brief copy src to dst (include \\0)
/// \param dst copy to
/// \param src copy from
/// \return copy char count (not include \\0)
i64 strcopy(char *dst, const char *src);
/// \brief get string length (not include \\0)
i64 strlen(const char *str);
/// \brief find substring in str
/// \return -1 if not found
i64 strfind(const char *str, const char *pat);
class string;
template <typename CE> class base_string_view
{
private:
struct value_fn
{
CE operator()(CE val) { return val; }
};
struct prev_fn
{
CE operator()(CE val) { return val - 1; }
};
struct next_fn
{
CE operator()(CE val) { return val + 1; }
};
public:
using iterator = base_bidirectional_iterator<CE, value_fn, prev_fn, next_fn>;
base_string_view()
: ptr(nullptr)
, len(0)
{
}
base_string_view(CE ptr, u64 len)
: ptr(ptr)
, len(len)
{
}
CE data() {
return ptr;
}
string to_string(memory::IAllocator *allocator);
iterator begin() { return iterator(ptr); }
iterator end() { return iterator(ptr + len); }
bool to_int(i64 &out) const
{
const char *beg = ptr;
const char *end = ptr + len;
return formatter::str2int(beg, end, out) != beg;
}
bool to_uint(u64 &out) const {
const char *beg = ptr;
const char *end = ptr + len;
return formatter::str2uint(beg, end, out) != beg;
}
bool to_int_ext(i64 &out, base_string_view &last) const {
CE beg = ptr;
CE end = ptr + len;
beg = formatter::str2int(beg, end, out);
last = base_string_view(beg, len - (beg - ptr));
return beg != ptr;
}
bool to_uint_ext(u64 &out, base_string_view &last) const {
CE beg = ptr;
CE end = ptr + len;
beg = const_cast<CE>(formatter::str2uint(beg, end, out));
last = base_string_view(beg, len - (beg - ptr));
return beg != ptr;
}
void split2(base_string_view &v0, base_string_view &v1, iterator iter)
{
v0 = base_string_view(ptr, iter.get() - ptr);
v1 = base_string_view(iter.get() + 1, len - (iter.get() - ptr));
}
array<base_string_view<CE>> split(char c, memory::IAllocator *vec_allocator)
{
array<base_string_view<CE>> vec(vec_allocator);
CE p = ptr;
CE prev = p;
for (u64 i = 0; i < len; i++)
{
if (*p == c)
{
if (prev < p)
{
vec.push_back(base_string_view<CE>(prev, p - prev));
}
prev = p + 1;
}
p++;
}
if (prev < p)
{
vec.push_back(base_string_view<CE>(prev, p - prev));
}
return vec;
}
private:
CE ptr;
u64 len;
};
using string_view = base_string_view<char *>;
using const_string_view = base_string_view<const char *>;
/// \brief kernel string type, use it everywhere
///
class string
{
private:
template <typename N> struct value_fn
{
N operator()(N val) { return val; }
};
template <typename N> struct prev_fn
{
N operator()(N val) { return val - 1; }
};
template <typename N> struct next_fn
{
N operator()(N val) { return val + 1; }
};
using CE = const char *;
using NE = char *;
public:
using const_iterator = base_bidirectional_iterator<CE, value_fn<CE>, prev_fn<CE>, next_fn<CE>>;
using iterator = base_bidirectional_iterator<NE, value_fn<NE>, prev_fn<NE>, next_fn<NE>>;
string(const string &rhs) { copy(rhs); }
string(string &&rhs) { move(std::move(rhs)); }
///\brief init empty string ""
string(memory::IAllocator *allocator);
///\brief init from char array
/// no_shared
string(memory::IAllocator *allocator, const char *str, i64 len = -1) { init(allocator, str, len); }
///\brief init from char array lit
/// readonly & shared
string(const char *str) { init_lit(str); }
~string() { free(); }
string &operator=(const string &rhs);
string &operator=(string &&rhs);
u64 size() const { return get_count(); }
u64 capacity() const
{
if (likely(is_sso()))
{
return stack.get_cap();
}
else
{
return head.get_cap();
}
}
u64 hash() const { return murmur_hash2_64(data(), get_count(), 0); }
iterator begin() { return iterator(data()); }
iterator end() { return iterator(data() + size()); }
const_iterator begin() const { return const_iterator(data()); }
const_iterator end() const { return const_iterator(data() + size()); }
string_view view() { return string_view(data(), size()); }
const_string_view view() const { return const_string_view(data(), size()); }
bool is_shared() const
{
if (likely(is_sso()))
{
return false;
}
else
{
return head.get_allocator() == nullptr;
}
}
char *data()
{
if (likely(is_sso()))
{
return stack.get_buffer();
}
else
{
return head.get_buffer();
}
}
const char *data() const
{
if (likely(is_sso()))
{
return stack.get_buffer();
}
else
{
return head.get_buffer();
}
}
void append(const string &rhs);
void append_buffer(const char *buf, u64 length);
void push_back(char ch);
char pop_back();
void remove_at(u64 index, u64 end_index);
void remove(iterator beg, iterator end)
{
u64 index = beg.get() - data();
u64 index_end = end.get() - data();
remove_at(index, index_end);
}
char at(u64 index) const
{
cassert(index < get_count());
return data()[index];
}
string &operator+=(const string &rhs)
{
append(rhs);
return *this;
}
bool operator==(const string &rhs) const;
bool operator!=(const string &rhs) const { return !operator==(rhs); }
private:
// littel endian machine
// 0x0
// |-----------------|---------------|
// | count(63) | char(64) 8 |
// | flag_shared(1) | |
// |-----------------|---------------|
// | buffer(64) | char(64) 8 |
// |----------------|----------------|
// | cap(63) | char(56) 7 |
// | none(1) | count(5) |
// |----------------|----------------|
// | flag_type(1)0 | flag_type(1)1 |
// | allocator(63) | allocator(63) |
// |----------------|----------------|
// 0x1F
struct head_t
{
u64 count;
char *buffer;
u64 cap;
memory::IAllocator *allocator;
u64 get_count() const { return count & ((1UL << 63) - 1); }
void set_count(u64 c) { count = (c & ((1UL << 63) - 1)) | (count & (1UL << 63)); };
u64 get_cap() const { return cap & ((1UL << 63) - 1); }
void set_cap(u64 c) { cap = (c & ((1UL << 63) - 1)) | (cap & (1UL << 63)); }
char *get_buffer() { return buffer; }
const char *get_buffer() const { return buffer; }
void set_buffer(char *b) { buffer = b; }
memory::IAllocator *get_allocator() const { return allocator; }
void set_allocator(memory::IAllocator *alc)
{
cassert((reinterpret_cast<u64>(alc) & 0x1) == 0); // bit 0
allocator = alc;
}
void init()
{
count = 0;
buffer = nullptr;
cap = 0;
allocator = 0;
}
};
struct stack_t
{
byte data[24];
memory::IAllocator *allocator;
public:
u64 get_count() const { return get_cap() - static_cast<u64>(data[23]); }
void set_count(u64 c) { data[23] = static_cast<byte>(get_cap() - c); }
u64 get_cap() const { return 23; }
char *get_buffer() { return reinterpret_cast<char *>(data); }
const char *get_buffer() const { return reinterpret_cast<const char *>(data); }
memory::IAllocator *get_allocator() const
{
return reinterpret_cast<memory::IAllocator *>(reinterpret_cast<u64>(allocator) & ~0x1);
}
void set_allocator(memory::IAllocator *alc)
{
allocator = reinterpret_cast<memory::IAllocator *>(reinterpret_cast<u64>(alc) | 0x1);
}
bool is_stack() const { return reinterpret_cast<u64>(allocator) & 0x1; }
};
union
{
stack_t stack;
head_t head;
};
static_assert(sizeof(stack_t) == sizeof(head_t));
private:
u64 select_capacity(u64 capacity);
void free();
void copy(const string &rhs);
void move(string &&rhs);
void init(memory::IAllocator *allocator, const char *str, i64 len = -1);
void init_lit(const char *str);
u64 get_count() const
{
if (likely(is_sso()))
return stack.get_count();
else
return head.get_count();
}
private:
bool is_sso() const { return stack.is_stack(); }
};
template <typename CE> string base_string_view<CE>::to_string(memory::IAllocator *allocator)
{
return string(allocator, ptr, len);
}
} // namespace util
| 25.025381 | 103 | 0.535497 |
efe6ee13015e03dd9051e0633494633c358b2e37 | 622 | cc | C++ | code/qttoolkit/contentbrowser/code/main.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/qttoolkit/contentbrowser/code/main.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/qttoolkit/contentbrowser/code/main.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
#include "stdneb.h"
#include "contentbrowserwindow.h"
#include "contentbrowserapp.h"
#include "extlibs/libqimg/qdevilplugin.h"
Q_IMPORT_PLUGIN(qdevil);
//------------------------------------------------------------------------------
/**
*/
int __cdecl
main(int argc, const char** argv)
{
Util::CommandLineArgs args(argc, argv);
ContentBrowser::ContentBrowserApp app;
app.SetCompanyName("gscept");
app.SetAppTitle("NebulaT Content Browser");
app.SetCmdLineArgs(args);
if (app.Open())
{
app.Run();
app.Close();
}
app.Exit();
} | 23.037037 | 80 | 0.530547 |
efec806f461fd802325dd210f9399cbef4211775 | 503 | hpp | C++ | source/ashes/renderer/TestRenderer/Sync/TestEvent.hpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 227 | 2018-09-17T16:03:35.000Z | 2022-03-19T02:02:45.000Z | source/ashes/renderer/TestRenderer/Sync/TestEvent.hpp | DragonJoker/RendererLib | 0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a | [
"MIT"
] | 39 | 2018-02-06T22:22:24.000Z | 2018-08-29T07:11:06.000Z | source/ashes/renderer/TestRenderer/Sync/TestEvent.hpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 8 | 2019-05-04T10:33:32.000Z | 2021-04-05T13:19:27.000Z | /*
This file belongs to Ashes.
See LICENSE file in root folder
*/
#pragma once
#include "renderer/TestRenderer/TestRendererPrerequisites.hpp"
namespace ashes::test
{
class Event
{
public:
Event( VkDevice device );
/**
*\copydoc ashes::Event::getStatus
*/
VkResult getStatus()const;
/**
*\copydoc ashes::Event::getStatus
*/
VkResult set()const;
/**
*\copydoc ashes::Event::getStatus
*/
VkResult reset()const;
private:
mutable VkResult m_status{ VK_EVENT_RESET };
};
}
| 15.71875 | 62 | 0.683897 |
efefffccc5b2dfe52e8eaa70f4732ce12a45df5e | 6,280 | cpp | C++ | src/ui/radio.cpp | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 1 | 2020-07-14T07:29:18.000Z | 2020-07-14T07:29:18.000Z | src/ui/radio.cpp | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 2 | 2019-01-01T22:35:56.000Z | 2022-03-14T07:34:00.000Z | src/ui/radio.cpp | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 2 | 2021-03-07T11:40:42.000Z | 2021-12-26T21:40:39.000Z | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*/
/*
* $Logfile: /Freespace2/code/UI/RADIO.cpp $
* $Revision: 307 $
* $Date: 2010-02-08 09:09:13 +0100 (Mon, 08 Feb 2010) $
* $Author: taylor $
*
* Code to handle radio buttons.
*
* $Log$
* Revision 1.3 2004/09/20 01:31:45 theoddone33
* GCC 3.4 fixes.
*
* Revision 1.2 2002/06/09 04:41:29 relnev
* added copyright header
*
* Revision 1.1.1.1 2002/05/03 03:28:11 root
* Initial import.
*
*
* 4 12/02/98 5:47p Dave
* Put in interface xstr code. Converted barracks screen to new format.
*
* 3 10/13/98 9:29a Dave
* Started neatening up freespace.h. Many variables renamed and
* reorganized. Added AlphaColors.[h,cpp]
*
* 2 10/07/98 10:54a Dave
* Initial checkin.
*
* 1 10/07/98 10:51a Dave
*
* 9 3/10/98 4:19p John
* Cleaned up graphics lib. Took out most unused gr functions. Made D3D
* & Glide have popups and print screen. Took out all >8bpp software
* support. Made Fred zbuffer. Made zbuffer allocate dynamically to
* support Fred. Made zbuffering key off of functions rather than one
* global variable.
*
* 8 2/03/98 4:21p Hoffoss
* Made UI controls draw white text when disabled.
*
* 7 1/14/98 6:44p Hoffoss
* Massive changes to UI code. A lot cleaner and better now. Did all
* this to get the new UI_DOT_SLIDER to work properly, which the old code
* wasn't flexible enough to handle.
*
* 6 6/12/97 12:39p John
* made ui use freespace colors
*
* 5 6/11/97 1:13p John
* Started fixing all the text colors in the game.
*
* 4 5/26/97 10:26a Lawrance
* get slider control working 100%
*
* 3 1/01/97 6:46p Lawrance
* changed text color of radio button to green from black
*
* 2 11/15/96 11:43a John
*
* 1 11/14/96 6:55p John
*
* $NoKeywords: $
*/
#include "uidefs.h"
#include "ui.h"
#include "alphacolors.h"
void UI_RADIO::create(UI_WINDOW *wnd, const char *_text, int _x, int _y, int _state, int _group )
{
int _w, _h;
// gr_get_string_size( &_w, &_h, "X" );
_w = 18;
_h = 18;
if (_text)
text = strdup(_text);
else
text = NULL;
base_create( wnd, UI_KIND_RADIO, _x, _y, _w, _h );
position = 0;
pressed_down = 0;
flag = _state;
group = _group;
};
void UI_RADIO::destroy()
{
if (text)
free(text);
UI_GADGET::destroy();
}
void UI_RADIO::draw()
{
int offset;
if ( uses_bmaps ) {
if ( disabled_flag ) {
if ( flag ) {
if ( bmap_ids[RADIO_DISABLED_MARKED] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DISABLED_MARKED], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
else {
if ( bmap_ids[RADIO_DISABLED_CLEAR] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DISABLED_CLEAR], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
}
else { // not disabled
if ( position == 0 ) { // up
if ( flag ) { // marked
if ( bmap_ids[RADIO_UP_MARKED] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_UP_MARKED], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
else { // not marked
if ( bmap_ids[RADIO_UP_CLEAR] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_UP_CLEAR], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
}
else { // down
if ( flag ) { // marked
if ( bmap_ids[RADIO_DOWN_MARKED] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DOWN_MARKED], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
else { // not marked
if ( bmap_ids[RADIO_DOWN_CLEAR] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DOWN_CLEAR], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
}
}
}
else {
gr_set_font(my_wnd->f_id);
gr_set_clip( x, y, w, h );
if (position == 0 ) {
ui_draw_box_out( 0, 0, w-1, h-1 );
offset = 0;
} else {
ui_draw_box_in( 0, 0, w-1, h-1 );
offset = 1;
}
if (disabled_flag)
gr_set_color_fast(&CDARK_GRAY);
else if (my_wnd->selected_gadget == this)
gr_set_color_fast(&CBRIGHT_GREEN);
else
gr_set_color_fast(&CGREEN);
// if (flag)
// ui_string_centered( Middle(w)+offset, Middle(h)+offset, "*" );
// else
// ui_string_centered( Middle(w)+offset, Middle(h)+offset, "o" );
if (flag) {
gr_circle( Middle(w)+offset, Middle(h)+offset, 8 );
} else {
gr_circle( Middle(w)+offset, Middle(h)+offset, 8 );
gr_set_color_fast( &CWHITE );
gr_circle( Middle(w)+offset, Middle(h)+offset, 4 );
}
if (disabled_flag)
gr_set_color_fast(&CDARK_GRAY);
else if (my_wnd->selected_gadget == this)
gr_set_color_fast(&CBRIGHT_GREEN);
else
gr_set_color_fast(&CGREEN);
if ( text ) {
gr_reset_clip();
gr_string( x+w+4, y+2, text );
}
}
}
void UI_RADIO::process(int focus)
{
int OnMe, oldposition;
if (disabled_flag) {
position = 0;
return;
}
if (my_wnd->selected_gadget == this)
focus = 1;
OnMe = is_mouse_on();
oldposition = position;
if (B1_PRESSED && OnMe) {
position = 1;
} else {
position = 0;
}
if (my_wnd->keypress == hotkey) {
position = 2;
my_wnd->last_keypress = 0;
}
if ( focus && ((my_wnd->keypress == KEY_SPACEBAR) || (my_wnd->keypress == KEY_ENTER)) )
position = 2;
if (focus)
if ( (oldposition == 2) && (keyd_pressed[KEY_SPACEBAR] || keyd_pressed[KEY_ENTER]) )
position = 2;
pressed_down = 0;
if (position) {
if ( (oldposition == 1) && OnMe )
pressed_down = 1;
if ( (oldposition == 2) && focus )
pressed_down = 1;
}
if (pressed_down && user_function) {
user_function();
}
if (pressed_down && (flag == 0)) {
UI_GADGET *tmp = (UI_GADGET *) next;
UI_RADIO *tmpr;
while (tmp != this) {
if (tmp->kind == UI_KIND_RADIO) {
tmpr = (UI_RADIO *) tmp;
if ((tmpr->group == group) && tmpr->flag) {
tmpr->flag = 0;
tmpr->pressed_down = 0;
}
}
tmp = tmp->next;
}
flag = 1;
}
}
int UI_RADIO::changed()
{
return pressed_down;
}
int UI_RADIO::checked()
{
return flag;
}
| 22.269504 | 109 | 0.62086 |
eff0238aa7ff1bec34896371a361d58922c057d1 | 2,097 | cpp | C++ | nori-base-2019/src/lightDepthArea.cpp | TamerMograbi/ShadowNet | 99a9fb4522546e58817bbdd373f63d6996685e21 | [
"BSD-3-Clause"
] | null | null | null | nori-base-2019/src/lightDepthArea.cpp | TamerMograbi/ShadowNet | 99a9fb4522546e58817bbdd373f63d6996685e21 | [
"BSD-3-Clause"
] | null | null | null | nori-base-2019/src/lightDepthArea.cpp | TamerMograbi/ShadowNet | 99a9fb4522546e58817bbdd373f63d6996685e21 | [
"BSD-3-Clause"
] | 1 | 2020-01-22T11:55:43.000Z | 2020-01-22T11:55:43.000Z | #include <nori/integrator.h>
#include <nori/scene.h>
#include <nori/bsdf.h>
NORI_NAMESPACE_BEGIN
class lightDepthAreaIntegrator : public Integrator {
public:
lightDepthAreaIntegrator(const PropertyList &props)
{
}
void preprocess(const Scene *scene)
{
emitterMeshes = scene->getEmitterMeshes();
const MatrixXf vertices = emitterMeshes[0]->getVertexPositions();
for (int colIdx = 0; colIdx < vertices.cols(); colIdx++)
{
meshCenter += vertices.col(colIdx);
}
meshCenter /= vertices.cols();
}
//point x will be visible only if light reaches it
//bool visiblity(const Scene *scene, Point3f x) const
//{
// Vector3f dir = position - x;//direction from point to light source
// dir.normalize();
// Ray3f ray(x, dir);
// return !scene->rayIntersect(ray);//if ray intersects, then it means that it hit another point in the mesh
// //while on it's way to the light source. so x won't recieve light
//}
//scale value x from range [-1,1] to [a,b]
float scaleToAB(float x, float a, float b) const
{
return (b - a)*(x + 1) / 2 + a;
}
Color3f Li(const Scene *scene, Sampler *sampler, const Ray3f &ray) const
{
Intersection its;
if (!scene->rayIntersect(ray, its))
{
return Color3f(0.f);
}
Point3f x = its.p; //where the ray hits the mesh
Vector3f intersectionToLight = (meshCenter - x).normalized();
float scaledX = scaleToAB(intersectionToLight[0], 0, 1);
float scaledY = scaleToAB(intersectionToLight[1], 0, 1);
float scaledZ = scaleToAB(intersectionToLight[2], 0, 1);
//we scale from -1 to 1 (which is the range that the coordinates of a normalized direction can be in) to 0 2
return Color3f(scaledX, scaledY, scaledZ);
}
std::string toString() const {
return "lightDepthAreaIntegrator[]";
}
EIntegratorType getIntegratorType() const
{
return EIntegratorType::ELightDepthArea;
}
std::vector<Mesh *> emitterMeshes;
Point3f meshCenter;
};
NORI_REGISTER_CLASS(lightDepthAreaIntegrator, "lightDepthArea");
NORI_NAMESPACE_END | 29.957143 | 116 | 0.674297 |
eff15b2b488eacb70224936cb68fa4bf82be018a | 14,983 | cc | C++ | MemoryBlock.cc | DrItanium/syn | bee289392e9e84a12d98a4b19f2a0ada9d7ae14a | [
"BSD-2-Clause"
] | 1 | 2017-04-17T14:46:28.000Z | 2017-04-17T14:46:28.000Z | MemoryBlock.cc | DrItanium/syn | bee289392e9e84a12d98a4b19f2a0ada9d7ae14a | [
"BSD-2-Clause"
] | 4 | 2017-03-15T23:28:14.000Z | 2017-10-29T22:48:28.000Z | MemoryBlock.cc | DrItanium/syn | bee289392e9e84a12d98a4b19f2a0ada9d7ae14a | [
"BSD-2-Clause"
] | null | null | null | /**
* @file
* implementation of methods described in ClipsExtensions.h
* @copyright
* syn
* Copyright (c) 2013-2017, Joshua Scoggins and Contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "BaseTypes.h"
#include "ClipsExtensions.h"
#include "Base.h"
#include "ExternalAddressWrapper.h"
#include "MemoryBlock.h"
#include <cstdint>
#include <climits>
#include <sstream>
#include <memory>
#include <map>
#include <iostream>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
extern "C" {
#include "clips.h"
}
namespace syn {
template<typename T>
using Block = T[];
//bool Arg2IsInteger(Environment* env, UDFValue* storage, const std::string& funcStr) noexcept {
// return tryGetArgumentAsInteger(env, funcStr, 2, storage);
//}
//bool Arg2IsSymbol(Environment* env, UDFValue* storage, const std::string& funcStr) noexcept {
// return tryGetArgumentAsSymbol(env, funcStr, 2, storage);
//}
void handleProblem(Environment* env, UDFValue* ret, const syn::Problem& p, const std::string funcErrorPrefix) noexcept {
setBoolean(env, ret, false);
std::stringstream s;
s << "an exception was thrown: " << p.what();
auto str = s.str();
errorMessage(env, "CALL", 2, funcErrorPrefix, str);
}
template<typename Word>
class ManagedMemoryBlock : public ExternalAddressWrapper<Block<Word>> {
public:
static_assert(std::is_integral<Word>::value, "Expected an integral type to be for type Word");
using Address = int64_t;
using WordBlock = Block<Word>;
using Parent = ExternalAddressWrapper<WordBlock>;
using Self = ManagedMemoryBlock;
using Self_Ptr = Self*;
static ManagedMemoryBlock* make(int64_t capacity) noexcept {
return new ManagedMemoryBlock(capacity);
}
using ManagedMemoryBlock_Ptr = ManagedMemoryBlock*;
static void newFunction(UDFContext* context, UDFValue* ret) {
auto* env = context->environment;
try {
UDFValue capacity;
if (!UDFNextArgument(context, MayaType::INTEGER_BIT, &capacity)) {
setBoolean(env, ret, false);
errorMessage(env, "NEW", 1, getFunctionErrorPrefixNew<WordBlock>(), " expected an integer for capacity!");
}
auto cap = getInteger(capacity);
auto idIndex = Self::getAssociatedEnvironmentId(env);
setExternalAddress(env, ret, Self::make(cap), idIndex);
} catch(const syn::Problem& p) {
handleProblem(env, ret, p, getFunctionErrorPrefixNew<WordBlock>());
}
}
enum class MemoryBlockOp {
Populate,
Size,
Type,
Set,
Move,
Swap,
Decrement,
Increment,
Get,
MapWrite,
Count,
};
static std::tuple<MemoryBlockOp, int> getParameters(const std::string& op) noexcept {
static std::map<std::string, std::tuple<MemoryBlockOp, int>> opTranslation = {
{ "populate", std::make_tuple(MemoryBlockOp:: Populate , 1) },
{ "size", std::make_tuple(MemoryBlockOp:: Size , 0) },
{ "type", std::make_tuple(MemoryBlockOp:: Type , 0) },
{ "write", std::make_tuple(MemoryBlockOp:: Set , 2) },
{ "move", std::make_tuple(MemoryBlockOp:: Move , 2) },
{ "swap", std::make_tuple(MemoryBlockOp:: Swap , 2) },
{ "decrement", std::make_tuple(MemoryBlockOp:: Decrement , 1) },
{ "increment", std::make_tuple(MemoryBlockOp:: Increment , 1) },
{ "read", std::make_tuple(MemoryBlockOp:: Get , 1) },
{ "map-write", std::make_tuple(MemoryBlockOp::MapWrite, 2) },
};
static std::tuple<MemoryBlockOp, int> bad;
static bool init = false;
if (!init) {
init = true;
bad = std::make_tuple(syn::defaultErrorState<MemoryBlockOp>, -1);
}
auto result = opTranslation.find(op);
if (result == opTranslation.end()) {
return bad;
} else {
return result->second;
}
}
static bool callFunction(UDFContext* context, UDFValue* theValue, UDFValue* ret) {
UDFValue operation;
if (!UDFNextArgument(context, MayaType::SYMBOL_BIT, &operation)) {
//TODO: put error messages in here
return false;
}
std::string str(getLexeme(&operation));
// translate the op to an enumeration
auto* env = context->environment;
auto result = getParameters(str);
if (syn::isErrorState(std::get<0>(result))) {
setBoolean(context, ret, false);
return false;
//return Parent::callErrorMessageCode3(env, ret, str, " <- unknown operation requested!");
}
MemoryBlockOp op;
int aCount;
setBoolean(env, ret, true);
auto ptr = static_cast<Self_Ptr>(getExternalAddress(theValue));
std::tie(op, aCount) = result;
switch(op) {
case MemoryBlockOp::Type:
Self::setType(context, ret);
break;
case MemoryBlockOp::Size:
setInteger(context, ret, ptr->size());
break;
case MemoryBlockOp::Get:
return ptr->load(env, context, ret);
case MemoryBlockOp::Populate:
return ptr->populate(env, context, ret);
case MemoryBlockOp::Increment:
return ptr->increment(env, context, ret);
case MemoryBlockOp::Decrement:
return ptr->decrement(env, context, ret);
case MemoryBlockOp::Swap:
return ptr->swap(env, context, ret);
case MemoryBlockOp::Move:
return ptr->move(env, context, ret);
case MemoryBlockOp::Set:
return ptr->store(env, context, ret);
case MemoryBlockOp::MapWrite:
return ptr->mapWrite(env, context, ret);
default:
setBoolean(context, ret, false);
//return Parent::callErrorMessageCode3(env, ret, str, "<- legal but unimplemented operation!");
//TODO: add error message
return false;
}
return true;
}
static void registerWithEnvironment(Environment* env, const char* title) {
Parent::registerWithEnvironment(env, title, callFunction, newFunction);
}
static void registerWithEnvironment(Environment* env) {
registerWithEnvironment(env, Parent::getType().c_str());
}
public:
ManagedMemoryBlock(Address capacity) : Parent(std::move(std::make_unique<WordBlock>(capacity))), _capacity(capacity) { }
inline Address size() const noexcept { return _capacity; }
inline bool legalAddress(Address idx) const noexcept { return addressInRange<Address>(_capacity, idx); }
inline Word getMemoryCellValue(Address addr) noexcept { return this->_value.get()[addr]; }
inline void setMemoryCell(Address addr0, Word value) noexcept { this->_value.get()[addr0] = value; }
inline void swapMemoryCells(Address addr0, Address addr1) noexcept { syn::swap<Word>(this->_value.get()[addr0], this->_value.get()[addr1]); }
inline void decrementMemoryCell(Address address) noexcept { --this->_value.get()[address]; }
inline void incrementMemoryCell(Address address) noexcept { ++this->_value.get()[address]; }
inline void copyMemoryCell(Address from, Address to) noexcept {
auto ptr = this->_value.get();
ptr[to] = ptr[from];
}
inline void setMemoryToSingleValue(Word value) noexcept {
auto ptr = this->_value.get();
for (Address i = 0; i < _capacity; ++i) {
ptr[i] = value;
}
}
private:
bool extractInteger(UDFContext* context, UDFValue& storage) noexcept {
if (!UDFNextArgument(context, MayaType::INTEGER_BIT, &storage)) {
// TODO: put error message here
return false;
}
return true;
}
bool defaultSingleOperationBody(Environment* env, UDFContext* context, UDFValue* ret, std::function<bool(Environment*, UDFContext*, UDFValue*, Address)> body) noexcept {
UDFValue address;
if (!extractInteger(context, address)) {
setBoolean(env, ret, false);
return false;
}
auto value = static_cast<Address>(getInteger(address));
if (!legalAddress(value)) {
// TODO: insert error message here about illegal address
setBoolean(env, ret, false);
return false;
}
return body(env, context, ret, value);
}
bool defaultTwoOperationBody(Environment* env, UDFContext* context, UDFValue* ret, std::function<bool(Environment*, UDFContext*, UDFValue*, Address, Address)> body) noexcept {
UDFValue address, address2;
if (!extractInteger(context, address)) {
setBoolean(env, ret, false);
return false;
}
if (!extractInteger(context, address2)) {
setBoolean(env, ret, false);
return false;
}
auto addr0 = static_cast<Address>(getInteger(address));
auto addr1 = static_cast<Address>(getInteger(address2));
if (!legalAddress(addr0) || !legalAddress(addr1)) {
setBoolean(env, ret, false);
return false;
}
return body(env, context, ret, addr0, addr1);
}
public:
bool populate(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
UDFValue value;
if (!extractInteger(context, value)) {
setBoolean(env, ret, false);
return false;
}
auto population = static_cast<Word>(getInteger(value));
setMemoryToSingleValue(population);
setBoolean(env, ret, true);
return true;
}
bool load(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultSingleOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto address) noexcept {
setInteger(env, ret, this->getMemoryCellValue(address));
return true;
});
}
bool increment(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultSingleOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto address) noexcept {
this->incrementMemoryCell(address);
setBoolean(env, ret, true);
return true;
});
}
bool decrement(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultSingleOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto address) noexcept {
this->decrementMemoryCell(address);
setBoolean(env, ret, true);
return true;
});
}
bool swap(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultTwoOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto addr0, auto addr1) noexcept {
this->swapMemoryCells(addr0, addr1);
setBoolean(env, ret, true);
return true;
});
}
bool move(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultTwoOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto from, auto to) noexcept {
this->copyMemoryCell(from, to);
setBoolean(env, ret, true);
return true;
});
}
bool store(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
UDFValue address, value;
if (!extractInteger(context, address)) {
setBoolean(env, ret, false);
return false;
}
if (!extractInteger(context, value)) {
setBoolean(env, ret, false);
return false;
}
auto addr = static_cast<Address>(getInteger(address));
if (!legalAddress(addr)) {
setBoolean(env, ret, false);
return false;
}
auto data = static_cast<Word>(getInteger(value));
this->setMemoryCell(addr, data);
setBoolean(env, ret, true);
return true;
}
bool mapWrite(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
UDFValue startingAddress;
if (!extractInteger(context, startingAddress)) {
setBoolean(env, ret, false);
return false;
}
auto addr = static_cast<Address>(getInteger(startingAddress));
while(UDFHasNextArgument(context)) {
if (!legalAddress(addr)) {
setBoolean(env, ret, false);
return false;
}
UDFValue currentItem;
if (!extractInteger(context, currentItem)) {
setBoolean(env, ret, false);
return false;
}
auto data = static_cast<Word>(getInteger(currentItem));
this->setMemoryCell(addr, data);
++addr;
}
setBoolean(env, ret, true);
return true;
}
private:
Address _capacity;
};
DefWrapperSymbolicName(Block<int64_t>, "memory-block");
using StandardManagedMemoryBlock = ManagedMemoryBlock<int64_t>;
#ifndef ENABLE_EXTENDED_MEMORY_BLOCKS
#define ENABLE_EXTENDED_MEMORY_BLOCKS 0
#endif // end ENABLE_EXTENDED_MEMORY_BLOCKS
#if ENABLE_EXTENDED_MEMORY_BLOCKS
#define DefMemoryBlock(name, type, alias) \
DefWrapperSymbolicName(Block< type > , name ); \
using alias = ManagedMemoryBlock< type >
DefMemoryBlock("memory-block:uint8", uint8, ManagedMemoryBlock_uint8);
DefMemoryBlock("memory-block:uint16", uint16, ManagedMemoryBlock_uint16);
DefMemoryBlock("memory-block:uint32", uint32, ManagedMemoryBlock_uint32);
DefMemoryBlock("memory-block:int32", int32, ManagedMemoryBlock_int32);
DefMemoryBlock("memory-block:int16", int16, ManagedMemoryBlock_int16);
DefMemoryBlock("memory-block:int8", int8, ManagedMemoryBlock_int8);
#undef DefMemoryBlock
#endif // end ENABLE_EXTENDED_MEMORY_BLOCKS
void installMemoryBlockTypes(Environment* theEnv) {
StandardManagedMemoryBlock::registerWithEnvironment(theEnv);
#if ENABLE_EXTENDED_MEMORY_BLOCKS
ManagedMemoryBlock_uint8::registerWithEnvironment(theEnv);
ManagedMemoryBlock_uint16::registerWithEnvironment(theEnv);
ManagedMemoryBlock_uint32::registerWithEnvironment(theEnv);
ManagedMemoryBlock_int8::registerWithEnvironment(theEnv);
ManagedMemoryBlock_int16::registerWithEnvironment(theEnv);
ManagedMemoryBlock_int32::registerWithEnvironment(theEnv);
#endif // end ENABLE_EXTENDED_MEMORY_BLOCKS
}
}
| 38.319693 | 178 | 0.680705 |
eff414eb37b93f36a5e9cd4a7a03fea2fdf00899 | 4,837 | hpp | C++ | libs/Core/include/argos-Core/Syntax/SyntaxParenthesizedExpression.hpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | null | null | null | libs/Core/include/argos-Core/Syntax/SyntaxParenthesizedExpression.hpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | 19 | 2021-12-01T20:37:23.000Z | 2022-02-14T21:05:43.000Z | libs/Core/include/argos-Core/Syntax/SyntaxParenthesizedExpression.hpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | null | null | null | #ifndef ARGOS_CORE_SYNTAX_SYNTAXPARENTHESIZEDEXPRESSION_H
#define ARGOS_CORE_SYNTAX_SYNTAXPARENTHESIZEDEXPRESSION_H
#include <string>
#include "argos-Core/argos_global.hpp"
#include "argos-Core/Syntax/ExpressionKinds.hpp"
#include "argos-Core/Syntax/ISyntaxParenthesizedExpression.hpp"
#include "argos-Core/Syntax/SyntaxExpression.hpp"
#include "argos-Core/Syntax/SyntaxVariant.hpp"
#include "argos-Core/Types.hpp"
namespace argos::Core::Syntax
{
class ISyntaxExpression;
class ISyntaxToken;
/**
* @brief Base class implementation for <code>ISyntaxParenthesizedExpression</code>.
*/
class ARGOS_CORE_API SyntaxParenthesizedExpression : public virtual ISyntaxParenthesizedExpression,
public SyntaxExpression
{
public:
SyntaxParenthesizedExpression() = delete;
/**
* @brief Creates a <code>SyntaxParenthesizedExpression</code> instance.
* @param expressionKind The <code>ExpressionKind</code> of the <code>SyntaxParenthesizedExpression</code>.
* @param openParenthesisToken The left sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
* @param expression The <code>ISyntaxExpression</code> in the parenthesized expression.
* @param closeParenthesisToken The right sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
*/
explicit SyntaxParenthesizedExpression(ExpressionKind expressionKind,
const ISyntaxToken* openParenthesisToken,
const ISyntaxExpression* expression,
const ISyntaxToken* closeParenthesisToken) noexcept;
~SyntaxParenthesizedExpression() noexcept override = default;
/**
* @brief Returns the children count of the parenthesized expression.
* @return The children count of the parenthesized expression.
*/
argos_size childCount() const noexcept override;
/**
* @brief Returns the child item of the parenthesized expression at the given <code>index</code>.
* @param index The index for which a child item will be returned.
* @return The child item of the parenthesized expression at the given <code>index</code>.
*/
SyntaxVariant child(argos_size index) const noexcept final;
/**
* @brief Returns the first child item of the parenthesized expression.
* @return The first child item of the parenthesized expression.
*/
SyntaxVariant first() const noexcept override;
/**
* @brief Returns the last child item of the parenthesized expression.
* @return The last child item of the parenthesized expression.
*/
SyntaxVariant last() const noexcept override;
/**
* @brief Returns a string representation of theparenthesized expression with basic data.
* @return A string representation of the parenthesized expression with basic data.
*/
std::string toString() const noexcept override;
/**
* @brief Returns a short string representation of the parenthesized expression with basic data.
* @return A short string representation of the parenthesized expression with basic data.
*/
std::string toShortString() const noexcept override;
/**
* @brief Returns the type name (e.g. the specific class name) of the parenthesized expression.
* @return The type name (e.g. the specific class name) of the parenthesized expression.
*/
std::string typeName() const noexcept override;
/**
* @brief Returns whether the expression is a parenthesized expression.
* @return Returns true.
*/
bool isParenthesizedExpression() const noexcept final;
/**
* @brief Returns the left sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
* @return The left sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
*/
const ISyntaxToken* openParenthesisToken() const noexcept final;
/**
* @brief Returns the <code>ISyntaxExpression</code> in the parenthesized expression.
* @return The <code>ISyntaxExpression</code> in the parenthesized expression.
*/
const ISyntaxExpression* expression() const noexcept final;
/**
* @brief Returns the right sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
* @return The right sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
*/
const ISyntaxToken* closeParenthesisToken() const noexcept final;
protected:
const ISyntaxToken* _openParenthesisToken;
const ISyntaxExpression* _expression;
const ISyntaxToken* _closeParenthesisToken;
};
} // end namespace argos::Core::Syntax
#endif // ARGOS_CORE_SYNTAX_SYNTAXBINARYEXPRESSION_H
| 40.991525 | 127 | 0.716767 |
56028334e37554e54761bca0249086aeb90bb51b | 2,091 | cc | C++ | services/ui/ws/window_server_test_impl.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | services/ui/ws/window_server_test_impl.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | services/ui/ws/window_server_test_impl.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 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 "services/ui/ws/window_server_test_impl.h"
#include "services/ui/public/interfaces/window_tree.mojom.h"
#include "services/ui/ws/server_window.h"
#include "services/ui/ws/window_server.h"
#include "services/ui/ws/window_tree.h"
namespace ui {
namespace ws {
WindowServerTestImpl::WindowServerTestImpl(WindowServer* window_server)
: window_server_(window_server) {}
WindowServerTestImpl::~WindowServerTestImpl() {}
void WindowServerTestImpl::OnSurfaceActivated(
const std::string& name,
EnsureClientHasDrawnWindowCallback cb,
ServerWindow* window) {
// This api is used to detect when a client has painted once, which is
// dictated by whether there is a CompositorFrameSink.
WindowTree* tree = window_server_->GetTreeWithClientName(name);
if (tree && tree->HasRoot(window) &&
window->has_created_compositor_frame_sink()) {
std::move(cb).Run(true);
} else {
// No tree with the given name, or it hasn't painted yet. Install a callback
// for the next time a client creates a CompositorFramesink.
InstallCallback(name, std::move(cb));
}
}
void WindowServerTestImpl::InstallCallback(
const std::string& client_name,
EnsureClientHasDrawnWindowCallback cb) {
window_server_->SetSurfaceActivationCallback(
base::BindOnce(&WindowServerTestImpl::OnSurfaceActivated,
base::Unretained(this), client_name, std::move(cb)));
}
void WindowServerTestImpl::EnsureClientHasDrawnWindow(
const std::string& client_name,
EnsureClientHasDrawnWindowCallback callback) {
WindowTree* tree = window_server_->GetTreeWithClientName(client_name);
if (tree) {
for (const ServerWindow* window : tree->roots()) {
if (window->has_created_compositor_frame_sink()) {
std::move(callback).Run(true);
return;
}
}
}
InstallCallback(client_name, std::move(callback));
}
} // namespace ws
} // namespace ui
| 33.725806 | 80 | 0.730751 |
56043e77013eda58e4eb07859c1cba7299bfe06d | 11,642 | cpp | C++ | tries/TST/lib/TST.cpp | hpaucar/datastructures-ii-repo | 203dbafcd4bb82a4214f93e21f15b3be89cea76c | [
"MIT"
] | null | null | null | tries/TST/lib/TST.cpp | hpaucar/datastructures-ii-repo | 203dbafcd4bb82a4214f93e21f15b3be89cea76c | [
"MIT"
] | null | null | null | tries/TST/lib/TST.cpp | hpaucar/datastructures-ii-repo | 203dbafcd4bb82a4214f93e21f15b3be89cea76c | [
"MIT"
] | null | null | null | // Copyright 2015 Maitesin
#include <string>
#include <vector>
#include <iostream>
#include "./TST.h"
template <class T> const T &TST::tst<T>::find(const std::string &key) {
node_ptr node(find(root, key, 0));
if (node != nullptr) {
aux_ret = node->value;
node.release();
return aux_ret;
} else {
return def;
}
}
template <class T>
typename TST::tst<T>::node_ptr
TST::tst<T>::find(TST::tst<T>::node_ptr &n, const std::string &key, size_t d) {
if (key.size() == d + 1) {
if (n == nullptr)
return nullptr;
else {
if (n->c > key[d] && n->left != nullptr) {
return find(n->left, key, d);
}
if (n->c == key[d]) {
if (n->value != def)
return node_ptr(n.get());
else
return nullptr;
}
if (n->c < key[d] && n->right != nullptr) {
return find(n->right, key, d);
}
}
} else {
if (n != nullptr) {
if (n->c > key[d] && n->left != nullptr) {
return find(n->left, key, d);
}
if (n->c == key[d])
return find(n->middle, key, d + 1);
if (n->c < key[d] && n->right != nullptr) {
return find(n->right, key, d);
}
}
}
return nullptr;
}
template <class T>
void TST::tst<T>::insert(const std::string &key, const T &value) {
if (key == "")
return;
if (root == nullptr)
root = node_ptr(new node(key[0]));
bool created = false;
root = insert(std::move(root), key, value, 0, created);
if (created)
++s;
}
template <class T>
typename TST::tst<T>::node_ptr
TST::tst<T>::insert(TST::tst<T>::node_ptr n, const std::string &key,
const T &value, size_t d, bool &created) {
if (key.size() == d + 1) {
if (n->c > key[d]) {
if (n->left == nullptr)
n->left = node_ptr(new node(key[d]));
n->left = insert(std::move(n->left), key, value, d, created);
}
if (n->c == key[d]) {
if (n->value == def)
created = true;
n->value = value;
}
if (n->c < key[d]) {
if (n->right == nullptr)
n->right = node_ptr(new node(key[d]));
n->right = insert(std::move(n->right), key, value, d, created);
}
return n;
} else {
if (n->c > key[d]) {
if (n->left == nullptr)
n->left = node_ptr(new node(key[d]));
n->left = insert(std::move(n->left), key, value, d, created);
}
if (n->c == key[d]) {
if (n->middle == nullptr)
n->middle = node_ptr(new node(key[d + 1]));
n->middle = insert(std::move(n->middle), key, value, d + 1, created);
}
if (n->c < key[d]) {
if (n->right == nullptr)
n->right = node_ptr(new node(key[d]));
n->right = insert(std::move(n->right), key, value, d, created);
}
return n;
}
}
template <class T> void TST::tst<T>::clear(TST::tst<T>::node_ptr n) {
if (n->left != nullptr)
clear(std::move(n->left));
if (n->middle != nullptr)
clear(std::move(n->middle));
if (n->right != nullptr)
clear(std::move(n->right));
n.reset();
}
template <class T> bool TST::tst<T>::contains(const std::string &key) {
return root != nullptr ? contains(root, key, 0) : false;
}
template <class T>
bool TST::tst<T>::contains(TST::tst<T>::node_ptr &n, const std::string &key,
size_t d) {
if (key.size() == d + 1) {
if (n == nullptr)
return false;
if (n->c > key[d] && n->left != nullptr) {
return contains(n->left, key, d);
}
if (n->c == key[d]) {
return n->value != def;
}
if (n->c < key[d] && n->right != nullptr) {
return contains(n->right, key, d);
}
} else {
if (n->c > key[d] && n->left != nullptr) {
return contains(n->left, key, d);
}
if (n->c == key[d]) {
if (n->middle != nullptr)
return contains(n->middle, key, d + 1);
return false;
}
if (n->c < key[d] && n->right != nullptr) {
return contains(n->right, key, d);
}
}
return false;
}
template <class T> void TST::tst<T>::erase(const std::string &key) {
bool decrease = false;
if (root != nullptr) {
erase(root, key, 0, decrease);
}
if (decrease)
--s;
}
template <class T>
bool TST::tst<T>::erase(TST::tst<T>::node_ptr &n, const std::string &key,
size_t d, bool &decrease) {
if (key.size() == d + 1 && n != nullptr) {
if (n->left != nullptr && n->c > key[d]) {
if (n->left->c == key[d]) {
bool deleted = erase(n->left, key, d, decrease);
if (deleted) {
n->left.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->left, key, d, decrease);
}
}
if (n->c == key[d]) {
if (n->value != def)
decrease = true;
n->value = T();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr)
return true;
}
if (n->right != nullptr && n->c < key[d]) {
if (n->right->c == key[d]) {
bool deleted = erase(n->right, key, d, decrease);
if (deleted) {
n->right.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->right, key, d, decrease);
}
}
} else {
if (n->left != nullptr && n->c > key[d]) {
if (n->left->c == key[d]) {
bool deleted = erase(n->left, key, d, decrease);
if (deleted) {
n->left.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->left, key, d, decrease);
}
}
if (n->middle != nullptr && n->c == key[d]) {
bool deleted = erase(n->middle, key, d + 1, decrease);
if (deleted) {
n->middle.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
}
if (n->right != nullptr && n->c < key[d]) {
if (n->right->c == key[d]) {
bool deleted = erase(n->right, key, d, decrease);
if (deleted) {
n->middle.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
}
if (n->right != nullptr && n->c < key[d]) {
if (n->right->c == key[d]) {
bool deleted = erase(n->right, key, d, decrease);
if (deleted) {
n->right.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->right, key, d, decrease);
}
} else {
return erase(n->right, key, d, decrease);
}
}
}
return false;
}
template <class T>
std::vector<std::string> TST::tst<T>::keys(const std::string &prefix) {
vec_ptr vec;
vec = vec_ptr(new std::vector<std::string>());
keys(root, prefix, 0, vec);
return *vec;
}
template <class T>
void TST::tst<T>::keys(TST::tst<T>::node_ptr &n, std::string prefix, size_t d,
TST::tst<T>::vec_ptr &v) {
if (prefix.size() <= d + 1) {
if (prefix.size() == d + 1) {
if (n->c > prefix[d] && n->left != nullptr)
keys(n->left, prefix, d, v);
if (n->c == prefix[d]) {
if (n->value != def)
v->push_back(prefix);
gather_keys(n->middle, prefix, v);
}
if (n->c < prefix[d] && n->right != nullptr)
keys(n->right, prefix, d, v);
} else
gather_keys(n, prefix, v);
} else {
if (n->c > prefix[d] && n->left != nullptr) {
keys(n->left, prefix, d, v);
}
if (n->c == prefix[d] && n->middle != nullptr)
keys(n->middle, prefix, d + 1, v);
if (n->c < prefix[d] && n->right != nullptr) {
keys(n->right, prefix, d, v);
}
}
}
template <class T>
void TST::tst<T>::gather_keys(TST::tst<T>::node_ptr &n, std::string prefix,
TST::tst<T>::vec_ptr &v) {
if (n == nullptr)
return;
if (n->value != def) {
v->push_back(prefix + n->c);
}
gather_keys(n->left, prefix, v);
gather_keys(n->middle, prefix + n->c, v);
gather_keys(n->right, prefix, v);
}
template <class T> void TST::tst<T>::show() {
std::cout << "digraph graphName{" << std::endl;
std::cout << "node [shape=record];" << std::endl;
// Node labels
size_t label = 0;
std::cout << label << " [shape=record,label=\"{ <data> " << root->c
<< " | {<left> l | <middle> m | <right> r}}\"];" << std::endl;
if (root->left != nullptr) {
++label;
show_label(root->left, label);
}
if (root->middle != nullptr) {
++label;
show_label(root->middle, label);
}
if (root->right != nullptr) {
++label;
show_label(root->right, label);
}
// Node hierarchy
label = 0;
if (root->left != nullptr) {
std::cout << "0:left"
<< "->";
++label;
show(root->left, label);
}
if (root->middle != nullptr) {
std::cout << "0:middle"
<< "->";
++label;
show(root->middle, label);
}
if (root->right != nullptr) {
std::cout << "0:right"
<< "->";
++label;
show(root->right, label);
}
std::cout << "}" << std::endl;
}
template <class T>
void TST::tst<T>::show_label(TST::tst<T>::node_ptr &n, size_t &label) {
std::cout << label << " [shape=record,label=\"{<data> " << n->c;
if (n->value != T())
std::cout << " | <value> " << n->value;
std::cout << " | {<left> l | <middle> m | <right> r}}\"";
if (n->value != T())
std::cout << "color=\"blue\"";
std::cout << "];" << std::endl;
if (n->left != nullptr) {
++label;
show_label(n->left, label);
}
if (n->middle != nullptr) {
++label;
show_label(n->middle, label);
}
if (n->right != nullptr) {
++label;
show_label(n->right, label);
}
}
template <class T>
void TST::tst<T>::show(TST::tst<T>::node_ptr &n, size_t &label) {
std::cout << label << ":data" << std::endl;
size_t copy_label = label;
if (n->left != nullptr) {
std::cout << copy_label << ":left"
<< "->";
++label;
show(n->left, label);
}
if (n->middle != nullptr) {
std::cout << copy_label << ":middle"
<< "->";
++label;
show(n->middle, label);
}
if (n->right != nullptr) {
std::cout << copy_label << ":right"
<< "->";
++label;
show(n->right, label);
}
}
template <class T> std::string TST::tst<T>::lcp() {
return lcp_clean_before(root);
}
template <class T>
std::string TST::tst<T>::lcp_clean_before(TST::tst<T>::node_ptr &n) {
if (n == nullptr) {
return "";
}
if (n->middle == nullptr) {
if (n->left == nullptr && n->right != nullptr) {
return lcp_clean_before(n->right);
} else if (n->left != nullptr && n->right == nullptr) {
return lcp_clean_before(n->left);
} else if (n->left == nullptr && n->right == nullptr) {
return "";
}
} else {
return lcp(n, "");
}
return "";
}
template <class T>
std::string TST::tst<T>::lcp(TST::tst<T>::node_ptr &n, std::string s) {
if (n != nullptr
&& n->left == nullptr
&& n->right == nullptr) {
return lcp(n->middle, s + n->c);
}
return s;
}
| 26.459091 | 79 | 0.49038 |
5605cbbccd04885598aebbc1699203f68164d32b | 20,333 | cpp | C++ | net/ias/mmc/nap/iasstringattributeeditor.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/ias/mmc/nap/iasstringattributeeditor.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/ias/mmc/nap/iasstringattributeeditor.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //////////////////////////////////////////////////////////////////////////////
/*++
Copyright (C) Microsoft Corporation, 1998 - 1999
Module Name:
IASStringAttributeEditor.cpp
Abstract:
Implementation file for the CIASStringAttributeEditor class.
Revision History:
mmaguire 06/25/98 - created
--*/
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// BEGIN INCLUDES
//
// standard includes:
//
#include "Precompiled.h"
//
// where we can find declaration for main class in this file:
//
#include "IASStringAttributeEditor.h"
//
// where we can find declarations needed in this file:
//
#include "IASStringEditorPage.h"
#include "iashelper.h"
//
// END INCLUDES
//////////////////////////////////////////////////////////////////////////////
BYTE PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD[] = {0,0,0,0};
UINT PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 4;
UINT PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 3; // 0 based index -- the fourth byte
UINT PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 1; // one byte
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::ShowEditor
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::ShowEditor( /*[in, out]*/ BSTR *pReserved )
{
TRACE(_T("CIASStringAttributeEditor::ShowEditor\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
HRESULT hr = S_OK;
try
{
// Load page title.
// ::CString strPageTitle;
// strPageTitle.LoadString(IDS_IAS_IP_EDITOR_TITLE);
//
// CPropertySheet propSheet( (LPCTSTR)strPageTitle );
//
// IP Address Editor
//
CIASPgSingleAttr cppPage;
// Initialize the page's data exchange fields with info from IAttributeInfo
CComBSTR bstrName;
CComBSTR bstrSyntax;
ATTRIBUTESYNTAX asSyntax = IAS_SYNTAX_OCTETSTRING;
ATTRIBUTEID Id = ATTRIBUTE_UNDEFINED;
if( m_spIASAttributeInfo )
{
hr = m_spIASAttributeInfo->get_AttributeName( &bstrName );
if( FAILED(hr) ) throw hr;
hr = m_spIASAttributeInfo->get_SyntaxString( &bstrSyntax );
if( FAILED(hr) ) throw hr;
hr = m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if( FAILED(hr) ) throw hr;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) throw hr;
}
cppPage.m_strAttrName = bstrName;
cppPage.m_AttrSyntax = asSyntax;
cppPage.m_nAttrId = Id;
cppPage.m_strAttrFormat = bstrSyntax;
// Attribute type is actually attribute ID in string format
WCHAR szTempId[MAX_PATH];
wsprintf(szTempId, _T("%ld"), Id);
cppPage.m_strAttrType = szTempId;
// Initialize the page's data exchange fields with info from VARIANT value passed in.
if ( V_VT(m_pvarValue) != VT_EMPTY )
{
EStringType sp;
CComBSTR bstrTemp;
get_ValueAsStringEx( &bstrTemp, &sp );
cppPage.m_strAttrValue = bstrTemp;
cppPage.m_OctetStringType = sp;
}
// propSheet.AddPage(&cppPage);
// int iResult = propSheet.DoModal();
int iResult = cppPage.DoModal();
if (IDOK == iResult)
{
CComBSTR bstrTemp = (LPCTSTR)cppPage.m_strAttrValue;
put_ValueAsStringEx( bstrTemp, cppPage.m_OctetStringType);
}
else
{
hr = S_FALSE;
}
//
// delete the property page pointer
//
// propSheet.RemovePage(&cppPage);
}
catch( HRESULT & hr )
{
return hr;
}
catch(...)
{
return hr = E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::SetAttributeValue
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::SetAttributeValue(VARIANT * pValue)
{
TRACE(_T("CIASStringAttributeEditor::SetAttributeValue\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
// Check for preconditions.
if( ! pValue )
{
return E_INVALIDARG;
}
// From Baogang's old code, it appears that this editor should accept
// either VT_BSTR, VT_BOOL, VT_I4 or VT_EMPTY.
if( V_VT(pValue) != VT_BSTR
&& V_VT(pValue) != VT_BOOL
&& V_VT(pValue) != VT_I4
&& V_VT(pValue) != VT_EMPTY
&& V_VT(pValue) != (VT_ARRAY | VT_UI1))
{
return E_INVALIDARG;
}
m_pvarValue = pValue;
return S_OK;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::get_ValueAsString
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::get_ValueAsString(BSTR * pbstrDisplayText )
{
TRACE(_T("CIASStringAttributeEditor::get_ValueAsString\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
// Check for preconditions.
if( ! pbstrDisplayText )
{
return E_INVALIDARG;
}
if( ! m_spIASAttributeInfo || ! m_pvarValue )
{
// We are not initialized properly.
return OLE_E_BLANK;
}
HRESULT hr = S_OK;
try
{
CComBSTR bstrDisplay;
VARTYPE vType = V_VT(m_pvarValue);
switch( vType )
{
case VT_BOOL:
{
if( V_BOOL(m_pvarValue) )
{
// ISSUE: This is not localizable!!!
// Should it be? Ask Ashwin about this as some of
// Baogang's error checking code was specifically looking
// for either hardcoded "TRUE" or "FALSE".
// ISSUE: I think that for Boolean syntax attributes,
// we should be popping up the same type of attribute
// editor as for the enumerables only with TRUE and FALSE in it.
bstrDisplay = L"TRUE";
}
else
{
bstrDisplay = L"FALSE";
}
}
break;
case VT_I4:
{
// The variant is some type which must be coerced to a bstr.
CComVariant varValue;
// Make sure you pass a VT_EMPTY variant to VariantChangeType
// or it will assert.
// So don't do: V_VT(&varValue) = VT_BSTR;
hr = VariantChangeType(&varValue, m_pvarValue, VARIANT_NOVALUEPROP, VT_BSTR);
if( FAILED( hr ) ) throw hr;
bstrDisplay = V_BSTR(&varValue);
}
break;
case VT_BSTR:
bstrDisplay = V_BSTR(m_pvarValue);
break;
case VT_UI1 | VT_ARRAY: // Treat as Octet string
{
EStringType t;
return get_ValueAsStringEx(pbstrDisplayText, &t);
}
break;
default:
// need to check what is happening here,
ASSERT(0);
break;
case VT_EMPTY:
// do nothing -- we will fall through and return a blank string.
break;
}
*pbstrDisplayText = bstrDisplay.Copy();
}
catch( HRESULT &hr )
{
return hr;
}
catch(...)
{
return E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::put_ValueAsString
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::put_ValueAsString(BSTR newVal)
{
TRACE(_T("CIASStringAttributeEditor::put_ValueAsString\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
if( ! m_pvarValue )
{
// We are not initialized properly.
return OLE_E_BLANK;
}
if( m_spIASAttributeInfo == NULL )
{
// We are not initialized properly.
return OLE_E_BLANK;
}
HRESULT hr = S_OK;
try
{
CComBSTR bstrTemp = newVal;
CComVariant varValue;
V_VT(&varValue) = VT_BSTR;
V_BSTR(&varValue) = bstrTemp.Copy();
VARTYPE vType = V_VT(m_pvarValue);
// Initialize the variant that was passed in.
VariantClear(m_pvarValue);
{
ATTRIBUTESYNTAX asSyntax;
hr = m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if( FAILED(hr) ) throw hr;
// if this Octet string, this should be BSTR, no matter what it was before.
if(asSyntax == IAS_SYNTAX_OCTETSTRING)
vType = VT_BSTR;
if ( VT_EMPTY == vType)
{
// decide the value type:
switch (asSyntax)
{
case IAS_SYNTAX_BOOLEAN:
vType = VT_BOOL;
break;
case IAS_SYNTAX_INTEGER:
case IAS_SYNTAX_UNSIGNEDINTEGER:
case IAS_SYNTAX_ENUMERATOR:
case IAS_SYNTAX_INETADDR:
vType = VT_I4;
break;
case IAS_SYNTAX_STRING:
case IAS_SYNTAX_UTCTIME:
case IAS_SYNTAX_PROVIDERSPECIFIC:
case IAS_SYNTAX_OCTETSTRING:
vType = VT_BSTR;
break;
default:
_ASSERTE(FALSE);
vType = VT_BSTR;
break;
}
}
}
hr = VariantChangeType(m_pvarValue, &varValue, VARIANT_NOVALUEPROP, vType);
if( FAILED( hr ) ) throw hr;
}
catch( HRESULT &hr )
{
return hr;
}
catch(...)
{
return E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::get_ValueAsStringEx
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::get_ValueAsStringEx(BSTR * pbstrDisplayText, EStringType* pType )
{
TRACE(_T("CIASStringAttributeEditor::get_ValueAsString\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
ATTRIBUTESYNTAX asSyntax;
m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if(asSyntax != IAS_SYNTAX_OCTETSTRING)
{
if(pType)
*pType = STRING_TYPE_NORMAL;
return get_ValueAsString(pbstrDisplayText);
}
// only care about IAS_SYNTAX_OCTETSTRING
ASSERT(pType);
VARTYPE vType = V_VT(m_pvarValue);
SAFEARRAY* psa = NULL;
HRESULT hr = S_OK;
switch(vType)
{
case VT_ARRAY | VT_UI1:
psa = V_ARRAY(m_pvarValue);
break;
case VT_EMPTY:
if(pType)
*pType = STRING_TYPE_NULL;
return get_ValueAsString(pbstrDisplayText);
break;
case VT_BSTR:
if(pType)
*pType = STRING_TYPE_NORMAL;
return get_ValueAsString(pbstrDisplayText);
break;
default:
ASSERT(0); // should not happen, should correct some code
if(pType)
*pType = STRING_TYPE_NORMAL;
return get_ValueAsString(pbstrDisplayText);
break;
};
// no data is available , or the safe array is not valid, don't intepret the string
if(psa == NULL || psa->cDims != 1 || psa->cbElements != 1)
{
*pType = STRING_TYPE_NULL;
return hr;
}
// need to figure out how to convert the binary to text
char* pData = NULL;
int nBytes = 0;
WCHAR* pWStr = NULL;
int nWStr = 0;
DWORD dwErr = 0;
BOOL bStringConverted = FALSE;
CComBSTR bstrDisplay;
EStringType sType = STRING_TYPE_NULL;
hr = ::SafeArrayAccessData( psa, (void**)&pData);
if(hr != S_OK)
return hr;
nBytes = psa->rgsabound[0].cElements;
ASSERT(pData);
if(!pData) goto Error;
#ifdef __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
// UTF8 requires the flag to be 0
nWStr = MultiByteToWideChar(CP_UTF8, 0, pData, nBytes, NULL, 0);
if(nWStr == 0)
dwErr = GetLastError();
#endif
try{
#ifdef __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
if(nWStr != 0) // succ
{
pWStr = new WCHAR[nWStr + 2]; // for the 2 "s
int i = 0;
nWStr == MultiByteToWideChar(CP_UTF8, 0, pData, nBytes, pWStr , nWStr);
// if every char is printable
for(i = 0; i < nWStr -1; i++)
{
if(iswprint(pWStr[i]) == 0)
break;
}
if(0 == nWStr || i != nWStr - 1 || pWStr[i] != L'\0')
{
delete[] pWStr;
pWStr = NULL;
}
else
{
// added quotes
memmove(pWStr + 1, pWStr, nWStr * sizeof(WCHAR));
pWStr[0] = L'"';
pWStr[nWStr] = L'"';
pWStr[nWStr + 1 ] = 0; // new end of string
bStringConverted = TRUE; // to prevent from furthe convertion to HEX
sType = STRING_TYPE_UNICODE;
}
}
#endif // __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
// check if the attriabute is RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
// this attribute has special format --- remove 0's from the binary and
// try to conver to text
{
ATTRIBUTEID Id;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) goto Error;
if ( Id == RADIUS_ATTRIBUTE_TUNNEL_PASSWORD)
{
//BYTE PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD[] = {0,0,0,0};
//UINT PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 4;
//UINT PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 3; // 0 based index -- the fourth byte
//UINT PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 1
if(PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD <=nBytes &&
memcmp(pData,
PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD - PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD) == 0)
{
// correct prefix,
// remove the prefix
pData += PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD;
nBytes -= PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD;
// try to convert to UNICODE TEXT using CP_ACP -- get length
nWStr = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, pData, nBytes, NULL, 0);
if(nWStr != 0) // which means, we can not convert
{
pWStr = new WCHAR[nWStr + 1];
// try to convert to UNICODE TEXT using CP_ACP
nWStr = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, pData, nBytes, pWStr, nWStr);
if(nWStr != 0)
{
int i = 0;
for(i = 0; i < nWStr; i++)
{
if(iswprint(pWStr[i]) == 0)
break;
}
if( i == nWStr) // all printable
{
bStringConverted = TRUE;
pWStr[nWStr] = 0; // NULL terminator
}
}
if (!bStringConverted) // undo the thing
{
// release the buffer
delete[] pWStr;
pWStr = NULL;
nWStr = 0;
}
}
}
}
}
if(!bStringConverted) // not converted above, convert to HEX string
{
nWStr = BinaryToHexString(pData, nBytes, NULL, 0); // find out the size of the buffer
pWStr = new WCHAR[nWStr];
ASSERT(pWStr); // should have thrown if there is not enough memory
BinaryToHexString(pData, nBytes, pWStr, nWStr);
bStringConverted = TRUE; // to prevent from furthe convertion to HEX
sType = STRING_TYPE_HEX_FROM_BINARY;
}
if(bStringConverted)
{
bstrDisplay = pWStr;
// fill in the output parameters
*pbstrDisplayText = bstrDisplay.Copy();
*pType = sType;
delete[] pWStr;
pWStr = NULL;
}
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
Error:
if(pWStr)
delete[] pWStr;
if(psa)
::SafeArrayUnaccessData(psa);
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
*/
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::put_ValueAsStringEx
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::put_ValueAsStringEx(BSTR newVal, EStringType type)
{
TRACE(_T("CIASStringAttributeEditor::put_ValueAsStringEx\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
ATTRIBUTESYNTAX asSyntax;
m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if(asSyntax != IAS_SYNTAX_OCTETSTRING)
return put_ValueAsString(newVal);
// only care about IAS_SYNTAX_OCTETSTRING
HRESULT hr = S_OK;
char* pData = NULL;
int nLen = 0;
switch(type)
{
case STRING_TYPE_NULL:
// remove the data
break;
case STRING_TYPE_NORMAL:
case STRING_TYPE_UNICODE:
#ifdef __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
// need to convert UTF8 before passing into SafeArray
nLen = WideCharToMultiByte(CP_UTF8, 0, newVal, -1, NULL, 0, NULL, NULL);
if(nLen != 0) // when == 0 , need not to do anything
{
try{
pData = new char[nLen];
nLen = WideCharToMultiByte(CP_UTF8, 0, newVal, -1, pData, nLen, NULL, NULL);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
}
break;
#else
// check if the attriabute is RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
// this attribute has special format --- remove 0's from the binary and
// try to conver to text
{
ATTRIBUTEID Id;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) goto Error;
if ( Id == RADIUS_ATTRIBUTE_TUNNEL_PASSWORD)
{
BOOL bUsedDefault = FALSE;
UINT nStrLen = wcslen(newVal);
// try to convert to UNICODE TEXT using CP_ACP -- get length
nLen = ::WideCharToMultiByte(CP_ACP, 0, newVal, nStrLen, NULL, 0, NULL, &bUsedDefault);
if(nLen != 0) // which means, we can not convert
{
try{
pData = new char[nLen];
ASSERT(pData);
// try to convert to UNICODE TEXT using CP_ACP
nLen = ::WideCharToMultiByte(CP_ACP, 0, newVal, nStrLen, pData, nLen, NULL, &bUsedDefault);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
}
if(nLen == 0 || bUsedDefault) // failed to convert, then error message
{
// ANSI code page is allowed
hr = E_INVALIDARG;
AfxMessageBox(IDS_IAS_ERR_INVALIDCHARINPASSWORD);
goto Error;
}
}
else
return put_ValueAsString(newVal);
}
break;
#endif
case STRING_TYPE_HEX_FROM_BINARY:
// need to convert to binary before passing into SafeArray
if(wcslen(newVal) != 0)
{
newVal = GetValidVSAHexString(newVal);
if(newVal == NULL)
{
hr = E_INVALIDARG;
goto Error;
}
nLen = HexStringToBinary(newVal, NULL, 0); // find out the size of the buffer
}
else
nLen = 0;
// get the binary
try{
pData = new char[nLen];
ASSERT(pData);
HexStringToBinary(newVal, pData, nLen);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
break;
default:
ASSERT(0); // this should not happen
break;
}
// check if the attriabute is RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
// this attribute has special format --- remove 0's from the binary and
// try to conver to text
{
ATTRIBUTEID Id;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) goto Error;
if ( Id == RADIUS_ATTRIBUTE_TUNNEL_PASSWORD)
{
char* pData1 = NULL;
// get the binary
//BYTE PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD[] = {0,0,0,0};
//UINT PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 4;
//UINT PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 3; // 0 based index -- the fourth byte
//UINT PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 1
try{
pData1 = new char[nLen + PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD];
ASSERT(pData1);
memcpy(pData1, PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD, PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD);
unsigned char lenByte = (unsigned char)nLen;
memcpy(pData1 + PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD, &lenByte, PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
if(pData)
{
memcpy(pData1 + PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD, pData, nLen);
delete [] pData;
pData = pData1;
nLen += PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD;
}
}
}
// put the data into the safe array
VariantClear(m_pvarValue);
if(pData) // need to put data to safe array
{
SAFEARRAY* psa = NULL;
SAFEARRAYBOUND sab[1];
sab[0].cElements = nLen;
sab[0].lLbound = 0;
try{
psa = SafeArrayCreate(VT_UI1, 1, sab);
char* pByte = NULL;
if(S_OK == SafeArrayAccessData(psa, (void**)&pByte))
{
ASSERT(pByte);
memcpy(pByte, pData, nLen);
SafeArrayUnaccessData(psa);
V_VT(m_pvarValue) = VT_ARRAY | VT_UI1;
V_ARRAY(m_pvarValue) = psa;
}
else
SafeArrayDestroy(psa);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
psa = NULL;
};
Error:
if(pData)
{
delete [] pData;
pData = NULL;
}
return hr;
}
| 23.105682 | 152 | 0.602321 |
56068b094935639c12ba5efca575ca59056eb0b4 | 8,551 | hpp | C++ | Unidad 4/src/biblioteca/funciones/strings.hpp | Franeiro/AyED | a53142ac0c92fb74e62064e26fb4a4f86bace388 | [
"Xnet",
"X11"
] | null | null | null | Unidad 4/src/biblioteca/funciones/strings.hpp | Franeiro/AyED | a53142ac0c92fb74e62064e26fb4a4f86bace388 | [
"Xnet",
"X11"
] | null | null | null | Unidad 4/src/biblioteca/funciones/strings.hpp | Franeiro/AyED | a53142ac0c92fb74e62064e26fb4a4f86bace388 | [
"Xnet",
"X11"
] | null | null | null | #ifndef _TSTRINGS_T_
#define _TSTRINGS_T_
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
int length(string s)
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
}
return i;
}
int charCount(string s, char c)
{
int i, veces;
veces = 0;
for (i = 0; i < length(s); i++)
{
if (s[i] == c)
{
veces++;
}
}
return veces;
}
string substring(string s, int d, int h)
{
int i = 0;
string aux;
for (i = d; i < h; i++)
{
aux += s[i];
}
return aux;
}
string substring(string s, int d) // ok
{
int i = 0;
string aux;
for (i = d; i < length(s); i++)
{
aux += s[i];
}
return aux;
return "";
}
int indexOf(string s, char c) // ok
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] == c)
{
return i;
}
}
return -1;
}
int indexOf(string s, char c, int offSet) // ok
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (i > offSet && s[i] == c)
{
return i;
}
}
return 0;
}
int indexOf(string s, string toSearch)
{
int a, j = 0;
for (int i = 0; i <= length(s); i++)
{
if (s[i] == toSearch[0])
{
a = i;
while (s[i] == toSearch[j] && j < length(toSearch))
{
i++;
j++;
if (j == length(toSearch))
{
return a;
break;
}
}
i = a;
}
}
return -1;
}
int indexOf(string s, string toSearch, int offset) // ok
{
int i, a, j = 0;
for (i = 0; i <= length(s); i++)
{
if (i > offset && s[i] == toSearch[0])
{
a = i;
while (s[i] == toSearch[j] && j < length(toSearch))
{
i++;
j++;
if (j == length(toSearch))
{
return a;
break;
}
}
i = a;
}
}
return 0;
}
int lastIndexOf(string s, char c)
{
int i;
for (i = length(s); i >= 0; i--)
{
if (s[i] == c)
{
return i;
break;
}
}
return -1;
}
int indexOfN(string s, char c, int n)
{
int i, veces = 0;
for (i = 0; i <= length(s); i++)
{
if (s[i] == c)
{
veces++;
if (veces == n)
{
return i;
break;
}
}
}
return -1;
}
int charToInt(char c)
{
/*
int numero;
numero = c - 48;
return numero;
*/
int i = '0';
int n = c;
int resultado = n - i;
return resultado;
}
char intToChar(int i)
{
char caracter;
caracter = (i + 48);
return caracter;
}
int potencia(int x, int y) // CREO FUNCION PARA CALCULAR POTENCIAS
{
if (y == 0)
{
return 1;
}
else
{
if (int(y % 2) == 0)
{
return (potencia(x, int(y / 2)) * potencia(x, int(y / 2)));
}
else
{
return (x * potencia(x, int(y / 2)) * potencia(x, int(y / 2)));
}
}
}
int getDigit(int n, int i)
{
int p = potencia(10, i);
int q = n / p;
return q % 10;
}
int digitCount(int n)
{
int a = 0, t;
for (t = 0; n / (long)potencia(10, t) >= 1; t++)
{
a++;
}
return a;
}
string intToString(int i)
{
int n = digitCount(i);
string parse = "";
for (int j = 0; j < n; j++)
{
int f = (n - j) - 1;
int digito = getDigit(i, f);
char c = digito + 48;
parse += c;
}
return parse;
}
int stringToInt(string s, int b) // ok
{
int parseInt, j;
int longitud = length(s) - 1;
char i = 0;
for (j = longitud; j >= 0; j--)
{
int x;
if (s[j] >= '0' and s[j] <= '9')
{
x = '0';
}
else
{
x = 'A' - 10;
}
parseInt = parseInt + (s[j] - x) * potencia(b, i);
i++;
}
return parseInt;
}
int stringToInt(string s) // ok
{
int parseInt = 0, j = 0;
int longitud = length(s) - 1;
int i = 0;
for (j = longitud; j >= 0; j--)
{
parseInt = parseInt + (charToInt(s[j]) * potencia(10, i));
i++;
}
return parseInt;
}
string charToString(char c)
{
string a;
a += c;
return a;
}
char stringToChar(string s)
{
char a;
a = s[0];
return a;
}
string stringToString(string s)
{
string a;
a = s;
return a;
}
string doubleToString(double d) // saltear
{
char x[100];
sprintf(x, "%f", d); // esto es de lenguaje C, no se usa
string ret = x;
return ret;
}
double stringToDouble(string s) // No se hace
{
return 1.1;
}
bool isEmpty(string s)
{
bool a;
string verdad;
a = s == "";
if (a == 0)
{
verdad = "false";
}
else
{
verdad = "true";
}
return a;
}
bool startsWith(string s, string x)
{
int coincidencia;
for (int i = 0; i <= length(x); i++)
{
if (x[i] == s[i])
{
coincidencia++;
}
}
if (coincidencia == length(x))
{
return true;
}
else
{
return false;
}
}
bool endsWith(string s, string x)
{
int coincidencia;
int posX = length(x);
for (int i = length(s); posX >= 0; i--)
{
if (x[posX] == s[i])
{
coincidencia++;
}
posX--;
}
if (coincidencia - 1 == length(x))
{
return true;
}
else
{
return false;
}
}
bool contains(string s, char c)
{
int coincidencia;
for (int i = 0; i <= length(s); i++)
{
if (s[i] == c)
{
coincidencia = 1;
}
}
if (coincidencia == 1)
{
return true;
}
else
{
return false;
}
}
string replace(string s, char oldChar, char newChar)
{
for (int i = 0; i <= length(s); i++)
{
if (s[i] == oldChar)
{
s[i] = newChar;
}
}
return s;
}
string insertAt(string s, int pos, char c)
{
string r = substring(s, 0, pos) + c + substring(s, pos);
return r;
}
string removeAt(string s, int pos)
{
string r = substring(s, 0, pos) + substring(s, pos + 1);
return r;
}
string ltrim(string s)
{
int largo = length(s);
int i = 0;
while (s[i] == ' ')
{
i++;
}
return substring(s, i, largo);
}
string rtrim(string s)
{
int largo = length(s) - 1;
while (s[largo] == ' ')
{
largo--;
}
return substring(s, 0, largo + 1);
}
string trim(string s)
{
return rtrim(ltrim(s));
}
string replicate(char c, int n)
{
string a;
for (int i = 0; i <= n; i++)
{
a += c;
}
return a;
}
string spaces(int n)
{
string a;
for (int i = 0; i <= n; i++)
{
a += ' ';
}
return a;
}
string lpad(string s, int n, char c)
{
string a;
for (int i = 0; i <= n; i++)
{
a += c;
}
a += s;
return a;
}
string rpad(string s, int n, char c)
{
string a;
a += s;
for (int i = 0; i <= n; i++)
{
a += c;
}
return a;
}
string cpad(string s, int n, char c)
{
string a;
int espacio = (n - length(s));
for (int i = 0; i <= espacio; i++)
{
if (i < (espacio / 2))
{
a += c;
}
if (i == (espacio / 2))
{
a += s;
}
if (i > (espacio / 2))
{
a += c;
}
}
return a;
}
bool isDigit(char c)
{
if (c >= 48 && c <= 57)
{
return true;
}
else
{
return false;
}
}
bool isLetter(char c)
{
if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
{
return true;
}
else
{
return false;
}
}
bool isUpperCase(char c)
{
if ((c >= 65 && c <= 90))
{
return true;
}
else
{
return false;
}
}
bool isLowerCase(char c)
{
if ((c >= 97 && c <= 122))
{
return true;
}
else
{
return false;
}
}
char toUpperCase(char c)
{
if (c >= 97 && c <= 122)
{
c -= 32;
}
else
{
return c;
}
return c;
}
char toLowerCase(char c)
{
if (c >= 65 && c <= 90)
{
c += 32;
}
else
{
return c;
}
return c;
}
string toUpperCase(string s)
{
for (int i = 0; i <= length(s); i++)
{
if (s[i] >= 97 && s[i] <= 122)
{
s[i] -= 32;
}
else
{
s[i] = s[i];
}
}
return s;
}
string toLowerCase(string s)
{
for (int i = 0; i <= length(s); i++)
{
if (s[i] >= 65 && s[i] <= 90)
{
s[i] += 32;
}
else
{
s[i] = s[i];
}
}
return s;
}
#endif
| 12.303597 | 72 | 0.422758 |
5608f4ab3eee3af228771b5bf8b4f6f59e63929b | 432 | hpp | C++ | inc/OptionParser.hpp | Aracthor/paranoidRM | 1d7200090f18db7f152461f47afd63b0e4f7f02f | [
"MIT"
] | null | null | null | inc/OptionParser.hpp | Aracthor/paranoidRM | 1d7200090f18db7f152461f47afd63b0e4f7f02f | [
"MIT"
] | null | null | null | inc/OptionParser.hpp | Aracthor/paranoidRM | 1d7200090f18db7f152461f47afd63b0e4f7f02f | [
"MIT"
] | null | null | null | //
// OptionParser.hpp for paranoidRM in /home/aracthor/programs/projects/paranoidRM
//
// Made by Aracthor
// Login <aracthor@epitech.net>
//
// Started on Mon Jun 8 20:05:10 2015 Aracthor
// Last Update Mon Jun 8 20:10:50 2015 Aracthor
//
char
OptionParser::getFlag() const
{
return (mFlag);
}
const char*
OptionParser::getName() const
{
return (mName);
}
bool
OptionParser::needArg() const
{
return (mNeedArg);
}
| 15.428571 | 81 | 0.69213 |
560acde3772fa021d6bf2942daf2b52dcf32eda5 | 563 | cpp | C++ | PhotonBox/src/component/SpotLight.cpp | strager/PhotonBox | aba8ad303012dd1ca75b7c00ab6b8d5fff2e4128 | [
"MIT"
] | 118 | 2018-01-20T04:41:50.000Z | 2022-03-27T12:52:19.000Z | PhotonBox/src/component/SpotLight.cpp | strager/PhotonBox | aba8ad303012dd1ca75b7c00ab6b8d5fff2e4128 | [
"MIT"
] | 18 | 2017-12-03T02:13:08.000Z | 2020-11-12T00:09:41.000Z | PhotonBox/src/component/SpotLight.cpp | strager/PhotonBox | aba8ad303012dd1ca75b7c00ab6b8d5fff2e4128 | [
"MIT"
] | 13 | 2018-03-05T23:23:38.000Z | 2021-07-19T22:33:04.000Z | #include "PhotonBox/component/SpotLight.h"
#include "PhotonBox/core/system/Lighting.h"
#include "PhotonBox/resource/shader/ForwardSpotLightShader.h"
#ifdef PB_MEM_DEBUG
#include "PhotonBox/util/MEMDebug.h"
#define new DEBUG_NEW
#endif
void SpotLight::init()
{
Lighting::addLight(this);
}
void SpotLight::destroy()
{
Lighting::removeLight(this);
}
Shader * SpotLight::getLightShader()
{
return ForwardSpotLightShader::getInstance();
}
void SpotLight::OnEnable()
{
Lighting::addLight(this);
}
void SpotLight::OnDisable()
{
Lighting::removeLight(this);
} | 16.558824 | 61 | 0.756661 |
560b1872dd11349dd3aa06f59fc9efe930c89299 | 3,079 | cxx | C++ | src/test/testMcClasses.cxx | fermi-lat/mcRootData | 1529a12d481fe1db38bfa7bc02780303232eb15d | [
"BSD-3-Clause"
] | null | null | null | src/test/testMcClasses.cxx | fermi-lat/mcRootData | 1529a12d481fe1db38bfa7bc02780303232eb15d | [
"BSD-3-Clause"
] | null | null | null | src/test/testMcClasses.cxx | fermi-lat/mcRootData | 1529a12d481fe1db38bfa7bc02780303232eb15d | [
"BSD-3-Clause"
] | null | null | null |
#include <mcRootData/McEvent.h>
#include <commonRootData/RootDataUtil.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TTree.h"
#include "TRandom.h"
/** @file testMcClasses.cxx
* @brief This defines a test routine for the Monte Carlo ROOT classes.
*
* This program create a new Monte Carlo ROOT file, and the opens it up again
* for reading. The contents are checked against the values known to be stored
* during the original writing of the file.
* The contents of the file are printed to the screen.
* The program returns 0 if the test passed.
* If failure, the program returns -1.
*
* $Header$
*/
const UInt_t RUN_NUM = 1 ;
Float_t RAND_NUM ;
int read( char * fileName, unsigned int numEvents) {
// Purpose and Method: Read in the ROOT file just generated via the
// write method
TFile *f = new TFile(fileName, "READ");
TTree *t = (TTree*)f->Get("Mc");
McEvent *evt = 0;
t->SetBranchAddress("McEvent", &evt);
std::cout << "Opened the ROOT file for reading" << std::endl;
UInt_t iEvent ;
for ( iEvent = 0 ; iEvent < numEvents ; ++iEvent ) {
t->GetEvent(iEvent);
std::cout << "McEvent iEvent = " << iEvent << std::endl;
evt->Print() ;
// DC: I CANNOT MAKE A McEvent::Fake() and
// a McEvent::CompareInRange(), because McEvent
// is designed as a singleton.
if (!evt->CompareToFake(iEvent,RUN_NUM,RAND_NUM)) {
return -1 ;
}
}
f->Close();
delete f;
return(0);
}
/// Create a new ROOT file
int write( char * fileName, UInt_t numEvents ) {
Int_t buffer = 64000;
Int_t splitLevel = 1;
TFile *f = new TFile(fileName, "RECREATE");
TTree *t = new TTree("Mc", "Mc");
McEvent * evt = new McEvent() ;
t->Branch("McEvent", "McEvent", &evt, buffer, splitLevel);
std::cout << "Created new ROOT file" << std::endl;
UInt_t iEvent ;
for (iEvent = 0; iEvent < numEvents; iEvent++) {
evt->Fake(iEvent,RUN_NUM,RAND_NUM) ;
t->Fill() ;
}
std::cout << "Filled ROOT file with " << numEvents << " events" << std::endl;
delete evt ;
f->Write();
f->Close();
delete f;
return(0);
}
/// Main program
/// Return 0 for success.
/// Returns -1 for failure.
int main(int argc, char **argv) {
char *fileName = "mc.root";
int n =1 ;
unsigned int numEvents =10 ;
if (argc > 1) {
fileName = argv[n++];
}
if (argc > 2) {
numEvents = atoi(argv[n++]);
}
TRandom randGen ;
RAND_NUM = randGen.Rndm() ;
int sc = 0;
try
{
sc = write(fileName, numEvents);
sc = read(fileName, numEvents);
}
catch (...)
{
std::cout<<"AN UNKNOWN EXCEPTION HAS BEEN RAISED"<<std::endl ;
sc = 1 ;
}
if (sc == 0) {
std::cout << "MC ROOT file writing and reading suceeded!" << std::endl;
} else {
std::cout << "FAILED" << std::endl;
}
return(sc);
}
| 23.868217 | 81 | 0.566418 |
560baacc70936168a133e01580e5c93943074455 | 19,257 | cpp | C++ | ts/src/clientData.cpp | GodofMonkeys/task-force-arma-3-radio | 874ca4774f0797d46120818d31c1ef72a62f2eda | [
"RSA-MD"
] | null | null | null | ts/src/clientData.cpp | GodofMonkeys/task-force-arma-3-radio | 874ca4774f0797d46120818d31c1ef72a62f2eda | [
"RSA-MD"
] | null | null | null | ts/src/clientData.cpp | GodofMonkeys/task-force-arma-3-radio | 874ca4774f0797d46120818d31c1ef72a62f2eda | [
"RSA-MD"
] | null | null | null | #include "clientData.hpp"
#include "Logger.hpp"
#include "task_force_radio.hpp"
#include "antennaManager.h"
#include <iomanip>
#define logParam(x) str << #x << " " << (x) << "\n"
#define logParamN(n,x) str << #n << " " << (x) << "\n"
void LISTED_INFO::operator<<(std::ostream& str) const {
logParamN(over, static_cast<uint32_t>(over));
logParamN(on, static_cast<uint32_t>(on));
logParam(volume);
logParamN(stereoMode, static_cast<uint32_t>(stereoMode));
logParam(radio_id);
logParamN(pos, pos.toString());
logParam(waveZ);
str << "vehicle:\n";
str << "\tvehicleName " << vehicle.vehicleName << "\n";
str << "\tvehicleIsolation " << vehicle.vehicleIsolation << "\n";
str << "\tintercomSlot " << vehicle.intercomSlot << "\n";
str << "antennaConnection:\n" << antennaConnection << "\n";
}
extern float debugDisplayThing;
extern float debugDisplayThing2;
//double interpTo(double target) {
// static double lastFreq;
// static std::chrono::system_clock::time_point lastTick;
//
// auto ms = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(std::chrono::system_clock::now() - lastTick).count();
// constexpr double freqPerMS = 10;
// lastTick = std::chrono::system_clock::now();
// if (lastFreq == target) return target;
//
// double distance = std::abs(lastFreq - target);
// double maxDistance = ms * freqPerMS;
//
// if (maxDistance > distance) {
// lastFreq = target;
// } else if (target < lastFreq) {
// lastFreq -= maxDistance;
// } else if (target > lastFreq) {
// lastFreq += maxDistance;
// }
// return lastFreq;
//}
Dsp::SimpleFilter<Dsp::Butterworth::LowPass<2>, MAX_CHANNELS>*
clientDataEffects::getFilterObjectInterception(uint8_t objectCount) {
objectCount = std::min(objectCount, static_cast<uint8_t>(5));
static float lastStrength = 400;
if (auto newStrength = TFAR::config.get<float>(Setting::objectInterceptionStrength); newStrength != lastStrength) {
LockGuard_exclusive lock_exclusive(m_lock);
filtersObjectInterception.clear();
lastStrength = newStrength;
}
debugDisplayThing = 2000 - (objectCount * lastStrength);
debugDisplayThing2 = objectCount;
LockGuard_shared lock_shared(m_lock);
if (!filtersObjectInterception.count(objectCount)) {
lock_shared.unlock();
LockGuard_exclusive lock_exclusive(m_lock);
filtersObjectInterception[objectCount] = std::make_unique<Dsp::SimpleFilter<
Dsp::Butterworth::LowPass<2>, MAX_CHANNELS>>();
filtersObjectInterception[objectCount]->setup(2, 48000, 2000 - (objectCount * lastStrength));
//#TODO not happy with that..
}
return filtersObjectInterception[objectCount].get();
}
void clientData::updatePosition(const unitPositionPacket & packet) {
LockGuard_exclusive lock(m_lock);
clientPosition = packet.position;//Could move assign if more performance is needed
viewDirection = packet.viewDirection;
canSpeak = packet.canSpeak;
if (packet.myData) {
//Ugly hack because the canUsees of other people don't respect if they even have that radio type
canUseSWRadio = packet.canUseSWRadio;
canUseLRRadio = packet.canUseLRRadio;
canUseDDRadio = packet.canUseDDRadio;
}
setVehicleId(packet.vehicleID);
terrainInterception = packet.terrainInterception;
voiceVolumeMultiplifier = packet.voiceVolume;
objectInterception = packet.objectInterception;
isSpectating = packet.isSpectating;
isEnemyToPlayer = packet.isEnemyToPlayer;
//OutputDebugStringA(std::to_string(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - lastPositionUpdateTime).count()).c_str());
//OutputDebugStringA("\n");
lastPositionUpdateTime = std::chrono::system_clock::now();
dataFrame = TFAR::getInstance().m_gameData.currentDataFrame;
}
Position3D clientData::getClientPosition() const {
LockGuard_shared lock(m_lock);
if (velocity.isNull())
return clientPosition;
const auto offsetTime = std::chrono::duration<float>(std::chrono::system_clock::now() - lastPositionUpdateTime).count();
const auto offset = velocity * offsetTime;
//float x, y, z;
//std::tie(x, y, z) = offset.get();
//OutputDebugStringA((std::to_string(offsetTime) + "o " + std::to_string(x) + "," + std::to_string(x) + ","+ std::to_string(z)).c_str());
//OutputDebugStringA("\n");
return clientPosition + offset;
}
float clientData::effectiveDistanceTo(std::shared_ptr<clientData>& other) const {
return effectiveDistanceTo(other.get());
}
float clientData::effectiveDistanceTo(clientData* other) const {
float d = getClientPosition().distanceTo(other->getClientPosition());
// (bob distance player) + (bob call TFAR_fnc_calcTerrainInterception) * 7 + (bob call TFAR_fnc_calcTerrainInterception) * 7 * ((bob distance player) / 2000.0)
float result = d +
other->terrainInterception * TFAR::getInstance().m_gameData.terrainIntersectionCoefficient
+
other->terrainInterception * TFAR::getInstance().m_gameData.terrainIntersectionCoefficient * (d / 2000.0f);
result *= TFAR::getInstance().m_gameData.receivingDistanceMultiplicator;
return result;
}
bool clientData::isAlive() {
if (dataFrame == INVALID_DATA_FRAME) return false;
const bool timeout = (std::chrono::system_clock::now() - getLastPositionUpdateTime() > (MILLIS_TO_EXPIRE * 5)) || (abs(TFAR::getInstance().m_gameData.currentDataFrame - dataFrame) > 1);
if (timeout)
dataFrame = INVALID_DATA_FRAME;
return !timeout;
}
clientData* lastORCheck = nullptr;
#include "Teamspeak.hpp"
#define DIAGLOG(x) if (lastORCheck != this) circularLog(x)
LISTED_INFO clientData::isOverLocalRadio(std::shared_ptr<clientData>& myData, bool ignoreSwTangent, bool ignoreLrTangent, AntennaConnection& antennaConnection) {
//Sender is this
LISTED_INFO result;
result.over = sendingRadioType::LISTEN_TO_NONE;
result.volume = 0;
result.on = receivingRadioType::LISTED_ON_NONE;
result.waveZ = 1.0f;
if (!myData) return result;
const auto senderNickname = getNickname();
const auto myPosition = myData->getClientPosition();
const auto clientPosition = getClientPosition();
//If we are underwater and can still use SWRadio then we are in a vehicle
const bool receiverUnderwater = myPosition.getHeight() < 0 && !myData->canUseSWRadio;
const bool senderUnderwater = clientPosition.getHeight() < 0 && !canUseSWRadio;
//If we didn't find anything result.on has to be LISTED_ON_NONE so we can set result.over
//even if we won't find a valid path on the receiver side
if ((currentTransmittingTangentOverType == sendingRadioType::LISTEN_TO_SW || ignoreSwTangent) && (canUseSWRadio || canUseDDRadio)) {//Sending from SW
result.over = senderUnderwater ? sendingRadioType::LISTEN_TO_DD : sendingRadioType::LISTEN_TO_SW;
} else if ((currentTransmittingTangentOverType == sendingRadioType::LISTEN_TO_LR || ignoreLrTangent) && canUseLRRadio) {//Sending from LR
result.over = sendingRadioType::LISTEN_TO_LR;
} else {
DIAGLOG("IOLR No Send? ttot="+std::to_string(static_cast<int>(currentTransmittingTangentOverType))+" CURF="+
std::to_string(canUseSWRadio) +
std::to_string(canUseDDRadio) +
std::to_string(canUseLRRadio));
//He isn't actually sending on anything...
return result;
}
result.radio_id = "local_radio";
result.vehicle = myData->getVehicleDescriptor();
const auto senderFrequency = getCurrentTransmittingFrequency();
LockGuard_shared countLock(TFAR::getInstance().m_gameData.m_lock);
//Sender is sending on a Frequency we are listening to on our LR Radio
const bool senderOnLRFrequency = TFAR::getInstance().m_gameData.myLrFrequencies.count(senderFrequency) != 0;
//Sender is sending on a Frequency we are listening to on our SW Radio
const bool senderOnSWFrequency = TFAR::getInstance().m_gameData.mySwFrequencies.count(senderFrequency) != 0;
countLock.unlock();
if (!senderOnSWFrequency && !senderOnLRFrequency) {
DIAGLOG("IOLR No freq sf=" + senderFrequency);
return result; //He's not on any frequency we can receive on
}
auto effectiveDist = myData->effectiveDistanceTo(this);
const bool isUnderwater = receiverUnderwater || senderUnderwater;
if (isUnderwater) {
DIAGLOG("IOLR underwater");
const auto underwaterDist = myPosition.distanceUnderwater(clientPosition);
//Seperate distance underwater and distance overwater.
effectiveDist = underwaterDist * (range / helpers::distanceForDiverRadio()) + (effectiveDist - underwaterDist);
if (effectiveDist > range && !antennaConnection.isNull()) {
effectiveDist = 0.f; //just use make the range check succeed
}
}
if (effectiveDist > range) { //Out of range
if (!antennaConnection.isNull()) {
//Normal range not sufficient. Check if Antenna reaches.
const auto antennaUnderwater = clientPosition.distanceUnderwater(antennaConnection.getAntenna()->getPos());
const auto antennaTotal = clientPosition.distanceTo(antennaConnection.getAntenna()->getPos());
const auto effectiveRangeToAntenna = antennaUnderwater * (range / helpers::distanceForDiverRadio())
+ (antennaTotal - antennaUnderwater);
if (effectiveRangeToAntenna > range) {//Antenna doesn't reach
DIAGLOG("IOLR No reach ed=" + std::to_string(effectiveDist) + " rng=" + std::to_string(range));
return result;
}
} else {
DIAGLOG("IOLR No reach ed=" + std::to_string(effectiveDist) + " rng=" + std::to_string(range));
return result;
}
}
//#TODO always have a "valid" antenna connection in the end result. Just to transmit the connectionLoss to not have to calculate it again
result.antennaConnection = antennaConnection;
std::string currentTransmittingRadio;
if (!TFAR::config.get<bool>(Setting::full_duplex)) {
//We have to get it here because we can't while m_gameData is Locked
currentTransmittingRadio = TFAR::getInstance().m_gameData.getCurrentTransmittingRadio();
}
if (senderOnLRFrequency && myData->canUseLRRadio) {//to our LR
LockGuard_shared lock(TFAR::getInstance().m_gameData.m_lock);
auto &frequencyInfo = TFAR::getInstance().m_gameData.myLrFrequencies[senderFrequency];
if (!TFAR::config.get<bool>(Setting::full_duplex) && //If we are currently transmitting on that Radio we can't hear so we return before result gets valid
frequencyInfo.radioClassname == currentTransmittingRadio) {
DIAGLOG("IOLR No duplex LR RECV");
return result;
}
result.on = receivingRadioType::LISTED_ON_LR;
result.volume = frequencyInfo.volume;
result.stereoMode = frequencyInfo.stereoMode;
DIAGLOG("IOLR RECV! RC=" + frequencyInfo.radioClassname);
} else if (senderOnSWFrequency && myData->canUseSWRadio) {//to our SW
LockGuard_shared lock(TFAR::getInstance().m_gameData.m_lock);
auto &frequencyInfo = TFAR::getInstance().m_gameData.mySwFrequencies[senderFrequency];
if (!TFAR::config.get<bool>(Setting::full_duplex) && //If we are currently transmitting on that Radio we can't hear so we return before result gets valid
frequencyInfo.radioClassname == currentTransmittingRadio) {
DIAGLOG("IOLR No duplex SR RECV");
return result;
}
result.on = receivingRadioType::LISTED_ON_SW;
result.volume = frequencyInfo.volume;
result.stereoMode = frequencyInfo.stereoMode;
DIAGLOG("IOLR RECV! RC="+ frequencyInfo.radioClassname);
}
return result;
}
std::vector<LISTED_INFO> clientData::isOverRadio(std::shared_ptr<clientData>& myData, bool ignoreSwTangent, bool ignoreLrTangent) {
execAtReturn setLastOr([this](){
lastORCheck = this;
});
std::string senderNickname = getNickname();
std::vector<LISTED_INFO> result;
if (!myData) {
DIAGLOG("IOR No Data");
return result;
}
//Intercom has to be here because it has to be before range==0 check
//vehicle intercom
const auto vecDescriptor = getVehicleDescriptor();
const auto myVecDescriptor = myData->getVehicleDescriptor();
if (TFAR::config.get<bool>(Setting::intercomEnabled) &&
currentTransmittingTangentOverType == sendingRadioType::LISTEN_TO_NONE && //Not currently transmitting on a Radio. If transmitting only direct speech.
vecDescriptor.vehicleName != "no" && vecDescriptor.vehicleName == myVecDescriptor.vehicleName //In same vehicle
&& vecDescriptor.intercomSlot != -1 && vecDescriptor.intercomSlot == myVecDescriptor.intercomSlot) { //On same Intercom Channel
result.emplace_back(
sendingRadioType::LISTEN_TO_SW, //unused
receivingRadioType::LISTED_ON_INTERCOM,
7, //unused
stereoMode::stereo, //unused
"intercom", //unused
Position3D(0, 0, 0), //unused
0.f, //unused
getVehicleDescriptor()); //unused
}
if (range == 0) {
DIAGLOG("IOR No Radio Transmit");
return result; //If we are sending range is set to Radio's range. Always!
}
auto antennaConnection = (clientId != myData->clientId) ? TFAR::getAntennaManager()->findConnection(getClientPosition(), static_cast<float>(range), myData->getClientPosition()) : AntennaConnection();
//check if we receive him over a radio we have on us
if (clientId != myData->clientId) {//We don't hear ourselves over our Radio ^^
const auto local = isOverLocalRadio(myData, ignoreSwTangent, ignoreLrTangent, antennaConnection);
if (local.on != receivingRadioType::LISTED_ON_NONE && local.over != sendingRadioType::LISTEN_TO_NONE) {
result.push_back(local);
} else {
DIAGLOG("IOR No Local Radio");
}
}
const auto effectiveDistance = myData->effectiveDistanceTo(this);
//check if we receive him over a radio laying on ground
//We reuse the antennaConnection for a nearby speaker. Technically antennaConnection measures connection to our body. But a speaker Radio is not that far away from us anyway
if (effectiveDistance > range && antennaConnection.isNull()) { //does senders range reach to us?
DIAGLOG("IOR No Range & no Ant efDist="+std::to_string(effectiveDistance)+" rng="+std::to_string(range));
return result; //His distance > range and no suitable Antenna
}
if (
(canUseSWRadio && (currentTransmittingTangentOverType == sendingRadioType::LISTEN_TO_SW || ignoreSwTangent)) || //Sending over SW
(canUseLRRadio && (currentTransmittingTangentOverType == sendingRadioType::LISTEN_TO_LR || ignoreLrTangent))) { //Sending over LR
auto currentFrequency = getCurrentTransmittingFrequency();
LockGuard_shared lock(TFAR::getInstance().m_gameData.m_lock);
for (const auto& it : TFAR::getInstance().m_gameData.speakers) {
if (it.first != currentFrequency) continue;
auto& speaker = it.second;
auto speakerOwner = speaker.client.lock();
//If the speaker is Senders backpack we don't hear it.. Because he is sending with his Backpack so it can't receive
//Also because we would normally hear him twice
if (speakerOwner && speakerOwner->clientId == clientId) continue;
auto speakerPosition = speaker.getPos(speakerOwner);
if (speakerPosition.isNull()) continue;//Don't know its position
if (speakerPosition.getHeight() < 0) continue;//Speakers don't work underwater.. duh
result.emplace_back(
(currentTransmittingTangentOverType == sendingRadioType::LISTEN_TO_SW || ignoreSwTangent) ? sendingRadioType::LISTEN_TO_SW : sendingRadioType::LISTEN_TO_LR,
receivingRadioType::LISTED_ON_GROUND,
speaker.volume,
stereoMode::stereo,
speaker.radio_id,
speakerPosition,
speaker.waveZ,
speaker.vehicle,
antennaConnection);
}
} else {
DIAGLOG("IOR No spk? cusw=" + std::to_string(canUseSWRadio) + " culr=" + std::to_string(canUseLRRadio)+
" ttot="+std::to_string(static_cast<int>(currentTransmittingTangentOverType))+
" tfrq="+ getCurrentTransmittingFrequency());
}
return result;
}
void clientData::addModificationLog(std::string mod) {
LockGuard_exclusive lock(m_lock);
//Logger::log(LoggerTypes::pluginCommands, "mod " + mod);
modificationLog.emplace_back(std::move(mod));
}
std::vector<std::string> clientData::getModificationLog() const {
LockGuard_shared lock(m_lock);
return modificationLog;
}
void clientData::circularLog(const std::string& message) {
std::stringstream msg;
const auto now = std::chrono::system_clock::now();
const auto in_time_t = std::chrono::system_clock::to_time_t(now);
msg << std::put_time(std::localtime(&in_time_t), "%H:%M:%S") << " " << message;
LockGuard_exclusive lock(m_lock);
messages.push_back(msg.str());
if (++offset > messageCount) offset = 0;
}
void clientData::verboseDataLog(std::ostream& str) {
LockGuard_shared lock(m_lock);
logParam(pluginEnabled);
logParamN(clientId,clientId.baseType());
logParamN(currentTransmittingTangentOverType,static_cast<uint32_t>(currentTransmittingTangentOverType));
logParam(voiceVolume);
logParam(range);
logParam(canSpeak);
logParam(clientTalkingNow);
logParam(dataFrame);
logParam(canUseSWRadio);
logParam(canUseLRRadio);
logParam(canUseDDRadio);
logParam(terrainInterception);
logParam(objectInterception);
logParam(voiceVolumeMultiplifier);
logParam(isSpectating);
logParam(isEnemyToPlayer);
logParamN(receivingTransmission,static_cast<uint32_t>(receivingTransmission));
str << "receivingFrequencies:\n";
for (auto& it : receivingFrequencies) {
str << "\t" << it << "\n";
}
str << "modificationLog:\n";
for (auto& it : modificationLog) {
str << "\t" << it << "\n";
}
logParam(nickname);
logParamN(clientPosition, clientPosition.toString());
logParamN(viewDirection, viewDirection.toString());
auto in_time_t = std::chrono::system_clock::to_time_t(lastPositionUpdateTime);
str << "lastPositionUpdateTime " << std::put_time(std::localtime(&in_time_t), "%H:%M:%S") << "\n";
logParam(currentTransmittingFrequency);
logParam(currentTransmittingSubtype);
str << "vehicleId:\n";
str << "\tvehicleName " << vehicleId.vehicleName << "\n";
str << "\tvehicleIsolation " << vehicleId.vehicleIsolation << "\n";
str << "\tintercomSlot " << vehicleId.intercomSlot << "\n";
logParamN(velocity,velocity.toString());
}
| 44.576389 | 203 | 0.682661 |
560c318ccb48481b339258f541ef6ee72900450d | 387 | cpp | C++ | src/server/src/ca_check.cpp | Eothred/hpsim | 526a00a9d1affcb83b642ea2aef939925a76cad9 | [
"Unlicense"
] | 6 | 2018-04-30T08:03:24.000Z | 2021-11-10T00:17:34.000Z | src/server/src/ca_check.cpp | Eothred/hpsim | 526a00a9d1affcb83b642ea2aef939925a76cad9 | [
"Unlicense"
] | 1 | 2018-09-26T17:04:27.000Z | 2018-09-26T17:35:04.000Z | src/server/src/ca_check.cpp | Eothred/hpsim | 526a00a9d1affcb83b642ea2aef939925a76cad9 | [
"Unlicense"
] | 4 | 2017-11-14T14:36:48.000Z | 2020-01-14T13:51:16.000Z | #include <string>
#include <iostream>
#include "cadef.h"
bool CACheck(int r_status, std::string r_op, std::string r_pv)
{
if(r_status != ECA_NORMAL)
{
std::cerr << "CA Error: ";
if(r_pv.compare("") != 0)
std::cerr << r_op << " failure for PV: " << r_pv << std::endl;
else
std::cerr << r_op << " failure" << std::endl;
return false;
}
return true;
}
| 21.5 | 68 | 0.571059 |
560d337df5e08c9730025627181dfee90cc5575b | 5,309 | cpp | C++ | sandbox/src/main.cpp | backwardspy/leviathan | 0b53656a5cca0b80d1ac0ae3f176f37948d0675f | [
"MIT"
] | null | null | null | sandbox/src/main.cpp | backwardspy/leviathan | 0b53656a5cca0b80d1ac0ae3f176f37948d0675f | [
"MIT"
] | null | null | null | sandbox/src/main.cpp | backwardspy/leviathan | 0b53656a5cca0b80d1ac0ae3f176f37948d0675f | [
"MIT"
] | null | null | null | #include <leviathan/leviathan.h>
class CustomLayer : public lv::Layer {
public:
explicit CustomLayer(lv::Application& app) :
Layer("Custom"),
app(app),
window(app.get_window()),
ctx(app.get_render_context()),
ent_registry(app.get_ent_registry()),
camera(ent_registry.create()),
duck(ent_registry.create()) {
init_camera();
init_ducks();
}
private:
bool handle(lv::Event const& event) override {
switch (event.type) {
case lv::Event::Type::WindowResized:
ent_registry.get<lv::Camera>(camera).aspect_ratio = window.get_aspect_ratio();
break;
case lv::Event::Type::KeyPressed:
if (event.key.code == lv::KeyCode::Space) {
zoom_level = 0;
auto& [cam, transform] = ent_registry.get<lv::Camera, lv::Transform>(camera);
cam.ortho_size = 1.0f;
transform.position = glm::vec3(0);
}
break;
case lv::Event::Type::ButtonPressed:
if (event.button.code == lv::ButtonCode::Right) dragging = true;
break;
case lv::Event::Type::ButtonReleased:
if (event.button.code == lv::ButtonCode::Right) dragging = false;
break;
case lv::Event::Type::MouseMoved:
if (dragging) drag_camera(event.mouse.delta);
break;
case lv::Event::Type::MouseScrolled:
zoom_camera(static_cast<int>(event.mouse.delta.y));
break;
}
return false;
}
void gui() override {
auto const dt = lv::time::render_delta_time();
ImGui::Begin("Sandbox");
ImGui::Text("Performance: %.3f ms/frame (%.f fps)", lv::time::to_milliseconds(dt).count(), 1.0f / lv::time::to_seconds(dt).count());
ImGui::Text("Simulation Time: %.3f", lv::time::to_seconds(lv::time::elapsed()).count());
ImGui::End();
ImGui::Begin("Shader");
if (ImGui::ColorPicker4("Tint", glm::value_ptr(tint))) {
ent_registry.get<lv::MeshRenderer>(duck).material->set_parameter("Tint", tint);
}
ImGui::End();
}
void drag_camera(glm::vec2 mouse_delta) {
auto motion_ndc = 2.0f * mouse_delta / static_cast<glm::vec2>(window.get_size());
// usually we'd flip the Y, but since we're subtracting this motion anyway we flip the x instead
motion_ndc.x = -motion_ndc.x;
auto& [cam, transform] = ent_registry.get<lv::Camera, lv::Transform>(camera);
auto world_motion = cam.unproject(motion_ndc);
transform.position += glm::vec3(world_motion, 0);
}
void zoom_camera(int zoom) {
zoom_level += zoom;
auto mouse_pos = lv::remap(
lv::Input::get_mouse_position(),
glm::vec2(0),
static_cast<glm::vec2>(window.get_size()),
glm::vec2(-1),
glm::vec2(1)
);
mouse_pos.y = -mouse_pos.y;
auto& [cam, transform] = ent_registry.get<lv::Camera, lv::Transform>(camera);
auto pos_before = cam.unproject(mouse_pos);
cam.ortho_size = pow(1.1f, -zoom_level);
auto diff = pos_before - cam.unproject(mouse_pos);
transform.position += glm::vec3(diff, 0);
}
void init_camera() {
ent_registry.emplace<lv::Transform>(camera);
ent_registry.emplace<lv::Camera>(camera, lv::Camera::make_orthographic(1.0f, window.get_aspect_ratio()));
}
void init_ducks() {
auto shader = ctx.make_shader("assets/shaders/unlit_generic.glsl", { lv::Shader::Type::Vertex, lv::Shader::Type::Pixel });
shader->set_alpha_blend(true);
auto material = ctx.make_material(shader);
material->set_texture("MainTex", 0, ctx.make_texture("assets/textures/duck.png"));
material->set_parameter("Tint", tint);
auto vertex_array = [&ctx = ctx] {
return ctx.make_vertex_array(
{
lv::Vertex{ glm::vec3(-0.5f, 0.5f, 0), glm::vec4(1), glm::vec2(0) },
lv::Vertex{ glm::vec3(0.5f, 0.5f, 0), glm::vec4(1), glm::vec2(1, 0) },
lv::Vertex{ glm::vec3(-0.5f, -0.5f, 0), glm::vec4(1), glm::vec2(0, 1) },
lv::Vertex{ glm::vec3(0.5f, -0.5f, 0), glm::vec4(1), glm::vec2(1) },
}, {
0, 1, 2,
1, 3, 2
});
}();
ent_registry.emplace<lv::Transform>(duck);
ent_registry.emplace<lv::MeshRenderer>(duck, material, vertex_array);
}
private:
lv::Application& app;
lv::Window& window;
lv::Context& ctx;
entt::registry& ent_registry;
entt::entity camera, duck;
int zoom_level = 0;
bool dragging = false;
glm::vec2 drag_start {};
// shader params
glm::vec4 tint = glm::vec4(1.0f);
};
class Sandbox : public lv::Application {
protected:
virtual lv::LayerVector get_layers() override {
lv::LayerVector layers;
layers.push_back(lv::make_scope<CustomLayer>(*this));
return layers;
}
};
lv::scope<lv::Application> lv::CreateApplication() {
return lv::make_scope<Sandbox>();
} | 35.15894 | 140 | 0.559427 |
560df1042a482b6fc705bf40aaae20c8924c6231 | 8,066 | cpp | C++ | test/math.t.cpp | ltjax/replay | 33680beae225c9c388f33e3f7ffd7e8bae4643e9 | [
"MIT"
] | 1 | 2015-09-15T19:52:50.000Z | 2015-09-15T19:52:50.000Z | test/math.t.cpp | ltjax/replay | 33680beae225c9c388f33e3f7ffd7e8bae4643e9 | [
"MIT"
] | 3 | 2017-12-03T21:53:09.000Z | 2019-11-23T02:11:50.000Z | test/math.t.cpp | ltjax/replay | 33680beae225c9c388f33e3f7ffd7e8bae4643e9 | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include <replay/math.hpp>
#include <replay/matrix2.hpp>
#include <replay/minimal_sphere.hpp>
#include <replay/vector_math.hpp>
#include <boost/math/constants/constants.hpp>
#include <random>
namespace
{
// FIXME: this is somewhat generically useful - lift it to a visible namespace?
replay::vector3f polar_to_model(float latitude, float longitude)
{
latitude = replay::math::convert_to_radians(latitude);
longitude = replay::math::convert_to_radians(longitude);
float cw = std::cos(latitude);
float sw = std::sin(latitude);
float ch = std::cos(longitude);
float sh = std::sin(longitude);
return {cw * ch, sw * ch, sh};
}
template <class IteratorType>
float distance_to_sphere(const IteratorType point_begin,
const IteratorType point_end,
const replay::vector3f& center,
const float square_radius)
{
float max_sqr_distance = 0.f;
for (IteratorType i = point_begin; i != point_end; ++i)
{
const float sqr_distance = (center - (*i)).squared();
max_sqr_distance = std::max(max_sqr_distance, sqr_distance);
}
float radius = std::sqrt(square_radius);
return std::max(0.f, std::sqrt(max_sqr_distance) - radius);
}
} // namespace
TEST_CASE("matrix2_operations")
{
using namespace replay;
matrix2 Rotation = matrix2::make_rotation(boost::math::constants::pi<float>() * 0.25f); // 45deg rotation
matrix2 Inv = Rotation;
REQUIRE(Inv.invert());
using math::fuzzy_equals;
using math::fuzzy_zero;
matrix2 I = Rotation * Inv;
// This should be identity
REQUIRE(fuzzy_equals(I[0], 1.f));
REQUIRE(fuzzy_zero(I[1]));
REQUIRE(fuzzy_zero(I[2]));
REQUIRE(fuzzy_equals(I[3], 1.f));
I = Inv * Rotation;
// This should be identity
REQUIRE(fuzzy_equals(I[0], 1.f));
REQUIRE(fuzzy_zero(I[1]));
REQUIRE(fuzzy_zero(I[2]));
REQUIRE(fuzzy_equals(I[3], 1.f));
}
// This test verifies integer arithmetic with a vector3.
// Hopefully, floating-point math will behave correct if this does.
TEST_CASE("vector3_integer_operations")
{
using namespace replay;
typedef vector3<int> vec3;
const vec3 a(-1, -67, 32);
const vec3 b(7777, 0, -111);
const vec3 c(a - b);
REQUIRE(c - a == -b);
const vec3 all_one(1, 1, 1);
REQUIRE(all_one.sum() == 3);
REQUIRE(all_one.squared() == 3);
int checksum = dot(a, all_one);
REQUIRE(checksum == a.sum());
checksum = dot(b, all_one);
REQUIRE(checksum == b.sum());
REQUIRE(a.sum() - b.sum() == c.sum());
REQUIRE((a * 42).sum()== a.sum() * 42);
const vec3 all_two(2, 2, 2);
REQUIRE(all_one * 2== all_two);
REQUIRE(all_one + all_one== all_two);
}
TEST_CASE("quadratic_equation_solver")
{
using namespace replay;
using range_type = std::uniform_real_distribution<float>;
// Attempt to solve a few equations of the form (x-b)(x-a)=0 <=> x^2+(-a-b)*x+b*a=0
std::mt19937 rng;
range_type range(-100.f, 300.f);
auto die = [&] { return range(rng); };
for (std::size_t i = 0; i < 32; ++i)
{
float a = die();
float b = die();
if (replay::math::fuzzy_equals(a, b))
continue;
interval<> r;
// FIXME: use a relative epsilon
math::solve_quadratic_eq(1.f, -a - b, a * b, r, 0.001f);
if (a > b)
std::swap(a, b);
REQUIRE(r[0] == Approx(a).margin(0.01f));
REQUIRE(r[1] == Approx(b).margin(0.01f));
}
}
TEST_CASE("matrix4_determinant_simple")
{
using namespace replay;
matrix4 M(0.f, 0.f, 3.f, 0.f, 4.f, 0.f, 0.f, 0.f, 0.f, 2.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);
float d = M.determinant();
REQUIRE(d == Approx(24.f).margin(0.0001f));
matrix4 N(2.f, 1.f, 0.f, 0.f, 1.f, 2.f, 1.f, 0.f, 0.f, 1.f, 2.f, 1.f, 0.f, 0.f, 1.f, 2.f);
float e = N.determinant();
REQUIRE(e == Approx(5.f).margin(0.0001f));
}
TEST_CASE("circumcircle")
{
using namespace replay;
// Construct a rotational matrix
vector3f x = polar_to_model(177.f, -34.f);
vector3f y = normalized(math::construct_perpendicular(x));
matrix3 M(x, y, cross(x, y));
// Construct three points on a circle and rotate them
const float radius = 14.f;
float angle = math::convert_to_radians(34.f);
vector3f a = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);
angle = math::convert_to_radians(134.f);
vector3f b = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);
angle = math::convert_to_radians(270.f);
vector3f c = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);
// Move the circle
const vector3f center(45.f, 32.f, -37.f);
a += center;
b += center;
c += center;
// Reconstruct it
equisphere<float, 3> s(1e-16f);
REQUIRE(s.push(a.ptr()));
REQUIRE(s.push(b.ptr()));
REQUIRE(s.push(c.ptr()));
vector3f equisphere_center(vector3f::cast(s.get_center()));
vector3f center_delta = center - equisphere_center;
REQUIRE(center_delta.squared() < 0.001f);
REQUIRE(std::sqrt(s.get_squared_radius()) == Approx(radius).margin(0.001f));
}
// Simple test case directly testing the minimal ball solver in 3D
TEST_CASE("minimal_ball")
{
using namespace replay;
typedef vector3f vec3;
using range_type = std::uniform_real_distribution<float>;
// setup random number generators
std::mt19937 rng;
auto random_latitude = [&] { return range_type(-180.f, 180.f)(rng); };
auto random_longitude = [&] { return range_type(-90.f, 90.f)(rng); };
auto random_scale = [&] { return range_type(0.f, 1.0f)(rng); };
// setup a simple point set
std::list<vec3> points{ vec3(1.f, 0.f, 0.f), vec3(0.f, 1.f, 0.f), vec3(0.f, 0.f, 1.f), vec3(0.f, -1.f, 0.f) };
for (std::size_t i = 0; i < 32; ++i)
{
vector3f t = polar_to_model(random_latitude(), random_longitude());
float s = random_scale();
points.push_back(t * s);
}
// run the solver
replay::minimal_ball<float, replay::vector3f, 3> ball(points, 1e-15f);
// check correctness
REQUIRE(ball.square_radius() == Approx(1.f).margin(0.001f));
REQUIRE(ball.center().squared() < 0.001f);
REQUIRE(distance_to_sphere(points.begin(), points.end(), ball.center(), ball.square_radius()) < 0.001f);
}
// Slightly more sophisticated test for the minimal ball routines using
// the wrapper from vector_math.hpp and an std::vector
TEST_CASE("minimal_sphere")
{
using namespace replay;
using range_type = std::uniform_real_distribution<float>;
std::mt19937 rng;
auto random_coord = [&] { return range_type(-100.f, 100.f)(rng); };
auto random_radius = [&] { return range_type(1.f, 3.f)(rng); };
auto random_latitude = [&] { return range_type(-180.f, 180.f)(rng); };
auto random_longitude = [&] { return range_type(-90.f, 90.f)(rng); };
auto random_scale = [&] { return range_type(0.0f, 1.0f)(rng); };
std::vector<vector3f> p(64);
for (std::size_t i = 0; i < 16; ++i)
{
const vector3f center(random_coord(), random_coord(), random_coord());
const float radius = random_radius();
std::size_t boundary_n = 2 + rng() % 3;
for (std::size_t j = 0; j < boundary_n; ++j)
p[j] = center + polar_to_model(random_latitude(), random_longitude()) * radius;
for (std::size_t j = boundary_n; j < 64; ++j)
p[j] = center + polar_to_model(random_latitude(), random_longitude()) * (random_scale() * radius);
std::shuffle(p.begin(), p.end(), rng);
auto const [result_center, result_square_radius] = math::minimal_sphere(p);
float square_radius = radius * radius;
// The generated boundary doesn't necessarily define the minimal ball, but it's an upper bound
REQUIRE(result_square_radius <= Approx(square_radius).margin(0.0001));
REQUIRE(distance_to_sphere(p.begin(), p.end(), result_center, result_square_radius) < 0.001f);
}
} | 31.263566 | 114 | 0.621994 |
5611367c686b3c2a208246818dffb47235350c88 | 983 | cpp | C++ | engine/utils.cpp | inexinferis/sXeMu | 70705553033228c98de2608ca2be6231065f83cf | [
"MIT"
] | 1 | 2021-06-04T02:34:55.000Z | 2021-06-04T02:34:55.000Z | engine/utils.cpp | inexinferis/sXeMu | 70705553033228c98de2608ca2be6231065f83cf | [
"MIT"
] | null | null | null | engine/utils.cpp | inexinferis/sXeMu | 70705553033228c98de2608ca2be6231065f83cf | [
"MIT"
] | 6 | 2019-04-03T14:01:36.000Z | 2020-04-19T01:54:34.000Z | #include "utils.h"
#include <windows.h>
extern cl_enginefuncs_s gEngfuncs;
void cGetFunc::Init(){}
pfnCommand cGetFunc::GetAddCommand(PCHAR name){
PBYTE address=(PBYTE)gEngfuncs.pfnAddCommand+0x1B;
command_t *uml=*(command_t**)(*(PDWORD)((address+*((PDWORD)address)+4)+0x0D));
while(uml){
if(!strncmp(uml->name,name,16))
return uml->pfn;
uml=uml->next;
}
return 0;
}
pfnEventHook cGetFunc::GetHookEvent(PCHAR name){
PBYTE address=(PBYTE)gEngfuncs.pfnHookEvent+0x1B;
event_t *uml=*(event_t**)(*(PDWORD)((address+*(PDWORD)(address)+4)+0x0D));
while(uml){
if(!strncmp(uml->name,name,16))
return uml->pfn;
uml=uml->next;
}
return 0;
}
pfnUserMsgHook cGetFunc::GetHookUserMsg(PCHAR name){
PBYTE address=(PBYTE)gEngfuncs.pfnHookUserMsg+0x1B;;
usermsg_t *uml=*(usermsg_t**)(*(PDWORD)((address+*(PDWORD)(address)+4)+0x0D));
while(uml){
if(!strncmp(uml->name,name,16))
return uml->pfn;
uml=uml->next;
}
return 0;
}
| 24.575 | 80 | 0.670397 |
56139a49800d5032c797beff52bcc9559e664d2b | 4,059 | cpp | C++ | WebKit/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | WebKit/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | WebKit/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BitLockerSkia.h"
#include "IntRect.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkRegion.h"
#include <CoreGraphics/CoreGraphics.h>
namespace WebCore {
static CGAffineTransform SkMatrixToCGAffineTransform(const SkMatrix& matrix)
{
// CGAffineTransforms don't support perspective transforms, so make sure
// we don't get those.
ASSERT(!matrix[SkMatrix::kMPersp0]);
ASSERT(!matrix[SkMatrix::kMPersp1]);
ASSERT(matrix[SkMatrix::kMPersp2] == 1.0f);
return CGAffineTransformMake(
matrix[SkMatrix::kMScaleX],
matrix[SkMatrix::kMSkewY],
matrix[SkMatrix::kMSkewX],
matrix[SkMatrix::kMScaleY],
matrix[SkMatrix::kMTransX],
matrix[SkMatrix::kMTransY]);
}
BitLockerSkia::BitLockerSkia(SkCanvas* canvas)
: m_canvas(canvas)
, m_cgContext(0)
{
}
BitLockerSkia::~BitLockerSkia()
{
releaseIfNeeded();
}
void BitLockerSkia::releaseIfNeeded()
{
if (!m_cgContext)
return;
m_canvas->getDevice()->accessBitmap(true).unlockPixels();
CGContextRelease(m_cgContext);
m_cgContext = 0;
}
CGContextRef BitLockerSkia::cgContext()
{
SkDevice* device = m_canvas->getDevice();
ASSERT(device);
if (!device)
return 0;
releaseIfNeeded();
const SkBitmap& bitmap = device->accessBitmap(true);
bitmap.lockPixels();
void* pixels = bitmap.getPixels();
m_cgContext = CGBitmapContextCreate(pixels, device->width(),
device->height(), 8, bitmap.rowBytes(), CGColorSpaceCreateDeviceRGB(),
kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst);
// Apply device matrix.
CGAffineTransform contentsTransform = CGAffineTransformMakeScale(1, -1);
contentsTransform = CGAffineTransformTranslate(contentsTransform, 0, -device->height());
CGContextConcatCTM(m_cgContext, contentsTransform);
// Apply clip in device coordinates.
CGMutablePathRef clipPath = CGPathCreateMutable();
SkRegion::Iterator iter(m_canvas->getTotalClip());
for (; !iter.done(); iter.next()) {
IntRect rect = iter.rect();
CGPathAddRect(clipPath, 0, rect);
}
CGContextAddPath(m_cgContext, clipPath);
CGContextClip(m_cgContext);
CGPathRelease(clipPath);
// Apply content matrix.
const SkMatrix& skMatrix = m_canvas->getTotalMatrix();
CGAffineTransform affine = SkMatrixToCGAffineTransform(skMatrix);
CGContextConcatCTM(m_cgContext, affine);
return m_cgContext;
}
}
| 33.825 | 92 | 0.725055 |
5618e356badef6dedb972f4a7c2ea09ff7dbfcd2 | 275 | hpp | C++ | src/modules/osg/generated_code/vector_less__bool__greater_.pypp.hpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osg/generated_code/vector_less__bool__greater_.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osg/generated_code/vector_less__bool__greater_.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#ifndef vector_less__bool__greater__hpp__pyplusplus_wrapper
#define vector_less__bool__greater__hpp__pyplusplus_wrapper
void register_vector_less__bool__greater__class();
#endif//vector_less__bool__greater__hpp__pyplusplus_wrapper
| 30.555556 | 59 | 0.887273 |
562072287f24126f19d8fae38014768b89bbfb53 | 6,232 | cpp | C++ | EndGame/EndGame/Src/SubSystems/RenderSubSystem/Renderer2D.cpp | siddharthgarg4/EndGame | ba608714b3eacb5dc05d0c852db573231c867d8b | [
"MIT"
] | null | null | null | EndGame/EndGame/Src/SubSystems/RenderSubSystem/Renderer2D.cpp | siddharthgarg4/EndGame | ba608714b3eacb5dc05d0c852db573231c867d8b | [
"MIT"
] | null | null | null | EndGame/EndGame/Src/SubSystems/RenderSubSystem/Renderer2D.cpp | siddharthgarg4/EndGame | ba608714b3eacb5dc05d0c852db573231c867d8b | [
"MIT"
] | null | null | null | //
// Renderer2D.cpp
//
//
// Created by Siddharth on 09/07/20.
//
#include "Renderer2D.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <EndGame/Src/SubSystems/RenderSubSystem/RenderCommand.h>
#include <EndGame/Src/SubSystems/RenderSubSystem/RenderApiFactory.hpp>
namespace EndGame {
Renderer2DStorage *Renderer2D::storage = nullptr;
void Renderer2D::init() {
//init storage
storage = new Renderer2DStorage();
storage->quadVertexArray = RenderApiFactory::createVertexArray();
//vertex buffer
storage->quadVertexBuffer = RenderApiFactory::createVertexBuffer(storage->maxQuadVerticesPerDraw * sizeof(QuadVertexData));
storage->quadVertexBuffer->setLayout({
{ShaderDataType::Float3, "attrPosition"},
{ShaderDataType::Float4, "attrColor"},
{ShaderDataType::Float2, "attrTextureCoord"},
{ShaderDataType::Float, "attrTextureIndex"},
{ShaderDataType::Float, "attrTilingFactor"}
});
storage->quadVertexArray->addVertexBuffer(storage->quadVertexBuffer);
//index buffer
uint32_t *quadIndices = new uint32_t[storage->maxQuadIndicesPerDraw];
for (uint32_t offset=0, i=0; i<storage->maxQuadIndicesPerDraw; i+=6) {
quadIndices[i+0] = offset+0;
quadIndices[i+1] = offset+1;
quadIndices[i+2] = offset+2;
quadIndices[i+3] = offset+2;
quadIndices[i+4] = offset+3;
quadIndices[i+5] = offset+0;
offset+=4;
}
std::shared_ptr<IndexBuffer> quadIndexBuffer = RenderApiFactory::createIndexBuffer(storage->maxQuadIndicesPerDraw * sizeof(uint32_t), quadIndices);
storage->quadVertexArray->setIndexBuffer(quadIndexBuffer);
delete[] quadIndices;
//shader
storage->quadShader = RenderApiFactory::createShader("Sandbox/Quad.glsl");
storage->quadShader->bind();
//setting sampler slots
std::shared_ptr<int32_t> samplers(new int32_t[storage->maxFragmentTextureSlots], std::default_delete<int[]>());
for (int32_t i=0; i<storage->maxFragmentTextureSlots; i++) {
samplers.get()[i] = i;
}
storage->quadShader->uploadUniform("u_textures", samplers, storage->maxFragmentTextureSlots);
}
void Renderer2D::shutdown() {
delete storage;
}
void Renderer2D::beginScene(const OrthographicCamera &camera) {
storage->quadShader->bind();
storage->quadShader->uploadUniform("u_viewProjection", camera.getViewProjectionMatrix());
beginNewBatch();
}
void Renderer2D::endScene() {
flushVertexBuffer();
}
void Renderer2D::flushVertexBuffer() {
//sort quadVertexBufferData by z-index to render textures with lower z index first
std::sort(storage->quadVertexBufferData.begin(), storage->quadVertexBufferData.begin() + storage->quadVertexBufferDataSize, [](const QuadVertexData &first, const QuadVertexData &second){
return first.position.z < second.position.z;
});
storage->quadShader->bind();
storage->quadVertexBuffer->setData(storage->quadVertexBufferDataSize * sizeof(QuadVertexData), storage->quadVertexBufferData.data());
storage->quadVertexArray->bind();
//bind all texture slots
for (uint32_t i=0; i<storage->textureSlotsDataSize; i++) {
storage->textureSlots[i]->bind(i);
}
//each quad is 6 indices (2 triangles)
uint32_t numberOfQuads = storage->quadVertexBufferDataSize/4;
RenderCommand::drawIndexed(storage->quadVertexArray, numberOfQuads*6);
}
void Renderer2D::drawQuad(QuadRendererData data, bool shouldRotate) {
//pushing to local buffer until data can be accomodated
if (storage->quadVertexBufferDataSize >= storage->maxQuadVerticesPerDraw ||
storage->textureSlotsDataSize >= storage->maxFragmentTextureSlots) {
//flush if we reach max quads or max textures
flushVertexBuffer();
beginNewBatch();
}
//transforms
glm::mat4 transform = glm::translate(glm::mat4(1.0f), data.position);
if (shouldRotate) {
transform *= glm::rotate(glm::mat4(1.0f), glm::radians(data.rotation), {0, 0, 1});
}
transform *= glm::scale(glm::mat4(1.0f), {data.size.x, data.size.y, 1.0f});
//textures - switch in shader defaults to no texture
float textureIndex = -1.0f;
if (data.texture != nullptr) {
//if quad has texture
for (uint32_t i=0; i<storage->textureSlotsDataSize; i++) {
if (*storage->textureSlots[i].get() == *data.texture.get()) {
textureIndex = (float)i;
break;
}
}
//texture hasn't been used before
if (textureIndex == -1.0f) {
textureIndex = (float)storage->textureSlotsDataSize;
addTextureSlot(data.texture);
}
}
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[0], data.color, {0.0f, 0.0f}, textureIndex, data.tilingFactor));
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[1], data.color, {1.0f, 0.0f}, textureIndex, data.tilingFactor));
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[2], data.color, {1.0f, 1.0f}, textureIndex, data.tilingFactor));
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[3], data.color, {0.0f, 1.0f}, textureIndex, data.tilingFactor));
}
void Renderer2D::beginNewBatch() {
storage->quadVertexBufferDataSize = 0;
storage->textureSlotsDataSize = 0;
}
void Renderer2D::addQuadVertexData(const QuadVertexData &data) {
storage->quadVertexBufferData[storage->quadVertexBufferDataSize] = data;
storage->quadVertexBufferDataSize++;
}
void Renderer2D::addTextureSlot(std::shared_ptr<Texture2D> texture) {
storage->textureSlots[storage->textureSlotsDataSize] = texture;
storage->textureSlotsDataSize++;
}
} | 45.823529 | 194 | 0.648748 |
56223febd33a024d24f2bee3f67e5889466d8b60 | 1,923 | cpp | C++ | intro/knight_scape.cpp | eder-matheus/programming_challenges | 9d318bf5b8df18f732c07e60aa72b302ea887419 | [
"BSD-3-Clause"
] | null | null | null | intro/knight_scape.cpp | eder-matheus/programming_challenges | 9d318bf5b8df18f732c07e60aa72b302ea887419 | [
"BSD-3-Clause"
] | null | null | null | intro/knight_scape.cpp | eder-matheus/programming_challenges | 9d318bf5b8df18f732c07e60aa72b302ea887419 | [
"BSD-3-Clause"
] | 1 | 2021-08-24T17:18:54.000Z | 2021-08-24T17:18:54.000Z | // knight scape
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
const int dimension = 8;
const int num_pieces = 9;
void findKnightMoviments(int row, int col, std::vector<std::pair<int, int> >& movements) {
for (int r = -2; r <= 2; r++) {
for (int c = -2; c <= 2; c++) {
if ((abs(r) == 2 && abs(c) == 1) ||
(abs(r) == 1 && abs(c) == 2)) {
if (((row + r) >= 0 && (row + r) < dimension) &&
((col + c) >= 0 && (col + c) < dimension)) {
movements.push_back(std::pair<int, int>(row+r, col+c));
}
}
}
}
}
void findPawnsAttacks(int row, int col, std::vector<std::pair<int, int> >& movements) {
int attack_row = row - 1;
int attack_col1 = col + 1;
int attack_col2 = col - 1;
if (attack_row < dimension) {
if (attack_col1 < dimension) {
movements.erase(
std::remove(
movements.begin(),
movements.end(),
std::pair<int, int>(attack_row, attack_col1)),
movements.end());
}
if (attack_col2 >= 0) {
movements.erase(
std::remove(
movements.begin(),
movements.end(),
std::pair<int, int>(attack_row, attack_col2)),
movements.end());
}
}
}
int main() {
int row = -1;
char column;
std::vector<std::pair<int, int> > movements;
int cnt = 0;
int test = 1;
while (row != 0) {
scanf("%d%c", &row, &column);
int col = (int)column - 96;
// first row of input --> knight position
if (cnt == 0) {
findKnightMoviments(row-1, col-1, movements);
} else { // other rows --> pawns position
findPawnsAttacks(row-1, col-1, movements);
}
cnt++;
if (cnt == num_pieces) {
std::cout << "Caso de Teste #" << test << ": " << movements.size() << " movimento(s).\n";
cnt = 0;
test++;
movements.clear();
}
}
return 0;
}
| 24.341772 | 95 | 0.514301 |
5622aa0f33e74cba4f4bb881ff2fc714394f2d5d | 4,264 | cpp | C++ | wnd/block_info_dlg.cpp | HyperBlockChain/Hyperchain-Core-YH | 2a7c4ac23f27c2034a678e61c2474e0008f5135e | [
"MIT"
] | 1 | 2019-08-30T07:36:33.000Z | 2019-08-30T07:36:33.000Z | wnd/block_info_dlg.cpp | HyperBlockChain/Hyperchain-Core-YH | 2a7c4ac23f27c2034a678e61c2474e0008f5135e | [
"MIT"
] | null | null | null | wnd/block_info_dlg.cpp | HyperBlockChain/Hyperchain-Core-YH | 2a7c4ac23f27c2034a678e61c2474e0008f5135e | [
"MIT"
] | 2 | 2019-11-01T03:39:57.000Z | 2020-03-26T06:21:22.000Z | /*Copyright 2016-2018 hyperchain.net (Hyperchain)
Distributed under the MIT software license, see the accompanying
file COPYING or https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "block_info_dlg.h"
#include "customui/base_frameless_wnd.h"
#include "channel/block_info_channel.h"
#include <QTextCodec>
#include <QtWebEngineWidgets/QWebEngineSettings>
#include <QtWebEngineWidgets/QWebEngineView>
#include <QtWebChannel/QWebChannel>
#include <QApplication>
#include <QVariantMap>
#include <QDebug>
block_info_dlg::block_info_dlg(QObject *parent) : QObject(parent)
{
QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
init();
}
void block_info_dlg::show(bool bShow)
{
dlg_->setHidden(!bShow);
}
void block_info_dlg::setGeometry(QRect rect)
{
dlg_->setGeometry(rect);
}
void block_info_dlg::refreshNodeInfo(QSharedPointer<TBLOCKINFO> pNodeInfo)
{
static int64 MAX_TIME_S = 9999999999;
QVariantMap m;
m["blockNum"] = (qint64)(pNodeInfo->iBlockNo);
m["fileName"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cFileName);
m["customInfo"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cCustomInfo);
m["rightOwner"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cRightOwner);
m["fileHash"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cFileHash);
m["regTime"] = (qint64)(pNodeInfo->tPoeRecordInfo.tRegisTime);
m["fileSize"] = (qint64)(pNodeInfo->tPoeRecordInfo.iFileSize);
m["fileState"] = pNodeInfo->tPoeRecordInfo.iFileState;
emit reg_->sigNewBlockInfo(m);
}
bool block_info_dlg::hasFcous()
{
return dlg_->hasFocus();
}
void block_info_dlg::setFocus()
{
dlg_->setFocus();
}
void block_info_dlg::setLanguage(int lang)
{
reg_->sigChangeLang(lang);
}
void block_info_dlg::onMouseEnter(QEvent *event)
{
mouseEnter_ = true;
}
void block_info_dlg::onMouseLeave(QEvent *event)
{
mouseEnter_ = false;
dlg_->hide();
}
void block_info_dlg::init()
{
dlg_ = QSharedPointer<base_frameless_wnd>(new base_frameless_wnd());
dlg_->setScale(false);
dlg_->showTitleBar(false);
dlg_->setGeometry(QRect(0,0,200,300));
dlg_->hide();
connect(dlg_.data(), &base_frameless_wnd::sigEnter, this, &block_info_dlg::onMouseEnter);
connect(dlg_.data(), &base_frameless_wnd::sigLeave, this, &block_info_dlg::onMouseLeave);
Qt::WindowFlags flags = dlg_->windowFlags();
flags |= Qt::ToolTip;
dlg_->setWindowFlags(flags);
view_ = new QWebEngineView((QWidget*)dlg_.data()->content_);
view_->setAcceptDrops(false);
dlg_->addWidget(view_);
QWebChannel *channel = new QWebChannel(this);
reg_ = new block_info_channel(this);
channel->registerObject(QString("qBlockInfo"), reg_);
view_->page()->setWebChannel(channel);
#ifdef QT_DEBUG
#if defined (Q_OS_WIN)
QString str = QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("../../ui/view/blockinfo.html");
#else
QString str = QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("../ui/view/blockinfo.html");
#endif
#else
QString str = QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("ui/view/blockinfo.html");
#endif
view_->page()->load(QUrl(str));
}
| 30.457143 | 123 | 0.739212 |
56275bb9eac3f7c05bcc5aaabc4a9261e55c7d7f | 26,432 | cpp | C++ | code_reading/oceanbase-master/unittest/sql/engine/sort/ob_sort_test.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/unittest/sql/engine/sort/ob_sort_test.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/unittest/sql/engine/sort/ob_sort_test.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "sql/engine/sort/ob_sort.h"
#include "sql/session/ob_sql_session_info.h"
#include "sql/engine/ob_physical_plan.h"
#include "lib/utility/ob_test_util.h"
#include "lib/utility/ob_tracepoint.h"
#include "lib/container/ob_se_array.h"
#include <gtest/gtest.h>
#include "ob_fake_table.h"
#include "sql/engine/ob_exec_context.h"
#include "share/ob_worker.h"
#include "observer/ob_signal_handle.h"
#include "storage/blocksstable/ob_data_file_prepare.h"
#include "observer/omt/ob_tenant_config_mgr.h"
#include <thread>
#include <vector>
#include <gtest/gtest.h>
using namespace oceanbase;
using namespace oceanbase::sql;
using namespace oceanbase::omt;
using namespace oceanbase::common;
using oceanbase::sql::test::ObFakeTable;
#define TEST_SORT_DUMP_GET_HASH_AREA_SIZE() (get_sort_area_size())
#define TEST_SORT_DUMP_SET_HASH_AREA_SIZE(size) (set_sort_area_size(size))
class ObSortTest : public blocksstable::TestDataFilePrepare {
public:
ObSortTest();
virtual ~ObSortTest();
private:
// disallow copy
ObSortTest(const ObSortTest& other);
ObSortTest& operator=(const ObSortTest& other);
protected:
virtual void SetUp() override
{
GCONF.enable_sql_operator_dump.set_value("True");
ASSERT_EQ(OB_SUCCESS, init_tenant_mgr());
blocksstable::TestDataFilePrepare::SetUp();
}
virtual void TearDown() override
{
blocksstable::TestDataFilePrepare::TearDown();
destroy_tenant_mgr();
}
int init_tenant_mgr();
int64_t get_sort_area_size()
{
int64_t sort_area_size = 0;
int ret = OB_SUCCESS;
ret = ObSqlWorkareaUtil::get_workarea_size(SORT_WORK_AREA, OB_SYS_TENANT_ID, sort_area_size);
if (OB_FAIL(ret)) {
SQL_ENG_LOG(WARN, "failed to get hash area size", K(ret), K(sort_area_size));
}
return sort_area_size;
}
void set_sort_area_size(int64_t size)
{
int ret = OB_SUCCESS;
int64_t tenant_id = OB_SYS_TENANT_ID;
ObTenantConfigGuard tenant_config(TENANT_CONF(tenant_id));
if (tenant_config.is_valid()) {
tenant_config->_sort_area_size = size;
} else {
ret = OB_ERR_UNEXPECTED;
SQL_ENG_LOG(WARN, "unexpected status: config is invalid", K(tenant_id));
}
// ASSERT_EQ(OB_SUCCESS, ret);
}
void destroy_tenant_mgr()
{
ObTenantManager::get_instance().destroy();
}
template <typename SortInit>
void sort_test(int64_t row_count, int64_t mem_limit, SortInit sort_init, int64_t verify_row_cnt = -1,
bool local_merge_sort = false);
void sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1, int64_t sort_col2,
ObCollationType cs_type2);
void local_merge_sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1,
int64_t sort_col2, ObCollationType cs_type2);
void serialize_test();
void sort_exception_test(int expect_ret);
private:
static void copy_cell_varchar(ObObj& cell, char* buf, int64_t buf_size)
{
ObString str;
ASSERT_EQ(OB_SUCCESS, cell.get_varchar(str));
ASSERT_TRUE(str.length() < buf_size);
memcpy(buf, str.ptr(), str.length());
str.assign_ptr(buf, str.length());
cell.set_varchar(str);
return;
}
void cons_op_schema_objs(const ObIArray<ObSortColumn>& sort_columns, ObIArray<ObOpSchemaObj>& op_schema_objs)
{
for (int64_t i = 0; i < sort_columns.count(); i++) {
ObOpSchemaObj op_schema_obj;
if (0 == sort_columns.at(i).index_) {
op_schema_obj.obj_type_ = common::ObVarcharType;
} else {
op_schema_obj.obj_type_ = common::ObIntType;
}
op_schema_objs.push_back(op_schema_obj);
}
return;
}
};
class ObSortPlan {
public:
static ObSort& get_instance()
{
return *sort_;
}
template <typename SortInit>
static int init(int64_t row_count, int64_t mem_limit, SortInit sort_init)
{
if (mem_limit <= 0) {
mem_limit = 1 << 20;
}
int ret = OB_SUCCESS;
sort_->set_id(0);
input_table_->set_id(1);
sort_->set_column_count(input_table_->get_column_count());
sort_->set_mem_limit(mem_limit);
int64_t tenant_id = OB_SYS_TENANT_ID;
ObTenantConfigGuard tenant_config(TENANT_CONF(tenant_id));
if (tenant_config.is_valid()) {
tenant_config->_sort_area_size = mem_limit;
} else {
ret = OB_ERR_UNEXPECTED;
SQL_ENG_LOG(WARN, "unexpected status: config is invalid", K(tenant_id));
}
cons_run_filename(*filename_);
input_table_->set_row_count(row_count);
input_table_->set_phy_plan(physical_plan_);
sort_->set_phy_plan(physical_plan_);
row_count_ = row_count;
if (OB_FAIL(sort_->set_child(0, *input_table_))) {
} else if (OB_FAIL(sort_init(*sort_))) {
}
return ret;
}
static void set_local_merge_sort()
{
sort_->set_local_merge_sort(true);
}
static int init(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1, int64_t sort_col2,
ObCollationType cs_type2)
{
return init(row_count, mem_limit, [&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col1, cs_type1, false, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col2, cs_type2, true, ObMaxType, default_asc_direction()))) {
}
return ret;
});
}
static void reset()
{
sort_->reset();
input_table_->reset();
row_count_ = -1;
}
static void reuse()
{
sort_->reuse();
input_table_->reuse();
row_count_ = -1;
}
private:
ObSortPlan();
static void cons_run_filename(ObString& filename)
{
char* filename_buf = (char*)"ob_sort_test.run";
filename.assign_ptr(filename_buf, (int32_t)strlen(filename_buf));
return;
}
public:
private:
static ObPhysicalPlan* physical_plan_;
static ObFakeTable* input_table_;
static ObSort* sort_;
static int64_t row_count_;
static ObString* filename_;
};
ObSortTest::ObSortTest() : blocksstable::TestDataFilePrepare("TestDiskIR", 2 << 20, 2000)
{}
ObSortTest::~ObSortTest()
{}
int ObSortTest::init_tenant_mgr()
{
int ret = OB_SUCCESS;
ObTenantManager& tm = ObTenantManager::get_instance();
ObAddr self;
oceanbase::rpc::frame::ObReqTransport req_transport(NULL, NULL);
oceanbase::obrpc::ObSrvRpcProxy rpc_proxy;
oceanbase::obrpc::ObCommonRpcProxy rs_rpc_proxy;
oceanbase::share::ObRsMgr rs_mgr;
int64_t tenant_id = 1;
self.set_ip_addr("127.0.0.1", 8086);
ret = ObTenantConfigMgr::get_instance().add_tenant_config(tenant_id);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.init(self, rpc_proxy, rs_rpc_proxy, rs_mgr, &req_transport, &ObServerConfig::get_instance());
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.add_tenant(tenant_id);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.set_tenant_mem_limit(tenant_id, 2L * 1024L * 1024L * 1024L, 4L * 1024L * 1024L * 1024L);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.add_tenant(OB_SYS_TENANT_ID);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.add_tenant(OB_SERVER_TENANT_ID);
EXPECT_EQ(OB_SUCCESS, ret);
const int64_t ulmt = 128LL << 30;
const int64_t llmt = 128LL << 30;
ret = tm.set_tenant_mem_limit(OB_SYS_TENANT_ID, ulmt, llmt);
EXPECT_EQ(OB_SUCCESS, ret);
oceanbase::lib::set_memory_limit(128LL << 32);
return ret;
}
#define BEGIN_THREAD_CODE_V2(num) \
{ \
std::vector<std::thread*> _threads; \
for (int _i = 0; _i < (num); _i++) _threads.push_back(new std::thread([&]
#define END_THREAD_CODE_V2() )); \
for (auto t : _threads) \
t->join(); \
}
template <typename SortInit>
void ObSortTest::sort_test(
int64_t row_count, int64_t mem_limit, SortInit sort_init, int64_t verify_row_cnt, bool local_merge_sort)
{
ASSERT_EQ(OB_SUCCESS, ObSortPlan::init(row_count, mem_limit, sort_init));
if (local_merge_sort) {
ObSortPlan::set_local_merge_sort();
}
BEGIN_THREAD_CODE_V2(2)
{
ObExecContext exec_ctx;
ASSERT_EQ(OB_SUCCESS, exec_ctx.init_phy_op(2));
ASSERT_EQ(OB_SUCCESS, exec_ctx.create_physical_plan_ctx());
ObSQLSessionInfo my_session;
my_session.test_init(0, 0, 0, NULL);
my_session.init_tenant("sys", 1);
exec_ctx.set_my_session(&my_session);
THIS_WORKER.set_timeout_ts(ObTimeUtility::current_time() + 600000000);
// do sort.
ObSort& sort = ObSortPlan::get_instance();
ASSERT_EQ(OB_SUCCESS, sort.open(exec_ctx));
auto& sort_columns = sort.get_sort_columns();
ObSEArray<ObOpSchemaObj, 8> op_schema_objs;
cons_op_schema_objs(sort_columns, op_schema_objs);
sort.get_op_schema_objs_for_update().assign(op_schema_objs);
ObObj pre[sort_columns.count()];
char varchar_buf[1024];
const ObNewRow* row = NULL;
int64_t cnt = verify_row_cnt > 0 ? verify_row_cnt : row_count;
for (int64_t i = 0; i < cnt; ++i) {
ASSERT_EQ(OB_SUCCESS, sort.get_next_row(exec_ctx, row)) << i;
// check order
for (int64_t j = 0; i > 0 && j < sort_columns.count(); j++) {
auto& col = sort_columns.at(j);
int cmp = pre[j].compare(row->cells_[col.index_], col.cs_type_);
if (cmp != 0) {
ASSERT_TRUE(col.is_ascending() ? cmp < 0 : cmp > 0);
break;
}
}
// save previous row
int64_t pos = 0;
for (int64_t j = 0; j < sort_columns.count(); j++) {
pre[j] = row->cells_[sort_columns.at(j).index_];
auto& c = pre[j];
if (c.is_string_type()) {
auto len = std::min((uint64_t)c.val_len_, sizeof(varchar_buf) - pos);
MEMCPY(varchar_buf + pos, c.v_.string_, len);
c.v_.string_ = varchar_buf + pos;
pos += len;
}
}
} // end for
ASSERT_EQ(OB_ITER_END, sort.get_next_row(exec_ctx, row));
ASSERT_EQ(OB_SUCCESS, sort.close(exec_ctx));
int64_t sort_row_count = 0;
ASSERT_EQ(OB_SUCCESS, sort.get_sort_row_count(exec_ctx, sort_row_count));
ASSERT_EQ(row_count, sort_row_count);
ob_print_mod_memory_usage();
ObTenantManager::get_instance().print_tenant_usage();
}
END_THREAD_CODE_V2();
ObSortPlan::reset();
}
void ObSortTest::sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1,
int64_t sort_col2, ObCollationType cs_type2)
{
sort_test(row_count, mem_limit, [&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col1, cs_type1, false, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col2, cs_type2, true, ObMaxType, default_asc_direction()))) {
}
return ret;
});
}
void ObSortTest::local_merge_sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1,
ObCollationType cs_type1, int64_t sort_col2, ObCollationType cs_type2)
{
sort_test(
row_count,
mem_limit,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col1, cs_type1, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col2, cs_type2, true, ObMaxType, default_asc_direction()))) {
}
return ret;
},
-1,
true);
}
void ObSortTest::serialize_test()
{
ObSort& sort_1 = ObSortPlan::get_instance();
ObArenaAllocator alloc;
ObSort sort_2(alloc);
const int64_t MAX_SERIALIZE_BUF_LEN = 1024;
char buf[MAX_SERIALIZE_BUF_LEN] = {'\0'};
ASSERT_EQ(OB_SUCCESS, ObSortPlan::init(1024, 1024, 0, CS_TYPE_INVALID, 1, CS_TYPE_INVALID));
int64_t pos = 0;
ASSERT_EQ(OB_SUCCESS, sort_1.serialize(buf, MAX_SERIALIZE_BUF_LEN, pos));
ASSERT_EQ(pos, sort_1.get_serialize_size());
int64_t data_len = pos;
sort_2.set_phy_plan(const_cast<ObPhysicalPlan*>(sort_1.get_phy_plan()));
pos = 0;
ASSERT_EQ(OB_SUCCESS, sort_2.deserialize(buf, data_len, pos));
ASSERT_EQ(pos, data_len);
const char* str_1 = to_cstring(sort_1);
const char* str_2 = to_cstring(sort_2);
ASSERT_EQ(0, strcmp(str_1, str_2)) << "sort_1: " << to_cstring(sort_1) << std::endl
<< "sort_2: " << to_cstring(sort_2);
ObSortPlan::reuse();
}
void ObSortTest::sort_exception_test(int expect_ret)
{
int ret = OB_SUCCESS;
ObExecContext exec_ctx;
const ObNewRow* row = NULL;
ObSQLSessionInfo my_session;
my_session.test_init(0, 0, 0, NULL);
my_session.init_tenant("sys", 1);
exec_ctx.set_my_session(&my_session);
ASSERT_EQ(OB_SUCCESS, exec_ctx.init_phy_op(2));
ASSERT_EQ(OB_SUCCESS, exec_ctx.create_physical_plan_ctx());
ObSort& sort = ObSortPlan::get_instance();
ObSortPlan::reset();
int64_t row_count = 16 * 1024;
if (OB_FAIL(ObSortPlan::init(row_count, 0, 0, CS_TYPE_UTF8MB4_BIN, 1, CS_TYPE_UTF8MB4_BIN))) {
} else if (OB_FAIL(sort.open(exec_ctx))) {
} else {
ObSEArray<ObOpSchemaObj, 8> op_schema_objs;
cons_op_schema_objs(sort.get_sort_columns(), op_schema_objs);
sort.get_op_schema_objs_for_update().assign(op_schema_objs);
while (OB_SUCC(ret)) {
ret = sort.get_next_row(exec_ctx, row);
}
if (OB_ITER_END == ret) {
int64_t sort_row_count = 0;
if (OB_FAIL(sort.close(exec_ctx))) {
} else if (OB_FAIL(sort.get_sort_row_count(exec_ctx, sort_row_count))) {
} else {
ASSERT_EQ(row_count, sort_row_count);
}
}
}
sort.close(exec_ctx);
ObSortPlan::reuse();
if (OB_FAIL(ret)) {
ASSERT_EQ(expect_ret, ret);
}
}
TEST_F(ObSortTest, varchar_int_item_in_mem_test)
{
int64_t sort_col1 = 0;
int64_t sort_col2 = 1;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
sort_test(16 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
cs_type2 = CS_TYPE_UTF8MB4_GENERAL_CI;
sort_test(16 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, varchar_int_item_merge_sort_test)
{
int64_t sort_col1 = 0;
int64_t sort_col2 = 1;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
sort_test(128 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 4 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
// recursive merge needed.
sort_test(256 * 1024, 512 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
cs_type2 = CS_TYPE_UTF8MB4_GENERAL_CI;
sort_test(128 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 4 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, int_int_item_in_mem_test)
{
int64_t sort_col1 = 1;
int64_t sort_col2 = 2;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
sort_test(16 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, int_int_item_merge_sort_test)
{
int64_t sort_col1 = 1;
int64_t sort_col2 = 2;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
// sort_test(64 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, test_conf)
{
TEST_SORT_DUMP_SET_HASH_AREA_SIZE(128 * 1024 * 1024);
int64_t sort_mem = 0;
sort_mem = TEST_SORT_DUMP_GET_HASH_AREA_SIZE();
ASSERT_EQ((128 * 1024 * 1024), sort_mem);
TEST_SORT_DUMP_SET_HASH_AREA_SIZE(1 * 1024 * 1024 * 1024);
sort_mem = TEST_SORT_DUMP_GET_HASH_AREA_SIZE();
ASSERT_EQ((1024 * 1024 * 1024), sort_mem);
TEST_SORT_DUMP_SET_HASH_AREA_SIZE(128 * 1024 * 1024);
}
TEST_F(ObSortTest, prefix_sort_test1)
{
sort_test(1024 * 1024, 1024 * 1024, [](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(3))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_BINARY, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_prefix_pos(1);
}
return ret;
});
}
TEST_F(ObSortTest, prefix_sort_test3)
{
sort_test(256 * 1024, 1024 * 1024, [](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(3))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL5_ROW_ID_DIV_3, CS_TYPE_BINARY, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_prefix_pos(1);
}
return ret;
});
}
TEST_F(ObSortTest, prefix_merge_sort_test)
{
sort_test(256 * 1024, 1024 * 1024, [](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(3))) {
} else if (OB_FAIL(sort.add_sort_column(ObFakeTable::COL11_ROW_ID_MULTIPLY_3_DIV_COUNT,
CS_TYPE_BINARY,
true,
ObMaxType,
default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_prefix_pos(1);
}
return ret;
});
}
class MockExpr : public ObSqlExpression {
public:
MockExpr(ObIAllocator& alloc, int64_t cnt) : ObSqlExpression(alloc)
{
set_item_count(1);
start_gen_infix_exr();
ObPostExprItem item;
item.set_int(cnt);
item.set_item_type(T_INT);
add_expr_item(item);
}
int calc(common::ObExprCtx&, const common::ObNewRow&, common::ObObj& result) const
{
result.set_int(get_expr_items().at(0).get_obj().get_int());
return OB_SUCCESS;
}
};
TEST_F(ObSortTest, topn_sort_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
20,
10 << 20,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4);
}
TEST_F(ObSortTest, topn_disk_sort_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
20,
0,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4);
}
TEST_F(ObSortTest, local_merge_sort_test)
{
int64_t sort_col1 = 1;
int64_t sort_col2 = 2;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
local_merge_sort_test(0, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(16, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(256, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(16, 0, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(256, 0, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, local_merge_sort_disk_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
256 * 1024,
1 << 20,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4,
true);
}
TEST_F(ObSortTest, local_merge_sort_topn_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
1024,
10 << 20,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4,
true);
}
TEST_F(ObSortTest, ser)
{
serialize_test();
}
#define SORT_EXCEPTION_TEST(file, func, key, err, expect_ret) \
do { \
TP_SET_ERROR("engine/sort/" file, func, key, err); \
sort_exception_test(expect_ret); \
TP_SET_ERROR("engine/sort/" file, func, key, NULL); \
ASSERT_FALSE(HasFatalFailure()); \
} while (0)
TEST_F(ObSortTest, sort_exception)
{
THIS_WORKER.set_timeout_ts(ObTimeUtility::current_time() + 600000000);
SORT_EXCEPTION_TEST("ob_sort.cpp", "add_sort_column", "t1", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t1", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t3", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t5", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t7", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t9", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "close", "t1", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "close", "t3", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t1", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t3", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t5", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t7", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t9", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t11", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t13", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t1", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t3", 1, OB_TIMEOUT);
// see comments for tracepoint t5 in inner_get_next_row() of ob_sort.cpp.
// SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t5", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t7", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t9", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "get_sort_row_count", "t1", 1, OB_ERR_UNEXPECTED);
}
ObPhysicalPlan* ObSortPlan::physical_plan_ = nullptr;
ObSort* ObSortPlan::sort_ = nullptr;
ObFakeTable* ObSortPlan::input_table_ = nullptr;
int64_t ObSortPlan::row_count_ = -1;
ObString* ObSortPlan::filename_ = nullptr;
int main(int argc, char** argv)
{
ObClockGenerator::init();
system("rm -f test_sort.log*");
OB_LOGGER.set_file_name("test_sort.log", true, true);
OB_LOGGER.set_log_level("INFO");
oceanbase::observer::ObSignalHandle signal_handle;
oceanbase::observer::ObSignalHandle::change_signal_mask();
signal_handle.start();
void* buf = nullptr;
ObArenaAllocator allocator;
buf = allocator.alloc(sizeof(ObPhysicalPlan));
ObSortPlan::physical_plan_ = new (buf) ObPhysicalPlan();
buf = allocator.alloc(sizeof(ObSort));
ObSortPlan::sort_ = new (buf) ObSort(ObSortPlan::physical_plan_->get_allocator());
buf = allocator.alloc(sizeof(ObFakeTable));
ObSortPlan::input_table_ = new (buf) ObFakeTable();
ObSortPlan::row_count_ = -1;
buf = allocator.alloc(sizeof(ObString));
ObSortPlan::filename_ = new (buf) ObString();
::testing::InitGoogleTest(&argc, argv);
oceanbase::common::ObLogger::get_logger().set_log_level("INFO");
return RUN_ALL_TESTS();
}
| 35.055703 | 119 | 0.687311 |