text
stringlengths
8
6.88M
/* This file is part of SMonitor. Copyright 2015~2016 by: rayx email rayx.cn@gmail.com SMonitor 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. SMonitor 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ #include "CSplashscreen.h" #include <QImageReader> #include <QFont> CSplashScreen::CSplashScreen(QWidget *parent) : QSplashScreen(parent) { } CSplashScreen::~CSplashScreen() { if (m_nTimerID > 0) { killTimer(m_nTimerID); } } CSplashScreen::CSplashScreen(QPixmap pixmap,const QString &text) : m_splashPixmap(pixmap) { Qt::Alignment bottomLeft = Qt::AlignLeft | Qt::AlignBottom; setPixmap(pixmap); showMessage(text, bottomLeft, Qt::white); show(); } void CSplashScreen::hide() { if (m_nTimerID > 0) { killTimer(m_nTimerID); } QWidget::hide(); } void CSplashScreen::showImage(const QString &strPath) { /// ½âÎö¶¯»­Í¼Æ¬ QImageReader oImageReader(strPath); if(oImageReader.canRead()) { int nCount = oImageReader.imageCount(); for (int nIndex = 0; nIndex < nCount; nIndex++) { QImage oImage = oImageReader.read(); m_oImageList << oImage; } if (m_oImageList.count() > 0) { setPixmap(QPixmap::fromImage(m_oImageList.at(0))); m_nCurrFrame = 0; m_nTimerID = startTimer(200); //show(); } } show(); } void CSplashScreen::setText(const QString &text) { Qt::Alignment bottomLeft = Qt::AlignLeft | Qt::AlignBottom; showMessage(text, bottomLeft, Qt::black); } void CSplashScreen::waitMainWindow(QWidget *widget) { if (m_nTimerID > 0) { killTimer(m_nTimerID); } finish(widget); } void CSplashScreen::timerEvent(QTimerEvent *event) { if (m_nTimerID == event->timerId()) { setPixmap(QPixmap::fromImage(m_oImageList.at(m_nCurrFrame))); m_nCurrFrame++; if (m_nCurrFrame >= m_oImageList.count()) { m_nCurrFrame = 0; } } }
#include "test-tool.hpp" #include <iostream> #include <string> #include <vector> /** * Testing material. Int_array_base have two children classes: * one behaves as expected, the other does not. */ struct Int_array_base { std::size_t m_size; std::vector<int> m_vec; Int_array_base(std::vector<int>&& vec) : m_size {vec.size()} , m_vec {std::move(vec)} {} int size() const { return m_size; } int const& operator[](int i) const { return m_vec[i]; } int& operator[](int i) { return m_vec[i]; } }; struct Good_int_array : public Int_array_base { int m_size; Good_int_array(int sz) noexcept // here int is used as vector size : Int_array_base {std::vector<int>(sz, 0)} {} }; struct Bad_int_array : public Int_array_base { std::vector<int> m_vec; Bad_int_array(int i) noexcept // vector will contain one int value : Int_array_base {std::vector<int>{i}} {} }; /** * Tests for our array types. */ void test_array(Int_array_base const& array, int n) { EXPECT(array.size() == n, "array size must be " + std::to_string(n)) && EXPECT(array[0] == 0, "array[0] must be 0"); } int main() { std::size_t n = 8; auto const good_array = Good_int_array(n); auto const bad_array = Bad_int_array(n); test_array(good_array, n); test_array(bad_array, n); // other examples EXPECT(true, "this passes"); EXPECT(false, "this fails"); // short-circuiting EXPECT(true, "doesn't fail") && EXPECT(false, "tests and fails") && EXPECT(true, "since previous failed, this one doesn't tests"); EXPECT(true, "doesn't fail") || EXPECT(false, "this fails") || EXPECT(true, "but this tests anyway, because logical OR"); }
#include "cvimagewidget.h" #include "tabwidget.h" using namespace cv; using namespace std; Rect getZoomx2Rect(Point2f p, int width, int height){ Rect r; int x_pos = (int)(p.x * 100) / 20; int y_pos = (int)(p.y * 100) / 20; // w y h r.width = 0.6 * width; r.height = 0.6 * height; // x e y if (x_pos == 0 || x_pos == 1) r.x = 0; if (x_pos == 2) r.x = 0.2 * width; if (x_pos == 3 || x_pos == 4) r.x = 0.4 * width; if (y_pos == 0 || y_pos == 1) r.y = 0; if (y_pos == 2) r.y = 0.2 * height; if (y_pos == 3 || y_pos == 4) r.y = 0.4 * height; return r; } Rect getZoomx4Rect(Point2f p, int width,int height){ Rect r; int x_pos = (int)(p.x*100)/10; int y_pos = (int)(p.y*100)/10; // w y h r.width = 0.3*width; r.height = 0.3*height; // x r.x = (x_pos-1)*0.1*width; if(x_pos == 0) r.x = 0; if(x_pos == 9) r.x = 0.7*width; // y r.y = (y_pos-1)*0.1*height; if(y_pos == 0) r.y = 0; if(y_pos == 9) r.y = 0.7*height; return r; } /*----------------------* * * * * * CV WIDGET * * * * * *----------------------*/ QImage getQImage(const Mat& mat){ const uchar *qImageBuffer = (const uchar*)mat.data; QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_RGB888); return img.rgbSwapped(); } void CVImageWidget::zoom_x2(QPoint p){ zoom_mutex.lock(); zoom_x = 2; zoom_p = Point2f((double)p.x()/(double)width(),(double)p.y()/(double)height()); zoom_mutex.unlock(); getZoomx2Rect(zoom_p,0,0); } void CVImageWidget::zoom_x4(QPoint p){ zoom_mutex.lock(); zoom_x = 4; zoom_p = Point2f((double)p.x()/(double)width(),(double)p.y()/(double)height()); zoom_mutex.unlock(); } void CVImageWidget::undo_zoom(){ zoom_mutex.lock(); zoom_x = 1; zoom_mutex.unlock(); } Point2f CVImageWidget::getZoomP(){ return zoom_p; } int CVImageWidget::getZoomX(){ return zoom_x; } void CVImageWidget::cutImage(Mat& img){ // hacer recorte de la imagen para el zoom zoom_mutex.lock(); int zoomx = zoom_x; Point2f zoomp = zoom_p; zoom_mutex.unlock(); if(zoomx == 2){ Rect r = getZoomx2Rect(zoomp,img.cols,img.rows); Mat cut(img,r); cv::resize(cut,cut,cv::Size(img.cols,img.rows)); img = cut.clone(); } if(zoomx == 4){ Rect r = getZoomx4Rect(zoomp,img.cols,img.rows); Mat cut(img,r); cv::resize(cut,cut,cv::Size(img.cols,img.rows)); img = cut.clone(); } } void CVImageWidget::showImage(const cv::Mat& image) { if(image.data != 0 && !image.empty()){ last_size_ = geometry(); isblack_ = false; Mat _tmp = image.clone(); QImage qimage = getQImage(_tmp); setPixmap(QPixmap::fromImage(qimage)); } } void CVImageWidget::showBlack() { if(sizeChanged() || !isblack_){ last_size_ = geometry(); isblack_ = true; cv::resize(black_image_,black_image_,cv::Size(this->width(),this->height())); QImage qimage = getQImage(black_image_); setPixmap(QPixmap::fromImage(qimage)); } } bool CVImageWidget::sizeChanged(){ if (geometry() != last_size_) return true; return false; } int CVImageWidget::ptzButtonClicked(QPoint p){ int y_margin = 15; int x_margin = 15; int button_w = 22; int button_h = 22; int vertical_space = 0; int buttons_count = 7; if(p.x()>width()-x_margin-button_w && p.x()<width()-x_margin){ for(int i=0;i<buttons_count;i++) if(p.y() > y_margin+vertical_space*i+button_h*i && p.y() < y_margin+vertical_space*i+button_h*(i+1)) return i; return -1; }else{ return -1; } } void CVImageWidget::mousePressEvent(QMouseEvent *event){ if(drag_ && event->button() == Qt::LeftButton){ if(added_to_rep_list_){ selected_camera = camera_; for(uint i=0;i<cvwidgets.size();i++) cvwidgets[i]->selected_ = false; selected_ = true; int ptz_button = ptzButtonClicked(event->pos()); if(show_ptz_ && ptz_button!= -1){ switch (ptz_button) { case 0: camera_->ptzMove("l"); break; case 1: camera_->ptzMove("r"); break; case 2: camera_->ptzMove("u"); break; case 3: camera_->ptzMove("d"); break; case 4: camera_->ptzMove("+"); break; case 5: camera_->ptzMove("-"); break; case 6: camera_->startTour(); break; default: break; } }else{ int index = 0; for(uint i=0;i<cvwidgets.size();i++) if(cvwidgets[i] == this) index = i; QString data_s = QString::number(index); QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); dataStream << data_s; QMimeData *mimeData = new QMimeData; mimeData->setData(QStringLiteral("widget"), itemData); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); if (drag->exec(Qt::MoveAction) == Qt::MoveAction){} event->accept(); } }else{ event->ignore(); } }else{ event->ignore(); } } void CVImageWidget::dragEnterEvent(QDragEnterEvent *event){ if(drag_ && event->mouseButtons() == Qt::LeftButton){ if (event->mimeData()->hasFormat(QStringLiteral("camera")) || event->mimeData()->hasFormat(QStringLiteral("widget"))) event->accept(); else event->ignore(); }else{ event->ignore(); } } void CVImageWidget::dragLeaveEvent(QDragLeaveEvent *event){ if(drag_) event->accept(); else event->ignore(); } void CVImageWidget::dragMoveEvent(QDragMoveEvent *event){ if(drag_ && event->mouseButtons() == Qt::LeftButton){ if (event->mimeData()->hasFormat(QStringLiteral("camera")) || event->mimeData()->hasFormat(QStringLiteral("widget"))) { event->setDropAction(Qt::MoveAction); event->accept(); } else { event->ignore(); } }else{ event->ignore(); } } void CVImageWidget::removeFromUserInfo(){ if(grid_index_ != -1 && widget_index_ != -1) userinfo.grids[grid_index_]->cameras_id[widget_index_] = "0"; } void CVImageWidget::updateSlider(){ if(visible_ && camera_->playback_on_ && show_playback_){ if(playback_slider_->maximum() != userinfo.playback_secs){ playback_slider_->setRange(0,userinfo.playback_secs); playback_slider_->setValue(userinfo.playback_secs); sliderChanged(userinfo.playback_secs); } play_stop_button_->setGeometry(5,height()-23,24,24); playback_slider_->setGeometry(5,height()-23,width()-40,20); playback_label_->setGeometry(width()-33,height()-23,30,20); //play_stop_button_->show(); playback_slider_->show(); playback_label_->show(); }else{ playback_slider_->setValue(userinfo.playback_secs); sliderChanged(userinfo.playback_secs); play_stop_button_->hide(); playback_label_->hide(); playback_slider_->hide(); playback_min_ = 0; } } void CVImageWidget::setUserinfoGridsIndex(int grid_index,int widgetindex){ grid_index_ = grid_index; widget_index_ = widgetindex; } void CVImageWidget::dropCamera(Camera* camera){ camera_ = camera; cvwidgets.push_back(this); added_to_rep_list_ = true; //actualizar userinfo if(grid_index_ != -1 && widget_index_ != -1){ if(camera_->is_channel_){ userinfo.grids[grid_index_]->cameras_id[widget_index_] = to_string(camera_->channel_)+"$"+camera_->dhdevice_id_; }else{ userinfo.grids[grid_index_]->cameras_id[widget_index_] = camera->unique_id_; } } bool mongo_con; vsmongo->updateUserInfoGrids(mongo_con); // } void CVImageWidget::disableDragDrop(){ drag_ = false; drop_ = false; } void CVImageWidget::setZoom(int zoomx, Point2f zoomp){ zoom_mutex.lock(); zoom_x = zoomx; zoom_p = zoomp; zoom_mutex.unlock(); } void CVImageWidget::dropEvent(QDropEvent *event){ if(drop_){ bool handled = false; // si se suelta otro widget if (event->mimeData()->hasFormat("widget")){ QByteArray widgetData = event->mimeData()->data("widget"); QDataStream dataStream(&widgetData, QIODevice::ReadOnly); QString data_s; dataStream >> data_s; int sender_index = data_s.toInt(); CVImageWidget* sender = cvwidgets[sender_index]; Camera* sender_camera = sender->camera_; bool sender_ptz = sender->show_ptz_; sender->show_ptz_ = show_ptz_; show_ptz_ = sender_ptz; int zoomx = sender->getZoomX(); Point2f zoomp = sender->getZoomP(); // si este widget estaba reproduciendo algo, que ahora lo haga el sender if(added_to_rep_list_){ sender->camera_ = camera_; if(sender->grid_index_!=-1&&sender->widget_index_!=-1){ if(camera_->is_channel_){ userinfo.grids[sender->grid_index_]->cameras_id[sender->widget_index_] = to_string(camera_->channel_)+"$"+camera_->dhdevice_id_; }else{ userinfo.grids[sender->grid_index_]->cameras_id[sender->widget_index_] = camera_->unique_id_; } bool mongo_con; vsmongo->updateUserInfoGrids(mongo_con); } sender->setZoom(zoom_x,zoom_p); }else{ // borrar el sender: //cvwidgets.erase(cvwidgets.begin()+sender_index); //sender->added_to_rep_list_ = false; } // empezar a reproducir la camara en este widget, con el zoom camera_ = sender_camera; setZoom(zoomx,zoomp); //actualizar userinfo if(grid_index_ != -1 && widget_index_ != -1){ if(camera_->is_channel_){ userinfo.grids[grid_index_]->cameras_id[widget_index_] =to_string(camera_->channel_)+"$"+ camera_->dhdevice_id_; }else{ userinfo.grids[grid_index_]->cameras_id[widget_index_] = camera_->unique_id_; } bool mongo_con; vsmongo->updateUserInfoGrids(mongo_con); } // if(!added_to_rep_list_){ cvwidgets.push_back(this); added_to_rep_list_ = true; } handled = true; } // se suelta una camara en el widget if (event->mimeData()->hasFormat("camera")){ QByteArray cameraData = event->mimeData()->data("camera"); QDataStream dataStream(&cameraData, QIODevice::ReadOnly); QString cameraname; dataStream >> cameraname; bool is_camera = false; bool is_channel = false; //buscar la camara que corresponde con ese nombre for(uint i=0;i<cameras.size();i++) if(cameras[i]->name_ == cameraname){ camera_ = cameras[i]; is_camera = true; break; } for(uint i=0;i<dhdevices.size();i++) for(uint j=0;j<dhdevices[i]->cameras_.size();j++) if(dhdevices[i]->cameras_[j]->name_ == cameraname){ is_channel = true; camera_ = dhdevices[i]->cameras_[j]; break; } //actualizar userinfo if(is_camera || is_channel){ if(grid_index_ != -1 && widget_index_ != -1){ if(camera_->is_channel_){ userinfo.grids[grid_index_]->cameras_id[widget_index_] =to_string(camera_->channel_)+"$"+ camera_->dhdevice_id_; }else{ userinfo.grids[grid_index_]->cameras_id[widget_index_] = camera_->unique_id_; } } bool mongo_con; vsmongo->updateUserInfoGrids(mongo_con); } // if(!added_to_rep_list_){ cvwidgets.push_back(this); added_to_rep_list_ = true; } handled = true; } if(!handled) event->ignore(); }else{ event->ignore(); } } void CVImageWidget::mouseDoubleClickEvent( QMouseEvent * e ){ if(ptzButtonClicked(e->pos()) == -1){ if(added_to_rep_list_){ maximized_ = !maximized_; if(maximized_){ // poner todos los cvwidgets que esten en la misma ventana como no visibles for(uint i=0;i<cvwidgets.size();i++) if(cvwidgets[i] != this && cvwidgets[i]->parentWidget() == parentWidget()){ cvwidgets[i]->visible_ = false; cvwidgets[i]->setGeometry(0,0,1,1); } }else{ for(uint i=0;i<cvwidgets.size();i++) if(cvwidgets[i]->parentWidget() == parentWidget()) cvwidgets[i]->visible_ = true; } } } } void CVImageWidget::sliderChanged(int val){ playback_min_ = abs(playback_slider_->value() - playback_slider_->maximum()); string time_s; if(playback_min_ < 60) time_s = to_string(playback_min_)+"s"; else if(playback_min_==3600) time_s = "1h"; else time_s = to_string(playback_min_/60) + "m"; playback_label_->setText("<font size=2>-"+QString::fromStdString(time_s)+"</font>"); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef SVG_SUPPORT #include "modules/svg/src/animation/svganimationtarget.h" #include "modules/svg/src/animation/svganimationcalculator.h" #include "modules/svg/src/animation/svganimationworkplace.h" #include "modules/svg/src/animation/svganimationschedule.h" #include "modules/svg/src/SVGTimedElementContext.h" #include "modules/svg/src/SVGDocumentContext.h" #include "modules/svg/src/AttrValueStore.h" #include "modules/svg/src/SVGDynamicChangeHandler.h" #include "modules/svg/src/SVGUtils.h" #include "modules/svg/src/SVGTimeValue.h" #include "modules/layout/cascade.h" SVGAnimationTarget::SVGAnimationTarget(HTML_Element *target_element) : animated_element(target_element) { } OP_STATUS SVGAnimationTarget::RegisterListener(SVGTimeObject* etv) { OP_ASSERT(etv); if (listeners.Find(etv) != -1) { return OpStatus::OK; } return listeners.Add(etv); } OP_STATUS SVGAnimationTarget::UnregisterListener(SVGTimeObject* etv) { OP_ASSERT(listeners.Find(etv) != -1); OpStatus::Ignore(listeners.RemoveByItem(etv)); return OpStatus::OK; } BOOL SVGAnimationTarget::ListensToEvent(DOM_EventType type) { for (UINT32 i=0; i<listeners.GetCount(); i++) { SVGTimeObject* etv = listeners.Get(i); if (etv->GetEventType() == type) return TRUE; } return FALSE; } BOOL SVGAnimationTarget::HandleEvent(HTML_Element* elm, const SVGManager::EventData& data) { OP_NEW_DBG("SVGElementStateContext::HandleEvent", "svg_animation"); SVGDocumentContext* doc_ctx = AttrValueStore::GetSVGDocumentContext(elm); if (!doc_ctx) return FALSE; SVGAnimationWorkplace *animation_workplace = doc_ctx->GetAnimationWorkplace(); if (!animation_workplace) return FALSE; BOOL handled = FALSE; for (UINT32 i=0; i<listeners.GetCount(); i++) { SVGTimeObject* etv = listeners.Get(i); if (etv->GetEventType() == data.type) { SVG_ANIMATION_TIME time_to_add = animation_workplace->VirtualDocumentTime() + etv->GetOffset(); RETURN_VALUE_IF_ERROR(etv->AddInstanceTime(time_to_add), FALSE); if (SVGTimingInterface *notifier = etv->GetNotifier()) animation_workplace->InvalidateTimingElement(notifier->GetElement()); handled = TRUE; } } return handled; } #endif // SVG_SUPPORT
// Copyright (c) 2012-2015 The Bitcoin Core developers // Copyright (c) 2018-2019 The NavCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <coins.h> #include <main.h> #include <memusage.h> #include <random.h> #include <util.h> #include <utiltime.h> #include <assert.h> /** * calculate number of bytes for the bitmask, and its number of non-zero bytes * each bit in the bitmask represents the availability of one output, but the * availabilities of the first two outputs are encoded separately */ void CCoins::CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const { unsigned int nLastUsedByte = 0; for (unsigned int b = 0; 2+b*8 < vout.size(); b++) { bool fZero = true; for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) { if (!vout[2+b*8+i].IsNull()) { fZero = false; continue; } } if (!fZero) { nLastUsedByte = b + 1; nNonzeroBytes++; } } nBytes += nLastUsedByte; } bool CCoins::Spend(uint32_t nPos) { if (nPos >= vout.size() || vout[nPos].IsNull()) return false; vout[nPos].SetNull(); Cleanup(); return true; } bool CStateView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; } bool CStateView::GetProposal(const uint256 &pid, CProposal &proposal) const { return false; } bool CStateView::GetPaymentRequest(const uint256 &prid, CPaymentRequest &prequest) const { return false; } bool CStateView::GetCachedVoter(const CVoteMapKey &voter, CVoteMapValue& vote) const { return false; } bool CStateView::GetConsultation(const uint256 &cid, CConsultation& consultation) const { return false; } bool CStateView::GetConsultationAnswer(const uint256 &cid, CConsultationAnswer& answer) const { return false; } bool CStateView::GetConsensusParameter(const int &pid, CConsensusParameter& cparameter) const { return false; } bool CStateView::HaveCoins(const uint256 &txid) const { return false; } bool CStateView::HaveProposal(const uint256 &pid) const { return false; } bool CStateView::HavePaymentRequest(const uint256 &prid) const { return false; } bool CStateView::HaveCachedVoter(const CVoteMapKey &voter) const { return false; } bool CStateView::HaveConsultation(const uint256 &cid) const { return false; } bool CStateView::HaveConsultationAnswer(const uint256 &cid) const { return false; } bool CStateView::HaveConsensusParameter(const int &pid) const { return false; } bool CStateView::GetAllProposals(CProposalMap& map) { return false; } bool CStateView::GetAllPaymentRequests(CPaymentRequestMap& map) { return false; } bool CStateView::GetAllVotes(CVoteMap& map) { return false; } bool CStateView::GetAllConsultations(CConsultationMap& map) { return false; } bool CStateView::GetAllConsultationAnswers(CConsultationAnswerMap& map) { return false; } uint256 CStateView::GetBestBlock() const { return uint256(); } bool CStateView::BatchWrite(CCoinsMap &mapCoins, CProposalMap &mapProposals, CPaymentRequestMap &mapPaymentRequests, CVoteMap &mapVotes, CConsultationMap& mapConsultations, CConsultationAnswerMap& mapAnswers, CConsensusParameterMap& mapConsensus, const uint256 &hashBlock) { return false; } CStateViewCursor *CStateView::Cursor() const { return 0; } CStateViewBacked::CStateViewBacked(CStateView *viewIn) : base(viewIn) { } bool CStateViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); } bool CStateViewBacked::GetProposal(const uint256 &pid, CProposal &proposal) const { return base->GetProposal(pid, proposal); } bool CStateViewBacked::GetPaymentRequest(const uint256 &prid, CPaymentRequest &prequest) const { return base->GetPaymentRequest(prid, prequest); } bool CStateViewBacked::GetConsultation(const uint256 &cid, CConsultation &consultation) const { return base->GetConsultation(cid, consultation); } bool CStateViewBacked::GetConsultationAnswer(const uint256 &cid, CConsultationAnswer &answer) const { return base->GetConsultationAnswer(cid, answer); } bool CStateViewBacked::GetConsensusParameter(const int &pid, CConsensusParameter& cparameter) const { return base->GetConsensusParameter(pid, cparameter); } bool CStateViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); } bool CStateViewBacked::HaveProposal(const uint256 &pid) const { return base->HaveProposal(pid); } bool CStateViewBacked::HavePaymentRequest(const uint256 &prid) const { return base->HavePaymentRequest(prid); } bool CStateViewBacked::HaveCachedVoter(const CVoteMapKey &voter) const { return base->HaveCachedVoter(voter); } bool CStateViewBacked::HaveConsultation(const uint256 &cid) const { return base->HaveConsultation(cid); } bool CStateViewBacked::HaveConsultationAnswer(const uint256 &cid) const { return base->HaveConsultationAnswer(cid); } bool CStateViewBacked::HaveConsensusParameter(const int &pid) const { return base->HaveConsensusParameter(pid); } bool CStateViewBacked::GetCachedVoter(const CVoteMapKey &voter, CVoteMapValue& vote) const { return base->GetCachedVoter(voter, vote); } bool CStateViewBacked::GetAllProposals(CProposalMap& map) { return base->GetAllProposals(map); } bool CStateViewBacked::GetAllPaymentRequests(CPaymentRequestMap& map) { return base->GetAllPaymentRequests(map); } bool CStateViewBacked::GetAllVotes(CVoteMap& map) { return base->GetAllVotes(map); } bool CStateViewBacked::GetAllConsultations(CConsultationMap& map) { return base->GetAllConsultations(map); } bool CStateViewBacked::GetAllConsultationAnswers(CConsultationAnswerMap& map) { return base->GetAllConsultationAnswers(map); } uint256 CStateViewBacked::GetBestBlock() const { return base->GetBestBlock(); } void CStateViewBacked::SetBackend(CStateView &viewIn) { base = &viewIn; } bool CStateViewBacked::BatchWrite(CCoinsMap &mapCoins, CProposalMap &mapProposals, CPaymentRequestMap &mapPaymentRequests, CVoteMap &mapVotes, CConsultationMap &mapConsultations, CConsultationAnswerMap &mapAnswers, CConsensusParameterMap& mapConsensus, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, mapProposals, mapPaymentRequests, mapVotes, mapConsultations, mapAnswers, mapConsensus, hashBlock); } CStateViewCursor *CStateViewBacked::Cursor() const { return base->Cursor(); } SaltedTxidHasher::SaltedTxidHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {} CStateViewCache::CStateViewCache(CStateView *baseIn) : CStateViewBacked(baseIn), hasModifier(false), hasModifierConsensus(false), cachedCoinsUsage(0) { } CStateViewCache::~CStateViewCache() { assert(!hasModifier); assert(!hasModifierConsensus); } size_t CStateViewCache::DynamicMemoryUsage() const { return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage; } CCoinsMap::const_iterator CStateViewCache::FetchCoins(const uint256 &txid) const { CCoinsMap::iterator it = cacheCoins.find(txid); if (it != cacheCoins.end()) return it; CCoins tmp; if (!base->GetCoins(txid, tmp)) return cacheCoins.end(); CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first; tmp.swap(ret->second.coins); if (ret->second.coins.IsPruned()) { // The parent only has an empty entry for this txid; we can consider our // version as fresh. ret->second.flags = CCoinsCacheEntry::FRESH; } cachedCoinsUsage += ret->second.coins.DynamicMemoryUsage(); return ret; } CProposalMap::const_iterator CStateViewCache::FetchProposal(const uint256 &pid) const { CProposalMap::iterator it = cacheProposals.find(pid); if (it != cacheProposals.end()) return it->second.IsNull() ? cacheProposals.end() : it; CProposal tmp; if (!base->GetProposal(pid, tmp) || tmp.IsNull()) return cacheProposals.end(); CProposalMap::iterator ret = cacheProposals.insert(std::make_pair(pid, CProposal())).first; tmp.swap(ret->second); return ret; } CPaymentRequestMap::const_iterator CStateViewCache::FetchPaymentRequest(const uint256 &prid) const { CPaymentRequestMap::iterator it = cachePaymentRequests.find(prid); if (it != cachePaymentRequests.end()) return it->second.IsNull() ? cachePaymentRequests.end() : it; CPaymentRequest tmp; if (!base->GetPaymentRequest(prid, tmp) || tmp.IsNull()) return cachePaymentRequests.end(); CPaymentRequestMap::iterator ret = cachePaymentRequests.insert(std::make_pair(prid, CPaymentRequest())).first; tmp.swap(ret->second); return ret; } CVoteMap::const_iterator CStateViewCache::FetchVote(const CVoteMapKey &voter) const { CVoteMap::iterator it = cacheVotes.find(voter); if (it != cacheVotes.end()) return it; CVoteList tmp; if (!base->GetCachedVoter(voter, tmp) || tmp.IsNull()) return cacheVotes.end(); CVoteMap::iterator ret = cacheVotes.insert(std::make_pair(voter, CVoteList())).first; tmp.swap(ret->second); return ret; } CConsultationMap::const_iterator CStateViewCache::FetchConsultation(const uint256 &cid) const { CConsultationMap::iterator it = cacheConsultations.find(cid); if (it != cacheConsultations.end()) return it; CConsultation tmp; if (!base->GetConsultation(cid, tmp) || tmp.IsNull()) return cacheConsultations.end(); CConsultationMap::iterator ret = cacheConsultations.insert(std::make_pair(cid, CConsultation())).first; tmp.swap(ret->second); return ret; } CConsultationAnswerMap::const_iterator CStateViewCache::FetchConsultationAnswer(const uint256 &cid) const { CConsultationAnswerMap::iterator it = cacheAnswers.find(cid); if (it != cacheAnswers.end()) return it; CConsultationAnswer tmp; if (!base->GetConsultationAnswer(cid, tmp) || tmp.IsNull()) return cacheAnswers.end(); CConsultationAnswerMap::iterator ret = cacheAnswers.insert(std::make_pair(cid, CConsultationAnswer())).first; tmp.swap(ret->second); return ret; } CConsensusParameterMap::const_iterator CStateViewCache::FetchConsensusParameter(const int &pid) const { CConsensusParameterMap::iterator it = cacheConsensus.find(pid); if (it != cacheConsensus.end()) return it; CConsensusParameter tmp; if (!base->GetConsensusParameter(pid, tmp) || tmp.IsNull()) return cacheConsensus.end(); CConsensusParameterMap::iterator ret = cacheConsensus.insert(std::make_pair(pid, CConsensusParameter())).first; tmp.swap(ret->second); return ret; } bool CStateViewCache::GetCoins(const uint256 &txid, CCoins &coins) const { CCoinsMap::const_iterator it = FetchCoins(txid); if (it != cacheCoins.end()) { coins = it->second.coins; return true; } return false; } bool CStateViewCache::GetCachedVoter(const CVoteMapKey &voter, CVoteMapValue& vote) const { CVoteMap::const_iterator it = FetchVote(voter); if (it != cacheVotes.end() && !it->second.IsNull()) { vote = it->second; return true; } return false; } bool CStateViewCache::GetProposal(const uint256 &pid, CProposal &proposal) const { CProposalMap::const_iterator it = FetchProposal(pid); if (it != cacheProposals.end() && !it->second.IsNull()) { proposal = it->second; return true; } return false; } bool CStateViewCache::GetPaymentRequest(const uint256 &pid, CPaymentRequest &prequest) const { CPaymentRequestMap::const_iterator it = FetchPaymentRequest(pid); if (it != cachePaymentRequests.end() && !it->second.IsNull()) { prequest = it->second; return true; } return false; } bool CStateViewCache::GetConsultation(const uint256 &cid, CConsultation &consultation) const { CConsultationMap::const_iterator it = FetchConsultation(cid); if (it != cacheConsultations.end()) { consultation = it->second; return !it->second.IsNull(); } return false; } bool CStateViewCache::GetConsultationAnswer(const uint256 &cid, CConsultationAnswer &answer) const { CConsultationAnswerMap::const_iterator it = FetchConsultationAnswer(cid); if (it != cacheAnswers.end() && !it->second.IsNull()) { answer = it->second; return true; } return false; } bool CStateViewCache::GetConsensusParameter(const int &pid, CConsensusParameter &cparameter) const { CConsensusParameterMap::const_iterator it = FetchConsensusParameter(pid); if (it != cacheConsensus.end() && !it->second.IsNull()) { cparameter = it->second; return true; } return false; } bool CStateViewCache::GetAllProposals(CProposalMap& mapProposal) { mapProposal.clear(); mapProposal.insert(cacheProposals.begin(), cacheProposals.end()); CProposalMap baseMap; if (!base->GetAllProposals(baseMap)) return false; for (CProposalMap::iterator it = baseMap.begin(); it != baseMap.end(); it++) if (!it->second.IsNull()) mapProposal.insert(make_pair(it->first, it->second)); for (auto it = mapProposal.begin(); it != mapProposal.end();) it->second.IsNull() ? mapProposal.erase(it++) : ++it; return true; } bool CStateViewCache::GetAllPaymentRequests(CPaymentRequestMap& mapPaymentRequests) { mapPaymentRequests.clear(); mapPaymentRequests.insert(cachePaymentRequests.begin(), cachePaymentRequests.end()); CPaymentRequestMap baseMap; if (!base->GetAllPaymentRequests(baseMap)) return false; for (CPaymentRequestMap::iterator it = baseMap.begin(); it != baseMap.end(); it++) if (!it->second.IsNull()) mapPaymentRequests.insert(make_pair(it->first, it->second)); for (auto it = mapPaymentRequests.begin(); it != mapPaymentRequests.end();) it->second.IsNull() ? mapPaymentRequests.erase(it++) : ++it; return true; } bool CStateViewCache::GetAllVotes(CVoteMap& mapVotes) { mapVotes.clear(); mapVotes.insert(cacheVotes.begin(), cacheVotes.end()); CVoteMap baseMap; if (!base->GetAllVotes(baseMap)) return false; for (CVoteMap::iterator it = baseMap.begin(); it != baseMap.end(); it++) if (!it->second.IsNull()) mapVotes.insert(make_pair(it->first, it->second)); for (auto it = mapVotes.begin(); it != mapVotes.end();) it->second.IsNull() ? mapVotes.erase(it++) : ++it; return true; } bool CStateViewCache::GetAllConsultations(CConsultationMap& mapConsultations) { mapConsultations.clear(); mapConsultations.insert(cacheConsultations.begin(), cacheConsultations.end()); CConsultationMap baseMap; if (!base->GetAllConsultations(baseMap)) return false; for (CConsultationMap::iterator it = baseMap.begin(); it != baseMap.end(); it++) if (!it->second.IsNull()) mapConsultations.insert(make_pair(it->first, it->second)); for (auto it = mapConsultations.begin(); it != mapConsultations.end();) it->second.IsNull() ? mapConsultations.erase(it++) : ++it; return true; } bool CStateViewCache::GetAllConsultationAnswers(CConsultationAnswerMap& mapAnswers) { mapAnswers.clear(); mapAnswers.insert(cacheAnswers.begin(), cacheAnswers.end()); CConsultationAnswerMap baseMap; if (!base->GetAllConsultationAnswers(baseMap)) return false; for (CConsultationAnswerMap::iterator it = baseMap.begin(); it != baseMap.end(); it++) if (!it->second.IsNull()) mapAnswers.insert(make_pair(it->first, it->second)); for (auto it = mapAnswers.begin(); it != mapAnswers.end();) it->second.IsNull() ? mapAnswers.erase(it++) : ++it; return true; } CCoinsModifier CStateViewCache::ModifyCoins(const uint256 &txid) { assert(!hasModifier); std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())); size_t cachedCoinUsage = 0; if (ret.second) { if (!base->GetCoins(txid, ret.first->second.coins)) { // The parent view does not have this entry; mark it as fresh. ret.first->second.coins.Clear(); ret.first->second.flags = CCoinsCacheEntry::FRESH; } else if (ret.first->second.coins.IsPruned()) { // The parent view only has a pruned entry for this; mark it as fresh. ret.first->second.flags = CCoinsCacheEntry::FRESH; } } else { cachedCoinUsage = ret.first->second.coins.DynamicMemoryUsage(); } // Assume that whenever ModifyCoins is called, the entry will be modified. ret.first->second.flags |= CCoinsCacheEntry::DIRTY; return CCoinsModifier(*this, ret.first, cachedCoinUsage); } CProposalModifier CStateViewCache::ModifyProposal(const uint256 &pid, int nHeight) { assert(!hasModifier); std::pair<CProposalMap::iterator, bool> ret = cacheProposals.insert(std::make_pair(pid, CProposal())); if (ret.second) { if (!base->GetProposal(pid, ret.first->second)) { ret.first->second.SetNull(); } } return CProposalModifier(*this, ret.first, nHeight); } CVoteModifier CStateViewCache::ModifyVote(const CVoteMapKey &voter, int nHeight) { assert(!hasModifier); std::pair<CVoteMap::iterator, bool> ret = cacheVotes.insert(std::make_pair(voter, CVoteList())); if (ret.second) { if (!base->GetCachedVoter(voter, ret.first->second)) { ret.first->second.SetNull(); } } return CVoteModifier(*this, ret.first, nHeight); } CConsensusParameterModifier CStateViewCache::ModifyConsensusParameter(const int &pid, int nHeight) { assert(!hasModifierConsensus); std::pair<CConsensusParameterMap::iterator, bool> ret = cacheConsensus.insert(std::make_pair(pid, CConsensusParameter())); if (ret.second) { if (!base->GetConsensusParameter(pid, ret.first->second)) { ret.first->second.SetNull(); } } return CConsensusParameterModifier(*this, ret.first, nHeight); } CPaymentRequestModifier CStateViewCache::ModifyPaymentRequest(const uint256 &prid, int nHeight) { assert(!hasModifier); std::pair<CPaymentRequestMap::iterator, bool> ret = cachePaymentRequests.insert(std::make_pair(prid, CPaymentRequest())); if (ret.second) { if (!base->GetPaymentRequest(prid, ret.first->second)) { ret.first->second.SetNull(); } } return CPaymentRequestModifier(*this, ret.first, nHeight); } CConsultationModifier CStateViewCache::ModifyConsultation(const uint256 &cid, int nHeight) { assert(!hasModifier); std::pair<CConsultationMap::iterator, bool> ret = cacheConsultations.insert(std::make_pair(cid, CConsultation())); if (ret.second) { if (!base->GetConsultation(cid, ret.first->second)) { ret.first->second.SetNull(); } } return CConsultationModifier(*this, ret.first, nHeight); } CConsultationAnswerModifier CStateViewCache::ModifyConsultationAnswer(const uint256 &cid, int nHeight) { assert(!hasModifier); std::pair<CConsultationAnswerMap::iterator, bool> ret = cacheAnswers.insert(std::make_pair(cid, CConsultationAnswer())); if (ret.second) { if (!base->GetConsultationAnswer(cid, ret.first->second)) { ret.first->second.SetNull(); } } return CConsultationAnswerModifier(*this, ret.first, nHeight); } // ModifyNewCoins has to know whether the new outputs its creating are for a // coinbase or not. If they are for a coinbase, it can not mark them as fresh. // This is to ensure that the historical duplicate coinbases before BIP30 was // in effect will still be properly overwritten when spent. CCoinsModifier CStateViewCache::ModifyNewCoins(const uint256 &txid, bool coinbase) { assert(!hasModifier); std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())); ret.first->second.coins.Clear(); if (!coinbase) { ret.first->second.flags = CCoinsCacheEntry::FRESH; } ret.first->second.flags |= CCoinsCacheEntry::DIRTY; return CCoinsModifier(*this, ret.first, 0); } bool CStateViewCache::AddProposal(const CProposal& proposal) const { if (HaveProposal(proposal.hash)) return false; assert(proposal.fDirty == true); if (cacheProposals.count(proposal.hash)) cacheProposals[proposal.hash]=proposal; else cacheProposals.insert(std::make_pair(proposal.hash, proposal)); return true; } bool CStateViewCache::AddCachedVoter(const CVoteMapKey &voter, CVoteMapValue& vote) const { if (HaveCachedVoter(voter)) return false; assert(vote.fDirty == true); if (cacheVotes.count(voter)) cacheVotes[voter]=vote; else cacheVotes.insert(std::make_pair(voter, vote)); return true; } bool CStateViewCache::AddPaymentRequest(const CPaymentRequest& prequest) const { if (HavePaymentRequest(prequest.hash)) return false; assert(prequest.fDirty == true); if (cachePaymentRequests.count(prequest.hash)) cachePaymentRequests[prequest.hash]=prequest; else cachePaymentRequests.insert(std::make_pair(prequest.hash, prequest)); return true; } bool CStateViewCache::AddConsultation(const CConsultation& consultation) const { if (HaveConsultation(consultation.hash)) return false; assert(consultation.fDirty == true); if (cacheConsultations.count(consultation.hash)) cacheConsultations[consultation.hash]=consultation; else cacheConsultations.insert(std::make_pair(consultation.hash, consultation)); return true; } bool CStateViewCache::AddConsultationAnswer(const CConsultationAnswer& answer) { if (HaveConsultationAnswer(answer.hash)) return false; CConsultationModifier mConsultation = ModifyConsultation(answer.parent); mConsultation->vAnswers.push_back(answer.hash); assert(answer.fDirty == true); if (cacheAnswers.count(answer.hash)) cacheAnswers[answer.hash]=answer; else cacheAnswers.insert(std::make_pair(answer.hash, answer)); return true; } bool CStateViewCache::RemoveProposal(const uint256 &pid) const { if (!HaveProposal(pid)) return false; cacheProposals[pid] = CProposal(); cacheProposals[pid].SetNull(); assert(cacheProposals[pid].IsNull()); return true; } bool CStateViewCache::RemovePaymentRequest(const uint256 &prid) const { if (!HavePaymentRequest(prid)) return false; cachePaymentRequests[prid] = CPaymentRequest(); cachePaymentRequests[prid].SetNull(); assert(cachePaymentRequests[prid].IsNull()); return true; } bool CStateViewCache::RemoveCachedVoter(const CVoteMapKey &voter) const { if (!HaveCachedVoter(voter)) return false; cacheVotes[voter] = CVoteList(); cacheVotes[voter].SetNull(); assert(cacheVotes[voter].IsNull()); return true; } bool CStateViewCache::RemoveConsultation(const uint256 &cid) { CConsultation consultation; if (!GetConsultation(cid, consultation)) return false; for (auto &it: consultation.vAnswers) { RemoveConsultationAnswer(it); } cacheConsultations[cid] = CConsultation(); cacheConsultations[cid].SetNull(); assert(cachePaymentRequests[cid].IsNull()); return true; } bool CStateViewCache::RemoveConsultationAnswer(const uint256 &cid) { CConsultationAnswer answer; if (!GetConsultationAnswer(cid, answer)) return false; CConsultationModifier mConsultation = ModifyConsultation(answer.parent); vector<uint256>::iterator it; for (it = mConsultation->vAnswers.begin(); it < mConsultation->vAnswers.end(); it++) if (*it == cid) mConsultation->vAnswers.erase(it); cacheAnswers[cid] = CConsultationAnswer(); cacheAnswers[cid].SetNull(); assert(cacheAnswers[cid].IsNull()); return true; } const CCoins* CStateViewCache::AccessCoins(const uint256 &txid) const { CCoinsMap::const_iterator it = FetchCoins(txid); if (it == cacheCoins.end()) { return nullptr; } else { return &it->second.coins; } } bool CStateViewCache::HaveCoins(const uint256 &txid) const { CCoinsMap::const_iterator it = FetchCoins(txid); // We're using vtx.empty() instead of IsPruned here for performance reasons, // as we only care about the case where a transaction was replaced entirely // in a reorganization (which wipes vout entirely, as opposed to spending // which just cleans individual outputs). return (it != cacheCoins.end() && !it->second.coins.vout.empty()); } bool CStateViewCache::HaveProposal(const uint256 &id) const { CProposalMap::const_iterator it = FetchProposal(id); return (it != cacheProposals.end() && !it->second.IsNull()); } bool CStateViewCache::HavePaymentRequest(const uint256 &id) const { CPaymentRequestMap::const_iterator it = FetchPaymentRequest(id); return (it != cachePaymentRequests.end() && !it->second.IsNull()); } bool CStateViewCache::HaveConsensusParameter(const int &pid) const { CConsensusParameterMap::const_iterator it = FetchConsensusParameter(pid); return (it != cacheConsensus.end() && !it->second.IsNull()); } bool CStateViewCache::HaveCachedVoter(const CVoteMapKey &voter) const { CVoteMap::const_iterator it = FetchVote(voter); // We're using vtx.empty() instead of IsPruned here for performance reasons, // as we only care about the case where a transaction was replaced entirely // in a reorganization (which wipes vout entirely, as opposed to spending // which just cleans individual outputs). return (it != cacheVotes.end() && !it->second.IsNull()); } bool CStateViewCache::HaveConsultation(const uint256 &cid) const { CConsultationMap::const_iterator it = FetchConsultation(cid); return (it != cacheConsultations.end() && !it->second.IsNull()); } bool CStateViewCache::HaveConsultationAnswer(const uint256 &cid) const { CConsultationAnswerMap::const_iterator it = FetchConsultationAnswer(cid); return (it != cacheAnswers.end() && !it->second.IsNull()); } bool CStateViewCache::HaveCoinsInCache(const uint256 &txid) const { CCoinsMap::const_iterator it = cacheCoins.find(txid); return it != cacheCoins.end(); } bool CStateViewCache::HaveProposalInCache(const uint256 &pid) const { auto it = cacheProposals.find(pid); return it != cacheProposals.end() && !it->second.IsNull(); } bool CStateViewCache::HavePaymentRequestInCache(const uint256 &txid) const { auto it = cachePaymentRequests.find(txid); return it != cachePaymentRequests.end() && !it->second.IsNull(); } uint256 CStateViewCache::GetBestBlock() const { if (hashBlock.IsNull()) hashBlock = base->GetBestBlock(); return hashBlock; } void CStateViewCache::SetBestBlock(const uint256 &hashBlockIn) { hashBlock = hashBlockIn; } bool CStateViewCache::BatchWrite(CCoinsMap &mapCoins, CProposalMap &mapProposals, CPaymentRequestMap &mapPaymentRequests, CVoteMap& mapVotes, CConsultationMap& mapConsultations, CConsultationAnswerMap& mapAnswers, CConsensusParameterMap& mapConsensus, const uint256 &hashBlockIn) { assert(!hasModifier); assert(!hasModifierConsensus); for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization). CCoinsMap::iterator itUs = cacheCoins.find(it->first); if (itUs == cacheCoins.end()) { // The parent cache does not have an entry, while the child does // We can ignore it if it's both FRESH and pruned in the child if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coins.IsPruned())) { // Otherwise we will need to create it in the parent // and move the data up and mark it as dirty CCoinsCacheEntry& entry = cacheCoins[it->first]; entry.coins.swap(it->second.coins); cachedCoinsUsage += entry.coins.DynamicMemoryUsage(); entry.flags = CCoinsCacheEntry::DIRTY; // We can mark it FRESH in the parent if it was FRESH in the child // Otherwise it might have just been flushed from the parent's cache // and already exist in the grandparent if (it->second.flags & CCoinsCacheEntry::FRESH) entry.flags |= CCoinsCacheEntry::FRESH; } } else { // Found the entry in the parent cache if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) { // The grandparent does not have an entry, and the child is // modified and being pruned. This means we can just delete // it from the parent. cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage(); cacheCoins.erase(itUs); } else { // A normal modification. cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage(); itUs->second.coins.swap(it->second.coins); cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage(); itUs->second.flags |= CCoinsCacheEntry::DIRTY; } } } CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } for (CProposalMap::iterator it = mapProposals.begin(); it != mapProposals.end();) { if (it->second.fDirty) { // Ignore non-dirty entries (optimization). CProposal& entry = cacheProposals[it->first]; entry.swap(it->second); } CProposalMap::iterator itOld = it++; mapProposals.erase(itOld); } for (CPaymentRequestMap::iterator it = mapPaymentRequests.begin(); it != mapPaymentRequests.end();) { if (it->second.fDirty) { // Ignore non-dirty entries (optimization). CPaymentRequest& entry = cachePaymentRequests[it->first]; entry.swap(it->second); } CPaymentRequestMap::iterator itOld = it++; mapPaymentRequests.erase(itOld); } for (CVoteMap::iterator it = mapVotes.begin(); it != mapVotes.end();){ if (it->second.fDirty) { // Ignore non-dirty entries (optimization). CVoteList& entry = cacheVotes[it->first]; entry.swap(it->second); } CVoteMap::iterator itOld = it++; mapVotes.erase(itOld); } for (CConsultationMap::iterator it = mapConsultations.begin(); it != mapConsultations.end();) { if (it->second.fDirty) { // Ignore non-dirty entries (optimization). CConsultation& entry = cacheConsultations[it->first]; entry.swap(it->second); } CConsultationMap::iterator itOld = it++; mapConsultations.erase(itOld); } for (CConsultationAnswerMap::iterator it = mapAnswers.begin(); it != mapAnswers.end();) { if (it->second.fDirty) { // Ignore non-dirty entries (optimization). CConsultationAnswer& entry = cacheAnswers[it->first]; entry.swap(it->second); } CConsultationAnswerMap::iterator itOld = it++; mapAnswers.erase(itOld); } for (CConsensusParameterMap::iterator it = mapConsensus.begin(); it != mapConsensus.end();) { if (it->second.fDirty) { // Ignore non-dirty entries (optimization). CConsensusParameter& entry = cacheConsensus[it->first]; entry.swap(it->second); } CConsensusParameterMap::iterator itOld = it++; mapConsensus.erase(itOld); } hashBlock = hashBlockIn; return true; } bool CStateViewCache::Flush() { bool fOk = base->BatchWrite(cacheCoins, cacheProposals, cachePaymentRequests, cacheVotes, cacheConsultations, cacheAnswers, cacheConsensus, hashBlock); cacheCoins.clear(); cacheProposals.clear(); cachePaymentRequests.clear(); cacheVotes.clear(); cacheConsultations.clear(); cacheAnswers.clear(); cacheConsensus.clear(); cachedCoinsUsage = 0; return fOk; } void CStateViewCache::Uncache(const uint256& hash) { CCoinsMap::iterator it = cacheCoins.find(hash); if (it != cacheCoins.end() && it->second.flags == 0) { cachedCoinsUsage -= it->second.coins.DynamicMemoryUsage(); cacheCoins.erase(it); } } unsigned int CStateViewCache::GetCacheSize() const { return cacheCoins.size(); } const CTxOut &CStateViewCache::GetOutputFor(const CTxIn& input) const { const CCoins* coins = AccessCoins(input.prevout.hash); assert(coins && coins->IsAvailable(input.prevout.n)); return coins->vout[input.prevout.n]; } CAmount CStateViewCache::GetValueIn(const CTransaction& tx) const { if (tx.IsCoinBase()) return 0; CAmount nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) nResult += GetOutputFor(tx.vin[i]).nValue; return nResult; } bool CStateViewCache::HaveInputs(const CTransaction& tx) const { if (!tx.IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; const CCoins* coins = AccessCoins(prevout.hash); if (!coins || !coins->IsAvailable(prevout.n)) { return false; } } } return true; } double CStateViewCache::GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const { inChainInputValue = 0; if (tx.IsCoinBase()) return 0.0; double dResult = 0.0; for(const CTxIn& txin: tx.vin) { const CCoins* coins = AccessCoins(txin.prevout.hash); assert(coins); if (!coins->IsAvailable(txin.prevout.n)) continue; if (coins->nHeight <= nHeight) { dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight); inChainInputValue += coins->vout[txin.prevout.n].nValue; } } return tx.ComputePriority(dResult); } CCoinsModifier::CCoinsModifier(CStateViewCache& cache_, CCoinsMap::iterator it_, size_t usage) : cache(cache_), it(it_), cachedCoinUsage(usage) { assert(!cache.hasModifier); cache.hasModifier = true; } CCoinsModifier::~CCoinsModifier() { assert(cache.hasModifier); cache.hasModifier = false; it->second.coins.Cleanup(); cache.cachedCoinsUsage -= cachedCoinUsage; // Subtract the old usage if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) { cache.cacheCoins.erase(it); } else { // If the coin still exists after the modification, add the new usage cache.cachedCoinsUsage += it->second.coins.DynamicMemoryUsage(); } } CProposalModifier::CProposalModifier(CStateViewCache& cache_, CProposalMap::iterator it_, int height_) : cache(cache_), it(it_), height(height_) { assert(!cache.hasModifier); cache.hasModifier = true; prev = it->second; } CProposalModifier::~CProposalModifier() { assert(cache.hasModifier); cache.hasModifier = false; if (it->second.IsNull()) { cache.cacheProposals[it->first].SetNull(); } if (prev != it->second) { it->second.fDirty = true; LogPrint("daoextra", "%s: Modified %s%s: %s\n", __func__, height>0?strprintf("at height %d ",height):"",it->first.ToString(), prev.diff(it->second)); } } CPaymentRequestModifier::CPaymentRequestModifier(CStateViewCache& cache_, CPaymentRequestMap::iterator it_, int height_) : cache(cache_), it(it_), height(height_) { assert(!cache.hasModifier); cache.hasModifier = true; prev = it->second; } CPaymentRequestModifier::~CPaymentRequestModifier() { assert(cache.hasModifier); cache.hasModifier = false; if (it->second.IsNull()) { cache.cacheProposals[it->first].SetNull(); } if (prev != it->second) { it->second.fDirty = true; LogPrint("daoextra", "%s: Modified %s%s: %s\n", __func__, height>0?strprintf("at height %d ",height):"",it->first.ToString(), prev.diff(it->second)); } } CVoteModifier::CVoteModifier(CStateViewCache& cache_, CVoteMap::iterator it_, int height_) : cache(cache_), it(it_), height(height_) { assert(!cache.hasModifier); cache.hasModifier = true; prev = it->second; } CVoteModifier::~CVoteModifier() { assert(cache.hasModifier); cache.hasModifier = false; if (it->second.IsNull()) { cache.cacheVotes[it->first].SetNull(); } if (prev != it->second) { it->second.fDirty = true; LogPrint("daoextra", "%s: Modified %s%s: %s\n", __func__, height>0?strprintf("at height %d ",height):"", HexStr(it->first), prev.diff(it->second)); } } CConsultationModifier::CConsultationModifier(CStateViewCache& cache_, CConsultationMap::iterator it_, int height_) : cache(cache_), it(it_), height(height_) { assert(!cache.hasModifier); cache.hasModifier = true; prev = it->second; } CConsultationModifier::~CConsultationModifier() { assert(cache.hasModifier); cache.hasModifier = false; if (it->second.IsNull()) { cache.cacheConsultations[it->first].SetNull(); } if (prev != it->second) { it->second.fDirty = true; LogPrint("daoextra", "%s: Modified %s%s: %s\n", __func__, height>0?strprintf("at height %d ",height):"",it->first.ToString(), prev.diff(it->second)); } } CConsultationAnswerModifier::CConsultationAnswerModifier(CStateViewCache& cache_, CConsultationAnswerMap::iterator it_, int height_) : cache(cache_), it(it_), height(height_) { assert(!cache.hasModifier); cache.hasModifier = true; prev = it->second; } CConsultationAnswerModifier::~CConsultationAnswerModifier() { assert(cache.hasModifier); cache.hasModifier = false; if (it->second.IsNull()) { cache.cacheAnswers[it->first].SetNull(); } if (prev != it->second) { it->second.fDirty = true; LogPrint("daoextra", "%s: Modified %s%s: %s\n", __func__, height>0?strprintf("at height %d ",height):"",it->first.ToString(), prev.diff(it->second)); } } CConsensusParameterModifier::CConsensusParameterModifier(CStateViewCache& cache_, CConsensusParameterMap::iterator it_, int height_) : cache(cache_), it(it_), height(height_) { assert(!cache.hasModifierConsensus); cache.hasModifierConsensus = true; prev = it->second; } CConsensusParameterModifier::~CConsensusParameterModifier() { assert(cache.hasModifierConsensus); cache.hasModifierConsensus = false; if (it->second.IsNull()) { cache.cacheConsensus[it->first].SetNull(); } if (prev != it->second) { it->second.fDirty = true; LogPrint("daoextra", "%s: Modified %sconsensus parameter %d: %s\n", __func__, height>0?strprintf("at height %d ",height):"",it->first, prev.diff(it->second)); } } CStateViewCursor::~CStateViewCursor() { }
#include <iostream> #include <cstdio> #include <string> #include <vector> #include <fstream> #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; class Neuron; // crtp template<typename Self> struct SomeNeurons { template<typename T> void connect_to(T &other); }; struct Neuron : SomeNeurons<Neuron> { std::vector<Neuron*> in, out; unsigned int id; Neuron() { static int id{1}; this->id = id++; } Neuron* begin() { return this; } Neuron* end() { return this+1; } /* void connect_to(Neuron &other) { out.push_back(&other); other.in.push_back(this); }*/ friend ostream& operator<<(ostream& os, Neuron const& neuron) { for (auto* n : neuron.in) os << n->id << "\t-->\t[" << neuron.id << "]" << std::endl; for (auto* n : neuron.out) os << "[" << neuron.id << "]\t-->\t" << n->id << std::endl; return os; } }; template<typename Self> template<typename T> void SomeNeurons<Self>::connect_to(T &other){ for (Neuron &from : *static_cast<Self*>(this)) { for (Neuron &to : other) { from.out.push_back(&to); to.in.push_back(&from); } } } struct NeuronLayer : vector<Neuron>, SomeNeurons<NeuronLayer> { NeuronLayer(int count) { while (count --> 0) emplace_back(Neuron{}); } friend ostream &operator<<(ostream &os, NeuronLayer const& obj) { for (auto &n : obj) os << n; return os; } }; int main() { Neuron n1, n2; n1.connect_to(n2); std::cout << n1 << n2 << std::endl; NeuronLayer layer1{2}, layer2{3}; n1.connect_to(layer1); std::cout << n1 << layer1 << std::endl; layer2.connect_to(n2); std::cout << layer2 << std::endl; // layer1.connect_to(layer2); return 0; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> using namespace std; class PalindromeGame { public: bool isPalindrome(string s) { for (int b=0,e=(int)s.size()-1; b <= e; ++b,--e) { if (s[b] != s[e]) { return false; } } return true; } struct state { string front; int back; }; static bool comp(const state &lhs,const state &rhs) { return lhs.back > rhs.back; } int getMaximum(vector <string> front, vector <int> back) { bool used[51] = {false}; vector<state> cs(front.size()); for (int i=0; i<front.size(); ++i) { state s; s.front = front[i]; s.back = back[i]; cs[i] = s; } sort(cs.begin(), cs.end(), comp); int ans = 0; for (int i=0; i<cs.size(); ++i) { for (int j=i+1; j<cs.size(); ++j) { if (isPalindrome(cs[i].front+cs[j].front) && !used[i] && !used[j]) { used[i] = true; used[j] = true; ans += cs[i].back + cs[j].back; } } } for (int i=0; i<cs.size(); ++i) { if (!used[i] && isPalindrome(cs[i].front)) { ans += cs[i].back; break; } } return ans; } };
#pragma once #include <QAbstractTableModel> #include <QList> class User; class UsersModel : public QAbstractTableModel { public: UsersModel(QObject *parent = nullptr); // QAbstractItemModel interface int rowCount(const QModelIndex &parent) const override; int columnCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; const QList<User> &getUsers() const; void setUsers(const QList<User> &users); User getUser(int index) const; int getUserId(int index) const; int getRemoveColumnIndex() const; private: void updateData(const QList<User> &users); void emitAllDataChanged(); QList<User> m_users; };
// Sharna Hossain // CSC 111 // Lab 5 | loan.cpp #include <iostream> using namespace std; int main() { char graduated, employed; double income; const double MIN_INCOME = 30000.0; cout << "Are you employed? (T/F): "; cin >> employed; cout << "Have you graduated? (T/F): "; cin >> graduated; cout << "Enter your annual income: "; cin >> income; // Using double quotation marks "" in logical comparisons will // refer to the memory location, single quotation marks '' refer // to the value of the char - much more preferable! if (employed == 'T' && graduated == 'T' && income > MIN_INCOME) { cout << "You qualify for a loan!"; } else { cout << "Unfortunately, you do not qualify for a loan."; } return 0; }
#include "Note.h" /************************************************************** *** Note *** ***************************************************************/ string* Note::ids = new string [5]; unsigned int Note::nbId =0; unsigned int Note::nbMaxId =5; static Iterator getIterator() const{return Iterator(ids, nbId);} void addID(const string & id){ if(nbId == nbMaxId){ string* old_ids = ids; ids = new string[nbIdMax+5]; for(int i = 0; i < nbId; i++){ ids[i] = old_ids[i]; } nbMaxId += 5; delete[] old_ids; } ids[nbId++]=id; } /************************************************************** *** Clone *** ***************************************************************/ Tache* Tache::clone(){return new Tache(*this);} Article* Article::clone(){return new Article(*this);} Image* Image::clone(){return new Image(*this);} Audio* Audio::clone(){return new Audio(*this);} Video* Video::clone(){return new Video(*this);}
#include "aeGameObject.h" namespace aeEngineSDK { aeGameObject::aeGameObject() { m_xName = "New GameObject"; m_xTransform.m_pGameObject = this; } aeGameObject::aeGameObject(const String & GO) { m_xName = GO; m_xTransform.m_pGameObject = this; } aeGameObject::aeGameObject(const aeGameObject & GO) { *this = GO; } aeGameObject::~aeGameObject() { } inline void aeGameObject::SetStatic(const bool & Bool) { m_bStatic = Bool; for (auto child : m_xTransform.m_aChildren) { child->m_pGameObject->m_bStatic = m_bStatic; } } inline void aeGameObject::AddComponent(aeGOAddOn * AddOn) { m_aAddOns.insert(Pair<AE_ADD_ON_ID, aeGOAddOn*>(AddOn->GetComponentId(), AddOn)); } inline bool aeGameObject::IsStatic() const { return m_bStatic; } inline AE_GAME_OBJECT_ID aeGameObject::GetID() const { return m_nID; } }
/* Arduino --> ThingSpeak Channel via Ethernet The ThingSpeak Client sketch is designed for the Arduino and Ethernet. This sketch updates a channel feed with an analog input reading via the ThingSpeak API (https://thingspeak.com/docs) using HTTP POST. The Arduino uses DHCP and DNS for a simpler network setup. The sketch also includes a Watchdog / Reset function to make sure the Arduino stays connected and/or regains connectivity after a network outage. Use the Serial Monitor on the Arduino IDE to see verbose network feedback and ThingSpeak connectivity status. Getting Started with ThingSpeak: * Sign Up for New User Account - https://thingspeak.com/users/new * Create a new Channel by selecting Channels and then Create New Channel * Enter the Write API Key in this sketch under "ThingSpeak Settings" Arduino Requirements: * Arduino with Ethernet Shield or Arduino Ethernet * Arduino 1.0+ IDE Network Requirements: * Ethernet port on Router * DHCP enabled on Router * Unique MAC Address for Arduino */ #include <SPI.h> #include <Ethernet.h> #include "DHT.h" #define DHTPIN 2 // what pin we're connected to #define DHTTYPE DHT11 // define type of sensor DHT 11 DHT dht (DHTPIN, DHTTYPE); int v; int Sound; // Local Network Settings byte mac[] = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network // ThingSpeak Settings char thingSpeakAddress[] = "api.thingspeak.com"; String writeAPIKey = "thingspeak write API"; const int updateThingSpeakInterval = 16 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval) // Variable Setup long lastConnectionTime = 0; boolean lastConnected = false; int failedCounter = 0; EthernetClient client; // Initialize Arduino Ethernet Client IPAddress ip(192,168,0,190); IPAddress gateway(192,168,0,1); IPAddress subnet(255, 255, 255, 0); void setup() { Serial.begin(9600); // Start Serial for debugging on the Serial Monitor startEthernet(); // Start Ethernet on Arduino Ethernet.begin(mac, ip, gateway, subnet); dht.begin(); } void loop() { //------------------------------------------------------------------------ // Read value of Humidity Sensor from Digital Pin 2 delay(2000); String h = String (dht.readHumidity(), DEC); String t = String (dht.readTemperature(), DEC); /*if (isnan(h) || isnan(t)) { Serial.println("Failed to read from DHT sensor!"); return; } Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C ");*/ //-------------------------------------------------------------------------- // Read Value of MQ-135 from Analog Input Pin A0 String MQ135 = String (analogRead(A0), DEC); //Serial.println(" MQ135 Value: "); //Serial.println(MQ135); //-------------------------------------------------------------------------- // Read Value of MQ-7 from Analog Input Pin A1 String CO = String (analogRead(A1), DEC); //Serial.println(" MQ7 Value: "); Serial.println(CO); //----------------------------------------------------------------------------- // Read Value of Sound Sensor from Analog Input Pin A3 int v = analogRead(A3); // Reads the value from the Analog PIN A3 Sound= map(v,0,1023,50,140); Serial.println(Sound); // Print Update Response to Serial Monitor if (client.available()) { char c = client.read(); client.stop(); Serial.print(c); } // Disconnect from ThingSpeak if (!client.connected() && lastConnected) { Serial.println("...disconnected"); Serial.println(); client.stop(); } // Update ThingSpeak if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) { updateThingSpeak("field1="+h+"&field2="+t+"&field3="+MQ135+"&field4="+CO+"&field5="+String (Sound)); } // Check if Arduino Ethernet needs to be restarted if (failedCounter > 3 ) {startEthernet();} lastConnected = client.connected(); } void updateThingSpeak(String tsData) { if (client.connect(thingSpeakAddress, 80)) { client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(tsData.length()); client.print("\n\n"); client.print(tsData); EthernetServer server(80); lastConnectionTime = millis(); if (client.connected()) { Serial.println("Connecting to ThingSpeak..."); Serial.println(); failedCounter = 0; } else { failedCounter++; Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")"); Serial.println(); } } else { failedCounter++; Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")"); Serial.println(); lastConnectionTime = millis(); } } void startEthernet() { client.stop(); Serial.println("Connecting Arduino to network..."); Serial.println(); delay(1000); // Connect to network amd obtain an IP address using DHCP if (Ethernet.begin(mac) == 0) { Serial.println("DHCP Failed, reset Arduino to try again"); Serial.println(); } else { Serial.println("Arduino connected to network using DHCP"); Serial.println(Ethernet.localIP()); Serial.println(); } delay(1000); }
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include "CryptoNoteCore/TransactionApi.h" #include "Logging/ConsoleLogger.h" #include "Transfers/TransfersConsumer.h" #include <algorithm> #include <limits> #include <Transfers/CommonTypes.h> #include <CryptoNoteCore/TransactionApi.h> #include "INodeStubs.h" #include "TransactionApiHelpers.h" #include "TransfersObserver.h" #include "TestBlockchainGenerator.h" using namespace cn; AccountSubscription getAccountSubscription(const AccountKeys& accountKeys) { AccountSubscription subscription; subscription.keys = accountKeys; return subscription; } AccountKeys getAccountKeysWithViewKey(const PublicKey& publicViewKey, const SecretKey& secretViewKey) { KeyPair viewKp; viewKp.publicKey = publicViewKey; viewKp.secretKey = secretViewKey; KeyPair p1; crypto::generate_keys(p1.publicKey, p1.secretKey); AccountKeys accountKeys = accountKeysFromKeypairs(viewKp, p1); return accountKeys; } class TransfersConsumerTest : public ::testing::Test { public: TransfersConsumerTest(); protected: ITransfersSubscription& addSubscription(TransfersConsumer& consumer, const AccountKeys& acc, uint64_t height = 0, uint64_t timestamp = 0, size_t age = 0) { AccountSubscription subscription = getAccountSubscription(acc); subscription.syncStart.height = height; subscription.syncStart.timestamp = timestamp; subscription.transactionSpendableAge = age; return consumer.addSubscription(subscription); } ITransfersSubscription& addSubscription(const AccountKeys& acc, uint64_t height = 0, uint64_t timestamp = 0, size_t age = 0) { return addSubscription(m_consumer, acc, height, timestamp, age); } ITransfersSubscription& addSubscription(uint64_t height = 0, uint64_t timestamp = 0, size_t age = 0) { return addSubscription(m_consumer, m_accountKeys, height, timestamp, age); } ITransfersSubscription& addSubscription(TransfersConsumer& consumer, uint64_t height = 0, uint64_t timestamp = 0, size_t age = 0) { return addSubscription(consumer, m_accountKeys, height, timestamp, age); } AccountKeys generateAccount() { return getAccountKeysWithViewKey(m_accountKeys.address.viewPublicKey, m_accountKeys.viewSecretKey); } logging::ConsoleLogger m_logger; cn::Currency m_currency; TestBlockchainGenerator m_generator; INodeTrivialRefreshStub m_node; AccountKeys m_accountKeys; TransfersConsumer m_consumer; }; TransfersConsumerTest::TransfersConsumerTest() : m_currency(cn::CurrencyBuilder(m_logger).currency()), m_generator(m_currency), m_node(m_generator, true), m_accountKeys(generateAccountKeys()), m_consumer(m_currency, m_node, m_logger, m_accountKeys.viewSecretKey) { } bool amountFound(const std::vector<TransactionOutputInformation>& outs, uint64_t amount) { return std::find_if(outs.begin(), outs.end(), [amount] (const TransactionOutputInformation& inf) { return inf.amount == amount; }) != outs.end(); } AccountSubscription getAccountSubscriptionWithSyncStart(const AccountKeys& keys, uint64_t timestamp, uint64_t height) { AccountSubscription subscription = getAccountSubscription(keys); subscription.syncStart.timestamp = timestamp; subscription.syncStart.height = height; return subscription; } TEST_F(TransfersConsumerTest, addSubscription_Success) { AccountSubscription subscription; subscription.keys = m_accountKeys; ITransfersSubscription& accountSubscription = m_consumer.addSubscription(subscription); ASSERT_EQ(subscription.keys.address, accountSubscription.getAddress()); } TEST_F(TransfersConsumerTest, addSubscription_WrongViewKey) { AccountKeys accountKeys = generateAccountKeys(); AccountSubscription subscription = getAccountSubscription(accountKeys); ASSERT_ANY_THROW(m_consumer.addSubscription(subscription)); } TEST_F(TransfersConsumerTest, addSubscription_SameSubscription) { AccountSubscription subscription = getAccountSubscription(m_accountKeys); ITransfersSubscription* ts1 = &m_consumer.addSubscription(subscription); ITransfersSubscription* ts2 = &m_consumer.addSubscription(subscription); ASSERT_EQ(ts1, ts2); } TEST_F(TransfersConsumerTest, removeSubscription_Success) { AccountSubscription subscription = getAccountSubscription(m_accountKeys); m_consumer.addSubscription(subscription); ITransfersSubscription* ts = m_consumer.getSubscription(m_accountKeys.address); ASSERT_NE(nullptr, ts); m_consumer.removeSubscription(m_accountKeys.address); ts = m_consumer.getSubscription(m_accountKeys.address); ASSERT_EQ(nullptr, ts); } TEST_F(TransfersConsumerTest, removeSubscription_OneAddressLeft) { AccountSubscription subscription1 = getAccountSubscription(m_accountKeys); m_consumer.addSubscription(subscription1); AccountKeys accountKeys = getAccountKeysWithViewKey(m_accountKeys.address.viewPublicKey, m_accountKeys.viewSecretKey); AccountSubscription subscription2 = getAccountSubscription(accountKeys); m_consumer.addSubscription(subscription2); ASSERT_FALSE(m_consumer.removeSubscription(subscription1.keys.address)); } TEST_F(TransfersConsumerTest, removeSubscription_RemoveAllAddresses) { AccountSubscription subscription1 = getAccountSubscription(m_accountKeys); m_consumer.addSubscription(subscription1); ASSERT_TRUE(m_consumer.removeSubscription(subscription1.keys.address)); } TEST_F(TransfersConsumerTest, getSubscription_ReturnSameValueForSameAddress) { AccountSubscription subscription = getAccountSubscription(m_accountKeys); m_consumer.addSubscription(subscription); ITransfersSubscription* ts1 = m_consumer.getSubscription(m_accountKeys.address); ITransfersSubscription* ts2 = m_consumer.getSubscription(m_accountKeys.address); ASSERT_EQ(ts1, ts2); } TEST_F(TransfersConsumerTest, getSubscription_ReturnNullForNonExistentAddr) { AccountSubscription subscription1 = getAccountSubscription(m_accountKeys); m_consumer.addSubscription(subscription1); AccountKeys accountKeys = getAccountKeysWithViewKey(m_accountKeys.address.viewPublicKey, m_accountKeys.viewSecretKey); ASSERT_EQ(nullptr, m_consumer.getSubscription(accountKeys.address)); } TEST_F(TransfersConsumerTest, getSubscriptions_Empty) { std::vector<AccountPublicAddress> subscriptions; m_consumer.getSubscriptions(subscriptions); ASSERT_TRUE(subscriptions.empty()); } TEST_F(TransfersConsumerTest, getSubscriptions_TwoSubscriptions) { AccountSubscription subscription1 = getAccountSubscription(m_accountKeys); m_consumer.addSubscription(subscription1); AccountKeys accountKeys = getAccountKeysWithViewKey(m_accountKeys.address.viewPublicKey, m_accountKeys.viewSecretKey); AccountSubscription subscription2 = getAccountSubscription(accountKeys); m_consumer.addSubscription(subscription2); std::vector<AccountPublicAddress> subscriptions; m_consumer.getSubscriptions(subscriptions); ASSERT_EQ(2, subscriptions.size()); ASSERT_NE(subscriptions.end(), std::find(subscriptions.begin(), subscriptions.end(), subscription1.keys.address)); ASSERT_NE(subscriptions.end(), std::find(subscriptions.begin(), subscriptions.end(), subscription2.keys.address)); } TEST_F(TransfersConsumerTest, getSyncStart_Empty) { auto syncStart = m_consumer.getSyncStart(); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), syncStart.height); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), syncStart.timestamp); } TEST_F(TransfersConsumerTest, getSyncStart_OneSubscription) { const uint64_t height = 1209384; const uint64_t timestamp = 99284512; AccountSubscription subscription = getAccountSubscription(m_accountKeys); subscription.syncStart.height = height; subscription.syncStart.timestamp = timestamp; m_consumer.addSubscription(subscription); auto sync = m_consumer.getSyncStart(); ASSERT_EQ(height, sync.height); ASSERT_EQ(timestamp, sync.timestamp); } TEST_F(TransfersConsumerTest, getSyncStart_MinSyncSameSubscription) { const uint64_t height = 1209384; const uint64_t timestamp = 99284512; const uint64_t minHeight = 120984; const uint64_t minTimestamp = 9984512; AccountSubscription subscription1 = getAccountSubscription(m_accountKeys); subscription1.syncStart.height = height; subscription1.syncStart.timestamp = timestamp; AccountKeys accountKeys = getAccountKeysWithViewKey(m_accountKeys.address.viewPublicKey, m_accountKeys.viewSecretKey); AccountSubscription subscription2 = getAccountSubscription(accountKeys); subscription2.syncStart.height = minHeight; subscription2.syncStart.timestamp = minTimestamp; m_consumer.addSubscription(subscription1); m_consumer.addSubscription(subscription2); auto sync = m_consumer.getSyncStart(); ASSERT_EQ(minHeight, sync.height); ASSERT_EQ(minTimestamp, sync.timestamp); } TEST_F(TransfersConsumerTest, getSyncStart_MinSyncDifferentSubscriptions) { const uint64_t height = 1209384; const uint64_t timestamp = 99284512; const uint64_t minHeight = 120984; const uint64_t minTimestamp = 9984512; AccountSubscription subscription1 = getAccountSubscription(m_accountKeys); subscription1.syncStart.height = minHeight; subscription1.syncStart.timestamp = timestamp; AccountKeys accountKeys = getAccountKeysWithViewKey(m_accountKeys.address.viewPublicKey, m_accountKeys.viewSecretKey); AccountSubscription subscription2 = getAccountSubscription(accountKeys); subscription2.syncStart.height = height; subscription2.syncStart.timestamp = minTimestamp; m_consumer.addSubscription(subscription1); m_consumer.addSubscription(subscription2); auto sync = m_consumer.getSyncStart(); ASSERT_EQ(minHeight, sync.height); ASSERT_EQ(minTimestamp, sync.timestamp); } TEST_F(TransfersConsumerTest, getSyncStart_RemoveMinSyncSubscription) { const uint64_t height = 1209384; const uint64_t timestamp = 99284512; const uint64_t minHeight = 120984; const uint64_t minTimestamp = 9984512; AccountSubscription subscription1 = getAccountSubscription(m_accountKeys); subscription1.syncStart.height = height; subscription1.syncStart.timestamp = timestamp; AccountKeys accountKeys = getAccountKeysWithViewKey(m_accountKeys.address.viewPublicKey, m_accountKeys.viewSecretKey); AccountSubscription subscription2 = getAccountSubscription(accountKeys); subscription2.syncStart.height = minHeight; subscription2.syncStart.timestamp = minTimestamp; m_consumer.addSubscription(subscription1); m_consumer.addSubscription(subscription2); m_consumer.removeSubscription(subscription2.keys.address); auto sync = m_consumer.getSyncStart(); ASSERT_EQ(height, sync.height); ASSERT_EQ(timestamp, sync.timestamp); } TEST_F(TransfersConsumerTest, onBlockchainDetach) { auto& container1 = addSubscription().getContainer(); auto keys = generateAccount(); auto& container2 = addSubscription(keys).getContainer(); std::shared_ptr<ITransaction> tx1 = createTransaction(); addTestInput(*tx1, 100); addTestKeyOutput(*tx1, 50, 1, m_accountKeys); std::shared_ptr<ITransaction> tx2 = createTransaction(); addTestInput(*tx1, 100); addTestKeyOutput(*tx1, 50, 1, keys); CompleteBlock blocks[3]; blocks[0].block = cn::Block(); blocks[0].block->timestamp = 1233; blocks[1].block = cn::Block(); blocks[1].block->timestamp = 1234; blocks[1].transactions.push_back(tx1); blocks[2].block = cn::Block(); blocks[2].block->timestamp = 1235; blocks[2].transactions.push_back(tx2); ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 0, 3)); m_consumer.onBlockchainDetach(0); std::vector<TransactionOutputInformation> trs; container1.getOutputs(trs, ITransfersContainer::IncludeAll); ASSERT_EQ(0, trs.size()); container2.getOutputs(trs, ITransfersContainer::IncludeAll); ASSERT_EQ(0, trs.size()); } TEST_F(TransfersConsumerTest, onNewBlocks_OneEmptyBlockOneFilled) { AccountSubscription subscription = getAccountSubscription(m_accountKeys); subscription.syncStart.height = 1; subscription.syncStart.timestamp = 1234; TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(1000, unknownSender); b1.addTestKeyOutput(123, 1, m_accountKeys); TestTransactionBuilder b2; b2.addTestInput(10000, unknownSender); b2.addTestKeyOutput(850, 2, m_accountKeys); b2.addTestKeyOutput(900, 3, m_accountKeys); auto tx1 = std::shared_ptr<ITransactionReader>(b1.build().release()); auto tx2 = std::shared_ptr<ITransactionReader>(b2.build().release()); CompleteBlock blocks[2]; blocks[0].transactions.push_back(tx1); blocks[1].block = cn::Block(); blocks[1].block->timestamp = 1235; blocks[1].transactions.push_back(tx2); ITransfersContainer& container = m_consumer.addSubscription(subscription).getContainer(); ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 1, 2)); auto outs = container.getTransactionOutputs(tx2->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_TRUE(amountFound(outs, 850)); ASSERT_TRUE(amountFound(outs, 900)); auto ignoredOuts = container.getTransactionOutputs(tx1->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(0, ignoredOuts.size()); } TEST_F(TransfersConsumerTest, onNewBlocks_DifferentTimestamps) { AccountSubscription subscription = getAccountSubscription(m_accountKeys); subscription.syncStart.timestamp = 12345; subscription.syncStart.height = 12; TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(1000, unknownSender); b1.addTestKeyOutput(123, 1, m_accountKeys); TestTransactionBuilder b2; b2.addTestInput(10000, unknownSender); b2.addTestKeyOutput(850, 2, m_accountKeys); b2.addTestKeyOutput(900, 3, m_accountKeys); auto tx1 = std::shared_ptr<ITransactionReader>(b1.build().release()); auto tx2 = std::shared_ptr<ITransactionReader>(b2.build().release()); CompleteBlock blocks[2]; blocks[0].transactions.push_back(tx1); blocks[0].block = cn::Block(); blocks[0].block->timestamp = subscription.syncStart.timestamp - 1; blocks[1].block = cn::Block(); blocks[1].block->timestamp = subscription.syncStart.timestamp; blocks[1].transactions.push_back(tx2); ITransfersContainer& container = m_consumer.addSubscription(subscription).getContainer(); ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 2, 2)); auto ignoredOuts = container.getTransactionOutputs(tx1->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(0, ignoredOuts.size()); auto outs = container.getTransactionOutputs(tx2->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_TRUE(amountFound(outs, 850)); ASSERT_TRUE(amountFound(outs, 900)); } TEST_F(TransfersConsumerTest, onNewBlocks_getTransactionOutsGlobalIndicesError) { class INodeGlobalIndicesStub: public INodeDummyStub { public: virtual void getTransactionOutsGlobalIndices(const crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices, const Callback& callback) override { callback(std::make_error_code(std::errc::operation_canceled)); }; }; INodeGlobalIndicesStub node; TransfersConsumer consumer(m_currency, node, m_logger, m_accountKeys.viewSecretKey); auto subscription = getAccountSubscriptionWithSyncStart(m_accountKeys, 1234, 10); std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); addTestKeyOutput(*tx, 900, 2, m_accountKeys); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = subscription.syncStart.timestamp; block.transactions.push_back(tx); consumer.addSubscription(subscription); ASSERT_FALSE(consumer.onNewBlocks(&block, static_cast<uint32_t>(subscription.syncStart.height), 1)); } TEST_F(TransfersConsumerTest, onNewBlocks_updateHeight) { AccountSubscription subscription = getAccountSubscription(m_accountKeys); subscription.syncStart.timestamp = 2131; subscription.syncStart.height = 32; subscription.transactionSpendableAge = 5; auto& container = m_consumer.addSubscription(subscription).getContainer(); std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); addTestKeyOutput(*tx, 900, 0, m_accountKeys); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = subscription.syncStart.timestamp; block.transactions.push_back(tx); ASSERT_TRUE(m_consumer.onNewBlocks(&block, static_cast<uint32_t>(subscription.syncStart.height), 1)); ASSERT_EQ(900, container.balance(ITransfersContainer::IncludeAllLocked)); std::unique_ptr<CompleteBlock[]> blocks(new CompleteBlock[subscription.transactionSpendableAge]); for (uint32_t i = 0; i < subscription.transactionSpendableAge; ++i) { blocks[i].block = cn::Block(); auto tr = createTransaction(); addTestInput(*tr, 1000); addTestKeyOutput(*tr, 100, i + 1, generateAccountKeys()); } ASSERT_TRUE(m_consumer.onNewBlocks(blocks.get(), static_cast<uint32_t>(subscription.syncStart.height + 1), static_cast<uint32_t>(subscription.transactionSpendableAge))); ASSERT_EQ(0, container.balance(ITransfersContainer::IncludeAllLocked)); ASSERT_EQ(900, container.balance(ITransfersContainer::IncludeAllUnlocked)); } TEST_F(TransfersConsumerTest, onNewBlocks_DifferentSubscribers) { auto& container1 = addSubscription().getContainer(); auto keys = generateAccount(); auto& container2 = addSubscription(keys).getContainer(); uint64_t amount1 = 900; uint64_t amount2 = 850; std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); addTestKeyOutput(*tx, amount1, 0, m_accountKeys); addTestKeyOutput(*tx, amount2, 1, keys); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = 0; block.transactions.push_back(tx); ASSERT_TRUE(m_consumer.onNewBlocks(&block, 0, 1)); auto outs1 = container1.getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(1, outs1.size()); ASSERT_EQ(amount1, outs1[0].amount); auto outs2 = container2.getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(1, outs2.size()); ASSERT_EQ(amount2, outs2[0].amount); } TEST_F(TransfersConsumerTest, onNewBlocks_MultisignatureTransaction) { auto& container1 = addSubscription().getContainer(); auto keys = generateAccount(); auto keys2 = generateAccount(); auto keys3 = generateAccount(); uint64_t amount = 900; std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); tx->addOutput(amount, { m_accountKeys.address, keys.address, keys2.address } , 3); tx->addOutput(800, { keys.address, keys2.address, keys3.address }, 3); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = 0; block.transactions.push_back(tx); ASSERT_TRUE(m_consumer.onNewBlocks(&block, 0, 1)); auto outs1 = container1.getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(1, outs1.size()); ASSERT_EQ(amount, outs1[0].amount); } TEST_F(TransfersConsumerTest, onNewBlocks_getTransactionOutsGlobalIndicesIsProperlyCalled) { class INodeGlobalIndicesStub: public INodeDummyStub { public: virtual void getTransactionOutsGlobalIndices(const crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices, const Callback& callback) override { outsGlobalIndices.push_back(3); hash = transactionHash; callback(std::error_code()); }; crypto::Hash hash; }; INodeGlobalIndicesStub node; TransfersConsumer consumer(m_currency, node, m_logger, m_accountKeys.viewSecretKey); AccountSubscription subscription = getAccountSubscription(m_accountKeys); subscription.syncStart.height = 0; subscription.syncStart.timestamp = 0; consumer.addSubscription(subscription); std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); addTestKeyOutput(*tx, 900, 2, m_accountKeys); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = 0; block.transactions.push_back(tx); ASSERT_TRUE(consumer.onNewBlocks(&block, 1, 1)); const crypto::Hash &hash = tx->getTransactionHash(); const crypto::Hash expectedHash = *reinterpret_cast<const crypto::Hash*>(&hash); ASSERT_EQ(expectedHash, node.hash); } TEST_F(TransfersConsumerTest, onNewBlocks_getTransactionOutsGlobalIndicesIsNotCalled) { class INodeGlobalIndicesStub: public INodeDummyStub { public: INodeGlobalIndicesStub() : called(false) {}; virtual void getTransactionOutsGlobalIndices(const crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices, const Callback& callback) override { outsGlobalIndices.push_back(3); called = true; callback(std::error_code()); }; bool called; }; INodeGlobalIndicesStub node; TransfersConsumer consumer(m_currency, node, m_logger, m_accountKeys.viewSecretKey); AccountSubscription subscription = getAccountSubscription(m_accountKeys); subscription.syncStart.height = 0; subscription.syncStart.timestamp = 0; consumer.addSubscription(subscription); std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); addTestKeyOutput(*tx, 900, 2, generateAccount()); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = 0; block.transactions.push_back(tx); ASSERT_TRUE(consumer.onNewBlocks(&block, 1, 1)); ASSERT_FALSE(node.called); } TEST_F(TransfersConsumerTest, onNewBlocks_markTransactionConfirmed) { auto& container = addSubscription().getContainer(); TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(10000, unknownSender); b1.addTestKeyOutput(10000, UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX, m_accountKeys); auto tx = std::shared_ptr<ITransactionReader>(b1.build().release()); std::unique_ptr<ITransactionReader> prefix = createTransactionPrefix(convertTx(*tx)); std::vector<std::unique_ptr<ITransactionReader>> v; v.push_back(std::move(prefix)); m_consumer.onPoolUpdated(v, {}); auto lockedOuts = container.getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeStateLocked | ITransfersContainer::IncludeTypeKey); ASSERT_EQ(1, lockedOuts.size()); ASSERT_EQ(10000, lockedOuts[0].amount); CompleteBlock blocks[2]; blocks[0].block = cn::Block(); blocks[0].block->timestamp = 0; blocks[0].transactions.push_back(tx); blocks[1].block = cn::Block(); blocks[1].block->timestamp = 0; blocks[1].transactions.push_back(createTransaction()); ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 0, 2)); auto softLockedOuts = container.getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeKeyUnlocked); ASSERT_EQ(1, softLockedOuts.size()); ASSERT_EQ(10000, softLockedOuts[0].amount); } class INodeGlobalIndexStub: public INodeDummyStub { public: virtual void getTransactionOutsGlobalIndices(const crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices, const Callback& callback) override { outsGlobalIndices.push_back(globalIndex); callback(std::error_code()); }; uint32_t globalIndex; }; TEST_F(TransfersConsumerTest, onNewBlocks_checkTransactionOutputInformation) { const uint64_t index = 2; INodeGlobalIndexStub node; TransfersConsumer consumer(m_currency, node, m_logger, m_accountKeys.viewSecretKey); node.globalIndex = index; auto& container = addSubscription(consumer).getContainer(); std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); auto out = addTestKeyOutput(*tx, 10000, index, m_accountKeys); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = 0; block.transactions.push_back(tx); ASSERT_TRUE(consumer.onNewBlocks(&block, 0, 1)); auto outs = container.getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(1, outs.size()); auto& o = outs[0]; ASSERT_EQ(out.type, o.type); ASSERT_EQ(out.amount, o.amount); ASSERT_EQ(out.outputKey, o.outputKey); ASSERT_EQ(out.globalOutputIndex, o.globalOutputIndex); ASSERT_EQ(out.outputInTransaction, o.outputInTransaction); ASSERT_EQ(out.transactionPublicKey, o.transactionPublicKey); } TEST_F(TransfersConsumerTest, onNewBlocks_checkTransactionOutputInformationMultisignature) { const uint64_t index = 2; INodeGlobalIndexStub node; TransfersConsumer consumer(m_currency, node, m_logger, m_accountKeys.viewSecretKey); node.globalIndex = index; auto& container = addSubscription(consumer).getContainer(); std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); size_t txIndex = tx->addOutput(300, { m_accountKeys.address, generateAccountKeys().address}, 2); TransactionOutputInformation expectedOut; expectedOut.type = transaction_types::OutputType::Multisignature; expectedOut.amount = 300; expectedOut.globalOutputIndex = index; expectedOut.outputInTransaction = static_cast<uint32_t>(txIndex); expectedOut.transactionPublicKey = tx->getTransactionPublicKey(); expectedOut.requiredSignatures = 2; CompleteBlock block; block.block = cn::Block(); block.block->timestamp = 0; block.transactions.push_back(tx); ASSERT_TRUE(consumer.onNewBlocks(&block, 0, 1)); auto outs = container.getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(1, outs.size()); auto& o = outs[0]; ASSERT_EQ(expectedOut.type, o.type); ASSERT_EQ(expectedOut.amount, o.amount); ASSERT_EQ(expectedOut.requiredSignatures, o.requiredSignatures); ASSERT_EQ(expectedOut.globalOutputIndex, o.globalOutputIndex); ASSERT_EQ(expectedOut.outputInTransaction, o.outputInTransaction); ASSERT_EQ(expectedOut.transactionPublicKey, o.transactionPublicKey); } TEST_F(TransfersConsumerTest, onNewBlocks_checkTransactionInformation) { auto& container = addSubscription().getContainer(); std::shared_ptr<ITransaction> tx(createTransaction()); addTestInput(*tx, 10000); addTestKeyOutput(*tx, 1000, 2, m_accountKeys); Hash paymentId = crypto::rand<Hash>(); uint64_t unlockTime = 10; tx->setPaymentId(paymentId); tx->setUnlockTime(unlockTime); CompleteBlock blocks[2]; blocks[0].block = cn::Block(); blocks[0].block->timestamp = 0; blocks[0].transactions.push_back(createTransaction()); blocks[1].block = cn::Block(); blocks[1].block->timestamp = 11; blocks[1].transactions.push_back(tx); ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 0, 2)); TransactionInformation info; ASSERT_TRUE(container.getTransactionInformation(tx->getTransactionHash(), info)); ASSERT_EQ(tx->getTransactionHash(), info.transactionHash); ASSERT_EQ(tx->getTransactionPublicKey(), info.publicKey); ASSERT_EQ(1, info.blockHeight); ASSERT_EQ(11, info.timestamp); ASSERT_EQ(unlockTime, info.unlockTime); ASSERT_EQ(10000, info.totalAmountIn); ASSERT_EQ(1000, info.totalAmountOut); ASSERT_EQ(paymentId, info.paymentId); ASSERT_TRUE(info.messages.empty()); } TEST_F(TransfersConsumerTest, onNewBlocks_manyBlocks) { const size_t blocksCount = 1000; const size_t txPerBlock = 10; auto& container = addSubscription().getContainer(); std::vector<CompleteBlock> blocks(blocksCount); uint64_t timestamp = 10000; uint64_t expectedAmount = 0; size_t expectedTransactions = 0; uint32_t globalOut = 0; size_t blockIdx = 0; for (auto& b : blocks) { b.block = Block(); b.block->timestamp = timestamp++; if (++blockIdx % 10 == 0) { for (size_t i = 0; i < txPerBlock; ++i) { TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(10000, unknownSender); if ((i % 3) == 0) { b1.addTestKeyOutput(1000, ++globalOut, m_accountKeys); b1.addTestKeyOutput(2000, ++globalOut, m_accountKeys); expectedAmount += 3000; ++expectedTransactions; } auto tx = std::shared_ptr<ITransactionReader>(b1.build().release()); b.transactions.push_back(tx); } } } ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 0, static_cast<uint32_t>(blocks.size()))); ASSERT_EQ(expectedTransactions, container.transactionsCount()); ASSERT_EQ(expectedAmount, container.balance(ITransfersContainer::IncludeAll)); } TEST_F(TransfersConsumerTest, onPoolUpdated_addTransaction) { auto& sub = addSubscription(); // construct tx TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(10000, unknownSender); auto out = b1.addTestKeyOutput(10000, UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX, m_accountKeys); auto tx = std::shared_ptr<ITransactionReader>(b1.build().release()); std::unique_ptr<ITransactionReader> prefix = createTransactionPrefix(convertTx(*tx)); std::vector<std::unique_ptr<ITransactionReader>> v; v.push_back(std::move(prefix)); m_consumer.onPoolUpdated(v, {}); auto outputs = sub.getContainer().getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(1, outputs.size()); auto& o = outputs[0]; ASSERT_EQ(out.type, o.type); ASSERT_EQ(out.amount, o.amount); ASSERT_EQ(out.outputKey, o.outputKey); ASSERT_EQ(UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX, o.globalOutputIndex); } TEST_F(TransfersConsumerTest, onPoolUpdated_addTransactionMultisignature) { auto& sub = addSubscription(); // construct tx with multisignature output TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(10000, unknownSender); auto addresses = std::vector<AccountPublicAddress>{ m_accountKeys.address, generateAccountKeys().address }; b1.addTestMultisignatureOutput(10000, addresses, 1); auto tx = std::shared_ptr<ITransactionReader>(b1.build().release()); std::unique_ptr<ITransactionReader> prefix = createTransactionPrefix(convertTx(*tx)); std::vector<std::unique_ptr<ITransactionReader>> v; v.push_back(std::move(prefix)); m_consumer.onPoolUpdated(v, {}); auto outputs = sub.getContainer().getTransactionOutputs(tx->getTransactionHash(), ITransfersContainer::IncludeAll); ASSERT_EQ(1, outputs.size()); auto& o = outputs[0]; uint64_t amount_; MultisignatureOutput out; tx->getOutput(0, out, amount_); ASSERT_EQ(transaction_types::OutputType::Multisignature, o.type); ASSERT_EQ(amount_, o.amount); ASSERT_EQ(out.requiredSignatureCount, o.requiredSignatures); ASSERT_EQ(UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX, o.globalOutputIndex); } TEST_F(TransfersConsumerTest, onPoolUpdated_addTransactionDoesNotGetsGlobalIndices) { addSubscription(); // construct tx auto tx = createTransaction(); addTestInput(*tx, 10000); addTestKeyOutput(*tx, 10000, UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX, m_accountKeys); std::unique_ptr<ITransactionReader> prefix = createTransactionPrefix(convertTx(*tx)); std::vector<std::unique_ptr<ITransactionReader>> v; v.push_back(std::move(prefix)); m_consumer.onPoolUpdated(v, {}); ASSERT_TRUE(m_node.calls_getTransactionOutsGlobalIndices.empty()); } TEST_F(TransfersConsumerTest, onPoolUpdated_deleteTransactionNotDeleted) { auto& sub = addSubscription(); TransfersObserver observer; sub.addObserver(&observer); std::vector<crypto::Hash> deleted = { crypto::rand<crypto::Hash>(), crypto::rand<crypto::Hash>() }; m_consumer.onPoolUpdated({}, deleted); ASSERT_EQ(0, observer.deleted.size()); } TEST_F(TransfersConsumerTest, onPoolUpdated_deleteTransaction) { const uint8_t TX_COUNT = 2; auto& sub = addSubscription(); TransfersObserver observer; sub.addObserver(&observer); std::vector<std::unique_ptr<ITransactionReader>> added; std::vector<crypto::Hash> deleted; for (uint8_t i = 0; i < TX_COUNT; ++i) { // construct tx TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(10000, unknownSender); auto out = b1.addTestKeyOutput(10000, UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX, m_accountKeys); auto tx = std::shared_ptr<ITransactionReader>(b1.build().release()); std::unique_ptr<ITransactionReader> prefix = createTransactionPrefix(convertTx(*tx)); added.push_back(std::move(prefix)); deleted.push_back(added.back()->getTransactionHash()); } m_consumer.onPoolUpdated(added, {}); m_consumer.onPoolUpdated({}, deleted); ASSERT_EQ(deleted.size(), observer.deleted.size()); ASSERT_EQ(deleted, observer.deleted); } TEST_F(TransfersConsumerTest, getKnownPoolTxIds_empty) { addSubscription(); const std::unordered_set<crypto::Hash>& ids = m_consumer.getKnownPoolTxIds(); ASSERT_TRUE(ids.empty()); } std::shared_ptr<ITransactionReader> createTransactionTo(const AccountKeys& to, uint64_t amountIn, uint64_t amountOut) { TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(amountIn, unknownSender); b1.addTestKeyOutput(amountOut, UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX, to); auto tx = std::shared_ptr<ITransactionReader>(b1.build().release()); return tx; } TEST_F(TransfersConsumerTest, getKnownPoolTxIds_returnsUnconfirmed) { auto acc1 = generateAccount(); auto acc2 = generateAccount(); addSubscription(acc1); addSubscription(acc2); std::vector<std::shared_ptr<ITransactionReader>> txs; txs.push_back(createTransactionTo(acc1, 10000, 10000)); txs.push_back(createTransactionTo(acc1, 20000, 20000)); txs.push_back(createTransactionTo(acc2, 30000, 30000)); std::vector<std::unique_ptr<ITransactionReader>> v; v.push_back(createTransactionPrefix(convertTx(*txs[0]))); v.push_back(createTransactionPrefix(convertTx(*txs[1]))); v.push_back(createTransactionPrefix(convertTx(*txs[2]))); m_consumer.onPoolUpdated(v, {}); const std::unordered_set<crypto::Hash>& ids = m_consumer.getKnownPoolTxIds(); ASSERT_EQ(3, ids.size()); for (int i = 0; i < 3; ++i) { auto txhash = txs[i]->getTransactionHash(); ASSERT_EQ(1, ids.count(txhash)); } } TEST_F(TransfersConsumerTest, onNewBlocks_getsDepositOutputCorrectly) { auto& container = addSubscription().getContainer(); const uint64_t AMOUNT = 84756; const uint32_t REQUIRED_SIGNATURES = 2; const uint32_t TERM = 444021; std::shared_ptr<ITransaction> tx = createTransaction(); tx->addOutput(AMOUNT, std::vector<AccountPublicAddress> {m_accountKeys.address}, REQUIRED_SIGNATURES, TERM); CompleteBlock block; block.block = cn::Block(); block.block->timestamp = 1235; block.transactions.push_back(tx); m_consumer.onNewBlocks(&block, 0, 1); std::vector<TransactionOutputInformation> transfers; container.getOutputs(transfers, ITransfersContainer::IncludeAll); ASSERT_EQ(1, transfers.size()); EXPECT_EQ(transaction_types::OutputType::Multisignature, transfers[0].type); EXPECT_EQ(AMOUNT, transfers[0].amount); EXPECT_EQ(REQUIRED_SIGNATURES, transfers[0].requiredSignatures); EXPECT_EQ(TERM, transfers[0].term); } class AutoTimer { public: AutoTimer(bool startNow = true) { if (startNow) { start(); } } void start() { startTime = std::chrono::steady_clock::now(); } std::chrono::duration<double> getSeconds() { return std::chrono::steady_clock::now() - startTime; } private: std::chrono::steady_clock::time_point startTime; }; class AutoPrintTimer : AutoTimer { public: ~AutoPrintTimer() { std::cout << "Running time: " << getSeconds().count() << "s" << std::endl; } }; class TransfersConsumerPerformanceTest : public TransfersConsumerTest { public: void addAndSubscribeAccounts(size_t count) { std::cout << "Creating " << count << " accounts" << std::endl; for (size_t i = 0; i < count; ++i) { recipients.push_back(generateAccount()); addSubscription(recipients.back()); } } size_t generateBlocks(size_t blocksCount, size_t txPerBlock, size_t eachNTx = 3) { std::cout << "Generating " << blocksCount << " blocks, " << blocksCount*txPerBlock << " transactions" << std::endl; blocks.resize(blocksCount); uint64_t timestamp = 10000; uint64_t expectedAmount = 0; size_t totalTransactions = 0; size_t expectedTransactions = 0; uint32_t globalOut = 0; for (auto& b : blocks) { b.transactions.clear(); b.block = Block(); b.block->timestamp = timestamp++; for (size_t i = 0; i < txPerBlock; ++i) { auto tx = createTransaction(); addTestInput(*tx, 10000); if ((totalTransactions % eachNTx) == 0) { auto& account = recipients[rand() % recipients.size()]; addTestKeyOutput(*tx, 1000, ++globalOut, account); addTestKeyOutput(*tx, 2000, ++globalOut, account); addTestKeyOutput(*tx, 3000, ++globalOut, account); expectedAmount += 6000; ++expectedTransactions; } tx->getTransactionHash(); b.transactions.push_back(std::move(tx)); ++totalTransactions; } } return expectedTransactions; } std::vector<AccountKeys> recipients; std::vector<CompleteBlock> blocks; }; TEST_F(TransfersConsumerPerformanceTest, DISABLED_memory) { addAndSubscribeAccounts(10000); size_t txcount = generateBlocks(1000, 50, 1); std::cout << "Blocks generated, calling onNewBlocks" << std::endl; { AutoPrintTimer t; ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 0, static_cast<uint32_t>(blocks.size()))); } blocks.clear(); blocks.shrink_to_fit(); std::cout << "Transactions to accounts: " << txcount << std::endl; char c; std::cin >> c; } TEST_F(TransfersConsumerPerformanceTest, DISABLED_performanceTest) { const size_t blocksCount = 1000; const size_t txPerBlock = 10; addAndSubscribeAccounts(1000); auto expectedTransactions = generateBlocks(blocksCount, txPerBlock, 3); auto start = std::chrono::steady_clock::now(); std::cout << "Calling onNewBlocks" << std::endl; ASSERT_TRUE(m_consumer.onNewBlocks(&blocks[0], 0, static_cast<uint32_t>(blocks.size()))); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> dur = end - start; std::cout << "Total transactions sent: " << blocksCount * txPerBlock << std::endl; std::cout << "Transactions sent to accounts: " << expectedTransactions << std::endl; std::cout << "Running time: " << dur.count() << "s" << std::endl; std::cout << "Finish" << std::endl; }
// // Created by nikita on 12/27/19. // #ifndef SERVER_CONNECTION_H #define SERVER_CONNECTION_H #include <thread> #include <queue> #include "../server_epoll/server.h" #include "../taskqueue.h" struct connection { using on_new_message_t = std::function<void (std::string)>; using on_disconnect_t = std::function<void ()>; connection(server_socket *h) : handler_(h) { std::cout << "connection created" << std::endl; h->set_on_read(std::bind(&connection::on_read, this, std::placeholders::_1)); h->set_on_write(std::bind(&connection::on_write, this, std::placeholders::_1)); h->set_on_close(std::bind(&connection::on_close, this)); } server_socket* handler() { return handler_; } void write(char* data, size_t size) { std::cout << "new data to send " << std::endl; auto v = std::vector(data, data + size); to_write.push(v); std::lock_guard<std::mutex> l(write_lock); handler_->set_on_write(std::bind(&connection::on_write, this, std::placeholders::_1)); } void set_on_new_message(on_new_message_t callback) { on_new_message = callback; } void set_on_disconnect(on_disconnect_t callback) { on_disconnect = callback; } void close() { to_write.finish(); handler_->close(); } private: void on_close() { std::cout << "closing..." << std::endl; if (on_disconnect) on_disconnect(); } void on_read(server_socket::reader reader) { std::array<char, 1024> data; size_t size = reader.read(data.data(), data.size()); auto end = data.begin() + size; auto beg = data.begin(); for (auto it = beg; it != end; ) { it = std::find(beg, end, '\n'); if (it != end) { msg.insert(msg.end(), beg, it - 1); on_new_message(std::move(msg)); msg.clear(); beg = it + 1; } } msg.insert(msg.end(), beg, end); } void on_write(server_socket::writer w) { std::lock_guard<std::mutex> l(write_lock); std::vector<char> msg; while(to_write.nonblock_pop(msg)) { w.write(msg.data(), msg.size()); } handler_->set_on_write(nullptr); } std::mutex write_lock; std::string msg; server_socket* handler_; on_new_message_t on_new_message; on_disconnect_t on_disconnect; TaskQueue<std::vector<char>> to_write; }; #endif //SERVER_CONNECTION_H
#include<iostream> #include<vector> #include<algorithm> using namespace std; #define maxn 1200000 int possible[maxn], n, mod = 1000000007; vector<int> divisors[maxn]; int main() { for(int i = 1; i < maxn; i++){ for(int j = i; j < maxn; j += i) divisors[j].push_back(i); reverse(divisors[i].begin(), divisors[i].end()); } cin >> n; possible[0] = 1; while(n--) { int a; cin >> a; for(int x : divisors[a]) { possible[x] = (possible[x] + possible[x-1]) % mod; // cout << x << " divof " << a << endl; } } int ans = 0; for(int i = 1; i < maxn; i++) ans = (ans + possible[i]) % mod; cout << ans; }
class ItemDocument: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_DOCUMENT; model = "\z\addons\dayz_epoch\models\doc_generic.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_doc_generic_ca.paa"; descriptionShort = $STR_EPOCH_DOCUMENT_DESC; sfx = "document"; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_188; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {}; randomOutput = 1; output[] = {{"ItemLetter",1},{"ItemDocumentRamp",1},{"ItemBook1",1},{"ItemBook2",1},{"ItemBook3",1},{"ItemBook4",1},{"ItemNewspaper",1},{"ItemORP",1},{"ItemAVE",1},{"ItemLRK",1},{"ItemTNK",1},{"ItemARM",1},{"ItemTruckORP",1},{"ItemTruckAVE",1},{"ItemTruckLRK",1},{"ItemTruckTNK",1},{"ItemTruckARM",1},{"ItemHeliAVE",1},{"ItemHeliLRK",1},{"ItemHeliTNK",1},{"ItemPlotDeed",1}}; input[] = {{"ItemDocument",1}}; }; }; }; class ItemPlotDeed: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_PLOTDEED; model = "\z\addons\dayz_epoch\models\doc_generic.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_doc_generic_ca.paa"; descriptionShort = $STR_EPOCH_PLOTDEED_DESC; sfx = "document"; class ItemActions { class Crafting { text = $STR_EPOCH_PLOTDEED_ACTION; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"plot_pole_kit",1}}; input[] = {{"ItemPlotDeed",1},{"ItemGoldBar10oz",2}}; }; }; }; class ItemLetter: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_LETTER; model = "\z\addons\dayz_epoch\models\doc_letter.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_doc_letter_ca.paa"; descriptionShort = $STR_EPOCH_LETTER_DESC; }; class ItemBook1: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_ROMANCENOVEL; model = "\z\addons\dayz_epoch\models\doc_trashy1.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_trashy1_ca.paa"; descriptionShort = $STR_EPOCH_ROMANCENOVEL_DESC; }; class ItemBook2: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_ROMANCENOVEL; model = "\z\addons\dayz_epoch\models\doc_trashy2.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_trashy2_ca.paa"; descriptionShort = $STR_EPOCH_ROMANCENOVEL_DESC2; }; class ItemBook3: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_BOOK; model = "\z\addons\dayz_epoch\models\doc_child1.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_child1_ca.paa"; descriptionShort = $STR_EPOCH_BOOK_DESC; }; class ItemBook4: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_BOOK; model = "\z\addons\dayz_epoch\models\doc_child2.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_child2_ca.paa"; descriptionShort = $STR_EPOCH_BOOK_DESC; }; class ItemNewspaper: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_TORNNEWSPAPER; model = "\z\addons\dayz_epoch\models\doc_deaths.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_deaths_ca.paa"; descriptionShort = $STR_EPOCH_TORNNEWSPAPER_DESC; class ItemActions { class Obituaries { text = $STR_EPOCH_TORNNEWSPAPER_ACTION; script = "spawn player_deathBoard;"; }; }; }; class ItemDocumentRamp: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_WOODRAMP; model = "\z\addons\dayz_epoch\models\doc_ramp.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_doc_ramp_ca.paa"; descriptionShort = $STR_EPOCH_WOODRAMP_DESC; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_189; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"wood_ramp_kit",1}}; input[] = {{"ItemDocumentRamp",1},{"PartWoodLumber",8}}; }; }; }; class ItemBookBible : CA_Magazine { scope = 2; count = 1; type = 256; model = "z\addons\dayz_communityassets\models\bible.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_bible_CA.paa"; displayName = $STR_BOOK_NAME_BIBLE; descriptionShort = $STR_BOOK_DESC_BIBLE; }; class ItemTrashPaper : CA_Magazine { scope = 2; count = 1; type = 256; model = "z\addons\dayz_communityassets\models\paper_sheet_clean_note.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_paper_sheet_note_ca.paa"; displayName = $STR_name_ItemTrashPaper; descriptionShort = $STR_desc_ItemTrashPaper; }; class ItemTrashPaperMusic : CA_Magazine { scope = 2; count = 1; type = 256; model = "z\addons\dayz_communityassets\models\paper_sheet_musical.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_paper_sheet_musical_ca.paa"; displayName = $STR_name_ItemTrashPaperMusic; descriptionShort = $STR_desc_ItemTrashPaperMusic; }; class equip_paper_sheet : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_paper_sheet; descriptionShort = $STR_ITEM_DESC_equip_paper_sheet; picture = "\z\addons\dayz_communityassets\CraftingPlaceholders\equip_paper_sheet.paa"; type = 256; }; class equip_note : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_note; descriptionShort = $STR_ITEM_DESC_equip_note; picture = "\z\addons\dayz_communityassets\CraftingPlaceholders\equip_note.paa"; type = 256; }; // Vehicle upgrade parts class ItemORP: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_ORP; model = "\z\addons\dayz_epoch\models\doc_Up1.p3d"; picture = "\dayz_epoch_c\icons\documents\car_offroad.paa"; descriptionShort = $STR_EPOCH_VEHUP_ORP_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemAVE: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_AVE; model = "\z\addons\dayz_epoch\models\doc_Up2.p3d"; picture = "\dayz_epoch_c\icons\documents\car_armor.paa"; descriptionShort = $STR_EPOCH_VEHUP_AVE_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemLRK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_LRK; model = "\z\addons\dayz_epoch\models\doc_Up3.p3d"; picture = "\dayz_epoch_c\icons\documents\car_cargo.paa"; descriptionShort = $STR_EPOCH_VEHUP_LRK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTNK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_TNK; model = "\z\addons\dayz_epoch\models\doc_Up4.p3d"; picture = "\dayz_epoch_c\icons\documents\car_fuel.paa"; descriptionShort = $STR_EPOCH_VEHUP_TNK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemARM: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_ARM; model = "\z\addons\dayz_epoch\models\doc_car_weps.p3d"; picture = "\dayz_epoch_c\icons\documents\car_weapon.paa"; descriptionShort = $STR_EPOCH_VEHUP_ARM_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTruckORP: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_ORP_TRUCK; model = "\z\addons\dayz_epoch\models\doc_Up_truck1.p3d"; picture = "\dayz_epoch_c\icons\documents\truck_offroad.paa"; descriptionShort = $STR_EPOCH_VEHUP_ORP_TRUCK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTruckAVE: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_AVE_TRUCK; model = "\z\addons\dayz_epoch\models\doc_Up_truck2.p3d"; picture = "\dayz_epoch_c\icons\documents\truck_armor.paa"; descriptionShort = $STR_EPOCH_VEHUP_AVE_TRUCK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTruckLRK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_LRK_TRUCK; model = "\z\addons\dayz_epoch\models\doc_Up_truck3.p3d"; picture = "\dayz_epoch_c\icons\documents\truck_cargo.paa"; descriptionShort = $STR_EPOCH_VEHUP_LRK_TRUCK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTruckTNK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_TNK_TRUCK; model = "\z\addons\dayz_epoch\models\doc_Up_truck4.p3d"; picture = "\dayz_epoch_c\icons\documents\truck_fuel.paa"; descriptionShort = $STR_EPOCH_VEHUP_TNK_TRUCK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTruckARM: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_ARM_TRUCK; model = "\z\addons\dayz_epoch\models\doc_Up_truck_weps.p3d"; picture = "\dayz_epoch_c\icons\documents\truck_weapon.paa"; descriptionShort = $STR_EPOCH_VEHUP_ARM_TRUCK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTankORP: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_ORP_TANK; model = "\z\addons\dayz_epoch\models\doc_Up_bmp1.p3d"; picture = "\dayz_epoch_c\icons\documents\bmp_offroad.paa"; descriptionShort = $STR_EPOCH_VEHUP_ORP_TANK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTankAVE: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_AVE_TANK; model = "\z\addons\dayz_epoch\models\doc_Up_bmp2.p3d"; picture = "\dayz_epoch_c\icons\documents\bmp_armor.paa"; descriptionShort = $STR_EPOCH_VEHUP_AVE_TANK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTankLRK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_LRK_TANK; model = "\z\addons\dayz_epoch\models\doc_Up_bmp3.p3d"; picture = "\dayz_epoch_c\icons\documents\bmp_cargo.paa"; descriptionShort = $STR_EPOCH_VEHUP_LRK_TANK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemTankTNK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_TNK_TANK; model = "\z\addons\dayz_epoch\models\doc_Up_bmp4.p3d"; picture = "\dayz_epoch_c\icons\documents\bmp_fuel.paa"; descriptionShort = $STR_EPOCH_VEHUP_TNK_TANK_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemHeliAVE: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_AVE_HELI; model = "\z\addons\dayz_epoch\models\doc_Up_heli1.p3d"; picture = "\dayz_epoch_c\icons\documents\heli_armor.paa"; descriptionShort = $STR_EPOCH_VEHUP_AVE_HELI_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemHeliLRK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_LRK_HELI; model = "\z\addons\dayz_epoch\models\doc_Up_heli2.p3d"; picture = "\dayz_epoch_c\icons\documents\heli_cargo.paa"; descriptionShort = $STR_EPOCH_VEHUP_LRK_HELI_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class ItemHeliTNK: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_VEHUP_TNK_HELI; model = "\z\addons\dayz_epoch\models\doc_Up_heli3.p3d"; picture = "\dayz_epoch_c\icons\documents\heli_fuel.paa"; descriptionShort = $STR_EPOCH_VEHUP_TNK_HELI_DESC; sfx = "document"; class ItemActions { class Upgrades { text = $STR_EPOCH_PLAYER_UPGRADEV; script = "spawn player_upgradeVehicle;"; }; }; }; class Blueprint_01: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_01; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_01; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_02: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_02; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_02; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_03: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_03; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_03; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_04: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_04; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_04; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_05: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_05; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_05; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_06: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_06; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_06; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_07: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_07; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_07; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_08: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_08; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_08; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_09: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_09; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_09; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_10: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_10; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_10; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_11: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_11; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_11; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_12: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_12; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_12; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_13: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_13; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_13; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_14: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_14; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_14; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_15: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_15; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_15; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_16: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_16; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_16; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_17: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_17; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_17; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_18: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_18; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_18; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_19: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_19; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_19; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class Blueprint_20: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_BLUEPRINT_20; descriptionShort = $STR_ITEM_DESC_BLUEPRINT_20; picture = "\dayz_epoch_c\icons\equipment\ItemBlueprint.paa"; model = "\z\addons\dayz_epoch_w\items\bluprint_01.p3d"; }; class PileBooks: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_PILEOFBOOKS; descriptionShort = $STR_ITEM_DESC_PILEOFBOOKS; picture = "\dayz_epoch_c\icons\equipment\ItemPileBooks.paa"; model = "\z\addons\dayz_epoch_w\items\books.p3d"; }; class PileMedBooks: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_PILEOFMEDBOOKS; descriptionShort = $STR_ITEM_DESC_PILEOFMEDBOOKS; picture = "\dayz_epoch_c\icons\equipment\ItemPileMedBooks.paa"; model = "\z\addons\dayz_epoch_w\items\books_med.p3d"; };
#include <iostream> #include <unistd.h> #include <plib.h> #include <Vec.h> #include <matrix.h> matrix<double> lowq2DenMat(fourVec ein,fourVec eout) { double cos_t,sin_t; matrix<double> R(2,2); matrix<double> Rinv(2,2); matrix<double> Rot(2,2); matrix<double> Rotinv(2,2); matrix<double> denMat(2,2); matrix<double> denMatTrans(2,2); threeVec Cross; double qsq = Qsq(ein.t(),eout.t(),((ein.V() - eout.V()).theta())); double eps = epsilon(ein.t(),eout.t(),((ein.V() - eout.V()).theta())); denMat.el(0,0) = 0.5 * (1 + eps); denMat.el(0,1) = 0.0; denMat.el(1,0) = 0.0; denMat.el(1,1) = 0.5 * (1 - eps); // what is the angle between the electron plane and the y axis? Cross = ein.V() / eout.V(); cos_t = Cross.y()/Cross.r(); sin_t = 1. - cos_t * cos_t; Rot.el(0,0) = Rot.el(1,1) = cos_t; Rot.el(0,1) = -sin_t; Rot.el(1,0) = sin_t; Rotinv = Rot.inv(); // rotate the density matrix denMatTrans = Rotinv * denMat * Rot; // now transform into helicity basis R.el(0,0) = 1.0/sqrt(2.0); R.el(1,0) = 1.0/sqrt(2.0); R.el(0,1) = -1.0/sqrt(2.0); R.el(1,1) = 1.0/sqrt(2.0); Rinv = R.inv(); denMat = Rinv * denMatTrans * R; return(denMat); }
#include <conio.h> #include <iostream.h> #include <stdio.h> void main () { clrscr(); int A[5],i; printf("Enter values: "); for (i=0; i<5; i++) { printf("\nA[%d]: ",i); scanf("%d",&A[i]); } printf("\n\nSequential Display"); for (i=0; i<5; i++) printf("\n\nA[%d]: %d",i,A[i]); printf("\n\nReverse Display"); for (i=4; i>=0; i--) printf("\n\nA[%d]: %d",i,A[i]); getche(); }
#include <stdio.h> #include <string.h> #include <iostream> #include <string> #include <windows.h> //definindo constantes #define MAX_CHAR 18 #define MAX_PAL 10 #define MAX_MAT 30 #define AZUL 9 #define VERMELHO 12 #define VERDE 10 #define BRANCO 15 #define AMARELO 6 #define ROXO 13 #define CINZA 8 #define BEGE 14 typedef struct posicoes_do_selecionado{ int x = 0; int y = 0; int tam = 1; } Posi; //ESSE STRUCT SERVIRA PARA GUARDAR AS POSIÇOES DAS PALAVRAS QUE JA FORAM ACERTADAS PARA POSTERIORMENTE MARCA-LAS COM COR DIFERENTE //O ULTIMO INDICE sera um lugar temporario para, caso a palavra selecionada estiver na lista de palavras, ele irá salvar permanentemente as posições // x, y no mesmo indice da palavra escolhida, para melhor organização Posi pos[MAX_PAL][MAX_CHAR]; typedef struct variaveis_da_marca{ int x = 1; int y = 1; int tam = 2; int dir = 6; } marcaVars; //teste marcaVars vars; //Inicializando variaveis globais int comando, linhas, colunas, nPalavras, resultado = -1, acertadas = 0, t; char matriz[MAX_MAT][MAX_MAT], palavras[MAX_PAL][MAX_CHAR], selecionado[MAX_CHAR]; bool terminou = false, leu = false, gameLoop = true; char escolha; using namespace std; void debuga(){ cout << "Insira o index da palavra acertada"; cin >> t; for (int i = 0; i < pos[t][0].tam; i++){ cout << "pos[0]["<<i<<"].x , pos[0]["<<i<<"].y= " << pos[t][i].x << ", " << pos[t][i].y; } } void troca_cor(int cor){ //Muda a cor do char impresso SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), cor); } bool eh_igual(char pal[]){ //Checa se a palavra (da matriz de palavras) é igual a char* selecionado for (int i = 0; i<vars.tam ; i++){ if(pal[i]!=selecionado[i]){ return false; } } return true; } int checa_palavras(){ //Passa por todas as palavras restantes e checa se é igual a palavra selecionada, adiciona as variaveis da posição no primeiro elemento disponivel no //array pos para serem marcados dps for(int i = 0; i < nPalavras; i++){ if(eh_igual(palavras[i])){ for(int p = 0; p < vars.tam; p++){ pos[acertadas][p].x = pos[MAX_PAL-1][p].x; pos[acertadas][p].y = pos[MAX_PAL-1][p].y; } pos[acertadas][0].tam = pos[MAX_PAL][0].tam; acertadas++; return i; } } return -1; } void elimina_palavra(){ if(leu){ for (int i = resultado; i < nPalavras; ++i){ memcpy(palavras[i], palavras[i + 1], MAX_CHAR+1); } nPalavras--; } } void junta_chars(){ if(leu){ int m, n; //Junta as letras selecionadas em um char para comparação if (vars.dir == 2){//esquerda para direita for(int i=0; i<vars.tam ;i++){ m = vars.x+i; n = vars.y; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } }else if (vars.dir == 8){//direita para esquerda for(int i=0; i<vars.tam ;i++){ m = vars.x-i; n = vars.y; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } }else if (vars.dir == 6){//cima para baixo for(int i=0; i<vars.tam ;i++){ m = vars.x; n = vars.y+i; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } }else if (vars.dir == 4){//baixo para cima for(int i=0; i<vars.tam ;i++){ m = vars.x; n = vars.y-i; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } }else if (vars.dir == 1){//diag baixo para cima, esquerda para direita for(int i=0; i<vars.tam ;i++){ m = vars.x+i; n = vars.y-i; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } }else if (vars.dir == 7){//diag baixo para cima, direita para esquerda for(int i=0; i<vars.tam ;i++){ m = vars.x-i; n = vars.y-i; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } }else if (vars.dir == 3){//diag cima para baixo, esquerda para direita for(int i=0; i<vars.tam ;i++){ m = vars.x+i; n = vars.y+i; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } }else if (vars.dir == 9){//diag cima para baixo, direita para esquerda for(int i=0; i<vars.tam ;i++){ m = vars.x-i; n = vars.y+i; selecionado[i] = matriz[m][n]; pos[MAX_PAL-1][i].x = m; pos[MAX_PAL-1][i].y = n; } } pos[MAX_PAL-1][0].tam=vars.tam; selecionado[vars.tam]='\0'; //finaliza o string } } void le_doc(){ if(leu){ cout << "Tem certeza que deseja carrega um novo arquivo (Isso irá apagar o progresso do caca palavras atual)?\nS/N:"; cin >> escolha; if(char(tolower(escolha))=='s'){ leu = false; le_doc(); }else if(char(tolower(escolha))=='n'){ return; }else{ troca_cor(VERMELHO); cout << "Comando invalido, por favor digite \'s\' ou \'n\' da proxima vez!\n"; troca_cor(BRANCO); return; } }else{ //Inicializando as variaveis do arquivo char nomeArquivo[30]; FILE* arquivo; troca_cor(AMARELO); cout << "Insira o nome do arquivo completo (com .txt) do caça palavras (note qe o arquivo deve estar com a formatacao adequada):\n"; troca_cor(BRANCO); cin >> nomeArquivo; //Abre o arquivo no modo "leitura" (read) arquivo = fopen(nomeArquivo, "r"); //Checa se o arquivo existe if(arquivo == NULL){ troca_cor(VERMELHO); cout << "Não foi possivel carregar o arquivo, cheque se o nome e o arquivo estão corretos\n"; troca_cor(BRANCO); }else{ //Coleta as informacoes do arquivo seguindo esse padrao fscanf(arquivo, "%d %d %d\n", &linhas, &colunas, &nPalavras);//1a linha com inteiros //Coleta o caca palavras e salva na matriz for(int j = 0; j < linhas; j++){ for(int k = 0; k < colunas; k++){ char st; if(k==colunas-1){ fscanf(arquivo, "%c\n", &st); }else{ fscanf(arquivo, "%c", &st); } matriz[j][k] = st; } } //le palavras int i = 0; char temp[MAX_CHAR]; do { //le a linha de palavras e salva em temp fgets(temp, sizeof (temp), arquivo); strcpy(palavras[i],temp); // LEMBRE QE O PALAVRAS[i] é salvo com o "\n" no final! i++; }while (i < nPalavras); fclose(arquivo); leu = true; } } } void imprime(){ troca_cor(AZUL); if(leu){ for(int j = 0; j < linhas + 2; j++) { cout << "\t\t\t\t\t\t"; for(int k = 0; k < colunas + 2; k++) { //Imprime numeros na 1a ou ultima linha if(j == 0 || j == linhas + 1){ if(k == 0) {//se for o elemento 0,0 ou linha -1, 0 cout << " "; } else if (k == colunas + 1) {//se for o elemento (0, coluna - 1) ou (linha - 1, coluna - 1) cout << " " << endl; } else{ if(k>10){ cout << k - 11 << " "; }else{ cout << k - 1 << " "; } } } else if(k == 0) {//se for a 1a coluna if(j>10){ cout << j - 11 << " "; }else{ cout << j - 1 << " "; } } else if(k == colunas + 1) {//se for a ultima coluna if(j>10){ cout << j - 11 << endl; }else{ cout << j - 1 << endl; } } else { //se nao for nenhuma das anteriores, então imprimiremos a matriz if(acertadas>0){//se houverem palavras acertadas for(int p = 0; p < acertadas; p++){//checa todas as palavras acertadas e suas posições, se x e y forem for(int q = 0; q < pos[p][0].tam ; q++){ if((j-1==pos[p][q].x) && (k-1==pos[p][q].y)){//imprime apenas se troca_cor(VERDE); cout << matriz[j-1][k-1] << " "; troca_cor(AZUL); goto prox; } } } goto continuar; }else{ continuar:; troca_cor(BRANCO); cout << matriz[j-1][k-1] << " "; troca_cor(AZUL); } prox:; } } } //Imprimir palavras que faltam cout<< "Palavras restantes:\n"; for(int p = 0; p < nPalavras; p++){ cout << palavras[p]; } }else{ troca_cor(VERMELHO); cout << "Primeiro carregue seu caca palavras com o comando 1 (carrega).\n"; troca_cor(BRANCO); } troca_cor(BRANCO); } void marca(){ if(leu){ cout << "Insira as coordenadas x, y da primeira letra, o tamanho da palavra e a direção seguindo o seguinte padrao: "; troca_cor(VERDE); cout << "\nX Y TAMANHO DIRECAO"; troca_cor(AMARELO); cout << "\nDIAGONAIS:\ \n1 - diag cima para baixo, direita para esquerda\ \n7 - diag baixo para cima, direita para esquerda\ \n9 - diag baixo para cima, esquerda para direita\ \n3 - diag cima para baixo, esquerda para direita\ \nORTOGONAIS:\ \n6 - esquerda para direita\ \n4 - direita para esquerda\ \n2 - cima para baixo\ \n8 - baixo para cima\n"; troca_cor(BRANCO); imprime(); cin >> vars.x >> vars.y >> vars.tam >> vars.dir; junta_chars(); resultado = checa_palavras(); if(resultado < 0){//char* "selecionado" não é igual a nenhuma das palavras troca_cor(ROXO); cout << "ERRROUUU, a palavra que você selecionou foi:\n" << selecionado << "\nTente de novo!\n"; troca_cor(BRANCO); }else{ troca_cor(VERDE); cout << "Boaa, uma a menos para a lista!\n"; elimina_palavra(); if(nPalavras == 0){ cout << "Parabens voce achou todas as palavras!\n"; } troca_cor(BRANCO); } } } int main(){ while(gameLoop==true){ cout << "Insira o comando desejado: 1 - carrega, 2 - marca, 3 - fecha, 4 - Teste do bool eh_igual\n"; cin >> comando; switch(comando){ case 1:{//carrega //Le o documento e salva toda sua informação le_doc(); imprime(); break; } case 2:{//marca //Imprime a matriz devidamente, com os numeros e com a formatação adequada marca(); imprime(); break; } case 3:{//fecha // Sai do jogo atual if(leu){ cout << "Todo seu progresso será perdido, tem certeza que quer continuar?\nS/N:"; cin >> escolha; if(char(tolower(escolha))=='s'){ cout << "Parabens todos os seus dados foram vendidos! Flw.\n" << endl; gameLoop = false; }else if(char(tolower(escolha))=='n'){ }else{ cout << "Comando invalido, por favor digite \'s\' ou \'n\' da proxima vez!\n"; } }else{ cout<< "Que decepcao..."; gameLoop = false; break; } break; } case 4:{ debuga(); break; } default: cout << "Comando invalido, por favor digite 1, 2 ou 3 da proxima vez!\n"; } } return 0; }
#include "gl_framework.h" #include <sstream> #include <map> #include <string> #include "command/glGetIntegerv.h" #include "command/glDeleteTextures.h" #include "command/glBindTexture.h" #include "command/glTexImage2D.h" #include "command/glBlendFunc.h" #include "command/glGetError.h" #include "command/glGenTextures.h" #include "command/glFlush.h" #include "command/glew/glUseProgram.h" using namespace glmock; ValidationException::ValidationException(CommandError* errors, unsigned int count) : mErrors(errors), mCount(count), IValidationException(mErrors, mCount) { } ValidationException::~ValidationException() { delete mErrors; } GLFramework* __instance = 0; GLFramework::GLFramework(IErrorCallback* calback) : mErrorCallback(calback) { __instance = this; } GLFramework::~GLFramework() { __instance = 0; if(mCommands.size() > 0) { // Not all commands where invoked!!! while(!mCommands.empty()) { GLCommand* cmd = mCommands.front(); mErrorCallback->OnFunctionNotCalled(cmd->Name); mCommands.pop(); } } delete mErrorCallback; } void GLFramework::glGetIntegerv(GLenum pname, GLint* params) { GLGetIntegerv* command = new GLGetIntegerv(pname, params); mCommands.push(command); } void GLFramework::glDeleteTextures(GLsizei n, const GLuint* textures) { GLDeleteTextures* command = new GLDeleteTextures(n, textures); mCommands.push(command); } void GLFramework::glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels) { GLTexImage2D* command = new GLTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); mCommands.push(command); } void GLFramework::glBindTexture(GLenum target, GLuint texture) { GLBindTexture* command = new GLBindTexture(target, texture); mCommands.push(command); } IReturns<GLenum>* GLFramework::glGetError() { GLGetError* command = new GLGetError(); mCommands.push(command); return command; } void GLFramework::glGenTextures(GLsizei n, GLuint* textures) { GLGenTextures* command = new GLGenTextures(n, textures); mCommands.push(command); } void GLFramework::glFlush() { GLFlush* command = new GLFlush(); mCommands.push(command); } void GLFramework::glBlendFunc(GLenum sfactor, GLenum dfactor) { GLBlendFunc* command = new GLBlendFunc(sfactor, dfactor); mCommands.push(command); } void GLFramework::glUseProgram(GLuint program) { GLUseProgram* command = new GLUseProgram(program); mCommands.push(command); } GLCommand* GLFramework::TryGet() { if(__instance == NULL) { throw new MockEngineNotInitializedException(); } std::queue<GLCommand*>& commands = __instance->mCommands; if(commands.empty()) return NULL; GLCommand* cmd = commands.front(); commands.pop(); return cmd; } void GLFramework::AddBadParameter(const char* function, const char* paramName, std::string expected, std::string actual) { __instance->mErrorCallback->OnBadParameter(function, paramName, expected.c_str(), actual.c_str()); } void GLFramework::AddBadFunctionCalled(const char* expected, const char* actual) { __instance->mErrorCallback->OnBadFunctionCalled(expected, actual); } void GLFramework::AddUnspecifiedFunctionCalled(const char* expected) { __instance->mErrorCallback->OnUnspecifiedFunctionCalled(expected); } namespace glmock { std::string IntToString(GLint val) { std::stringstream ss; ss << val; return ss.str(); } std::string FloatToString(GLfloat val) { std::stringstream ss; ss << val; return ss.str(); } std::string DoubleToString(GLdouble val) { std::stringstream ss; ss << val; return ss.str(); } }
/** * created: 2013-4-7 22:53 * filename: FKHashDBPool * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #pragma once //------------------------------------------------------------------------ #include "FKDBConnPool.h" #include "../FKSingleton.h" #include "../RTTI/FKReflect.h" #include <malloc.h> //------------------------------------------------------------------------ struct stDBParam { int m_nHashDBCount; int m_nOneHashDBTblCount; //每个数据库几个表 int m_nAllTblCount; //一共分散在多少个表里 char m_sztblnamefmt[MAX_PATH]; }; //------------------------------------------------------------------------ class HashDBPool : public CLD_DBConnPool { public: std::map<int,stDBParam> m_dbparams; public: HashDBPool( const char* tblnamefmt = "mydb_name_nameex_tbl%d", int DBCount = 1, int OneDBTblCount = 1, int nhashcode = 0); public: void init (const char* tblnamefmt, int DBCount, int OneDBTblCount, int nhashcode = 0); const char* gethash_tblname (const char* szaccount, unsigned int& ndbhashcode, unsigned int& nhashvalue, int nhashcode = 0); const char* gethash_tblinfo (const char* szaccount, unsigned int& ntblid, unsigned int& ndbhashcode, unsigned int& nhashvalue, int nhashcode = 0); }; //------------------------------------------------------------------------
/* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * File: ctcdf_terminate.c * * MATLAB Coder version : 3.3 * C/C++ source code generated on : 24-Apr-2018 18:23:19 */ /* Include Files */ #include "rt_nonfinite.h" #include "ctcdf.h" #include "ctcdf_terminate.h" namespace matlabautogen { /* Function Definitions */ /* * Arguments : void * Return Type : void */ void ctcdf_terminate(void) { /* (no terminate code required) */ } } /* * File trailer for ctcdf_terminate.c * * [EOF] */
#ifndef _PushOutCard_H_ #define _PushOutCard_H_ #include "BaseProcess.h" class PushOperateResult :public BaseProcess { public: PushOperateResult(); virtual ~PushOperateResult(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) ; virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ; }; #endif
#pragma once #include "system.hpp" #include "Collision/collisionbody.h" #include "Collision/collisionentity.h" #include "Collision/sat_able.h" #include "Collision/point_able.h" #include "Collision/aabb_able.h" #include "Collision/aabbbox.h" #include "Collision/line.h" #include "Collision/circle.h" #include "Collision/point.h" #include "Collision/polygon.h" #include "Collision/quadtree.h" #include "Collision/compoundcollision.h" #include "Collision/CollisionHandlers/collisionhandler.h" #include "Collision/CollisionTester/collisiontester.h" #include "Collision/CollisionTester/sattester.h" #include "Collision/CollisionTester/quadtreetester.h" #include "Collision/CollisionTester/compoundtester.h" #include "Collision/CollisionResults/collisionresult.h" #include "Collision/CollisionResults/resultdata.h" #include "Collision/CollisionResults/satresult.h" #include "Collision/satresultaccumulator.h" #include "Collision/Engines/test.h" #include "Collision/Engines/group.h" #include "Collision/Engines/groupcontainer.h" #include "Collision/Engines/collisionengine.h"
#include "grid.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "define.h" enum direction { FRONT = 1, RIGHT, BACK, LEFT}; //コンストラクタ Grid::Grid() { } //デストラクタ Grid::~Grid() { } //乱数により壁か道かを決定する char choiceWallOrPath() { int choice = (rand() % 2) + 1; switch (choice) { case 1: return '#'; case 2: return ' '; default: break; } return '#'; } //乱数により使用するテンプレートの番号を選ぶ int choiceTemplateNum() { return rand() % NUMBER_OF_GRID_TEMPLATE; } //設置するグリッドを回転させる方向を選ぶ int choiceDirection() { switch (rand() % 4 + 1) { case FRONT: return FRONT; case BACK: return BACK; case RIGHT: return RIGHT; case LEFT: return LEFT; default: break; } return FRONT; } //設置するグリッドを反転させるか決定する int choiceFlip() { switch (rand() % 2) { case VERTICAL: return VERTICAL; case HORIZONTAL: return HORIZONTAL; default: return 0; } return 0; } //グリッドを回転させる void Grid::rotateGrid() { int direction = choiceDirection(); char rotated_grid[GRID_SIZE][GRID_SIZE] = {}; while (direction != FRONT) { for (int y = 0; y < GRID_SIZE; y++) { for (int x = 0; x < GRID_SIZE; x++) { if (y == 0) { if (x == 0) { rotated_grid[y][2] = grid[y][x]; } else if (x == 1) { rotated_grid[1][2] = grid[y][x]; } else if (x == 2) { rotated_grid[2][x] = grid[y][x]; } } else if (y == 1) { if (x == 0) { rotated_grid[0][1] = grid[y][x]; } else if (x == 1) { rotated_grid[y][x] = grid[y][x]; } else if (x == 2) { rotated_grid[2][1] = grid[y][x]; } } else if (y == 2) { if (x == 0) { rotated_grid[0][x] = grid[y][x]; } else if (x == 1) { rotated_grid[1][0] = grid[y][x]; } else if (x == 2) { rotated_grid[y][0] = grid[y][x]; } } } } for (int y = 0; y < GRID_SIZE; y++) { for (int x = 0; x < GRID_SIZE; x++) { grid[y][x] = rotated_grid[y][x]; } } direction--; } } //グリッドを反転させる void Grid::flipGrid() { int flip = choiceFlip(); char flipped_grid[GRID_SIZE][GRID_SIZE] = {}; switch (flip) { case VERTICAL: { for (int y = 0; y < GRID_SIZE; y++) { for (int x = 0; x < GRID_SIZE; x++) { if (y == 0) { flipped_grid[GRID_SIZE - 1][x] = grid[y][x]; } else if (y == GRID_SIZE - 1) { flipped_grid[0][x] = grid[y][x]; } else flipped_grid[y][x] = grid[y][x]; } } break; } case HORIZONTAL: { for (int y = 0; y < GRID_SIZE; y++) { for (int x = 0; x < GRID_SIZE; x++) { if (x == 0) { flipped_grid[y][GRID_SIZE - 1] = grid[y][x]; } else if (x == GRID_SIZE - 1) { flipped_grid[y][0] = grid[y][x]; } else flipped_grid[y][x] = grid[y][x]; } } break; } default: break; } if (flip != 0) { for (int y = 0; y < GRID_SIZE; y++) { for (int x = 0; x < GRID_SIZE; x++) { grid[y][x] = flipped_grid[y][x]; } } } } //乱数でグリッド内の配置を決定する void Grid::setGrid() { for (int y = 0; y < GRID_SIZE; y++) { for (int x = 0; x < GRID_SIZE; x++) { grid[y][x] = choiceWallOrPath(); } } rotateGrid(); flipGrid(); } //テンプレートの配置を利用しグリッドを作成する void Grid::setGridTemplate() { FILE *fp; int grid_num = choiceTemplateNum(); char filename[100]; char str[16]; sprintf_s(filename, 100, "GridTemplate/grid%d.txt", grid_num); if (fopen_s(&fp, filename, "r") != 0) { printf("ファイルを開けませんでした。\n"); return; } for (int y = 0; y < GRID_SIZE; y++) { fgets(str, 16, fp); for (int i = 0, x = 0; i < (GRID_SIZE * 3) - 1; i++) { switch (str[i]) { case ',': { break; } case '-': { grid[y][x] = '#'; x++; i++; break; } case '0': { grid[y][x] = ' '; x++; break; } default: break; } } } fclose(fp); rotateGrid(); flipGrid(); } //グリッドを表示する void Grid::printGrid() { for (int y = 0; y < GRID_SIZE; y++) { for (int x = 0; x < GRID_SIZE; x++) { if (grid[y][x] == '#') printf("##"); else if (grid[y][x] == '@') printf("P "); else if (grid[y][x] == '$') printf("■"); else if (grid[y][x] == '.') printf("○"); else if (grid[y][x] == ' ') printf("・"); } printf("\n"); } printf("\n"); }
// Example 7.1 Functors. Lambda expressions. // Created by Oleksiy Grechnyev 2017 #include <iostream> #include <functional> #include <memory> using namespace std; //============================== /// PrintOp that uses std::function static void printOp(function<int(int, int)> op) { cout << "printOp: op(7, 3) = " << op(7, 3) << endl; } //============================== /// PrintOp version that uses function pointer (C syntax, not good idea in C++ !) static void printOp2(int (*op)(int, int)) { cout << "printOp2: op(7, 3) = " << op(7, 3) << endl; } //============================== /// PrintOp version that uses templates template <typename T> void printOp3(T op) { cout << "printOp3: op(7, 3) = " << op(7, 3) << endl; } //============================== // various operations we can try static int add(int x, int y) { return x + y; } // Different signature ! static int addRef(const int &x, const int &y) { return x + y; } static int mul(int x, int y) { return x * y; } /// Add 3 numbers, not a binary OP ! p is in the middle for fun ! static int add3(int x, int p, int y) { return x + p + y; } //============================== int main() { { cout << "\nFunction pointers, functors: binary operation :\n\n"; // Pass a function to printOp() cout << "add:\n"; // Pointer to add and add is basically the same thing // Just like for arrays // Both printOp and printOp2 work in this case printOp(add); printOp(&add); printOp2(add); printOp2(&add); // printOp3 is fine too printOp3(add); printOp3(&add); // Now let's try variables cout << "mul (variables):\n"; int (*mulPtr)(int, int) = mul; // Function pointer var function<int(int, int)> mulFun = mul; // std::function var printOp(mulFun); // printOp works with both pointer and std::function printOp(mulPtr); printOp2(mulPtr); // printOp2 only works with the pointer // Now we use addRef with a different signature cout << "adddRef:\n"; printOp(addRef); // std::function does implicit conversions ... // printOp2(addRef); // ... while function pointers don't // No let's try a functor to add x+y+p (p = parameter) // Remember, struct is same as class but with default public struct FunctorAdd { int p = 0; // Parameter int operator()(int x, int y) { return x + y + p; } }; FunctorAdd fa{17}; // Sets p cout << "FunctorAdd fa{17};\n"; printOp(fa); // std::function works fine with functors ... // printOp2(fa); // while function pointers don't !!! // What about operators ? cout << "plus<int>()\n"; // printOp(operator+); // Does not work printOp(plus<int>()); // plus is a functor template which wraps operator+ printOp(plus<>()); // or even like this (C++ 14) } { cout << "\nLambdas: binary operation :\n\n"; // Lambdas are anonymous functors, sort of // Captured variables are class fields cout << "Lambda add : \n"; // No capture, return type is optional, but better to specify it printOp([](int x, int y)->int{ return x + y; }); cout << "Lambda auto add (C++ 14) : \n"; printOp([](auto x, auto y){ return x + y; }); cout << "Capture by value: add + 17 :\n"; // Lambdas are stored in auto, since capture class has no name int p = 17; // Capture by value : auto lamAdd = [p](int x, int y)->int{ return x + y + p; }; function<int(int, int)> lamAdd2 = lamAdd; // Lambdas can be also kept in std::function // Now we change p, the value captured by the lambda does not change ! p = 0; printOp(lamAdd); printOp(lamAdd2); // Now let's capture by ref: cout << "Capture by ref: mul* 3 :\n"; // At present, p = 0 auto lamMul = [&p] (int x, int y)->int{ return x * y * p; }; // Now we change p ! p = 3; printOp(lamMul); // Value p=3 is used because of the ref capture ! cout << "Emulate lambda with a functor (add + 3) :\n"; struct { int pCap; // Parameter int operator()(int x, int y) { return x + y + pCap; } } functor{p}; // pCap captures p by value printOp(functor); // Now the init capture ! // I wanted to show unique_ptr, but it doesn't work with std::function !!! // std::function needs lambda to be copyable, and unique_ptr is not ! cout << "Init capture mul* 2 :\n"; printOp([z = p - 1](int x, int y)->int{ return x * y * z; }); // By ref also work ! printOp([&z = p](int x, int y)->int{ return x * y * z; }); // Let's try unique_ptr anyway, works only with printOp3 (template version) auto uI = make_unique<int>(3); printOp3([u = move(uI)](int x, int y)->int{ return x * y * *u; }); } { cout << "\nstd::bind, lambdas, class members :\n\n"; // std::bind example cout << "add3() with std::bind : p = 10 :\n"; // Make a binary op out of add3 with bind printOp(bind(add3, placeholders::_1, 10, placeholders::_2)); // Most programmers prefer lambdas to bind, same effect with a lambda cout << "add3() with lambdas : p = 10 :\n"; printOp([](int x, int y)->int{ return add3(x, 10, y); }); // How to pass a non-static class member as a function ? cout << "Non-static class member : p = 20 :\n"; struct Z{ int p = 0; int op(int x, int y) { return x + y + p; } }; Z z{20}; // Create an object with p = 20 // printOp(z.op); // This does not work ! // Class methods have invisible first argument this : function<int(Z*, int, int)> funny = &Z::op; // This works ! // You have to use bind or lambda wrapper (preferred !) // Note the hidden 1st argument, which is this (&z) ! printOp(bind(&Z::op, &z, placeholders::_1, placeholders::_2)); printOp([&z](int x, int y)->int{ return z.op(x,y); }); cout << "Fun with mutable lambda : \n"; int n = 10; auto lam = [n]() mutable -> void{ n += 10; cout << "n = " << n << endl; }; lam(); } return 0; }
#include <iostream> #include <iomanip> #include <cmath> #include <ctime> #include "diceroller.h" void DiceRoller::diceroll(){ std::cout << "This function prints out six rolled die." << std::endl; std::srand(std::time(NULL)); //seed = # of seconds since Jan 1 1970 double face; for(int i = 0; i <= 20; ++i){ face = (1 + std::rand() % 6); std::cout << std::left; std::cout << face << std::setw(5); if (i%5==0){ std::cout << std::endl; //starts a new line once the output reaches 5 on one line }//if }//for }//diceroll void DiceRoller::dicefreq(){ std::cout << "This function prints out six rolled die." << std::endl; int freq1 = 0; int freq2 = 0; int freq3 = 0; int freq4 = 0; int freq5 = 0; int freq6 = 0; int face = 1; //declares face and stores the most recent face value std::srand(std::time(NULL)); for(int i = 0; i <= 6000000; ++i){ face = (1 + rand() % 6); switch(face){ case 1: ++freq1; break; case 2: ++freq2; break; case 3: ++freq3; break; case 4: ++freq4; break; case 5: ++freq5; break; case 6: ++freq6; break; default: std::cout << "There has been a critical error." << std::endl; break; }//switch }//face std::cout << "Frequency of rolling a 1: " << freq1 << std::endl; std::cout << "Frequency of rolling a 2: " << freq2 << std::endl; std::cout << "Frequency of rolling a 3: " << freq3 << std::endl; std::cout << "Frequency of rolling a 4: " << freq4 << std::endl; std::cout << "Frequency of rolling a 5: " << freq5 << std::endl; std::cout << "Frequency of rolling a 6: " << freq6 << std::endl; }//dicefreq
#pragma once #include "reg.h" #include <iostream> // 本类不属于硬件操作的一部分 // 模拟硬件的数据输入和输出功能 class CData_io { public: CData_io(char fileIn[], char fileOut[]); // 初始化 int getData_1Frame(CReg RAx, int frameLen); // 取一帧数据 void outData_1Frame(CReg RAx, int frameLen); // 输出一帧数据 void outData_Data32(CReg RAx, int bLen); // 输出调试信息(标量) void CData_io::outData_Steam(CReg RAx, int bLen); // 输出调试信息(标量) int loop = 0; // 统计大循环轮数 private: int* inBuf; // 输入数据缓存 char fileInPath[256]; // 输入文件路径 char fileOutPath[256]; // 输出文件路径 int inBufNum; // 输入数据个数 int inBufIndex; // 输入数据缓存当前位置 FILE* fp_out; int readFile(char file[]); int readFileBin(char file[]); int readFileBin2(char file[]); int writeFile(char file[], int* buf, int len); int writeFileBin(char file[], int* buf, int len); int writeFileBin2(char file[], int* buf, int len); int writeFileBin_data32(int* buf, int len); short limit(int data); void createFile(char file[]); };
/* * Copyright (c) 2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_EMPTY_SORTER_H_ #define CPPSORT_DETAIL_EMPTY_SORTER_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <array> #include <cstddef> #include <functional> #include <type_traits> #include <cpp-sort/sorter_traits.h> #include <cpp-sort/utility/functional.h> #include <cpp-sort/utility/sorting_networks.h> #include "attributes.h" namespace cppsort { namespace detail { //////////////////////////////////////////////////////////// // Basic empty fixed-size "sorter", generally the one used // by fixed-size sorters of size 0 or 1, which don't need // to reorder anything struct empty_sorter_impl { template< typename ForwardIterator, typename Compare = std::less<>, typename Projection = utility::identity, typename = std::enable_if_t<is_projection_iterator_v< Projection, ForwardIterator, Compare >> > constexpr auto operator()(ForwardIterator, ForwardIterator, Compare={}, Projection={}) const noexcept -> void {} }; //////////////////////////////////////////////////////////// // Dedicated empty sorter for sorting networks, providing // additional sorting network-specific functions struct empty_network_sorter_impl: empty_sorter_impl { template<typename DifferenceType=std::ptrdiff_t> CPPSORT_ATTRIBUTE_NODISCARD static constexpr auto index_pairs() -> std::array<utility::index_pair<DifferenceType>, 0> { return {}; } }; }} #endif // CPPSORT_DETAIL_EMPTY_SORTER_H_
#include "include/Render/bioluminescentfluidrenderer.h" #include <QOpenGLContext> #include <QOpenGLFunctions> BioluminescentFluidRenderer::BioluminescentFluidRenderer(int _w, int _h) : FluidRenderer(_w, _h) { m_colour = glm::vec3(0.2f, 0.9f, 0.4f); } BioluminescentFluidRenderer::~BioluminescentFluidRenderer() { CleanUpGL(); } void BioluminescentFluidRenderer::SetSphParticles(std::shared_ptr<BaseSphParticle> _sphParticles, std::shared_ptr<Algae> _algaeParticles) { m_sphParticles = _sphParticles; m_posBO = std::make_shared<QOpenGLBuffer>(m_sphParticles->GetPosBO()); m_velBO = std::make_shared<QOpenGLBuffer>(m_sphParticles->GetVelBO()); m_denBO = std::make_shared<QOpenGLBuffer>(m_sphParticles->GetDenBO()); m_pressBO = std::make_shared<QOpenGLBuffer>(m_sphParticles->GetPressBO()); m_algaeParticles = _algaeParticles; m_algaePosBO = std::make_shared<QOpenGLBuffer>(m_algaeParticles->GetPosBO()); m_algaeIllumBO = std::make_shared<QOpenGLBuffer>(m_algaeParticles->GetIllumBO()); Init(); } void BioluminescentFluidRenderer::Draw() { QOpenGLFunctions *glFuncs = QOpenGLContext::currentContext()->functions(); //--------------------------------------------------------------------------- // Fluid stuff // Render Depth m_depthShader.bind(); m_depthFBO->bind(); glFuncs->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFuncs->glEnable(GL_DEPTH_TEST); glFuncs->glDisable(GL_BLEND); m_vao.bind(); glFuncs->glDrawArrays(GL_POINTS, 0, m_sphParticles->GetProperty()->numParticles); m_vao.release(); m_depthFBO->release(); m_depthShader.release(); // Smooth depth m_smoothDepthShader.bind(); m_smoothDepthFBO->bind(); glFuncs->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_smoothDepthShader.setUniformValue("uDepthTex", 0); glFuncs->glActiveTexture(GL_TEXTURE0); glFuncs->glBindTexture(GL_TEXTURE_2D, m_depthFBO->texture()); m_quadVAO.bind(); glFuncs->glDrawArrays(GL_TRIANGLES, 0, 6); m_quadVAO.release(); m_smoothDepthFBO->release(); m_smoothDepthShader.release(); // Render thickness m_thicknessShader.bind(); m_thicknessFBO->bind(); glFuncs->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFuncs->glDisable(GL_DEPTH_TEST); glFuncs->glEnable(GL_BLEND); glFuncs->glBlendFunc(GL_ONE, GL_ONE); glFuncs->glBlendEquation(GL_FUNC_ADD); m_vao.bind(); glFuncs->glDrawArrays(GL_POINTS, 0, m_sphParticles->GetProperty()->numParticles); m_vao.release(); glFuncs->glDisable(GL_BLEND); glFuncs->glEnable(GL_DEPTH_TEST); m_thicknessFBO->release(); m_thicknessShader.release(); //--------------------------------------------------------------------------- // Algae stuff // Render Depth m_depthShader.bind(); glFuncs->glUniform1f(m_depthShader.uniformLocation("uRad"), m_algaeParticles->GetProperty()->particleRadius); glFuncs->glUniform1f(m_depthShader.uniformLocation("uRestDen"), m_algaeParticles->GetProperty()->restDensity); m_algaeDepthFBO->bind(); glFuncs->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFuncs->glEnable(GL_DEPTH_TEST); glFuncs->glDisable(GL_BLEND); m_algaeVao.bind(); glFuncs->glDrawArrays(GL_POINTS, 0, m_algaeParticles->GetProperty()->numParticles); m_algaeVao.release(); m_algaeDepthFBO->release(); m_depthShader.release(); // Smooth depth m_smoothDepthShader.bind(); m_algaeSmoothDepthFBO->bind(); glFuncs->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_smoothDepthShader.setUniformValue("uDepthTex", 0); glFuncs->glActiveTexture(GL_TEXTURE0); glFuncs->glBindTexture(GL_TEXTURE_2D, m_algaeDepthFBO->texture()); m_quadVAO.bind(); glFuncs->glDrawArrays(GL_TRIANGLES, 0, 6); m_quadVAO.release(); m_algaeSmoothDepthFBO->release(); m_smoothDepthShader.release(); // Render thickness m_biolumIntensityShader.bind(); m_algaeThicknessFBO->bind(); glFuncs->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFuncs->glDisable(GL_DEPTH_TEST); // glFuncs->glEnable(GL_FRONT_AND_BACK); glFuncs->glEnable(GL_BLEND); // glFuncs->glBlendFunc(GL_ONE, GL_DST_ALPHA); glFuncs->glBlendFunc(GL_SRC_ALPHA, GL_ONE); // glFuncs->glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); // glFuncs->glBlendFunc(GL_ONE, GL_ONE); glFuncs->glBlendEquation(GL_FUNC_ADD); m_algaeVao.bind(); glFuncs->glDrawArrays(GL_POINTS, 0, m_algaeParticles->GetProperty()->numParticles); m_algaeVao.release(); glFuncs->glDisable(GL_BLEND); glFuncs->glEnable(GL_DEPTH_TEST); m_algaeThicknessFBO->release(); m_biolumIntensityShader.release(); //--------------------------------------------------------------------------- // Final render // Render Bioluminescent Fluid int texId = 0; m_bioluminescentShader.bind(); // glFuncs->glEnable(GL_DEPTH_TEST); glFuncs->glEnable(GL_BLEND); glFuncs->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glFuncs->glBlendEquation(GL_FUNC_ADD); m_bioluminescentShader.setUniformValue("uDepthTex", texId); glFuncs->glActiveTexture(GL_TEXTURE0 + texId++); glFuncs->glBindTexture(GL_TEXTURE_2D, m_smoothDepthFBO->texture()); m_bioluminescentShader.setUniformValue("uThicknessTex", texId); glFuncs->glActiveTexture(GL_TEXTURE0+ texId++); glFuncs->glBindTexture(GL_TEXTURE_2D, m_thicknessFBO->texture()); m_bioluminescentShader.setUniformValue("uAlgaeDepthTex", texId); glFuncs->glActiveTexture(GL_TEXTURE0 + texId++); glFuncs->glBindTexture(GL_TEXTURE_2D, m_algaeSmoothDepthFBO->texture()); m_bioluminescentShader.setUniformValue("uAlgaeThicknessTex", texId); glFuncs->glActiveTexture(GL_TEXTURE0+ texId++); glFuncs->glBindTexture(GL_TEXTURE_2D, m_algaeThicknessFBO->texture()); m_bioluminescentShader.setUniformValue("uCubeMapTex", texId); glFuncs->glActiveTexture(GL_TEXTURE0+ texId++); glFuncs->glBindTexture(GL_TEXTURE_CUBE_MAP, m_cubeMapTex->textureId()); m_quadVAO.bind(); glFuncs->glDrawArrays(GL_TRIANGLES, 0, 6); m_quadVAO.release(); glFuncs->glDisable(GL_BLEND); m_bioluminescentShader.release(); } void BioluminescentFluidRenderer::SetShaderUniforms(const glm::mat4 &_projMat, const glm::mat4 &_viewMat, const glm::mat4 &_modelMat, const glm::mat3 &_normalMat, const glm::vec3 &_lightPos, const glm::vec3 &_camPos) { if(m_sphParticles == nullptr) { return; } QOpenGLFunctions *glFuncs = QOpenGLContext::currentContext()->functions(); m_depthShader.bind(); glFuncs->glUniformMatrix4fv(m_depthShader.uniformLocation("uProjMatrix"), 1, false, &_projMat[0][0]); glFuncs->glUniformMatrix4fv(m_depthShader.uniformLocation("uMVMatrix"), 1, false, &(_viewMat*_modelMat)[0][0]); glFuncs->glUniform3fv(m_depthShader.uniformLocation("uCameraPos"), 1, &_camPos[0]); glFuncs->glUniform1f(m_depthShader.uniformLocation("uRad"), 1.5f*m_sphParticles->GetProperty()->particleRadius); glFuncs->glUniform1f(m_depthShader.uniformLocation("uRestDen"), m_sphParticles->GetProperty()->restDensity); m_depthShader.release(); m_smoothDepthShader.bind(); m_smoothDepthShader.release(); m_thicknessShader.bind(); glFuncs->glUniformMatrix4fv(m_thicknessShader.uniformLocation("uProjMatrix"), 1, false, &_projMat[0][0]); glFuncs->glUniformMatrix4fv(m_thicknessShader.uniformLocation("uMVMatrix"), 1, false, &(_viewMat*_modelMat)[0][0]); glFuncs->glUniform3fv(m_thicknessShader.uniformLocation("uCameraPos"), 1, &_camPos[0]); glFuncs->glUniform1f(m_thicknessShader.uniformLocation("uRad"), 1.5f*m_sphParticles->GetProperty()->particleRadius); glFuncs->glUniform1f(m_thicknessShader.uniformLocation("uRestDen"), m_sphParticles->GetProperty()->restDensity); m_thicknessShader.release(); m_biolumIntensityShader.bind(); glFuncs->glUniformMatrix4fv(m_biolumIntensityShader.uniformLocation("uProjMatrix"), 1, false, &_projMat[0][0]); glFuncs->glUniformMatrix4fv(m_biolumIntensityShader.uniformLocation("uMVMatrix"), 1, false, &(_viewMat*_modelMat)[0][0]); glFuncs->glUniform3fv(m_biolumIntensityShader.uniformLocation("uCameraPos"), 1, &_camPos[0]); glFuncs->glUniform1f(m_biolumIntensityShader.uniformLocation("uRad"), m_algaeParticles->GetProperty()->particleRadius); glFuncs->glUniform1f(m_biolumIntensityShader.uniformLocation("uRestDen"), m_algaeParticles->GetProperty()->restDensity); m_biolumIntensityShader.release(); m_bioluminescentShader.bind(); glFuncs->glUniform3f(m_bioluminescentShader.uniformLocation("uCameraPos"), _camPos.x, _camPos.y, _camPos.z); glFuncs->glUniform3fv(m_bioluminescentShader.uniformLocation("uLightPos"), 1, &_lightPos[0]); glFuncs->glUniformMatrix4fv(m_bioluminescentShader.uniformLocation("uInvPVMatrix"), 1, false, &(glm::inverse(_projMat*_viewMat))[0][0]); glFuncs->glUniformMatrix3fv(m_bioluminescentShader.uniformLocation("uNormalMatrix"), 1, true, &(_normalMat)[0][0]); m_bioluminescentShader.release(); m_shaderProg.bind(); glFuncs->glUniformMatrix4fv(m_shaderProg.uniformLocation("uProjMatrix"), 1, false, &_projMat[0][0]); glFuncs->glUniformMatrix4fv(m_shaderProg.uniformLocation("uMVMatrix"), 1, false, &(_viewMat*_modelMat)[0][0]); glFuncs->glUniform3fv(m_shaderProg.uniformLocation("uCameraPos"), 1, &_camPos[0]); glFuncs->glUniform1f(m_shaderProg.uniformLocation("uRad"), m_sphParticles->GetProperty()->particleRadius); glFuncs->glUniform3fv(m_shaderProg.uniformLocation("uLightPos"), 1, &_lightPos[0]); glFuncs->glUniform3fv(m_shaderProg.uniformLocation("uColour"), 1, &m_colour[0]); glFuncs->glUniform1f(m_shaderProg.uniformLocation("uRestDen"), m_sphParticles->GetProperty()->restDensity); m_shaderProg.release(); } void BioluminescentFluidRenderer::Init() { InitGL(); } void BioluminescentFluidRenderer::InitGL() { InitShader(); InitFluidVAO(); InitAlgaeVAO(); InitQuadVAO(); InitFBOs(); } void BioluminescentFluidRenderer::InitShader() { CreateDefaultParticleShader(); CreateDepthShader(); CreateSmoothDepthShader(); CreateThicknessShader(); CreateBiolumIntensityShader(); CreateBioluminescentShader(); } void BioluminescentFluidRenderer::InitQuadVAO() { QOpenGLFunctions *glFuncs = QOpenGLContext::currentContext()->functions(); m_bioluminescentShader.bind(); m_quadVAO.create(); m_quadVAO.bind(); const GLfloat quadVerts[] = { -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f }; m_quadVBO.create(); m_quadVBO.bind(); m_quadVBO.allocate(quadVerts, 6 * 3 * sizeof(float)); glFuncs->glEnableVertexAttribArray(m_bioluminescentShader.attributeLocation("vPos")); glFuncs->glVertexAttribPointer(m_bioluminescentShader.attributeLocation("vPos"), 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), 0); m_quadVBO.release(); const GLfloat quadUVs[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, }; m_quadUVBO.create(); m_quadUVBO.bind(); m_quadUVBO.allocate(quadUVs,6 * 2 * sizeof(float)); glFuncs->glEnableVertexAttribArray(m_bioluminescentShader.attributeLocation("vUV")); glFuncs->glVertexAttribPointer(m_bioluminescentShader.attributeLocation("vUV"), 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), 0); m_quadUVBO.release(); m_quadVAO.release(); m_bioluminescentShader.release(); } void BioluminescentFluidRenderer::InitAlgaeVAO() { QOpenGLFunctions *glFuncs = QOpenGLContext::currentContext()->functions(); // Set up the VAO m_algaeVao.create(); m_algaeVao.bind(); // Setup our alge pos buffer object. m_algaePosBO->bind(); glFuncs->glEnableVertexAttribArray(m_posAttrLoc); glFuncs->glVertexAttribPointer(m_posAttrLoc, 3, GL_FLOAT, GL_FALSE, 1 * sizeof(float3), 0); m_algaePosBO->release(); m_biolumIntensityShader.bind(); // Setup our algae illumination buffer object. m_algaeIllumBO->bind(); glFuncs->glEnableVertexAttribArray(m_biolumIntensityShader.attributeLocation("vBio")); glFuncs->glVertexAttribPointer(m_biolumIntensityShader.attributeLocation("vBio"), 1, GL_FLOAT, GL_FALSE, 1 * sizeof(float), 0); m_algaeIllumBO->release(); m_biolumIntensityShader.release(); printf("%i", m_algaeIllumAttrLoc); m_algaeVao.release(); } void BioluminescentFluidRenderer::CleanUpGL() { m_posBO = nullptr; m_velBO = nullptr; m_denBO = nullptr; m_pressBO = nullptr; m_algaePosBO = nullptr; m_algaeIllumBO = nullptr; m_vao.destroy(); m_algaeVao.destroy(); m_quadVBO.destroy(); m_quadUVBO.destroy(); m_quadVAO.destroy(); m_depthFBO = nullptr; m_smoothDepthFBO = nullptr; m_thicknessFBO = nullptr; m_smoothThicknessFBO = nullptr; m_algaeDepthFBO = nullptr; m_algaeSmoothDepthFBO = nullptr; m_algaeThicknessFBO = nullptr; m_shaderProg.destroyed(); m_depthShader.destroyed(); m_smoothDepthShader.destroyed(); m_thicknessShader.destroyed(); m_fluidShader.destroyed(); m_biolumIntensityShader.destroyed(); m_bioluminescentShader.destroyed(); } void BioluminescentFluidRenderer::InitFBOs() { QOpenGLFramebufferObjectFormat fboFormat; fboFormat.setAttachment(QOpenGLFramebufferObject::Attachment::Depth); fboFormat.setInternalTextureFormat(QOpenGLTexture::RGBA32F); m_depthFBO.reset(new QOpenGLFramebufferObject(m_width, m_height, fboFormat)); m_smoothDepthFBO.reset(new QOpenGLFramebufferObject(m_width, m_height, fboFormat)); m_thicknessFBO.reset(new QOpenGLFramebufferObject(m_width, m_height, fboFormat)); m_smoothThicknessFBO.reset(new QOpenGLFramebufferObject(m_width, m_height, fboFormat)); m_algaeDepthFBO.reset(new QOpenGLFramebufferObject(m_width, m_height, fboFormat)); m_algaeSmoothDepthFBO.reset(new QOpenGLFramebufferObject(m_width, m_height, fboFormat)); m_algaeThicknessFBO.reset(new QOpenGLFramebufferObject(m_width, m_height, fboFormat)); } void BioluminescentFluidRenderer::CreateBiolumIntensityShader() { m_biolumIntensityShader.addShaderFromSourceFile(QOpenGLShader::Vertex, "../shader/Fluid/Bioluminescent/biolumIntensity.vert"); m_biolumIntensityShader.addShaderFromSourceFile(QOpenGLShader::Geometry, "../shader/Fluid/Bioluminescent/biolumIntensity.geom"); m_biolumIntensityShader.addShaderFromSourceFile(QOpenGLShader::Fragment, "../shader/Fluid/Bioluminescent/biolumIntensity.frag"); m_biolumIntensityShader.link(); m_biolumIntensityShader.bind(); m_biolumIntensityShader.release(); m_algaeIllumAttrLoc = m_biolumIntensityShader.attributeLocation("vBio"); } void BioluminescentFluidRenderer::CreateBioluminescentShader() { m_bioluminescentShader.addShaderFromSourceFile(QOpenGLShader::Vertex, "../shader/Fluid/Bioluminescent/bioluminescent.vert"); m_bioluminescentShader.addShaderFromSourceFile(QOpenGLShader::Fragment, "../shader/Fluid/Bioluminescent/bioluminescent.frag"); m_bioluminescentShader.link(); m_bioluminescentShader.bind(); m_bioluminescentShader.release(); }
#include <string> #ifndef _Client_h #define _Client_h class Client { public: Client(int id, std::string name, std::string prenom, int reservenumbers); int getId(); std::string getName(); std::string getPrenom(); int getReservenumbers(); void set_Client(int id = 0, int reservenumbers = -1, std::string name = "Indiquer", std::string prenom = "Indiquer"); private: int m_id; std::string m_name; std::string m_prenom; int m_reservenumbers; };
#include "adapter.hpp" void client(ITarget *p) { p->Do(); } int main(int argc, char const *argv[]) { Adaptee old; Adapter adapter(&old); AnotherAdapter ano; client(&adapter); client(&ano); return 0; }
#include "ros/ros.h" #include <iostream> #include "geometry_msgs/PoseStamped.h" #include "std_msgs/Float64.h" std_msgs::Float64 vel1; std_msgs::Float64 vel2; ros::Publisher give_vel; ros::Publisher give_vel2; void msgCallback(const geometry_msgs::PoseStamped::ConstPtr& PoseStamped) { //ROS_INFO("Point x = %f", PoseStamped->pose.position.x); if(PoseStamped->pose.position.z > 0.5) { vel1.data = 3.0; vel2.data = -3.0; } else if(PoseStamped->pose.position.z <= 0.5 && PoseStamped->pose.position.z >= 0.3) { vel1.data = 0.0; vel2.data = 0.0; } else if(PoseStamped->pose.position.z < 0.3) { vel1.data = -3.0; vel2.data = 3.0; } give_vel.publish(vel1); give_vel2.publish(vel2); } int main(int argc, char **argv) { ros::init(argc, argv, "pose2command"); ros::NodeHandle nh; ros::Subscriber get_pose = nh.subscribe("/aruco_single/pose", 100, msgCallback); give_vel = nh.advertise<std_msgs::Float64>("/pan_controller/command", 50); give_vel2 = nh.advertise<std_msgs::Float64>("/pan_controller2/command", 50); ros::spin(); return 0; }
// Created on: 1993-09-07 // Created by: Christian CAILLET // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESData_SpecificModule_HeaderFile #define _IGESData_SpecificModule_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Transient.hxx> #include <Standard_Integer.hxx> class IGESData_IGESEntity; class IGESData_IGESDumper; class IGESData_SpecificModule; DEFINE_STANDARD_HANDLE(IGESData_SpecificModule, Standard_Transient) //! This class defines some Services which are specifically //! attached to IGES Entities : Dump class IGESData_SpecificModule : public Standard_Transient { public: //! Specific Dump for each type of IGES Entity : it concerns only //! own parameters, the general data (Directory Part, Lists) are //! taken into account by the IGESDumper //! See class IGESDumper for the rules to follow for <own> and //! <attached> level Standard_EXPORT virtual void OwnDump (const Standard_Integer CN, const Handle(IGESData_IGESEntity)& ent, const IGESData_IGESDumper& dumper, Standard_OStream& S, const Standard_Integer own) const = 0; //! Specific Automatic Correction on own Parameters of an Entity. //! It works by setting in accordance redundant data, if there are //! when there is no ambiguity (else, it does nothing). //! Remark that classic Corrections on Directory Entry (to set //! void data) are taken into account alsewhere. //! //! For instance, many "Associativity Entities" have a Number of //! Properties which must have a fixed value. //! Or, a ConicalArc has its Form Number which records the kind of //! Conic, also determined from its coefficients //! But, a CircularArc of which Distances (Center-Start) and //! (Center-End) are not equal cannot be corrected ... //! //! Returns True if something has been corrected in <ent> //! By default, does nothing. If at least one of the Types //! processed by a sub-class of SpecificModule has a Correct //! procedure attached, this method can be redefined Standard_EXPORT virtual Standard_Boolean OwnCorrect (const Standard_Integer CN, const Handle(IGESData_IGESEntity)& ent) const; DEFINE_STANDARD_RTTIEXT(IGESData_SpecificModule,Standard_Transient) protected: private: }; #endif // _IGESData_SpecificModule_HeaderFile
#include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define sful(a) scanf("%llu",&a); #define sfulul(a,b) scanf("%llu %llu",&a,&b); #define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different #define sfc(a) scanf("%c",&a); #define sfs(a) scanf("%s",a); #define getl(s) getline(cin,s); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define vi vector<int> #define vll vector<ll> #define mii map<int,int> #define mlli map<ll,int> #define mib map<int,bool> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define cCASE(t) cout<<"Case "<<++t<<": "; #define D(v,status) cout<<status<<" "<<v<<endl; #define INF 1000000000 //10e9 #define EPS 1e-9 #define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c ) #define CONTEST 1 using namespace std; char grid[55][55]; bool vis[55][55]; int dx[]= {0,0,1,-1,1,-1,1,-1}; int dy[]= {1,-1,0,0,1,1,-1,-1}; int dis[55][55]; int h,w; int valid(int x,int y) { if(x<1 || x>h || y<1 || y>w) return 0; return 1; } int bfs(int sr,int sc) { int mx = 0; ms(vis,false); paii s = mp(sr,sc); queue< paii >q; q.push(s); vis[s.fs][s.sc]=1; dis[s.fs][s.sc]=0; while(!q.empty()) { paii u = q.front(); q.pop(); for(int i=0; i<8; i++) { if(valid(u.fs+dx[i],u.sc+dy[i])) { if(grid[u.fs+dx[i]][u.sc+dy[i]] - grid[u.fs][u.sc]==1) { paii v = mp(u.fs+dx[i], u.sc+dy[i]); if(vis[v.fs][v.sc]==0) { vis[v.fs][v.sc]=1; dis[v.fs][v.sc]= dis[u.fs][u.sc]+1; q.push(v); mx = max(mx,dis[v.fs][v.sc]); } } } } } return mx; } int main() { int cas = 0; while(scanf("%d %d",&h,&w)==2) { if(h==0 && w==0) break; ms(dis,0); loop(i,1,h) { loop(j,1,w) { cin>>grid[i][j]; } } int ans = 0; int cnt = 0; loop(i,1,h) { loop(j,1,w) { if(grid[i][j]=='A') { cnt++; int bal = bfs(i,j); ans=max(ans, bal); } } } if(cnt!=0) { ans++; } CASE(cas); pf("%d\n",ans); } return 0; }
#include "H/KBscancodes.h" #include "H/printf.h" #include "H/IDT.h" #include "H/sound.h" #include "H/Memory.h" #include "H/Heap.h" #include "H/Colors.h" #include "H/typedefs.h" #include "H/vga.h" #include "H/Font.h" #include "H/serial.h" #include "H/3D.h" //#include "H/2D.h" #include "H/mouse.h" //#include "H/Time.h" #include "H/stddef.h" #include "H/ramdisk.h" #include "H/cstring.h" extern "C" uint16_t Total_paged; void delay(int clocks) { asm("push %rax"); for(uint64 i = 0; i < clocks; i+=8){ asm("xor %rax, %rax"); } asm("pop %rax"); return; } extern "C" void _start(){ //__BOOTSCREEN__(); MasterVolume = 100; //PlaySound(469,MasterVolume); MemoryMapEntry** usableMemoryMaps = GetUsableMemoryRegions(); InitHeap(0x100000, 0x100000); write_serial('a'); //IDT MainInterrupt; //MainInterrupt.InitIDT(); MainKeyboardHandler = Keyboardhandler; write_serial('b'); init_serial(); write_serial('c'); //mouseinit(); write_serial('d'); // TODO: font, mouse ,buttons and others //taskbar WindowMananger.NewWindow(0, 190, 320, 10, (char*)"", 0); //double windowing test write_serial('e'); WindowProperty* Win1 = WindowMananger.NewWindow(10, 25, 50, 100, (char*)"\n\r"); KBmouse.x = 160; KBmouse.y = 100; ctmouse(160, 100); write_serial('f'); //initRAMDISK(); //restart(); while(1) { //mainloop Win1->left= Win1->left + 10; ctmouse(160, 100); /*mouse_updater(inb(0x60)); MousePacket(); PlaySound(1043,MasterVolume);for (int i = 0; i<200000;i++);{} PlaySound(1570,MasterVolume);for (int ii = 0; ii<200000;ii++);{} PlaySound(1969,MasterVolume);for (int iii = 0; iii<200000;iii++);{} PlaySound(1477,MasterVolume);for (int iiii = 0; iiii<200000;iiii++);{}*/ } return; }
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010-2012 Alessandro Tasora // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // ChLcpInteriorPoint.cpp // // // file for CHRONO HYPEROCTANT LCP solver // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "ChLcpInteriorPoint.h" #include "ChLcpConstraintTwoFrictionT.h" #include "pdip_solve.h" namespace chrono { double ChLcpInteriorPoint::Solve( ChLcpSystemDescriptor& sysd ///< system description with constraints and variables ) { std::cout << "-------time for lulu's solver!!------" << std::endl; std::vector<ChLcpConstraint*>& mconstraints = sysd.GetConstraintsList(); std::vector<ChLcpVariables*>& mvariables = sysd.GetVariablesList(); ChMatrixDynamic <double> mv0; ChSparseMatrix mM; ChSparseMatrix mCq; ChSparseMatrix mE; ChMatrixDynamic <double> mf; ChMatrixDynamic <double> mb; ChMatrixDynamic <double> mfric; sysd.ConvertToMatrixForm(&mCq, &mM, &mE, &mf, &mb, &mfric); sysd.FromVariablesToVector(mv0); ChStreamOutAsciiFile file_V0( "dump_V_old.dat" ) ; mv0.StreamOUTdenseMatlabFormat(file_V0) ; ChStreamOutAsciiFile file_M ( "dump_M.dat" ) ; mM.StreamOUTsparseMatlabFormat ( file_M ) ; ChStreamOutAsciiFile file_Cq ( "dump_Cq.dat" ) ; mCq.StreamOUTsparseMatlabFormat ( file_Cq ) ; ChStreamOutAsciiFile file_E ( "dump_E.dat" ) ; mE.StreamOUTsparseMatlabFormat ( file_E ) ; ChStreamOutAsciiFile file_fric ( "dump_fric.dat" ) ; mfric.StreamOUTdenseMatlabFormat ( file_fric ) ; ChStreamOutAsciiFile file_f ( "dump_f.dat" ) ; mf.StreamOUTdenseMatlabFormat ( file_f ) ; ChStreamOutAsciiFile file_b ( "dump_b.dat" ) ; mb.StreamOUTdenseMatlabFormat ( file_b ) ; printf("Successfully writing files!\n"); /* file_f.GetFstream().close(); file_fric.GetFstream().close(); file_V0.GetFstream().close(); file_M.GetFstream().close(); file_Cq.GetFstream().close(); file_b.GetFstream().close(); */ int nBodies = mM.GetColumns()/6; size_t nVariables = mvariables.size(); size_t nConstraints = sysd.CountActiveConstraints(); int numContacts = nConstraints/3; int nc_original = numContacts; /* ALWYAS DO THIS IN THE LCP SOLVER!!!*/ for (unsigned int ic = 0; ic < nConstraints; ic++) mconstraints[ic]->Update_auxiliary(); //Get sparse info of contact Jacobian Cq std::vector<int> index_i_Cq; std::vector<int> index_j_Cq; std::vector<double> val_Cq; double val; for (int ii = 0; ii < mCq.GetRows(); ii++){ for (int jj = 0; jj < mCq.GetColumns(); jj++){ val = mCq.GetElement(ii,jj); if (val){ index_i_Cq.push_back(jj); index_j_Cq.push_back(ii); val_Cq.push_back(val); } } } /////////////////////////////// //Parameters for reduced PDIP// /////////////////////////////// bool modified = false; double res = 1e-6; std::vector<int> throwaway; // Minv matrix std::vector<int> index_i_Minv; std::vector<int> index_j_Minv; std::vector<double> val_Minv; for (int i = 0; i < nBodies*6; i++){ index_i_Minv.push_back(i); index_j_Minv.push_back(i); val_Minv.push_back(1.0/mM.GetElement(i,i)); } // create reference to pass on to SPIKE int *Cq_i = &index_i_Cq[0]; int *Cq_j = &index_j_Cq[0]; int Cq_nnz = val_Cq.size(); double *Cq_val = &val_Cq[0]; int *Minv_i = &index_i_Minv[0]; int *Minv_j = &index_j_Minv[0]; double *Minv_val = &val_Minv[0]; ///////////////////////////////////////// //Formulate rhs of optimization problem// ///////////////////////////////////////// ChMatrixDynamic <double> opt_r_tmp(nConstraints,1); for (unsigned int iv = 0; iv < nVariables; iv ++) // M^[-1] * k if (mvariables[iv]->IsActive()){ mvariables[iv]->Compute_invMb_v(mvariables[iv]->Get_qb(), mvariables[iv]->Get_fb()); ChMatrix<double> k = mvariables[iv]->Get_fb(); ChMatrix<double> Mk = mvariables[iv]->Get_qb(); } int s_i = 0; // opt_r.Resize(nConstraints,1); for (unsigned int ic = 0; ic < nConstraints; ic ++) if (mconstraints[ic]->IsActive()){ opt_r(s_i,0) = mconstraints[ic]->Compute_Cq_q(); ++s_i; } sysd.BuildBiVector(opt_r_tmp); opt_r.MatrInc(opt_r_tmp); //////////// //backup q// //////////// ChMatrixDynamic<double> mq; sysd.FromVariablesToVector(mq, true); // printChMatrix(mq); //////////////////////////// //assign solver parameters// //////////////////////////// double barrier_t = 1; double eta_hat; int numStages = 725; int mu1 = 10; double b1 = 0.8; double a1 = 0.01; double res1 = 1e-10; double res2 = 1e-8; // assign vectors here ff.Resize(numContacts*2,1); lambda_k.Resize(numContacts*2,1); /*initialize lambda_k*/ xk.Resize(numContacts*3,1); r_dual.Resize(numContacts*3,1); r_cent.Resize(numContacts*2,1); d_x.Resize(numContacts*3,1); d_lambda.Resize(numContacts*2,1); Schur_rhs.Resize(3*numContacts,1); grad_f.Resize(3*numContacts,1); if (mconstraints.size() == 0){ sysd.FromVectorToConstraints(xk); sysd.FromVectorToVariables(mq); for (size_t ic = 0; ic < mconstraints.size(); ic ++){ if (mconstraints[ic]->IsActive()) mconstraints[ic]->Increment_q(mconstraints[ic]->Get_l_i()); } return 1e-8; } double *BlockDiagonal_val = new double[9*numContacts]; int *BlockDiagonal_i = new int[9*numContacts]; int *BlockDiagonal_j = new int[9*numContacts]; double *spike_rhs = new double[3*numContacts]; int tmp0, tmp1, tmp2; for (int i = 0; i < numContacts; i ++){ tmp0 = 3*i; tmp1 = 3*i+1; tmp2 = 3*i+2; *(BlockDiagonal_i + 9*i) = tmp0; *(BlockDiagonal_i + 9*i+1) = tmp0; *(BlockDiagonal_i + 9*i+2) = tmp0; *(BlockDiagonal_i + 9*i+3) = tmp1; *(BlockDiagonal_i + 9*i+4) = tmp1; *(BlockDiagonal_i + 9*i+5) = tmp1; *(BlockDiagonal_i + 9*i+6) = tmp2; *(BlockDiagonal_i + 9*i+7) = tmp2; *(BlockDiagonal_i + 9*i+8) = tmp2; *(BlockDiagonal_j + 9*i) = tmp0; *(BlockDiagonal_j + 9*i+1) = tmp1; *(BlockDiagonal_j + 9*i+2) = tmp2; *(BlockDiagonal_j + 9*i+3) = tmp0; *(BlockDiagonal_j + 9*i+4) = tmp1; *(BlockDiagonal_j + 9*i+5) = tmp2; *(BlockDiagonal_j + 9*i+6) = tmp0; *(BlockDiagonal_j + 9*i+7) = tmp1; *(BlockDiagonal_j + 9*i+8) = tmp2; } // initialize xk for (int i = 0; i < numContacts; i ++){ xk(3*i, 0) = 1; xk(3*i+1, 0) = 0; xk(3*i+2, 0) = 0; } evaluateConstraints(mfric.GetAddress(), numContacts, false); //initialize lambda for (int i = 0; i < lambda_k.GetRows(); i++) lambda_k(i,0) = -1/(barrier_t * ff(i,0)); int throwaway_size = 0; int erase_start; int erase_end; bool DO = true; ChMatrixDynamic<double> xk_padded(3*numContacts,1); //xk padded with zeros bool contactTable[numContacts]; for (int i = 0; i < numContacts; i++) contactTable[i] = true; // set true for non-zero items ///////////////////////////// ////GO THROUGH EACH STAGE//// ///////////////////////////// for (int stage = 0; stage < numStages; stage++){ /////////////////// // Modified PDIP // /////////////////// throwaway_size = throwaway.size(); if (throwaway_size == numContacts){ sysd.FromVectorToConstraints(xk); sysd.FromVectorToVariables(mq); for (size_t ic = 0; ic < mconstraints.size(); ic ++){ if (mconstraints[ic]->IsActive()) mconstraints[ic]->Increment_q(mconstraints[ic]->Get_l_i()); } return 1e-8; } for (int i = 0; i < throwaway.size(); i++) fprintf(stderr, "%d ", throwaway[i]); fprintf(stderr, "thrown away\n"); if (throwaway_size != 0) modified = true; // shrink problem size! if (modified == true){ int throw_nc; std::vector <int> eraseCqIndex; // vector stores the index eraseCqIndex.resize(2*throwaway_size); // get the index Cq_i, Cq_j, Cq_val to be thrown away int i = 0; int j = 0; /* fprintf(stderr, "-------index_j_Cq before shrinked-----\n"); for (int i = 0; i < index_j_Cq.size(); i ++) fprintf(stderr, "loc[%d]: %d\n", i , index_j_Cq[i]); fprintf(stderr, "-------Cq before shrinked-----\n"); for (int i = 0; i < index_j_Cq.size(); i ++) fprintf(stderr, "%d, %d, %.20f\n", index_i_Cq[i], index_j_Cq[i], val_Cq[i] ); */ //////////////////////////////// //Need to rewrite this part...// //////////////////////////////// DO = true; while (DO){ throw_nc = throwaway[j]; while (index_j_Cq[i] < 3*throw_nc && i < index_j_Cq.size()){ index_j_Cq[i] = index_j_Cq[i] - 3*j; i ++; } eraseCqIndex[2*j] = i; while (index_j_Cq[i] <= 3*throw_nc+2 && i < index_j_Cq.size()){ index_j_Cq[i] = index_j_Cq[i] - 3*j; i ++; } eraseCqIndex[2*j+1] = i; j = j + 1; if ( i >= index_j_Cq.size()) i--; while ( j >= throwaway_size && i < index_j_Cq.size()){ index_j_Cq[i] = index_j_Cq[i] - 3*j; i ++; if (i >= index_j_Cq.size()){ DO = false; break; } } } /* fprintf(stderr, "-------index_j_Cq after shrinked-----\n"); for (int i = 0; i < index_j_Cq.size(); i ++) fprintf(stderr, "loc[%d]: %d\n", i , index_j_Cq[i]); */ /* fprintf(stderr, "----eraseCqIndex-----\n"); for (int i = 0; i < 2*throwaway_size; i ++) fprintf(stderr, "%d \n", eraseCqIndex[i]); */ int numDeleted = 0; for (i = 0; i < throwaway_size; i ++){ erase_start = eraseCqIndex[2*i]; erase_end = eraseCqIndex[2*i+1]; index_i_Cq.erase(index_i_Cq.begin()+erase_start - numDeleted,index_i_Cq.begin()+erase_end - numDeleted); index_j_Cq.erase(index_j_Cq.begin()+erase_start - numDeleted,index_j_Cq.begin()+erase_end - numDeleted); /* fprintf(stderr, "erase #%d from location[%d] to [%d]\n", i, erase_start - numDeleted, erase_end - numDeleted); for (int i = 0; i < index_j_Cq.size(); i++) fprintf(stderr, "loc[%d]: %d\n", i , index_j_Cq[i]); */ val_Cq.erase(val_Cq.begin()+erase_start - numDeleted,val_Cq.begin()+erase_end - numDeleted); numDeleted += (erase_end - erase_start); } /* fprintf(stderr, "-------Cq_shrinked-----\n"); for (int i = 0; i < index_j_Cq.size(); i ++) fprintf(stderr, "%d, %d, %.20f\n", index_i_Cq[i], index_j_Cq[i], val_Cq[i] ); */ Cq_i = &index_i_Cq[0]; Cq_j = &index_j_Cq[0]; Cq_nnz = val_Cq.size(); Cq_val = &val_Cq[0]; ///////////////////////////////////// //Shrink x_k, opt_r, m_fric, lambda// ///////////////////////////////////// { ChMatrixDynamic<double> xk_shrinked(3*(numContacts - throwaway_size),1); ChMatrixDynamic<double> opt_r_shrinked(3*(numContacts - throwaway_size),1); ChMatrixDynamic<double> m_fric_shrinked(3*(numContacts - throwaway_size),1); ChMatrixDynamic<double> lambda_shrinked(2*(numContacts - throwaway_size),1); ChMatrixDynamic<double> ff_shrinked(2*(numContacts - throwaway_size),1); int index = 0; // index going through throwaway vector int j=0; // index going through the shrinked variables for (int i = 0; i < numContacts; i ++){ if ( throwaway[index] == i){ index = index + 1; if (index >= throwaway.size()) index = throwaway.size()-1; //check index goes out of bounds. } else{ xk_shrinked.SetElementN(3*j , xk.GetElementN(3*i )); xk_shrinked.SetElementN(3*j+1, xk.GetElementN(3*i+1)); xk_shrinked.SetElementN(3*j+2, xk.GetElementN(3*i+2)); opt_r_shrinked.SetElementN(3*j , opt_r.GetElementN(3*i )); opt_r_shrinked.SetElementN(3*j+1, opt_r.GetElementN(3*i+1)); opt_r_shrinked.SetElementN(3*j+2, opt_r.GetElementN(3*i+2)); m_fric_shrinked.SetElementN(3*j , mfric.GetElementN(3*i )); m_fric_shrinked.SetElementN(3*j+1, mfric.GetElementN(3*i+1)); m_fric_shrinked.SetElementN(3*j+2, mfric.GetElementN(3*i+2)); lambda_shrinked.SetElementN(j , lambda_k.GetElementN(i )); lambda_shrinked.SetElementN(j + numContacts - throwaway_size, lambda_k.GetElementN(i + numContacts)); ff_shrinked.SetElementN(j , ff.GetElementN(i )); ff_shrinked.SetElementN(j + numContacts - throwaway_size, ff.GetElementN(i + numContacts)); j = j + 1; } } xk.Resize(3*(numContacts - throwaway_size),1); xk = xk_shrinked; opt_r.Resize(3*(numContacts - throwaway_size),1); opt_r = opt_r_shrinked; mfric.Resize(3*(numContacts - throwaway_size),1); mfric = m_fric_shrinked; lambda_k.Resize(2*(numContacts - throwaway_size),1); lambda_k = lambda_shrinked; ff.Resize(2*(numContacts - throwaway_size),1); ff = ff_shrinked; } /* fprintf(stderr, "-----opt_r_shrinked----\n"); for (int i = 0; i < opt_r.GetRows(); i ++) fprintf(stderr, "%.20f\n", opt_r.GetElementN(i)); fprintf(stderr, "-----lambda_k_shrinked----\n"); for (int i = 0; i < lambda_k.GetRows(); i ++) fprintf(stderr, "%.20f\n", lambda_k.GetElementN(i)); */ numContacts = numContacts - throwaway_size; ////////////////////////////// //Resize remaining variables// ////////////////////////////// grad_f.Resize(3*numContacts,1); ff.Resize(2*numContacts,1); r_dual.Resize(3*numContacts,1); r_cent.Resize(2*numContacts,1); d_x.Resize(3*numContacts,1); d_lambda.Resize(2*numContacts,1); Schur_rhs.Resize(3*numContacts,1); } //////////////////////////////// //generate xk_padded (always!)// //////////////////////////////// if (xk.GetRows() != 3*nc_original){ int j = 0; // index goes through shrinked xk for (int i = 0; i < nc_original; i ++){ if (contactTable[i] == true){ xk_padded.SetElementN(3*i , xk.GetElementN(3*j )); xk_padded.SetElementN(3*i+1, xk.GetElementN(3*j+1)); xk_padded.SetElementN(3*i+2, xk.GetElementN(3*j+2)); j ++; } else{ xk_padded.SetElementN(3*i, 0); xk_padded.SetElementN(3*i+1,0); xk_padded.SetElementN(3*i+2,0); } } } else xk_padded = xk; /* fprintf(stderr, "-----ff_shrinked----\n"); for (int i = 0; i < ff.GetRows(); i ++) fprintf(stderr, "%.20f\n", ff.GetElementN(i)); */ eta_hat = - lambda_k.MatrDot(&lambda_k, &ff); barrier_t = mu1 * (2*numContacts)/eta_hat; // assemble grad_f = N*x + r // if (grad_f.GetRows() != 3*nc_original){ ChMatrixDynamic<double> grad_f_padded(3*nc_original,1); sysd.ShurComplementProduct(grad_f_padded, &xk_padded, 0); // map grad_f_padded to grad_f_shrinked int j = 0; // index goes through shrinked grad_f for (int i = 0; i < nc_original; i ++){ if (contactTable[i] == true){ grad_f.SetElementN(3*j, grad_f_padded.GetElementN(3*i)); grad_f.SetElementN(3*j+1, grad_f_padded.GetElementN(3*i+1)); grad_f.SetElementN(3*j+2, grad_f_padded.GetElementN(3*i+2)); j ++; } } } else { sysd.ShurComplementProduct(grad_f, &xk_padded, 0); } grad_f.MatrInc(opt_r); /* fprintf(stderr, "-----grad_f_shrinked----\n"); for (int i = 0; i < grad_f.GetRows(); i ++) fprintf(stderr, "%.20f\n", grad_f.GetElementN(i)); */ // compute r_d and r_c for schur implementation computeSchurRHS(grad_f.GetAddress(), mfric.GetAddress(), numContacts, barrier_t); // assemble block diagonal matrix computeBlockDiagonal(BlockDiagonal_val, mfric.GetAddress(), numContacts, barrier_t); // assemble rhs vector for spike solver computeSpikeRHS(spike_rhs, mfric.GetAddress(), numContacts, barrier_t); double *spike_dx = new double [3*numContacts]; //call ang's solver here.... bool print = false; // if (stage == 39) // print = true; bool solveSuc = solveSPIKE(nBodies, numContacts, Cq_i, Cq_j, Cq_nnz, Cq_val, Minv_i, Minv_j, Minv_val, BlockDiagonal_i, BlockDiagonal_j, BlockDiagonal_val, spike_dx, spike_rhs, print); if (solveSuc == false) std::cerr << "Solve Failed!" << std::endl; for (int i = 0; i < numContacts; i++){ d_x(3*i,0) = *(spike_dx + 3*i); d_x(3*i+1,0) = *(spike_dx + 3*i + 1); d_x(3*i+2,0) = *(spike_dx + 3*i + 2); } /* fprintf(stderr, "-----spike_rhs_shrinked----\n"); for (int i = 0; i < 3*numContacts; i ++) fprintf(stderr, "%.20f\n", *(spike_rhs+i)); fprintf(stderr, "-----spike_dx_shrinked----\n"); for (int i = 0; i < d_x.GetRows(); i ++) fprintf(stderr, "%.20f\n", d_x.GetElementN(i)); */ // free the heap! delete [] spike_dx; // evaluate d_lambda for (int i = 0; i < numContacts; i++){ d_lambda(i) = lambda_k(i,0)/ff(i,0) * (pow(mfric(3*i,0),2)*xk(3*i,0)*d_x(3*i,0) - xk(3*i+1,0)*d_x(3*i+1,0) -xk(3*i+2,0)*d_x(3*i+2,0) - r_cent(i,0) ); d_lambda(i + numContacts) = lambda_k(i+numContacts,0)/ff(i+numContacts)*(d_x(3*i) - r_cent(i + numContacts)); } /* fprintf(stderr, "------d_x------\n"); for (int i = 0; i < 3*numContacts; i++) fprintf(stderr, "%.20f\n", d_x(i)); */ /////////////// //LINE SEARCH// /////////////// double s_max = 1; double tmp; for (int i = 0; i < 2*numContacts; i ++){ if (d_lambda(i,0) < 0){ tmp = -lambda_k(i,0)/d_lambda(i,0); if (tmp < s_max){ s_max = tmp; } } } double bla = 0.99; double ss = bla * s_max; ff_tmp.Resize(2*numContacts,1); lambda_k_tmp.Resize(2*numContacts,1); xk_tmp.Resize(3*numContacts,1);; x_old_tmp.Resize(3*numContacts,1);; r_dual_tmp.Resize(3*numContacts,1);; r_cent_tmp.Resize(3*numContacts,1);; DO = true; int count = 0; while (DO){ xk_tmp = d_x; xk_tmp.MatrScale(ss); xk_tmp.MatrAdd(xk,xk_tmp); evaluateConstraints(mfric.GetAddress(), numContacts, true); if (ff_tmp.Max()<0){ DO = false; } else{ count++; ss = b1 * ss; } } DO = true; double norm_r_t = sqrt(pow(r_dual.NormTwo(),2) + pow(r_cent.NormTwo(),2)); double norm_r_t_ss; count = 0; while (DO){ xk_tmp = d_x; xk_tmp.MatrScale(ss); xk_tmp.MatrAdd(xk,xk_tmp); lambda_k_tmp = d_lambda; lambda_k_tmp.MatrScale(ss); lambda_k_tmp.MatrAdd(lambda_k, lambda_k_tmp); evaluateConstraints(mfric.GetAddress(),numContacts,true); { ChMatrixDynamic<double> xk_tmp_padded(3*nc_original,1); int j = 0; // index goes through shrinked xk_tmp for (int i = 0; i < nc_original; i ++){ if (contactTable[i] == true){ xk_tmp_padded.SetElementN(3*i , xk_tmp.GetElementN(3*j )); xk_tmp_padded.SetElementN(3*i+1, xk_tmp.GetElementN(3*j+1)); xk_tmp_padded.SetElementN(3*i+2, xk_tmp.GetElementN(3*j+2)); j ++; } else{ xk_tmp_padded.SetElementN(3*i, 0); xk_tmp_padded.SetElementN(3*i+1,0); xk_tmp_padded.SetElementN(3*i+2,0); } } /* fprintf(stderr, "------xk_tmp - xk_tmp_padded------\n"); for (int i = 0; i < 3*numContacts; i++) fprintf(stderr, "%.20f\n", xk_tmp(i)- xk_tmp_padded(i)); */ ChMatrixDynamic<double> grad_f_padded(3*nc_original,1); sysd.ShurComplementProduct(grad_f_padded, &xk_tmp_padded, 0); // map grad_f_padded to grad_f_shrinked j = 0; // index goes through shrinked grad_f for (int i = 0; i < nc_original; i ++){ if (contactTable[i] == true){ grad_f.SetElementN(3*j, grad_f_padded.GetElementN(3*i)); grad_f.SetElementN(3*j+1, grad_f_padded.GetElementN(3*i+1)); grad_f.SetElementN(3*j+2, grad_f_padded.GetElementN(3*i+2)); j ++; } } } grad_f.MatrInc(opt_r); /* fprintf(stderr, "------grad_f = N*xk +r ----with ss = %f---\n", ss); for (int i = 0; i < 3*numContacts; i++) fprintf(stderr, "%.20f\n", grad_f(i)); */ computeSchurKKT(grad_f.GetAddress(), mfric.GetAddress(), numContacts, barrier_t, true); norm_r_t_ss = sqrt(pow(r_dual_tmp.NormTwo(),2) + pow(r_cent_tmp.NormTwo(),2)); if (norm_r_t_ss < (1 - a1*ss)*norm_r_t) DO = false; else{ count ++; ss = b1*ss; } } // upadate xk and lambda_k d_x.MatrScale(ss); xk.MatrInc(d_x); d_lambda.MatrScale(ss); lambda_k.MatrInc(d_lambda); int j = 0; // index goes through shrinked xk_tmp for (int i = 0; i < nc_original; i ++){ if (contactTable[i] == true){ xk_padded.SetElementN(3*i , xk.GetElementN(3*j )); xk_padded.SetElementN(3*i+1, xk.GetElementN(3*j+1)); xk_padded.SetElementN(3*i+2, xk.GetElementN(3*j+2)); j ++; } else{ xk_padded.SetElementN(3*i, 0); xk_padded.SetElementN(3*i+1,0); xk_padded.SetElementN(3*i+2,0); } } ChMatrixDynamic<double> grad_f_padded(3*nc_original,1); sysd.ShurComplementProduct(grad_f_padded, &xk_padded, 0); // map grad_f_padded to grad_f_shrinked j = 0; // index goes through shrinked grad_f for (int i = 0; i < nc_original; i ++){ if (contactTable[i] == true){ grad_f.SetElementN(3*j, grad_f_padded.GetElementN(3*i)); grad_f.SetElementN(3*j+1, grad_f_padded.GetElementN(3*i+1)); grad_f.SetElementN(3*j+2, grad_f_padded.GetElementN(3*i+2)); j ++; } } grad_f.MatrInc(opt_r); evaluateConstraints(mfric.GetAddress(), numContacts, false); computeSchurKKT(grad_f.GetAddress(), mfric.GetAddress(), numContacts, barrier_t, false); fprintf(stderr, "stage[%d], rd = %e, rg = %e, s = %f, t = %f\n", stage+1, r_dual.NormInf(), r_cent.NormInf(), ss, barrier_t); /* fprintf(stderr, "-------xk-------\n"); for (int i = 0; i < xk.GetRows(); i++){ fprintf(stderr, "%.20f\n", xk.GetElementN(i)); } fprintf(stderr, "-------contactTable-------\n"); for (int i = 0; i < nc_original; i++){ fprintf(stderr, "%d\n", contactTable[i]); } */ throwaway = findModifiedIndex(numContacts, res); modified = false; if (throwaway.size() != 0){ modified = true; /* for (int i = 0; i < throwaway.size(); i++) fprintf(stderr, "%d\n",throwaway[i]); */ } // update contact table if (modified == true){ int i = 0; int nc_zero = throwaway.at(i); int count = 0; std::vector<int> tmp; for (int countTable = 0; countTable < 3*nc_original; countTable ++){ if (count == nc_zero && contactTable[countTable] == true){ tmp.push_back(countTable); i++; if ( i >= throwaway.size()) break; else nc_zero = throwaway.at(i); } if (contactTable[countTable] == true) count ++; } for (i = 0; i < tmp.size(); i ++){ contactTable[tmp.at(i)] = false; } /* fprintf(stderr, "-----countTable----\n"); for (int i = 0; i < nc_original; i ++) fprintf(stderr, "contactTable[%d] = %d\n", i, contactTable[i]); */ } if ((r_cent.NormInf() < res1 && r_dual.NormInf() < res2) || stage+1 >= numStages){ // fprintf(stderr, "stage[%d], rd = %e, rg = %e, s = %f, t = %f\n", stage+1, r_dual.NormInf(), r_cent.NormInf(), ss, barrier_t); delete [] BlockDiagonal_val; delete [] BlockDiagonal_i; delete [] BlockDiagonal_j; delete [] spike_rhs; int j = 0; // index goes through shrinked xk for (int i = 0; i < nc_original; i ++){ if (contactTable[i] == true){ xk_padded.SetElementN(3*i , xk.GetElementN(3*j )); xk_padded.SetElementN(3*i+1, xk.GetElementN(3*j+1)); xk_padded.SetElementN(3*i+2, xk.GetElementN(3*j+2)); j ++; } else{ xk_padded.SetElementN(3*i, 0); xk_padded.SetElementN(3*i+1,0); xk_padded.SetElementN(3*i+2,0); } } /* fprintf(stderr, "----------xk--------"); for (int i = 0; i < xk_padded.GetRows(); i++){ fprintf(stderr, "%.20f\n", xk_padded.ElementN(i)); } */ sysd.FromVectorToConstraints(xk_padded); sysd.FromVectorToVariables(mq); for (size_t ic = 0; ic < nConstraints; ic ++){ if (mconstraints[ic]->IsActive()) mconstraints[ic]->Increment_q(mconstraints[ic]->Get_l_i()); } fprintf(stderr, "solution found after %d stages!\n", stage+1); return r_cent.NormInf(); } } } std::vector<int> ChLcpInteriorPoint::findModifiedIndex(int nc, double res){ std::vector<int> index; for (int i = 0; i < nc; i++){ if (ff.GetElementN(nc + i) < res && ff.GetElementN(nc + i) > -res){ index.push_back(i); } } return index; } void ChLcpInteriorPoint::computeSpikeRHS(double *rhs, double *fric, int nc, double t){ double gamma_n, gamma_u, gamma_v; double l1, l2; double c1, c2; double one = 1; for (int i = 0; i < nc; i++){ gamma_n = xk.GetElementN(3*i); gamma_u = xk.GetElementN(3*i + 1); gamma_v = xk.GetElementN(3*i + 2); l1 = lambda_k.GetElementN(i); l2 = lambda_k.GetElementN(i + nc); c1 = ff.GetElementN(i); c2 = ff.GetElementN(i + nc); *(rhs + 3*i) = - pow(*(fric+3*i),2) * gamma_n *(l1 + one/(c1*t)) - (l2 + one/(c2*t)) - r_dual.GetElementN(3*i); *(rhs + 3*i+1) = gamma_u * (l1 + one/(c1*t))- r_dual.GetElementN(3*i+1); *(rhs + 3*i+2) = gamma_v * (l1 + one/(c1*t))- r_dual.GetElementN(3*i+2); } } void ChLcpInteriorPoint::evaluateConstraints(double* fric, int nc, bool tmp){ double *px; double *pff; double half = 0.5; if (tmp == true){ px = xk_tmp.GetAddress(); pff = ff_tmp.GetAddress(); } else { px = xk.GetAddress(); pff = ff.GetAddress(); } double gamma_n, gamma_u, gamma_v, mu; for (int i = 0; i < nc; i ++){ gamma_n = *(px + 3*i); gamma_u = *(px + 3*i+1); gamma_v = *(px + 3*i+2); mu = *(fric + 3*i); *(pff + i) = half*(pow(gamma_u,2) + pow(gamma_v,2) - pow(mu,2) * pow(gamma_n,2)); *(pff + i + nc) = -gamma_n; } } /* computing the rhs for the case of schur */ void ChLcpInteriorPoint::computeSchurRHS(double* grad_f, double* fric, int nc, double t){ double *prd = r_dual.GetAddress(); double *prc = r_cent.GetAddress(); double *plambda = lambda_k.GetAddress(); double *px = xk.GetAddress(); double *pff = ff.GetAddress(); double one = 1; for (int i = 0; i < nc; i ++){ *(prd + 3*i) = (*(grad_f + 3*i)- *(plambda + i)*pow(*(fric+3*i),2)*(*(px + 3*i)) - *(plambda + i +nc)); *(prd + 3*i + 1) = (*(grad_f + 3*i + 1)+ *(plambda + i)*(*(px + 3*i + 1))); *(prd + 3*i + 2) = (*(grad_f + 3*i + 2)+ *(plambda + i)*(*(px + 3*i + 2))); *(prc + i) = *(pff + i) + one/(*(plambda + i)*t); *(prc + nc +i) = *(pff + nc +i) + one/(*(plambda + nc + i)*t); } } /* computing the rhs for the case of KKT */ void ChLcpInteriorPoint::computeSchurKKT(double* grad_f, double* fric, int nc, double t, bool tmp){ double *prd, *prc, *plambda, *px, *pff, one; one = 1; if (tmp == true){ prd = r_dual_tmp.GetAddress(); prc = r_cent_tmp.GetAddress(); plambda = lambda_k_tmp.GetAddress(); px = xk_tmp.GetAddress(); pff = ff_tmp.GetAddress(); } else{ prd = r_dual.GetAddress(); prc = r_cent.GetAddress(); plambda = lambda_k.GetAddress(); px = xk.GetAddress(); pff = ff.GetAddress(); } for (int i = 0; i < nc; i ++){ *(prd + 3*i) = (*(grad_f + 3*i)- *(plambda + i)*pow(*(fric+3*i),2)*(*(px + 3*i)) - *(plambda + i +nc)); *(prd + 3*i + 1) = (*(grad_f + 3*i + 1)+ *(plambda + i)*(*(px + 3*i + 1))); *(prd + 3*i + 2) = (*(grad_f + 3*i + 2)+ *(plambda + i)*(*(px + 3*i + 2))); *(prc + i) = -*(pff + i)*(*(plambda+i)) - one/t; *(prc + nc +i) = -*(pff + nc +i)*(*(plambda+nc+i)) - one/t; } } /* formulate block diagonal matrix in row fashion*/ void ChLcpInteriorPoint::computeBlockDiagonal(double* val_diagonal, double *fric, int nc, double t){ double *plambda = lambda_k.GetAddress(); double *px = xk.GetAddress(); double *pff = ff.GetAddress(); double b11, b12, b13, b22, b23, b33; double tmp1, tmp2, tmp3; int count = 0; double mu; double gamma_n, gamma_u, gamma_v; for (int i = 0; i < nc; i++){ mu = *(fric + 3*i); tmp1 = *(plambda + i)/(*(pff + i)); tmp2 = tmp1 * pow(mu,2); tmp3 = *(plambda + i + nc)/(*(pff + i + nc)); gamma_n = *(px + 3*i); gamma_u = *(px + 3*i + 1); gamma_v = *(px + 3*i + 2); b11 = -pow(mu,2)*pow(gamma_n,2)*tmp2 - tmp3 - pow(mu,2)*(*(plambda + i)); b12 = gamma_n * gamma_u * tmp2; b13 = gamma_n * gamma_v * tmp2; b22 = -pow(gamma_u,2) * tmp1 + (*(plambda+i)); b23 = -gamma_u * gamma_v * tmp1; b33 = -pow(gamma_v,2) * tmp1 + (*(plambda+i)); /* assign value to sparse block! */ *(val_diagonal + 9*i) = b11; *(val_diagonal + 9*i + 1) = b12; *(val_diagonal + 9*i + 2) = b13; *(val_diagonal + 9*i + 3) = b12; *(val_diagonal + 9*i + 4) = b22; *(val_diagonal + 9*i + 5) = b23; *(val_diagonal + 9*i + 6) = b13; *(val_diagonal + 9*i + 7) = b23; *(val_diagonal + 9*i + 8) = b33; } } } // END_OF_NAMESPACE____
#include<bits/stdc++.h> using namespace std; main() { int s, v1, v2, t1, t2; while(cin>>s>>v1>>v2>>t1>>t2) { int first , second; first = (s*v1) + (2*t1); second = (s*v2)+ (2*t2); if(first<second)printf("First\n"); else if(first>second)printf("Second\n"); else printf("Friendship\n"); } return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; int a[10][10],n,m; string s1,s2; int dfs(int k,int x) { if (k == n) return 1; int ans = 0; for (int i = 0;i < 6; i++) if (a[x][i]) ans += dfs(k+1,i)*a[x][i]; return ans; } int main() { scanf("%d%d",&n,&m); for (int i = 1;i <= m; i++) { cin >> s1 >> s2; a[s2[0] - 'a'][s1[0] - 'a']++; } printf("%d\n",dfs(1,0)); return 0; }
#ifndef CoinConf_H #define CoinConf_H #include "BaseCoinConf.h" #include "Player.h" class CoinConf : public BaseCoinConf { public: public: static CoinConf* getInstance(); virtual ~CoinConf(); virtual bool GetCoinConfigData(); CoinCfg* getCoinCfg() { return &m_coincfg; } private: CoinCfg m_coincfg; CoinConf(); }; #endif
#include <iostream> #include <queue> #include <cstdlib> using namespace std; // Node class class Node { public: Node() { mData = -1; mParent = NULL; mLeft = NULL; mRight = NULL; } ~Node() {} int data() { return mData; } void setData(int data) { mData = data; } Node* left() { return mLeft; } void setLeft(Node* left) { mLeft = left; } Node* right() { return mRight; } void setRight(Node* right) { mRight = right; } Node* parent() { return mParent; } void setParent(Node* parent) { mParent = parent; } private: int mData; Node* mLeft; Node* mRight; Node* mParent; }; // Tree class class Tree { public: Tree() { mRoot = NULL; } ~Tree() {} Node* root() { return mRoot; } void addNode(int data); void zigzag(Node *node); private: void addNode(Node* node, int data); private: Node* mRoot; }; void Tree::addNode(int data) { if ( mRoot == NULL ) { Node* tmp = new Node(); tmp->setData(data); mRoot = tmp; } else { addNode(mRoot, data); } } void Tree::addNode(Node* node, int data) { if ( data <= node->data() ) { if ( node->left() != NULL ) addNode(node->left(), data); else { Node* tmp = new Node(); tmp->setData(data); tmp->setParent(node); node->setLeft(tmp); } } else { if ( node->right() != NULL ) addNode(node->right(), data); else { Node* tmp = new Node(); tmp->setData(data); tmp->setParent(node); node->setRight(tmp); } } } void Tree::zigzag(Node* node) { queue<Node*> q; q.push(node); while ( ! q.empty() ) { Node* tmp = q.front(); q.pop(); cout << tmp->data() << " "; if ( tmp->right() ) q.push(tmp->right()); if ( tmp->left() ) q.push(tmp->left()); } cout << endl; } // Test program int main() { Tree* t = new Tree(); t->addNode(500); t->addNode(300); t->addNode(600); t->addNode(550); t->addNode(700); t->addNode(750); t->addNode(200); t->addNode(150); t->addNode(250); t->addNode(350); t->addNode(800); t->zigzag(t->root()); delete t; }
#pragma once #include "Ficha.h" #include <math.h> #include"glut.h" class Peon :public Ficha { public: Peon(); virtual ~Peon(); void Mueve(); virtual void SetColor(Color col); virtual void SetRadio(float rad); virtual void SetPos(float ix, float iy); //////////////////////// virtual int GetPosX(); virtual int GetPosY(); virtual Color GetColor(); virtual Tipo GetTipo(); //////////////////////// virtual void Mueve(int pos_finX, int pos_finY); virtual void Dibuja(); virtual void BorraFicha(); };
#include <iostream> #include <cstring> #include <vector> #define MAX 81 #define MAX_T 6401 int n, m, map[MAX][MAX], d[MAX_T]; int dx[6] = {-1, -1, 0, 0, 1, 1}, dy[6] = {-1, 1, -1, 1, -1, 1}; std::vector<int> adj[MAX_T]; bool check[MAX_T]; bool dfs(int x) { if(check[x]) { return false; } check[x] = true; for(int y : adj[x]) { if(d[y] == 0 || dfs(d[y])) { d[y] = x; return true; } } return false; } int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); int tc; std::cin >> tc; while(tc--) { std::cin >> n >> m; int tot = 0; std::vector<int> list; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { char c; std::cin >> c; if(c == '.') { map[i][j] = ++tot; if(j % 2 == 0) { list.push_back(tot); } } } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(map[i][j] > 0) { for(int k = 0; k < 6; k++) { int nx = dx[k] + i; int ny = dy[k] + j; if(nx <= 0 || ny <= 0 || nx > n || ny > m) { continue; } if(map[nx][ny] > 0) { adj[map[i][j]].push_back(map[nx][ny]); } } } } } int ans = 0; for(int i : list) { std::memset(check, 0, sizeof(check)); if(dfs(i)) { ans++; } } std::cout << tot - ans << '\n'; std::memset(d, 0, sizeof(d)); std::memset(map, 0, sizeof(map)); for(int i = 1; i <= tot; i++) { adj[i].clear(); } } return 0; }
#ifndef __WPP__QT__QGuiApplication_H__ #define __WPP__QT__QGuiApplication_H__ #include <QGuiApplication> #include "Wpp.h" namespace wpp { namespace qt { class QGuiApplication : public ::QGuiApplication { Q_OBJECT private: bool m_keyboardWasAnimating; public: #ifdef Q_QDOC QGuiApplication(int &argc, char **argv); #else QGuiApplication(int &argc, char **argv, int = ApplicationFlags); #endif virtual ~QGuiApplication(); void loadTranslations(const QString& qmFilenameNoExtension); void enableQtWebEngineIfPossible(); void registerApplePushNotificationService(); void enableAutoScreenOrientation(bool autoRotate) { wpp::qt::Wpp::getInstance().enableAutoScreenOrientation(true); } private://helpers void init(); private: Q_SLOT void onFocusWindowYChanged(); Q_SLOT void onInputMethodVisibleChanged(); }; } } #endif
/* * @lc app=leetcode.cn id=125 lang=cpp * * [125] 验证回文串 */ // @lc code=start #include<iostream> #include<string> using namespace std; class Solution { public: bool isPalindrome(string s) { string sgood; for(char ch:s) { if(isalnum(ch)) { sgood+=tolower(ch); } } string sgood_rev(sgood.rbegin(),sgood.rend()); return sgood==sgood_rev; } // bool isPalindrome(string s) { // auto i=s.begin(),j=s.end()-1; // while(i<j){ // if(isalpha(*i)||isdigit(*i)){ // if(isalpha(*i)){ // *i = tolower(*i); // } // }else{ // ++i; // } // if(isalpha(*j)||isdigit(*j)){ // if(isalpha(*j)){ // *j = tolower(*j); // } // }else{ // --j; // } // if((isalpha(*i)||isdigit(*i))&&(isalpha(*j)||isdigit(*j))){ // if(isalpha(*i)){ // *i = tolower(*i); // } // if(isalpha(*j)){ // *j = tolower(*j); // } // if(*i!=*j) // { // cout<<*i<<endl; // cout<<*j<<endl; // return false; // } // ++i; // --j; // } // } // return true; // } }; // @lc code=end
//my solution class Solution { public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> res; for(int i = 0; i < words.size(); ){ string str = words[i]; int len = words[i].size(), j; for(j = i+1; j < words.size(); ++j){ if(len + 1 + words[j].size() > maxWidth) break; len += 1 + words[j].size(); } int num = j-i-1; if(!num || j == words.size()){ for(int k = i+1; k < j; ++k){ str += ' ' + words[k]; } str += string(maxWidth - str.size(), ' '); }else{ len -= num; int red = (maxWidth - len)%num; int space = (maxWidth - len - red)/num; for(int k = i+1; k < j; ++k){ if(red > 0){ str += string(space+1, ' ') + words[k]; --red; }else{ str += string(space, ' ') + words[k]; } } } res.push_back(str); i = j; } return res; } };
extern "C" { #include <iconv.h> } #include <array> #include <cstddef> #include <cstdlib> #include <iostream> #include <string> #include <system_error> class iconv_desc { private: iconv_t iconvd_; public: iconv_desc(const std::string& tocode, const std::string& fromcode) { iconvd_ = iconv_open(tocode.c_str(), fromcode.c_str()); if (iconvd_ == reinterpret_cast<iconv_t>(-1)) throw std::system_error(errno, std::system_category()); } ~iconv_desc() { iconv_close(iconvd_); } operator iconv_t() { return this->iconvd_; } }; int main() { try { auto conv_d = iconv_desc{ "ISO-8859-1", "UTF-8" }; auto from_str = std::array<char, 10>{ u8"a\xC3\xA4o\xC3\xB6u\xC3\xBC" }; auto to_str = std::array<char, 7>{}; auto from_str_ptr = from_str.data(); auto from_len = from_str.size(); auto to_str_ptr = to_str.data(); auto to_len = to_str.size(); const auto iconv_ret = iconv(conv_d, &from_str_ptr, &from_len, &to_str_ptr, &to_len); if (iconv_ret == static_cast<std::size_t>(-1)) throw std::system_error(errno, std::system_category()); std::cout << '\'' << from_str.data() << "\' converted to \'" << to_str.data() << '\'' << std::endl; return EXIT_SUCCESS; } catch (const std::system_error& ex) { std::cerr << "ERROR: " << ex.code() << '\n' << ex.code().message() << std::endl; } return EXIT_FAILURE; }
#include "stdio.h" int main(){ int T; char a[1000][1000]; int i,j,n,m,k; scanf("%d",&T); while(T--){ scanf("%d%d%d",&n,&m,&k); for(i=0;i<n;i++){ for(j=0;j<m;j++) scanf("%c",a[i][j]); } } }
#include <iostream> #include <fstream> #include <string> #include "BiDirectionalList.h" #include "Parallelepiped.h" void AddByPerimeter(BiDirectionalList<Parallelepiped>& list, Parallelepiped tmp) { bool found = 0; BiDirectionalList<Parallelepiped>::Node* element; for (int i = 0; i < list.Size(); i++){ if (list[i] -> value.GetPerimeter() > tmp.GetPerimeter()){ found = 1; element = list[i]; break; } } if (!found){ list.PushBack(tmp); } else { list.InsertBefore(element, tmp); } } void AddByVolume(BiDirectionalList<Parallelepiped>& list, Parallelepiped tmp) { bool found = 0; BiDirectionalList<Parallelepiped>::Node* element; for (int i = 0; i < list.Size(); i++){ if (list[i] -> value.GetVolume() > tmp.GetVolume()){ found = 1; element = list[i]; break; } } if (!found){ list.PushBack(tmp); } else { list.InsertBefore(element, tmp); } } int main() { std::ifstream in; try { in.open("input.txt"); } catch(...) { std::cout << "Error while opening the input file.\n"; exit(1); } int n; in >> n; std::string s; in >> s; SortType sort_type; if (s == "perimeter"){ sort_type = Perimeter; } if (s == "volume"){ sort_type = Volume; } std::getline(in, s); BiDirectionalList<Parallelepiped> list = BiDirectionalList<Parallelepiped>(); for (int i = 1; i <= n; i++){ std::getline(in, s); //std::cout << s << "\n"; std::string buffer = ""; int index = 0; while (index < (int)s.size() && s[index] != ' '){ buffer += s[index]; index++; } if (buffer != "cube" && buffer != "parallelepiped"){ continue; } std::string type = ((buffer == "cube") ? "cube" : "parallelepiped"); index++; buffer = ""; if (type == "cube"){ while (index < (int)s.size() && s[index] != ' '){ buffer += s[index]; index++; } double length; if (index == (int)s.size()){ length = std::stod(buffer); Parallelepiped tmp = Parallelepiped(type, length, length, length, 12 * length, length * length * length); if (sort_type == Perimeter){ AddByPerimeter(list, tmp); } else { AddByVolume(list, tmp); } } else { continue; } } else { //std::cout << type << "\n"; while (index < (int)s.size() && s[index] != ' '){ buffer += s[index]; index++; } double length = std::stod(buffer); //std::cout << length << "\n"; if (index == (int)s.size()){ continue; } index++; buffer = ""; while (index < (int)s.size() && s[index] != ' '){ buffer += s[index]; index++; } double width = std::stod(buffer); //std::cout << width << "\n"; if (index == (int)s.size()){ continue; } index++; buffer = ""; while (index < (int)s.size() && s[index] != ' '){ buffer += s[index]; index++; } double height = std::stod(buffer); //std::cout << height << "\n"; if (index == (int)s.size()){ Parallelepiped tmp = Parallelepiped(type, length, width, height, 4 * (length + width + height), length * width * height); if (sort_type == Perimeter){ AddByPerimeter(list, tmp); } else { AddByVolume(list, tmp); } } else { continue; } } } in.close(); std::ofstream out; try { out.open("output.txt"); } catch(...) { std::cout << "Error while opening the output file.\n"; exit(1); } out << list.Size() << "\n"; for (int i = 0; i < list.Size(); i++){ out << list[i] -> value.GetId() << " "; if (list[i] -> value.GetType() == Cube){ out << "cube "; out << list[i] -> value.GetLength() << " "; if (sort_type == Perimeter){ out << list[i] -> value.GetPerimeter() << "\n"; } else { out << list[i] -> value.GetVolume() << "\n"; } } else { out << "parallelepiped "; out << list[i] -> value.GetLength() << " "; out << list[i] -> value.GetWidth() << " "; out << list[i] -> value.GetHeight() << " "; if (sort_type == Perimeter){ out << list[i] -> value.GetPerimeter() << "\n"; } else { out << list[i] -> value.GetVolume() << "\n"; } } } return 0; }
////////////////////////////////////////////////////////////////////////// // // pgAdmin 4 - PostgreSQL Tools // // Copyright (C) 2013 - 2017, The pgAdmin Development Team // This software is released under the PostgreSQL Licence // // TabWindow.cpp - Implementation of the custom tab widget // ////////////////////////////////////////////////////////////////////////// #include "pgAdmin4.h" // App headers #include "TabWindow.h" #ifdef PGADMIN4_USE_WEBENGINE #include <QWebEngineHistory> #else #include <QWebHistory> #endif DockTabWidget *DockTabWidget::mainTabWidget = NULL; DockTabWidget::DockTabWidget(QWidget *parent) : QTabWidget(parent) { floatingWidget = NULL; floatingEnabled = false; setParent(parent); setTabsClosable(false); setElideMode(Qt::ElideRight); // set custom tab bar in tab widget to receive events for docking. setTabBar(new DockTabBar(this)); setDocumentMode(true); setAcceptDrops(true); // Get the system colours we need QPalette palette = QApplication::palette("QPushButton"); QColor activebg = palette.color(QPalette::Button); QColor activefg = palette.color(QPalette::ButtonText); QColor inactivebg = palette.color(QPalette::Dark); QColor inactivefg = palette.color(QPalette::ButtonText); QColor border = palette.color(QPalette::Mid); setStyleSheet( "QTabBar::tab { " "background-color: " + inactivebg.name() + "; " "color: " + inactivefg.name() + "; " "border: 1px solid " + border.name() + "; " "padding: 1px 0px; " "margin-left: 0px; " "margin-top: 1px; " #ifndef __APPLE__ "width: 15em; " "height: 1.5em; " #endif "} " "QTabBar::tab:selected { " "background-color: " + activebg.name() + "; " "color: " + activefg.name() + "; " "border-bottom-style: none; " "} " "QTabWidget::pane { " "border: 0; " "} " "QTabWidget::tab-bar {" "alignment: left; " "}" ); if (mainTabWidget == NULL) mainTabWidget = this; } DockTabWidget::DockTabWidget(DockTabWidget *other, QWidget *parent) : QTabWidget(parent) { setFloatingBaseWidget(other->floatingBaseWidget()); setFloatingEnabled(other->isFloatingEnabled()); resize(other->size()); // set custom tab bar in tab widget to receive events for docking. setTabBar(new DockTabBar(this)); setDocumentMode(true); setAcceptDrops(true); // Get the system colours we need QPalette palette = QApplication::palette("QPushButton"); QColor activebg = palette.color(QPalette::Button); QColor activefg = palette.color(QPalette::ButtonText); QColor inactivebg = palette.color(QPalette::Dark); QColor inactivefg = palette.color(QPalette::ButtonText); QColor border = palette.color(QPalette::Mid); setStyleSheet( "QTabBar::tab { " "background-color: " + inactivebg.name() + "; " "color: " + inactivefg.name() + "; " "border: 1px solid " + border.name() + "; " "padding: 1px 0px; " "margin-left: 0px; " "margin-top: 1px; " #ifndef __APPLE__ "width: 15em; " "height: 1.5em; " #else "font: 11pt; " "width: 19em; " "height: 1.5em; " #endif "} " "QTabBar::tab:selected { " "background-color: " + activebg.name() + "; " "color: " + activefg.name() + "; " "border-bottom-style: none; " "} " "QTabWidget::pane { " "border: 0; " "} " "QTabWidget::tab-bar {" "alignment: left; " "}" ); } void DockTabWidget::setFloatingBaseWidget(QWidget *widget) { floatingWidget = widget; if (floatingEnabled && parentWidget() == 0) setParent(widget); } void DockTabWidget::setFloatingEnabled(bool x) { floatingEnabled = x; if (parent() == 0) { if (x) setWindowFlags(Qt::Tool); else setWindowFlags(Qt::Window); } } // Slot: go back to page and enable/disable toolbutton void DockTabWidget::dockGoBackPage() { WebViewWindow *webviewPtr = NULL; QWidget *tab = this->widget(this->currentIndex()); if (tab != NULL) { QList<QWidget*> widgetList = tab->findChildren<QWidget*>(); foreach( QWidget* widgetPtr, widgetList ) { if (widgetPtr != NULL) { webviewPtr = dynamic_cast<WebViewWindow*>(widgetPtr); if (webviewPtr != NULL) webviewPtr->back(); } } } } // Slot: go forward to page and enable/disable toolbutton void DockTabWidget::dockGoForwardPage() { WebViewWindow *webviewPtr = NULL; QWidget *tab = this->widget(this->currentIndex()); if (tab != NULL) { QList<QWidget*> widgetList = tab->findChildren<QWidget*>(); foreach( QWidget* widgetPtr, widgetList ) { if (widgetPtr != NULL) { webviewPtr = dynamic_cast<WebViewWindow*>(widgetPtr); if (webviewPtr != NULL) webviewPtr->forward(); } } } } // Close the tab and remove the memory of the given index tab void DockTabWidget::dockClosetabs() { int totalTabs = 0; QToolButton *btn = NULL; QWidget *tab = NULL; DockTabWidget *l_tab_widget = NULL; QObject *senderPtr = QObject::sender(); if (senderPtr != NULL) { btn = dynamic_cast<QToolButton*>(senderPtr); if (btn != NULL) { l_tab_widget = dynamic_cast<DockTabWidget*>(btn->parent()->parent()); int current_tab_index = 0; if (l_tab_widget != NULL) { totalTabs = l_tab_widget->count(); for (int loopCount = l_tab_widget->count();loopCount >= 0;loopCount--) { QWidget *l_tab = l_tab_widget->tabBar()->tabButton(loopCount, QTabBar::RightSide); if (l_tab != NULL) { QToolButton *nextBtnPtr = dynamic_cast<QToolButton*>(l_tab); if (nextBtnPtr != NULL && btn != NULL && nextBtnPtr == btn) current_tab_index = loopCount; } } QList<QWidget*> widgetList = l_tab_widget->tabBar()->findChildren<QWidget*>(); foreach(QWidget* widgetPtr, widgetList) { if (widgetPtr != NULL) { QToolButton *toolBtnPtr = dynamic_cast<QToolButton*>(widgetPtr); if (toolBtnPtr != NULL && toolBtnPtr == btn) { tab = l_tab_widget->widget(current_tab_index); break; } } } } if (tab != NULL) tab->deleteLater(); // If user close the last tab then close the parent tab widget also. if (totalTabs == 1 && l_tab_widget != NULL) l_tab_widget->deleteLater(); } } if (tab != NULL) { WebViewWindow *webviewPtr = NULL; QList<QWidget*> widgetList = tab->findChildren<QWidget*>(); foreach (QWidget* widgetPtr, widgetList) { if (widgetPtr != NULL) { webviewPtr = dynamic_cast<WebViewWindow*>(widgetPtr); if (webviewPtr != NULL) { /* Trigger the action for tab window close so unload event will be called and * resources will be freed properly. * Trigger 'RequestClose' action from Qt5 onwards. Here we have triggerred the action * 'ToggleVideoFullscreen + 1' because we do not know from which webkit * version 'RequestClose' action was added so increment with previous enum value so that * it will be backward webkit version compatible. */ #if QT_VERSION >= 0x050000 #ifndef PGADMIN4_USE_WEBENGINE webviewPtr->page()->triggerAction(static_cast<QWebPage::WebAction>(QWebPage::ToggleVideoFullscreen + 1)); #endif #endif } } } } // Check if main pgAdmin4 application has only one tab then close tab bar. // Here - check for count 2 because tab will be deleted later. DockTabWidget *mainTab = DockTabWidget::getMainTabWidget(); if (mainTab != NULL && l_tab_widget != NULL && l_tab_widget == mainTab && mainTab->count() == 2) mainTab->tabBar()->setVisible(false); } // This function is used to set back/forward/close buttons on new tabbar. void DockTabWidget::setButtonsNewTabbar(int index) { QWidget *m_widget = new QWidget(); QToolButton *m_toolBtnBack = new QToolButton(m_widget); m_toolBtnBack->setFixedHeight(PGA_BTN_SIZE); m_toolBtnBack->setFixedWidth(PGA_BTN_SIZE); m_toolBtnBack->setIcon(QIcon(":/back.png")); m_toolBtnBack->setToolTip(tr("Go back")); QToolButton *m_toolBtnForward = new QToolButton(m_widget); m_toolBtnForward->setFixedHeight(PGA_BTN_SIZE); m_toolBtnForward->setFixedWidth(PGA_BTN_SIZE); m_toolBtnForward->setIcon(QIcon(":/forward.png")); m_toolBtnForward->setToolTip(tr("Go forward")); QToolButton *m_btnClose = new QToolButton(m_widget); m_btnClose->setFixedHeight(PGA_BTN_SIZE); m_btnClose->setFixedWidth(PGA_BTN_SIZE); m_btnClose->setIcon(QIcon(":/close.png")); m_btnClose->setToolTip(tr("Close tab")); QHBoxLayout *m_horizontalLayout = new QHBoxLayout(m_widget); m_horizontalLayout->setContentsMargins(0,1,0,0); m_horizontalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); m_horizontalLayout->setSpacing(1); m_horizontalLayout->addWidget(m_toolBtnBack); m_horizontalLayout->addWidget(m_toolBtnForward); // Register the slot on toolbutton to show the previous history of web connect(m_toolBtnBack, SIGNAL(clicked()), this, SLOT(dockGoBackPage())); // Register the slot on toolbutton to show the next history of web connect(m_toolBtnForward, SIGNAL(clicked()), this, SLOT(dockGoForwardPage())); // Register the slot on close button , added manually connect(m_btnClose, SIGNAL(clicked()), SLOT(dockClosetabs())); // Register the slot on tab index change connect(this, SIGNAL(currentChanged(int )), this,SLOT(tabIndexChanged(int ))); // Set the back and forward button on tab this->tabBar()->setTabButton(index, QTabBar::LeftSide, m_widget); this->tabBar()->setTabButton(index, QTabBar::RightSide, m_btnClose); // find the webview and hide/show button depending on flag set with web view. QWidget *tab = this->widget(index); if (tab != NULL) { QList<QWidget*> widgetList = tab->findChildren<QWidget*>(); foreach( QWidget* widgetPtr, widgetList ) { if (widgetPtr != NULL) { WebViewWindow *webViewPtr = dynamic_cast<WebViewWindow*>(widgetPtr); if (webViewPtr != NULL) { // If user open any file in query tool then "Query -" name will not appear // but it is still query tool so hide the tool button. if (!webViewPtr->getBackForwardButtonHidden()) { m_toolBtnBack->show(); m_toolBtnForward->show(); } else { m_toolBtnBack->hide(); m_toolBtnForward->hide(); } break; } } } } } // This function is used to move to old tab widget to new tab widget. void DockTabWidget::moveTab(DockTabWidget *source, int sourceIndex, DockTabWidget *dest, int destIndex) { if (source == dest && sourceIndex < destIndex) destIndex--; QWidget *widget = source->widget(sourceIndex); QString text = source->tabText(sourceIndex); source->removeTab(sourceIndex); dest->insertTab(destIndex, widget, text); dest->setCurrentIndex(destIndex); } // This function is used to decode actual drop event on tab widget. void DockTabWidget::decodeTabDropEvent(QDropEvent *event, DockTabWidget **p_tabWidget, int *p_index) { DockTabBar *tabBar = qobject_cast<DockTabBar *>(event->source()); if (!tabBar) { *p_tabWidget = NULL; *p_index = 0; return; } QByteArray data = event->mimeData()->data(MIMETYPE_TABINDEX); QDataStream stream(&data, QIODevice::ReadOnly); int index; stream >> index; *p_tabWidget = tabBar->tabWidget(); *p_index = index; } // This function is used to check event is actually drop event or not. bool DockTabWidget::eventIsTabDrag(QDragEnterEvent *event) { return event->mimeData()->hasFormat(MIMETYPE_TABINDEX) && qobject_cast<DockTabBar *>(event->source()); } // This function is used to delete tab widget when there is no tab inside. void DockTabWidget::deleteIfEmpty() { if (count() == 0) { emit willBeAutomaticallyDeleted(this); deleteLater(); } } // This is function is used to create another tab widget from parent window. DockTabWidget *DockTabWidget::createAnotherTabWidget(QWidget *parent) { DockTabWidget *tab_widget = new DockTabWidget(this, parent); tab_widget->tabBar()->setVisible(true); return tab_widget; } // Check wether tab is insertable or not. bool DockTabWidget::isInsertable(QWidget *widget) { Q_UNUSED(widget) return true; } // Hide the close button of given index displayed on right side of tab void DockTabWidget::enableDisableToolButton(const int &index) { QToolButton *toolBtnPtr = NULL; WebViewWindow *tmpwebviewPtr = NULL; WebViewWindow *webviewPtr = NULL; // Enable/disable the toolbutton based on the history QWidget *tab1 = this->widget(index); if (tab1 != NULL) { QList<QWidget*> widgetList = tab1->findChildren<QWidget*>(); foreach( QWidget* widgetPtr, widgetList ) { if (widgetPtr != NULL) tmpwebviewPtr = dynamic_cast<WebViewWindow*>(widgetPtr); if (tmpwebviewPtr != NULL) webviewPtr = tmpwebviewPtr; } } QWidget *tab = tabBar()->tabButton(index, QTabBar::LeftSide); if (tab != NULL) { QList<QWidget*> widgetList = tab->findChildren<QWidget*>(); foreach( QWidget* widgetPtr, widgetList ) { if (widgetPtr != NULL) { toolBtnPtr = dynamic_cast<QToolButton*>(widgetPtr); if (webviewPtr != NULL && toolBtnPtr != NULL) { if (!QString::compare(toolBtnPtr->toolTip(), tr("Go back"), Qt::CaseInsensitive)) { if (webviewPtr->page()->history()->canGoBack()) toolBtnPtr->setDisabled(false); else toolBtnPtr->setDisabled(true); } if (!QString::compare(toolBtnPtr->toolTip(), tr("Go forward"), Qt::CaseInsensitive)) { if (webviewPtr->page()->history()->canGoForward()) toolBtnPtr->setDisabled(false); else toolBtnPtr->setDisabled(true); } } } } } } // Slot: When the tab index change, hide/show the toolbutton displayed on tab void DockTabWidget::tabIndexChanged(int index) { int tabCount = 0; WebViewWindow *webViewPtr = NULL; for (tabCount = 0; tabCount < this->count(); tabCount++) { // if main pgAdmin4 application tab then do nothing. if (!QString::compare(this->tabText(tabCount), tr("pgAdmin 4"), Qt::CaseInsensitive)) continue; QWidget *tab = this->widget(tabCount); if (tab != NULL) { QList<QWidget*> widgetList = tab->findChildren<QWidget*>(); foreach( QWidget* widgetPtr, widgetList ) { if (widgetPtr != NULL) { webViewPtr = dynamic_cast<WebViewWindow*>(widgetPtr); if (webViewPtr != NULL) break; } } } if (tabCount != index) this->showHideToolButton(tabCount, 0); else { if (!webViewPtr->getBackForwardButtonHidden()) this->showHideToolButton(tabCount, 1); else this->showHideToolButton(tabCount, 0); } } // paint the tab text again as index of the tab widget changed. this->tabBar()->update(); } // Show and Hide the toolbutton once the tab is deselected depending on the option // option 0: Hide the toolButton // option 1: Show the toolButton void DockTabWidget::showHideToolButton(const int &index, const int &option) { QToolButton *toolBtnPtr = NULL; QWidget *tab = tabBar()->tabButton(index, QTabBar::LeftSide); if (tab != NULL) { QList<QWidget*> widgetList = tab->findChildren<QWidget*>(); foreach( QWidget* widgetPtr, widgetList ) { if (widgetPtr != NULL) { toolBtnPtr = dynamic_cast<QToolButton*>(widgetPtr); if (toolBtnPtr != NULL) { if (!option) toolBtnPtr->hide(); else toolBtnPtr->show(); } } } } } // Set the tab tool tip text void DockTabWidget::setTabToolTipText(const int &index, const QString &toolTipString) { tabBar()->setTabToolTip(index, toolTipString); } // Implementation of custom tab bar for docking window. DockTabBar::DockTabBar(DockTabWidget *tabWidget, QWidget *parent) : QTabBar(parent), tab_widget(tabWidget) { isStartingDrag = false; setAcceptDrops(true); } // Insert new tab at specified index. int DockTabBar::insertionIndexAt(const QPoint &pos) { int index = count(); for (int i = 0; i < count(); ++i) { QRect rect = tabRect(i); QRect rect1(rect.x(), rect.y(), rect.width() / 2, rect.height()); QRect rect2(rect.x() + rect1.width(), rect.y(), rect.width() - rect1.width(), rect.height()); if (rect1.contains(pos)) { index = i; break; } if (rect2.contains(pos)) { index = i + 1; break; } } return index; } // Mouse press event handler for tab drag. void DockTabBar::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { dragStartPos = event->pos(); isStartingDrag = true; } QTabBar::mousePressEvent(event); } // Mouse move event handler for tab drag. void DockTabBar::mouseMoveEvent(QMouseEvent *event) { if (!isStartingDrag) return; if ((!event->buttons()) && Qt::LeftButton) return; if ((event->pos() - dragStartPos).manhattanLength() < QApplication::startDragDistance()) return; int index = tabAt(event->pos()); if (index < 0) return; // Don't allow to drag the pgAdmin4 main tab. if (!QString::compare(tab_widget->tabText(index), tr("pgAdmin 4"), Qt::CaseInsensitive)) { return; } // create data QMimeData *mimeData = new QMimeData; QByteArray data; QDataStream stream(&data, QIODevice::WriteOnly); stream << index; mimeData->setData(MIMETYPE_TABINDEX, data); // create pixmap QRect rect = tabRect(index); QPixmap pixmap(rect.size()); render(&pixmap, QPoint(), QRegion(rect)); // exec drag QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); drag->setPixmap(pixmap); QPoint offset = dragStartPos - rect.topLeft(); drag->setHotSpot(offset); Qt::DropAction dropAction = drag->exec(Qt::MoveAction | Qt::IgnoreAction); if (dropAction != Qt::MoveAction) { DockTabWidget *newTabWidget = tab_widget->createAnotherTabWidget(); if (!newTabWidget->isInsertable(tab_widget, index)) { newTabWidget->deleteLater(); return; } DockTabWidget::moveTab(tab_widget, index, newTabWidget, 0); newTabWidget->setButtonsNewTabbar(0); newTabWidget->enableDisableToolButton(0); QRect newGeometry = newTabWidget->geometry(); newGeometry.moveTopLeft(QCursor::pos() - offset); newTabWidget->setGeometry(newGeometry); newTabWidget->show(); // Check if main pgAdmin4 application has only one tab then close tab bar. // Here - check for count 2 because tab will be deleted later. DockTabWidget *mainTab = DockTabWidget::getMainTabWidget(); if (mainTab != NULL && tab_widget != NULL && tab_widget == mainTab && mainTab->count() == 1) mainTab->tabBar()->setVisible(false); } tab_widget->deleteIfEmpty(); isStartingDrag = false; } // Actual tab drag started. void DockTabBar::dragEnterEvent(QDragEnterEvent *event) { if (DockTabWidget::eventIsTabDrag(event)) event->acceptProposedAction(); } // Drag event leave the actual area. void DockTabBar::dragLeaveEvent(QDragLeaveEvent * event) { Q_UNUSED(event) } // Drop event handler for tabbar. void DockTabBar::dropEvent(QDropEvent *event) { DockTabWidget *oldTabWidget = NULL; int oldIndex; DockTabWidget::decodeTabDropEvent(event, &oldTabWidget, &oldIndex); if (oldTabWidget && tab_widget && tab_widget->isInsertable(oldTabWidget, oldIndex)) { int newIndex = insertionIndexAt(event->pos()); DockTabWidget::moveTab(oldTabWidget, oldIndex, tab_widget, newIndex); // create new back/forward/close buttons and register its events. tab_widget->setButtonsNewTabbar(newIndex); tab_widget->enableDisableToolButton(newIndex); // Check if main pgAdmin4 application has only one tab then close tab bar. // Here - check for count 2 because tab will be deleted later. DockTabWidget *mainTab = DockTabWidget::getMainTabWidget(); if (mainTab != NULL && oldTabWidget != NULL && oldTabWidget == mainTab && mainTab->count() == 1) mainTab->tabBar()->setVisible(false); event->acceptProposedAction(); } }
#pragma once #include <gsl/span> #include <vector> #include "PticaGovorunCore.h" #include "VoiceActivity.h" namespace PticaGovorun { /// Parameters to sphinx_fe utility. struct SphinxVadParams { float WindowLength = 0.025625; // ms, -wlen, for SampleRate=16000 corresponds to 16k*this=410 samples int FrameRate = 100; // frames per second, for SampleRate=16000 corresponds to 16k/this=160 samples int PreSpeech = 20; // -vad_prespeech int PostSpeech = 50; // -vad_postspeech int StartSpeech = 10; // -vad_startspeech float VadThreashold = 2; // -vad_threshold }; struct ErrMsgList; /// Gets speech/silence regions for audio using Sphinx implementation. PG_EXPORTS bool detectVoiceActivitySphinx(gsl::span<const short> samples, float sampRate, const SphinxVadParams& vadArgs, std::vector<SegmentSpeechActivity>& activity, ErrMsgList* errMsg); }
#pragma once #include "../../Toolbox/Toolbox.h" #include "../Vector/Vector3.h" #include "../Matrix/Matrix4x4.h" // https://www.3dgep.com/understanding-quaternions/ namespace ae { /// \ingroup math /** * Represent a rotation around an axis in 3D space. */ class AERO_CORE_EXPORT Quaternion { public: /** Default constructor. */ Quaternion(); /** * Constructor with composante. * * @param _X The x part of the axis. * @param _Y The y part of the axis. * @param _Z The z part of the axis. * @param _W The amount of rotation around the axis. */ Quaternion( float _X, float _Y, float _Z, float _W ); /** * Constructor from Axis Angle. * * @param _Axis The axis to rotate around. * @param _Angle The angle in radians. */ Quaternion( const Vector3& _Axis, float _Angle); /** * Copy constructor. * * @param _Quat The other Quaternion. */ Quaternion( const Quaternion& _Quat ); /** * Multiplication with an other Quaternion. * Quaternion multiplication IS NOT commutative. * * @param _Quat The other Quaternion. */ inline void operator*=( const Quaternion& _Quat ); /** * Addition with an other Quaternion. * * @param _Quat The other Quaternion. */ inline void operator+=( const Quaternion& _Quat ); /** * Gets the conjugate of the Quaternion. * * @return The conjugate. */ Quaternion GetConjugate() const; /** * Gets the magnitude of the Quaternion. * * @return The magnitude of the Quaternion. */ float Length() const; /** * Gets the magnitude squared of the Quaternion. * * @return The magnitude of the Quaternion. */ float LengthSquared() const; /** * Make unit the Quaternion. */ void Normalise(); /** * Get a copy of the Quaternion but normalised. * * @return The Quaternion normalised. */ Quaternion GetNormalised() const; /** * Get the Quaternion matrix. * * @return Quaternion matrix. */ Matrix4x4 GetMatrix() const; /** * Get the Quaternion matrix transposed. * * @return Quaternion matrix transposed. */ Matrix4x4 GetTransposedMatrix() const; /** * Get the Axis with which the Quaternion turn around. * * @return The Quaternion axis. */ Vector3 GetAxis() const; /** * Get Euler rotation of the Quaternion. * * @return The Euler rotation. */ Vector3 GetEulerAngle() const; /** * Get the angle of the Quaternion. * * @return The angle in radians. */ float GetAngle() const; public: /** The x coordinate. */ float X; /** The y coordinate. */ float Y; /** The z coordinate. */ float Z; /** The amount of rotation. */ float W; /** The zero Quaternion. ( x = 0, y = 0, z = 0, w = 0 ) */ static const Quaternion Zero; /** The Quaternion identity. ( x = 0, y = 0, z = 0, w = 1 ) */ static const Quaternion Identity; }; /** * Multiplication between two Quaternion. * Quaternion multiplication IS NOT commutative. * * @param _Quat1 The first Quaternion to multiply. * @param _Quat2 The second Quaternion to multiply. * * @return The result of the multiplication. */ AERO_CORE_EXPORT inline Quaternion operator*( const Quaternion& _Quat1, const Quaternion& _Quat2 ); /** * Addition between two Quaternion. * * @param _Quat1 The Quaternion value. * @param _Quat2 Quaternion to add to it. * * @return The result of the addition. */ AERO_CORE_EXPORT inline Quaternion operator+( const Quaternion& _Quat1, const Quaternion& _Quat2 ); } // ae
#pragma once #include <iberbar/Paper2d/Node.h> namespace iberbar { namespace RHI { class ITexture; } namespace Renderer { class CTrianglesCommand; } namespace Paper2d { class __iberbarPaper2dApis__ CGridTerrain : public CNode { public: struct UGridPaletteNode { CColor4B Color; CRect2f rcTexCoord; }; public: CGridTerrain(); virtual ~CGridTerrain(); protected: CGridTerrain( const CGridTerrain& terrain ); public: virtual CGridTerrain* Clone() const override; virtual void Init() override; virtual void UpdateTransform() override; virtual void DrawSelf( CDrawContext* pContext ) override; public: void SetGridSize( float nWidth, float nHeight ); void SetGrids( int nGridRow, int nGridCol, const UGridPaletteNode* pPalette, int nPaletteSize, const int* pGrids ); void SetTexture( RHI::ITexture* pTexture ); int GetGridRow() { return m_nGridRow; } int GetGridCol() { return m_nGridCol; } protected: void BuildGrids( const UGridPaletteNode* pPalette, int nPaletteSize, const int* pGrids ); void BuildGrids(); protected: int m_nGridRow; int m_nGridCol; CSize2f m_GridSize; RHI::ITexture* m_pTexture; void* m_pVertices; uint16* m_pIndices; Renderer::CTrianglesCommand* m_pRenderCommand; }; } }
#pragma once /* watchdog callback: resets the hardware timer if a "read" action over ble is done */ // watchdog switch. true for enable, false for disable bool enable_wd = false; const int wdtTimeout = 120000; //time in ms to trigger the watchdog hw_timer_t *timer = NULL; // initialise hardware timer // reboot esp void IRAM_ATTR resetModule() { ets_printf("reboot\n"); esp_restart(); } // manage what happens on read of watchdog charactericstic // reset hardware timer on read of watchdog characteristic class watchdogCallback: public BLECharacteristicCallbacks { void onRead(BLECharacteristic *pCharacteristic) { if (enable_wd==true){ timerWrite(timer, 0); } } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_RICH_MENU_WINDOW_H #define OP_RICH_MENU_WINDOW_H #include "adjunct/quick_toolkit/windows/DesktopWindow.h" #include "adjunct/quick_toolkit/widgets/OpToolbar.h" class OpWidget; class OpRichMenuToolbar : public OpToolbar { public: static OP_STATUS Construct(OpRichMenuToolbar** toolbar); // == OpInputContext ====================== BOOL IsInputContextAvailable(FOCUS_REASON reason) { return TRUE; } }; /** Popup menu using a vertical toolbar for its contents. */ class OpRichMenuWindow : public DesktopWindow { public : class Listener { public: virtual ~Listener() {} virtual void OnMenuClosed() {}; }; /** Widget will animate if the style is set to OpWindow::STYLE_NOTIFIER. */ OP_STATUS Construct(const char *toolbar_name, OpWindow::Style style = OpWindow::STYLE_POPUP); OpRichMenuWindow(OpWidget *owner, DesktopWindow* parent_window); virtual ~OpRichMenuWindow(); /** Show menu and call back to the given listener. */ void Show(Listener &listener); /** Close menu. Will call listeners OnMenuClosed. Use this method instead of DesktopWindow::Close! */ void CloseMenu(); OpWidget* GetToolbarWidgetOfType(OpTypedObject::Type type); // DesktopWindow methods virtual void OnLayout(); virtual void OnShow(BOOL show); virtual void OnClose(BOOL user_initiated); virtual void Close(BOOL immediately = FALSE, BOOL user_initiated = FALSE, BOOL force = TRUE); virtual const char* GetWindowName() { return "Rich Menu Window"; } // OpInputContext virtual BOOL IsInputContextAvailable(FOCUS_REASON reason) { return TRUE; } virtual const char* GetInputContextName() {return "Rich Menu Window";} private: void Animate(BOOL show); private: BOOL m_close_on_complete; BOOL m_animate; OpRichMenuToolbar *m_toolbar; OpWidget *m_owner; Listener *m_listener; DesktopWindow* m_parent_window; }; #endif // OP_RICH_MENU_WINDOW_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/QuickBrowserView.h" #include "adjunct/desktop_pi/DesktopOpWindow.h" #include "adjunct/quick_toolkit/windows/DesktopWindow.h" DEFINE_CONSTRUCT(BrowserView); OP_STATUS BrowserView::Init() { RETURN_IF_ERROR(OpBrowserView::Init()); if (GetParentDesktopWindow() != NULL) RETURN_IF_ERROR(GetParentDesktopWindow()->AddListener(this)); return OpStatus::OK; } void BrowserView::OnDesktopWindowClosing(DesktopWindow* desktop_window, BOOL user_initiated) { OP_ASSERT(desktop_window == GetParentDesktopWindow() || GetParentDesktopWindow() == NULL); OpBrowserView::OnDeleted(); } void BrowserView::OnAdded() { OpBrowserView::OnAdded(); GetOpWindow()->Show(TRUE); if (m_listener != NULL) m_listener->OnBrowserViewReady(*this); } void BrowserView::OnRemoved() { OpBrowserView::OnRemoved(); GetOpWindow()->Show(FALSE); } void BrowserView::OnDeleted() { OpBrowserView::OnDeleted(); if (GetParentDesktopWindow() != NULL) GetParentDesktopWindow()->RemoveListener(this); }
#include "../User.h" #define PROCESS(name, Name, type, parameterType) \ User::Builder& User::Builder::set##Name(parameterType name) { \ m_##name = name;\ return *this; \ } #include "UserBuilderXMacros.h" #undef PROCESS User User::Builder::build() const { User user; #define PROCESS(name, Name, type, parameterType) user.set##Name(m_##name); #include "UserBuilderXMacros.h" #undef PROCESS return user; }
#include "color.h" const Color Color::INVISIBLE(0,0,0,0); Color::Color() : _red(255), _green(0), _blue(0), _alpha(0) {} Color::Color(const unsigned char red, const unsigned char green, const unsigned char blue) :Color(red, green, blue, 255) {} Color::Color(const unsigned char red, const unsigned char green, const unsigned char blue, const unsigned char alpha) :_red(red), _green(green), _blue(blue), _alpha(alpha) {} const unsigned char Color::get_red() const { return _red; } const unsigned char Color::get_green() const { return _green; } const unsigned char Color::get_blue() const { return _blue; } const unsigned char Color::get_alpha() const { return _alpha; } int Color::to_raw() const { return (_red << 24) | (_green << 16) | (_blue << 8) | _alpha; } int Color::to_bgra_raw() const { return (_blue << 24) | (_green << 16) | (_red << 8) | _alpha; } const Color Color::operator=( Color rhs) { this->_red = rhs._red; this->_green = rhs._green; this->_blue = rhs._blue; this->_alpha = rhs._alpha; return *this; }
/* * typedefs.h * * Created on: Mar 4, 2015 * Author: robmrk */ #ifndef TYPEDEFS_H_ #define TYPEDEFS_H_ #include "defines.h" #include <omp.h> #include <iostream> #include <cstdlib> #include <cstddef> #include <cctype> #include <iomanip> #include <cmath> #include <cstring> #include <fstream> #include <cassert> #include <string> #include <sstream> #include <algorithm> #include "matrix.h" #include "matrixIO.h" #include <vector> using std::vector; //Numerical recipes type definitions for Amoeba/Golden typedef std::vector<int> VecInt, VecInt_O, VecInt_IO; typedef const std::vector<int> VecInt_I; typedef std::vector<double> VecDoub, VecDoub_O, VecDoub_IO; typedef const std::vector<double> VecDoub_I; typedef Numeric_lib::Matrix<int, 2> MatInt, MatInt_O, MatInt_IO; typedef const Numeric_lib::Matrix<int, 2> MatInt_I; typedef Numeric_lib::Matrix<double, 2> MatDoub, MatDoub_O, MatDoub_IO; typedef const Numeric_lib::Matrix<double, 2> MatDoub_I; typedef Numeric_lib::Matrix<double, 3> Mat3Doub; typedef Numeric_lib::Matrix<double, 4> Mat4Doub; typedef Numeric_lib::Matrix<double, 5> Mat5Doub; enum COUNTRYID { C1 = 0, C2 = 1 }; #endif /* TYPEDEFS_H_ */
#include <bits/stdc++.h> #define ll long long #define ull unsigned long long #define FOR(i,n) for(ll i=0;i<n;i++) #define FOR1(i,n) for(ll i=1;i<n;i++) #define FORn1(i,n) for(ll i=1;i<=n;i++) #define FORmap(i,mp) for(auto i=mp.begin();i!=mp.end();i++) #define vll vector<ll> #define vs vector<string> #define pb(x) push_back(x) #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define mod 1000000007 using namespace std; int main() { // your code goes here fast; ll t; cin>>t; while(t--) { ll n,k; cin>>n>>k; ll a[n]; FOR(i,n) cin>>a[i]; if(k<=n) { FOR(i,n/2) { if((n-i-1)<k) { ll tmp=a[i]; a[i]^=a[n-i-1]; a[n-i-1]=tmp; } else if(i<k) { a[i]^=a[n-i-1]; } } if((n&1) && (n/2)<k) a[n/2]=0; } else { ll x=k/n; //cout<<x<<" "; x%=3; FOR(i,n/2) { FOR(j,x) { ll tmp=a[i]; a[i]^=a[n-i-1]; a[n-i-1]=tmp; } } if((n&1)) a[n/2]=0; x=k%n; if(x!=0) { FOR(i,n/2) { if(i<x && (n-i-1)<x) { ll tmp=a[i]; a[i]^=a[n-i-1]; a[n-i-1]=tmp; } else if(i<x) { a[i]^=a[n-i-1]; } } } } FOR(i,n) cout<<a[i]<<" "; cout<<endl; } return 0; }
/* BEGIN LICENSE */ /***************************************************************************** * SKFind : the SK search engine * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: unicodemodule.cpp,v 1.1.2.2 2005/02/17 15:29:24 krys Exp $ * * Authors: Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #include <skcore/skcore.h> #include "unicodesimplifier.h" SKERR skStringUnicodeSimplifier::CreateUnicodeSimplifier(const char* pszParam, SKRefCount** ppInstance) { SK_ASSERT(NULL != pszParam); SK_ASSERT(NULL != ppInstance); if(!pszParam || !ppInstance) return err_invalid; *ppInstance = NULL; skPtr<skStringUnicodeSimplifier> pSimp; *pSimp.already_AddRefed() = sk_CreateInstance(skStringUnicodeSimplifier) (pszParam); if(!pSimp) return err_memory; *ppInstance = pSimp; (*ppInstance)->AddRef(); return noErr; } /* // Module static SKComponentData_t g_ComponentData[] = { {"simplifier", "unicode", CreateUnicodeSimplifier}, {NULL, NULL, NULL} }; extern "C" { void SKAPI SKModuleInitialize(SKEnvir *pEnv, SKFactory *pFactory) { SKEnvir::SetEnvir(pEnv); SKFactory::SetFactory(pFactory); } SKAPI SKComponentData_t *SKModuleGetComponentData() { return g_ComponentData; } } */
#include "_pch.h" #include "MObjCatalog.h" using namespace wh; using namespace wh::object_catalog; using namespace wh::object_catalog::model; //------------------------------------------------------------------------- //------------------------------------------------------------------------- MPathItem::MPathItem(const char option) :TModelData<T_Data>(option) { } //------------------------------------------------------------------------- bool MPathItem::LoadThisDataFromDb(std::shared_ptr<whTable>& table, const size_t row) { T_Data data; if (table->GetColumnCount()>2) { data.mObj.mId = table->GetAsString(0, row); data.mObj.mLabel = table->GetAsString(1, row); data.mCls.mId = table->GetAsString(2, row ); data.mCls.mLabel = table->GetAsString(3, row); SetData(data); return true; } else { data.mCls.mId = table->GetAsString(0, row); data.mCls.mLabel = table->GetAsString(1, row); SetData(data); return true; } return false; }; //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- bool MPath::GetSelectChildsQuery(wxString& query)const { auto catalog = dynamic_cast<MObjCatalog*>(this->GetParent()); if (!catalog) return false; const auto& root = catalog->GetRoot(); if (catalog->IsObjTree()) { query = wxString::Format( "SELECT oid, otitle, cid, ctitle " " FROM get_path_obj_info(%s)" , root.mObj.mId.SqlVal() ); return true; } if (catalog->IsClsTree()) { query = wxString::Format( "SELECT id, title " " FROM get_path_cls_info(%s)" , root.mCls.mId.SqlVal() ); return true; } return false; } //------------------------------------------------------------------------- wxString MPath::GetPathStr()const { auto catalog = dynamic_cast<MObjCatalog*>(GetParent()); if (!catalog) return "**error**"; wxString str_path = "/"; unsigned int qty = GetChildQty(); if (qty > 0 && catalog->GetData().mHideSystemRoot) qty -= 1; for (unsigned int i = qty; i > 0; i--) { auto node = std::dynamic_pointer_cast<MPathItem>(GetChild(i - 1)); if (catalog->IsObjTree()) { str_path += wxString::Format("[%s]%s/" , node->GetData().mCls.mLabel.toStr() , node->GetData().mObj.mLabel.toStr() ); } else { str_path += wxString::Format("%s/" , node->GetData().mCls.mLabel.toStr()); } } return str_path; } //------------------------------------------------------------------------- wxString MPath::GetLastItemStr()const { auto catalog = dynamic_cast<MObjCatalog*>(GetParent()); if (!catalog) return "**error**"; wxString str_path = "/"; unsigned int qty = GetChildQty(); unsigned int skip_root = catalog->GetData().mHideSystemRoot ? 1 : 0; if (qty>skip_root) { auto node = std::dynamic_pointer_cast<MPathItem>(GetChild(0)); if (catalog->IsObjTree()) { str_path = wxString::Format("../[%s]%s" , node->GetData().mCls.mLabel.toStr() , node->GetData().mObj.mLabel.toStr() ); } else { str_path = wxString::Format("../%s" , node->GetData().mCls.mLabel.toStr()); } } return str_path; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- ClsPathItem::ClsPathItem(const char option) :TModelData<T_Data>(option) { } //------------------------------------------------------------------------- bool ClsPathItem::LoadThisDataFromDb(std::shared_ptr<whTable>& table, const size_t row) { T_Data data; data.mId = table->GetAsString(0, row); data.mLabel= table->GetAsString(1, row ); SetData(data); return true; }; //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- bool ClsPath::GetSelectChildsQuery(wxString& query)const { auto cls = dynamic_cast<object_catalog::MTypeItem*>(this->GetParent()); if (cls) { const auto& cls_data = cls->GetData(); query = wxString::Format( "SELECT id, title " " FROM get_path_cls_info(%s)" , cls_data.mId.SqlVal() ); return true; } return false; } //------------------------------------------------------------------------- wxString ClsPath::AsString()const { wxString str_path = "/"; unsigned int qty = GetChildQty(); for (unsigned int i = qty; i > 0; i--) { auto node = std::dynamic_pointer_cast<ClsPathItem>(GetChild(i - 1)); str_path += wxString::Format("%s/", node->GetData().mLabel.toStr() ); } return str_path; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- ObjPathItem::ObjPathItem(const char option) :TModelData<T_Data>(option) { } //------------------------------------------------------------------------- bool ObjPathItem::LoadThisDataFromDb(std::shared_ptr<whTable>& table, const size_t row) { T_Data data; data.mObj.mId = table->GetAsString(0, row); data.mObj.mLabel = table->GetAsString(1, row); data.mCls.mId = table->GetAsString(2, row); data.mCls.mLabel = table->GetAsString(3, row); SetData(data); return true; }; //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- bool ObjPath::GetSelectChildsQuery(wxString& query)const { auto obj = dynamic_cast<object_catalog::MObjItem*>(this->GetParent()); if (obj) { const auto& obj_data = obj->GetData(); query = wxString::Format( "SELECT oid, otitle, cid, ctitle " " FROM get_path_obj_info(%s)" , obj_data.mParent.mId.IsNull() ? "0" : obj_data.mParent.mId.toStr() ); return true; } return false; } //------------------------------------------------------------------------- wxString ObjPath::AsString()const { wxString str_path = "/"; unsigned int qty = GetChildQty(); for (unsigned int i = qty; i > 0; i--) { auto node = std::dynamic_pointer_cast<ObjPathItem>(GetChild(i - 1)); str_path += wxString::Format("[%s]%s/" , node->GetData().mCls.mLabel.toStr() , node->GetData().mObj.mLabel.toStr() ); } return str_path; }
////////////////////////////////////////////////////////////////////// ///Copyright (C) 2011-2012 Benjamin Quach // //This file is part of the "Lost Horizons" video game demo // //"Lost Horizons" is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "areaofeffect.h" #define AOE_TIME 500 areaofeffect::areaofeffect(irr::IrrlichtDevice *graphics, vector3df &pos, int radius, int maxdamage, int mindamage): graphics(graphics), pos(pos), radius(radius), maxdamage(maxdamage), mindamage(mindamage) { //initialize variables this->time = graphics->getTimer()->getTime()+AOE_TIME; } areaofeffect::~areaofeffect() { } void areaofeffect::drop() { delete this; }
#include <iostream> #include <string> #include <vector> using namespace std; void reverseStr(string& str) { int n = str.length(); for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } string multiply(string num1, string num2) { int len1 = num1.size(); int len2 = num2.size(); if (len1 == 0 || len2 == 0) return "0"; vector<int> result(len1 + len2, 0); int i_n1 = 0; int i_n2 = 0; for (int i=len1-1; i>=0; i--) { int carry = 0; int n1 = num1[i] - '0'; i_n2 = 0; for (int j=len2-1; j>=0; j--) { int n2 = num2[j] - '0'; int sum = n1*n2 + result[i_n1 + i_n2] + carry; carry = sum/10; result[i_n1 + i_n2] = sum % 10; i_n2++; } if (carry > 0) result[i_n1 + i_n2] += carry; i_n1++; } int i = result.size() - 1; while (i>=0 && result[i] == 0) i--; if (i == -1) return "0"; string s = ""; while (i >= 0) s +=char(result[i--])+'0'; return s; } string fsum(string str1, string str2) { if(str1.length()>str2.length()) swap(str1,str2); string str=""; int n1=str1.length(),n2=str2.length(); reverseStr(str1); reverseStr(str2); int carry=0; for (int i=0; i<n1; i++) { int sum = ((str1[i]-'0')+(str2[i]-'0')+carry); str.push_back(sum%10 + '0'); carry = sum/10; } for (int i=n1; i<n2; i++) { int sum = ((str2[i]-'0')+carry); str.push_back(sum%10 + '0'); carry = sum/10; } if (carry) str.push_back(carry+'0'); reverseStr(str); return str; } int main() { string str1,str2; cin>>str1>>str2; cout<<fsum(str1,str2)<<'\n'; cout<<multiply(str1,str2)<<'\n'; }
#include "monitor_connection_p.hpp" #include "server_p.hpp" #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" #include <boost/bind.hpp> namespace ioremap { namespace thevoid { monitor_connection::monitor_connection(boost::asio::io_service &io_service) : m_io_service(io_service), m_socket(io_service) { } monitor_connection::~monitor_connection() { } monitor_connection::socket_type &monitor_connection::socket() { return m_socket; } void monitor_connection::start(const std::shared_ptr<base_server> &) { async_read(); } std::string monitor_connection::get_information() { rapidjson::MemoryPoolAllocator<> allocator; rapidjson::Value information; information.SetObject(); information.AddMember("active-connections", get_connections_counter(), allocator); rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); information.Accept(writer); buffer.Put('\n'); return std::string(buffer.GetString(), buffer.GetSize()); } void monitor_connection::async_read() { m_socket.async_read_some(boost::asio::buffer(m_buffer), std::bind(&monitor_connection::handle_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } void monitor_connection::handle_read(const boost::system::error_code &err, std::size_t bytes_transferred) { if (err || bytes_transferred < 1) { close(); return; } switch (m_buffer[0]) { case 'i': case 'I': async_write(get_information()); break; case 's': case 'S': async_write("not supported yet\n"); break; case 'h': case 'H': async_write("i - statistics information\n" "s - stop server\n" "h - this help message\n"); break; } } void monitor_connection::async_write(const std::string &data) { m_storage = data; boost::asio::async_write(m_socket, boost::asio::buffer(m_storage), std::bind(&monitor_connection::handle_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } void monitor_connection::handle_write(const boost::system::error_code &, size_t) { close(); } void monitor_connection::close() { // gratefull shutdown boost::system::error_code ignored_ec; m_socket.shutdown(boost::asio::socket_base::shutdown_both, ignored_ec); } } // namespace thevoid } // namespace ioremap
#include<iostream> using namespace std; int arr[1000001]; int n,k; void kflip() { int max=-1; int l=0,r=0,start=0,end=0,z=0; while(l<=r && r!=n) { if(arr[r]==1) { int c=r-l+1; if(c>max) { max=c; start=l; end=r; } } else if(arr[r]==0) {int c; if(z<=k) { z=z+1; c=r-l+1; } while(z>k) { if(arr[l]==0) z--; l++; } //z++; c=r-l+1; if(c>max) { max=c; start=l; end=r; } } r++; } cout<<max<<endl; cout<<start<<" "<<end<<endl; } int main() { cin>>n; cin>>k; for(int i=0;i<n;i++) cin>>arr[i]; kflip(); return 0; }
#ifndef SIMCONSTANTS_H #define SIMCONSTANTS_H namespace Simulation { // Universe size static const float MIN_XY_WORLDPOS = -10000.0f; static const float MAX_XY_WORLDPOS = 10000.0f; // Universe content static const int MAX_WORLDS = 1000; static const int MAX_SOLARSYSTEMS = 500; static const int MAX_WORLDS_PER_SOLARSYSTEM = 10; static const int MIN_WORLDS_PER_SOLARSYSTEM = 2; static const int MAX_UNIQUE_NAMES = 1000; // Generator static const float MIN_SOLARSYSTEM_DISTANCE = 100.0f; // Population enum Species { Human, Orcish, Elvish, Reptillian }; static const unsigned int SPECIES_MAX = 4; static const long HIGH_POPULATION = 1234908; static const long MED_POPULATION = 125922; static const long LOW_POPULATION = 15312; static const long POP_PER_TRADEHUB = 10000; static const long POP_PER_SPACESTATION = 100000; // Planet orbits static const int ORBIT_BASESIZE = 10; static const float ORBIT_BASESPEED = 1.0f; static const int ORBIT_INC_X = 5; static const int ORBIT_INC_Y = 5; } #endif
// // Created by stanislav on 23.11.18. // #include <iostream> #include <array> using namespace std; int main() { int n = 0; cin >> n; int arr[n]; for (int i = 0; i < n; ++i) { cin >> arr[i]; } int count=0; int indexlS=0; int lastseqLengh=0; for (int j = 0; j < n; ++j) { if (arr[j] == arr[j + 1]) { count++; indexlS=j; lastseqLengh=count; }else if(arr[j]!=arr[j+1]){ count=0; } } for (int k = 0; k <= lastseqLengh; ++k) { cout<<" "<<arr[indexlS]; } }
/* This file is part of SMonitor. Copyright 2015~2016 by: rayx email rayx.cn@gmail.com SMonitor 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. SMonitor 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ #include "stdafx.h" #include "CPushButton.h" #include <QPainter> #include <QFontDatabase> #include <QFontMetrics> #include <QMouseEvent> #include <QFile> #include "CMisc.h" CPushButton::CPushButton(const QChar& fchar, const QString& text, QWidget *parent) : QPushButton(parent) , m_btnIconChar(fchar) , m_btnText(text) , m_curState(Normal) { setFlat(true); setCheckable(true); //setFixedSize(100, 120); setObjectName("sideBarButton"); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); m_btnIconFont = CMisc::FontAwesome(28); QFontMetrics metricsIcon(m_btnIconFont); m_btnIconCharSize = metricsIcon.size(Qt::TextSingleLine, m_btnIconChar); m_btnTextFont = QFont("Microsoft yahei", 10); QFontMetrics metricsText(m_btnTextFont); m_btnTextSize = metricsText.size(Qt::TextSingleLine, m_btnText); } CPushButton::~CPushButton() { } void CPushButton::setState(State state) { m_curState = state; update(); } QLinearGradient CPushButton::linearGraident(State state) { QLinearGradient linear(0, 0, 0, 1); switch(state) { case Normal: { linear.setColorAt(0, QColor(27, 137, 202)); linear.setColorAt(1, QColor(16, 119, 181)); } break; case Enter: { linear.setColorAt(0, QColor(12, 98, 162)); linear.setColorAt(1, QColor(13, 94, 154)); } break; case Pressed: { linear.setColorAt(0, QColor(5, 59, 101)); linear.setColorAt(1, QColor(5, 58, 98)); } break; case Disable: break; default: break; } return linear; } void CPushButton::enterEvent(QEvent *) { setState(Enter); } void CPushButton::leaveEvent(QEvent *) { setState(Normal); } void CPushButton::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { setState(Pressed); } QPushButton::mousePressEvent(event); } void CPushButton::mouseReleaseEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton && !this->isChecked()) { setState(Normal); } QPushButton::mouseReleaseEvent(event); } void CPushButton::paintEvent(QPaintEvent* event) { QPushButton::paintEvent(event); QPainter painter(this); //计算图标所在的矩形 QRect iconRect = QRect(rect().center().x() - m_btnIconCharSize.rwidth() / 2, rect().center().y() - m_btnIconCharSize.rheight() / 2 - 12, m_btnIconCharSize.rwidth(), m_btnIconCharSize.rheight()); //计算文字所在的矩形 QRect textRect = QRect(rect().center().x() - m_btnTextSize.rwidth() / 2, rect().center().y() + 12, m_btnTextSize.rwidth(), m_btnTextSize.rheight()); QLinearGradient linear = linearGraident(m_curState); QColor color = QColor(Qt::white); if(isChecked()) { linear = linearGraident(Pressed); color = QColor(44, 162, 252); } //绘制背景色 painter.setPen(Qt::NoPen); painter.setBrush(QBrush(linear)); painter.drawRect(rect()); //绘制下部分割线 painter.setPen(QColor(12, 101, 169)); painter.drawLine(rect().bottomLeft(), rect().bottomRight()); //绘制图标 painter.setPen(QPen(color, 1)); painter.setFont(m_btnIconFont); painter.drawText(iconRect,m_btnIconChar); //绘制文字 painter.setPen(QPen(color, 1)); painter.setFont(m_btnTextFont); painter.drawText(textRect, m_btnText); }
#include <iostream> #include <vector> #include "Utils.h" using namespace std; using namespace utils; template <class Iterator, typename CollectionType> void IsHeap(Iterator last, std::vector<CollectionType> const& collection) { if (last == end(collection)) { cout << "This collection is a heap" << endl << endl; } else { cout << "Failed at item = " << *last << endl << endl; }; } int main() { cout << "--------------------------------------------------" << endl; cout << "Collection One: (Collection is not a heap) : "; std::vector<int> collectionOne {1, 2, 3, 4, 5}; PrintCollection(collectionOne); auto lastOne = std::is_heap_until(begin(collectionOne), end(collectionOne)); IsHeap(lastOne, collectionOne); cout << "--------------------------------------------------" << endl; cout << "Collection Two: (Collection is a heap) : "; std::vector<int> collectionTwo {9, 8, 7, 6, 4}; PrintCollection(collectionTwo); auto lastTwo = std::is_heap_until(begin(collectionTwo), end(collectionTwo)); IsHeap(lastTwo, collectionTwo); cout << "--------------------------------------------------" << endl; cout << "Collection Three: (Collection with only 1 element) : "; std::vector<int> collectionThree {1}; PrintCollection(collectionThree); auto lastThree = std::is_heap_until(begin(collectionThree), end(collectionThree)); IsHeap(lastThree, collectionThree); cout << "--------------------------------------------------" << endl; cout << "Collection Four: (Collection with no elements) : "; std::vector<int> collectionFour {}; PrintCollection(collectionFour); auto lastFour = std::is_heap_until(begin(collectionFour), end(collectionFour)); IsHeap(lastFour, collectionFour); return 0; }
#include<iostream> using namespace std; class Simple { public: Simple() {mIntPtr=new int();} ~Simple() {delete mIntPtr;} void setIntPtr(int inInt) {*mIntPtr=inInt;} void go() {cout<<"Hello there "<<endl;} protected: int* mInPtr; }; void doSomething(Simple*& outSimplePtr) { outSimplePtr=new Simple();//Bug,doesn't delete . } int main(int argc,char** argv) { Simple* simplePtr=new Simple(); doSomething(simplePtr); delete simplePtr;//Only cleans up the second object. }
/*In this lets see about pointer in class concept in C++ Program.*/ /*pointer to a c++ class is as same as the conceptof pointer to a Structure.*/ /*to access member of a pointer to a class member access operator -> has used*/ /*including preprocessor / headerfile in the program*/ #include <iostream> #include <string> /*using namespace*/ using namespace std ; /*creating a class named Student for this program*/ /*MAIN CLASS of the program*/ class Student { public: string Name; int RollNo; int MobileNo; void PrintStudent(); // Defining a constructor with an Parameter in this pointer Student ( string Name , int RollNo , int MobileNo ) { this->Name = Name ; this->RollNo = RollNo ; this->MobileNo = MobileNo ; } }; /*Defining a member function.*/ void Student :: PrintStudent() { cout<<"\nThe student Name is : " << Name << endl ; cout<<"\nThe student RollNo is : " << RollNo << endl ; cout<<"\nThe student MobileNo is : " << MobileNo << endl ; } /*creating a main() function of the program*/ int main( void ) { /*creating Object called student1 and student2 for the class Student*/ Student student1 = Student ( "Maayon" , 1001001 , 1010101010 ) ; Student student2 = Student ( "Tech Guru", 1011011 , 1212121212 ) ; /*Declaring a pointer variable to access the class*/ Student *ptrStudent ; /*assigning the object to the pointer variable.*/ ptrStudent = &student1; /*Accessing the member function of a class using pointer variable with the help of member access operator*/ ptrStudent->PrintStudent ( ) ; /*assigning the object to the pointer variable.*/ ptrStudent = &student2; /*Accessing the member function of a class using pointer variable with the help of member access operator*/ ptrStudent->PrintStudent ( ) ; }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ // GDCM #include <gdcmWriter.h> // fwComEd #include <fwComEd/fieldHelper/MedicalImageHelpers.hpp> #include <fwComEd/Dictionary.hpp> // fwData #include <fwData/Point.hpp> #include <fwData/PointList.hpp> #include <fwData/String.hpp> #include "gdcmIO/writer/DicomSRWriter.hpp" #include "gdcmIO/writer/DicomLandmarkWriter.hpp" #include "gdcmIO/writer/DicomDistanceWriter.hpp" #include "gdcmIO/helper/GdcmHelper.hpp" #include "gdcmIO/DicomDictionarySR.hpp" namespace gdcmIO { namespace writer { //------------------------------------------------------------------------------ DicomSRWriter::DicomSRWriter() { SLM_TRACE_FUNC(); // Instantiate genereic GDCM writer this->setWriter( ::boost::shared_ptr< ::gdcm::Writer >( new ::gdcm::Writer ) ); } //------------------------------------------------------------------------------ DicomSRWriter::~DicomSRWriter() { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ void DicomSRWriter::write() throw (::fwTools::Failed) { SLM_TRACE_FUNC(); ::fwData::Image::sptr image = this->getConcreteObject(); SLM_ASSERT("fwData::Image not instanced", image); ::boost::shared_ptr< DicomInstance > dicominstance = this->getDicomInstance(); SLM_ASSERT("gdcmIO::DicomInstance not instanced", dicominstance); //***** Handled SR content *****// ::gdcm::DataSet & gDsRoot = this->getWriter()->GetFile().GetDataSet(); //***** Handled Landmarks *****// ::fwData::PointList::sptr pl; pl = image->getField< ::fwData::PointList >( fwComEd::Dictionary::m_imageLandmarksId ); if (pl && pl->getPoints().size() > 0) { DicomLandmarkWriter landmarkWriter; landmarkWriter.setObject(image); landmarkWriter.setDicomInstance( dicominstance ); try {// Write landmark in the content sequence of root landmarkWriter.write(gDsRoot); } catch(::fwTools::Failed & e) { std::stringstream sStr; sStr.str(""); sStr << "Landmark writing error : " << e.what(); throw ::fwTools::Failed(sStr.str()); } } //***** Handled distances *****// if (image->getField( fwComEd::Dictionary::m_imageDistancesId )) { DicomDistanceWriter distanceWriter; distanceWriter.setObject(image); distanceWriter.setDicomInstance( dicominstance ); try {// Write distance in the content sequence of root distanceWriter.write(gDsRoot); } catch(::fwTools::Failed & e) { std::stringstream sStr; sStr.str(""); sStr << "Distance writing error : " << e.what(); throw ::fwTools::Failed(sStr.str()); } } //***** Handled SR document *****// this->writeSRDocumentSeries(); this->writeSRDocumentGeneral(); // Add missing attributes // Manufacturer helper::GdcmData::setTagValue<0x0008,0x0070>("IRCAD", gDsRoot); // Type 2 (eg : VRMed or IRCAD or ?) OSLM_TRACE("Manufacturer : "<<""); // 0008 0090 PN 1 Referring Physician Name helper::GdcmData::setTagValue<0x0008,0x0090>("", gDsRoot); // Type 2 OSLM_TRACE("Referring Physician Name : "<<""); //***** Complete the file *****// // Set the instance to SR document ::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance(); dicomInstance->setSOPClassUID( ::gdcm::MediaStorage::GetMSString( ::gdcm::MediaStorage::ComprehensiveSR ) ); ::gdcm::UIDGenerator gUIDgen; gUIDgen.SetRoot( dicomInstance->getSOPClassUID().c_str() ); dicomInstance->setSOPInstanceUID( gUIDgen.Generate() ); //***** Write the file *****// DicomInstanceWriter< ::fwData::Image >::write(); } //------------------------------------------------------------------------------ void DicomSRWriter::writeSRDocumentSeries() { SLM_TRACE_FUNC(); ::gdcm::DataSet & gDsRoot = this->getDataSet(); // Modality (will be written by DicomInstanceWriter) ::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance(); dicomInstance->setModality("SR"); // Series Instance UID (0020,000E) // (Already written by DicomSeriesWriter) // Series Number (0020,0011) // (Already written by DicomSeriesWriter) // Have to be checked ? // Referenced Performed Procedure Step Sequence (0008,1111) // Type 2 { ::gdcm::SmartPointer< ::gdcm::SequenceOfItems > gSqProcedure = new ::gdcm::SequenceOfItems(); gSqProcedure->SetLengthToUndefined(); helper::GdcmData::insertSQ<0x0008,0x1111>(gSqProcedure, gDsRoot); // Referenced Performed Procedure Step Sequence } } //------------------------------------------------------------------------------ void DicomSRWriter::writeSRDocumentGeneral() { SLM_TRACE_FUNC(); ::gdcm::DataSet & gDsRoot = this->getDataSet(); // Instance Number (0020,0013) this->getDicomInstance()->setInstanceNumber("1"); const ::boost::posix_time::ptime now = ::boost::posix_time::second_clock::local_time(); const std::string currentDateAndTime = ::boost::posix_time::to_iso_string(now); const size_t pos = currentDateAndTime.find("T"); // "T" is the separator between date and time const std::string date = currentDateAndTime.substr(0, pos); const std::string time = currentDateAndTime.substr(pos+1); // Content Date helper::GdcmData::setTagValue<0x0008,0x0023>(date, gDsRoot); OSLM_TRACE("Content date : "<<date); // Content Time helper::GdcmData::setTagValue<0x0008,0x0033>(time, gDsRoot); OSLM_TRACE("Content time : "<<time); // Type value helper::GdcmData::setTagValue<0x0040,0xa040>(DicomDictionarySR::getTypeString(DicomDictionarySR::CONTAINER), gDsRoot); // Continuity of content (landmarks and distances are separated) // NOTE : Continuity is fixed to SEPARATE because it provides a better compatibility. helper::GdcmData::setTagValue<0x0040,0xa050>(DicomDictionarySR::getContinuityString(DicomDictionarySR::SEPARATE), gDsRoot); // Performed Procedure Code Sequence (0040,A372) // Type 2 ::gdcm::SmartPointer< ::gdcm::SequenceOfItems > gSqProcedure = new ::gdcm::SequenceOfItems(); gSqProcedure->SetLengthToUndefined(); { // CID 7000 ?? } helper::GdcmData::setSQ<0x0040,0xa372>(gSqProcedure, gDsRoot); // Performed Procedure Code Sequence // Completion flag helper::GdcmData::setTagValue<0x0040,0xa491>("PARTIAL", gDsRoot); // Set to COMPLETE? // Verification Flag const std::string verifFlag = "UNVERIFIED"; // Set to VERIFIED? helper::GdcmData::setTagValue<0x0040,0xa493>(verifFlag, gDsRoot); /* if (verifFlag == "VERIFIED") { // Verifying Observer Sequence (0040,A073) // >Verifying Observer Name (0040,A075) // >Verifying Observer (0040,A088) // Type 2 // >>Include 'Code Sequence Macro' Table 8.8-1 // >Verifying Organization (0040,A027) // >Verification DateTime (0040,A030) } */ } } // namespace writer } // namespace gdcmIO
#ifndef __BST_H #define __BST_H #include <string> #include <vector> using namespace std; template <class T> struct bst_node { string value; T key; bst_node<T> *left; bst_node<T> *right; bst_node<T> *parent; bst_node(string val,T key1) { this->value=val; this->key=key1; this->parent=NULL; this->left=NULL; this->right=NULL; } }; template <class T> class bst { bst_node<T> *root; public: bst(); void insert(string val,T key1); bst_node<T>* search(T key1); void delete_node(T key1); int height(bst_node<T>* temp); void replace(T old_key,T new_key); bst_node<T>* getroot(); // utility func. void insert_recursive(bst_node<T> *temp, bst_node<T> *node); bool isExternal(bst_node<T> *node); double execute(bst_node<T> *node); void buildExpTree(string exp); }; #endif
#include "msg_0x3d_soundorparticleeffect_stc.h" namespace MC { namespace Protocol { namespace Msg { SoundOrParticleEffect::SoundOrParticleEffect() { _pf_packetId = static_cast<int8_t>(0x3D); _pf_initialized = false; } SoundOrParticleEffect::SoundOrParticleEffect(int32_t _effectId, int32_t _x, int8_t _y, int32_t _z, int32_t _data, bool _disableRelativeVolume) : _pf_effectId(_effectId) , _pf_x(_x) , _pf_y(_y) , _pf_z(_z) , _pf_data(_data) , _pf_disableRelativeVolume(_disableRelativeVolume) { _pf_packetId = static_cast<int8_t>(0x3D); _pf_initialized = true; } size_t SoundOrParticleEffect::serialize(Buffer& _dst, size_t _offset) { _pm_checkInit(); if(_offset == 0) _dst.clear(); _offset = WriteInt8(_dst, _offset, _pf_packetId); _offset = WriteInt32(_dst, _offset, _pf_effectId); _offset = WriteInt32(_dst, _offset, _pf_x); _offset = WriteInt8(_dst, _offset, _pf_y); _offset = WriteInt32(_dst, _offset, _pf_z); _offset = WriteInt32(_dst, _offset, _pf_data); _offset = WriteBool(_dst, _offset, _pf_disableRelativeVolume); return _offset; } size_t SoundOrParticleEffect::deserialize(const Buffer& _src, size_t _offset) { _offset = _pm_checkPacketId(_src, _offset); _offset = ReadInt32(_src, _offset, _pf_effectId); _offset = ReadInt32(_src, _offset, _pf_x); _offset = ReadInt8(_src, _offset, _pf_y); _offset = ReadInt32(_src, _offset, _pf_z); _offset = ReadInt32(_src, _offset, _pf_data); _offset = ReadBool(_src, _offset, _pf_disableRelativeVolume); _pf_initialized = true; return _offset; } int32_t SoundOrParticleEffect::getEffectId() const { return _pf_effectId; } int32_t SoundOrParticleEffect::getX() const { return _pf_x; } int8_t SoundOrParticleEffect::getY() const { return _pf_y; } int32_t SoundOrParticleEffect::getZ() const { return _pf_z; } int32_t SoundOrParticleEffect::getData() const { return _pf_data; } bool SoundOrParticleEffect::getDisableRelativeVolume() const { return _pf_disableRelativeVolume; } void SoundOrParticleEffect::setEffectId(int32_t _val) { _pf_effectId = _val; } void SoundOrParticleEffect::setX(int32_t _val) { _pf_x = _val; } void SoundOrParticleEffect::setY(int8_t _val) { _pf_y = _val; } void SoundOrParticleEffect::setZ(int32_t _val) { _pf_z = _val; } void SoundOrParticleEffect::setData(int32_t _val) { _pf_data = _val; } void SoundOrParticleEffect::setDisableRelativeVolume(bool _val) { _pf_disableRelativeVolume = _val; } } // namespace Msg } // namespace Protocol } // namespace MC
#include<bits/stdc++.h> long long int as[1000000]; using namespace std; main() { long long int n, c; while(cin>>n>>c) { long long int x, i, t=1; for(i=1; i<=n; i++) cin>>as[i]; for(i=2; i<=n; i++) { if(as[i]-as[i-1]>c)t=1; // else if(t==0)t=2; else t++; } cout<<t<<endl; } return 0; }
#ifndef HASH_MAP_INTERNAL_CHAINING_HPP #define HASH_MAP_INTERNAL_CHAINING_HPP // Pedro Escoboza // A01251531 // TCB1004.500 // 21/11/2020 #include <vector> #include <list> #include <memory> /** * Implementation a hash table of constant size. * * @param T Type of the entry value * @param K Type of the entry key * @param Size Constant size of the hash table * @param Hash Struct with overloaded operator() as with hash function */ template <class K, class T, class Hasher = std::hash<K>> class HashMapInternalChaining { public: using Entry = std::pair<const K, T>; using Bucket = std::list<Entry>; using BucketUPtr = std::unique_ptr<Bucket>; private: std::vector<BucketUPtr> m_table; // Associative table container for key value pairs Hasher m_hasher; // Hashing struct with overloaded operator() size_t m_bucketCount; // Number of buckets in the table size_t m_size; // Number of entries in the table public: /** * Default constructor for HastMap. * Time: O(1) * Space: O(1) * * @return HashMapInternalChaining */ HashMapInternalChaining(size_t bucket_count) : m_table{}, m_hasher{ Hasher{} }, m_bucketCount{ bucket_count }, m_size{ 0U } { m_table.resize(m_bucketCount); m_table.shrink_to_fit(); } /** * Copy constructor. Allows for nesting of hash maps as values themselves. * Time: O(n) * Space: O(n) * * @return HashMapInternalChaining */ HashMapInternalChaining(const HashMapInternalChaining& copy) : m_table{}, m_hasher{}, m_bucketCount{ copy.bucket_count() }, m_size{copy.size()}{ m_table.resize(m_bucketCount); for (const auto& bucket : copy.m_table) { if (bucket == nullptr) { continue; } for (const auto& entry : *bucket) { insert(entry.first, entry.second); } } } /** * Insert a new element in the hash table if no element already has the key. * Time: O(1) * Space: O(1) * * @param key Key to insert * @param value Value to map to the key * @return Pointer to the newly inserted pair OR the previously mapped element */ const std::pair<bool, Entry*> insert(const K& key, const T& value); /** * Finds an element on the hash table. * Time: O(1) * Space: O(1) * * @param key Key to insert * @return Pointer to the found entry or nullptr if not found */ Entry* find(const K& key); /** * Erases an entry with a given key. * Time: O(1) * Space: O(1) * * @param key Key of the entry to erase */ void erase(const K& key); /** * Returns the number of entries in the container. * Time: O(1) * Space: O(1) * * @return Container size */ size_t size() const { return m_size; } /** * Tells if the table is empty. * Time: O(1) * Space: O(1) * * @return Wether the table has elements */ bool empty() const { return m_size == 0U; } /** * Clears the content of the hash map. * Time: O(1) * Space: O(1) * * @return void */ void clear() { m_table.clear(); m_table.resize(m_bucketCount); } /* * Gets the number of filled buckets in the container. * Time: O(1) * Space: O(1) * * @return Number of filled buckets */ size_t bucket_count() const { return m_bucketCount; } /** * Helper to run a callbach on each element of the hash map * Time: O(n) * Space: O(1) * * @param func Unary function that takes a const std::pair<const K, T>& as parameter */ template <class UnaryFunction> void forEach(UnaryFunction func) const { for (const auto& bucket : m_table) { if (bucket != nullptr) { for (const auto& entry : *bucket) { func(entry); } } } } private: /** * Generates a container index mapped to the key. * Time: O(1) * Space: O(1) * * @param key Key of the entry to hash * @return Index of the table mapped to the key */ size_t hash(const K& key) const; /** * Private helper for finding a bucket node in the * given bucket. * Time: O(n) * Space: O(1) * * @param bucket Reference to linked list bucket of pair pointers * @return Unique pointer to entry pair or nullptr if not found. */ static typename Bucket::iterator findNodeInBucket(const K& key, Bucket& bucket); /** * Finds the node element of the given key. * Private helper for other functions * Time: O(1) * Space: O(1) * * @param key Key of the entry to hash * @param [out] bucketPos Bucket index in the table * @return Pair with result and iteartor of node in bucket */ std::pair<bool, typename Bucket::iterator > findNode(const K& key, size_t& bucketPos); /** * Helper to print the hash map. * Time: O(n) * Space: O(n) * * @param [out] out Ostream to print out the hash map * @param hm Const reference to the hash map to print * @return Ostream reference after the insertion */ friend std::ostream& operator<<(std::ostream& out, const HashMapInternalChaining& hm) { for (const auto& bucket : hm.m_table) { if (bucket == nullptr) { continue; } for (const auto& entry : *bucket) { out << entry.first << " : " << entry.second << '\n'; } } return out; } }; template<class K, class T, class Hasher> inline const std::pair<bool, typename HashMapInternalChaining<K, T, Hasher>::Entry*> HashMapInternalChaining<K, T, Hasher>::insert(const K& key, const T& value) { // Get the bucket at the given key position BucketUPtr& bucketSlot{ m_table[hash(key)] }; // If no bucket is found, create it and isert the element if (bucketSlot == nullptr) { bucketSlot = std::make_unique<Bucket>(); bucketSlot->emplace_back(key, value); m_size++; return {true, &bucketSlot->back()}; } // The node was full, look for the entry node in the bucket auto nodeIt{findNodeInBucket(key, *bucketSlot)}; // Check the result of the lookup if (nodeIt != bucketSlot->end()) { // The key was occupied return {false, &*nodeIt}; } else { // The bucket did not container the key, emplace it bucketSlot->emplace_back(key, value); m_size++; return { true, &bucketSlot->back() }; } } template<class K, class T, class Hasher> inline typename HashMapInternalChaining<K, T, Hasher>::Entry* HashMapInternalChaining<K, T, Hasher>::find(const K& key) { // Look for the node size_t i{ 0U }; auto res{ findNode(key, i) }; // If the bucket does not exist, or the bucket does not contain the key if (!res.first) { // Return nothing return nullptr; } // The result iterator is valid, return its content return &*res.second; } template<class K, class T, class Hasher> inline void HashMapInternalChaining<K, T, Hasher>::erase(const K& key) { // Look for the node size_t bucketPos; auto res{ findNode(key, bucketPos) }; // Check that the bucket is valid and that the node exists in the bucket if (res.first) { // Erase the node from the bucket m_size--; m_table[bucketPos]->erase(res.second); } } template<class K, class T, class Hasher> inline size_t HashMapInternalChaining<K, T, Hasher>::hash(const K& key) const { return m_hasher(key) % m_bucketCount; } template<class K, class T, class Hasher> inline typename HashMapInternalChaining<K, T, Hasher>::Bucket::iterator HashMapInternalChaining<K, T, Hasher>::findNodeInBucket(const K& key, Bucket& bucket){ // Find the node in the linked list return std::find_if(bucket.begin(), bucket.end(), [&key](const Entry& entry) { return (entry.first == key); } ); } template<class K, class T, class Hasher> inline std::pair<bool , typename HashMapInternalChaining<K, T, Hasher>::Bucket::iterator> HashMapInternalChaining<K, T, Hasher>::findNode(const K& key, size_t& bucketPos) { // Look for the node in the bucket list of the index mapped to the key size_t i{ hash(key) }; bucketPos = i; BucketUPtr& bucketPtr{ m_table[i] }; if (bucketPtr != nullptr) { // The bucket is valid auto it{ findNodeInBucket(key, *bucketPtr) }; if (it != bucketPtr->end()) { // The bucket contains the key return { true, it }; } else { // The bucket does NOT contain the key return { false, it }; } } // The bucket was empty return { false, typename Bucket::iterator{} }; } #endif // !HASH_MAP_INTERNAL_CHAINING_HPP
#ifndef _IEEE_FLOAT_HPP_ #define _IEEE_FLOAT_HPP_ #include <string.h> namespace fmt { template<class Dest, class Source> inline Dest bit_cast(const Source& source) { static_assert((sizeof(Dest) == sizeof(Source)), "(sizeof(Dest) == sizeof(Source)"); Dest dest; memmove(&dest, &source, sizeof(dest)); return dest; } template <class Dest, class Source> inline Dest bit_cast(Source* source) { return bit_cast<Dest>(reinterpret_cast<uintptr_t>(source)); } template<typename T> class IeeeFloatTraits {}; template<typename T> class IeeeFloat { public: using traits = IeeeFloatTraits<T>; public: IeeeFloat() : d_(0) {} explicit IeeeFloat(typename traits::type v) : d_(bit_cast<typename traits::uint_type>(v)) {} explicit IeeeFloat(typename traits::uint_type v) : d_(v) {} typename traits::uint_type as_uint() const { return d_; } // Returns the next greater double. Returns +infinity on input +infinity. typename traits::type next() const { if (d_ == traits::Infinity) { return IeeeFloat(traits::Infinity).value(); } if (sign() < 0 && significand() == 0) { // -0.0 return 0.0; } if (sign() < 0) { return IeeeFloat(d_ - 1).value(); } else { return IeeeFloat(d_ + 1).value(); } } typename traits::type prev() const { if (d_ == (traits::Infinity | traits::Sign_Mask)) { return -IeeeFloat::infinity(); } if (sign() < 0) { return IeeeFloat(d_ + 1).value(); } else { if (significand() == 0) return -0.0; return IeeeFloat(d_ - 1).value(); } } int exponent() const { if (is_denormal()) { return traits::Denormal_Exponent; } typename traits::uint_type d = as_uint(); int biased_e = static_cast<int>((d & traits::Exponent_Mask) >> traits::Physical_Significand_Size); return biased_e - traits::Exponent_Bias; } typename traits::uint_type significand() const { typename traits::uint_type d = as_uint(); typename traits::uint_type signif = d & traits::Significand_Mask; if (!is_denormal()) { return signif + traits::Hidden_Bit; } else { return signif; } } bool is_denormal() const { typename traits::uint_type d = as_uint(); return (d & traits::Exponent_Mask) == 0; } // We consider denormals not to be special. // Hence only Infinity and NaN are special. bool is_special() const { typename traits::uint_type d = as_uint(); return (d & traits::Exponent_Mask) == traits::Exponent_Mask; } bool is_nan() const { typename traits::uint_type d = as_uint(); return ((d & traits::Exponent_Mask) == traits::Exponent_Mask) && ((d & traits::Significand_Mask) != 0); } bool is_infinite() const { typename traits::uint_type d = as_uint(); return ((d & traits::Exponent_Mask) == traits::Exponent_Mask) && ((d & traits::Significand_Mask) == 0); } int sign() const { typename traits::uint_type d = as_uint(); return (d & traits::Sign_Mask) == 0? 1: -1; } typename traits::type value() const { return bit_cast<typename traits::type>(d_); } static typename traits::type infinity() { return IeeeFloat(traits::Infinity).value(); } static typename traits::type nan() { return IeeeFloat(traits::Nan).value(); } private: typename traits::uint_type d_; }; template<> class IeeeFloatTraits<double> { public: static constexpr uint64_t Sign_Mask = 0x8000000000000000U; static constexpr uint64_t Exponent_Mask = 0x7FF0000000000000UL; static constexpr uint64_t Significand_Mask = 0x000FFFFFFFFFFFFFU; static constexpr uint64_t Hidden_Bit = 0x0010000000000000U; static constexpr int Physical_Significand_Size = 52; // Excludes the hidden bit. static constexpr int Significand_Size = 53; using uint_type = uint64_t; using type = double; static constexpr int Exponent_Bias = 0x3FF + Physical_Significand_Size; static constexpr int Denormal_Exponent = -Exponent_Bias + 1; static constexpr int Max_Exponent = 0x7FF - Exponent_Bias; static constexpr uint64_t Infinity = 0x7FF0000000000000U; static constexpr uint64_t Nan = 0x7FF8000000000000U; }; template<> class IeeeFloatTraits<float> { public: static constexpr uint32_t Sign_Mask = 0x80000000U; static constexpr uint32_t Exponent_Mask = 0x7F800000U; static constexpr uint32_t Significand_Mask = 0x007FFFFFU; static constexpr uint32_t Hidden_Bit = 0x00800000U; static constexpr int Physical_Significand_Size = 23; // Excludes the hidden bit. static constexpr int Significand_Size = 24; using uint_type = uint32_t; using type = float; static constexpr int Exponent_Bias = 0x7F + Physical_Significand_Size; static constexpr int Denormal_Exponent = -Exponent_Bias + 1; static constexpr int Max_Exponent = 0xFF - Exponent_Bias; static constexpr uint32_t Infinity = 0x7F800000U; static constexpr uint32_t Nan = 0x7FC00000U; }; using IeeeSingle = IeeeFloat<float>; using IeeeDouble = IeeeFloat<double>; } #endif
#ifndef _MSG_0X2A_REMOVEENTITYEFFECT_STC_H_ #define _MSG_0X2A_REMOVEENTITYEFFECT_STC_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class RemoveEntityEffect : public BaseMessage { public: RemoveEntityEffect(); RemoveEntityEffect(int32_t _entityId, int32_t _effectId); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getEntityId() const; int32_t getEffectId() const; void setEntityId(int32_t _val); void setEffectId(int32_t _val); private: int32_t _pf_entityId; int32_t _pf_effectId; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X2A_REMOVEENTITYEFFECT_STC_H_
#include "widget.h" void Widget::initializeGL() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set the screen color to black glEnable(GL_DEPTH_TEST); // Enable depth test glEnable(GL_CULL_FACE); // Cut the back side of the cube initShaders(); // Initialize shaders /* --- Surface cubes --- */ m_groups.append(new Group3D); // Create group to fill it with cubes for (auto x = 0; x <= 7; x++) { // Set needed x, y, z coordinates for (auto z = 0; z <= 10; z ++) { initCube(1.0f, QImage (":/dirt.png")); // Initialize cube with size of float m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, 0.0f, z)); // Set the location where this cube is needed m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); // Include the created cube in group created above } } for (auto x = 3; x <= 5; x++) { for (auto z = 0; z >= -2; z--){ initCube(1.0f, QImage (":/dirt.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, 0.0f, z)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } /* ---------------------- */ /* -- Perimeter walls -- */ m_groups.append(new Group3D); /* --- Walls on x axis --- */ for (auto x = 0; x <= 3; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 0.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto x = 5; x <= 7; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 0.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto x = 0; x <= 7; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 10.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } /* --- Walls on z axis --- */ for (auto z = 0; z <= 10; z++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(0.0f, y, z)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto z = 0; z <= 10; z++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(7.0f, y, z)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } /* ---------------------- */ /* ---- Inner walls ----- */ m_groups.append(new Group3D); /* --- Walls on x axis --- */ for (auto x = 3; x < 6; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 2.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto x = 3; x < 4; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 4.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto x = 1; x < 3; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 4.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto x = 5; x < 7; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 4.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto x = 2; x < 6; x++) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(x, y, 8.0f)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } /* --- Walls on z axis --- */ for (auto z = 8; z > 6; z--) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(2.0f, y, z)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto z = 5; z > 3; z--) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(2.0f, y, z)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto z = 2; z > 0; z--) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(2.0f, y, z)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } for (auto z = 6; z > 4; z--) { for (auto y = 1; y < 3; y++) { initCube(1.0f, QImage (":/grass.png")); m_cube[m_cube.size() - 1]->setTranslate(QVector3D(5.0f, y, z)); m_groups[m_groups.size() - 1]->addObject(m_cube[m_cube.size() - 1]); } } /* ---------------------- */ m_groups[0]->setTranslate(QVector3D(-5.0f, -8.0f, -5.0f)); // Surface cubes translation m_groups[1]->setTranslate(QVector3D(-5.0f, -8.0f, -5.0f)); // Perimeter wall cubes translation m_groups[2]->setTranslate(QVector3D(-5.0f, -8.0f, -5.0f)); // Inner wall cubes translation m_skybox = new SkyBox(25.0f, QImage (":/skybox.png")); // Creating skybox object of size 25 float with specified image file m_camera = new Camera3D; // Creating camera object m_camera->setTranslate(QVector3D(0.0f, 7.0f, -4.0f)); // Camera translation to a starting point } void Widget::resizeGL(int width, int height) { float aspect = width / static_cast <float> (height); // Initializing aspect ratio of width to height m_projectionMatrix.setToIdentity(); // Sets matrix to identity m_projectionMatrix.perspective(45, aspect, 0.01f, 100.0f); // Creates perspective projection } void Widget::paintGL() { glClear (GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); // Tells glClear() to clear depth and color buffers m_programSkyBox.bind(); // Binds to the current OpenGLContext and makes current shader program active. Any previously binded shader program will be realeased m_programSkyBox.setUniformValue("u_projectionMatrix", m_projectionMatrix); // Set the value to the variable from the location in the resource file m_camera->draw(&m_programSkyBox); // Draws skybox in the program m_skybox->draw(&m_programSkyBox, context()->functions()); // Also needed to draw skybox m_programSkyBox.release(); // Sets the shader program to unactive state m_program.bind(); m_program.setUniformValue("u_projectionMatrix", m_projectionMatrix); m_program.setUniformValue("u_lightPosition", QVector4D (0.0, 0.0, 0.0, 0.0)); // Sets the light position m_program.setUniformValue("u_lightPower", 1.05f); // Sets the light power m_camera->draw(&m_program); // Draws the cubes for (int i = 0; i < m_groups.size(); i++) { // Using loop to draw all the objects m_groups[i]->draw(&m_program, context()->functions()); } m_program.release(); } void Widget::mousePressEvent(QMouseEvent *event) { if (event->buttons() == Qt::LeftButton) // If left button was clicked, m_mousePosition recieves the cursor position, relatively to the widget. m_mousePosition = QVector2D (event->localPos()); event->accept(); // Indicates that event receiver wants the event. } void Widget::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() != Qt::LeftButton) return; // Enable rotation only in case if left button was clicked QVector2D diff = QVector2D (event->localPos()) - m_mousePosition; m_mousePosition = QVector2D (event->localPos()); float angle = diff.length() / 20.0f; // Sets the rotation speed. QVector3D axis = QVector3D (diff.y(), diff.x(), 0.0); // Sets the axis of rotation. m_camera->setRotate(QQuaternion::fromAxisAndAngle(axis, angle)); // Enable mouse rotation with quanternion using axis and angle. update(); // Updates the widget and sets higher priority for the paintGL function. } void Widget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Left: m_camera->setTranslate(QVector3D(0.15f, 0.0f, 0.0f)); // If left arrow is pressed, camera moves left. break; case Qt::Key_Right: m_camera->setTranslate(QVector3D(-0.15f, 0.0f, 0.0f)); // If right arrow is pressed, camera moves right. break; case Qt::Key_Down: m_camera->setTranslate(QVector3D(0.0f, 0.0f, -0.15f)); // If down arrow is pressed, camera moves backwards. break; case Qt::Key_Up: m_camera->setTranslate(QVector3D(0.0f, 0.0f, 0.15f)); // If up arrow is pressed, camera moves forward. break; case Qt::Key_Escape: close(); // If escape button is pressed, program terminates. break; case Qt::Key_W: m_camera->setTranslate(QVector3D(0.0f, -0.15f, 0.0f)); // If W button is pressed, camera moves up. break; case Qt::Key_S: m_camera->setTranslate(QVector3D(0.0f, 0.15f, 0.0f)); // If S button is pressed, camera moves down. break; } update(); } void Widget::initShaders() { if (!m_program.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/vshader.vsh")) // Adds shader files to the shader program. If add function was failed to execute, program terminates. close(); if (!m_program.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/fshader.fsh")) close(); if (!m_program.link()) // Links together shaders that were added to current shader program. If link function was failed to execute, program terminates. close(); if (!m_programSkyBox.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/vskybox.vsh")) close(); if (!m_programSkyBox.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/fskybox.fsh")) close(); if (!m_programSkyBox.link()) close(); } void Widget::initCube(float width, const QImage &texture) // Creates the geometry of cube using specified texture. { float width_div_2 = width / 2.0f; QVector<VertexData> vertexes; // Initialize vertexes for cube type of structure that contains data about vertexes and indexes. // Front side of the cube. vertexes.append(VertexData(QVector3D(-width_div_2, width_div_2, width_div_2), QVector2D(0.0, 1.0), QVector3D(0.0, 0.0, 1.0))); // Append function inserts value at the end of the vector. vertexes.append(VertexData(QVector3D(-width_div_2, -width_div_2, width_div_2), QVector2D(0.0, 0.0), QVector3D(0.0, 0.0, 1.0))); vertexes.append(VertexData(QVector3D(width_div_2, width_div_2, width_div_2), QVector2D(1.0, 1.0), QVector3D(0.0, 0.0, 1.0))); vertexes.append(VertexData(QVector3D(width_div_2, -width_div_2, width_div_2), QVector2D(1.0, 0.0), QVector3D(0.0, 0.0, 1.0))); // Right side of the cube. vertexes.append(VertexData(QVector3D(width_div_2, width_div_2, width_div_2), QVector2D(0.0, 1.0), QVector3D(1.0, 0.0, 0.0))); vertexes.append(VertexData(QVector3D(width_div_2, -width_div_2, width_div_2), QVector2D(0.0, 0.0), QVector3D(1.0, 0.0, 0.0))); vertexes.append(VertexData(QVector3D(width_div_2, width_div_2, -width_div_2), QVector2D(1.0, 1.0), QVector3D(1.0, 0.0, 0.0))); vertexes.append(VertexData(QVector3D(width_div_2, -width_div_2, -width_div_2), QVector2D(1.0, 0.0), QVector3D(1.0, 0.0, 0.0))); // Top side of the cube. vertexes.append(VertexData(QVector3D(width_div_2, width_div_2, width_div_2), QVector2D(0.0, 1.0), QVector3D(0.0, 1.0, 0.0))); vertexes.append(VertexData(QVector3D(width_div_2, width_div_2, -width_div_2), QVector2D(0.0, 0.0), QVector3D(0.0, 1.0, 0.0))); vertexes.append(VertexData(QVector3D(-width_div_2, width_div_2, width_div_2), QVector2D(1.0, 1.0), QVector3D(0.0, 1.0, 0.0))); vertexes.append(VertexData(QVector3D(-width_div_2, width_div_2, -width_div_2), QVector2D(1.0, 0.0), QVector3D(0.0, 1.0, 0.0))); // Back side of the cube. vertexes.append(VertexData(QVector3D(width_div_2, width_div_2, -width_div_2), QVector2D(0.0, 1.0), QVector3D(0.0, 0.0, -1.0))); vertexes.append(VertexData(QVector3D(width_div_2, -width_div_2, -width_div_2), QVector2D(0.0, 0.0), QVector3D(0.0, 0.0, -1.0))); vertexes.append(VertexData(QVector3D(-width_div_2, width_div_2, -width_div_2), QVector2D(1.0, 1.0), QVector3D(0.0, 0.0, -1.0))); vertexes.append(VertexData(QVector3D(-width_div_2, -width_div_2, -width_div_2), QVector2D(1.0, 0.0), QVector3D(0.0, 0.0, -1.0))); // Left side of the cube. vertexes.append(VertexData(QVector3D(-width_div_2, width_div_2, width_div_2), QVector2D(0.0, 1.0), QVector3D(-1.0, 0.0, 0.0))); vertexes.append(VertexData(QVector3D(-width_div_2, width_div_2, -width_div_2), QVector2D(0.0, 0.0), QVector3D(-1.0, 0.0, 0.0))); vertexes.append(VertexData(QVector3D(-width_div_2, -width_div_2, width_div_2), QVector2D(1.0, 1.0), QVector3D(-1.0, 0.0, 0.0))); vertexes.append(VertexData(QVector3D(-width_div_2, -width_div_2, -width_div_2), QVector2D(1.0, 0.0), QVector3D(-1.0, 0.0, 0.0))); // Bottom side of the cube. vertexes.append(VertexData(QVector3D(-width_div_2, -width_div_2, width_div_2), QVector2D(0.0, 1.0), QVector3D(0.0, -1.0, 0.0))); vertexes.append(VertexData(QVector3D(-width_div_2, -width_div_2, -width_div_2), QVector2D(0.0, 0.0), QVector3D(0.0, -1.0, 0.0))); vertexes.append(VertexData(QVector3D(width_div_2, -width_div_2, width_div_2), QVector2D(1.0, 1.0), QVector3D(0.0, -1.0, 0.0))); vertexes.append(VertexData(QVector3D(width_div_2, -width_div_2, -width_div_2), QVector2D(1.0, 0.0), QVector3D(0.0, -1.0, 0.0))); QVector<GLuint> indexes; // Initialize indexes of the cube. for (auto i = 0; i < 24; i+=4) { // Loop used set the location of corner points of the cube. indexes.append (static_cast <unsigned int> (i + 0)); indexes.append (static_cast <unsigned int> (i + 1)); indexes.append (static_cast <unsigned int> (i + 2)); indexes.append (static_cast <unsigned int> (i + 2)); indexes.append (static_cast <unsigned int> (i + 1)); indexes.append (static_cast <unsigned int> (i + 3)); } m_cube.append(new SimpleObject3D(vertexes, indexes, texture)); // Adds the created cube to the array of objectes. } Widget::Widget(QWidget *parent) : QOpenGLWidget(parent) { } Widget::~Widget() { delete m_camera; // Deletes the camera object. for (auto i = 0; i < m_cube.size(); ++i) // Loop deletes all the created objectes. delete m_cube[i]; for (auto i = 0; i < m_groups.size(); ++i) // Loop deletes all the created groups of objects. delete m_groups[i]; }
// // Created by Administrator on 2021/1/22. // #ifndef BILIRTMP_JAVACALLHELPER_H #define BILIRTMP_JAVACALLHELPER_H #include <jni.h> //标记线程 因为子线程需要attach #define THREAD_MAIN 1 #define THREAD_CHILD 2 class JavaCallHelper { public: JavaCallHelper(JavaVM *_javaVM, JNIEnv *_env, jobject &_jobj); void postH264(char *data,int length, int thread = THREAD_MAIN); public: JavaVM *javaVM; JNIEnv *env; jobject jobj; jmethodID jmid_postData; }; #endif //BILIRTMP_JAVACALLHELPER_H
#pragma once /* * Wrapper around libfreenect2 to use a kinect and write images out as files * Basing this impl off of libfreenect2's Protonect.cpp */ #include <cstddef> #include <cstdint> #include <filesystem> #include <future> #include <optional> #include <queue> #include <thread> #include <libfreenect2/frame_listener.hpp> #include <libfreenect2/frame_listener_impl.h> #include <libfreenect2/libfreenect2.hpp> #include <libfreenect2/logger.h> #include <libfreenect2/packet_pipeline.h> #include <libfreenect2/registration.h> namespace mik { /// @TODO A to_string method enum class InputPipeline { CUDA, OPENGL, CPU, OTHER }; struct KinectConfig { InputPipeline framework = InputPipeline::CPU; int32_t gpu_device_id = 0; // TODO Figure out what this should be, also make optional std::filesystem::path image_output_dir = std::filesystem::path() / "kinect-frames"; // Use rgb and depth by default }; class Kinect { public: Kinect(KinectConfig config = KinectConfig()); ~Kinect(); static std::string frame_type_to_string(libfreenect2::Frame::Type type); static std::string frame_format_to_string(libfreenect2::Frame::Format format); // Save frame to disk, best for checking functionality void save_frames(std::uint32_t n_frames_to_save); void start_recording(); void stop_recording(); private: /// @todo void lower_resolution(libfreenect2::Frame* frame); /// @todo void convert_to_gesture_net(const libfreenect2::Frame* frame); void save_frame(libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame) const; void save_frame_async(libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame); void save_gnet_frame_async(libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame); static void save_frame_impl(std::filesystem::path image_output_dir, libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame); KinectConfig config_; std::queue<std::future<void>> saveTasks_; std::atomic<bool> should_record_ = false; std::thread recorder_; // libfreenect2 members // Don't use smart pointers as it messes with how libfreenect2 manages these objects. libfreenect2::Freenect2 freenect2_; libfreenect2::PacketPipeline* pipeline_ = nullptr; libfreenect2::Freenect2Device* device_ptr_ = nullptr; libfreenect2::Registration* registration_ = nullptr; libfreenect2::Frame* undistorted_ptr_ = nullptr; libfreenect2::Frame* registered_ptr_ = nullptr; libfreenect2::FrameMap frame_map_; libfreenect2::SyncMultiFrameListener* listener_ptr_ = nullptr; }; } // namespace mik
#pragma once #if defined ROSS_DEBUG #include <cassert> #include <limits> #endif namespace ross { typedef double real_t; typedef int64_t integer_t; typedef size_t size_t; constexpr real_t kPI = 3.14159265358979323846; constexpr real_t kPI_4 = 0.785398163397448309616; template<typename T> inline size_t sizeT(T v) { return static_cast<size_t>(v); } #if defined ROSS_DEBUG inline size_t sizeT(real_t v) { assert(v >= 0.0); assert(v <= static_cast<real_t>(std::numeric_limits<size_t>::max())); return static_cast<size_t>(v); } #endif }
#ifndef APPLICATION_REGISTRATIONCMD_H #define APPLICATION_REGISTRATIONCMD_H #include <iostream> #include "BaseCmd.h" #include "Commands/CmdCreator/Commands.h" #include "ChatObjects/UserInfo.h" // Command for registration class RegistrationCmd : public BaseCmd { public: ~RegistrationCmd() override = default; RegistrationCmd(int numRequest, const std::optional<std::string>& error, const std::string& body); // Execute command void execute(std::shared_ptr<CallbacksHolder> holder) override; }; #endif //APPLICATION_REGISTRATIONCMD_H
template<class T> double romberg(const T&f,double a,double b,double eps=1e-6){ vector<double>t; double h=b-a,last,curr,x,k1,k2,temp; int k=1,i=1; t.emplace_back(h*(f(a)+f(b))/2); do { last=t.back(); curr=0; x=a+h/2; for(int j=0;j<k;++j) curr+=f(x),x+=h; curr=(t[0]+h*curr)/2; k1=4.0/3.0,k2=1.0/3.0; for(int j=0; j<i; j++) { temp=k1*curr-k2*t[j]; t[j]=curr; curr=temp; k2/=4*k1-k2; k1=k2+1; } t.emplace_back(curr); k*=2; h/=2; i++; }while(fabs(last-curr)>eps); return t.back(); }//调用romberg(f,a,b,eps),a是积分上界,b是积分下界; double f(double x){ return x*x; }//被积函数f
#include "ntrajectory.h" /* NearestTrajectory :: NearestTrajectory(uint q, const kdTree& t, uint p) : Nearest(q, t, p), trajectory_points(p) { } void NearestTrajectory :: Add_Point(uint index) { const IOVector& bucket_point = kdtree[index]; const fp distance = Distance(query_point, bucket_point); // squared furthest distance if (distance == fp_ZERO) { // zero nearest neighbour zero_nn_list.push_back(index); return; } if (distance > furthest_distance) return; uint i = 0; uint j = near_neighbours.size(); while (i < j && distance > near_neighbours[i]->distance) i++; if (distance == near_neighbours[i]->distance) // equal nearest neighbour near_neighbours[i]->index_list.push_back(index); else { // insert point into list j--; delete near_neighbours[j]; while (j > i) { near_neighbours[j] = near_neighbours[j-1]; j--; } near_neighbours[i] = new near_points(distance, index); furthest_distance = near_neighbours[near_neighbours.size()-1]->distance; } } void NearestTrajectory :: Search(const node* root) { if (root->Terminal()) { for (uint i = 0; i < root->index_list.size(); i++) Add_Point(root->index_list[i]); return; } const uint d = root->partition_key; // partition key const fp p = kdtree[root->median].Input_Vector()[d]; // partition value const valarray_fp& query_input = query_point.Input_Vector(); if (query_input[d] < p) { // recurse on nearest child fp temp = upper_bound[d]; upper_bound[d] = p; Search(root->left); upper_bound[d] = temp; temp = lower_bound[d]; lower_bound[d] = p; if (Bounds_Overlap_Ball()) Search(root->right); lower_bound[d] = temp; } else { fp temp = lower_bound[d]; lower_bound[d] = p; Search(root->right); lower_bound[d] = temp; temp = upper_bound[d]; upper_bound[d] = p; if (Bounds_Overlap_Ball()) Search(root->left); upper_bound[d] = temp; } } */
/* You are given a generic tree. You have to replace each node with its depth value. You just have to update the data of each node, there is no need to return or print anything. Input format : The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space. Output format: The updated tree is printed level wise. Each level is printed in a new line. Please refer to sample output 1 for more details. Constraints: Time Limit: 1 sec Sample Input 1: 10 3 20 30 40 2 40 50 0 0 0 0 Sample Output 1: 0 1 1 1 2 2 */ #include<bits/stdc++.h> using namespace std; template<typename T> class TreeNode{ public: T data; vector<TreeNode<T>*> children; TreeNode(T data){ this -> data = data; } }; TreeNode<int>* takeinput(){ int rootData; cin >> rootData; TreeNode<int>* root = new TreeNode<int>(rootData); queue<TreeNode<int>*> pendingNodes; pendingNodes.push(root); while(!pendingNodes.empty()){ TreeNode<int>* front = pendingNodes.front(); pendingNodes.pop(); int numofchild; cin >> numofchild; for(int i=0;i<numofchild;i++){ int childData; cin >> childData; TreeNode<int>* child = new TreeNode<int>(childData); front -> children.push_back(child); pendingNodes.push(child); } } return root; } void helper(TreeNode<int>* root,int depth){ root -> data = depth; for(int i=0;i<root->children.size();i++){ helper(root->children[i],depth + 1); } } void replaceWithDepthValue(TreeNode<int>* root){ if(root == NULL){ return; } int depth = 0; helper(root,depth); } void printLevelAtNewline(TreeNode<int>* root){ queue<TreeNode<int>*> q; q.push(root); q.push(NULL); while(!q.empty()){ TreeNode<int>* first = q.front(); q.pop(); if(first == NULL){ if(q.empty()){ break; } cout << endl; q.push(NULL); continue; } cout << first->data << " "; for(int i=0;i<first->children.size();i++){ q.push(first->children[i]); } } } int main(){ TreeNode<int>* root = takeinput(); replaceWithDepthValue(root); printLevelAtNewline(root); cout << endl; return 0; }
#include <iostream> #include <stdio.h> #include <glm/glm.hpp> #include <display.h> #include <text_renderer.h> #include <camera.h> #include <gameobject.h> #include <input_handler.h> #include <gui_objects.h> #define WIDTH 800 #define HEIGHT 500 glm::vec4 purple(1.0f,0.0f,1.0f,1.0f); glm::vec4 black(0.0f,0.0f,0.0f,1.0f); using namespace GUI; int main(int argc, char** argv) { // window/display, camera and clock-struct Display* window = new Display(WIDTH,HEIGHT, argv[0]+2); Camera* cam = new Camera(glm::vec3(0,0,100), 0, window); Clock clock; // basic shader BasicShader* shader1 = new BasicShader("../res/shaders/basicShader", cam); TextShader* text_shader = new TextShader("../res/shaders/textShader", cam); GUI_Shader* gui_shader = new GUI_Shader("../res/shaders/gui_shader", cam); GUI_RectBoundShader* gui_shader_bound = new GUI_RectBoundShader("../res/shaders/gui_bound_shader", cam); TextRenderer* text_rend = new TextRenderer(text_shader, "../res/fonts/FreeSans.ttf"); // Texture* texture1 = new Texture("../res/tex.png"); Texture* texture2 = new Texture("../res/img1.png"); Texture* texture3 = new Texture("../res/buttontex.png"); // init gui Canvas* canvas = new Canvas(window); Panel* panel1 = canvas->NewPanel(glm::vec2(0.2f, 0.2f), glm::vec2(0.8f, 0.2f), glm::vec2(0.2f, 0.8f), glm::vec2(0.8f, 0.8f)); Panel* panel2 = canvas->NewPanel(glm::vec2(-0.25f, -0.25f), glm::vec2(0.75f, -0.25f), glm::vec2(-0.25f, 0.75f), glm::vec2(0.75f, 0.75f), panel1); panel1->InitDrawing(gui_shader, texture1); panel1->SetBorder(20.0f, BLACK); glm::vec4 rect = glm::vec4(panel1->GetRectTransform()->m_top_left.x + 20.0f, panel1->GetRectTransform()->m_top_right.x-20.0f, panel1->GetRectTransform()->m_top_left.y + 20.0f, panel1->GetRectTransform()->m_bottom_left.y - 20.0f); gui_shader_bound->SetBoundRect(rect); panel2->InitDrawing(gui_shader_bound, texture2); panel2->SetBorder(10.0f, PURPLE); panel2->Disable(); Label* label1 = canvas->NewLabel(glm::vec2(0.0f,0.005f), panel1, text_rend, "FPS: ", FS_18); // Buttons Button* button1 = canvas->NewButton(glm::vec2(0.1f), glm::vec2(60,20), panel2); button1->InitDrawing(gui_shader_bound, texture3); Button* button2 = canvas->NewButton(glm::vec2(0.6f, 0.1f), glm::vec2(60,20), panel2); button2->InitDrawing(gui_shader_bound, texture3); button2->Disable(); std::function<void(void*)> SwitchButtons = [button1, button2](void* num) { std::cout << *(int*)num << std::endl; if (button1->IsDisabled()) { button1->Enable(); button2->Disable(); } else { button1->Disable(); button2->Enable(); } }; int num1 = 123; int num2 = 321; button1->SetOnClick( SwitchButtons, (void*)&num1 ); button2->SetOnClick( SwitchButtons, (void*)&num2 ); Button* button3 = canvas->NewButton(glm::vec2(0.4f, 0.5f), glm::vec2(60,20), panel1); button3->InitDrawing(gui_shader, texture3); Button* button4 = canvas->NewButton(glm::vec2(0.6f, 0.7f), glm::vec2(60,20), panel2); button4->InitDrawing(gui_shader, texture3); std::function<void(void*)> TogglePanel = [](void* p) { Panel* panel = static_cast<Panel*>(p); if (!panel->IsDisabled()) { panel->Disable(); } else { panel->Enable(); } }; button3->SetOnClick( TogglePanel, panel2 ); button4->SetOnClick( TogglePanel, panel2 ); // initlialize textrenderer with font. DrawableGameObject* go1 = new DrawableGameObject("GO 1", texture2, shader1); DrawableGameObject* go2 = new DrawableGameObject("GO 1", texture1, shader1); go1->GetTransform()->GetScale()->x *= 10; go1->GetTransform()->GetScale()->y *= 10; // Input handling SDL_Event e; bool isRunning = true; InputHandler* input_handler = new InputHandler(cam, window, canvas); float delta_time; float fps; char fps_string[10]; while(isRunning) { window->Clear(0.0f, 0.2f, 0.0f, 1.0f); clock.tick(); delta_time = clock.delta_time / 1000.0f; // in seconds. fps = 1.0f / delta_time; sprintf(fps_string, "FPS: %d", (int)fps); label1->ConfigText(fps_string, FS_18, glm::vec2(0)); //// HANDLE INPUT HERE try { input_handler->HandleInput(&e, delta_time, &isRunning); } catch ( const GUI::GUIException &e ) { std::cout << "Error in GUI while running: " << e.what() << std::endl; return 1; } /// END INPUT HANDLING go1->DrawSprite(); go2->DrawSprite(); canvas->DrawGUI(cam); window->SwapBuffers(); SDL_Delay(10); } std::cout << "Cleaning up" << std::endl; delete go1; delete go2; delete cam; delete window; // delete texs and shaders delete shader1; delete texture1; delete texture2; return 0; }
/* * HeartbeatServiceClient.cc * * Created on: Nov 18, 2017 * Author: cis505 */ #include "ServerToServerClient.h" vector<WriteCommandRequest> ServerToServerClient::AskForLog(int seqNum) { ClientContext context; LogRequest request; // TODO: set seqNum request.set_sequencenum(seqNum); unique_ptr<ClientReader<WriteCommandRequest>> reader(stub_->AskForLog(&context, request)); WriteCommandRequest logEntry; vector<WriteCommandRequest> logEntries; while (reader->Read(&logEntry)) { logEntries.push_back(logEntry); } Status status = reader->Finish(); if (!status.ok()) { cerr << "AskForLog rpc failed." << endl; } return logEntries; }
// rplidarReader.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "..\ultra_simple\RplidarClass.h" #include <chrono> #include <thread> #include <iterator> #include <vector> #include <algorithm> #include "c:/usr/include/gregutils/Sqlbuilder.h" #include "/usr/include/rplidar/rosstuff.h" //#define DLL_EXPORT __declspec(dllexport) RplidarReadingQueue * gpRPInstance = nullptr; extern "C" { DLL_EXPORT int test(void) { return 42; } DLL_EXPORT int StartLidar(float fromRadial, float toRadial, int qSize){ SGUP_ODS(__FUNCTION__) if (gpRPInstance == nullptr) gpRPInstance = new RplidarReadingQueue(fromRadial, toRadial, qSize); gpRPInstance->setRange(fromRadial, toRadial); gpRPInstance->runThreaded(); return 0; } DLL_EXPORT int StartLidarWithParams(float fromRadial, float toRadial, int qSize, int baud, const char* comport) { SGUP_ODS(__FUNCTION__) if (gpRPInstance == nullptr) gpRPInstance = new RplidarReadingQueue(fromRadial, toRadial, qSize,baud, comport); SGUP_ODSA(__FUNCTION__,"COMPORT RECEIVED:", comport) gpRPInstance->runThreaded(); return 0; } DLL_EXPORT int StopLidar(void) { SGUP_ODS(__FUNCTION__) if (gpRPInstance) { gpRPInstance->stop(); while (gpRPInstance->getLidarStatus() != rp::STOPPED) { OutputDebugStringA(__FUNCTION__); // SGUP_ODS(__FUNCTION__, "waiting until status becomes stopped!") std::this_thread::sleep_for(std::chrono::milliseconds(100)); } SGUP_ODS(__FUNCTION__, "status is STOPPED") delete gpRPInstance; gpRPInstance = nullptr; } return 0; } DLL_EXPORT int GetMeasure(rp::measure &m) { int ret; if (gpRPInstance) { ret=gpRPInstance->getFront(m); } else return -1; } DLL_EXPORT rp::enumLidarStatus GetLidarStatus() { if (gpRPInstance) return gpRPInstance->getLidarStatus(); else return rp::UNKNOWN; } DLL_EXPORT void GetScan(rp::RplidarProxy::ScanVecType2 ** theScan){ if (gpRPInstance) gpRPInstance->getScan(theScan); } DLL_EXPORT void GetScanWithExpiry(rp::RplidarProxy::ScanVecType2 ** theScan, int NewerThanMsec) { // SGUP_ODSA(__FUNCTION__) if (gpRPInstance) { gpRPInstance->getScan(theScan,NewerThanMsec); } } DLL_EXPORT void DestroyScan(rp::RplidarProxy::ScanVecType2 ** theScan) { if (*theScan==nullptr) { SGUP_ODSA(__FUNCTION__, "deleting a *scan that is nullptr! returning..."); return; } if (theScan == nullptr) { SGUP_ODSA(__FUNCTION__, "deleting a scan that is nullptr! returning..."); return; } delete *theScan; //if (gpRPInstance) //gpRPInstance->getScan(theScan); } DLL_EXPORT void DumpScanToFile(std::string &fname , rp::RplidarProxy::ScanVecType2 * theScan, bool append) { if (gpRPInstance) { gpRPInstance->dumpScanToFile(fname ,theScan, append); } //if (gpRPInstance) } DLL_EXPORT void SavePresentScan(int id, std::string & database, rp::RplidarProxy::ScanVecType2 * theScan, float tilt) { if (gpRPInstance) { gpRPInstance->savePresentScan(id,database, theScan, "sweep"); } } DLL_EXPORT bool SendSQL(std::string & path, std::shared_ptr<std::string> & sql) { // if (gpRPInstance) { return gpRPInstance->sendSQL(path, sql); //} } DLL_EXPORT void SetTiltLidar(float tilt) { if (gpRPInstance) { gpRPInstance->setTiltLidar(tilt); } } DLL_EXPORT int SVToString(rp::RplidarProxy::ScanVecType2 * theScan, std::stringstream & ss) { if (theScan == nullptr) { SGUP_ODSA(__FUNCTION__, "no scan sent in..."); return 0; } for (auto &p : *theScan) { ss << p.first << ": ," << p.second.distance << " , " <<p.second.tilt << std::endl; } return theScan->size(); } DLL_EXPORT int GetScanFromDatabase(rp::RplidarProxy::ScanVecType2 ** psv, std::string & path, std::optional<int> & id, std::optional<std::string> & sweepTableName) { return RplidarReadingQueue::getScanFromDatabase(psv, path, id, sweepTableName); } DLL_EXPORT int SaveScanToDatabase(rp::RplidarProxy::ScanVecType2 * psv, std::string & path, std::optional<int> & id, std::optional<std::string> & sweepTableName) { return RplidarReadingQueue::saveScanToDatabase(psv, path, id, sweepTableName); } DLL_EXPORT int GetRangeOfScansFromDatabase(rp::RplidarProxy::ScanVecType2 ** sv, std::string & path, rp::RplidarProxy::scanRange rng, bool loop, bool reset, std::optional<std::string> & sweepTableName) { // static rp::RplidarProxy::scanRange theRange=std::nullopt; std::stringstream ss; std::string theSweepTableName; if (sweepTableName) { theSweepTableName = *sweepTableName; } else theSweepTableName = "sweep"; SGUP_ODSA(__FUNCTION__, "!!!hasvalue:", theRange.has_value()); SQLBuilder sb; sb.createOrOpenDatabase(path); auto rst = [&]() { theRange = std::nullopt; *sv = nullptr; SGUP_ODSA(__FUNCTION__, "reset called"); //return -1; }; if (reset) { rst(); return -1; } if (theRange.has_value()==false) //this is the first call of the function, because theRange is static optional and has not been initialized { SGUP_ODSA(__FUNCTION__, "HASVAL:",theRange.has_value(), "First call"); if (rng) //we are intended to move through a range they gave us { SGUP_ODSA(__FUNCTION__, "Setting range passed in:", rng->first, rng->second); theRange = rng; *sv = nullptr;// don't expect a result set because this is first call } else { //means we should go LIFO from max to min of whatever is in the database //theRange->first= ss<< "select ifnull(max(id),0),ifnull(min(id),0) from "<<theSweepTableName<<";"; auto b=sb.execSQL(ss.str()); if (!b) { SGUP_ODSA(__FUNCTION__, "error in tablename", theSweepTableName); *sv = nullptr; return 1; } theRange = std::pair<int,int>(std::stoi(sb.results[0][0].second), std::stoi(sb.results[0][1].second)); //theRange->first = std::stoi(sb.results[0][0].second); //theRange->second = std::stoi(sb.results[0][1].second); SGUP_ODSA(__FUNCTION__, "max:", theRange->first, "min:", theRange->second); *sv = nullptr; } } else //repeated call where theRange is properly set, ie, theRAnge IS valid { //if max < min, because I decrement theRange->first and use it as a last index if (theRange->first < theRange->second) { SGUP_ODSA(__FUNCTION__, "past minimum, returning, should either reset or loop"); *sv = nullptr; if (loop) { rst(); } } auto sql = boost::format("select id, angle, distance, tilt from %1% where id == %2%") %theSweepTableName % theRange->first--; //count backward from max *sv = new rp::RplidarProxy::ScanVecType2; sqlite3_stmt *statement; if (sqlite3_prepare_v2(sb.gdb, sql.str().c_str(), -1, &statement, 0) == SQLITE_OK) { //int cols = sqlite3_column_count(statement); int result = 0; //int id = -1; while (true) { result = sqlite3_step(statement); if (result == SQLITE_ROW) { auto id = sqlite3_column_int(statement, 0); auto angle = sqlite3_column_double(statement, 1); auto distance = sqlite3_column_int(statement, 2 ); auto tilt = sqlite3_column_double(statement, 3); //auto cnt = sqlite3_column_double(statement, 4); (*sv)->push_back({ angle, rp::beam((_u16)distance, tilt,id) }); } else if (result == SQLITE_DONE) { //SGUP_ODSA(__FUNCTION__, "SQLITE_DONE, at id:", id); break; } else { break; } } sqlite3_finalize(statement); } } return 0; } DLL_EXPORT bool ROSAction(const rp::ROSArgs & args, rp::enumROSCommand command) { int spinMsec = 100; auto it = args.find("spinMsec"); auto topic = args.find("topic"); auto serviceCommand = args.find("serviceCommand"); auto nodeName = args.find("nodeName"); std::string theTopic; std::string theNodeName="rplidar_client"; ros::master::V_TopicInfo master_topics; ros::master::V_TopicInfo::iterator tit; rp::ROSArgs cleanArgs; std::vector<std::string> specialArgs = { "spinMsec", "topic", "qSize", "serviceCommand", "nodeName" }; //just for reference, specialArgs not used anywhere auto fnNotSpecialWord = [&](std::pair<std::string, std::string> p) { if (STRGUPLE::helpers::is_in(p.first, "spinMsec", "topic", "qSize", "serviceCommand", "nodeName")) { return false; } SG2("not special word:", p.second); return true; }; //#ROS_INIT_SWITCH switch (command) { case rp::START_SUB: if (topic != args.end()) { int qSize = 1000; auto f = args.find("qSize"); if (topic != args.end()) theTopic = topic->second; else { SGUP_ODSA(__FUNCTION__, "no topic found in args...error."); return false; } if (f != args.end()) { qSize = std::stoi( f->second); } auto cnt = getTopics(master_topics); tit=std::find_if(master_topics.begin(), master_topics.end(), [&](ros::master::TopicInfo & top)->bool { if (top.name == theTopic) { SGUP_ODSA(__FUNCTION__, "found topic:", theTopic,"vs", top.name); return true; } else { SGUP_ODSA(__FUNCTION__, "not matching topic:", theTopic, "vs", top.name); return false; } }); if (tit!= master_topics.end()) { SGUP_ODSA(__FUNCTION__,__LINE__, "topic found:", theTopic, "starting subscription"); ROSStuff::startSub(theTopic,qSize); SGUP_DEBUGLINE return true; } else { SGUP_ODSA(__FUNCTION__, "look through master topics and didn't find:", theTopic); return false; } } else { SG2("START_SUB, but no topic!") SGUP_ODSA(__FUNCTION__, "The Topic does no exist..", theTopic); } break; case rp::STOP_SUB: ROSStuff::stopSub(); break; case rp::INTITIALIZE: if (it != args.end()) { spinMsec = std::stoi(it->second); SGUP_ODSA(__FUNCTION__, "spinMsec argument found in initialize:", it->first, spinMsec); } else{ SGUP_ODSA(__FUNCTION__, "warning: initialize called but no spinMsec argument was given, might be ok"); } //the presence of spinMsec means startSpin will be called in here. //note that args is used for ros libraries, so we need to purge all my custom uses (like topic, qSize, etc.) if (nodeName != args.end()) theNodeName = nodeName->second; //removes all my keywords and leaves only the official ros ones, like __master if present. std::copy_if(args.begin(), args.end(), std::inserter(cleanArgs, cleanArgs.end()), fnNotSpecialWord); return ROSStuff::init(cleanArgs,theNodeName,std::optional<int>(spinMsec)); break; case rp::TICK_SPIN: if(ROSStuff::isSubscribing) ros::spinOnce(); break; case rp::SHUTDOWN: ROSStuff::shutdown(); break; case rp::START_MOTOR: ROSStuff::callService("/start_motor"); break; case rp::STOP_MOTOR: ROSStuff::callService("/stop_motor"); break; case rp::CALL_SERVICE: if(serviceCommand!=args.end()) ROSStuff::callService(serviceCommand->second); default: break; } return true; } DLL_EXPORT void GetROSScan(rp::RplidarProxy::ScanVecType2 ** theScan) { ROSStuff::GetROSScan(theScan); } }
#ifndef __Config__ #define __Config__ #include <wx/fileconf.h> class Config { private: wxFileConfig *config; public: Config(wxString filename); void WriteData(const wxString &key, const wxString &value); void ReadData(const wxString &key, wxString *str); ~Config(); }; #endif // __Config__
#include "needs/seekfoodai.hpp" #include "components/item.hpp" #include "components/foodstuff.hpp" #include "components/position.hpp" #include "components/ai/pathai.hpp" #include "needs/needs.hpp" namespace needs { int SeekFoodAI::start(ai::AI* ai) { return update(ai); } int SeekFoodAI::update(ai::AI* ai) { if (!food) { return findfood(ai); } return findpath(ai); } const std::string& SeekFoodAI::description() const { return desc; } int SeekFoodAI::findfood(ai::AI* ai) { auto it = global_set<item::Item>::begin(); while (it != global_set<item::Item>::end()) { if ((*it)->locked) { ++it; continue; } if ((*it)->parent->has<Foodstuff>()) { // I have found food! if ((food = (*it)->try_lock())) { // It's mine! return findpath(ai); } // I was unable to lock the food. } ++it; } // Didn't find food.... :( // Try again later. return 200; } int SeekFoodAI::findpath(ai::AI* ai) { assert(food); auto dest = food->pos(); if (dest != ai->parent->get<Position>()->as_point()) { // We are not at the food. We must travel! return ai->push_script(ai::make_pathai(point{ dest.x, dest.y })); } // We are at the food! Rejoice! return eatfood(ai); } int SeekFoodAI::eatfood(ai::AI* ai) { auto fs = food->parent->assert_get<Foodstuff>(); auto needs = ai->parent->assert_get<Needs>(); // Consume the food. needs->food += fs->amount; if (needs->food > needs->max_food) needs->food = needs->max_food; // Release and delete the food. It has been consumed. food.delete_reset(); return ai->pop_script(); } std::string SeekFoodAI::desc = "Seeking food"; ai::AI::script_ptr make_seek_food_script() { return make_shared<SeekFoodAI>(); } }
// // HEAP.hpp // ADT // // Created by Jalor on 2020/12/25. // Copyright © 2020 Jalor. All rights reserved. // #ifndef HEAP_hpp #define HEAP_hpp #include <iostream> #include <ctime> #include <cstdlib> using namespace std; const int MAX = 10; class Heap { private: int a[MAX+1] = {0}; void Sift(int,int);//堆调整 public: void onCreate();//创建数组 void heapSort(int);//堆排序 void outArray();//输出 }; #endif /* HEAP_hpp */
#include<cstdio> #include<iostream> #include<string> using namespace std; int main() { char s[]="D:\\My Documents\\chengxu\\Useful function\\清除无用文件\\clear.plg"; if(remove(s)) cout<<"Can not delete!\n"; }
//--------------------------------------------------------- // // Project: dada // Module: core // File: Object.h // Author: Viacheslav Pryshchepa // // Description: // //--------------------------------------------------------- #ifndef DADA_CORE_OBJECT_H #define DADA_CORE_OBJECT_H #include "dada/core/MetaInfo.h" #define DADA_OBJECT(object, super) \ const dada::MetaInfo& getMetaInfo() const \ { \ return object::getMetaInformation(); \ } \ static const dada::MetaInfo& getMetaInformation() \ { \ static dada::MetaInfo mi(#object, &super::getMetaInformation()); \ return mi; \ } namespace dada { class Object { public: const char* getClassName() const; bool isInstance(const Object& obj) const; bool isKind(const Object& obj) const; virtual const MetaInfo& getMetaInfo() const; static const MetaInfo& getMetaInformation(); template<class T> const T* cast() const; template<class T> T* cast(); protected: Object(); virtual ~Object(); private: Object(const Object& obj); // disabled Object& operator = (const Object& obj); // disabled }; inline const char* Object::getClassName() const { return getMetaInfo().getName(); } inline bool Object::isInstance(const Object& obj) const { return getMetaInfo().isInstance(obj.getMetaInfo()); } inline bool Object::isKind(const Object& obj) const { return getMetaInfo().isKind(obj.getMetaInfo()); } inline const MetaInfo& Object::getMetaInfo() const { return getMetaInformation(); } inline const MetaInfo& Object::getMetaInformation() { static MetaInfo mi("Object", NULL); return mi; } template<class T> inline const T* Object::cast() const { return getMetaInfo().isKind(T::getMetaInformation()) ? static_cast<const T*>(this) : NULL; } template<class T> inline T* Object::cast() { return getMetaInfo().isKind(T::getMetaInformation()) ? static_cast<T*>(this) : NULL; } inline Object::Object() { } inline Object::~Object() { } } // dada #endif // DADA_CORE_OBJECT_H
#ifndef MD5_H #define MD5_H #include<iostream> #include<string> #define F( X ,Y ,Z ) (( X & Y ) | ( (~X) & Z )) #define G( X ,Y ,Z ) (( X & Z ) | ( Y & (~Z) )) #define H( X ,Y ,Z ) (X ^ Y ^ Z) #define I( X ,Y ,Z ) (Y ^ ( X | (~Z) )) #define FF(a ,b ,c ,d ,Mj ,s ,ti ) (a = b + ( (a + F(b,c,d) + Mj + ti) << s)) #define GG(a ,b ,c ,d ,Mj ,s ,ti ) (a = b + ( (a + G(b,c,d) + Mj + ti) << s)) #define HH(a ,b ,c ,d ,Mj ,s ,ti) (a = b + ( (a + H(b,c,d) + Mj + ti) << s)) #define II(a ,b ,c ,d ,Mj ,s ,ti) (a = b + ( (a + I(b,c,d) + Mj + ti) << s)) char * initial(std::string & input, int N) { long int len = input.size(); char * str = new char[N * 64]; for (int i = 0; i<input.size(); i++) { str[i] = input[i]; } str[input.size()] = 0x8; for (int i = input.size() + 1; i<64 * N; i++) { str[i] = 0x0; } for (int i = 64 * N - 1; i>64 * N - 5; i--) { str[i] = len % 128; len = len >> 8; } return str; } void MD5(unsigned long int &A, unsigned long int &B, unsigned long int &C, unsigned long int &D, int N, char * str) { unsigned long int a, b, c, d; int M[16]; for (int i = 0; i<N; i++) { for (int j = 0; j<16; j++) { M[j] = str[j * 4 + 64 * i] + str[j * 4 + 1 + 64 * i] * 128 + str[j * 4 + 2 + 64 * i] * 128 * 128 + str[j * 4 + 3 + 64 * i] * 128 * 128 * 128; } a = A, b = B, c = C, d = D; FF(a, b, c, d, M[0], 7, 0xd76aa478); FF(d, a, b, c, M[1], 12, 0xe8c7b756); FF(c, d, a, b, M[2], 17, 0x242070db); FF(b, c, d, a, M[3], 22, 0xc1bdceee); FF(a, b, c, d, M[4], 7, 0xf57c0faf); FF(d, a, b, c, M[5], 12, 0x4787c62a); FF(c, d, a, b, M[6], 17, 0xa8304613); FF(b, c, d, a, M[7], 22, 0xfd469501); FF(a, b, c, d, M[8], 7, 0x698098d8); FF(d, a, b, c, M[9], 12, 0x8b44f7af); FF(c, d, a, b, M[10], 17, 0xffff5bb1); FF(b, c, d, a, M[11], 22, 0x895cd7be); FF(a, b, c, d, M[12], 7, 0x6b901122); FF(d, a, b, c, M[13], 12, 0xfd987193); FF(c, d, a, b, M[14], 17, 0xa679438e); FF(b, c, d, a, M[15], 22, 0x49b40821); GG(a, b, c, d, M[1], 5, 0xf61e2562); GG(d, a, b, c, M[6], 9, 0xc040b340); GG(c, d, a, b, M[11], 14, 0x265e5a51); GG(b, c, d, a, M[0], 20, 0xe9b6c7aa); GG(a, b, c, d, M[5], 5, 0xd62f105d); GG(d, a, b, c, M[10], 9, 0x02441453); GG(c, d, a, b, M[15], 14, 0xd8a1e681); GG(b, c, d, a, M[4], 20, 0xe7d3fbc8); GG(a, b, c, d, M[9], 5, 0x21e1cde6); GG(d, a, b, c, M[14], 9, 0xc33707d6); GG(c, d, a, b, M[3], 14, 0xf4d50d87); GG(b, c, d, a, M[8], 20, 0x455a14ed); GG(a, b, c, d, M[13], 5, 0xa9e3e905); GG(d, a, b, c, M[2], 9, 0xfcefa3f8); GG(c, d, a, b, M[7], 14, 0x676f02d9); GG(b, c, d, a, M[12], 20, 0x8d2a4c8a); HH(a, b, c, d, M[5], 4, 0xfffa3942); HH(d, a, b, c, M[8], 11, 0x8771f681); HH(c, d, a, b, M[11], 16, 0x6d9d6122); HH(b, c, d, a, M[14], 23, 0xfde5380c); HH(a, b, c, d, M[1], 4, 0xa4beea44); HH(d, a, b, c, M[4], 11, 0x4bdecfa9); HH(c, d, a, b, M[7], 16, 0xf6bb4b60); HH(b, c, d, a, M[10], 23, 0xbebfbc70); HH(a, b, c, d, M[13], 4, 0x289b7ec6); HH(d, a, b, c, M[0], 11, 0xeaa127fa); HH(c, d, a, b, M[3], 16, 0xd4ef3085); HH(b, c, d, a, M[6], 23, 0x04881d05); HH(a, b, c, d, M[9], 4, 0xd9d4d039); HH(d, a, b, c, M[12], 11, 0xe6db99e5); HH(c, d, a, b, M[15], 16, 0x1fa27cf8); HH(b, c, d, a, M[2], 23, 0xc4ac5665); II(a, b, c, d, M[0], 6, 0xf4292244); II(d, a, b, c, M[7], 10, 0x432aff97); II(c, d, a, b, M[14], 15, 0xab9423a7); II(b, c, d, a, M[5], 21, 0xfc93a039); II(a, b, c, d, M[12], 6, 0x655b59c3); II(d, a, b, c, M[3], 10, 0x8f0ccc92); II(c, d, a, b, M[10], 15, 0xffeff47d); II(b, c, d, a, M[1], 21, 0x85845dd1); II(a, b, c, d, M[8], 6, 0x6fa87e4f); II(d, a, b, c, M[15], 10, 0xfe2ce6e0); II(c, d, a, b, M[6], 15, 0xa3014314); II(b, c, d, a, M[13], 21, 0x4e0811a1); II(a, b, c, d, M[4], 6, 0xf7537e82); II(d, a, b, c, M[11], 10, 0xbd3af235); II(c, d, a, b, M[2], 15, 0x2ad7d2bb); II(b, c, d, a, M[9], 21, 0xeb86d391); A += a; B += b; C += c; D += d; } } #endif
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "Chaingen.h" #include "Common/CommandLine.h" #include "BlockReward.h" #include "BlockValidation.h" #include "ChainSplit1.h" #include "ChainSwitch1.h" #include "Chaingen001.h" #include "DoubleSpend.h" #include "IntegerOverflow.h" #include "RingSignature.h" #include "TransactionTests.h" #include "TransactionValidation.h" #include "Upgrade.h" #include "RandomOuts.h" #include "Deposit.h" namespace po = boost::program_options; namespace { const command_line::arg_descriptor<std::string> arg_test_data_path = {"test_data_path", "", ""}; const command_line::arg_descriptor<bool> arg_generate_test_data = {"generate_test_data", ""}; const command_line::arg_descriptor<bool> arg_play_test_data = {"play_test_data", ""}; const command_line::arg_descriptor<bool> arg_generate_and_play_test_data = {"generate_and_play_test_data", ""}; const command_line::arg_descriptor<bool> arg_test_transactions = {"test_transactions", ""}; } int main(int argc, char* argv[]) { try { po::options_description desc_options("Allowed options"); command_line::add_arg(desc_options, command_line::arg_help); command_line::add_arg(desc_options, arg_test_data_path); command_line::add_arg(desc_options, arg_generate_test_data); command_line::add_arg(desc_options, arg_play_test_data); command_line::add_arg(desc_options, arg_generate_and_play_test_data); command_line::add_arg(desc_options, arg_test_transactions); po::variables_map vm; bool r = command_line::handle_error_helper(desc_options, [&]() { po::store(po::parse_command_line(argc, argv, desc_options), vm); po::notify(vm); return true; }); if (!r) return 1; if (command_line::get_arg(vm, command_line::arg_help)) { std::cout << desc_options << std::endl; return 0; } size_t tests_count = 0; std::vector<std::string> failed_tests; std::string tests_folder = command_line::get_arg(vm, arg_test_data_path); if (command_line::get_arg(vm, arg_generate_test_data)) { GENERATE("chain001.dat", gen_simple_chain_001); } else if (command_line::get_arg(vm, arg_play_test_data)) { PLAY("chain001.dat", gen_simple_chain_001); } else if (command_line::get_arg(vm, arg_generate_and_play_test_data)) { #define GENERATE_AND_PLAY_EX_2VER(TestCase) \ GENERATE_AND_PLAY_EX(TestCase(cn::BLOCK_MAJOR_VERSION_1)) \ GENERATE_AND_PLAY_EX(TestCase(cn::BLOCK_MAJOR_VERSION_2)) // GENERATE_AND_PLAY(DepositTests::TransactionWithDepositUnrolesPartOfAmountAfterSwitchToAlternativeChain); GENERATE_AND_PLAY(DepositTests::TransactionWithDepositExtendsTotalDeposit); GENERATE_AND_PLAY(DepositTests::TransactionWithMultipleDepositOutsExtendsTotalDeposit); // GENERATE_AND_PLAY(DepositTests::TransactionWithDepositUpdatesInterestAfterDepositUnlock); // GENERATE_AND_PLAY(DepositTests::TransactionWithDepositUnrolesInterestAfterSwitchToAlternativeChain); // GENERATE_AND_PLAY(DepositTests::TransactionWithDepositUnrolesAmountAfterSwitchToAlternativeChain); GENERATE_AND_PLAY(DepositTests::TransactionWithDepositIsClearedAfterInputSpend); // GENERATE_AND_PLAY(DepositTests::TransactionWithDepositUpdatesInterestAfterDepositUnlockMultiple); GENERATE_AND_PLAY(DepositTests::BlocksOfFirstTypeCantHaveTransactionsOfTypeTwo); GENERATE_AND_PLAY(DepositTests::BlocksOfSecondTypeCanHaveTransactionsOfTypeOne); GENERATE_AND_PLAY(DepositTests::BlocksOfSecondTypeCanHaveTransactionsOfTypeTwo); GENERATE_AND_PLAY(DepositTests::TransactionOfTypeOneWithDepositInputIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionOfTypeOneWithDepositOutputIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithAmountLowerThenMinIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithMinAmountIsAccepted); GENERATE_AND_PLAY(DepositTests::TransactionWithTermLowerThenMinIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithMinTermIsAccepted); GENERATE_AND_PLAY(DepositTests::TransactionWithTermGreaterThenMaxIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithMaxTermIsAccepted); GENERATE_AND_PLAY(DepositTests::TransactionWithoutSignaturesIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithZeroRequiredSignaturesIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithNumberOfRequiredSignaturesGreaterThanKeysIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithInvalidKeyIsRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithOutputToSpentInputWillBeRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithMultipleInputsThatSpendOneOutputWillBeRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithInputWithAmountThatIsDoesntHaveOutputWithSameAmountWillBeRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithInputWithIndexLargerThanNumberOfOutputsWithThisSumWillBeRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithInputThatPointsToTheOutputButHasAnotherTermWillBeRejected); GENERATE_AND_PLAY(DepositTests::TransactionThatTriesToSpendOutputWhosTermHasntFinishedWillBeRejected); GENERATE_AND_PLAY(DepositTests::TransactionWithAmountThatHasAlreadyFinishedWillBeAccepted); GENERATE_AND_PLAY(DepositTests::TransactionWithDepositExtendsEmission); // GENERATE_AND_PLAY(DepositTests::TransactionWithDepositRestorsEmissionOnAlternativeChain); // GENERATE_AND_PLAY(gen_simple_chain_001); // GENERATE_AND_PLAY(gen_simple_chain_split_1); GENERATE_AND_PLAY(one_block); // GENERATE_AND_PLAY(gen_chain_switch_1); // GENERATE_AND_PLAY(gen_ring_signature_1); // GENERATE_AND_PLAY(gen_ring_signature_2); //GENERATE_AND_PLAY(gen_ring_signature_big); // Takes up to XXX hours (if CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW == 10) //// Block verification tests GENERATE_AND_PLAY_EX_2VER(TestBlockMajorVersionAccepted); GENERATE_AND_PLAY_EX(TestBlockMajorVersionRejected(cn::BLOCK_MAJOR_VERSION_1, cn::BLOCK_MAJOR_VERSION_2)); GENERATE_AND_PLAY_EX(TestBlockMajorVersionRejected(cn::BLOCK_MAJOR_VERSION_2, cn::BLOCK_MAJOR_VERSION_1)); GENERATE_AND_PLAY_EX(TestBlockMajorVersionRejected(cn::BLOCK_MAJOR_VERSION_2, cn::BLOCK_MAJOR_VERSION_2 + 1)); GENERATE_AND_PLAY_EX_2VER(TestBlockBigMinorVersion); GENERATE_AND_PLAY_EX_2VER(gen_block_ts_not_checked); GENERATE_AND_PLAY_EX_2VER(gen_block_ts_in_past); GENERATE_AND_PLAY_EX_2VER(gen_block_ts_in_future_rejected); GENERATE_AND_PLAY_EX_2VER(gen_block_ts_in_future_accepted); // GENERATE_AND_PLAY_EX_2VER(gen_block_invalid_prev_id); GENERATE_AND_PLAY_EX_2VER(gen_block_invalid_nonce); GENERATE_AND_PLAY_EX_2VER(gen_block_no_miner_tx); GENERATE_AND_PLAY_EX_2VER(gen_block_unlock_time_is_low); GENERATE_AND_PLAY_EX_2VER(gen_block_unlock_time_is_high); GENERATE_AND_PLAY_EX_2VER(gen_block_unlock_time_is_timestamp_in_past); GENERATE_AND_PLAY_EX_2VER(gen_block_unlock_time_is_timestamp_in_future); GENERATE_AND_PLAY_EX_2VER(gen_block_height_is_low); GENERATE_AND_PLAY_EX_2VER(gen_block_height_is_high); GENERATE_AND_PLAY_EX_2VER(gen_block_miner_tx_has_2_tx_gen_in); GENERATE_AND_PLAY_EX_2VER(gen_block_miner_tx_has_2_in); GENERATE_AND_PLAY_EX_2VER(gen_block_miner_tx_with_txin_to_key); GENERATE_AND_PLAY_EX_2VER(gen_block_miner_tx_out_is_small); GENERATE_AND_PLAY_EX_2VER(gen_block_miner_tx_out_is_big); GENERATE_AND_PLAY_EX_2VER(gen_block_miner_tx_has_no_out); GENERATE_AND_PLAY_EX_2VER(gen_block_miner_tx_has_out_to_alice); GENERATE_AND_PLAY_EX_2VER(gen_block_has_invalid_tx); GENERATE_AND_PLAY_EX_2VER(gen_block_is_too_big); GENERATE_AND_PLAY_EX_2VER(TestBlockCumulativeSizeExceedsLimit); // GENERATE_AND_PLAY_EX_2VER(gen_block_invalid_binary_format); // Takes up to 30 minutes, if CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW == 10 // Transaction verification tests // GENERATE_AND_PLAY(gen_tx_big_version); // GENERATE_AND_PLAY(gen_tx_unlock_time); GENERATE_AND_PLAY(gen_tx_no_inputs_no_outputs); GENERATE_AND_PLAY(gen_tx_no_inputs_has_outputs); // GENERATE_AND_PLAY(gen_tx_has_inputs_no_outputs); // GENERATE_AND_PLAY(gen_tx_invalid_input_amount); // GENERATE_AND_PLAY(gen_tx_in_to_key_wo_key_offsets); // GENERATE_AND_PLAY(gen_tx_sender_key_offest_not_exist); // GENERATE_AND_PLAY(gen_tx_key_offest_points_to_foreign_key); // GENERATE_AND_PLAY(gen_tx_mixed_key_offest_not_exist); // GENERATE_AND_PLAY(gen_tx_key_image_not_derive_from_tx_key); // GENERATE_AND_PLAY(gen_tx_key_image_is_invalid); // GENERATE_AND_PLAY(gen_tx_check_input_unlock_time); // GENERATE_AND_PLAY(gen_tx_txout_to_key_has_invalid_key); // GENERATE_AND_PLAY(gen_tx_output_with_zero_amount); // GENERATE_AND_PLAY(gen_tx_signatures_are_invalid); // GENERATE_AND_PLAY_EX(GenerateTransactionWithZeroFee(false)); // GENERATE_AND_PLAY_EX(GenerateTransactionWithZeroFee(true)); // multisignature output GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(1, 1, true)); GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(2, 2, true)); GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(3, 2, true)); GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(0, 0, true)); GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(1, 0, true)); GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(0, 1, false)); GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(1, 2, false)); GENERATE_AND_PLAY_EX(MultiSigTx_OutputSignatures(2, 3, false)); // GENERATE_AND_PLAY_EX(MultiSigTx_InvalidOutputSignature()); // multisignature input GENERATE_AND_PLAY_EX(MultiSigTx_Input(1, 1, 1, true)); GENERATE_AND_PLAY_EX(MultiSigTx_Input(2, 1, 1, true)); GENERATE_AND_PLAY_EX(MultiSigTx_Input(3, 2, 2, true)); GENERATE_AND_PLAY_EX(MultiSigTx_Input(1, 1, 0, false)); GENERATE_AND_PLAY_EX(MultiSigTx_Input(2, 2, 1, false)); GENERATE_AND_PLAY_EX(MultiSigTx_Input(3, 2, 1, false)); GENERATE_AND_PLAY_EX(MultiSigTx_BadInputSignature()); // Double spend // GENERATE_AND_PLAY(gen_double_spend_in_tx<false>); // GENERATE_AND_PLAY(gen_double_spend_in_tx<true>); // GENERATE_AND_PLAY(gen_double_spend_in_the_same_block<false>); // GENERATE_AND_PLAY(gen_double_spend_in_the_same_block<true>); // GENERATE_AND_PLAY(gen_double_spend_in_different_blocks<false>); // GENERATE_AND_PLAY(gen_double_spend_in_different_blocks<true>); // GENERATE_AND_PLAY(gen_double_spend_in_different_chains); // GENERATE_AND_PLAY(gen_double_spend_in_alt_chain_in_the_same_block<false>); // GENERATE_AND_PLAY(gen_double_spend_in_alt_chain_in_the_same_block<true>); // GENERATE_AND_PLAY(gen_double_spend_in_alt_chain_in_different_blocks<false>); // GENERATE_AND_PLAY(gen_double_spend_in_alt_chain_in_different_blocks<true>); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendInTx(false)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendInTx(true)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendSameBlock(false)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendSameBlock(true)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendDifferentBlocks(false)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendDifferentBlocks(true)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendAltChainSameBlock(false)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendAltChainSameBlock(true)); GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendAltChainDifferentBlocks(false)); // GENERATE_AND_PLAY_EX(MultiSigTx_DoubleSpendAltChainDifferentBlocks(true)); // GENERATE_AND_PLAY(gen_uint_overflow_1); // GENERATE_AND_PLAY(gen_uint_overflow_2); // GENERATE_AND_PLAY(gen_block_reward); // GENERATE_AND_PLAY(gen_upgrade); // GENERATE_AND_PLAY(GetRandomOutputs); std::cout << (failed_tests.empty() ? concolor::green : concolor::magenta); std::cout << "\nREPORT:\n"; std::cout << " Test run: " << tests_count << '\n'; std::cout << " Failures: " << failed_tests.size() << '\n'; if (!failed_tests.empty()) { std::cout << "FAILED TESTS:\n"; BOOST_FOREACH(auto test_name, failed_tests) { std::cout << " " << test_name << '\n'; } } std::cout << concolor::normal << std::endl; } else if (command_line::get_arg(vm, arg_test_transactions)) { CALL_TEST("TRANSACTIONS TESTS", test_transactions); } else { std::cout << concolor::magenta << "Wrong arguments" << concolor::normal << std::endl; std::cout << desc_options << std::endl; return 2; } return failed_tests.empty() ? 0 : 1; } catch (std::exception& e) { std::cout << "Exception in main(): " << e.what() << std::endl; } }
#include "u_can_i_up_app_MainActivity.h" #include <string.h> #include <jni.h> JNIEXPORT jstring JNICALL Java_u_can_i_up_app_MainActivity_getLocation(JNIEnv* env, jobject thiz){ return env->NewStringUTF("LOC!"); }
#ifndef FakeMarkerPublisher_h #define FakeMarkerPublisher_h #include <ros/ros.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> class FakeMarkerPublisher { public: FakeMarkerPublisher(); bool initialize(); enum RunResult { SUCCESS = 0, FAILED_TO_INITIALIZE }; int run(); private: ros::NodeHandle nh_; ros::NodeHandle ph_; ros::Publisher markers_pub_; tf::TransformListener listener_; tf::TransformBroadcaster broadcaster_; std::string camera_frame_; std::string wrist_frame_; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_PLUGIMISSINGBAR_H #define OP_PLUGIMISSINGBAR_H #include "adjunct/quick/widgets/OpInfobar.h" #include "adjunct/quick/managers/PluginInstallManager.h" #include "adjunct/quick/windows/DocumentWindowListener.h" #ifdef PLUGIN_AUTO_INSTALL class OpLabel; /** * OpPluginMissingBar * * Informs the user the current status of the missing plugin, allows to trigger actions for the current status, * i.e. starting download of a plugin that is available for downloading. * The Plugin Missing Bar will change it's content depending on the current status of the plugin item pointed to * the mime-type that is assigned to it. * * There should be one Plugin Missing Bar per missing plugin (i.e. per mime-type) per window. The bars will in different * windows will automatically adapt to the current missing plugin item state. * DocumentDesktopWindow maintains the Plugin Missing Bar for itself on its own, creating them and deleting basing on the * currently shown page and callbacks from core. */ class OpPluginMissingBar: public OpInfobar, public DocumentWindowListener, public PIM_PluginInstallManagerListener { public: static OP_STATUS Construct(OpPluginMissingBar** obj); /** * Retrieve the mime-type that is tracked by this bar. */ const OpStringC& GetMimeType() const { return m_mime_type; } /** * Set the mime-type that should be tracked with this Plugin Missing Bar. * The Plugin Missing Bar willnot show at all if the mime-type is left empty. * * @param mime_type - the mime-type of the missing plugin to track. * @return - OpStatus::OK if everything went well, ERR otherwise. */ OP_STATUS SetMimeType(const OpStringC& mime_type); /** * Schedule showing this Plugin Missing Bar when the document in the owning window finishes loading. * Prevents showing the bar too early. */ void ShowWhenLoaded(); /** * Hide the Plugin Missing Bar and focus the current page. None of these will happen if the bar is * already hidden. * * @return - FALSE if hiding the bar failed or if it was already hidden, TRUE otherwise. */ BOOL Hide(); virtual void OnLayout(BOOL compute_size_only, INT32 available_width, INT32 available_height, INT32& used_width, INT32& used_height); protected: OpPluginMissingBar(); ~OpPluginMissingBar(); /** * Show the Plugin Missing Bar, only succeeds if the mime-type was set earlier with SetMimeType(). * * @return - TRUE if the bar was shown, FALSE if there was an error showing it or if the mime-type * is empty for this Plugin Missing Bar. */ BOOL Show(); /** * Changes the content of this Plugin Missing Bar depending on the current state of the tracked missing * plugin. Changes the strings, visibility of the buttons and the OpProgressField. * To be used internally by this class. Note that this method may be called within the OnLayout() event * for the toolbar, calling any methods causing a layout will in such case cause a loop with both methods * calling each other. To avoid that do not call any methods causing the toolbar to relayout when do_not_layout * is set to TRUE. * * @param new_state - the new state of the tracked missing plugin item. * @param do_not_layout - indicates that it is forbidden to call any methods causing the OnLayout() callback. * @returns - OpStatus::ERR on error, OK otherwise. */ OP_STATUS ConfigureCurrentLayout(PIM_ItemState new_state, bool do_not_layout = false); /** * Implementation of PIM_PluginInstallManagerListener */ virtual void OnPluginResolved(const OpStringC& mime_type); virtual void OnPluginAvailable(const OpStringC& mime_type); virtual void OnPluginDownloaded(const OpStringC& mime_type); virtual void OnPluginDownloadStarted(const OpStringC& mime_type); virtual void OnPluginDownloadCancelled(const OpStringC& mime_type); virtual void OnPluginInstalledOK(const OpStringC& mime_type); virtual void OnPluginInstallFailed(const OpStringC& mime_type); virtual void OnPluginsRefreshed(); virtual void OnFileDownloadProgress(const OpStringC& mime_type, OpFileLength total_size, OpFileLength downloaded_size, double kbps, unsigned long estimate); virtual void OnFileDownloadDone(const OpStringC& mime_type, OpFileLength total_size); virtual void OnFileDownloadFailed(const OpStringC& mime_type); virtual void OnFileDownloadAborted(const OpStringC& mime_type); /** * Implementation of OpInputContext */ virtual BOOL OnInputAction(OpInputAction* action); virtual const char* GetInputContextName() { return "Plugin Missing Bar"; } /** * Implementation of DocumentWindowListener */ void OnUrlChanged(DocumentDesktopWindow* document_window, const uni_char* url); void OnStartLoading(DocumentDesktopWindow* document_window); void OnLoadingFinished(DocumentDesktopWindow* document_window, OpLoadingListener::LoadingFinishStatus, BOOL was_stopped_by_user = FALSE); private: OpString m_mime_type; OpString m_plugin_name; BOOL m_is_loading; BOOL m_show_when_loaded; double m_show_time; PIM_ItemState m_current_state; }; #endif // PLUGIN_AUTO_INSTALL #endif // OP_PLUGIMISSINGBAR_H