blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
6736df540b88b51e2b40e8237bd52a161686d26b
d2fa803d61836e9ac411ead501747bb99c56c839
/plugins/channeltx/modnfm/nfmmodgui.cpp
471a36cd61d09a769d292317a8976e11e67f8f7f
[]
no_license
hmne/sdrangel
9eac60c843cc8da3bf1f7fe4dfca24a45b28d120
1d442fd077981087fb7733dde486d8501885d56e
refs/heads/master
2020-03-29T21:00:38.928842
2017-12-02T17:57:55
2017-12-02T17:57:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,942
cpp
/////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2016 Edouard Griffiths, F4EXB // // // // 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 as version 3 of the License, or // // // // 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 V3 for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////////////////// #include <QDockWidget> #include <QMainWindow> #include <QFileDialog> #include <QTime> #include <QDebug> #include "device/devicesinkapi.h" #include "device/deviceuiset.h" #include "plugin/pluginapi.h" #include "util/simpleserializer.h" #include "util/db.h" #include "dsp/dspengine.h" #include "mainwindow.h" #include "ui_nfmmodgui.h" #include "nfmmodgui.h" NFMModGUI* NFMModGUI::create(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSource *channelTx) { NFMModGUI* gui = new NFMModGUI(pluginAPI, deviceUISet, channelTx); return gui; } void NFMModGUI::destroy() { delete this; } void NFMModGUI::setName(const QString& name) { setObjectName(name); } QString NFMModGUI::getName() const { return objectName(); } qint64 NFMModGUI::getCenterFrequency() const { return m_channelMarker.getCenterFrequency(); } void NFMModGUI::setCenterFrequency(qint64 centerFrequency) { m_channelMarker.setCenterFrequency(centerFrequency); applySettings(); } void NFMModGUI::resetToDefaults() { m_settings.resetToDefaults(); displaySettings(); applySettings(true); } QByteArray NFMModGUI::serialize() const { return m_settings.serialize(); } bool NFMModGUI::deserialize(const QByteArray& data) { if(m_settings.deserialize(data)) { displaySettings(); applySettings(true); return true; } else { resetToDefaults(); return false; } } bool NFMModGUI::handleMessage(const Message& message) { if (NFMMod::MsgReportFileSourceStreamData::match(message)) { m_recordSampleRate = ((NFMMod::MsgReportFileSourceStreamData&)message).getSampleRate(); m_recordLength = ((NFMMod::MsgReportFileSourceStreamData&)message).getRecordLength(); m_samplesCount = 0; updateWithStreamData(); return true; } else if (NFMMod::MsgReportFileSourceStreamTiming::match(message)) { m_samplesCount = ((NFMMod::MsgReportFileSourceStreamTiming&)message).getSamplesCount(); updateWithStreamTime(); return true; } else { return false; } } void NFMModGUI::channelMarkerChangedByCursor() { ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); applySettings(); } void NFMModGUI::handleSourceMessages() { Message* message; while ((message = getInputMessageQueue()->pop()) != 0) { if (handleMessage(*message)) { delete message; } } } void NFMModGUI::on_deltaFrequency_changed(qint64 value) { m_channelMarker.setCenterFrequency(value); m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency(); applySettings(); } void NFMModGUI::on_rfBW_currentIndexChanged(int index) { m_channelMarker.setBandwidth(NFMModSettings::getRFBW(index)); m_settings.m_rfBandwidth = NFMModSettings::getRFBW(index); applySettings(); } void NFMModGUI::on_afBW_valueChanged(int value) { ui->afBWText->setText(QString("%1k").arg(value)); m_settings.m_afBandwidth = value * 1000.0; applySettings(); } void NFMModGUI::on_fmDev_valueChanged(int value) { ui->fmDevText->setText(QString("%1k").arg(value / 10.0, 0, 'f', 1)); m_settings.m_fmDeviation = value * 100.0; applySettings(); } void NFMModGUI::on_volume_valueChanged(int value) { ui->volumeText->setText(QString("%1").arg(value / 10.0, 0, 'f', 1)); m_settings.m_volumeFactor = value / 10.0; applySettings(); } void NFMModGUI::on_toneFrequency_valueChanged(int value) { ui->toneFrequencyText->setText(QString("%1k").arg(value / 100.0, 0, 'f', 2)); m_settings.m_toneFrequency = value * 10.0; applySettings(); } void NFMModGUI::on_channelMute_toggled(bool checked) { m_settings.m_channelMute = checked; applySettings(); } void NFMModGUI::on_playLoop_toggled(bool checked) { m_settings.m_playLoop = checked; applySettings(); } void NFMModGUI::on_play_toggled(bool checked) { ui->tone->setEnabled(!checked); // release other source inputs ui->mic->setEnabled(!checked); ui->morseKeyer->setEnabled(!checked); m_modAFInput = checked ? NFMMod::NFMModInputFile : NFMMod::NFMModInputNone; NFMMod::MsgConfigureAFInput* message = NFMMod::MsgConfigureAFInput::create(m_modAFInput); m_nfmMod->getInputMessageQueue()->push(message); ui->navTimeSlider->setEnabled(!checked); m_enableNavTime = !checked; } void NFMModGUI::on_tone_toggled(bool checked) { ui->play->setEnabled(!checked); // release other source inputs ui->mic->setEnabled(!checked); ui->morseKeyer->setEnabled(!checked); m_modAFInput = checked ? NFMMod::NFMModInputTone : NFMMod::NFMModInputNone; NFMMod::MsgConfigureAFInput* message = NFMMod::MsgConfigureAFInput::create(m_modAFInput); m_nfmMod->getInputMessageQueue()->push(message); } void NFMModGUI::on_morseKeyer_toggled(bool checked) { ui->tone->setEnabled(!checked); // release other source inputs ui->mic->setEnabled(!checked); ui->play->setEnabled(!checked); m_modAFInput = checked ? NFMMod::NFMModInputCWTone : NFMMod::NFMModInputNone; NFMMod::MsgConfigureAFInput* message = NFMMod::MsgConfigureAFInput::create(m_modAFInput); m_nfmMod->getInputMessageQueue()->push(message); } void NFMModGUI::on_mic_toggled(bool checked) { ui->play->setEnabled(!checked); // release other source inputs ui->tone->setEnabled(!checked); // release other source inputs ui->morseKeyer->setEnabled(!checked); m_modAFInput = checked ? NFMMod::NFMModInputAudio : NFMMod::NFMModInputNone; NFMMod::MsgConfigureAFInput* message = NFMMod::MsgConfigureAFInput::create(m_modAFInput); m_nfmMod->getInputMessageQueue()->push(message); } void NFMModGUI::on_navTimeSlider_valueChanged(int value) { if (m_enableNavTime && ((value >= 0) && (value <= 100))) { int t_sec = (m_recordLength * value) / 100; QTime t(0, 0, 0, 0); t = t.addSecs(t_sec); NFMMod::MsgConfigureFileSourceSeek* message = NFMMod::MsgConfigureFileSourceSeek::create(value); m_nfmMod->getInputMessageQueue()->push(message); } } void NFMModGUI::on_showFileDialog_clicked(bool checked __attribute__((unused))) { QString fileName = QFileDialog::getOpenFileName(this, tr("Open raw audio file"), ".", tr("Raw audio Files (*.raw)")); if (fileName != "") { m_fileName = fileName; ui->recordFileText->setText(m_fileName); ui->play->setEnabled(true); configureFileName(); } } void NFMModGUI::on_ctcss_currentIndexChanged(int index) { m_settings.m_ctcssIndex = index; applySettings(); } void NFMModGUI::on_ctcssOn_toggled(bool checked) { m_settings.m_ctcssOn = checked; applySettings(); } void NFMModGUI::configureFileName() { qDebug() << "FileSourceGui::configureFileName: " << m_fileName.toStdString().c_str(); NFMMod::MsgConfigureFileSourceName* message = NFMMod::MsgConfigureFileSourceName::create(m_fileName); m_nfmMod->getInputMessageQueue()->push(message); } void NFMModGUI::onWidgetRolled(QWidget* widget __attribute__((unused)), bool rollDown __attribute__((unused))) { } NFMModGUI::NFMModGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSource *channelTx, QWidget* parent) : RollupWidget(parent), ui(new Ui::NFMModGUI), m_pluginAPI(pluginAPI), m_deviceUISet(deviceUISet), m_channelMarker(this), m_doApplySettings(true), m_channelPowerDbAvg(20,0), m_recordLength(0), m_recordSampleRate(48000), m_samplesCount(0), m_tickCount(0), m_enableNavTime(false), m_modAFInput(NFMMod::NFMModInputNone) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); blockApplySettings(true); ui->rfBW->clear(); for (int i = 0; i < NFMModSettings::m_nbRfBW; i++) { ui->rfBW->addItem(QString("%1").arg(NFMModSettings::getRFBW(i) / 1000.0, 0, 'f', 2)); } ui->rfBW->setCurrentIndex(6); blockApplySettings(false); connect(this, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); m_nfmMod = (NFMMod*) channelTx; //new NFMMod(m_deviceUISet->m_deviceSinkAPI); m_nfmMod->setMessageQueueToGUI(getInputMessageQueue()); connect(&MainWindow::getInstance()->getMasterTimer(), SIGNAL(timeout()), this, SLOT(tick())); ui->deltaFrequencyLabel->setText(QString("%1f").arg(QChar(0x94, 0x03))); ui->deltaFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold)); ui->deltaFrequency->setValueRange(false, 7, -9999999, 9999999); m_channelMarker.blockSignals(true); m_channelMarker.setColor(Qt::red); m_channelMarker.setBandwidth(12500); m_channelMarker.setCenterFrequency(0); m_channelMarker.setTitle("NFM Modulator"); m_channelMarker.setUDPAddress("127.0.0.1"); m_channelMarker.setUDPSendPort(9999); m_channelMarker.blockSignals(false); m_channelMarker.setVisible(true); // activate signal on the last setting only m_deviceUISet->registerTxChannelInstance(NFMMod::m_channelIdURI, this); m_deviceUISet->addChannelMarker(&m_channelMarker); m_deviceUISet->addRollupWidget(this); connect(&m_channelMarker, SIGNAL(changedByCursor()), this, SLOT(channelMarkerChangedByCursor())); ui->play->setEnabled(false); ui->play->setChecked(false); ui->tone->setChecked(false); ui->mic->setChecked(false); for (int i=0; i< NFMModSettings::m_nbCTCSSFreqs; i++) { ui->ctcss->addItem(QString("%1").arg((double) NFMModSettings::getCTCSSFreq(i), 0, 'f', 1)); } ui->cwKeyerGUI->setBuddies(m_nfmMod->getInputMessageQueue(), m_nfmMod->getCWKeyer()); connect(getInputMessageQueue(), SIGNAL(messageEnqueued()), this, SLOT(handleSourceMessages())); connect(m_nfmMod, SIGNAL(levelChanged(qreal, qreal, int)), ui->volumeMeter, SLOT(levelChanged(qreal, qreal, int))); m_settings.setChannelMarker(&m_channelMarker); m_settings.setCWKeyerGUI(ui->cwKeyerGUI); displaySettings(); applySettings(); } NFMModGUI::~NFMModGUI() { m_deviceUISet->removeTxChannelInstance(this); delete m_nfmMod; // TODO: check this: when the GUI closes it has to delete the modulator delete ui; } void NFMModGUI::blockApplySettings(bool block) { m_doApplySettings = !block; } void NFMModGUI::applySettings(bool force) { if (m_doApplySettings) { NFMMod::MsgConfigureChannelizer *msgChan = NFMMod::MsgConfigureChannelizer::create( 48000, m_channelMarker.getCenterFrequency()); m_nfmMod->getInputMessageQueue()->push(msgChan); NFMMod::MsgConfigureNFMMod *msg = NFMMod::MsgConfigureNFMMod::create(m_settings, force); m_nfmMod->getInputMessageQueue()->push(msg); } } void NFMModGUI::displaySettings() { m_channelMarker.blockSignals(true); m_channelMarker.setCenterFrequency(m_settings.m_inputFrequencyOffset); m_channelMarker.setBandwidth(m_settings.m_rfBandwidth); m_channelMarker.blockSignals(false); m_channelMarker.setColor(m_settings.m_rgbColor); // activate signal on the last setting only setTitleColor(m_settings.m_rgbColor); setWindowTitle(m_channelMarker.getTitle()); blockApplySettings(true); ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency()); ui->rfBW->setCurrentIndex(NFMModSettings::getRFBWIndex(m_settings.m_rfBandwidth)); ui->afBWText->setText(QString("%1k").arg(m_settings.m_afBandwidth / 1000.0)); ui->afBW->setValue(m_settings.m_afBandwidth / 1000.0); ui->fmDevText->setText(QString("%1k").arg(m_settings.m_fmDeviation / 1000.0, 0, 'f', 1)); ui->fmDev->setValue(m_settings.m_fmDeviation / 100.0); ui->volumeText->setText(QString("%1").arg(m_settings.m_volumeFactor, 0, 'f', 1)); ui->volume->setValue(m_settings.m_volumeFactor * 10.0); ui->toneFrequencyText->setText(QString("%1k").arg(m_settings.m_toneFrequency / 1000.0, 0, 'f', 2)); ui->toneFrequency->setValue(m_settings.m_toneFrequency / 10.0); ui->ctcssOn->setChecked(m_settings.m_ctcssOn); ui->ctcss->setCurrentIndex(m_settings.m_ctcssIndex); ui->channelMute->setChecked(m_settings.m_channelMute); ui->playLoop->setChecked(m_settings.m_playLoop); blockApplySettings(false); } void NFMModGUI::leaveEvent(QEvent*) { m_channelMarker.setHighlighted(false); } void NFMModGUI::enterEvent(QEvent*) { m_channelMarker.setHighlighted(true); } void NFMModGUI::tick() { double powDb = CalcDb::dbPower(m_nfmMod->getMagSq()); m_channelPowerDbAvg.feed(powDb); ui->channelPower->setText(tr("%1 dB").arg(m_channelPowerDbAvg.average(), 0, 'f', 1)); if (((++m_tickCount & 0xf) == 0) && (m_modAFInput == NFMMod::NFMModInputFile)) { NFMMod::MsgConfigureFileSourceStreamTiming* message = NFMMod::MsgConfigureFileSourceStreamTiming::create(); m_nfmMod->getInputMessageQueue()->push(message); } } void NFMModGUI::updateWithStreamData() { QTime recordLength(0, 0, 0, 0); recordLength = recordLength.addSecs(m_recordLength); QString s_time = recordLength.toString("hh:mm:ss"); ui->recordLengthText->setText(s_time); updateWithStreamTime(); } void NFMModGUI::updateWithStreamTime() { int t_sec = 0; int t_msec = 0; if (m_recordSampleRate > 0) { t_msec = ((m_samplesCount * 1000) / m_recordSampleRate) % 1000; t_sec = m_samplesCount / m_recordSampleRate; } QTime t(0, 0, 0, 0); t = t.addSecs(t_sec); t = t.addMSecs(t_msec); QString s_timems = t.toString("hh:mm:ss.zzz"); QString s_time = t.toString("hh:mm:ss"); ui->relTimeText->setText(s_timems); if (!m_enableNavTime) { float posRatio = (float) t_sec / (float) m_recordLength; ui->navTimeSlider->setValue((int) (posRatio * 100.0)); } }
[ "f4exb06@gmail.com" ]
f4exb06@gmail.com
ed1b10674976c421a3126fa959618fad1783d17d
52ca17dca8c628bbabb0f04504332c8fdac8e7ea
/boost/phoenix/statement/detail/preprocessed/try_catch_expression_30.hpp
8df8e47cb05f5064f3625a91f6ec55dec9161fd7
[]
no_license
qinzuoyan/thirdparty
f610d43fe57133c832579e65ca46e71f1454f5c4
bba9e68347ad0dbffb6fa350948672babc0fcb50
refs/heads/master
2021-01-16T17:47:57.121882
2015-04-21T06:59:19
2015-04-21T06:59:19
33,612,579
0
0
null
2015-04-08T14:39:51
2015-04-08T14:39:51
null
UTF-8
C++
false
false
107
hpp
#include "thirdparty/boost_1_58_0/boost/phoenix/statement/detail/preprocessed/try_catch_expression_30.hpp"
[ "qinzuoyan@xiaomi.com" ]
qinzuoyan@xiaomi.com
c8a490935064fc18df19cc877693a844713d81fa
15ae3c07d969f1e75bc2af9555cf3e952be9bfff
/analysis/pragma_before/pragma_243.hpp
12cf526c1e9df691b44f2a14bc8357b49c834be9
[]
no_license
marroko/generators
d2d1855d9183cbc32f9cd67bdae8232aba2d1131
9e80511155444f42f11f25063c0176cb3b6f0a66
refs/heads/master
2023-02-01T16:55:03.955738
2020-12-12T14:11:17
2020-12-12T14:11:17
316,802,086
0
0
null
null
null
null
UTF-8
C++
false
false
101
hpp
#ifndef CXUOUPGHIOJ_OAHWQNCI_HPP #define CXUOUPGHIOJ_OAHWQNCI_HPP #endif // CXUOUPGHIOJ_OAHWQNCI_HPP
[ "marcus1.2.3@wp.pl" ]
marcus1.2.3@wp.pl
24302f83e44e9efe50950628a352b4d5e3e93c10
6446c6e0649895e8b8fc6442e334f92641df4d15
/branches/0.5.7.experimental/EScript/Utils/IO/AbstractFileSystemHandler.h
c1924c21ab2ff2d057c3c431ed37ddddb3a8fecd
[]
no_license
BackupTheBerlios/escript-svn
e33b5dc2192de09b62078cfcec38ad8eec61747a
36b2e5f69adb768214cd05204a47cf03c09eba9e
refs/heads/master
2016-08-04T17:36:45.234689
2014-01-06T20:08:03
2014-01-06T20:08:03
40,668,676
0
0
null
null
null
null
UTF-8
C++
false
false
2,460
h
// AbstractFileSystemHandler.h // This file is part of the EScript programming language. // See copyright notice in EScript.h // ------------------------------------------------------ #ifndef ABSTRACTFILESYSTEMHANDLER_H #define ABSTRACTFILESYSTEMHANDLER_H #include "../StringData.h" #include "IOBase.h" #include <ios> #include <list> #include <map> #include <string> #include <cstddef> namespace EScript{ namespace IO{ /*! A FileSystemHandler servers as interface to the file system. Exchaninging this handler allows to globally add support for additional file systems (e.g. by implementing a http interface), or to add an access restriction to file operations (e.g. limit all operations to certain folders). \todo - (?) add flush() - add streaming support */ class AbstractFileSystemHandler { protected: AbstractFileSystemHandler(){} public: virtual ~AbstractFileSystemHandler(){} //! ---o virtual void deleteFile(const std::string &){ throw std::ios_base::failure("unsupported operation"); } /*! ---o * @param dirname * flags: 1 ... Files * 2 ... Directories * 4 ... Recurse Subdirectories * @throw std::ios_base::failure on failure. */ virtual void dir(const std::string &/*path*/, std::list<std::string> &/*result*/, uint8_t/*flags*/){ throw std::ios_base::failure("unsupported operation"); } //! ---o virtual entryType_t getEntryType(const std::string & path){ return getEntryInfo(path).type; } //! ---o virtual EntryInfo getEntryInfo(const std::string &){ throw std::ios_base::failure("unsupported operation"); } //! ---o virtual uint32_t getFileCTime(const std::string & path){ return getEntryInfo(path).cTime; } //! ---o virtual uint32_t getFileMTime(const std::string & path){ return getEntryInfo(path).mTime; } //! ---o virtual uint64_t getFileSize(const std::string & path){ return getEntryInfo(path).fileSize; } //! ---o virtual void makeDir(const std::string &){ throw std::ios_base::failure("unsupported operation"); } //! ---o virtual StringData loadFile(const std::string &){ throw std::ios_base::failure("unsupported operation"); } //! ---o virtual void saveFile(const std::string &, const std::string & /*data*/, bool /*overwrite*/){ throw std::ios_base::failure("unsupported operation"); } }; } } #endif // ABSTRACTFILESYSTEMHANDLER_H
[ "claudiusj@5693b1fc-3b75-4070-9b6b-3ce3692a40d5" ]
claudiusj@5693b1fc-3b75-4070-9b6b-3ce3692a40d5
d8f9d3fbce8afa766d306a29613a690a98826b9e
0b50797347e410b680ce1f4fb784d3462a8cfed3
/Item.h
c40083d5d353782106263d1f206d69b198bc5201
[]
no_license
yangbodong22011/kioskcached
8c936d00df626baf5022c950c68a6e9f96f156f7
7af3c826c721c93d74937678c21c0f7d6712da2c
refs/heads/master
2021-01-11T21:01:40.536799
2017-04-20T01:17:37
2017-04-20T01:17:37
79,231,746
8
2
null
null
null
null
UTF-8
C++
false
false
2,881
h
/************************************************************************* > File Name: Item.h > Author: YangBodong > Mail: ybd@xiyoulinux.org > Created Time: Wed 15 Feb 2017 08:36:15 PM CST ************************************************************************/ #ifndef _ITEM_H #define _ITEM_H #include<memory> #include<iostream> #include<stdlib.h> #include<stdio.h> class Item; typedef std::shared_ptr<Item> ItemPtr; typedef std::shared_ptr<const Item> ConstItemPtr; class Item { public: enum UpdatePolicy { kInvalid, kSet, kAdd, kReplace, }; static ItemPtr makeItem(std::string keyArg, uint32_t flagsArg, int exptimeArg, int valuelen, uint64_t casArg) { return std::make_shared<Item>(keyArg,flagsArg,exptimeArg,valuelen,casArg); } Item() = default; Item(std::string keyArg, uint32_t flagsArg, int exptimeArg, int valuelen, uint64_t casArg); ~Item() { free(data_); } std::string key() const { //所有需要调用key的地方传递.size()方法. std::string ret(data_); return ret.substr(0,keylen_); } uint32_t flags() const { return flags_; } int rel_exptime() const { return rel_exptime_; } const char* value() const { return data_+keylen_; } size_t valueLength() const { return valuelen_; } uint64_t cas() const { return cas_; } size_t hash() const { return hash_; } void setCas(uint64_t casArg) { cas_ = casArg; } size_t neededBytes() const { return totalLen() - receivedBytes_; } void append(const char* data,size_t len); bool endsWithCRLF() const { return receivedBytes_ == totalLen() && data_[totalLen()-2] == '\r' && data_[totalLen()-1] == '\n'; } void output() const { std::cout << "keylen_ : " << keylen_ << std::endl; std::cout << "flags : " << flags_ << std::endl; std::cout << "rel_exptime_ : " << rel_exptime_ << std::endl; std::cout << "valuelen_ : " << valuelen_ << std::endl; std::cout << "receivedBytes_ : " << receivedBytes_ << std::endl; std::cout << "cas_ : " << cas_ << std::endl; std::cout << "hash_ : " << hash_ << std::endl; std::cout << "data_ : " << data_ << std::endl; } void resetKey(std::string k); private: int totalLen() const { return keylen_ + valuelen_;} int keylen_; const uint32_t flags_; const int rel_exptime_; const int valuelen_; int receivedBytes_; uint64_t cas_; size_t hash_; char* data_; }; #endif
[ "ybd@xiyoulinux.org" ]
ybd@xiyoulinux.org
b42b444fd132f271c2952742b51fce1169e4f72a
3c7859a0d2643c4a90170189bf71e5046d6e8c0d
/src/entities/space_craft.cpp
b0a5efa3118de62b79306044bbbeff68be8b4599
[ "MIT" ]
permissive
MORTAL2000/planets
5d775bcc85e014a6b78bc7353c844ac8746dda4b
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
refs/heads/master
2022-07-03T14:39:25.840344
2020-05-15T16:20:45
2020-05-15T16:20:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
#include "space_craft.hpp" Spacecraft::Spacecraft() {} void Spacecraft::upload() {} void Spacecraft::render(RenderType type) {}
[ "me@alexkafer.com" ]
me@alexkafer.com
96d67493767400d880a9be1b195385b74acd812c
16886879d215500e06bc7625131e81c1541b4008
/src/internal/timereventdata.cpp
3e1c092f35a7c2f0211e55bd98031debacfe7e14
[ "MIT" ]
permissive
ZaoLahma/ThreadFramework
d138caebf0c5dcbb764996147a74fe68b6a50c2b
994367fe1ccd6b22b307645eb73757916aaa55f0
refs/heads/master
2022-09-29T08:24:09.670380
2022-09-18T12:49:46
2022-09-18T12:49:46
51,267,266
1
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
/* * timereventdata.cpp * * Created on: Apr 27, 2016 * Author: janne */ #include "internal/timereventdata.h" TimerEventData::TimerEventData(const uint32_t _timerId) : timerId(_timerId) { } uint32_t TimerEventData::GetTimerId() const { return timerId; }
[ "thyberg.jan@gmail.com" ]
thyberg.jan@gmail.com
022365e95f4d03cebba2e85a20da97d821c10424
aba44f99398f2e33ceb6731e23bc7bedf8fe2532
/include/caffe/layers/crf3_loss_layer.hpp
6561143d178537757023dc445b6fe77df553a3e5
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
permissive
myBestLove/caffe-dev-160608
d24842230e1693a428bd85bb6a1df0e458b4c213
6ff590f921b53de7cec00d4bd150826a7a31829c
refs/heads/master
2021-06-22T01:37:12.260542
2017-08-21T13:09:15
2017-08-21T13:09:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,196
hpp
#ifndef CAFFE_CRF3_LOSS_LAYER_HPP_ #define CAFFE_CRF3_LOSS_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/loss_layer.hpp" /* * This layer is modified from the crf2loaslayer, which use different binary segment * result as the pairwise parameter similarity. * Instead, this layer use the gpbucm segment result as the pairwise similarity * ================================================================================= * NOTE: * The pairwise term R = alpha * exp(-beta*X) * The X is input of the pairwise value * The beta and the alpha are learnable params * alpha stored in the this->blobs_[0] * beta stored in the this->blobs_[1] * ================================================================================= * Note this layer perform the CRF loss based on the network output * It contains three bottoms * bottom[0]: The prediction of the network, which can be n*c*h*w, and the * space dimension doesn't matter * bottom[1]: The ground truth label, which can be n*c*h*w, also the space dimension * will not be used. It only required that the bottom[0]->count() == bottom[1]->count() * bottom[2]: The pairwise potential, each channel indicate one type of similarity measurement * height == width == botton[0/1]->channels()*bottom[0/1]->height()*bottom[0/1]->width() * The output of this loss is the energy of the CRF * * In addition, this layer can have 2 tops * If only one top is set, it only produce the loss value * If the top[1] is also set, it can estimate the depth through the top[1] * Its's shape is the same as the bottom[0] */ namespace caffe { template <typename Dtype> class Crf3LossLayer : public LossLayer<Dtype> { public: explicit Crf3LossLayer(const LayerParameter& param) : LossLayer<Dtype>(param){} virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline int ExactNumBottomBlobs() const { return 3; } virtual inline int ExactNumTopBlobs() const { return -1; } virtual inline const char* type() const { return "Crf3Loss"; } /** * Unlike most loss layers, in the Crf3LossLayer we can backpropagate * to both inputs -- override to return true and always allow force_backward. */ virtual inline bool AllowForceBackward(const int bottom_index) const { return true; } protected: /// @copydoc Crf3LossLayer virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); // Calc the R matrix according to the pairwise input virtual void Calc_R_cpu(const Blob<Dtype>*); virtual void Calc_R_gpu(const Blob<Dtype>*); // In forward process calc the matrix A according to R // The param is the pairwise matrix virtual void Calc_A_cpu(void); virtual void Calc_A_gpu(void); // Calc the A_inv matrix according to A virtual void Calc_A_inv_cpu(void); virtual void Calc_A_inv_gpu(void); // Inference the network virtual void Inference_cpu(const Blob<Dtype>* Z); virtual void Inference_gpu(const Blob<Dtype>* Z); // Normalize the weight according to the setting virtual void Normalize_weight_cpu(void); // Calc the loss between Pred_ and the bottom[1] virtual void Euclidean_loss_cpu(const Blob<Dtype>* gt, Blob<Dtype>* top); virtual void Euclidean_loss_gpu(const Blob<Dtype>* gt, Blob<Dtype>* top); // Calc the J matrix for BP process according to the pairwise input bottom[2] virtual void Calc_J_cpu(const Blob<Dtype>* bottom); virtual void Calc_J_gpu(const Blob<Dtype>* bottom); // Do the pairwise bp, and store the diff in the blob_[0].diff virtual void Pairwise_BP_cpu(const Blob<Dtype>* gt); virtual void Pairwise_BP_gpu(const Blob<Dtype>* gt); // Define the type of the unary potential enum UnaryDist { L2 }; UnaryDist unary_mode_; // Define the base learning rate for pairwise params Dtype pairwise_lr_; // Define the internal param Blob<Dtype> A_; // Define the matrix to store the pairwise relationship Blob<Dtype> R_; // Define the inverse of the A Blob<Dtype> A_inv_; // Define the prediction of the crf Blob<Dtype> Pred_; // Define the J matrix used for pairwise BP Blob<Dtype> J_; // Params for the pairwise parameters // whether to normalize the parameters bool normalize_; // Whether to keep the parameters positive bool positive_; // Whether to use partition function bool partition_; // The interval iteration to display the CRF W parameters, for debug // 0 indicate not display int disp_w_; // The counter to support the disp_w_ int counter_; }; } // namespace caffe #endif // CAFFE_CRF3_LOSS_LAYER_HPP_
[ "yan2006nt@sina.com" ]
yan2006nt@sina.com
a201f07782845822a24e85b8eca06d73c5c47e8c
cb82ac5b89726ed3ac0841dac7be9419208bb748
/include/FLIGHT/Graphics/Color.hpp
4ed68a5d35626af326f7714a506dbb35a1a258ca
[ "BSD-2-Clause" ]
permissive
evanbowman/FLIGHT
9d009f4a43f8011c9c33ad35fda6c994e47d6f12
cdb06059498efd63d9a94b27e8b9501e90bde86c
refs/heads/master
2021-10-16T15:14:47.595974
2019-02-11T21:11:00
2019-02-11T21:11:00
80,398,092
18
4
null
null
null
null
UTF-8
C++
false
false
75
hpp
#pragma once namespace FLIGHT { struct Color { float r, g, b, a; }; }
[ "ebowman@bu.edu" ]
ebowman@bu.edu
fe5c11f2da719448619733f024fe6b9706650a53
6097d80e8221e47398d6f78729766aee1e42ff97
/src/Engine/Exception.h
0cf62ec11fbde621cbf4485db25948db4dbd7244
[]
no_license
smaximov/falltergeist
7cd2e4744d93055cc697f0faa1f96892d2746295
f59da17ae310558783d238f720205798fd0f3f75
refs/heads/master
2021-01-24T23:00:26.425492
2014-09-30T11:49:11
2014-09-30T11:49:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,180
h
/* * Copyright 2012-2014 Falltergeist Developers. * * This file is part of Falltergeist. * * Falltergeist is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Falltergeist 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 Falltergeist. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FALLTERGEIST_EXCEPTION_H #define FALLTERGEIST_EXCEPTION_H // C++ standard includes #include <exception> #include <string> // Falltergeist includes // Third party includes namespace Falltergeist { class Exception : std::exception { private: std::string _message; public: Exception(std::string message) throw(); ~Exception() throw(); std::string message() throw(); }; } #endif // FALLTERGEIST_EXCEPTION_H
[ "mail@alexeevdv.ru" ]
mail@alexeevdv.ru
ccd3a3d1def7cadf6d07cac123b88b7ce6d4c287
1e4c7f5ba2a1da6a249cd891e24e9d9459c55802
/httpserver/beldexd_rpc.h
50729ee8aa41b4e43358c531f43da6b31b54f1c0
[ "MIT" ]
permissive
sanada08/beldex-storage-server
49ffbb6927665e85387ff0b8c3df8b52c49c8433
097d0a7815601e59705ce38f3ee440fdd2e42702
refs/heads/master
2023-06-24T22:45:26.495254
2021-07-30T05:58:15
2021-07-30T05:58:15
390,947,656
0
0
MIT
2021-07-30T05:53:18
2021-07-30T05:53:17
null
UTF-8
C++
false
false
950
h
#pragma once #include "beldexd_key.h" #include <string_view> #include <functional> namespace beldex { using beldexd_seckeys = std::tuple<legacy_seckey, ed25519_seckey, x25519_seckey>; // Synchronously retrieves MN private keys from beldex via the given oxenmq address. This constructs // a temporary OxenMQ instance to do the request (because generally storage server will have to // re-construct one once we have the private keys). // // Returns legacy privkey; ed25519 privkey; x25519 privkey. // // Takes an optional callback to invoke immediately before each attempt and immediately after each // failed attempt: if the callback returns false then get_mn_privkeys aborts, returning a tuple of // empty keys. // // This retries indefinitely until the connection & request are successful, or the callback returns // false. beldexd_seckeys get_mn_privkeys(std::string_view beldexd_rpc_address, std::function<bool()> keep_trying = nullptr); }
[ "sarath.kumar@beldex.io" ]
sarath.kumar@beldex.io
2c28b48ff21d60fe9592498447bc11d326daa859
91b01e7ef7230959b1ea411917065b3661fbbcfa
/src/arduino/arduino.ino
0867d5e4ba94da94ab5c14d5a4eb88b35496b465
[]
no_license
mmaao/maarika-rtech
f88c4fa0f99747328e25ec61ba437b07420b4020
84263fda71469e9304a063041e859118eea7842d
refs/heads/master
2020-04-25T21:03:13.188529
2019-05-30T14:52:18
2019-05-30T14:52:18
173,068,928
0
0
null
null
null
null
UTF-8
C++
false
false
972
ino
#include <ros.h> #include <sensor_msgs/Range.h> int echoPin = A4; int trigPin = A5; ros::NodeHandle nh; sensor_msgs::Range msg; ros::Publisher range("ultrasound/raw", &msg); void setup() { nh.initNode(); nh.advertise(range); pinMode(echoPin,INPUT); pinMode(trigPin,OUTPUT); } long getSonarReadingMillimeters() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); long duration_us = pulseIn(echoPin, HIGH); long distance_mm = (duration_us / 58.0) * 10; return distance_mm; } void loop() { float us = getSonarReadingMillimeters(); //Get distance from wall with ultrasonic sensor //sensor_msgs::Range msg; msg.header.frame_id = "bla"; msg.min_range = 0.02; msg.max_range = 4; msg.field_of_view = 0.785; double reading = getSonarReadingMillimeters(); msg.range = us/1000; range.publish(&msg); nh.spinOnce(); delay(100); }
[ "maarika.oidekivi@gmail.com" ]
maarika.oidekivi@gmail.com
fd0596a4e76d07e45b82e2d9dbb1c9004dadaa39
3c89aad5a33b6377fc8a1ac329b15396a0ea9d54
/classpath/ClassPath.h
a3b662fb55f3d2f2c1926d81d0e2301ca27ccd58
[]
no_license
luili16/TinyJvm
93733cfd75f758c6c0518a668c644ddfd754e1b7
2ff9a1fcae41aef1e8555856a979beebeec00f19
refs/heads/main
2023-02-16T05:06:09.800018
2021-01-14T02:55:29
2021-01-14T02:55:29
315,226,777
1
0
null
null
null
null
UTF-8
C++
false
false
535
h
// // Created by 刘立新 on 2020/11/17. // #ifndef CH01_CLASSPATH_H #define CH01_CLASSPATH_H #include <memory> #include "Entry.h" #include <string> namespace class_path { class ClassPath { public: ClassPath(std::string& jreOption,std::string& cpOption); ~ClassPath(); std::string toString(); std::vector<uint8_t>* readClass(std::string &className); private: Entry* bootClassPath; Entry* extClassPath; Entry* userClassPath; }; } #endif //CH01_CLASSPATH_H
[ "luili16@126.com" ]
luili16@126.com
ef55a9983d2e2c0270946e89858ebce1d72b778c
6840a13334ae8a5d7bd64f64f6e27a7aaf89c7b9
/800/801. Minimum Swaps To Make Sequences Increasing.hpp
a6745e551f58b166e50a64b41e603423739981aa
[]
no_license
wjhssfs/myLeetcode
2662c9f57262879ac87c3aaf77a153d62aaf3ea1
f076948f013eff610f072ae5af7808b582998805
refs/heads/master
2021-07-18T01:55:31.752794
2020-06-29T01:46:41
2020-06-29T01:46:41
32,279,021
1
0
null
null
null
null
UTF-8
C++
false
false
2,578
hpp
// 801. Minimum Swaps To Make Sequences Increasing // We have two integer sequences A and B of the same non-zero length. // We are allowed to swap elements A[i] and B[i]. Note that both elements are in the same index position in their respective sequences. // At the end of some number of swaps, A and B are both strictly increasing. (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.length - 1].) // Given A and B, return the minimum number of swaps to make both sequences strictly increasing. It is guaranteed that the given input always makes it possible. // Example: // Input: A = [1,3,5,4], B = [1,2,3,7] // Output: 1 // Explanation: // Swap A[3] and B[3]. Then the sequences are: // A = [1, 3, 5, 7] and B = [1, 2, 3, 4] // which are both strictly increasing. // Note: // A, B are arrays with the same length, and that length will be in the range [1, 1000]. // A[i], B[i] are integer values in the range [0, 2000]. class Solution { public: int minSwap(vector<int>& A, vector<int>& B) { int n = A.size(); vector<int> swapped(n, INT_MAX), notSwapped(n, INT_MAX); swapped[0] = 1, notSwapped[0] = 0; for (int i = 1; i < n; ++i) { if (A[i] > A[i - 1] && B[i] > B[i - 1]) { notSwapped[i] = notSwapped[i - 1]; swapped[i] = swapped[i - 1] + 1; } if (A[i] > B[i - 1] && B[i] > A[i - 1]) { notSwapped[i] = min(notSwapped[i], swapped[i - 1]); swapped[i] = min(swapped[i], notSwapped[i - 1] + 1); } } return min(swapped[n - 1], notSwapped[n - 1]); } }; // swapRecord means for the ith element in A and B, the minimum swaps if we swap A[i] and B[i]; fixRecord means for the ith element in A and B, the minimum swaps if we DONOT swap A[i] and B[i]. public int minSwap(int[] A, int[] B) { int swapRecord = 1, fixRecord = 0; for (int i = 1; i < A.length; i++) { if (A[i - 1] >= B[i] || B[i - 1] >= A[i]) { // The ith manipulation should be same as the i-1th manipulation fixRecord = fixRecord; swapRecord++; } else if (A[i - 1] >= A[i] || B[i - 1] >= B[i]) { // The ith manipulation should be the opposite of the i-1th manipulation int temp = swapRecord; swapRecord = fixRecord + 1; fixRecord = temp; } else { // Either swap or fix is OK. Let's keep the minimum one int min = Math.min(swapRecord, fixRecord); swapRecord = min + 1; fixRecord = min; } } return Math.min(swapRecord, fixRecord); }
[ "wjhssfs@gmail.com" ]
wjhssfs@gmail.com
94e756584d4ad9fbd1324697538997abee44c06a
af2dfde60ea72d9b6bc15a9cef27b0a23d3252bb
/Libs/spuce/filters/iir_allpass_variable_cascade.h
4860571dc996e67b5a8064d6f5ab184ceacfe73b
[ "BSL-1.0" ]
permissive
SCIBERCODE/volumeter
ea994283f127c61e9900f283779dc9909e4705c1
9e91c26dfb68ebf2a30237df362007409ad399f6
refs/heads/main
2023-02-23T19:35:46.530863
2021-01-29T21:05:52
2021-01-29T21:05:52
313,993,446
1
0
null
null
null
null
UTF-8
C++
false
false
3,612
h
#pragma once // Copyright (c) 2015 Tony Kirke. License MIT (http://www.opensource.org/licenses/mit-license.php) // from directory: double_templates #include <spuce/complex_operators.h> //#include <spuce/dsp_functions/math.h> //#include <spuce/fixed/round.h> #include <spuce/dsp_classes/circ_buffer.h> #include <spuce/filters/allpass.h> #include <spuce/filters/elliptic_allpass.h> #include <iostream> namespace spuce { //! \file //! \brief Template Class for iir filter consisting of 1st order allpass sections // //! This is a halfband IIR filter with two branches of cascades of //! 1st order allpass sections //! \author Tony Kirke //! \image html iir_allpass1_cascade.png //! \author Tony Kirke //! \ingroup double_templates double_templates iir template <class Numeric, class Coeff = float_type> class iir_allpass_variable_cascade { public: long stages; allpass<Numeric, Coeff> A0; allpass<Numeric, Coeff> A1; #ifdef OLD_WAY_B delay<Numeric> prev_input; #else circ_buffer<Numeric> prev_input; #endif bool hpf; Numeric out0, out1; public: //! n = Filter stages iir_allpass_variable_cascade(float_type fp = 0, int n = 1, int dly = 2) { int j = 0; int k = 0; hpf = false; prev_input.set_size(dly / 2); stages = n; // prev_input = (Numeric)0; if (stages > 0) { std::vector<float_type> a0(stages); std::vector<float_type> a1(stages); elliptic_allpass(a0, a1, fp, stages); j = (stages + 1) / 2; k = stages - j; // CONVERT FROM DOUBLE to COEFF std::vector<Coeff> a0c(stages); std::vector<Coeff> a1c(stages); for (int i = 0; i < stages; i++) { a0c[i] = (Coeff)a0[i]; a1c[i] = (Coeff)a1[i]; } A0.init(a0c, j, dly); A1.init(a1c, k, dly); } } //! n = Filter stages void set_coeffs(float_type fp, int n = 1, int dly = 2) { int j = 0; int k = 0; stages = n; prev_input.set_size(dly / 2); prev_input.reset(); //= (Numeric)0; if (stages > 0) { std::vector<float_type> a0(stages); std::vector<float_type> a1(stages); elliptic_allpass(a0, a1, fp, stages); j = (stages + 1) / 2; k = stages - j; // CONVERT FROM DOUBLE to COEFF std::vector<Coeff> a0c(stages); std::vector<Coeff> a1c(stages); for (int i = 0; i < stages; i++) { a0c[i] = (Coeff)a0[i]; a1c[i] = (Coeff)a1[i]; } A0.init(a0c, j, dly); A1.init(a1c, k, dly); } } Coeff get_a0(int i) { int j = (stages + 1) / 2; if ((i < j) && (i > -1)) return (A0.ap[i].get_coefficient()); else return (0); } Coeff get_a1(int i) { int j = (stages + 1) / 2; if ((i < stages - j) && (i > -1)) return (A1.ap[i].get_coefficient()); else return (0); } //! Destructor ~iir_allpass_variable_cascade() {} //! Reset history void reset() { A0.reset(); A1.reset(); prev_input.reset(); } void set_hpf(bool h) { hpf = h; } //! Clock in sample and get output. Numeric clock(Numeric input) { out0 = A0.clock(input); out1 = A1.clock(input); // std::cout << "IAVC out1 = " << out1 << " "; #ifdef OLD_WAY_B out1 = prev_input.input(out1); #else prev_input.input(out1); out1 = prev_input.last(); #endif // std::cout << out1 << "\n"; if (hpf) { return (round((out0 - out1), 1)); } else { return (round((out0 + out1), 1)); } } //! Clock in sample and get output. Numeric get_hp_out() { return (round((out0 - out1), 1)); } }; // template_instantiations: float_type } // namespace spuce
[ "62929889+SCIBERCODE@users.noreply.github.com" ]
62929889+SCIBERCODE@users.noreply.github.com
cf47afd8d118ba980bdc082a60b1d2325d989b36
8305f2b5231d3e7e5fe073e03b1ba2241e35fd1a
/TestClientADN/Sensor/sensor.h
741b712192b5e93bede27a14d6a18c95d09b0f16
[]
no_license
AikM2M/test-client-adn
f76ce99d1e4be3126c009a3bf6388d2156c0af52
35de80e9e8744b5c1a461ecad9050e9c72b0538a
refs/heads/master
2020-08-06T03:27:52.154169
2019-10-05T03:46:36
2019-10-05T03:46:36
212,816,912
0
0
null
null
null
null
UTF-8
C++
false
false
4,316
h
#pragma once #include <string> using namespace std; extern int ty, op, cst, rsc, mmg; extern std::string resourceType, cseType, operation, response; extern bool RequestReachability; extern bool rr, local; extern std::string mma, mmt, mgd, DevID, Man, Mod, DevType, FwV, SwV, HwV; extern std::string ri, pi, ct, et, lt, dmma, dmmt; extern std::string From, csi, api, poa, to, rqi, aei, rn; extern char URI[100]; extern char* c_aei; extern std::string con, cnf; extern std::string nu; extern std::string sur; extern int net, nct; extern const char* content; extern void resource_type(); extern void Operation_Type(); extern void Response_Type(); extern void CSE_Type(); struct Resource { string resourceName; //rn 1 int Resource_Type; //ty 1 string resourceID; //ri 1 string parentID; //pi 1 string creationTime; //ct 1 string lastModifiedTime; //lt 1 string labels; // 0-1 }; struct Management { string memoryAvailabe; //mma 1 string memoryTotal; //mmt 1 string DeviceID; //DevID string Manufacturer; //Man string Model; //Mod string DeviceType; //DevType string FirmwareVersion; //FwV string SoftwareVersion; //SwV string HardwareVersion; //HwV }; struct regularResource { //struct RES; string accessControlPolicyIDs; // string expirationTime; //et 1 string dynamicAuthorizationConsultationIDs; // }; struct announceableResource { //struct regRES; string announceTo; // string announcedAttribute; // }; struct announcedResource { //struct RES; string accessControlPolicyIDs; // 1 string expirationTime; //et 1 string link; // 1 string dynamicAuthorizationConsultationIDs; // 0-1 }; struct subordinateResource { //struct RES; string expirationTime; //et 1 }; struct announceableSubordinateResource { //struct RES; string expirationTime; //et 1 string announceTo; // 0-1 string announcedAttribute; // 0-1 }; struct announcedSubordinateResource { //struct RES; string expirationTime; //et 1 string link; // 1 }; class Response { public: int responseStatusCode; string Request_Identifier; string To; string From; int releaseVersion; }; class Request{ public: int Operation; string To; string From; string Request_Identifier; int Resource_Type; }; struct CreateAE { string resourceName; string App_ID; string pointOfAccess; bool requestReachability; }; struct CreateCIN { string resourceName; //rn string contentInfo; //cnf string content; //con }; struct CreateSub { string resourceName; //rn string notificationURI; //nu int notificationContentType; //nct int notificationEventType; //net }; struct respAE { string App_ID; bool requestReachability; string AE_ID; string pointOfAccess; }; struct respCnt { int stateTag; int CurrentNrOfInstances; int CurrentByteSize; }; struct respCin { string contentInfo; int contentSize; int stateTag; string content; }; struct respSub { string notificationURI; int notificationContentType; int notificationEventType; }; const char* Create_Req(Request Req); const char* Retrive_Req(Request Req); const char* Update_Req(Request Req); const char* Delete_Req(Request Req); ///////////////////////////////////// const char* Create_Resp(Response Resp); const char* Notify_Resp(Response Resp); void process_msg(const char* Buffer);
[ "noreply@github.com" ]
AikM2M.noreply@github.com
dfae7f1e9ae78a40a7e424a1639dcd551411949e
f24e7daff602a5e3f2b4909721548a9f84598a56
/topcoder/Single-Round-Match-653/900/driver.cc
103a1df95442f95ee83644c4e77afd65976a308a
[]
no_license
permin/Olymp
05b594e8c09adb04c1aa065ba6dd7f2dae8f4d6e
51ac43fcbcc14136ed718481f64e09036f10ddf8
refs/heads/master
2021-01-18T23:04:00.491119
2017-03-08T22:22:25
2017-03-08T22:22:25
23,457,833
0
0
null
null
null
null
UTF-8
C++
false
false
3,911
cc
#include "RockPaperScissorsMagic.cc" #include <algorithm> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <sys/time.h> #include <vector> const static double __EPSILON = 1e-9; static double __time = 0.0; static void __timer_start() { struct timeval tv; if (gettimeofday(&tv, NULL) == 0) { __time = double(tv.tv_sec) * 1000.0 + double(tv.tv_usec) * 0.001; } } static double __timer_stop() { double start = __time; __timer_start(); return __time - start; } static void __eat_whitespace(std::istream& in) { while (in.good() && std::isspace(in.peek())) in.get(); } std::ostream& operator << (std::ostream& out, const std::string& str) { out << '"' << str.c_str() << '"'; return out; } std::istream& operator >> (std::istream& in, std::string& str) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '"') { std::ostringstream s; while (in.good() && (c = in.get()) != '"') { s.put(char(c)); } str = s.str(); } return in; } template <class T> std::istream& operator >> (std::istream& in, std::vector<T>& vec) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '{') { __eat_whitespace(in); vec.clear(); while (in.good() && (c = in.get()) != '}') { if (c != ',') in.putback(static_cast<char>(c)); T t; in >> t; __eat_whitespace(in); vec.push_back(t); } } return in; } template <class T> bool __equals(const T& actual, const T& expected) { return actual == expected; } bool __equals(double actual, double expected) { if (std::abs(actual - expected) < __EPSILON) { return true; } else { double minimum = std::min(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); double maximum = std::max(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); return actual > minimum && actual < maximum; } } bool __equals(const std::vector<double>& actual, const std::vector<double>& expected) { if (actual.size() != expected.size()) { return false; } for (size_t i = 0; i < actual.size(); ++i) { if (!__equals(actual[i], expected[i])) { return false; } } return true; } int main(int argc, char** ) { bool __abort_on_fail = false; int __pass = 0; int __fail = 0; if (1 < argc) __abort_on_fail = true; std::cout << "TAP version 13" << std::endl; std::cout.flush(); std::ifstream __in("testcases.txt"); for(;;) { int __testnum = __pass + __fail + 1; int __expected; int win; int lose; int tie; vector <int> card; __in >> __expected >> win >> lose >> tie >> card; if (!__in.good()) break; std::cout << "===============Test " << __testnum<< "==================\n"; std::cout << "input for test: " << win << ", " << lose << ", " << tie << ", " << card << std::endl; std::cout.flush(); __timer_start(); RockPaperScissorsMagic __object; int __actual = __object.count(win, lose, tie, card); double __t = __timer_stop(); std::cout << "test completed in " << __t << "ms" << std::endl; std::cout.flush(); if (__equals(__actual, __expected)) { std::cout << "\033[1;32mOK\033[0m"; ++__pass; } else { std::cout << "\033[1;31mWA\033[0m"; ++__fail; } std::cout << " - " << __actual << " must equal " << __expected << std::endl; std::cout.flush(); if (__abort_on_fail && 0 < __fail) std::abort(); } std::cout << "===============Total==================\n"; std::cout << "1.." << (__pass + __fail) << std::endl << "Passed: \033[1;32m" << __pass << "\033[0m" << std::endl << "Failed: \033[1;31m" << __fail << "\033[0m" << std::endl; if (__fail == 0) { std::cout << std::endl << "\033[1;32mNice!\033[0m DON'T FORGET TO COMPILE REMOTELY BEFORE SUBMITTING!\n" << std::endl; } else { std::cout << "\n" << "\033[1;31mWrong answer\033[0m"<<"\n" << std::endl; } return __fail; } // vim:ft=cpp:noet:ts=8
[ "rodion.permin@gmail.com" ]
rodion.permin@gmail.com
1801d41d9be85b9f413b20b036bd60bc0a8dbdc1
7545c40501810c14b702ef8017e0c3e9359ffc94
/Arkanoid/main.cpp
375429981306fa1536d2d13f8de96e5f1c9993d3
[]
no_license
mava4233/Pac-Man-Example
2db0fcad97f4decccc37e51dafa6f96c7df35c18
f4095c6456f361303ca60666688cf53f18aca20d
refs/heads/master
2016-09-10T19:17:47.253160
2015-01-29T16:07:54
2015-01-29T16:07:54
30,026,340
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
// main.cpp #include "stdafx.h" #include "Engine.h" // !! bit.ly/1vSPzOk !! // topics // == previous: // Engine // DrawManager // InputManager // Mouse // Keyboard // == today: // StateManager // State // GameState // TextureManager // CollisionManager int main(int argc, char* argv[]) { Engine engine; if (engine.Initialize()) engine.Update(); engine.Shutdown(); return 0; }
[ "marcus.vanaller@gmail.com" ]
marcus.vanaller@gmail.com
2a3f836ac5f6743e027845468ccec422f2515629
71256c73349c649d8110c0c8ddbf57f536b1c7d5
/NewAtCoderC++/TadaLib/BinarySearchLib.h
8ca08880e94ebc85d1831f0a2b5e010d2a1ecc6d
[]
no_license
tada0389/NewAtCoder
afe6c20df9f6fa09bf64ace08cde198f6003d909
bfe68240c1274a66a011792d0ca09a80bcb1651b
refs/heads/master
2021-03-22T18:33:31.604815
2020-11-05T09:30:19
2020-11-05T09:30:19
247,392,212
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,835
h
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <array> #include <queue> #include <deque> #include <map> #include <set> #include <sstream> #include <cstdio> #include <cstring> #include <cmath> #include <list> #include <numeric> #include <stack> #include <iomanip> #include <random> #include <complex> #include <functional> using namespace std; #define Rep(i,a,b) for(int i = a; i < b; ++i) #define rep(i,b) Rep(i,0,b) #define allof(a) (a).begin(), (a).end() #define Yes(q) ((q) ? "Yes" : "No") #define YES(q) ((q) ? "YES" : "NO") #define Possible(q) ((q) ? "Possible" : "Impossible") #define POSSIBLE(q) ((q) ? "POSSIBLE" : "IMPOSSIBLE") using ll = long long; using pint = std::pair<int, int>; using pll = std::pair<ll, ll>; constexpr int inf = 1e9 + 7; constexpr ll infll = 1ll << 60ll; constexpr ll mod = 1e9 + 7; // 0~3までは右左下上 4~7までは斜め constexpr int dx[] = { 1, 0, -1, 0, 1, 1, -1, -1 }; constexpr int dy[] = { 0, -1, 0, 1, 1, -1, -1, 1 }; namespace { template<typename T> void chmax(T& a, T b) { a = std::max(a, b); } template<typename T> void chmin(T& a, T b) { a = std::min(a, b); } template<typename T> void chadd(T& a, T b) { a = a + b; } template<typename T> T gcd(T a, T b) { if (a < b) std::swap(a, b); while (b) std::swap(a %= b, b); return a; } template<typename T> T lcm(const T a, const T b) { return a / gcd(a, b) * b; } template <typename T> void Cout(T& x, char end = '\n') { std::cout << x << end; } template <typename T> void Cout(std::vector<T>& x, char sep = ' ', char end = '\n') { for (std::size_t i = 0, sz = x.size(); i < sz; i++) { std::cout << x[i] << (i == sz - 1 ? end : sep); } } // 標準入出力 struct Read { size_t sz; Read(size_t _sz = 1) : sz(_sz) {} template <typename T> operator T () const { T a; std::cin >> a; return a; } template <typename T> operator std::vector<T>() const { vector<T> a(sz); for (std::size_t i = 0; i < sz; i++) std::cin >> a[i]; return a; } template <typename T, typename U> operator std::pair<T, U>() const { T f; U s; std::cin >> f >> s; return std::pair<T, U>(f, s); } }; Read inp1; // input one // 二分探索を行うライブラリ // @author tada // T は返り値の型 template<typename T> T BinarySearch(T left, T right, std::function<bool(T)> Check) { while (right - left > 1) { T mid = (right + left) / 2; if (Check(mid)) left = mid; // 右を探す else right = mid; // 左を探す } // mid = left, mid = right - 1 となっている return left; } } // https://atcoder.jp/contests/exawizards2019/tasks/exawizards2019_c //int main() { // // int n, q; // string s; // cin >> n >> q >> s; // vector<char> t(q), d(q); // rep(i, q) cin >> t[i] >> d[i]; // // int left_drop = BinarySearch<int>(0, n, [&](int mid)->bool { // // midが左にドロップするかどうか // int pos = mid; // bool drop = false; // rep(i, q) { // if (s[pos] != t[i]) continue; // // 移動する番 // if (d[i] == 'L') --pos; // else ++pos; // // if (pos < 0) { // drop = true; // break; // } // if (pos >= n) { // break; // } // } // return drop; // }); // // int right_drop = BinarySearch<int>(0, n, [&](int mid)->bool { // // midが右にドロップするかどうか // int pos = mid; // bool drop = false; // rep(i, q) { // if (s[pos] != t[i]) continue; // // 移動する番 // if (d[i] == 'L') --pos; // else ++pos; // // if (pos < 0) { // //drop = true; // break; // } // if (pos >= n) { // drop = true; // break; // } // } // return !drop; // }) + 1; // // int ans = right_drop - left_drop - 1; // Cout(ans); // // return 0; //}
[ "tatata0389@gmail.com" ]
tatata0389@gmail.com
3e87403b46c3e432c8cc2a504d2e835d54aed186
6f36ab50dc7578f5ca161c5b861c68e839535b74
/c++/decltype.cpp
67bdcbf9cf35defef778c94e7115b8e9fcbb89c6
[]
no_license
RandyLambert/daily
144e49eb945ce6b33a8d06c409b8db1318d01526
be1634663d5248f7abcc92e4a42f193411ad5aca
refs/heads/master
2021-06-24T01:45:54.574544
2021-04-14T16:15:35
2021-04-14T16:15:35
207,723,773
2
0
null
null
null
null
UTF-8
C++
false
false
2,719
cpp
#include <iostream> #include <map> using namespace std; template <typename T1,typename T2> auto add(T1 x,T2 y)->decltype(x+y);//1,声明一种函数返回类型,特殊用法 int getSize(); /* typedef typename decltype(obj)::iterator iType; *///2.函数模板的应用,获取obj的类型,里面的typename可以不要,那个是给编译器看的 auto cmp= [](const int a,int b){ return a<b; }; map<int,decltype(cmp)> q;//lambdas一般很难写出是什么类型的,所以使用auto和decltype来辅助编程 int main(){ map<int,double> a; decltype(a)::value_type c; //判断类型 int tempAi = 2; /*1.dclTempA为int.*/ decltype(tempAi) dclTempAi; /*2.dclTempB为int,对于getSize根本没有定义,但是程序依旧正常,因为decltype只做分析,并不调用getSize().*/ decltype(getSize()) dclTempBi; double tempA = 3.0; const double ctempA = 5.0; const double ctempB = 6.0; const double *const cptrTempA = &ctempA; /*1.dclTempA推断为const double(保留顶层const,此处与auto不同)*/ decltype(ctempA) dclTempA = 4.1; /*2.dclTempA为const double,不能对其赋值,编译不过*/ /* dclTempA = 5; */ /*3.dclTempB推断为const double * const*/ decltype(cptrTempA) dclTempB = &ctempA; /*4.输出为4(32位计算机)和5*/ cout<<sizeof(dclTempB)<<" "<<*dclTempB<<endl; /*5.保留顶层const,不能修改指针指向的对象,编译不过*/ /* dclTempB = &ctempB; */ /*6.保留底层const,不能修改指针指向的对象的值,编译不过*/ /* *dclTempB = 7.0; */ int tempAy = 0, &refTempAy = tempAy; /*1.dclTempA为引用,绑定到tempA*/ decltype(refTempAy) dclTempAy = tempAy; /*2.dclTempB为引用,必须绑定到变量,编译不过*/ /* decltype(refTempAy) dclTempBy = 0; */ /*3.dclTempC为引用,必须初始化,编译不过*/ /* decltype(refTempAy) dclTempCy; */ /*4.双层括号表示引用,dclTempD为引用,绑定到tempA*/ decltype((tempA)) dclTempD = tempA; const int ctempAy = 1, &crefTempA = ctempA; /*5.dclTempE为常量引用,可以绑定到普通变量tempA*/ decltype(crefTempA) dclTempE = tempA; /*6.dclTempF为常量引用,可以绑定到常量ctempA*/ decltype(crefTempA) dclTempF = ctempA; /*7.dclTempG为常量引用,绑定到一个临时变量*/ decltype(crefTempA) dclTempG = 0; /*8.dclTempH为常量引用,必须初始化,编译不过*/ /* decltype(crefTempA) dclTempH; */ /*9.双层括号表示引用,dclTempI为常量引用,可以绑定到普通变量tempA*/ decltype((ctempA)) dclTempI = ctempA; return 0; }
[ "1249604462@qq.com" ]
1249604462@qq.com
521e9b0001d91d4e2631e20f40b57a1e7b205343
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/Chaste/2016/12/AbstractGeneralizedRushLarsenCardiacCell.cpp
5739e017ad66ecc9f3461bb064f9d6c23df9c87a
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
6,099
cpp
/* Copyright (c) 2005-2016, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Megan E. Marsh, Raymond J. Spiteri Numerical Simulation Laboratory University of Saskatchewan December 2011 Partial support provided by research grants from the National Science and Engineering Research Council (NSERC) of Canada and the MITACS/Mprime Canadian Network of Centres of Excellence. */ #include "AbstractGeneralizedRushLarsenCardiacCell.hpp" #include <cassert> #include <cmath> #include "Exception.hpp" #include "OdeSolution.hpp" #include "TimeStepper.hpp" AbstractGeneralizedRushLarsenCardiacCell::AbstractGeneralizedRushLarsenCardiacCell(unsigned numberOfStateVariables, unsigned voltageIndex, boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus) : AbstractCardiacCell(boost::shared_ptr<AbstractIvpOdeSolver>(), numberOfStateVariables, voltageIndex, pIntracellularStimulus), mHasAnalyticJacobian(false) { mPartialF.resize(numberOfStateVariables); mEvalF.resize(numberOfStateVariables); mYInit.resize(numberOfStateVariables); } AbstractGeneralizedRushLarsenCardiacCell::~AbstractGeneralizedRushLarsenCardiacCell() {} OdeSolution AbstractGeneralizedRushLarsenCardiacCell::Compute(double tStart, double tEnd, double tSamp) { // Check length of time interval if (tSamp < mDt) { tSamp = mDt; } const unsigned n_steps = (unsigned) floor((tEnd - tStart)/tSamp + 0.5); assert(fabs(tStart+n_steps*tSamp - tEnd) < 1e-12); const unsigned n_small_steps = (unsigned) floor(tSamp/mDt+0.5); assert(fabs(mDt*n_small_steps - tSamp) < 1e-12); // Initialise solution store OdeSolution solutions; solutions.SetNumberOfTimeSteps(n_steps); solutions.rGetSolutions().push_back(rGetStateVariables()); solutions.rGetTimes().push_back(tStart); solutions.SetOdeSystemInformation(this->mpSystemInfo); // Loop over time double v_old, v_new; double& r_V = rGetStateVariables()[GetVoltageIndex()]; for (unsigned i=0; i<n_steps; i++) { double curr_time = tStart; for (unsigned j=0; j<n_small_steps; j++) { curr_time = tStart + i*tSamp + j*mDt; v_old = r_V; UpdateTransmembranePotential(curr_time); v_new = r_V; r_V = v_old; ComputeOneStepExceptVoltage(curr_time); r_V = v_new; VerifyStateVariables(); } // Update solutions solutions.rGetSolutions().push_back(rGetStateVariables()); solutions.rGetTimes().push_back(curr_time+mDt); } return solutions; } void AbstractGeneralizedRushLarsenCardiacCell::ComputeExceptVoltage(double tStart, double tEnd) { SetVoltageDerivativeToZero(true); TimeStepper stepper(tStart, tEnd, mDt); while (!stepper.IsTimeAtEnd()) { ComputeOneStepExceptVoltage(stepper.GetTime()); #ifndef NDEBUG // Check gating variables are still in range VerifyStateVariables(); #endif // NDEBUG stepper.AdvanceOneTimeStep(); } SetVoltageDerivativeToZero(false); } void AbstractGeneralizedRushLarsenCardiacCell::SolveAndUpdateState(double tStart, double tEnd) { TimeStepper stepper(tStart, tEnd, mDt); double v_old, v_new; double& r_V = rGetStateVariables()[GetVoltageIndex()]; while (!stepper.IsTimeAtEnd()) { v_old = r_V; UpdateTransmembranePotential(stepper.GetTime()); v_new = r_V; r_V = v_old; ComputeOneStepExceptVoltage(stepper.GetTime()); r_V = v_new; VerifyStateVariables(); stepper.AdvanceOneTimeStep(); } } bool AbstractGeneralizedRushLarsenCardiacCell::HasAnalyticJacobian() const { return mHasAnalyticJacobian; } void AbstractGeneralizedRushLarsenCardiacCell::ForceUseOfNumericalJacobian(bool useNumericalJacobian) { if (!useNumericalJacobian) { EXCEPTION("Using analytic Jacobian terms for generalised Rush-Larsen is not yet supported."); } // if (!useNumericalJacobian && !mHasAnalyticJacobian) // { // EXCEPTION("Analytic Jacobian requested, but this ODE system doesn't have one. You can check this with HasAnalyticJacobian()."); // } mUseAnalyticJacobian = !useNumericalJacobian; }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
3caf344e917874b6d1ed8ac09765035e56502c57
aae79375bee5bbcaff765fc319a799f843b75bac
/srm_6xx/srm_662/ExactTreeEasy.cpp
067a9820b8427376bf33cb1eae1530f4589b9ef3
[]
no_license
firewood/topcoder
b50b6a709ea0f5d521c2c8870012940f7adc6b19
4ad02fc500bd63bc4b29750f97d4642eeab36079
refs/heads/master
2023-08-17T18:50:01.575463
2023-08-11T10:28:59
2023-08-11T10:28:59
1,628,606
21
6
null
null
null
null
UTF-8
C++
false
false
2,618
cpp
// BEGIN CUT HERE /* SRM 662 Div2 Medium (500) 問題 -N個のノードがある -M個の葉を持つ木を構築せよ */ // END CUT HERE #include <algorithm> #include <cstring> #include <string> #include <vector> #include <iostream> #include <sstream> using namespace std; class ExactTreeEasy { public: vector <int> getTree(int n, int m) { vector <int> ans(n * 2 - 2); for (int i = 0; i < n - 1; ++i) { if (i <= n - m) { ans[i * 2] = i; } else { ans[i * 2] = n - m; } ans[i * 2 + 1] = i + 1; } return ans; } // BEGIN CUT HERE private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } public: void run_test(int Case) { int n = 0; // test_case_0 if ((Case == -1) || (Case == n)){ int Arg0 = 4; int Arg1 = 2; int Arr2[] = {0, 1, 1, 2, 2, 3 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(n, Arg2, getTree(Arg0, Arg1)); } n++; // test_case_1 if ((Case == -1) || (Case == n)){ int Arg0 = 4; int Arg1 = 3; int Arr2[] = {0, 1, 1, 2, 1, 3 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(n, Arg2, getTree(Arg0, Arg1)); } n++; // test_case_2 if ((Case == -1) || (Case == n)){ int Arg0 = 3; int Arg1 = 2; int Arr2[] = {0, 1, 1, 2 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(n, Arg2, getTree(Arg0, Arg1)); } n++; // test_case_3 if ((Case == -1) || (Case == n)){ int Arg0 = 5; int Arg1 = 3; int Arr2[] = {0, 1, 1, 2, 1, 3, 3, 4 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(n, Arg2, getTree(Arg0, Arg1)); } n++; // test_case_4 if ((Case == -1) || (Case == n)){ int Arg0 = 10; int Arg1 = 9; int Arr2[] = {0, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(n, Arg2, getTree(Arg0, Arg1)); } n++; } // END CUT HERE }; // BEGIN CUT HERE int main() { ExactTreeEasy ___test; ___test.run_test(-1); } // END CUT HERE
[ "karamaki@gmail.com" ]
karamaki@gmail.com
e555f0dffe734f54a6074aa9fdf56791fc066aec
3a7fddd38ce5135367381819b01974528b47c912
/gnc/matlab/code_generation/sharedutils/kfcjlnglmgdbgdjm_all.cpp
08e8cd03a240358cd05218674be8e618fb5bc466
[ "Apache-2.0", "LGPL-2.1-only", "LGPL-2.0-or-later", "LGPL-3.0-only", "MIT", "GPL-3.0-only", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "CC-BY-NC-4.0", "GPL-2.0-only", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-philippe-de-muyter", "MPL-2.0", "MPL-1.0", "LGPL-2.1-or-later", "LicenseRef-scancode-other-copyleft" ]
permissive
Hackjaku/astrobee
8409b671d88535d8d729a3f301019726d01e78d1
0ee5a7e90939ab7d81835f56a81fa0d329da0004
refs/heads/master
2020-03-30T02:49:58.241804
2018-09-27T18:17:47
2018-09-27T18:17:47
150,653,073
3
0
Apache-2.0
2018-09-27T22:03:21
2018-09-27T22:03:21
null
UTF-8
C++
false
false
715
cpp
// // File: kfcjlnglmgdbgdjm_all.cpp // // Code generated for Simulink model 'sim_model_lib0'. // // Model version : 1.1142 // Simulink Coder version : 8.11 (R2016b) 25-Aug-2016 // C/C++ source code generated on : Mon Dec 4 08:34:45 2017 // #include "rtwtypes.h" #include "kfcjlnglmgdbgdjm_all.h" // Function for MATLAB Function: '<S79>/generate_output' boolean_T kfcjlnglmgdbgdjm_all(const boolean_T x[4]) { boolean_T y; int32_T k; boolean_T exitg1; y = true; k = 0; exitg1 = false; while ((!exitg1) && (k < 4)) { if (!x[k]) { y = false; exitg1 = true; } else { k++; } } return y; } // // File trailer for generated code. // // [EOF] //
[ "theodore.f.morse@nasa.gov" ]
theodore.f.morse@nasa.gov
0f5247954991210c50026c6d8055abb34caf05d1
e48c0f097573727af67058b6858b1bd47a0173e8
/chaper1/1-1.cpp
93949e9a9998c85a939cc39cfcf94d231b3d364a
[]
no_license
xiliangjianke/learn_cpp_primer
94a54306fca859a2933f8144ce787e1d77c7fa19
be245c8be4d3a1e0adff92f75f59766315c54d30
refs/heads/main
2023-02-01T21:05:07.326356
2020-12-19T13:38:35
2020-12-19T13:38:35
322,823,798
0
0
null
null
null
null
UTF-8
C++
false
false
27
cpp
int main() { return 0; }
[ "biankairui@163.com" ]
biankairui@163.com
ef56eb4ffd387d7f3f5d9afa2de89a434c82d4ce
3e48907a6388fb9d4369d1a3e22424ed9e0a1756
/server/wsserver.cpp
e035e721afe9ad9bbd3460d6c855f5f205fa2d0c
[]
no_license
tarmoj/mysterium
96a3bd73771d1f9d4f4220fddfa3926696ff23b1
725f3018e3a4d1463372f70f7cce01726cb85fd7
refs/heads/master
2021-10-26T14:28:49.847817
2021-10-14T06:42:34
2021-10-14T06:42:34
160,786,413
0
0
null
null
null
null
UTF-8
C++
false
false
5,596
cpp
#include "wsserver.h" #include "QtWebSockets/qwebsocketserver.h" #include "QtWebSockets/qwebsocket.h" #include <QtCore/QDebug> #include "player.h" #include <QFile> QT_USE_NAMESPACE WsServer::WsServer(quint16 port, QObject *parent) : QObject(parent), counter(-10), everyNthCommand(1), m_pWebSocketServer(new QWebSocketServer(QStringLiteral("MysteriumServer"), QWebSocketServer::NonSecureMode, this)), m_clients() { if (m_pWebSocketServer->listen(QHostAddress::Any, port)) { qDebug() << "WsServer listening on port" << port; connect(m_pWebSocketServer, &QWebSocketServer::newConnection, this, &WsServer::onNewConnection); connect(m_pWebSocketServer, &QWebSocketServer::closed, this, &WsServer::closed); } playerSockets << nullptr << nullptr << nullptr << nullptr << nullptr << nullptr; connect(&timer, SIGNAL(timeout()), this, SLOT(counterChanged()) ); for (int i=0;i<6;i++) { players << new Player(this, i); connect(players[i], SIGNAL(sendCommand(int, QString)), this, SIGNAL(sendCommand(int, QString))); } loadDensities(); } WsServer::~WsServer() { m_pWebSocketServer->close(); qDeleteAll(m_clients.begin(), m_clients.end()); } void WsServer::onNewConnection() { QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection(); connect(pSocket, &QWebSocket::textMessageReceived, this, &WsServer::processTextMessage); //connect(pSocket, &QWebSocket::binaryMessageReceived, this, &WsServer::processBinaryMessage); connect(pSocket, &QWebSocket::disconnected, this, &WsServer::socketDisconnected); m_clients << pSocket; emit newConnection(m_clients.count()); } void WsServer::processTextMessage(QString message) // message must be an array of numbers (8bit), separated with colons { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); if (!pClient) { return; } qDebug()<<"Message received: "<<message; QStringList messageParts = message.split(","); if (messageParts[0].toLower()=="fl") { int index = playerSockets.indexOf(pClient); if (index>0) { // remove the old one if player changed the name playerSockets[index] = nullptr; } playerSockets[FLUTE] = pClient; } if (messageParts[0].toLower()=="cl") { int index = playerSockets.indexOf(pClient); // stupid copy, rather use another function. But copying is faster... if (index>=0) { // remove the old one if player changed the name playerSockets[index] = nullptr; } playerSockets[CLARINET] = pClient; } if (messageParts[0].toLower()=="vl") { int index = playerSockets.indexOf(pClient); if (index>=0) { // remove the old one if player changed the name playerSockets[index] = nullptr; } playerSockets[VIOLIN] = pClient; } if (messageParts[0].toLower()=="vlc") { int index = playerSockets.indexOf(pClient); if (index>=0) { // remove the old one if player changed the name playerSockets[index] = nullptr; } playerSockets[CELLO] = pClient; } if (messageParts[0].toLower()=="pf") { int index = playerSockets.indexOf(pClient); if (index>=0) { // remove the old one if player changed the name playerSockets[index] = nullptr; } playerSockets[PIANO] = pClient; } if (messageParts[0].toLower()=="perc") { int index = playerSockets.indexOf(pClient); if (index>=0) { // remove the old one if player changed the name playerSockets[index] = nullptr; } playerSockets[PERCUSSION] = pClient; } } void WsServer::socketDisconnected() { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); if (pClient) { int index = playerSockets.indexOf(pClient); if (index>=0) { playerSockets[index] = nullptr; // probably crash if it disconnects exatly when message is being sent. Not likely } m_clients.removeAll(pClient); emit newConnection(m_clients.count()); pClient->deleteLater(); } } void WsServer::counterChanged() // timer timeOut slot { counter++; emit newCounter(counter); for (int i=0;i<players.count();i++) { players[i]->checkEvents(); } //TODO: check density QHash< int, int >::const_iterator foundHash = densityHash.find(counter); if (foundHash != densityHash.end() && foundHash.key() == counter) { setDensity(foundHash.value()); emit newDensity(foundHash.value()); } } void WsServer::sendToAll(QString message ) { foreach(QWebSocket *socket, m_clients) { if (socket) { socket->sendTextMessage(message); } } } void WsServer::loadDensities() { QString fileName = ":/command-files/density"; QFile inputFile(fileName); if (inputFile.open(QIODevice::ReadOnly|QIODevice::Text)) { QTextStream in(&inputFile); int counter = 0; while (!in.atEnd()) { QString line = in.readLine(); QStringList fields = line.split("\t"); if (fields.count()>=2) { bool timeOk, densityOk; int time = fields[0].toInt(&timeOk); int density = fields[1].toInt(&densityOk); if (timeOk && densityOk) { densityHash.insert(time, density); counter++; } } } qDebug()<<"Added " << counter << "densities"; inputFile.close(); } else { qDebug()<<"Could not open file " <<fileName; } } void WsServer::setDensity(int density) { if (density>0 && density <= 12) { everyNthCommand = density; qDebug() << "Setting density to " << everyNthCommand; } else { qDebug() << "Illegal density value: " << density; } }
[ "tarmo@otsakool.edu.ee" ]
tarmo@otsakool.edu.ee
2ca650150129f2e5b9199700f601c38010c64e0f
bc24f3d1dfd76dddce1e0e0e00ec6c28818496f3
/source/TexturePainter.cpp
140f7f24dbf4725865247119916ae53e8ae646a7
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
vonLeebpl/WKIrrlichtLime
515ff5031c06680219d91f31e5d46575a5214a03
79e17540574bceaecc27049d99eb4ee2f6ca3479
refs/heads/master
2021-04-21T08:19:39.320661
2020-04-26T10:57:01
2020-04-26T10:57:01
249,764,538
0
0
null
null
null
null
UTF-8
C++
false
false
5,902
cpp
#include "stdafx.h" #include "Image.h" #include "Texture.h" #include "TexturePainter.h" using namespace irr; using namespace System; using namespace IrrlichtLime::Core; namespace IrrlichtLime { namespace Video { TexturePainter::TexturePainter(Video::Texture^ texture) { LIME_ASSERT(texture != nullptr); LIME_ASSERT(Image::GetBitsPerPixelFromFormat(texture->ColorFormat) / 8 > 0); m_texture = texture; m_format = texture->m_Texture->getColorFormat(); m_rowSize = texture->m_Texture->getPitch(); m_pixelSize = video::IImage::getBitsPerPixelFromFormat(texture->m_Texture->getColorFormat()) / 8; core::dimension2du d = texture->m_Texture->getSize(); int m = d.Width < d.Height ? d.Width : d.Height; m_mipmapLevelCount = (int)ceil(log((float)m) / log(2.0f)) + 1; m_mipmapLevel = -1; m_mipmapLevelWidth = -1; m_mipmapLevelHeight = -1; } Color^ TexturePainter::GetPixel(int x, int y) { LIME_ASSERT(Locked); LIME_ASSERT(LockMode == TextureLockMode::ReadWrite || LockMode == TextureLockMode::ReadOnly); LIME_ASSERT(x >= 0 && x < MipMapLevelWidth); LIME_ASSERT(y >= 0 && y < MipMapLevelHeight); Color^ c = gcnew Color(); c->m_NativeValue->setData( (unsigned char*)m_pointer + y * (m_rowSize/(1 << m_mipmapLevel)) + x * m_pixelSize, m_format); return c; } bool TexturePainter::Lock(TextureLockMode lockMode, int mipmapLevel) { LIME_ASSERT(mipmapLevel >= 0 && mipmapLevel < m_mipmapLevelCount); m_pointer = m_texture->m_Texture->lock((video::E_TEXTURE_LOCK_MODE)lockMode, mipmapLevel); if (m_pointer == nullptr) return false; m_lockMode = lockMode; m_mipmapLevel = mipmapLevel; int f = 1 << m_mipmapLevel; m_mipmapLevelWidth = m_texture->m_Texture->getSize().Width / f; m_mipmapLevelHeight = m_texture->m_Texture->getSize().Height / f; return true; } bool TexturePainter::Lock(TextureLockMode lockMode) { m_pointer = m_texture->m_Texture->lock((video::E_TEXTURE_LOCK_MODE)lockMode); if (m_pointer == nullptr) return false; m_lockMode = lockMode; m_mipmapLevel = 0; m_mipmapLevelWidth = m_texture->m_Texture->getSize().Width; m_mipmapLevelHeight = m_texture->m_Texture->getSize().Height; return true; } bool TexturePainter::Lock() { m_pointer = m_texture->m_Texture->lock(); if (m_pointer == nullptr) return false; m_lockMode = TextureLockMode::ReadWrite; m_mipmapLevel = 0; m_mipmapLevelWidth = m_texture->m_Texture->getSize().Width; m_mipmapLevelHeight = m_texture->m_Texture->getSize().Height; return true; } void TexturePainter::SetLine(int x1, int y1, int x2, int y2, Color^ color) { LIME_ASSERT(Locked); LIME_ASSERT(LockMode == TextureLockMode::ReadWrite || LockMode == TextureLockMode::WriteOnly); LIME_ASSERT(x1 >= 0 && x1 < MipMapLevelWidth); LIME_ASSERT(y1 >= 0 && y1 < MipMapLevelHeight); LIME_ASSERT(x2 >= 0 && x2 < MipMapLevelWidth); LIME_ASSERT(y2 >= 0 && y2 < MipMapLevelHeight); LIME_ASSERT(color != nullptr); bool t = abs(y2 - y1) > abs(x2 - x1); if (t) { x1 ^= y1; y1 ^= x1; x1 ^= y1; // swap x1, y1 x2 ^= y2; y2 ^= x2; x2 ^= y2; // swap x2, y2 } if (x1 > x2) { x1 ^= x2; x2 ^= x1; x1 ^= x2; // swap x1, x2 y1 ^= y2; y2 ^= y1; y1 ^= y2; // swap y1, y2 } int dx = x2 - x1; int dy = abs(y2 - y1); int sy = y1 < y2 ? 1 : -1; int e = dx / 2; int y = y1; int rs = m_rowSize / (1 << m_mipmapLevel); for (int x = x1; x <= x2; x++) { if (t) color->m_NativeValue->getData( (unsigned char*)m_pointer + x * rs + y * m_pixelSize, // set pixel to y,x m_format); else color->m_NativeValue->getData( (unsigned char*)m_pointer + y * rs + x * m_pixelSize, // set pixel to x,y m_format); e -= dy; if (e < 0) { y += sy; e += dx; } } } void TexturePainter::SetPixel(int x, int y, Color^ color) { LIME_ASSERT(Locked); LIME_ASSERT(LockMode == TextureLockMode::ReadWrite || LockMode == TextureLockMode::WriteOnly); LIME_ASSERT(x >= 0 && x < MipMapLevelWidth); LIME_ASSERT(y >= 0 && y < MipMapLevelHeight); LIME_ASSERT(color != nullptr); color->m_NativeValue->getData( (unsigned char*)m_pointer + y * (m_rowSize/(1 << m_mipmapLevel)) + x * m_pixelSize, m_format); } void TexturePainter::Unlock(bool alsoRegenerateMipMapLevels) { LIME_ASSERT(Locked); m_texture->m_Texture->unlock(); if (alsoRegenerateMipMapLevels) m_texture->m_Texture->regenerateMipMapLevels(); m_mipmapLevel = -1; m_mipmapLevelWidth = -1; m_mipmapLevelHeight = -1; m_pointer = nullptr; } void TexturePainter::Unlock() { LIME_ASSERT(Locked); m_texture->m_Texture->unlock(); m_mipmapLevel = -1; m_mipmapLevelWidth = -1; m_mipmapLevelHeight = -1; m_pointer = nullptr; } bool TexturePainter::Locked::get() { return m_mipmapLevel != -1; } TextureLockMode TexturePainter::LockMode::get() { LIME_ASSERT(Locked); return m_lockMode; } int TexturePainter::MipMapLevel::get() { LIME_ASSERT(Locked); return m_mipmapLevel; } int TexturePainter::MipMapLevelCount::get() { return m_mipmapLevelCount; } int TexturePainter::MipMapLevelHeight::get() { LIME_ASSERT(Locked); return m_mipmapLevelHeight; } System::IntPtr TexturePainter::MipMapLevelData::get() { LIME_ASSERT(Locked); return System::IntPtr(m_pointer); } int TexturePainter::MipMapLevelWidth::get() { LIME_ASSERT(Locked); return m_mipmapLevelWidth; } Video::Texture^ TexturePainter::Texture::get() { return m_texture; } String^ TexturePainter::ToString() { if (Locked) { return String::Format("TexturePainter: [Locked] <{0}> MipMap#{1}: {2}x{3}", m_lockMode, m_mipmapLevel, m_mipmapLevelWidth, m_mipmapLevelHeight); } else { return String::Format("TexturePainter: [Unlocked]"); } } } // end namespace Video } // end namespace IrrlichtLime
[ "greenyadzer@gmail.com" ]
greenyadzer@gmail.com
6da069648e0a670d28ba5b7233c9c786c3a44c2c
bf437a984f4176f99ff1a8c6a7f60a64259b2415
/src/ansa/linklayer/rbridge/TRILLInterfaceData.cc
af8871b27bbf45d32d7b7165dfd57172e3275957
[]
no_license
kvetak/ANSA
b8bcd25c9c04a09d5764177e7929f6d2de304e57
fa0f011b248eacf25f97987172d99b39663e44ce
refs/heads/ansainet-3.3.0
2021-04-09T16:36:26.173317
2017-02-16T12:43:17
2017-02-16T12:43:17
3,823,817
10
16
null
2017-02-16T12:43:17
2012-03-25T11:25:51
C++
UTF-8
C++
false
false
5,051
cc
// Copyright (C) 2013 Brno University of Technology (http://nes.fit.vutbr.cz/ansa) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // /** * @file TRILLInterfaceData.cc * @author Marcel Marek (mailto:xscrew02@gmail.com), Vladimir Vesely (mailto:ivesely@fit.vutbr.cz) * @date 24.3.2013 * @brief Represents TRILL related data on interface. * @detail Represents TRILL related data on interface. * @todo Z9 */ #include "TRILLInterfaceData.h" namespace inet { TRILLInterfaceData::TRILLInterfaceData() { // TODO Auto-generated constructor stub } TRILLInterfaceData::~TRILLInterfaceData() { // TODO Auto-generated destructor stub } void TRILLInterfaceData::setDefaults(void){ this->disabled = false; this->trunk = false; this->access = false; this->p2p = false; this->announcingSet.push_back(1); //TODO A2 FIX change to some configurable default VLAN this->enabledgSet.push_back(1); this->nonAdj = false; this->inhibitionInterval = 30; this->disLearning = false; this->vlanId = 1; this->inhibited = false; this->desigVLAN = 1; this->vlanMapping = false; } int TRILLInterfaceData::getVlanId() const { return vlanId; } bool TRILLInterfaceData::isAccess() const { return access; } bool TRILLInterfaceData::isDisLearning() const { return disLearning; } bool TRILLInterfaceData::isDisabled() const { return disabled; } bool TRILLInterfaceData::isP2p() const { return p2p; } bool TRILLInterfaceData::isTrunk() const { return trunk; } void TRILLInterfaceData::setAccess(bool access) { this->access = access; } void TRILLInterfaceData::setDisLearning(bool disLearning) { this->disLearning = disLearning; } void TRILLInterfaceData::setDisabled(bool disabled) { this->disabled = disabled; } void TRILLInterfaceData::setP2p(bool p2p) { this->p2p = p2p; } void TRILLInterfaceData::setTrunk(bool trunk) { this->trunk = trunk; } void TRILLInterfaceData::setVlanId(int vlanId) { this->vlanId = vlanId; } bool TRILLInterfaceData::isInhibited() const { return inhibited; } bool TRILLInterfaceData::isEnabled(int vlanId) { for(VLANVector::iterator it = this->enabledgSet.begin(); it != this->enabledgSet.end(); ++it){ if((*it) == vlanId){ return true; } } return false; } int TRILLInterfaceData::getDesigVlan() const { return desigVLAN; } bool TRILLInterfaceData::isVlanMapping() const { return vlanMapping; } int TRILLInterfaceData::getDesiredDesigVlan() const { return desiredDesigVLAN; } void TRILLInterfaceData::setDesiredDesigVlan(int desiredDesigVlan) { desiredDesigVLAN = desiredDesigVlan; } void TRILLInterfaceData::setVlanMapping(bool vlanMapping) { this->vlanMapping = vlanMapping; } void TRILLInterfaceData::setDesigVlan(int desigVlan) { desigVLAN = desigVlan; } void TRILLInterfaceData::setInhibited(bool inhibited) { this->inhibited = inhibited; } bool TRILLInterfaceData::isAppointedForwarder(int vlanId, TRILLNickname nickname){ //TODO A2 // if(nickname == 0){ // nickname = getNicknameOfThisRBridge(); // } std::map<int, TRILLNickname>::iterator it = this->appointedForwarder.find(vlanId); if(it != this->appointedForwarder.end()){ if((*it).second == nickname){ return true; } }else{ return false; } // for(VLANVector::iterator iter = appointedForwarder.begin(); iter != appointedForwarder.end(); ++iter){ // if(vlanId == (*iter)){ // return true; // } // } return false; } void TRILLInterfaceData::setAppointedForwarder(int vlanId, TRILLNickname nickname) { this->appointedForwarder.clear(); this->appointedForwarder.insert(std::make_pair(vlanId, nickname)); } void TRILLInterfaceData::addAppointedForwarder(int vlanId, TRILLNickname nickname) { this->appointedForwarder.insert(std::make_pair(vlanId, nickname)); } void TRILLInterfaceData::clearAppointedForwarder(){ this->appointedForwarder.clear(); } /* * TODO B2 To be determined if nickname has to match too. */ void TRILLInterfaceData::removeAppointedFowrwarder(int vlanId, TRILLNickname nickname) { std::map<int, TRILLNickname>::iterator it = this->appointedForwarder.find(vlanId); if(it != this->appointedForwarder.end()){ this->appointedForwarder.erase(it); }else{ // return false; } } }
[ "imarek@fit.vutbr.cz" ]
imarek@fit.vutbr.cz
948ff4530bc201733035f60cc4ac49ec57d811b0
6a5e4fee9dbbb5c0482c745acc2865c2cae19da7
/Generator BBS/RC4.cpp
053e8694af02d0f4ca5f1efcc756cb9157642485
[]
no_license
madragonse/Generator-BBS
3f8194238b0bff6c1db6df663a9db43b7df735db
78c52d509fb6c707f4d72101425303791251f786
refs/heads/master
2023-01-08T23:55:04.777150
2020-10-28T10:22:28
2020-10-28T10:22:28
307,963,089
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,193
cpp
#include "RC4.h" #include <xpolymorphic_allocator.h> RC4::RC4(uint8_t key[128], int key_length) { this->key_length = key_length; for (int i = 0; i < this->key_length; i++) this->key[i] = key[i]; } void RC4::generateKey() { for (int i = 0; i < 256; i++)//for i from 0 to 255 { this->S[i] = i; //S[i] : = i } long long j = 0; //j := 0 for (int i = 0; i < 256; i++) //for i from 0 to 255 { j = ((j + this->S[i] + this->key[i % this->key_length]) % 256); //j: = (j + S[i] + klucz[i mod długość_klucza]) mod 256 std::swap(S[i], S[j]); //zamień(S[i], S[j]) } } std::vector<uint8_t> RC4::generate(long long ile) { this->wynik = std::vector<uint8_t>(); int i = 0;//i: = 0 int j = 0;//j : = 0 for (int l = 0; l < ile; l++)//while TworzonyStrumieńSzyfrujący : { i = (i + 1) % 256;//i: = (i + 1) mod 256 j = (j + this->S[i]) % 256; //j : = (j + S[i]) mod 256 std::swap(this->S[i], this->S[j]);//zamień(S[i], S[j]) this->wynik.push_back(this->S[(this->S[i] + this->S[j]) % 256]);//wynik S[(S[i] + S[j]) mod 256] } return this->wynik; }
[ "48411094+madragonse@users.noreply.github.com" ]
48411094+madragonse@users.noreply.github.com
e6db2bb7150a374e88c52224fad12afa9c5e11fc
480e72d832d4218c28c6acf09948c303f06b0de2
/ThreadPool/src/TaskManager.cpp
beb40ccf9a809d3ba24d3b0bc02c41f5f803c52b
[]
no_license
a83376750/API
69ec6319dc90c16ff761136097485c58168003a5
6e8bfb7315ec6ec38b0062f0b91bd29113a31926
refs/heads/master
2020-08-02T17:48:52.206124
2017-01-13T11:01:28
2017-01-13T11:01:28
73,559,963
0
0
null
null
null
null
GB18030
C++
false
false
1,374
cpp
#include "..\inc\TaskManager.h" #include <iostream> namespace thread_pool_task { TaskManager::TaskManager() { } TaskManager::~TaskManager() { } void TaskManager::PushTask(Task *task) { std::lock_guard<std::mutex> lock{ mutex_task_ }; queue_task_.emplace(task); } thread_pool_task::Task* TaskManager::PopTask() { std::lock_guard<std::mutex> lock{ mutex_task_ }; if (queue_task_.empty()) return nullptr; Task *task = queue_task_.front(); queue_task_.pop(); return task; } size_t TaskManager::GetTaskCount() const { return queue_task_.size(); } void Json_Task::StartTask() { std::cout << "Json_Task_start!!!\n"; } FunctionManager::FunctionManager() { open_flag_ = true; } FunctionManager::~FunctionManager() { } thread_pool_task::FunctionManager::void_function FunctionManager::PopFunction() { std::unique_lock<std::mutex> lock{ mutex_function_ }; cv_function_.wait( lock, [this]() { return !queue_function_.empty() || !open_flag_; } ); if (!open_flag_) return nullptr; //这里不能使用NULL,编译时会 /*未能使函数模板“unknown-type std::invoke(_Callable &&,_Types &&...)”专用化*/ auto fun = std::move(queue_function_.front()); queue_function_.pop(); return fun; } void FunctionManager::CloseManager() { open_flag_ = false; cv_function_.notify_all(); } }
[ "394315001@qq.com" ]
394315001@qq.com
f721e0cd07532f25bad61c87e29a8126636c57ed
1afec3e10c24e43da24c77aa681e582e06f4e7d8
/cpp/myob/ob_fetched_log_buffer.cpp
42ad46f81521734d64b14bb3f8fcf084f11875e7
[]
no_license
jeffreywugz/code-repository
8ade372c334f9ce74ff927f5b9c4a8f4c7fe7deb
163ede173179309daa3b29a81f0e93ee51da0896
refs/heads/master
2020-04-20T13:13:06.606368
2014-07-18T06:56:15
2014-07-18T06:56:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,379
cpp
/** * (C) 2007-2010 Taobao Inc. * * This program 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. * * Version: $Id$ * * Authors: * yuanqi <yuanqi.xhf@taobao.com> * - some work details if you want */ #include "tbsys.h" #include "ob_prefetch_log_buffer.h" #include "ob_ups_log_utils.h" using namespace oceanbase::common; namespace oceanbase { namespace updateserver { ObPrefetchLogBuffer::ObPrefetchLogBuffer(): read_pos_(0) {} ObPrefetchLogBuffer::~ObPrefetchLogBuffer() {} int ObPrefetchLogBuffer::reset() { int err = OB_SUCCESS; int64_t next_end_pos = end_pos_; if (!is_inited()) { err = OB_NOT_INIT; } else if (__sync_bool_compare_and_swap(&next_end_pos_, next_end_pos, next_end_pos + 1)) { err = OB_EAGAIN; } else { read_pos_ = next_end_pos; end_pos_ = next_end_pos; } return err; } int ObPrefetchLogBuffer::get_log(const int64_t start_id, int64_t& end_id, char* buf, const int64_t len, int64_t& read_count) { int err = OB_SUCCESS; int64_t copy_count = 0; int64_t real_start_id = start_id; if (!is_inited()) { err = OB_NOT_INIT; } else if (NULL == buf || 0 >= len || 0 >= start_id) { err = OB_INVALID_ARGUMENT; } else if (OB_SUCCESS != (err = read(read_pos_, buf, len, copy_count))) { if (OB_EAGAIN != err) { TBSYS_LOG(ERROR, "log_buf_.append_log(pos, buf, len)=>%d", err); } } else if (OB_SUCCESS != (err = trim_log_buffer(buf, copy_count, read_count, real_start_id, end_id))) { err = OB_DISCONTINUOUS_LOG; TBSYS_LOG(WARN, "trim_log_buffer(buf=%p[%ld], start_id=%ld)=>%d", buf, copy_count, start_id); } else if (real_start_id != start_id) { err = OB_DISCONTINUOUS_LOG; } return err; } int ObPrefetchLogBuffer::append_log(const int64_t pos, char* buf, const int64_t len) { int err = OB_SUCCESS; bool granted = false; if (!is_inited()) { err = OB_NOT_INIT; } else if (NULL == buf || 0 > len) { err = OB_INVALID_ARGUMENT; TBSYS_LOG(ERROR, "append(buf=%p[%ld]): invalid argument", buf, len); } else if (len > buf_len_) { err = OB_BUF_NOT_ENOUGH; TBSYS_LOG(WARN, "append(len[%ld] > buf_len_[%ld])", len , buf_len_); } else if (pos != end_pos_ || !__sync_bool_compare_and_swap(&next_end_pos_, pos, pos + len)) { err = OB_EAGAIN; TBSYS_LOG(DEBUG, "append(pos=%ld, next_end_pos=%ld): another appender working.", pos, next_end_pos_); } else { granted = true; } if (OB_SUCCESS == err && OB_SUCCESS != (err = append(pos, buf, len))) { TBSYS_LOG(ERROR, "append(pos=%ld, buf=%p[%ld])=>%d", pos, buf, len, err); } if (granted && OB_SUCCESS != err && !__sync_bool_compare_and_swap(&next_end_pos_, pos+len, end_pos_)) { err = OB_ERR_UNEXPECTED; } return err; } }; // end namespace updateserver }; // end namespace oceanbase
[ "huafengxi@gmail.com" ]
huafengxi@gmail.com
854fb24464bf600d4b13dd3c0dc04bea586b7dff
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/CredentialStore/UNIX_CredentialStore_STUB.hxx
8e728b20eda86fa160505a803ebbf0c598a794d8
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
125
hxx
#ifdef PEGASUS_OS_STUB #ifndef __UNIX_CREDENTIALSTORE_PRIVATE_H #define __UNIX_CREDENTIALSTORE_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
3fdf0c6978512f41be56f7a8dc461ed3f77bedcd
b82136612e27642edaa6c635e5f8d966fffb0e14
/Toolbox/Math.h
5ae248ff7d73d07d73242605f279455d87786b00
[]
no_license
anehrkor/KappaTools
6426236826c034fc8cb1122b54a97f412d721de5
05998997eeeced041acad1bc5aeddb723453ee2d
refs/heads/master
2021-01-22T23:07:20.149241
2015-04-13T07:51:48
2015-04-13T07:51:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
804
h
#ifndef TBMATH_H #define TBMATH_H #include <string> #include <algorithm> #include <cmath> #ifndef M_PI static const double M_PI = 3.141592653589793238; #endif typedef std::pair<double, double> edouble; template <typename T> inline const int sgn(const T a) { return (a > T(0)) - (a < T(0)); } template<typename T> inline const T sqr(const T a) { return a * a; } template<typename T> inline const T min(const T a, const T b, const T c) { return std::min(std::min(a, b), c); } template<typename T> inline const T max(const T a, const T b, const T c) { return std::max(std::max(a, b), c); } double fround_p(double n, unsigned int d); double fround(double n, int p); edouble fround(edouble x); std::pair<std::string, std::string> sround(edouble x); std::string str(edouble x, int p = -1); #endif
[ "stober@cern.ch" ]
stober@cern.ch
79da8d69ab77bb72751404570c47212098937732
b16f99c5d6d36b82790c0960e38725b6a8b78e69
/Q12_Implement_strStr/Q12_Implement_strStr.cpp
6eca012aca4291004029f25c00a682fa1d9e14ba
[]
no_license
disha-surana/LeetCode
bf0a620f160286bdcad0b13ba339d6f58c228c46
2c4cbc46e6dad90fe3f4759748fd566fbf8106f6
refs/heads/master
2020-07-02T20:25:28.800119
2020-03-31T07:29:52
2020-03-31T07:29:52
201,654,655
0
0
null
null
null
null
UTF-8
C++
false
false
752
cpp
class Solution { public: int strStr(string haystack, string needle) { if(needle == "") return 0; else if(haystack.length() < needle.length()) return -1; int len = haystack.length()-needle.length()+1; for(int i=0; i< len; i++) { int j=0,k=i; while(j < needle.length()) { if(haystack[k]!=needle[j]){ break; } else{ k++; j++; } } if(j==needle.length()) return i; } return -1; } };
[ "dishasurana11@gmail.com" ]
dishasurana11@gmail.com
009a0c10081fea9c747008206881147ac2165174
2268f55ef77ce9c0064ab23f915d1ab3cf34d4c9
/Server/ServerDlg.h
a94ba9d23e247c4619be5b3cfbc4a673af0a6208
[]
no_license
JoyLeeA/CatchMind
fca81afa8e189c00c01c11e3a694d939b47fd473
786796c415e3a80af17fdc9b3bcb9720a2dee1b7
refs/heads/master
2022-03-29T23:03:47.742644
2020-01-09T15:47:32
2020-01-09T15:47:32
232,841,760
3
0
null
null
null
null
UHC
C++
false
false
2,322
h
// ServerDlg.h : 헤더 파일 // #pragma once #include "atltypes.h" #include "afxcolorbutton.h" #include "afxcmn.h" #include "afxwin.h" #include "atltime.h" #include "ScoreBoardDlg.h" // CServerDlg 대화 상자 class CServerDlg : public CDialogEx { // 생성입니다. public: CServerDlg(CWnd* pParent = NULL); // 표준 생성자입니다. // 대화 상자 데이터입니다. enum { IDD = IDD_SERVER_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. // 구현입니다. protected: HICON m_hIcon; // 생성된 메시지 맵 함수 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: clientsock* m_pChild; CIPAddressCtrl Serv_Addr; afx_msg void OnClickedButtonSend(); CString ServIP; afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); CPoint m_cpDraw; BOOL pen_flag; afx_msg void OnLButtonUp(UINT nFlags, CPoint point); COLORREF m_color; int m_Thickness; CSpinButtonCtrl m_ctrSpin; CMFCColorButton m_ColorButton; afx_msg void OnClickedLinecolor(); int m_LineThickness; afx_msg void OnDeltaposSpin(NMHDR *pNMHDR, LRESULT *pResult); virtual BOOL PreTranslateMessage(MSG* pMsg); int m_Mode; CString m_Question; CString m_Solution; afx_msg void OnBnClickedQuestionmode(); afx_msg void OnBnClickedSolutionmode(); afx_msg void OnBnClickedButtonQuestion(); afx_msg void OnBnClickedButtonAnswer(); int m_Score; CTime timer; CTime StartTime; CTime EndTime; afx_msg void OnTimer(UINT_PTR nIDEvent); CStatic m_Text; afx_msg void OnBnClickedButtonClear(); int a; void StopQuestion(void); CListBox m_list; void AllClear(void); int Start_X; int Start_Y; int End_X; int End_Y; int Draw_X; int Draw_Y; void DrawPicture(CPoint& ptStart, CPoint& ptEnd); CString Clear; void ScreenClear(void); char h; int n; afx_msg void OnBnClickedStartgame(); afx_msg void OnBnClickedOpenroom(); CString m_SID; CString ScoreS; int gameflag; CProgressCtrl m_GameTimebar; int myturn, gameturn, circle; CString RecieveID; CString UserID[5]; CString Score_STR[5]; int Score[5]; void FinishGame(); };
[ "59664050+JoyLeeA@users.noreply.github.com" ]
59664050+JoyLeeA@users.noreply.github.com
aae902b172f50b6f7659132b444e9162c3d4b178
fe7dfc6ff8f24881fe4097bc3f3005cfdf361962
/Plugin~/WebRTCPlugin/Codec/NvCodec/NvEncoderCudaWithCUarray.cpp
f974000821d878215415cf07d1904f098ed77df1
[ "Apache-2.0" ]
permissive
Unity-Technologies/com.unity.webrtc
b897e87a99b10bb616ca378c03a1cecad0894ed5
84718a6e2f76f8755f880f1bed043e3f438fc5e3
refs/heads/main
2023-09-04T05:34:17.116673
2023-09-01T03:14:25
2023-09-01T03:14:25
206,225,948
711
186
NOASSERTION
2023-09-13T00:52:53
2019-09-04T03:46:05
Assembly
UTF-8
C++
false
false
7,604
cpp
#include "pch.h" #include "NvEncoder/NvEncoder.h" #include "NvEncoder/NvEncoderCuda.h" #include "NvEncoderCudaWithCUarray.h" namespace unity { namespace webrtc { static CUresult CreateCUarray(CUarray* pDstArray, uint32_t width, uint32_t height, CUarray_format format, int numChannels) { CUDA_ARRAY3D_DESCRIPTOR arrayDesc = CUDA_ARRAY3D_DESCRIPTOR(); arrayDesc.Width = width; arrayDesc.Height = height; arrayDesc.Depth = 0; /* CUDA 2D arrays are defined to have depth 0 */ arrayDesc.Format = format; arrayDesc.NumChannels = static_cast<uint32_t>(numChannels); arrayDesc.Flags = CUDA_ARRAY3D_SURFACE_LDST; return cuArray3DCreate(pDstArray, &arrayDesc); } NvEncoderCudaWithCUarray::NvEncoderCudaWithCUarray( CUcontext cuContext, uint32_t nWidth, uint32_t nHeight, NV_ENC_BUFFER_FORMAT eBufferFormat, uint32_t nExtraOutputDelay, bool bMotionEstimationOnly, bool bOutputInVideoMemory) : NvEncoder( NV_ENC_DEVICE_TYPE_CUDA, cuContext, nWidth, nHeight, eBufferFormat, nExtraOutputDelay, bMotionEstimationOnly, bOutputInVideoMemory) , m_cuContext(cuContext) { if (!m_hEncoder) { NVENC_THROW_ERROR("Encoder Initialization failed", NV_ENC_ERR_INVALID_DEVICE); } if (!m_cuContext) { NVENC_THROW_ERROR("Invalid Cuda Context", NV_ENC_ERR_INVALID_DEVICE); } } NvEncoderCudaWithCUarray::~NvEncoderCudaWithCUarray() { ReleaseCudaResources(); } void NvEncoderCudaWithCUarray::AllocateInputBuffers(int32_t numInputBuffers) { if (!IsHWEncoderInitialized()) { NVENC_THROW_ERROR("Encoder intialization failed", NV_ENC_ERR_ENCODER_NOT_INITIALIZED); } // for MEOnly mode we need to allocate seperate set of buffers for reference frame int numCount = m_bMotionEstimationOnly ? 2 : 1; for (int count = 0; count < numCount; count++) { CUDA_DRVAPI_CALL(cuCtxPushCurrent(m_cuContext)); std::vector<void*> inputFrames; for (int i = 0; i < numInputBuffers; i++) { CUarray frame; CUDA_DRVAPI_CALL( CreateCUarray(&frame, GetMaxEncodeWidth(), GetMaxEncodeHeight(), CU_AD_FORMAT_UNSIGNED_INT32, 1)); inputFrames.push_back(static_cast<void*>(frame)); } CUDA_DRVAPI_CALL(cuCtxPopCurrent(NULL)); int encodeWidth = static_cast<int>(GetMaxEncodeWidth()); int encodeHeight = static_cast<int>(GetMaxEncodeHeight()); int widthInBytes = static_cast<int>(GetWidthInBytes(GetPixelFormat(), GetMaxEncodeWidth())); RegisterInputResources( inputFrames, NV_ENC_INPUT_RESOURCE_TYPE_CUDAARRAY, encodeWidth, encodeHeight, widthInBytes, GetPixelFormat(), (count == 1) ? true : false); } } void NvEncoderCudaWithCUarray::ReleaseInputBuffers() { ReleaseCudaResources(); } void NvEncoderCudaWithCUarray::ReleaseCudaResources() { if (!m_hEncoder) { return; } if (!m_cuContext) { return; } UnregisterInputResources(); cuCtxPushCurrent(m_cuContext); for (uint32_t i = 0; i < m_vInputFrames.size(); ++i) { if (m_vInputFrames[i].inputPtr) { cuMemFree(reinterpret_cast<CUdeviceptr>(m_vInputFrames[i].inputPtr)); } } m_vInputFrames.clear(); for (uint32_t i = 0; i < m_vReferenceFrames.size(); ++i) { if (m_vReferenceFrames[i].inputPtr) { cuMemFree(reinterpret_cast<CUdeviceptr>(m_vReferenceFrames[i].inputPtr)); } } m_vReferenceFrames.clear(); cuCtxPopCurrent(nullptr); m_cuContext = nullptr; } void NvEncoderCudaWithCUarray::CopyToDeviceFrame( CUcontext device, void* pSrcArray, uint32_t nSrcPitch, CUarray pDstArray, uint32_t dstPitch, int width, int height, CUmemorytype srcMemoryType, NV_ENC_BUFFER_FORMAT pixelFormat, const uint32_t dstChromaOffsets[], uint32_t numChromaPlanes, bool bUnAlignedDeviceCopy, CUstream stream) { if (srcMemoryType != CU_MEMORYTYPE_HOST && srcMemoryType != CU_MEMORYTYPE_ARRAY) { NVENC_THROW_ERROR("Invalid source memory type for copy", NV_ENC_ERR_INVALID_PARAM); } CUDA_DRVAPI_CALL(cuCtxPushCurrent(device)); uint32_t srcPitch = nSrcPitch ? nSrcPitch : NvEncoder::GetWidthInBytes(pixelFormat, static_cast<uint32_t>(width)); CUDA_MEMCPY2D m = CUDA_MEMCPY2D(); m.srcMemoryType = srcMemoryType; if (srcMemoryType == CU_MEMORYTYPE_HOST) { m.srcHost = pSrcArray; } else { m.srcArray = static_cast<CUarray>(pSrcArray); } m.srcPitch = srcPitch; m.dstMemoryType = CU_MEMORYTYPE_ARRAY; m.dstArray = pDstArray; m.dstPitch = dstPitch; m.WidthInBytes = NvEncoder::GetWidthInBytes(pixelFormat, static_cast<uint32_t>(width)); m.Height = static_cast<size_t>(height); if (bUnAlignedDeviceCopy && srcMemoryType == CU_MEMORYTYPE_ARRAY) { CUDA_DRVAPI_CALL(cuMemcpy2DUnaligned(&m)); } else { CUDA_DRVAPI_CALL(stream == NULL ? cuMemcpy2D(&m) : cuMemcpy2DAsync(&m, stream)); } std::vector<uint32_t> srcChromaOffsets; NvEncoder::GetChromaSubPlaneOffsets(pixelFormat, srcPitch, static_cast<uint32_t>(height), srcChromaOffsets); uint32_t chromaHeight = NvEncoder::GetChromaHeight(pixelFormat, static_cast<uint32_t>(height)); uint32_t destChromaPitch = NvEncoder::GetChromaPitch(pixelFormat, dstPitch); uint32_t srcChromaPitch = NvEncoder::GetChromaPitch(pixelFormat, srcPitch); uint32_t chromaWidthInBytes = NvEncoder::GetChromaWidthInBytes(pixelFormat, static_cast<uint32_t>(width)); for (uint32_t i = 0; i < numChromaPlanes; ++i) { if (chromaHeight) { if (srcMemoryType == CU_MEMORYTYPE_HOST) { m.srcHost = (static_cast<uint8_t*>(pSrcArray) + srcChromaOffsets[i]); } else { m.srcArray = (CUarray)(static_cast<uint8_t*>(pSrcArray) + srcChromaOffsets[i]); } m.srcPitch = srcChromaPitch; m.dstArray = (CUarray)((uint8_t*)pDstArray + dstChromaOffsets[i]); m.dstPitch = destChromaPitch; m.WidthInBytes = chromaWidthInBytes; m.Height = chromaHeight; if (bUnAlignedDeviceCopy && srcMemoryType == CU_MEMORYTYPE_ARRAY) { CUDA_DRVAPI_CALL(cuMemcpy2DUnaligned(&m)); } else { CUDA_DRVAPI_CALL(stream == NULL ? cuMemcpy2D(&m) : cuMemcpy2DAsync(&m, stream)); } } } CUDA_DRVAPI_CALL(cuCtxPopCurrent(NULL)); } } // end namespace webrtc } // end namespace unity
[ "noreply@github.com" ]
Unity-Technologies.noreply@github.com
baf27cc686174b5daa3b7bb6e9fc648cd7fa5592
e4b417e613476bc24df93980ca7e4159cbba53ba
/OpenGL/src/Render/IndexBuffer.h
5975e61f362ddb68f1d1db4e403f38a1ec146249
[]
no_license
mnursey/VoxelEngine
6f48f472877c853aaea0b53d841051628fc4170b
6a527382fb1a15ba537f319ce6ec26d6c89003af
refs/heads/master
2020-03-26T15:35:07.207887
2018-09-29T10:17:34
2018-09-29T10:17:34
145,051,997
0
0
null
null
null
null
UTF-8
C++
false
false
275
h
#pragma once class IndexBuffer { private: unsigned int m_RendererID; unsigned int m_Count; public: IndexBuffer(const unsigned int* data, int count); ~IndexBuffer(); void Bind() const; void Unbind() const; inline unsigned int GetCount() const { return m_Count; } };
[ "mitchnursey@gmail.com" ]
mitchnursey@gmail.com
fd650efc9b9518707a6d00f4243ae06614cce2bf
24f6b87096237a191ddbb2def6893499cf6e79ff
/DrugTraceability/InfoSearch.cpp
d80ca45cc255baf7c326327feba4c13e25380a5f
[]
no_license
maoxiangyu1/DrugTraceability
c6879a0c4d176bd33e2b421a6705aff994a6ce22
61c675848b2c4c5cff4d07dd9a3638331cf1e859
refs/heads/master
2020-04-14T22:54:42.470421
2019-04-11T08:31:45
2019-04-11T08:31:45
164,183,089
2
0
null
null
null
null
GB18030
C++
false
false
19,202
cpp
// InfoSearch.cpp : 实现文件 // #include "stdafx.h" #include "DrugTraceability.h" #include "InfoSearch.h" #include "afxdialogex.h" // CInfoSearch 对话框 IMPLEMENT_DYNAMIC(CInfoSearch, CDialogEx) CInfoSearch::CInfoSearch(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_INFOSEARCH_DIALOG, pParent) , m_type(_T("")) , m_key(_T("")) { #ifndef _WIN32_WCE EnableActiveAccessibility(); #endif EnableAutomation(); } CInfoSearch::~CInfoSearch() { } void CInfoSearch::OnFinalRelease() { // 释放了对自动化对象的最后一个引用后,将调用 // OnFinalRelease。 基类将自动 // 删除该对象。 在调用该基类之前,请添加您的 // 对象所需的附加清理代码。 CDialogEx::OnFinalRelease(); } void CInfoSearch::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_COMBO1, com); DDX_Control(pDX, IDC_LIST1, m_listPerson); DDX_CBString(pDX, IDC_COMBO1, m_type); DDX_Text(pDX, IDC_EDIT2, m_key); } BEGIN_MESSAGE_MAP(CInfoSearch, CDialogEx) ON_WM_DESTROY() ON_BN_CLICKED(IDDEL, &CInfoSearch::OnBnClickedDel) ON_BN_CLICKED(IDSEARCH, &CInfoSearch::OnBnClickedSearch) ON_BN_CLICKED(IDCHANGE, &CInfoSearch::OnBnClickedChange) END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(CInfoSearch, CDialogEx) END_DISPATCH_MAP() // 注意: 我们添加 IID_IInfoSearch 支持 // 以支持来自 VBA 的类型安全绑定。 此 IID 必须同附加到 .IDL 文件中的 // 调度接口的 GUID 匹配。 // {4814F9AB-6A8B-47FA-98E8-C5D6350CAB88} static const IID IID_IInfoSearch = { 0x4814F9AB, 0x6A8B, 0x47FA, { 0x98, 0xE8, 0xC5, 0xD6, 0x35, 0xC, 0xAB, 0x88 } }; BEGIN_INTERFACE_MAP(CInfoSearch, CDialogEx) INTERFACE_PART(CInfoSearch, IID_IInfoSearch, Dispatch) END_INTERFACE_MAP() // CInfoSearch 消息处理程序 BOOL CInfoSearch::OnInitDialog() { CDialogEx::OnInitDialog(); HICON m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化 CString s; CString strsql; s = "File Name=linkDB.udl"; pDB = new CADODatabase; pRs = new CADORecordset(pDB); if (!pDB->Open(s)) { AfxMessageBox("数据库链接失败!单击退出!"); this->EndDialog(0); return TRUE; } m_listPerson.ModifyStyle(0L, LVS_REPORT); m_listPerson.ModifyStyle(LVS_SHOWSELALWAYS, 0L); m_listPerson.ModifyStyle(0L, LVS_SHOWSELALWAYS); //高亮显示被选中项 m_listPerson.SetExtendedStyle(LVS_EX_FULLROWSELECT | //允许整行选中 LVS_EX_HEADERDRAGDROP | //允许整列拖动 LVS_EX_GRIDLINES | //画出网格线 LVS_EX_ONECLICKACTIVATE | //单击选中项 LVS_EX_FLATSB); //扁平风格显示滚动条 if (type == 1) { //==== SetWindowText("公司查询"); com.AddString("公司编号"); com.AddString("公司名称"); com.AddString("公司地址"); com.AddString("公司负责人"); com.AddString("公司类型"); com.AddString("公司简述"); com.AddString("公司电话"); //=== m_listPerson.InsertColumn(0, "公司编号", LVCFMT_LEFT, 130, 0); m_listPerson.InsertColumn(1, "公司名称", LVCFMT_LEFT, 130, 1); m_listPerson.InsertColumn(2, "公司地址", LVCFMT_LEFT, 130, 2); m_listPerson.InsertColumn(3, "公司负责人", LVCFMT_LEFT, 130, 3); m_listPerson.InsertColumn(4, "公司类别", LVCFMT_LEFT, 130, 4); m_listPerson.InsertColumn(5, "公司简介", LVCFMT_LEFT, 130, 5); m_listPerson.InsertColumn(6, "公司电话", LVCFMT_LEFT, 130, 6); m_listPerson.InsertColumn(7, "注册时间", LVCFMT_LEFT, 130, 7); m_listPerson.InsertColumn(8, "注册时长(月)", LVCFMT_LEFT, 130, 8); strsql.Format("SELECT * FROM Firm"); pRs->Open(_bstr_t(strsql), 1); } if (type == 2) { //=== SetWindowText("药品查询"); com.AddString("药品编号"); com.AddString("药品名称"); com.AddString("药品成份"); com.AddString("药品效用"); com.AddString("药品简述"); //=== m_listPerson.InsertColumn(0, "药品编号", LVCFMT_LEFT, 130, 0); m_listPerson.InsertColumn(1, "药品名称", LVCFMT_LEFT, 130, 1); m_listPerson.InsertColumn(2, "药品成分", LVCFMT_LEFT, 130, 2); m_listPerson.InsertColumn(3, "药品效用", LVCFMT_LEFT, 130, 3); m_listPerson.InsertColumn(4, "注册时间", LVCFMT_LEFT, 130, 4); m_listPerson.InsertColumn(5, "药品简介", LVCFMT_LEFT, 130, 5); m_listPerson.InsertColumn(6, "有效时长(月)", LVCFMT_LEFT, 130, 6); strsql.Format("SELECT * FROM Drug"); pRs->Open(_bstr_t(strsql), 1); } if (type == 3) { if (degree == 0) { //=== SetWindowText("药品流通查询"); com.AddString("流通编号"); com.AddString("公司编号"); com.AddString("公司名称"); com.AddString("药品编号"); com.AddString("药品名称"); //=== m_listPerson.InsertColumn(0, "流通编号", LVCFMT_LEFT, 130, 0); m_listPerson.InsertColumn(1, "公司编号", LVCFMT_LEFT, 130, 1); m_listPerson.InsertColumn(2, "公司名称", LVCFMT_LEFT, 130, 2); m_listPerson.InsertColumn(3, "药品编号", LVCFMT_LEFT, 130, 3); m_listPerson.InsertColumn(4, "药品名称", LVCFMT_LEFT, 130, 4); m_listPerson.InsertColumn(5, "流通数量", LVCFMT_LEFT, 130, 5); m_listPerson.InsertColumn(6, "流通时间", LVCFMT_LEFT, 130, 6); strsql.Format("SELECT * FROM view_1"); pRs->Open(_bstr_t(strsql), 1); } if (degree == 1) { HID = m_p->m_main->HID; //=== SetWindowText("生产记录查询"); com.AddString("流通编号"); com.AddString("药品编号"); com.AddString("药品名称"); //=== m_listPerson.InsertColumn(0, "流通编号", LVCFMT_LEFT, 130, 0); m_listPerson.InsertColumn(1, "药品编号", LVCFMT_LEFT, 130, 1); m_listPerson.InsertColumn(2, "药品名称", LVCFMT_LEFT, 130, 2); m_listPerson.InsertColumn(3, "流通数量", LVCFMT_LEFT, 130, 3); m_listPerson.InsertColumn(4, "流通时间", LVCFMT_LEFT, 130, 4); strsql.Format("SELECT CID,DID,DName,CNum,PTime FROM view_1 where FID = '%s'",m_p->m_main->HID); pRs->Open(_bstr_t(strsql), 1); } if (degree == 2) { HID = m_t->m_main->HID; //=== SetWindowText("中转记录查询"); com.AddString("流通编号"); com.AddString("药品编号"); com.AddString("药品名称"); //=== m_listPerson.InsertColumn(0, "流通编号", LVCFMT_LEFT, 130, 0); m_listPerson.InsertColumn(1, "药品编号", LVCFMT_LEFT, 130, 1); m_listPerson.InsertColumn(2, "药品名称", LVCFMT_LEFT, 130, 2); m_listPerson.InsertColumn(3, "流通数量", LVCFMT_LEFT, 130, 3); m_listPerson.InsertColumn(4, "流通时间", LVCFMT_LEFT, 130, 4); strsql.Format("SELECT CID,DID,DName,CNum,PTime FROM view_1 where FID = '%s'", m_t->m_main->HID); pRs->Open(_bstr_t(strsql), 1); } if (degree == 3) { HID = m_d->m_main->HID; //=== SetWindowText("出售记录查询"); com.AddString("流通编号"); com.AddString("药品编号"); com.AddString("药品名称"); //=== m_listPerson.InsertColumn(0, "流通编号", LVCFMT_LEFT, 130, 0); m_listPerson.InsertColumn(1, "药品编号", LVCFMT_LEFT, 130, 1); m_listPerson.InsertColumn(2, "药品名称", LVCFMT_LEFT, 130, 2); m_listPerson.InsertColumn(3, "流通数量", LVCFMT_LEFT, 130, 3); m_listPerson.InsertColumn(4, "流通时间", LVCFMT_LEFT, 130, 4); strsql.Format("SELECT CID,DID,DName,CNum,PTime FROM view_1 where FID = '%s'", m_d->m_main->HID); pRs->Open(_bstr_t(strsql), 1); } } if (!pRs->GetRecordCount()) { m_listPerson.DeleteAllItems(); return TRUE; } pRs->Open(_bstr_t(strsql), 1); RefreshList(*pRs); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } void CInfoSearch::OnDestroy() { CDialogEx::OnDestroy(); pRs->Close(); pDB->Close(); free(pRs); free(pDB); // TODO: 在此处添加消息处理程序代码 } BOOL CInfoSearch::RefreshList(CADORecordset& recordset) { if (type == 1) { m_listPerson.DeleteAllItems(); if (!recordset.IsOpen()) return FALSE; recordset.MoveFirst(); CString FID, FName, FLeader, Faddress, FTel, FInfo, FRegTime, FType, deadline; int indexofList = 0; while (!(recordset.IsEOF())) { recordset.GetFieldValue("FID", FID); recordset.GetFieldValue("FName", FName); recordset.GetFieldValue("FAddress", Faddress); recordset.GetFieldValue("FLeader", FLeader); recordset.GetFieldValue("FType", FType); recordset.GetFieldValue("FInfo", FInfo); recordset.GetFieldValue("FTel", FTel); recordset.GetFieldValue("FRegisterTime", FRegTime); recordset.GetFieldValue("FDeadline", deadline); m_listPerson.InsertItem(indexofList, FID); m_listPerson.SetItemText(indexofList, 1, FName); m_listPerson.SetItemText(indexofList, 2, Faddress); m_listPerson.SetItemText(indexofList, 3, FLeader); m_listPerson.SetItemText(indexofList, 4, FType); m_listPerson.SetItemText(indexofList, 5, FInfo); m_listPerson.SetItemText(indexofList, 6, FTel); m_listPerson.SetItemText(indexofList, 7, FRegTime); m_listPerson.SetItemText(indexofList, 8, deadline); indexofList += 1; recordset.MoveNext(); } recordset.MoveFirst(); return TRUE; } if (type == 2) { m_listPerson.DeleteAllItems(); if (!recordset.IsOpen()) return FALSE; recordset.MoveFirst(); CString DID, DName, DComponent, DEffect, DRegisterTime, DInfo,DDeadline; int indexofList = 0; while (!(recordset.IsEOF())) { recordset.GetFieldValue("DID", DID); recordset.GetFieldValue("DName", DName); recordset.GetFieldValue("DComponent", DComponent); recordset.GetFieldValue("DEffect", DEffect); recordset.GetFieldValue("DRegisterTime", DRegisterTime); recordset.GetFieldValue("DInfo", DInfo); recordset.GetFieldValue("DDeadline", DDeadline); m_listPerson.InsertItem(indexofList, DID); m_listPerson.SetItemText(indexofList, 1, DName); m_listPerson.SetItemText(indexofList, 2, DComponent); m_listPerson.SetItemText(indexofList, 3, DEffect); m_listPerson.SetItemText(indexofList, 4, DRegisterTime); m_listPerson.SetItemText(indexofList, 5, DInfo); m_listPerson.SetItemText(indexofList, 6, DDeadline); indexofList += 1; recordset.MoveNext(); } recordset.MoveFirst(); return TRUE; } if (type == 3) { if (degree == 0) { m_listPerson.DeleteAllItems(); if (!recordset.IsOpen()) return FALSE; recordset.MoveFirst(); CString CID,FID, FName, DID, DName, CNum, PTime; int indexofList = 0; while (!(recordset.IsEOF())) { recordset.GetFieldValue("CID", CID); recordset.GetFieldValue("FID", FID); recordset.GetFieldValue("FName", FName); recordset.GetFieldValue("DID", DID); recordset.GetFieldValue("DName", DName); recordset.GetFieldValue("CNum", CNum); recordset.GetFieldValue("PTime", PTime); m_listPerson.InsertItem(indexofList, CID); m_listPerson.SetItemText(indexofList, 1, FID); m_listPerson.SetItemText(indexofList, 2, FName); m_listPerson.SetItemText(indexofList, 3, DID); m_listPerson.SetItemText(indexofList, 4, DName); m_listPerson.SetItemText(indexofList, 5, CNum); m_listPerson.SetItemText(indexofList, 6, PTime); indexofList += 1; recordset.MoveNext(); } recordset.MoveFirst(); return TRUE; } else { m_listPerson.DeleteAllItems(); if (!recordset.IsOpen()) return FALSE; recordset.MoveFirst(); CString CID,DID, DName, CNum, PTime; int indexofList = 0; while (!(recordset.IsEOF())) { recordset.GetFieldValue("CID", CID); recordset.GetFieldValue("DID", DID); recordset.GetFieldValue("DName", DName); recordset.GetFieldValue("CNum", CNum); recordset.GetFieldValue("PTime", PTime); m_listPerson.InsertItem(indexofList, CID); m_listPerson.SetItemText(indexofList, 1, DID); m_listPerson.SetItemText(indexofList, 2, DName); m_listPerson.SetItemText(indexofList, 3, CNum); m_listPerson.SetItemText(indexofList, 4, PTime); indexofList += 1; recordset.MoveNext(); } recordset.MoveFirst(); return TRUE; } } } void CInfoSearch::OnBnClickedDel() { if (type == 1) { POSITION pos = m_listPerson.GetFirstSelectedItemPosition(); int nItem = m_listPerson.GetNextSelectedItem(pos); CString s = m_listPerson.GetItemText(nItem, 0); if (s == "") { AfxMessageBox("请选中您要删除的信息!"); return; } CString S; S.Format("delete Firm where FID='%s'", s); if (pDB->Execute(S) == TRUE) { m_listPerson.DeleteItem(nItem); AfxMessageBox("删除公司信息成功!"); return; } else { AfxMessageBox("删除公司信息失败!"); return; } } if (type == 2) { POSITION pos = m_listPerson.GetFirstSelectedItemPosition(); int nItem = m_listPerson.GetNextSelectedItem(pos); CString s = m_listPerson.GetItemText(nItem, 0); if (s == "") { AfxMessageBox("请选中您要删除的信息!"); return; } CString S; S.Format("delete Drug where DID='%s'", s); if (pDB->Execute(S) == TRUE) { m_listPerson.DeleteItem(nItem); AfxMessageBox("删除药品信息成功!"); return; } else { AfxMessageBox("删除药品信息失败!"); return; } } if (type == 3) { if (degree == 0) { POSITION pos = m_listPerson.GetFirstSelectedItemPosition(); int nItem = m_listPerson.GetNextSelectedItem(pos); CString s1 = m_listPerson.GetItemText(nItem, 0); CString s2 = m_listPerson.GetItemText(nItem, 1); CString s3 = m_listPerson.GetItemText(nItem, 3); CString s4 = m_listPerson.GetItemText(nItem, 6); if (s1 == "" || s2 == ""|| s3 == "" || s4 == "") { AfxMessageBox("请选中您要删除的信息!"); return; } CString S; S.Format("delete Currency where CID = '%s' and FID = '%s' and DID = '%s' and PTime = '%s'",s1,s2,s3,s4 ); if (pDB->Execute(S) == TRUE) { m_listPerson.DeleteItem(nItem); AfxMessageBox("删除信息成功!"); return; } else { AfxMessageBox("删除信息失败!"); return; } } else { POSITION pos = m_listPerson.GetFirstSelectedItemPosition(); int nItem = m_listPerson.GetNextSelectedItem(pos); CString s1 = m_listPerson.GetItemText(nItem, 0); CString s2 = m_listPerson.GetItemText(nItem, 1); CString s3 = m_listPerson.GetItemText(nItem, 4); if (s1 == "" || s2 == "" || s3 == "" ) { AfxMessageBox("请选中您要删除的信息!"); return; } CString S; S.Format("delete Currency where CID='%s' and FID = '%s' and DID = '%s' and PTime = '%s'", s1,HID,s2,s3); if (pDB->Execute(S) == TRUE) { m_listPerson.DeleteItem(nItem); AfxMessageBox("删除信息成功!"); return; } else { AfxMessageBox("删除信息失败!"); return; } } } // TODO: 在此添加控件通知处理程序代码 } void CInfoSearch::OnBnClickedSearch() { UpdateData(TRUE); CString strsql; if (type == 1) { if (m_key == "") { strsql.Format("SELECT * FROM Firm"); pRs->Open(_bstr_t(strsql), 1); if (!pRs->GetRecordCount()) { m_listPerson.DeleteAllItems(); return; } pRs->Open(_bstr_t(strsql), 1); RefreshList(*(pRs)); return; } if (m_type == "") { AfxMessageBox("请选择查询类型!"); return; } if (m_type == "公司编号") { strsql = "select * from Firm where FID like '%" + m_key + "%'"; } if (m_type == "公司名称") { strsql = "select * from Firm where FName like '%" + m_key + "%'"; } if (m_type == "公司地址") { strsql = "select * from Firm where FAddress like '%" + m_key + "%'"; } if (m_type == "公司负责人") { strsql = "select * from Firm where FLeader like '%" + m_key + "%'"; } if (m_type == "公司类型") { strsql = "select * from Firm where FType like '%" + m_key + "%'"; } if (m_type == "公司简述") { strsql = "select * from Firm where FInfo like '%" + m_key + "%'"; } if (m_type == "公司电话") { strsql = "select * from Firm where FTel like '%" + m_key + "%'"; } } if (type == 2) { if (m_key == "") { strsql.Format("SELECT * FROM Drug"); pRs->Open(_bstr_t(strsql), 1); if (!pRs->GetRecordCount()) { m_listPerson.DeleteAllItems(); return; } pRs->Open(_bstr_t(strsql), 1); RefreshList(*(pRs)); return; } if (m_type == "") { AfxMessageBox("请选择查询类型!"); return; } if (m_type == "药品编号") { strsql = "select * from Drug where DID like '%" + m_key + "%'"; } if (m_type == "药品名称") { strsql = "select * from Drug where DName like '%" + m_key + "%'"; } if (m_type == "药品成份") { strsql = "select * from Drug where DComponent like '%" + m_key + "%'"; } if (m_type == "药品效用") { strsql = "select * from Drug where DEffect like '%" + m_key + "%'"; } if (m_type == "药品简述") { strsql = "select * from Drug where DInfo like '%" + m_key + "%'"; } } if (type == 3) { if (degree == 0) { if (m_key == "") { strsql.Format("SELECT * FROM view_1"); pRs->Open(_bstr_t(strsql), 1); if (!pRs->GetRecordCount()) { m_listPerson.DeleteAllItems(); return; } pRs->Open(_bstr_t(strsql), 1); RefreshList(*(pRs)); return; } if (m_type == "") { AfxMessageBox("请选择查询类型!"); return; } if (m_type == "药品编号") { strsql = "select * from view_1 where DID like '%" + m_key + "%'"; } if (m_type == "药品名称") { strsql = "select * from view_1 where DName like '%" + m_key + "%'"; } if (m_type == "公司编号") { strsql = "select * from view_1 where FID like '%" + m_key + "%'"; } if (m_type == "公司名称") { strsql = "select * from view_1 where FName like '%" + m_key + "%'"; } if (m_type == "流通编号") { strsql = "select * from view_1 where CID like '%" + m_key + "%'"; } } else { if (m_key == "") { strsql.Format("SELECT * FROM view_1 where FID = '%s'",HID); pRs->Open(_bstr_t(strsql), 1); if (!pRs->GetRecordCount()) { m_listPerson.DeleteAllItems(); return; } pRs->Open(_bstr_t(strsql), 1); RefreshList(*(pRs)); return; } if (m_type == "") { AfxMessageBox("请选择查询类型!"); return; } if (m_type == "药品编号") { strsql = "select CID,DID,DName,CNum,PTime from view_1 where DID like '%" + m_key + "%' and FID = '" + HID + "'"; } if (m_type == "药品名称") { strsql = "select CID,DID,DName,CNum,PTime from view_1 where DName like '%" + m_key + "%' and FID = '" + HID + "'"; } if (m_type == "流通编号") { strsql = "select CID,DID,DName,CNum,PTime from view_1 where CID like '%" + m_key + "%' and FID = '" + HID + "'"; } } } pRs->Open(_bstr_t(strsql), 1); if (!pRs->GetRecordCount()) { m_listPerson.DeleteAllItems(); return; } pRs->Open(_bstr_t(strsql), 1); RefreshList(*(pRs)); // TODO: 在此添加控件通知处理程序代码 } void CInfoSearch::OnBnClickedChange() { AfxMessageBox("刷新成功!"); // TODO: 在此添加控件通知处理程序代码 }
[ "1838123571@qq.com" ]
1838123571@qq.com
621161e8e52cc4fab715d73024d5985f4ea0c541
5abc5a5b4d6c72b33bd28543da802daf2123e7ba
/RecastDemo/Include/InputGeom.h
d2b440ec486fc8c155d965b54b29fb9cfd603ec1
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
suyangman/recast
484687784b01f658498e28d899353b87af726bab
7028c09638b2086b40a90a6cc9620009a455f6b3
refs/heads/master
2022-12-06T19:15:38.587904
2020-08-21T11:27:55
2020-08-21T11:27:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,592
h
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #ifndef INPUTGEOM_H #define INPUTGEOM_H #include "ChunkyTriMesh.h" #include "MeshLoaderObj.h" #include "BufferStream.h" #include "ImportScene.h" static const int MAX_CONVEXVOL_PTS = 12; struct ConvexVolume { float verts[MAX_CONVEXVOL_PTS*3]; float hmin, hmax; int nverts; int area; }; struct BuildSettings { // Cell size in world units float cellSize; // Cell height in world units float cellHeight; // Agent height in world units float agentHeight; // Agent radius in world units float agentRadius; // Agent max climb in world units float agentMaxClimb; // Agent max slope in degrees float agentMaxSlope; // Region minimum size in voxels. // regionMinSize = sqrt(regionMinArea) float regionMinSize; // Region merge size in voxels. // regionMergeSize = sqrt(regionMergeArea) float regionMergeSize; // Edge max length in world units float edgeMaxLen; // Edge max error in voxels float edgeMaxError; float vertsPerPoly; // Detail sample distance in voxels float detailSampleDist; // Detail sample max error in voxel heights. float detailSampleMaxError; // Partition type, see SamplePartitionType int partitionType; // Bounds of the area to mesh float navMeshBMin[3]; float navMeshBMax[3]; // Size of the tiles in voxels float tileSize; }; class InputGeom { rcChunkyTriMesh* m_chunkyMesh; rcMeshLoaderObj* m_mesh; float m_meshBMin[3], m_meshBMax[3]; BuildSettings m_buildSettings; bool m_hasBuildSettings; /// @name Off-Mesh connections. ///@{ static const int MAX_OFFMESH_CONNECTIONS = 256; float m_offMeshConVerts[MAX_OFFMESH_CONNECTIONS*3*2]; float m_offMeshConRads[MAX_OFFMESH_CONNECTIONS]; unsigned char m_offMeshConDirs[MAX_OFFMESH_CONNECTIONS]; unsigned char m_offMeshConAreas[MAX_OFFMESH_CONNECTIONS]; unsigned short m_offMeshConFlags[MAX_OFFMESH_CONNECTIONS]; unsigned int m_offMeshConId[MAX_OFFMESH_CONNECTIONS]; int m_offMeshConCount; ///@} /// @name Convex Volumes. ///@{ static const int MAX_VOLUMES = 256; ConvexVolume m_volumes[MAX_VOLUMES]; int m_volumeCount; ///@} /// ImportScene m_vImportScene; bool loadMesh(class rcContext* ctx, const std::string& filepath); bool loadGeomSet(class rcContext* ctx, const std::string& filepath); bool loadBinInfo(class rcContext* ctx, const std::string& filepath); void LoadMeshFormat(BufferStream& stream); void LoadTerrainFormat(BufferStream& stream); public: InputGeom(); ~InputGeom(); bool load(class rcContext* ctx, const std::string& filepath); bool saveGeomSet(const BuildSettings* settings); /// Method to return static mesh data. const rcMeshLoaderObj* getMesh() const { return m_mesh; } const float* getMeshBoundsMin() const { return m_meshBMin; } const float* getMeshBoundsMax() const { return m_meshBMax; } const float* getNavMeshBoundsMin() const { return m_hasBuildSettings ? m_buildSettings.navMeshBMin : m_meshBMin; } const float* getNavMeshBoundsMax() const { return m_hasBuildSettings ? m_buildSettings.navMeshBMax : m_meshBMax; } const rcChunkyTriMesh* getChunkyMesh() const { return m_chunkyMesh; } const BuildSettings* getBuildSettings() const { return m_hasBuildSettings ? &m_buildSettings : 0; } bool raycastMesh(float* src, float* dst, float& tmin); /// @name Off-Mesh connections. ///@{ int getOffMeshConnectionCount() const { return m_offMeshConCount; } const float* getOffMeshConnectionVerts() const { return m_offMeshConVerts; } const float* getOffMeshConnectionRads() const { return m_offMeshConRads; } const unsigned char* getOffMeshConnectionDirs() const { return m_offMeshConDirs; } const unsigned char* getOffMeshConnectionAreas() const { return m_offMeshConAreas; } const unsigned short* getOffMeshConnectionFlags() const { return m_offMeshConFlags; } const unsigned int* getOffMeshConnectionId() const { return m_offMeshConId; } void addOffMeshConnection(const float* spos, const float* epos, const float rad, unsigned char bidir, unsigned char area, unsigned short flags); void deleteOffMeshConnection(int i); void drawOffMeshConnections(struct duDebugDraw* dd, bool hilight = false); ///@} /// @name Box Volumes. ///@{ int getConvexVolumeCount() const { return m_volumeCount; } const ConvexVolume* getConvexVolumes() const { return m_volumes; } void addConvexVolume(const float* verts, const int nverts, const float minh, const float maxh, unsigned char area); void deleteConvexVolume(int i); void drawConvexVolumes(struct duDebugDraw* dd, bool hilight = false); ///@} private: // Explicitly disabled copy constructor and copy assignment operator. InputGeom(const InputGeom&); InputGeom& operator=(const InputGeom&); }; #endif // INPUTGEOM_H
[ "suyang575547919@qq.com" ]
suyang575547919@qq.com
5d3bc90a4682ea189fa4538d8d77049414eb57b6
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/new_hunk_3891.cpp
7838a31e5c98eebd1f22e1d367701e1d6b8e8b44
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
assert(pd); const char *host = pd->host.termedBuf(); storeAppendPrintf(e, "\npeer digest from %s\n", host); cacheDigestGuessStatsReport(&pd->stats.guess, e, host);
[ "993273596@qq.com" ]
993273596@qq.com
f4e6a7b25ae5a36473531e1556567b35d522dccf
a30feb4bc5daa8218d4b6add22f92e71dc3776ea
/Lab3/inc/list.hh
bc73d791c6bbfddd156ba43b97d770a259838520
[]
no_license
218731/PAMSI-sort
07185c8a9fd32be582cfd5bbea78c8b3c2c1ff5d
595a8a5772f98309a68fc6ef2c12d19b6913ff72
refs/heads/master
2020-12-26T09:05:45.123717
2016-04-13T20:41:37
2016-04-13T20:41:37
55,774,108
0
0
null
null
null
null
UTF-8
C++
false
false
1,808
hh
#ifndef LIST_HH #define LIST_HH #include "tab.hh" /* Klasa implementuj±ca listê */ template <class T> class List { private: Tablica <T> *lista; public: void add (T element, int position); // throws outOfRangeException; void remove (int position); T get (int position); int size (); List(); ~List(); class outOfRangeException{}; int search (T element); }; template<class T> List<T>::List() { lista = new Tablica <T>; } template<class T>List<T>::~List() { delete[] lista; } template<class T> void List<T>::add (T element, int position) { try{ if (position < 1 || position > lista->rozmiar()) { throw outOfRangeException(); } lista->dodaj(element, position); } catch (outOfRangeException) { std::cout <<"Wyjście poza zakres listy w czasie dodawania" << std::endl; } } template<class T>void List<T>::remove (int position) { try{ if (position < 1 || position > lista->rozmiar()) { throw outOfRangeException(); } lista->usun(position); } catch (outOfRangeException) { std::cout <<"Wyjście poza zakres listy w czasie usuwania" << std::endl; } } template<class T>T List<T>::get (int position) { try{ if (position < 1 || position > lista->rozmiar()) { throw outOfRangeException(); } return lista->wyswietl(position); } catch (outOfRangeException) { std::cout <<"Wyjście poza zakres listy w czasie wyswietlania" << std::endl; } } template<class T> int List<T>::size () { return lista->rozmiar(); } template<class T> int List<T>::search (T element) { int position; for (int a=0; a<lista->rozmiar(); a++) { T checker = get(a); if (element==checker){ position=a+1; } } if (position>0) { return position; } else return 0; } #endif
[ "218731@student.pwr.edu.pl" ]
218731@student.pwr.edu.pl
43275e47142f99b01b274a77734fd7a25feac3d8
f1404c11700326a29ce2d6149006e7b752726560
/src/walletdb.cpp
ca1a716e040b43bdb8854d2a17f770465bdc59ef
[ "MIT" ]
permissive
futurecash/futurecash
407baf028509d329876a722cb60dd9b162bbec80
0030225172a15efdb146c3b7d1e897782f540246
refs/heads/master
2021-01-18T14:13:42.609431
2015-08-15T20:13:58
2015-08-15T20:13:58
40,563,382
0
1
null
null
null
null
UTF-8
C++
false
false
27,352
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletdb.h" #include "base58.h" #include "protocol.h" #include "serialize.h" #include "sync.h" #include "wallet.h" #include <boost/filesystem.hpp> #include <boost/foreach.hpp> using namespace std; using namespace boost; static uint64_t nAccountingEntryNumber = 0; extern bool fWalletUnlockStakingOnly; // // CWalletDB // bool CWalletDB::WriteName(const string& strAddress, const string& strName) { nWalletDBUpdated++; return Write(make_pair(string("name"), strAddress), strName); } bool CWalletDB::EraseName(const string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; return Erase(make_pair(string("name"), strAddress)); } bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx) { nWalletDBUpdated++; return Write(std::make_pair(std::string("tx"), hash), wtx); } bool CWalletDB::EraseTx(uint256 hash) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("tx"), hash)); } bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta) { nWalletDBUpdated++; if (!Write(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta, false)) return false; // hash pubkey/privkey to accelerate wallet load std::vector<unsigned char> vchKey; vchKey.reserve(vchPubKey.size() + vchPrivKey.size()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end()); return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false); } bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta) { const bool fEraseUnencryptedKey = true; nWalletDBUpdated++; if (!Write(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta)) return false; if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false)) return false; if (fEraseUnencryptedKey) { Erase(std::make_pair(std::string("key"), vchPubKey)); Erase(std::make_pair(std::string("wkey"), vchPubKey)); } return true; } bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey) { nWalletDBUpdated++; return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true); } bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript) { nWalletDBUpdated++; return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false); } bool CWalletDB::WriteBestBlock(const CBlockLocator& locator) { nWalletDBUpdated++; return Write(std::string("bestblock"), locator); } bool CWalletDB::ReadBestBlock(CBlockLocator& locator) { return Read(std::string("bestblock"), locator); } bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext) { nWalletDBUpdated++; return Write(std::string("orderposnext"), nOrderPosNext); } bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey) { nWalletDBUpdated++; return Write(std::string("defaultkey"), vchPubKey); } bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool) { return Read(std::make_pair(std::string("pool"), nPool), keypool); } bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool) { nWalletDBUpdated++; return Write(std::make_pair(std::string("pool"), nPool), keypool); } bool CWalletDB::ErasePool(int64_t nPool) { nWalletDBUpdated++; return Erase(std::make_pair(std::string("pool"), nPool)); } bool CWalletDB::WriteMinVersion(int nVersion) { return Write(std::string("minversion"), nVersion); } bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) { account.SetNull(); return Read(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) { return Write(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) { return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry); } bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry) { return WriteAccountingEntry(++nAccountingEntryNumber, acentry); } int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount) { list<CAccountingEntry> entries; ListAccountCreditDebit(strAccount, entries); int64_t nCreditDebit = 0; BOOST_FOREACH (const CAccountingEntry& entry, entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; } void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); } DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) { LOCK(pwallet->cs_wallet); // Old wallets didn't have any defined order for transactions // Probably a bad idea to change the output of this // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64_t, TxPair > TxItems; TxItems txByTime; for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; ListAccountCreditDebit("", acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } int64_t& nOrderPosNext = pwallet->nOrderPosNext; nOrderPosNext = 0; std::vector<int64_t> nOrderPosOffsets; for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) { CWalletTx *const pwtx = (*it).second.first; CAccountingEntry *const pacentry = (*it).second.second; int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos; if (nOrderPos == -1) { nOrderPos = nOrderPosNext++; nOrderPosOffsets.push_back(nOrderPos); if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } else { int64_t nOrderPosOff = 0; BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets) { if (nOrderPos >= nOffsetStart) ++nOrderPosOff; } nOrderPos += nOrderPosOff; nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1); if (!nOrderPosOff) continue; // Since we're changing the order, write it back if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } } WriteOrderPosNext(nOrderPosNext); return DB_LOAD_OK; } class CWalletScanState { public: unsigned int nKeys; unsigned int nCKeys; unsigned int nKeyMeta; bool fIsEncrypted; bool fAnyUnordered; int nFileVersion; vector<uint256> vWalletUpgrade; CWalletScanState() { nKeys = nCKeys = nKeyMeta = 0; fIsEncrypted = false; fAnyUnordered = false; nFileVersion = 0; } }; bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState &wss, string& strType, string& strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other ssKey >> strType; if (strType == "name") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()]; } else if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx& wtx = pwallet->mapWallet[hash]; ssValue >> wtx; if (wtx.CheckTransaction() && (wtx.GetHash() == hash)) wtx.BindWallet(pwallet); else { pwallet->mapWallet.erase(hash); return false; } // Undo serialize changes in 31600 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) { if (!ssValue.empty()) { char fTmp; char fUnused; ssValue >> fTmp >> fUnused >> wtx.strFromAccount; strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString()); wtx.fTimeReceivedIsTxTime = fTmp; } else { strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString()); wtx.fTimeReceivedIsTxTime = 0; } wss.vWalletUpgrade.push_back(hash); } if (wtx.nOrderPos == -1) wss.fAnyUnordered = true; //// debug print //LogPrintf("LoadWallet %s\n", wtx.GetHash().ToString()); //LogPrintf(" %12d %s %s %s\n", // wtx.vout[0].nValue, // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()), // wtx.hashBlock.ToString(), // wtx.mapValue["message"]); } else if (strType == "acentry") { string strAccount; ssKey >> strAccount; uint64_t nNumber; ssKey >> nNumber; if (nNumber > nAccountingEntryNumber) nAccountingEntryNumber = nNumber; if (!wss.fAnyUnordered) { CAccountingEntry acentry; ssValue >> acentry; if (acentry.nOrderPos == -1) wss.fAnyUnordered = true; } } else if (strType == "key" || strType == "wkey") { CPubKey vchPubKey; ssKey >> vchPubKey; if (!vchPubKey.IsValid()) { strErr = "Error reading wallet database: CPubKey corrupt"; return false; } CKey key; CPrivKey pkey; uint256 hash = 0; if (strType == "key") { wss.nKeys++; ssValue >> pkey; } else { CWalletKey wkey; ssValue >> wkey; pkey = wkey.vchPrivKey; } // Old wallets store keys as "key" [pubkey] => [privkey] // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key // using EC operations as a checksum. // Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while // remaining backwards-compatible. try { ssValue >> hash; } catch(...){} bool fSkipCheck = false; if (hash != 0) { // hash pubkey/privkey to accelerate wallet load std::vector<unsigned char> vchKey; vchKey.reserve(vchPubKey.size() + pkey.size()); vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end()); vchKey.insert(vchKey.end(), pkey.begin(), pkey.end()); if (Hash(vchKey.begin(), vchKey.end()) != hash) { strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt"; return false; } fSkipCheck = true; } if (!key.Load(pkey, vchPubKey, fSkipCheck)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (!pwallet->LoadKey(key, vchPubKey)) { strErr = "Error reading wallet database: LoadKey failed"; return false; } } else if (strType == "mkey") { unsigned int nID; ssKey >> nID; CMasterKey kMasterKey; ssValue >> kMasterKey; if(pwallet->mapMasterKeys.count(nID) != 0) { strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID); return false; } pwallet->mapMasterKeys[nID] = kMasterKey; if (pwallet->nMasterKeyMaxID < nID) pwallet->nMasterKeyMaxID = nID; } else if (strType == "ckey") { wss.nCKeys++; vector<unsigned char> vchPubKey; ssKey >> vchPubKey; vector<unsigned char> vchPrivKey; ssValue >> vchPrivKey; if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) { strErr = "Error reading wallet database: LoadCryptedKey failed"; return false; } wss.fIsEncrypted = true; } else if (strType == "keymeta") { CPubKey vchPubKey; ssKey >> vchPubKey; CKeyMetadata keyMeta; ssValue >> keyMeta; wss.nKeyMeta++; pwallet->LoadKeyMetadata(vchPubKey, keyMeta); // find earliest key creation time, as wallet birthday if (!pwallet->nTimeFirstKey || (keyMeta.nCreateTime < pwallet->nTimeFirstKey)) pwallet->nTimeFirstKey = keyMeta.nCreateTime; } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; } else if (strType == "pool") { int64_t nIndex; ssKey >> nIndex; CKeyPool keypool; ssValue >> keypool; pwallet->setKeyPool.insert(nIndex); // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (pwallet->mapKeyMetadata.count(keyid) == 0) pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } else if (strType == "version") { ssValue >> wss.nFileVersion; if (wss.nFileVersion == 10300) wss.nFileVersion = 300; } else if (strType == "cscript") { uint160 hash; ssKey >> hash; CScript script; ssValue >> script; if (!pwallet->LoadCScript(script)) { strErr = "Error reading wallet database: LoadCScript failed"; return false; } } else if (strType == "orderposnext") { ssValue >> pwallet->nOrderPosNext; } } catch (...) { return false; } return true; } static bool IsKeyType(string strType) { return (strType== "key" || strType == "wkey" || strType == "mkey" || strType == "ckey"); } DBErrors CWalletDB::LoadWallet(CWallet* pwallet) { pwallet->vchDefaultKey = CPubKey(); CWalletScanState wss; bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string)"minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { LogPrintf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { LogPrintf("Error reading next record from wallet database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strType, strErr; if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: if (IsKeyType(strType)) result = DB_CORRUPT; else { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. if (strType == "tx") // Rescan if there is a bad transaction record: SoftSetBoolArg("-rescan", true); } } if (!strErr.empty()) LogPrintf("%s\n", strErr); } pcursor->close(); } catch (boost::thread_interrupted) { throw; } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; LogPrintf("nFileVersion = %d\n", wss.nFileVersion); LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n", wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys); // nTimeFirstKey is only reliable if all keys have metadata if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta) pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value' BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000)) return DB_NEED_REWRITE; if (wss.nFileVersion < CLIENT_VERSION) // Update WriteVersion(CLIENT_VERSION); if (wss.fAnyUnordered) result = ReorderTransactions(pwallet); return result; } void ThreadFlushWalletDB(const string& strFile) { // Make this thread recognisable as the wallet flushing thread RenameThread("futurecash-wallet"); static bool fOneThread; if (fOneThread) return; fOneThread = true; if (!GetBoolArg("-flushwallet", true)) return; unsigned int nLastSeen = nWalletDBUpdated; unsigned int nLastFlushed = nWalletDBUpdated; int64_t nLastWalletUpdate = GetTime(); while (true) { MilliSleep(500); if (nLastSeen != nWalletDBUpdated) { nLastSeen = nWalletDBUpdated; nLastWalletUpdate = GetTime(); } if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) { TRY_LOCK(bitdb.cs_db,lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; map<string, int>::iterator mi = bitdb.mapFileUseCount.begin(); while (mi != bitdb.mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; } if (nRefCount == 0) { boost::this_thread::interruption_point(); map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile); if (mi != bitdb.mapFileUseCount.end()) { LogPrint("db", "Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; int64_t nStart = GetTimeMillis(); // Flush wallet.dat so it's self contained bitdb.CloseDb(strFile); bitdb.CheckpointLSN(strFile); bitdb.mapFileUseCount.erase(mi++); LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart); } } } } } } bool BackupWallet(const CWallet& wallet, const string& strDest) { if (!wallet.fFileBacked) return false; while (true) { { LOCK(bitdb.cs_db); if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0) { // Flush log data to the dat file bitdb.CloseDb(wallet.strWalletFile); bitdb.CheckpointLSN(wallet.strWalletFile); bitdb.mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; filesystem::path pathDest(strDest); if (filesystem::is_directory(pathDest)) pathDest /= wallet.strWalletFile; try { #if BOOST_VERSION >= 104000 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists); #else filesystem::copy_file(pathSrc, pathDest); #endif LogPrintf("copied wallet.dat to %s\n", pathDest.string()); return true; } catch(const filesystem::filesystem_error &e) { LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what()); return false; } } } MilliSleep(100); } return false; } // // Try to (very carefully!) recover wallet.dat if there is a problem. // bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) { // Recovery procedure: // move wallet.dat to wallet.timestamp.bak // Call Salvage with fAggressive=true to // get as much data as possible. // Rewrite salvaged data to wallet.dat // Set -rescan so any missing transactions will be // found. int64_t now = GetTime(); std::string newFilename = strprintf("wallet.%d.bak", now); int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL, newFilename.c_str(), DB_AUTO_COMMIT); if (result == 0) LogPrintf("Renamed %s to %s\n", filename, newFilename); else { LogPrintf("Failed to rename %s to %s\n", filename, newFilename); return false; } std::vector<CDBEnv::KeyValPair> salvagedData; bool allOK = dbenv.Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename); return false; } LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size()); bool fSuccess = allOK; Db* pdbCopy = new Db(&dbenv.dbenv, 0); int ret = pdbCopy->open(NULL, // Txn pointer filename.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { LogPrintf("Cannot create database file %s\n", filename); return false; } CWallet dummyWallet; CWalletScanState wss; DbTxn* ptxn = dbenv.TxnBegin(); BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData) { if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); string strType, strErr; bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, wss, strType, strErr); if (!IsKeyType(strType)) continue; if (!fReadOK) { LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr); continue; } } Dbt datKey(&row.first[0], row.first.size()); Dbt datValue(&row.second[0], row.second.size()); int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } ptxn->commit(0); pdbCopy->close(0); delete pdbCopy; return fSuccess; } bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename) { return CWalletDB::Recover(dbenv, filename, false); }
[ "futurecash@safe-mail.net" ]
futurecash@safe-mail.net
bd45713dba702e2bc4bb3c4b06f562d019e4a00c
f17a88ddef74abe099a0c9d9d9aa91b90075959c
/Code/AbstractEngine/Gfx/GfxVertexBuffer.h
e4336a246a48d18735f3f583aba385cd61f6b70a
[ "MIT", "Apache-2.0" ]
permissive
NathanSaidas/LiteForgeMirror
bf4b0feb9702b590b510f98f32a3cc1d472f9bb0
dcb7f690378dd0abe0d1dc3e2783510ce9462fde
refs/heads/master
2022-06-12T11:55:06.321048
2022-05-30T04:37:59
2022-05-30T04:37:59
184,840,363
0
0
null
null
null
null
UTF-8
C++
false
false
3,313
h
// ******************************************************************** // Copyright (c) 2021 Nathan Hanlan // // 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. // ******************************************************************** #pragma once #include "Core/Memory/MemoryBuffer.h" #include "Core/Utility/APIResult.h" #include "AbstractEngine/Gfx/GfxTypes.h" #include "AbstractEngine/Gfx/GfxResourceObject.h" namespace lf { // Usage: // GfxVertexBuffer buffer; // buffer.SetUsage( ... ); // buffer.SetVertices( ... ); class LF_ABSTRACT_ENGINE_API GfxVertexBuffer : public GfxResourceObject { DECLARE_CLASS(GfxVertexBuffer, GfxResourceObject); public: GfxVertexBuffer(); ~GfxVertexBuffer() override; void SetUsage(Gfx::BufferUsage value); Gfx::BufferUsage GetUsage() const { return mUsage; } SizeT GetStride() const { return mStride; } SizeT GetNumElements() const { return mNumElements; } template<typename VertexT> APIResult<bool> SetVertices(const TVector<VertexT>& vertices) { MemoryBuffer buffer(vertices.data(), vertices.size() * sizeof(VertexT), MemoryBuffer::STATIC); buffer.SetSize(vertices.size() * sizeof(VertexT)); return SetVertices(buffer, sizeof(VertexT), vertices.size()); } template<typename VertexT, SizeT StackSize> APIResult<bool> SetVertices(const TStackVector<VertexT, StackSize>& vertices) { MemoryBuffer buffer(vertices.data(), vertices.size() * sizeof(VertexT), MemoryBuffer::STATIC); buffer.SetSize(vertices.size() * sizeof(VertexT)); return SetVertices(buffer, sizeof(VertexT), vertices.size()); } virtual APIResult<bool> SetVertices(const MemoryBuffer& vertices, SizeT stride, SizeT numElements) = 0; virtual APIResult<bool> SetVertices(MemoryBuffer&& vertices, SizeT stride, SizeT numElements) = 0; bool IsGPUReady() const { return AtomicLoad(&mGPUReady) != 0; } protected: void SetStride(SizeT value) { mStride = value; } void SetNumElements(SizeT value) { mNumElements = value; } void SetGPUReady(bool value) { AtomicStore(&mGPUReady, value ? 1 : 0); } private: volatile Atomic32 mGPUReady; Gfx::BufferUsage mUsage; SizeT mStride; SizeT mNumElements; }; } // namespace lf
[ "nathanhanlan@gmail.com" ]
nathanhanlan@gmail.com
83ff9698cbb0fc0403ccc3a3755b01d8e46e6133
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/agc008/A/2244665.cpp
8d059e7d219fd1f135dedd50b54fa2b6057a738b
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,229
cpp
#include <iostream> #include <string> #define INC(i, a, b) for(i = a; i < b; ++i) #define DEC(i, a, b) for(i = a; i > b; --i) #define REP(i, n) INC(i, 0, n) typedef unsigned int uint; typedef unsigned long ul; typedef long long ll; typedef unsigned long long ull; int abs(int x){ return x > 0? x : -x; } int max(int a, int b){ return a > b? a : b; } int min(int a, int b){ return a < b? a : b; } void TFprint(bool b, std::string T, std::string F){ if(b){ std::cout << T; }else{ std::cout << F; } } long calc(long init, long goal){ long ret; if((init >= 0 && goal >= 0)|| (init < 0 && goal < 0)){ if(init > goal){ ret = init - goal + 2; if(goal == 0){ ret--; } }else{ ret = goal - init; } }else{ ret = abs(init + goal) + 1; if(goal == 0){ ret--; } } return ret; } int main(){ long init, goal; std::cin >> init >> goal; //std::cout << init << ' ' << goal << std::endl; long ans = calc(init, goal); std::cout << std::dec << ans << std::endl; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
24eef44578c57cd3b5f3960937d6d433a42240bf
08bfc8a1f8e44adc624d1f1c6250a3d9635f99de
/SDKs/Alembic/lib/Bootstrap/TrivialBoostUsageUtil/Tests/main.cpp
2a7180e9f95a3da68b54bcb06e5f7b0072ae28d2
[]
no_license
Personwithhat/CE_SDKs
cd998a2181fcbc9e3de8c58c7cc7b2156ca21d02
7afbd2f7767c9c5e95912a1af42b37c24d57f0d4
refs/heads/master
2020-04-09T22:14:56.917176
2019-07-04T00:19:11
2019-07-04T00:19:11
160,623,495
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
version https://git-lfs.github.com/spec/v1 oid sha256:50f02f548dda609d337ac033d0abc8be7a80cf6e5d927655f7625d2c63b94c50 size 3822
[ "personwithhats2@Gmail.com" ]
personwithhats2@Gmail.com
d59b33fd46bca3266081eb252a318ddbd6d277f2
22dc9c7aa6cebaabc6c6cfac8640b0a75e39877c
/exercise 3/Sketch.cpp
35c62cbb832a4b81a67928c666d8d671e2e7a5d3
[]
no_license
Embedded-Software-kurssi/pusanen
6e18589e7a42fbd370b0280369cfa11dcb8b1615
4e51690d572512c9e21156b98326dcbc78a828e0
refs/heads/master
2021-01-12T14:43:32.871631
2016-12-07T20:08:05
2016-12-07T20:08:05
72,071,235
0
0
null
null
null
null
UTF-8
C++
false
false
697
cpp
 #include <Arduino.h> #include "farenheit.h" #include "morse.h" #include "SOS.h" void assigmentSix(); void setup() { pinMode(13, OUTPUT); } void loop(){ showText("SOS"); assigmentSix(); BlinkThreeDots(); BlinkThreeDashes(); BlinkThreeDots(); } void assigmentSix() { // Is Volatile because compiler otherwise optimizes variable away because it is not in use. // Thus makeing debuging impossiple. volatile float lampotila; lampotila=toFarenheit (1); lampotila=toFarenheit (5.0); lampotila=toFarenheit (10); lampotila=toFarenheit (25); volatile float temperature; temperature=toCelsius (1); temperature=toCelsius (5); temperature=toCelsius (10); temperature=toCelsius (25); }
[ "eikuulu@sulle.t" ]
eikuulu@sulle.t
98db07b832adbd1da38e0ac967d1dbfb11a6d4e2
ff0d2bfae27de7792ecb4b5a1c2c0b4b74b01de8
/Searching and Sorting/bubble_sort.cpp
329cf31e2faaeeb5f46858ed5ef6b7a3ea101e0e
[]
no_license
RachnaShriwas/Algorithm-Programs
6a9a7343c1d5d83b5b12f6ae85045b21bdbe4321
e108d91c29caca6065b6b96035b5289894049044
refs/heads/master
2021-08-19T03:52:29.996134
2017-11-24T16:45:04
2017-11-24T16:45:04
106,584,138
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
//bubble sort #include<iostream> using namespace std; void bubble_sort(int a[], int n) { for(int i = n-1; i >= 0; i--) { for(int j = 0; j < i; j++) { if(a[j] > a[j+1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } for(int k = 0; k < n; k++) cout<<a[k]<<" "; cout<<endl; } } int main() { //worst case int arr[] = {10,9,8,7,6,5,4,3,2,1}; cout<<"\nUnsorted array:\n"; for(int i = 0; i < sizeof(arr)/sizeof(int); i++) cout<<arr[i]<<" "; cout<<endl; cout<<"Sorting\n"; bubble_sort(arr, sizeof(arr)/sizeof(int)); cout<<"\nSorted array:\n"; for(int i = 0; i < sizeof(arr)/sizeof(int); i++) cout<<arr[i]<<" "; cout<<"\n\n"; //average case int b[] = {3,1,4,5,2,6,0,8,10}; cout<<"\nUnsorted array:\n"; for(int i = 0; i < sizeof(b)/sizeof(int); i++) cout<<b[i]<<" "; cout<<endl; cout<<"Sorting\n"; bubble_sort(b, sizeof(b)/sizeof(int)); cout<<"\nSorted array:\n"; for(int i = 0; i < sizeof(b)/sizeof(int); i++) cout<<b[i]<<" "; return 0; }
[ "rachnashriwas@gmail.com" ]
rachnashriwas@gmail.com
adec20c092fc96c89ab92c49b69c315e1ef8235d
5d3f49bfbb5c2cbf5b594753a40284559568ebfd
/implement/oglplus/enums/texture_filter_def.ipp
9d89c86363a2841c29d0c6be55d516e26f8ba6e0
[ "BSL-1.0" ]
permissive
highfidelity/oglplus
f28e41c20e2776b8bd9c0a87758fb6b9395ff649
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
refs/heads/develop
2021-01-16T18:57:37.366227
2015-04-08T18:35:37
2015-04-08T18:54:19
33,630,979
2
8
null
2015-04-08T20:38:33
2015-04-08T20:38:32
null
UTF-8
C++
false
false
1,352
ipp
// File implement/oglplus/enums/texture_filter_def.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/texture_filter.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2015 Matus Chochlik. // 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 // #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif #if defined GL_NEAREST # if OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Nearest # pragma push_macro("Nearest") # undef Nearest OGLPLUS_ENUM_CLASS_VALUE(Nearest, GL_NEAREST) # pragma pop_macro("Nearest") # else OGLPLUS_ENUM_CLASS_VALUE(Nearest, GL_NEAREST) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_LINEAR # if OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Linear # pragma push_macro("Linear") # undef Linear OGLPLUS_ENUM_CLASS_VALUE(Linear, GL_LINEAR) # pragma pop_macro("Linear") # else OGLPLUS_ENUM_CLASS_VALUE(Linear, GL_LINEAR) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif
[ "chochlik@gmail.com" ]
chochlik@gmail.com
2dadfc1badcbde28cc8a47d9d1f1954dc79613a4
7344512e9a37b194e5654f86cb15d600fcd95c45
/Genetic.h
f489db2d772e940d2649501f7dfa3d187a6bb141
[ "MIT" ]
permissive
alekseyl1992/Genetic2048
89369ca5852bc2cadceac79a7f915c1d90e40a4d
730b435d584189f1befefddd1b8c0025c18cb488
refs/heads/master
2020-04-06T05:00:13.660061
2015-05-05T21:03:07
2015-05-05T21:03:07
34,798,215
0
0
null
null
null
null
UTF-8
C++
false
false
1,134
h
#ifndef TETRIS_GENETIC_H #define TETRIS_GENETIC_H #include <vector> #include <boost/circular_buffer.hpp> #include "Game2048.h" #include "Chromosome.h" using GeneticRow = std::vector<int>; using GeneticField = std::vector<GeneticRow>; using Pool = std::vector<Chromosome>; class Genetic { public: Genetic(int populationSize = 20, double mutationProbability = 1./50.); movDir activate(const Game2048::Board& board); void init(); void step(int score); void newGeneration(); void newGeneration2(); GeneticField createGeneticField(const Game2048::Board& board); void printGeneticField(GeneticField &geneticField); std::vector<double> geneticFieldToInput(const GeneticField& field); int getCurrentChromosomeId() const; Pool getPopulation() const; void mutateCurrent(); private: int populationSize; std::vector<int> nnSizes; size_t chromosomeSize; double mutationProbability; Pool pool; int currentChromosomeId; static constexpr int historySize = 10; boost::circular_buffer<double> buttonsHistory; int maxScores = 0; }; #endif //TETRIS_GENETIC_H
[ "alekseyl@list.ru" ]
alekseyl@list.ru
6eb709a57296804a905d87e1a14f85071a9dcffa
bed6b9c57ead54dfa0f04b9a730bf1fd13ee83df
/BFSMarsTraveller.cpp
ba4d955c36bbdf34632c23205701196f50adb8c5
[]
no_license
alexander-jh/GoalBasedAgent
14e91a2c98a817e2eda2eead5f77f79a5473329b
3193b7510680c1310f796b34bd45a9ff67ddb856
refs/heads/master
2023-01-07T16:54:08.142128
2020-11-08T21:48:41
2020-11-08T21:48:41
311,119,505
0
0
null
null
null
null
UTF-8
C++
false
false
902
cpp
/* BFSMarsTraveller.cpp * * Main implementation for the BFS agent. * Testing framework is Catch, which is a header based testing * framework. * * Author: Alex Hoke * Date: 10/22/2020 * C++ Version: C++11 * Compiler: GNU G++ */ #include "MarsTraveller.hpp" int main(int argv, char **args) { // Get file destination const char *file = *(args + 3); // Get starting position char *start = *(args + 2); // Verify proper arguements were received if(file == nullptr) { fprintf(stderr,"Error: no valid file, exiting\n"); exit(1); } else if(start == nullptr) { fprintf(stderr,"Error: no valid starting position, exiting\n"); exit(1); } // Instantiate BFS class BFSMarsTraveller bfs = BFSMarsTraveller(file, start); // Run class bool status = bfs.run_rover(); bfs.rover_report(status); return 0; }
[ "alexander.j.hoke@gmail.com" ]
alexander.j.hoke@gmail.com
b33fa5230a25ca3942edc1c427d5d075e0a20b23
a47f2343c7b33772af650eb70583d6bb52811858
/day22/solution.cpp
4772ac488a5bd72ba4c391c5cdca0d2a7ef9984f
[ "MIT" ]
permissive
qwoprocks/Advent-of-Code-2020-Solutions
aee8b7a7db9996ff618ea8c9e824471599e1c289
65d96f89af013585ac994b8556d003b6455b0de1
refs/heads/main
2023-02-11T17:08:27.686818
2021-01-10T17:10:35
2021-01-10T17:10:35
321,987,967
0
0
null
null
null
null
UTF-8
C++
false
false
3,005
cpp
/* Link to problem: https://adventofcode.com/2020/day/22 */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <set> #include <deque> using namespace std; int part1(deque<int> player1, deque<int> player2) { while (player1.size() != 0 && player2.size() != 0) { int c1 = player1.front(); int c2 = player2.front(); player1.pop_front(); player2.pop_front(); if (c1 > c2) { player1.push_back(c1); player1.push_back(c2); } else { player2.push_back(c2); player2.push_back(c1); } } deque<int> *winning_player = player1.size() != 0 ? &player1 : &player2; int result = 0; int i = winning_player->size(); for (auto p = winning_player->begin(); p != winning_player->end(); ++p) { result += i * (*p); --i; } return result; } bool recursive_game(deque<int> &player1, deque<int> &player2) { set<vector<deque<int>>> past_rounds; while (player1.size() != 0 && player2.size() != 0) { vector<deque<int>> curr_round = {player1, player2}; if (past_rounds.find(curr_round) != past_rounds.end()) { return true; } past_rounds.insert(curr_round); int c1 = player1.front(); int c2 = player2.front(); player1.pop_front(); player2.pop_front(); if (player1.size() >= c1 && player2.size() >= c2) { deque<int> new_player1(player1.begin(), player1.begin() + c1); deque<int> new_player2(player2.begin(), player2.begin() + c2); if (recursive_game(new_player1, new_player2)) { player1.push_back(c1); player1.push_back(c2); } else { player2.push_back(c2); player2.push_back(c1); } } else { if (c1 > c2) { player1.push_back(c1); player1.push_back(c2); } else { player2.push_back(c2); player2.push_back(c1); } } } return player1.size() != 0; } int part2(deque<int> player1, deque<int> player2) { recursive_game(player1, player2); deque<int> *winning_player = player1.size() != 0 ? &player1 : &player2; int result = 0; int i = winning_player->size(); for (auto p = winning_player->begin(); p != winning_player->end(); ++p) { result += i * (*p); --i; } return result; } int main() { ifstream reader("input.txt"); string line; deque<int> player1; deque<int> player2; deque<int> *curr_player = &player1; while(getline(reader, line)) { if (line.empty()) { curr_player = &player2; } else if (line.find(":") == string::npos) { curr_player->push_back(stoi(line)); } } cout << "Part 1: " << part1(player1, player2) << endl; cout << "Part 2: " << part2(player1, player2) << endl; return 0; }
[ "46164638+qwoprocks@users.noreply.github.com" ]
46164638+qwoprocks@users.noreply.github.com
e8802fc23ef81c76e8d8852751f6900df93d3fc4
474bb820fb472ff350bf032ee502010da0e455cb
/contest/wannafly2020/day6/6.cpp
2db576611e4372e6a87c6888e65ec9f6cb77bece
[]
no_license
wqrqwerqrw/acm_code
839b1f3f50abcacec6f83acf3f002a887468b0d7
15b90fa1f12b8dca64d751525f9c73509f61328b
refs/heads/master
2020-05-02T20:02:42.232841
2020-02-10T11:59:55
2020-02-10T11:59:55
178,177,685
3
0
null
null
null
null
UTF-8
C++
false
false
654
cpp
// Wqr_ // Time : 20/01/17 #include <stdio.h> int n, a, b, c, p, d, ans; int main() { // freopen("in.txt","r",stdin); scanf("%d", &n); scanf("%d%d%d%d%d", &a, &b, &c, &p, &d); int i, j, k; bool ta, tb, tc; for (i = 1; i <= n; i++) { for (j = i + 1; j <= n; j++) { for (k = j + 1; k <= n; k++) { ta = (a * (i + j) * (i + j) + b * (i - j) * (i - j) + c) % p > d; tb = (a * (i + k) * (i + k) + b * (i - k) * (i - k) + c) % p > d; tc = (a * (k + j) * (k + j) + b * (k - j) * (k - j) + c) % p > d; if (ta == tb && tb == tc) ++ans; } } } printf("%d", ans); return 0; }
[ "wqrlink@outlook.com" ]
wqrlink@outlook.com
9f17be6a5b2282bba13c6de2039d85c756a108be
2126109717bf6b768fc09395b1284aa5cab6e2e3
/src/init.cpp
7d6035e7a803a3406100cc9fad0eaa196531e5d6
[ "MIT" ]
permissive
bonesdevcoin/bon
bf9bbafce44dd2960b499df45284ff23c769fc48
c92338c58e3275cdb20b65cf482f14b497ebeb89
refs/heads/master
2021-01-01T04:58:15.834439
2016-05-20T18:26:28
2016-05-20T18:26:28
59,317,774
0
0
null
null
null
null
UTF-8
C++
false
false
36,135
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "net.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "checkpoints.h" #include "zerocoin/ZeroTest.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/algorithm/string/predicate.hpp> #include <openssl/crypto.h> #ifndef WIN32 #include <signal.h> #endif using namespace std; using namespace boost; CWallet* pwalletMain; CClientUIInterface uiInterface; bool fConfChange; bool fEnforceCanonical; unsigned int nNodeLifespan; unsigned int nDerivationMethodIndex; unsigned int nMinerSleep; bool fUseFastIndex; enum Checkpoints::CPMode CheckpointsMode; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // void ExitTimeout(void* parg) { #ifdef WIN32 MilliSleep(5000); ExitProcess(0); #endif } void StartShutdown() { #ifdef QT_GUI // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards) uiInterface.QueueShutdown(); #else // Without UI, Shutdown() can simply be started in a new thread NewThread(Shutdown, NULL); #endif } void Shutdown(void* parg) { static CCriticalSection cs_Shutdown; static bool fTaken; // Make this thread recognisable as the shutdown thread RenameThread("bonescoin-shutoff"); bool fFirstThread = false; { TRY_LOCK(cs_Shutdown, lockShutdown); if (lockShutdown) { fFirstThread = !fTaken; fTaken = true; } } static bool fExit; if (fFirstThread) { fShutdown = true; nTransactionsUpdated++; // CTxDB().Close(); bitdb.Flush(false); StopNode(); bitdb.Flush(true); boost::filesystem::remove(GetPidFile()); UnregisterWallet(pwalletMain); delete pwalletMain; NewThread(ExitTimeout, NULL); MilliSleep(50); printf("BonesCoin exited\n\n"); fExit = true; #ifndef QT_GUI // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp exit(0); #endif } else { while (!fExit) MilliSleep(500); MilliSleep(100); ExitThread(0); } } void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } ////////////////////////////////////////////////////////////////////////////// // // Start // #if !defined(QT_GUI) bool AppInit(int argc, char* argv[]) { bool fRet = false; try { // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() ParseParameters(argc, argv); if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); Shutdown(NULL); } ReadConfigFile(mapArgs, mapMultiArgs); if (mapArgs.count("-?") || mapArgs.count("--help")) { // First part of help message is specific to bitcoind / RPC client std::string strUsage = _("BonesCoin version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " bonescoind [options] " + "\n" + " bonescoind [options] <command> [params] " + _("Send command to -server or bonescoind") + "\n" + " bonescoind [options] help " + _("List commands") + "\n" + " bonescoind [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessage(); fprintf(stdout, "%s", strUsage.c_str()); return false; } // Command-line RPC for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bonescoin:")) fCommandLine = true; if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } fRet = AppInit2(); } catch (std::exception& e) { PrintException(&e, "AppInit()"); } catch (...) { PrintException(NULL, "AppInit()"); } if (!fRet) Shutdown(NULL); return fRet; } extern void noui_connect(); int main(int argc, char* argv[]) { bool fRet = false; // Connect bitcoind signal handlers noui_connect(); fRet = AppInit(argc, argv); if (fRet && fDaemon) return 0; return 1; } #endif bool static InitError(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, _("BonesCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL); return false; } bool static InitWarning(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, _("BonesCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); return true; } bool static Bind(const CService &addr, bool fError = true) { if (IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError)) { if (fError) return InitError(strError); return false; } return true; } // Core-specific options shared between UI and daemon std::string HelpMessage() { string strUsage = _("Options:") + "\n" + " -? " + _("This help message") + "\n" + " -conf=<file> " + _("Specify configuration file (default: bonescoin.conf)") + "\n" + " -pid=<file> " + _("Specify pid file (default: bonescoind.pid)") + "\n" + " -datadir=<dir> " + _("Specify data directory") + "\n" + " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" + " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" + " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" + " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" + " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" + " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" + " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n" " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" + " -port=<port> " + _("Listen for connections on <port> (default: 7135 or testnet: 17135)") + "\n" + " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" + " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" + " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" + " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" + " -externalip=<ip> " + _("Specify your own public address") + "\n" + " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" + " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" + " -irc " + _("Find peers using internet relay chat (default: 0)") + "\n" + " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" + " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" + " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" + " -staking " + _("Stake your coins to support network and gain reward (default: 1)") + "\n" + " -synctime " + _("Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)") + "\n" + " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" + " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" + " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" + " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" + " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" + #ifdef USE_UPNP #if USE_UPNP " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" + #else " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" + #endif #endif " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" + " -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" + #ifdef QT_GUI " -server " + _("Accept command line and JSON-RPC commands") + "\n" + #endif #if !defined(WIN32) && !defined(QT_GUI) " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" + #endif " -testnet " + _("Use the test network") + "\n" + " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" + " -debugnet " + _("Output extra network debugging information") + "\n" + " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" + " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" + " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" + #ifdef WIN32 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" + #endif " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" + " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" + " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 7136 or testnet: 17136)") + "\n" + " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" + " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" + " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" + " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" + " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" + " -enforcecanonical " + _("Enforce transaction scripts to use canonical PUSH operators (default: 1)") + "\n" + " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" + " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" + " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" + " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" + " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" + " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" + " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" + " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" + "\n" + _("Block creation options:") + "\n" + " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" + " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" + " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" + "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" + " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" + " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" + " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" + " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n"; return strUsage; } /** Sanity checks * Ensure that Bitcoin is running in a usable environment with all * necessary library support. */ bool InitSanityCheck(void) { if(!ECC_InitSanityCheck()) { InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more " "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries"); return false; } // TODO: remaining sanity checks, see #4081 return true; } /** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2() { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #endif // ********************************************************* Step 2: parameter interactions nNodeLifespan = GetArg("-addrlifespan", 7); fUseFastIndex = GetBoolArg("-fastindex", true); nMinerSleep = GetArg("-minersleep", 500); CheckpointsMode = Checkpoints::STRICT; std::string strCpMode = GetArg("-cppolicy", "strict"); if(strCpMode == "strict") CheckpointsMode = Checkpoints::STRICT; if(strCpMode == "advisory") CheckpointsMode = Checkpoints::ADVISORY; if(strCpMode == "permissive") CheckpointsMode = Checkpoints::PERMISSIVE; nDerivationMethodIndex = 0; fTestNet = GetBoolArg("-testnet"); if (fTestNet) { SoftSetBoolArg("-irc", true); } if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified SoftSetBoolArg("-listen", true); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default SoftSetBoolArg("-dnsseed", false); SoftSetBoolArg("-listen", false); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a proxy server is specified SoftSetBoolArg("-listen", false); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) SoftSetBoolArg("-upnp", false); SoftSetBoolArg("-discover", false); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others SoftSetBoolArg("-discover", false); } if (GetBoolArg("-salvagewallet")) { // Rewrite just private keys: rescan to find transactions SoftSetBoolArg("-rescan", true); } // ********************************************************* Step 3: parameter-to-internal-flags fDebug = GetBoolArg("-debug"); // -debug implies fDebug* if (fDebug) fDebugNet = true; else fDebugNet = GetBoolArg("-debugnet"); #if !defined(WIN32) && !defined(QT_GUI) fDaemon = GetBoolArg("-daemon"); #else fDaemon = false; #endif if (fDaemon) fServer = true; else fServer = GetBoolArg("-server"); /* force fServer when running without GUI */ #if !defined(QT_GUI) fServer = true; #endif fPrintToConsole = GetBoolArg("-printtoconsole"); fPrintToDebugger = GetBoolArg("-printtodebugger"); fLogTimestamps = GetBoolArg("-logtimestamps"); if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; } if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str())); if (nTransactionFee > 0.25 * COIN) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); } fConfChange = GetBoolArg("-confchange", false); fEnforceCanonical = GetBoolArg("-enforcecanonical", true); if (mapArgs.count("-mininput")) { if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue)) return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str())); } // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log // Sanity check if (!InitSanityCheck()) return InitError(_("Initialization sanity check failed. BonesCoin is shutting down.")); std::string strDataDir = GetDataDir().string(); std::string strWalletFileName = GetArg("-wallet", "wallet.dat"); // strWalletFileName must be a plain filename without a directory if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName)) return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str())); // Make sure only a single Bitcoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. BonesCoin is probably already running."), strDataDir.c_str())); #if !defined(WIN32) && !defined(QT_GUI) if (fDaemon) { // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) { CreatePidFile(GetPidFile(), pid); return true; } pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("BonesCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); printf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); printf("Used data directory %s\n", strDataDir.c_str()); std::ostringstream strErrors; if (fDaemon) fprintf(stdout, "BonesCoin server starting\n"); int64_t nStart; // ********************************************************* Step 5: verify database integrity uiInterface.InitMessage(_("Verifying database integrity...")); if (!bitdb.Open(GetDataDir())) { string msg = strprintf(_("Error initializing database environment %s!" " To recover, BACKUP THAT DIRECTORY, then remove" " everything from it except for wallet.dat."), strDataDir.c_str()); return InitError(msg); } if (GetBoolArg("-salvagewallet")) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, strWalletFileName, true)) return false; } if (filesystem::exists(GetDataDir() / strWalletFileName)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), strDataDir.c_str()); uiInterface.ThreadSafeMessageBox(msg, _("BonesCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); } if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); } // ********************************************************* Step 6: network initialization int nSocksVersion = GetArg("-socks", 5); if (nSocksVersion != 4 && nSocksVersion != 5) return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion)); if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str())); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } CService addrProxy; bool fProxy = false; if (mapArgs.count("-proxy")) { addrProxy = CService(mapArgs["-proxy"], 9050); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str())); if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); SetNameProxy(addrProxy, nSocksVersion); } fProxy = true; } // -tor can override normal proxy, -notor disables tor entirely if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) { CService addrOnion; if (!mapArgs.count("-tor")) addrOnion = addrProxy; else addrOnion = CService(mapArgs["-tor"], 9050); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str())); SetProxy(NET_TOR, addrOnion, 5); SetReachable(NET_TOR); } // see Step 2: parameter interactions for more information about these fNoListen = !GetBoolArg("-listen", true); fDiscover = GetBoolArg("-discover", true); fNameLookup = GetBoolArg("-dns", true); #ifdef USE_UPNP fUseUPnP = GetBoolArg("-upnp", USE_UPNP); #endif bool fBound = false; if (!fNoListen) { std::string strError; if (mapArgs.count("-bind")) { BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str())); fBound |= Bind(addrBind); } } else { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; if (!IsLimited(NET_IPV6)) fBound |= Bind(CService(in6addr_any, GetListenPort()), false); if (!IsLimited(NET_IPV4)) fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapArgs.count("-externalip")) { BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort(), fNameLookup); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str())); AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); } } if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount { if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) { InitError(_("Invalid amount for -reservebalance=<amount>")); return false; } } if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key { if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", ""))) InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n")); } BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) AddOneShot(strDest); // ********************************************************* Step 7: load blockchain if (!bitdb.Open(GetDataDir())) { string msg = strprintf(_("Error initializing database environment %s!" " To recover, BACKUP THAT DIRECTORY, then remove" " everything from it except for wallet.dat."), strDataDir.c_str()); return InitError(msg); } if (GetBoolArg("-loadblockindextest")) { CTxDB txdb("r"); txdb.LoadBlockIndex(); PrintBlockTree(); return false; } uiInterface.InitMessage(_("Loading block index...")); printf("Loading block index...\n"); nStart = GetTimeMillis(); if (!LoadBlockIndex()) return InitError(_("Error loading blkindex.dat")); // as LoadBlockIndex can take several minutes, it's possible the user // requested to kill bitcoin-qt during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { printf("Shutdown requested. Exiting.\n"); return false; } printf(" block index %15"PRId64"ms\n", GetTimeMillis() - nStart); if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree")) { PrintBlockTree(); return false; } if (mapArgs.count("-printblock")) { string strMatch = mapArgs["-printblock"]; int nFound = 0; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { uint256 hash = (*mi).first; if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0) { CBlockIndex* pindex = (*mi).second; CBlock block; block.ReadFromDisk(pindex); block.BuildMerkleTree(); block.print(); printf("\n"); nFound++; } } if (nFound == 0) printf("No blocks matching %s were found\n", strMatch.c_str()); return false; } // ********************************************************* Testing Zerocoin if (GetBoolArg("-zerotest", false)) { printf("\n=== ZeroCoin tests start ===\n"); Test_RunAllTests(); printf("=== ZeroCoin tests end ===\n\n"); } // ********************************************************* Step 8: load wallet uiInterface.InitMessage(_("Loading wallet...")); printf("Loading wallet...\n"); nStart = GetTimeMillis(); bool fFirstRun = true; pwalletMain = new CWallet(strWalletFileName); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) { if (nLoadWalletRet == DB_CORRUPT) strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) { string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.")); uiInterface.ThreadSafeMessageBox(msg, _("BonesCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); } else if (nLoadWalletRet == DB_TOO_NEW) strErrors << _("Error loading wallet.dat: Wallet requires newer version of BonesCoin") << "\n"; else if (nLoadWalletRet == DB_NEED_REWRITE) { strErrors << _("Wallet needed to be rewritten: restart BonesCoin to complete") << "\n"; printf("%s", strErrors.str().c_str()); return InitError(strErrors.str()); } else strErrors << _("Error loading wallet.dat") << "\n"; } if (GetBoolArg("-upgradewallet", fFirstRun)) { int nMaxVersion = GetArg("-upgradewallet", 0); if (nMaxVersion == 0) // the -upgradewallet without argument case { printf("Performing wallet upgrade to %i\n", FEATURE_LATEST); nMaxVersion = CLIENT_VERSION; pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else printf("Allowing wallet upgrade up to %i\n", nMaxVersion); if (nMaxVersion < pwalletMain->GetVersion()) strErrors << _("Cannot downgrade wallet") << "\n"; pwalletMain->SetMaxVersion(nMaxVersion); } if (fFirstRun) { // Create new keyUser and set as default key RandAddSeedPerfmon(); CPubKey newDefaultKey; if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) { pwalletMain->SetDefaultKey(newDefaultKey); if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), "")) strErrors << _("Cannot write default address") << "\n"; } } printf("%s", strErrors.str().c_str()); printf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart); RegisterWallet(pwalletMain); CBlockIndex *pindexRescan = pindexBest; if (GetBoolArg("-rescan")) pindexRescan = pindexGenesisBlock; else { CWalletDB walletdb(strWalletFileName); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) pindexRescan = locator.GetBlockIndex(); } if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight) { uiInterface.InitMessage(_("Rescanning...")); printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); printf(" rescan %15"PRId64"ms\n", GetTimeMillis() - nStart); } // ********************************************************* Step 9: import blocks if (mapArgs.count("-loadblock")) { uiInterface.InitMessage(_("Importing blockchain data file.")); BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"]) { FILE *file = fopen(strFile.c_str(), "rb"); if (file) LoadExternalBlockFile(file); } exit(0); } filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (filesystem::exists(pathBootstrap)) { uiInterface.InitMessage(_("Importing bootstrap blockchain data file.")); FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LoadExternalBlockFile(file); RenameOver(pathBootstrap, pathBootstrapOld); } } // ********************************************************* Step 10: load peers uiInterface.InitMessage(_("Loading addresses...")); printf("Loading addresses...\n"); nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) printf("Invalid or missing peers.dat; recreating\n"); } printf("Loaded %i addresses from peers.dat %"PRId64"ms\n", addrman.size(), GetTimeMillis() - nStart); // ********************************************************* Step 11: start node if (!CheckDiskSpace()) return false; RandAddSeedPerfmon(); //// debug print printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size()); printf("nBestHeight = %d\n", nBestHeight); printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size()); printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size()); printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size()); if (!NewThread(StartNode, NULL)) InitError(_("Error: could not start node")); if (fServer) NewThread(ThreadRPCServer, NULL); // ********************************************************* Step 12: finished uiInterface.InitMessage(_("Done loading")); printf("Done loading\n"); if (!strErrors.str().empty()) return InitError(strErrors.str()); // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); #if !defined(QT_GUI) // Loop until process is exit()ed from shutdown() function, // called from ThreadRPCServer thread when a "stop" command is received. while (1) MilliSleep(5000); #endif return true; }
[ "bones" ]
bones
bce5047980049c2173178cf719bf477b67ac876a
76db065e8dba737b4c9c81a95800ebe8e7918063
/qt/vbox/vbox.cpp
d8da154364b67657dd992383815d2dd340a4e23c
[]
no_license
sahil87/learning-nitt
43c876adcb067de74ab2f6642e8d14a881da1c51
486c9cd08d1b671e66c40c56b0c9706595829b23
refs/heads/master
2021-01-15T15:16:13.337286
2015-04-15T20:23:55
2015-04-15T20:23:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
929
cpp
#include <qapplication.h> #include <qpushbutton.h> #include <qlayout.h> #include <qcanvas.h> #include <qwidget.h> #include <qnamespace.h> #include <qvbox.h> int main( int argc, char **argv ) { QApplication a( argc, argv ); QVBox widget(0); // QBoxLayout qbox(& widget,QBoxLayout::Down,0,-1,"Qbox"); QCanvasView canvasview(& widget); // QCanvas canvas(canvasview,"can"); // canvas.resize(100,100); QCanvas canvas(100,150); canvasview.setCanvas(& canvas); // // // qbox.addWidget(&canvasview); //canvas.resize(100,110); QPushButton hello(& widget , "hellobutton"); hello.setText("hello world!!"); hello.setFont(QFont("Times",18,QFont::Bold)); // QLabel *splashScreen = new QLabel( 0, "mySplashScreen", // Qt::WStyle_Customize | Qt::WStyle_Splash ); // a.setMainWidget(splashScreen); widget.show(); return a.exec(); }
[ "sahilahuja@gmail.com" ]
sahilahuja@gmail.com
cf15742755b305644e1be48d49b48a956cbe1b68
4765dd8790ffcd830eda65e371b326190664c765
/backend/entity/User.hpp
6ad340c101c3ad655796b434b57a588ea784d08a
[ "MIT" ]
permissive
EricJeffrey/TheCheatSheet
31eac0124e0f319846bab322faadc1bab2f29591
d3a9c91be10ad9179fdcbb25832d3235ea644115
refs/heads/main
2023-04-08T18:08:34.667182
2021-04-18T05:47:39
2021-04-18T05:47:39
305,010,267
3
1
MIT
2021-04-12T13:40:03
2020-10-18T02:52:56
C++
UTF-8
C++
false
false
1,442
hpp
#if !defined(USER_HPP) #define USER_HPP #include <string> #include <vector> #include "nlohmann/json.hpp" using std::string; using std::vector; class User { public: static constexpr char KEY_ID[] = "_id"; static constexpr char KEY_NAME[] = "name"; static constexpr char KEY_EMAIL[] = "email"; static constexpr char KEY_PASSWORD[] = "password"; static constexpr char KEY_FAVORS[] = "favors"; string mId; string mName; string mEmail; string mPassword; vector<string> mFavorIds; User() = default; ~User() = default; User(const string &name, const string &email, const string &password) : mName(name), mEmail(email), mPassword(password) {} bool operator==(const User &t) const { return mName == t.mName && mEmail == t.mEmail && mPassword == t.mPassword && mFavorIds == t.mFavorIds; } nlohmann::json toJson() { return nlohmann::json{ {KEY_ID, mId}, {KEY_NAME, mName}, {KEY_EMAIL, mEmail}, {KEY_PASSWORD, mPassword}, {KEY_FAVORS, mFavorIds}, }; } void setId(const string &id) { mId = id; } void setName(const string &name) { mName = name; } void setEmail(const string &email) { mEmail = email; } void setPassword(const string &password) { mPassword = password; } void setFavors(const vector<string> &favors) { mFavorIds = favors; } }; #endif // USER_HPP
[ "1719937412@qq.com" ]
1719937412@qq.com
ce538d010f143082fb858ee1bade0b07967419d8
be0345e5aef813db69303e0a3c29142c8274c5f6
/include/wwidget/Window.hpp
72acd321e37f34749e49f325598a7b0885094e86
[]
no_license
Cannedfood/WonkyWidgets
778f53751d5fecd2efb63ef140ccc634813fe2c5
62690f3ce261aa5a49ed5375974c5571d162c047
refs/heads/master
2021-07-12T07:41:48.742412
2018-10-14T17:53:25
2018-10-14T17:53:25
107,892,077
2
2
null
null
null
null
UTF-8
C++
false
false
1,502
hpp
#pragma once #include "BasicContext.hpp" #include <stdexcept> namespace wwidget { namespace exceptions { struct FailedOpeningWindow : public std::runtime_error { FailedOpeningWindow(std::string const& val) : std::runtime_error(val) {} }; } // namespace exception /// A desktop environment window. class Window : public Widget, public BasicContext { void* mWindowPtr; Mouse mMouse; uint32_t mFlags; protected: PreferredSize onCalcPreferredSize(PreferredSize const& constraint) override; void onResized() override; void onDrawBackground(Canvas& c) override; void onDraw(Canvas& canvas) override; public: enum Flags { FlagSinglebuffered = 1, FlagNoVsync = 2, FlagAntialias = 4, FlagRelative = 8, FlagUpdateOnEvent = 16, FlagDrawDebug = 32, FlagShrinkFit = 64 }; Window(); Window(const char* title, unsigned width = 800, unsigned height = 600, uint32_t flags = 0); virtual ~Window(); void open(const char* title, unsigned width = 800, unsigned height = 600, uint32_t flags = 0); void close(); void requestClose(); bool update() override; /// Blocks and updates the window until it is closed void keepOpen(); /// Draws the window with it's own canvas, dpi is calculated by default void draw(float dpi = -1) override; Mouse& mouse() { return mMouse; } inline bool relative() const noexcept { return mFlags & FlagRelative; } bool doesShrinkFit() const noexcept { return mFlags & FlagShrinkFit; } }; } // namespace wwidget
[ "benno.straub@outlook.de" ]
benno.straub@outlook.de
0921345e0499b11e2d0f5c207439963f086a9832
3b97b786b99c3e4e72bf8fe211bb710ecb674f2b
/TClient_Branch101012/TClient/Tools/TQuestPath/TQuestPath.cpp
914d151a5d4753416220a05270e64b639dfd4bdd
[]
no_license
moooncloud/4s
930384e065d5172cd690c3d858fdaaa6c7fdcb34
a36a5785cc20da19cd460afa92a3f96e18ecd026
refs/heads/master
2023-03-17T10:47:28.154021
2017-04-20T21:42:01
2017-04-20T21:42:01
null
0
0
null
null
null
null
UHC
C++
false
false
3,862
cpp
// TQuestPath.cpp : 응용 프로그램에 대한 클래스 동작을 정의합니다. // #include "stdafx.h" #include "TQuestPath.h" #include "MainFrm.h" #include "TQuestPathDoc.h" #include "TQuestPathView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CTQuestPathApp BEGIN_MESSAGE_MAP(CTQuestPathApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // 표준 파일을 기초로 하는 문서 명령입니다. ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) END_MESSAGE_MAP() // CTQuestPathApp 생성 CTQuestPathApp::CTQuestPathApp() { // TODO: 여기에 생성 코드를 추가합니다. // InitInstance에 모든 중요한 초기화 작업을 배치합니다. } // 유일한 CTQuestPathApp 개체입니다. CTQuestPathApp theApp; // CTQuestPathApp 초기화 BOOL CTQuestPathApp::InitInstance() { // 응용 프로그램 매니페스트가 ComCtl32.dll 버전 6 이상을 사용하여 비주얼 스타일을 // 사용하도록 지정하는 경우, Windows XP 상에서 반드시 InitCommonControls()가 필요합니다. // InitCommonControls()를 사용하지 않으면 창을 만들 수 없습니다. InitCommonControls(); CWinApp::InitInstance(); // OLE 라이브러리를 초기화합니다. if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // 표준 초기화 // 이들 기능을 사용하지 않고 최종 실행 파일의 크기를 줄이려면 // 아래에서 필요 없는 특정 초기화 루틴을 제거해야 합니다. // 해당 설정이 저장된 레지스트리 키를 변경하십시오. // TODO: 이 문자열을 회사 또는 조직의 이름과 같은 // 적절한 내용으로 수정해야 합니다. SetRegistryKey(_T("로컬 응용 프로그램 마법사에서 생성된 응용 프로그램")); LoadStdProfileSettings(4); // MRU를 포함하여 표준 INI 파일 옵션을 로드합니다. // 응용 프로그램의 문서 템플릿을 등록합니다. 문서 템플릿은 // 문서, 프레임 창 및 뷰 사이의 연결 역할을 합니다. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CTQuestPathDoc), RUNTIME_CLASS(CMainFrame), // 주 SDI 프레임 창입니다. RUNTIME_CLASS(CTQuestPathView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // 표준 셸 명령, DDE, 파일 열기에 대한 명령줄을 구문 분석합니다. CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // 명령줄에 지정된 명령을 디스패치합니다. 응용 프로그램이 /RegServer, /Register, /Unregserver 또는 /Unregister로 시작된 경우 FALSE를 반환합니다. if (!ProcessShellCommand(cmdInfo)) return FALSE; // 창 하나만 초기화되었으므로 이를 표시하고 업데이트합니다. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // 접미사가 있을 경우에만 DragAcceptFiles를 호출합니다. // SDI 응용 프로그램에서는 ProcessShellCommand 후에 이러한 호출이 발생해야 합니다. return TRUE; } // 응용 프로그램 정보에 사용되는 CAboutDlg 대화 상자입니다. class CAboutDlg : public CDialog { public: CAboutDlg(); // 대화 상자 데이터 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원 // 구현 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // 대화 상자를 실행하기 위한 응용 프로그램 명령입니다. void CTQuestPathApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CTQuestPathApp 메시지 처리기
[ "great.mafia2010@gmail.com" ]
great.mafia2010@gmail.com
d93f109e6205ab3025c38ea6666f13e11c112023
b71b8bd385c207dffda39d96c7bee5f2ccce946c
/testcases/CWE23_Relative_Path_Traversal/s03/CWE23_Relative_Path_Traversal__wchar_t_connect_socket_ifstream_15.cpp
6c624a765f42d32044248f14b710657942145aa3
[]
no_license
Sporknugget/Juliet_prep
e9bda84a30bdc7938bafe338b4ab2e361449eda5
97d8922244d3d79b62496ede4636199837e8b971
refs/heads/master
2023-05-05T14:41:30.243718
2021-05-25T16:18:13
2021-05-25T16:18:13
369,334,230
0
0
null
null
null
null
UTF-8
C++
false
false
5,627
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__wchar_t_connect_socket_ifstream_15.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-15.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed file name * Sink: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 15 Control flow: switch(6) * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH L"c:\\temp\\" #else #include <wchar.h> #define BASEPATH L"/tmp/" #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__wchar_t_connect_socket_ifstream_15 { #ifndef OMITBAD void bad() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */ static void goodG2B1() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; /* FIX: Use a fixed file name */ wcscat(data, L"file.txt"); { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */ static void goodG2B2() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; /* FIX: Use a fixed file name */ wcscat(data, L"file.txt"); { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE23_Relative_Path_Traversal__wchar_t_connect_socket_ifstream_15; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "jaredzap@rams.colostate.edu" ]
jaredzap@rams.colostate.edu
ebce0dc5af5936f165941a96d7db880abaf1b774
1341ff13f329a0eb4479f88e5d13033f7319271c
/ocl/traffic_statistics.cpp
522dd6308cad49bf725304fea0583fb9fe272270
[]
no_license
GSSBMW/SoftwareRouter
c5e576f2fea3536b6d40a3cf7074627081ff8ed4
843b3f5990f8cf0b6d2272999a7be182e3a7b89b
refs/heads/master
2021-01-10T19:47:11.301814
2015-05-11T12:12:13
2015-05-11T12:12:13
34,667,341
0
0
null
null
null
null
UTF-8
C++
false
false
2,681
cpp
#include "traffic_statistics.hpp" #include <malloc.h> void ConstructPacketsInfo(packet_info_t *&packets_info, const size_t num) { free(packets_info); int ret = posix_memalign((void**)&packets_info, 64, num*sizeof(packet_info_t)); if (0 != ret) { printf("Error: posix_memalign() return %d\n", ret); } for (int i=0; i<num; ++i) { packets_info[i].flow_id.src_ip = 0xC0A80304; //192.168.3.4 packets_info[i].flow_id.dst_ip = 0xC0A80403; //192.168.4.3 packets_info[i].flow_id.src_port = 5000; packets_info[i].flow_id.dst_port = 4000; packets_info[i].flow_id.protocol = 3; packets_info[i].packet_size = 1024; packets_info[i].index = -1; } } void TrafficStatistics(const unsigned int &flow_table_size, flow_table_entry_t **flow_table, const unsigned int &packets_num, packet_info_t *packets) { unsigned int index; flow_table_entry_t *pp, *p; for (int i=0; i<packets_num; ++i) { index = packets[i].index; if (NULL == flow_table[index]) { flow_table[index] = (flow_table_entry_t*)malloc(sizeof(flow_table_entry_t)); flow_table[index]->flow_id.src_ip = packets[i].flow_id.src_ip; flow_table[index]->flow_id.dst_ip = packets[i].flow_id.dst_ip; flow_table[index]->flow_id.src_port = packets[i].flow_id.src_port; flow_table[index]->flow_id.dst_port = packets[i].flow_id.dst_port; flow_table[index]->flow_id.protocol = packets[i].flow_id.protocol; flow_table[index]->throughput = packets[i].packet_size; flow_table[index]->next = NULL; continue; } pp = NULL; p = flow_table[index]; while (NULL != p) { if ( Tuple5Equal(packets[i].flow_id, p->flow_id) ) { p->throughput += packets[i].packet_size; break; } else { pp = p; p = p->next; } } // New flow with conflict if (NULL == p) { pp->next = (flow_table_entry_t*)malloc(sizeof(flow_table_entry_t)); pp->next->flow_id.src_ip = packets[i].flow_id.src_ip; pp->next->flow_id.dst_ip = packets[i].flow_id.dst_ip; pp->next->flow_id.src_port = packets[i].flow_id.src_port; pp->next->flow_id.dst_port = packets[i].flow_id.dst_port; pp->next->flow_id.protocol = packets[i].flow_id.protocol; pp->next->throughput = packets[i].packet_size; pp->next->next = NULL; continue; } } // for (int i=0; i<packets_num; ++i) } // FlowStatistics() bool Tuple5Equal(const tuple5_t &v1, const tuple5_t &v2) { if ( (v1.src_ip == v2.src_ip ) && (v1.dst_ip == v2.dst_ip ) && (v1.src_port == v2.src_port) && (v1.dst_port == v2.dst_port) && (v1.protocol == v2.protocol) ) return true; else return false; }
[ "wangyigss@163.com" ]
wangyigss@163.com
9f3eab9eeff3dc1cb18f1cd5314126e8919ef06e
d648dfdb71d8184abcf6b9de397475890eeb0701
/src/Application.cpp
1bba04a64ada332f37ae33f8e7feff6d9a331245
[]
no_license
bikz007/OpenGLFun
ef69d2545cc4ae07abb0f329844ba077a9ec552e
6a67a5a644bdef6f517dab54d2d8f0ce252cb3a7
refs/heads/master
2022-04-20T14:00:02.125858
2020-04-20T16:15:59
2020-04-20T18:12:28
257,335,250
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
#define GLEW_STATIC #include <GL/glew.h> #include "glew.c" #include <GLFW/glfw3.h> #include<iostream> int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); if(glewInit() != GLEW_OK) { std::cout << "Error" <<std::endl; } /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { /* Render here */ glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_TRIANGLES); glVertex2f(-0.1f,-0.5f); glVertex2f(0.2f,0.5f); glVertex2f(0.5f,-0.4f); glEnd(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; }
[ "bikrammodak75@gmail.com" ]
bikrammodak75@gmail.com
4a08d6d781f3594a7f7bbc1d57becdfef020b085
474ca3fbc2b3513d92ed9531a9a99a2248ec7f63
/ThirdParty/boost_1_63_0/libs/asio/example/cpp03/timeouts/blocking_tcp_client.cpp
75f7ed84079d577fef9ef8bf58d6dd3a6dc0d5f5
[ "BSL-1.0" ]
permissive
LazyPlanet/MX-Architecture
17b7b2e6c730409b22b7f38633e7b1f16359d250
732a867a5db3ba0c716752bffaeb675ebdc13a60
refs/heads/master
2020-12-30T15:41:18.664826
2018-03-02T00:59:12
2018-03-02T00:59:12
91,156,170
4
0
null
2018-02-04T03:29:46
2017-05-13T07:05:52
C++
UTF-8
C++
false
false
9,275
cpp
// // blocking_tcp_client.cpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #include <boost/asio/connect.hpp> #include <boost/asio/deadline_timer.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/read_until.hpp> #include <boost/asio/streambuf.hpp> #include <boost/system/system_error.hpp> #include <boost/asio/write.hpp> #include <cstdlib> #include <iostream> #include <string> #include <boost/lambda/bind.hpp> #include <boost/lambda/lambda.hpp> using boost::asio::deadline_timer; using boost::asio::ip::tcp; using boost::lambda::bind; using boost::lambda::var; using boost::lambda::_1; //---------------------------------------------------------------------- // // This class manages socket timeouts by applying the concept of a deadline. // Each asynchronous operation is given a deadline by which it must complete. // Deadlines are enforced by an "actor" that persists for the lifetime of the // client object: // // +----------------+ // | | // | check_deadline |<---+ // | | | // +----------------+ | async_wait() // | | // +---------+ // // If the actor determines that the deadline has expired, the socket is closed // and any outstanding operations are consequently cancelled. The socket // operations themselves use boost::lambda function objects as completion // handlers. For a given socket operation, the client object runs the // io_service to block thread execution until the actor completes. // class client { public: client() : socket_(io_service_), deadline_(io_service_) { // No deadline is required until the first socket operation is started. We // set the deadline to positive infinity so that the actor takes no action // until a specific deadline is set. deadline_.expires_at(boost::posix_time::pos_infin); // Start the persistent actor that checks for deadline expiry. check_deadline(); } void connect(const std::string& host, const std::string& service, boost::posix_time::time_duration timeout) { // Resolve the host name and service to a list of endpoints. tcp::resolver::query query(host, service); tcp::resolver::iterator iter = tcp::resolver(io_service_).resolve(query); // Set a deadline for the asynchronous operation. As a host name may // resolve to multiple endpoints, this function uses the composed operation // async_connect. The deadline applies to the entire operation, rather than // individual connection attempts. deadline_.expires_from_now(timeout); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. boost::system::error_code ec = boost::asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. The blocking_udp_client.cpp example shows how you // can use boost::bind rather than boost::lambda. boost::asio::async_connect(socket_, iter, var(ec) = _1); // Block until the asynchronous operation has completed. do io_service_.run_one(); while (ec == boost::asio::error::would_block); // Determine whether a connection was successfully established. The // deadline actor may have had a chance to run and close our socket, even // though the connect operation notionally succeeded. Therefore we must // check whether the socket is still open before deciding if we succeeded // or failed. if (ec || !socket_.is_open()) throw boost::system::system_error( ec ? ec : boost::asio::error::operation_aborted); } std::string read_line(boost::posix_time::time_duration timeout) { // Set a deadline for the asynchronous operation. Since this function uses // a composed operation (async_read_until), the deadline applies to the // entire operation, rather than individual reads from the socket. deadline_.expires_from_now(timeout); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. boost::system::error_code ec = boost::asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. The blocking_udp_client.cpp example shows how you // can use boost::bind rather than boost::lambda. boost::asio::async_read_until(socket_, input_buffer_, '\n', var(ec) = _1); // Block until the asynchronous operation has completed. do io_service_.run_one(); while (ec == boost::asio::error::would_block); if (ec) throw boost::system::system_error(ec); std::string line; std::istream is(&input_buffer_); std::getline(is, line); return line; } void write_line(const std::string& line, boost::posix_time::time_duration timeout) { std::string data = line + "\n"; // Set a deadline for the asynchronous operation. Since this function uses // a composed operation (async_write), the deadline applies to the entire // operation, rather than individual writes to the socket. deadline_.expires_from_now(timeout); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. boost::system::error_code ec = boost::asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. The blocking_udp_client.cpp example shows how you // can use boost::bind rather than boost::lambda. boost::asio::async_write(socket_, boost::asio::buffer(data), var(ec) = _1); // Block until the asynchronous operation has completed. do io_service_.run_one(); while (ec == boost::asio::error::would_block); if (ec) throw boost::system::system_error(ec); } private: void check_deadline() { // Check whether the deadline has passed. We compare the deadline against // the current time since a new asynchronous operation may have moved the // deadline before this actor had a chance to run. if (deadline_.expires_at() <= deadline_timer::traits_type::now()) { // The deadline has passed. The socket is closed so that any outstanding // asynchronous operations are cancelled. This allows the blocked // connect(), read_line() or write_line() functions to return. boost::system::error_code ignored_ec; socket_.close(ignored_ec); // There is no longer an active deadline. The expiry is set to positive // infinity so that the actor takes no action until a new deadline is set. deadline_.expires_at(boost::posix_time::pos_infin); } // Put the actor back to sleep. deadline_.async_wait(bind(&client::check_deadline, this)); } boost::asio::io_service io_service_; tcp::socket socket_; deadline_timer deadline_; boost::asio::streambuf input_buffer_; }; //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { if (argc != 4) { std::cerr << "Usage: blocking_tcp <host> <port> <message>\n"; return 1; } client c; c.connect(argv[1], argv[2], boost::posix_time::seconds(10)); boost::posix_time::ptime time_sent = boost::posix_time::microsec_clock::universal_time(); c.write_line(argv[3], boost::posix_time::seconds(10)); for (;;) { std::string line = c.read_line(boost::posix_time::seconds(10)); // Keep going until we get back the line that was sent. if (line == argv[3]) break; } boost::posix_time::ptime time_received = boost::posix_time::microsec_clock::universal_time(); std::cout << "Round trip time: "; std::cout << (time_received - time_sent).total_microseconds(); std::cout << " microseconds\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
[ "1211618464@qq.com" ]
1211618464@qq.com
516d9b29fcdbb2857c40e822a55c877215cb8cd6
ed4047088747820cd3c50bc7a0cdf6a56b9508f0
/Projects/HW5/time24.h
963597ace720d1a7bd7b862852966088dd633805
[ "Apache-2.0" ]
permissive
ToyVo/CSIIStout
536c2ea7791c76c66f26fc7e9a2f81b83479da76
79b32021d940a488fa9aa878369503078eed4831
refs/heads/main
2022-08-26T14:51:20.475426
2022-06-24T16:04:48
2022-08-10T03:52:35
231,264,051
0
0
null
null
null
null
UTF-8
C++
false
false
2,825
h
#ifndef TIME24_H #define TIME24_H #include "d_except.h" // for rangeError exception using namespace std; class time24 { public: // constructor initializes hour and minute time24(); time24(int m); time24(int h , int m); void addTime(int m); // update time by adding m minutes to the current time // Precondition: m must be >= 0 // Postcondition: The new time is m minutes later void subtractHour(int h); //subratact time //precondition h >= 0 //postcondition time is h hours earlier time24 duration(const time24& t); // return the length of time from the current time to some later // time t as a time24 value // Precondition: time t must not be earlier than the current time. // if it is, throw a rangeError exception void readTime(); // input from the keyboard time in the form hh:mm // Postcondition: Assign value hh to hour and mm to minute and // adjust units to the proper range. void writeTime() const; // display on the screen the current time in the form hh:mm int getHour() const; // return the hour value for the current time int getMinute() const; // return the minute value for the current time // THESE FUNCTIONS ARE DISCUSSED IN CHAPTER 2 ON OPERATOR // OVERLOADING friend bool operator== (const time24& lhs, const time24& rhs); friend bool operator< (const time24& lhs, const time24& rhs); friend bool operator> (const time24& lhs, const time24& rhs); friend time24 operator+ (const time24& lhs, const time24& rhs); // form and return lhs + rhs friend time24 operator+ (const time24& lhs, int min); // form and return lhs + min // Precondition: min must be >= 0 friend time24 operator+ (int min, const time24& rhs); // form and return min + rhs // Precondition: min must be >= 0 friend time24 operator- (const time24& lhs, const time24& rhs); // form and return lhs - rhs // Precondition: lhs >= rhs. if not, throw a rangeError exception time24& operator+= (const time24& rhs); // current object = current object + rhs // Postcondition: the time increases by the value of rhs time24& operator+= (int min); // current object = current object + min // Precondition: min must be >= 0 // Postcondition: the time increases by min minutes friend istream& operator>> (istream& istr, time24& t); // input t in the format hh:mm. may omit the leading digit // if hours or minutes < 10 friend ostream& operator<< (ostream& ostr, const time24& t); // output t in the format hh:mm. always include two digits // for the minute (e.g. 15:07). hours before 12 use 1 digit // and precede the hour by a blank (e.g. " 7:15") private: int hour, minute; // data members // utility function sets the hour value in the range 0 to 23 // and the minute value in the range 0 to 50 void normalizeTime(); }; #endif //TIME24_H
[ "collin@diekvoss.com" ]
collin@diekvoss.com
908bb3272950dc7af71557198812ebdb0d027af5
09c77550af1b5b4de3290e38efe842bdb7cf9fdd
/Exp4_BLUETOOTH_CONTROLLED_LED/bluetooth.ino
f5d1cf66b52260e36baee8b96229233df9179735
[]
no_license
Karan-Choudhary/BEEE_CU19
dd410bbb56d8b35fe7ce3967e69a227d015de744
e68be2b39db1d2028db675c19c9330c5295a1d2c
refs/heads/master
2020-07-14T21:33:38.992349
2019-11-03T15:12:19
2019-11-03T15:12:19
205,407,712
2
0
null
null
null
null
UTF-8
C++
false
false
246
ino
char data = 0; void setup() { pinMode(13,OUTPUT); Serial.begin(9600); } void loop() { if(Serial.available()>0) { data=Serial.read(); if(data=='1') { digitalWrite(13,HIGH); } else if(data=='0') { digitalWrite(13,LOW); } } }
[ "noreply@github.com" ]
Karan-Choudhary.noreply@github.com
d03d51bb496f14403d2158ea36259b93008aed01
2ccbd5ca4588d5edee12d5ac5d1044927c797b49
/wac6p1.cpp
5028062993161e7027d13006bc0547df07f0e130
[]
no_license
2ee2ee2ee/Competitive_Programming
9c1ab1da209b000ab27bf908f8b38d80e0ac9c31
cf7558f62fb2fa1dc5ad21727ecdbba63a3224c0
refs/heads/master
2023-03-11T20:31:49.234470
2021-02-20T22:13:29
2021-02-20T22:13:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
207
cpp
#include <bits/stdc++.h> using namespace std; int main() { double p,c; int n; scanf("%d",&n); while (n--) { scanf("%lf%lf",&p,&c); double denom = c+100.00; printf("%.9lf\n",p/denom * 100.00); } }
[ "38817928+sa35577@users.noreply.github.com" ]
38817928+sa35577@users.noreply.github.com
5f0cee754342bf696219a61ef27431ca3e8e0b4f
572962dfe837e392e8e3f0ec9926383f1f385067
/hw4/bag/bag.cpp
a0727218f6729a8b2fb09085c456f2c3e5dc90b1
[]
no_license
LinkHS/Object-Oriented-Programming
4e5c309dfa4eb561e356313807b3cab911a0f6d7
9651096370d2c884f94ce25f5f2f2ca2a43e46c0
refs/heads/main
2023-03-07T02:46:33.212244
2021-02-19T05:48:31
2021-02-19T05:48:31
330,078,652
0
0
null
null
null
null
UTF-8
C++
false
false
3,744
cpp
// Partial static array implementation of Bag. // Sara Krehbiel + group work, 1/16/21 and 1/29/21 (F Week 4, file 3/3) #include "bag.h" // copy constructor deep-copies existing other bag contents into this new bag Bag::Bag(const Bag& other) { size_ = other.size_; cap_ = other.cap_; data_ = new int[cap_]; for (size_t i=0; i<size_; i++) { data_[i] = other.data_[i]; } } // destructor releases memory and restores default values Bag::~Bag() { delete [] data_; data_ = nullptr; // avoid leaving pointers pointing to released memory! size_ = cap_ = 0; } // assignment deep copies existing rhs contents into existing calling object Bag& Bag::operator =(const Bag& rhs) { if (cap_ != rhs.cap_) { // check if you need a new block of memory cap_ = rhs.cap_; delete [] data_; data_ = new int[cap_]; } size_ = rhs.size_; for (size_t i = 0; i<size_; i++) { // copy the contents of rhs into data_ data_[i] = rhs.data_[i]; } return *this; // return (reference to) updated self } // sweep the contents of bag, keeping track of # of occurences of target size_t Bag::count(int target) const { size_t count = 0; for (size_t i = 0; i<size_; i++) { if (data_[i]==target) count++; } return count; } // add an element to the appropriate slot in the bag array void Bag::insert(int target) { if (size_==cap_) { // get a new double-size array if (cap_==0) cap_ = 1; else cap_ *= 2; int *newArr = new int[cap_]; for (size_t i = 0; i<size_; i++) { newArr[i] = data_[i]; } delete [] data_; data_ = newArr; } data_[size_] = target; size_++; } // sweep data for target, shift everything after target back and decrement size bool Bag::erase_one(int target) { for (size_t i=0; i<size_; i++) { if (data_[i]==target) { // shift everything after removed elem back one for (size_t j=i+1; j<size_; j++) { data_[j-1] = data_[j]; } size_--; if (size_<=0.25*cap_) { // downsize if we aren't using much of the total capacity cap_ /= 2; int *newArr = new int[cap_]; for (size_t i=0; i<size_; i++) { newArr[i] = data_[i]; } delete [] data_; data_ = newArr; } return true; } } return false; } // call erase_one as many times as it takes to remove all copies of target size_t Bag::erase(int target) { int k = 0; while (erase_one(target)) { k++; } return k; } // if space, insert everything from rhs into this object void Bag::operator +=(const Bag & rhs) { //if (size_ + rhs.size_ <= CAPACITY) { // add contents of rhs to data_ for (size_t i = 0; i<rhs.size_; i++) { // add an element of rhs to this object insert(rhs.data_[i]); } // } } // if space, create/populate/return a bag with the combined contents of lhs+rhs Bag operator +(const Bag & lhs, const Bag & rhs) { Bag b; // this is an empty bag to populate and return size_t lsize = lhs.size(), rsize = rhs.size(); // if (lsize + rsize <= Bag::CAPACITY) { // insert all contents of lhs for (size_t i=0; i<lsize; i++) { b.insert(lhs[i]); } // then insert all contents of rhs for (size_t i=0; i<rsize; i++) { b.insert(rhs[i]); } // } return b; // empty if lhs+rhs wouldn't have fit } // overload insertion operator << to insert bag contents into an ostream ostream& operator <<(ostream& out, const Bag& b) { size_t n = b.size(); for (size_t i=0; i<n; i++) { out << b[i]; // use << for numbers/strings in defining it for a whole bag out << " "; } return out; }
[ "381082014@qq.com" ]
381082014@qq.com
bb9f32e0e31b1ba4f130203ed0e22d34f0af412c
b8506a61077f2a58a4884c650eaebb1e146790c7
/chaos/CoCycle.cpp
7e7c5e982db8f8e5a5d552c4dd395c53b89f4dc1
[]
no_license
alpha2z/chaos
49697fcaf3b243d5365acf7ed79df61829e163e4
3933f2e6a7808c3bfe50a65152d3c0865367ff62
refs/heads/master
2021-01-10T14:30:13.188679
2015-11-03T06:44:38
2015-11-03T06:44:38
45,446,821
0
0
null
null
null
null
UTF-8
C++
false
false
1,270
cpp
#include <sys/param.h> #include <sys/time.h> #include <sys/resource.h> #include <stdlib.h> #include <sys/stat.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <signal.h> #include "CoCycle.h" #include "CoConstants.h" #include <iostream> using namespace chaos; CoCycle *g_cycle = NULL; void CoCycle::daemon() { int fd; signal(SIGALRM, SIG_IGN); signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGCHLD, SIG_IGN); signal(SIGTERM, SIG_IGN); if (fork()) exit(0); if (setsid() == -1) exit(-1); for(fd=3;fd<NOFILE;fd++) close(fd); // chdir("/"); // umask(0); /* {//ulimit -c iMaxCoreFileSize struct rlimit rlim; getrlimit(RLIMIT_CORE, &rlim); rlim.rlim_max = rlim.rlim_cur = MAX_CORE_FILE_SIZE; if(setrlimit(RLIMIT_CORE, &rlim)) { printf("setrlimit core file size failed!\n"); } } {//ulimit -s iMaxStackSize struct rlimit rlim; getrlimit(RLIMIT_STACK, &rlim); rlim.rlim_max = rlim.rlim_cur = MAX_STACK_SIZE; if(setrlimit(RLIMIT_STACK, &rlim)) { printf("setrlimit stack size failed!\n"); } }*/ return; }
[ "chandler.alpha@gmail.com" ]
chandler.alpha@gmail.com
6f16b2d729b7985b6067b3ade99763e4e390bafb
c3050205fef29e223b702d378c898cdf255c1d8d
/Factory Machine.cpp
654874b6290cf60027023ec3a0749587f2da9c90
[]
no_license
ap-darknight/CSES-SET-
ac4386ffa71982577ebff6b9ac55d42fb206b58a
e1218caaa8e85daf7f5e0b4d54ee5e30ad7c2f80
refs/heads/master
2023-05-07T23:25:41.705364
2021-05-30T12:06:19
2021-05-30T12:06:19
362,016,256
1
1
null
2021-05-30T12:06:20
2021-04-27T07:13:41
C++
UTF-8
C++
false
false
1,224
cpp
//----------Coded By: ap_darknight-------------// #include <bits/stdc++.h> #include<string> using namespace std; typedef long long ll; #define mapL map<ll, ll> #define mapC map<char,ll> #define mapS map<string,ll> #define pll pair<ll,ll> #define ff first #define ss second #define vecL vector<ll> #define vecC vector<char> #define vecS vector<string> #define pb push_back #define repf(i,j,k) for(ll i=j; i<k; i++) #define repb(i,j,k) for(ll i=j; i>k; i--) #define mod 1000000007 #define bin_mod 4294967296 #define bit 32 #define BLK 200 //----------------------GRAPH LCA---------------------// ll gcd(ll a, ll b){ if(a==0) return b; else return gcd(b%a, a); } void solve(){ ll n,x,q,y,m,k,sum=0; cin>>n>>k; vecL arr; priority_queue<pll, vector<pll>, greater<pll>> pq; repf(i,0,n) cin>>x, pq.push({0, x}); ll time = 0; while(t--){ ll curr_time = pq.top().ff, time_taken = pq.top().ss; pq.pop(); pq.push({curr_time + time_taken, time_taken}); time+=time_taken; } cout<<time<<endl; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll t=1,n,x,y,k,e; // cin>>t; // while(t--) solve(); return 0; }
[ "52396786+ap-darknight@users.noreply.github.com" ]
52396786+ap-darknight@users.noreply.github.com
abe5225df6cb2aaebcbf6048919bd841921512b3
b2e2ed042ac7611b707c8316f5870909cfc391ee
/include/crombie2/ConfigModel.h
8979a6586aaeabd4db029cf9c6ca19dc57d4d223
[]
no_license
dabercro/crombie2
4e9e255bf745946ff9d55e8c07a3890e8f446684
e5efbe59e8dd3694739818da24542c331d1f7f7b
refs/heads/master
2021-06-29T22:42:08.518290
2020-09-30T16:49:37
2020-09-30T16:49:37
164,029,920
0
0
null
null
null
null
UTF-8
C++
false
false
2,413
h
#ifndef CROMBIE2_CONFIG_MODEL_H #define CROMBIE2_CONFIG_MODEL_H #include <list> #include <crombie2/Types.h> namespace crombie2 { /** @brief Abstract class that each saveable object should implement */ class ConfigModel { public: ConfigModel (const std::string& file_name = ""); virtual ~ConfigModel () = default; /// Get the class name of the configuration object virtual std::string get_name () const = 0; /** Loads the configuration from a file @param file_name Name of the file that holds the configuration */ void load (const std::string& file_name); /** Loads the configuration given by a tag @param tag The name of the tag */ void load_tag (const std::string& tag); /** Saves the configuration in a file @param file_name Name of the file to save the configuration in */ void save (const std::string& file_name); /** Hashes configuration and saves in a set location @returns The file name where the configuration was saved */ std::string save (); /// Gives what the filename would be std::string filename () const; /** Saves the configuration in a file @param tag The name of the tag @param overwrite Set to true if you definitely want to overwrite tag. Otherwise, a prompt is displayed to confirm overwriting. @returns The name of the config file */ std::string save_tag (const std::string& tag, bool overwrite = false); /** Change the location to save the config directories @param dir The name of the directory to save everything */ static void set_config_dir (const std::string& dir); static const std::string& get_config_dir (); virtual bool is_valid () const; void replace (const std::string& target, const std::string& newstr); protected: /** Loads the configuration from a bunch of strings @param config Configuration file after being parsed */ virtual void read (const Types::strings& config) = 0; /// Creates a string version of the configuration virtual std::list<std::string> serialize () const = 0; private: /// Make a hash of the serialization std::string hash () const; /// The location to save all used configurations static std::string config_directory; }; } #endif
[ "dabercro@mit.edu" ]
dabercro@mit.edu
df7b7dd157b671c84481cce7b6c9b68ae0373e13
5df12e96c75353d7ff5f6bd80e4c0c33a54a0e46
/platfrom/client/Codec.h
aefaa854d079835d9def89934dedb7a10cd3d17d
[]
no_license
wangdong7-7/safe-market
7bb02a0e06294190a77894172f955bda4db19a66
2a86ed737e12eda67f0fde1b881ea1181329709e
refs/heads/main
2023-06-19T05:31:26.647051
2021-07-19T04:46:15
2021-07-19T04:46:15
387,201,429
0
0
null
null
null
null
UTF-8
C++
false
false
295
h
#pragma once #include "SequenceASN1.h" // 编解码的父类 class Codec : public SequenceASN1 { public: Codec(); virtual ~Codec(); // 数据编码 virtual int msgEncode(char** outData, int &len); // 数据解码 virtual void* msgDecode(char *inData, int inLen); };
[ "noreply@github.com" ]
wangdong7-7.noreply@github.com
0a4df7ce4c9e5800ff2e62d15153b7cacaccc5f6
7f74c236881176d673fd5b8bed6e18283232deca
/modules/boost/simd/sdk/include/boost/simd/sdk/simd/details/native/meta.hpp
640a84cb1731ece409241e1f16716d552017cfa0
[ "BSL-1.0" ]
permissive
pesterie/nt2
57a3cbe4e3631d5eacbd1703b79af769f40b13f1
94e4062794466136987bf0afd9a94d43275b13cf
refs/heads/master
2021-01-18T06:52:52.070291
2011-08-31T12:04:16
2011-08-31T12:04:16
1,566,046
0
0
null
null
null
null
UTF-8
C++
false
false
973
hpp
/******************************************************************************* * Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II * Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI * * Distributed under the Boost Software License, Version 1.0. * See accompanying file LICENSE.txt or copy at * http://www.boost.org/LICENSE_1_0.txt ******************************************************************************/ #ifndef BOOST_SIMD_SDK_SIMD_DETAILS_NATIVE_META_HPP_INCLUDED #define BOOST_SIMD_SDK_SIMD_DETAILS_NATIVE_META_HPP_INCLUDED #include <boost/simd/sdk/simd/details/native/meta/hierarchy_of.hpp> #include <boost/simd/sdk/simd/details/native/meta/factory_of.hpp> #include <boost/simd/sdk/simd/details/native/meta/primitive_of.hpp> #include <boost/simd/sdk/simd/details/native/meta/scalar_of.hpp> #include <boost/simd/sdk/simd/details/native/meta/cardinal_of.hpp> #endif
[ "naabed.ptr@gmail.com" ]
naabed.ptr@gmail.com
8f1f0be0dd5199cc73174084e42be165fea6108b
c43b0d1e041d004d1fa8e1469f57b62d4d4bea88
/tools/fidlcat/lib/syscall_decoder.cc
0b9d5ca0361fe27a1cebf1a36cb7373402ebd69b
[ "BSD-3-Clause" ]
permissive
ZVNexus/fuchsia
75122894e09c79f26af828d6132202796febf3f3
c5610ad15208208c98693618a79c705af935270c
refs/heads/master
2023-01-12T10:48:06.597690
2019-07-04T05:09:11
2019-07-04T05:09:11
195,169,207
0
0
BSD-3-Clause
2023-01-05T20:35:36
2019-07-04T04:34:33
C++
UTF-8
C++
false
false
14,490
cc
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tools/fidlcat/lib/syscall_decoder.h" #include <zircon/system/public/zircon/types.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <iostream> #include <vector> #include "src/developer/debug/zxdb/client/breakpoint.h" #include "src/developer/debug/zxdb/client/frame.h" #include "src/developer/debug/zxdb/client/memory_dump.h" #include "src/developer/debug/zxdb/client/process.h" #include "src/developer/debug/zxdb/client/register.h" #include "src/developer/debug/zxdb/client/step_thread_controller.h" #include "src/developer/debug/zxdb/client/thread.h" #include "src/lib/fxl/logging.h" // TODO: Look into this. Removing the hack that led to this (in // debug_ipc/helper/message_loop.h) seems to work, except it breaks SDK builds // on CQ in a way I can't repro locally. #undef __TA_REQUIRES #include "tools/fidlcat/lib/interception_workflow.h" #include "tools/fidlcat/lib/syscall_decoder.h" namespace fidlcat { #define ErrorNameCase(name) \ case name: \ os << #name; \ return // TODO: (use zx_status_get_string when it will be available). void ErrorName(int64_t error_code, std::ostream& os) { switch (error_code) { ErrorNameCase(ZX_ERR_INTERNAL); ErrorNameCase(ZX_ERR_NOT_SUPPORTED); ErrorNameCase(ZX_ERR_NO_RESOURCES); ErrorNameCase(ZX_ERR_NO_MEMORY); ErrorNameCase(ZX_ERR_INTERNAL_INTR_RETRY); ErrorNameCase(ZX_ERR_INVALID_ARGS); ErrorNameCase(ZX_ERR_BAD_HANDLE); ErrorNameCase(ZX_ERR_WRONG_TYPE); ErrorNameCase(ZX_ERR_BAD_SYSCALL); ErrorNameCase(ZX_ERR_OUT_OF_RANGE); ErrorNameCase(ZX_ERR_BUFFER_TOO_SMALL); ErrorNameCase(ZX_ERR_BAD_STATE); ErrorNameCase(ZX_ERR_TIMED_OUT); ErrorNameCase(ZX_ERR_SHOULD_WAIT); ErrorNameCase(ZX_ERR_CANCELED); ErrorNameCase(ZX_ERR_PEER_CLOSED); ErrorNameCase(ZX_ERR_NOT_FOUND); ErrorNameCase(ZX_ERR_ALREADY_EXISTS); ErrorNameCase(ZX_ERR_ALREADY_BOUND); ErrorNameCase(ZX_ERR_UNAVAILABLE); ErrorNameCase(ZX_ERR_ACCESS_DENIED); ErrorNameCase(ZX_ERR_IO); ErrorNameCase(ZX_ERR_IO_REFUSED); ErrorNameCase(ZX_ERR_IO_DATA_INTEGRITY); ErrorNameCase(ZX_ERR_IO_DATA_LOSS); ErrorNameCase(ZX_ERR_IO_NOT_PRESENT); ErrorNameCase(ZX_ERR_IO_OVERRUN); ErrorNameCase(ZX_ERR_IO_MISSED_DEADLINE); ErrorNameCase(ZX_ERR_IO_INVALID); ErrorNameCase(ZX_ERR_BAD_PATH); ErrorNameCase(ZX_ERR_NOT_DIR); ErrorNameCase(ZX_ERR_NOT_FILE); ErrorNameCase(ZX_ERR_FILE_BIG); ErrorNameCase(ZX_ERR_NO_SPACE); ErrorNameCase(ZX_ERR_NOT_EMPTY); ErrorNameCase(ZX_ERR_STOP); ErrorNameCase(ZX_ERR_NEXT); ErrorNameCase(ZX_ERR_ASYNC); ErrorNameCase(ZX_ERR_PROTOCOL_NOT_SUPPORTED); ErrorNameCase(ZX_ERR_ADDRESS_UNREACHABLE); ErrorNameCase(ZX_ERR_ADDRESS_IN_USE); ErrorNameCase(ZX_ERR_NOT_CONNECTED); ErrorNameCase(ZX_ERR_CONNECTION_REFUSED); ErrorNameCase(ZX_ERR_CONNECTION_RESET); ErrorNameCase(ZX_ERR_CONNECTION_ABORTED); default: os << "errno=" << error_code; return; } } // Helper function to convert a vector of bytes to a T. template <typename T> T GetValueFromBytes(const std::vector<uint8_t>& bytes, size_t offset) { T ret = 0; for (size_t i = 0; (i < sizeof(ret)) && (offset < bytes.size()); i++) { ret |= ((uint64_t)(bytes[offset++])) << (i * 8); } return ret; } uint64_t GetRegisterValue(const std::vector<zxdb::Register>& general_registers, const debug_ipc::RegisterID register_id) { for (const auto& reg : general_registers) { if (reg.id() == register_id) { return GetValueFromBytes<uint64_t>(reg.data(), 0); } } return 0; } void MemoryDumpToVector(const zxdb::MemoryDump& dump, std::vector<uint8_t>* output_vector) { output_vector->reserve(dump.size()); for (const debug_ipc::MemoryBlock& block : dump.blocks()) { FXL_DCHECK(block.valid); for (size_t offset = 0; offset < block.size; ++offset) { output_vector->push_back(block.data[offset]); } } } void SyscallUse::SyscallDecoded(SyscallDecoder* syscall) { syscall->Destroy(); } void SyscallUse::SyscallDecodingError(const SyscallDecoderError& error, SyscallDecoder* syscall) { FXL_LOG(ERROR) << error.message(); syscall->Destroy(); } void SyscallDecoder::LoadMemory(uint64_t address, size_t size, std::vector<uint8_t>* destination) { if (address == 0) { // Null pointer => don't load anything. return; } ++pending_request_count_; thread_->GetProcess()->ReadMemory( address, size, [this, address, size, destination](const zxdb::Err& err, zxdb::MemoryDump dump) { --pending_request_count_; if (!err.ok()) { Error(SyscallDecoderError::Type::kCantReadMemory) << "Can't load memory at " << address << ": " << err.msg(); } else if ((dump.size() != size) || !dump.AllValid()) { Error(SyscallDecoderError::Type::kCantReadMemory) << "Can't load memory at " << address << ": not enough data"; } else { MemoryDumpToVector(dump, destination); } if (input_arguments_loaded_) { LoadOutputs(); } else { LoadInputs(); } }); } void SyscallDecoder::LoadArgument(int argument_index, size_t size) { if (decoded_arguments_[argument_index].loading()) { return; } decoded_arguments_[argument_index].set_loading(); LoadMemory(Value(argument_index), size, &decoded_arguments_[argument_index].loaded_values()); } void SyscallDecoder::Decode() { static std::vector<debug_ipc::RegisterCategory::Type> types = { debug_ipc::RegisterCategory::Type::kGeneral}; const std::vector<zxdb::Register>& general_registers = thread_->GetStack()[0]->GetGeneralRegisters(); // The order of parameters in the System V AMD64 ABI we use, according to // Wikipedia: static debug_ipc::RegisterID amd64_abi[] = { debug_ipc::RegisterID::kX64_rdi, debug_ipc::RegisterID::kX64_rsi, debug_ipc::RegisterID::kX64_rdx, debug_ipc::RegisterID::kX64_rcx, debug_ipc::RegisterID::kX64_r8, debug_ipc::RegisterID::kX64_r9}; // The order of parameters in the System V AArch64 ABI we use, according to // Wikipedia: static debug_ipc::RegisterID aarch64_abi[] = { debug_ipc::RegisterID::kARMv8_x0, debug_ipc::RegisterID::kARMv8_x1, debug_ipc::RegisterID::kARMv8_x2, debug_ipc::RegisterID::kARMv8_x3, debug_ipc::RegisterID::kARMv8_x4, debug_ipc::RegisterID::kARMv8_x5, debug_ipc::RegisterID::kARMv8_x6, debug_ipc::RegisterID::kARMv8_x7}; debug_ipc::RegisterID* abi; size_t register_count; if (arch_ == debug_ipc::Arch::kX64) { abi = amd64_abi; register_count = sizeof(amd64_abi) / sizeof(debug_ipc::RegisterID); entry_sp_ = GetRegisterValue(general_registers, debug_ipc::RegisterID::kX64_rsp); } else if (arch_ == debug_ipc::Arch::kArm64) { abi = aarch64_abi; register_count = sizeof(aarch64_abi) / sizeof(debug_ipc::RegisterID); entry_sp_ = GetRegisterValue(general_registers, debug_ipc::RegisterID::kARMv8_sp); return_address_ = GetRegisterValue(general_registers, debug_ipc::RegisterID::kARMv8_lr); } else { Error(SyscallDecoderError::Type::kUnknownArchitecture) << "Unknown architecture"; use_->SyscallDecodingError(error_, this); return; } size_t argument_count = syscall_->arguments().size(); decoded_arguments_.reserve(argument_count); register_count = std::min(argument_count, register_count); for (size_t i = 0; i < register_count; i++) { decoded_arguments_.emplace_back(GetRegisterValue(general_registers, abi[i])); } LoadStack(); } void SyscallDecoder::LoadStack() { size_t stack_size = (syscall_->arguments().size() - decoded_arguments_.size()) * sizeof(uint64_t); if (arch_ == debug_ipc::Arch::kX64) { stack_size += sizeof(uint64_t); } if (stack_size == 0) { LoadInputs(); return; } uint64_t address = entry_sp_; ++pending_request_count_; thread_->GetProcess()->ReadMemory( address, stack_size, [this, address, stack_size](const zxdb::Err& err, zxdb::MemoryDump dump) { --pending_request_count_; if (!err.ok()) { Error(SyscallDecoderError::Type::kCantReadMemory) << "Can't load stack at " << address << ": " << err.msg(); } else if ((dump.size() != stack_size) || !dump.AllValid()) { Error(SyscallDecoderError::Type::kCantReadMemory) << "Can't load stack at " << address << ": not enough data"; } else { std::vector<uint8_t> data; MemoryDumpToVector(dump, &data); size_t offset = 0; if (arch_ == debug_ipc::Arch::kX64) { return_address_ = GetValueFromBytes<uint64_t>(data, 0); offset += sizeof(uint64_t); } while (offset < data.size()) { decoded_arguments_.emplace_back(GetValueFromBytes<uint64_t>(data, offset)); offset += sizeof(uint64_t); } } LoadInputs(); }); } void SyscallDecoder::LoadInputs() { if (error_.type() != SyscallDecoderError::Type::kNone) { if (pending_request_count_ == 0) { use_->SyscallDecodingError(error_, this); } return; } for (const auto& input : syscall_->inputs()) { input->Load(this); } if (pending_request_count_ > 0) { return; } input_arguments_loaded_ = true; if (error_.type() != SyscallDecoderError::Type::kNone) { use_->SyscallDecodingError(error_, this); } else { StepToReturnAddress(); } } void SyscallDecoder::StepToReturnAddress() { zxdb::BreakpointSettings settings; settings.enabled = true; settings.stop_mode = zxdb::BreakpointSettings::StopMode::kThread; settings.type = debug_ipc::BreakpointType::kSoftware; settings.location.address = return_address_; settings.location.type = zxdb::InputLocation::Type::kAddress; settings.scope = zxdb::BreakpointSettings::Scope::kThread; settings.scope_thread = thread_.get(); settings.scope_target = thread_->GetProcess()->GetTarget(); settings.one_shot = true; thread_observer_->CreateNewBreakpoint(settings); // Registers a one time breakpoint for this decoder. thread_observer_->Register(thread_->GetKoid(), this); // Restarts the stopped thread. When the breakpoint will be reached (at the // end of the syscall), LoadSyscallReturnValue will be called. thread_->Continue(); } void SyscallDecoder::LoadSyscallReturnValue() { const std::vector<zxdb::Register>& general_registers = thread_->GetStack()[0]->GetGeneralRegisters(); debug_ipc::RegisterID result_register = (arch_ == debug_ipc::Arch::kX64) ? debug_ipc::RegisterID::kX64_rax : debug_ipc::RegisterID::kARMv8_x0; syscall_return_value_ = GetRegisterValue(general_registers, result_register); LoadOutputs(); } void SyscallDecoder::LoadOutputs() { if (error_.type() != SyscallDecoderError::Type::kNone) { if (pending_request_count_ == 0) { use_->SyscallDecodingError(error_, this); } return; } for (const auto& output : syscall_->outputs()) { if (output->error_code() == static_cast<zx_status_t>(syscall_return_value_)) { output->Load(this); } } if (pending_request_count_ > 0) { return; } if (error_.type() != SyscallDecoderError::Type::kNone) { use_->SyscallDecodingError(error_, this); } else { DecodeAndDisplay(); } } void SyscallDecoder::DecodeAndDisplay() { if (pending_request_count_ > 0) { return; } use_->SyscallDecoded(this); } void SyscallDecoder::Destroy() { dispatcher_->DeleteDecoder(this); } void SyscallDisplay::SyscallDecoded(SyscallDecoder* syscall) { os_ << '\n'; const Colors& colors = dispatcher_->colors(); // Displays the header and the inline input arguments. os_ << syscall->thread()->GetProcess()->GetName() << ' ' << colors.red << syscall->thread()->GetProcess()->GetKoid() << colors.reset << ':' << colors.red << syscall->thread_id() << colors.reset << ' ' << syscall->syscall()->name() << '('; const char* separator = ""; for (const auto& input : syscall->syscall()->inputs()) { separator = input->DisplayInline(dispatcher_, syscall, separator, os_); } os_ << ")\n"; // Displays the outline input arguments. for (const auto& input : syscall->syscall()->inputs()) { input->DisplayOutline(dispatcher_, syscall, /*tabs=*/1, os_); } // Displays the returned value. os_ << " -> "; if (static_cast<zx_status_t>(syscall->syscall_return_value()) == ZX_OK) { os_ << colors.green << "ZX_OK" << colors.reset; } else { os_ << colors.red; ErrorName(static_cast<zx_status_t>(syscall->syscall_return_value()), os_); os_ << colors.reset; } // And the inline output arguments (if any). separator = " ("; for (const auto& output : syscall->syscall()->outputs()) { if (output->error_code() == static_cast<zx_status_t>(syscall->syscall_return_value())) { separator = output->DisplayInline(dispatcher_, syscall, separator, os_); } } if (std::string(" (") != separator) { os_ << ')'; } os_ << '\n'; // Displays the outline output arguments. for (const auto& output : syscall->syscall()->outputs()) { if (output->error_code() == static_cast<zx_status_t>(syscall->syscall_return_value())) { output->DisplayOutline(dispatcher_, syscall, /*tabs=*/2, os_); } } // Now our job is done, we can destroy the object. syscall->Destroy(); } void SyscallDisplay::SyscallDecodingError(const SyscallDecoderError& error, SyscallDecoder* syscall) { std::string message = error.message(); size_t pos = 0; for (;;) { size_t end = message.find('\n', pos); const Colors& colors = dispatcher_->colors(); os_ << syscall->thread()->GetProcess()->GetName() << ' ' << colors.red << syscall->thread()->GetProcess()->GetKoid() << colors.reset << ':' << colors.red << syscall->thread_id() << colors.reset << ' ' << syscall->syscall()->name() << ": " << colors.red << error.message().substr(pos, end) << colors.reset << '\n'; if (end == std::string::npos) { break; } pos = end + 1; } os_ << '\n'; syscall->Destroy(); } } // namespace fidlcat
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
8272e6e9200f965e00ee6ac7ace9f6c2fcf00332
ce76319fc3c4294f83a5f13b48e8007bb5b1d179
/Basket.h
e81b8e6248a207c077d2859112883cce7a4b55e7
[]
no_license
flappyZeng/C-plus-plus-Learning
80d6526b856a1e35447dfee2035552afcffe7a65
f5e51596448f3941f2ac1afa80619f919041d74b
refs/heads/master
2023-03-28T23:10:46.069448
2021-03-25T13:07:08
2021-03-25T14:07:07
342,803,754
0
0
null
null
null
null
UTF-8
C++
false
false
663
h
#pragma once #include<memory> #include<set> #include"quote.h" class cmp { public: bool operator()(const std::shared_ptr<Quote>& lhs, const std::shared_ptr<Quote>& rhs) { return lhs->isbn() < rhs->isbn(); } }; class Basket{ public: void add_item(const std::shared_ptr<Quote>& sale) { items.insert(sale); } void add_item(const Quote& sale); void add_item(const Quote&& sale); double total_receipt(std::ostream& os) const; private: using spQ = std::shared_ptr<Quote>; static bool compare(std::shared_ptr<Quote> a, std::shared_ptr<Quote> b) { return a->isbn() < b->isbn(); } std::multiset<std::shared_ptr<Quote>, decltype(compare)*>items{compare}; };
[ "962990169@qq.com" ]
962990169@qq.com
d2d0f0a65fe9dbeb4c1d197c19c4b7aed7b53e38
9c5ed15b94f72a1c8d61cdc4d817ef41ea0e4edd
/2016/January-June/perle/main.cpp
4524fd65f40194e6e72ffc6c03944d70b6265672
[]
no_license
caprariuap/infoarena
6a2e74aa61472b4f9d429ad03710726d60856324
a3a740d2c179f21b7177e5422072dfa61033437e
refs/heads/master
2020-04-04T21:28:32.588930
2018-11-05T22:14:52
2018-11-05T22:14:52
156,287,370
2
1
null
null
null
null
UTF-8
C++
false
false
810
cpp
#include <fstream> using namespace std; ifstream fin("perle.in"); ofstream fout("perle.out"); int n,a[10001],i; int mutareC(int k); int mutareB(int k); int mutareB(int k) { if (k+1<=a[0]) if (a[k]==2) return mutareB(k+1); if (k+4<=a[0]) if (a[k+2]==3&&a[k]==1) return mutareC(k+4); return a[0]+2; } int mutareC(int k) { if (k+2<=a[0]) if (a[k]==3) return mutareC(mutareB(k+1)); if (k+2<=a[0]) if (a[k]==1&&a[k+1]==2) return k+3; if (k<=a[0]) if (a[k]==2) return k+1; return a[0]+2; } int main() { fin>>n; for (i=1; i<=n; i++) { fin>>a[0]; for (int j=1; j<=a[0]; j++) fin>>a[j]; if (a[0]==1||mutareB(1)==a[0]+1||mutareC(1)==a[0]+1) fout<<'1'; else fout<<'0'; fout<<'\n'; } }
[ "caprariu.ap@gmail.com" ]
caprariu.ap@gmail.com
f36894c5b6eb66be49b7dfd12f804ceab8b2c91b
635c344550534c100e0a86ab318905734c95390d
/wpilibc/src/test/native/cpp/SolenoidTestREV.cpp
75ea261e6895c6188c588f5e32dece05ed281eb7
[ "BSD-3-Clause" ]
permissive
wpilibsuite/allwpilib
2435cd2f5c16fb5431afe158a5b8fd84da62da24
8f3d6a1d4b1713693abc888ded06023cab3cab3a
refs/heads/main
2023-08-23T21:04:26.896972
2023-08-23T17:47:32
2023-08-23T17:47:32
24,655,143
986
769
NOASSERTION
2023-09-14T03:51:22
2014-09-30T20:51:33
C++
UTF-8
C++
false
false
1,491
cpp
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include <hal/HAL.h> #include "frc/DoubleSolenoid.h" #include "frc/PneumaticsControlModule.h" #include "frc/Solenoid.h" #include "gtest/gtest.h" namespace frc { TEST(SolenoidREVTest, ValidInitialization) { Solenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2}; EXPECT_EQ(2, solenoid.GetChannel()); solenoid.Set(true); EXPECT_TRUE(solenoid.Get()); solenoid.Set(false); EXPECT_FALSE(solenoid.Get()); } TEST(SolenoidREVTest, DoubleInitialization) { Solenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2}; EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::REVPH, 2), std::runtime_error); } TEST(SolenoidREVTest, DoubleInitializationFromDoubleSolenoid) { DoubleSolenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2, 3}; EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::REVPH, 2), std::runtime_error); } TEST(SolenoidREVTest, InvalidChannel) { EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::REVPH, 100), std::runtime_error); } TEST(SolenoidREVTest, Toggle) { Solenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2}; solenoid.Set(true); EXPECT_TRUE(solenoid.Get()); solenoid.Toggle(); EXPECT_FALSE(solenoid.Get()); solenoid.Toggle(); EXPECT_TRUE(solenoid.Get()); } } // namespace frc
[ "noreply@github.com" ]
wpilibsuite.noreply@github.com
67eab7d5b9a819317cd4e70b60d08a076acaef2a
28476e6f67b37670a87bfaed30fbeabaa5f773a2
/src/AutumnGen/src/Configuration.h
9869b03ead1385479c656d67c51dbac779da4708
[]
no_license
rdmenezes/autumnframework
d1aeb657cd470b67616dfcf0aacdb173ac1e96e1
d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d
refs/heads/master
2021-01-20T13:48:52.187425
2008-07-17T18:25:19
2008-07-17T18:25:19
32,969,073
1
1
null
null
null
null
UTF-8
C++
false
false
1,742
h
/* * Copyright 2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AUTUMNGEN_CONFIGURATION_H #define AUTUMNGEN_CONFIGURATION_H #include <string> #include <map> using namespace std; class Configuration{ /** * suffix of wrapper class name, like _Wrapper. * This must be consistent with Autumn framework, user can't set it. */ static string ClassWrapperSuffix; /** suffix of wrapper file name, like _Wrapper */ static string FileWrapperSuffix; /** suffix of head file, like .h, .hh, etc */ static string HeadFileSuffix; /** suffix of implementation file, like .cpp, .cc, etc */ static string ImplFileSuffix; /** out put path to generated file */ static string OutPath; public: static void setConfigs(map<string, string>& cons); static string getCWS() { return Configuration::ClassWrapperSuffix; } static string getFWS(){ return Configuration::FileWrapperSuffix; } static string getHFS(){ return Configuration::HeadFileSuffix; } static string getIFS(){ return Configuration::ImplFileSuffix; } static string getOutPath(){ return Configuration::OutPath; } }; #endif
[ "sharplog@c16174ff-a625-0410-88e5-87db5789ed7d" ]
sharplog@c16174ff-a625-0410-88e5-87db5789ed7d
113e3cee2d6e9df63fc5dee0480ff016b7334aa9
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/orbsvcs/orbsvcs/LoadBalancing/LB_ServerRequestInterceptor.h
cb95039e570ddf8f2d49626407b2b12a3a00a7b5
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
2,469
h
// -*- C++ -*- //============================================================================= /** * @file LB_ServerRequestInterceptor.h * * @author Ossama Othman <ossama@uci.edu> */ //============================================================================= #ifndef TAO_LB_SERVER_REQUEST_INTERCEPTOR_H #define TAO_LB_SERVER_REQUEST_INTERCEPTOR_H #include /**/ "ace/pre.h" #include "ace/config-all.h" #include "orbsvcs/LoadBalancing/LoadBalancing_export.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "tao/PI_Server/PI_Server.h" #include "tao/PortableInterceptorC.h" #include "tao/LocalObject.h" #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4250) #endif /* _MSC_VER */ TAO_BEGIN_VERSIONED_NAMESPACE_DECL class TAO_LB_LoadAlert; /** * @class TAO_LB_ServerRequestInterceptor * * @brief ServerRequestInterceptor that interacts with the TAO-shipped * LoadAlert implementation. * * This ServerRequestInterceptor is responsible for redirecting * requests back to the LoadManager. */ class TAO_LoadBalancing_Export TAO_LB_ServerRequestInterceptor : public virtual PortableInterceptor::ServerRequestInterceptor, public virtual ::CORBA::LocalObject { public: /// Constructor. TAO_LB_ServerRequestInterceptor (TAO_LB_LoadAlert & load_alert); /** * @name Methods Required by the ServerRequestInterceptor * Interface * * These are the canonical methods required for all * ServerRequestInterceptors. */ //@{ virtual char * name (void); virtual void destroy (void); virtual void receive_request_service_contexts ( PortableInterceptor::ServerRequestInfo_ptr ri); virtual void receive_request ( PortableInterceptor::ServerRequestInfo_ptr ri); virtual void send_reply ( PortableInterceptor::ServerRequestInfo_ptr ri); virtual void send_exception ( PortableInterceptor::ServerRequestInfo_ptr ri); virtual void send_other ( PortableInterceptor::ServerRequestInfo_ptr ri); //@} protected: /// Destructor. /** * Protected destructor to enforce correct memory management via * reference counting. */ ~TAO_LB_ServerRequestInterceptor (void); private: TAO_LB_LoadAlert & load_alert_; }; TAO_END_VERSIONED_NAMESPACE_DECL #if defined(_MSC_VER) #pragma warning(pop) #endif /* _MSC_VER */ #include /**/ "ace/post.h" #endif /* TAO_LB_SERVER_REQUEST_INTERCEPTOR_H */
[ "lihuibin705@163.com" ]
lihuibin705@163.com
6bed5c12629a4f9a0789f80d7dfc5351bb1bb3ce
c2871061140d04152a5e05be0cdc4d3f3967064f
/src/kinematics/Transformation.h
35a911c362fcea21db353b2d48282e6a140f0f65
[]
no_license
yutingye/RTQL8
b987baf40aee5a6aaf3e7a2e7d909a8b95ae7193
755e099edb8df8335f6c5260b89226fc773095de
refs/heads/master
2021-01-18T14:15:55.872140
2013-09-11T08:49:09
2013-09-11T08:49:09
12,529,202
2
0
null
null
null
null
UTF-8
C++
false
false
5,374
h
/* RTQL8, Copyright (c) 2011, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Sumit Jain <sumitj83@gmail.com>, Sehoon Ha <sehoon.ha@gmail.com> * Georgia Tech Graphics Lab * * This file is provided under the following "BSD-style" License: * 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 code incorporates portions of Open Dynamics Engine * (Copyright (c) 2001-2004, Russell L. Smith. All rights * reserved.) and portions of FCL (Copyright (c) 2011, Willow * Garage, Inc. All rights reserved.), which were released under * the same BSD license as below * * 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. */ #ifndef KINEMATICS_TRANSFORMATION_H #define KINEMATICS_TRANSFORMATION_H #include <vector> #include <Eigen/Dense> #include <Eigen/Geometry> #include "renderer/RenderInterface.h" namespace rtql8 { namespace kinematics { #define MAX_TRANSFORMATION_NAME 182 class Joint; class Dof; enum AxisType{ A_X=0, A_Y=1, A_Z=2 }; class Transformation { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW enum TransFormType { T_ROTATEX, T_ROTATEY, T_ROTATEZ, T_ROTATEEXPMAP, T_ROTATEEXPMAP2, T_ROTATEQUAT, T_TRANSLATE, T_TRANSLATEX, T_TRANSLATEY, T_TRANSLATEZ }; public: Transformation(); virtual ~Transformation(); inline TransFormType getType() const { return mType; } inline char* getName() { return mName; } inline int getSkelIndex() const { return mSkelIndex; } inline void setSkelIndex(int _idx) { mSkelIndex = _idx; } inline Joint* getJoint() const { return mJoint; } inline void setJoint(Joint *_joint) { mJoint = _joint; } inline int getNumDofs() const { return mDofs.size(); } inline Dof* getDof(int i) const { return mDofs[i]; } inline bool getVariable() const { return mVariable; } inline void setVariable(bool _var) { mVariable = _var; } inline void setDirty() { mDirty = true; } Eigen::Matrix4d getTransform(); bool isPresent(const Dof *d) const; // true if d is present in the dof list virtual Eigen::Matrix4d getInvTransform(); virtual void applyTransform(Eigen::Vector3d& _v); virtual void applyTransform(Eigen::Matrix4d& _m); virtual void applyInvTransform(Eigen::Vector3d& _v); virtual void applyInvTransform(Eigen::Matrix4d& _m); virtual void applyDeriv(const Dof* _q, Eigen::Vector3d& _v); virtual void applyDeriv(const Dof* _q, Eigen::Matrix4d& _m); virtual void applySecondDeriv(const Dof* _q1, const Dof* _q2, Eigen::Vector3d& _v); virtual void applySecondDeriv(const Dof* _q1, const Dof* _q2, Eigen::Matrix4d& _m); virtual void applyGLTransform(renderer::RenderInterface* _ri) const = 0; // apply transform in GL virtual void computeTransform() = 0; // computes and stores in above virtual Eigen::Matrix4d getDeriv(const Dof *_q) = 0; // get derivative wrt to a dof virtual Eigen::Matrix4d getSecondDeriv(const Dof *_q1, const Dof *_q2) = 0; // get derivative wrt to 2 dofs present in a transformation protected: std::vector<Dof *> mDofs; // collection of Dofs TransFormType mType; int mSkelIndex; // position in the model transform vector char mName[MAX_TRANSFORMATION_NAME]; Joint *mJoint; // Transformation associated with bool mVariable; // true when it is a variable and included int he model Eigen::Matrix4d mTransform; // transformation matrix will be stored here bool mDirty; }; } // namespace kinematics } // namespace rtql8 #endif // #ifndef KINEMATICS_TRANSFORMATION_H
[ "yuting@gatech.edu" ]
yuting@gatech.edu
a77ec1da3dc24378c1ffaaa6cf8bf60e68abb67b
6d07e19cb66c427f7913a1f75de218d6adca1e74
/src/image.cc
6571152f2c094e77876749a41c8299e9e31d4bd9
[ "MIT" ]
permissive
unclearness/ugu
81c38186caf7266f1848bd7047ed4dbf686b5d95
adcd13480c3179b6da213f15bc6e57590586a09a
refs/heads/develop
2023-08-12T05:38:25.457326
2023-07-30T11:54:54
2023-07-30T11:54:54
211,345,214
34
4
MIT
2023-03-04T10:34:02
2019-09-27T15:07:03
C++
UTF-8
C++
false
false
2,129
cc
/* * Copyright (C) 2022, unclearness * All rights reserved. */ #include "ugu/image.h" namespace ugu { #ifdef UGU_USE_OPENCV #else int GetBitsFromCvType(int cv_type) { int cv_depth = CV_MAT_DEPTH(cv_type); if (cv_depth < 0) { throw std::runtime_error(""); } if (cv_depth <= CV_8S) { return 8; } else if (cv_depth <= CV_16S) { return 16; } else if (cv_depth <= CV_32S) { return 32; } else if (cv_depth <= CV_32F) { return 32; } else if (cv_depth <= CV_64F) { return 64; } else if (cv_depth <= CV_16F) { return 16; } throw std::runtime_error(""); } const std::type_info& GetTypeidFromCvType(int cv_type) { int cv_depth = CV_MAT_DEPTH(cv_type); if (cv_depth < CV_8S) { return typeid(uint8_t); } else if (cv_depth < CV_16U) { return typeid(int8_t); } else if (cv_depth < CV_16S) { return typeid(uint16_t); } else if (cv_depth < CV_32S) { return typeid(int16_t); } else if (cv_depth < CV_32F) { return typeid(int32_t); } else if (cv_depth < CV_64F) { return typeid(float); } else if (cv_depth < CV_16F) { return typeid(double); } throw std::runtime_error(""); } size_t SizeInBytes(const ImageBase& mat) { // https://stackoverflow.com/questions/26441072/finding-the-size-in-bytes-of-cvmat return size_t(mat.step[0] * mat.rows); } InputOutputArray noArray() { static _InputOutputArray no_array; return no_array; } int MakeCvType(const std::type_info* info, int ch) { int code = -1; if (info == &typeid(uint8_t)) { code = CV_MAKETYPE(CV_8U, ch); } else if (info == &typeid(int8_t)) { code = CV_MAKETYPE(CV_8S, ch); } else if (info == &typeid(uint16_t)) { code = CV_MAKETYPE(CV_16U, ch); } else if (info == &typeid(int16_t)) { code = CV_MAKETYPE(CV_16S, ch); } else if (info == &typeid(int32_t)) { code = CV_MAKETYPE(CV_32S, ch); } else if (info == &typeid(float)) { code = CV_MAKETYPE(CV_32F, ch); } else if (info == &typeid(double)) { code = CV_MAKETYPE(CV_64F, ch); } else { throw std::runtime_error("type error"); } return code; } #endif } // namespace ugu
[ "unclearness.dev@gmail.com" ]
unclearness.dev@gmail.com
b0bba6810b588c034b33d39869b5ee967b16020c
c411f2d0d84adbc6562f389cf9cbeeebc0e2034e
/.history/connected_components/twostage_pccl_20180130142334.cpp
b4ffeb5cabfe8aeea9485089c73d9444b896312b
[]
no_license
ajbolous/ParallelComputing
10c0e62d2c383d8d83df80752e159eb5593aa848
097317d850441d117793fa9cacfad354305ab1af
refs/heads/master
2021-09-05T22:52:40.640810
2018-01-31T13:33:30
2018-01-31T13:33:30
119,337,555
0
0
null
null
null
null
UTF-8
C++
false
false
3,088
cpp
#include <stdio.h> #include <stdlib.h> #include <CL/cl.h> #include <opencv2/opencv.hpp> #include "../ocl/ocl_loader.hpp" void linearTwoStage(uchar *image, int width, int height) { printf("width %d, height %d", width, height); int *labeledImage = (int *)malloc(sizeof(int) * width * height); int *labels = (int *)malloc(sizeof(int) * width * height); int counter = 1; int index = 0; for (int i = 0; i < width * height; i++) labels[i] = i; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { index = i * width + j; labeledImage[index] = (int)image[index]; if (labeledImage[index] >= 255) { int label = 0; int upn = 0; int ln = 0; if ((i - 1) >= 0) upn = labeledImage[(i - 1) * width + j]; if ((j - 1) >= 0) ln = labeledImage[i * width + j - 1]; if (upn == 0 && ln == 0) { counter++; labeledImage[index] = counter; } else if (upn == 0) labeledImage[index] = ln; else if (ln == 0) labeledImage[index] = upn; else { if (ln <= upn) { labeledImage[index] = ln; labels[upn] = ln; } else { labeledImage[index] = upn; labels[ln] = upn; } } } } } printf("height: %d, width %d", height, width); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { index = i * width + j; if (image[index] != 0) { image[index] = labels[labeledImage[index]]; } } } } /* 1. read image 2. convert into binary and shape 1920x1080 3. run the sequential algorithm and time it 4. run the parallel algorithm and time it 5. output results * Maybe we do a live video feed with euclid ... */ cv::Mat loadImage() { cv::Mat src = cv::imread("test3.jpg", 1); // load source image cv::Size size(1920, 1080); //the dst image size,e.g.100x100 cv::resize(src, src, size); //resize image cv::Mat gray; cv::cvtColor(src, gray, CV_BGR2GRAY); //perform gray scale conversion. cv::threshold(gray, gray, 127, 255, cv::THRESH_BINARY); cv::namedWindow("Display window", cv::WINDOW_AUTOSIZE); // Create a window for display. imshow("Display window", gray); // Show our image inside it. cv::waitKey(0); return gray; } int main() { OpenClLoader ocl; Kernel *kernel = ocl.load_kernel("pccl.cl", "twoStagePccl"); // char image[HEIGHT][WIDTH]; // size_t globalWorkSize[2] = {WIDTH, HEIGHT}; // size_t localWorkSize[2] = {20, 20}; // int changed = 1; // int width = WIDTH; // int height = HEIGHT; // int *changedPtr = &changed; // kernel->setArg(0, WIDTH * HEIGHT * sizeof(char), image); // kernel->setArg(1, sizeof(int *), &changedPtr); // while (changed) // { // changed = 0; // kernel->execute("ParallelCCL", 2, globalWorkSize, localWorkSize); // } cv::Mat image = loadImage(); linearTwoStage(image.data, 1920, 1080); cv::applyColorMap(image, image, cv::COLORMAP_RAINBOW); cv::namedWindow("Display window", cv::WINDOW_AUTOSIZE); // Create a window for display. imshow("Display window", image); // Show our image inside it. cv::waitKey(0); }
[ "ajbolous@gmail.com" ]
ajbolous@gmail.com
dc28971c643d5d42d42b7308016f28d4ff1fe1ab
f30af6e688cfbe2c97c404ef11e4352294a3ea26
/include/graphics/materials/skybox.h
99768f78680221d74a5a857c06a348b45ebf0c24
[ "MIT" ]
permissive
pjdixit/vxr
19a286d72f05e3a466d6f6b1c637e8dc668bd13f
9b21596dd8447fb6c8a0ff41a7a16a920401946b
refs/heads/master
2020-08-12T09:01:55.626397
2019-04-19T20:41:09
2019-04-19T20:41:09
214,734,046
1
0
MIT
2019-10-13T00:07:41
2019-10-13T00:07:41
null
WINDOWS-1250
C++
false
false
2,147
h
#pragma once // ---------------------------------------------------------------------------------------- // MIT License // // Copyright(c) 2018 Víctor Ávila // // 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 "material.h" #include "material_instance.h" /** * \file skybox.h * * \author Victor Avila (avilapa.github.io) * * \brief Engine default material definitions. * */ namespace vxr { namespace mat { class Skybox : public Material { VXR_OBJECT(Skybox, Material); public: Skybox(); class Instance : public MaterialInstance { VXR_OBJECT(Instance, MaterialInstance); public: Instance(); virtual void onGUI() override; void set_tint(Color color); Color tint() const; void set_color_texture(ref_ptr<Texture> texture); ref_ptr<Texture> color_texture() const; }; }; } /* end of mat namespace */ } /* end of vxr namespace */
[ "victorap97@gmail.com" ]
victorap97@gmail.com
b17aa206b575957762cdd19e2a18618ffd1e170f
bc56aa80d0417b002cb1381e3911ff1d0df40d06
/BbrStdUtils/Collection.hh
2a3fe0956880903cdd0c723d2a5addad4ec74346
[ "Apache-2.0" ]
permissive
brownd1978/FastSim
177d79e8ce7bbd71df6f24295b157a8651962981
05f590d72d8e7f71856fd833114a38b84fc7fd48
refs/heads/master
2023-01-08T07:48:49.843154
2020-11-04T00:52:23
2020-11-04T00:52:23
284,155,237
0
0
null
null
null
null
UTF-8
C++
false
false
222
hh
// Note: this is obsolete. Please do not use it or add to this file. // See BbrCollectionUtils.hh instead. #ifndef BABAR_COLLECTION_HH #define BABAR_COLLECTION_HH #include "BbrStdUtils/BbrCollectionUtils.hh" #endif
[ "dave_brown@lbl.gov" ]
dave_brown@lbl.gov
2d7fa2e327817c89b744047901e552945c7db8aa
aeb49fe4cef963fcff288f35b5da82c000feba09
/BOMARBLE.cpp
37ebf5212724d8c507ffc638d3bf678e3255c6d9
[]
no_license
kanha95/SPOJ-solutions
b5febec31c08a8f0b229ca2578253da81ecfd687
6a6038236eab4e40773fafae142d01678f62d611
refs/heads/master
2020-09-07T07:29:06.760163
2016-03-04T09:16:08
2016-03-04T09:16:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
#include<cstdio> #include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<vector> #include<list> #define ll long long #define ri(T) scanf("%d",&T) #define rl(T) scanf("%lld",&T) #define MOD 1000000007 using namespace std; #include<stdio.h> int main() { ll t,n,p,res; rl(t); while(t) { cout<<(3*t*t+5*t+2)/2<<endl; rl(t); } }
[ "pallesai1995@gmail.com" ]
pallesai1995@gmail.com
55993af5b000fe35aefa5c8d7969587412cc7a80
a2923ac220a9968682b4b71bbe76ef74299bc71a
/laberinto.hpp
408897a64d29fd945186960950bb50d139a801e4
[]
no_license
dmarcob/algoritmo_busqueda_retroceso
1b81d6b9238334d2dbe1700fce12ffbc89c223db
a23d4c8498e688ab9af858044f0dad4f67aa4139
refs/heads/master
2020-05-18T19:57:08.199037
2019-06-29T15:39:10
2019-06-29T15:39:10
184,621,036
0
0
null
null
null
null
UTF-8
C++
false
false
5,574
hpp
//***************************************************************** // File: laberinto.hpp // Author: Programación II. Diego Marco 755232 // Date: March 27, 2019 // Coms: Definición del tipo "Laberinto" para la práctica 3 de la asignatura //***************************************************************** #include <fstream> #include <iostream> using namespace std; // Dimensión máxima de los laberintos const int MAX_DIM = 120; // Posibles valores de las posiciones del laberinto const char LIBRE = ' '; // (espacio en blanco), posición libre const char MURO = '#'; // (almohadilla), posición bloqueada const char CAMINO = '.'; // (punto), camino const char IMPOSIBLE = 'I'; // posición ya visitada que no llevó a solución // Retraso en microsegundos tras mostrar el laberinto const int RETRASO_MOSTRAR = 75000; struct Laberinto{ // Altura en char (número de filas) del laberinto int alto; // Anchura en char (número de columnas) del laberinto int ancho; // Matriz del laberinto // Cada posición puede tomar el valor LIBRE, MURO, CAMINO o IMPOSIBLE char mapa[MAX_DIM][MAX_DIM]; }; //************************************************************************* // AUX1:Encontrar un camino en el laberinto //************************************************************************* // Pre: * "lab" es un laberinto correcto y limpio // * las casillas (1,1) y (lab.alto-2,lab.ancho-2) contienen LIBRE // o CAMINO y se ha marcado con CAMINO las casillas de un camino // que une las casillas (1,1) y (y - 1, x - 1) // Post: busqueda(lab,x,y) = <true> sii, se cumplen las condiciones siguientes: // * en "lab" se ha marcado con CAMINO las casillas de un camino // que une las casillas (1,1) y (lab.alto-2,lab.ancho-2) // * las casillas visitadas que no llevaban a la salida quedan marcadas // como IMPOSIBLE // * el resto de casillas no se han modificado bool busqueda(Laberinto& lab, int x, int y); //************************************************************************* // Encontrar un camino en el laberinto //************************************************************************* // Pre: * "lab" es un laberinto correcto y limpio // * las casillas (1,1) y (lab.alto-2,lab.ancho-2) contienen LIBRE // Post: "encontrado" si, y solo si, se cumplen las condiciones siguientes: // * en "lab" se ha marcado con CAMINO las casillas de un camino // que une las casillas (1,1) y (lab.alto-2,lab.ancho-2) // * las casillas visitadas que no llevaban a la salida quedan marcadas // como IMPOSIBLE // * el resto de casillas no se han modificado void buscarCamino(Laberinto& lab, bool &encontrado); //************************************************************************* // AUX1:Generar el laberinto1 //************************************************************************* void cargarLaberinto(ifstream& f, Laberinto& lab, const int y, const int x, const int columnas ); //************************************************************************* // Generar el laberinto1 //************************************************************************* // Pre: "nombFichero" es el nombre de un fichero que contiene un laberinto // almacenado, correcto // Post: "lab" contiene el laberinto del fichero, almacenado de acuerdo a la // especificación dada para el tipo void cargarLaberinto(const char nombFichero[], Laberinto& lab); //************************************************************************* // Generar el laberinto2 //************************************************************************* //Pre: * 3<=lab.alto, lab.ancho, fila, col <=MAX_DIM // * 0 <= densidad <= 1 //Post: "lab" queda inicializado con un laberinto aleatorio con "nFils" filas // y "nCols" columnas, correcto void generarLaberinto(Laberinto& lab, const double densidad, const int nFils, const int nCols); //************************************************************************* // Visualizar el camino encontrado:ITERATIVO //************************************************************************* // Pre: "lab" es un laberinto correcto // Post: Se ha mostrado el laberinto por la salida estándar // Coms: Versión iterativa void mostrarLaberinto(const Laberinto& lab); //************************************************************************* // Aux1:Visualizar el camino encontrado: RECURSIVO //************************************************************************* void mostrarLaberintoR(const Laberinto& lab,const int y, const int x); //************************************************************************* // Visualizar el camino encontrado:ITERATIVO //************************************************************************* // Pre: "lab" es un laberinto correcto // Post: Se ha mostrado el laberinto por la salida estándar // Coms: Versión recursiva void mostrarLaberintoR(const Laberinto& lab); // Set Attribute Mode <ESC>[{attr1};...;{attrn}m // Sets multiple display attribute settings. The following lists standard attributes: // 0 Reset all attributes // 1 Bright // 2 Dim // 4 Underscore // 5 Blink // 7 Reverse // 8 Hidden // Foreground Colours // 30 Black // 31 Red // 32 Green // 33 Yellow // 34 Blue // 35 Magenta // 36 Cyan // 37 White // Background Colours // 40 Black // 41 Red // 42 Green // 43 Yellow // 44 Blue // 45 Magenta // 46 Cyan // 47 White
[ "755232@unizar.es" ]
755232@unizar.es
ab2a7a3138fe21d6b6bfb836f625ea1a09289a91
606d02e59bf8e13fe12665f1f095faa5f63081e7
/include/spoa/version.hpp
119ebfd4c8d21b261f1ca5d376905e6faab7cc77
[ "MIT" ]
permissive
rvaser/spoa
07d857ed6a890551f3ebab811cdc5cd2f3917821
1ab9ab076171e5e4f5fcd4d2a2369f26c7f8f48f
refs/heads/master
2023-09-01T15:48:25.828243
2023-08-30T12:46:13
2023-08-30T14:06:50
52,782,725
141
51
MIT
2023-08-30T14:06:52
2016-02-29T10:21:20
C++
UTF-8
C++
false
false
201
hpp
// Copyright (c) 2023 Robert Vaser #ifndef SPOA_VERSION_HPP_ #define SPOA_VERSION_HPP_ #include <string> namespace spoa { std::string Version(); } // namespace spoa #endif // SPOA_VERSION_HPP_
[ "robert.vaser@gmail.com" ]
robert.vaser@gmail.com
c7e050c622d41ea70a327f1f976d6c877f11307b
ff598f8c79e302c0c9ecbd513b755f7fa28de424
/src/caffe/util/math_functions.cpp
6c8b1fcb83c9d1d8718206fe5af1a86ef7254b1b
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
GongCheng1919/Quantitative-and-ternary-caffe-for-network-compression
596cdbd2df276f0164b6ad8488f7157d22587a20
a529f00ac51982b2e3eda213edecfda12f922c76
refs/heads/master
2020-03-29T21:02:48.535548
2019-01-16T11:21:13
2019-01-16T11:21:13
150,345,963
1
1
null
null
null
null
UTF-8
C++
false
false
18,831
cpp
#include <boost/math/special_functions/next.hpp> #include <boost/random.hpp> #include <limits> #include "caffe/common.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/rng.hpp" namespace caffe { template<> void caffe_cpu_gemm<float>(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float* A, const float* B, const float beta, float* C) { int lda = (TransA == CblasNoTrans) ? K : M; int ldb = (TransB == CblasNoTrans) ? N : K; cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, N); } template<> void caffe_cpu_gemm<double>(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double* A, const double* B, const double beta, double* C) { int lda = (TransA == CblasNoTrans) ? K : M; int ldb = (TransB == CblasNoTrans) ? N : K; cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, N); } template <> void caffe_cpu_gemv<float>(const CBLAS_TRANSPOSE TransA, const int M, const int N, const float alpha, const float* A, const float* x, const float beta, float* y) { cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1); } template <> void caffe_cpu_gemv<double>(const CBLAS_TRANSPOSE TransA, const int M, const int N, const double alpha, const double* A, const double* x, const double beta, double* y) { cblas_dgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1); } template <> void caffe_axpy<float>(const int N, const float alpha, const float* X, float* Y) { cblas_saxpy(N, alpha, X, 1, Y, 1); } template <> void caffe_axpy<double>(const int N, const double alpha, const double* X, double* Y) { cblas_daxpy(N, alpha, X, 1, Y, 1); } template <typename Dtype> void caffe_set(const int N, const Dtype alpha, Dtype* Y) { if (alpha == 0) { memset(Y, 0, sizeof(Dtype) * N); // NOLINT(caffe/alt_fn) return; } for (int i = 0; i < N; ++i) { Y[i] = alpha; } } template void caffe_set<int>(const int N, const int alpha, int* Y); template void caffe_set<float>(const int N, const float alpha, float* Y); template void caffe_set<double>(const int N, const double alpha, double* Y); template <> void caffe_add_scalar(const int N, const float alpha, float* Y) { for (int i = 0; i < N; ++i) { Y[i] += alpha; } } template <> void caffe_add_scalar(const int N, const double alpha, double* Y) { for (int i = 0; i < N; ++i) { Y[i] += alpha; } } template <typename Dtype> void caffe_copy(const int N, const Dtype* X, Dtype* Y) { if (X != Y) { if (Caffe::mode() == Caffe::GPU) { #ifndef CPU_ONLY // NOLINT_NEXT_LINE(caffe/alt_fn) CUDA_CHECK(cudaMemcpy(Y, X, sizeof(Dtype) * N, cudaMemcpyDefault)); #else NO_GPU; #endif } else { memcpy(Y, X, sizeof(Dtype) * N); // NOLINT(caffe/alt_fn) } } } template void caffe_copy<int>(const int N, const int* X, int* Y); template void caffe_copy<unsigned int>(const int N, const unsigned int* X, unsigned int* Y); template void caffe_copy<float>(const int N, const float* X, float* Y); template void caffe_copy<double>(const int N, const double* X, double* Y); template <> void caffe_scal<float>(const int N, const float alpha, float *X) { cblas_sscal(N, alpha, X, 1); } template <> void caffe_scal<double>(const int N, const double alpha, double *X) { cblas_dscal(N, alpha, X, 1); } template <> void caffe_cpu_axpby<float>(const int N, const float alpha, const float* X, const float beta, float* Y) { cblas_saxpby(N, alpha, X, 1, beta, Y, 1); } template <> void caffe_cpu_axpby<double>(const int N, const double alpha, const double* X, const double beta, double* Y) { cblas_daxpby(N, alpha, X, 1, beta, Y, 1); } template <> void caffe_add<float>(const int n, const float* a, const float* b, float* y) { vsAdd(n, a, b, y); } template <> void caffe_add<double>(const int n, const double* a, const double* b, double* y) { vdAdd(n, a, b, y); } template <> void caffe_sub<float>(const int n, const float* a, const float* b, float* y) { vsSub(n, a, b, y); } template <> void caffe_sub<double>(const int n, const double* a, const double* b, double* y) { vdSub(n, a, b, y); } template <> void caffe_mul<float>(const int n, const float* a, const float* b, float* y) { vsMul(n, a, b, y); } template <> void caffe_mul<double>(const int n, const double* a, const double* b, double* y) { vdMul(n, a, b, y); } template <> void caffe_div<float>(const int n, const float* a, const float* b, float* y) { vsDiv(n, a, b, y); } template <> void caffe_div<double>(const int n, const double* a, const double* b, double* y) { vdDiv(n, a, b, y); } template <> void caffe_powx<float>(const int n, const float* a, const float b, float* y) { vsPowx(n, a, b, y); } template <> void caffe_powx<double>(const int n, const double* a, const double b, double* y) { vdPowx(n, a, b, y); } template <> void caffe_sqr<float>(const int n, const float* a, float* y) { vsSqr(n, a, y); } template <> void caffe_sqr<double>(const int n, const double* a, double* y) { vdSqr(n, a, y); } template <> void caffe_sqrt<float>(const int n, const float* a, float* y) { vsSqrt(n, a, y); } template <> void caffe_sqrt<double>(const int n, const double* a, double* y) { vdSqrt(n, a, y); } template <> void caffe_exp<float>(const int n, const float* a, float* y) { vsExp(n, a, y); } template <> void caffe_exp<double>(const int n, const double* a, double* y) { vdExp(n, a, y); } template <> void caffe_log<float>(const int n, const float* a, float* y) { vsLn(n, a, y); } template <> void caffe_log<double>(const int n, const double* a, double* y) { vdLn(n, a, y); } template <> void caffe_abs<float>(const int n, const float* a, float* y) { vsAbs(n, a, y); } template <> void caffe_abs<double>(const int n, const double* a, double* y) { vdAbs(n, a, y); } unsigned int caffe_rng_rand() { return (*caffe_rng())(); } template <typename Dtype> Dtype caffe_nextafter(const Dtype b) { return boost::math::nextafter<Dtype>( b, std::numeric_limits<Dtype>::max()); } template float caffe_nextafter(const float b); template double caffe_nextafter(const double b); template <typename Dtype> void caffe_rng_uniform(const int n, const Dtype a, const Dtype b, Dtype* r) { CHECK_GE(n, 0); CHECK(r); CHECK_LE(a, b); boost::uniform_real<Dtype> random_distribution(a, caffe_nextafter<Dtype>(b)); boost::variate_generator<caffe::rng_t*, boost::uniform_real<Dtype> > variate_generator(caffe_rng(), random_distribution); for (int i = 0; i < n; ++i) { r[i] = variate_generator(); } } template void caffe_rng_uniform<float>(const int n, const float a, const float b, float* r); template void caffe_rng_uniform<double>(const int n, const double a, const double b, double* r); template <typename Dtype> void caffe_rng_gaussian(const int n, const Dtype a, const Dtype sigma, Dtype* r) { CHECK_GE(n, 0); CHECK(r); CHECK_GT(sigma, 0); boost::normal_distribution<Dtype> random_distribution(a, sigma); boost::variate_generator<caffe::rng_t*, boost::normal_distribution<Dtype> > variate_generator(caffe_rng(), random_distribution); for (int i = 0; i < n; ++i) { r[i] = variate_generator(); } } template void caffe_rng_gaussian<float>(const int n, const float mu, const float sigma, float* r); template void caffe_rng_gaussian<double>(const int n, const double mu, const double sigma, double* r); template <typename Dtype> void caffe_rng_bernoulli(const int n, const Dtype p, int* r) { CHECK_GE(n, 0); CHECK(r); CHECK_GE(p, 0); CHECK_LE(p, 1); boost::bernoulli_distribution<Dtype> random_distribution(p); boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> > variate_generator(caffe_rng(), random_distribution); for (int i = 0; i < n; ++i) { r[i] = variate_generator(); } } template void caffe_rng_bernoulli<double>(const int n, const double p, int* r); template void caffe_rng_bernoulli<float>(const int n, const float p, int* r); template <typename Dtype> void caffe_rng_bernoulli(const int n, const Dtype p, unsigned int* r) { CHECK_GE(n, 0); CHECK(r); CHECK_GE(p, 0); CHECK_LE(p, 1); boost::bernoulli_distribution<Dtype> random_distribution(p); boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> > variate_generator(caffe_rng(), random_distribution); for (int i = 0; i < n; ++i) { r[i] = static_cast<unsigned int>(variate_generator()); } } template void caffe_rng_bernoulli<double>(const int n, const double p, unsigned int* r); template void caffe_rng_bernoulli<float>(const int n, const float p, unsigned int* r); template <> float caffe_cpu_strided_dot<float>(const int n, const float* x, const int incx, const float* y, const int incy) { return cblas_sdot(n, x, incx, y, incy); } template <> double caffe_cpu_strided_dot<double>(const int n, const double* x, const int incx, const double* y, const int incy) { return cblas_ddot(n, x, incx, y, incy); } template <typename Dtype> Dtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y) { return caffe_cpu_strided_dot(n, x, 1, y, 1); } template float caffe_cpu_dot<float>(const int n, const float* x, const float* y); template double caffe_cpu_dot<double>(const int n, const double* x, const double* y); template <> float caffe_cpu_asum<float>(const int n, const float* x) { return cblas_sasum(n, x, 1); } template <> double caffe_cpu_asum<double>(const int n, const double* x) { return cblas_dasum(n, x, 1); } template <> void caffe_cpu_scale<int>(const int n, const int alpha, const int *x, int* y) { } template <> void caffe_cpu_scale<unsigned>(const int n, const unsigned alpha, const unsigned *x, unsigned* y) { } template <> void caffe_cpu_scale<float>(const int n, const float alpha, const float *x, float* y) { cblas_scopy(n, x, 1, y, 1); cblas_sscal(n, alpha, y, 1); } template <> void caffe_cpu_scale<double>(const int n, const double alpha, const double *x, double* y) { cblas_dcopy(n, x, 1, y, 1); cblas_dscal(n, alpha, y, 1); } template<> void caffe_cpu_ternary<int>(const int N, const int delta, const int* X, int* Y,int* alpha){} template<> void caffe_cpu_ternary<unsigned>(const int N, const unsigned delta, const unsigned* X, unsigned* Y,unsigned* alpha){} template<> void caffe_cpu_ternary<float>(const int N, const float delta, const float* X, float* Y,float* alpha){ float alpha_tmp=0; int num=0; for(int i=0; i<N; i++){ float x = X[i]; Y[i] = (x>delta) - (x<-delta); alpha_tmp+=Y[i]*x; num+=Y[i]*Y[i]; } if(num==0){ *alpha=0; return; } *alpha=alpha_tmp/num; } template<> void caffe_cpu_ternary<double>(const int N, const double delta, const double* X, double* Y,double* alpha){ double alpha_tmp=0; int num=0; for(int i=0; i<N; i++){ double x = X[i]; Y[i] = (x>delta) - (x<-delta); alpha_tmp+=Y[i]*x; num+=Y[i]*Y[i]; } if(num==0){ *alpha=0; return; } *alpha=alpha_tmp/num; } template<> void caffe_cpu_quantizea<int>(const int count, const int* X, int* Y, int* fixed_point, int max_bits, bool calc_fixed_point){} template<> void caffe_cpu_quantizea<unsigned>(const int count, const unsigned* X, unsigned* Y, int* fixed_point, int max_bits, bool calc_fixed_point){} template<> void caffe_cpu_quantizea<float>(const int count, const float* X, float* Y, int* fixed_point, int max_bits, bool calc_fixed_point){ if(calc_fixed_point){ float max_n = fabsf(X[0]); for (int i = 1; i < count; i++){ const float absx = fabsf(X[i]); //if (absx < min_n){ min_n = absx; } if (absx >max_n){ max_n = absx; } } if (max_n == 0){ *fixed_point = 0; }else{ *fixed_point = floor(log2(max_n)) - (max_bits - 1); } } //std::cout<<",X[0]="<<X[0]<<",fabsf X[0]="<<fabsf(X[0])<<",max_n="<<max_n<<std::endl; const float max_num = pow(2, max_bits); const float min_num = -max_num; const float fixed_value = pow(2, *fixed_point); //生成随机数,用于随机化量化 boost::uniform_real<float> random_distribution(-0.5, caffe_nextafter<float>(0.5)); boost::variate_generator<caffe::rng_t*, boost::uniform_real<float> > variate_generator(caffe_rng(), random_distribution); //for (int i = 0; i < n; ++i) { //r[i] = variate_generator(); //} for (int i = 0; i < count; i++){ float x_q = X[i] / fixed_value; float randN=variate_generator(); x_q+=randN; x_q = (x_q > 0.0) ? floor(x_q + 0.5) : ceil(x_q - 0.5); if (x_q >= max_num) { Y[i]= max_num - 1; }else if(x_q <= min_num){ Y[i]= min_num + 1; }else { Y[i] = x_q;} } } template<> void caffe_cpu_quantizea<double>(const int count, const double* X, double* Y, int* fixed_point, int max_bits, bool calc_fixed_point){ if(calc_fixed_point){ double max_n = fabs(X[0]); for (int i = 1; i < count; i++){ const double absx = fabs(X[i]); //if (absx < min_n){ min_n = absx; } if (absx >max_n){ max_n = absx; } } if (max_n == 0){ *fixed_point = 0; }else{ *fixed_point = floor(log2(max_n)) - (max_bits - 1); } } const double max_num = pow(2, max_bits); const double min_num = -max_num; const double fixed_value = pow(2, *fixed_point); //生成随机数,用于随机化量化 boost::uniform_real<double> random_distribution(-0.5, caffe_nextafter<double>(0.5)); boost::variate_generator<caffe::rng_t*, boost::uniform_real<double> > variate_generator(caffe_rng(), random_distribution); for (int i = 0; i < count; i++){ double x_q = X[i] / fixed_value; double randN=variate_generator(); x_q+=randN; //round x_q = (x_q > 0.0) ? floor(x_q + 0.5) : ceil(x_q - 0.5); if (x_q >= max_num) { Y[i]= max_num - 1; }else if(x_q <= min_num){ Y[i]= min_num + 1; }else { Y[i] = x_q;} } } //quantization——planb template<> void caffe_cpu_quantizeb<int>(const int count, int* X, int max_bits){} template<> void caffe_cpu_quantizeb<unsigned>(const int count, unsigned* X, int max_bits){} template<> void caffe_cpu_quantizeb<float>(const int count, float* X, int max_bits){ //实现剪切 float max_pos=(float)pow(2,max_bits-1)-1; float max_neg=-(float)pow(2,max_bits-1); for(int i=0;i<count;i++){ //std::cout<<"value="<<X[i]<<",max_pos="<<max_pos<<",max_neg="<<max_neg<<std::endl; if(X[i]>max_pos){ X[i]=max_pos; } if(X[i]<max_neg){ X[i]=max_neg; } } } template<> void caffe_cpu_quantizeb<double>(const int count, double* X, int max_bits){ //实现剪切 double max_pos=(double)pow(2,max_bits-1)-1; double max_neg=-(double)pow(2,max_bits-1); for(int i=0;i<count;i++){ //std::cout<<"value="<<X[i]<<",max_pos="<<max_pos<<",max_neg="<<max_neg<<std::endl; if(X[i]>max_pos){ X[i]=max_pos; } if(X[i]<max_neg){ X[i]=max_neg; } } } //scale clip template<> void caffe_cpu_quantizec<int>(const int count, int* X, int max_bits){} template<> void caffe_cpu_quantizec<unsigned>(const int count, unsigned* X, int max_bits){} template<> void caffe_cpu_quantizec<float>(const int count, float* X, int max_bits){ //首先找到最大值,进行缩放,缩放到[-127,127]之间(-128不能取到) float max_n = fabsf(X[0]); for (int i = 1; i < count; i++){ const float absx = X[i]>=0?X[i]:-X[i]; //if (absx < min_n){ min_n = absx; } if (absx >max_n){ max_n = absx; } } //scale:scaler=127/max_n; float dst_range=(float)pow(2,max_bits-1)-1; float scaler=dst_range/max_n; caffe_cpu_scale(count, scaler, X, X); //量化为整型 for (int i = 0; i < count; i++){ X[i] = (X[i] > 0.0) ? floor(X[i] + 0.5) : ceil(X[i] - 0.5); } } template<> void caffe_cpu_quantizec<double>(const int count, double* X, int max_bits){ //首先找到最大值,进行缩放,缩放到[-127,127]之间(-128不能取到) double max_n = fabsf(X[0]); for (int i = 1; i < count; i++){ const double absx = X[i]>=0?X[i]:-X[i]; //if (absx < min_n){ min_n = absx; } if (absx >max_n){ max_n = absx; } } //scale:scaler=127/max_n; double dst_range=(double)pow(2,max_bits-1)-1; double scaler=dst_range/max_n; caffe_cpu_scale(count, scaler, X, X); //量化为整型 for (int i = 0; i < count; i++){ X[i] = (X[i] > 0.0) ? floor(X[i] + 0.5) : ceil(X[i] - 0.5); } } //ulq //ULQ:Q=Round( Clip ((F-delta)*alpha+0.5))#alpha=1/alpha,此处是为了避免除法 // [1-2^(k-1),2^(k-1)] template<> void caffe_cpu_ulq<int>(const int count, const int mean_old, const int sigma_old,const int* X, int* Y, int max_bits){} template<> void caffe_cpu_ulq<unsigned>(const int count, const unsigned mean_old, const unsigned sigma_old,const unsigned* X, unsigned* Y, int max_bits){} template<> void caffe_cpu_ulq<float>(const int count, const float mean_old, const float sigma_old,const float* X, float* Y, int max_bits){ float mins=1-pow(2,max_bits-1); float maxs=pow(2,max_bits-1); for(int i=0;i<count;i++){ //scale Y[i]=(X[i]-mean_old)*sigma_old+0.5; //clip if(Y[i]>maxs){Y[i]=maxs;} if(Y[i]<mins){Y[i]=mins;} //round Y[i]=(Y[i] > 0.0) ? floor(Y[i] + 0.5) : ceil(Y[i] - 0.5); //还原为相同的range,以进行前向传播 Y[i]=((Y[i]-0.5)/sigma_old)+mean_old; } } template<> void caffe_cpu_ulq<double>(const int count, const double mean_old, const double sigma_old,const double* X, double* Y, int max_bits){} //meanstd template<> void caffe_cpu_meanstd<int>(const int count, const int* X, int& mean, int& std){} template<> void caffe_cpu_meanstd<unsigned>(const int count, const unsigned* X, unsigned& mean, unsigned& std){} template<> void caffe_cpu_meanstd<float>(const int count, const float* X, float& mean, float& stds){ //calc mean //float total=cblas_ssum(count, X, 1); //LOG(INFO)<<"count="<<count<<",X[0]="<<X[0]<<",X[count-1]="<<X[count-1]; float total=0.0; for(int i=0;i<count;i++){ total+=X[i]; } mean=total/count; //LOG(INFO)<<"CPU sum is "<<total; //calc std total=caffe_cpu_dot(count, X, X); stds=sqrt(total/count-pow(mean,2)); //LOG(INFO)<<"CPU mean="<<mean<<",std="<<stds; } template<> void caffe_cpu_meanstd<double>(const int count, const double* X, double& mean, double& stds){ //calc mean //double total=cblas_dsum(count, X, 1); double total=0.0; for(int i=0;i<count;i++){ total+=X[i]; } mean=total/count; //calc std total=caffe_cpu_dot(count, X, X); stds=sqrt(total/count-pow(mean,2)); //LOG(INFO)<<"mean="<<mean<<",std="<<stds; } } // namespace caffe
[ "gongcheng_nankai@163.com" ]
gongcheng_nankai@163.com
d13264b65898e206d2c6f7baa733ec67c4e6c026
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/rsync/gumtree/rsync_old_hunk_611.cpp
005f22e2a8e9814264bf9362ba861b61b92c6c30
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
907
cpp
if (fd[1] != -1) close(fd[1]); if (listener != -1) close(listener); return -1; } /******************************************************************* run a program on a local tcp socket, this is used to launch smbd when regression testing the return value is a socket which is attached to a subprocess running "prog". stdin and stdout are attached. stderr is left attached to the original stderr ******************************************************************/ int sock_exec(const char *prog) { int fd[2]; if (socketpair_tcp(fd) != 0) { rprintf (FERROR, RSYNC_NAME ": socketpair_tcp failed (%s)\n", strerror(errno)); return -1; } if (fork() == 0) { close(fd[0]); close(0); close(1); dup(fd[1]); dup(fd[1]); if (verbose > 3) fprintf (stderr, RSYNC_NAME ": execute socket program \"%s\"\n", prog); exit (system (prog)); } close (fd[1]); return fd[0]; }
[ "993273596@qq.com" ]
993273596@qq.com
96d4dd6e0de431e6f22272985ecd47f5940fa893
be5cb586bad9aa78ab7d6c9c273757cf087a0138
/death.cpp
09466cf073d3c792ff519afd4146e3e6549533bf
[]
no_license
steaphangreene/aa
5f10a7fd6f4e6db59b4b1a5086cb74d3fd04dacf
6daf6ce9685d19b9d7a4f0a01ac7c95d238a9970
refs/heads/master
2020-05-19T08:18:07.335986
2014-02-03T05:30:07
2014-02-03T05:30:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,511
cpp
#include <stdlib.h> #include "../user/user.h" extern int deathxoff[20]; extern int deathyoff[20]; extern Graphic *death[20]; extern Screen *screen; void defdeath() { death[2] = NULL; death[3] = NULL; death[4] = NULL; death[5] = NULL; death[6] = NULL; death[7] = NULL; death[8] = NULL; death[9] = NULL; death[10] = NULL; death[11] = NULL; death[12] = NULL; death[13] = NULL; death[14] = NULL; death[15] = NULL; death[16] = NULL; death[17] = NULL; death[18] = NULL; death[19] = NULL; death[0] = new Graphic(36, 18); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("--------------------------------01010101--------------------------------"); death[0]->DefLinH("----------------------------0101010505010101----------------------------"); death[0]->DefLinH("--------------------01010101010105050505010101010101--------------------"); death[0]->DefLinH("--01010101010101010101010101010105050505010101010101010101010101010101--"); death[0]->DefLinH("010101010101010101010101010101010105050101010101010101010101010101010101"); death[0]->DefLinH("010101010101010101010101010101010101010101010101010101010101010101010101"); death[0]->DefLinH("010101010101010101010101010101010101010101010101010101010101010101010101"); death[0]->DefLinH("010101010101010101010101010101010101010101010101010101010101010101010101"); death[0]->DefLinH("010101010101010101010101010101010101010101010101010101010101010101010101"); screen->MakeFriendly(death[0]); death[1] = new Graphic(36, 18); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01010101--------------------------------"); death[1]->DefLinH("--------------------------------01050501--------------------------------"); death[1]->DefLinH("-----------------------------015050505050501----------------------------"); death[1]->DefLinH("--------------------------01050505060605050501--------------------------"); death[1]->DefLinH("--------------------01010105050506060606050505010101--------------------"); death[1]->DefLinH("--01010101010101010101010105050506060606050505010101010101010101010101--"); death[1]->DefLinH("010101010101010101010101010105050506060505050101010101010101010101010101"); death[1]->DefLinH("010101010101010101010101010101050505050505010101010101010101010101010101"); death[1]->DefLinH("010101010101010101010101010101010105050101010101010101010101010101010101"); death[1]->DefLinH("010101010101010101010101010101010101010101010101010101010101010101010101"); death[1]->DefLinH("010101010101010101010101010101010101010101010101010101010101010101010101"); screen->MakeFriendly(death[1]); death[2] = new Graphic(36, 18); death[2]->DefLinH("----------------------------------01010101------------------------------"); death[2]->DefLinH("----------------------------------01010101------------------------------"); death[2]->DefLinH("----------------------------------01010101------------------------------"); death[2]->DefLinH("----------------------------------01010101------------------------------"); death[2]->DefLinH("--------------------------------01010101--------------------------------"); death[2]->DefLinH("--------------------------------01010101--------------------------------"); death[2]->DefLinH("--------------------------------01010101--------------------------------"); death[2]->DefLinH("--------------------01--------010505050501--------------------------------"); death[2]->DefLinH("------------------------------050506060505------------------------------"); death[2]->DefLinH("--------------------------05050606060606060505------01------------------"); death[2]->DefLinH("------------------------050506060607070506060505------------------------"); death[2]->DefLinH("--------------------01050506060607070707060606050501--------------------"); death[2]->DefLinH("--01010101010101010101050506060607070707060606050501010101010101010101--"); death[2]->DefLinH("010101010101010101010105050506060607070606060505050101010101010101010101"); death[2]->DefLinH("010101010101010101010101050505060606060606050505010101010101010101010101"); death[2]->DefLinH("010101010101010101010101010505050506060505050501010101010101010101010101"); death[2]->DefLinH("010101010101010101010101010101050505050505010101010101010101010101010101"); death[2]->DefLinH("010101010101010101010101010101010101010101010101010101010101010101010101"); screen->MakeFriendly(death[2]); death[3] = new Graphic(36, 18); death[3]->DefLinH("------------------------------------------------------------------------"); death[3]->DefLinH("--------------------------------------01010101--------------------------"); death[3]->DefLinH("--------------------------------------01010101--------------------------"); death[3]->DefLinH("------------------------------------01010101----------------------------"); death[3]->DefLinH("------------------------------------01010101----------------------------"); death[3]->DefLinH("----01----------------------------01010101------------------------------"); death[3]->DefLinH("----------------------------------01010101------------------------------"); death[3]->DefLinH("--------------------050505----0106060606010505--------------------------"); death[3]->DefLinH("------------------0505050505--06060707060605050505--------------------"); death[3]->DefLinH("--------------01050505050506060707070707070606050505------------------"); death[3]->DefLinH("----------0101010505050506060707070707070707060605050505--01------------"); death[3]->DefLinH("------0101010105050505060607070707070707070707060605050505--------------"); death[3]->DefLinH("--01010101010105050505060607070707070707070707060605050101010101010101--"); death[3]->DefLinH("010101010101010105050506060607070707070707070606060501010101010101010101"); death[3]->DefLinH("010101010101010101050505060606070707070707060606050501010101010101010101"); death[3]->DefLinH("010101010101010101010505050606060607070606060605050501010101010101010101"); death[3]->DefLinH("010101010101010101010105050505060606060606050505050101010101010101010101"); death[3]->DefLinH("010101010101010101010101050505050505050505050505050101010101010101010101"); screen->MakeFriendly(death[3]); death[4] = new Graphic(36, 18); death[4]->DefLinH("------------------------------------------------------------------------"); death[4]->DefLinH("------------------------------------------------------------------------"); death[4]->DefLinH("----------------------------------------01010101------------------------"); death[4]->DefLinH("--------------------------------05050501010101--------------------------"); death[4]->DefLinH("----------------------------050505050505050505--------------------------"); death[4]->DefLinH("----------------------05050505050505050505050505------------------------"); death[4]->DefLinH("------------------0505050505050606060606060505050505--------------------"); death[4]->DefLinH("----------------05050505050606060606060606060605050505------------------"); death[4]->DefLinH("--------------05050505050606060606070706060606060505050505------------"); death[4]->DefLinH("------------050505050506050606070707070707060606060505050505----------"); death[4]->DefLinH("----------0505050505060606060707070707070707060606060505050505----------"); death[4]->DefLinH("------0101050505050606060607070707070707070707060606060505050505--------"); death[4]->DefLinH("--01010101050505050606060607070707070707070707060606060505050505010101--"); death[4]->DefLinH("010101010505050505060606060607070707070707070606060606050505050501010101"); death[4]->DefLinH("010101010505050505050606060606070707070707060606060605050505050501010101"); death[4]->DefLinH("010101010505050505050506060606060607070606060606060505050505050501010101"); death[4]->DefLinH("010101010505050505050505060606060606060606060606050505050505050501010101"); death[4]->DefLinH("010101010105050505050505050606060606060606060605050505050505050501010101"); screen->MakeFriendly(death[4]); death[5] = new Graphic(36, 18); death[5]->DefLinH("------------------------------------------------------------------------"); death[5]->DefLinH("------------------------------------------------------------------------"); death[5]->DefLinH("----------------------------------------01010101------------------------"); death[5]->DefLinH("----------------------------050505050505050505--------------------------"); death[5]->DefLinH("----------------------0505050506060606060606050505----------------------"); death[5]->DefLinH("----------------050505050505060606060606060606060505--------------------"); death[5]->DefLinH("--------------050505050505060606060606060606060606050505----------------"); death[5]->DefLinH("------------050505050505060606060706060606060606060605050505------------"); death[5]->DefLinH("----------050505050505060606070707070706060606060606050505050505--------"); death[5]->DefLinH("--------0505050505050606050707070707070707060606060505050505050505------"); death[5]->DefLinH("------0505050505050606060607070707070707070706060606050505050505050505--"); death[5]->DefLinH("------0505050505060606060707070707070707070707060606060505050505050505--"); death[5]->DefLinH("--0105050505050506060606070707070707070707070706060606050505050505050505"); death[5]->DefLinH("010105050505050506060607070707070707070707070606060606050505050505050505"); death[5]->DefLinH("010505050505050506060606070707070707070707070606060606050505050505050505"); death[5]->DefLinH("010505050505050505060606060707070707070707070606060605050505050505050505"); death[5]->DefLinH("010505050505050505050606060607070707070707060606060606050505050505050505"); death[5]->DefLinH("010105050505050505050506060606070707070707060606060605050505050505050501"); screen->MakeFriendly(death[5]); death[6] = new Graphic(36, 18); death[6]->DefLinH("------------------------------------------------------------------------"); death[6]->DefLinH("--------------------------------060606----------------------------------"); death[6]->DefLinH("------------------------------0607070706--------------------------------"); death[6]->DefLinH("----------------------------050506060605050505--------------------------"); death[6]->DefLinH("----------------------0505050506060606060606050505----------------------"); death[6]->DefLinH("----------------050505050505060606060606060606060505--------------------"); death[6]->DefLinH("--------------050505050505070707070707070606060606050505----------------"); death[6]->DefLinH("------------05050505050507070707--07070707060606060605050505------------"); death[6]->DefLinH("----------050505050505070707----------07070706060606050505050505--------"); death[6]->DefLinH("--------050505050505070707----------------070707060505050505050505------"); death[6]->DefLinH("------05050505050507070707------------------070707070505050505050505----"); death[6]->DefLinH("------050505050507070707----------------------070707060505050505050505--"); death[6]->DefLinH("----05050505050507070707----------------------070707060505050505050505--"); death[6]->DefLinH("--05050605050505070707----------------------0707070706050505050505050505"); death[6]->DefLinH("--0506060505050507070707--------------------0707070606050505050505050505"); death[6]->DefLinH("--050606050505050507070707------------------0707070605050505050505050505"); death[6]->DefLinH("--05060605050505050507070707--------------0707070606060505050505050505--"); death[6]->DefLinH("----05060606060606060607070707------------0707070606050505050505050505--"); screen->MakeFriendly(death[6]); death[7] = new Graphic(36, 18); death[7]->DefLinH("------------------------------------------------------------------------"); death[7]->DefLinH("--------------------------------050505----------------------------------"); death[7]->DefLinH("------------------------------0506060605--------------------------------"); death[7]->DefLinH("--------------------------------050505----------------------------------"); death[7]->DefLinH("------------------------------050505050505------------------------------"); death[7]->DefLinH("--------------------------050505050505050505----------------------------"); death[7]->DefLinH("----------------------0505070707070707070606050505----------------------"); death[7]->DefLinH("--------------------050506060606--070707070605050505--------------------"); death[7]->DefLinH("--------------------------------------06060605050505--------------------"); death[7]->DefLinH("--------------0505050606------------------06060606050505----------------"); death[7]->DefLinH("----------0505050507070706------------------06060606050505--------------"); death[7]->DefLinH("----------05050507070706----------------------0606060605050505----------"); death[7]->DefLinH("--------0505050507070706----------------------06060606050505050505------"); death[7]->DefLinH("------0605050505070706----------------------060606060605050505050505----"); death[7]->DefLinH("------060505050507070706--------------------060606060605050505050505----"); death[7]->DefLinH("------06050505050507070706------------------060606060505050505050505----"); death[7]->DefLinH("--------05050505050507070706--------------060606060606050505050505------"); death[7]->DefLinH("----------06060606060607070706------------0606060606050505050505--------"); screen->MakeFriendly(death[7]); death[8] = new Graphic(36, 18); death[8]->DefLinH("------------------------------------------------------------------------"); death[8]->DefLinH("------------------------------------------------------------------------"); death[8]->DefLinH("--------------------------------050505----------------------------------"); death[8]->DefLinH("------------------------------------------------------------------------"); death[8]->DefLinH("------------------------------------------------------------------------"); death[8]->DefLinH("------------------------------------------------------------------------"); death[8]->DefLinH("--------------------------060606060606060-------------------------------"); death[8]->DefLinH("----------------------------------06060606------------------------------"); death[8]->DefLinH("------------------------------------------------------------------------"); death[8]->DefLinH("------------------------------------------------------------------------"); death[8]->DefLinH("--------------0505060606--------------------------0505------------------"); death[8]->DefLinH("------------0505060606--------------------------0505050505--------------"); death[8]->DefLinH("------------0505060706--------------------------050506050505------------"); death[8]->DefLinH("------------0505060706------------------------0505060605050505----------"); death[8]->DefLinH("------05----050506070706----------------------0505060605050505----------"); death[8]->DefLinH("------------050505060707----------------------0505060505050505----------"); death[8]->DefLinH("--------------0505050606------------------------050506050505------------"); death[8]->DefLinH("----------------06060606--------------------------05050505--------------"); screen->MakeFriendly(death[8]); death[9] = new Graphic(36, 18); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("----------------------------------0606----------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("----------------------------------------------------05------------------"); death[9]->DefLinH("--------------------0706--------------------------0505------------------"); death[9]->DefLinH("--------------------06------------------------------05------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); death[9]->DefLinH("------------------------------------------------------------------------"); screen->MakeFriendly(death[9]); death[10] = new Graphic(36, 18); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); death[10]->DefLinH("------------------------------------------------------------------------"); screen->MakeFriendly(death[10]); }
[ "steaphan@gmail.com" ]
steaphan@gmail.com
b2dd5e01bb819e60896c3b6706f4032a6c08c55c
2e9b40d51adbf70f1f43bd561876abba7da2d2aa
/Homework 1/testSSNSet.cpp
4e1bc499b4893df6c3ebffabca060186bba6e66a
[]
no_license
just-ma/CS32
5485b05b423f12391fc797d8196337b5abe0ecfd
4671076df95acae0ad1e9ea0bcc61313fb012942
refs/heads/master
2020-03-26T19:06:16.034987
2018-08-19T18:23:43
2018-08-19T18:23:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
975
cpp
#include "SSNSet.h" #include <iostream> #include <cassert> using namespace std; int main() { SSNSet s; assert(s.size()==0); //test if size function works when empty ItemType x = 123; s.add(x); s.add(678); assert (s.size()==2); //test if size function works when unempty assert (!s.add(678)); //test if add function return false for duplicates assert (s.size() ==2); //test if size remains the same after duplicate SSNSet n; assert (n.size()==0);//test if new SSNSet begins with 0 size n.add(5); n.add(7); n.add(89); n=s; assert(n.size()==2);//test if = operator works for size cout<<"Output must look like:\n123\n678\n\nOutput looks like:\n"; s.print(); //check if it matches to see if print function works cout<<"\nOutput must also look like:\n123\n678\n\nOutput looks like:\n"; n.print(); //check if = operator works cout<<"If so, all tests passed!"<<endl; }
[ "noreply@github.com" ]
just-ma.noreply@github.com
66c95affbbe23e36f84386151426377c8090b7d9
b53795b88ab0201e48c5dc5737e97dfd27e07b22
/tools/DumpProto - OFFİCAL AÇICI/dump_proto/dump_proto.cpp
4f8c012cd7b32bb2f31ca6eef603c3b9926b2489
[]
no_license
davidkm2/globalmetin
9cc63395974eb74b5784a1bf5e733622c7303aa4
d1a21b549c68e311416544e03ca6218351e12d2f
refs/heads/main
2023-05-27T08:10:08.506239
2021-05-24T01:57:37
2021-05-24T01:57:37
370,181,109
2
1
null
null
null
null
UTF-8
C++
false
false
31,000
cpp
#include "dump_proto.h" #include <locale.h> bool LoadNPrint = false; CPythonNonPlayer::TMobTable * m_pMobTable = NULL; int m_iMobTableSize = 0; CItemData::TItemTable * m_pItemTable = NULL; int m_iItemTableSize = 0; bool Set_Proto_Mob_Table(CPythonNonPlayer::TMobTable *mobTable, cCsvTable &csvTable, std::map<int,const char*> &nameMap) { int col = 0; mobTable->dwVnum = atoi(csvTable.AsStringByIndex(col++)); strncpy(mobTable->szName, csvTable.AsStringByIndex(col++), CHARACTER_NAME_MAX_LEN); map<int,const char*>::iterator it; it = nameMap.find(mobTable->dwVnum); if (it != nameMap.end()) { const char * localeName = it->second; strncpy(mobTable->szLocaleName, localeName, sizeof (mobTable->szLocaleName)); } else strncpy(mobTable->szLocaleName, mobTable->szName, sizeof (mobTable->szLocaleName)); int rankValue = get_Mob_Rank_Value(csvTable.AsStringByIndex(col++)); mobTable->bRank = rankValue; int typeValue = get_Mob_Type_Value(csvTable.AsStringByIndex(col++)); mobTable->bType = typeValue; int battleTypeValue = get_Mob_BattleType_Value(csvTable.AsStringByIndex(col++)); mobTable->bBattleType = battleTypeValue; mobTable->bLevel = atoi(csvTable.AsStringByIndex(col++)); mobTable->bScalePct = atoi(csvTable.AsStringByIndex(col++)); int sizeValue = get_Mob_Size_Value(csvTable.AsStringByIndex(col++)); mobTable->bSize = sizeValue; int aiFlagValue = get_Mob_AIFlag_Value(csvTable.AsStringByIndex(col++)); mobTable->dwAIFlag = aiFlagValue; mobTable->bMountCapacity = atoi(csvTable.AsStringByIndex(col++)); int raceFlagValue = get_Mob_RaceFlag_Value(csvTable.AsStringByIndex(col++)); mobTable->dwRaceFlag = raceFlagValue; int immuneFlagValue = get_Mob_ImmuneFlag_Value(csvTable.AsStringByIndex(col++)); mobTable->dwImmuneFlag = immuneFlagValue; mobTable->bEmpire = atoi(csvTable.AsStringByIndex(col++)); strncpy(mobTable->szFolder, csvTable.AsStringByIndex(col++), sizeof(mobTable->szFolder)); mobTable->bOnClickType = atoi(csvTable.AsStringByIndex(col++)); mobTable->bStr = atoi(csvTable.AsStringByIndex(col++)); mobTable->bDex = atoi(csvTable.AsStringByIndex(col++)); mobTable->bCon = atoi(csvTable.AsStringByIndex(col++)); mobTable->bInt = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwDamageRange[0] = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwDamageRange[1] = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwMaxHP = atoi(csvTable.AsStringByIndex(col++)); mobTable->bRegenCycle = atoi(csvTable.AsStringByIndex(col++)); mobTable->bRegenPercent = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwGoldMin = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwGoldMax = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwExp = atoi(csvTable.AsStringByIndex(col++)); mobTable->wDef = atoi(csvTable.AsStringByIndex(col++)); mobTable->sAttackSpeed = atoi(csvTable.AsStringByIndex(col++)); mobTable->sMovingSpeed = atoi(csvTable.AsStringByIndex(col++)); mobTable->bAggresiveHPPct = atoi(csvTable.AsStringByIndex(col++)); mobTable->wAggressiveSight = atoi(csvTable.AsStringByIndex(col++)); mobTable->wAttackRange = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwDropItemVnum = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwResurrectionVnum = atoi(csvTable.AsStringByIndex(col++)); for (int i = 0; i < CPythonNonPlayer::MOB_ENCHANTS_MAX_NUM; ++i) mobTable->cEnchants[i] = atoi(csvTable.AsStringByIndex(col++)); for (int i = 0; i < CPythonNonPlayer::MOB_RESISTS_MAX_NUM; ++i) mobTable->cResists[i] = atoi(csvTable.AsStringByIndex(col++)); for (int i = 0; i < CPythonNonPlayer::ATT_MAX_NUM; ++i) mobTable->cAttrs[i] = atoi(csvTable.AsStringByIndex(col++)); mobTable->fDamMultiply = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwSummonVnum = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwDrainSP = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwMonsterColor = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwPolymorphItemVnum = atoi(csvTable.AsStringByIndex(col++)); for (int i = 0; i < CPythonNonPlayer::MOB_SKILL_MAX_NUM; ++i) { mobTable->Skills[i].bLevel = atoi(csvTable.AsStringByIndex(col++)); mobTable->Skills[i].dwVnum = atoi(csvTable.AsStringByIndex(col++)); } mobTable->bBerserkPoint = atoi(csvTable.AsStringByIndex(col++)); mobTable->bStoneSkinPoint = atoi(csvTable.AsStringByIndex(col++)); mobTable->bGodSpeedPoint = atoi(csvTable.AsStringByIndex(col++)); mobTable->bDeathBlowPoint = atoi(csvTable.AsStringByIndex(col++)); mobTable->bRevivePoint = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwHealerPoint = atoi(csvTable.AsStringByIndex(col++)); mobTable->dwHitRange = atoi(csvTable.AsStringByIndex(col++)); return true; } bool BuildMobTable() { fprintf(stderr, "sizeof(TMobTable): %u\n", sizeof(CPythonNonPlayer::TMobTable)); bool isNameFile = true; map<int,const char*> localMap; cCsvTable nameData; if(!nameData.Load("mob_names.txt",'\t')) { fprintf(stderr, "mob_names.txt Unable to read file\n"); isNameFile = false; } else { nameData.Next(); while(nameData.Next()) { localMap[atoi(nameData.AsStringByIndex(0))] = nameData.AsStringByIndex(1); } } set<int> vnumSet; map<DWORD, CPythonNonPlayer::TMobTable *> test_map_mobTableByVnum; //파일 읽어오기. cCsvTable data; if(!data.Load("mob_proto.txt",'\t')) { fprintf(stderr, "mob_proto.txt Unable to read file\n"); return false; } data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분) //===== 몹 테이블 생성=====// if (m_pMobTable) { delete m_pMobTable; m_pMobTable = NULL; } //새로 추가되는 갯수를 파악한다. int addNumber = 0; while(data.Next()) { int vnum = atoi(data.AsStringByIndex(0)); std::map<DWORD, CPythonNonPlayer::TMobTable *>::iterator it_map_mobTable; it_map_mobTable = test_map_mobTableByVnum.find(vnum); if(it_map_mobTable != test_map_mobTableByVnum.end()) { addNumber++; } } m_iMobTableSize = data.m_File.GetRowCount()-1 + addNumber; m_pMobTable = new CPythonNonPlayer::TMobTable[m_iMobTableSize]; memset(m_pMobTable, 0, sizeof(CPythonNonPlayer::TMobTable) * m_iMobTableSize); CPythonNonPlayer::TMobTable * mob_table = m_pMobTable; //data를 다시 첫줄로 옮긴다.(다시 읽어온다;;) data.Destroy(); if(!data.Load("mob_proto.txt",'\t')) { fprintf(stderr, "mob_proto.txt Unable to read file\n"); return false; } data.Next(); //맨 윗줄 제외 (아이템 칼럼을 설명하는 부분) while (data.Next()) { int col = 0; //테스트 파일에 같은 vnum이 있는지 조사. std::map<DWORD, CPythonNonPlayer::TMobTable *>::iterator it_map_mobTable; it_map_mobTable = test_map_mobTableByVnum.find(atoi(data.AsStringByIndex(col))); if (it_map_mobTable == test_map_mobTableByVnum.end()) if (!Set_Proto_Mob_Table(mob_table, data, localMap)) fprintf(stderr, "Mob prototype table setting failed.\n"); fprintf(stdout, "MOB #%-5d %-16s %-16s sight: %u color %u[%s]\n", mob_table->dwVnum, mob_table->szName, mob_table->szLocaleName, mob_table->wAggressiveSight, mob_table->dwMonsterColor, 0); //셋에 vnum 추가 vnumSet.insert(mob_table->dwVnum); ++mob_table; } return true; } DWORD g_adwMobProtoKey[4] = { 4813894, 18955, 552631, 6822045 }; void SaveMobProto() { FILE * fp; fopen_s(&fp, "mob_proto", "wb"); if (!fp) { printf("cannot open %s for writing\n", "mob_proto"); return; } DWORD fourcc = MAKEFOURCC('M', 'M', 'P', 'T'); fwrite(&fourcc, sizeof(DWORD), 1, fp); DWORD dwElements = m_iMobTableSize; fwrite(&dwElements, sizeof(DWORD), 1, fp); CLZObject zObj; printf("sizeof(TMobTable) %d\n", sizeof(CPythonNonPlayer::TMobTable)); if (!CLZO::instance().CompressEncryptedMemory(zObj, m_pMobTable, sizeof(CPythonNonPlayer::TMobTable) * m_iMobTableSize, g_adwMobProtoKey)) { printf("cannot compress\n"); fclose(fp); return; } const CLZObject::THeader & r = zObj.GetHeader(); printf("MobProto count %u\n%u --Compress--> %u --Encrypt--> %u, GetSize %u\n", m_iMobTableSize, r.dwRealSize, r.dwCompressedSize, r.dwEncryptSize, zObj.GetSize()); DWORD dwDataSize = zObj.GetSize(); fwrite(&dwDataSize, sizeof(DWORD), 1, fp); fwrite(zObj.GetBuffer(), dwDataSize, 1, fp); fclose(fp); } void LoadMobProto() { FILE * fp; DWORD fourcc, tableSize, dataSize; fopen_s(&fp, "mob_proto", "rb"); if (fp==NULL) { printf("mob_proto not found\n"); return; } fread(&fourcc, sizeof(DWORD), 1, fp); fread(&tableSize, sizeof(DWORD), 1, fp); fread(&dataSize, sizeof(DWORD), 1, fp); BYTE * data = (BYTE *) malloc(dataSize); printf("fourcc %u\n", fourcc); printf("tableSize %u\n", tableSize); printf("dataSize %u\n", dataSize); if (data) { fread(data, dataSize, 1, fp); CLZObject zObj; if (CLZO::instance().Decompress(zObj, data, g_adwMobProtoKey)) { printf("real_size %u\n", zObj.GetSize()); DWORD structSize = zObj.GetSize() / tableSize; DWORD structDiff = zObj.GetSize() % tableSize; printf("struct_size %u\n", structSize); printf("struct_diff %u\n", structDiff); /*#ifdef ENABLE_PROTOSTRUCT_AUTODETECT if (structDiff!=0 && !CPythonNonPlayer::TMobTableAll::IsValidStruct(structSize)) #else if ((zObj.GetSize() % sizeof(TMobTable)) != 0) #endif { printf("LoadMobProto: invalid size %u check data format. structSize %u, structDiff %u\n", zObj.GetSize(), structSize, structDiff); return; }*/ if (LoadNPrint) { for (DWORD i = 0; i < tableSize; ++i) { #ifdef ENABLE_PROTOSTRUCT_AUTODETECT CPythonNonPlayer::TMobTable rTable = {0}; CPythonNonPlayer::TMobTableAll::Process(zObj.GetBuffer(), structSize, i, rTable); #else CPythonNonPlayer::TMobTable & rTable = *((CItemData::TItemTable *) zObj.GetBuffer() + i); #endif printf("%u %s\n", rTable.dwVnum, rTable.szLocaleName); } } else { FILE * mf1; fopen_s(&mf1, "mob_names.txt", "w"); FILE * mf2; fopen_s(&mf2, "mob_proto.txt", "w"); // FILE * mf3; fopen_s(&mf3, "mob_proto1.txt", "w"); if (mf1==NULL) { printf("mob_names.txt not writable"); return; } if (mf2==NULL) { printf("mob_proto.txt not writable"); return; } fprintf(mf1, "VNUM\tLOCALE_NAME\n"); fprintf(mf2, "VNUM\tNAME\tRANK\tTYPE\tBATTLE_TYPE\tLEVEL\tSCALE_PCT\tSIZE\tAI_FLAG\tMOUNT_CAPACITY\tRACE_FLAG\tIMMUNE_FLAG\tEMPIRE\tFOLDER\tON_CLICK\tST\tDX\tHT\tIQ\tDAMAGE_MIN\tDAMAGE_MAX\tMAX_HP\tREGEN_CYCLE\tREGEN_PERCENT\tGOLD_MIN\tGOLD_MAX\tEXP\tDEF\tATTACK_SPEED\tMOVE_SPEED\tAGGRESSIVE_HP_PCT\tAGGRESSIVE_SIGHT\tATTACK_RANGE\tDROP_ITEM\tRESURRECTION_VNUM\tENCHANT_CURSE\tENCHANT_SLOW\tENCHANT_POISON\tENCHANT_STUN\tENCHANT_CRITICAL\tENCHANT_PENETRATE\tRESIST_SWORD\tRESIST_TWOHAND\tRESIST_DAGGER\tRESIST_BELL\tRESIST_FAN\tRESIST_BOW\tRESIST_CLAW\tRESIST_FIRE\tRESIST_ELECT\tRESIST_MAGIC\tRESIST_WIND\tRESIST_ICE\tRESIST_EARTH\tRESIST_DARK\tRESIST_POISON\tRESIST_BLEEDING\tRESIST_FIST\tATT_ELEC\tATT_FIRE\tATT_ICE\tATT_WIND\tATT_EARTH\tATT_DARK\tDAM_MULTIPLY\tSUMMON\tDRAIN_SP\tMOB_COLOR\tPOLYMORPH_ITEM\tSKILL_LEVEL0\tSKILL_VNUM0\tSKILL_LEVEL1\tSKILL_VNUM1\tSKILL_LEVEL2\tSKILL_VNUM2\tSKILL_LEVEL3\tSKILL_VNUM3\tSKILL_LEVEL4\tSKILL_VNUM4\tSP_BERSERK\tSP_STONESKIN\tSP_GODSPEED\tSP_DEATHBLOW\tSP_REVIVE\tHEAL_VNUM\tHIT_RANGE\n"); for (DWORD i = 0; i < tableSize; ++i) { #ifdef ENABLE_PROTOSTRUCT_AUTODETECT CPythonNonPlayer::TMobTable rTable = {0}; CPythonNonPlayer::TMobTableAll::Process(zObj.GetBuffer(), structSize, i, rTable); #else CPythonNonPlayer::TMobTable & rTable = *((CItemData::TItemTable *) zObj.GetBuffer() + i); #endif fprintf(mf1, "%u %s\n", rTable.dwVnum, rTable.szLocaleName); // fprintf(mf3, "%d %d %d %d %d %d %d\n", rTable.cAttrs[CPythonNonPlayer::ATT_ELEC], rTable.cAttrs[CPythonNonPlayer::ATT_FIRE], rTable.cAttrs[CPythonNonPlayer::ATT_ICE], rTable.cAttrs[CPythonNonPlayer::ATT_WIND], rTable.cAttrs[CPythonNonPlayer::ATT_EARTH], rTable.cAttrs[CPythonNonPlayer::ATT_DARK], rTable.cResists[CPythonNonPlayer::MOB_RESIST_1]); fprintf(mf2, "%u %s" //2 " %s %s %s %u %u" //7 " %s %s %u %s" //11 " %s %u %s %u %u %u %u %u" //19 " %u %u %u %u %u %u %u %u %u" //28 " %d %d %u %u %u %u %u" //35 " %d %d %d" //38 " %d %d %d" //41 " %d %d %d %d" //45 " %d %d %d" //48 " %d %d" //50 " %d %d" //52 " %d %d %d" //55 " %d %d %d" //58 " %d %d %d" //61 " %d %d %d" //64 " %s %u %u %u %u" //67 " %u %u %u %u %u %u" //75 " %u %u %u %u" //79 " %u %u %u %u %u" //84 " %d %u" //86 "\n", rTable.dwVnum, rTable.szName, //2 set_Mob_Rank_Value(rTable.bRank).c_str(), set_Mob_Type_Value(rTable.bType).c_str(), set_Mob_BattleType_Value(rTable.bBattleType).c_str(), rTable.bLevel, rTable.bScalePct, //7 set_Mob_Size_Value(rTable.bSize).c_str(), set_Mob_AIFlag_Value(rTable.dwAIFlag).c_str(), rTable.bMountCapacity, set_Mob_RaceFlag_Value(rTable.dwRaceFlag).c_str(), //11 set_Mob_ImmuneFlag_Value(rTable.dwImmuneFlag).c_str(), rTable.bEmpire, set_Mob_Char(rTable.szFolder).c_str(), rTable.bOnClickType, rTable.bStr, rTable.bDex, rTable.bCon, rTable.bInt, //19 rTable.dwDamageRange[0], rTable.dwDamageRange[1], rTable.dwMaxHP, rTable.bRegenCycle, rTable.bRegenPercent, rTable.dwGoldMin, rTable.dwGoldMax, rTable.dwExp, rTable.wDef, //28 rTable.sAttackSpeed, rTable.sMovingSpeed, rTable.bAggresiveHPPct, rTable.wAggressiveSight, rTable.wAttackRange, rTable.dwDropItemVnum, rTable.dwResurrectionVnum, //35 rTable.cEnchants[CPythonNonPlayer::MOB_ENCHANT_CURSE], rTable.cEnchants[CPythonNonPlayer::MOB_ENCHANT_SLOW], rTable.cEnchants[CPythonNonPlayer::MOB_ENCHANT_POISON], //38 rTable.cEnchants[CPythonNonPlayer::MOB_ENCHANT_STUN], rTable.cEnchants[CPythonNonPlayer::MOB_ENCHANT_CRITICAL], rTable.cEnchants[CPythonNonPlayer::MOB_ENCHANT_PENETRATE], //41 rTable.cResists[CPythonNonPlayer::MOB_RESIST_SWORD], rTable.cResists[CPythonNonPlayer::MOB_RESIST_TWOHAND], rTable.cResists[CPythonNonPlayer::MOB_RESIST_DAGGER], rTable.cResists[CPythonNonPlayer::MOB_RESIST_BELL], //45 rTable.cResists[CPythonNonPlayer::MOB_RESIST_FAN], rTable.cResists[CPythonNonPlayer::MOB_RESIST_BOW], rTable.cResists[CPythonNonPlayer::MOB_RESIST_CLAW], //48 rTable.cResists[CPythonNonPlayer::MOB_RESIST_FIRE], rTable.cResists[CPythonNonPlayer::MOB_RESIST_ELECT], //50 rTable.cResists[CPythonNonPlayer::MOB_RESIST_MAGIC], rTable.cResists[CPythonNonPlayer::MOB_RESIST_WIND], //52 rTable.cResists[CPythonNonPlayer::MOB_RESIST_ICE], rTable.cResists[CPythonNonPlayer::MOB_RESIST_EARTH], rTable.cResists[CPythonNonPlayer::MOB_RESIST_DARK], //55 rTable.cResists[CPythonNonPlayer::MOB_RESIST_POISON], rTable.cResists[CPythonNonPlayer::MOB_RESIST_BLEEDING], rTable.cResists[CPythonNonPlayer::MOB_RESIST_FIST], //58 rTable.cAttrs[CPythonNonPlayer::ATT_ELEC], rTable.cAttrs[CPythonNonPlayer::ATT_FIRE], rTable.cAttrs[CPythonNonPlayer::ATT_ICE], //61 rTable.cAttrs[CPythonNonPlayer::ATT_WIND], rTable.cAttrs[CPythonNonPlayer::ATT_EARTH], rTable.cAttrs[CPythonNonPlayer::ATT_DARK], //64 set_Mob_Dam(rTable.fDamMultiply).c_str(), rTable.dwSummonVnum, rTable.dwDrainSP, rTable.dwMonsterColor, rTable.dwPolymorphItemVnum, //69 rTable.Skills[0].bLevel, rTable.Skills[0].dwVnum, rTable.Skills[1].bLevel, rTable.Skills[1].dwVnum, rTable.Skills[2].bLevel, rTable.Skills[2].dwVnum, //75 rTable.Skills[3].bLevel, rTable.Skills[3].dwVnum, rTable.Skills[4].bLevel, rTable.Skills[4].dwVnum, //79 rTable.bBerserkPoint, rTable.bStoneSkinPoint, rTable.bGodSpeedPoint, rTable.bDeathBlowPoint, rTable.bRevivePoint, //84 rTable.dwHealerPoint, rTable.dwHitRange //86 ); } ; } } free(data); } fclose(fp); } string retrieveVnumRange(DWORD dwVnum, DWORD dwVnumRange) { static char buf[10*2+1]; if (dwVnumRange>0) snprintf(buf, sizeof(buf), "%u~%u", dwVnum, dwVnum+dwVnumRange); else snprintf(buf, sizeof(buf), "%u", dwVnum); return buf; } int retrieveAddonType(DWORD dwVnum) { int addon_type = 0; #ifdef ENABLE_ADDONTYPE_AUTODETECT static DWORD vnumlist[] = {180, 190, 290, 1130, 1170, 2150, 2170, 3160, 3210, 5110, 5120, 7160, 6010, 6060, 6070}; for (DWORD i = 0; i < (sizeof(vnumlist)/sizeof(DWORD)); i++) { if ((dwVnum >= vnumlist[i]) && (dwVnum <= vnumlist[i]+9)) { addon_type = -1; } } #endif return addon_type; } bool Set_Proto_Item_Table(CItemData::TItemTable *itemTable, cCsvTable &csvTable, std::map<int,const char*> &nameMap) { { std::string s(csvTable.AsStringByIndex(0)); int pos = s.find("~"); if (std::string::npos == pos) { itemTable->dwVnum = atoi(s.c_str()); if (0 == itemTable->dwVnum) { printf ("INVALID VNUM %s\n", s.c_str()); return false; } itemTable->dwVnumRange = 0; } else { std::string s_start_vnum (s.substr(0, pos)); std::string s_end_vnum (s.substr(pos +1 )); int start_vnum = atoi(s_start_vnum.c_str()); int end_vnum = atoi(s_end_vnum.c_str()); if (0 == start_vnum || (0 != end_vnum && end_vnum < start_vnum)) { printf ("INVALID VNUM RANGE%s\n", s.c_str()); return false; } itemTable->dwVnum = start_vnum; itemTable->dwVnumRange = end_vnum - start_vnum; } } int col = 1; strncpy(itemTable->szName, csvTable.AsStringByIndex(col++), CItemData::ITEM_NAME_MAX_LEN); map<int,const char*>::iterator it; it = nameMap.find(itemTable->dwVnum); if (it != nameMap.end()) { const char * localeName = it->second; strncpy(itemTable->szLocaleName, localeName, sizeof(itemTable->szLocaleName)); } else strncpy(itemTable->szLocaleName, itemTable->szName, sizeof(itemTable->szLocaleName)); itemTable->bType = get_Item_Type_Value(csvTable.AsStringByIndex(col++)); itemTable->bSubType = get_Item_SubType_Value(itemTable->bType, csvTable.AsStringByIndex(col++)); itemTable->bMaskType = get_Item_MaskType_Value(csvTable.AsStringByIndex(col++)); itemTable->bMaskSubType = get_Item_MaskSubType_Value(itemTable->bMaskType, csvTable.AsStringByIndex(col++)); itemTable->bSize = atoi(csvTable.AsStringByIndex(col++)); itemTable->dwAntiFlags = get_Item_AntiFlag_Value(csvTable.AsStringByIndex(col++)); itemTable->dwFlags = get_Item_Flag_Value(csvTable.AsStringByIndex(col++)); itemTable->dwWearFlags = get_Item_WearFlag_Value(csvTable.AsStringByIndex(col++)); itemTable->dwImmuneFlag = get_Item_Immune_Value(csvTable.AsStringByIndex(col++)); itemTable->dwIBuyItemPrice = atoi(csvTable.AsStringByIndex(col++)); itemTable->dwISellItemPrice = atoi(csvTable.AsStringByIndex(col++)); itemTable->dwRefinedVnum = atoi(csvTable.AsStringByIndex(col++)); itemTable->wRefineSet = atoi(csvTable.AsStringByIndex(col++)); itemTable->bAlterToMagicItemPct = atoi(csvTable.AsStringByIndex(col++)); int i; for (i = 0; i < CItemData::ITEM_LIMIT_MAX_NUM; ++i) { itemTable->aLimits[i].bType = get_Item_LimitType_Value(csvTable.AsStringByIndex(col++)); itemTable->aLimits[i].lValue = atoi(csvTable.AsStringByIndex(col++)); } for (i = 0; i < CItemData::ITEM_APPLY_MAX_NUM; ++i) { itemTable->aApplies[i].bType = get_Item_ApplyType_Value(csvTable.AsStringByIndex(col++)); itemTable->aApplies[i].lValue = atoi(csvTable.AsStringByIndex(col++)); } for (i = 0; i < CItemData::ITEM_VALUES_MAX_NUM; ++i) itemTable->alValues[i] = atoi(csvTable.AsStringByIndex(col++)); itemTable->bSpecular = atoi(csvTable.AsStringByIndex(col++)); itemTable->bGainSocketPct = atoi(csvTable.AsStringByIndex(col++)); col++; //AddonType itemTable->bWeight = 0; return true; } bool BuildItemTable() { fprintf(stderr, "sizeof(TClientItemTable): %u\n", sizeof(CItemData::TItemTable)); bool isNameFile = true; map<int,const char*> localMap; cCsvTable nameData; if(!nameData.Load("item_names.txt",'\t')) { fprintf(stderr, "item_names.txt Unable to read file\n"); isNameFile = false; } else { nameData.Next(); while(nameData.Next()) { localMap[atoi(nameData.AsStringByIndex(0))] = nameData.AsStringByIndex(1); } } map<DWORD, CItemData::TItemTable *> test_map_itemTableByVnum; set<int> vnumSet; cCsvTable data; if (!data.Load("item_proto.txt",'\t')) { fprintf(stderr, "item_proto.txt Unable to read file\n"); return false; } data.Next(); if (m_pItemTable) { free(m_pItemTable); m_pItemTable = NULL; } int addNumber = 0; while(data.Next()) { int vnum = atoi(data.AsStringByIndex(0)); std::map<DWORD, CItemData::TItemTable *>::iterator it_map_itemTable; it_map_itemTable = test_map_itemTableByVnum.find(vnum); if (it_map_itemTable != test_map_itemTableByVnum.end()) addNumber++; } data.Destroy(); if(!data.Load("item_proto.txt",'\t')) { fprintf(stderr, "item_proto.txt Unable to read file\n"); return false; } data.Next(); m_iItemTableSize = data.m_File.GetRowCount()-1+addNumber; m_pItemTable = new CItemData::TItemTable[m_iItemTableSize]; memset(m_pItemTable, 0, sizeof(CItemData::TItemTable) * m_iItemTableSize); CItemData::TItemTable * item_table = m_pItemTable; while (data.Next()) { int col = 0; std::map<DWORD, CItemData::TItemTable *>::iterator it_map_itemTable; it_map_itemTable = test_map_itemTableByVnum.find(atoi(data.AsStringByIndex(col))); if (!Set_Proto_Item_Table(item_table, data, localMap)) fprintf(stderr, "Mob prototype table setting failed.\n"); fprintf(stdout, "ITEM #%-5u %-24s %-24s VAL: %ld %ld %ld %ld %ld %ld WEAR %u ANTI %u IMMUNE %u REFINE %u\n", item_table->dwVnum, item_table->szName, item_table->szLocaleName, item_table->alValues[0], item_table->alValues[1], item_table->alValues[2], item_table->alValues[3], item_table->alValues[4], item_table->alValues[5], item_table->dwWearFlags, item_table->dwAntiFlags, item_table->dwImmuneFlag, item_table->dwRefinedVnum); vnumSet.insert(item_table->dwVnum); ++item_table; } return true; } DWORD g_adwItemProtoKey[4] = { // 173217, // 72619434, // 408587239, // 27973291 1411666002, 2304517176, 2304517192, }; void LoadItemProto() { FILE * fp; DWORD fourcc, tableSize, dataSize, protoVersion, structSize; fopen_s(&fp, "item_proto", "rb"); if (fp==NULL) { printf("item_proto not found\n"); return; } fread(&fourcc, sizeof(DWORD), 1, fp); fread(&protoVersion, sizeof(DWORD), 1, fp); fread(&structSize, sizeof(DWORD), 1, fp); fread(&tableSize, sizeof(DWORD), 1, fp); fread(&dataSize, sizeof(DWORD), 1, fp); BYTE * data = (BYTE *) malloc(dataSize); printf("fourcc %u\n", fourcc); printf("protoVersion %u\n", protoVersion); printf("struct_size %u\n", structSize); printf("tableSize %u\n", tableSize); printf("dataSize %u\n", dataSize); // #ifdef ENABLE_PROTOSTRUCT_AUTODETECT // if (!CItemData::TItemTableAll::IsValidStruct(structSize)) // #else // if (structSize != sizeof(CItemData::TItemTable)) // #endif // { // printf("LoadItemProto: invalid item_proto structSize[%d] != sizeof(SItemTable)\n", structSize, sizeof(CItemData::TItemTable)); // return; // } if (data) { fread(data, dataSize, 1, fp); CLZObject zObj; if (CLZO::instance().Decompress(zObj, data, g_adwItemProtoKey)) { printf("real_size %u\n", zObj.GetSize()); if (LoadNPrint) { for (DWORD i = 0; i < tableSize; ++i) { #ifdef ENABLE_PROTOSTRUCT_AUTODETECT CItemData::TItemTable rTable = {0}; CItemData::TItemTableAll::Process(zObj.GetBuffer(), structSize, i, rTable); #else CItemData::TItemTable & rTable = *((CItemData::TItemTable *) zObj.GetBuffer() + i); #endif printf("%u %s\n", rTable.dwVnum, rTable.szLocaleName); } } else { FILE * mf1; fopen_s(&mf1, "item_names.txt", "w"); FILE * mf2; fopen_s(&mf2, "item_proto.txt", "w"); // FILE * mf3; fopen_s(&mf3, "i1tem_proto.txt", "w"); if (mf1==NULL) { printf("item_names.txt not writable"); return; } if (mf2==NULL) { printf("item_proto.txt not writable"); return; } fprintf(mf1, "VNUM\tLOCALE_NAME\n"); fprintf(mf2, "ITEM_VNUM~RANGE\tITEM_NAME(K)\tITEM_TYPE\tSUB_TYPE\tMASKED_TYPE\tMASKED_SUB_TYPE\tSIZE\tANTI_FLAG\tFLAG\tITEM_WEAR\tIMMUNE\tGOLD\tSHOP_BUY_PRICE\tREFINE\tREFINESET\tMAGIC_PCT\tLIMIT_TYPE0\tLIMIT_VALUE0\tLIMIT_TYPE1\tLIMIT_VALUE1\tADDON_TYPE0\tADDON_VALUE0\tADDON_TYPE1\tADDON_VALUE1\tADDON_TYPE2\tADDON_VALUE2\tADDON_TYPE3\tADDON_VALUE3\tVALUE0\tVALUE1\tVALUE2\tVALUE3\tVALUE4\tVALUE5\tSpecular\tSOCKET\tATTU_ADDON\n"); for (DWORD i = 0; i < tableSize; ++i) { #ifdef ENABLE_PROTOSTRUCT_AUTODETECT CItemData::TItemTable rTable = {0}; CItemData::TItemTableAll::Process(zObj.GetBuffer(), structSize, i, rTable); #else CItemData::TItemTable & rTable = *((CItemData::TItemTable *) zObj.GetBuffer() + i); #endif fprintf(mf1, "%u %s\n", rTable.dwVnum, rTable.szLocaleName); // fprintf(mf3, "%d %d\n", rTable.bMaskType, rTable.bMaskSubType); fprintf(mf2, "%s %s" // 2 " %s %s %s %s %u %s" // 8 " %s %s %s" // 11 " %u %u %u %u %u" // 16 " %s %d %s %d" // 20 " %s %d %s %d %s %d %s %d" // 28 " %d %d %d %d %d %d" // 34 " %u %u %d" // 37 "\n", retrieveVnumRange(rTable.dwVnum, rTable.dwVnumRange).c_str(), rTable.szName, // 2 set_Item_Type_Value(rTable.bType).c_str(), set_Item_SubType_Value(rTable.bType, rTable.bSubType).c_str(), set_Item_MaskType_Value(rTable.bMaskType).c_str(), set_Item_MaskSubType_Value(rTable.bMaskType, rTable.bMaskSubType).c_str(), rTable.bSize, set_Item_AntiFlag_Value(rTable.dwAntiFlags).c_str(), // 8 set_Item_Flag_Value(rTable.dwFlags).c_str(), set_Item_WearFlag_Value(rTable.dwWearFlags).c_str(), set_Item_Immune_Value(rTable.dwImmuneFlag).c_str(), // 11 rTable.dwIBuyItemPrice, rTable.dwISellItemPrice, rTable.dwRefinedVnum, rTable.wRefineSet, rTable.bAlterToMagicItemPct, // 16 set_Item_LimitType_Value(rTable.aLimits[0].bType).c_str(), rTable.aLimits[0].lValue, set_Item_LimitType_Value(rTable.aLimits[1].bType).c_str(), rTable.aLimits[1].lValue, // 20 set_Item_ApplyType_Value(rTable.aApplies[0].bType).c_str(), rTable.aApplies[0].lValue, set_Item_ApplyType_Value(rTable.aApplies[1].bType).c_str(), rTable.aApplies[1].lValue, // 24 set_Item_ApplyType_Value(rTable.aApplies[2].bType).c_str(), rTable.aApplies[2].lValue, set_Item_ApplyType_Value(rTable.aApplies[3].bType).c_str(), rTable.aApplies[3].lValue, // 28 rTable.alValues[0], rTable.alValues[1], rTable.alValues[2], rTable.alValues[3], rTable.alValues[4], rTable.alValues[5], // 34 rTable.bSpecular, rTable.bGainSocketPct, retrieveAddonType(rTable.dwVnum) // 37 ); } ; } } free(data); } fclose(fp); } void SaveItemProto() { FILE * fp; fopen_s(&fp, "item_proto", "wb"); if (!fp) { printf("cannot open %s for writing\n", "item_proto"); return; } DWORD fourcc = MAKEFOURCC('M', 'I', 'P', 'X'); fwrite(&fourcc, sizeof(DWORD), 1, fp); DWORD dwVersion = 0x00000001; fwrite(&dwVersion, sizeof(DWORD), 1, fp); DWORD dwStride = sizeof(CItemData::TItemTable); fwrite(&dwStride, sizeof(DWORD), 1, fp); DWORD dwElements = m_iItemTableSize; fwrite(&dwElements, sizeof(DWORD), 1, fp); CLZObject zObj; std::vector <CItemData::TItemTable> vec_item_table (&m_pItemTable[0], &m_pItemTable[m_iItemTableSize - 1]); sort (&m_pItemTable[0], &m_pItemTable[0] + m_iItemTableSize); if (!CLZO::instance().CompressEncryptedMemory(zObj, m_pItemTable, sizeof(CItemData::TItemTable) * m_iItemTableSize, g_adwItemProtoKey)) { printf("cannot compress\n"); fclose(fp); return; } const CLZObject::THeader & r = zObj.GetHeader(); printf("Elements %d\n%u --Compress--> %u --Encrypt--> %u, GetSize %u\n", m_iItemTableSize, r.dwRealSize, r.dwCompressedSize, r.dwEncryptSize, zObj.GetSize()); DWORD dwDataSize = zObj.GetSize(); fwrite(&dwDataSize, sizeof(DWORD), 1, fp); fwrite(zObj.GetBuffer(), dwDataSize, 1, fp); fclose(fp); fopen_s(&fp, "item_proto", "rb"); if (!fp) { printf("Error!!\n"); return; } fread(&fourcc, sizeof(DWORD), 1, fp); fread(&dwElements, sizeof(DWORD), 1, fp); printf("Elements Check %u fourcc match %d\n", dwElements, fourcc == MAKEFOURCC('M', 'I', 'P', 'T')); fclose(fp); } int main(void) { setlocale(LC_ALL, "Turkish"); printf("Lütfen Yapmak İstediğiniz İşlemi Seçiniz:\n"); printf("Açma : 0\n"); printf("Kapatma : 1\n"); printf("Struct Size : 2\n"); BYTE a, b; bas: scanf("%d", &a); #ifdef _DEBUG printf("sizeof(TItemTable) %d\n", sizeof(CItemData::TItemTable)); printf("sizeof(TMobTable) %d\n", sizeof(CPythonNonPlayer::TMobTable)); #endif switch(a) { case 0: printf("Lütfen Açmak İstediğiniz Protoyu Seçiniz:\n"); printf("İtem : 0\n"); printf("Mob : 1\n"); printf("Her İkisi : 2\n"); bas1: scanf("%d", &b); switch(b) { case 0: LoadItemProto(); break; case 1: LoadMobProto(); break; case 2: LoadItemProto(); LoadMobProto(); break; default: printf("Lütfen Geçerli İşlemi Seçiniz !!"); goto bas1; } break; case 1: printf("Lütfen Kapatmak İstediğiniz Protoyu Seçiniz:\n"); printf("İtem : 0\n"); printf("Mob : 1\n"); printf("Her İkisi : 2\n"); bas2: scanf("%d", &b); switch(b) { case 0: if (BuildItemTable()) SaveItemProto(); break; case 1: if (BuildMobTable()) SaveMobProto(); break; case 2: if (BuildItemTable()) SaveItemProto(); if (BuildMobTable()) SaveMobProto(); break; default: printf("Lütfen Geçerli İşlemi Seçiniz !!"); goto bas2; } break; case 2: printf("İtem: %d\n", sizeof(CItemData::TItemTable)); printf("Mob: %d\n", sizeof(CPythonNonPlayer::TMobTable)); break; default: printf("Lütfen Geçerli İşlemi Seçiniz !!"); goto bas; } system("Pause"); return 0; }
[ "davidkm2012@gmail.com" ]
davidkm2012@gmail.com
c5d7c1fc3511197399e0a080010efbaa0c475c05
002fee4f2bfaeafd4c20116ec2ea3d49ecd91783
/macro/macroNparams2.cpp
11cf37312a97fb94065bb74e058e5526c1317502
[]
no_license
RuslanIvanov/testcpp
4d073e01ed191626d94ef91ce2a9613737b3bdb8
a8583cf6e81bc6456771b62ac9cfb596764c46fa
refs/heads/master
2022-06-27T00:49:38.990539
2022-06-17T07:02:40
2022-06-17T07:02:40
74,291,578
0
0
null
null
null
null
UTF-8
C++
false
false
264
cpp
// @author Subbotin B.P. // @see http://sbp-program.ru #include <stdio.h> #define mFirstMacro(nVar) ((nVar) + mSecondMacro(nVar)) #define mSecondMacro(nVar) ((nVar) * 2) int main() { int nVar = 5; printf("\nnVar = %d\n\n", mFirstMacro(nVar)); return 0; }
[ "rus_iv@list.ru" ]
rus_iv@list.ru
206f8f1dea4f8f4a5d273d50f38252e54c3a4661
f19896ff3a1016d4ae63db6e9345cfcc4d0a2967
/Topics/Topic/Data Structures and Alogrithms (Topic)/Grokking the Coding Interview/70(Search in a sorted infinte array).cpp
c692fbc59e4a463beecdefaf478b70fd0a832a8d
[]
no_license
Akshay199456/100DaysOfCode
079800b77a44abe560866cf4750dfc6c7fe01a59
b4ed8a6793c17bcb71c56686d98fcd683af64841
refs/heads/master
2023-08-08T07:59:02.723675
2023-08-01T03:44:15
2023-08-01T03:44:15
226,718,143
3
0
null
null
null
null
UTF-8
C++
false
false
4,047
cpp
/* Problem statement: Given an infinite sorted array (or an array with unknown size), find if a given number ‘key’ is present in the array. Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1. Since it is not possible to define an array with infinite (unknown) size, you will be provided with an interface ArrayReader to read elements of the array. ArrayReader.get(index) will return the number at index; if the array’s size is smaller than the index, it will return Integer.MAX_VALUE. Example 1: Input: [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30], key = 16 Output: 6 Explanation: The key is present at index '6' in the array. Example 2: Input: [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30], key = 11 Output: -1 Explanation: The key is not present in the array. Example 3: Input: [1, 3, 8, 10, 15], key = 15 Output: 4 Explanation: The key is present at index '4' in the array. Example 4: Input: [1, 3, 8, 10, 15], key = 200 Output: -1 Explanation: The key is not present in the array. */ /* ------------------------- My Approaches: 1. Time complexity: O() Space complexity: O() */ /* ------------------------- Other Approaches 1. Time complexity: O() Space complexity: O() */ /* ------------------------- Notes folllows the binary search pattern. since binary search helps us find a number in a sorted array efficiently, we can use a modified version of the binary search to find the 'key' in an infiinte sorted array. only issue with applying binary search in this problem is that we don't know the bounds of the array. to handle this situation, we will first find the proper bounds off the array where we can perform a binary search an efficeint way to find th eproper bounds is to start at the beginning of the array with the bound size as '1' and exponentailly increases the bounds's size (i.e double it ) untitl we fnd the bounds that can have the key. Time complexityy: two parts to algorithm. in first path, we keep increasing the bounds' size exponentailly (double it every time) while searching for the proper bounds. threfore,, this stepp will takle O(logn) assuming that the array will have maximum 'n' numbers. in the second step, we perform binary search which is O(logn). thus thte total time compelxity is O(logn + logn) = O(logn) Space compleixty: O(1) */ // My approaches(1) // Other Approaches(1) using namespace std; #include <iostream> #include <limits> #include <vector> class ArrayReader { public: vector<int> arr; ArrayReader(const vector<int> &arr) { this->arr = arr; } virtual int get(int index) { if (index >= arr.size()) { return numeric_limits<int>::max(); } return arr[index]; } }; class SearchInfiniteSortedArray { public: static int search(ArrayReader *reader, int key) { // find the proper bounds first int start = 0, end = 1; while (reader->get(end) < key) { int newStart = end + 1; end += (end - start + 1) * 2; // increase to double the bounds size start = newStart; } return binarySearch(reader, key, start, end); } private: static int binarySearch(ArrayReader *reader, int key, int start, int end) { while (start <= end) { int mid = start + (end - start) / 2; if (key < reader->get(mid)) { end = mid - 1; } else if (key > reader->get(mid)) { start = mid + 1; } else { // found the key return mid; } } return -1; } }; int main(int argc, char *argv[]) { ArrayReader *reader = new ArrayReader(vector<int>{4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}); cout << SearchInfiniteSortedArray::search(reader, 16) << endl; cout << SearchInfiniteSortedArray::search(reader, 11) << endl; reader = new ArrayReader(vector<int>{1, 3, 8, 10, 15}); cout << SearchInfiniteSortedArray::search(reader, 15) << endl; cout << SearchInfiniteSortedArray::search(reader, 200) << endl; delete reader; }
[ "akshay.kum94@gmail.com" ]
akshay.kum94@gmail.com
69ea27806f05e228d3f4daccff95354251e9bab0
084dad324cabef224ebe483792274f8b985beec6
/toolchain/hackImage/getCGImage.cpp
85906b5d4ee4b0b2ea509cb40d069cf14687cf6b
[]
no_license
iBruCe07/CrossGateRemastered
26c6cd71224ba8bd6b4f5f11053f150c6229c365
b99cd7c9c1bd823270feb016db62d8feb64ff41d
refs/heads/master
2020-05-16T04:55:17.424102
2019-03-16T16:25:35
2019-03-16T16:25:35
null
0
0
null
null
null
null
GB18030
C++
false
false
10,066
cpp
#include <iostream> #include <windows.h> #include <io.h> #include <sstream> #include <fstream> #include "getCGImage.h" #include "gdiImg.h" CGetCGImage::CGetCGImage() { // 获取程序路径 _strPath = Utils::getExePath(); } CGetCGImage::~CGetCGImage() { SAFE_DELETE_A(_imgEncode); SAFE_DELETE_A(_imgData); SAFE_DELETE_A(_imgPixel); } void CGetCGImage::doRun() { readCgp(); for (auto &item : g_ImgMap) { readInfo(item.first); readAndSaveImg(item.second); _vecImginfo.clear(); } saveFileJson(); } void CGetCGImage::clearData() { _uMapCgp.clear(); _vecImginfo.clear(); } void CGetCGImage::readCgp() { // 遍历pal目录下的所有文件 // 该目录下的调色板实际上只存有236个颜色,对应到图片为16-252 FILE *pFile = nullptr; intptr_t hFile = 0; struct _finddata_t fileinfo; std::string strPath = _strPath + "\\bin\\pal\\"; if ((hFile = _findfirst((strPath + "*").c_str(), &fileinfo)) != -1) { do { if (fileinfo.attrib & _A_SUBDIR) continue; std::string name = fileinfo.name; if (0 == fopen_s(&pFile, (strPath + name).c_str(), "rb")) { // 直接把调色板读写到数组中 std::array<unsigned char, DEFAULT_CPG_LEN> c; unsigned char *p = c.data(); if (708 == fread_s(p + 16 * 3, 708, 1, 708, pFile)) { // 将默认的调色板写入 前16后16 memcpy(p, g_c0_15, 16 * 3); memcpy(p + 240 * 3, g_c240_245, 16 * 3); _uMapCgp[name] = c; } else { // 调色板错误 } } if (pFile) fclose(pFile); } while (_findnext(hFile, &fileinfo) == 0); } } void CGetCGImage::readInfo(const std::string &strInfo) { FILE *pFile = nullptr; std::string strPath = _strPath + "\\bin\\"; if (0 == fopen_s(&pFile, (strPath + strInfo).c_str(), "rb")) { imgInfoHead tHead = { 0 }; int len = sizeof(imgInfoHead); while (len == fread_s(&tHead, len, 1, len, pFile)) { _vecImginfo.push_back(tHead); if (tHead.tileId != 0) { _tiledFilesJson[std::to_string(tHead.tileId)] = { {"id", tHead.id}, {"width", tHead.width}, {"height", tHead.height}, {"xOffset", tHead.xOffset}, {"yOffset", tHead.yOffset}, {"tileEast", tHead.tileEast}, {"tileSouth", tHead.tileSouth}, {"flag", tHead.flag} }; } } } if (pFile) fclose(pFile); std::cout << "readImgInfo: " << strInfo << " end" << std::endl; } void CGetCGImage::readAndSaveImg(const std::string &strName) { // 读取图片 FILE *pFile = nullptr; std::string strPath = _strPath + "\\bin\\"; if (0 != fopen_s(&pFile, (strPath + strName).c_str(), "rb")) return; // 记录错误日志 std::string strErrorFile = _strPath + "\\data\\"; Utils::makeSureDirExsits(strErrorFile); strErrorFile += "error.log"; // 生成的文件目录 std::string strSavePath = _strPath + "\\data\\" + strName.substr(0, strName.find_last_of(".")) + "\\"; for (auto &ii : _vecImginfo) { if (getImgData(pFile, ii, strName, strErrorFile)) { std::string strCgp = filleImgPixel(ii.width, ii.height); saveImgData(strCgp, strSavePath, ii); } } if (pFile) fclose(pFile); } bool CGetCGImage::getImgData(FILE *pFile, const imgInfoHead &imgHead, const std::string &strName, const std::string &strErrorFile) { if (!pFile) return false; // 定位到图片位置 fseek(pFile, imgHead.addr, SEEK_SET); // 取出对应图片数据头 imgData tHead = { 0 }; int len = sizeof(imgData); if (len == fread_s(&tHead, len, 1, len, pFile)) { // 这种是错误的图 if (tHead.width > 5000 || tHead.height > 5000) { saveLog(LOG_ERROR, strErrorFile, strName, "img w or h error", imgHead, tHead); return false; } _cgpLen = 0; // 调色板长度 if (tHead.cVer == 3) { // 多读取4个字节,代表的是调色板的长度 if (4 != fread_s(&_cgpLen, 4, 1, 4, pFile)) { saveLog(LOG_ERROR, strErrorFile, strName, "read cgpLen error", imgHead, tHead); return false; } len += 4; } int imgLen = imgHead.len - len; if (imgLen == fread_s(_imgEncode, imgLen, 1, imgLen, pFile)) { if (tHead.cVer == 0) { // 未压缩图片 _imgDataIdx = imgLen; memcpy(_imgData, _imgEncode, imgLen); } else if (tHead.cVer == 1 || tHead.cVer == 3) { // 压缩的图片 _imgDataIdx = decodeImgData(_imgEncode, imgLen); if (_imgDataIdx != tHead.width * tHead.height + _cgpLen) { // 这种情况按说是错的 if (_imgDataIdx < tHead.width * tHead.height + _cgpLen) { saveLog(LOG_ERROR, strErrorFile, strName, "decode len more", imgHead, tHead); return false; } else { // 大于的话应该算是不够严谨 saveLog(LOG_INFO, strErrorFile, strName, "decode len less", imgHead, tHead); } } } } } return true; } std::string CGetCGImage::filleImgPixel(int w, int h) { std::string strCgpName; memset(_imgPixel, 0, sizeof(_imgPixel) * sizeof(unsigned int)); // 默认使用palet_08.cgp(白天) 调色版 unsigned char *pCgp = _uMapCgp.begin()->second.data(); strCgpName = _uMapCgp.begin()->first; // 使用图片自带调色板 if (_cgpLen > 0 && (int)_imgDataIdx >= w * h + _cgpLen) { pCgp = _imgData + (_imgDataIdx - _cgpLen); strCgpName = "self"; } // 图片数据,竖向方向是反的,从最后一行开始 int imgLen = w * h; for (int i = 0; i < imgLen; ++i) { // 调色板编号 int cIdx = _imgData[i] * 3; int idx = (h - i / w - 1) * w + i % w; _imgPixel[idx] = (pCgp[cIdx]) + (pCgp[cIdx + 1] << 8) + (pCgp[cIdx + 2] << 16); if (pCgp[cIdx] != 0 || pCgp[cIdx + 1] != 0 || pCgp[cIdx + 2] != 0) _imgPixel[idx] |= 0xff000000; } return std::move(strCgpName); } void CGetCGImage::saveImgData(const std::string &cgpName, const std::string &strPath, const imgInfoHead &tHead) { // 存储_vecImgData // data/name/cgp/*.png FILE *pFile = nullptr; // 生成不同的目录,地图文件额外一个目录 int rangeBegin = tHead.id / 20000; std::string strSaveName = strPath; if (tHead.tileId == 0) strSaveName += std::to_string(rangeBegin * 20000) + "--" + std::to_string(rangeBegin * 20000 + 19999) + "\\"; else strSaveName += "tiled\\" + std::to_string(tHead.tileId) + "_"; strSaveName += cgpName + "_" + std::to_string(tHead.id); Utils::makeSureDirExsits(Utils::extractFileDir(strSaveName)); _tiledFilesJson[std::to_string(tHead.tileId)]["fullName"] = strSaveName + ".png"; CGdiSaveImg::getInstance()->saveImage(_imgPixel, tHead.width, tHead.height, strSaveName, "png"); std::cout << "createImg: id = " << tHead.id << " name = " << strSaveName << std::endl; } void CGetCGImage::saveFileJson() { std::ofstream ofs((_strPath + "\\data\\fileInfo.json").c_str(), std::ios::out | std::ios::trunc); if (ofs.bad()) return; ofs << _tiledFilesJson.dump(4); ofs.close(); } int CGetCGImage::decodeImgData(unsigned char *p, int len) { // 图片解密 Run-Length压缩 int iPos = 0; int idx = 0; while (iPos < len) { switch (p[iPos] & 0xF0) { case 0x00: { // 0x0n 第二个字节c,代表连续n个字符 int count = p[iPos] & 0x0F; ++iPos; for (int i = 0; i < count; ++i) _imgData[idx++] = p[iPos++]; } break; case 0x10: { // 0x1n 第二个字节x,第三个字节c,代表n*0x100+x个字符 int count = (p[iPos] & 0x0F) * 0x100 + p[iPos + 1]; iPos += 2; for (int i = 0; i < count; ++i) _imgData[idx++] = p[iPos++]; } break; case 0x20: { // 0x2n 第二个字节x,第三个字节y,第四个字节c,代表n*0x10000+x*0x100+y个字符 int count = (p[iPos] & 0x0F) * 0x10000 + p[iPos + 1] * 0x100 + p[iPos + 2]; iPos += 3; for (int i = 0; i < count; ++i) _imgData[idx++] = p[iPos++]; } break; case 0x80: { // 0x8n 第二个字节X,代表连续n个X int count = p[iPos] & 0x0F; for (int i = 0; i < count; ++i) _imgData[idx++] = p[iPos + 1]; iPos += 2; } break; case 0x90: { // 0x9n 第二个字节X,第三个字节m,代表连续n*0x100+m个X int count = (p[iPos] & 0x0F) * 0x100 + p[iPos + 2]; for (int i = 0; i < count; ++i) _imgData[idx++] = p[iPos + 1]; iPos += 3; } break; case 0xa0: { // 0xan 第二个字节X,第三个字节m,第四个字节z,代表连续n*0x10000+m*0x100+z个X int count = (p[iPos] & 0x0F) * 0x10000 + p[iPos + 2] * 0x100 + p[iPos + 3]; for (int i = 0; i < count; ++i) _imgData[idx++] = p[iPos + 1]; iPos += 4; } break; case 0xc0: { // 0xcn 同0x8n,只不过填充的是背景色 int count = p[iPos] & 0x0F; for (int i = 0; i < count; ++i) _imgData[idx++] = 0; iPos += 1; } break; case 0xd0: { // 0xdn 同0x9n,只不过填充的是背景色 int count = (p[iPos] & 0x0F) * 0x100 + p[iPos + 1]; for (int i = 0; i < count; ++i) _imgData[idx++] = 0; iPos += 2; } break; case 0xe0: { int count = (p[iPos] & 0x0F) * 0x10000 + p[iPos + 1] * 0x100 + p[iPos + 2]; for (int i = 0; i < count; ++i) _imgData[idx++] = 0; iPos += 3; } break; default: break; } } return idx; } void CGetCGImage::saveLog(int logLevel, const std::string &strErrorFile, const std::string &strName, const std::string &strTag, const imgInfoHead &tIdxHead, const imgData &tImgData) { std::ostringstream ostr; ostr << strTag << " file=" << strName << " id=" << tIdxHead.id << " tileId=" << tIdxHead.tileId << " ver=" << (int)tImgData.cVer << " w=" << tImgData.width << " h=" << tImgData.height << " imgHeadLen=" << tImgData.len << " cgpLen=" << _cgpLen << " decodeLen=" << _imgDataIdx << " expectLen=" << tImgData.width * tImgData.height; Utils::saveError((eLogLevel)logLevel, strErrorFile, ostr.str()); }
[ "447801388@qq.com" ]
447801388@qq.com
577a4b1347f88cde3ca9dc59fa7476e65ae767a6
ee146f21465cdd04ff78127aca1cf19b75263c7d
/EventNetwork.cpp
4d25a8ce9c56a4f163fc9a0b3b6c0de4afe64c8f
[]
no_license
mwcaisse/CS4513-Project4
a6c68d56f93482c57127022ba1903cb8d8de7e2b
fee88e225360c562b004d5afc0e2fac2157b1478
refs/heads/master
2016-08-07T14:06:24.573118
2014-05-07T02:13:53
2014-05-07T02:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,683
cpp
/* * EventNetwork.cpp * * Created on: Apr 30, 2014 * Author: mitchell */ #include "EventNetwork.h" #include "NetworkManager.h" EventNetwork::~EventNetwork() { // TODO Auto-generated destructor stub } EventNetwork::EventNetwork(message_header header, std::string data) { setData(data); setObjectType(header.object_type); setMiscInt(header.misc); setLength(header.len); setOperation((MessageOp)header.op); setType(NETWORK_EVENT); // set the type } /** Returns the length of the data stored * */ int EventNetwork::getLength() { return length; } int EventNetwork::getTotalLength() { return length + sizeof(message_header); } /** Returns the operation of the message * */ MessageOp EventNetwork::getOperation() { return operation; } /** Returns the object type * */ std::string EventNetwork::getObjectType() { return objectType; } /** Returns the misc int * */ int EventNetwork::getMiscInt() { return miscInt; } /** Returns the data of the message * */ std::string EventNetwork::getData() { return data; } /** Sets the length to the specified length * */ void EventNetwork::setLength(int len) { this->length = len; } /** Sets the message operation to the specified op * */ void EventNetwork::setOperation(MessageOp op) { this->operation = op; } /** Sets the object type to the specified type * */ void EventNetwork::setObjectType(std::string type) { this->objectType = type; } /** Sets the misc int to the specified int * */ void EventNetwork::setMiscInt(int misc) { this->miscInt = misc; } /** Sets the network data to the specified data * */ void EventNetwork::setData(std::string data) { this->data = data; }
[ "computers1055@gmail.com" ]
computers1055@gmail.com
a9c24ee695860b23e54d584db433392dbb1255cc
1c83efc404e92c94d0eafa6ecc1ff14068c8e152
/LR - 3 M - 2/TInteger.h
84317beb9f6a77ccfa793bd2fd7b5f2a030c066f
[]
no_license
anasteyshakoshman/BMSTU-projects
d5a355c36dc094d40ce20ea802655885bbc3962c
859f2c4dcf1e636daad997962a3408351193bbf9
refs/heads/master
2020-05-28T02:12:30.097470
2019-02-21T14:48:26
2019-02-21T14:48:26
82,578,531
0
0
null
null
null
null
UTF-8
C++
false
false
2,683
h
#pragma once #include <iostream> class TInteger { int Num; bool Error(const long long int); public: TInteger(); TInteger(const int); TInteger(const long long int); TInteger& operator =(const long long int); TInteger& operator +=(const long long int); TInteger& operator *=(const long long int); TInteger& operator %=(const long long int); TInteger& operator /=(const long long int); TInteger& operator -=(const long long int); bool operator ==(const int) const; bool operator <(const int) const; TInteger& operator ++(); TInteger& operator--(); TInteger(const TInteger&); TInteger& operator =(const TInteger&); TInteger& operator +=(const TInteger&); TInteger& operator *=(const TInteger&); TInteger& operator %=(const TInteger&); TInteger& operator /=(const TInteger&); TInteger& operator -=(const TInteger&); bool operator ==(const TInteger&) const; bool operator <(const TInteger&) const; operator int(); TInteger& operator =(const int); TInteger& operator +=(const int); TInteger& operator *=(const int); TInteger& operator %=(const int); TInteger& operator /=(const int); TInteger& operator -=(const int); friend std::ostream & operator<<(std::ostream & out, const TInteger &); }; TInteger operator %(const TInteger&, const long long int); TInteger operator /(const TInteger&, const long long int); TInteger operator *(const TInteger&, const long long int); TInteger operator +(const TInteger&, const long long int); TInteger operator -(const TInteger&, const long long int); bool operator !=(const TInteger&, const int); bool operator >(const TInteger&, const int); TInteger operator %(const long long int, const TInteger&); TInteger operator /(const long long int, const TInteger&); TInteger operator *(const long long int, const TInteger&); TInteger operator +(const long long int, const TInteger&); TInteger operator -(const long long int, const TInteger&); bool operator !=(const int, const TInteger&); bool operator >(const int, const TInteger&); TInteger operator %(const TInteger&, const TInteger&); TInteger operator /(const TInteger&, const TInteger&); TInteger operator *(const TInteger&, const TInteger&); TInteger operator +(const TInteger&, const TInteger&); TInteger operator -(const TInteger&, const TInteger&); bool operator !=(const TInteger&, const TInteger&); bool operator >(const TInteger&, const TInteger&); TInteger operator %(const TInteger&, const int); TInteger operator /(const TInteger&, const int); TInteger operator *(const TInteger&, const int); TInteger operator +(const TInteger&, const int); TInteger operator -(const TInteger&, const int);
[ "noreply@github.com" ]
anasteyshakoshman.noreply@github.com
0c640b4c6d80c37ad17871f9b0368268d1ce5947
996bc0532faeb4412900da251aa0355303dee60d
/Src/Modules/Modeling/KalmanWorldModelGenerator/Models/MultiKalmanModel_impl.h
bc9e840b131b799c8ee5ebc5dc6ac64e5ba0c88b
[ "BSD-2-Clause" ]
permissive
HospitableHost/NaoDevilsCodeRelease
66814d1126a1b226c16c391f367df54e55290b62
b47d2ce3474236325b9114913968b2eb39d0754e
refs/heads/master
2022-04-01T13:10:59.507343
2020-01-22T19:42:18
2020-01-22T19:46:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,666
h
/** * \file MultiKalmanModel_impl.h * \author <a href="mailto:heiner.walter@tu-dortmund.de">Heiner Walter</a> * * Implementation of class \c MultiKalmanModel. */ #include "MultiKalmanModel.h" #include "Tools/Math/Covariance.h" #include "Tools/Debugging/DebugDrawings.h" #include <algorithm> // std::find //MARK: Kalman filter related methods template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::removeOdometry(const Pose2f& odometryOffset) { // Encapsulate matrices describing the odometry offset (translation and rotation) // into this struct which is used to predict the kalman filter state. KalmanPositionTracking2D<double>::KalmanStateTransformation reverseOdometry; // Precompute sine and cosine of the odometry offset rotation. float odometryCos = std::cos(-odometryOffset.rotation); float odometrySin = std::sin(-odometryOffset.rotation); // Compute rotation and translation of the kalman state vector. reverseOdometry.stateRotationMatrix << odometryCos, -odometrySin, 0.0, 0.0, odometrySin, odometryCos, 0.0, 0.0, 0.0, 0.0, odometryCos, -odometrySin, 0.0, 0.0, odometrySin, odometryCos; reverseOdometry.stateTranslationVector << -odometryOffset.translation.x(), -odometryOffset.translation.y(), 0.0, 0.0; // Apply odometry offset to kalman filters of each hypothesis. for (size_t i = 0; i < m_hypotheses.size(); i++) { m_hypotheses[i].removeOdometry(reverseOdometry); } } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::motionUpdate(unsigned currentTimestamp, float friction) { // Run prediction step of each hypothesis. for (size_t i = 0; i < m_hypotheses.size(); i++) { m_hypotheses[i].motionUpdate(currentTimestamp, friction); } } template <typename hypothesis_t, bool towardsOneModel> hypothesis_t* MultiKalmanModel<hypothesis_t, towardsOneModel>::sensorUpdate( const Vector2f& measuredPosition, float measuredDistance, unsigned timestamp, float perceptValidity, float minDistanceForNewHypothesis, float initialValidityForNewHypothesis, const KalmanPositionTracking2D<double>::KalmanMatrices::Noise& kalmanNoiseMatrices) { return sensorUpdate( measuredPosition, measuredDistance, nullptr, // Run sensor update without measured velocity. timestamp, perceptValidity, minDistanceForNewHypothesis, initialValidityForNewHypothesis, kalmanNoiseMatrices); } template <typename hypothesis_t, bool towardsOneModel> hypothesis_t* MultiKalmanModel<hypothesis_t, towardsOneModel>::sensorUpdate( const Vector2f& measuredPosition, float measuredDistance, const Vector2f* measuredVelocity, unsigned timestamp, float perceptValidity, float minDistanceForNewHypothesis, float initialValidityForNewHypothesis, const KalmanPositionTracking2D<double>::KalmanMatrices::Noise& kalmanNoiseMatrices) { // Reset index of best hypothesis. This must be recalculated each frame. resetBestHypothesisIndex(); // Find the hypothesis which is nearest to the measurement. float distance; hypothesis_t* nearestHypothesis = findNearestHypothesis(measuredPosition, distance); if (nearestHypothesis != nullptr && distance < minDistanceForNewHypothesis) { // TODO: make parameter float measurementNoiseFactor = measuredDistance / 1000.f < 1.f ? 1.f : measuredDistance / 1000.f; // convert distance to m // Set measurementNoiseMatrix according to the direction from robot to measurement position. // In this direction (^= distance) the noise is set to a higher value than in the orthogonal direction (^= angle). float max = static_cast<float>(nearestHypothesis->kalman.matrices.noise.maxMeasurementNoise); max *= measurementNoiseFactor; nearestHypothesis->kalman.matrices.noise.measurementNoiseMatrix = Covariance::create((Vector2f() << max, max / 10.f).finished(), measuredPosition.angle()).cast<double>(); // Correct kalman filter with the perception. if (measuredVelocity == nullptr) nearestHypothesis->sensorUpdate(measuredPosition, timestamp, perceptValidity); else nearestHypothesis->sensorUpdate(measuredPosition, *measuredVelocity, timestamp, perceptValidity); } else { // Add new hypothesis if all existing ones are too far. m_hypotheses.push_back(hypothesis_t(kalmanNoiseMatrices, initialValidityForNewHypothesis, timestamp, perceptValidity, measuredPosition, getPerceptDuration(), measuredVelocity != nullptr ? *measuredVelocity : Vector2f::Zero())); nearestHypothesis = &m_hypotheses.back(); } return nearestHypothesis; } //MARK: Validity methods template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::updateValidity( float maxPerceptsPerSecond, float goodValidityThreshold, float weightOfPreviousValidity, float weightOfPreviousValidity_goodHypotheses) { // If there is at least one real good hypothesis, reduce validity of other hypotheses faster. bool goodHypothesisExists = false; if (bestHypothesis() && bestHypothesis()->validity >= goodValidityThreshold) { goodHypothesisExists = true; } // Update validity of all hypotheses. for (size_t i = 0; i < m_hypotheses.size(); i++) { if (m_hypotheses[i].validity >= goodValidityThreshold) m_hypotheses[i].updateValidity(maxPerceptsPerSecond, weightOfPreviousValidity_goodHypotheses); else if (towardsOneModel && goodHypothesisExists) m_hypotheses[i].updateValidity(maxPerceptsPerSecond, weightOfPreviousValidity / 2); else m_hypotheses[i].updateValidity(maxPerceptsPerSecond, weightOfPreviousValidity); } } //MARK: Helper methods template <typename hypothesis_t, bool towardsOneModel> hypothesis_t* MultiKalmanModel<hypothesis_t, towardsOneModel>::findNearestHypothesis( const Vector2f& measuredPosition, float& distance) { hypothesis_t* nearestHypothesis = nullptr; float minDistance = -1; for (size_t i = 0; i < m_hypotheses.size(); i++) { // Calculate distance from the perception to the current hypothesis. float currentDistance = Geometry::distance(measuredPosition, m_hypotheses[i].kalman.position()); // Check whether the current distance is shorter than the minimum of all // previous hypotheses. if (minDistance < 0 || currentDistance < minDistance) { nearestHypothesis = &m_hypotheses[i]; minDistance = currentDistance; } } distance = minDistance; return nearestHypothesis; } template <typename hypothesis_t, bool towardsOneModel> const hypothesis_t* MultiKalmanModel<hypothesis_t, towardsOneModel>::bestHypothesis() { updateBestHypothesisIndexIfNecessary(); if (m_bestHypothesisIndex == static_cast<size_t>(-1)) // Maximum size_t number { return nullptr; } return &m_hypotheses[m_bestHypothesisIndex]; } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::setParametersForUpdateBestHypothesis( float minValidity, std::size_t minNumber, float decreaseValidity) { minValidityForChangingBestHypothesis = minValidity; minNumberOfSensorUpdatesForBestHypothesis = minNumber; decreaseValidityOnChangingBestHypothesis = decreaseValidity; } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::resetBestHypothesisIndex() { // Reset index of best hypothesis. This must be recalculated each frame. m_lastBestHypothesisIndex = m_bestHypothesisIndex; m_bestHypothesisIndex = static_cast<size_t>(-1); // Maximum size_t number } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::updateBestHypothesis() { // If there is no hypothesis, there cannot be a best one. if (m_hypotheses.size() <= 0) { m_bestHypothesisIndex = static_cast<size_t>(-1); // Maximum size_t number return; } float minValidity = minValidityForChangingBestHypothesis; // If there was no best hypothesis in the last iteration or there is only one hypothesis, // use the current best one without limitations on validity. if (m_lastBestHypothesisIndex == static_cast<size_t>(-1) || m_hypotheses.size() == size_t(1)) { minValidity = 0.f; } // Search for the best hypothesis. size_t bestIndex = -1; float bestValidity = -1.f; for (size_t i = 0; i < m_hypotheses.size(); i++) { // Check validity and number of sensor updates. if (m_hypotheses[i].validity > bestValidity && // highest validity and m_hypotheses[i].numberOfSensorUpdates() >= minNumberOfSensorUpdatesForBestHypothesis) { // Found even better hypothesis. Remember new best one. bestIndex = i; bestValidity = m_hypotheses[bestIndex].validity; } } // Update pointer to best hypothesis if bestValidity exceeds the // validity threshold. if (bestValidity >= minValidity) { if (m_lastBestHypothesisIndex < m_hypotheses.size() && m_lastBestHypothesisIndex != bestIndex) { // Best hypothesis has changed. float lastBestValidity = m_hypotheses[m_lastBestHypothesisIndex].validity; if (bestValidity > lastBestValidity) { // For changing the best hypothesis, the validity must be truly greater than the old one. // Hysteresis: Reduce validity of last best hypothesis. m_hypotheses[m_lastBestHypothesisIndex].validity -= decreaseValidityOnChangingBestHypothesis; // Set new best hypothesis m_bestHypothesisIndex = bestIndex; } } else { // Set best hypothesis. m_bestHypothesisIndex = bestIndex; } } } template <typename hypothesis_t, bool towardsOneModel> std::size_t MultiKalmanModel<hypothesis_t, towardsOneModel>::updateBestHypothesisIndexIfNecessary() { if (m_bestHypothesisIndex == static_cast<size_t>(-1) && m_hypotheses.size() > 0) { // Compute index of best hypothesis. updateBestHypothesis(); } return m_bestHypothesisIndex; } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::increaseVelocityUncertainty(double factor, bool onlyBestHypothesis) { updateBestHypothesisIndexIfNecessary(); if (onlyBestHypothesis) { if (m_bestHypothesisIndex == static_cast<size_t>(-1)) // Maximum size_t number return; // No best hypothesis available // Increase velocity covariance. Position covariance stays unchanged. m_hypotheses[m_bestHypothesisIndex].increaseFilterCovariance(1.f, factor); } else { for (size_t i = 0; i < m_hypotheses.size(); i++) { // Increase velocity covariance. Position covariance stays unchanged. m_hypotheses[i].increaseFilterCovariance(1.f, factor); } } } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::cleanUpHypothesesOutsideField( const FieldDimensions& theFieldDimensions, const RobotPose& theRobotPose, float fieldBorderThreshold) { updateBestHypothesisIndexIfNecessary(); // ----- Remove hypotheses outside the field ----- ASSERT(fieldBorderThreshold > 0.f); for (size_t i = 0; i < m_hypotheses.size(); i++) { // The check isInsideField requires global field coordinates. Use RobotPose // (from last frame) to calculate this. Vector2f globalPos = m_hypotheses[i].kalman.position(); if (usesRelativeCoordinates()) globalPos = Transformation::robotToField(theRobotPose, globalPos); // Hypothesis must be outside the field border ... if (!theFieldDimensions.fieldBorder.isInside(globalPos)) { // ... and outside the field border + threshold to be removed. // Get closest distance from position to field border. Vector2f closestPosOnBorder = theFieldDimensions.fieldBorder.getClosestPoint(globalPos); float distance = (closestPosOnBorder - globalPos).norm(); // Check if hypothesis is inside field border + threshold to allow a bit clearance for inaccuracy. if (distance > fieldBorderThreshold) { m_hypotheses.erase(m_hypotheses.begin() + i); if (m_bestHypothesisIndex == i) m_bestHypothesisIndex = static_cast<size_t>(-1); // Maximum size_t number else if (i < m_bestHypothesisIndex && m_bestHypothesisIndex != static_cast<size_t>(-1)) m_bestHypothesisIndex--; i--; } } } } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::cleanUpHypothesesLowValidity(float validityThreshold, bool saveBestHypothesis) { // Do nothing if there is no hypothesis. if (m_hypotheses.size() <= 0) return; // Get validity of best hypothesis. float bestValidity = 1.f; if (saveBestHypothesis) { updateBestHypothesisIndexIfNecessary(); if (m_bestHypothesisIndex == static_cast<size_t>(-1) && m_lastBestHypothesisIndex < m_hypotheses.size()){ m_bestHypothesisIndex = m_lastBestHypothesisIndex; } if (m_bestHypothesisIndex < m_hypotheses.size()) { bestValidity = m_hypotheses[m_bestHypothesisIndex].validity; } } // ----- Clean low validity hypotheses ----- // Remove hypotheses with too small validity, but do not remove the best one. // This ensures, that at least one hypothesis is left (if set was not empty). for (size_t i = 0; i < m_hypotheses.size(); i++) { if (m_hypotheses[i].validity < validityThreshold && m_hypotheses[i].validity < bestValidity) { m_hypotheses.erase(m_hypotheses.begin() + i); if (m_bestHypothesisIndex == i) m_bestHypothesisIndex = static_cast<size_t>(-1); // Maximum size_t number else if (i < m_bestHypothesisIndex && m_bestHypothesisIndex != static_cast<size_t>(-1)) m_bestHypothesisIndex--; i--; } } } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::cleanUpHypothesesSimilarToBestOne( float minDistanceForSeparateHypotheses, float minAngleForSeparateHypotheses) { updateBestHypothesisIndexIfNecessary(); if (m_bestHypothesisIndex == static_cast<size_t>(-1)) return; // ----- Clean similar hypotheses (similar to the best one) ----- // Search for hypotheses to remove. for (size_t i = 0; i < m_hypotheses.size(); i++) { // Do nothing if current hypothesis is the best one. if (i != m_bestHypothesisIndex && m_bestHypothesisIndex < m_hypotheses.size()) { // Calculate distance and angle (velocity) between best and current hypothesis. float distance = Geometry::distance(m_hypotheses[m_bestHypothesisIndex].kalman.position(), m_hypotheses[i].kalman.position()); float angle = Geometry::angleBetween(m_hypotheses[m_bestHypothesisIndex].kalman.velocity(), m_hypotheses[i].kalman.velocity()); bool smallVelocities = m_hypotheses[m_bestHypothesisIndex].kalman.velocity().norm() < minDistanceForSeparateHypotheses / 30.f && m_hypotheses[i].kalman.velocity().norm() < minDistanceForSeparateHypotheses / 30.f; // Remove current hypothesis if it is too similar to the best one. if (distance < minDistanceForSeparateHypotheses && (angle < minAngleForSeparateHypotheses || smallVelocities)) { m_hypotheses[m_bestHypothesisIndex].merge(m_hypotheses[i]); // Remove hypothesis i m_hypotheses.erase(m_hypotheses.begin() + i); if (i < m_bestHypothesisIndex && m_bestHypothesisIndex != static_cast<size_t>(-1)) m_bestHypothesisIndex--; i--; } } } } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::clear() { m_hypotheses.clear(); m_bestHypothesisIndex = static_cast<size_t>(-1); // Maximum size_t number } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::addHypothesis(const hypothesis_t& newHypothesis) { m_hypotheses.push_back(newHypothesis); } template <typename hypothesis_t, bool towardsOneModel> void MultiKalmanModel<hypothesis_t, towardsOneModel>::addHypothesis(hypothesis_t&& newHypothesis) { m_hypotheses.push_back(std::forward<hypothesis_t>(newHypothesis)); }
[ "aaron.larisch@tu-dortmund.de" ]
aaron.larisch@tu-dortmund.de
cd584bbdd1c900fa39dd54bcb986aab153cb9f1a
cdcb94426af4b4842aad35b487214f282ed457a0
/COM/models/modcpua21.h
741c73f80600aa42c1ef6c39e839e6a0b4794c9b
[]
no_license
MEN-Mikro-Elektronik/13Y008-90
968898487c637b7cd26b7922b11adbc448d3a242
1877b1cc897c11e81b5526e68cdda4802240ba5e
refs/heads/master
2023-05-25T05:06:02.116975
2023-05-04T07:49:23
2023-05-04T07:49:23
143,159,201
0
0
null
2023-05-04T07:49:25
2018-08-01T13:22:53
C++
UTF-8
C++
false
false
2,781
h
/*************************************************************************** */ /*! \file modcpua21.h * \brief MEN CPU A21 classes * \author Dieter.Pfeuffer@men.de * $Date: 2015/05/26 17:19:18 $ * $Revision: 2.4 $ * * Switches: - */ /*-------------------------------[ History ]--------------------------------- * * $Log: modcpua21.h,v $ * Revision 2.4 2015/05/26 17:19:18 ts * R: gituser autocheckin: updated source * * Revision 2.3 2014/08/22 15:56:54 dpfeuffer * R: inconsistent PC-MIP/PMC/PCI104/XMC and Chameleon usage * M: PC-MIP/PMC/PCI104/XMC and Chameleon usage completely revised * * Revision 2.2 2014/07/18 15:12:30 dpfeuffer * R: erroneous PMC support, missing ComExpress support, general maintenance * M: intermediate check-in during development * * Revision 2.1 2013/03/04 13:07:31 dpfeuffer * Initial Revision * *--------------------------------------------------------------------------- * (c) Copyright 2003-2013 by MEN Mikro Elektronik GmbH, Nuremberg, Germany ****************************************************************************/ #ifndef MODCPUA21_H #define MODCPUA21_H #include "hwcomponent.h" #include "descriptor.h" #include "modbbispcigen.h" // ----------------------------------------------------------------- //! MEN CPU A21 class ModCpuA21 : public CpuDeviceSmb { public: enum SubModel { A21, A21Msi }; enum Mezzanines { WithMmods, WithPmcs }; ModCpuA21(SubModel submod, Mezzanines mezzanines, bool withSubDevs=true ); // create another instance virtual Device *create(bool withSubDevs=true); SwModuleList *enumSwModules(); Arch getArch() { return Ppc; } private: SubModel _submod; Mezzanines _mezzanines; }; //! BBIS class for A21 onboard M-Modules/devices class ModBbisA21 : public BbisDevice { public: ModBbisA21(bool withSubDevs=true); virtual Device *create(bool withSubDevs=true) { return new ModBbisA21(withSubDevs); } SwModuleList *enumSwModules(); virtual QString getDriverName( bool fullName=false, bool withSw=true); }; //! BBIS class for A21 onboard M-Modules/devices with MSI support class ModBbisA21Msi : public BbisDevice { public: ModBbisA21Msi(bool withSubDevs=true); virtual Device *create(bool withSubDevs=true) { return new ModBbisA21Msi(withSubDevs); } SwModuleList *enumSwModules(); virtual QString getDriverName( bool fullName=false, bool withSw=true); }; //! BBIS helper class for A21 MSI activation class ModBbisA21MsiEnable : public BbisDevice { public: ModBbisA21MsiEnable(bool withSubDevs=true); virtual Device *create(bool withSubDevs=true) { return new ModBbisA21MsiEnable(withSubDevs); } SwModuleList *enumSwModules(); virtual QString getDriverName( bool fullName=false, bool withSw=true); }; #endif
[ "thomas.schnuerer@men" ]
thomas.schnuerer@men
c2643b0e11c55404324d443d2339e2f88812c306
4e19a3a8500460337f22a9844eaa1bf2d8c59a5a
/CvGameCoreDLL_Expansion2/CvNotifications.cpp
7c91962c2fc5eebefacbe1f91d9ac8c5afc05928
[]
no_license
ZadesSC/Civilization-5-DLL
bc7a52515f7d080d3efe2da45838ab60d17b3372
9d3d7928768619dfd73bfa126d83dcac4799338e
refs/heads/master
2020-04-25T13:43:11.731893
2015-02-22T15:40:39
2015-02-22T15:40:39
31,167,527
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
58,803
cpp
/* ------------------------------------------------------------------------------------------------------- © 1991-2012 Take-Two Interactive Software and its subsidiaries. Developed by Firaxis Games. Sid Meier's Civilization V, Civ, Civilization, 2K Games, Firaxis Games, Take-Two Interactive Software and their respective logos are all trademarks of Take-Two interactive Software, Inc. All other marks and trademarks are the property of their respective owners. All rights reserved. ------------------------------------------------------------------------------------------------------- */ #include "CvGameCoreDLLPCH.h" #include "CvNotifications.h" #include "CvPlayer.h" #include "CvDiplomacyAI.h" #include "FStlContainerSerialization.h" #include "ICvDLLUserInterface.h" #include "CvEnumSerialization.h" #include "CvDllPlot.h" // Include this after all other headers. #include "LintFree.h" #define MAX_NOTIFICATIONS 100 static uint V1_IndexToHash[] = { NOTIFICATION_GENERIC, NOTIFICATION_TECH, NOTIFICATION_FREE_TECH, NOTIFICATION_POLICY, NOTIFICATION_PRODUCTION, NOTIFICATION_MET_MINOR, NOTIFICATION_MINOR, NOTIFICATION_MINOR_QUEST, NOTIFICATION_ENEMY_IN_TERRITORY, NOTIFICATION_CITY_RANGE_ATTACK, NOTIFICATION_BARBARIAN, NOTIFICATION_GOODY, NOTIFICATION_BUY_TILE, NOTIFICATION_CITY_GROWTH, NOTIFICATION_CITY_TILE, NOTIFICATION_DEMAND_RESOURCE, NOTIFICATION_UNIT_PROMOTION, NOTIFICATION_WONDER_COMPLETED_ACTIVE_PLAYER, NOTIFICATION_WONDER_COMPLETED, NOTIFICATION_WONDER_BEATEN, NOTIFICATION_GOLDEN_AGE_BEGUN_ACTIVE_PLAYER, NOTIFICATION_GOLDEN_AGE_ENDED_ACTIVE_PLAYER, NOTIFICATION_GREAT_PERSON_ACTIVE_PLAYER, NOTIFICATION_STARVING, NOTIFICATION_WAR_ACTIVE_PLAYER, NOTIFICATION_WAR, NOTIFICATION_PEACE_ACTIVE_PLAYER, NOTIFICATION_PEACE, NOTIFICATION_VICTORY, NOTIFICATION_UNIT_DIED, NOTIFICATION_CITY_LOST, NOTIFICATION_CAPITAL_LOST_ACTIVE_PLAYER, NOTIFICATION_CAPITAL_LOST, NOTIFICATION_CAPITAL_RECOVERED, NOTIFICATION_PLAYER_KILLED, NOTIFICATION_DISCOVERED_LUXURY_RESOURCE, NOTIFICATION_DISCOVERED_STRATEGIC_RESOURCE, NOTIFICATION_DISCOVERED_BONUS_RESOURCE, NOTIFICATION_DIPLO_VOTE, NOTIFICATION_RELIGION_RACE, NOTIFICATION_EXPLORATION_RACE, NOTIFICATION_DIPLOMACY_DECLARATION, NOTIFICATION_DEAL_EXPIRED_GPT, NOTIFICATION_DEAL_EXPIRED_RESOURCE, NOTIFICATION_DEAL_EXPIRED_OPEN_BORDERS, NOTIFICATION_DEAL_EXPIRED_DEFENSIVE_PACT, NOTIFICATION_DEAL_EXPIRED_RESEARCH_AGREEMENT, NOTIFICATION_DEAL_EXPIRED_TRADE_AGREEMENT, NOTIFICATION_TECH_AWARD, NOTIFICATION_PLAYER_DEAL, NOTIFICATION_PLAYER_DEAL_RECEIVED, NOTIFICATION_PLAYER_DEAL_RESOLVED, NOTIFICATION_PROJECT_COMPLETED, NOTIFICATION_REBELS, NOTIFICATION_FREE_POLICY, NOTIFICATION_FREE_GREAT_PERSON, NOTIFICATION_DENUNCIATION_EXPIRED, NOTIFICATION_FRIENDSHIP_EXPIRED, NOTIFICATION_RELIGION_FOUNDED_ACTIVE_PLAYER, NOTIFICATION_RELIGION_FOUNDED, NOTIFICATION_PANTHEON_FOUNDED_ACTIVE_PLAYER, NOTIFICATION_PANTHEON_FOUNDED, NOTIFICATION_FOUND_PANTHEON, NOTIFICATION_FOUND_RELIGION, NOTIFICATION_ENHANCE_RELIGION, NOTIFICATION_RELIGION_ENHANCED_ACTIVE_PLAYER, NOTIFICATION_RELIGION_ENHANCED, NOTIFICATION_SPY_CREATED_ACTIVE_PLAYER, NOTIFICATION_SPY_STOLE_TECH, NOTIFICATION_SPY_CANT_STEAL_TECH, NOTIFICATION_CAN_BUILD_MISSIONARY, NOTIFICATION_OTHER_PLAYER_NEW_ERA, NOTIFICATION_SPY_EVICTED, NOTIFICATION_RELIGION_SPREAD, NOTIFICATION_TECH_STOLEN_SPY_DETECTED, NOTIFICATION_TECH_STOLEN_SPY_IDENTIFIED, NOTIFICATION_SPY_WAS_KILLED, NOTIFICATION_SPY_KILLED_A_SPY, NOTIFICATION_SPY_REPLACEMENT, NOTIFICATION_MAYA_LONG_COUNT, NOTIFICATION_FAITH_GREAT_PERSON, NOTIFICATION_SPY_PROMOTION, NOTIFICATION_INTRIGUE_DECEPTION, NOTIFICATION_SPY_RIG_ELECTION_SUCCESS, NOTIFICATION_SPY_RIG_ELECTION_FAILURE, NOTIFICATION_SPY_RIG_ELECTION_ALERT, NOTIFICATION_SPY_YOU_STAGE_COUP_SUCCESS, NOTIFICATION_SPY_YOU_STAGE_COUP_FAILURE, NOTIFICATION_SPY_STAGE_COUP_SUCCESS, NOTIFICATION_SPY_STAGE_COUP_FAILURE, NOTIFICATION_INTRIGUE_BUILDING_SNEAK_ATTACK_ARMY, NOTIFICATION_INTRIGUE_BUILDING_SNEAK_ATTACK_AMPHIBIOUS, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_ARMY_AGAINST_KNOWN_CITY_UNKNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_ARMY_AGAINST_KNOWN_CITY_KNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_ARMY_AGAINST_YOU_CITY_UNKNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_ARMY_AGAINST_YOU_CITY_KNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_ARMY_AGAINST_UNKNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_AMPHIB_AGAINST_KNOWN_CITY_UNKNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_AMPHIB_AGAINST_KNOWN_CITY_KNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_AMPHIB_AGAINST_YOU_CITY_UNKNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_AMPHIB_AGAINST_YOU_CITY_KNOWN, NOTIFICATION_INTRIGUE_SNEAK_ATTACK_AMPHIB_AGAINST_UNKNOWN, NOTIFICATION_RELIGION_ERROR, NOTIFICATION_AUTOMATIC_FAITH_PURCHASE_STOPPED, NOTIFICATION_EXPANSION_PROMISE_EXPIRED, NOTIFICATION_BORDER_PROMISE_EXPIRED, NOTIFICATION_TRADE_ROUTE, NOTIFICATION_TRADE_ROUTE_BROKEN, NOTIFICATION_RELIGION_SPREAD_NATURAL, NOTIFICATION_INTRIGUE_CONSTRUCTING_WONDER, NOTIFICATION_MINOR_BUYOUT, NOTIFICATION_REQUEST_RESOURCE, NOTIFICATION_LIBERATED_MAJOR_CITY, NOTIFICATION_RESURRECTED_MAJOR_CIV, NOTIFICATION_ADD_REFORMATION_BELIEF, NOTIFICATION_LEAGUE_CALL_FOR_PROPOSALS, NOTIFICATION_CHOOSE_ARCHAEOLOGY, NOTIFICATION_LEAGUE_CALL_FOR_VOTES, NOTIFICATION_CHOOSE_IDEOLOGY, NOTIFICATION_IDEOLOGY_CHOSEN, NOTIFICATION_DIPLOMAT_EJECTED, NOTIFICATION_INTERNATIONAL_TRADE_UNIT_PLUNDERED_TRADER, NOTIFICATION_INTERNATIONAL_TRADE_UNIT_PLUNDERED_TRADEE, NOTIFICATION_REFORMATION_BELIEF_ADDED_ACTIVE_PLAYER, NOTIFICATION_REFORMATION_BELIEF_ADDED, NOTIFICATION_GREAT_WORK_COMPLETED_ACTIVE_PLAYER, NOTIFICATION_LEAGUE_VOTING_DONE, NOTIFICATION_LEAGUE_VOTING_SOON, NOTIFICATION_CULTURE_VICTORY_SOMEONE_INFLUENTIAL, NOTIFICATION_CULTURE_VICTORY_WITHIN_TWO, NOTIFICATION_CULTURE_VICTORY_WITHIN_TWO_ACTIVE_PLAYER, NOTIFICATION_CULTURE_VICTORY_WITHIN_ONE, NOTIFICATION_CULTURE_VICTORY_WITHIN_ONE_ACTIVE_PLAYER, NOTIFICATION_CULTURE_VICTORY_NO_LONGER_INFLUENTIAL, NOTIFICATION_PLAYER_RECONNECTED, NOTIFICATION_PLAYER_DISCONNECTED, NOTIFICATION_TURN_MODE_SEQUENTIAL, NOTIFICATION_TURN_MODE_SIMULTANEOUS, NOTIFICATION_HOST_MIGRATION, NOTIFICATION_PLAYER_CONNECTING, NOTIFICATION_CITY_REVOLT_POSSIBLE, NOTIFICATION_CITY_REVOLT }; /// Serialization read FDataStream& operator>>(FDataStream& loadFrom, CvNotifications::Notification& writeTo) { loadFrom >> writeTo.m_eNotificationType; loadFrom >> writeTo.m_strMessage; loadFrom >> writeTo.m_strSummary; loadFrom >> writeTo.m_iX; loadFrom >> writeTo.m_iY; loadFrom >> writeTo.m_iGameDataIndex; loadFrom >> writeTo.m_iExtraGameData; loadFrom >> writeTo.m_iTurn; loadFrom >> writeTo.m_iLookupIndex; loadFrom >> writeTo.m_bDismissed; loadFrom >> writeTo.m_ePlayerID; writeTo.m_bNeedsBroadcast = true; // all loads should re-broadcast their events writeTo.m_bWaitExtraTurn = false; // not saving this return loadFrom; } /// Serialization write FDataStream& operator<<(FDataStream& saveTo, const CvNotifications::Notification& readFrom) { saveTo << readFrom.m_eNotificationType; saveTo << readFrom.m_strMessage; saveTo << readFrom.m_strSummary; saveTo << readFrom.m_iX; saveTo << readFrom.m_iY; saveTo << readFrom.m_iGameDataIndex; saveTo << readFrom.m_iExtraGameData; saveTo << readFrom.m_iTurn; saveTo << readFrom.m_iLookupIndex; saveTo << readFrom.m_bDismissed; saveTo << readFrom.m_ePlayerID; // this is not saved because we want to re-broadcast on load // saveTo << writeTo.m_bBroadcast; // Not saving this either // saveTo << readFrom.m_bWaitExtraTurn; return saveTo; } void CvNotifications::Notification::Clear() { m_eNotificationType = NO_NOTIFICATION_TYPE; m_strMessage = ""; m_strSummary = ""; m_iX = -1; m_iY = -1; m_iGameDataIndex = -1; m_iTurn = -1; m_iLookupIndex = -1; m_bNeedsBroadcast = false; m_bDismissed = false; m_bWaitExtraTurn = false; } /// Constructor CvNotifications::CvNotifications(void) { Uninit(); } /// Destructor CvNotifications::~CvNotifications(void) { Uninit(); } /// Init void CvNotifications::Init(PlayerTypes ePlayer) { Uninit(); m_ePlayer = ePlayer; m_aNotifications.resize(MAX_NOTIFICATIONS); for(uint ui = 0; ui < m_aNotifications.size(); ui++) { m_aNotifications[ui].Clear(); } m_iNotificationsBeginIndex = 0; m_iNotificationsEndIndex = 0; } /// Uninit void CvNotifications::Uninit(void) { m_ePlayer = NO_PLAYER; m_iCurrentLookupIndex = 0; m_aNotifications.clear(); m_iNotificationsBeginIndex = -1; m_iNotificationsEndIndex = -1; } /// Serialization read void CvNotifications::Read(FDataStream& kStream) { // Version number to maintain backwards compatibility uint uiVersion; kStream >> uiVersion; kStream >> m_ePlayer; kStream >> m_iCurrentLookupIndex; kStream >> m_iNotificationsBeginIndex; kStream >> m_iNotificationsEndIndex; for(uint ui = 0; ui < MAX_NOTIFICATIONS; ui++) { kStream >> m_aNotifications[ui]; if (uiVersion <= 1) { // Translate the old index the hash ID. int iIndex = (int)(m_aNotifications[ui].m_eNotificationType); if (iIndex >= 0 && iIndex < sizeof(V1_IndexToHash)/sizeof(uint)) m_aNotifications[ui].m_eNotificationType = (NotificationTypes)V1_IndexToHash[iIndex]; } } } /// Serialization write void CvNotifications::Write(FDataStream& kStream) const { // Current version number uint uiVersion = 2; kStream << uiVersion; // need to serialize notification list kStream << m_ePlayer; kStream << m_iCurrentLookupIndex; kStream << m_iNotificationsBeginIndex; kStream << m_iNotificationsEndIndex; for(uint ui = 0; ui < MAX_NOTIFICATIONS; ui++) { kStream << m_aNotifications[ui]; } } /// Update - called from within CvPlayer void CvNotifications::Update(void) { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { Notification& kNotification = m_aNotifications[iIndex]; if(!kNotification.m_bDismissed) { if(IsNotificationExpired(iIndex)) { Dismiss(kNotification.m_iLookupIndex, /*bUserInvoked*/ false); //GC.GetEngineUserInterface()->RemoveNotification(kNotification.m_iLookupIndex); //kNotification.m_bDismissed = true; } else { if(kNotification.m_bNeedsBroadcast) { // If the notification is for the 'active' player and that active player actually has his turn active or its not hotseat, then show the notification, else wait. // The 'active' player is only set to a human and during the AI turn, the 'active' player is the last human to do their turn. if(kNotification.m_ePlayerID == GC.getGame().getActivePlayer()) { if(!CvPreGame::isHotSeatGame() || GET_PLAYER(GC.getGame().getActivePlayer()).isTurnActive()) { GC.GetEngineUserInterface()->AddNotification(kNotification.m_iLookupIndex, kNotification.m_eNotificationType, kNotification.m_strMessage.c_str(), kNotification.m_strSummary.c_str(), kNotification.m_iGameDataIndex, kNotification.m_iExtraGameData, m_ePlayer, kNotification.m_iX, kNotification.m_iY); kNotification.m_bNeedsBroadcast = false; } } else if(gDLL->IsPlayerConnected(kNotification.m_ePlayerID)) {//We consider a notification to have been broadcast if the notification //is for a remote player who is network connected to the game. kNotification.m_bNeedsBroadcast = false; } } } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } } // EndOfTurnCleanup - called from within CvPlayer at the end of turn void CvNotifications::EndOfTurnCleanup(void) { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(!m_aNotifications[iIndex].m_bDismissed) { if(IsNotificationEndOfTurnExpired(iIndex)) { if (m_aNotifications[iIndex].m_bWaitExtraTurn) m_aNotifications[iIndex].m_bWaitExtraTurn = false; else Dismiss(m_aNotifications[iIndex].m_iLookupIndex, /*bUserInvoked*/ false); } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } } /// Adds a new notification to the list int CvNotifications::AddByName(const char* pszNotificationName, const char* strMessage, const char* strSummary, int iX, int iY, int iGameDataIndex, int iExtraGameData) { if (pszNotificationName && pszNotificationName[0] != 0) { return Add((NotificationTypes) FString::Hash(pszNotificationName), strMessage, strSummary, iX, iY, iGameDataIndex, iExtraGameData); } return -1; } /// Adds a new notification to the list int CvNotifications::Add(NotificationTypes eNotificationType, const char* strMessage, const char* strSummary, int iX, int iY, int iGameDataIndex, int iExtraGameData) { // if the player is not human, do not record if(!GET_PLAYER(m_ePlayer).isHuman()) { return -1; } // If we're in debug mode, don't do anything if(GC.getGame().isDebugMode()) return -1; Notification newNotification; newNotification.Clear(); newNotification.m_ePlayerID = m_ePlayer; newNotification.m_eNotificationType = eNotificationType; newNotification.m_strMessage = strMessage; newNotification.m_strSummary = strSummary; newNotification.m_iX = iX; newNotification.m_iY = iY; newNotification.m_iGameDataIndex = iGameDataIndex; newNotification.m_iExtraGameData = iExtraGameData; newNotification.m_iTurn = GC.getGame().getGameTurn(); newNotification.m_iLookupIndex = m_iCurrentLookupIndex; newNotification.m_bNeedsBroadcast = true; newNotification.m_bDismissed = false; newNotification.m_bWaitExtraTurn = false; // Is this notification being added during the player's auto-moves and will it expire at the end of the turn? // If so, set a flag so the notification will stick around for an extra turn. if (GET_PLAYER(m_ePlayer).isTurnActive() && GET_PLAYER(m_ePlayer).isAutoMoves() && IsNotificationTypeEndOfTurnExpired(eNotificationType)) newNotification.m_bWaitExtraTurn = true; if(IsNotificationRedundant(newNotification)) { // redundant notification return -1; } if(IsArrayFull()) { RemoveOldestNotification(); } m_aNotifications[m_iNotificationsEndIndex] = newNotification; if(GC.getGame().isFinalInitialized()) { // If the notification is for the 'active' player and that active player actually has his turn active or its not hotseat, then show the notification, else wait // The 'active' player is only set to a human and during the AI turn, the 'active' player is the last human to do their turn. if(newNotification.m_ePlayerID == GC.getGame().getActivePlayer() && (!CvPreGame::isHotSeatGame() || GET_PLAYER(GC.getGame().getActivePlayer()).isTurnActive())) { GC.GetEngineUserInterface()->AddNotification(newNotification.m_iLookupIndex, newNotification.m_eNotificationType, newNotification.m_strMessage.c_str(), newNotification.m_strSummary.c_str(), newNotification.m_iGameDataIndex, newNotification.m_iExtraGameData, m_ePlayer, iX, iY); // Don't show effect with production notification if(eNotificationType != NOTIFICATION_PRODUCTION) { CvPlot* pPlot = GC.getMap().plot(iX, iY); if(pPlot != NULL) { auto_ptr<ICvPlot1> pDllPlot(new CvDllPlot(pPlot)); gDLL->GameplayDoFX(pDllPlot.get()); } else { gDLL->GameplayDoFX(NULL); } } m_aNotifications[m_iNotificationsEndIndex].m_bNeedsBroadcast = false; } gDLL->GameplayMinimapNotification(iX, iY, m_iCurrentLookupIndex+1); // The index is used to uniquely identify each flashing dot on the minimap. We're adding 1 since the selected unit is always 0. It ain't pretty, but it'll work } IncrementEndIndex(); m_iCurrentLookupIndex++; return newNotification.m_iLookupIndex; } // --------------------------------------------------------------------------- void CvNotifications::Activate(int iLookupIndex) { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(m_aNotifications[iIndex].m_iLookupIndex == iLookupIndex) { Activate(m_aNotifications[iIndex]); break; } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } } // --------------------------------------------------------------------------- void CvNotifications::Dismiss(int iLookupIndex, bool bUserInvoked) { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(m_aNotifications[iIndex].m_iLookupIndex == iLookupIndex) { m_aNotifications[iIndex].m_bDismissed = true; GC.GetEngineUserInterface()->RemoveNotification(m_aNotifications[iIndex].m_iLookupIndex, m_ePlayer); switch(m_aNotifications[iIndex].m_eNotificationType) { case NOTIFICATION_POLICY: { if(m_ePlayer == GC.getGame().getActivePlayer() && bUserInvoked) { GC.GetEngineUserInterface()->SetPolicyNotificationSeen(true); } } default: break; } break; } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } } // --------------------------------------------------------------------------- bool CvNotifications::MayUserDismiss(int iLookupIndex) { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(m_aNotifications[iIndex].m_iLookupIndex == iLookupIndex) { switch(m_aNotifications[iIndex].m_eNotificationType) { case NOTIFICATION_DIPLO_VOTE: case NOTIFICATION_PRODUCTION: case NOTIFICATION_TECH: case NOTIFICATION_FREE_TECH: case NOTIFICATION_FREE_POLICY: case NOTIFICATION_FREE_GREAT_PERSON: case NOTIFICATION_FOUND_PANTHEON: case NOTIFICATION_FOUND_RELIGION: case NOTIFICATION_ENHANCE_RELIGION: case NOTIFICATION_SPY_STOLE_TECH: case NOTIFICATION_MAYA_LONG_COUNT: case NOTIFICATION_FAITH_GREAT_PERSON: case NOTIFICATION_ADD_REFORMATION_BELIEF: case NOTIFICATION_LEAGUE_CALL_FOR_PROPOSALS: case NOTIFICATION_CHOOSE_ARCHAEOLOGY: case NOTIFICATION_LEAGUE_CALL_FOR_VOTES: case NOTIFICATION_CHOOSE_IDEOLOGY: return false; break; case NOTIFICATION_POLICY: if(GC.getGame().isOption(GAMEOPTION_POLICY_SAVING)) { return true; break; } else { return false; break; } default: return true; break; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } // --------------------------------------------------------------------------- void CvNotifications::Rebroadcast(void) { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(!m_aNotifications[iIndex].m_bDismissed) { m_aNotifications[iIndex].m_bNeedsBroadcast = true; } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } } // --------------------------------------------------------------------------- bool CvNotifications::GetEndTurnBlockedType(EndTurnBlockingTypes& eBlockingType, int& iNotificationIndex) { eBlockingType = NO_ENDTURN_BLOCKING_TYPE; iNotificationIndex = -1; int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(!m_aNotifications[iIndex].m_bDismissed) { switch(m_aNotifications[iIndex].m_eNotificationType) { case NOTIFICATION_CITY_RANGE_ATTACK: { bool automaticallyEndTurns = GC.getGame().isGameMultiPlayer() ? GC.GetEngineUserInterface()->IsMPAutoEndTurnEnabled() : GC.GetEngineUserInterface()->IsSPAutoEndTurnEnabled(); if(automaticallyEndTurns) {//City range attacks only block turns if the player is using auto end turn. eBlockingType = ENDTURN_BLOCKING_CITY_RANGE_ATTACK; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; } break; } case NOTIFICATION_DIPLO_VOTE: eBlockingType = ENDTURN_BLOCKING_DIPLO_VOTE; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_PRODUCTION: eBlockingType = ENDTURN_BLOCKING_PRODUCTION; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_POLICY: eBlockingType = ENDTURN_BLOCKING_POLICY; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_FREE_POLICY: eBlockingType = ENDTURN_BLOCKING_FREE_POLICY; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_TECH: eBlockingType = ENDTURN_BLOCKING_RESEARCH; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_FREE_TECH: eBlockingType = ENDTURN_BLOCKING_FREE_TECH; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_FREE_GREAT_PERSON: eBlockingType = ENDTURN_BLOCKING_FREE_ITEMS; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_FOUND_PANTHEON: eBlockingType = ENDTURN_BLOCKING_FOUND_PANTHEON; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_FOUND_RELIGION: eBlockingType = ENDTURN_BLOCKING_FOUND_RELIGION; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_ENHANCE_RELIGION: eBlockingType = ENDTURN_BLOCKING_ENHANCE_RELIGION; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_SPY_STOLE_TECH: eBlockingType = ENDTURN_BLOCKING_STEAL_TECH; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_MAYA_LONG_COUNT: eBlockingType = ENDTURN_BLOCKING_MAYA_LONG_COUNT; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_FAITH_GREAT_PERSON: eBlockingType = ENDTURN_BLOCKING_FAITH_GREAT_PERSON; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_ADD_REFORMATION_BELIEF: eBlockingType = ENDTURN_BLOCKING_ADD_REFORMATION_BELIEF; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_LEAGUE_CALL_FOR_PROPOSALS: eBlockingType = ENDTURN_BLOCKING_LEAGUE_CALL_FOR_PROPOSALS; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_CHOOSE_ARCHAEOLOGY: eBlockingType = ENDTURN_BLOCKING_CHOOSE_ARCHAEOLOGY; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_LEAGUE_CALL_FOR_VOTES: eBlockingType = ENDTURN_BLOCKING_LEAGUE_CALL_FOR_VOTES; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; case NOTIFICATION_CHOOSE_IDEOLOGY: eBlockingType = ENDTURN_BLOCKING_CHOOSE_IDEOLOGY; iNotificationIndex = m_aNotifications[iIndex].m_iLookupIndex; return true; break; default: // these notifications don't block, so don't return a blocking type break; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } // --------------------------------------------------------------------------- int CvNotifications::GetNumNotifications(void) { if(m_iNotificationsEndIndex >= m_iNotificationsBeginIndex) { int iValue = m_iNotificationsEndIndex - m_iNotificationsBeginIndex; return iValue; } int iValue = (m_aNotifications.size() - m_iNotificationsBeginIndex) + m_iNotificationsEndIndex; return iValue; } CvString CvNotifications::GetNotificationStr(int iZeroBasedIndex) // ignores the begin/end values { int iRealIndex = (m_iNotificationsBeginIndex + iZeroBasedIndex) % m_aNotifications.size(); return m_aNotifications[iRealIndex].m_strMessage; } CvString CvNotifications::GetNotificationSummary(int iZeroBasedIndex) { int iRealIndex = (m_iNotificationsBeginIndex + iZeroBasedIndex) % m_aNotifications.size(); return m_aNotifications[iRealIndex].m_strSummary; } int CvNotifications::GetNotificationID(int iZeroBasedIndex) // ignores begin/end values { int iRealIndex = (m_iNotificationsBeginIndex + iZeroBasedIndex) % m_aNotifications.size(); return m_aNotifications[iRealIndex].m_iLookupIndex; } int CvNotifications::GetNotificationTurn(int iZeroBasedIndex) { int iRealIndex = (m_iNotificationsBeginIndex + iZeroBasedIndex) % m_aNotifications.size(); return m_aNotifications[iRealIndex].m_iTurn; } bool CvNotifications::IsNotificationDismissed(int iZeroBasedIndex) { int iRealIndex = (m_iNotificationsBeginIndex + iZeroBasedIndex) % m_aNotifications.size(); return m_aNotifications[iRealIndex].m_bDismissed; } void CvNotifications::Activate(Notification& notification) { GC.GetEngineUserInterface()->ActivateNotification(notification.m_iLookupIndex, notification.m_eNotificationType, notification.m_strMessage, notification.m_iX, notification.m_iY, notification.m_iGameDataIndex, notification.m_iExtraGameData, m_ePlayer); gDLL->GameplayMinimapNotification(notification.m_iX, notification.m_iY, notification.m_iLookupIndex+1); // The index is used to uniquely identify each flashing dot on the minimap. We're adding 1 since the selected unit is always 0. It ain't pretty, but it'll work switch(notification.m_eNotificationType) { case NOTIFICATION_WONDER_COMPLETED_ACTIVE_PLAYER: { CvPopupInfo kPopup(BUTTONPOPUP_WONDER_COMPLETED_ACTIVE_PLAYER, notification.m_iGameDataIndex, notification.m_iExtraGameData, notification.m_iX, notification.m_iY); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_GREAT_WORK_COMPLETED_ACTIVE_PLAYER: { CvPopupInfo kPopup(BUTTONPOPUP_GREAT_WORK_COMPLETED_ACTIVE_PLAYER, notification.m_iGameDataIndex, notification.m_iExtraGameData, notification.m_iX, notification.m_iY); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_BUY_TILE: { // Jon say - do like Sid would! CvCity* pCity = GET_PLAYER(m_ePlayer).getCapitalCity(); if(pCity) { auto_ptr<ICvPlot1> pDllPlot = GC.WrapPlotPointer(pCity->plot()); GC.GetEngineUserInterface()->lookAt(pDllPlot.get(), CAMERALOOKAT_NORMAL); } } break; case NOTIFICATION_TECH: case NOTIFICATION_FREE_TECH: { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSETECH, m_ePlayer, notification.m_iGameDataIndex, notification.m_iExtraGameData); strcpy_s(kPopup.szText, notification.m_strMessage); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_TECH_AWARD: { if(notification.m_iExtraGameData != -1) { CvPopupInfo kPopup(BUTTONPOPUP_TECH_AWARD, m_ePlayer, notification.m_iGameDataIndex, notification.m_iExtraGameData); strcpy_s(kPopup.szText, notification.m_strMessage); GC.GetEngineUserInterface()->AddPopup(kPopup); } } break; case NOTIFICATION_POLICY: case NOTIFICATION_FREE_POLICY: { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSEPOLICY, m_ePlayer); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_DIPLO_VOTE: { CvPopupInfo kPopup(BUTTONPOPUP_DIPLO_VOTE, m_ePlayer); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_MINOR_QUEST: { int iQuestFlags = notification.m_iExtraGameData; CvPlot* pPlot = GC.getMap().plot(notification.m_iX, notification.m_iY); if(pPlot) { auto_ptr<ICvPlot1> pDllPlot = GC.WrapPlotPointer(pPlot); GC.GetEngineUserInterface()->lookAt(pDllPlot.get(), CAMERALOOKAT_NORMAL); gDLL->GameplayDoFX(pDllPlot.get()); } PlayerTypes ePlayer = (PlayerTypes)notification.m_iGameDataIndex; if (GET_PLAYER(ePlayer).isAlive()) { GC.GetEngineUserInterface()->SetTempString(notification.m_strMessage); CvPopupInfo kPopup(BUTTONPOPUP_CITY_STATE_MESSAGE, notification.m_iGameDataIndex, iQuestFlags); GC.GetEngineUserInterface()->AddPopup(kPopup); } } break; case NOTIFICATION_PRODUCTION: { CvCity* pCity = GC.getMap().plot(notification.m_iX, notification.m_iY)->getPlotCity();//GET_PLAYER(m_ePlayer).getCity(notification.m_iGameDataIndex); if(!pCity) { return; } CvPopupInfo kPopupInfo(BUTTONPOPUP_CHOOSEPRODUCTION); kPopupInfo.iData1 = pCity->GetID(); kPopupInfo.bOption2 = false; // Not in purchase mode // slewis - do we need the stuff below? //kPopupInfo.setOption1(false); OrderTypes eOrder = (OrderTypes) notification.m_iGameDataIndex; int iItemID = notification.m_iExtraGameData; kPopupInfo.iData2 = eOrder; kPopupInfo.iData3 = iItemID; GC.GetEngineUserInterface()->AddPopup(kPopupInfo); } break; case NOTIFICATION_UNIT_PROMOTION: { UnitHandle pUnit = GET_PLAYER(m_ePlayer).getUnit(notification.m_iExtraGameData); if(pUnit) { CvPlot* pPlot = pUnit->plot(); if(pPlot) { auto_ptr<ICvPlot1> pDllPlot = GC.WrapPlotPointer(pPlot); auto_ptr<ICvUnit1> pDllUnit = GC.WrapUnitPointer(pUnit.pointer()); GC.GetEngineUserInterface()->lookAt(pDllPlot.get(), CAMERALOOKAT_NORMAL); GC.GetEngineUserInterface()->selectUnit(pDllUnit.get(), false); gDLL->GameplayDoFX(pDllPlot.get()); } } } break; case NOTIFICATION_PLAYER_DEAL: { GC.GetEngineUserInterface()->OpenPlayerDealScreen((PlayerTypes) notification.m_iX); } break; case NOTIFICATION_PLAYER_DEAL_RECEIVED: { GC.GetEngineUserInterface()->OpenPlayerDealScreen((PlayerTypes) notification.m_iX); } break; case NOTIFICATION_FREE_GREAT_PERSON: { if(GET_PLAYER(m_ePlayer).GetNumFreeGreatPeople() > 0) { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSE_FREE_GREAT_PERSON, m_ePlayer, notification.m_iGameDataIndex, notification.m_iExtraGameData); GC.GetEngineUserInterface()->AddPopup(kPopup); } } break; case NOTIFICATION_FOUND_PANTHEON: { CvPopupInfo kPopup(BUTTONPOPUP_FOUND_PANTHEON, m_ePlayer, true /*bPantheonBelief*/); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_ADD_REFORMATION_BELIEF: { CvPopupInfo kPopup(BUTTONPOPUP_FOUND_PANTHEON, m_ePlayer, false /*bPantheonBelief*/); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_FOUND_RELIGION: case NOTIFICATION_ENHANCE_RELIGION: { CvPopupInfo kPopup(BUTTONPOPUP_FOUND_RELIGION, m_ePlayer); kPopup.iData1 = notification.m_iX; kPopup.iData2 = notification.m_iY; if(notification.m_eNotificationType == NOTIFICATION_FOUND_RELIGION) { kPopup.bOption1 = true; } else { kPopup.bOption1 = false; } GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_SPY_CREATED_ACTIVE_PLAYER: case NOTIFICATION_SPY_EVICTED: case NOTIFICATION_SPY_PROMOTION: { CvPopupInfo kPopup(BUTTONPOPUP_ESPIONAGE_OVERVIEW, m_ePlayer); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_SPY_STOLE_TECH: { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSE_TECH_TO_STEAL, m_ePlayer, notification.m_iGameDataIndex, notification.m_iExtraGameData); strcpy(kPopup.szText, notification.m_strMessage); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_MAYA_LONG_COUNT: { if(GET_PLAYER(m_ePlayer).GetNumMayaBoosts() > 0) { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSE_MAYA_BONUS, m_ePlayer, notification.m_iGameDataIndex, notification.m_iExtraGameData); GC.GetEngineUserInterface()->AddPopup(kPopup); } } break; case NOTIFICATION_FAITH_GREAT_PERSON: { if(GET_PLAYER(m_ePlayer).GetNumFaithGreatPeople() > 0) { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSE_FAITH_GREAT_PERSON, m_ePlayer, notification.m_iGameDataIndex, notification.m_iExtraGameData); GC.GetEngineUserInterface()->AddPopup(kPopup); } } break; case NOTIFICATION_TECH_STOLEN_SPY_IDENTIFIED: case NOTIFICATION_SPY_KILLED_A_SPY: { CvAssertMsg(notification.m_iGameDataIndex >= 0, "notification.m_iGameDataIndex is out of bounds"); if(notification.m_iGameDataIndex >= 0 && notification.m_iExtraGameData == -1) { PlayerTypes eTargetPlayer = (PlayerTypes)notification.m_iGameDataIndex; if (!GET_PLAYER(eTargetPlayer).isHuman()) { GET_PLAYER((PlayerTypes)notification.m_iGameDataIndex).GetDiplomacyAI()->DoBeginDiploWithHumanEspionageResult(); } GC.GetEngineUserInterface()->RemoveNotification(notification.m_iLookupIndex, m_ePlayer); notification.m_iExtraGameData = 1; // slewis hack to mark notification as seen so we don't re-enter diplomacy } } break; case NOTIFICATION_INTRIGUE_DECEPTION: case NOTIFICATION_INTRIGUE_SNEAK_ATTACK_ARMY_AGAINST_KNOWN_CITY_KNOWN: case NOTIFICATION_INTRIGUE_SNEAK_ATTACK_ARMY_AGAINST_KNOWN_CITY_UNKNOWN: case NOTIFICATION_INTRIGUE_SNEAK_ATTACK_AMPHIB_AGAINST_KNOWN_CITY_UNKNOWN: case NOTIFICATION_INTRIGUE_SNEAK_ATTACK_AMPHIB_AGAINST_KNOWN_CITY_KNOWN: CvAssertMsg(notification.m_iGameDataIndex >= 0, "notification.m_iGameDataIndex is out of bounds"); if(notification.m_iGameDataIndex >= 0) { PlayerTypes ePlayerToContact = (PlayerTypes)notification.m_iGameDataIndex; if (!GET_PLAYER(ePlayerToContact).isHuman() && ePlayerToContact != m_ePlayer && GET_PLAYER(m_ePlayer).GetEspionage()->HasRecentIntrigueAbout(ePlayerToContact) && !GET_TEAM(GET_PLAYER(m_ePlayer).getTeam()).isAtWar(GET_PLAYER(ePlayerToContact).getTeam())) { GET_PLAYER(ePlayerToContact).GetDiplomacyAI()->DoBeginDiploWithHumanInDiscuss(); } } break; case NOTIFICATION_LEAGUE_CALL_FOR_PROPOSALS: case NOTIFICATION_LEAGUE_CALL_FOR_VOTES: case NOTIFICATION_LEAGUE_VOTING_DONE: case NOTIFICATION_LEAGUE_VOTING_SOON: CvAssertMsg(notification.m_iGameDataIndex >= 0, "notification.m_iGameDataIndex is out of bounds"); if (notification.m_iGameDataIndex >= 0) { LeagueTypes eLeague = (LeagueTypes) notification.m_iGameDataIndex; CvPopupInfo kPopup(BUTTONPOPUP_LEAGUE_OVERVIEW, eLeague); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_IDEOLOGY_CHOSEN: case NOTIFICATION_CULTURE_VICTORY_SOMEONE_INFLUENTIAL: case NOTIFICATION_CULTURE_VICTORY_WITHIN_TWO: case NOTIFICATION_CULTURE_VICTORY_WITHIN_TWO_ACTIVE_PLAYER: case NOTIFICATION_CULTURE_VICTORY_WITHIN_ONE: case NOTIFICATION_CULTURE_VICTORY_WITHIN_ONE_ACTIVE_PLAYER: case NOTIFICATION_CULTURE_VICTORY_NO_LONGER_INFLUENTIAL: CvAssertMsg(notification.m_iGameDataIndex >= 0, "notification.m_iGameDataIndex is out of bounds"); if (notification.m_iGameDataIndex >= 0) { CvPopupInfo kPopup(BUTTONPOPUP_CULTURE_OVERVIEW); kPopup.iData2 = 3; // Tab to select GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_CHOOSE_ARCHAEOLOGY: CvAssertMsg(notification.m_iGameDataIndex >= 0, "notification.m_iGameDataIndex is out of bounds"); if (notification.m_iGameDataIndex >= 0) { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSE_ARCHAEOLOGY, m_ePlayer); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_CHOOSE_IDEOLOGY: CvAssertMsg(notification.m_iGameDataIndex >= 0, "notification.m_iGameDataIndex is out of bounds"); if (notification.m_iGameDataIndex >= 0) { CvPopupInfo kPopup(BUTTONPOPUP_CHOOSE_IDEOLOGY, m_ePlayer); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; case NOTIFICATION_LEAGUE_PROJECT_COMPLETE: CvAssertMsg(notification.m_iGameDataIndex >= 0, "notification.m_iGameDataIndex is out of bounds"); if (notification.m_iGameDataIndex >= 0) { LeagueTypes eLeague = (LeagueTypes) notification.m_iGameDataIndex; LeagueProjectTypes eProject = (LeagueProjectTypes) notification.m_iExtraGameData; CvPopupInfo kPopup(BUTTONPOPUP_LEAGUE_PROJECT_COMPLETED, eLeague, eProject); GC.GetEngineUserInterface()->AddPopup(kPopup); } break; default: // Default behavior is to move the camera to the X,Y passed in { CvPlot* pPlot = GC.getMap().plot(notification.m_iX, notification.m_iY); if(pPlot) { auto_ptr<ICvPlot1> pDllPlot = GC.WrapPlotPointer(pPlot); GC.GetEngineUserInterface()->lookAt(pDllPlot.get(), CAMERALOOKAT_NORMAL); gDLL->GameplayDoFX(pDllPlot.get()); } } break; } } // --------------------------------------------------------------------------- bool CvNotifications::IsNotificationRedundant(Notification& notification) { switch(notification.m_eNotificationType) { case NOTIFICATION_TECH: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { if (IsNotificationTypeEndOfTurnExpired(notification.m_eNotificationType) && notification.m_bWaitExtraTurn) { if (m_aNotifications[iIndex].m_bWaitExtraTurn) return true; } else // We already added this kind of notification so we don't need another return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_FREE_TECH: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // we've already added a free tech notification, don't need another return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_POLICY: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // we've already added a policy notification, don't need another return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_FREE_POLICY: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // we've already added a tech notification, don't need another return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_PRODUCTION: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType && notification.m_iX == m_aNotifications[iIndex].m_iX && notification.m_iY == m_aNotifications[iIndex].m_iY) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // we've already added a notification for this city to the notification system, so don't add another one return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_ENEMY_IN_TERRITORY: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { // Only one "enemy in territory" notification at a time if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_UNIT_PROMOTION: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(notification.m_iExtraGameData == m_aNotifications[iIndex].m_iExtraGameData) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // we've already added a notification for this unit to the notification system, so don't add another one return true; } } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_DIPLOMACY_DECLARATION: { PlayerTypes eOurPlayer1 = (PlayerTypes) notification.m_iGameDataIndex; PlayerTypes eOurPlayer2 = (PlayerTypes) notification.m_iExtraGameData; // Notification is NOT being used to inform of a DoF or Denouncement (otherwise there would be valid players in these slots) if(eOurPlayer1 == -1 || eOurPlayer2 == -1) return false; PlayerTypes eCheckingPlayer1, eCheckingPlayer2; int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { eCheckingPlayer1 = (PlayerTypes) m_aNotifications[iIndex].m_iGameDataIndex; eCheckingPlayer2 = (PlayerTypes) m_aNotifications[iIndex].m_iExtraGameData; // Players match - we already have a notification with this player combo if((eOurPlayer1 == eCheckingPlayer1 && eOurPlayer2 == eCheckingPlayer2) || (eOurPlayer1 == eCheckingPlayer2 && eOurPlayer2 == eCheckingPlayer1)) { return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) iIndex = 0; } return false; } break; case NOTIFICATION_FOUND_PANTHEON: case NOTIFICATION_FOUND_RELIGION: case NOTIFICATION_ENHANCE_RELIGION: case NOTIFICATION_ADD_REFORMATION_BELIEF: case NOTIFICATION_CHOOSE_ARCHAEOLOGY: case NOTIFICATION_CHOOSE_IDEOLOGY: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // we've already added a pantheon notification, don't need another return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_LEAGUE_CALL_FOR_PROPOSALS: case NOTIFICATION_LEAGUE_CALL_FOR_VOTES: case NOTIFICATION_LEAGUE_VOTING_SOON: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // we've already added one of this notification type, don't need another return true; } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; case NOTIFICATION_LEAGUE_PROJECT_COMPLETE: case NOTIFICATION_LEAGUE_PROJECT_PROGRESS: { int iIndex = m_iNotificationsBeginIndex; while(iIndex != m_iNotificationsEndIndex) { if(notification.m_eNotificationType == m_aNotifications[iIndex].m_eNotificationType) { if(!notification.m_bDismissed && !m_aNotifications[iIndex].m_bDismissed) { // Same League ID if (notification.m_iGameDataIndex == m_aNotifications[iIndex].m_iGameDataIndex) { // Same Project type if (notification.m_iExtraGameData == m_aNotifications[iIndex].m_iExtraGameData) { return true; } } } } iIndex++; if(iIndex >= (int)m_aNotifications.size()) { iIndex = 0; } } return false; } break; default: return false; break; } } bool CvNotifications::IsNotificationExpired(int iIndex) { switch(m_aNotifications[iIndex].m_eNotificationType) { case NOTIFICATION_BUY_TILE: { if(GET_PLAYER(m_ePlayer).GetTreasury()->GetGold() < GET_PLAYER(m_ePlayer).GetBuyPlotCost()) { return true; } } break; case NOTIFICATION_BARBARIAN: { CvPlot* pPlot = GC.getMap().plot(m_aNotifications[iIndex].m_iX, m_aNotifications[iIndex].m_iY); if(!pPlot->HasBarbarianCamp()) { return true; } } break; case NOTIFICATION_CITY_RANGE_ATTACK: { int iCityID = m_aNotifications[iIndex].m_iGameDataIndex; CvCity* pCity = GET_PLAYER(m_ePlayer).getCity(iCityID); if(pCity == NULL) return true; else if(!pCity->CanRangeStrikeNow()) return true; } break; case NOTIFICATION_GOODY: { CvPlot* pPlot = GC.getMap().plot(m_aNotifications[iIndex].m_iX, m_aNotifications[iIndex].m_iY); if(!pPlot->isGoody(GET_PLAYER(m_ePlayer).getTeam())) { return true; } } break; case NOTIFICATION_TECH: { CvPlayerAI& kPlayer = GET_PLAYER(m_ePlayer); CvPlayerTechs* pkPlayerTechs = kPlayer.GetPlayerTechs(); if(pkPlayerTechs->GetCurrentResearch() != NO_TECH) { return true; } int iNotificationIndex = m_iNotificationsBeginIndex; while(iNotificationIndex != m_iNotificationsEndIndex) { if(NOTIFICATION_FREE_TECH == m_aNotifications[iNotificationIndex].m_eNotificationType) { if(!m_aNotifications[iNotificationIndex].m_bDismissed) { return true; } } iNotificationIndex++; if(iNotificationIndex >= (int)m_aNotifications.size()) { iNotificationIndex = 0; } } //Expire this notification if there are no more techs that can be researched at this time. return pkPlayerTechs->GetNumTechsCanBeResearched() == 0; } break; case NOTIFICATION_FREE_TECH: { CvPlayerAI& kPlayer = GET_PLAYER(m_ePlayer); if(kPlayer.GetNumFreeTechs() == 0) { return true; } else { //Expire this notification if there are no more techs that can be researched at this time. return kPlayer.GetPlayerTechs()->GetNumTechsCanBeResearched() == 0; } } break; case NOTIFICATION_FREE_POLICY: { if(GC.getGame().isOption(GAMEOPTION_POLICY_SAVING)) { if(GET_PLAYER(m_ePlayer).GetNumFreePolicies() == 0 && GET_PLAYER(m_ePlayer).GetNumFreeTenets() == 0) return true; } else { if((GET_PLAYER(m_ePlayer).getJONSCulture() < GET_PLAYER(m_ePlayer).getNextPolicyCost() && GET_PLAYER(m_ePlayer).GetNumFreePolicies() == 0 && GET_PLAYER(m_ePlayer).GetNumFreeTenets() == 0)) return true; } } break; case NOTIFICATION_FREE_GREAT_PERSON: { if(GET_PLAYER(m_ePlayer).GetNumFreeGreatPeople() == 0) { return true; } } break; case NOTIFICATION_MAYA_LONG_COUNT: { if(GET_PLAYER(m_ePlayer).GetNumMayaBoosts() == 0) { return true; } } break; case NOTIFICATION_FAITH_GREAT_PERSON: { if(GET_PLAYER(m_ePlayer).GetNumFaithGreatPeople() == 0) { return true; } } break; case NOTIFICATION_POLICY: { if(GET_PLAYER(m_ePlayer).getJONSCulture() < GET_PLAYER(m_ePlayer).getNextPolicyCost() && GET_PLAYER(m_ePlayer).GetNumFreePolicies() == 0 && GET_PLAYER(m_ePlayer).GetNumFreeTenets() == 0) { return true; } } break; case NOTIFICATION_PRODUCTION: { //CvCity* pCity = GET_PLAYER(m_ePlayer).getCity(m_aNotifications[iIndex].m_iGameDataIndex); CvCity* pCity = GC.getMap().plot(m_aNotifications[iIndex].m_iX, m_aNotifications[iIndex].m_iY)->getPlotCity();//GET_PLAYER(m_ePlayer).getCity(notification.m_iGameDataIndex); // if the city no longer exists if(!pCity) { return true; } // if the city is a puppet if(pCity->IsPuppet()) { return true; } // City has chosen something if(pCity->getOrderQueueLength() > 0) { return true; } } break; case NOTIFICATION_DIPLO_VOTE: { TeamTypes eTeam = GET_PLAYER(m_ePlayer).getTeam(); // Vote from this team registered if(GC.getGame().GetVoteCast(eTeam) != NO_TEAM) { return true; } // Votes from ALL teams registered. This is necessary in addition to the above if block, because if this player is the last to vote // then everything gets reset immediately, and it'll be NO_TEAM by the time this function is tested again if(GC.getGame().GetNumVictoryVotesExpected() == 0) { return true; } } break; case NOTIFICATION_UNIT_PROMOTION: { UnitHandle pUnit = GET_PLAYER(m_ePlayer).getUnit(m_aNotifications[iIndex].m_iExtraGameData); if(!pUnit || !pUnit->isPromotionReady()) { return true; } } break; case NOTIFICATION_PLAYER_DEAL: { CvGame& game = GC.getGame(); CvGameDeals* pDeals = game.GetGameDeals(); if(!pDeals->ProposedDealExists(m_ePlayer, (PlayerTypes)(m_aNotifications[iIndex].m_iX))) { return true; } } break; case NOTIFICATION_PLAYER_DEAL_RECEIVED: { CvGame& game = GC.getGame(); CvGameDeals* pDeals = game.GetGameDeals(); if(!pDeals->ProposedDealExists((PlayerTypes)(m_aNotifications[iIndex].m_iX), m_ePlayer)) { return true; } } break; case NOTIFICATION_DEMAND_RESOURCE: { // if this is a "you ran out of this resource" demand resource. // I did this so not to break the save format if(m_aNotifications[iIndex].m_iX == -1 && m_aNotifications[iIndex].m_iY == -1) { if(GET_PLAYER(m_ePlayer).getNumResourceAvailable((ResourceTypes)m_aNotifications[iIndex].m_iGameDataIndex, true) >= 0) { return true; } } } case NOTIFICATION_FOUND_PANTHEON: { CvGame& kGame(GC.getGame()); CvGameReligions* pkReligions(kGame.GetGameReligions()); return pkReligions->CanCreatePantheon(m_ePlayer, true) != CvGameReligions::FOUNDING_OK; } break; case NOTIFICATION_ADD_REFORMATION_BELIEF: { CvGame& kGame(GC.getGame()); CvGameReligions* pkReligions(kGame.GetGameReligions()); return pkReligions->HasAddedReformationBelief(m_ePlayer); } case NOTIFICATION_FOUND_RELIGION: { CvGame& kGame(GC.getGame()); CvGameReligions* pkReligions(kGame.GetGameReligions()); if (pkReligions->GetNumReligionsStillToFound() <= 0) return true; // None left, dismiss the notification return pkReligions->HasCreatedReligion(m_ePlayer); } break; case NOTIFICATION_ENHANCE_RELIGION: { CvGame& kGame(GC.getGame()); CvGameReligions* pkReligions(kGame.GetGameReligions()); if (pkReligions->GetAvailableEnhancerBeliefs().size() == 0) return true; // None left, dismiss the notification. if (pkReligions->GetAvailableFollowerBeliefs().size() == 0) return true; // None left, dismiss the notification. ReligionTypes eReligion = pkReligions->GetReligionCreatedByPlayer(m_ePlayer); const CvReligion* pReligion = pkReligions->GetReligion(eReligion, m_ePlayer); return (NULL != pReligion && pReligion->m_bEnhanced); } break; case NOTIFICATION_SPY_STOLE_TECH: { CvPlayerEspionage* pEspionage = GET_PLAYER(m_ePlayer).GetEspionage(); if (pEspionage->m_aiNumTechsToStealList[m_aNotifications[iIndex].m_iGameDataIndex] <= 0) { return true; } else { return false; } } break; case NOTIFICATION_LEAGUE_CALL_FOR_PROPOSALS: { LeagueTypes eLeague = (LeagueTypes) m_aNotifications[iIndex].m_iGameDataIndex; CvLeague* pLeague = GC.getGame().GetGameLeagues()->GetLeague(eLeague); if (!pLeague->CanPropose(m_ePlayer)) { return true; } else { return false; } } break; case NOTIFICATION_CHOOSE_ARCHAEOLOGY: { if (GET_PLAYER(m_ePlayer).GetNumArchaeologyChoices() == 0) { return true; } } break; case NOTIFICATION_CHOOSE_IDEOLOGY: { if (GET_PLAYER(m_ePlayer).GetPlayerPolicies()->GetLateGamePolicyTree() != NO_POLICY_BRANCH_TYPE) { return true; } } break; case NOTIFICATION_LEAGUE_CALL_FOR_VOTES: { LeagueTypes eLeague = (LeagueTypes) m_aNotifications[iIndex].m_iGameDataIndex; CvLeague* pLeague = GC.getGame().GetGameLeagues()->GetLeague(eLeague); if (!pLeague->CanVote(m_ePlayer)) { return true; } else { return false; } } break; case NOTIFICATION_PLAYER_CONNECTING: { if(!gDLL->IsPlayerHotJoining(m_aNotifications[iIndex].m_iGameDataIndex)){ //Player has finished hot joining. Remove this notification, we'll add a NOTIFICATION_PLAYER_RECONNECTED in NetProxy::OnHotJoinComplete(). return true; } } break; default: // don't expire { return false; } break; } return false; } // --------------------------------------------------------------------------- bool CvNotifications::IsNotificationTypeEndOfTurnExpired(NotificationTypes eNotificationType, int iForSpecificEntry /*= -1*/) { switch(eNotificationType) { case NOTIFICATION_POLICY: case NOTIFICATION_FREE_POLICY: case NOTIFICATION_TECH: case NOTIFICATION_FREE_TECH: case NOTIFICATION_PRODUCTION: case NOTIFICATION_DIPLO_VOTE: case NOTIFICATION_PLAYER_DEAL: case NOTIFICATION_PLAYER_DEAL_RECEIVED: case NOTIFICATION_FREE_GREAT_PERSON: case NOTIFICATION_FOUND_PANTHEON: case NOTIFICATION_FOUND_RELIGION: case NOTIFICATION_ENHANCE_RELIGION: case NOTIFICATION_SPY_STOLE_TECH: case NOTIFICATION_MAYA_LONG_COUNT: case NOTIFICATION_FAITH_GREAT_PERSON: case NOTIFICATION_ADD_REFORMATION_BELIEF: case NOTIFICATION_LEAGUE_CALL_FOR_PROPOSALS: case NOTIFICATION_CHOOSE_ARCHAEOLOGY: case NOTIFICATION_LEAGUE_CALL_FOR_VOTES: case NOTIFICATION_CHOOSE_IDEOLOGY: return false; break; // These multiplayer notifications expire at the end of the next turn. case NOTIFICATION_PLAYER_RECONNECTED: case NOTIFICATION_PLAYER_DISCONNECTED: case NOTIFICATION_HOST_MIGRATION: case NOTIFICATION_PLAYER_CONNECTING: if(iForSpecificEntry != -1 && m_aNotifications[iForSpecificEntry].m_iTurn == GC.getGame().getGameTurn()) //same turn as creation. { return false; } break; // In multiplayer, these notifications expire once they've been broadcast for the player and // it is at least the end of the next turn. // These are notifications that can occur mid-turn and are important enough that they shouldn't // expire until the player has seen them. case NOTIFICATION_UNIT_PROMOTION: case NOTIFICATION_CAPITAL_LOST_ACTIVE_PLAYER: case NOTIFICATION_CAPITAL_LOST: case NOTIFICATION_WAR_ACTIVE_PLAYER: case NOTIFICATION_WAR: case NOTIFICATION_PEACE_ACTIVE_PLAYER: case NOTIFICATION_PEACE: case NOTIFICATION_VICTORY: case NOTIFICATION_UNIT_DIED: case NOTIFICATION_CITY_LOST: case NOTIFICATION_PLAYER_KILLED: case NOTIFICATION_DIPLOMACY_DECLARATION: case NOTIFICATION_OTHER_PLAYER_NEW_ERA: case NOTIFICATION_MINOR_BUYOUT: case NOTIFICATION_LIBERATED_MAJOR_CITY: case NOTIFICATION_RESURRECTED_MAJOR_CIV: case NOTIFICATION_TURN_MODE_SEQUENTIAL: case NOTIFICATION_TURN_MODE_SIMULTANEOUS: case NOTIFICATION_PLAYER_KICKED: //XP1 case NOTIFICATION_RELIGION_FOUNDED_ACTIVE_PLAYER: case NOTIFICATION_RELIGION_FOUNDED: case NOTIFICATION_PANTHEON_FOUNDED_ACTIVE_PLAYER: case NOTIFICATION_PANTHEON_FOUNDED: //XP2 case NOTIFICATION_TRADE_ROUTE_BROKEN: case NOTIFICATION_REFORMATION_BELIEF_ADDED_ACTIVE_PLAYER: case NOTIFICATION_REFORMATION_BELIEF_ADDED: if(iForSpecificEntry != -1 && GC.getGame().isGameMultiPlayer() && (m_aNotifications[iForSpecificEntry].m_bNeedsBroadcast //not broadcast yet. || m_aNotifications[iForSpecificEntry].m_iTurn == GC.getGame().getGameTurn())) //same turn as creation. { return false; } break; default: return true; break; } return true; } // --------------------------------------------------------------------------- bool CvNotifications::IsNotificationEndOfTurnExpired(int iIndex) { return IsNotificationTypeEndOfTurnExpired( m_aNotifications[iIndex].m_eNotificationType, iIndex ); } // --------------------------------------------------------------------------- bool CvNotifications::IsArrayFull() { int iAdjustedEndIndex = m_iNotificationsEndIndex + 1; if(iAdjustedEndIndex >= (int)m_aNotifications.size()) { iAdjustedEndIndex = 0; } if(iAdjustedEndIndex == m_iNotificationsBeginIndex) { return true; } else { return false; } } // --------------------------------------------------------------------------- void CvNotifications::RemoveOldestNotification() { // if the notification is somehow active, dismiss it if(!m_aNotifications[m_iNotificationsBeginIndex].m_bDismissed) { Dismiss(m_aNotifications[m_iNotificationsBeginIndex].m_iLookupIndex, /*bUserInvoked*/ false); } m_aNotifications[m_iNotificationsBeginIndex].Clear(); IncrementBeginIndex(); } void CvNotifications::IncrementBeginIndex() { m_iNotificationsBeginIndex++; if(m_iNotificationsBeginIndex >= (int)m_aNotifications.size()) { m_iNotificationsBeginIndex = 0; } } void CvNotifications::IncrementEndIndex() { m_iNotificationsEndIndex++; if(m_iNotificationsEndIndex >= (int)m_aNotifications.size()) { m_iNotificationsEndIndex = 0; } } // --------------------------------------------------------------------------- // static void CvNotifications::AddToPlayer(PlayerTypes ePlayer, NotificationTypes eNotificationType, const char* strMessage, const char* strSummary, int iX/*=-1*/, int iY/*=-1*/, int iGameDataIndex/*=-1*/, int iExtraGameData/*=-1*/) { if(ePlayer != NO_PLAYER) { CvPlayer& kPlayer = GET_PLAYER(ePlayer); if(kPlayer.isLocalPlayer()) { CvNotifications* pNotifications = kPlayer.GetNotifications(); if(pNotifications) { pNotifications->Add(eNotificationType, strMessage, strSummary, iX, iY, iGameDataIndex, iExtraGameData); } } } }
[ "zades@outlook.com" ]
zades@outlook.com
91690926e728a5896d6946e23c384b5199fe08ac
dea7524c07a10f7f4efdb8e8c652d0b2f7b5b816
/elementary/elementary3.cpp
fa346606853a9dc4e995ebd02904d52b951e9dc1
[]
no_license
gachikuku/simple_programming_cpp
e2b10ea7a3dd847a34ed49b8f0a42c9e42907c87
c02c18b2e221784d06e0aadcd3986c1332212c27
refs/heads/main
2023-08-26T04:41:24.728038
2021-11-03T11:23:54
2021-11-03T11:23:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
330
cpp
#include <bits/stdc++.h> #include <iostream> using namespace std; int main(void){ string name; cout << "What's your name. \n"; cin >> name; if (name == "Alice" || name == "Bob"){ cout << "Greetings, " << name << endl; } else{ printf("ew \n"); } return 0; }
[ "noreply@github.com" ]
gachikuku.noreply@github.com
752827ca7369d417581e282f8a901aa54d6dc8ec
1159aad523e90a3b6a724624a57050467b776712
/41FirstMissingPositive.cpp
a5868cc836d543abed779064767e51ecf9641641
[]
no_license
imlihao/leetcode
604fa52f2bd964af9d635fff9798808cfd5c7605
6724f935bcb00b3de68a061616ecf5913f3018f5
refs/heads/master
2021-01-04T20:34:03.897710
2020-05-02T11:37:50
2020-05-02T11:37:50
240,750,215
0
0
null
null
null
null
UTF-8
C++
false
false
1,761
cpp
#include <algorithm> #include <functional> #include <iostream> #include <queue> #include <sstream> #include <stack> #include <string> #include <vector> using namespace std; class Solution { public: int firstMissingPositive(vector<int> &nums) { // if (nums.size() == 0) // return 1; // if (nums.size() == 1) // return nums[0] == 1 ? 2 : 1; // vector<int> vec(nums.size() + 2, 1); // // for (int i = 0; i <= nums.size(); i++) // // { // // vec.push_back(i); // // } // for (auto &a : nums) // { // if (a > 0 && a <= nums.size()+1) // { // vec[a] = 0; // } // } // for (int i = 1; i <= nums.size()+1; i++) // { // if (vec[i] > 0) // return i; // } // return 1; if(nums.size() == 0) return 1; //case: nums == null or nums == [], return 1 for(int i = 0;i < nums.size();i++){ //use nums array itself, the ideal array should be {1,2,3,4} int curr = nums[i]; //swap if nums[index] != index + 1; while(curr - 1 >= 0 && curr - 1 < nums.size() && curr != nums[curr-1]){ int next = nums[curr-1]; nums[curr-1] = curr; curr = next; } } for(int i = 0;i< nums.size();i++){ //check if nums[index] == index + 1; if(nums[i] != i+1) return i+1; } return nums.size()+1; } }; int main() { vector<int> vt{3,4,-1,1}; auto vec = Solution().firstMissingPositive(vt); cout << vec << endl; system("pause"); }
[ "lihao92beyond@163.com" ]
lihao92beyond@163.com
5213f5d6672e76e69453384eecdd393f2b1553c9
c707f8d47e9aa04204a0709cc133777962efb477
/lengthqueue.cpp
438933cf4116ddc94a0d76d387462c3ce436f4fe
[]
no_license
yueyiqiu178/DataStructure
995cc55d2abd1ab2c30b7ef6b4dc697790dfd597
70b18a2c7c512b72f8b317d81cd41e3252fa9d43
refs/heads/master
2020-04-22T09:24:38.577376
2019-02-12T07:36:36
2019-02-12T07:36:36
170,271,182
0
0
null
null
null
null
BIG5
C++
false
false
2,380
cpp
#include<iostream> #define N 5 using namespace std; struct Queue{ int queuearray[N]; int front; int length; }; void createQueue(Queue *); int isFull(Queue *); int isEmpty(Queue *); void enQueue(Queue *,int *); void deQueue(Queue *,int *); void queueList(Queue *); int main(void) { Queue q; createQueue(&q); int choose,loopflag=1; int data; int k,y; while(loopflag){ cout << "\n(1)從佇列後端放資料\n(2)從佇列前端取資料\n(3)列出佇列中所有元素\n(0)結束 => "; cin >> choose; switch(choose){ case 0: loopflag=0; break; case 1: if(isFull(&q)){ cout<<"佇列已滿,Enqueue失敗"<<endl; break;} else cout << "請輸入欲放入之資料=> "; cin >> data; enQueue(&q,&data); break; case 2: if(isEmpty(&q)) cout << "佇列已空,Dequeue失敗"<<endl; else { deQueue(&q,&data); cout << "取出之資料為 => " <<data<< endl;} break; case 3: queueList(&q); break; default: cout<<"輸入錯誤"<<endl; break; } } getchar(); return 0; } void createQueue(Queue *p){ p->length=0; p->front=0; } int isFull(Queue *p){ if(p->length==N) return 1; } int isEmpty(Queue *p){ if(p->length==0) return 1; } void enQueue(Queue *p,int *x){ p->queuearray[(p->front+p->length)%N]=*x; p->length++; } void deQueue(Queue *p,int *x){ *x=p->queuearray[p->front]; p->front=(p->front+1)%N; p->length--; } void queueList(Queue *p){ int i,j; for (i=p->front,j=1;j<=p->length;i=(i+1)%N,j++ ) cout<<p->queuearray[i]<<" "; cout<<endl; }
[ "noreply@github.com" ]
yueyiqiu178.noreply@github.com
39cf381842aee9f9798d094ecdac71c3c67c7d85
68ff39ba5ea1905b0a3d05dbcc96a7efaa11a351
/catkin_ws/src/probot_demo/src/moveit_ik_demo (copy).cpp
77e165ba144f625957ac591de1ac7f5d57ddee61
[]
no_license
UndergroundCoderNeo/dual_arm_robot
60e3282a24643539bc61d35226a3362269308e0f
3b47c905b25aef67edbcadfb6e89a1a5af765827
refs/heads/master
2023-04-12T00:50:24.349890
2021-05-05T12:31:02
2021-05-05T12:31:02
363,605,051
1
0
null
null
null
null
UTF-8
C++
false
false
4,976
cpp
/*********************************************************************** Copyright 2019 Wuhan PS-Micro Technology Co., Itd. 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 <string> #include <ros/ros.h> #include <moveit/move_group_interface/move_group_interface.h> int getCup(moveit::planning_interface::MoveGroupInterface arm) { // 设置机器人终端的目标位置 geometry_msgs::Pose target_pose; target_pose.orientation.x = 0; target_pose.orientation.y = -0.819; target_pose.orientation.z = 0; target_pose.orientation.w = 0.574; target_pose.position.x = 0.1; target_pose.position.y = -0.3; target_pose.position.z = 0.9; // 设置机器臂当前的状态作为运动初始状态 arm.setStartStateToCurrentState(); arm.setPoseTarget(target_pose); // 进行运动规划,计算机器人移动到目标的运动轨迹,此时只是计算出轨迹,并不会控制机械臂运动 moveit::planning_interface::MoveGroupInterface::Plan plan; moveit::planning_interface::MoveItErrorCode success = arm.plan(plan); ROS_INFO("Plan (pose goal) %s",success?"":"FAILED"); //让机械臂按照规划的轨迹开始运动。 if(success) arm.execute(plan); sleep(10); return success; } int raiseCup(moveit::planning_interface::MoveGroupInterface arm) { // 设置机器人终端的目标位置 geometry_msgs::Pose target_pose; target_pose.orientation.x = 0; target_pose.orientation.y = -0.819; target_pose.orientation.z = 0; target_pose.orientation.w = 0.574; target_pose.position.x = 0.1; target_pose.position.y = -0.3; target_pose.position.z = 1.3; // 设置机器臂当前的状态作为运动初始状态 arm.setStartStateToCurrentState(); arm.setPoseTarget(target_pose); // 进行运动规划,计算机器人移动到目标的运动轨迹,此时只是计算出轨迹,并不会控制机械臂运动 moveit::planning_interface::MoveGroupInterface::Plan plan; moveit::planning_interface::MoveItErrorCode success = arm.plan(plan); ROS_INFO("Plan (pose goal) %s",success?"":"FAILED"); //让机械臂按照规划的轨迹开始运动。 if(success) arm.execute(plan); sleep(5); return success; } int rotateCup(moveit::planning_interface::MoveGroupInterface arm) { // 设置机器人终端的目标位置 geometry_msgs::Pose target_pose; target_pose.orientation.x = 0; target_pose.orientation.y = -0.819; target_pose.orientation.z = 0; target_pose.orientation.w = 0.574; target_pose.position.x = 0.1; target_pose.position.y = -0.3; target_pose.position.z = 1.3; // 设置机器臂当前的状态作为运动初始状态 arm.setStartStateToCurrentState(); arm.setPoseTarget(target_pose); // 进行运动规划,计算机器人移动到目标的运动轨迹,此时只是计算出轨迹,并不会控制机械臂运动 moveit::planning_interface::MoveGroupInterface::Plan plan; moveit::planning_interface::MoveItErrorCode success = arm.plan(plan); ROS_INFO("Plan (pose goal) %s",success?"":"FAILED"); //让机械臂按照规划的轨迹开始运动。 if(success) arm.execute(plan); sleep(5); return success; } int main(int argc, char **argv) { ros::init(argc, argv, "moveit_fk_demo"); ros::AsyncSpinner spinner(1); spinner.start(); moveit::planning_interface::MoveGroupInterface arm("left_manipulator"); //获取终端link的名称 std::string end_effector_link = arm.getEndEffectorLink(); //设置目标位置所使用的参考坐标系 std::string reference_frame = "base_link"; arm.setPoseReferenceFrame(reference_frame); //当运动规划失败后,允许重新规划 arm.allowReplanning(true); //设置位置(单位:米)和姿态(单位:弧度)的允许误差 arm.setGoalPositionTolerance(0.001); arm.setGoalOrientationTolerance(0.01); //设置允许的最大速度和加速度 arm.setMaxAccelerationScalingFactor(0.2); arm.setMaxVelocityScalingFactor(0.2); // 控制机械臂先回到初始化位置 arm.setNamedTarget("left_original"); arm.move(); sleep(1); // 控制机械臂先回到初始化位置 arm.setNamedTarget("left_original"); arm.move(); sleep(5); ros::shutdown(); return 0; }
[ "mac@Tc-X-deMacBook-Pro.local" ]
mac@Tc-X-deMacBook-Pro.local